LLVM 22.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 true if the predicated reduction select should be used to set the
1409 /// incoming value for the reduction phi.
1411 // Force to use predicated reduction select since the EVL of the
1412 // second-to-last iteration might not be VF*UF.
1413 if (foldTailWithEVL())
1414 return true;
1416 TTI.preferPredicatedReductionSelect();
1417 }
1418
1419 /// Estimate cost of an intrinsic call instruction CI if it were vectorized
1420 /// with factor VF. Return the cost of the instruction, including
1421 /// scalarization overhead if it's needed.
1422 InstructionCost getVectorIntrinsicCost(CallInst *CI, ElementCount VF) const;
1423
1424 /// Estimate cost of a call instruction CI if it were vectorized with factor
1425 /// VF. Return the cost of the instruction, including scalarization overhead
1426 /// if it's needed.
1427 InstructionCost getVectorCallCost(CallInst *CI, ElementCount VF) const;
1428
1429 /// Invalidates decisions already taken by the cost model.
1431 WideningDecisions.clear();
1432 CallWideningDecisions.clear();
1433 Uniforms.clear();
1434 Scalars.clear();
1435 }
1436
1437 /// Returns the expected execution cost. The unit of the cost does
1438 /// not matter because we use the 'cost' units to compare different
1439 /// vector widths. The cost that is returned is *not* normalized by
1440 /// the factor width.
1441 InstructionCost expectedCost(ElementCount VF);
1442
1443 bool hasPredStores() const { return NumPredStores > 0; }
1444
1445 /// Returns true if epilogue vectorization is considered profitable, and
1446 /// false otherwise.
1447 /// \p VF is the vectorization factor chosen for the original loop.
1448 /// \p Multiplier is an aditional scaling factor applied to VF before
1449 /// comparing to EpilogueVectorizationMinVF.
1450 bool isEpilogueVectorizationProfitable(const ElementCount VF,
1451 const unsigned IC) const;
1452
1453 /// Returns the execution time cost of an instruction for a given vector
1454 /// width. Vector width of one means scalar.
1455 InstructionCost getInstructionCost(Instruction *I, ElementCount VF);
1456
1457 /// Return the cost of instructions in an inloop reduction pattern, if I is
1458 /// part of that pattern.
1459 std::optional<InstructionCost> getReductionPatternCost(Instruction *I,
1460 ElementCount VF,
1461 Type *VectorTy) const;
1462
1463 /// Returns true if \p Op should be considered invariant and if it is
1464 /// trivially hoistable.
1465 bool shouldConsiderInvariant(Value *Op);
1466
1467 /// Return the value of vscale used for tuning the cost model.
1468 std::optional<unsigned> getVScaleForTuning() const { return VScaleForTuning; }
1469
1470private:
1471 unsigned NumPredStores = 0;
1472
1473 /// Used to store the value of vscale used for tuning the cost model. It is
1474 /// initialized during object construction.
1475 std::optional<unsigned> VScaleForTuning;
1476
1477 /// Initializes the value of vscale used for tuning the cost model. If
1478 /// vscale_range.min == vscale_range.max then return vscale_range.max, else
1479 /// return the value returned by the corresponding TTI method.
1480 void initializeVScaleForTuning() {
1481 const Function *Fn = TheLoop->getHeader()->getParent();
1482 if (Fn->hasFnAttribute(Attribute::VScaleRange)) {
1483 auto Attr = Fn->getFnAttribute(Attribute::VScaleRange);
1484 auto Min = Attr.getVScaleRangeMin();
1485 auto Max = Attr.getVScaleRangeMax();
1486 if (Max && Min == Max) {
1487 VScaleForTuning = Max;
1488 return;
1489 }
1490 }
1491
1492 VScaleForTuning = TTI.getVScaleForTuning();
1493 }
1494
1495 /// \return An upper bound for the vectorization factors for both
1496 /// fixed and scalable vectorization, where the minimum-known number of
1497 /// elements is a power-of-2 larger than zero. If scalable vectorization is
1498 /// disabled or unsupported, then the scalable part will be equal to
1499 /// ElementCount::getScalable(0).
1500 FixedScalableVFPair computeFeasibleMaxVF(unsigned MaxTripCount,
1501 ElementCount UserVF,
1502 bool FoldTailByMasking);
1503
1504 /// If \p VF > MaxTripcount, clamps it to the next lower VF that is <=
1505 /// MaxTripCount.
1506 ElementCount clampVFByMaxTripCount(ElementCount VF, unsigned MaxTripCount,
1507 bool FoldTailByMasking) const;
1508
1509 /// \return the maximized element count based on the targets vector
1510 /// registers and the loop trip-count, but limited to a maximum safe VF.
1511 /// This is a helper function of computeFeasibleMaxVF.
1512 ElementCount getMaximizedVFForTarget(unsigned MaxTripCount,
1513 unsigned SmallestType,
1514 unsigned WidestType,
1515 ElementCount MaxSafeVF,
1516 bool FoldTailByMasking);
1517
1518 /// Checks if scalable vectorization is supported and enabled. Caches the
1519 /// result to avoid repeated debug dumps for repeated queries.
1520 bool isScalableVectorizationAllowed();
1521
1522 /// \return the maximum legal scalable VF, based on the safe max number
1523 /// of elements.
1524 ElementCount getMaxLegalScalableVF(unsigned MaxSafeElements);
1525
1526 /// Calculate vectorization cost of memory instruction \p I.
1527 InstructionCost getMemoryInstructionCost(Instruction *I, ElementCount VF);
1528
1529 /// The cost computation for scalarized memory instruction.
1530 InstructionCost getMemInstScalarizationCost(Instruction *I, ElementCount VF);
1531
1532 /// The cost computation for interleaving group of memory instructions.
1533 InstructionCost getInterleaveGroupCost(Instruction *I, ElementCount VF);
1534
1535 /// The cost computation for Gather/Scatter instruction.
1536 InstructionCost getGatherScatterCost(Instruction *I, ElementCount VF);
1537
1538 /// The cost computation for widening instruction \p I with consecutive
1539 /// memory access.
1540 InstructionCost getConsecutiveMemOpCost(Instruction *I, ElementCount VF);
1541
1542 /// The cost calculation for Load/Store instruction \p I with uniform pointer -
1543 /// Load: scalar load + broadcast.
1544 /// Store: scalar store + (loop invariant value stored? 0 : extract of last
1545 /// element)
1546 InstructionCost getUniformMemOpCost(Instruction *I, ElementCount VF);
1547
1548 /// Estimate the overhead of scalarizing an instruction. This is a
1549 /// convenience wrapper for the type-based getScalarizationOverhead API.
1551 ElementCount VF) const;
1552
1553 /// Returns true if an artificially high cost for emulated masked memrefs
1554 /// should be used.
1555 bool useEmulatedMaskMemRefHack(Instruction *I, ElementCount VF);
1556
1557 /// Map of scalar integer values to the smallest bitwidth they can be legally
1558 /// represented as. The vector equivalents of these values should be truncated
1559 /// to this type.
1560 MapVector<Instruction *, uint64_t> MinBWs;
1561
1562 /// A type representing the costs for instructions if they were to be
1563 /// scalarized rather than vectorized. The entries are Instruction-Cost
1564 /// pairs.
1565 using ScalarCostsTy = MapVector<Instruction *, InstructionCost>;
1566
1567 /// A set containing all BasicBlocks that are known to present after
1568 /// vectorization as a predicated block.
1569 DenseMap<ElementCount, SmallPtrSet<BasicBlock *, 4>>
1570 PredicatedBBsAfterVectorization;
1571
1572 /// Records whether it is allowed to have the original scalar loop execute at
1573 /// least once. This may be needed as a fallback loop in case runtime
1574 /// aliasing/dependence checks fail, or to handle the tail/remainder
1575 /// iterations when the trip count is unknown or doesn't divide by the VF,
1576 /// or as a peel-loop to handle gaps in interleave-groups.
1577 /// Under optsize and when the trip count is very small we don't allow any
1578 /// iterations to execute in the scalar loop.
1579 ScalarEpilogueLowering ScalarEpilogueStatus = CM_ScalarEpilogueAllowed;
1580
1581 /// Control finally chosen tail folding style. The first element is used if
1582 /// the IV update may overflow, the second element - if it does not.
1583 std::optional<std::pair<TailFoldingStyle, TailFoldingStyle>>
1584 ChosenTailFoldingStyle;
1585
1586 /// true if scalable vectorization is supported and enabled.
1587 std::optional<bool> IsScalableVectorizationAllowed;
1588
1589 /// Maximum safe number of elements to be processed per vector iteration,
1590 /// which do not prevent store-load forwarding and are safe with regard to the
1591 /// memory dependencies. Required for EVL-based veectorization, where this
1592 /// value is used as the upper bound of the safe AVL.
1593 std::optional<unsigned> MaxSafeElements;
1594
1595 /// A map holding scalar costs for different vectorization factors. The
1596 /// presence of a cost for an instruction in the mapping indicates that the
1597 /// instruction will be scalarized when vectorizing with the associated
1598 /// vectorization factor. The entries are VF-ScalarCostTy pairs.
1599 MapVector<ElementCount, ScalarCostsTy> InstsToScalarize;
1600
1601 /// Holds the instructions known to be uniform after vectorization.
1602 /// The data is collected per VF.
1603 DenseMap<ElementCount, SmallPtrSet<Instruction *, 4>> Uniforms;
1604
1605 /// Holds the instructions known to be scalar after vectorization.
1606 /// The data is collected per VF.
1607 DenseMap<ElementCount, SmallPtrSet<Instruction *, 4>> Scalars;
1608
1609 /// Holds the instructions (address computations) that are forced to be
1610 /// scalarized.
1611 DenseMap<ElementCount, SmallPtrSet<Instruction *, 4>> ForcedScalars;
1612
1613 /// PHINodes of the reductions that should be expanded in-loop.
1614 SmallPtrSet<PHINode *, 4> InLoopReductions;
1615
1616 /// A Map of inloop reduction operations and their immediate chain operand.
1617 /// FIXME: This can be removed once reductions can be costed correctly in
1618 /// VPlan. This was added to allow quick lookup of the inloop operations.
1619 DenseMap<Instruction *, Instruction *> InLoopReductionImmediateChains;
1620
1621 /// Returns the expected difference in cost from scalarizing the expression
1622 /// feeding a predicated instruction \p PredInst. The instructions to
1623 /// scalarize and their scalar costs are collected in \p ScalarCosts. A
1624 /// non-negative return value implies the expression will be scalarized.
1625 /// Currently, only single-use chains are considered for scalarization.
1626 InstructionCost computePredInstDiscount(Instruction *PredInst,
1627 ScalarCostsTy &ScalarCosts,
1628 ElementCount VF);
1629
1630 /// Collect the instructions that are uniform after vectorization. An
1631 /// instruction is uniform if we represent it with a single scalar value in
1632 /// the vectorized loop corresponding to each vector iteration. Examples of
1633 /// uniform instructions include pointer operands of consecutive or
1634 /// interleaved memory accesses. Note that although uniformity implies an
1635 /// instruction will be scalar, the reverse is not true. In general, a
1636 /// scalarized instruction will be represented by VF scalar values in the
1637 /// vectorized loop, each corresponding to an iteration of the original
1638 /// scalar loop.
1639 void collectLoopUniforms(ElementCount VF);
1640
1641 /// Collect the instructions that are scalar after vectorization. An
1642 /// instruction is scalar if it is known to be uniform or will be scalarized
1643 /// during vectorization. collectLoopScalars should only add non-uniform nodes
1644 /// to the list if they are used by a load/store instruction that is marked as
1645 /// CM_Scalarize. Non-uniform scalarized instructions will be represented by
1646 /// VF values in the vectorized loop, each corresponding to an iteration of
1647 /// the original scalar loop.
1648 void collectLoopScalars(ElementCount VF);
1649
1650 /// Keeps cost model vectorization decision and cost for instructions.
1651 /// Right now it is used for memory instructions only.
1652 using DecisionList = DenseMap<std::pair<Instruction *, ElementCount>,
1653 std::pair<InstWidening, InstructionCost>>;
1654
1655 DecisionList WideningDecisions;
1656
1657 using CallDecisionList =
1658 DenseMap<std::pair<CallInst *, ElementCount>, CallWideningDecision>;
1659
1660 CallDecisionList CallWideningDecisions;
1661
1662 /// Returns true if \p V is expected to be vectorized and it needs to be
1663 /// extracted.
1664 bool needsExtract(Value *V, ElementCount VF) const {
1666 if (VF.isScalar() || !I || !TheLoop->contains(I) ||
1667 TheLoop->isLoopInvariant(I) ||
1668 getWideningDecision(I, VF) == CM_Scalarize ||
1669 (isa<CallInst>(I) &&
1670 getCallWideningDecision(cast<CallInst>(I), VF).Kind == CM_Scalarize))
1671 return false;
1672
1673 // Assume we can vectorize V (and hence we need extraction) if the
1674 // scalars are not computed yet. This can happen, because it is called
1675 // via getScalarizationOverhead from setCostBasedWideningDecision, before
1676 // the scalars are collected. That should be a safe assumption in most
1677 // cases, because we check if the operands have vectorizable types
1678 // beforehand in LoopVectorizationLegality.
1679 return !Scalars.contains(VF) || !isScalarAfterVectorization(I, VF);
1680 };
1681
1682 /// Returns a range containing only operands needing to be extracted.
1683 SmallVector<Value *, 4> filterExtractingOperands(Instruction::op_range Ops,
1684 ElementCount VF) const {
1685
1686 SmallPtrSet<const Value *, 4> UniqueOperands;
1688 for (Value *Op : Ops) {
1689 if (isa<Constant>(Op) || !UniqueOperands.insert(Op).second ||
1690 !needsExtract(Op, VF))
1691 continue;
1692 Res.push_back(Op);
1693 }
1694 return Res;
1695 }
1696
1697public:
1698 /// The loop that we evaluate.
1700
1701 /// Predicated scalar evolution analysis.
1703
1704 /// Loop Info analysis.
1706
1707 /// Vectorization legality.
1709
1710 /// Vector target information.
1712
1713 /// Target Library Info.
1715
1716 /// Demanded bits analysis.
1718
1719 /// Assumption cache.
1721
1722 /// Interface to emit optimization remarks.
1724
1725 /// A function to lazily fetch BlockFrequencyInfo. This avoids computing it
1726 /// unless necessary, e.g. when the loop isn't legal to vectorize or when
1727 /// there is no predication.
1728 std::function<BlockFrequencyInfo &()> GetBFI;
1729 /// The BlockFrequencyInfo returned from GetBFI.
1731 /// Returns the BlockFrequencyInfo for the function if cached, otherwise
1732 /// fetches it via GetBFI. Avoids an indirect call to the std::function.
1734 if (!BFI)
1735 BFI = &GetBFI();
1736 return *BFI;
1737 }
1738
1740
1741 /// Loop Vectorize Hint.
1743
1744 /// The interleave access information contains groups of interleaved accesses
1745 /// with the same stride and close to each other.
1747
1748 /// Values to ignore in the cost model.
1750
1751 /// Values to ignore in the cost model when VF > 1.
1753
1754 /// All element types found in the loop.
1756
1757 /// The kind of cost that we are calculating
1759
1760 /// Whether this loop should be optimized for size based on function attribute
1761 /// or profile information.
1763
1764 /// The highest VF possible for this loop, without using MaxBandwidth.
1766};
1767} // end namespace llvm
1768
1769namespace {
1770/// Helper struct to manage generating runtime checks for vectorization.
1771///
1772/// The runtime checks are created up-front in temporary blocks to allow better
1773/// estimating the cost and un-linked from the existing IR. After deciding to
1774/// vectorize, the checks are moved back. If deciding not to vectorize, the
1775/// temporary blocks are completely removed.
1776class GeneratedRTChecks {
1777 /// Basic block which contains the generated SCEV checks, if any.
1778 BasicBlock *SCEVCheckBlock = nullptr;
1779
1780 /// The value representing the result of the generated SCEV checks. If it is
1781 /// nullptr no SCEV checks have been generated.
1782 Value *SCEVCheckCond = nullptr;
1783
1784 /// Basic block which contains the generated memory runtime checks, if any.
1785 BasicBlock *MemCheckBlock = nullptr;
1786
1787 /// The value representing the result of the generated memory runtime checks.
1788 /// If it is nullptr no memory runtime checks have been generated.
1789 Value *MemRuntimeCheckCond = nullptr;
1790
1791 DominatorTree *DT;
1792 LoopInfo *LI;
1794
1795 SCEVExpander SCEVExp;
1796 SCEVExpander MemCheckExp;
1797
1798 bool CostTooHigh = false;
1799
1800 Loop *OuterLoop = nullptr;
1801
1803
1804 /// The kind of cost that we are calculating
1806
1807public:
1808 GeneratedRTChecks(PredicatedScalarEvolution &PSE, DominatorTree *DT,
1811 : DT(DT), LI(LI), TTI(TTI),
1812 SCEVExp(*PSE.getSE(), DL, "scev.check", /*PreserveLCSSA=*/false),
1813 MemCheckExp(*PSE.getSE(), DL, "scev.check", /*PreserveLCSSA=*/false),
1814 PSE(PSE), CostKind(CostKind) {}
1815
1816 /// Generate runtime checks in SCEVCheckBlock and MemCheckBlock, so we can
1817 /// accurately estimate the cost of the runtime checks. The blocks are
1818 /// un-linked from the IR and are added back during vector code generation. If
1819 /// there is no vector code generation, the check blocks are removed
1820 /// completely.
1821 void create(Loop *L, const LoopAccessInfo &LAI,
1822 const SCEVPredicate &UnionPred, ElementCount VF, unsigned IC) {
1823
1824 // Hard cutoff to limit compile-time increase in case a very large number of
1825 // runtime checks needs to be generated.
1826 // TODO: Skip cutoff if the loop is guaranteed to execute, e.g. due to
1827 // profile info.
1828 CostTooHigh =
1830 if (CostTooHigh) {
1831 // Mark runtime checks as never succeeding when they exceed the threshold.
1832 MemRuntimeCheckCond = ConstantInt::getTrue(L->getHeader()->getContext());
1833 SCEVCheckCond = ConstantInt::getTrue(L->getHeader()->getContext());
1834 return;
1835 }
1836
1837 BasicBlock *LoopHeader = L->getHeader();
1838 BasicBlock *Preheader = L->getLoopPreheader();
1839
1840 // Use SplitBlock to create blocks for SCEV & memory runtime checks to
1841 // ensure the blocks are properly added to LoopInfo & DominatorTree. Those
1842 // may be used by SCEVExpander. The blocks will be un-linked from their
1843 // predecessors and removed from LI & DT at the end of the function.
1844 if (!UnionPred.isAlwaysTrue()) {
1845 SCEVCheckBlock = SplitBlock(Preheader, Preheader->getTerminator(), DT, LI,
1846 nullptr, "vector.scevcheck");
1847
1848 SCEVCheckCond = SCEVExp.expandCodeForPredicate(
1849 &UnionPred, SCEVCheckBlock->getTerminator());
1850 if (isa<Constant>(SCEVCheckCond)) {
1851 // Clean up directly after expanding the predicate to a constant, to
1852 // avoid further expansions re-using anything left over from SCEVExp.
1853 SCEVExpanderCleaner SCEVCleaner(SCEVExp);
1854 SCEVCleaner.cleanup();
1855 }
1856 }
1857
1858 const auto &RtPtrChecking = *LAI.getRuntimePointerChecking();
1859 if (RtPtrChecking.Need) {
1860 auto *Pred = SCEVCheckBlock ? SCEVCheckBlock : Preheader;
1861 MemCheckBlock = SplitBlock(Pred, Pred->getTerminator(), DT, LI, nullptr,
1862 "vector.memcheck");
1863
1864 auto DiffChecks = RtPtrChecking.getDiffChecks();
1865 if (DiffChecks) {
1866 Value *RuntimeVF = nullptr;
1867 MemRuntimeCheckCond = addDiffRuntimeChecks(
1868 MemCheckBlock->getTerminator(), *DiffChecks, MemCheckExp,
1869 [VF, &RuntimeVF](IRBuilderBase &B, unsigned Bits) {
1870 if (!RuntimeVF)
1871 RuntimeVF = getRuntimeVF(B, B.getIntNTy(Bits), VF);
1872 return RuntimeVF;
1873 },
1874 IC);
1875 } else {
1876 MemRuntimeCheckCond = addRuntimeChecks(
1877 MemCheckBlock->getTerminator(), L, RtPtrChecking.getChecks(),
1879 }
1880 assert(MemRuntimeCheckCond &&
1881 "no RT checks generated although RtPtrChecking "
1882 "claimed checks are required");
1883 }
1884
1885 SCEVExp.eraseDeadInstructions(SCEVCheckCond);
1886
1887 if (!MemCheckBlock && !SCEVCheckBlock)
1888 return;
1889
1890 // Unhook the temporary block with the checks, update various places
1891 // accordingly.
1892 if (SCEVCheckBlock)
1893 SCEVCheckBlock->replaceAllUsesWith(Preheader);
1894 if (MemCheckBlock)
1895 MemCheckBlock->replaceAllUsesWith(Preheader);
1896
1897 if (SCEVCheckBlock) {
1898 SCEVCheckBlock->getTerminator()->moveBefore(
1899 Preheader->getTerminator()->getIterator());
1900 auto *UI = new UnreachableInst(Preheader->getContext(), SCEVCheckBlock);
1901 UI->setDebugLoc(DebugLoc::getTemporary());
1902 Preheader->getTerminator()->eraseFromParent();
1903 }
1904 if (MemCheckBlock) {
1905 MemCheckBlock->getTerminator()->moveBefore(
1906 Preheader->getTerminator()->getIterator());
1907 auto *UI = new UnreachableInst(Preheader->getContext(), MemCheckBlock);
1908 UI->setDebugLoc(DebugLoc::getTemporary());
1909 Preheader->getTerminator()->eraseFromParent();
1910 }
1911
1912 DT->changeImmediateDominator(LoopHeader, Preheader);
1913 if (MemCheckBlock) {
1914 DT->eraseNode(MemCheckBlock);
1915 LI->removeBlock(MemCheckBlock);
1916 }
1917 if (SCEVCheckBlock) {
1918 DT->eraseNode(SCEVCheckBlock);
1919 LI->removeBlock(SCEVCheckBlock);
1920 }
1921
1922 // Outer loop is used as part of the later cost calculations.
1923 OuterLoop = L->getParentLoop();
1924 }
1925
1927 if (SCEVCheckBlock || MemCheckBlock)
1928 LLVM_DEBUG(dbgs() << "Calculating cost of runtime checks:\n");
1929
1930 if (CostTooHigh) {
1932 Cost.setInvalid();
1933 LLVM_DEBUG(dbgs() << " number of checks exceeded threshold\n");
1934 return Cost;
1935 }
1936
1937 InstructionCost RTCheckCost = 0;
1938 if (SCEVCheckBlock)
1939 for (Instruction &I : *SCEVCheckBlock) {
1940 if (SCEVCheckBlock->getTerminator() == &I)
1941 continue;
1943 LLVM_DEBUG(dbgs() << " " << C << " for " << I << "\n");
1944 RTCheckCost += C;
1945 }
1946 if (MemCheckBlock) {
1947 InstructionCost MemCheckCost = 0;
1948 for (Instruction &I : *MemCheckBlock) {
1949 if (MemCheckBlock->getTerminator() == &I)
1950 continue;
1952 LLVM_DEBUG(dbgs() << " " << C << " for " << I << "\n");
1953 MemCheckCost += C;
1954 }
1955
1956 // If the runtime memory checks are being created inside an outer loop
1957 // we should find out if these checks are outer loop invariant. If so,
1958 // the checks will likely be hoisted out and so the effective cost will
1959 // reduce according to the outer loop trip count.
1960 if (OuterLoop) {
1961 ScalarEvolution *SE = MemCheckExp.getSE();
1962 // TODO: If profitable, we could refine this further by analysing every
1963 // individual memory check, since there could be a mixture of loop
1964 // variant and invariant checks that mean the final condition is
1965 // variant.
1966 const SCEV *Cond = SE->getSCEV(MemRuntimeCheckCond);
1967 if (SE->isLoopInvariant(Cond, OuterLoop)) {
1968 // It seems reasonable to assume that we can reduce the effective
1969 // cost of the checks even when we know nothing about the trip
1970 // count. Assume that the outer loop executes at least twice.
1971 unsigned BestTripCount = 2;
1972
1973 // Get the best known TC estimate.
1974 if (auto EstimatedTC = getSmallBestKnownTC(
1975 PSE, OuterLoop, /* CanUseConstantMax = */ false))
1976 if (EstimatedTC->isFixed())
1977 BestTripCount = EstimatedTC->getFixedValue();
1978
1979 InstructionCost NewMemCheckCost = MemCheckCost / BestTripCount;
1980
1981 // Let's ensure the cost is always at least 1.
1982 NewMemCheckCost = std::max(NewMemCheckCost.getValue(),
1983 (InstructionCost::CostType)1);
1984
1985 if (BestTripCount > 1)
1987 << "We expect runtime memory checks to be hoisted "
1988 << "out of the outer loop. Cost reduced from "
1989 << MemCheckCost << " to " << NewMemCheckCost << '\n');
1990
1991 MemCheckCost = NewMemCheckCost;
1992 }
1993 }
1994
1995 RTCheckCost += MemCheckCost;
1996 }
1997
1998 if (SCEVCheckBlock || MemCheckBlock)
1999 LLVM_DEBUG(dbgs() << "Total cost of runtime checks: " << RTCheckCost
2000 << "\n");
2001
2002 return RTCheckCost;
2003 }
2004
2005 /// Remove the created SCEV & memory runtime check blocks & instructions, if
2006 /// unused.
2007 ~GeneratedRTChecks() {
2008 SCEVExpanderCleaner SCEVCleaner(SCEVExp);
2009 SCEVExpanderCleaner MemCheckCleaner(MemCheckExp);
2010 bool SCEVChecksUsed = !SCEVCheckBlock || !pred_empty(SCEVCheckBlock);
2011 bool MemChecksUsed = !MemCheckBlock || !pred_empty(MemCheckBlock);
2012 if (SCEVChecksUsed)
2013 SCEVCleaner.markResultUsed();
2014
2015 if (MemChecksUsed) {
2016 MemCheckCleaner.markResultUsed();
2017 } else {
2018 auto &SE = *MemCheckExp.getSE();
2019 // Memory runtime check generation creates compares that use expanded
2020 // values. Remove them before running the SCEVExpanderCleaners.
2021 for (auto &I : make_early_inc_range(reverse(*MemCheckBlock))) {
2022 if (MemCheckExp.isInsertedInstruction(&I))
2023 continue;
2024 SE.forgetValue(&I);
2025 I.eraseFromParent();
2026 }
2027 }
2028 MemCheckCleaner.cleanup();
2029 SCEVCleaner.cleanup();
2030
2031 if (!SCEVChecksUsed)
2032 SCEVCheckBlock->eraseFromParent();
2033 if (!MemChecksUsed)
2034 MemCheckBlock->eraseFromParent();
2035 }
2036
2037 /// Retrieves the SCEVCheckCond and SCEVCheckBlock that were generated as IR
2038 /// outside VPlan.
2039 std::pair<Value *, BasicBlock *> getSCEVChecks() const {
2040 using namespace llvm::PatternMatch;
2041 if (!SCEVCheckCond || match(SCEVCheckCond, m_ZeroInt()))
2042 return {nullptr, nullptr};
2043
2044 return {SCEVCheckCond, SCEVCheckBlock};
2045 }
2046
2047 /// Retrieves the MemCheckCond and MemCheckBlock that were generated as IR
2048 /// outside VPlan.
2049 std::pair<Value *, BasicBlock *> getMemRuntimeChecks() const {
2050 using namespace llvm::PatternMatch;
2051 if (MemRuntimeCheckCond && match(MemRuntimeCheckCond, m_ZeroInt()))
2052 return {nullptr, nullptr};
2053 return {MemRuntimeCheckCond, MemCheckBlock};
2054 }
2055
2056 /// Return true if any runtime checks have been added
2057 bool hasChecks() const {
2058 return getSCEVChecks().first || getMemRuntimeChecks().first;
2059 }
2060};
2061} // namespace
2062
2068
2073
2074// Return true if \p OuterLp is an outer loop annotated with hints for explicit
2075// vectorization. The loop needs to be annotated with #pragma omp simd
2076// simdlen(#) or #pragma clang vectorize(enable) vectorize_width(#). If the
2077// vector length information is not provided, vectorization is not considered
2078// explicit. Interleave hints are not allowed either. These limitations will be
2079// relaxed in the future.
2080// Please, note that we are currently forced to abuse the pragma 'clang
2081// vectorize' semantics. This pragma provides *auto-vectorization hints*
2082// (i.e., LV must check that vectorization is legal) whereas pragma 'omp simd'
2083// provides *explicit vectorization hints* (LV can bypass legal checks and
2084// assume that vectorization is legal). However, both hints are implemented
2085// using the same metadata (llvm.loop.vectorize, processed by
2086// LoopVectorizeHints). This will be fixed in the future when the native IR
2087// representation for pragma 'omp simd' is introduced.
2088static bool isExplicitVecOuterLoop(Loop *OuterLp,
2090 assert(!OuterLp->isInnermost() && "This is not an outer loop");
2091 LoopVectorizeHints Hints(OuterLp, true /*DisableInterleaving*/, *ORE);
2092
2093 // Only outer loops with an explicit vectorization hint are supported.
2094 // Unannotated outer loops are ignored.
2096 return false;
2097
2098 Function *Fn = OuterLp->getHeader()->getParent();
2099 if (!Hints.allowVectorization(Fn, OuterLp,
2100 true /*VectorizeOnlyWhenForced*/)) {
2101 LLVM_DEBUG(dbgs() << "LV: Loop hints prevent outer loop vectorization.\n");
2102 return false;
2103 }
2104
2105 if (Hints.getInterleave() > 1) {
2106 // TODO: Interleave support is future work.
2107 LLVM_DEBUG(dbgs() << "LV: Not vectorizing: Interleave is not supported for "
2108 "outer loops.\n");
2109 Hints.emitRemarkWithHints();
2110 return false;
2111 }
2112
2113 return true;
2114}
2115
2119 // Collect inner loops and outer loops without irreducible control flow. For
2120 // now, only collect outer loops that have explicit vectorization hints. If we
2121 // are stress testing the VPlan H-CFG construction, we collect the outermost
2122 // loop of every loop nest.
2123 if (L.isInnermost() || VPlanBuildStressTest ||
2125 LoopBlocksRPO RPOT(&L);
2126 RPOT.perform(LI);
2128 V.push_back(&L);
2129 // TODO: Collect inner loops inside marked outer loops in case
2130 // vectorization fails for the outer loop. Do not invoke
2131 // 'containsIrreducibleCFG' again for inner loops when the outer loop is
2132 // already known to be reducible. We can use an inherited attribute for
2133 // that.
2134 return;
2135 }
2136 }
2137 for (Loop *InnerL : L)
2138 collectSupportedLoops(*InnerL, LI, ORE, V);
2139}
2140
2141//===----------------------------------------------------------------------===//
2142// Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
2143// LoopVectorizationCostModel and LoopVectorizationPlanner.
2144//===----------------------------------------------------------------------===//
2145
2146/// Compute the transformed value of Index at offset StartValue using step
2147/// StepValue.
2148/// For integer induction, returns StartValue + Index * StepValue.
2149/// For pointer induction, returns StartValue[Index * StepValue].
2150/// FIXME: The newly created binary instructions should contain nsw/nuw
2151/// flags, which can be found from the original scalar operations.
2152static Value *
2154 Value *Step,
2156 const BinaryOperator *InductionBinOp) {
2157 using namespace llvm::PatternMatch;
2158 Type *StepTy = Step->getType();
2159 Value *CastedIndex = StepTy->isIntegerTy()
2160 ? B.CreateSExtOrTrunc(Index, StepTy)
2161 : B.CreateCast(Instruction::SIToFP, Index, StepTy);
2162 if (CastedIndex != Index) {
2163 CastedIndex->setName(CastedIndex->getName() + ".cast");
2164 Index = CastedIndex;
2165 }
2166
2167 // Note: the IR at this point is broken. We cannot use SE to create any new
2168 // SCEV and then expand it, hoping that SCEV's simplification will give us
2169 // a more optimal code. Unfortunately, attempt of doing so on invalid IR may
2170 // lead to various SCEV crashes. So all we can do is to use builder and rely
2171 // on InstCombine for future simplifications. Here we handle some trivial
2172 // cases only.
2173 auto CreateAdd = [&B](Value *X, Value *Y) {
2174 assert(X->getType() == Y->getType() && "Types don't match!");
2175 if (match(X, m_ZeroInt()))
2176 return Y;
2177 if (match(Y, m_ZeroInt()))
2178 return X;
2179 return B.CreateAdd(X, Y);
2180 };
2181
2182 // We allow X to be a vector type, in which case Y will potentially be
2183 // splatted into a vector with the same element count.
2184 auto CreateMul = [&B](Value *X, Value *Y) {
2185 assert(X->getType()->getScalarType() == Y->getType() &&
2186 "Types don't match!");
2187 if (match(X, m_One()))
2188 return Y;
2189 if (match(Y, m_One()))
2190 return X;
2191 VectorType *XVTy = dyn_cast<VectorType>(X->getType());
2192 if (XVTy && !isa<VectorType>(Y->getType()))
2193 Y = B.CreateVectorSplat(XVTy->getElementCount(), Y);
2194 return B.CreateMul(X, Y);
2195 };
2196
2197 switch (InductionKind) {
2199 assert(!isa<VectorType>(Index->getType()) &&
2200 "Vector indices not supported for integer inductions yet");
2201 assert(Index->getType() == StartValue->getType() &&
2202 "Index type does not match StartValue type");
2203 if (isa<ConstantInt>(Step) && cast<ConstantInt>(Step)->isMinusOne())
2204 return B.CreateSub(StartValue, Index);
2205 auto *Offset = CreateMul(Index, Step);
2206 return CreateAdd(StartValue, Offset);
2207 }
2209 return B.CreatePtrAdd(StartValue, CreateMul(Index, Step));
2211 assert(!isa<VectorType>(Index->getType()) &&
2212 "Vector indices not supported for FP inductions yet");
2213 assert(Step->getType()->isFloatingPointTy() && "Expected FP Step value");
2214 assert(InductionBinOp &&
2215 (InductionBinOp->getOpcode() == Instruction::FAdd ||
2216 InductionBinOp->getOpcode() == Instruction::FSub) &&
2217 "Original bin op should be defined for FP induction");
2218
2219 Value *MulExp = B.CreateFMul(Step, Index);
2220 return B.CreateBinOp(InductionBinOp->getOpcode(), StartValue, MulExp,
2221 "induction");
2222 }
2224 return nullptr;
2225 }
2226 llvm_unreachable("invalid enum");
2227}
2228
2229static std::optional<unsigned> getMaxVScale(const Function &F,
2230 const TargetTransformInfo &TTI) {
2231 if (std::optional<unsigned> MaxVScale = TTI.getMaxVScale())
2232 return MaxVScale;
2233
2234 if (F.hasFnAttribute(Attribute::VScaleRange))
2235 return F.getFnAttribute(Attribute::VScaleRange).getVScaleRangeMax();
2236
2237 return std::nullopt;
2238}
2239
2240/// For the given VF and UF and maximum trip count computed for the loop, return
2241/// whether the induction variable might overflow in the vectorized loop. If not,
2242/// then we know a runtime overflow check always evaluates to false and can be
2243/// removed.
2245 const LoopVectorizationCostModel *Cost,
2246 ElementCount VF, std::optional<unsigned> UF = std::nullopt) {
2247 // Always be conservative if we don't know the exact unroll factor.
2248 unsigned MaxUF = UF ? *UF : Cost->TTI.getMaxInterleaveFactor(VF);
2249
2250 IntegerType *IdxTy = Cost->Legal->getWidestInductionType();
2251 APInt MaxUIntTripCount = IdxTy->getMask();
2252
2253 // We know the runtime overflow check is known false iff the (max) trip-count
2254 // is known and (max) trip-count + (VF * UF) does not overflow in the type of
2255 // the vector loop induction variable.
2256 if (unsigned TC = Cost->PSE.getSmallConstantMaxTripCount()) {
2257 uint64_t MaxVF = VF.getKnownMinValue();
2258 if (VF.isScalable()) {
2259 std::optional<unsigned> MaxVScale =
2260 getMaxVScale(*Cost->TheFunction, Cost->TTI);
2261 if (!MaxVScale)
2262 return false;
2263 MaxVF *= *MaxVScale;
2264 }
2265
2266 return (MaxUIntTripCount - TC).ugt(MaxVF * MaxUF);
2267 }
2268
2269 return false;
2270}
2271
2272// Return whether we allow using masked interleave-groups (for dealing with
2273// strided loads/stores that reside in predicated blocks, or for dealing
2274// with gaps).
2276 // If an override option has been passed in for interleaved accesses, use it.
2277 if (EnableMaskedInterleavedMemAccesses.getNumOccurrences() > 0)
2279
2280 return TTI.enableMaskedInterleavedAccessVectorization();
2281}
2282
2284 BasicBlock *CheckIRBB) {
2285 // Note: The block with the minimum trip-count check is already connected
2286 // during earlier VPlan construction.
2287 VPBlockBase *ScalarPH = Plan.getScalarPreheader();
2288 VPBlockBase *PreVectorPH = VectorPHVPBB->getSinglePredecessor();
2289 assert(PreVectorPH->getNumSuccessors() == 2 && "Expected 2 successors");
2290 assert(PreVectorPH->getSuccessors()[0] == ScalarPH && "Unexpected successor");
2291 VPIRBasicBlock *CheckVPIRBB = Plan.createVPIRBasicBlock(CheckIRBB);
2292 VPBlockUtils::insertOnEdge(PreVectorPH, VectorPHVPBB, CheckVPIRBB);
2293 PreVectorPH = CheckVPIRBB;
2294 VPBlockUtils::connectBlocks(PreVectorPH, ScalarPH);
2295 PreVectorPH->swapSuccessors();
2296
2297 // We just connected a new block to the scalar preheader. Update all
2298 // VPPhis by adding an incoming value for it, replicating the last value.
2299 unsigned NumPredecessors = ScalarPH->getNumPredecessors();
2300 for (VPRecipeBase &R : cast<VPBasicBlock>(ScalarPH)->phis()) {
2301 assert(isa<VPPhi>(&R) && "Phi expected to be VPPhi");
2302 assert(cast<VPPhi>(&R)->getNumIncoming() == NumPredecessors - 1 &&
2303 "must have incoming values for all operands");
2304 R.addOperand(R.getOperand(NumPredecessors - 2));
2305 }
2306}
2307
2309 BasicBlock *VectorPH, ElementCount VF, unsigned UF) const {
2310 // Generate code to check if the loop's trip count is less than VF * UF, or
2311 // equal to it in case a scalar epilogue is required; this implies that the
2312 // vector trip count is zero. This check also covers the case where adding one
2313 // to the backedge-taken count overflowed leading to an incorrect trip count
2314 // of zero. In this case we will also jump to the scalar loop.
2315 auto P = Cost->requiresScalarEpilogue(VF.isVector()) ? ICmpInst::ICMP_ULE
2317
2318 // Reuse existing vector loop preheader for TC checks.
2319 // Note that new preheader block is generated for vector loop.
2320 BasicBlock *const TCCheckBlock = VectorPH;
2322 TCCheckBlock->getContext(),
2323 InstSimplifyFolder(TCCheckBlock->getDataLayout()));
2324 Builder.SetInsertPoint(TCCheckBlock->getTerminator());
2325
2326 // If tail is to be folded, vector loop takes care of all iterations.
2328 Type *CountTy = Count->getType();
2329 Value *CheckMinIters = Builder.getFalse();
2330 auto CreateStep = [&]() -> Value * {
2331 // Create step with max(MinProTripCount, UF * VF).
2332 if (UF * VF.getKnownMinValue() >= MinProfitableTripCount.getKnownMinValue())
2333 return createStepForVF(Builder, CountTy, VF, UF);
2334
2335 Value *MinProfTC =
2336 Builder.CreateElementCount(CountTy, MinProfitableTripCount);
2337 if (!VF.isScalable())
2338 return MinProfTC;
2339 return Builder.CreateBinaryIntrinsic(
2340 Intrinsic::umax, MinProfTC, createStepForVF(Builder, CountTy, VF, UF));
2341 };
2342
2343 TailFoldingStyle Style = Cost->getTailFoldingStyle();
2344 if (Style == TailFoldingStyle::None) {
2345 Value *Step = CreateStep();
2346 ScalarEvolution &SE = *PSE.getSE();
2347 // TODO: Emit unconditional branch to vector preheader instead of
2348 // conditional branch with known condition.
2349 const SCEV *TripCountSCEV = SE.applyLoopGuards(SE.getSCEV(Count), OrigLoop);
2350 // Check if the trip count is < the step.
2351 if (SE.isKnownPredicate(P, TripCountSCEV, SE.getSCEV(Step))) {
2352 // TODO: Ensure step is at most the trip count when determining max VF and
2353 // UF, w/o tail folding.
2354 CheckMinIters = Builder.getTrue();
2356 TripCountSCEV, SE.getSCEV(Step))) {
2357 // Generate the minimum iteration check only if we cannot prove the
2358 // check is known to be true, or known to be false.
2359 CheckMinIters = Builder.CreateICmp(P, Count, Step, "min.iters.check");
2360 } // else step known to be < trip count, use CheckMinIters preset to false.
2361 } else if (VF.isScalable() && !TTI->isVScaleKnownToBeAPowerOfTwo() &&
2364 // vscale is not necessarily a power-of-2, which means we cannot guarantee
2365 // an overflow to zero when updating induction variables and so an
2366 // additional overflow check is required before entering the vector loop.
2367
2368 // Get the maximum unsigned value for the type.
2369 Value *MaxUIntTripCount =
2370 ConstantInt::get(CountTy, cast<IntegerType>(CountTy)->getMask());
2371 Value *LHS = Builder.CreateSub(MaxUIntTripCount, Count);
2372
2373 // Don't execute the vector loop if (UMax - n) < (VF * UF).
2374 CheckMinIters = Builder.CreateICmp(ICmpInst::ICMP_ULT, LHS, CreateStep());
2375 }
2376 return CheckMinIters;
2377}
2378
2379/// Replace \p VPBB with a VPIRBasicBlock wrapping \p IRBB. All recipes from \p
2380/// VPBB are moved to the end of the newly created VPIRBasicBlock. All
2381/// predecessors and successors of VPBB, if any, are rewired to the new
2382/// VPIRBasicBlock. If \p VPBB may be unreachable, \p Plan must be passed.
2384 BasicBlock *IRBB,
2385 VPlan *Plan = nullptr) {
2386 if (!Plan)
2387 Plan = VPBB->getPlan();
2388 VPIRBasicBlock *IRVPBB = Plan->createVPIRBasicBlock(IRBB);
2389 auto IP = IRVPBB->begin();
2390 for (auto &R : make_early_inc_range(VPBB->phis()))
2391 R.moveBefore(*IRVPBB, IP);
2392
2393 for (auto &R :
2395 R.moveBefore(*IRVPBB, IRVPBB->end());
2396
2397 VPBlockUtils::reassociateBlocks(VPBB, IRVPBB);
2398 // VPBB is now dead and will be cleaned up when the plan gets destroyed.
2399 return IRVPBB;
2400}
2401
2403 BasicBlock *VectorPH = OrigLoop->getLoopPreheader();
2404 assert(VectorPH && "Invalid loop structure");
2405 assert((OrigLoop->getUniqueLatchExitBlock() ||
2406 Cost->requiresScalarEpilogue(VF.isVector())) &&
2407 "loops not exiting via the latch without required epilogue?");
2408
2409 // NOTE: The Plan's scalar preheader VPBB isn't replaced with a VPIRBasicBlock
2410 // wrapping the newly created scalar preheader here at the moment, because the
2411 // Plan's scalar preheader may be unreachable at this point. Instead it is
2412 // replaced in executePlan.
2413 return SplitBlock(VectorPH, VectorPH->getTerminator(), DT, LI, nullptr,
2414 Twine(Prefix) + "scalar.ph");
2415}
2416
2417/// Return the expanded step for \p ID using \p ExpandedSCEVs to look up SCEV
2418/// expansion results.
2420 const SCEV2ValueTy &ExpandedSCEVs) {
2421 const SCEV *Step = ID.getStep();
2422 if (auto *C = dyn_cast<SCEVConstant>(Step))
2423 return C->getValue();
2424 if (auto *U = dyn_cast<SCEVUnknown>(Step))
2425 return U->getValue();
2426 Value *V = ExpandedSCEVs.lookup(Step);
2427 assert(V && "SCEV must be expanded at this point");
2428 return V;
2429}
2430
2431/// Knowing that loop \p L executes a single vector iteration, add instructions
2432/// that will get simplified and thus should not have any cost to \p
2433/// InstsToIgnore.
2436 SmallPtrSetImpl<Instruction *> &InstsToIgnore) {
2437 auto *Cmp = L->getLatchCmpInst();
2438 if (Cmp)
2439 InstsToIgnore.insert(Cmp);
2440 for (const auto &KV : IL) {
2441 // Extract the key by hand so that it can be used in the lambda below. Note
2442 // that captured structured bindings are a C++20 extension.
2443 const PHINode *IV = KV.first;
2444
2445 // Get next iteration value of the induction variable.
2446 Instruction *IVInst =
2447 cast<Instruction>(IV->getIncomingValueForBlock(L->getLoopLatch()));
2448 if (all_of(IVInst->users(),
2449 [&](const User *U) { return U == IV || U == Cmp; }))
2450 InstsToIgnore.insert(IVInst);
2451 }
2452}
2453
2455 // Create a new IR basic block for the scalar preheader.
2456 BasicBlock *ScalarPH = createScalarPreheader("");
2457 return ScalarPH->getSinglePredecessor();
2458}
2459
2460namespace {
2461
2462struct CSEDenseMapInfo {
2463 static bool canHandle(const Instruction *I) {
2466 }
2467
2468 static inline Instruction *getEmptyKey() {
2470 }
2471
2472 static inline Instruction *getTombstoneKey() {
2473 return DenseMapInfo<Instruction *>::getTombstoneKey();
2474 }
2475
2476 static unsigned getHashValue(const Instruction *I) {
2477 assert(canHandle(I) && "Unknown instruction!");
2478 return hash_combine(I->getOpcode(),
2479 hash_combine_range(I->operand_values()));
2480 }
2481
2482 static bool isEqual(const Instruction *LHS, const Instruction *RHS) {
2483 if (LHS == getEmptyKey() || RHS == getEmptyKey() ||
2484 LHS == getTombstoneKey() || RHS == getTombstoneKey())
2485 return LHS == RHS;
2486 return LHS->isIdenticalTo(RHS);
2487 }
2488};
2489
2490} // end anonymous namespace
2491
2492/// FIXME: This legacy common-subexpression-elimination routine is scheduled for
2493/// removal, in favor of the VPlan-based one.
2494static void legacyCSE(BasicBlock *BB) {
2495 // Perform simple cse.
2497 for (Instruction &In : llvm::make_early_inc_range(*BB)) {
2498 if (!CSEDenseMapInfo::canHandle(&In))
2499 continue;
2500
2501 // Check if we can replace this instruction with any of the
2502 // visited instructions.
2503 if (Instruction *V = CSEMap.lookup(&In)) {
2504 In.replaceAllUsesWith(V);
2505 In.eraseFromParent();
2506 continue;
2507 }
2508
2509 CSEMap[&In] = &In;
2510 }
2511}
2512
2513/// This function attempts to return a value that represents the ElementCount
2514/// at runtime. For fixed-width VFs we know this precisely at compile
2515/// time, but for scalable VFs we calculate it based on an estimate of the
2516/// vscale value.
2518 std::optional<unsigned> VScale) {
2519 unsigned EstimatedVF = VF.getKnownMinValue();
2520 if (VF.isScalable())
2521 if (VScale)
2522 EstimatedVF *= *VScale;
2523 assert(EstimatedVF >= 1 && "Estimated VF shouldn't be less than 1");
2524 return EstimatedVF;
2525}
2526
2529 ElementCount VF) const {
2530 // We only need to calculate a cost if the VF is scalar; for actual vectors
2531 // we should already have a pre-calculated cost at each VF.
2532 if (!VF.isScalar())
2533 return getCallWideningDecision(CI, VF).Cost;
2534
2535 Type *RetTy = CI->getType();
2537 if (auto RedCost = getReductionPatternCost(CI, VF, RetTy))
2538 return *RedCost;
2539
2541 for (auto &ArgOp : CI->args())
2542 Tys.push_back(ArgOp->getType());
2543
2544 InstructionCost ScalarCallCost =
2545 TTI.getCallInstrCost(CI->getCalledFunction(), RetTy, Tys, CostKind);
2546
2547 // If this is an intrinsic we may have a lower cost for it.
2550 return std::min(ScalarCallCost, IntrinsicCost);
2551 }
2552 return ScalarCallCost;
2553}
2554
2556 if (VF.isScalar() || !canVectorizeTy(Ty))
2557 return Ty;
2558 return toVectorizedTy(Ty, VF);
2559}
2560
2563 ElementCount VF) const {
2565 assert(ID && "Expected intrinsic call!");
2566 Type *RetTy = maybeVectorizeType(CI->getType(), VF);
2567 FastMathFlags FMF;
2568 if (auto *FPMO = dyn_cast<FPMathOperator>(CI))
2569 FMF = FPMO->getFastMathFlags();
2570
2573 SmallVector<Type *> ParamTys;
2574 std::transform(FTy->param_begin(), FTy->param_end(),
2575 std::back_inserter(ParamTys),
2576 [&](Type *Ty) { return maybeVectorizeType(Ty, VF); });
2577
2578 IntrinsicCostAttributes CostAttrs(ID, RetTy, Arguments, ParamTys, FMF,
2581 return TTI.getIntrinsicInstrCost(CostAttrs, CostKind);
2582}
2583
2585 // Fix widened non-induction PHIs by setting up the PHI operands.
2586 fixNonInductionPHIs(State);
2587
2588 // Don't apply optimizations below when no (vector) loop remains, as they all
2589 // require one at the moment.
2590 VPBasicBlock *HeaderVPBB =
2591 vputils::getFirstLoopHeader(*State.Plan, State.VPDT);
2592 if (!HeaderVPBB)
2593 return;
2594
2595 BasicBlock *HeaderBB = State.CFG.VPBB2IRBB[HeaderVPBB];
2596
2597 // Remove redundant induction instructions.
2598 legacyCSE(HeaderBB);
2599}
2600
2602 auto Iter = vp_depth_first_shallow(Plan.getEntry());
2604 for (VPRecipeBase &P : VPBB->phis()) {
2606 if (!VPPhi)
2607 continue;
2608 PHINode *NewPhi = cast<PHINode>(State.get(VPPhi));
2609 // Make sure the builder has a valid insert point.
2610 Builder.SetInsertPoint(NewPhi);
2611 for (const auto &[Inc, VPBB] : VPPhi->incoming_values_and_blocks())
2612 NewPhi->addIncoming(State.get(Inc), State.CFG.VPBB2IRBB[VPBB]);
2613 }
2614 }
2615}
2616
2617void LoopVectorizationCostModel::collectLoopScalars(ElementCount VF) {
2618 // We should not collect Scalars more than once per VF. Right now, this
2619 // function is called from collectUniformsAndScalars(), which already does
2620 // this check. Collecting Scalars for VF=1 does not make any sense.
2621 assert(VF.isVector() && !Scalars.contains(VF) &&
2622 "This function should not be visited twice for the same VF");
2623
2624 // This avoids any chances of creating a REPLICATE recipe during planning
2625 // since that would result in generation of scalarized code during execution,
2626 // which is not supported for scalable vectors.
2627 if (VF.isScalable()) {
2628 Scalars[VF].insert_range(Uniforms[VF]);
2629 return;
2630 }
2631
2633
2634 // These sets are used to seed the analysis with pointers used by memory
2635 // accesses that will remain scalar.
2637 SmallPtrSet<Instruction *, 8> PossibleNonScalarPtrs;
2638 auto *Latch = TheLoop->getLoopLatch();
2639
2640 // A helper that returns true if the use of Ptr by MemAccess will be scalar.
2641 // The pointer operands of loads and stores will be scalar as long as the
2642 // memory access is not a gather or scatter operation. The value operand of a
2643 // store will remain scalar if the store is scalarized.
2644 auto IsScalarUse = [&](Instruction *MemAccess, Value *Ptr) {
2645 InstWidening WideningDecision = getWideningDecision(MemAccess, VF);
2646 assert(WideningDecision != CM_Unknown &&
2647 "Widening decision should be ready at this moment");
2648 if (auto *Store = dyn_cast<StoreInst>(MemAccess))
2649 if (Ptr == Store->getValueOperand())
2650 return WideningDecision == CM_Scalarize;
2651 assert(Ptr == getLoadStorePointerOperand(MemAccess) &&
2652 "Ptr is neither a value or pointer operand");
2653 return WideningDecision != CM_GatherScatter;
2654 };
2655
2656 // A helper that returns true if the given value is a getelementptr
2657 // instruction contained in the loop.
2658 auto IsLoopVaryingGEP = [&](Value *V) {
2659 return isa<GetElementPtrInst>(V) && !TheLoop->isLoopInvariant(V);
2660 };
2661
2662 // A helper that evaluates a memory access's use of a pointer. If the use will
2663 // be a scalar use and the pointer is only used by memory accesses, we place
2664 // the pointer in ScalarPtrs. Otherwise, the pointer is placed in
2665 // PossibleNonScalarPtrs.
2666 auto EvaluatePtrUse = [&](Instruction *MemAccess, Value *Ptr) {
2667 // We only care about bitcast and getelementptr instructions contained in
2668 // the loop.
2669 if (!IsLoopVaryingGEP(Ptr))
2670 return;
2671
2672 // If the pointer has already been identified as scalar (e.g., if it was
2673 // also identified as uniform), there's nothing to do.
2674 auto *I = cast<Instruction>(Ptr);
2675 if (Worklist.count(I))
2676 return;
2677
2678 // If the use of the pointer will be a scalar use, and all users of the
2679 // pointer are memory accesses, place the pointer in ScalarPtrs. Otherwise,
2680 // place the pointer in PossibleNonScalarPtrs.
2681 if (IsScalarUse(MemAccess, Ptr) &&
2683 ScalarPtrs.insert(I);
2684 else
2685 PossibleNonScalarPtrs.insert(I);
2686 };
2687
2688 // We seed the scalars analysis with three classes of instructions: (1)
2689 // instructions marked uniform-after-vectorization and (2) bitcast,
2690 // getelementptr and (pointer) phi instructions used by memory accesses
2691 // requiring a scalar use.
2692 //
2693 // (1) Add to the worklist all instructions that have been identified as
2694 // uniform-after-vectorization.
2695 Worklist.insert_range(Uniforms[VF]);
2696
2697 // (2) Add to the worklist all bitcast and getelementptr instructions used by
2698 // memory accesses requiring a scalar use. The pointer operands of loads and
2699 // stores will be scalar unless the operation is a gather or scatter.
2700 // The value operand of a store will remain scalar if the store is scalarized.
2701 for (auto *BB : TheLoop->blocks())
2702 for (auto &I : *BB) {
2703 if (auto *Load = dyn_cast<LoadInst>(&I)) {
2704 EvaluatePtrUse(Load, Load->getPointerOperand());
2705 } else if (auto *Store = dyn_cast<StoreInst>(&I)) {
2706 EvaluatePtrUse(Store, Store->getPointerOperand());
2707 EvaluatePtrUse(Store, Store->getValueOperand());
2708 }
2709 }
2710 for (auto *I : ScalarPtrs)
2711 if (!PossibleNonScalarPtrs.count(I)) {
2712 LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *I << "\n");
2713 Worklist.insert(I);
2714 }
2715
2716 // Insert the forced scalars.
2717 // FIXME: Currently VPWidenPHIRecipe() often creates a dead vector
2718 // induction variable when the PHI user is scalarized.
2719 auto ForcedScalar = ForcedScalars.find(VF);
2720 if (ForcedScalar != ForcedScalars.end())
2721 for (auto *I : ForcedScalar->second) {
2722 LLVM_DEBUG(dbgs() << "LV: Found (forced) scalar instruction: " << *I << "\n");
2723 Worklist.insert(I);
2724 }
2725
2726 // Expand the worklist by looking through any bitcasts and getelementptr
2727 // instructions we've already identified as scalar. This is similar to the
2728 // expansion step in collectLoopUniforms(); however, here we're only
2729 // expanding to include additional bitcasts and getelementptr instructions.
2730 unsigned Idx = 0;
2731 while (Idx != Worklist.size()) {
2732 Instruction *Dst = Worklist[Idx++];
2733 if (!IsLoopVaryingGEP(Dst->getOperand(0)))
2734 continue;
2735 auto *Src = cast<Instruction>(Dst->getOperand(0));
2736 if (llvm::all_of(Src->users(), [&](User *U) -> bool {
2737 auto *J = cast<Instruction>(U);
2738 return !TheLoop->contains(J) || Worklist.count(J) ||
2739 ((isa<LoadInst>(J) || isa<StoreInst>(J)) &&
2740 IsScalarUse(J, Src));
2741 })) {
2742 Worklist.insert(Src);
2743 LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *Src << "\n");
2744 }
2745 }
2746
2747 // An induction variable will remain scalar if all users of the induction
2748 // variable and induction variable update remain scalar.
2749 for (const auto &Induction : Legal->getInductionVars()) {
2750 auto *Ind = Induction.first;
2751 auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
2752
2753 // If tail-folding is applied, the primary induction variable will be used
2754 // to feed a vector compare.
2755 if (Ind == Legal->getPrimaryInduction() && foldTailByMasking())
2756 continue;
2757
2758 // Returns true if \p Indvar is a pointer induction that is used directly by
2759 // load/store instruction \p I.
2760 auto IsDirectLoadStoreFromPtrIndvar = [&](Instruction *Indvar,
2761 Instruction *I) {
2762 return Induction.second.getKind() ==
2765 Indvar == getLoadStorePointerOperand(I) && IsScalarUse(I, Indvar);
2766 };
2767
2768 // Determine if all users of the induction variable are scalar after
2769 // vectorization.
2770 bool ScalarInd = all_of(Ind->users(), [&](User *U) -> bool {
2771 auto *I = cast<Instruction>(U);
2772 return I == IndUpdate || !TheLoop->contains(I) || Worklist.count(I) ||
2773 IsDirectLoadStoreFromPtrIndvar(Ind, I);
2774 });
2775 if (!ScalarInd)
2776 continue;
2777
2778 // If the induction variable update is a fixed-order recurrence, neither the
2779 // induction variable or its update should be marked scalar after
2780 // vectorization.
2781 auto *IndUpdatePhi = dyn_cast<PHINode>(IndUpdate);
2782 if (IndUpdatePhi && Legal->isFixedOrderRecurrence(IndUpdatePhi))
2783 continue;
2784
2785 // Determine if all users of the induction variable update instruction are
2786 // scalar after vectorization.
2787 bool ScalarIndUpdate = all_of(IndUpdate->users(), [&](User *U) -> bool {
2788 auto *I = cast<Instruction>(U);
2789 return I == Ind || !TheLoop->contains(I) || Worklist.count(I) ||
2790 IsDirectLoadStoreFromPtrIndvar(IndUpdate, I);
2791 });
2792 if (!ScalarIndUpdate)
2793 continue;
2794
2795 // The induction variable and its update instruction will remain scalar.
2796 Worklist.insert(Ind);
2797 Worklist.insert(IndUpdate);
2798 LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *Ind << "\n");
2799 LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *IndUpdate
2800 << "\n");
2801 }
2802
2803 Scalars[VF].insert_range(Worklist);
2804}
2805
2807 ElementCount VF) {
2808 if (!isPredicatedInst(I))
2809 return false;
2810
2811 // Do we have a non-scalar lowering for this predicated
2812 // instruction? No - it is scalar with predication.
2813 switch(I->getOpcode()) {
2814 default:
2815 return true;
2816 case Instruction::Call:
2817 if (VF.isScalar())
2818 return true;
2820 case Instruction::Load:
2821 case Instruction::Store: {
2822 auto *Ptr = getLoadStorePointerOperand(I);
2823 auto *Ty = getLoadStoreType(I);
2824 unsigned AS = getLoadStoreAddressSpace(I);
2825 Type *VTy = Ty;
2826 if (VF.isVector())
2827 VTy = VectorType::get(Ty, VF);
2828 const Align Alignment = getLoadStoreAlignment(I);
2829 return isa<LoadInst>(I) ? !(isLegalMaskedLoad(Ty, Ptr, Alignment, AS) ||
2830 TTI.isLegalMaskedGather(VTy, Alignment))
2831 : !(isLegalMaskedStore(Ty, Ptr, Alignment, AS) ||
2832 TTI.isLegalMaskedScatter(VTy, Alignment));
2833 }
2834 case Instruction::UDiv:
2835 case Instruction::SDiv:
2836 case Instruction::SRem:
2837 case Instruction::URem: {
2838 // We have the option to use the safe-divisor idiom to avoid predication.
2839 // The cost based decision here will always select safe-divisor for
2840 // scalable vectors as scalarization isn't legal.
2841 const auto [ScalarCost, SafeDivisorCost] = getDivRemSpeculationCost(I, VF);
2842 return isDivRemScalarWithPredication(ScalarCost, SafeDivisorCost);
2843 }
2844 }
2845}
2846
2847// TODO: Fold into LoopVectorizationLegality::isMaskRequired.
2849 // TODO: We can use the loop-preheader as context point here and get
2850 // context sensitive reasoning for isSafeToSpeculativelyExecute.
2852 (isa<LoadInst, StoreInst, CallInst>(I) && !Legal->isMaskRequired(I)) ||
2854 return false;
2855
2856 // If the instruction was executed conditionally in the original scalar loop,
2857 // predication is needed with a mask whose lanes are all possibly inactive.
2858 if (Legal->blockNeedsPredication(I->getParent()))
2859 return true;
2860
2861 // If we're not folding the tail by masking, predication is unnecessary.
2862 if (!foldTailByMasking())
2863 return false;
2864
2865 // All that remain are instructions with side-effects originally executed in
2866 // the loop unconditionally, but now execute under a tail-fold mask (only)
2867 // having at least one active lane (the first). If the side-effects of the
2868 // instruction are invariant, executing it w/o (the tail-folding) mask is safe
2869 // - it will cause the same side-effects as when masked.
2870 switch(I->getOpcode()) {
2871 default:
2873 "instruction should have been considered by earlier checks");
2874 case Instruction::Call:
2875 // Side-effects of a Call are assumed to be non-invariant, needing a
2876 // (fold-tail) mask.
2877 assert(Legal->isMaskRequired(I) &&
2878 "should have returned earlier for calls not needing a mask");
2879 return true;
2880 case Instruction::Load:
2881 // If the address is loop invariant no predication is needed.
2882 return !Legal->isInvariant(getLoadStorePointerOperand(I));
2883 case Instruction::Store: {
2884 // For stores, we need to prove both speculation safety (which follows from
2885 // the same argument as loads), but also must prove the value being stored
2886 // is correct. The easiest form of the later is to require that all values
2887 // stored are the same.
2888 return !(Legal->isInvariant(getLoadStorePointerOperand(I)) &&
2889 TheLoop->isLoopInvariant(cast<StoreInst>(I)->getValueOperand()));
2890 }
2891 case Instruction::UDiv:
2892 case Instruction::SDiv:
2893 case Instruction::SRem:
2894 case Instruction::URem:
2895 // If the divisor is loop-invariant no predication is needed.
2896 return !Legal->isInvariant(I->getOperand(1));
2897 }
2898}
2899
2903 return 1;
2904 // If the block wasn't originally predicated then return early to avoid
2905 // computing BlockFrequencyInfo unnecessarily.
2906 if (!Legal->blockNeedsPredication(BB))
2907 return 1;
2908
2909 uint64_t HeaderFreq =
2910 getBFI().getBlockFreq(TheLoop->getHeader()).getFrequency();
2911 uint64_t BBFreq = getBFI().getBlockFreq(BB).getFrequency();
2912 assert(HeaderFreq >= BBFreq &&
2913 "Header has smaller block freq than dominated BB?");
2914 return std::round((double)HeaderFreq / BBFreq);
2915}
2916
2917std::pair<InstructionCost, InstructionCost>
2919 ElementCount VF) {
2920 assert(I->getOpcode() == Instruction::UDiv ||
2921 I->getOpcode() == Instruction::SDiv ||
2922 I->getOpcode() == Instruction::SRem ||
2923 I->getOpcode() == Instruction::URem);
2925
2926 // Scalarization isn't legal for scalable vector types
2927 InstructionCost ScalarizationCost = InstructionCost::getInvalid();
2928 if (!VF.isScalable()) {
2929 // Get the scalarization cost and scale this amount by the probability of
2930 // executing the predicated block. If the instruction is not predicated,
2931 // we fall through to the next case.
2932 ScalarizationCost = 0;
2933
2934 // These instructions have a non-void type, so account for the phi nodes
2935 // that we will create. This cost is likely to be zero. The phi node
2936 // cost, if any, should be scaled by the block probability because it
2937 // models a copy at the end of each predicated block.
2938 ScalarizationCost +=
2939 VF.getFixedValue() * TTI.getCFInstrCost(Instruction::PHI, CostKind);
2940
2941 // The cost of the non-predicated instruction.
2942 ScalarizationCost +=
2943 VF.getFixedValue() *
2944 TTI.getArithmeticInstrCost(I->getOpcode(), I->getType(), CostKind);
2945
2946 // The cost of insertelement and extractelement instructions needed for
2947 // scalarization.
2948 ScalarizationCost += getScalarizationOverhead(I, VF);
2949
2950 // Scale the cost by the probability of executing the predicated blocks.
2951 // This assumes the predicated block for each vector lane is equally
2952 // likely.
2953 ScalarizationCost =
2954 ScalarizationCost / getPredBlockCostDivisor(CostKind, I->getParent());
2955 }
2956
2957 InstructionCost SafeDivisorCost = 0;
2958 auto *VecTy = toVectorTy(I->getType(), VF);
2959 // The cost of the select guard to ensure all lanes are well defined
2960 // after we speculate above any internal control flow.
2961 SafeDivisorCost +=
2962 TTI.getCmpSelInstrCost(Instruction::Select, VecTy,
2963 toVectorTy(Type::getInt1Ty(I->getContext()), VF),
2965
2966 SmallVector<const Value *, 4> Operands(I->operand_values());
2967 SafeDivisorCost += TTI.getArithmeticInstrCost(
2968 I->getOpcode(), VecTy, CostKind,
2969 {TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None},
2970 {TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None},
2971 Operands, I);
2972 return {ScalarizationCost, SafeDivisorCost};
2973}
2974
2976 Instruction *I, ElementCount VF) const {
2977 assert(isAccessInterleaved(I) && "Expecting interleaved access.");
2979 "Decision should not be set yet.");
2980 auto *Group = getInterleavedAccessGroup(I);
2981 assert(Group && "Must have a group.");
2982 unsigned InterleaveFactor = Group->getFactor();
2983
2984 // If the instruction's allocated size doesn't equal its type size, it
2985 // requires padding and will be scalarized.
2986 auto &DL = I->getDataLayout();
2987 auto *ScalarTy = getLoadStoreType(I);
2988 if (hasIrregularType(ScalarTy, DL))
2989 return false;
2990
2991 // For scalable vectors, the interleave factors must be <= 8 since we require
2992 // the (de)interleaveN intrinsics instead of shufflevectors.
2993 if (VF.isScalable() && InterleaveFactor > 8)
2994 return false;
2995
2996 // If the group involves a non-integral pointer, we may not be able to
2997 // losslessly cast all values to a common type.
2998 bool ScalarNI = DL.isNonIntegralPointerType(ScalarTy);
2999 for (unsigned Idx = 0; Idx < InterleaveFactor; Idx++) {
3000 Instruction *Member = Group->getMember(Idx);
3001 if (!Member)
3002 continue;
3003 auto *MemberTy = getLoadStoreType(Member);
3004 bool MemberNI = DL.isNonIntegralPointerType(MemberTy);
3005 // Don't coerce non-integral pointers to integers or vice versa.
3006 if (MemberNI != ScalarNI)
3007 // TODO: Consider adding special nullptr value case here
3008 return false;
3009 if (MemberNI && ScalarNI &&
3010 ScalarTy->getPointerAddressSpace() !=
3011 MemberTy->getPointerAddressSpace())
3012 return false;
3013 }
3014
3015 // Check if masking is required.
3016 // A Group may need masking for one of two reasons: it resides in a block that
3017 // needs predication, or it was decided to use masking to deal with gaps
3018 // (either a gap at the end of a load-access that may result in a speculative
3019 // load, or any gaps in a store-access).
3020 bool PredicatedAccessRequiresMasking =
3021 blockNeedsPredicationForAnyReason(I->getParent()) &&
3022 Legal->isMaskRequired(I);
3023 bool LoadAccessWithGapsRequiresEpilogMasking =
3024 isa<LoadInst>(I) && Group->requiresScalarEpilogue() &&
3026 bool StoreAccessWithGapsRequiresMasking =
3027 isa<StoreInst>(I) && !Group->isFull();
3028 if (!PredicatedAccessRequiresMasking &&
3029 !LoadAccessWithGapsRequiresEpilogMasking &&
3030 !StoreAccessWithGapsRequiresMasking)
3031 return true;
3032
3033 // If masked interleaving is required, we expect that the user/target had
3034 // enabled it, because otherwise it either wouldn't have been created or
3035 // it should have been invalidated by the CostModel.
3037 "Masked interleave-groups for predicated accesses are not enabled.");
3038
3039 if (Group->isReverse())
3040 return false;
3041
3042 // TODO: Support interleaved access that requires a gap mask for scalable VFs.
3043 bool NeedsMaskForGaps = LoadAccessWithGapsRequiresEpilogMasking ||
3044 StoreAccessWithGapsRequiresMasking;
3045 if (VF.isScalable() && NeedsMaskForGaps)
3046 return false;
3047
3048 auto *Ty = getLoadStoreType(I);
3049 const Align Alignment = getLoadStoreAlignment(I);
3050 unsigned AS = getLoadStoreAddressSpace(I);
3051 return isa<LoadInst>(I) ? TTI.isLegalMaskedLoad(Ty, Alignment, AS)
3052 : TTI.isLegalMaskedStore(Ty, Alignment, AS);
3053}
3054
3056 Instruction *I, ElementCount VF) {
3057 // Get and ensure we have a valid memory instruction.
3058 assert((isa<LoadInst, StoreInst>(I)) && "Invalid memory instruction");
3059
3060 auto *Ptr = getLoadStorePointerOperand(I);
3061 auto *ScalarTy = getLoadStoreType(I);
3062
3063 // In order to be widened, the pointer should be consecutive, first of all.
3064 if (!Legal->isConsecutivePtr(ScalarTy, Ptr))
3065 return false;
3066
3067 // If the instruction is a store located in a predicated block, it will be
3068 // scalarized.
3069 if (isScalarWithPredication(I, VF))
3070 return false;
3071
3072 // If the instruction's allocated size doesn't equal it's type size, it
3073 // requires padding and will be scalarized.
3074 auto &DL = I->getDataLayout();
3075 if (hasIrregularType(ScalarTy, DL))
3076 return false;
3077
3078 return true;
3079}
3080
3081void LoopVectorizationCostModel::collectLoopUniforms(ElementCount VF) {
3082 // We should not collect Uniforms more than once per VF. Right now,
3083 // this function is called from collectUniformsAndScalars(), which
3084 // already does this check. Collecting Uniforms for VF=1 does not make any
3085 // sense.
3086
3087 assert(VF.isVector() && !Uniforms.contains(VF) &&
3088 "This function should not be visited twice for the same VF");
3089
3090 // Visit the list of Uniforms. If we find no uniform value, we won't
3091 // analyze again. Uniforms.count(VF) will return 1.
3092 Uniforms[VF].clear();
3093
3094 // Now we know that the loop is vectorizable!
3095 // Collect instructions inside the loop that will remain uniform after
3096 // vectorization.
3097
3098 // Global values, params and instructions outside of current loop are out of
3099 // scope.
3100 auto IsOutOfScope = [&](Value *V) -> bool {
3102 return (!I || !TheLoop->contains(I));
3103 };
3104
3105 // Worklist containing uniform instructions demanding lane 0.
3106 SetVector<Instruction *> Worklist;
3107
3108 // Add uniform instructions demanding lane 0 to the worklist. Instructions
3109 // that require predication must not be considered uniform after
3110 // vectorization, because that would create an erroneous replicating region
3111 // where only a single instance out of VF should be formed.
3112 auto AddToWorklistIfAllowed = [&](Instruction *I) -> void {
3113 if (IsOutOfScope(I)) {
3114 LLVM_DEBUG(dbgs() << "LV: Found not uniform due to scope: "
3115 << *I << "\n");
3116 return;
3117 }
3118 if (isPredicatedInst(I)) {
3119 LLVM_DEBUG(
3120 dbgs() << "LV: Found not uniform due to requiring predication: " << *I
3121 << "\n");
3122 return;
3123 }
3124 LLVM_DEBUG(dbgs() << "LV: Found uniform instruction: " << *I << "\n");
3125 Worklist.insert(I);
3126 };
3127
3128 // Start with the conditional branches exiting the loop. If the branch
3129 // condition is an instruction contained in the loop that is only used by the
3130 // branch, it is uniform. Note conditions from uncountable early exits are not
3131 // uniform.
3133 TheLoop->getExitingBlocks(Exiting);
3134 for (BasicBlock *E : Exiting) {
3135 if (Legal->hasUncountableEarlyExit() && TheLoop->getLoopLatch() != E)
3136 continue;
3137 auto *Cmp = dyn_cast<Instruction>(E->getTerminator()->getOperand(0));
3138 if (Cmp && TheLoop->contains(Cmp) && Cmp->hasOneUse())
3139 AddToWorklistIfAllowed(Cmp);
3140 }
3141
3142 auto PrevVF = VF.divideCoefficientBy(2);
3143 // Return true if all lanes perform the same memory operation, and we can
3144 // thus choose to execute only one.
3145 auto IsUniformMemOpUse = [&](Instruction *I) {
3146 // If the value was already known to not be uniform for the previous
3147 // (smaller VF), it cannot be uniform for the larger VF.
3148 if (PrevVF.isVector()) {
3149 auto Iter = Uniforms.find(PrevVF);
3150 if (Iter != Uniforms.end() && !Iter->second.contains(I))
3151 return false;
3152 }
3153 if (!Legal->isUniformMemOp(*I, VF))
3154 return false;
3155 if (isa<LoadInst>(I))
3156 // Loading the same address always produces the same result - at least
3157 // assuming aliasing and ordering which have already been checked.
3158 return true;
3159 // Storing the same value on every iteration.
3160 return TheLoop->isLoopInvariant(cast<StoreInst>(I)->getValueOperand());
3161 };
3162
3163 auto IsUniformDecision = [&](Instruction *I, ElementCount VF) {
3164 InstWidening WideningDecision = getWideningDecision(I, VF);
3165 assert(WideningDecision != CM_Unknown &&
3166 "Widening decision should be ready at this moment");
3167
3168 if (IsUniformMemOpUse(I))
3169 return true;
3170
3171 return (WideningDecision == CM_Widen ||
3172 WideningDecision == CM_Widen_Reverse ||
3173 WideningDecision == CM_Interleave);
3174 };
3175
3176 // Returns true if Ptr is the pointer operand of a memory access instruction
3177 // I, I is known to not require scalarization, and the pointer is not also
3178 // stored.
3179 auto IsVectorizedMemAccessUse = [&](Instruction *I, Value *Ptr) -> bool {
3180 if (isa<StoreInst>(I) && I->getOperand(0) == Ptr)
3181 return false;
3182 return getLoadStorePointerOperand(I) == Ptr &&
3183 (IsUniformDecision(I, VF) || Legal->isInvariant(Ptr));
3184 };
3185
3186 // Holds a list of values which are known to have at least one uniform use.
3187 // Note that there may be other uses which aren't uniform. A "uniform use"
3188 // here is something which only demands lane 0 of the unrolled iterations;
3189 // it does not imply that all lanes produce the same value (e.g. this is not
3190 // the usual meaning of uniform)
3191 SetVector<Value *> HasUniformUse;
3192
3193 // Scan the loop for instructions which are either a) known to have only
3194 // lane 0 demanded or b) are uses which demand only lane 0 of their operand.
3195 for (auto *BB : TheLoop->blocks())
3196 for (auto &I : *BB) {
3197 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I)) {
3198 switch (II->getIntrinsicID()) {
3199 case Intrinsic::sideeffect:
3200 case Intrinsic::experimental_noalias_scope_decl:
3201 case Intrinsic::assume:
3202 case Intrinsic::lifetime_start:
3203 case Intrinsic::lifetime_end:
3204 if (TheLoop->hasLoopInvariantOperands(&I))
3205 AddToWorklistIfAllowed(&I);
3206 break;
3207 default:
3208 break;
3209 }
3210 }
3211
3212 if (auto *EVI = dyn_cast<ExtractValueInst>(&I)) {
3213 if (IsOutOfScope(EVI->getAggregateOperand())) {
3214 AddToWorklistIfAllowed(EVI);
3215 continue;
3216 }
3217 // Only ExtractValue instructions where the aggregate value comes from a
3218 // call are allowed to be non-uniform.
3219 assert(isa<CallInst>(EVI->getAggregateOperand()) &&
3220 "Expected aggregate value to be call return value");
3221 }
3222
3223 // If there's no pointer operand, there's nothing to do.
3224 auto *Ptr = getLoadStorePointerOperand(&I);
3225 if (!Ptr)
3226 continue;
3227
3228 // If the pointer can be proven to be uniform, always add it to the
3229 // worklist.
3230 if (isa<Instruction>(Ptr) && Legal->isUniform(Ptr, VF))
3231 AddToWorklistIfAllowed(cast<Instruction>(Ptr));
3232
3233 if (IsUniformMemOpUse(&I))
3234 AddToWorklistIfAllowed(&I);
3235
3236 if (IsVectorizedMemAccessUse(&I, Ptr))
3237 HasUniformUse.insert(Ptr);
3238 }
3239
3240 // Add to the worklist any operands which have *only* uniform (e.g. lane 0
3241 // demanding) users. Since loops are assumed to be in LCSSA form, this
3242 // disallows uses outside the loop as well.
3243 for (auto *V : HasUniformUse) {
3244 if (IsOutOfScope(V))
3245 continue;
3246 auto *I = cast<Instruction>(V);
3247 bool UsersAreMemAccesses = all_of(I->users(), [&](User *U) -> bool {
3248 auto *UI = cast<Instruction>(U);
3249 return TheLoop->contains(UI) && IsVectorizedMemAccessUse(UI, V);
3250 });
3251 if (UsersAreMemAccesses)
3252 AddToWorklistIfAllowed(I);
3253 }
3254
3255 // Expand Worklist in topological order: whenever a new instruction
3256 // is added , its users should be already inside Worklist. It ensures
3257 // a uniform instruction will only be used by uniform instructions.
3258 unsigned Idx = 0;
3259 while (Idx != Worklist.size()) {
3260 Instruction *I = Worklist[Idx++];
3261
3262 for (auto *OV : I->operand_values()) {
3263 // isOutOfScope operands cannot be uniform instructions.
3264 if (IsOutOfScope(OV))
3265 continue;
3266 // First order recurrence Phi's should typically be considered
3267 // non-uniform.
3268 auto *OP = dyn_cast<PHINode>(OV);
3269 if (OP && Legal->isFixedOrderRecurrence(OP))
3270 continue;
3271 // If all the users of the operand are uniform, then add the
3272 // operand into the uniform worklist.
3273 auto *OI = cast<Instruction>(OV);
3274 if (llvm::all_of(OI->users(), [&](User *U) -> bool {
3275 auto *J = cast<Instruction>(U);
3276 return Worklist.count(J) || IsVectorizedMemAccessUse(J, OI);
3277 }))
3278 AddToWorklistIfAllowed(OI);
3279 }
3280 }
3281
3282 // For an instruction to be added into Worklist above, all its users inside
3283 // the loop should also be in Worklist. However, this condition cannot be
3284 // true for phi nodes that form a cyclic dependence. We must process phi
3285 // nodes separately. An induction variable will remain uniform if all users
3286 // of the induction variable and induction variable update remain uniform.
3287 // The code below handles both pointer and non-pointer induction variables.
3288 BasicBlock *Latch = TheLoop->getLoopLatch();
3289 for (const auto &Induction : Legal->getInductionVars()) {
3290 auto *Ind = Induction.first;
3291 auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
3292
3293 // Determine if all users of the induction variable are uniform after
3294 // vectorization.
3295 bool UniformInd = all_of(Ind->users(), [&](User *U) -> bool {
3296 auto *I = cast<Instruction>(U);
3297 return I == IndUpdate || !TheLoop->contains(I) || Worklist.count(I) ||
3298 IsVectorizedMemAccessUse(I, Ind);
3299 });
3300 if (!UniformInd)
3301 continue;
3302
3303 // Determine if all users of the induction variable update instruction are
3304 // uniform after vectorization.
3305 bool UniformIndUpdate = all_of(IndUpdate->users(), [&](User *U) -> bool {
3306 auto *I = cast<Instruction>(U);
3307 return I == Ind || Worklist.count(I) ||
3308 IsVectorizedMemAccessUse(I, IndUpdate);
3309 });
3310 if (!UniformIndUpdate)
3311 continue;
3312
3313 // The induction variable and its update instruction will remain uniform.
3314 AddToWorklistIfAllowed(Ind);
3315 AddToWorklistIfAllowed(IndUpdate);
3316 }
3317
3318 Uniforms[VF].insert_range(Worklist);
3319}
3320
3322 LLVM_DEBUG(dbgs() << "LV: Performing code size checks.\n");
3323
3324 if (Legal->getRuntimePointerChecking()->Need) {
3325 reportVectorizationFailure("Runtime ptr check is required with -Os/-Oz",
3326 "runtime pointer checks needed. Enable vectorization of this "
3327 "loop with '#pragma clang loop vectorize(enable)' when "
3328 "compiling with -Os/-Oz",
3329 "CantVersionLoopWithOptForSize", ORE, TheLoop);
3330 return true;
3331 }
3332
3333 if (!PSE.getPredicate().isAlwaysTrue()) {
3334 reportVectorizationFailure("Runtime SCEV check is required with -Os/-Oz",
3335 "runtime SCEV checks needed. Enable vectorization of this "
3336 "loop with '#pragma clang loop vectorize(enable)' when "
3337 "compiling with -Os/-Oz",
3338 "CantVersionLoopWithOptForSize", ORE, TheLoop);
3339 return true;
3340 }
3341
3342 // FIXME: Avoid specializing for stride==1 instead of bailing out.
3343 if (!Legal->getLAI()->getSymbolicStrides().empty()) {
3344 reportVectorizationFailure("Runtime stride check for small trip count",
3345 "runtime stride == 1 checks needed. Enable vectorization of "
3346 "this loop without such check by compiling with -Os/-Oz",
3347 "CantVersionLoopWithOptForSize", ORE, TheLoop);
3348 return true;
3349 }
3350
3351 return false;
3352}
3353
3354bool LoopVectorizationCostModel::isScalableVectorizationAllowed() {
3355 if (IsScalableVectorizationAllowed)
3356 return *IsScalableVectorizationAllowed;
3357
3358 IsScalableVectorizationAllowed = false;
3359 if (!TTI.supportsScalableVectors() && !ForceTargetSupportsScalableVectors)
3360 return false;
3361
3362 if (Hints->isScalableVectorizationDisabled()) {
3363 reportVectorizationInfo("Scalable vectorization is explicitly disabled",
3364 "ScalableVectorizationDisabled", ORE, TheLoop);
3365 return false;
3366 }
3367
3368 LLVM_DEBUG(dbgs() << "LV: Scalable vectorization is available\n");
3369
3370 auto MaxScalableVF = ElementCount::getScalable(
3371 std::numeric_limits<ElementCount::ScalarTy>::max());
3372
3373 // Test that the loop-vectorizer can legalize all operations for this MaxVF.
3374 // FIXME: While for scalable vectors this is currently sufficient, this should
3375 // be replaced by a more detailed mechanism that filters out specific VFs,
3376 // instead of invalidating vectorization for a whole set of VFs based on the
3377 // MaxVF.
3378
3379 // Disable scalable vectorization if the loop contains unsupported reductions.
3380 if (!canVectorizeReductions(MaxScalableVF)) {
3382 "Scalable vectorization not supported for the reduction "
3383 "operations found in this loop.",
3384 "ScalableVFUnfeasible", ORE, TheLoop);
3385 return false;
3386 }
3387
3388 // Disable scalable vectorization if the loop contains any instructions
3389 // with element types not supported for scalable vectors.
3390 if (any_of(ElementTypesInLoop, [&](Type *Ty) {
3391 return !Ty->isVoidTy() &&
3393 })) {
3394 reportVectorizationInfo("Scalable vectorization is not supported "
3395 "for all element types found in this loop.",
3396 "ScalableVFUnfeasible", ORE, TheLoop);
3397 return false;
3398 }
3399
3400 if (!Legal->isSafeForAnyVectorWidth() && !getMaxVScale(*TheFunction, TTI)) {
3401 reportVectorizationInfo("The target does not provide maximum vscale value "
3402 "for safe distance analysis.",
3403 "ScalableVFUnfeasible", ORE, TheLoop);
3404 return false;
3405 }
3406
3407 IsScalableVectorizationAllowed = true;
3408 return true;
3409}
3410
3411ElementCount
3412LoopVectorizationCostModel::getMaxLegalScalableVF(unsigned MaxSafeElements) {
3413 if (!isScalableVectorizationAllowed())
3414 return ElementCount::getScalable(0);
3415
3416 auto MaxScalableVF = ElementCount::getScalable(
3417 std::numeric_limits<ElementCount::ScalarTy>::max());
3418 if (Legal->isSafeForAnyVectorWidth())
3419 return MaxScalableVF;
3420
3421 std::optional<unsigned> MaxVScale = getMaxVScale(*TheFunction, TTI);
3422 // Limit MaxScalableVF by the maximum safe dependence distance.
3423 MaxScalableVF = ElementCount::getScalable(MaxSafeElements / *MaxVScale);
3424
3425 if (!MaxScalableVF)
3427 "Max legal vector width too small, scalable vectorization "
3428 "unfeasible.",
3429 "ScalableVFUnfeasible", ORE, TheLoop);
3430
3431 return MaxScalableVF;
3432}
3433
3434FixedScalableVFPair LoopVectorizationCostModel::computeFeasibleMaxVF(
3435 unsigned MaxTripCount, ElementCount UserVF, bool FoldTailByMasking) {
3436 MinBWs = computeMinimumValueSizes(TheLoop->getBlocks(), *DB, &TTI);
3437 unsigned SmallestType, WidestType;
3438 std::tie(SmallestType, WidestType) = getSmallestAndWidestTypes();
3439
3440 // Get the maximum safe dependence distance in bits computed by LAA.
3441 // It is computed by MaxVF * sizeOf(type) * 8, where type is taken from
3442 // the memory accesses that is most restrictive (involved in the smallest
3443 // dependence distance).
3444 unsigned MaxSafeElementsPowerOf2 =
3445 bit_floor(Legal->getMaxSafeVectorWidthInBits() / WidestType);
3446 if (!Legal->isSafeForAnyStoreLoadForwardDistances()) {
3447 unsigned SLDist = Legal->getMaxStoreLoadForwardSafeDistanceInBits();
3448 MaxSafeElementsPowerOf2 =
3449 std::min(MaxSafeElementsPowerOf2, SLDist / WidestType);
3450 }
3451 auto MaxSafeFixedVF = ElementCount::getFixed(MaxSafeElementsPowerOf2);
3452 auto MaxSafeScalableVF = getMaxLegalScalableVF(MaxSafeElementsPowerOf2);
3453
3454 if (!Legal->isSafeForAnyVectorWidth())
3455 this->MaxSafeElements = MaxSafeElementsPowerOf2;
3456
3457 LLVM_DEBUG(dbgs() << "LV: The max safe fixed VF is: " << MaxSafeFixedVF
3458 << ".\n");
3459 LLVM_DEBUG(dbgs() << "LV: The max safe scalable VF is: " << MaxSafeScalableVF
3460 << ".\n");
3461
3462 // First analyze the UserVF, fall back if the UserVF should be ignored.
3463 if (UserVF) {
3464 auto MaxSafeUserVF =
3465 UserVF.isScalable() ? MaxSafeScalableVF : MaxSafeFixedVF;
3466
3467 if (ElementCount::isKnownLE(UserVF, MaxSafeUserVF)) {
3468 // If `VF=vscale x N` is safe, then so is `VF=N`
3469 if (UserVF.isScalable())
3470 return FixedScalableVFPair(
3471 ElementCount::getFixed(UserVF.getKnownMinValue()), UserVF);
3472
3473 return UserVF;
3474 }
3475
3476 assert(ElementCount::isKnownGT(UserVF, MaxSafeUserVF));
3477
3478 // Only clamp if the UserVF is not scalable. If the UserVF is scalable, it
3479 // is better to ignore the hint and let the compiler choose a suitable VF.
3480 if (!UserVF.isScalable()) {
3481 LLVM_DEBUG(dbgs() << "LV: User VF=" << UserVF
3482 << " is unsafe, clamping to max safe VF="
3483 << MaxSafeFixedVF << ".\n");
3484 ORE->emit([&]() {
3485 return OptimizationRemarkAnalysis(DEBUG_TYPE, "VectorizationFactor",
3486 TheLoop->getStartLoc(),
3487 TheLoop->getHeader())
3488 << "User-specified vectorization factor "
3489 << ore::NV("UserVectorizationFactor", UserVF)
3490 << " is unsafe, clamping to maximum safe vectorization factor "
3491 << ore::NV("VectorizationFactor", MaxSafeFixedVF);
3492 });
3493 return MaxSafeFixedVF;
3494 }
3495
3497 LLVM_DEBUG(dbgs() << "LV: User VF=" << UserVF
3498 << " is ignored because scalable vectors are not "
3499 "available.\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 ignored because the target does not support scalable "
3507 "vectors. The compiler will pick a more suitable value.";
3508 });
3509 } else {
3510 LLVM_DEBUG(dbgs() << "LV: User VF=" << UserVF
3511 << " is unsafe. Ignoring scalable UserVF.\n");
3512 ORE->emit([&]() {
3513 return OptimizationRemarkAnalysis(DEBUG_TYPE, "VectorizationFactor",
3514 TheLoop->getStartLoc(),
3515 TheLoop->getHeader())
3516 << "User-specified vectorization factor "
3517 << ore::NV("UserVectorizationFactor", UserVF)
3518 << " is unsafe. Ignoring the hint to let the compiler pick a "
3519 "more suitable value.";
3520 });
3521 }
3522 }
3523
3524 LLVM_DEBUG(dbgs() << "LV: The Smallest and Widest types: " << SmallestType
3525 << " / " << WidestType << " bits.\n");
3526
3527 FixedScalableVFPair Result(ElementCount::getFixed(1),
3529 if (auto MaxVF =
3530 getMaximizedVFForTarget(MaxTripCount, SmallestType, WidestType,
3531 MaxSafeFixedVF, FoldTailByMasking))
3532 Result.FixedVF = MaxVF;
3533
3534 if (auto MaxVF =
3535 getMaximizedVFForTarget(MaxTripCount, SmallestType, WidestType,
3536 MaxSafeScalableVF, FoldTailByMasking))
3537 if (MaxVF.isScalable()) {
3538 Result.ScalableVF = MaxVF;
3539 LLVM_DEBUG(dbgs() << "LV: Found feasible scalable VF = " << MaxVF
3540 << "\n");
3541 }
3542
3543 return Result;
3544}
3545
3546FixedScalableVFPair
3548 if (Legal->getRuntimePointerChecking()->Need && TTI.hasBranchDivergence()) {
3549 // TODO: It may be useful to do since it's still likely to be dynamically
3550 // uniform if the target can skip.
3552 "Not inserting runtime ptr check for divergent target",
3553 "runtime pointer checks needed. Not enabled for divergent target",
3554 "CantVersionLoopWithDivergentTarget", ORE, TheLoop);
3556 }
3557
3558 ScalarEvolution *SE = PSE.getSE();
3560 unsigned MaxTC = PSE.getSmallConstantMaxTripCount();
3561 LLVM_DEBUG(dbgs() << "LV: Found trip count: " << TC << '\n');
3562 if (TC != ElementCount::getFixed(MaxTC))
3563 LLVM_DEBUG(dbgs() << "LV: Found maximum trip count: " << MaxTC << '\n');
3564 if (TC.isScalar()) {
3565 reportVectorizationFailure("Single iteration (non) loop",
3566 "loop trip count is one, irrelevant for vectorization",
3567 "SingleIterationLoop", ORE, TheLoop);
3569 }
3570
3571 // If BTC matches the widest induction type and is -1 then the trip count
3572 // computation will wrap to 0 and the vector trip count will be 0. Do not try
3573 // to vectorize.
3574 const SCEV *BTC = SE->getBackedgeTakenCount(TheLoop);
3575 if (!isa<SCEVCouldNotCompute>(BTC) &&
3576 BTC->getType()->getScalarSizeInBits() >=
3577 Legal->getWidestInductionType()->getScalarSizeInBits() &&
3579 SE->getMinusOne(BTC->getType()))) {
3581 "Trip count computation wrapped",
3582 "backedge-taken count is -1, loop trip count wrapped to 0",
3583 "TripCountWrapped", ORE, TheLoop);
3585 }
3586
3587 switch (ScalarEpilogueStatus) {
3589 return computeFeasibleMaxVF(MaxTC, UserVF, false);
3591 [[fallthrough]];
3593 LLVM_DEBUG(
3594 dbgs() << "LV: vector predicate hint/switch found.\n"
3595 << "LV: Not allowing scalar epilogue, creating predicated "
3596 << "vector loop.\n");
3597 break;
3599 // fallthrough as a special case of OptForSize
3601 if (ScalarEpilogueStatus == CM_ScalarEpilogueNotAllowedOptSize)
3602 LLVM_DEBUG(
3603 dbgs() << "LV: Not allowing scalar epilogue due to -Os/-Oz.\n");
3604 else
3605 LLVM_DEBUG(dbgs() << "LV: Not allowing scalar epilogue due to low trip "
3606 << "count.\n");
3607
3608 // Bail if runtime checks are required, which are not good when optimising
3609 // for size.
3612
3613 break;
3614 }
3615
3616 // Now try the tail folding
3617
3618 // Invalidate interleave groups that require an epilogue if we can't mask
3619 // the interleave-group.
3621 assert(WideningDecisions.empty() && Uniforms.empty() && Scalars.empty() &&
3622 "No decisions should have been taken at this point");
3623 // Note: There is no need to invalidate any cost modeling decisions here, as
3624 // none were taken so far.
3625 InterleaveInfo.invalidateGroupsRequiringScalarEpilogue();
3626 }
3627
3628 FixedScalableVFPair MaxFactors = computeFeasibleMaxVF(MaxTC, UserVF, true);
3629
3630 // Avoid tail folding if the trip count is known to be a multiple of any VF
3631 // we choose.
3632 std::optional<unsigned> MaxPowerOf2RuntimeVF =
3633 MaxFactors.FixedVF.getFixedValue();
3634 if (MaxFactors.ScalableVF) {
3635 std::optional<unsigned> MaxVScale = getMaxVScale(*TheFunction, TTI);
3636 if (MaxVScale && TTI.isVScaleKnownToBeAPowerOfTwo()) {
3637 MaxPowerOf2RuntimeVF = std::max<unsigned>(
3638 *MaxPowerOf2RuntimeVF,
3639 *MaxVScale * MaxFactors.ScalableVF.getKnownMinValue());
3640 } else
3641 MaxPowerOf2RuntimeVF = std::nullopt; // Stick with tail-folding for now.
3642 }
3643
3644 auto NoScalarEpilogueNeeded = [this, &UserIC](unsigned MaxVF) {
3645 // Return false if the loop is neither a single-latch-exit loop nor an
3646 // early-exit loop as tail-folding is not supported in that case.
3647 if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch() &&
3648 !Legal->hasUncountableEarlyExit())
3649 return false;
3650 unsigned MaxVFtimesIC = UserIC ? MaxVF * UserIC : MaxVF;
3651 ScalarEvolution *SE = PSE.getSE();
3652 // Calling getSymbolicMaxBackedgeTakenCount enables support for loops
3653 // with uncountable exits. For countable loops, the symbolic maximum must
3654 // remain identical to the known back-edge taken count.
3655 const SCEV *BackedgeTakenCount = PSE.getSymbolicMaxBackedgeTakenCount();
3656 assert((Legal->hasUncountableEarlyExit() ||
3657 BackedgeTakenCount == PSE.getBackedgeTakenCount()) &&
3658 "Invalid loop count");
3659 const SCEV *ExitCount = SE->getAddExpr(
3660 BackedgeTakenCount, SE->getOne(BackedgeTakenCount->getType()));
3661 const SCEV *Rem = SE->getURemExpr(
3662 SE->applyLoopGuards(ExitCount, TheLoop),
3663 SE->getConstant(BackedgeTakenCount->getType(), MaxVFtimesIC));
3664 return Rem->isZero();
3665 };
3666
3667 if (MaxPowerOf2RuntimeVF > 0u) {
3668 assert((UserVF.isNonZero() || isPowerOf2_32(*MaxPowerOf2RuntimeVF)) &&
3669 "MaxFixedVF must be a power of 2");
3670 if (NoScalarEpilogueNeeded(*MaxPowerOf2RuntimeVF)) {
3671 // Accept MaxFixedVF if we do not have a tail.
3672 LLVM_DEBUG(dbgs() << "LV: No tail will remain for any chosen VF.\n");
3673 return MaxFactors;
3674 }
3675 }
3676
3677 auto ExpectedTC = getSmallBestKnownTC(PSE, TheLoop);
3678 if (ExpectedTC && ExpectedTC->isFixed() &&
3679 ExpectedTC->getFixedValue() <=
3680 TTI.getMinTripCountTailFoldingThreshold()) {
3681 if (MaxPowerOf2RuntimeVF > 0u) {
3682 // If we have a low-trip-count, and the fixed-width VF is known to divide
3683 // the trip count but the scalable factor does not, use the fixed-width
3684 // factor in preference to allow the generation of a non-predicated loop.
3685 if (ScalarEpilogueStatus == CM_ScalarEpilogueNotAllowedLowTripLoop &&
3686 NoScalarEpilogueNeeded(MaxFactors.FixedVF.getFixedValue())) {
3687 LLVM_DEBUG(dbgs() << "LV: Picking a fixed-width so that no tail will "
3688 "remain for any chosen VF.\n");
3689 MaxFactors.ScalableVF = ElementCount::getScalable(0);
3690 return MaxFactors;
3691 }
3692 }
3693
3695 "The trip count is below the minial threshold value.",
3696 "loop trip count is too low, avoiding vectorization", "LowTripCount",
3697 ORE, TheLoop);
3699 }
3700
3701 // If we don't know the precise trip count, or if the trip count that we
3702 // found modulo the vectorization factor is not zero, try to fold the tail
3703 // by masking.
3704 // FIXME: look for a smaller MaxVF that does divide TC rather than masking.
3705 bool ContainsScalableVF = MaxFactors.ScalableVF.isNonZero();
3706 setTailFoldingStyles(ContainsScalableVF, UserIC);
3707 if (foldTailByMasking()) {
3708 if (foldTailWithEVL()) {
3709 LLVM_DEBUG(
3710 dbgs()
3711 << "LV: tail is folded with EVL, forcing unroll factor to be 1. Will "
3712 "try to generate VP Intrinsics with scalable vector "
3713 "factors only.\n");
3714 // Tail folded loop using VP intrinsics restricts the VF to be scalable
3715 // for now.
3716 // TODO: extend it for fixed vectors, if required.
3717 assert(ContainsScalableVF && "Expected scalable vector factor.");
3718
3719 MaxFactors.FixedVF = ElementCount::getFixed(1);
3720 }
3721 return MaxFactors;
3722 }
3723
3724 // If there was a tail-folding hint/switch, but we can't fold the tail by
3725 // masking, fallback to a vectorization with a scalar epilogue.
3726 if (ScalarEpilogueStatus == CM_ScalarEpilogueNotNeededUsePredicate) {
3727 LLVM_DEBUG(dbgs() << "LV: Cannot fold tail by masking: vectorize with a "
3728 "scalar epilogue instead.\n");
3729 ScalarEpilogueStatus = CM_ScalarEpilogueAllowed;
3730 return MaxFactors;
3731 }
3732
3733 if (ScalarEpilogueStatus == CM_ScalarEpilogueNotAllowedUsePredicate) {
3734 LLVM_DEBUG(dbgs() << "LV: Can't fold tail by masking: don't vectorize\n");
3736 }
3737
3738 if (TC.isZero()) {
3740 "unable to calculate the loop count due to complex control flow",
3741 "UnknownLoopCountComplexCFG", ORE, TheLoop);
3743 }
3744
3746 "Cannot optimize for size and vectorize at the same time.",
3747 "cannot optimize for size and vectorize at the same time. "
3748 "Enable vectorization of this loop with '#pragma clang loop "
3749 "vectorize(enable)' when compiling with -Os/-Oz",
3750 "NoTailLoopWithOptForSize", ORE, TheLoop);
3752}
3753
3755 ElementCount VF) {
3756 if (ConsiderRegPressure.getNumOccurrences())
3757 return ConsiderRegPressure;
3758
3759 // TODO: We should eventually consider register pressure for all targets. The
3760 // TTI hook is temporary whilst target-specific issues are being fixed.
3761 if (TTI.shouldConsiderVectorizationRegPressure())
3762 return true;
3763
3764 if (!useMaxBandwidth(VF.isScalable()
3767 return false;
3768 // Only calculate register pressure for VFs enabled by MaxBandwidth.
3770 VF, VF.isScalable() ? MaxPermissibleVFWithoutMaxBW.ScalableVF
3772}
3773
3776 return MaximizeBandwidth || (MaximizeBandwidth.getNumOccurrences() == 0 &&
3777 (TTI.shouldMaximizeVectorBandwidth(RegKind) ||
3779 Legal->hasVectorCallVariants())));
3780}
3781
3782ElementCount LoopVectorizationCostModel::clampVFByMaxTripCount(
3783 ElementCount VF, unsigned MaxTripCount, bool FoldTailByMasking) const {
3784 unsigned EstimatedVF = VF.getKnownMinValue();
3785 if (VF.isScalable() && TheFunction->hasFnAttribute(Attribute::VScaleRange)) {
3786 auto Attr = TheFunction->getFnAttribute(Attribute::VScaleRange);
3787 auto Min = Attr.getVScaleRangeMin();
3788 EstimatedVF *= Min;
3789 }
3790
3791 // When a scalar epilogue is required, at least one iteration of the scalar
3792 // loop has to execute. Adjust MaxTripCount accordingly to avoid picking a
3793 // max VF that results in a dead vector loop.
3794 if (MaxTripCount > 0 && requiresScalarEpilogue(true))
3795 MaxTripCount -= 1;
3796
3797 if (MaxTripCount && MaxTripCount <= EstimatedVF &&
3798 (!FoldTailByMasking || isPowerOf2_32(MaxTripCount))) {
3799 // If upper bound loop trip count (TC) is known at compile time there is no
3800 // point in choosing VF greater than TC (as done in the loop below). Select
3801 // maximum power of two which doesn't exceed TC. If VF is
3802 // scalable, we only fall back on a fixed VF when the TC is less than or
3803 // equal to the known number of lanes.
3804 auto ClampedUpperTripCount = llvm::bit_floor(MaxTripCount);
3805 LLVM_DEBUG(dbgs() << "LV: Clamping the MaxVF to maximum power of two not "
3806 "exceeding the constant trip count: "
3807 << ClampedUpperTripCount << "\n");
3808 return ElementCount::get(ClampedUpperTripCount,
3809 FoldTailByMasking ? VF.isScalable() : false);
3810 }
3811 return VF;
3812}
3813
3814ElementCount LoopVectorizationCostModel::getMaximizedVFForTarget(
3815 unsigned MaxTripCount, unsigned SmallestType, unsigned WidestType,
3816 ElementCount MaxSafeVF, bool FoldTailByMasking) {
3817 bool ComputeScalableMaxVF = MaxSafeVF.isScalable();
3818 const TypeSize WidestRegister = TTI.getRegisterBitWidth(
3819 ComputeScalableMaxVF ? TargetTransformInfo::RGK_ScalableVector
3821
3822 // Convenience function to return the minimum of two ElementCounts.
3823 auto MinVF = [](const ElementCount &LHS, const ElementCount &RHS) {
3824 assert((LHS.isScalable() == RHS.isScalable()) &&
3825 "Scalable flags must match");
3826 return ElementCount::isKnownLT(LHS, RHS) ? LHS : RHS;
3827 };
3828
3829 // Ensure MaxVF is a power of 2; the dependence distance bound may not be.
3830 // Note that both WidestRegister and WidestType may not be a powers of 2.
3831 auto MaxVectorElementCount = ElementCount::get(
3832 llvm::bit_floor(WidestRegister.getKnownMinValue() / WidestType),
3833 ComputeScalableMaxVF);
3834 MaxVectorElementCount = MinVF(MaxVectorElementCount, MaxSafeVF);
3835 LLVM_DEBUG(dbgs() << "LV: The Widest register safe to use is: "
3836 << (MaxVectorElementCount * WidestType) << " bits.\n");
3837
3838 if (!MaxVectorElementCount) {
3839 LLVM_DEBUG(dbgs() << "LV: The target has no "
3840 << (ComputeScalableMaxVF ? "scalable" : "fixed")
3841 << " vector registers.\n");
3842 return ElementCount::getFixed(1);
3843 }
3844
3845 ElementCount MaxVF = clampVFByMaxTripCount(MaxVectorElementCount,
3846 MaxTripCount, FoldTailByMasking);
3847 // If the MaxVF was already clamped, there's no point in trying to pick a
3848 // larger one.
3849 if (MaxVF != MaxVectorElementCount)
3850 return MaxVF;
3851
3853 ComputeScalableMaxVF ? TargetTransformInfo::RGK_ScalableVector
3855
3856 if (MaxVF.isScalable())
3857 MaxPermissibleVFWithoutMaxBW.ScalableVF = MaxVF;
3858 else
3859 MaxPermissibleVFWithoutMaxBW.FixedVF = MaxVF;
3860
3861 if (useMaxBandwidth(RegKind)) {
3862 auto MaxVectorElementCountMaxBW = ElementCount::get(
3863 llvm::bit_floor(WidestRegister.getKnownMinValue() / SmallestType),
3864 ComputeScalableMaxVF);
3865 MaxVF = MinVF(MaxVectorElementCountMaxBW, MaxSafeVF);
3866
3867 if (ElementCount MinVF =
3868 TTI.getMinimumVF(SmallestType, ComputeScalableMaxVF)) {
3869 if (ElementCount::isKnownLT(MaxVF, MinVF)) {
3870 LLVM_DEBUG(dbgs() << "LV: Overriding calculated MaxVF(" << MaxVF
3871 << ") with target's minimum: " << MinVF << '\n');
3872 MaxVF = MinVF;
3873 }
3874 }
3875
3876 MaxVF = clampVFByMaxTripCount(MaxVF, MaxTripCount, FoldTailByMasking);
3877
3878 if (MaxVectorElementCount != MaxVF) {
3879 // Invalidate any widening decisions we might have made, in case the loop
3880 // requires prediction (decided later), but we have already made some
3881 // load/store widening decisions.
3882 invalidateCostModelingDecisions();
3883 }
3884 }
3885 return MaxVF;
3886}
3887
3888bool LoopVectorizationPlanner::isMoreProfitable(const VectorizationFactor &A,
3889 const VectorizationFactor &B,
3890 const unsigned MaxTripCount,
3891 bool HasTail,
3892 bool IsEpilogue) const {
3893 InstructionCost CostA = A.Cost;
3894 InstructionCost CostB = B.Cost;
3895
3896 // Improve estimate for the vector width if it is scalable.
3897 unsigned EstimatedWidthA = A.Width.getKnownMinValue();
3898 unsigned EstimatedWidthB = B.Width.getKnownMinValue();
3899 if (std::optional<unsigned> VScale = CM.getVScaleForTuning()) {
3900 if (A.Width.isScalable())
3901 EstimatedWidthA *= *VScale;
3902 if (B.Width.isScalable())
3903 EstimatedWidthB *= *VScale;
3904 }
3905
3906 // When optimizing for size choose whichever is smallest, which will be the
3907 // one with the smallest cost for the whole loop. On a tie pick the larger
3908 // vector width, on the assumption that throughput will be greater.
3909 if (CM.CostKind == TTI::TCK_CodeSize)
3910 return CostA < CostB ||
3911 (CostA == CostB && EstimatedWidthA > EstimatedWidthB);
3912
3913 // Assume vscale may be larger than 1 (or the value being tuned for),
3914 // so that scalable vectorization is slightly favorable over fixed-width
3915 // vectorization.
3916 bool PreferScalable = !TTI.preferFixedOverScalableIfEqualCost(IsEpilogue) &&
3917 A.Width.isScalable() && !B.Width.isScalable();
3918
3919 auto CmpFn = [PreferScalable](const InstructionCost &LHS,
3920 const InstructionCost &RHS) {
3921 return PreferScalable ? LHS <= RHS : LHS < RHS;
3922 };
3923
3924 // To avoid the need for FP division:
3925 // (CostA / EstimatedWidthA) < (CostB / EstimatedWidthB)
3926 // <=> (CostA * EstimatedWidthB) < (CostB * EstimatedWidthA)
3927 if (!MaxTripCount)
3928 return CmpFn(CostA * EstimatedWidthB, CostB * EstimatedWidthA);
3929
3930 auto GetCostForTC = [MaxTripCount, HasTail](unsigned VF,
3931 InstructionCost VectorCost,
3932 InstructionCost ScalarCost) {
3933 // If the trip count is a known (possibly small) constant, the trip count
3934 // will be rounded up to an integer number of iterations under
3935 // FoldTailByMasking. The total cost in that case will be
3936 // VecCost*ceil(TripCount/VF). When not folding the tail, the total
3937 // cost will be VecCost*floor(TC/VF) + ScalarCost*(TC%VF). There will be
3938 // some extra overheads, but for the purpose of comparing the costs of
3939 // different VFs we can use this to compare the total loop-body cost
3940 // expected after vectorization.
3941 if (HasTail)
3942 return VectorCost * (MaxTripCount / VF) +
3943 ScalarCost * (MaxTripCount % VF);
3944 return VectorCost * divideCeil(MaxTripCount, VF);
3945 };
3946
3947 auto RTCostA = GetCostForTC(EstimatedWidthA, CostA, A.ScalarCost);
3948 auto RTCostB = GetCostForTC(EstimatedWidthB, CostB, B.ScalarCost);
3949 return CmpFn(RTCostA, RTCostB);
3950}
3951
3952bool LoopVectorizationPlanner::isMoreProfitable(const VectorizationFactor &A,
3953 const VectorizationFactor &B,
3954 bool HasTail,
3955 bool IsEpilogue) const {
3956 const unsigned MaxTripCount = PSE.getSmallConstantMaxTripCount();
3957 return LoopVectorizationPlanner::isMoreProfitable(A, B, MaxTripCount, HasTail,
3958 IsEpilogue);
3959}
3960
3963 using RecipeVFPair = std::pair<VPRecipeBase *, ElementCount>;
3964 SmallVector<RecipeVFPair> InvalidCosts;
3965 for (const auto &Plan : VPlans) {
3966 for (ElementCount VF : Plan->vectorFactors()) {
3967 // The VPlan-based cost model is designed for computing vector cost.
3968 // Querying VPlan-based cost model with a scarlar VF will cause some
3969 // errors because we expect the VF is vector for most of the widen
3970 // recipes.
3971 if (VF.isScalar())
3972 continue;
3973
3974 VPCostContext CostCtx(CM.TTI, *CM.TLI, *Plan, CM, CM.CostKind,
3975 *CM.PSE.getSE(), OrigLoop);
3976 precomputeCosts(*Plan, VF, CostCtx);
3977 auto Iter = vp_depth_first_deep(Plan->getVectorLoopRegion()->getEntry());
3979 for (auto &R : *VPBB) {
3980 if (!R.cost(VF, CostCtx).isValid())
3981 InvalidCosts.emplace_back(&R, VF);
3982 }
3983 }
3984 }
3985 }
3986 if (InvalidCosts.empty())
3987 return;
3988
3989 // Emit a report of VFs with invalid costs in the loop.
3990
3991 // Group the remarks per recipe, keeping the recipe order from InvalidCosts.
3993 unsigned I = 0;
3994 for (auto &Pair : InvalidCosts)
3995 if (Numbering.try_emplace(Pair.first, I).second)
3996 ++I;
3997
3998 // Sort the list, first on recipe(number) then on VF.
3999 sort(InvalidCosts, [&Numbering](RecipeVFPair &A, RecipeVFPair &B) {
4000 unsigned NA = Numbering[A.first];
4001 unsigned NB = Numbering[B.first];
4002 if (NA != NB)
4003 return NA < NB;
4004 return ElementCount::isKnownLT(A.second, B.second);
4005 });
4006
4007 // For a list of ordered recipe-VF pairs:
4008 // [(load, VF1), (load, VF2), (store, VF1)]
4009 // group the recipes together to emit separate remarks for:
4010 // load (VF1, VF2)
4011 // store (VF1)
4012 auto Tail = ArrayRef<RecipeVFPair>(InvalidCosts);
4013 auto Subset = ArrayRef<RecipeVFPair>();
4014 do {
4015 if (Subset.empty())
4016 Subset = Tail.take_front(1);
4017
4018 VPRecipeBase *R = Subset.front().first;
4019
4020 unsigned Opcode =
4023 [](const auto *R) { return Instruction::PHI; })
4024 .Case<VPWidenSelectRecipe>(
4025 [](const auto *R) { return Instruction::Select; })
4026 .Case<VPWidenStoreRecipe>(
4027 [](const auto *R) { return Instruction::Store; })
4028 .Case<VPWidenLoadRecipe>(
4029 [](const auto *R) { return Instruction::Load; })
4030 .Case<VPWidenCallRecipe, VPWidenIntrinsicRecipe>(
4031 [](const auto *R) { return Instruction::Call; })
4034 [](const auto *R) { return R->getOpcode(); })
4035 .Case<VPInterleaveRecipe>([](const VPInterleaveRecipe *R) {
4036 return R->getStoredValues().empty() ? Instruction::Load
4037 : Instruction::Store;
4038 })
4039 .Case<VPReductionRecipe>([](const auto *R) {
4040 return RecurrenceDescriptor::getOpcode(R->getRecurrenceKind());
4041 });
4042
4043 // If the next recipe is different, or if there are no other pairs,
4044 // emit a remark for the collated subset. e.g.
4045 // [(load, VF1), (load, VF2))]
4046 // to emit:
4047 // remark: invalid costs for 'load' at VF=(VF1, VF2)
4048 if (Subset == Tail || Tail[Subset.size()].first != R) {
4049 std::string OutString;
4050 raw_string_ostream OS(OutString);
4051 assert(!Subset.empty() && "Unexpected empty range");
4052 OS << "Recipe with invalid costs prevented vectorization at VF=(";
4053 for (const auto &Pair : Subset)
4054 OS << (Pair.second == Subset.front().second ? "" : ", ") << Pair.second;
4055 OS << "):";
4056 if (Opcode == Instruction::Call) {
4057 StringRef Name = "";
4058 if (auto *Int = dyn_cast<VPWidenIntrinsicRecipe>(R)) {
4059 Name = Int->getIntrinsicName();
4060 } else {
4061 auto *WidenCall = dyn_cast<VPWidenCallRecipe>(R);
4062 Function *CalledFn =
4063 WidenCall ? WidenCall->getCalledScalarFunction()
4064 : cast<Function>(R->getOperand(R->getNumOperands() - 1)
4065 ->getLiveInIRValue());
4066 Name = CalledFn->getName();
4067 }
4068 OS << " call to " << Name;
4069 } else
4070 OS << " " << Instruction::getOpcodeName(Opcode);
4071 reportVectorizationInfo(OutString, "InvalidCost", ORE, OrigLoop, nullptr,
4072 R->getDebugLoc());
4073 Tail = Tail.drop_front(Subset.size());
4074 Subset = {};
4075 } else
4076 // Grow the subset by one element
4077 Subset = Tail.take_front(Subset.size() + 1);
4078 } while (!Tail.empty());
4079}
4080
4081/// Check if any recipe of \p Plan will generate a vector value, which will be
4082/// assigned a vector register.
4084 const TargetTransformInfo &TTI) {
4085 assert(VF.isVector() && "Checking a scalar VF?");
4086 VPTypeAnalysis TypeInfo(Plan);
4087 DenseSet<VPRecipeBase *> EphemeralRecipes;
4088 collectEphemeralRecipesForVPlan(Plan, EphemeralRecipes);
4089 // Set of already visited types.
4090 DenseSet<Type *> Visited;
4093 for (VPRecipeBase &R : *VPBB) {
4094 if (EphemeralRecipes.contains(&R))
4095 continue;
4096 // Continue early if the recipe is considered to not produce a vector
4097 // result. Note that this includes VPInstruction where some opcodes may
4098 // produce a vector, to preserve existing behavior as VPInstructions model
4099 // aspects not directly mapped to existing IR instructions.
4100 switch (R.getVPDefID()) {
4101 case VPDef::VPDerivedIVSC:
4102 case VPDef::VPScalarIVStepsSC:
4103 case VPDef::VPReplicateSC:
4104 case VPDef::VPInstructionSC:
4105 case VPDef::VPCanonicalIVPHISC:
4106 case VPDef::VPVectorPointerSC:
4107 case VPDef::VPVectorEndPointerSC:
4108 case VPDef::VPExpandSCEVSC:
4109 case VPDef::VPEVLBasedIVPHISC:
4110 case VPDef::VPPredInstPHISC:
4111 case VPDef::VPBranchOnMaskSC:
4112 continue;
4113 case VPDef::VPReductionSC:
4114 case VPDef::VPActiveLaneMaskPHISC:
4115 case VPDef::VPWidenCallSC:
4116 case VPDef::VPWidenCanonicalIVSC:
4117 case VPDef::VPWidenCastSC:
4118 case VPDef::VPWidenGEPSC:
4119 case VPDef::VPWidenIntrinsicSC:
4120 case VPDef::VPWidenSC:
4121 case VPDef::VPWidenSelectSC:
4122 case VPDef::VPBlendSC:
4123 case VPDef::VPFirstOrderRecurrencePHISC:
4124 case VPDef::VPHistogramSC:
4125 case VPDef::VPWidenPHISC:
4126 case VPDef::VPWidenIntOrFpInductionSC:
4127 case VPDef::VPWidenPointerInductionSC:
4128 case VPDef::VPReductionPHISC:
4129 case VPDef::VPInterleaveEVLSC:
4130 case VPDef::VPInterleaveSC:
4131 case VPDef::VPWidenLoadEVLSC:
4132 case VPDef::VPWidenLoadSC:
4133 case VPDef::VPWidenStoreEVLSC:
4134 case VPDef::VPWidenStoreSC:
4135 break;
4136 default:
4137 llvm_unreachable("unhandled recipe");
4138 }
4139
4140 auto WillGenerateTargetVectors = [&TTI, VF](Type *VectorTy) {
4141 unsigned NumLegalParts = TTI.getNumberOfParts(VectorTy);
4142 if (!NumLegalParts)
4143 return false;
4144 if (VF.isScalable()) {
4145 // <vscale x 1 x iN> is assumed to be profitable over iN because
4146 // scalable registers are a distinct register class from scalar
4147 // ones. If we ever find a target which wants to lower scalable
4148 // vectors back to scalars, we'll need to update this code to
4149 // explicitly ask TTI about the register class uses for each part.
4150 return NumLegalParts <= VF.getKnownMinValue();
4151 }
4152 // Two or more elements that share a register - are vectorized.
4153 return NumLegalParts < VF.getFixedValue();
4154 };
4155
4156 // If no def nor is a store, e.g., branches, continue - no value to check.
4157 if (R.getNumDefinedValues() == 0 &&
4159 continue;
4160 // For multi-def recipes, currently only interleaved loads, suffice to
4161 // check first def only.
4162 // For stores check their stored value; for interleaved stores suffice
4163 // the check first stored value only. In all cases this is the second
4164 // operand.
4165 VPValue *ToCheck =
4166 R.getNumDefinedValues() >= 1 ? R.getVPValue(0) : R.getOperand(1);
4167 Type *ScalarTy = TypeInfo.inferScalarType(ToCheck);
4168 if (!Visited.insert({ScalarTy}).second)
4169 continue;
4170 Type *WideTy = toVectorizedTy(ScalarTy, VF);
4171 if (any_of(getContainedTypes(WideTy), WillGenerateTargetVectors))
4172 return true;
4173 }
4174 }
4175
4176 return false;
4177}
4178
4179static bool hasReplicatorRegion(VPlan &Plan) {
4181 Plan.getVectorLoopRegion()->getEntry())),
4182 [](auto *VPRB) { return VPRB->isReplicator(); });
4183}
4184
4185#ifndef NDEBUG
4186VectorizationFactor LoopVectorizationPlanner::selectVectorizationFactor() {
4187 InstructionCost ExpectedCost = CM.expectedCost(ElementCount::getFixed(1));
4188 LLVM_DEBUG(dbgs() << "LV: Scalar loop costs: " << ExpectedCost << ".\n");
4189 assert(ExpectedCost.isValid() && "Unexpected invalid cost for scalar loop");
4190 assert(
4191 any_of(VPlans,
4192 [](std::unique_ptr<VPlan> &P) { return P->hasScalarVFOnly(); }) &&
4193 "Expected Scalar VF to be a candidate");
4194
4195 const VectorizationFactor ScalarCost(ElementCount::getFixed(1), ExpectedCost,
4196 ExpectedCost);
4197 VectorizationFactor ChosenFactor = ScalarCost;
4198
4199 bool ForceVectorization = Hints.getForce() == LoopVectorizeHints::FK_Enabled;
4200 if (ForceVectorization &&
4201 (VPlans.size() > 1 || !VPlans[0]->hasScalarVFOnly())) {
4202 // Ignore scalar width, because the user explicitly wants vectorization.
4203 // Initialize cost to max so that VF = 2 is, at least, chosen during cost
4204 // evaluation.
4205 ChosenFactor.Cost = InstructionCost::getMax();
4206 }
4207
4208 for (auto &P : VPlans) {
4209 ArrayRef<ElementCount> VFs(P->vectorFactors().begin(),
4210 P->vectorFactors().end());
4211
4213 if (any_of(VFs, [this](ElementCount VF) {
4214 return CM.shouldConsiderRegPressureForVF(VF);
4215 }))
4216 RUs = calculateRegisterUsageForPlan(*P, VFs, TTI, CM.ValuesToIgnore);
4217
4218 for (unsigned I = 0; I < VFs.size(); I++) {
4219 ElementCount VF = VFs[I];
4220 // The cost for scalar VF=1 is already calculated, so ignore it.
4221 if (VF.isScalar())
4222 continue;
4223
4224 /// If the register pressure needs to be considered for VF,
4225 /// don't consider the VF as valid if it exceeds the number
4226 /// of registers for the target.
4227 if (CM.shouldConsiderRegPressureForVF(VF) &&
4228 RUs[I].exceedsMaxNumRegs(TTI, ForceTargetNumVectorRegs))
4229 continue;
4230
4231 InstructionCost C = CM.expectedCost(VF);
4232
4233 // Add on other costs that are modelled in VPlan, but not in the legacy
4234 // cost model.
4235 VPCostContext CostCtx(CM.TTI, *CM.TLI, *P, CM, CM.CostKind,
4236 *CM.PSE.getSE(), OrigLoop);
4237 VPRegionBlock *VectorRegion = P->getVectorLoopRegion();
4238 assert(VectorRegion && "Expected to have a vector region!");
4239 for (VPBasicBlock *VPBB : VPBlockUtils::blocksOnly<VPBasicBlock>(
4240 vp_depth_first_shallow(VectorRegion->getEntry()))) {
4241 for (VPRecipeBase &R : *VPBB) {
4242 auto *VPI = dyn_cast<VPInstruction>(&R);
4243 if (!VPI)
4244 continue;
4245 switch (VPI->getOpcode()) {
4246 // Selects are only modelled in the legacy cost model for safe
4247 // divisors.
4248 case Instruction::Select: {
4249 if (auto *WR =
4250 dyn_cast_or_null<VPWidenRecipe>(VPI->getSingleUser())) {
4251 switch (WR->getOpcode()) {
4252 case Instruction::UDiv:
4253 case Instruction::SDiv:
4254 case Instruction::URem:
4255 case Instruction::SRem:
4256 continue;
4257 default:
4258 break;
4259 }
4260 }
4261 C += VPI->cost(VF, CostCtx);
4262 break;
4263 }
4265 unsigned Multiplier =
4266 cast<ConstantInt>(VPI->getOperand(2)->getLiveInIRValue())
4267 ->getZExtValue();
4268 C += VPI->cost(VF * Multiplier, CostCtx);
4269 break;
4270 }
4272 C += VPI->cost(VF, CostCtx);
4273 break;
4274 default:
4275 break;
4276 }
4277 }
4278 }
4279
4280 VectorizationFactor Candidate(VF, C, ScalarCost.ScalarCost);
4281 unsigned Width =
4282 estimateElementCount(Candidate.Width, CM.getVScaleForTuning());
4283 LLVM_DEBUG(dbgs() << "LV: Vector loop of width " << VF
4284 << " costs: " << (Candidate.Cost / Width));
4285 if (VF.isScalable())
4286 LLVM_DEBUG(dbgs() << " (assuming a minimum vscale of "
4287 << CM.getVScaleForTuning().value_or(1) << ")");
4288 LLVM_DEBUG(dbgs() << ".\n");
4289
4290 if (!ForceVectorization && !willGenerateVectors(*P, VF, TTI)) {
4291 LLVM_DEBUG(
4292 dbgs()
4293 << "LV: Not considering vector loop of width " << VF
4294 << " because it will not generate any vector instructions.\n");
4295 continue;
4296 }
4297
4298 if (CM.OptForSize && !ForceVectorization && hasReplicatorRegion(*P)) {
4299 LLVM_DEBUG(
4300 dbgs()
4301 << "LV: Not considering vector loop of width " << VF
4302 << " because it would cause replicated blocks to be generated,"
4303 << " which isn't allowed when optimizing for size.\n");
4304 continue;
4305 }
4306
4307 if (isMoreProfitable(Candidate, ChosenFactor, P->hasScalarTail()))
4308 ChosenFactor = Candidate;
4309 }
4310 }
4311
4312 if (!EnableCondStoresVectorization && CM.hasPredStores()) {
4314 "There are conditional stores.",
4315 "store that is conditionally executed prevents vectorization",
4316 "ConditionalStore", ORE, OrigLoop);
4317 ChosenFactor = ScalarCost;
4318 }
4319
4320 LLVM_DEBUG(if (ForceVectorization && !ChosenFactor.Width.isScalar() &&
4321 !isMoreProfitable(ChosenFactor, ScalarCost,
4322 !CM.foldTailByMasking())) dbgs()
4323 << "LV: Vectorization seems to be not beneficial, "
4324 << "but was forced by a user.\n");
4325 return ChosenFactor;
4326}
4327#endif
4328
4329bool LoopVectorizationPlanner::isCandidateForEpilogueVectorization(
4330 ElementCount VF) const {
4331 // Cross iteration phis such as fixed-order recurrences and FMaxNum/FMinNum
4332 // reductions need special handling and are currently unsupported.
4333 if (any_of(OrigLoop->getHeader()->phis(), [&](PHINode &Phi) {
4334 if (!Legal->isReductionVariable(&Phi))
4335 return Legal->isFixedOrderRecurrence(&Phi);
4336 return RecurrenceDescriptor::isFPMinMaxNumRecurrenceKind(
4337 Legal->getRecurrenceDescriptor(&Phi).getRecurrenceKind());
4338 }))
4339 return false;
4340
4341 // Phis with uses outside of the loop require special handling and are
4342 // currently unsupported.
4343 for (const auto &Entry : Legal->getInductionVars()) {
4344 // Look for uses of the value of the induction at the last iteration.
4345 Value *PostInc =
4346 Entry.first->getIncomingValueForBlock(OrigLoop->getLoopLatch());
4347 for (User *U : PostInc->users())
4348 if (!OrigLoop->contains(cast<Instruction>(U)))
4349 return false;
4350 // Look for uses of penultimate value of the induction.
4351 for (User *U : Entry.first->users())
4352 if (!OrigLoop->contains(cast<Instruction>(U)))
4353 return false;
4354 }
4355
4356 // Epilogue vectorization code has not been auditted to ensure it handles
4357 // non-latch exits properly. It may be fine, but it needs auditted and
4358 // tested.
4359 // TODO: Add support for loops with an early exit.
4360 if (OrigLoop->getExitingBlock() != OrigLoop->getLoopLatch())
4361 return false;
4362
4363 return true;
4364}
4365
4367 const ElementCount VF, const unsigned IC) const {
4368 // FIXME: We need a much better cost-model to take different parameters such
4369 // as register pressure, code size increase and cost of extra branches into
4370 // account. For now we apply a very crude heuristic and only consider loops
4371 // with vectorization factors larger than a certain value.
4372
4373 // Allow the target to opt out entirely.
4374 if (!TTI.preferEpilogueVectorization())
4375 return false;
4376
4377 // We also consider epilogue vectorization unprofitable for targets that don't
4378 // consider interleaving beneficial (eg. MVE).
4379 if (TTI.getMaxInterleaveFactor(VF) <= 1)
4380 return false;
4381
4382 unsigned MinVFThreshold = EpilogueVectorizationMinVF.getNumOccurrences() > 0
4384 : TTI.getEpilogueVectorizationMinVF();
4385 return estimateElementCount(VF * IC, VScaleForTuning) >= MinVFThreshold;
4386}
4387
4389 const ElementCount MainLoopVF, unsigned IC) {
4392 LLVM_DEBUG(dbgs() << "LEV: Epilogue vectorization is disabled.\n");
4393 return Result;
4394 }
4395
4396 if (!CM.isScalarEpilogueAllowed()) {
4397 LLVM_DEBUG(dbgs() << "LEV: Unable to vectorize epilogue because no "
4398 "epilogue is allowed.\n");
4399 return Result;
4400 }
4401
4402 // Not really a cost consideration, but check for unsupported cases here to
4403 // simplify the logic.
4404 if (!isCandidateForEpilogueVectorization(MainLoopVF)) {
4405 LLVM_DEBUG(dbgs() << "LEV: Unable to vectorize epilogue because the loop "
4406 "is not a supported candidate.\n");
4407 return Result;
4408 }
4409
4411 LLVM_DEBUG(dbgs() << "LEV: Epilogue vectorization factor is forced.\n");
4413 if (hasPlanWithVF(ForcedEC))
4414 return {ForcedEC, 0, 0};
4415
4416 LLVM_DEBUG(dbgs() << "LEV: Epilogue vectorization forced factor is not "
4417 "viable.\n");
4418 return Result;
4419 }
4420
4421 if (OrigLoop->getHeader()->getParent()->hasOptSize()) {
4422 LLVM_DEBUG(
4423 dbgs() << "LEV: Epilogue vectorization skipped due to opt for size.\n");
4424 return Result;
4425 }
4426
4427 if (!CM.isEpilogueVectorizationProfitable(MainLoopVF, IC)) {
4428 LLVM_DEBUG(dbgs() << "LEV: Epilogue vectorization is not profitable for "
4429 "this loop\n");
4430 return Result;
4431 }
4432
4433 // If MainLoopVF = vscale x 2, and vscale is expected to be 4, then we know
4434 // the main loop handles 8 lanes per iteration. We could still benefit from
4435 // vectorizing the epilogue loop with VF=4.
4436 ElementCount EstimatedRuntimeVF = ElementCount::getFixed(
4437 estimateElementCount(MainLoopVF, CM.getVScaleForTuning()));
4438
4439 ScalarEvolution &SE = *PSE.getSE();
4440 Type *TCType = Legal->getWidestInductionType();
4441 const SCEV *RemainingIterations = nullptr;
4442 unsigned MaxTripCount = 0;
4443 const SCEV *TC =
4444 vputils::getSCEVExprForVPValue(getPlanFor(MainLoopVF).getTripCount(), SE);
4445 assert(!isa<SCEVCouldNotCompute>(TC) && "Trip count SCEV must be computable");
4446 const SCEV *KnownMinTC;
4447 bool ScalableTC = match(TC, m_scev_c_Mul(m_SCEV(KnownMinTC), m_SCEVVScale()));
4448 bool ScalableRemIter = false;
4449 // Use versions of TC and VF in which both are either scalable or fixed.
4450 if (ScalableTC == MainLoopVF.isScalable()) {
4451 ScalableRemIter = ScalableTC;
4452 RemainingIterations =
4453 SE.getURemExpr(TC, SE.getElementCount(TCType, MainLoopVF * IC));
4454 } else if (ScalableTC) {
4455 const SCEV *EstimatedTC = SE.getMulExpr(
4456 KnownMinTC,
4457 SE.getConstant(TCType, CM.getVScaleForTuning().value_or(1)));
4458 RemainingIterations = SE.getURemExpr(
4459 EstimatedTC, SE.getElementCount(TCType, MainLoopVF * IC));
4460 } else
4461 RemainingIterations =
4462 SE.getURemExpr(TC, SE.getElementCount(TCType, EstimatedRuntimeVF * IC));
4463
4464 // No iterations left to process in the epilogue.
4465 if (RemainingIterations->isZero())
4466 return Result;
4467
4468 if (MainLoopVF.isFixed()) {
4469 MaxTripCount = MainLoopVF.getFixedValue() * IC - 1;
4470 if (SE.isKnownPredicate(CmpInst::ICMP_ULT, RemainingIterations,
4471 SE.getConstant(TCType, MaxTripCount))) {
4472 MaxTripCount = SE.getUnsignedRangeMax(RemainingIterations).getZExtValue();
4473 }
4474 LLVM_DEBUG(dbgs() << "LEV: Maximum Trip Count for Epilogue: "
4475 << MaxTripCount << "\n");
4476 }
4477
4478 auto SkipVF = [&](const SCEV *VF, const SCEV *RemIter) -> bool {
4479 return SE.isKnownPredicate(CmpInst::ICMP_UGT, VF, RemIter);
4480 };
4481 for (auto &NextVF : ProfitableVFs) {
4482 // Skip candidate VFs without a corresponding VPlan.
4483 if (!hasPlanWithVF(NextVF.Width))
4484 continue;
4485
4486 // Skip candidate VFs with widths >= the (estimated) runtime VF (scalable
4487 // vectors) or > the VF of the main loop (fixed vectors).
4488 if ((!NextVF.Width.isScalable() && MainLoopVF.isScalable() &&
4489 ElementCount::isKnownGE(NextVF.Width, EstimatedRuntimeVF)) ||
4490 (NextVF.Width.isScalable() &&
4491 ElementCount::isKnownGE(NextVF.Width, MainLoopVF)) ||
4492 (!NextVF.Width.isScalable() && !MainLoopVF.isScalable() &&
4493 ElementCount::isKnownGT(NextVF.Width, MainLoopVF)))
4494 continue;
4495
4496 // If NextVF is greater than the number of remaining iterations, the
4497 // epilogue loop would be dead. Skip such factors.
4498 // TODO: We should also consider comparing against a scalable
4499 // RemainingIterations when SCEV be able to evaluate non-canonical
4500 // vscale-based expressions.
4501 if (!ScalableRemIter) {
4502 // Handle the case where NextVF and RemainingIterations are in different
4503 // numerical spaces.
4504 ElementCount EC = NextVF.Width;
4505 if (NextVF.Width.isScalable())
4507 estimateElementCount(NextVF.Width, CM.getVScaleForTuning()));
4508 if (SkipVF(SE.getElementCount(TCType, EC), RemainingIterations))
4509 continue;
4510 }
4511
4512 if (Result.Width.isScalar() ||
4513 isMoreProfitable(NextVF, Result, MaxTripCount, !CM.foldTailByMasking(),
4514 /*IsEpilogue*/ true))
4515 Result = NextVF;
4516 }
4517
4518 if (Result != VectorizationFactor::Disabled())
4519 LLVM_DEBUG(dbgs() << "LEV: Vectorizing epilogue loop with VF = "
4520 << Result.Width << "\n");
4521 return Result;
4522}
4523
4524std::pair<unsigned, unsigned>
4526 unsigned MinWidth = -1U;
4527 unsigned MaxWidth = 8;
4528 const DataLayout &DL = TheFunction->getDataLayout();
4529 // For in-loop reductions, no element types are added to ElementTypesInLoop
4530 // if there are no loads/stores in the loop. In this case, check through the
4531 // reduction variables to determine the maximum width.
4532 if (ElementTypesInLoop.empty() && !Legal->getReductionVars().empty()) {
4533 for (const auto &PhiDescriptorPair : Legal->getReductionVars()) {
4534 const RecurrenceDescriptor &RdxDesc = PhiDescriptorPair.second;
4535 // When finding the min width used by the recurrence we need to account
4536 // for casts on the input operands of the recurrence.
4537 MinWidth = std::min(
4538 MinWidth,
4539 std::min(RdxDesc.getMinWidthCastToRecurrenceTypeInBits(),
4541 MaxWidth = std::max(MaxWidth,
4543 }
4544 } else {
4545 for (Type *T : ElementTypesInLoop) {
4546 MinWidth = std::min<unsigned>(
4547 MinWidth, DL.getTypeSizeInBits(T->getScalarType()).getFixedValue());
4548 MaxWidth = std::max<unsigned>(
4549 MaxWidth, DL.getTypeSizeInBits(T->getScalarType()).getFixedValue());
4550 }
4551 }
4552 return {MinWidth, MaxWidth};
4553}
4554
4556 ElementTypesInLoop.clear();
4557 // For each block.
4558 for (BasicBlock *BB : TheLoop->blocks()) {
4559 // For each instruction in the loop.
4560 for (Instruction &I : BB->instructionsWithoutDebug()) {
4561 Type *T = I.getType();
4562
4563 // Skip ignored values.
4564 if (ValuesToIgnore.count(&I))
4565 continue;
4566
4567 // Only examine Loads, Stores and PHINodes.
4568 if (!isa<LoadInst>(I) && !isa<StoreInst>(I) && !isa<PHINode>(I))
4569 continue;
4570
4571 // Examine PHI nodes that are reduction variables. Update the type to
4572 // account for the recurrence type.
4573 if (auto *PN = dyn_cast<PHINode>(&I)) {
4574 if (!Legal->isReductionVariable(PN))
4575 continue;
4576 const RecurrenceDescriptor &RdxDesc =
4577 Legal->getRecurrenceDescriptor(PN);
4579 TTI.preferInLoopReduction(RdxDesc.getRecurrenceKind(),
4580 RdxDesc.getRecurrenceType()))
4581 continue;
4582 T = RdxDesc.getRecurrenceType();
4583 }
4584
4585 // Examine the stored values.
4586 if (auto *ST = dyn_cast<StoreInst>(&I))
4587 T = ST->getValueOperand()->getType();
4588
4589 assert(T->isSized() &&
4590 "Expected the load/store/recurrence type to be sized");
4591
4592 ElementTypesInLoop.insert(T);
4593 }
4594 }
4595}
4596
4597unsigned
4599 InstructionCost LoopCost) {
4600 // -- The interleave heuristics --
4601 // We interleave the loop in order to expose ILP and reduce the loop overhead.
4602 // There are many micro-architectural considerations that we can't predict
4603 // at this level. For example, frontend pressure (on decode or fetch) due to
4604 // code size, or the number and capabilities of the execution ports.
4605 //
4606 // We use the following heuristics to select the interleave count:
4607 // 1. If the code has reductions, then we interleave to break the cross
4608 // iteration dependency.
4609 // 2. If the loop is really small, then we interleave to reduce the loop
4610 // overhead.
4611 // 3. We don't interleave if we think that we will spill registers to memory
4612 // due to the increased register pressure.
4613
4614 // Only interleave tail-folded loops if wide lane masks are requested, as the
4615 // overhead of multiple instructions to calculate the predicate is likely
4616 // not beneficial. If a scalar epilogue is not allowed for any other reason,
4617 // do not interleave.
4618 if (!CM.isScalarEpilogueAllowed() &&
4619 !(CM.preferPredicatedLoop() && CM.useWideActiveLaneMask()))
4620 return 1;
4621
4624 LLVM_DEBUG(dbgs() << "LV: Preference for VP intrinsics indicated. "
4625 "Unroll factor forced to be 1.\n");
4626 return 1;
4627 }
4628
4629 // We used the distance for the interleave count.
4630 if (!Legal->isSafeForAnyVectorWidth())
4631 return 1;
4632
4633 // We don't attempt to perform interleaving for loops with uncountable early
4634 // exits because the VPInstruction::AnyOf code cannot currently handle
4635 // multiple parts.
4636 if (Plan.hasEarlyExit())
4637 return 1;
4638
4639 const bool HasReductions =
4642
4643 // If we did not calculate the cost for VF (because the user selected the VF)
4644 // then we calculate the cost of VF here.
4645 if (LoopCost == 0) {
4646 if (VF.isScalar())
4647 LoopCost = CM.expectedCost(VF);
4648 else
4649 LoopCost = cost(Plan, VF);
4650 assert(LoopCost.isValid() && "Expected to have chosen a VF with valid cost");
4651
4652 // Loop body is free and there is no need for interleaving.
4653 if (LoopCost == 0)
4654 return 1;
4655 }
4656
4657 VPRegisterUsage R =
4658 calculateRegisterUsageForPlan(Plan, {VF}, TTI, CM.ValuesToIgnore)[0];
4659 // We divide by these constants so assume that we have at least one
4660 // instruction that uses at least one register.
4661 for (auto &Pair : R.MaxLocalUsers) {
4662 Pair.second = std::max(Pair.second, 1U);
4663 }
4664
4665 // We calculate the interleave count using the following formula.
4666 // Subtract the number of loop invariants from the number of available
4667 // registers. These registers are used by all of the interleaved instances.
4668 // Next, divide the remaining registers by the number of registers that is
4669 // required by the loop, in order to estimate how many parallel instances
4670 // fit without causing spills. All of this is rounded down if necessary to be
4671 // a power of two. We want power of two interleave count to simplify any
4672 // addressing operations or alignment considerations.
4673 // We also want power of two interleave counts to ensure that the induction
4674 // variable of the vector loop wraps to zero, when tail is folded by masking;
4675 // this currently happens when OptForSize, in which case IC is set to 1 above.
4676 unsigned IC = UINT_MAX;
4677
4678 for (const auto &Pair : R.MaxLocalUsers) {
4679 unsigned TargetNumRegisters = TTI.getNumberOfRegisters(Pair.first);
4680 LLVM_DEBUG(dbgs() << "LV: The target has " << TargetNumRegisters
4681 << " registers of "
4682 << TTI.getRegisterClassName(Pair.first)
4683 << " register class\n");
4684 if (VF.isScalar()) {
4685 if (ForceTargetNumScalarRegs.getNumOccurrences() > 0)
4686 TargetNumRegisters = ForceTargetNumScalarRegs;
4687 } else {
4688 if (ForceTargetNumVectorRegs.getNumOccurrences() > 0)
4689 TargetNumRegisters = ForceTargetNumVectorRegs;
4690 }
4691 unsigned MaxLocalUsers = Pair.second;
4692 unsigned LoopInvariantRegs = 0;
4693 if (R.LoopInvariantRegs.contains(Pair.first))
4694 LoopInvariantRegs = R.LoopInvariantRegs[Pair.first];
4695
4696 unsigned TmpIC = llvm::bit_floor((TargetNumRegisters - LoopInvariantRegs) /
4697 MaxLocalUsers);
4698 // Don't count the induction variable as interleaved.
4700 TmpIC = llvm::bit_floor((TargetNumRegisters - LoopInvariantRegs - 1) /
4701 std::max(1U, (MaxLocalUsers - 1)));
4702 }
4703
4704 IC = std::min(IC, TmpIC);
4705 }
4706
4707 // Clamp the interleave ranges to reasonable counts.
4708 unsigned MaxInterleaveCount = TTI.getMaxInterleaveFactor(VF);
4709
4710 // Check if the user has overridden the max.
4711 if (VF.isScalar()) {
4712 if (ForceTargetMaxScalarInterleaveFactor.getNumOccurrences() > 0)
4713 MaxInterleaveCount = ForceTargetMaxScalarInterleaveFactor;
4714 } else {
4715 if (ForceTargetMaxVectorInterleaveFactor.getNumOccurrences() > 0)
4716 MaxInterleaveCount = ForceTargetMaxVectorInterleaveFactor;
4717 }
4718
4719 // Try to get the exact trip count, or an estimate based on profiling data or
4720 // ConstantMax from PSE, failing that.
4721 auto BestKnownTC = getSmallBestKnownTC(PSE, OrigLoop);
4722
4723 // For fixed length VFs treat a scalable trip count as unknown.
4724 if (BestKnownTC && (BestKnownTC->isFixed() || VF.isScalable())) {
4725 // Re-evaluate trip counts and VFs to be in the same numerical space.
4726 unsigned AvailableTC =
4727 estimateElementCount(*BestKnownTC, CM.getVScaleForTuning());
4728 unsigned EstimatedVF = estimateElementCount(VF, CM.getVScaleForTuning());
4729
4730 // At least one iteration must be scalar when this constraint holds. So the
4731 // maximum available iterations for interleaving is one less.
4732 if (CM.requiresScalarEpilogue(VF.isVector()))
4733 --AvailableTC;
4734
4735 unsigned InterleaveCountLB = bit_floor(std::max(
4736 1u, std::min(AvailableTC / (EstimatedVF * 2), MaxInterleaveCount)));
4737
4738 if (getSmallConstantTripCount(PSE.getSE(), OrigLoop).isNonZero()) {
4739 // If the best known trip count is exact, we select between two
4740 // prospective ICs, where
4741 //
4742 // 1) the aggressive IC is capped by the trip count divided by VF
4743 // 2) the conservative IC is capped by the trip count divided by (VF * 2)
4744 //
4745 // The final IC is selected in a way that the epilogue loop trip count is
4746 // minimized while maximizing the IC itself, so that we either run the
4747 // vector loop at least once if it generates a small epilogue loop, or
4748 // else we run the vector loop at least twice.
4749
4750 unsigned InterleaveCountUB = bit_floor(std::max(
4751 1u, std::min(AvailableTC / EstimatedVF, MaxInterleaveCount)));
4752 MaxInterleaveCount = InterleaveCountLB;
4753
4754 if (InterleaveCountUB != InterleaveCountLB) {
4755 unsigned TailTripCountUB =
4756 (AvailableTC % (EstimatedVF * InterleaveCountUB));
4757 unsigned TailTripCountLB =
4758 (AvailableTC % (EstimatedVF * InterleaveCountLB));
4759 // If both produce same scalar tail, maximize the IC to do the same work
4760 // in fewer vector loop iterations
4761 if (TailTripCountUB == TailTripCountLB)
4762 MaxInterleaveCount = InterleaveCountUB;
4763 }
4764 } else {
4765 // If trip count is an estimated compile time constant, limit the
4766 // IC to be capped by the trip count divided by VF * 2, such that the
4767 // vector loop runs at least twice to make interleaving seem profitable
4768 // when there is an epilogue loop present. Since exact Trip count is not
4769 // known we choose to be conservative in our IC estimate.
4770 MaxInterleaveCount = InterleaveCountLB;
4771 }
4772 }
4773
4774 assert(MaxInterleaveCount > 0 &&
4775 "Maximum interleave count must be greater than 0");
4776
4777 // Clamp the calculated IC to be between the 1 and the max interleave count
4778 // that the target and trip count allows.
4779 if (IC > MaxInterleaveCount)
4780 IC = MaxInterleaveCount;
4781 else
4782 // Make sure IC is greater than 0.
4783 IC = std::max(1u, IC);
4784
4785 assert(IC > 0 && "Interleave count must be greater than 0.");
4786
4787 // Interleave if we vectorized this loop and there is a reduction that could
4788 // benefit from interleaving.
4789 if (VF.isVector() && HasReductions) {
4790 LLVM_DEBUG(dbgs() << "LV: Interleaving because of reductions.\n");
4791 return IC;
4792 }
4793
4794 // For any scalar loop that either requires runtime checks or predication we
4795 // are better off leaving this to the unroller. Note that if we've already
4796 // vectorized the loop we will have done the runtime check and so interleaving
4797 // won't require further checks.
4798 bool ScalarInterleavingRequiresPredication =
4799 (VF.isScalar() && any_of(OrigLoop->blocks(), [this](BasicBlock *BB) {
4800 return Legal->blockNeedsPredication(BB);
4801 }));
4802 bool ScalarInterleavingRequiresRuntimePointerCheck =
4803 (VF.isScalar() && Legal->getRuntimePointerChecking()->Need);
4804
4805 // We want to interleave small loops in order to reduce the loop overhead and
4806 // potentially expose ILP opportunities.
4807 LLVM_DEBUG(dbgs() << "LV: Loop cost is " << LoopCost << '\n'
4808 << "LV: IC is " << IC << '\n'
4809 << "LV: VF is " << VF << '\n');
4810 const bool AggressivelyInterleaveReductions =
4811 TTI.enableAggressiveInterleaving(HasReductions);
4812 if (!ScalarInterleavingRequiresRuntimePointerCheck &&
4813 !ScalarInterleavingRequiresPredication && LoopCost < SmallLoopCost) {
4814 // We assume that the cost overhead is 1 and we use the cost model
4815 // to estimate the cost of the loop and interleave until the cost of the
4816 // loop overhead is about 5% of the cost of the loop.
4817 unsigned SmallIC = std::min(IC, (unsigned)llvm::bit_floor<uint64_t>(
4818 SmallLoopCost / LoopCost.getValue()));
4819
4820 // Interleave until store/load ports (estimated by max interleave count) are
4821 // saturated.
4822 unsigned NumStores = 0;
4823 unsigned NumLoads = 0;
4826 for (VPRecipeBase &R : *VPBB) {
4828 NumLoads++;
4829 continue;
4830 }
4832 NumStores++;
4833 continue;
4834 }
4835
4836 if (auto *InterleaveR = dyn_cast<VPInterleaveRecipe>(&R)) {
4837 if (unsigned StoreOps = InterleaveR->getNumStoreOperands())
4838 NumStores += StoreOps;
4839 else
4840 NumLoads += InterleaveR->getNumDefinedValues();
4841 continue;
4842 }
4843 if (auto *RepR = dyn_cast<VPReplicateRecipe>(&R)) {
4844 NumLoads += isa<LoadInst>(RepR->getUnderlyingInstr());
4845 NumStores += isa<StoreInst>(RepR->getUnderlyingInstr());
4846 continue;
4847 }
4848 if (isa<VPHistogramRecipe>(&R)) {
4849 NumLoads++;
4850 NumStores++;
4851 continue;
4852 }
4853 }
4854 }
4855 unsigned StoresIC = IC / (NumStores ? NumStores : 1);
4856 unsigned LoadsIC = IC / (NumLoads ? NumLoads : 1);
4857
4858 // There is little point in interleaving for reductions containing selects
4859 // and compares when VF=1 since it may just create more overhead than it's
4860 // worth for loops with small trip counts. This is because we still have to
4861 // do the final reduction after the loop.
4862 bool HasSelectCmpReductions =
4863 HasReductions &&
4865 [](VPRecipeBase &R) {
4866 auto *RedR = dyn_cast<VPReductionPHIRecipe>(&R);
4867 return RedR && (RecurrenceDescriptor::isAnyOfRecurrenceKind(
4868 RedR->getRecurrenceKind()) ||
4869 RecurrenceDescriptor::isFindIVRecurrenceKind(
4870 RedR->getRecurrenceKind()));
4871 });
4872 if (HasSelectCmpReductions) {
4873 LLVM_DEBUG(dbgs() << "LV: Not interleaving select-cmp reductions.\n");
4874 return 1;
4875 }
4876
4877 // If we have a scalar reduction (vector reductions are already dealt with
4878 // by this point), we can increase the critical path length if the loop
4879 // we're interleaving is inside another loop. For tree-wise reductions
4880 // set the limit to 2, and for ordered reductions it's best to disable
4881 // interleaving entirely.
4882 if (HasReductions && OrigLoop->getLoopDepth() > 1) {
4883 bool HasOrderedReductions =
4885 [](VPRecipeBase &R) {
4886 auto *RedR = dyn_cast<VPReductionPHIRecipe>(&R);
4887
4888 return RedR && RedR->isOrdered();
4889 });
4890 if (HasOrderedReductions) {
4891 LLVM_DEBUG(
4892 dbgs() << "LV: Not interleaving scalar ordered reductions.\n");
4893 return 1;
4894 }
4895
4896 unsigned F = MaxNestedScalarReductionIC;
4897 SmallIC = std::min(SmallIC, F);
4898 StoresIC = std::min(StoresIC, F);
4899 LoadsIC = std::min(LoadsIC, F);
4900 }
4901
4903 std::max(StoresIC, LoadsIC) > SmallIC) {
4904 LLVM_DEBUG(
4905 dbgs() << "LV: Interleaving to saturate store or load ports.\n");
4906 return std::max(StoresIC, LoadsIC);
4907 }
4908
4909 // If there are scalar reductions and TTI has enabled aggressive
4910 // interleaving for reductions, we will interleave to expose ILP.
4911 if (VF.isScalar() && AggressivelyInterleaveReductions) {
4912 LLVM_DEBUG(dbgs() << "LV: Interleaving to expose ILP.\n");
4913 // Interleave no less than SmallIC but not as aggressive as the normal IC
4914 // to satisfy the rare situation when resources are too limited.
4915 return std::max(IC / 2, SmallIC);
4916 }
4917
4918 LLVM_DEBUG(dbgs() << "LV: Interleaving to reduce branch cost.\n");
4919 return SmallIC;
4920 }
4921
4922 // Interleave if this is a large loop (small loops are already dealt with by
4923 // this point) that could benefit from interleaving.
4924 if (AggressivelyInterleaveReductions) {
4925 LLVM_DEBUG(dbgs() << "LV: Interleaving to expose ILP.\n");
4926 return IC;
4927 }
4928
4929 LLVM_DEBUG(dbgs() << "LV: Not Interleaving.\n");
4930 return 1;
4931}
4932
4933bool LoopVectorizationCostModel::useEmulatedMaskMemRefHack(Instruction *I,
4934 ElementCount VF) {
4935 // TODO: Cost model for emulated masked load/store is completely
4936 // broken. This hack guides the cost model to use an artificially
4937 // high enough value to practically disable vectorization with such
4938 // operations, except where previously deployed legality hack allowed
4939 // using very low cost values. This is to avoid regressions coming simply
4940 // from moving "masked load/store" check from legality to cost model.
4941 // Masked Load/Gather emulation was previously never allowed.
4942 // Limited number of Masked Store/Scatter emulation was allowed.
4943 assert((isPredicatedInst(I)) &&
4944 "Expecting a scalar emulated instruction");
4945 return isa<LoadInst>(I) ||
4946 (isa<StoreInst>(I) &&
4947 NumPredStores > NumberOfStoresToPredicate);
4948}
4949
4951 assert(VF.isVector() && "Expected VF >= 2");
4952
4953 // If we've already collected the instructions to scalarize or the predicated
4954 // BBs after vectorization, there's nothing to do. Collection may already have
4955 // occurred if we have a user-selected VF and are now computing the expected
4956 // cost for interleaving.
4957 if (InstsToScalarize.contains(VF) ||
4958 PredicatedBBsAfterVectorization.contains(VF))
4959 return;
4960
4961 // Initialize a mapping for VF in InstsToScalalarize. If we find that it's
4962 // not profitable to scalarize any instructions, the presence of VF in the
4963 // map will indicate that we've analyzed it already.
4964 ScalarCostsTy &ScalarCostsVF = InstsToScalarize[VF];
4965
4966 // Find all the instructions that are scalar with predication in the loop and
4967 // determine if it would be better to not if-convert the blocks they are in.
4968 // If so, we also record the instructions to scalarize.
4969 for (BasicBlock *BB : TheLoop->blocks()) {
4971 continue;
4972 for (Instruction &I : *BB)
4973 if (isScalarWithPredication(&I, VF)) {
4974 ScalarCostsTy ScalarCosts;
4975 // Do not apply discount logic for:
4976 // 1. Scalars after vectorization, as there will only be a single copy
4977 // of the instruction.
4978 // 2. Scalable VF, as that would lead to invalid scalarization costs.
4979 // 3. Emulated masked memrefs, if a hacked cost is needed.
4980 if (!isScalarAfterVectorization(&I, VF) && !VF.isScalable() &&
4981 !useEmulatedMaskMemRefHack(&I, VF) &&
4982 computePredInstDiscount(&I, ScalarCosts, VF) >= 0) {
4983 for (const auto &[I, IC] : ScalarCosts)
4984 ScalarCostsVF.insert({I, IC});
4985 // Check if we decided to scalarize a call. If so, update the widening
4986 // decision of the call to CM_Scalarize with the computed scalar cost.
4987 for (const auto &[I, Cost] : ScalarCosts) {
4988 auto *CI = dyn_cast<CallInst>(I);
4989 if (!CI || !CallWideningDecisions.contains({CI, VF}))
4990 continue;
4991 CallWideningDecisions[{CI, VF}].Kind = CM_Scalarize;
4992 CallWideningDecisions[{CI, VF}].Cost = Cost;
4993 }
4994 }
4995 // Remember that BB will remain after vectorization.
4996 PredicatedBBsAfterVectorization[VF].insert(BB);
4997 for (auto *Pred : predecessors(BB)) {
4998 if (Pred->getSingleSuccessor() == BB)
4999 PredicatedBBsAfterVectorization[VF].insert(Pred);
5000 }
5001 }
5002 }
5003}
5004
5005InstructionCost LoopVectorizationCostModel::computePredInstDiscount(
5006 Instruction *PredInst, ScalarCostsTy &ScalarCosts, ElementCount VF) {
5007 assert(!isUniformAfterVectorization(PredInst, VF) &&
5008 "Instruction marked uniform-after-vectorization will be predicated");
5009
5010 // Initialize the discount to zero, meaning that the scalar version and the
5011 // vector version cost the same.
5012 InstructionCost Discount = 0;
5013
5014 // Holds instructions to analyze. The instructions we visit are mapped in
5015 // ScalarCosts. Those instructions are the ones that would be scalarized if
5016 // we find that the scalar version costs less.
5018
5019 // Returns true if the given instruction can be scalarized.
5020 auto CanBeScalarized = [&](Instruction *I) -> bool {
5021 // We only attempt to scalarize instructions forming a single-use chain
5022 // from the original predicated block that would otherwise be vectorized.
5023 // Although not strictly necessary, we give up on instructions we know will
5024 // already be scalar to avoid traversing chains that are unlikely to be
5025 // beneficial.
5026 if (!I->hasOneUse() || PredInst->getParent() != I->getParent() ||
5027 isScalarAfterVectorization(I, VF))
5028 return false;
5029
5030 // If the instruction is scalar with predication, it will be analyzed
5031 // separately. We ignore it within the context of PredInst.
5032 if (isScalarWithPredication(I, VF))
5033 return false;
5034
5035 // If any of the instruction's operands are uniform after vectorization,
5036 // the instruction cannot be scalarized. This prevents, for example, a
5037 // masked load from being scalarized.
5038 //
5039 // We assume we will only emit a value for lane zero of an instruction
5040 // marked uniform after vectorization, rather than VF identical values.
5041 // Thus, if we scalarize an instruction that uses a uniform, we would
5042 // create uses of values corresponding to the lanes we aren't emitting code
5043 // for. This behavior can be changed by allowing getScalarValue to clone
5044 // the lane zero values for uniforms rather than asserting.
5045 for (Use &U : I->operands())
5046 if (auto *J = dyn_cast<Instruction>(U.get()))
5047 if (isUniformAfterVectorization(J, VF))
5048 return false;
5049
5050 // Otherwise, we can scalarize the instruction.
5051 return true;
5052 };
5053
5054 // Compute the expected cost discount from scalarizing the entire expression
5055 // feeding the predicated instruction. We currently only consider expressions
5056 // that are single-use instruction chains.
5057 Worklist.push_back(PredInst);
5058 while (!Worklist.empty()) {
5059 Instruction *I = Worklist.pop_back_val();
5060
5061 // If we've already analyzed the instruction, there's nothing to do.
5062 if (ScalarCosts.contains(I))
5063 continue;
5064
5065 // Cannot scalarize fixed-order recurrence phis at the moment.
5066 if (isa<PHINode>(I) && Legal->isFixedOrderRecurrence(cast<PHINode>(I)))
5067 continue;
5068
5069 // Compute the cost of the vector instruction. Note that this cost already
5070 // includes the scalarization overhead of the predicated instruction.
5071 InstructionCost VectorCost = getInstructionCost(I, VF);
5072
5073 // Compute the cost of the scalarized instruction. This cost is the cost of
5074 // the instruction as if it wasn't if-converted and instead remained in the
5075 // predicated block. We will scale this cost by block probability after
5076 // computing the scalarization overhead.
5077 InstructionCost ScalarCost =
5078 VF.getFixedValue() * getInstructionCost(I, ElementCount::getFixed(1));
5079
5080 // Compute the scalarization overhead of needed insertelement instructions
5081 // and phi nodes.
5082 if (isScalarWithPredication(I, VF) && !I->getType()->isVoidTy()) {
5083 Type *WideTy = toVectorizedTy(I->getType(), VF);
5084 for (Type *VectorTy : getContainedTypes(WideTy)) {
5085 ScalarCost += TTI.getScalarizationOverhead(
5087 /*Insert=*/true,
5088 /*Extract=*/false, CostKind);
5089 }
5090 ScalarCost +=
5091 VF.getFixedValue() * TTI.getCFInstrCost(Instruction::PHI, CostKind);
5092 }
5093
5094 // Compute the scalarization overhead of needed extractelement
5095 // instructions. For each of the instruction's operands, if the operand can
5096 // be scalarized, add it to the worklist; otherwise, account for the
5097 // overhead.
5098 for (Use &U : I->operands())
5099 if (auto *J = dyn_cast<Instruction>(U.get())) {
5100 assert(canVectorizeTy(J->getType()) &&
5101 "Instruction has non-scalar type");
5102 if (CanBeScalarized(J))
5103 Worklist.push_back(J);
5104 else if (needsExtract(J, VF)) {
5105 Type *WideTy = toVectorizedTy(J->getType(), VF);
5106 for (Type *VectorTy : getContainedTypes(WideTy)) {
5107 ScalarCost += TTI.getScalarizationOverhead(
5108 cast<VectorType>(VectorTy),
5109 APInt::getAllOnes(VF.getFixedValue()), /*Insert*/ false,
5110 /*Extract*/ true, CostKind);
5111 }
5112 }
5113 }
5114
5115 // Scale the total scalar cost by block probability.
5116 ScalarCost /= getPredBlockCostDivisor(CostKind, I->getParent());
5117
5118 // Compute the discount. A non-negative discount means the vector version
5119 // of the instruction costs more, and scalarizing would be beneficial.
5120 Discount += VectorCost - ScalarCost;
5121 ScalarCosts[I] = ScalarCost;
5122 }
5123
5124 return Discount;
5125}
5126
5129
5130 // If the vector loop gets executed exactly once with the given VF, ignore the
5131 // costs of comparison and induction instructions, as they'll get simplified
5132 // away.
5133 SmallPtrSet<Instruction *, 2> ValuesToIgnoreForVF;
5134 auto TC = getSmallConstantTripCount(PSE.getSE(), TheLoop);
5135 if (TC == VF && !foldTailByMasking())
5137 ValuesToIgnoreForVF);
5138
5139 // For each block.
5140 for (BasicBlock *BB : TheLoop->blocks()) {
5141 InstructionCost BlockCost;
5142
5143 // For each instruction in the old loop.
5144 for (Instruction &I : BB->instructionsWithoutDebug()) {
5145 // Skip ignored values.
5146 if (ValuesToIgnore.count(&I) || ValuesToIgnoreForVF.count(&I) ||
5147 (VF.isVector() && VecValuesToIgnore.count(&I)))
5148 continue;
5149
5151
5152 // Check if we should override the cost.
5153 if (C.isValid() && ForceTargetInstructionCost.getNumOccurrences() > 0) {
5154 // For interleave groups, use ForceTargetInstructionCost once for the
5155 // whole group.
5156 if (VF.isVector() && getWideningDecision(&I, VF) == CM_Interleave) {
5157 if (getInterleavedAccessGroup(&I)->getInsertPos() == &I)
5159 else
5160 C = InstructionCost(0);
5161 } else {
5163 }
5164 }
5165
5166 BlockCost += C;
5167 LLVM_DEBUG(dbgs() << "LV: Found an estimated cost of " << C << " for VF "
5168 << VF << " For instruction: " << I << '\n');
5169 }
5170
5171 // If we are vectorizing a predicated block, it will have been
5172 // if-converted. This means that the block's instructions (aside from
5173 // stores and instructions that may divide by zero) will now be
5174 // unconditionally executed. For the scalar case, we may not always execute
5175 // the predicated block, if it is an if-else block. Thus, scale the block's
5176 // cost by the probability of executing it.
5177 // getPredBlockCostDivisor will return 1 for blocks that are only predicated
5178 // by the header mask when folding the tail.
5179 if (VF.isScalar())
5180 BlockCost /= getPredBlockCostDivisor(CostKind, BB);
5181
5182 Cost += BlockCost;
5183 }
5184
5185 return Cost;
5186}
5187
5188/// Gets Address Access SCEV after verifying that the access pattern
5189/// is loop invariant except the induction variable dependence.
5190///
5191/// This SCEV can be sent to the Target in order to estimate the address
5192/// calculation cost.
5194 Value *Ptr,
5197 const Loop *TheLoop) {
5198
5199 auto *Gep = dyn_cast<GetElementPtrInst>(Ptr);
5200 if (!Gep)
5201 return nullptr;
5202
5203 // We are looking for a gep with all loop invariant indices except for one
5204 // which should be an induction variable.
5205 auto *SE = PSE.getSE();
5206 unsigned NumOperands = Gep->getNumOperands();
5207 for (unsigned Idx = 1; Idx < NumOperands; ++Idx) {
5208 Value *Opd = Gep->getOperand(Idx);
5209 if (!SE->isLoopInvariant(SE->getSCEV(Opd), TheLoop) &&
5210 !Legal->isInductionVariable(Opd))
5211 return nullptr;
5212 }
5213
5214 // Now we know we have a GEP ptr, %inv, %ind, %inv. return the Ptr SCEV.
5215 return PSE.getSCEV(Ptr);
5216}
5217
5219LoopVectorizationCostModel::getMemInstScalarizationCost(Instruction *I,
5220 ElementCount VF) {
5221 assert(VF.isVector() &&
5222 "Scalarization cost of instruction implies vectorization.");
5223 if (VF.isScalable())
5224 return InstructionCost::getInvalid();
5225
5226 Type *ValTy = getLoadStoreType(I);
5227 auto *SE = PSE.getSE();
5228
5229 unsigned AS = getLoadStoreAddressSpace(I);
5231 Type *PtrTy = toVectorTy(Ptr->getType(), VF);
5232 // NOTE: PtrTy is a vector to signal `TTI::getAddressComputationCost`
5233 // that it is being called from this specific place.
5234
5235 // Figure out whether the access is strided and get the stride value
5236 // if it's known in compile time
5237 const SCEV *PtrSCEV = getAddressAccessSCEV(Ptr, Legal, PSE, TheLoop);
5238
5239 // Get the cost of the scalar memory instruction and address computation.
5241 PtrTy, SE, PtrSCEV, CostKind);
5242
5243 // Don't pass *I here, since it is scalar but will actually be part of a
5244 // vectorized loop where the user of it is a vectorized instruction.
5245 const Align Alignment = getLoadStoreAlignment(I);
5246 TTI::OperandValueInfo OpInfo = TTI::getOperandInfo(I->getOperand(0));
5247 Cost += VF.getFixedValue() *
5248 TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(), Alignment,
5249 AS, CostKind, OpInfo);
5250
5251 // Get the overhead of the extractelement and insertelement instructions
5252 // we might create due to scalarization.
5254
5255 // If we have a predicated load/store, it will need extra i1 extracts and
5256 // conditional branches, but may not be executed for each vector lane. Scale
5257 // the cost by the probability of executing the predicated block.
5258 if (isPredicatedInst(I)) {
5259 Cost /= getPredBlockCostDivisor(CostKind, I->getParent());
5260
5261 // Add the cost of an i1 extract and a branch
5262 auto *VecI1Ty =
5263 VectorType::get(IntegerType::getInt1Ty(ValTy->getContext()), VF);
5265 VecI1Ty, APInt::getAllOnes(VF.getFixedValue()),
5266 /*Insert=*/false, /*Extract=*/true, CostKind);
5267 Cost += TTI.getCFInstrCost(Instruction::Br, CostKind);
5268
5269 if (useEmulatedMaskMemRefHack(I, VF))
5270 // Artificially setting to a high enough value to practically disable
5271 // vectorization with such operations.
5272 Cost = 3000000;
5273 }
5274
5275 return Cost;
5276}
5277
5279LoopVectorizationCostModel::getConsecutiveMemOpCost(Instruction *I,
5280 ElementCount VF) {
5281 Type *ValTy = getLoadStoreType(I);
5282 auto *VectorTy = cast<VectorType>(toVectorTy(ValTy, VF));
5284 unsigned AS = getLoadStoreAddressSpace(I);
5285 int ConsecutiveStride = Legal->isConsecutivePtr(ValTy, Ptr);
5286
5287 assert((ConsecutiveStride == 1 || ConsecutiveStride == -1) &&
5288 "Stride should be 1 or -1 for consecutive memory access");
5289 const Align Alignment = getLoadStoreAlignment(I);
5291 if (Legal->isMaskRequired(I)) {
5292 unsigned IID = I->getOpcode() == Instruction::Load
5293 ? Intrinsic::masked_load
5294 : Intrinsic::masked_store;
5296 MemIntrinsicCostAttributes(IID, VectorTy, Alignment, AS), CostKind);
5297 } else {
5298 TTI::OperandValueInfo OpInfo = TTI::getOperandInfo(I->getOperand(0));
5299 Cost += TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS,
5300 CostKind, OpInfo, I);
5301 }
5302
5303 bool Reverse = ConsecutiveStride < 0;
5304 if (Reverse)
5306 VectorTy, {}, CostKind, 0);
5307 return Cost;
5308}
5309
5311LoopVectorizationCostModel::getUniformMemOpCost(Instruction *I,
5312 ElementCount VF) {
5313 assert(Legal->isUniformMemOp(*I, VF));
5314
5315 Type *ValTy = getLoadStoreType(I);
5317 auto *VectorTy = cast<VectorType>(toVectorTy(ValTy, VF));
5318 const Align Alignment = getLoadStoreAlignment(I);
5319 unsigned AS = getLoadStoreAddressSpace(I);
5320 if (isa<LoadInst>(I)) {
5321 return TTI.getAddressComputationCost(PtrTy, nullptr, nullptr, CostKind) +
5322 TTI.getMemoryOpCost(Instruction::Load, ValTy, Alignment, AS,
5323 CostKind) +
5325 VectorTy, {}, CostKind);
5326 }
5327 StoreInst *SI = cast<StoreInst>(I);
5328
5329 bool IsLoopInvariantStoreValue = Legal->isInvariant(SI->getValueOperand());
5330 // TODO: We have existing tests that request the cost of extracting element
5331 // VF.getKnownMinValue() - 1 from a scalable vector. This does not represent
5332 // the actual generated code, which involves extracting the last element of
5333 // a scalable vector where the lane to extract is unknown at compile time.
5335 TTI.getAddressComputationCost(PtrTy, nullptr, nullptr, CostKind) +
5336 TTI.getMemoryOpCost(Instruction::Store, ValTy, Alignment, AS, CostKind);
5337 if (!IsLoopInvariantStoreValue)
5338 Cost += TTI.getIndexedVectorInstrCostFromEnd(Instruction::ExtractElement,
5339 VectorTy, CostKind, 0);
5340 return Cost;
5341}
5342
5344LoopVectorizationCostModel::getGatherScatterCost(Instruction *I,
5345 ElementCount VF) {
5346 Type *ValTy = getLoadStoreType(I);
5347 auto *VectorTy = cast<VectorType>(toVectorTy(ValTy, VF));
5348 const Align Alignment = getLoadStoreAlignment(I);
5350 Type *PtrTy = Ptr->getType();
5351
5352 if (!Legal->isUniform(Ptr, VF))
5353 PtrTy = toVectorTy(PtrTy, VF);
5354
5355 unsigned IID = I->getOpcode() == Instruction::Load
5356 ? Intrinsic::masked_gather
5357 : Intrinsic::masked_scatter;
5358 return TTI.getAddressComputationCost(PtrTy, nullptr, nullptr, CostKind) +
5360 MemIntrinsicCostAttributes(IID, VectorTy, Ptr,
5361 Legal->isMaskRequired(I), Alignment, I),
5362 CostKind);
5363}
5364
5366LoopVectorizationCostModel::getInterleaveGroupCost(Instruction *I,
5367 ElementCount VF) {
5368 const auto *Group = getInterleavedAccessGroup(I);
5369 assert(Group && "Fail to get an interleaved access group.");
5370
5371 Instruction *InsertPos = Group->getInsertPos();
5372 Type *ValTy = getLoadStoreType(InsertPos);
5373 auto *VectorTy = cast<VectorType>(toVectorTy(ValTy, VF));
5374 unsigned AS = getLoadStoreAddressSpace(InsertPos);
5375
5376 unsigned InterleaveFactor = Group->getFactor();
5377 auto *WideVecTy = VectorType::get(ValTy, VF * InterleaveFactor);
5378
5379 // Holds the indices of existing members in the interleaved group.
5380 SmallVector<unsigned, 4> Indices;
5381 for (unsigned IF = 0; IF < InterleaveFactor; IF++)
5382 if (Group->getMember(IF))
5383 Indices.push_back(IF);
5384
5385 // Calculate the cost of the whole interleaved group.
5386 bool UseMaskForGaps =
5387 (Group->requiresScalarEpilogue() && !isScalarEpilogueAllowed()) ||
5388 (isa<StoreInst>(I) && !Group->isFull());
5390 InsertPos->getOpcode(), WideVecTy, Group->getFactor(), Indices,
5391 Group->getAlign(), AS, CostKind, Legal->isMaskRequired(I),
5392 UseMaskForGaps);
5393
5394 if (Group->isReverse()) {
5395 // TODO: Add support for reversed masked interleaved access.
5396 assert(!Legal->isMaskRequired(I) &&
5397 "Reverse masked interleaved access not supported.");
5398 Cost += Group->getNumMembers() *
5400 VectorTy, {}, CostKind, 0);
5401 }
5402 return Cost;
5403}
5404
5405std::optional<InstructionCost>
5407 ElementCount VF,
5408 Type *Ty) const {
5409 using namespace llvm::PatternMatch;
5410 // Early exit for no inloop reductions
5411 if (InLoopReductions.empty() || VF.isScalar() || !isa<VectorType>(Ty))
5412 return std::nullopt;
5413 auto *VectorTy = cast<VectorType>(Ty);
5414
5415 // We are looking for a pattern of, and finding the minimal acceptable cost:
5416 // reduce(mul(ext(A), ext(B))) or
5417 // reduce(mul(A, B)) or
5418 // reduce(ext(A)) or
5419 // reduce(A).
5420 // The basic idea is that we walk down the tree to do that, finding the root
5421 // reduction instruction in InLoopReductionImmediateChains. From there we find
5422 // the pattern of mul/ext and test the cost of the entire pattern vs the cost
5423 // of the components. If the reduction cost is lower then we return it for the
5424 // reduction instruction and 0 for the other instructions in the pattern. If
5425 // it is not we return an invalid cost specifying the orignal cost method
5426 // should be used.
5427 Instruction *RetI = I;
5428 if (match(RetI, m_ZExtOrSExt(m_Value()))) {
5429 if (!RetI->hasOneUser())
5430 return std::nullopt;
5431 RetI = RetI->user_back();
5432 }
5433
5434 if (match(RetI, m_OneUse(m_Mul(m_Value(), m_Value()))) &&
5435 RetI->user_back()->getOpcode() == Instruction::Add) {
5436 RetI = RetI->user_back();
5437 }
5438
5439 // Test if the found instruction is a reduction, and if not return an invalid
5440 // cost specifying the parent to use the original cost modelling.
5441 Instruction *LastChain = InLoopReductionImmediateChains.lookup(RetI);
5442 if (!LastChain)
5443 return std::nullopt;
5444
5445 // Find the reduction this chain is a part of and calculate the basic cost of
5446 // the reduction on its own.
5447 Instruction *ReductionPhi = LastChain;
5448 while (!isa<PHINode>(ReductionPhi))
5449 ReductionPhi = InLoopReductionImmediateChains.at(ReductionPhi);
5450
5451 const RecurrenceDescriptor &RdxDesc =
5452 Legal->getRecurrenceDescriptor(cast<PHINode>(ReductionPhi));
5453
5454 InstructionCost BaseCost;
5455 RecurKind RK = RdxDesc.getRecurrenceKind();
5458 BaseCost = TTI.getMinMaxReductionCost(MinMaxID, VectorTy,
5459 RdxDesc.getFastMathFlags(), CostKind);
5460 } else {
5461 BaseCost = TTI.getArithmeticReductionCost(
5462 RdxDesc.getOpcode(), VectorTy, RdxDesc.getFastMathFlags(), CostKind);
5463 }
5464
5465 // For a call to the llvm.fmuladd intrinsic we need to add the cost of a
5466 // normal fmul instruction to the cost of the fadd reduction.
5467 if (RK == RecurKind::FMulAdd)
5468 BaseCost +=
5469 TTI.getArithmeticInstrCost(Instruction::FMul, VectorTy, CostKind);
5470
5471 // If we're using ordered reductions then we can just return the base cost
5472 // here, since getArithmeticReductionCost calculates the full ordered
5473 // reduction cost when FP reassociation is not allowed.
5474 if (useOrderedReductions(RdxDesc))
5475 return BaseCost;
5476
5477 // Get the operand that was not the reduction chain and match it to one of the
5478 // patterns, returning the better cost if it is found.
5479 Instruction *RedOp = RetI->getOperand(1) == LastChain
5482
5483 VectorTy = VectorType::get(I->getOperand(0)->getType(), VectorTy);
5484
5485 Instruction *Op0, *Op1;
5486 if (RedOp && RdxDesc.getOpcode() == Instruction::Add &&
5487 match(RedOp,
5489 match(Op0, m_ZExtOrSExt(m_Value())) &&
5490 Op0->getOpcode() == Op1->getOpcode() &&
5491 Op0->getOperand(0)->getType() == Op1->getOperand(0)->getType() &&
5492 !TheLoop->isLoopInvariant(Op0) && !TheLoop->isLoopInvariant(Op1) &&
5493 (Op0->getOpcode() == RedOp->getOpcode() || Op0 == Op1)) {
5494
5495 // Matched reduce.add(ext(mul(ext(A), ext(B)))
5496 // Note that the extend opcodes need to all match, or if A==B they will have
5497 // been converted to zext(mul(sext(A), sext(A))) as it is known positive,
5498 // which is equally fine.
5499 bool IsUnsigned = isa<ZExtInst>(Op0);
5500 auto *ExtType = VectorType::get(Op0->getOperand(0)->getType(), VectorTy);
5501 auto *MulType = VectorType::get(Op0->getType(), VectorTy);
5502
5503 InstructionCost ExtCost =
5504 TTI.getCastInstrCost(Op0->getOpcode(), MulType, ExtType,
5506 InstructionCost MulCost =
5507 TTI.getArithmeticInstrCost(Instruction::Mul, MulType, CostKind);
5508 InstructionCost Ext2Cost =
5509 TTI.getCastInstrCost(RedOp->getOpcode(), VectorTy, MulType,
5511
5512 InstructionCost RedCost = TTI.getMulAccReductionCost(
5513 IsUnsigned, RdxDesc.getOpcode(), RdxDesc.getRecurrenceType(), ExtType,
5514 CostKind);
5515
5516 if (RedCost.isValid() &&
5517 RedCost < ExtCost * 2 + MulCost + Ext2Cost + BaseCost)
5518 return I == RetI ? RedCost : 0;
5519 } else if (RedOp && match(RedOp, m_ZExtOrSExt(m_Value())) &&
5520 !TheLoop->isLoopInvariant(RedOp)) {
5521 // Matched reduce(ext(A))
5522 bool IsUnsigned = isa<ZExtInst>(RedOp);
5523 auto *ExtType = VectorType::get(RedOp->getOperand(0)->getType(), VectorTy);
5524 InstructionCost RedCost = TTI.getExtendedReductionCost(
5525 RdxDesc.getOpcode(), IsUnsigned, RdxDesc.getRecurrenceType(), ExtType,
5526 RdxDesc.getFastMathFlags(), CostKind);
5527
5528 InstructionCost ExtCost =
5529 TTI.getCastInstrCost(RedOp->getOpcode(), VectorTy, ExtType,
5531 if (RedCost.isValid() && RedCost < BaseCost + ExtCost)
5532 return I == RetI ? RedCost : 0;
5533 } else if (RedOp && RdxDesc.getOpcode() == Instruction::Add &&
5534 match(RedOp, m_Mul(m_Instruction(Op0), m_Instruction(Op1)))) {
5535 if (match(Op0, m_ZExtOrSExt(m_Value())) &&
5536 Op0->getOpcode() == Op1->getOpcode() &&
5537 !TheLoop->isLoopInvariant(Op0) && !TheLoop->isLoopInvariant(Op1)) {
5538 bool IsUnsigned = isa<ZExtInst>(Op0);
5539 Type *Op0Ty = Op0->getOperand(0)->getType();
5540 Type *Op1Ty = Op1->getOperand(0)->getType();
5541 Type *LargestOpTy =
5542 Op0Ty->getIntegerBitWidth() < Op1Ty->getIntegerBitWidth() ? Op1Ty
5543 : Op0Ty;
5544 auto *ExtType = VectorType::get(LargestOpTy, VectorTy);
5545
5546 // Matched reduce.add(mul(ext(A), ext(B))), where the two ext may be of
5547 // different sizes. We take the largest type as the ext to reduce, and add
5548 // the remaining cost as, for example reduce(mul(ext(ext(A)), ext(B))).
5549 InstructionCost ExtCost0 = TTI.getCastInstrCost(
5550 Op0->getOpcode(), VectorTy, VectorType::get(Op0Ty, VectorTy),
5552 InstructionCost ExtCost1 = TTI.getCastInstrCost(
5553 Op1->getOpcode(), VectorTy, VectorType::get(Op1Ty, VectorTy),
5555 InstructionCost MulCost =
5556 TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy, CostKind);
5557
5558 InstructionCost RedCost = TTI.getMulAccReductionCost(
5559 IsUnsigned, RdxDesc.getOpcode(), RdxDesc.getRecurrenceType(), ExtType,
5560 CostKind);
5561 InstructionCost ExtraExtCost = 0;
5562 if (Op0Ty != LargestOpTy || Op1Ty != LargestOpTy) {
5563 Instruction *ExtraExtOp = (Op0Ty != LargestOpTy) ? Op0 : Op1;
5564 ExtraExtCost = TTI.getCastInstrCost(
5565 ExtraExtOp->getOpcode(), ExtType,
5566 VectorType::get(ExtraExtOp->getOperand(0)->getType(), VectorTy),
5568 }
5569
5570 if (RedCost.isValid() &&
5571 (RedCost + ExtraExtCost) < (ExtCost0 + ExtCost1 + MulCost + BaseCost))
5572 return I == RetI ? RedCost : 0;
5573 } else if (!match(I, m_ZExtOrSExt(m_Value()))) {
5574 // Matched reduce.add(mul())
5575 InstructionCost MulCost =
5576 TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy, CostKind);
5577
5578 InstructionCost RedCost = TTI.getMulAccReductionCost(
5579 true, RdxDesc.getOpcode(), RdxDesc.getRecurrenceType(), VectorTy,
5580 CostKind);
5581
5582 if (RedCost.isValid() && RedCost < MulCost + BaseCost)
5583 return I == RetI ? RedCost : 0;
5584 }
5585 }
5586
5587 return I == RetI ? std::optional<InstructionCost>(BaseCost) : std::nullopt;
5588}
5589
5591LoopVectorizationCostModel::getMemoryInstructionCost(Instruction *I,
5592 ElementCount VF) {
5593 // Calculate scalar cost only. Vectorization cost should be ready at this
5594 // moment.
5595 if (VF.isScalar()) {
5596 Type *ValTy = getLoadStoreType(I);
5598 const Align Alignment = getLoadStoreAlignment(I);
5599 unsigned AS = getLoadStoreAddressSpace(I);
5600
5601 TTI::OperandValueInfo OpInfo = TTI::getOperandInfo(I->getOperand(0));
5602 return TTI.getAddressComputationCost(PtrTy, nullptr, nullptr, CostKind) +
5603 TTI.getMemoryOpCost(I->getOpcode(), ValTy, Alignment, AS, CostKind,
5604 OpInfo, I);
5605 }
5606 return getWideningCost(I, VF);
5607}
5608
5610LoopVectorizationCostModel::getScalarizationOverhead(Instruction *I,
5611 ElementCount VF) const {
5612
5613 // There is no mechanism yet to create a scalable scalarization loop,
5614 // so this is currently Invalid.
5615 if (VF.isScalable())
5616 return InstructionCost::getInvalid();
5617
5618 if (VF.isScalar())
5619 return 0;
5620
5622 Type *RetTy = toVectorizedTy(I->getType(), VF);
5623 if (!RetTy->isVoidTy() &&
5625
5626 for (Type *VectorTy : getContainedTypes(RetTy)) {
5629 /*Insert=*/true,
5630 /*Extract=*/false, CostKind);
5631 }
5632 }
5633
5634 // Some targets keep addresses scalar.
5636 return Cost;
5637
5638 // Some targets support efficient element stores.
5640 return Cost;
5641
5642 // Collect operands to consider.
5643 CallInst *CI = dyn_cast<CallInst>(I);
5644 Instruction::op_range Ops = CI ? CI->args() : I->operands();
5645
5646 // Skip operands that do not require extraction/scalarization and do not incur
5647 // any overhead.
5649 for (auto *V : filterExtractingOperands(Ops, VF))
5650 Tys.push_back(maybeVectorizeType(V->getType(), VF));
5652}
5653
5655 if (VF.isScalar())
5656 return;
5657 NumPredStores = 0;
5658 for (BasicBlock *BB : TheLoop->blocks()) {
5659 // For each instruction in the old loop.
5660 for (Instruction &I : *BB) {
5662 if (!Ptr)
5663 continue;
5664
5665 // TODO: We should generate better code and update the cost model for
5666 // predicated uniform stores. Today they are treated as any other
5667 // predicated store (see added test cases in
5668 // invariant-store-vectorization.ll).
5670 NumPredStores++;
5671
5672 if (Legal->isUniformMemOp(I, VF)) {
5673 auto IsLegalToScalarize = [&]() {
5674 if (!VF.isScalable())
5675 // Scalarization of fixed length vectors "just works".
5676 return true;
5677
5678 // We have dedicated lowering for unpredicated uniform loads and
5679 // stores. Note that even with tail folding we know that at least
5680 // one lane is active (i.e. generalized predication is not possible
5681 // here), and the logic below depends on this fact.
5682 if (!foldTailByMasking())
5683 return true;
5684
5685 // For scalable vectors, a uniform memop load is always
5686 // uniform-by-parts and we know how to scalarize that.
5687 if (isa<LoadInst>(I))
5688 return true;
5689
5690 // A uniform store isn't neccessarily uniform-by-part
5691 // and we can't assume scalarization.
5692 auto &SI = cast<StoreInst>(I);
5693 return TheLoop->isLoopInvariant(SI.getValueOperand());
5694 };
5695
5696 const InstructionCost GatherScatterCost =
5698 getGatherScatterCost(&I, VF) : InstructionCost::getInvalid();
5699
5700 // Load: Scalar load + broadcast
5701 // Store: Scalar store + isLoopInvariantStoreValue ? 0 : extract
5702 // FIXME: This cost is a significant under-estimate for tail folded
5703 // memory ops.
5704 const InstructionCost ScalarizationCost =
5705 IsLegalToScalarize() ? getUniformMemOpCost(&I, VF)
5707
5708 // Choose better solution for the current VF, Note that Invalid
5709 // costs compare as maximumal large. If both are invalid, we get
5710 // scalable invalid which signals a failure and a vectorization abort.
5711 if (GatherScatterCost < ScalarizationCost)
5712 setWideningDecision(&I, VF, CM_GatherScatter, GatherScatterCost);
5713 else
5714 setWideningDecision(&I, VF, CM_Scalarize, ScalarizationCost);
5715 continue;
5716 }
5717
5718 // We assume that widening is the best solution when possible.
5719 if (memoryInstructionCanBeWidened(&I, VF)) {
5720 InstructionCost Cost = getConsecutiveMemOpCost(&I, VF);
5721 int ConsecutiveStride = Legal->isConsecutivePtr(
5723 assert((ConsecutiveStride == 1 || ConsecutiveStride == -1) &&
5724 "Expected consecutive stride.");
5725 InstWidening Decision =
5726 ConsecutiveStride == 1 ? CM_Widen : CM_Widen_Reverse;
5727 setWideningDecision(&I, VF, Decision, Cost);
5728 continue;
5729 }
5730
5731 // Choose between Interleaving, Gather/Scatter or Scalarization.
5733 unsigned NumAccesses = 1;
5734 if (isAccessInterleaved(&I)) {
5735 const auto *Group = getInterleavedAccessGroup(&I);
5736 assert(Group && "Fail to get an interleaved access group.");
5737
5738 // Make one decision for the whole group.
5739 if (getWideningDecision(&I, VF) != CM_Unknown)
5740 continue;
5741
5742 NumAccesses = Group->getNumMembers();
5744 InterleaveCost = getInterleaveGroupCost(&I, VF);
5745 }
5746
5747 InstructionCost GatherScatterCost =
5749 ? getGatherScatterCost(&I, VF) * NumAccesses
5751
5752 InstructionCost ScalarizationCost =
5753 getMemInstScalarizationCost(&I, VF) * NumAccesses;
5754
5755 // Choose better solution for the current VF,
5756 // write down this decision and use it during vectorization.
5758 InstWidening Decision;
5759 if (InterleaveCost <= GatherScatterCost &&
5760 InterleaveCost < ScalarizationCost) {
5761 Decision = CM_Interleave;
5762 Cost = InterleaveCost;
5763 } else if (GatherScatterCost < ScalarizationCost) {
5764 Decision = CM_GatherScatter;
5765 Cost = GatherScatterCost;
5766 } else {
5767 Decision = CM_Scalarize;
5768 Cost = ScalarizationCost;
5769 }
5770 // If the instructions belongs to an interleave group, the whole group
5771 // receives the same decision. The whole group receives the cost, but
5772 // the cost will actually be assigned to one instruction.
5773 if (const auto *Group = getInterleavedAccessGroup(&I)) {
5774 if (Decision == CM_Scalarize) {
5775 for (unsigned Idx = 0; Idx < Group->getFactor(); ++Idx) {
5776 if (auto *I = Group->getMember(Idx)) {
5777 setWideningDecision(I, VF, Decision,
5778 getMemInstScalarizationCost(I, VF));
5779 }
5780 }
5781 } else {
5782 setWideningDecision(Group, VF, Decision, Cost);
5783 }
5784 } else
5785 setWideningDecision(&I, VF, Decision, Cost);
5786 }
5787 }
5788
5789 // Make sure that any load of address and any other address computation
5790 // remains scalar unless there is gather/scatter support. This avoids
5791 // inevitable extracts into address registers, and also has the benefit of
5792 // activating LSR more, since that pass can't optimize vectorized
5793 // addresses.
5794 if (TTI.prefersVectorizedAddressing())
5795 return;
5796
5797 // Start with all scalar pointer uses.
5799 for (BasicBlock *BB : TheLoop->blocks())
5800 for (Instruction &I : *BB) {
5801 Instruction *PtrDef =
5803 if (PtrDef && TheLoop->contains(PtrDef) &&
5805 AddrDefs.insert(PtrDef);
5806 }
5807
5808 // Add all instructions used to generate the addresses.
5810 append_range(Worklist, AddrDefs);
5811 while (!Worklist.empty()) {
5812 Instruction *I = Worklist.pop_back_val();
5813 for (auto &Op : I->operands())
5814 if (auto *InstOp = dyn_cast<Instruction>(Op))
5815 if (TheLoop->contains(InstOp) && !isa<PHINode>(InstOp) &&
5816 AddrDefs.insert(InstOp).second)
5817 Worklist.push_back(InstOp);
5818 }
5819
5820 auto UpdateMemOpUserCost = [this, VF](LoadInst *LI) {
5821 // If there are direct memory op users of the newly scalarized load,
5822 // their cost may have changed because there's no scalarization
5823 // overhead for the operand. Update it.
5824 for (User *U : LI->users()) {
5826 continue;
5828 continue;
5831 getMemInstScalarizationCost(cast<Instruction>(U), VF));
5832 }
5833 };
5834 for (auto *I : AddrDefs) {
5835 if (isa<LoadInst>(I)) {
5836 // Setting the desired widening decision should ideally be handled in
5837 // by cost functions, but since this involves the task of finding out
5838 // if the loaded register is involved in an address computation, it is
5839 // instead changed here when we know this is the case.
5840 InstWidening Decision = getWideningDecision(I, VF);
5841 if (Decision == CM_Widen || Decision == CM_Widen_Reverse ||
5842 (!isPredicatedInst(I) && !Legal->isUniformMemOp(*I, VF) &&
5843 Decision == CM_Scalarize)) {
5844 // Scalarize a widened load of address or update the cost of a scalar
5845 // load of an address.
5847 I, VF, CM_Scalarize,
5848 (VF.getKnownMinValue() *
5849 getMemoryInstructionCost(I, ElementCount::getFixed(1))));
5850 UpdateMemOpUserCost(cast<LoadInst>(I));
5851 } else if (const auto *Group = getInterleavedAccessGroup(I)) {
5852 // Scalarize all members of this interleaved group when any member
5853 // is used as an address. The address-used load skips scalarization
5854 // overhead, other members include it.
5855 for (unsigned Idx = 0; Idx < Group->getFactor(); ++Idx) {
5856 if (Instruction *Member = Group->getMember(Idx)) {
5858 AddrDefs.contains(Member)
5859 ? (VF.getKnownMinValue() *
5860 getMemoryInstructionCost(Member,
5862 : getMemInstScalarizationCost(Member, VF);
5864 UpdateMemOpUserCost(cast<LoadInst>(Member));
5865 }
5866 }
5867 }
5868 } else {
5869 // Cannot scalarize fixed-order recurrence phis at the moment.
5870 if (isa<PHINode>(I) && Legal->isFixedOrderRecurrence(cast<PHINode>(I)))
5871 continue;
5872
5873 // Make sure I gets scalarized and a cost estimate without
5874 // scalarization overhead.
5875 ForcedScalars[VF].insert(I);
5876 }
5877 }
5878}
5879
5881 assert(!VF.isScalar() &&
5882 "Trying to set a vectorization decision for a scalar VF");
5883
5884 auto ForcedScalar = ForcedScalars.find(VF);
5885 for (BasicBlock *BB : TheLoop->blocks()) {
5886 // For each instruction in the old loop.
5887 for (Instruction &I : *BB) {
5889
5890 if (!CI)
5891 continue;
5892
5896 Function *ScalarFunc = CI->getCalledFunction();
5897 Type *ScalarRetTy = CI->getType();
5898 SmallVector<Type *, 4> Tys, ScalarTys;
5899 for (auto &ArgOp : CI->args())
5900 ScalarTys.push_back(ArgOp->getType());
5901
5902 // Estimate cost of scalarized vector call. The source operands are
5903 // assumed to be vectors, so we need to extract individual elements from
5904 // there, execute VF scalar calls, and then gather the result into the
5905 // vector return value.
5906 if (VF.isFixed()) {
5907 InstructionCost ScalarCallCost =
5908 TTI.getCallInstrCost(ScalarFunc, ScalarRetTy, ScalarTys, CostKind);
5909
5910 // Compute costs of unpacking argument values for the scalar calls and
5911 // packing the return values to a vector.
5912 InstructionCost ScalarizationCost = getScalarizationOverhead(CI, VF);
5913 ScalarCost = ScalarCallCost * VF.getKnownMinValue() + ScalarizationCost;
5914 } else {
5915 // There is no point attempting to calculate the scalar cost for a
5916 // scalable VF as we know it will be Invalid.
5918 "Unexpected valid cost for scalarizing scalable vectors");
5919 ScalarCost = InstructionCost::getInvalid();
5920 }
5921
5922 // Honor ForcedScalars and UniformAfterVectorization decisions.
5923 // TODO: For calls, it might still be more profitable to widen. Use
5924 // VPlan-based cost model to compare different options.
5925 if (VF.isVector() && ((ForcedScalar != ForcedScalars.end() &&
5926 ForcedScalar->second.contains(CI)) ||
5927 isUniformAfterVectorization(CI, VF))) {
5928 setCallWideningDecision(CI, VF, CM_Scalarize, nullptr,
5929 Intrinsic::not_intrinsic, std::nullopt,
5930 ScalarCost);
5931 continue;
5932 }
5933
5934 bool MaskRequired = Legal->isMaskRequired(CI);
5935 // Compute corresponding vector type for return value and arguments.
5936 Type *RetTy = toVectorizedTy(ScalarRetTy, VF);
5937 for (Type *ScalarTy : ScalarTys)
5938 Tys.push_back(toVectorizedTy(ScalarTy, VF));
5939
5940 // An in-loop reduction using an fmuladd intrinsic is a special case;
5941 // we don't want the normal cost for that intrinsic.
5943 if (auto RedCost = getReductionPatternCost(CI, VF, RetTy)) {
5946 std::nullopt, *RedCost);
5947 continue;
5948 }
5949
5950 // Find the cost of vectorizing the call, if we can find a suitable
5951 // vector variant of the function.
5952 VFInfo FuncInfo;
5953 Function *VecFunc = nullptr;
5954 // Search through any available variants for one we can use at this VF.
5955 for (VFInfo &Info : VFDatabase::getMappings(*CI)) {
5956 // Must match requested VF.
5957 if (Info.Shape.VF != VF)
5958 continue;
5959
5960 // Must take a mask argument if one is required
5961 if (MaskRequired && !Info.isMasked())
5962 continue;
5963
5964 // Check that all parameter kinds are supported
5965 bool ParamsOk = true;
5966 for (VFParameter Param : Info.Shape.Parameters) {
5967 switch (Param.ParamKind) {
5969 break;
5971 Value *ScalarParam = CI->getArgOperand(Param.ParamPos);
5972 // Make sure the scalar parameter in the loop is invariant.
5973 if (!PSE.getSE()->isLoopInvariant(PSE.getSCEV(ScalarParam),
5974 TheLoop))
5975 ParamsOk = false;
5976 break;
5977 }
5979 Value *ScalarParam = CI->getArgOperand(Param.ParamPos);
5980 // Find the stride for the scalar parameter in this loop and see if
5981 // it matches the stride for the variant.
5982 // TODO: do we need to figure out the cost of an extract to get the
5983 // first lane? Or do we hope that it will be folded away?
5984 ScalarEvolution *SE = PSE.getSE();
5985 if (!match(SE->getSCEV(ScalarParam),
5987 m_SCEV(), m_scev_SpecificSInt(Param.LinearStepOrPos),
5989 ParamsOk = false;
5990 break;
5991 }
5993 break;
5994 default:
5995 ParamsOk = false;
5996 break;
5997 }
5998 }
5999
6000 if (!ParamsOk)
6001 continue;
6002
6003 // Found a suitable candidate, stop here.
6004 VecFunc = CI->getModule()->getFunction(Info.VectorName);
6005 FuncInfo = Info;
6006 break;
6007 }
6008
6009 if (TLI && VecFunc && !CI->isNoBuiltin())
6010 VectorCost = TTI.getCallInstrCost(nullptr, RetTy, Tys, CostKind);
6011
6012 // Find the cost of an intrinsic; some targets may have instructions that
6013 // perform the operation without needing an actual call.
6015 if (IID != Intrinsic::not_intrinsic)
6017
6018 InstructionCost Cost = ScalarCost;
6019 InstWidening Decision = CM_Scalarize;
6020
6021 if (VectorCost <= Cost) {
6022 Cost = VectorCost;
6023 Decision = CM_VectorCall;
6024 }
6025
6026 if (IntrinsicCost <= Cost) {
6028 Decision = CM_IntrinsicCall;
6029 }
6030
6031 setCallWideningDecision(CI, VF, Decision, VecFunc, IID,
6033 }
6034 }
6035}
6036
6038 if (!Legal->isInvariant(Op))
6039 return false;
6040 // Consider Op invariant, if it or its operands aren't predicated
6041 // instruction in the loop. In that case, it is not trivially hoistable.
6042 auto *OpI = dyn_cast<Instruction>(Op);
6043 return !OpI || !TheLoop->contains(OpI) ||
6044 (!isPredicatedInst(OpI) &&
6045 (!isa<PHINode>(OpI) || OpI->getParent() != TheLoop->getHeader()) &&
6046 all_of(OpI->operands(),
6047 [this](Value *Op) { return shouldConsiderInvariant(Op); }));
6048}
6049
6052 ElementCount VF) {
6053 // If we know that this instruction will remain uniform, check the cost of
6054 // the scalar version.
6056 VF = ElementCount::getFixed(1);
6057
6058 if (VF.isVector() && isProfitableToScalarize(I, VF))
6059 return InstsToScalarize[VF][I];
6060
6061 // Forced scalars do not have any scalarization overhead.
6062 auto ForcedScalar = ForcedScalars.find(VF);
6063 if (VF.isVector() && ForcedScalar != ForcedScalars.end()) {
6064 auto InstSet = ForcedScalar->second;
6065 if (InstSet.count(I))
6067 VF.getKnownMinValue();
6068 }
6069
6070 Type *RetTy = I->getType();
6072 RetTy = IntegerType::get(RetTy->getContext(), MinBWs[I]);
6073 auto *SE = PSE.getSE();
6074
6075 Type *VectorTy;
6076 if (isScalarAfterVectorization(I, VF)) {
6077 [[maybe_unused]] auto HasSingleCopyAfterVectorization =
6078 [this](Instruction *I, ElementCount VF) -> bool {
6079 if (VF.isScalar())
6080 return true;
6081
6082 auto Scalarized = InstsToScalarize.find(VF);
6083 assert(Scalarized != InstsToScalarize.end() &&
6084 "VF not yet analyzed for scalarization profitability");
6085 return !Scalarized->second.count(I) &&
6086 llvm::all_of(I->users(), [&](User *U) {
6087 auto *UI = cast<Instruction>(U);
6088 return !Scalarized->second.count(UI);
6089 });
6090 };
6091
6092 // With the exception of GEPs and PHIs, after scalarization there should
6093 // only be one copy of the instruction generated in the loop. This is
6094 // because the VF is either 1, or any instructions that need scalarizing
6095 // have already been dealt with by the time we get here. As a result,
6096 // it means we don't have to multiply the instruction cost by VF.
6097 assert(I->getOpcode() == Instruction::GetElementPtr ||
6098 I->getOpcode() == Instruction::PHI ||
6099 (I->getOpcode() == Instruction::BitCast &&
6100 I->getType()->isPointerTy()) ||
6101 HasSingleCopyAfterVectorization(I, VF));
6102 VectorTy = RetTy;
6103 } else
6104 VectorTy = toVectorizedTy(RetTy, VF);
6105
6106 if (VF.isVector() && VectorTy->isVectorTy() &&
6107 !TTI.getNumberOfParts(VectorTy))
6109
6110 // TODO: We need to estimate the cost of intrinsic calls.
6111 switch (I->getOpcode()) {
6112 case Instruction::GetElementPtr:
6113 // We mark this instruction as zero-cost because the cost of GEPs in
6114 // vectorized code depends on whether the corresponding memory instruction
6115 // is scalarized or not. Therefore, we handle GEPs with the memory
6116 // instruction cost.
6117 return 0;
6118 case Instruction::Br: {
6119 // In cases of scalarized and predicated instructions, there will be VF
6120 // predicated blocks in the vectorized loop. Each branch around these
6121 // blocks requires also an extract of its vector compare i1 element.
6122 // Note that the conditional branch from the loop latch will be replaced by
6123 // a single branch controlling the loop, so there is no extra overhead from
6124 // scalarization.
6125 bool ScalarPredicatedBB = false;
6127 if (VF.isVector() && BI->isConditional() &&
6128 (PredicatedBBsAfterVectorization[VF].count(BI->getSuccessor(0)) ||
6129 PredicatedBBsAfterVectorization[VF].count(BI->getSuccessor(1))) &&
6130 BI->getParent() != TheLoop->getLoopLatch())
6131 ScalarPredicatedBB = true;
6132
6133 if (ScalarPredicatedBB) {
6134 // Not possible to scalarize scalable vector with predicated instructions.
6135 if (VF.isScalable())
6137 // Return cost for branches around scalarized and predicated blocks.
6138 auto *VecI1Ty =
6140 return (
6141 TTI.getScalarizationOverhead(
6142 VecI1Ty, APInt::getAllOnes(VF.getFixedValue()),
6143 /*Insert*/ false, /*Extract*/ true, CostKind) +
6144 (TTI.getCFInstrCost(Instruction::Br, CostKind) * VF.getFixedValue()));
6145 }
6146
6147 if (I->getParent() == TheLoop->getLoopLatch() || VF.isScalar())
6148 // The back-edge branch will remain, as will all scalar branches.
6149 return TTI.getCFInstrCost(Instruction::Br, CostKind);
6150
6151 // This branch will be eliminated by if-conversion.
6152 return 0;
6153 // Note: We currently assume zero cost for an unconditional branch inside
6154 // a predicated block since it will become a fall-through, although we
6155 // may decide in the future to call TTI for all branches.
6156 }
6157 case Instruction::Switch: {
6158 if (VF.isScalar())
6159 return TTI.getCFInstrCost(Instruction::Switch, CostKind);
6160 auto *Switch = cast<SwitchInst>(I);
6161 return Switch->getNumCases() *
6162 TTI.getCmpSelInstrCost(
6163 Instruction::ICmp,
6164 toVectorTy(Switch->getCondition()->getType(), VF),
6165 toVectorTy(Type::getInt1Ty(I->getContext()), VF),
6167 }
6168 case Instruction::PHI: {
6169 auto *Phi = cast<PHINode>(I);
6170
6171 // First-order recurrences are replaced by vector shuffles inside the loop.
6172 if (VF.isVector() && Legal->isFixedOrderRecurrence(Phi)) {
6174 std::iota(Mask.begin(), Mask.end(), VF.getKnownMinValue() - 1);
6175 return TTI.getShuffleCost(TargetTransformInfo::SK_Splice,
6176 cast<VectorType>(VectorTy),
6177 cast<VectorType>(VectorTy), Mask, CostKind,
6178 VF.getKnownMinValue() - 1);
6179 }
6180
6181 // Phi nodes in non-header blocks (not inductions, reductions, etc.) are
6182 // converted into select instructions. We require N - 1 selects per phi
6183 // node, where N is the number of incoming values.
6184 if (VF.isVector() && Phi->getParent() != TheLoop->getHeader()) {
6185 Type *ResultTy = Phi->getType();
6186
6187 // All instructions in an Any-of reduction chain are narrowed to bool.
6188 // Check if that is the case for this phi node.
6189 auto *HeaderUser = cast_if_present<PHINode>(
6190 find_singleton<User>(Phi->users(), [this](User *U, bool) -> User * {
6191 auto *Phi = dyn_cast<PHINode>(U);
6192 if (Phi && Phi->getParent() == TheLoop->getHeader())
6193 return Phi;
6194 return nullptr;
6195 }));
6196 if (HeaderUser) {
6197 auto &ReductionVars = Legal->getReductionVars();
6198 auto Iter = ReductionVars.find(HeaderUser);
6199 if (Iter != ReductionVars.end() &&
6201 Iter->second.getRecurrenceKind()))
6202 ResultTy = Type::getInt1Ty(Phi->getContext());
6203 }
6204 return (Phi->getNumIncomingValues() - 1) *
6205 TTI.getCmpSelInstrCost(
6206 Instruction::Select, toVectorTy(ResultTy, VF),
6207 toVectorTy(Type::getInt1Ty(Phi->getContext()), VF),
6209 }
6210
6211 // When tail folding with EVL, if the phi is part of an out of loop
6212 // reduction then it will be transformed into a wide vp_merge.
6213 if (VF.isVector() && foldTailWithEVL() &&
6214 Legal->getReductionVars().contains(Phi) && !isInLoopReduction(Phi)) {
6216 Intrinsic::vp_merge, toVectorTy(Phi->getType(), VF),
6217 {toVectorTy(Type::getInt1Ty(Phi->getContext()), VF)});
6218 return TTI.getIntrinsicInstrCost(ICA, CostKind);
6219 }
6220
6221 return TTI.getCFInstrCost(Instruction::PHI, CostKind);
6222 }
6223 case Instruction::UDiv:
6224 case Instruction::SDiv:
6225 case Instruction::URem:
6226 case Instruction::SRem:
6227 if (VF.isVector() && isPredicatedInst(I)) {
6228 const auto [ScalarCost, SafeDivisorCost] = getDivRemSpeculationCost(I, VF);
6229 return isDivRemScalarWithPredication(ScalarCost, SafeDivisorCost) ?
6230 ScalarCost : SafeDivisorCost;
6231 }
6232 // We've proven all lanes safe to speculate, fall through.
6233 [[fallthrough]];
6234 case Instruction::Add:
6235 case Instruction::Sub: {
6236 auto Info = Legal->getHistogramInfo(I);
6237 if (Info && VF.isVector()) {
6238 const HistogramInfo *HGram = Info.value();
6239 // Assume that a non-constant update value (or a constant != 1) requires
6240 // a multiply, and add that into the cost.
6242 ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1));
6243 if (!RHS || RHS->getZExtValue() != 1)
6244 MulCost =
6245 TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy, CostKind);
6246
6247 // Find the cost of the histogram operation itself.
6248 Type *PtrTy = VectorType::get(HGram->Load->getPointerOperandType(), VF);
6249 Type *ScalarTy = I->getType();
6250 Type *MaskTy = VectorType::get(Type::getInt1Ty(I->getContext()), VF);
6251 IntrinsicCostAttributes ICA(Intrinsic::experimental_vector_histogram_add,
6252 Type::getVoidTy(I->getContext()),
6253 {PtrTy, ScalarTy, MaskTy});
6254
6255 // Add the costs together with the add/sub operation.
6256 return TTI.getIntrinsicInstrCost(ICA, CostKind) + MulCost +
6257 TTI.getArithmeticInstrCost(I->getOpcode(), VectorTy, CostKind);
6258 }
6259 [[fallthrough]];
6260 }
6261 case Instruction::FAdd:
6262 case Instruction::FSub:
6263 case Instruction::Mul:
6264 case Instruction::FMul:
6265 case Instruction::FDiv:
6266 case Instruction::FRem:
6267 case Instruction::Shl:
6268 case Instruction::LShr:
6269 case Instruction::AShr:
6270 case Instruction::And:
6271 case Instruction::Or:
6272 case Instruction::Xor: {
6273 // If we're speculating on the stride being 1, the multiplication may
6274 // fold away. We can generalize this for all operations using the notion
6275 // of neutral elements. (TODO)
6276 if (I->getOpcode() == Instruction::Mul &&
6277 ((TheLoop->isLoopInvariant(I->getOperand(0)) &&
6278 PSE.getSCEV(I->getOperand(0))->isOne()) ||
6279 (TheLoop->isLoopInvariant(I->getOperand(1)) &&
6280 PSE.getSCEV(I->getOperand(1))->isOne())))
6281 return 0;
6282
6283 // Detect reduction patterns
6284 if (auto RedCost = getReductionPatternCost(I, VF, VectorTy))
6285 return *RedCost;
6286
6287 // Certain instructions can be cheaper to vectorize if they have a constant
6288 // second vector operand. One example of this are shifts on x86.
6289 Value *Op2 = I->getOperand(1);
6290 if (!isa<Constant>(Op2) && TheLoop->isLoopInvariant(Op2) &&
6291 PSE.getSE()->isSCEVable(Op2->getType()) &&
6292 isa<SCEVConstant>(PSE.getSCEV(Op2))) {
6293 Op2 = cast<SCEVConstant>(PSE.getSCEV(Op2))->getValue();
6294 }
6295 auto Op2Info = TTI.getOperandInfo(Op2);
6296 if (Op2Info.Kind == TargetTransformInfo::OK_AnyValue &&
6299
6300 SmallVector<const Value *, 4> Operands(I->operand_values());
6301 return TTI.getArithmeticInstrCost(
6302 I->getOpcode(), VectorTy, CostKind,
6303 {TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None},
6304 Op2Info, Operands, I, TLI);
6305 }
6306 case Instruction::FNeg: {
6307 return TTI.getArithmeticInstrCost(
6308 I->getOpcode(), VectorTy, CostKind,
6309 {TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None},
6310 {TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None},
6311 I->getOperand(0), I);
6312 }
6313 case Instruction::Select: {
6315 const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
6316 bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
6317
6318 const Value *Op0, *Op1;
6319 using namespace llvm::PatternMatch;
6320 if (!ScalarCond && (match(I, m_LogicalAnd(m_Value(Op0), m_Value(Op1))) ||
6321 match(I, m_LogicalOr(m_Value(Op0), m_Value(Op1))))) {
6322 // select x, y, false --> x & y
6323 // select x, true, y --> x | y
6324 const auto [Op1VK, Op1VP] = TTI::getOperandInfo(Op0);
6325 const auto [Op2VK, Op2VP] = TTI::getOperandInfo(Op1);
6326 assert(Op0->getType()->getScalarSizeInBits() == 1 &&
6327 Op1->getType()->getScalarSizeInBits() == 1);
6328
6329 return TTI.getArithmeticInstrCost(
6330 match(I, m_LogicalOr()) ? Instruction::Or : Instruction::And,
6331 VectorTy, CostKind, {Op1VK, Op1VP}, {Op2VK, Op2VP}, {Op0, Op1}, I);
6332 }
6333
6334 Type *CondTy = SI->getCondition()->getType();
6335 if (!ScalarCond)
6336 CondTy = VectorType::get(CondTy, VF);
6337
6339 if (auto *Cmp = dyn_cast<CmpInst>(SI->getCondition()))
6340 Pred = Cmp->getPredicate();
6341 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy, Pred,
6342 CostKind, {TTI::OK_AnyValue, TTI::OP_None},
6343 {TTI::OK_AnyValue, TTI::OP_None}, I);
6344 }
6345 case Instruction::ICmp:
6346 case Instruction::FCmp: {
6347 Type *ValTy = I->getOperand(0)->getType();
6348
6350 [[maybe_unused]] Instruction *Op0AsInstruction =
6351 dyn_cast<Instruction>(I->getOperand(0));
6352 assert((!canTruncateToMinimalBitwidth(Op0AsInstruction, VF) ||
6353 MinBWs[I] == MinBWs[Op0AsInstruction]) &&
6354 "if both the operand and the compare are marked for "
6355 "truncation, they must have the same bitwidth");
6356 ValTy = IntegerType::get(ValTy->getContext(), MinBWs[I]);
6357 }
6358
6359 VectorTy = toVectorTy(ValTy, VF);
6360 return TTI.getCmpSelInstrCost(
6361 I->getOpcode(), VectorTy, CmpInst::makeCmpResultType(VectorTy),
6362 cast<CmpInst>(I)->getPredicate(), CostKind,
6363 {TTI::OK_AnyValue, TTI::OP_None}, {TTI::OK_AnyValue, TTI::OP_None}, I);
6364 }
6365 case Instruction::Store:
6366 case Instruction::Load: {
6367 ElementCount Width = VF;
6368 if (Width.isVector()) {
6369 InstWidening Decision = getWideningDecision(I, Width);
6370 assert(Decision != CM_Unknown &&
6371 "CM decision should be taken at this point");
6374 if (Decision == CM_Scalarize)
6375 Width = ElementCount::getFixed(1);
6376 }
6377 VectorTy = toVectorTy(getLoadStoreType(I), Width);
6378 return getMemoryInstructionCost(I, VF);
6379 }
6380 case Instruction::BitCast:
6381 if (I->getType()->isPointerTy())
6382 return 0;
6383 [[fallthrough]];
6384 case Instruction::ZExt:
6385 case Instruction::SExt:
6386 case Instruction::FPToUI:
6387 case Instruction::FPToSI:
6388 case Instruction::FPExt:
6389 case Instruction::PtrToInt:
6390 case Instruction::IntToPtr:
6391 case Instruction::SIToFP:
6392 case Instruction::UIToFP:
6393 case Instruction::Trunc:
6394 case Instruction::FPTrunc: {
6395 // Computes the CastContextHint from a Load/Store instruction.
6396 auto ComputeCCH = [&](Instruction *I) -> TTI::CastContextHint {
6398 "Expected a load or a store!");
6399
6400 if (VF.isScalar() || !TheLoop->contains(I))
6402
6403 switch (getWideningDecision(I, VF)) {
6415 llvm_unreachable("Instr did not go through cost modelling?");
6418 llvm_unreachable_internal("Instr has invalid widening decision");
6419 }
6420
6421 llvm_unreachable("Unhandled case!");
6422 };
6423
6424 unsigned Opcode = I->getOpcode();
6426 // For Trunc, the context is the only user, which must be a StoreInst.
6427 if (Opcode == Instruction::Trunc || Opcode == Instruction::FPTrunc) {
6428 if (I->hasOneUse())
6429 if (StoreInst *Store = dyn_cast<StoreInst>(*I->user_begin()))
6430 CCH = ComputeCCH(Store);
6431 }
6432 // For Z/Sext, the context is the operand, which must be a LoadInst.
6433 else if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt ||
6434 Opcode == Instruction::FPExt) {
6435 if (LoadInst *Load = dyn_cast<LoadInst>(I->getOperand(0)))
6436 CCH = ComputeCCH(Load);
6437 }
6438
6439 // We optimize the truncation of induction variables having constant
6440 // integer steps. The cost of these truncations is the same as the scalar
6441 // operation.
6442 if (isOptimizableIVTruncate(I, VF)) {
6443 auto *Trunc = cast<TruncInst>(I);
6444 return TTI.getCastInstrCost(Instruction::Trunc, Trunc->getDestTy(),
6445 Trunc->getSrcTy(), CCH, CostKind, Trunc);
6446 }
6447
6448 // Detect reduction patterns
6449 if (auto RedCost = getReductionPatternCost(I, VF, VectorTy))
6450 return *RedCost;
6451
6452 Type *SrcScalarTy = I->getOperand(0)->getType();
6453 Instruction *Op0AsInstruction = dyn_cast<Instruction>(I->getOperand(0));
6454 if (canTruncateToMinimalBitwidth(Op0AsInstruction, VF))
6455 SrcScalarTy =
6456 IntegerType::get(SrcScalarTy->getContext(), MinBWs[Op0AsInstruction]);
6457 Type *SrcVecTy =
6458 VectorTy->isVectorTy() ? toVectorTy(SrcScalarTy, VF) : SrcScalarTy;
6459
6461 // If the result type is <= the source type, there will be no extend
6462 // after truncating the users to the minimal required bitwidth.
6463 if (VectorTy->getScalarSizeInBits() <= SrcVecTy->getScalarSizeInBits() &&
6464 (I->getOpcode() == Instruction::ZExt ||
6465 I->getOpcode() == Instruction::SExt))
6466 return 0;
6467 }
6468
6469 return TTI.getCastInstrCost(Opcode, VectorTy, SrcVecTy, CCH, CostKind, I);
6470 }
6471 case Instruction::Call:
6472 return getVectorCallCost(cast<CallInst>(I), VF);
6473 case Instruction::ExtractValue:
6474 return TTI.getInstructionCost(I, CostKind);
6475 case Instruction::Alloca:
6476 // We cannot easily widen alloca to a scalable alloca, as
6477 // the result would need to be a vector of pointers.
6478 if (VF.isScalable())
6480 [[fallthrough]];
6481 default:
6482 // This opcode is unknown. Assume that it is the same as 'mul'.
6483 return TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy, CostKind);
6484 } // end of switch.
6485}
6486
6488 // Ignore ephemeral values.
6490
6491 SmallVector<Value *, 4> DeadInterleavePointerOps;
6493
6494 // If a scalar epilogue is required, users outside the loop won't use
6495 // live-outs from the vector loop but from the scalar epilogue. Ignore them if
6496 // that is the case.
6497 bool RequiresScalarEpilogue = requiresScalarEpilogue(true);
6498 auto IsLiveOutDead = [this, RequiresScalarEpilogue](User *U) {
6499 return RequiresScalarEpilogue &&
6500 !TheLoop->contains(cast<Instruction>(U)->getParent());
6501 };
6502
6504 DFS.perform(LI);
6505 for (BasicBlock *BB : reverse(make_range(DFS.beginRPO(), DFS.endRPO())))
6506 for (Instruction &I : reverse(*BB)) {
6507 if (VecValuesToIgnore.contains(&I) || ValuesToIgnore.contains(&I))
6508 continue;
6509
6510 // Add instructions that would be trivially dead and are only used by
6511 // values already ignored to DeadOps to seed worklist.
6513 all_of(I.users(), [this, IsLiveOutDead](User *U) {
6514 return VecValuesToIgnore.contains(U) ||
6515 ValuesToIgnore.contains(U) || IsLiveOutDead(U);
6516 }))
6517 DeadOps.push_back(&I);
6518
6519 // For interleave groups, we only create a pointer for the start of the
6520 // interleave group. Queue up addresses of group members except the insert
6521 // position for further processing.
6522 if (isAccessInterleaved(&I)) {
6523 auto *Group = getInterleavedAccessGroup(&I);
6524 if (Group->getInsertPos() == &I)
6525 continue;
6526 Value *PointerOp = getLoadStorePointerOperand(&I);
6527 DeadInterleavePointerOps.push_back(PointerOp);
6528 }
6529
6530 // Queue branches for analysis. They are dead, if their successors only
6531 // contain dead instructions.
6532 if (auto *Br = dyn_cast<BranchInst>(&I)) {
6533 if (Br->isConditional())
6534 DeadOps.push_back(&I);
6535 }
6536 }
6537
6538 // Mark ops feeding interleave group members as free, if they are only used
6539 // by other dead computations.
6540 for (unsigned I = 0; I != DeadInterleavePointerOps.size(); ++I) {
6541 auto *Op = dyn_cast<Instruction>(DeadInterleavePointerOps[I]);
6542 if (!Op || !TheLoop->contains(Op) || any_of(Op->users(), [this](User *U) {
6543 Instruction *UI = cast<Instruction>(U);
6544 return !VecValuesToIgnore.contains(U) &&
6545 (!isAccessInterleaved(UI) ||
6546 getInterleavedAccessGroup(UI)->getInsertPos() == UI);
6547 }))
6548 continue;
6549 VecValuesToIgnore.insert(Op);
6550 append_range(DeadInterleavePointerOps, Op->operands());
6551 }
6552
6553 // Mark ops that would be trivially dead and are only used by ignored
6554 // instructions as free.
6555 BasicBlock *Header = TheLoop->getHeader();
6556
6557 // Returns true if the block contains only dead instructions. Such blocks will
6558 // be removed by VPlan-to-VPlan transforms and won't be considered by the
6559 // VPlan-based cost model, so skip them in the legacy cost-model as well.
6560 auto IsEmptyBlock = [this](BasicBlock *BB) {
6561 return all_of(*BB, [this](Instruction &I) {
6562 return ValuesToIgnore.contains(&I) || VecValuesToIgnore.contains(&I) ||
6563 (isa<BranchInst>(&I) && !cast<BranchInst>(&I)->isConditional());
6564 });
6565 };
6566 for (unsigned I = 0; I != DeadOps.size(); ++I) {
6567 auto *Op = dyn_cast<Instruction>(DeadOps[I]);
6568
6569 // Check if the branch should be considered dead.
6570 if (auto *Br = dyn_cast_or_null<BranchInst>(Op)) {
6571 BasicBlock *ThenBB = Br->getSuccessor(0);
6572 BasicBlock *ElseBB = Br->getSuccessor(1);
6573 // Don't considers branches leaving the loop for simplification.
6574 if (!TheLoop->contains(ThenBB) || !TheLoop->contains(ElseBB))
6575 continue;
6576 bool ThenEmpty = IsEmptyBlock(ThenBB);
6577 bool ElseEmpty = IsEmptyBlock(ElseBB);
6578 if ((ThenEmpty && ElseEmpty) ||
6579 (ThenEmpty && ThenBB->getSingleSuccessor() == ElseBB &&
6580 ElseBB->phis().empty()) ||
6581 (ElseEmpty && ElseBB->getSingleSuccessor() == ThenBB &&
6582 ThenBB->phis().empty())) {
6583 VecValuesToIgnore.insert(Br);
6584 DeadOps.push_back(Br->getCondition());
6585 }
6586 continue;
6587 }
6588
6589 // Skip any op that shouldn't be considered dead.
6590 if (!Op || !TheLoop->contains(Op) ||
6591 (isa<PHINode>(Op) && Op->getParent() == Header) ||
6593 any_of(Op->users(), [this, IsLiveOutDead](User *U) {
6594 return !VecValuesToIgnore.contains(U) &&
6595 !ValuesToIgnore.contains(U) && !IsLiveOutDead(U);
6596 }))
6597 continue;
6598
6599 // If all of Op's users are in ValuesToIgnore, add it to ValuesToIgnore
6600 // which applies for both scalar and vector versions. Otherwise it is only
6601 // dead in vector versions, so only add it to VecValuesToIgnore.
6602 if (all_of(Op->users(),
6603 [this](User *U) { return ValuesToIgnore.contains(U); }))
6604 ValuesToIgnore.insert(Op);
6605
6606 VecValuesToIgnore.insert(Op);
6607 append_range(DeadOps, Op->operands());
6608 }
6609
6610 // Ignore type-promoting instructions we identified during reduction
6611 // detection.
6612 for (const auto &Reduction : Legal->getReductionVars()) {
6613 const RecurrenceDescriptor &RedDes = Reduction.second;
6614 const SmallPtrSetImpl<Instruction *> &Casts = RedDes.getCastInsts();
6615 VecValuesToIgnore.insert_range(Casts);
6616 }
6617 // Ignore type-casting instructions we identified during induction
6618 // detection.
6619 for (const auto &Induction : Legal->getInductionVars()) {
6620 const InductionDescriptor &IndDes = Induction.second;
6621 VecValuesToIgnore.insert_range(IndDes.getCastInsts());
6622 }
6623}
6624
6626 // Avoid duplicating work finding in-loop reductions.
6627 if (!InLoopReductions.empty())
6628 return;
6629
6630 for (const auto &Reduction : Legal->getReductionVars()) {
6631 PHINode *Phi = Reduction.first;
6632 const RecurrenceDescriptor &RdxDesc = Reduction.second;
6633
6634 // Multi-use reductions (e.g., used in FindLastIV patterns) are handled
6635 // separately and should not be considered for in-loop reductions.
6636 if (RdxDesc.hasUsesOutsideReductionChain())
6637 continue;
6638
6639 // We don't collect reductions that are type promoted (yet).
6640 if (RdxDesc.getRecurrenceType() != Phi->getType())
6641 continue;
6642
6643 // In-loop AnyOf and FindIV reductions are not yet supported.
6644 RecurKind Kind = RdxDesc.getRecurrenceKind();
6647 continue;
6648
6649 // If the target would prefer this reduction to happen "in-loop", then we
6650 // want to record it as such.
6651 if (!PreferInLoopReductions && !useOrderedReductions(RdxDesc) &&
6652 !TTI.preferInLoopReduction(Kind, Phi->getType()))
6653 continue;
6654
6655 // Check that we can correctly put the reductions into the loop, by
6656 // finding the chain of operations that leads from the phi to the loop
6657 // exit value.
6658 SmallVector<Instruction *, 4> ReductionOperations =
6659 RdxDesc.getReductionOpChain(Phi, TheLoop);
6660 bool InLoop = !ReductionOperations.empty();
6661
6662 if (InLoop) {
6663 InLoopReductions.insert(Phi);
6664 // Add the elements to InLoopReductionImmediateChains for cost modelling.
6665 Instruction *LastChain = Phi;
6666 for (auto *I : ReductionOperations) {
6667 InLoopReductionImmediateChains[I] = LastChain;
6668 LastChain = I;
6669 }
6670 }
6671 LLVM_DEBUG(dbgs() << "LV: Using " << (InLoop ? "inloop" : "out of loop")
6672 << " reduction for phi: " << *Phi << "\n");
6673 }
6674}
6675
6676// This function will select a scalable VF if the target supports scalable
6677// vectors and a fixed one otherwise.
6678// TODO: we could return a pair of values that specify the max VF and
6679// min VF, to be used in `buildVPlans(MinVF, MaxVF)` instead of
6680// `buildVPlans(VF, VF)`. We cannot do it because VPLAN at the moment
6681// doesn't have a cost model that can choose which plan to execute if
6682// more than one is generated.
6685 unsigned WidestType;
6686 std::tie(std::ignore, WidestType) = CM.getSmallestAndWidestTypes();
6687
6689 TTI.enableScalableVectorization()
6692
6693 TypeSize RegSize = TTI.getRegisterBitWidth(RegKind);
6694 unsigned N = RegSize.getKnownMinValue() / WidestType;
6695 return ElementCount::get(N, RegSize.isScalable());
6696}
6697
6700 ElementCount VF = UserVF;
6701 // Outer loop handling: They may require CFG and instruction level
6702 // transformations before even evaluating whether vectorization is profitable.
6703 // Since we cannot modify the incoming IR, we need to build VPlan upfront in
6704 // the vectorization pipeline.
6705 if (!OrigLoop->isInnermost()) {
6706 // If the user doesn't provide a vectorization factor, determine a
6707 // reasonable one.
6708 if (UserVF.isZero()) {
6709 VF = determineVPlanVF(TTI, CM);
6710 LLVM_DEBUG(dbgs() << "LV: VPlan computed VF " << VF << ".\n");
6711
6712 // Make sure we have a VF > 1 for stress testing.
6713 if (VPlanBuildStressTest && (VF.isScalar() || VF.isZero())) {
6714 LLVM_DEBUG(dbgs() << "LV: VPlan stress testing: "
6715 << "overriding computed VF.\n");
6716 VF = ElementCount::getFixed(4);
6717 }
6718 } else if (UserVF.isScalable() && !TTI.supportsScalableVectors() &&
6720 LLVM_DEBUG(dbgs() << "LV: Not vectorizing. Scalable VF requested, but "
6721 << "not supported by the target.\n");
6723 "Scalable vectorization requested but not supported by the target",
6724 "the scalable user-specified vectorization width for outer-loop "
6725 "vectorization cannot be used because the target does not support "
6726 "scalable vectors.",
6727 "ScalableVFUnfeasible", ORE, OrigLoop);
6729 }
6730 assert(EnableVPlanNativePath && "VPlan-native path is not enabled.");
6732 "VF needs to be a power of two");
6733 LLVM_DEBUG(dbgs() << "LV: Using " << (!UserVF.isZero() ? "user " : "")
6734 << "VF " << VF << " to build VPlans.\n");
6735 buildVPlans(VF, VF);
6736
6737 if (VPlans.empty())
6739
6740 // For VPlan build stress testing, we bail out after VPlan construction.
6743
6744 return {VF, 0 /*Cost*/, 0 /* ScalarCost */};
6745 }
6746
6747 LLVM_DEBUG(
6748 dbgs() << "LV: Not vectorizing. Inner loops aren't supported in the "
6749 "VPlan-native path.\n");
6751}
6752
6753void LoopVectorizationPlanner::plan(ElementCount UserVF, unsigned UserIC) {
6754 assert(OrigLoop->isInnermost() && "Inner loop expected.");
6755 CM.collectValuesToIgnore();
6756 CM.collectElementTypesForWidening();
6757
6758 FixedScalableVFPair MaxFactors = CM.computeMaxVF(UserVF, UserIC);
6759 if (!MaxFactors) // Cases that should not to be vectorized nor interleaved.
6760 return;
6761
6762 // Invalidate interleave groups if all blocks of loop will be predicated.
6763 if (CM.blockNeedsPredicationForAnyReason(OrigLoop->getHeader()) &&
6765 LLVM_DEBUG(
6766 dbgs()
6767 << "LV: Invalidate all interleaved groups due to fold-tail by masking "
6768 "which requires masked-interleaved support.\n");
6769 if (CM.InterleaveInfo.invalidateGroups())
6770 // Invalidating interleave groups also requires invalidating all decisions
6771 // based on them, which includes widening decisions and uniform and scalar
6772 // values.
6773 CM.invalidateCostModelingDecisions();
6774 }
6775
6776 if (CM.foldTailByMasking())
6777 Legal->prepareToFoldTailByMasking();
6778
6779 ElementCount MaxUserVF =
6780 UserVF.isScalable() ? MaxFactors.ScalableVF : MaxFactors.FixedVF;
6781 if (UserVF) {
6782 if (!ElementCount::isKnownLE(UserVF, MaxUserVF)) {
6784 "UserVF ignored because it may be larger than the maximal safe VF",
6785 "InvalidUserVF", ORE, OrigLoop);
6786 } else {
6788 "VF needs to be a power of two");
6789 // Collect the instructions (and their associated costs) that will be more
6790 // profitable to scalarize.
6791 CM.collectInLoopReductions();
6792 if (CM.selectUserVectorizationFactor(UserVF)) {
6793 LLVM_DEBUG(dbgs() << "LV: Using user VF " << UserVF << ".\n");
6794 buildVPlansWithVPRecipes(UserVF, UserVF);
6796 return;
6797 }
6798 reportVectorizationInfo("UserVF ignored because of invalid costs.",
6799 "InvalidCost", ORE, OrigLoop);
6800 }
6801 }
6802
6803 // Collect the Vectorization Factor Candidates.
6804 SmallVector<ElementCount> VFCandidates;
6805 for (auto VF = ElementCount::getFixed(1);
6806 ElementCount::isKnownLE(VF, MaxFactors.FixedVF); VF *= 2)
6807 VFCandidates.push_back(VF);
6808 for (auto VF = ElementCount::getScalable(1);
6809 ElementCount::isKnownLE(VF, MaxFactors.ScalableVF); VF *= 2)
6810 VFCandidates.push_back(VF);
6811
6812 CM.collectInLoopReductions();
6813 for (const auto &VF : VFCandidates) {
6814 // Collect Uniform and Scalar instructions after vectorization with VF.
6815 CM.collectNonVectorizedAndSetWideningDecisions(VF);
6816 }
6817
6818 buildVPlansWithVPRecipes(ElementCount::getFixed(1), MaxFactors.FixedVF);
6819 buildVPlansWithVPRecipes(ElementCount::getScalable(1), MaxFactors.ScalableVF);
6820
6822}
6823
6825 ElementCount VF) const {
6826 InstructionCost Cost = CM.getInstructionCost(UI, VF);
6827 if (Cost.isValid() && ForceTargetInstructionCost.getNumOccurrences())
6829 return Cost;
6830}
6831
6833 ElementCount VF) const {
6834 return CM.isUniformAfterVectorization(I, VF);
6835}
6836
6837bool VPCostContext::skipCostComputation(Instruction *UI, bool IsVector) const {
6838 return CM.ValuesToIgnore.contains(UI) ||
6839 (IsVector && CM.VecValuesToIgnore.contains(UI)) ||
6840 SkipCostComputation.contains(UI);
6841}
6842
6844 return CM.getPredBlockCostDivisor(CostKind, BB);
6845}
6846
6848LoopVectorizationPlanner::precomputeCosts(VPlan &Plan, ElementCount VF,
6849 VPCostContext &CostCtx) const {
6851 // Cost modeling for inductions is inaccurate in the legacy cost model
6852 // compared to the recipes that are generated. To match here initially during
6853 // VPlan cost model bring up directly use the induction costs from the legacy
6854 // cost model. Note that we do this as pre-processing; the VPlan may not have
6855 // any recipes associated with the original induction increment instruction
6856 // and may replace truncates with VPWidenIntOrFpInductionRecipe. We precompute
6857 // the cost of induction phis and increments (both that are represented by
6858 // recipes and those that are not), to avoid distinguishing between them here,
6859 // and skip all recipes that represent induction phis and increments (the
6860 // former case) later on, if they exist, to avoid counting them twice.
6861 // Similarly we pre-compute the cost of any optimized truncates.
6862 // TODO: Switch to more accurate costing based on VPlan.
6863 for (const auto &[IV, IndDesc] : Legal->getInductionVars()) {
6865 IV->getIncomingValueForBlock(OrigLoop->getLoopLatch()));
6866 SmallVector<Instruction *> IVInsts = {IVInc};
6867 for (unsigned I = 0; I != IVInsts.size(); I++) {
6868 for (Value *Op : IVInsts[I]->operands()) {
6869 auto *OpI = dyn_cast<Instruction>(Op);
6870 if (Op == IV || !OpI || !OrigLoop->contains(OpI) || !Op->hasOneUse())
6871 continue;
6872 IVInsts.push_back(OpI);
6873 }
6874 }
6875 IVInsts.push_back(IV);
6876 for (User *U : IV->users()) {
6877 auto *CI = cast<Instruction>(U);
6878 if (!CostCtx.CM.isOptimizableIVTruncate(CI, VF))
6879 continue;
6880 IVInsts.push_back(CI);
6881 }
6882
6883 // If the vector loop gets executed exactly once with the given VF, ignore
6884 // the costs of comparison and induction instructions, as they'll get
6885 // simplified away.
6886 // TODO: Remove this code after stepping away from the legacy cost model and
6887 // adding code to simplify VPlans before calculating their costs.
6888 auto TC = getSmallConstantTripCount(PSE.getSE(), OrigLoop);
6889 if (TC == VF && !CM.foldTailByMasking())
6890 addFullyUnrolledInstructionsToIgnore(OrigLoop, Legal->getInductionVars(),
6891 CostCtx.SkipCostComputation);
6892
6893 for (Instruction *IVInst : IVInsts) {
6894 if (CostCtx.skipCostComputation(IVInst, VF.isVector()))
6895 continue;
6896 InstructionCost InductionCost = CostCtx.getLegacyCost(IVInst, VF);
6897 LLVM_DEBUG({
6898 dbgs() << "Cost of " << InductionCost << " for VF " << VF
6899 << ": induction instruction " << *IVInst << "\n";
6900 });
6901 Cost += InductionCost;
6902 CostCtx.SkipCostComputation.insert(IVInst);
6903 }
6904 }
6905
6906 /// Compute the cost of all exiting conditions of the loop using the legacy
6907 /// cost model. This is to match the legacy behavior, which adds the cost of
6908 /// all exit conditions. Note that this over-estimates the cost, as there will
6909 /// be a single condition to control the vector loop.
6911 CM.TheLoop->getExitingBlocks(Exiting);
6912 SetVector<Instruction *> ExitInstrs;
6913 // Collect all exit conditions.
6914 for (BasicBlock *EB : Exiting) {
6915 auto *Term = dyn_cast<BranchInst>(EB->getTerminator());
6916 if (!Term || CostCtx.skipCostComputation(Term, VF.isVector()))
6917 continue;
6918 if (auto *CondI = dyn_cast<Instruction>(Term->getOperand(0))) {
6919 ExitInstrs.insert(CondI);
6920 }
6921 }
6922 // Compute the cost of all instructions only feeding the exit conditions.
6923 for (unsigned I = 0; I != ExitInstrs.size(); ++I) {
6924 Instruction *CondI = ExitInstrs[I];
6925 if (!OrigLoop->contains(CondI) ||
6926 !CostCtx.SkipCostComputation.insert(CondI).second)
6927 continue;
6928 InstructionCost CondICost = CostCtx.getLegacyCost(CondI, VF);
6929 LLVM_DEBUG({
6930 dbgs() << "Cost of " << CondICost << " for VF " << VF
6931 << ": exit condition instruction " << *CondI << "\n";
6932 });
6933 Cost += CondICost;
6934 for (Value *Op : CondI->operands()) {
6935 auto *OpI = dyn_cast<Instruction>(Op);
6936 if (!OpI || CostCtx.skipCostComputation(OpI, VF.isVector()) ||
6937 any_of(OpI->users(), [&ExitInstrs, this](User *U) {
6938 return OrigLoop->contains(cast<Instruction>(U)->getParent()) &&
6939 !ExitInstrs.contains(cast<Instruction>(U));
6940 }))
6941 continue;
6942 ExitInstrs.insert(OpI);
6943 }
6944 }
6945
6946 // Pre-compute the costs for branches except for the backedge, as the number
6947 // of replicate regions in a VPlan may not directly match the number of
6948 // branches, which would lead to different decisions.
6949 // TODO: Compute cost of branches for each replicate region in the VPlan,
6950 // which is more accurate than the legacy cost model.
6951 for (BasicBlock *BB : OrigLoop->blocks()) {
6952 if (CostCtx.skipCostComputation(BB->getTerminator(), VF.isVector()))
6953 continue;
6954 CostCtx.SkipCostComputation.insert(BB->getTerminator());
6955 if (BB == OrigLoop->getLoopLatch())
6956 continue;
6957 auto BranchCost = CostCtx.getLegacyCost(BB->getTerminator(), VF);
6958 Cost += BranchCost;
6959 }
6960
6961 // Pre-compute costs for instructions that are forced-scalar or profitable to
6962 // scalarize. Their costs will be computed separately in the legacy cost
6963 // model.
6964 for (Instruction *ForcedScalar : CM.ForcedScalars[VF]) {
6965 if (CostCtx.skipCostComputation(ForcedScalar, VF.isVector()))
6966 continue;
6967 CostCtx.SkipCostComputation.insert(ForcedScalar);
6968 InstructionCost ForcedCost = CostCtx.getLegacyCost(ForcedScalar, VF);
6969 LLVM_DEBUG({
6970 dbgs() << "Cost of " << ForcedCost << " for VF " << VF
6971 << ": forced scalar " << *ForcedScalar << "\n";
6972 });
6973 Cost += ForcedCost;
6974 }
6975 for (const auto &[Scalarized, ScalarCost] : CM.InstsToScalarize[VF]) {
6976 if (CostCtx.skipCostComputation(Scalarized, VF.isVector()))
6977 continue;
6978 CostCtx.SkipCostComputation.insert(Scalarized);
6979 LLVM_DEBUG({
6980 dbgs() << "Cost of " << ScalarCost << " for VF " << VF
6981 << ": profitable to scalarize " << *Scalarized << "\n";
6982 });
6983 Cost += ScalarCost;
6984 }
6985
6986 return Cost;
6987}
6988
6989InstructionCost LoopVectorizationPlanner::cost(VPlan &Plan,
6990 ElementCount VF) const {
6991 VPCostContext CostCtx(CM.TTI, *CM.TLI, Plan, CM, CM.CostKind, *PSE.getSE(),
6992 OrigLoop);
6993 InstructionCost Cost = precomputeCosts(Plan, VF, CostCtx);
6994
6995 // Now compute and add the VPlan-based cost.
6996 Cost += Plan.cost(VF, CostCtx);
6997#ifndef NDEBUG
6998 unsigned EstimatedWidth = estimateElementCount(VF, CM.getVScaleForTuning());
6999 LLVM_DEBUG(dbgs() << "Cost for VF " << VF << ": " << Cost
7000 << " (Estimated cost per lane: ");
7001 if (Cost.isValid()) {
7002 double CostPerLane = double(Cost.getValue()) / EstimatedWidth;
7003 LLVM_DEBUG(dbgs() << format("%.1f", CostPerLane));
7004 } else /* No point dividing an invalid cost - it will still be invalid */
7005 LLVM_DEBUG(dbgs() << "Invalid");
7006 LLVM_DEBUG(dbgs() << ")\n");
7007#endif
7008 return Cost;
7009}
7010
7011#ifndef NDEBUG
7012/// Return true if the original loop \ TheLoop contains any instructions that do
7013/// not have corresponding recipes in \p Plan and are not marked to be ignored
7014/// in \p CostCtx. This means the VPlan contains simplification that the legacy
7015/// cost-model did not account for.
7017 VPCostContext &CostCtx,
7018 Loop *TheLoop,
7019 ElementCount VF) {
7020 // First collect all instructions for the recipes in Plan.
7021 auto GetInstructionForCost = [](const VPRecipeBase *R) -> Instruction * {
7022 if (auto *S = dyn_cast<VPSingleDefRecipe>(R))
7023 return dyn_cast_or_null<Instruction>(S->getUnderlyingValue());
7024 if (auto *WidenMem = dyn_cast<VPWidenMemoryRecipe>(R))
7025 return &WidenMem->getIngredient();
7026 return nullptr;
7027 };
7028
7029 // Check if a select for a safe divisor was hoisted to the pre-header. If so,
7030 // the select doesn't need to be considered for the vector loop cost; go with
7031 // the more accurate VPlan-based cost model.
7032 for (VPRecipeBase &R : *Plan.getVectorPreheader()) {
7033 auto *VPI = dyn_cast<VPInstruction>(&R);
7034 if (!VPI || VPI->getOpcode() != Instruction::Select)
7035 continue;
7036
7037 if (auto *WR = dyn_cast_or_null<VPWidenRecipe>(VPI->getSingleUser())) {
7038 switch (WR->getOpcode()) {
7039 case Instruction::UDiv:
7040 case Instruction::SDiv:
7041 case Instruction::URem:
7042 case Instruction::SRem:
7043 return true;
7044 default:
7045 break;
7046 }
7047 }
7048 }
7049
7050 DenseSet<Instruction *> SeenInstrs;
7051 auto Iter = vp_depth_first_deep(Plan.getVectorLoopRegion()->getEntry());
7053 for (VPRecipeBase &R : *VPBB) {
7054 if (auto *IR = dyn_cast<VPInterleaveRecipe>(&R)) {
7055 auto *IG = IR->getInterleaveGroup();
7056 unsigned NumMembers = IG->getNumMembers();
7057 for (unsigned I = 0; I != NumMembers; ++I) {
7058 if (Instruction *M = IG->getMember(I))
7059 SeenInstrs.insert(M);
7060 }
7061 continue;
7062 }
7063 // Unused FOR splices are removed by VPlan transforms, so the VPlan-based
7064 // cost model won't cost it whilst the legacy will.
7065 if (auto *FOR = dyn_cast<VPFirstOrderRecurrencePHIRecipe>(&R)) {
7066 using namespace VPlanPatternMatch;
7067 if (none_of(FOR->users(),
7068 match_fn(m_VPInstruction<
7070 return true;
7071 }
7072 // The VPlan-based cost model is more accurate for partial reductions and
7073 // comparing against the legacy cost isn't desirable.
7074 if (auto *VPR = dyn_cast<VPReductionRecipe>(&R))
7075 if (VPR->isPartialReduction())
7076 return true;
7077
7078 // The VPlan-based cost model can analyze if recipes are scalar
7079 // recursively, but the legacy cost model cannot.
7080 if (auto *WidenMemR = dyn_cast<VPWidenMemoryRecipe>(&R)) {
7081 auto *AddrI = dyn_cast<Instruction>(
7082 getLoadStorePointerOperand(&WidenMemR->getIngredient()));
7083 if (AddrI && vputils::isSingleScalar(WidenMemR->getAddr()) !=
7084 CostCtx.isLegacyUniformAfterVectorization(AddrI, VF))
7085 return true;
7086 }
7087
7088 /// If a VPlan transform folded a recipe to one producing a single-scalar,
7089 /// but the original instruction wasn't uniform-after-vectorization in the
7090 /// legacy cost model, the legacy cost overestimates the actual cost.
7091 if (auto *RepR = dyn_cast<VPReplicateRecipe>(&R)) {
7092 if (RepR->isSingleScalar() &&
7094 RepR->getUnderlyingInstr(), VF))
7095 return true;
7096 }
7097 if (Instruction *UI = GetInstructionForCost(&R)) {
7098 // If we adjusted the predicate of the recipe, the cost in the legacy
7099 // cost model may be different.
7100 using namespace VPlanPatternMatch;
7101 CmpPredicate Pred;
7102 if (match(&R, m_Cmp(Pred, m_VPValue(), m_VPValue())) &&
7103 cast<VPRecipeWithIRFlags>(R).getPredicate() !=
7104 cast<CmpInst>(UI)->getPredicate())
7105 return true;
7106 SeenInstrs.insert(UI);
7107 }
7108 }
7109 }
7110
7111 // Return true if the loop contains any instructions that are not also part of
7112 // the VPlan or are skipped for VPlan-based cost computations. This indicates
7113 // that the VPlan contains extra simplifications.
7114 return any_of(TheLoop->blocks(), [&SeenInstrs, &CostCtx,
7115 TheLoop](BasicBlock *BB) {
7116 return any_of(*BB, [&SeenInstrs, &CostCtx, TheLoop, BB](Instruction &I) {
7117 // Skip induction phis when checking for simplifications, as they may not
7118 // be lowered directly be lowered to a corresponding PHI recipe.
7119 if (isa<PHINode>(&I) && BB == TheLoop->getHeader() &&
7120 CostCtx.CM.Legal->isInductionPhi(cast<PHINode>(&I)))
7121 return false;
7122 return !SeenInstrs.contains(&I) && !CostCtx.skipCostComputation(&I, true);
7123 });
7124 });
7125}
7126#endif
7127
7129 if (VPlans.empty())
7131 // If there is a single VPlan with a single VF, return it directly.
7132 VPlan &FirstPlan = *VPlans[0];
7133 if (VPlans.size() == 1 && size(FirstPlan.vectorFactors()) == 1)
7134 return {*FirstPlan.vectorFactors().begin(), 0, 0};
7135
7136 LLVM_DEBUG(dbgs() << "LV: Computing best VF using cost kind: "
7137 << (CM.CostKind == TTI::TCK_RecipThroughput
7138 ? "Reciprocal Throughput\n"
7139 : CM.CostKind == TTI::TCK_Latency
7140 ? "Instruction Latency\n"
7141 : CM.CostKind == TTI::TCK_CodeSize ? "Code Size\n"
7142 : CM.CostKind == TTI::TCK_SizeAndLatency
7143 ? "Code Size and Latency\n"
7144 : "Unknown\n"));
7145
7147 assert(hasPlanWithVF(ScalarVF) &&
7148 "More than a single plan/VF w/o any plan having scalar VF");
7149
7150 // TODO: Compute scalar cost using VPlan-based cost model.
7151 InstructionCost ScalarCost = CM.expectedCost(ScalarVF);
7152 LLVM_DEBUG(dbgs() << "LV: Scalar loop costs: " << ScalarCost << ".\n");
7153 VectorizationFactor ScalarFactor(ScalarVF, ScalarCost, ScalarCost);
7154 VectorizationFactor BestFactor = ScalarFactor;
7155
7156 bool ForceVectorization = Hints.getForce() == LoopVectorizeHints::FK_Enabled;
7157 if (ForceVectorization) {
7158 // Ignore scalar width, because the user explicitly wants vectorization.
7159 // Initialize cost to max so that VF = 2 is, at least, chosen during cost
7160 // evaluation.
7161 BestFactor.Cost = InstructionCost::getMax();
7162 }
7163
7164 for (auto &P : VPlans) {
7165 ArrayRef<ElementCount> VFs(P->vectorFactors().begin(),
7166 P->vectorFactors().end());
7167
7169 if (any_of(VFs, [this](ElementCount VF) {
7170 return CM.shouldConsiderRegPressureForVF(VF);
7171 }))
7172 RUs = calculateRegisterUsageForPlan(*P, VFs, TTI, CM.ValuesToIgnore);
7173
7174 for (unsigned I = 0; I < VFs.size(); I++) {
7175 ElementCount VF = VFs[I];
7176 if (VF.isScalar())
7177 continue;
7178 if (!ForceVectorization && !willGenerateVectors(*P, VF, TTI)) {
7179 LLVM_DEBUG(
7180 dbgs()
7181 << "LV: Not considering vector loop of width " << VF
7182 << " because it will not generate any vector instructions.\n");
7183 continue;
7184 }
7185 if (CM.OptForSize && !ForceVectorization && hasReplicatorRegion(*P)) {
7186 LLVM_DEBUG(
7187 dbgs()
7188 << "LV: Not considering vector loop of width " << VF
7189 << " because it would cause replicated blocks to be generated,"
7190 << " which isn't allowed when optimizing for size.\n");
7191 continue;
7192 }
7193
7194 InstructionCost Cost = cost(*P, VF);
7195 VectorizationFactor CurrentFactor(VF, Cost, ScalarCost);
7196
7197 if (CM.shouldConsiderRegPressureForVF(VF) &&
7198 RUs[I].exceedsMaxNumRegs(TTI, ForceTargetNumVectorRegs)) {
7199 LLVM_DEBUG(dbgs() << "LV(REG): Not considering vector loop of width "
7200 << VF << " because it uses too many registers\n");
7201 continue;
7202 }
7203
7204 if (isMoreProfitable(CurrentFactor, BestFactor, P->hasScalarTail()))
7205 BestFactor = CurrentFactor;
7206
7207 // If profitable add it to ProfitableVF list.
7208 if (isMoreProfitable(CurrentFactor, ScalarFactor, P->hasScalarTail()))
7209 ProfitableVFs.push_back(CurrentFactor);
7210 }
7211 }
7212
7213#ifndef NDEBUG
7214 // Select the optimal vectorization factor according to the legacy cost-model.
7215 // This is now only used to verify the decisions by the new VPlan-based
7216 // cost-model and will be retired once the VPlan-based cost-model is
7217 // stabilized.
7218 VectorizationFactor LegacyVF = selectVectorizationFactor();
7219 VPlan &BestPlan = getPlanFor(BestFactor.Width);
7220
7221 // Pre-compute the cost and use it to check if BestPlan contains any
7222 // simplifications not accounted for in the legacy cost model. If that's the
7223 // case, don't trigger the assertion, as the extra simplifications may cause a
7224 // different VF to be picked by the VPlan-based cost model.
7225 VPCostContext CostCtx(CM.TTI, *CM.TLI, BestPlan, CM, CM.CostKind,
7226 *CM.PSE.getSE(), OrigLoop);
7227 precomputeCosts(BestPlan, BestFactor.Width, CostCtx);
7228 // Verify that the VPlan-based and legacy cost models agree, except for
7229 // * VPlans with early exits,
7230 // * VPlans with additional VPlan simplifications,
7231 // * EVL-based VPlans with gather/scatters (the VPlan-based cost model uses
7232 // vp_scatter/vp_gather).
7233 // The legacy cost model doesn't properly model costs for such loops.
7234 bool UsesEVLGatherScatter =
7236 BestPlan.getVectorLoopRegion()->getEntry())),
7237 [](VPBasicBlock *VPBB) {
7238 return any_of(*VPBB, [](VPRecipeBase &R) {
7239 return isa<VPWidenLoadEVLRecipe, VPWidenStoreEVLRecipe>(&R) &&
7240 !cast<VPWidenMemoryRecipe>(&R)->isConsecutive();
7241 });
7242 });
7243 assert(
7244 (BestFactor.Width == LegacyVF.Width || BestPlan.hasEarlyExit() ||
7245 !Legal->getLAI()->getSymbolicStrides().empty() || UsesEVLGatherScatter ||
7247 getPlanFor(BestFactor.Width), CostCtx, OrigLoop, BestFactor.Width) ||
7249 getPlanFor(LegacyVF.Width), CostCtx, OrigLoop, LegacyVF.Width)) &&
7250 " VPlan cost model and legacy cost model disagreed");
7251 assert((BestFactor.Width.isScalar() || BestFactor.ScalarCost > 0) &&
7252 "when vectorizing, the scalar cost must be computed.");
7253#endif
7254
7255 LLVM_DEBUG(dbgs() << "LV: Selecting VF: " << BestFactor.Width << ".\n");
7256 return BestFactor;
7257}
7258
7260 using namespace VPlanPatternMatch;
7262 "RdxResult must be ComputeFindIVResult");
7263 VPValue *StartVPV = RdxResult->getOperand(1);
7264 match(StartVPV, m_Freeze(m_VPValue(StartVPV)));
7265 return StartVPV->getLiveInIRValue();
7266}
7267
7268// If \p EpiResumePhiR is resume VPPhi for a reduction when vectorizing the
7269// epilog loop, fix the reduction's scalar PHI node by adding the incoming value
7270// from the main vector loop.
7272 VPPhi *EpiResumePhiR, PHINode &EpiResumePhi, BasicBlock *BypassBlock) {
7273 // Get the VPInstruction computing the reduction result in the middle block.
7274 // The first operand may not be from the middle block if it is not connected
7275 // to the scalar preheader. In that case, there's nothing to fix.
7276 VPValue *Incoming = EpiResumePhiR->getOperand(0);
7279 auto *EpiRedResult = dyn_cast<VPInstruction>(Incoming);
7280 if (!EpiRedResult ||
7281 (EpiRedResult->getOpcode() != VPInstruction::ComputeAnyOfResult &&
7282 EpiRedResult->getOpcode() != VPInstruction::ComputeReductionResult &&
7283 EpiRedResult->getOpcode() != VPInstruction::ComputeFindIVResult))
7284 return;
7285
7286 auto *EpiRedHeaderPhi =
7287 cast<VPReductionPHIRecipe>(EpiRedResult->getOperand(0));
7288 RecurKind Kind = EpiRedHeaderPhi->getRecurrenceKind();
7289 Value *MainResumeValue;
7290 if (auto *VPI = dyn_cast<VPInstruction>(EpiRedHeaderPhi->getStartValue())) {
7291 assert((VPI->getOpcode() == VPInstruction::Broadcast ||
7292 VPI->getOpcode() == VPInstruction::ReductionStartVector) &&
7293 "unexpected start recipe");
7294 MainResumeValue = VPI->getOperand(0)->getUnderlyingValue();
7295 } else
7296 MainResumeValue = EpiRedHeaderPhi->getStartValue()->getUnderlyingValue();
7298 [[maybe_unused]] Value *StartV =
7299 EpiRedResult->getOperand(1)->getLiveInIRValue();
7300 auto *Cmp = cast<ICmpInst>(MainResumeValue);
7301 assert(Cmp->getPredicate() == CmpInst::ICMP_NE &&
7302 "AnyOf expected to start with ICMP_NE");
7303 assert(Cmp->getOperand(1) == StartV &&
7304 "AnyOf expected to start by comparing main resume value to original "
7305 "start value");
7306 MainResumeValue = Cmp->getOperand(0);
7308 Value *StartV = getStartValueFromReductionResult(EpiRedResult);
7309 Value *SentinelV = EpiRedResult->getOperand(2)->getLiveInIRValue();
7310 using namespace llvm::PatternMatch;
7311 Value *Cmp, *OrigResumeV, *CmpOp;
7312 [[maybe_unused]] bool IsExpectedPattern =
7313 match(MainResumeValue,
7314 m_Select(m_OneUse(m_Value(Cmp)), m_Specific(SentinelV),
7315 m_Value(OrigResumeV))) &&
7317 m_Value(CmpOp))) &&
7318 ((CmpOp == StartV && isGuaranteedNotToBeUndefOrPoison(CmpOp))));
7319 assert(IsExpectedPattern && "Unexpected reduction resume pattern");
7320 MainResumeValue = OrigResumeV;
7321 }
7322 PHINode *MainResumePhi = cast<PHINode>(MainResumeValue);
7323
7324 // When fixing reductions in the epilogue loop we should already have
7325 // created a bc.merge.rdx Phi after the main vector body. Ensure that we carry
7326 // over the incoming values correctly.
7327 EpiResumePhi.setIncomingValueForBlock(
7328 BypassBlock, MainResumePhi->getIncomingValueForBlock(BypassBlock));
7329}
7330
7332 ElementCount BestVF, unsigned BestUF, VPlan &BestVPlan,
7333 InnerLoopVectorizer &ILV, DominatorTree *DT, bool VectorizingEpilogue) {
7334 assert(BestVPlan.hasVF(BestVF) &&
7335 "Trying to execute plan with unsupported VF");
7336 assert(BestVPlan.hasUF(BestUF) &&
7337 "Trying to execute plan with unsupported UF");
7338 if (BestVPlan.hasEarlyExit())
7339 ++LoopsEarlyExitVectorized;
7340 // TODO: Move to VPlan transform stage once the transition to the VPlan-based
7341 // cost model is complete for better cost estimates.
7344 BestVPlan);
7347 bool HasBranchWeights =
7348 hasBranchWeightMD(*OrigLoop->getLoopLatch()->getTerminator());
7349 if (HasBranchWeights) {
7350 std::optional<unsigned> VScale = CM.getVScaleForTuning();
7352 BestVPlan, BestVF, VScale);
7353 }
7354
7355 // Checks are the same for all VPlans, added to BestVPlan only for
7356 // compactness.
7357 attachRuntimeChecks(BestVPlan, ILV.RTChecks, HasBranchWeights);
7358
7359 // Retrieving VectorPH now when it's easier while VPlan still has Regions.
7360 VPBasicBlock *VectorPH = cast<VPBasicBlock>(BestVPlan.getVectorPreheader());
7361
7362 VPlanTransforms::optimizeForVFAndUF(BestVPlan, BestVF, BestUF, PSE);
7365 if (BestVPlan.getEntry()->getSingleSuccessor() ==
7366 BestVPlan.getScalarPreheader()) {
7367 // TODO: The vector loop would be dead, should not even try to vectorize.
7368 ORE->emit([&]() {
7369 return OptimizationRemarkAnalysis(DEBUG_TYPE, "VectorizationDead",
7370 OrigLoop->getStartLoc(),
7371 OrigLoop->getHeader())
7372 << "Created vector loop never executes due to insufficient trip "
7373 "count.";
7374 });
7376 }
7377
7379 BestVPlan, BestVF,
7380 TTI.getRegisterBitWidth(BestVF.isScalable()
7384
7386 // Regions are dissolved after optimizing for VF and UF, which completely
7387 // removes unneeded loop regions first.
7389 // Canonicalize EVL loops after regions are dissolved.
7393 BestVPlan, VectorPH, CM.foldTailByMasking(),
7394 CM.requiresScalarEpilogue(BestVF.isVector()));
7395 VPlanTransforms::materializeVFAndVFxUF(BestVPlan, VectorPH, BestVF);
7396 VPlanTransforms::cse(BestVPlan);
7398
7399 // 0. Generate SCEV-dependent code in the entry, including TripCount, before
7400 // making any changes to the CFG.
7401 DenseMap<const SCEV *, Value *> ExpandedSCEVs =
7402 VPlanTransforms::expandSCEVs(BestVPlan, *PSE.getSE());
7403 if (!ILV.getTripCount())
7404 ILV.setTripCount(BestVPlan.getTripCount()->getLiveInIRValue());
7405 else
7406 assert(VectorizingEpilogue && "should only re-use the existing trip "
7407 "count during epilogue vectorization");
7408
7409 // Perform the actual loop transformation.
7410 VPTransformState State(&TTI, BestVF, LI, DT, ILV.AC, ILV.Builder, &BestVPlan,
7411 OrigLoop->getParentLoop(),
7412 Legal->getWidestInductionType());
7413
7414#ifdef EXPENSIVE_CHECKS
7415 assert(DT->verify(DominatorTree::VerificationLevel::Fast));
7416#endif
7417
7418 // 1. Set up the skeleton for vectorization, including vector pre-header and
7419 // middle block. The vector loop is created during VPlan execution.
7420 State.CFG.PrevBB = ILV.createVectorizedLoopSkeleton();
7422 State.CFG.PrevBB->getSingleSuccessor(), &BestVPlan);
7424
7425 assert(verifyVPlanIsValid(BestVPlan, true /*VerifyLate*/) &&
7426 "final VPlan is invalid");
7427
7428 // After vectorization, the exit blocks of the original loop will have
7429 // additional predecessors. Invalidate SCEVs for the exit phis in case SE
7430 // looked through single-entry phis.
7431 ScalarEvolution &SE = *PSE.getSE();
7432 for (VPIRBasicBlock *Exit : BestVPlan.getExitBlocks()) {
7433 if (!Exit->hasPredecessors())
7434 continue;
7435 for (VPRecipeBase &PhiR : Exit->phis())
7437 &cast<VPIRPhi>(PhiR).getIRPhi());
7438 }
7439 // Forget the original loop and block dispositions.
7440 SE.forgetLoop(OrigLoop);
7442
7444
7445 //===------------------------------------------------===//
7446 //
7447 // Notice: any optimization or new instruction that go
7448 // into the code below should also be implemented in
7449 // the cost-model.
7450 //
7451 //===------------------------------------------------===//
7452
7453 // Retrieve loop information before executing the plan, which may remove the
7454 // original loop, if it becomes unreachable.
7455 MDNode *LID = OrigLoop->getLoopID();
7456 unsigned OrigLoopInvocationWeight = 0;
7457 std::optional<unsigned> OrigAverageTripCount =
7458 getLoopEstimatedTripCount(OrigLoop, &OrigLoopInvocationWeight);
7459
7460 BestVPlan.execute(&State);
7461
7462 // 2.6. Maintain Loop Hints
7463 // Keep all loop hints from the original loop on the vector loop (we'll
7464 // replace the vectorizer-specific hints below).
7465 VPBasicBlock *HeaderVPBB = vputils::getFirstLoopHeader(BestVPlan, State.VPDT);
7466 // Add metadata to disable runtime unrolling a scalar loop when there
7467 // are no runtime checks about strides and memory. A scalar loop that is
7468 // rarely used is not worth unrolling.
7469 bool DisableRuntimeUnroll = !ILV.RTChecks.hasChecks() && !BestVF.isScalar();
7471 HeaderVPBB ? LI->getLoopFor(State.CFG.VPBB2IRBB.lookup(HeaderVPBB))
7472 : nullptr,
7473 HeaderVPBB, BestVPlan, VectorizingEpilogue, LID, OrigAverageTripCount,
7474 OrigLoopInvocationWeight,
7475 estimateElementCount(BestVF * BestUF, CM.getVScaleForTuning()),
7476 DisableRuntimeUnroll);
7477
7478 // 3. Fix the vectorized code: take care of header phi's, live-outs,
7479 // predication, updating analyses.
7480 ILV.fixVectorizedLoop(State);
7481
7483
7484 return ExpandedSCEVs;
7485}
7486
7487//===--------------------------------------------------------------------===//
7488// EpilogueVectorizerMainLoop
7489//===--------------------------------------------------------------------===//
7490
7491/// This function is partially responsible for generating the control flow
7492/// depicted in https://llvm.org/docs/Vectorizers.html#epilogue-vectorization.
7494 BasicBlock *ScalarPH = createScalarPreheader("");
7495 BasicBlock *VectorPH = ScalarPH->getSinglePredecessor();
7496
7497 // Generate the code to check the minimum iteration count of the vector
7498 // epilogue (see below).
7499 EPI.EpilogueIterationCountCheck =
7500 emitIterationCountCheck(VectorPH, ScalarPH, true);
7501 EPI.EpilogueIterationCountCheck->setName("iter.check");
7502
7503 VectorPH = cast<BranchInst>(EPI.EpilogueIterationCountCheck->getTerminator())
7504 ->getSuccessor(1);
7505 // Generate the iteration count check for the main loop, *after* the check
7506 // for the epilogue loop, so that the path-length is shorter for the case
7507 // that goes directly through the vector epilogue. The longer-path length for
7508 // the main loop is compensated for, by the gain from vectorizing the larger
7509 // trip count. Note: the branch will get updated later on when we vectorize
7510 // the epilogue.
7511 EPI.MainLoopIterationCountCheck =
7512 emitIterationCountCheck(VectorPH, ScalarPH, false);
7513
7514 return cast<BranchInst>(EPI.MainLoopIterationCountCheck->getTerminator())
7515 ->getSuccessor(1);
7516}
7517
7519 LLVM_DEBUG({
7520 dbgs() << "Create Skeleton for epilogue vectorized loop (first pass)\n"
7521 << "Main Loop VF:" << EPI.MainLoopVF
7522 << ", Main Loop UF:" << EPI.MainLoopUF
7523 << ", Epilogue Loop VF:" << EPI.EpilogueVF
7524 << ", Epilogue Loop UF:" << EPI.EpilogueUF << "\n";
7525 });
7526}
7527
7530 dbgs() << "intermediate fn:\n"
7531 << *OrigLoop->getHeader()->getParent() << "\n";
7532 });
7533}
7534
7536 BasicBlock *VectorPH, BasicBlock *Bypass, bool ForEpilogue) {
7537 assert(Bypass && "Expected valid bypass basic block.");
7540 Value *CheckMinIters = createIterationCountCheck(
7541 VectorPH, ForEpilogue ? EPI.EpilogueVF : EPI.MainLoopVF,
7542 ForEpilogue ? EPI.EpilogueUF : EPI.MainLoopUF);
7543
7544 BasicBlock *const TCCheckBlock = VectorPH;
7545 if (!ForEpilogue)
7546 TCCheckBlock->setName("vector.main.loop.iter.check");
7547
7548 // Create new preheader for vector loop.
7549 VectorPH = SplitBlock(TCCheckBlock, TCCheckBlock->getTerminator(),
7550 static_cast<DominatorTree *>(nullptr), LI, nullptr,
7551 "vector.ph");
7552 if (ForEpilogue) {
7553 // Save the trip count so we don't have to regenerate it in the
7554 // vec.epilog.iter.check. This is safe to do because the trip count
7555 // generated here dominates the vector epilog iter check.
7556 EPI.TripCount = Count;
7557 } else {
7559 }
7560
7561 BranchInst &BI = *BranchInst::Create(Bypass, VectorPH, CheckMinIters);
7562 if (hasBranchWeightMD(*OrigLoop->getLoopLatch()->getTerminator()))
7563 setBranchWeights(BI, MinItersBypassWeights, /*IsExpected=*/false);
7564 ReplaceInstWithInst(TCCheckBlock->getTerminator(), &BI);
7565
7566 // When vectorizing the main loop, its trip-count check is placed in a new
7567 // block, whereas the overall trip-count check is placed in the VPlan entry
7568 // block. When vectorizing the epilogue loop, its trip-count check is placed
7569 // in the VPlan entry block.
7570 if (!ForEpilogue)
7571 introduceCheckBlockInVPlan(TCCheckBlock);
7572 return TCCheckBlock;
7573}
7574
7575//===--------------------------------------------------------------------===//
7576// EpilogueVectorizerEpilogueLoop
7577//===--------------------------------------------------------------------===//
7578
7579/// This function creates a new scalar preheader, using the previous one as
7580/// entry block to the epilogue VPlan. The minimum iteration check is being
7581/// represented in VPlan.
7583 BasicBlock *NewScalarPH = createScalarPreheader("vec.epilog.");
7584 BasicBlock *OriginalScalarPH = NewScalarPH->getSinglePredecessor();
7585 OriginalScalarPH->setName("vec.epilog.iter.check");
7586 VPIRBasicBlock *NewEntry = Plan.createVPIRBasicBlock(OriginalScalarPH);
7587 VPBasicBlock *OldEntry = Plan.getEntry();
7588 for (auto &R : make_early_inc_range(*OldEntry)) {
7589 // Skip moving VPIRInstructions (including VPIRPhis), which are unmovable by
7590 // defining.
7591 if (isa<VPIRInstruction>(&R))
7592 continue;
7593 R.moveBefore(*NewEntry, NewEntry->end());
7594 }
7595
7596 VPBlockUtils::reassociateBlocks(OldEntry, NewEntry);
7597 Plan.setEntry(NewEntry);
7598 // OldEntry is now dead and will be cleaned up when the plan gets destroyed.
7599
7600 return OriginalScalarPH;
7601}
7602
7604 LLVM_DEBUG({
7605 dbgs() << "Create Skeleton for epilogue vectorized loop (second pass)\n"
7606 << "Epilogue Loop VF:" << EPI.EpilogueVF
7607 << ", Epilogue Loop UF:" << EPI.EpilogueUF << "\n";
7608 });
7609}
7610
7613 dbgs() << "final fn:\n" << *OrigLoop->getHeader()->getParent() << "\n";
7614 });
7615}
7616
7617VPWidenMemoryRecipe *VPRecipeBuilder::tryToWidenMemory(VPInstruction *VPI,
7618 VFRange &Range) {
7619 assert((VPI->getOpcode() == Instruction::Load ||
7620 VPI->getOpcode() == Instruction::Store) &&
7621 "Must be called with either a load or store");
7623
7624 auto WillWiden = [&](ElementCount VF) -> bool {
7626 CM.getWideningDecision(I, VF);
7628 "CM decision should be taken at this point.");
7630 return true;
7631 if (CM.isScalarAfterVectorization(I, VF) ||
7632 CM.isProfitableToScalarize(I, VF))
7633 return false;
7635 };
7636
7638 return nullptr;
7639
7640 VPValue *Mask = nullptr;
7641 if (Legal->isMaskRequired(I))
7642 Mask = getBlockInMask(Builder.getInsertBlock());
7643
7644 // Determine if the pointer operand of the access is either consecutive or
7645 // reverse consecutive.
7647 CM.getWideningDecision(I, Range.Start);
7649 bool Consecutive =
7651
7652 VPValue *Ptr = VPI->getOpcode() == Instruction::Load ? VPI->getOperand(0)
7653 : VPI->getOperand(1);
7654 if (Consecutive) {
7657 VPSingleDefRecipe *VectorPtr;
7658 if (Reverse) {
7659 // When folding the tail, we may compute an address that we don't in the
7660 // original scalar loop: drop the GEP no-wrap flags in this case.
7661 // Otherwise preserve existing flags without no-unsigned-wrap, as we will
7662 // emit negative indices.
7663 GEPNoWrapFlags Flags =
7664 CM.foldTailByMasking() || !GEP
7666 : GEP->getNoWrapFlags().withoutNoUnsignedWrap();
7667 VectorPtr = new VPVectorEndPointerRecipe(
7668 Ptr, &Plan.getVF(), getLoadStoreType(I),
7669 /*Stride*/ -1, Flags, VPI->getDebugLoc());
7670 } else {
7671 VectorPtr = new VPVectorPointerRecipe(Ptr, getLoadStoreType(I),
7672 GEP ? GEP->getNoWrapFlags()
7674 VPI->getDebugLoc());
7675 }
7676 Builder.insert(VectorPtr);
7677 Ptr = VectorPtr;
7678 }
7679 if (VPI->getOpcode() == Instruction::Load) {
7680 auto *Load = cast<LoadInst>(I);
7681 return new VPWidenLoadRecipe(*Load, Ptr, Mask, Consecutive, Reverse, *VPI,
7682 VPI->getDebugLoc());
7683 }
7684
7685 StoreInst *Store = cast<StoreInst>(I);
7686 return new VPWidenStoreRecipe(*Store, Ptr, VPI->getOperand(0), Mask,
7687 Consecutive, Reverse, *VPI, VPI->getDebugLoc());
7688}
7689
7690/// Creates a VPWidenIntOrFpInductionRecipe for \p PhiR. If needed, it will
7691/// also insert a recipe to expand the step for the induction recipe.
7694 const InductionDescriptor &IndDesc, VPlan &Plan,
7695 ScalarEvolution &SE, Loop &OrigLoop) {
7696 assert(SE.isLoopInvariant(IndDesc.getStep(), &OrigLoop) &&
7697 "step must be loop invariant");
7698
7699 VPValue *Start = PhiR->getOperand(0);
7700 assert((Plan.getLiveIn(IndDesc.getStartValue()) == Start ||
7701 (SE.isSCEVable(IndDesc.getStartValue()->getType()) &&
7702 SE.getSCEV(IndDesc.getStartValue()) ==
7703 vputils::getSCEVExprForVPValue(Start, SE))) &&
7704 "Start VPValue must match IndDesc's start value");
7705
7706 // It is always safe to copy over the NoWrap and FastMath flags. In
7707 // particular, when folding tail by masking, the masked-off lanes are never
7708 // used, so it is safe.
7709 VPIRFlags Flags = vputils::getFlagsFromIndDesc(IndDesc);
7710 VPValue *Step =
7712
7713 // Update wide induction increments to use the same step as the corresponding
7714 // wide induction. This enables detecting induction increments directly in
7715 // VPlan and removes redundant splats.
7716 using namespace llvm::VPlanPatternMatch;
7717 if (match(PhiR->getOperand(1), m_Add(m_Specific(PhiR), m_VPValue())))
7718 PhiR->getOperand(1)->getDefiningRecipe()->setOperand(1, Step);
7719
7721 return new VPWidenIntOrFpInductionRecipe(Phi, Start, Step, &Plan.getVF(),
7722 IndDesc, Flags, PhiR->getDebugLoc());
7723}
7724
7726VPRecipeBuilder::tryToOptimizeInductionPHI(VPInstruction *VPI) {
7727 auto *Phi = cast<PHINode>(VPI->getUnderlyingInstr());
7728
7729 // Check if this is an integer or fp induction. If so, build the recipe that
7730 // produces its scalar and vector values.
7731 if (auto *II = Legal->getIntOrFpInductionDescriptor(Phi))
7732 return createWidenInductionRecipes(VPI, *II, Plan, *PSE.getSE(), *OrigLoop);
7733
7734 // Check if this is pointer induction. If so, build the recipe for it.
7735 if (auto *II = Legal->getPointerInductionDescriptor(Phi)) {
7736 VPValue *Step = vputils::getOrCreateVPValueForSCEVExpr(Plan, II->getStep());
7737 return new VPWidenPointerInductionRecipe(Phi, VPI->getOperand(0), Step,
7738 &Plan.getVFxUF(), *II,
7739 VPI->getDebugLoc());
7740 }
7741 return nullptr;
7742}
7743
7745VPRecipeBuilder::tryToOptimizeInductionTruncate(VPInstruction *VPI,
7746 VFRange &Range) {
7747 auto *I = cast<TruncInst>(VPI->getUnderlyingInstr());
7748 // Optimize the special case where the source is a constant integer
7749 // induction variable. Notice that we can only optimize the 'trunc' case
7750 // because (a) FP conversions lose precision, (b) sext/zext may wrap, and
7751 // (c) other casts depend on pointer size.
7752
7753 // Determine whether \p K is a truncation based on an induction variable that
7754 // can be optimized.
7755 auto IsOptimizableIVTruncate =
7756 [&](Instruction *K) -> std::function<bool(ElementCount)> {
7757 return [=](ElementCount VF) -> bool {
7758 return CM.isOptimizableIVTruncate(K, VF);
7759 };
7760 };
7761
7763 IsOptimizableIVTruncate(I), Range))
7764 return nullptr;
7765
7767 VPI->getOperand(0)->getDefiningRecipe());
7768 PHINode *Phi = WidenIV->getPHINode();
7769 VPValue *Start = WidenIV->getStartValue();
7770 const InductionDescriptor &IndDesc = WidenIV->getInductionDescriptor();
7771
7772 // It is always safe to copy over the NoWrap and FastMath flags. In
7773 // particular, when folding tail by masking, the masked-off lanes are never
7774 // used, so it is safe.
7775 VPIRFlags Flags = vputils::getFlagsFromIndDesc(IndDesc);
7776 VPValue *Step =
7778 return new VPWidenIntOrFpInductionRecipe(
7779 Phi, Start, Step, &Plan.getVF(), IndDesc, I, Flags, VPI->getDebugLoc());
7780}
7781
7782VPSingleDefRecipe *VPRecipeBuilder::tryToWidenCall(VPInstruction *VPI,
7783 VFRange &Range) {
7784 CallInst *CI = cast<CallInst>(VPI->getUnderlyingInstr());
7786 [this, CI](ElementCount VF) {
7787 return CM.isScalarWithPredication(CI, VF);
7788 },
7789 Range);
7790
7791 if (IsPredicated)
7792 return nullptr;
7793
7795 if (ID && (ID == Intrinsic::assume || ID == Intrinsic::lifetime_end ||
7796 ID == Intrinsic::lifetime_start || ID == Intrinsic::sideeffect ||
7797 ID == Intrinsic::pseudoprobe ||
7798 ID == Intrinsic::experimental_noalias_scope_decl))
7799 return nullptr;
7800
7802 VPI->op_begin() + CI->arg_size());
7803
7804 // Is it beneficial to perform intrinsic call compared to lib call?
7805 bool ShouldUseVectorIntrinsic =
7807 [&](ElementCount VF) -> bool {
7808 return CM.getCallWideningDecision(CI, VF).Kind ==
7810 },
7811 Range);
7812 if (ShouldUseVectorIntrinsic)
7813 return new VPWidenIntrinsicRecipe(*CI, ID, Ops, CI->getType(), *VPI, *VPI,
7814 VPI->getDebugLoc());
7815
7816 Function *Variant = nullptr;
7817 std::optional<unsigned> MaskPos;
7818 // Is better to call a vectorized version of the function than to to scalarize
7819 // the call?
7820 auto ShouldUseVectorCall = LoopVectorizationPlanner::getDecisionAndClampRange(
7821 [&](ElementCount VF) -> bool {
7822 // The following case may be scalarized depending on the VF.
7823 // The flag shows whether we can use a usual Call for vectorized
7824 // version of the instruction.
7825
7826 // If we've found a variant at a previous VF, then stop looking. A
7827 // vectorized variant of a function expects input in a certain shape
7828 // -- basically the number of input registers, the number of lanes
7829 // per register, and whether there's a mask required.
7830 // We store a pointer to the variant in the VPWidenCallRecipe, so
7831 // once we have an appropriate variant it's only valid for that VF.
7832 // This will force a different vplan to be generated for each VF that
7833 // finds a valid variant.
7834 if (Variant)
7835 return false;
7836 LoopVectorizationCostModel::CallWideningDecision Decision =
7837 CM.getCallWideningDecision(CI, VF);
7839 Variant = Decision.Variant;
7840 MaskPos = Decision.MaskPos;
7841 return true;
7842 }
7843
7844 return false;
7845 },
7846 Range);
7847 if (ShouldUseVectorCall) {
7848 if (MaskPos.has_value()) {
7849 // We have 2 cases that would require a mask:
7850 // 1) The block needs to be predicated, either due to a conditional
7851 // in the scalar loop or use of an active lane mask with
7852 // tail-folding, and we use the appropriate mask for the block.
7853 // 2) No mask is required for the block, but the only available
7854 // vector variant at this VF requires a mask, so we synthesize an
7855 // all-true mask.
7856 VPValue *Mask = nullptr;
7857 if (Legal->isMaskRequired(CI))
7858 Mask = getBlockInMask(Builder.getInsertBlock());
7859 else
7860 Mask = Plan.getOrAddLiveIn(
7861 ConstantInt::getTrue(IntegerType::getInt1Ty(Plan.getContext())));
7862
7863 Ops.insert(Ops.begin() + *MaskPos, Mask);
7864 }
7865
7866 Ops.push_back(VPI->getOperand(VPI->getNumOperands() - 1));
7867 return new VPWidenCallRecipe(CI, Variant, Ops, *VPI, *VPI,
7868 VPI->getDebugLoc());
7869 }
7870
7871 return nullptr;
7872}
7873
7874bool VPRecipeBuilder::shouldWiden(Instruction *I, VFRange &Range) const {
7876 !isa<StoreInst>(I) && "Instruction should have been handled earlier");
7877 // Instruction should be widened, unless it is scalar after vectorization,
7878 // scalarization is profitable or it is predicated.
7879 auto WillScalarize = [this, I](ElementCount VF) -> bool {
7880 return CM.isScalarAfterVectorization(I, VF) ||
7881 CM.isProfitableToScalarize(I, VF) ||
7882 CM.isScalarWithPredication(I, VF);
7883 };
7885 Range);
7886}
7887
7888VPWidenRecipe *VPRecipeBuilder::tryToWiden(VPInstruction *VPI) {
7889 auto *I = VPI->getUnderlyingInstr();
7890 switch (VPI->getOpcode()) {
7891 default:
7892 return nullptr;
7893 case Instruction::SDiv:
7894 case Instruction::UDiv:
7895 case Instruction::SRem:
7896 case Instruction::URem: {
7897 // If not provably safe, use a select to form a safe divisor before widening the
7898 // div/rem operation itself. Otherwise fall through to general handling below.
7899 if (CM.isPredicatedInst(I)) {
7901 VPValue *Mask = getBlockInMask(Builder.getInsertBlock());
7902 VPValue *One = Plan.getConstantInt(I->getType(), 1u);
7903 auto *SafeRHS =
7904 Builder.createSelect(Mask, Ops[1], One, VPI->getDebugLoc());
7905 Ops[1] = SafeRHS;
7906 return new VPWidenRecipe(*I, Ops, *VPI, *VPI, VPI->getDebugLoc());
7907 }
7908 [[fallthrough]];
7909 }
7910 case Instruction::Add:
7911 case Instruction::And:
7912 case Instruction::AShr:
7913 case Instruction::FAdd:
7914 case Instruction::FCmp:
7915 case Instruction::FDiv:
7916 case Instruction::FMul:
7917 case Instruction::FNeg:
7918 case Instruction::FRem:
7919 case Instruction::FSub:
7920 case Instruction::ICmp:
7921 case Instruction::LShr:
7922 case Instruction::Mul:
7923 case Instruction::Or:
7924 case Instruction::Select:
7925 case Instruction::Shl:
7926 case Instruction::Sub:
7927 case Instruction::Xor:
7928 case Instruction::Freeze: {
7929 SmallVector<VPValue *> NewOps(VPI->operands());
7930 if (Instruction::isBinaryOp(VPI->getOpcode())) {
7931 // The legacy cost model uses SCEV to check if some of the operands are
7932 // constants. To match the legacy cost model's behavior, use SCEV to try
7933 // to replace operands with constants.
7934 ScalarEvolution &SE = *PSE.getSE();
7935 auto GetConstantViaSCEV = [this, &SE](VPValue *Op) {
7936 if (!Op->isLiveIn())
7937 return Op;
7938 Value *V = Op->getUnderlyingValue();
7939 if (isa<Constant>(V) || !SE.isSCEVable(V->getType()))
7940 return Op;
7941 auto *C = dyn_cast<SCEVConstant>(SE.getSCEV(V));
7942 if (!C)
7943 return Op;
7944 return Plan.getOrAddLiveIn(C->getValue());
7945 };
7946 // For Mul, the legacy cost model checks both operands.
7947 if (VPI->getOpcode() == Instruction::Mul)
7948 NewOps[0] = GetConstantViaSCEV(NewOps[0]);
7949 // For other binops, the legacy cost model only checks the second operand.
7950 NewOps[1] = GetConstantViaSCEV(NewOps[1]);
7951 }
7952 return new VPWidenRecipe(*I, NewOps, *VPI, *VPI, VPI->getDebugLoc());
7953 }
7954 case Instruction::ExtractValue: {
7955 SmallVector<VPValue *> NewOps(VPI->operands());
7956 auto *EVI = cast<ExtractValueInst>(I);
7957 assert(EVI->getNumIndices() == 1 && "Expected one extractvalue index");
7958 unsigned Idx = EVI->getIndices()[0];
7959 NewOps.push_back(Plan.getConstantInt(32, Idx));
7960 return new VPWidenRecipe(*I, NewOps, *VPI, *VPI, VPI->getDebugLoc());
7961 }
7962 };
7963}
7964
7965VPHistogramRecipe *VPRecipeBuilder::tryToWidenHistogram(const HistogramInfo *HI,
7966 VPInstruction *VPI) {
7967 // FIXME: Support other operations.
7968 unsigned Opcode = HI->Update->getOpcode();
7969 assert((Opcode == Instruction::Add || Opcode == Instruction::Sub) &&
7970 "Histogram update operation must be an Add or Sub");
7971
7973 // Bucket address.
7974 HGramOps.push_back(VPI->getOperand(1));
7975 // Increment value.
7976 HGramOps.push_back(getVPValueOrAddLiveIn(HI->Update->getOperand(1)));
7977
7978 // In case of predicated execution (due to tail-folding, or conditional
7979 // execution, or both), pass the relevant mask.
7980 if (Legal->isMaskRequired(HI->Store))
7981 HGramOps.push_back(getBlockInMask(Builder.getInsertBlock()));
7982
7983 return new VPHistogramRecipe(Opcode, HGramOps, VPI->getDebugLoc());
7984}
7985
7987 VFRange &Range) {
7988 auto *I = VPI->getUnderlyingInstr();
7990 [&](ElementCount VF) { return CM.isUniformAfterVectorization(I, VF); },
7991 Range);
7992
7993 bool IsPredicated = CM.isPredicatedInst(I);
7994
7995 // Even if the instruction is not marked as uniform, there are certain
7996 // intrinsic calls that can be effectively treated as such, so we check for
7997 // them here. Conservatively, we only do this for scalable vectors, since
7998 // for fixed-width VFs we can always fall back on full scalarization.
7999 if (!IsUniform && Range.Start.isScalable() && isa<IntrinsicInst>(I)) {
8000 switch (cast<IntrinsicInst>(I)->getIntrinsicID()) {
8001 case Intrinsic::assume:
8002 case Intrinsic::lifetime_start:
8003 case Intrinsic::lifetime_end:
8004 // For scalable vectors if one of the operands is variant then we still
8005 // want to mark as uniform, which will generate one instruction for just
8006 // the first lane of the vector. We can't scalarize the call in the same
8007 // way as for fixed-width vectors because we don't know how many lanes
8008 // there are.
8009 //
8010 // The reasons for doing it this way for scalable vectors are:
8011 // 1. For the assume intrinsic generating the instruction for the first
8012 // lane is still be better than not generating any at all. For
8013 // example, the input may be a splat across all lanes.
8014 // 2. For the lifetime start/end intrinsics the pointer operand only
8015 // does anything useful when the input comes from a stack object,
8016 // which suggests it should always be uniform. For non-stack objects
8017 // the effect is to poison the object, which still allows us to
8018 // remove the call.
8019 IsUniform = true;
8020 break;
8021 default:
8022 break;
8023 }
8024 }
8025 VPValue *BlockInMask = nullptr;
8026 if (!IsPredicated) {
8027 // Finalize the recipe for Instr, first if it is not predicated.
8028 LLVM_DEBUG(dbgs() << "LV: Scalarizing:" << *I << "\n");
8029 } else {
8030 LLVM_DEBUG(dbgs() << "LV: Scalarizing and predicating:" << *I << "\n");
8031 // Instructions marked for predication are replicated and a mask operand is
8032 // added initially. Masked replicate recipes will later be placed under an
8033 // if-then construct to prevent side-effects. Generate recipes to compute
8034 // the block mask for this region.
8035 BlockInMask = getBlockInMask(Builder.getInsertBlock());
8036 }
8037
8038 // Note that there is some custom logic to mark some intrinsics as uniform
8039 // manually above for scalable vectors, which this assert needs to account for
8040 // as well.
8041 assert((Range.Start.isScalar() || !IsUniform || !IsPredicated ||
8042 (Range.Start.isScalable() && isa<IntrinsicInst>(I))) &&
8043 "Should not predicate a uniform recipe");
8044 auto *Recipe =
8045 new VPReplicateRecipe(I, VPI->operands(), IsUniform, BlockInMask, *VPI,
8046 *VPI, VPI->getDebugLoc());
8047 return Recipe;
8048}
8049
8050/// Find all possible partial reductions in the loop and track all of those that
8051/// are valid so recipes can be formed later.
8053 // Find all possible partial reductions, grouping chains by their PHI. This
8054 // grouping allows invalidating the whole chain, if any link is not a valid
8055 // partial reduction.
8058 ChainsByPhi;
8059 for (const auto &[Phi, RdxDesc] : Legal->getReductionVars()) {
8060 if (Instruction *RdxExitInstr = RdxDesc.getLoopExitInstr())
8061 getScaledReductions(Phi, RdxExitInstr, Range, ChainsByPhi[Phi]);
8062 }
8063
8064 // A partial reduction is invalid if any of its extends are used by
8065 // something that isn't another partial reduction. This is because the
8066 // extends are intended to be lowered along with the reduction itself.
8067
8068 // Build up a set of partial reduction ops for efficient use checking.
8069 SmallPtrSet<User *, 4> PartialReductionOps;
8070 for (const auto &[_, Chains] : ChainsByPhi)
8071 for (const auto &[PartialRdx, _] : Chains)
8072 PartialReductionOps.insert(PartialRdx.ExtendUser);
8073
8074 auto ExtendIsOnlyUsedByPartialReductions =
8075 [&PartialReductionOps](Instruction *Extend) {
8076 return all_of(Extend->users(), [&](const User *U) {
8077 return PartialReductionOps.contains(U);
8078 });
8079 };
8080
8081 // Check if each use of a chain's two extends is a partial reduction
8082 // and only add those that don't have non-partial reduction users.
8083 for (const auto &[_, Chains] : ChainsByPhi) {
8084 for (const auto &[Chain, Scale] : Chains) {
8085 if (ExtendIsOnlyUsedByPartialReductions(Chain.ExtendA) &&
8086 (!Chain.ExtendB ||
8087 ExtendIsOnlyUsedByPartialReductions(Chain.ExtendB)))
8088 ScaledReductionMap.try_emplace(Chain.Reduction, Scale);
8089 }
8090 }
8091
8092 // Check that all partial reductions in a chain are only used by other
8093 // partial reductions with the same scale factor. Otherwise we end up creating
8094 // users of scaled reductions where the types of the other operands don't
8095 // match.
8096 for (const auto &[Phi, Chains] : ChainsByPhi) {
8097 for (const auto &[Chain, Scale] : Chains) {
8098 auto AllUsersPartialRdx = [ScaleVal = Scale, RdxPhi = Phi,
8099 this](const User *U) {
8100 auto *UI = cast<Instruction>(U);
8101 if (isa<PHINode>(UI) && UI->getParent() == OrigLoop->getHeader())
8102 return UI == RdxPhi;
8103 return ScaledReductionMap.lookup_or(UI, 0) == ScaleVal ||
8104 !OrigLoop->contains(UI->getParent());
8105 };
8106
8107 // If any partial reduction entry for the phi is invalid, invalidate the
8108 // whole chain.
8109 if (!all_of(Chain.Reduction->users(), AllUsersPartialRdx)) {
8110 for (const auto &[Chain, _] : Chains)
8111 ScaledReductionMap.erase(Chain.Reduction);
8112 break;
8113 }
8114 }
8115 }
8116}
8117
8118bool VPRecipeBuilder::getScaledReductions(
8119 Instruction *PHI, Instruction *RdxExitInstr, VFRange &Range,
8120 SmallVectorImpl<std::pair<PartialReductionChain, unsigned>> &Chains) {
8121 if (!CM.TheLoop->contains(RdxExitInstr))
8122 return false;
8123
8124 auto *Update = dyn_cast<BinaryOperator>(RdxExitInstr);
8125 if (!Update)
8126 return false;
8127
8128 Value *Op = Update->getOperand(0);
8129 Value *PhiOp = Update->getOperand(1);
8130 if (Op == PHI)
8131 std::swap(Op, PhiOp);
8132
8133 using namespace llvm::PatternMatch;
8134 // If Op is an extend, then it's still a valid partial reduction if the
8135 // extended mul fulfills the other requirements.
8136 // For example, reduce.add(ext(mul(ext(A), ext(B)))) is still a valid partial
8137 // reduction since the inner extends will be widened. We already have oneUse
8138 // checks on the inner extends so widening them is safe.
8139 std::optional<TTI::PartialReductionExtendKind> OuterExtKind = std::nullopt;
8140 if (match(Op, m_ZExtOrSExt(m_Mul(m_Value(), m_Value())))) {
8141 auto *Cast = cast<CastInst>(Op);
8142 OuterExtKind = TTI::getPartialReductionExtendKind(Cast->getOpcode());
8143 Op = Cast->getOperand(0);
8144 }
8145
8146 // Try and get a scaled reduction from the first non-phi operand.
8147 // If one is found, we use the discovered reduction instruction in
8148 // place of the accumulator for costing.
8149 if (auto *OpInst = dyn_cast<Instruction>(Op)) {
8150 if (getScaledReductions(PHI, OpInst, Range, Chains)) {
8151 PHI = Chains.rbegin()->first.Reduction;
8152
8153 Op = Update->getOperand(0);
8154 PhiOp = Update->getOperand(1);
8155 if (Op == PHI)
8156 std::swap(Op, PhiOp);
8157 }
8158 }
8159 if (PhiOp != PHI)
8160 return false;
8161
8162 // If the update is a binary operator, check both of its operands to see if
8163 // they are extends. Otherwise, see if the update comes directly from an
8164 // extend.
8165 Instruction *Exts[2] = {nullptr};
8166 BinaryOperator *ExtendUser = dyn_cast<BinaryOperator>(Op);
8167 std::optional<unsigned> BinOpc;
8168 Type *ExtOpTypes[2] = {nullptr};
8170
8171 auto CollectExtInfo = [this, OuterExtKind, &Exts, &ExtOpTypes,
8172 &ExtKinds](SmallVectorImpl<Value *> &Ops) -> bool {
8173 for (const auto &[I, OpI] : enumerate(Ops)) {
8174 const APInt *C;
8175 if (I > 0 && match(OpI, m_APInt(C)) &&
8176 canConstantBeExtended(C, ExtOpTypes[0], ExtKinds[0])) {
8177 ExtOpTypes[I] = ExtOpTypes[0];
8178 ExtKinds[I] = ExtKinds[0];
8179 continue;
8180 }
8181 Value *ExtOp;
8182 if (!match(OpI, m_ZExtOrSExt(m_Value(ExtOp))))
8183 return false;
8184 Exts[I] = cast<Instruction>(OpI);
8185
8186 // TODO: We should be able to support live-ins.
8187 if (!CM.TheLoop->contains(Exts[I]))
8188 return false;
8189
8190 ExtOpTypes[I] = ExtOp->getType();
8191 ExtKinds[I] = TTI::getPartialReductionExtendKind(Exts[I]);
8192 // The outer extend kind must be the same as the inner extends, so that
8193 // they can be folded together.
8194 if (OuterExtKind.has_value() && OuterExtKind.value() != ExtKinds[I])
8195 return false;
8196 }
8197 return true;
8198 };
8199
8200 if (ExtendUser) {
8201 if (!ExtendUser->hasOneUse())
8202 return false;
8203
8204 // Use the side-effect of match to replace BinOp only if the pattern is
8205 // matched, we don't care at this point whether it actually matched.
8206 match(ExtendUser, m_Neg(m_BinOp(ExtendUser)));
8207
8208 SmallVector<Value *> Ops(ExtendUser->operands());
8209 if (!CollectExtInfo(Ops))
8210 return false;
8211
8212 BinOpc = std::make_optional(ExtendUser->getOpcode());
8213 } else if (match(Update, m_Add(m_Value(), m_Value()))) {
8214 // We already know the operands for Update are Op and PhiOp.
8216 if (!CollectExtInfo(Ops))
8217 return false;
8218
8219 ExtendUser = Update;
8220 BinOpc = std::nullopt;
8221 } else
8222 return false;
8223
8224 PartialReductionChain Chain(RdxExitInstr, Exts[0], Exts[1], ExtendUser);
8225
8226 TypeSize PHISize = PHI->getType()->getPrimitiveSizeInBits();
8227 TypeSize ASize = ExtOpTypes[0]->getPrimitiveSizeInBits();
8228 if (!PHISize.hasKnownScalarFactor(ASize))
8229 return false;
8230 unsigned TargetScaleFactor = PHISize.getKnownScalarFactor(ASize);
8231
8233 [&](ElementCount VF) {
8234 InstructionCost Cost = TTI->getPartialReductionCost(
8235 Update->getOpcode(), ExtOpTypes[0], ExtOpTypes[1],
8236 PHI->getType(), VF, ExtKinds[0], ExtKinds[1], BinOpc,
8237 CM.CostKind);
8238 return Cost.isValid();
8239 },
8240 Range)) {
8241 Chains.emplace_back(Chain, TargetScaleFactor);
8242 return true;
8243 }
8244
8245 return false;
8246}
8247
8249 VFRange &Range) {
8250 // First, check for specific widening recipes that deal with inductions, Phi
8251 // nodes, calls and memory operations.
8252 VPRecipeBase *Recipe;
8253 if (auto *PhiR = dyn_cast<VPPhi>(R)) {
8254 VPBasicBlock *Parent = PhiR->getParent();
8255 [[maybe_unused]] VPRegionBlock *LoopRegionOf =
8256 Parent->getEnclosingLoopRegion();
8257 assert(LoopRegionOf && LoopRegionOf->getEntry() == Parent &&
8258 "Non-header phis should have been handled during predication");
8259 auto *Phi = cast<PHINode>(R->getUnderlyingInstr());
8260 assert(R->getNumOperands() == 2 && "Must have 2 operands for header phis");
8261 if ((Recipe = tryToOptimizeInductionPHI(PhiR)))
8262 return Recipe;
8263
8264 VPHeaderPHIRecipe *PhiRecipe = nullptr;
8265 assert((Legal->isReductionVariable(Phi) ||
8266 Legal->isFixedOrderRecurrence(Phi)) &&
8267 "can only widen reductions and fixed-order recurrences here");
8268 VPValue *StartV = R->getOperand(0);
8269 if (Legal->isReductionVariable(Phi)) {
8270 const RecurrenceDescriptor &RdxDesc = Legal->getRecurrenceDescriptor(Phi);
8271 assert(RdxDesc.getRecurrenceStartValue() ==
8272 Phi->getIncomingValueForBlock(OrigLoop->getLoopPreheader()));
8273
8274 // If the PHI is used by a partial reduction, set the scale factor.
8275 bool UseInLoopReduction = CM.isInLoopReduction(Phi);
8276 bool UseOrderedReductions = CM.useOrderedReductions(RdxDesc);
8277 unsigned ScaleFactor =
8278 getScalingForReduction(RdxDesc.getLoopExitInstr()).value_or(1);
8279
8280 PhiRecipe = new VPReductionPHIRecipe(
8281 Phi, RdxDesc.getRecurrenceKind(), *StartV,
8282 getReductionStyle(UseInLoopReduction, UseOrderedReductions,
8283 ScaleFactor),
8285 } else {
8286 // TODO: Currently fixed-order recurrences are modeled as chains of
8287 // first-order recurrences. If there are no users of the intermediate
8288 // recurrences in the chain, the fixed order recurrence should be modeled
8289 // directly, enabling more efficient codegen.
8290 PhiRecipe = new VPFirstOrderRecurrencePHIRecipe(Phi, *StartV);
8291 }
8292 // Add backedge value.
8293 PhiRecipe->addOperand(R->getOperand(1));
8294 return PhiRecipe;
8295 }
8296 assert(!R->isPhi() && "only VPPhi nodes expected at this point");
8297
8298 auto *VPI = cast<VPInstruction>(R);
8299 Instruction *Instr = R->getUnderlyingInstr();
8300 if (VPI->getOpcode() == Instruction::Trunc &&
8301 (Recipe = tryToOptimizeInductionTruncate(VPI, Range)))
8302 return Recipe;
8303
8304 // All widen recipes below deal only with VF > 1.
8306 [&](ElementCount VF) { return VF.isScalar(); }, Range))
8307 return nullptr;
8308
8309 if (VPI->getOpcode() == Instruction::Call)
8310 return tryToWidenCall(VPI, Range);
8311
8312 if (VPI->getOpcode() == Instruction::Store)
8313 if (auto HistInfo = Legal->getHistogramInfo(cast<StoreInst>(Instr)))
8314 return tryToWidenHistogram(*HistInfo, VPI);
8315
8316 if (VPI->getOpcode() == Instruction::Load ||
8317 VPI->getOpcode() == Instruction::Store)
8318 return tryToWidenMemory(VPI, Range);
8319
8320 if (std::optional<unsigned> ScaleFactor = getScalingForReduction(Instr))
8321 return tryToCreatePartialReduction(VPI, ScaleFactor.value());
8322
8323 if (!shouldWiden(Instr, Range))
8324 return nullptr;
8325
8326 if (VPI->getOpcode() == Instruction::GetElementPtr)
8327 return new VPWidenGEPRecipe(cast<GetElementPtrInst>(Instr), R->operands(),
8328 *VPI, VPI->getDebugLoc());
8329
8330 if (VPI->getOpcode() == Instruction::Select)
8331 return new VPWidenSelectRecipe(cast<SelectInst>(Instr), R->operands(), *VPI,
8332 *VPI, VPI->getDebugLoc());
8333
8334 if (Instruction::isCast(VPI->getOpcode())) {
8335 auto *CI = cast<CastInst>(Instr);
8336 auto *CastR = cast<VPInstructionWithType>(VPI);
8337 return new VPWidenCastRecipe(CI->getOpcode(), VPI->getOperand(0),
8338 CastR->getResultType(), CI, *VPI, *VPI,
8339 VPI->getDebugLoc());
8340 }
8341
8342 return tryToWiden(VPI);
8343}
8344
8347 unsigned ScaleFactor) {
8348 assert(Reduction->getNumOperands() == 2 &&
8349 "Unexpected number of operands for partial reduction");
8350
8351 VPValue *BinOp = Reduction->getOperand(0);
8352 VPValue *Accumulator = Reduction->getOperand(1);
8353 VPRecipeBase *BinOpRecipe = BinOp->getDefiningRecipe();
8354 if (isa<VPReductionPHIRecipe>(BinOpRecipe) ||
8355 (isa<VPReductionRecipe>(BinOpRecipe) &&
8356 cast<VPReductionRecipe>(BinOpRecipe)->isPartialReduction()))
8357 std::swap(BinOp, Accumulator);
8358
8359 assert(ScaleFactor ==
8360 vputils::getVFScaleFactor(Accumulator->getDefiningRecipe()) &&
8361 "all accumulators in chain must have same scale factor");
8362
8363 auto *ReductionI = Reduction->getUnderlyingInstr();
8364 if (Reduction->getOpcode() == Instruction::Sub) {
8365 auto *const Zero = ConstantInt::get(ReductionI->getType(), 0);
8367 Ops.push_back(Plan.getOrAddLiveIn(Zero));
8368 Ops.push_back(BinOp);
8369 BinOp = new VPWidenRecipe(*ReductionI, Ops, VPIRFlags(*ReductionI),
8370 VPIRMetadata(), ReductionI->getDebugLoc());
8371 Builder.insert(BinOp->getDefiningRecipe());
8372 }
8373
8374 VPValue *Cond = nullptr;
8375 if (CM.blockNeedsPredicationForAnyReason(ReductionI->getParent()))
8376 Cond = getBlockInMask(Builder.getInsertBlock());
8377
8378 return new VPReductionRecipe(
8379 RecurKind::Add, FastMathFlags(), ReductionI, Accumulator, BinOp, Cond,
8380 RdxUnordered{/*VFScaleFactor=*/ScaleFactor}, ReductionI->getDebugLoc());
8381}
8382
8383void LoopVectorizationPlanner::buildVPlansWithVPRecipes(ElementCount MinVF,
8384 ElementCount MaxVF) {
8385 if (ElementCount::isKnownGT(MinVF, MaxVF))
8386 return;
8387
8388 assert(OrigLoop->isInnermost() && "Inner loop expected.");
8389
8390 const LoopAccessInfo *LAI = Legal->getLAI();
8392 OrigLoop, LI, DT, PSE.getSE());
8393 if (!LAI->getRuntimePointerChecking()->getChecks().empty() &&
8395 // Only use noalias metadata when using memory checks guaranteeing no
8396 // overlap across all iterations.
8397 LVer.prepareNoAliasMetadata();
8398 }
8399
8400 // Create initial base VPlan0, to serve as common starting point for all
8401 // candidates built later for specific VF ranges.
8402 auto VPlan0 = VPlanTransforms::buildVPlan0(
8403 OrigLoop, *LI, Legal->getWidestInductionType(),
8404 getDebugLocFromInstOrOperands(Legal->getPrimaryInduction()), PSE, &LVer);
8405
8406 auto MaxVFTimes2 = MaxVF * 2;
8407 for (ElementCount VF = MinVF; ElementCount::isKnownLT(VF, MaxVFTimes2);) {
8408 VFRange SubRange = {VF, MaxVFTimes2};
8409 if (auto Plan = tryToBuildVPlanWithVPRecipes(
8410 std::unique_ptr<VPlan>(VPlan0->duplicate()), SubRange, &LVer)) {
8411 // Now optimize the initial VPlan.
8412 VPlanTransforms::hoistPredicatedLoads(*Plan, *PSE.getSE(), OrigLoop);
8413 VPlanTransforms::sinkPredicatedStores(*Plan, *PSE.getSE(), OrigLoop);
8415 *Plan, CM.getMinimalBitwidths());
8417 // TODO: try to put it close to addActiveLaneMask().
8418 if (CM.foldTailWithEVL())
8420 *Plan, CM.getMaxSafeElements());
8421 assert(verifyVPlanIsValid(*Plan) && "VPlan is invalid");
8422 VPlans.push_back(std::move(Plan));
8423 }
8424 VF = SubRange.End;
8425 }
8426}
8427
8428VPlanPtr LoopVectorizationPlanner::tryToBuildVPlanWithVPRecipes(
8429 VPlanPtr Plan, VFRange &Range, LoopVersioning *LVer) {
8430
8431 using namespace llvm::VPlanPatternMatch;
8432 SmallPtrSet<const InterleaveGroup<Instruction> *, 1> InterleaveGroups;
8433
8434 // ---------------------------------------------------------------------------
8435 // Build initial VPlan: Scan the body of the loop in a topological order to
8436 // visit each basic block after having visited its predecessor basic blocks.
8437 // ---------------------------------------------------------------------------
8438
8439 bool RequiresScalarEpilogueCheck =
8441 [this](ElementCount VF) {
8442 return !CM.requiresScalarEpilogue(VF.isVector());
8443 },
8444 Range);
8445 VPlanTransforms::handleEarlyExits(*Plan, Legal->hasUncountableEarlyExit());
8446 VPlanTransforms::addMiddleCheck(*Plan, RequiresScalarEpilogueCheck,
8447 CM.foldTailByMasking());
8448
8450
8451 // Don't use getDecisionAndClampRange here, because we don't know the UF
8452 // so this function is better to be conservative, rather than to split
8453 // it up into different VPlans.
8454 // TODO: Consider using getDecisionAndClampRange here to split up VPlans.
8455 bool IVUpdateMayOverflow = false;
8456 for (ElementCount VF : Range)
8457 IVUpdateMayOverflow |= !isIndvarOverflowCheckKnownFalse(&CM, VF);
8458
8459 TailFoldingStyle Style = CM.getTailFoldingStyle(IVUpdateMayOverflow);
8460 // Use NUW for the induction increment if we proved that it won't overflow in
8461 // the vector loop or when not folding the tail. In the later case, we know
8462 // that the canonical induction increment will not overflow as the vector trip
8463 // count is >= increment and a multiple of the increment.
8464 VPRegionBlock *LoopRegion = Plan->getVectorLoopRegion();
8465 bool HasNUW = !IVUpdateMayOverflow || Style == TailFoldingStyle::None;
8466 if (!HasNUW) {
8467 auto *IVInc =
8468 LoopRegion->getExitingBasicBlock()->getTerminator()->getOperand(0);
8469 assert(match(IVInc,
8470 m_VPInstruction<Instruction::Add>(
8471 m_Specific(LoopRegion->getCanonicalIV()), m_VPValue())) &&
8472 "Did not find the canonical IV increment");
8473 cast<VPRecipeWithIRFlags>(IVInc)->dropPoisonGeneratingFlags();
8474 }
8475
8476 // ---------------------------------------------------------------------------
8477 // Pre-construction: record ingredients whose recipes we'll need to further
8478 // process after constructing the initial VPlan.
8479 // ---------------------------------------------------------------------------
8480
8481 // For each interleave group which is relevant for this (possibly trimmed)
8482 // Range, add it to the set of groups to be later applied to the VPlan and add
8483 // placeholders for its members' Recipes which we'll be replacing with a
8484 // single VPInterleaveRecipe.
8485 for (InterleaveGroup<Instruction> *IG : IAI.getInterleaveGroups()) {
8486 auto ApplyIG = [IG, this](ElementCount VF) -> bool {
8487 bool Result = (VF.isVector() && // Query is illegal for VF == 1
8488 CM.getWideningDecision(IG->getInsertPos(), VF) ==
8490 // For scalable vectors, the interleave factors must be <= 8 since we
8491 // require the (de)interleaveN intrinsics instead of shufflevectors.
8492 assert((!Result || !VF.isScalable() || IG->getFactor() <= 8) &&
8493 "Unsupported interleave factor for scalable vectors");
8494 return Result;
8495 };
8496 if (!getDecisionAndClampRange(ApplyIG, Range))
8497 continue;
8498 InterleaveGroups.insert(IG);
8499 }
8500
8501 // ---------------------------------------------------------------------------
8502 // Predicate and linearize the top-level loop region.
8503 // ---------------------------------------------------------------------------
8504 auto BlockMaskCache = VPlanTransforms::introduceMasksAndLinearize(
8505 *Plan, CM.foldTailByMasking());
8506
8507 // ---------------------------------------------------------------------------
8508 // Construct wide recipes and apply predication for original scalar
8509 // VPInstructions in the loop.
8510 // ---------------------------------------------------------------------------
8511 VPRecipeBuilder RecipeBuilder(*Plan, OrigLoop, TLI, &TTI, Legal, CM, PSE,
8512 Builder, BlockMaskCache);
8513 // TODO: Handle partial reductions with EVL tail folding.
8514 if (!CM.foldTailWithEVL())
8515 RecipeBuilder.collectScaledReductions(Range);
8516
8517 // Scan the body of the loop in a topological order to visit each basic block
8518 // after having visited its predecessor basic blocks.
8519 VPBasicBlock *HeaderVPBB = LoopRegion->getEntryBasicBlock();
8520 ReversePostOrderTraversal<VPBlockShallowTraversalWrapper<VPBlockBase *>> RPOT(
8521 HeaderVPBB);
8522
8523 auto *MiddleVPBB = Plan->getMiddleBlock();
8524 VPBasicBlock::iterator MBIP = MiddleVPBB->getFirstNonPhi();
8525 // Mapping from VPValues in the initial plan to their widened VPValues. Needed
8526 // temporarily to update created block masks.
8527 DenseMap<VPValue *, VPValue *> Old2New;
8528 for (VPBasicBlock *VPBB : VPBlockUtils::blocksOnly<VPBasicBlock>(RPOT)) {
8529 // Convert input VPInstructions to widened recipes.
8530 for (VPRecipeBase &R : make_early_inc_range(*VPBB)) {
8531 auto *SingleDef = cast<VPSingleDefRecipe>(&R);
8532 auto *UnderlyingValue = SingleDef->getUnderlyingValue();
8533 // Skip recipes that do not need transforming, including canonical IV,
8534 // wide canonical IV and VPInstructions without underlying values. The
8535 // latter are added above for masking.
8536 // FIXME: Migrate code relying on the underlying instruction from VPlan0
8537 // to construct recipes below to not use the underlying instruction.
8539 &R) ||
8540 (isa<VPInstruction>(&R) && !UnderlyingValue))
8541 continue;
8542 assert(isa<VPInstruction>(&R) && UnderlyingValue && "unsupported recipe");
8543
8544 // TODO: Gradually replace uses of underlying instruction by analyses on
8545 // VPlan.
8546 Instruction *Instr = cast<Instruction>(UnderlyingValue);
8547 Builder.setInsertPoint(SingleDef);
8548
8549 // The stores with invariant address inside the loop will be deleted, and
8550 // in the exit block, a uniform store recipe will be created for the final
8551 // invariant store of the reduction.
8552 StoreInst *SI;
8553 if ((SI = dyn_cast<StoreInst>(Instr)) &&
8554 Legal->isInvariantAddressOfReduction(SI->getPointerOperand())) {
8555 // Only create recipe for the final invariant store of the reduction.
8556 if (Legal->isInvariantStoreOfReduction(SI)) {
8557 auto *VPI = cast<VPInstruction>(SingleDef);
8558 auto *Recipe = new VPReplicateRecipe(
8559 SI, R.operands(), true /* IsUniform */, nullptr /*Mask*/, *VPI,
8560 *VPI, VPI->getDebugLoc());
8561 Recipe->insertBefore(*MiddleVPBB, MBIP);
8562 }
8563 R.eraseFromParent();
8564 continue;
8565 }
8566
8567 VPRecipeBase *Recipe =
8568 RecipeBuilder.tryToCreateWidenRecipe(SingleDef, Range);
8569 if (!Recipe)
8570 Recipe = RecipeBuilder.handleReplication(cast<VPInstruction>(SingleDef),
8571 Range);
8572
8573 RecipeBuilder.setRecipe(Instr, Recipe);
8574 if (isa<VPWidenIntOrFpInductionRecipe>(Recipe) && isa<TruncInst>(Instr)) {
8575 // Optimized a truncate to VPWidenIntOrFpInductionRecipe. It needs to be
8576 // moved to the phi section in the header.
8577 Recipe->insertBefore(*HeaderVPBB, HeaderVPBB->getFirstNonPhi());
8578 } else {
8579 Builder.insert(Recipe);
8580 }
8581 if (Recipe->getNumDefinedValues() == 1) {
8582 SingleDef->replaceAllUsesWith(Recipe->getVPSingleValue());
8583 Old2New[SingleDef] = Recipe->getVPSingleValue();
8584 } else {
8585 assert(Recipe->getNumDefinedValues() == 0 &&
8586 "Unexpected multidef recipe");
8587 R.eraseFromParent();
8588 }
8589 }
8590 }
8591
8592 // replaceAllUsesWith above may invalidate the block masks. Update them here.
8593 // TODO: Include the masks as operands in the predicated VPlan directly
8594 // to remove the need to keep a map of masks beyond the predication
8595 // transform.
8596 RecipeBuilder.updateBlockMaskCache(Old2New);
8597 for (VPValue *Old : Old2New.keys())
8598 Old->getDefiningRecipe()->eraseFromParent();
8599
8600 assert(isa<VPRegionBlock>(LoopRegion) &&
8601 !LoopRegion->getEntryBasicBlock()->empty() &&
8602 "entry block must be set to a VPRegionBlock having a non-empty entry "
8603 "VPBasicBlock");
8604
8605 // TODO: We can't call runPass on these transforms yet, due to verifier
8606 // failures.
8608 DenseMap<VPValue *, VPValue *> IVEndValues;
8609 VPlanTransforms::updateScalarResumePhis(*Plan, IVEndValues);
8610
8611 // ---------------------------------------------------------------------------
8612 // Transform initial VPlan: Apply previously taken decisions, in order, to
8613 // bring the VPlan to its final state.
8614 // ---------------------------------------------------------------------------
8615
8616 // Adjust the recipes for any inloop reductions.
8617 adjustRecipesForReductions(Plan, RecipeBuilder, Range.Start);
8618
8619 // Apply mandatory transformation to handle reductions with multiple in-loop
8620 // uses if possible, bail out otherwise.
8622 *Plan))
8623 return nullptr;
8624 // Apply mandatory transformation to handle FP maxnum/minnum reduction with
8625 // NaNs if possible, bail out otherwise.
8627 *Plan))
8628 return nullptr;
8629
8630 // Transform recipes to abstract recipes if it is legal and beneficial and
8631 // clamp the range for better cost estimation.
8632 // TODO: Enable following transform when the EVL-version of extended-reduction
8633 // and mulacc-reduction are implemented.
8634 if (!CM.foldTailWithEVL()) {
8635 VPCostContext CostCtx(CM.TTI, *CM.TLI, *Plan, CM, CM.CostKind,
8636 *CM.PSE.getSE(), OrigLoop);
8638 CostCtx, Range);
8639 }
8640
8641 for (ElementCount VF : Range)
8642 Plan->addVF(VF);
8643 Plan->setName("Initial VPlan");
8644
8645 // Interleave memory: for each Interleave Group we marked earlier as relevant
8646 // for this VPlan, replace the Recipes widening its memory instructions with a
8647 // single VPInterleaveRecipe at its insertion point.
8649 InterleaveGroups, RecipeBuilder,
8650 CM.isScalarEpilogueAllowed());
8651
8652 // Replace VPValues for known constant strides.
8654 Legal->getLAI()->getSymbolicStrides());
8655
8656 auto BlockNeedsPredication = [this](BasicBlock *BB) {
8657 return Legal->blockNeedsPredication(BB);
8658 };
8660 BlockNeedsPredication);
8661
8662 // Sink users of fixed-order recurrence past the recipe defining the previous
8663 // value and introduce FirstOrderRecurrenceSplice VPInstructions.
8665 *Plan, Builder))
8666 return nullptr;
8667
8668 if (useActiveLaneMask(Style)) {
8669 // TODO: Move checks to VPlanTransforms::addActiveLaneMask once
8670 // TailFoldingStyle is visible there.
8671 bool ForControlFlow = useActiveLaneMaskForControlFlow(Style);
8672 bool WithoutRuntimeCheck =
8674 VPlanTransforms::addActiveLaneMask(*Plan, ForControlFlow,
8675 WithoutRuntimeCheck);
8676 }
8677 VPlanTransforms::optimizeInductionExitUsers(*Plan, IVEndValues, *PSE.getSE());
8678
8679 assert(verifyVPlanIsValid(*Plan) && "VPlan is invalid");
8680 return Plan;
8681}
8682
8683VPlanPtr LoopVectorizationPlanner::tryToBuildVPlan(VFRange &Range) {
8684 // Outer loop handling: They may require CFG and instruction level
8685 // transformations before even evaluating whether vectorization is profitable.
8686 // Since we cannot modify the incoming IR, we need to build VPlan upfront in
8687 // the vectorization pipeline.
8688 assert(!OrigLoop->isInnermost());
8689 assert(EnableVPlanNativePath && "VPlan-native path is not enabled.");
8690
8691 auto Plan = VPlanTransforms::buildVPlan0(
8692 OrigLoop, *LI, Legal->getWidestInductionType(),
8693 getDebugLocFromInstOrOperands(Legal->getPrimaryInduction()), PSE);
8695 /*HasUncountableExit*/ false);
8696 VPlanTransforms::addMiddleCheck(*Plan, /*RequiresScalarEpilogue*/ true,
8697 /*TailFolded*/ false);
8698
8700
8701 for (ElementCount VF : Range)
8702 Plan->addVF(VF);
8703
8705 *Plan,
8706 [this](PHINode *P) {
8707 return Legal->getIntOrFpInductionDescriptor(P);
8708 },
8709 *TLI))
8710 return nullptr;
8711
8712 // TODO: IVEndValues are not used yet in the native path, to optimize exit
8713 // values.
8714 // TODO: We can't call runPass on the transform yet, due to verifier
8715 // failures.
8716 DenseMap<VPValue *, VPValue *> IVEndValues;
8717 VPlanTransforms::updateScalarResumePhis(*Plan, IVEndValues);
8718
8719 assert(verifyVPlanIsValid(*Plan) && "VPlan is invalid");
8720 return Plan;
8721}
8722
8723// Adjust the recipes for reductions. For in-loop reductions the chain of
8724// instructions leading from the loop exit instr to the phi need to be converted
8725// to reductions, with one operand being vector and the other being the scalar
8726// reduction chain. For other reductions, a select is introduced between the phi
8727// and users outside the vector region when folding the tail.
8728//
8729// A ComputeReductionResult recipe is added to the middle block, also for
8730// in-loop reductions which compute their result in-loop, because generating
8731// the subsequent bc.merge.rdx phi is driven by ComputeReductionResult recipes.
8732//
8733// Adjust AnyOf reductions; replace the reduction phi for the selected value
8734// with a boolean reduction phi node to check if the condition is true in any
8735// iteration. The final value is selected by the final ComputeReductionResult.
8736void LoopVectorizationPlanner::adjustRecipesForReductions(
8737 VPlanPtr &Plan, VPRecipeBuilder &RecipeBuilder, ElementCount MinVF) {
8738 using namespace VPlanPatternMatch;
8739 VPTypeAnalysis TypeInfo(*Plan);
8740 VPRegionBlock *VectorLoopRegion = Plan->getVectorLoopRegion();
8741 VPBasicBlock *Header = VectorLoopRegion->getEntryBasicBlock();
8742 VPBasicBlock *MiddleVPBB = Plan->getMiddleBlock();
8744
8745 for (VPRecipeBase &R : Header->phis()) {
8746 auto *PhiR = dyn_cast<VPReductionPHIRecipe>(&R);
8747 if (!PhiR || !PhiR->isInLoop() || (MinVF.isScalar() && !PhiR->isOrdered()))
8748 continue;
8749
8750 RecurKind Kind = PhiR->getRecurrenceKind();
8751 assert(
8754 "AnyOf and FindIV reductions are not allowed for in-loop reductions");
8755
8756 bool IsFPRecurrence =
8758 FastMathFlags FMFs =
8759 IsFPRecurrence ? FastMathFlags::getFast() : FastMathFlags();
8760
8761 // Collect the chain of "link" recipes for the reduction starting at PhiR.
8762 SetVector<VPSingleDefRecipe *> Worklist;
8763 Worklist.insert(PhiR);
8764 for (unsigned I = 0; I != Worklist.size(); ++I) {
8765 VPSingleDefRecipe *Cur = Worklist[I];
8766 for (VPUser *U : Cur->users()) {
8767 auto *UserRecipe = cast<VPSingleDefRecipe>(U);
8768 if (!UserRecipe->getParent()->getEnclosingLoopRegion()) {
8769 assert((UserRecipe->getParent() == MiddleVPBB ||
8770 UserRecipe->getParent() == Plan->getScalarPreheader()) &&
8771 "U must be either in the loop region, the middle block or the "
8772 "scalar preheader.");
8773 continue;
8774 }
8775 Worklist.insert(UserRecipe);
8776 }
8777 }
8778
8779 // Visit operation "Links" along the reduction chain top-down starting from
8780 // the phi until LoopExitValue. We keep track of the previous item
8781 // (PreviousLink) to tell which of the two operands of a Link will remain
8782 // scalar and which will be reduced. For minmax by select(cmp), Link will be
8783 // the select instructions. Blend recipes of in-loop reduction phi's will
8784 // get folded to their non-phi operand, as the reduction recipe handles the
8785 // condition directly.
8786 VPSingleDefRecipe *PreviousLink = PhiR; // Aka Worklist[0].
8787 for (VPSingleDefRecipe *CurrentLink : drop_begin(Worklist)) {
8788 if (auto *Blend = dyn_cast<VPBlendRecipe>(CurrentLink)) {
8789 assert(Blend->getNumIncomingValues() == 2 &&
8790 "Blend must have 2 incoming values");
8791 if (Blend->getIncomingValue(0) == PhiR) {
8792 Blend->replaceAllUsesWith(Blend->getIncomingValue(1));
8793 } else {
8794 assert(Blend->getIncomingValue(1) == PhiR &&
8795 "PhiR must be an operand of the blend");
8796 Blend->replaceAllUsesWith(Blend->getIncomingValue(0));
8797 }
8798 continue;
8799 }
8800
8801 if (IsFPRecurrence) {
8802 FastMathFlags CurFMF =
8803 cast<VPRecipeWithIRFlags>(CurrentLink)->getFastMathFlags();
8804 if (match(CurrentLink, m_Select(m_VPValue(), m_VPValue(), m_VPValue())))
8805 CurFMF |= cast<VPRecipeWithIRFlags>(CurrentLink->getOperand(0))
8806 ->getFastMathFlags();
8807 FMFs &= CurFMF;
8808 }
8809
8810 Instruction *CurrentLinkI = CurrentLink->getUnderlyingInstr();
8811
8812 // Index of the first operand which holds a non-mask vector operand.
8813 unsigned IndexOfFirstOperand;
8814 // Recognize a call to the llvm.fmuladd intrinsic.
8815 bool IsFMulAdd = (Kind == RecurKind::FMulAdd);
8816 VPValue *VecOp;
8817 VPBasicBlock *LinkVPBB = CurrentLink->getParent();
8818 if (IsFMulAdd) {
8819 assert(
8821 "Expected instruction to be a call to the llvm.fmuladd intrinsic");
8822 assert(((MinVF.isScalar() && isa<VPReplicateRecipe>(CurrentLink)) ||
8823 isa<VPWidenIntrinsicRecipe>(CurrentLink)) &&
8824 CurrentLink->getOperand(2) == PreviousLink &&
8825 "expected a call where the previous link is the added operand");
8826
8827 // If the instruction is a call to the llvm.fmuladd intrinsic then we
8828 // need to create an fmul recipe (multiplying the first two operands of
8829 // the fmuladd together) to use as the vector operand for the fadd
8830 // reduction.
8831 VPInstruction *FMulRecipe = new VPInstruction(
8832 Instruction::FMul,
8833 {CurrentLink->getOperand(0), CurrentLink->getOperand(1)},
8834 CurrentLinkI->getFastMathFlags());
8835 LinkVPBB->insert(FMulRecipe, CurrentLink->getIterator());
8836 VecOp = FMulRecipe;
8837 } else if (PhiR->isInLoop() && Kind == RecurKind::AddChainWithSubs &&
8838 match(CurrentLink, m_Sub(m_VPValue(), m_VPValue()))) {
8839 Type *PhiTy = TypeInfo.inferScalarType(PhiR);
8840 auto *Zero = Plan->getConstantInt(PhiTy, 0);
8841 auto *Sub = new VPInstruction(Instruction::Sub,
8842 {Zero, CurrentLink->getOperand(1)}, {},
8843 {}, CurrentLinkI->getDebugLoc());
8844 Sub->setUnderlyingValue(CurrentLinkI);
8845 LinkVPBB->insert(Sub, CurrentLink->getIterator());
8846 VecOp = Sub;
8847 } else {
8849 if (match(CurrentLink, m_Cmp(m_VPValue(), m_VPValue())))
8850 continue;
8851 assert(isa<VPWidenSelectRecipe>(CurrentLink) &&
8852 "must be a select recipe");
8853 IndexOfFirstOperand = 1;
8854 } else {
8855 assert((MinVF.isScalar() || isa<VPWidenRecipe>(CurrentLink)) &&
8856 "Expected to replace a VPWidenSC");
8857 IndexOfFirstOperand = 0;
8858 }
8859 // Note that for non-commutable operands (cmp-selects), the semantics of
8860 // the cmp-select are captured in the recurrence kind.
8861 unsigned VecOpId =
8862 CurrentLink->getOperand(IndexOfFirstOperand) == PreviousLink
8863 ? IndexOfFirstOperand + 1
8864 : IndexOfFirstOperand;
8865 VecOp = CurrentLink->getOperand(VecOpId);
8866 assert(VecOp != PreviousLink &&
8867 CurrentLink->getOperand(CurrentLink->getNumOperands() - 1 -
8868 (VecOpId - IndexOfFirstOperand)) ==
8869 PreviousLink &&
8870 "PreviousLink must be the operand other than VecOp");
8871 }
8872
8873 VPValue *CondOp = nullptr;
8874 if (CM.blockNeedsPredicationForAnyReason(CurrentLinkI->getParent()))
8875 CondOp = RecipeBuilder.getBlockInMask(CurrentLink->getParent());
8876
8877 ReductionStyle Style = getReductionStyle(true, PhiR->isOrdered(), 1);
8878 auto *RedRecipe =
8879 new VPReductionRecipe(Kind, FMFs, CurrentLinkI, PreviousLink, VecOp,
8880 CondOp, Style, CurrentLinkI->getDebugLoc());
8881 // Append the recipe to the end of the VPBasicBlock because we need to
8882 // ensure that it comes after all of it's inputs, including CondOp.
8883 // Delete CurrentLink as it will be invalid if its operand is replaced
8884 // with a reduction defined at the bottom of the block in the next link.
8885 if (LinkVPBB->getNumSuccessors() == 0)
8886 RedRecipe->insertBefore(&*std::prev(std::prev(LinkVPBB->end())));
8887 else
8888 LinkVPBB->appendRecipe(RedRecipe);
8889
8890 CurrentLink->replaceAllUsesWith(RedRecipe);
8891 ToDelete.push_back(CurrentLink);
8892 PreviousLink = RedRecipe;
8893 }
8894 }
8895 VPBasicBlock *LatchVPBB = VectorLoopRegion->getExitingBasicBlock();
8896 Builder.setInsertPoint(&*std::prev(std::prev(LatchVPBB->end())));
8897 VPBasicBlock::iterator IP = MiddleVPBB->getFirstNonPhi();
8898 for (VPRecipeBase &R :
8899 Plan->getVectorLoopRegion()->getEntryBasicBlock()->phis()) {
8900 VPReductionPHIRecipe *PhiR = dyn_cast<VPReductionPHIRecipe>(&R);
8901 if (!PhiR)
8902 continue;
8903
8904 const RecurrenceDescriptor &RdxDesc = Legal->getRecurrenceDescriptor(
8906 Type *PhiTy = TypeInfo.inferScalarType(PhiR);
8907 // If tail is folded by masking, introduce selects between the phi
8908 // and the users outside the vector region of each reduction, at the
8909 // beginning of the dedicated latch block.
8910 auto *OrigExitingVPV = PhiR->getBackedgeValue();
8911 auto *NewExitingVPV = PhiR->getBackedgeValue();
8912 // Don't output selects for partial reductions because they have an output
8913 // with fewer lanes than the VF. So the operands of the select would have
8914 // different numbers of lanes. Partial reductions mask the input instead.
8915 auto *RR = dyn_cast<VPReductionRecipe>(OrigExitingVPV->getDefiningRecipe());
8916 if (!PhiR->isInLoop() && CM.foldTailByMasking() &&
8917 (!RR || !RR->isPartialReduction())) {
8918 VPValue *Cond = RecipeBuilder.getBlockInMask(PhiR->getParent());
8919 std::optional<FastMathFlags> FMFs =
8920 PhiTy->isFloatingPointTy()
8921 ? std::make_optional(RdxDesc.getFastMathFlags())
8922 : std::nullopt;
8923 NewExitingVPV =
8924 Builder.createSelect(Cond, OrigExitingVPV, PhiR, {}, "", FMFs);
8925 OrigExitingVPV->replaceUsesWithIf(NewExitingVPV, [](VPUser &U, unsigned) {
8926 return isa<VPInstruction>(&U) &&
8927 (cast<VPInstruction>(&U)->getOpcode() ==
8929 cast<VPInstruction>(&U)->getOpcode() ==
8931 cast<VPInstruction>(&U)->getOpcode() ==
8933 });
8934 if (CM.usePredicatedReductionSelect())
8935 PhiR->setOperand(1, NewExitingVPV);
8936 }
8937
8938 // We want code in the middle block to appear to execute on the location of
8939 // the scalar loop's latch terminator because: (a) it is all compiler
8940 // generated, (b) these instructions are always executed after evaluating
8941 // the latch conditional branch, and (c) other passes may add new
8942 // predecessors which terminate on this line. This is the easiest way to
8943 // ensure we don't accidentally cause an extra step back into the loop while
8944 // debugging.
8945 DebugLoc ExitDL = OrigLoop->getLoopLatch()->getTerminator()->getDebugLoc();
8946
8947 // TODO: At the moment ComputeReductionResult also drives creation of the
8948 // bc.merge.rdx phi nodes, hence it needs to be created unconditionally here
8949 // even for in-loop reductions, until the reduction resume value handling is
8950 // also modeled in VPlan.
8951 VPInstruction *FinalReductionResult;
8952 VPBuilder::InsertPointGuard Guard(Builder);
8953 Builder.setInsertPoint(MiddleVPBB, IP);
8954 RecurKind RecurrenceKind = PhiR->getRecurrenceKind();
8956 VPValue *Start = PhiR->getStartValue();
8957 VPValue *Sentinel = Plan->getOrAddLiveIn(RdxDesc.getSentinelValue());
8958 FinalReductionResult =
8959 Builder.createNaryOp(VPInstruction::ComputeFindIVResult,
8960 {PhiR, Start, Sentinel, NewExitingVPV}, ExitDL);
8961 } else if (RecurrenceDescriptor::isAnyOfRecurrenceKind(RecurrenceKind)) {
8962 VPValue *Start = PhiR->getStartValue();
8963 FinalReductionResult =
8964 Builder.createNaryOp(VPInstruction::ComputeAnyOfResult,
8965 {PhiR, Start, NewExitingVPV}, ExitDL);
8966 } else {
8967 VPIRFlags Flags =
8969 ? VPIRFlags(RdxDesc.getFastMathFlags())
8970 : VPIRFlags();
8971 FinalReductionResult =
8972 Builder.createNaryOp(VPInstruction::ComputeReductionResult,
8973 {PhiR, NewExitingVPV}, Flags, ExitDL);
8974 }
8975 // If the vector reduction can be performed in a smaller type, we truncate
8976 // then extend the loop exit value to enable InstCombine to evaluate the
8977 // entire expression in the smaller type.
8978 if (MinVF.isVector() && PhiTy != RdxDesc.getRecurrenceType() &&
8980 assert(!PhiR->isInLoop() && "Unexpected truncated inloop reduction!");
8982 "Unexpected truncated min-max recurrence!");
8983 Type *RdxTy = RdxDesc.getRecurrenceType();
8984 VPWidenCastRecipe *Trunc;
8985 Instruction::CastOps ExtendOpc =
8986 RdxDesc.isSigned() ? Instruction::SExt : Instruction::ZExt;
8987 VPWidenCastRecipe *Extnd;
8988 {
8989 VPBuilder::InsertPointGuard Guard(Builder);
8990 Builder.setInsertPoint(
8991 NewExitingVPV->getDefiningRecipe()->getParent(),
8992 std::next(NewExitingVPV->getDefiningRecipe()->getIterator()));
8993 Trunc =
8994 Builder.createWidenCast(Instruction::Trunc, NewExitingVPV, RdxTy);
8995 Extnd = Builder.createWidenCast(ExtendOpc, Trunc, PhiTy);
8996 }
8997 if (PhiR->getOperand(1) == NewExitingVPV)
8998 PhiR->setOperand(1, Extnd->getVPSingleValue());
8999
9000 // Update ComputeReductionResult with the truncated exiting value and
9001 // extend its result.
9002 FinalReductionResult->setOperand(1, Trunc);
9003 FinalReductionResult =
9004 Builder.createScalarCast(ExtendOpc, FinalReductionResult, PhiTy, {});
9005 }
9006
9007 // Update all users outside the vector region. Also replace redundant
9008 // extracts.
9009 for (auto *U : to_vector(OrigExitingVPV->users())) {
9010 auto *Parent = cast<VPRecipeBase>(U)->getParent();
9011 if (FinalReductionResult == U || Parent->getParent())
9012 continue;
9013 U->replaceUsesOfWith(OrigExitingVPV, FinalReductionResult);
9014
9015 // Look through ExtractLastPart.
9017 U = cast<VPInstruction>(U)->getSingleUser();
9018
9021 cast<VPInstruction>(U)->replaceAllUsesWith(FinalReductionResult);
9022 }
9023
9024 // Adjust AnyOf reductions; replace the reduction phi for the selected value
9025 // with a boolean reduction phi node to check if the condition is true in
9026 // any iteration. The final value is selected by the final
9027 // ComputeReductionResult.
9028 if (RecurrenceDescriptor::isAnyOfRecurrenceKind(RecurrenceKind)) {
9029 auto *Select = cast<VPRecipeBase>(*find_if(PhiR->users(), [](VPUser *U) {
9030 return isa<VPWidenSelectRecipe>(U) ||
9031 (isa<VPReplicateRecipe>(U) &&
9032 cast<VPReplicateRecipe>(U)->getUnderlyingInstr()->getOpcode() ==
9033 Instruction::Select);
9034 }));
9035 VPValue *Cmp = Select->getOperand(0);
9036 // If the compare is checking the reduction PHI node, adjust it to check
9037 // the start value.
9038 if (VPRecipeBase *CmpR = Cmp->getDefiningRecipe())
9039 CmpR->replaceUsesOfWith(PhiR, PhiR->getStartValue());
9040 Builder.setInsertPoint(Select);
9041
9042 // If the true value of the select is the reduction phi, the new value is
9043 // selected if the negated condition is true in any iteration.
9044 if (Select->getOperand(1) == PhiR)
9045 Cmp = Builder.createNot(Cmp);
9046 VPValue *Or = Builder.createOr(PhiR, Cmp);
9047 Select->getVPSingleValue()->replaceAllUsesWith(Or);
9048 // Delete Select now that it has invalid types.
9049 ToDelete.push_back(Select);
9050
9051 // Convert the reduction phi to operate on bools.
9052 PhiR->setOperand(0, Plan->getFalse());
9053 continue;
9054 }
9055
9057 RdxDesc.getRecurrenceKind())) {
9058 // Adjust the start value for FindFirstIV/FindLastIV recurrences to use
9059 // the sentinel value after generating the ResumePhi recipe, which uses
9060 // the original start value.
9061 PhiR->setOperand(0, Plan->getOrAddLiveIn(RdxDesc.getSentinelValue()));
9062 }
9063 RecurKind RK = RdxDesc.getRecurrenceKind();
9067 VPBuilder PHBuilder(Plan->getVectorPreheader());
9068 VPValue *Iden = Plan->getOrAddLiveIn(
9069 getRecurrenceIdentity(RK, PhiTy, RdxDesc.getFastMathFlags()));
9070 // If the PHI is used by a partial reduction, set the scale factor.
9071 unsigned ScaleFactor =
9072 RecipeBuilder.getScalingForReduction(RdxDesc.getLoopExitInstr())
9073 .value_or(1);
9074 auto *ScaleFactorVPV = Plan->getConstantInt(32, ScaleFactor);
9075 VPValue *StartV = PHBuilder.createNaryOp(
9077 {PhiR->getStartValue(), Iden, ScaleFactorVPV},
9078 PhiTy->isFloatingPointTy() ? RdxDesc.getFastMathFlags()
9079 : FastMathFlags());
9080 PhiR->setOperand(0, StartV);
9081 }
9082 }
9083 for (VPRecipeBase *R : ToDelete)
9084 R->eraseFromParent();
9085
9087}
9088
9089void LoopVectorizationPlanner::attachRuntimeChecks(
9090 VPlan &Plan, GeneratedRTChecks &RTChecks, bool HasBranchWeights) const {
9091 const auto &[SCEVCheckCond, SCEVCheckBlock] = RTChecks.getSCEVChecks();
9092 if (SCEVCheckBlock && SCEVCheckBlock->hasNPredecessors(0)) {
9093 assert((!CM.OptForSize ||
9094 CM.Hints->getForce() == LoopVectorizeHints::FK_Enabled) &&
9095 "Cannot SCEV check stride or overflow when optimizing for size");
9096 VPlanTransforms::attachCheckBlock(Plan, SCEVCheckCond, SCEVCheckBlock,
9097 HasBranchWeights);
9098 }
9099 const auto &[MemCheckCond, MemCheckBlock] = RTChecks.getMemRuntimeChecks();
9100 if (MemCheckBlock && MemCheckBlock->hasNPredecessors(0)) {
9101 // VPlan-native path does not do any analysis for runtime checks
9102 // currently.
9103 assert((!EnableVPlanNativePath || OrigLoop->isInnermost()) &&
9104 "Runtime checks are not supported for outer loops yet");
9105
9106 if (CM.OptForSize) {
9107 assert(
9108 CM.Hints->getForce() == LoopVectorizeHints::FK_Enabled &&
9109 "Cannot emit memory checks when optimizing for size, unless forced "
9110 "to vectorize.");
9111 ORE->emit([&]() {
9112 return OptimizationRemarkAnalysis(DEBUG_TYPE, "VectorizationCodeSize",
9113 OrigLoop->getStartLoc(),
9114 OrigLoop->getHeader())
9115 << "Code-size may be reduced by not forcing "
9116 "vectorization, or by source-code modifications "
9117 "eliminating the need for runtime checks "
9118 "(e.g., adding 'restrict').";
9119 });
9120 }
9121 VPlanTransforms::attachCheckBlock(Plan, MemCheckCond, MemCheckBlock,
9122 HasBranchWeights);
9123 }
9124}
9125
9127 VPlan &Plan, ElementCount VF, unsigned UF,
9128 ElementCount MinProfitableTripCount) const {
9129 // vscale is not necessarily a power-of-2, which means we cannot guarantee
9130 // an overflow to zero when updating induction variables and so an
9131 // additional overflow check is required before entering the vector loop.
9132 bool IsIndvarOverflowCheckNeededForVF =
9133 VF.isScalable() && !TTI.isVScaleKnownToBeAPowerOfTwo() &&
9134 !isIndvarOverflowCheckKnownFalse(&CM, VF, UF) &&
9135 CM.getTailFoldingStyle() !=
9137 const uint32_t *BranchWeigths =
9138 hasBranchWeightMD(*OrigLoop->getLoopLatch()->getTerminator())
9140 : nullptr;
9142 Plan, VF, UF, MinProfitableTripCount,
9143 CM.requiresScalarEpilogue(VF.isVector()), CM.foldTailByMasking(),
9144 IsIndvarOverflowCheckNeededForVF, OrigLoop, BranchWeigths,
9145 OrigLoop->getLoopPredecessor()->getTerminator()->getDebugLoc(),
9146 *PSE.getSE());
9147}
9148
9150 assert(!State.Lane && "VPDerivedIVRecipe being replicated.");
9151
9152 // Fast-math-flags propagate from the original induction instruction.
9153 IRBuilder<>::FastMathFlagGuard FMFG(State.Builder);
9154 if (FPBinOp)
9155 State.Builder.setFastMathFlags(FPBinOp->getFastMathFlags());
9156
9157 Value *Step = State.get(getStepValue(), VPLane(0));
9158 Value *Index = State.get(getOperand(1), VPLane(0));
9159 Value *DerivedIV = emitTransformedIndex(
9160 State.Builder, Index, getStartValue()->getLiveInIRValue(), Step, Kind,
9162 DerivedIV->setName(Name);
9163 State.set(this, DerivedIV, VPLane(0));
9164}
9165
9166// Determine how to lower the scalar epilogue, which depends on 1) optimising
9167// for minimum code-size, 2) predicate compiler options, 3) loop hints forcing
9168// predication, and 4) a TTI hook that analyses whether the loop is suitable
9169// for predication.
9171 Function *F, Loop *L, LoopVectorizeHints &Hints, bool OptForSize,
9174 // 1) OptSize takes precedence over all other options, i.e. if this is set,
9175 // don't look at hints or options, and don't request a scalar epilogue.
9176 if (F->hasOptSize() ||
9177 (OptForSize && Hints.getForce() != LoopVectorizeHints::FK_Enabled))
9179
9180 // 2) If set, obey the directives
9181 if (PreferPredicateOverEpilogue.getNumOccurrences()) {
9189 };
9190 }
9191
9192 // 3) If set, obey the hints
9193 switch (Hints.getPredicate()) {
9198 };
9199
9200 // 4) if the TTI hook indicates this is profitable, request predication.
9201 TailFoldingInfo TFI(TLI, &LVL, IAI);
9202 if (TTI->preferPredicateOverEpilogue(&TFI))
9204
9206}
9207
9208// Process the loop in the VPlan-native vectorization path. This path builds
9209// VPlan upfront in the vectorization pipeline, which allows to apply
9210// VPlan-to-VPlan transformations from the very beginning without modifying the
9211// input LLVM IR.
9217 std::function<BlockFrequencyInfo &()> GetBFI, bool OptForSize,
9218 LoopVectorizeHints &Hints, LoopVectorizationRequirements &Requirements) {
9219
9221 LLVM_DEBUG(dbgs() << "LV: cannot compute the outer-loop trip count\n");
9222 return false;
9223 }
9224 assert(EnableVPlanNativePath && "VPlan-native path is disabled.");
9225 Function *F = L->getHeader()->getParent();
9226 InterleavedAccessInfo IAI(PSE, L, DT, LI, LVL->getLAI());
9227
9229 getScalarEpilogueLowering(F, L, Hints, OptForSize, TTI, TLI, *LVL, &IAI);
9230
9231 LoopVectorizationCostModel CM(SEL, L, PSE, LI, LVL, *TTI, TLI, DB, AC, ORE,
9232 GetBFI, F, &Hints, IAI, OptForSize);
9233 // Use the planner for outer loop vectorization.
9234 // TODO: CM is not used at this point inside the planner. Turn CM into an
9235 // optional argument if we don't need it in the future.
9236 LoopVectorizationPlanner LVP(L, LI, DT, TLI, *TTI, LVL, CM, IAI, PSE, Hints,
9237 ORE);
9238
9239 // Get user vectorization factor.
9240 ElementCount UserVF = Hints.getWidth();
9241
9243
9244 // Plan how to best vectorize, return the best VF and its cost.
9245 const VectorizationFactor VF = LVP.planInVPlanNativePath(UserVF);
9246
9247 // If we are stress testing VPlan builds, do not attempt to generate vector
9248 // code. Masked vector code generation support will follow soon.
9249 // Also, do not attempt to vectorize if no vector code will be produced.
9251 return false;
9252
9253 VPlan &BestPlan = LVP.getPlanFor(VF.Width);
9254
9255 {
9256 GeneratedRTChecks Checks(PSE, DT, LI, TTI, F->getDataLayout(), CM.CostKind);
9257 InnerLoopVectorizer LB(L, PSE, LI, DT, TTI, AC, VF.Width, /*UF=*/1, &CM,
9258 Checks, BestPlan);
9259 LLVM_DEBUG(dbgs() << "Vectorizing outer loop in \""
9260 << L->getHeader()->getParent()->getName() << "\"\n");
9261 LVP.addMinimumIterationCheck(BestPlan, VF.Width, /*UF=*/1,
9263
9264 LVP.executePlan(VF.Width, /*UF=*/1, BestPlan, LB, DT, false);
9265 }
9266
9267 reportVectorization(ORE, L, VF, 1);
9268
9269 assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()));
9270 return true;
9271}
9272
9273// Emit a remark if there are stores to floats that required a floating point
9274// extension. If the vectorized loop was generated with floating point there
9275// will be a performance penalty from the conversion overhead and the change in
9276// the vector width.
9279 for (BasicBlock *BB : L->getBlocks()) {
9280 for (Instruction &Inst : *BB) {
9281 if (auto *S = dyn_cast<StoreInst>(&Inst)) {
9282 if (S->getValueOperand()->getType()->isFloatTy())
9283 Worklist.push_back(S);
9284 }
9285 }
9286 }
9287
9288 // Traverse the floating point stores upwards searching, for floating point
9289 // conversions.
9292 while (!Worklist.empty()) {
9293 auto *I = Worklist.pop_back_val();
9294 if (!L->contains(I))
9295 continue;
9296 if (!Visited.insert(I).second)
9297 continue;
9298
9299 // Emit a remark if the floating point store required a floating
9300 // point conversion.
9301 // TODO: More work could be done to identify the root cause such as a
9302 // constant or a function return type and point the user to it.
9303 if (isa<FPExtInst>(I) && EmittedRemark.insert(I).second)
9304 ORE->emit([&]() {
9305 return OptimizationRemarkAnalysis(LV_NAME, "VectorMixedPrecision",
9306 I->getDebugLoc(), L->getHeader())
9307 << "floating point conversion changes vector width. "
9308 << "Mixed floating point precision requires an up/down "
9309 << "cast that will negatively impact performance.";
9310 });
9311
9312 for (Use &Op : I->operands())
9313 if (auto *OpI = dyn_cast<Instruction>(Op))
9314 Worklist.push_back(OpI);
9315 }
9316}
9317
9318/// For loops with uncountable early exits, find the cost of doing work when
9319/// exiting the loop early, such as calculating the final exit values of
9320/// variables used outside the loop.
9321/// TODO: This is currently overly pessimistic because the loop may not take
9322/// the early exit, but better to keep this conservative for now. In future,
9323/// it might be possible to relax this by using branch probabilities.
9325 VPlan &Plan, ElementCount VF) {
9326 InstructionCost Cost = 0;
9327 for (auto *ExitVPBB : Plan.getExitBlocks()) {
9328 for (auto *PredVPBB : ExitVPBB->getPredecessors()) {
9329 // If the predecessor is not the middle.block, then it must be the
9330 // vector.early.exit block, which may contain work to calculate the exit
9331 // values of variables used outside the loop.
9332 if (PredVPBB != Plan.getMiddleBlock()) {
9333 LLVM_DEBUG(dbgs() << "Calculating cost of work in exit block "
9334 << PredVPBB->getName() << ":\n");
9335 Cost += PredVPBB->cost(VF, CostCtx);
9336 }
9337 }
9338 }
9339 return Cost;
9340}
9341
9342/// This function determines whether or not it's still profitable to vectorize
9343/// the loop given the extra work we have to do outside of the loop:
9344/// 1. Perform the runtime checks before entering the loop to ensure it's safe
9345/// to vectorize.
9346/// 2. In the case of loops with uncountable early exits, we may have to do
9347/// extra work when exiting the loop early, such as calculating the final
9348/// exit values of variables used outside the loop.
9349/// 3. The middle block, if expected TC <= VF.Width.
9350static bool isOutsideLoopWorkProfitable(GeneratedRTChecks &Checks,
9351 VectorizationFactor &VF, Loop *L,
9353 VPCostContext &CostCtx, VPlan &Plan,
9355 std::optional<unsigned> VScale) {
9356 InstructionCost TotalCost = Checks.getCost();
9357 if (!TotalCost.isValid())
9358 return false;
9359
9360 // Add on the cost of any work required in the vector early exit block, if
9361 // one exists.
9362 TotalCost += calculateEarlyExitCost(CostCtx, Plan, VF.Width);
9363
9364 // If the expected trip count is less than the VF, the vector loop will only
9365 // execute a single iteration. Then the middle block is executed the same
9366 // number of times as the vector region.
9367 // TODO: Extend logic to always account for the cost of the middle block.
9368 auto ExpectedTC = getSmallBestKnownTC(PSE, L);
9369 if (ExpectedTC && ElementCount::isKnownLE(*ExpectedTC, VF.Width))
9370 TotalCost += Plan.getMiddleBlock()->cost(VF.Width, CostCtx);
9371
9372 // When interleaving only scalar and vector cost will be equal, which in turn
9373 // would lead to a divide by 0. Fall back to hard threshold.
9374 if (VF.Width.isScalar()) {
9375 // TODO: Should we rename VectorizeMemoryCheckThreshold?
9376 if (TotalCost > VectorizeMemoryCheckThreshold) {
9377 LLVM_DEBUG(
9378 dbgs()
9379 << "LV: Interleaving only is not profitable due to runtime checks\n");
9380 return false;
9381 }
9382 return true;
9383 }
9384
9385 // The scalar cost should only be 0 when vectorizing with a user specified
9386 // VF/IC. In those cases, runtime checks should always be generated.
9387 uint64_t ScalarC = VF.ScalarCost.getValue();
9388 if (ScalarC == 0)
9389 return true;
9390
9391 // First, compute the minimum iteration count required so that the vector
9392 // loop outperforms the scalar loop.
9393 // The total cost of the scalar loop is
9394 // ScalarC * TC
9395 // where
9396 // * TC is the actual trip count of the loop.
9397 // * ScalarC is the cost of a single scalar iteration.
9398 //
9399 // The total cost of the vector loop is
9400 // RtC + VecC * (TC / VF) + EpiC
9401 // where
9402 // * RtC is the sum of the costs cost of
9403 // - the generated runtime checks
9404 // - performing any additional work in the vector.early.exit block for
9405 // loops with uncountable early exits.
9406 // - the middle block, if ExpectedTC <= VF.Width.
9407 // * VecC is the cost of a single vector iteration.
9408 // * TC is the actual trip count of the loop
9409 // * VF is the vectorization factor
9410 // * EpiCost is the cost of the generated epilogue, including the cost
9411 // of the remaining scalar operations.
9412 //
9413 // Vectorization is profitable once the total vector cost is less than the
9414 // total scalar cost:
9415 // RtC + VecC * (TC / VF) + EpiC < ScalarC * TC
9416 //
9417 // Now we can compute the minimum required trip count TC as
9418 // VF * (RtC + EpiC) / (ScalarC * VF - VecC) < TC
9419 //
9420 // For now we assume the epilogue cost EpiC = 0 for simplicity. Note that
9421 // the computations are performed on doubles, not integers and the result
9422 // is rounded up, hence we get an upper estimate of the TC.
9423 unsigned IntVF = estimateElementCount(VF.Width, VScale);
9424 uint64_t RtC = TotalCost.getValue();
9425 uint64_t Div = ScalarC * IntVF - VF.Cost.getValue();
9426 uint64_t MinTC1 = Div == 0 ? 0 : divideCeil(RtC * IntVF, Div);
9427
9428 // Second, compute a minimum iteration count so that the cost of the
9429 // runtime checks is only a fraction of the total scalar loop cost. This
9430 // adds a loop-dependent bound on the overhead incurred if the runtime
9431 // checks fail. In case the runtime checks fail, the cost is RtC + ScalarC
9432 // * TC. To bound the runtime check to be a fraction 1/X of the scalar
9433 // cost, compute
9434 // RtC < ScalarC * TC * (1 / X) ==> RtC * X / ScalarC < TC
9435 uint64_t MinTC2 = divideCeil(RtC * 10, ScalarC);
9436
9437 // Now pick the larger minimum. If it is not a multiple of VF and a scalar
9438 // epilogue is allowed, choose the next closest multiple of VF. This should
9439 // partly compensate for ignoring the epilogue cost.
9440 uint64_t MinTC = std::max(MinTC1, MinTC2);
9441 if (SEL == CM_ScalarEpilogueAllowed)
9442 MinTC = alignTo(MinTC, IntVF);
9444
9445 LLVM_DEBUG(
9446 dbgs() << "LV: Minimum required TC for runtime checks to be profitable:"
9447 << VF.MinProfitableTripCount << "\n");
9448
9449 // Skip vectorization if the expected trip count is less than the minimum
9450 // required trip count.
9451 if (auto ExpectedTC = getSmallBestKnownTC(PSE, L)) {
9452 if (ElementCount::isKnownLT(*ExpectedTC, VF.MinProfitableTripCount)) {
9453 LLVM_DEBUG(dbgs() << "LV: Vectorization is not beneficial: expected "
9454 "trip count < minimum profitable VF ("
9455 << *ExpectedTC << " < " << VF.MinProfitableTripCount
9456 << ")\n");
9457
9458 return false;
9459 }
9460 }
9461 return true;
9462}
9463
9465 : InterleaveOnlyWhenForced(Opts.InterleaveOnlyWhenForced ||
9467 VectorizeOnlyWhenForced(Opts.VectorizeOnlyWhenForced ||
9469
9470/// Prepare \p MainPlan for vectorizing the main vector loop during epilogue
9471/// vectorization. Remove ResumePhis from \p MainPlan for inductions that
9472/// don't have a corresponding wide induction in \p EpiPlan.
9473static void preparePlanForMainVectorLoop(VPlan &MainPlan, VPlan &EpiPlan) {
9474 // Collect PHI nodes of widened phis in the VPlan for the epilogue. Those
9475 // will need their resume-values computed in the main vector loop. Others
9476 // can be removed from the main VPlan.
9477 SmallPtrSet<PHINode *, 2> EpiWidenedPhis;
9478 for (VPRecipeBase &R :
9481 continue;
9482 EpiWidenedPhis.insert(
9483 cast<PHINode>(R.getVPSingleValue()->getUnderlyingValue()));
9484 }
9485 for (VPRecipeBase &R :
9486 make_early_inc_range(MainPlan.getScalarHeader()->phis())) {
9487 auto *VPIRInst = cast<VPIRPhi>(&R);
9488 if (EpiWidenedPhis.contains(&VPIRInst->getIRPhi()))
9489 continue;
9490 // There is no corresponding wide induction in the epilogue plan that would
9491 // need a resume value. Remove the VPIRInst wrapping the scalar header phi
9492 // together with the corresponding ResumePhi. The resume values for the
9493 // scalar loop will be created during execution of EpiPlan.
9494 VPRecipeBase *ResumePhi = VPIRInst->getOperand(0)->getDefiningRecipe();
9495 VPIRInst->eraseFromParent();
9496 ResumePhi->eraseFromParent();
9497 }
9499
9500 using namespace VPlanPatternMatch;
9501 // When vectorizing the epilogue, FindFirstIV & FindLastIV reductions can
9502 // introduce multiple uses of undef/poison. If the reduction start value may
9503 // be undef or poison it needs to be frozen and the frozen start has to be
9504 // used when computing the reduction result. We also need to use the frozen
9505 // value in the resume phi generated by the main vector loop, as this is also
9506 // used to compute the reduction result after the epilogue vector loop.
9507 auto AddFreezeForFindLastIVReductions = [](VPlan &Plan,
9508 bool UpdateResumePhis) {
9509 VPBuilder Builder(Plan.getEntry());
9510 for (VPRecipeBase &R : *Plan.getMiddleBlock()) {
9511 auto *VPI = dyn_cast<VPInstruction>(&R);
9512 if (!VPI || VPI->getOpcode() != VPInstruction::ComputeFindIVResult)
9513 continue;
9514 VPValue *OrigStart = VPI->getOperand(1);
9516 continue;
9517 VPInstruction *Freeze =
9518 Builder.createNaryOp(Instruction::Freeze, {OrigStart}, {}, "fr");
9519 VPI->setOperand(1, Freeze);
9520 if (UpdateResumePhis)
9521 OrigStart->replaceUsesWithIf(Freeze, [Freeze](VPUser &U, unsigned) {
9522 return Freeze != &U && isa<VPPhi>(&U);
9523 });
9524 }
9525 };
9526 AddFreezeForFindLastIVReductions(MainPlan, true);
9527 AddFreezeForFindLastIVReductions(EpiPlan, false);
9528
9529 VPBasicBlock *MainScalarPH = MainPlan.getScalarPreheader();
9530 VPValue *VectorTC = &MainPlan.getVectorTripCount();
9531 // If there is a suitable resume value for the canonical induction in the
9532 // scalar (which will become vector) epilogue loop, use it and move it to the
9533 // beginning of the scalar preheader. Otherwise create it below.
9534 auto ResumePhiIter =
9535 find_if(MainScalarPH->phis(), [VectorTC](VPRecipeBase &R) {
9536 return match(&R, m_VPInstruction<Instruction::PHI>(m_Specific(VectorTC),
9537 m_ZeroInt()));
9538 });
9539 VPPhi *ResumePhi = nullptr;
9540 if (ResumePhiIter == MainScalarPH->phis().end()) {
9541 VPBuilder ScalarPHBuilder(MainScalarPH, MainScalarPH->begin());
9542 ResumePhi = ScalarPHBuilder.createScalarPhi(
9543 {VectorTC,
9545 {}, "vec.epilog.resume.val");
9546 } else {
9547 ResumePhi = cast<VPPhi>(&*ResumePhiIter);
9548 if (MainScalarPH->begin() == MainScalarPH->end())
9549 ResumePhi->moveBefore(*MainScalarPH, MainScalarPH->end());
9550 else if (&*MainScalarPH->begin() != ResumePhi)
9551 ResumePhi->moveBefore(*MainScalarPH, MainScalarPH->begin());
9552 }
9553 // Add a user to to make sure the resume phi won't get removed.
9554 VPBuilder(MainScalarPH)
9556}
9557
9558/// Prepare \p Plan for vectorizing the epilogue loop. That is, re-use expanded
9559/// SCEVs from \p ExpandedSCEVs and set resume values for header recipes. Some
9560/// reductions require creating new instructions to compute the resume values.
9561/// They are collected in a vector and returned. They must be moved to the
9562/// preheader of the vector epilogue loop, after created by the execution of \p
9563/// Plan.
9565 VPlan &Plan, Loop *L, const SCEV2ValueTy &ExpandedSCEVs,
9567 ScalarEvolution &SE) {
9568 VPRegionBlock *VectorLoop = Plan.getVectorLoopRegion();
9569 VPBasicBlock *Header = VectorLoop->getEntryBasicBlock();
9570 Header->setName("vec.epilog.vector.body");
9571
9572 VPCanonicalIVPHIRecipe *IV = VectorLoop->getCanonicalIV();
9573 // When vectorizing the epilogue loop, the canonical induction needs to be
9574 // adjusted by the value after the main vector loop. Find the resume value
9575 // created during execution of the main VPlan. It must be the first phi in the
9576 // loop preheader. Use the value to increment the canonical IV, and update all
9577 // users in the loop region to use the adjusted value.
9578 // FIXME: Improve modeling for canonical IV start values in the epilogue
9579 // loop.
9580 using namespace llvm::PatternMatch;
9581 PHINode *EPResumeVal = &*L->getLoopPreheader()->phis().begin();
9582 for (Value *Inc : EPResumeVal->incoming_values()) {
9583 if (match(Inc, m_SpecificInt(0)))
9584 continue;
9585 assert(!EPI.VectorTripCount &&
9586 "Must only have a single non-zero incoming value");
9587 EPI.VectorTripCount = Inc;
9588 }
9589 // If we didn't find a non-zero vector trip count, all incoming values
9590 // must be zero, which also means the vector trip count is zero. Pick the
9591 // first zero as vector trip count.
9592 // TODO: We should not choose VF * UF so the main vector loop is known to
9593 // be dead.
9594 if (!EPI.VectorTripCount) {
9595 assert(EPResumeVal->getNumIncomingValues() > 0 &&
9596 all_of(EPResumeVal->incoming_values(),
9597 [](Value *Inc) { return match(Inc, m_SpecificInt(0)); }) &&
9598 "all incoming values must be 0");
9599 EPI.VectorTripCount = EPResumeVal->getOperand(0);
9600 }
9601 VPValue *VPV = Plan.getOrAddLiveIn(EPResumeVal);
9602 assert(all_of(IV->users(),
9603 [](const VPUser *U) {
9604 return isa<VPScalarIVStepsRecipe>(U) ||
9605 isa<VPDerivedIVRecipe>(U) ||
9606 cast<VPRecipeBase>(U)->isScalarCast() ||
9607 cast<VPInstruction>(U)->getOpcode() ==
9608 Instruction::Add;
9609 }) &&
9610 "the canonical IV should only be used by its increment or "
9611 "ScalarIVSteps when resetting the start value");
9612 VPBuilder Builder(Header, Header->getFirstNonPhi());
9613 VPInstruction *Add = Builder.createNaryOp(Instruction::Add, {IV, VPV});
9614 IV->replaceAllUsesWith(Add);
9615 Add->setOperand(0, IV);
9616
9618 SmallVector<Instruction *> InstsToMove;
9619 // Ensure that the start values for all header phi recipes are updated before
9620 // vectorizing the epilogue loop. Skip the canonical IV, which has been
9621 // handled above.
9622 for (VPRecipeBase &R : drop_begin(Header->phis())) {
9623 Value *ResumeV = nullptr;
9624 // TODO: Move setting of resume values to prepareToExecute.
9625 if (auto *ReductionPhi = dyn_cast<VPReductionPHIRecipe>(&R)) {
9626 auto *RdxResult =
9627 cast<VPInstruction>(*find_if(ReductionPhi->users(), [](VPUser *U) {
9628 auto *VPI = dyn_cast<VPInstruction>(U);
9629 return VPI &&
9630 (VPI->getOpcode() == VPInstruction::ComputeAnyOfResult ||
9631 VPI->getOpcode() == VPInstruction::ComputeReductionResult ||
9632 VPI->getOpcode() == VPInstruction::ComputeFindIVResult);
9633 }));
9634 ResumeV = cast<PHINode>(ReductionPhi->getUnderlyingInstr())
9635 ->getIncomingValueForBlock(L->getLoopPreheader());
9636 RecurKind RK = ReductionPhi->getRecurrenceKind();
9638 Value *StartV = RdxResult->getOperand(1)->getLiveInIRValue();
9639 // VPReductionPHIRecipes for AnyOf reductions expect a boolean as
9640 // start value; compare the final value from the main vector loop
9641 // to the start value.
9642 BasicBlock *PBB = cast<Instruction>(ResumeV)->getParent();
9643 IRBuilder<> Builder(PBB, PBB->getFirstNonPHIIt());
9644 ResumeV = Builder.CreateICmpNE(ResumeV, StartV);
9645 if (auto *I = dyn_cast<Instruction>(ResumeV))
9646 InstsToMove.push_back(I);
9648 Value *StartV = getStartValueFromReductionResult(RdxResult);
9649 ToFrozen[StartV] = cast<PHINode>(ResumeV)->getIncomingValueForBlock(
9651
9652 // VPReductionPHIRecipe for FindFirstIV/FindLastIV reductions requires
9653 // an adjustment to the resume value. The resume value is adjusted to
9654 // the sentinel value when the final value from the main vector loop
9655 // equals the start value. This ensures correctness when the start value
9656 // might not be less than the minimum value of a monotonically
9657 // increasing induction variable.
9658 BasicBlock *ResumeBB = cast<Instruction>(ResumeV)->getParent();
9659 IRBuilder<> Builder(ResumeBB, ResumeBB->getFirstNonPHIIt());
9660 Value *Cmp = Builder.CreateICmpEQ(ResumeV, ToFrozen[StartV]);
9661 if (auto *I = dyn_cast<Instruction>(Cmp))
9662 InstsToMove.push_back(I);
9663 Value *Sentinel = RdxResult->getOperand(2)->getLiveInIRValue();
9664 ResumeV = Builder.CreateSelect(Cmp, Sentinel, ResumeV);
9665 if (auto *I = dyn_cast<Instruction>(ResumeV))
9666 InstsToMove.push_back(I);
9667 } else {
9668 VPValue *StartVal = Plan.getOrAddLiveIn(ResumeV);
9669 auto *PhiR = dyn_cast<VPReductionPHIRecipe>(&R);
9670 if (auto *VPI = dyn_cast<VPInstruction>(PhiR->getStartValue())) {
9672 "unexpected start value");
9673 VPI->setOperand(0, StartVal);
9674 continue;
9675 }
9676 }
9677 } else {
9678 // Retrieve the induction resume values for wide inductions from
9679 // their original phi nodes in the scalar loop.
9680 PHINode *IndPhi = cast<VPWidenInductionRecipe>(&R)->getPHINode();
9681 // Hook up to the PHINode generated by a ResumePhi recipe of main
9682 // loop VPlan, which feeds the scalar loop.
9683 ResumeV = IndPhi->getIncomingValueForBlock(L->getLoopPreheader());
9684 }
9685 assert(ResumeV && "Must have a resume value");
9686 VPValue *StartVal = Plan.getOrAddLiveIn(ResumeV);
9687 cast<VPHeaderPHIRecipe>(&R)->setStartValue(StartVal);
9688 }
9689
9690 // For some VPValues in the epilogue plan we must re-use the generated IR
9691 // values from the main plan. Replace them with live-in VPValues.
9692 // TODO: This is a workaround needed for epilogue vectorization and it
9693 // should be removed once induction resume value creation is done
9694 // directly in VPlan.
9695 for (auto &R : make_early_inc_range(*Plan.getEntry())) {
9696 // Re-use frozen values from the main plan for Freeze VPInstructions in the
9697 // epilogue plan. This ensures all users use the same frozen value.
9698 auto *VPI = dyn_cast<VPInstruction>(&R);
9699 if (VPI && VPI->getOpcode() == Instruction::Freeze) {
9701 ToFrozen.lookup(VPI->getOperand(0)->getLiveInIRValue())));
9702 continue;
9703 }
9704
9705 // Re-use the trip count and steps expanded for the main loop, as
9706 // skeleton creation needs it as a value that dominates both the scalar
9707 // and vector epilogue loops
9708 auto *ExpandR = dyn_cast<VPExpandSCEVRecipe>(&R);
9709 if (!ExpandR)
9710 continue;
9711 VPValue *ExpandedVal =
9712 Plan.getOrAddLiveIn(ExpandedSCEVs.lookup(ExpandR->getSCEV()));
9713 ExpandR->replaceAllUsesWith(ExpandedVal);
9714 if (Plan.getTripCount() == ExpandR)
9715 Plan.resetTripCount(ExpandedVal);
9716 ExpandR->eraseFromParent();
9717 }
9718
9719 auto VScale = CM.getVScaleForTuning();
9720 unsigned MainLoopStep =
9721 estimateElementCount(EPI.MainLoopVF * EPI.MainLoopUF, VScale);
9722 unsigned EpilogueLoopStep =
9723 estimateElementCount(EPI.EpilogueVF * EPI.EpilogueUF, VScale);
9725 Plan, EPI.TripCount, EPI.VectorTripCount,
9727 EPI.EpilogueUF, MainLoopStep, EpilogueLoopStep, SE);
9728
9729 return InstsToMove;
9730}
9731
9732// Generate bypass values from the additional bypass block. Note that when the
9733// vectorized epilogue is skipped due to iteration count check, then the
9734// resume value for the induction variable comes from the trip count of the
9735// main vector loop, passed as the second argument.
9737 PHINode *OrigPhi, const InductionDescriptor &II, IRBuilder<> &BypassBuilder,
9738 const SCEV2ValueTy &ExpandedSCEVs, Value *MainVectorTripCount,
9739 Instruction *OldInduction) {
9740 Value *Step = getExpandedStep(II, ExpandedSCEVs);
9741 // For the primary induction the additional bypass end value is known.
9742 // Otherwise it is computed.
9743 Value *EndValueFromAdditionalBypass = MainVectorTripCount;
9744 if (OrigPhi != OldInduction) {
9745 auto *BinOp = II.getInductionBinOp();
9746 // Fast-math-flags propagate from the original induction instruction.
9748 BypassBuilder.setFastMathFlags(BinOp->getFastMathFlags());
9749
9750 // Compute the end value for the additional bypass.
9751 EndValueFromAdditionalBypass =
9752 emitTransformedIndex(BypassBuilder, MainVectorTripCount,
9753 II.getStartValue(), Step, II.getKind(), BinOp);
9754 EndValueFromAdditionalBypass->setName("ind.end");
9755 }
9756 return EndValueFromAdditionalBypass;
9757}
9758
9760 VPlan &BestEpiPlan,
9762 const SCEV2ValueTy &ExpandedSCEVs,
9763 Value *MainVectorTripCount) {
9764 // Fix reduction resume values from the additional bypass block.
9765 BasicBlock *PH = L->getLoopPreheader();
9766 for (auto *Pred : predecessors(PH)) {
9767 for (PHINode &Phi : PH->phis()) {
9768 if (Phi.getBasicBlockIndex(Pred) != -1)
9769 continue;
9770 Phi.addIncoming(Phi.getIncomingValueForBlock(BypassBlock), Pred);
9771 }
9772 }
9773 auto *ScalarPH = cast<VPIRBasicBlock>(BestEpiPlan.getScalarPreheader());
9774 if (ScalarPH->hasPredecessors()) {
9775 // If ScalarPH has predecessors, we may need to update its reduction
9776 // resume values.
9777 for (const auto &[R, IRPhi] :
9778 zip(ScalarPH->phis(), ScalarPH->getIRBasicBlock()->phis())) {
9780 BypassBlock);
9781 }
9782 }
9783
9784 // Fix induction resume values from the additional bypass block.
9785 IRBuilder<> BypassBuilder(BypassBlock, BypassBlock->getFirstInsertionPt());
9786 for (const auto &[IVPhi, II] : LVL.getInductionVars()) {
9787 auto *Inc = cast<PHINode>(IVPhi->getIncomingValueForBlock(PH));
9789 IVPhi, II, BypassBuilder, ExpandedSCEVs, MainVectorTripCount,
9790 LVL.getPrimaryInduction());
9791 // TODO: Directly add as extra operand to the VPResumePHI recipe.
9792 Inc->setIncomingValueForBlock(BypassBlock, V);
9793 }
9794}
9795
9796/// Connect the epilogue vector loop generated for \p EpiPlan to the main vector
9797// loop, after both plans have executed, updating branches from the iteration
9798// and runtime checks of the main loop, as well as updating various phis. \p
9799// InstsToMove contains instructions that need to be moved to the preheader of
9800// the epilogue vector loop.
9802 VPlan &EpiPlan, Loop *L, EpilogueLoopVectorizationInfo &EPI,
9804 DenseMap<const SCEV *, Value *> &ExpandedSCEVs, GeneratedRTChecks &Checks,
9805 ArrayRef<Instruction *> InstsToMove) {
9806 BasicBlock *VecEpilogueIterationCountCheck =
9807 cast<VPIRBasicBlock>(EpiPlan.getEntry())->getIRBasicBlock();
9808
9809 BasicBlock *VecEpiloguePreHeader =
9810 cast<BranchInst>(VecEpilogueIterationCountCheck->getTerminator())
9811 ->getSuccessor(1);
9812 // Adjust the control flow taking the state info from the main loop
9813 // vectorization into account.
9815 "expected this to be saved from the previous pass.");
9816 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
9818 VecEpilogueIterationCountCheck, VecEpiloguePreHeader);
9819
9821 VecEpilogueIterationCountCheck},
9823 VecEpiloguePreHeader}});
9824
9825 BasicBlock *ScalarPH =
9826 cast<VPIRBasicBlock>(EpiPlan.getScalarPreheader())->getIRBasicBlock();
9828 VecEpilogueIterationCountCheck, ScalarPH);
9829 DTU.applyUpdates(
9831 VecEpilogueIterationCountCheck},
9833
9834 // Adjust the terminators of runtime check blocks and phis using them.
9835 BasicBlock *SCEVCheckBlock = Checks.getSCEVChecks().second;
9836 BasicBlock *MemCheckBlock = Checks.getMemRuntimeChecks().second;
9837 if (SCEVCheckBlock) {
9838 SCEVCheckBlock->getTerminator()->replaceUsesOfWith(
9839 VecEpilogueIterationCountCheck, ScalarPH);
9840 DTU.applyUpdates({{DominatorTree::Delete, SCEVCheckBlock,
9841 VecEpilogueIterationCountCheck},
9842 {DominatorTree::Insert, SCEVCheckBlock, ScalarPH}});
9843 }
9844 if (MemCheckBlock) {
9845 MemCheckBlock->getTerminator()->replaceUsesOfWith(
9846 VecEpilogueIterationCountCheck, ScalarPH);
9847 DTU.applyUpdates(
9848 {{DominatorTree::Delete, MemCheckBlock, VecEpilogueIterationCountCheck},
9849 {DominatorTree::Insert, MemCheckBlock, ScalarPH}});
9850 }
9851
9852 // The vec.epilog.iter.check block may contain Phi nodes from inductions
9853 // or reductions which merge control-flow from the latch block and the
9854 // middle block. Update the incoming values here and move the Phi into the
9855 // preheader.
9856 SmallVector<PHINode *, 4> PhisInBlock(
9857 llvm::make_pointer_range(VecEpilogueIterationCountCheck->phis()));
9858
9859 for (PHINode *Phi : PhisInBlock) {
9860 Phi->moveBefore(VecEpiloguePreHeader->getFirstNonPHIIt());
9861 Phi->replaceIncomingBlockWith(
9862 VecEpilogueIterationCountCheck->getSinglePredecessor(),
9863 VecEpilogueIterationCountCheck);
9864
9865 // If the phi doesn't have an incoming value from the
9866 // EpilogueIterationCountCheck, we are done. Otherwise remove the
9867 // incoming value and also those from other check blocks. This is needed
9868 // for reduction phis only.
9869 if (none_of(Phi->blocks(), [&](BasicBlock *IncB) {
9870 return EPI.EpilogueIterationCountCheck == IncB;
9871 }))
9872 continue;
9873 Phi->removeIncomingValue(EPI.EpilogueIterationCountCheck);
9874 if (SCEVCheckBlock)
9875 Phi->removeIncomingValue(SCEVCheckBlock);
9876 if (MemCheckBlock)
9877 Phi->removeIncomingValue(MemCheckBlock);
9878 }
9879
9880 auto IP = VecEpiloguePreHeader->getFirstNonPHIIt();
9881 for (auto *I : InstsToMove)
9882 I->moveBefore(IP);
9883
9884 // VecEpilogueIterationCountCheck conditionally skips over the epilogue loop
9885 // after executing the main loop. We need to update the resume values of
9886 // inductions and reductions during epilogue vectorization.
9887 fixScalarResumeValuesFromBypass(VecEpilogueIterationCountCheck, L, EpiPlan,
9888 LVL, ExpandedSCEVs, EPI.VectorTripCount);
9889}
9890
9892 assert((EnableVPlanNativePath || L->isInnermost()) &&
9893 "VPlan-native path is not enabled. Only process inner loops.");
9894
9895 LLVM_DEBUG(dbgs() << "\nLV: Checking a loop in '"
9896 << L->getHeader()->getParent()->getName() << "' from "
9897 << L->getLocStr() << "\n");
9898
9899 LoopVectorizeHints Hints(L, InterleaveOnlyWhenForced, *ORE, TTI);
9900
9901 LLVM_DEBUG(
9902 dbgs() << "LV: Loop hints:"
9903 << " force="
9905 ? "disabled"
9907 ? "enabled"
9908 : "?"))
9909 << " width=" << Hints.getWidth()
9910 << " interleave=" << Hints.getInterleave() << "\n");
9911
9912 // Function containing loop
9913 Function *F = L->getHeader()->getParent();
9914
9915 // Looking at the diagnostic output is the only way to determine if a loop
9916 // was vectorized (other than looking at the IR or machine code), so it
9917 // is important to generate an optimization remark for each loop. Most of
9918 // these messages are generated as OptimizationRemarkAnalysis. Remarks
9919 // generated as OptimizationRemark and OptimizationRemarkMissed are
9920 // less verbose reporting vectorized loops and unvectorized loops that may
9921 // benefit from vectorization, respectively.
9922
9923 if (!Hints.allowVectorization(F, L, VectorizeOnlyWhenForced)) {
9924 LLVM_DEBUG(dbgs() << "LV: Loop hints prevent vectorization.\n");
9925 return false;
9926 }
9927
9928 PredicatedScalarEvolution PSE(*SE, *L);
9929
9930 // Query this against the original loop and save it here because the profile
9931 // of the original loop header may change as the transformation happens.
9932 bool OptForSize = llvm::shouldOptimizeForSize(
9933 L->getHeader(), PSI,
9934 PSI && PSI->hasProfileSummary() ? &GetBFI() : nullptr,
9936
9937 // Check if it is legal to vectorize the loop.
9938 LoopVectorizationRequirements Requirements;
9939 LoopVectorizationLegality LVL(L, PSE, DT, TTI, TLI, F, *LAIs, LI, ORE,
9940 &Requirements, &Hints, DB, AC,
9941 /*AllowRuntimeSCEVChecks=*/!OptForSize, AA);
9943 LLVM_DEBUG(dbgs() << "LV: Not vectorizing: Cannot prove legality.\n");
9944 Hints.emitRemarkWithHints();
9945 return false;
9946 }
9947
9949 reportVectorizationFailure("Auto-vectorization of loops with uncountable "
9950 "early exit is not enabled",
9951 "UncountableEarlyExitLoopsDisabled", ORE, L);
9952 return false;
9953 }
9954
9955 if (!LVL.getPotentiallyFaultingLoads().empty()) {
9956 reportVectorizationFailure("Auto-vectorization of loops with potentially "
9957 "faulting load is not supported",
9958 "PotentiallyFaultingLoadsNotSupported", ORE, L);
9959 return false;
9960 }
9961
9962 // Entrance to the VPlan-native vectorization path. Outer loops are processed
9963 // here. They may require CFG and instruction level transformations before
9964 // even evaluating whether vectorization is profitable. Since we cannot modify
9965 // the incoming IR, we need to build VPlan upfront in the vectorization
9966 // pipeline.
9967 if (!L->isInnermost())
9968 return processLoopInVPlanNativePath(L, PSE, LI, DT, &LVL, TTI, TLI, DB, AC,
9969 ORE, GetBFI, OptForSize, Hints,
9970 Requirements);
9971
9972 assert(L->isInnermost() && "Inner loop expected.");
9973
9974 InterleavedAccessInfo IAI(PSE, L, DT, LI, LVL.getLAI());
9975 bool UseInterleaved = TTI->enableInterleavedAccessVectorization();
9976
9977 // If an override option has been passed in for interleaved accesses, use it.
9978 if (EnableInterleavedMemAccesses.getNumOccurrences() > 0)
9979 UseInterleaved = EnableInterleavedMemAccesses;
9980
9981 // Analyze interleaved memory accesses.
9982 if (UseInterleaved)
9984
9985 if (LVL.hasUncountableEarlyExit()) {
9986 BasicBlock *LoopLatch = L->getLoopLatch();
9987 if (IAI.requiresScalarEpilogue() ||
9989 [LoopLatch](BasicBlock *BB) { return BB != LoopLatch; })) {
9990 reportVectorizationFailure("Auto-vectorization of early exit loops "
9991 "requiring a scalar epilogue is unsupported",
9992 "UncountableEarlyExitUnsupported", ORE, L);
9993 return false;
9994 }
9995 }
9996
9997 // Check the function attributes and profiles to find out if this function
9998 // should be optimized for size.
10000 getScalarEpilogueLowering(F, L, Hints, OptForSize, TTI, TLI, LVL, &IAI);
10001
10002 // Check the loop for a trip count threshold: vectorize loops with a tiny trip
10003 // count by optimizing for size, to minimize overheads.
10004 auto ExpectedTC = getSmallBestKnownTC(PSE, L);
10005 if (ExpectedTC && ExpectedTC->isFixed() &&
10006 ExpectedTC->getFixedValue() < TinyTripCountVectorThreshold) {
10007 LLVM_DEBUG(dbgs() << "LV: Found a loop with a very small trip count. "
10008 << "This loop is worth vectorizing only if no scalar "
10009 << "iteration overheads are incurred.");
10011 LLVM_DEBUG(dbgs() << " But vectorizing was explicitly forced.\n");
10012 else {
10013 LLVM_DEBUG(dbgs() << "\n");
10014 // Predicate tail-folded loops are efficient even when the loop
10015 // iteration count is low. However, setting the epilogue policy to
10016 // `CM_ScalarEpilogueNotAllowedLowTripLoop` prevents vectorizing loops
10017 // with runtime checks. It's more effective to let
10018 // `isOutsideLoopWorkProfitable` determine if vectorization is
10019 // beneficial for the loop.
10022 }
10023 }
10024
10025 // Check the function attributes to see if implicit floats or vectors are
10026 // allowed.
10027 if (F->hasFnAttribute(Attribute::NoImplicitFloat)) {
10029 "Can't vectorize when the NoImplicitFloat attribute is used",
10030 "loop not vectorized due to NoImplicitFloat attribute",
10031 "NoImplicitFloat", ORE, L);
10032 Hints.emitRemarkWithHints();
10033 return false;
10034 }
10035
10036 // Check if the target supports potentially unsafe FP vectorization.
10037 // FIXME: Add a check for the type of safety issue (denormal, signaling)
10038 // for the target we're vectorizing for, to make sure none of the
10039 // additional fp-math flags can help.
10040 if (Hints.isPotentiallyUnsafe() &&
10041 TTI->isFPVectorizationPotentiallyUnsafe()) {
10043 "Potentially unsafe FP op prevents vectorization",
10044 "loop not vectorized due to unsafe FP support.",
10045 "UnsafeFP", ORE, L);
10046 Hints.emitRemarkWithHints();
10047 return false;
10048 }
10049
10050 bool AllowOrderedReductions;
10051 // If the flag is set, use that instead and override the TTI behaviour.
10052 if (ForceOrderedReductions.getNumOccurrences() > 0)
10053 AllowOrderedReductions = ForceOrderedReductions;
10054 else
10055 AllowOrderedReductions = TTI->enableOrderedReductions();
10056 if (!LVL.canVectorizeFPMath(AllowOrderedReductions)) {
10057 ORE->emit([&]() {
10058 auto *ExactFPMathInst = Requirements.getExactFPInst();
10059 return OptimizationRemarkAnalysisFPCommute(DEBUG_TYPE, "CantReorderFPOps",
10060 ExactFPMathInst->getDebugLoc(),
10061 ExactFPMathInst->getParent())
10062 << "loop not vectorized: cannot prove it is safe to reorder "
10063 "floating-point operations";
10064 });
10065 LLVM_DEBUG(dbgs() << "LV: loop not vectorized: cannot prove it is safe to "
10066 "reorder floating-point operations\n");
10067 Hints.emitRemarkWithHints();
10068 return false;
10069 }
10070
10071 // Use the cost model.
10072 LoopVectorizationCostModel CM(SEL, L, PSE, LI, &LVL, *TTI, TLI, DB, AC, ORE,
10073 GetBFI, F, &Hints, IAI, OptForSize);
10074 // Use the planner for vectorization.
10075 LoopVectorizationPlanner LVP(L, LI, DT, TLI, *TTI, &LVL, CM, IAI, PSE, Hints,
10076 ORE);
10077
10078 // Get user vectorization factor and interleave count.
10079 ElementCount UserVF = Hints.getWidth();
10080 unsigned UserIC = Hints.getInterleave();
10081 if (UserIC > 1 && !LVL.isSafeForAnyVectorWidth())
10082 UserIC = 1;
10083
10084 // Plan how to best vectorize.
10085 LVP.plan(UserVF, UserIC);
10087 unsigned IC = 1;
10088
10089 if (ORE->allowExtraAnalysis(LV_NAME))
10091
10092 GeneratedRTChecks Checks(PSE, DT, LI, TTI, F->getDataLayout(), CM.CostKind);
10093 if (LVP.hasPlanWithVF(VF.Width)) {
10094 // Select the interleave count.
10095 IC = LVP.selectInterleaveCount(LVP.getPlanFor(VF.Width), VF.Width, VF.Cost);
10096
10097 unsigned SelectedIC = std::max(IC, UserIC);
10098 // Optimistically generate runtime checks if they are needed. Drop them if
10099 // they turn out to not be profitable.
10100 if (VF.Width.isVector() || SelectedIC > 1) {
10101 Checks.create(L, *LVL.getLAI(), PSE.getPredicate(), VF.Width, SelectedIC);
10102
10103 // Bail out early if either the SCEV or memory runtime checks are known to
10104 // fail. In that case, the vector loop would never execute.
10105 using namespace llvm::PatternMatch;
10106 if (Checks.getSCEVChecks().first &&
10107 match(Checks.getSCEVChecks().first, m_One()))
10108 return false;
10109 if (Checks.getMemRuntimeChecks().first &&
10110 match(Checks.getMemRuntimeChecks().first, m_One()))
10111 return false;
10112 }
10113
10114 // Check if it is profitable to vectorize with runtime checks.
10115 bool ForceVectorization =
10117 VPCostContext CostCtx(CM.TTI, *CM.TLI, LVP.getPlanFor(VF.Width), CM,
10118 CM.CostKind, *CM.PSE.getSE(), L);
10119 if (!ForceVectorization &&
10120 !isOutsideLoopWorkProfitable(Checks, VF, L, PSE, CostCtx,
10121 LVP.getPlanFor(VF.Width), SEL,
10122 CM.getVScaleForTuning())) {
10123 ORE->emit([&]() {
10125 DEBUG_TYPE, "CantReorderMemOps", L->getStartLoc(),
10126 L->getHeader())
10127 << "loop not vectorized: cannot prove it is safe to reorder "
10128 "memory operations";
10129 });
10130 LLVM_DEBUG(dbgs() << "LV: Too many memory checks needed.\n");
10131 Hints.emitRemarkWithHints();
10132 return false;
10133 }
10134 }
10135
10136 // Identify the diagnostic messages that should be produced.
10137 std::pair<StringRef, std::string> VecDiagMsg, IntDiagMsg;
10138 bool VectorizeLoop = true, InterleaveLoop = true;
10139 if (VF.Width.isScalar()) {
10140 LLVM_DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n");
10141 VecDiagMsg = {
10142 "VectorizationNotBeneficial",
10143 "the cost-model indicates that vectorization is not beneficial"};
10144 VectorizeLoop = false;
10145 }
10146
10147 if (UserIC == 1 && Hints.getInterleave() > 1) {
10149 "UserIC should only be ignored due to unsafe dependencies");
10150 LLVM_DEBUG(dbgs() << "LV: Ignoring user-specified interleave count.\n");
10151 IntDiagMsg = {"InterleavingUnsafe",
10152 "Ignoring user-specified interleave count due to possibly "
10153 "unsafe dependencies in the loop."};
10154 InterleaveLoop = false;
10155 } else if (!LVP.hasPlanWithVF(VF.Width) && UserIC > 1) {
10156 // Tell the user interleaving was avoided up-front, despite being explicitly
10157 // requested.
10158 LLVM_DEBUG(dbgs() << "LV: Ignoring UserIC, because vectorization and "
10159 "interleaving should be avoided up front\n");
10160 IntDiagMsg = {"InterleavingAvoided",
10161 "Ignoring UserIC, because interleaving was avoided up front"};
10162 InterleaveLoop = false;
10163 } else if (IC == 1 && UserIC <= 1) {
10164 // Tell the user interleaving is not beneficial.
10165 LLVM_DEBUG(dbgs() << "LV: Interleaving is not beneficial.\n");
10166 IntDiagMsg = {
10167 "InterleavingNotBeneficial",
10168 "the cost-model indicates that interleaving is not beneficial"};
10169 InterleaveLoop = false;
10170 if (UserIC == 1) {
10171 IntDiagMsg.first = "InterleavingNotBeneficialAndDisabled";
10172 IntDiagMsg.second +=
10173 " and is explicitly disabled or interleave count is set to 1";
10174 }
10175 } else if (IC > 1 && UserIC == 1) {
10176 // Tell the user interleaving is beneficial, but it explicitly disabled.
10177 LLVM_DEBUG(dbgs() << "LV: Interleaving is beneficial but is explicitly "
10178 "disabled.\n");
10179 IntDiagMsg = {"InterleavingBeneficialButDisabled",
10180 "the cost-model indicates that interleaving is beneficial "
10181 "but is explicitly disabled or interleave count is set to 1"};
10182 InterleaveLoop = false;
10183 }
10184
10185 // If there is a histogram in the loop, do not just interleave without
10186 // vectorizing. The order of operations will be incorrect without the
10187 // histogram intrinsics, which are only used for recipes with VF > 1.
10188 if (!VectorizeLoop && InterleaveLoop && LVL.hasHistograms()) {
10189 LLVM_DEBUG(dbgs() << "LV: Not interleaving without vectorization due "
10190 << "to histogram operations.\n");
10191 IntDiagMsg = {
10192 "HistogramPreventsScalarInterleaving",
10193 "Unable to interleave without vectorization due to constraints on "
10194 "the order of histogram operations"};
10195 InterleaveLoop = false;
10196 }
10197
10198 // Override IC if user provided an interleave count.
10199 IC = UserIC > 0 ? UserIC : IC;
10200
10201 // Emit diagnostic messages, if any.
10202 const char *VAPassName = Hints.vectorizeAnalysisPassName();
10203 if (!VectorizeLoop && !InterleaveLoop) {
10204 // Do not vectorize or interleaving the loop.
10205 ORE->emit([&]() {
10206 return OptimizationRemarkMissed(VAPassName, VecDiagMsg.first,
10207 L->getStartLoc(), L->getHeader())
10208 << VecDiagMsg.second;
10209 });
10210 ORE->emit([&]() {
10211 return OptimizationRemarkMissed(LV_NAME, IntDiagMsg.first,
10212 L->getStartLoc(), L->getHeader())
10213 << IntDiagMsg.second;
10214 });
10215 return false;
10216 }
10217
10218 if (!VectorizeLoop && InterleaveLoop) {
10219 LLVM_DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n');
10220 ORE->emit([&]() {
10221 return OptimizationRemarkAnalysis(VAPassName, VecDiagMsg.first,
10222 L->getStartLoc(), L->getHeader())
10223 << VecDiagMsg.second;
10224 });
10225 } else if (VectorizeLoop && !InterleaveLoop) {
10226 LLVM_DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width
10227 << ") in " << L->getLocStr() << '\n');
10228 ORE->emit([&]() {
10229 return OptimizationRemarkAnalysis(LV_NAME, IntDiagMsg.first,
10230 L->getStartLoc(), L->getHeader())
10231 << IntDiagMsg.second;
10232 });
10233 } else if (VectorizeLoop && InterleaveLoop) {
10234 LLVM_DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width
10235 << ") in " << L->getLocStr() << '\n');
10236 LLVM_DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n');
10237 }
10238
10239 // Report the vectorization decision.
10240 if (VF.Width.isScalar()) {
10241 using namespace ore;
10242 assert(IC > 1);
10243 ORE->emit([&]() {
10244 return OptimizationRemark(LV_NAME, "Interleaved", L->getStartLoc(),
10245 L->getHeader())
10246 << "interleaved loop (interleaved count: "
10247 << NV("InterleaveCount", IC) << ")";
10248 });
10249 } else {
10250 // Report the vectorization decision.
10251 reportVectorization(ORE, L, VF, IC);
10252 }
10253 if (ORE->allowExtraAnalysis(LV_NAME))
10255
10256 // If we decided that it is *legal* to interleave or vectorize the loop, then
10257 // do it.
10258
10259 VPlan &BestPlan = LVP.getPlanFor(VF.Width);
10260 // Consider vectorizing the epilogue too if it's profitable.
10261 VectorizationFactor EpilogueVF =
10263 if (EpilogueVF.Width.isVector()) {
10264 std::unique_ptr<VPlan> BestMainPlan(BestPlan.duplicate());
10265
10266 // The first pass vectorizes the main loop and creates a scalar epilogue
10267 // to be vectorized by executing the plan (potentially with a different
10268 // factor) again shortly afterwards.
10269 VPlan &BestEpiPlan = LVP.getPlanFor(EpilogueVF.Width);
10270 BestEpiPlan.getMiddleBlock()->setName("vec.epilog.middle.block");
10271 BestEpiPlan.getVectorPreheader()->setName("vec.epilog.ph");
10272 preparePlanForMainVectorLoop(*BestMainPlan, BestEpiPlan);
10273 EpilogueLoopVectorizationInfo EPI(VF.Width, IC, EpilogueVF.Width, 1,
10274 BestEpiPlan);
10275 EpilogueVectorizerMainLoop MainILV(L, PSE, LI, DT, TTI, AC, EPI, &CM,
10276 Checks, *BestMainPlan);
10277 auto ExpandedSCEVs = LVP.executePlan(EPI.MainLoopVF, EPI.MainLoopUF,
10278 *BestMainPlan, MainILV, DT, false);
10279 ++LoopsVectorized;
10280
10281 // Second pass vectorizes the epilogue and adjusts the control flow
10282 // edges from the first pass.
10283 EpilogueVectorizerEpilogueLoop EpilogILV(L, PSE, LI, DT, TTI, AC, EPI, &CM,
10284 Checks, BestEpiPlan);
10286 BestEpiPlan, L, ExpandedSCEVs, EPI, CM, *PSE.getSE());
10287 LVP.executePlan(EPI.EpilogueVF, EPI.EpilogueUF, BestEpiPlan, EpilogILV, DT,
10288 true);
10289 connectEpilogueVectorLoop(BestEpiPlan, L, EPI, DT, LVL, ExpandedSCEVs,
10290 Checks, InstsToMove);
10291 ++LoopsEpilogueVectorized;
10292 } else {
10293 InnerLoopVectorizer LB(L, PSE, LI, DT, TTI, AC, VF.Width, IC, &CM, Checks,
10294 BestPlan);
10295 // TODO: Move to general VPlan pipeline once epilogue loops are also
10296 // supported.
10299 IC, PSE);
10300 LVP.addMinimumIterationCheck(BestPlan, VF.Width, IC,
10302
10303 LVP.executePlan(VF.Width, IC, BestPlan, LB, DT, false);
10304 ++LoopsVectorized;
10305 }
10306
10307 assert(DT->verify(DominatorTree::VerificationLevel::Fast) &&
10308 "DT not preserved correctly");
10309 assert(!verifyFunction(*F, &dbgs()));
10310
10311 return true;
10312}
10313
10315
10316 // Don't attempt if
10317 // 1. the target claims to have no vector registers, and
10318 // 2. interleaving won't help ILP.
10319 //
10320 // The second condition is necessary because, even if the target has no
10321 // vector registers, loop vectorization may still enable scalar
10322 // interleaving.
10323 if (!TTI->getNumberOfRegisters(TTI->getRegisterClassForType(true)) &&
10324 TTI->getMaxInterleaveFactor(ElementCount::getFixed(1)) < 2)
10325 return LoopVectorizeResult(false, false);
10326
10327 bool Changed = false, CFGChanged = false;
10328
10329 // The vectorizer requires loops to be in simplified form.
10330 // Since simplification may add new inner loops, it has to run before the
10331 // legality and profitability checks. This means running the loop vectorizer
10332 // will simplify all loops, regardless of whether anything end up being
10333 // vectorized.
10334 for (const auto &L : *LI)
10335 Changed |= CFGChanged |=
10336 simplifyLoop(L, DT, LI, SE, AC, nullptr, false /* PreserveLCSSA */);
10337
10338 // Build up a worklist of inner-loops to vectorize. This is necessary as
10339 // the act of vectorizing or partially unrolling a loop creates new loops
10340 // and can invalidate iterators across the loops.
10341 SmallVector<Loop *, 8> Worklist;
10342
10343 for (Loop *L : *LI)
10344 collectSupportedLoops(*L, LI, ORE, Worklist);
10345
10346 LoopsAnalyzed += Worklist.size();
10347
10348 // Now walk the identified inner loops.
10349 while (!Worklist.empty()) {
10350 Loop *L = Worklist.pop_back_val();
10351
10352 // For the inner loops we actually process, form LCSSA to simplify the
10353 // transform.
10354 Changed |= formLCSSARecursively(*L, *DT, LI, SE);
10355
10356 Changed |= CFGChanged |= processLoop(L);
10357
10358 if (Changed) {
10359 LAIs->clear();
10360
10361#ifndef NDEBUG
10362 if (VerifySCEV)
10363 SE->verify();
10364#endif
10365 }
10366 }
10367
10368 // Process each loop nest in the function.
10369 return LoopVectorizeResult(Changed, CFGChanged);
10370}
10371
10374 LI = &AM.getResult<LoopAnalysis>(F);
10375 // There are no loops in the function. Return before computing other
10376 // expensive analyses.
10377 if (LI->empty())
10378 return PreservedAnalyses::all();
10387 AA = &AM.getResult<AAManager>(F);
10388
10389 auto &MAMProxy = AM.getResult<ModuleAnalysisManagerFunctionProxy>(F);
10390 PSI = MAMProxy.getCachedResult<ProfileSummaryAnalysis>(*F.getParent());
10391 GetBFI = [&AM, &F]() -> BlockFrequencyInfo & {
10393 };
10394 LoopVectorizeResult Result = runImpl(F);
10395 if (!Result.MadeAnyChange)
10396 return PreservedAnalyses::all();
10398
10399 if (isAssignmentTrackingEnabled(*F.getParent())) {
10400 for (auto &BB : F)
10402 }
10403
10404 PA.preserve<LoopAnalysis>();
10408
10409 if (Result.MadeCFGChange) {
10410 // Making CFG changes likely means a loop got vectorized. Indicate that
10411 // extra simplification passes should be run.
10412 // TODO: MadeCFGChanges is not a prefect proxy. Extra passes should only
10413 // be run if runtime checks have been added.
10416 } else {
10418 }
10419 return PA;
10420}
10421
10423 raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
10424 static_cast<PassInfoMixin<LoopVectorizePass> *>(this)->printPipeline(
10425 OS, MapClassName2PassName);
10426
10427 OS << '<';
10428 OS << (InterleaveOnlyWhenForced ? "" : "no-") << "interleave-forced-only;";
10429 OS << (VectorizeOnlyWhenForced ? "" : "no-") << "vectorize-forced-only;";
10430 OS << '>';
10431}
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
AMDGPU Register Bank Select
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 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:80
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 VPWidenIntOrFpInductionRecipe * createWidenInductionRecipes(VPInstruction *PhiR, const InductionDescriptor &IndDesc, VPlan &Plan, ScalarEvolution &SE, Loop &OrigLoop)
Creates a VPWidenIntOrFpInductionRecipe for PhiR.
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 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 const SCEV * getAddressAccessSCEV(Value *Ptr, LoopVectorizationLegality *Legal, PredicatedScalarEvolution &PSE, const Loop *TheLoop)
Gets Address Access SCEV after verifying that the access pattern is loop invariant except the inducti...
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:1541
unsigned getActiveBits() const
Compute the number of active bits in the value.
Definition APInt.h:1513
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:528
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:63
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
static FastMathFlags getFast()
Definition FMF.h:50
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:2788
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.
Value * getStartValue() const
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
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
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 ...
bool isBinaryOp() const
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...
LLVM_ABI FastMathFlags getFastMathFlags() const LLVM_READONLY
Convenience function for getting all the fast-math flags, which must be an operator which supports th...
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.
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.
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:1576
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:1627
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:1560
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:1541
void printPlans(raw_ostream &O)
Definition VPlan.cpp:1705
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
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:230
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
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.
unsigned getMinWidthCastToRecurrenceTypeInBits() const
Returns the minimum width used by the recurrence in bits.
TrackingVH< Value > getRecurrenceStartValue() const
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,...
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 bool isSCEVable(Type *Ty) const
Test if values of the given type are analyzable within the SCEV framework.
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:88
TypeSwitch< T, ResultT > & Case(CallableT &&caseFn)
Add a case on the given type.
Definition TypeSwitch.h:97
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:292
LLVM_ABI bool replaceUsesOfWith(Value *From, Value *To)
Replace uses of one Value with another.
Definition User.cpp:24
Value * getOperand(unsigned i) const
Definition User.h:232
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:3966
void appendRecipe(VPRecipeBase *Recipe)
Augment the existing recipes of a VPBasicBlock with an additional Recipe as the last recipe.
Definition VPlan.h:4041
RecipeListTy::iterator iterator
Instruction iterators...
Definition VPlan.h:3993
iterator end()
Definition VPlan.h:4003
iterator begin()
Recipe iterator methods.
Definition VPlan.h:4001
iterator_range< iterator > phis()
Returns an iterator range over the PHI-like recipes in the block.
Definition VPlan.h:4054
InstructionCost cost(ElementCount VF, VPCostContext &Ctx) override
Return the cost of this VPBasicBlock.
Definition VPlan.cpp:763
iterator getFirstNonPhi()
Return the position of the first non-phi node recipe in the block.
Definition VPlan.cpp:216
VPRegionBlock * getEnclosingLoopRegion()
Definition VPlan.cpp:578
VPRecipeBase * getTerminator()
If the block has multiple successors, return the branch recipe terminating the block.
Definition VPlan.cpp:623
void insert(VPRecipeBase *Recipe, iterator InsertPt)
Definition VPlan.h:4032
bool empty() const
Definition VPlan.h:4012
VPBlockBase is the building block of the Hierarchical Control-Flow Graph.
Definition VPlan.h:81
VPRegionBlock * getParent()
Definition VPlan.h:173
const VPBasicBlock * getExitingBasicBlock() const
Definition VPlan.cpp:186
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:161
const VPBasicBlock * getEntryBasicBlock() const
Definition VPlan.cpp:166
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:211
static void insertOnEdge(VPBlockBase *From, VPBlockBase *To, VPBlockBase *BlockPtr)
Inserts BlockPtr on the edge between From and To.
Definition VPlanUtils.h:232
static void connectBlocks(VPBlockBase *From, VPBlockBase *To, unsigned PredIdx=-1u, unsigned SuccIdx=-1u)
Connect VPBlockBases From and To bi-directionally.
Definition VPlanUtils.h:170
static void reassociateBlocks(VPBlockBase *Old, VPBlockBase *New)
Reassociate all the blocks connected to Old so that they now point to New.
Definition VPlanUtils.h:197
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:3547
unsigned getNumDefinedValues() const
Returns the number of values defined by the VPDef.
Definition VPlanValue.h:431
VPValue * getVPSingleValue()
Returns the only VPValue defined by the VPDef.
Definition VPlanValue.h:404
void execute(VPTransformState &State) override
Generate the transformed value of the induction at offset StartValue (1.
VPValue * getStepValue() const
Definition VPlan.h:3766
VPValue * getStartValue() const
Definition VPlan.h:3765
A pure virtual base class for all recipes modeling header phis, including phis for first order recurr...
Definition VPlan.h:2049
virtual VPValue * getBackedgeValue()
Returns the incoming value from the loop backedge.
Definition VPlan.h:2092
VPValue * getStartValue()
Returns the start value of the phi, if one is set.
Definition VPlan.h:2081
A recipe representing a sequence of load -> update -> store as part of a histogram operation.
Definition VPlan.h:1757
A special type of VPBasicBlock that wraps an existing IR basic block.
Definition VPlan.h:4119
Class to record and manage LLVM IR flags.
Definition VPlan.h:609
Helper to manage IR metadata for recipes.
Definition VPlan.h:982
This is a concrete Recipe that models a single VPlan-level instruction.
Definition VPlan.h:1036
@ ComputeAnyOfResult
Compute the final result of a AnyOf reduction with select(cmp(),x,y), where one of (x,...
Definition VPlan.h:1074
@ ResumeForEpilogue
Explicit user for the resume phi of the canonical induction in the main VPlan, used by the epilogue v...
Definition VPlan.h:1130
@ ReductionStartVector
Start vector for reductions with 3 operands: the original start value, the identity value for the red...
Definition VPlan.h:1121
unsigned getOpcode() const
Definition VPlan.h:1182
VPInterleaveRecipe is a recipe for transforming an interleave group of load or stores into one wide l...
Definition VPlan.h:2686
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:1362
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.
VPRecipeBase * tryToCreateWidenRecipe(VPSingleDefRecipe *R, VFRange &Range)
Create and return a widened recipe for R if one can be created within the given VF Range.
VPValue * getBlockInMask(VPBasicBlock *VPBB) const
Returns the entry mask for block VPBB or null if the mask is all-true.
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.
A recipe for handling reduction phis.
Definition VPlan.h:2427
bool isInLoop() const
Returns true if the phi is part of an in-loop reduction.
Definition VPlan.h:2482
RecurKind getRecurrenceKind() const
Returns the recurrence kind of the reduction.
Definition VPlan.h:2476
A recipe to represent inloop, ordered or partial reduction operations.
Definition VPlan.h:2779
VPRegionBlock represents a collection of VPBasicBlocks and VPRegionBlocks which form a Single-Entry-S...
Definition VPlan.h:4154
const VPBlockBase * getEntry() const
Definition VPlan.h:4190
VPCanonicalIVPHIRecipe * getCanonicalIV()
Returns the canonical induction recipe of the region.
Definition VPlan.h:4252
VPReplicateRecipe replicates a given instruction producing multiple scalar copies of the original sca...
Definition VPlan.h:2935
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:595
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:207
operand_range operands()
Definition VPlanValue.h:275
void setOperand(unsigned I, VPValue *New)
Definition VPlanValue.h:251
unsigned getNumOperands() const
Definition VPlanValue.h:245
operand_iterator op_begin()
Definition VPlanValue.h:271
VPValue * getOperand(unsigned N) const
Definition VPlanValue.h:246
void addOperand(VPValue *Operand)
Definition VPlanValue.h:240
This is the base class of the VPlan Def/Use graph, used for modeling the data flow into,...
Definition VPlanValue.h:48
VPRecipeBase * getDefiningRecipe()
Returns the recipe defining this VPValue or nullptr if it is not defined by a recipe,...
Definition VPlan.cpp:131
Value * getLiveInIRValue() const
Returns the underlying IR value, if this VPValue is defined outside the scope of VPlan.
Definition VPlanValue.h:183
Value * getUnderlyingValue() const
Return the underlying Value attached to this VPValue.
Definition VPlanValue.h:85
void replaceAllUsesWith(VPValue *New)
Definition VPlan.cpp:1377
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:1381
user_range users()
Definition VPlanValue.h:134
A recipe to compute a pointer to the last element of each part of a widened memory access for widened...
Definition VPlan.h:1911
VPWidenCastRecipe is a recipe to create vector cast instructions.
Definition VPlan.h:1552
A recipe for handling GEP instructions.
Definition VPlan.h:1848
A recipe for handling phi nodes of integer and floating-point inductions, producing their vector valu...
Definition VPlan.h:2192
A common base class for widening memory operations.
Definition VPlan.h:3246
A recipe for widened phis.
Definition VPlan.h:2326
VPWidenRecipe is a recipe for producing a widened instruction using the opcode and operands of the re...
Definition VPlan.h:1512
VPlan models a candidate for vectorization, encoding various decisions take to produce efficient outp...
Definition VPlan.h:4284
bool hasVF(ElementCount VF) const
Definition VPlan.h:4489
VPBasicBlock * getEntry()
Definition VPlan.h:4377
VPValue & getVectorTripCount()
The vector trip count.
Definition VPlan.h:4468
VPValue & getVF()
Returns the VF of the vector loop region.
Definition VPlan.h:4471
VPValue * getTripCount() const
The trip count of the original loop.
Definition VPlan.h:4439
iterator_range< SmallSetVector< ElementCount, 2 >::iterator > vectorFactors() const
Returns an iterator range over all VFs of the plan.
Definition VPlan.h:4496
bool hasUF(unsigned UF) const
Definition VPlan.h:4507
ArrayRef< VPIRBasicBlock * > getExitBlocks() const
Return an ArrayRef containing VPIRBasicBlocks wrapping the exit blocks of the original scalar loop.
Definition VPlan.h:4429
LLVM_ABI_FOR_TEST VPRegionBlock * getVectorLoopRegion()
Returns the VPRegionBlock of the vector loop.
Definition VPlan.cpp:1011
bool hasEarlyExit() const
Returns true if the VPlan is based on a loop with an early exit.
Definition VPlan.h:4645
InstructionCost cost(ElementCount VF, VPCostContext &Ctx)
Return the cost of this plan.
Definition VPlan.cpp:993
void resetTripCount(VPValue *NewTripCount)
Resets the trip count for the VPlan.
Definition VPlan.h:4453
VPBasicBlock * getMiddleBlock()
Returns the 'middle' block of the plan, that is the block that selects whether to execute the scalar ...
Definition VPlan.h:4402
VPValue * getOrAddLiveIn(Value *V)
Gets the live-in VPValue for V or adds a new live-in (if none exists yet) for V.
Definition VPlan.h:4531
VPBasicBlock * getScalarPreheader() const
Return the VPBasicBlock for the preheader of the scalar loop.
Definition VPlan.h:4420
void execute(VPTransformState *State)
Generate the IR code for this VPlan.
Definition VPlan.cpp:905
VPIRBasicBlock * getScalarHeader() const
Return the VPIRBasicBlock wrapping the header of the scalar loop.
Definition VPlan.h:4425
VPValue * getLiveIn(Value *V) const
Return the live-in VPValue for V, if there is one or nullptr otherwise.
Definition VPlan.h:4568
VPBasicBlock * getVectorPreheader()
Returns the preheader of the vector loop region, if one exists, or null otherwise.
Definition VPlan.h:4382
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:1153
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:390
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:546
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:701
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.
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.
MatchFunctor< Val, Pattern > match_fn(const Pattern &P)
A match functor that can be used as a UnaryPredicate in functional algorithms like all_of.
BinaryOp_match< LHS, RHS, Instruction::Sub > m_Sub(const LHS &L, const RHS &R)
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()
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.
VPIRFlags getFlagsFromIndDesc(const InductionDescriptor &ID)
Extracts and returns NoWrap and FastMath flags from the induction binop in ID.
Definition VPlanUtils.h:85
unsigned getVFScaleFactor(VPRecipeBase *R)
Get the VF scaling factor applied to the recipe's output, if the recipe has one.
const SCEV * getSCEVExprForVPValue(const VPValue *V, ScalarEvolution &SE, const Loop *L=nullptr)
Return the SCEV expression for V.
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI bool simplifyLoop(Loop *L, DominatorTree *DT, LoopInfo *LI, ScalarEvolution *SE, AssumptionCache *AC, MemorySSAUpdater *MSSAU, bool PreserveLCSSA)
Simplify each loop in a loop nest recursively.
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
ReductionStyle getReductionStyle(bool InLoop, bool Ordered, unsigned ScaleFactor)
Definition VPlan.h:2413
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:2484
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:2148
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:1718
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:1799
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.
@ Or
Bitwise or logical OR of integers.
@ FMulAdd
Sum of float products with llvm.fmuladd(a * b + sum).
@ Sub
Subtraction of integers.
@ Add
Sum of integers.
@ AddChainWithSubs
A chain of adds and subs.
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 >
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:363
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)
std::variant< RdxOrdered, RdxInLoop, RdxUnordered > ReductionStyle
Definition VPlan.h:2411
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:69
This reduction is unordered with the partial result scaled down by some factor.
Definition VPlan.h:2408
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 recipe for handling first-order recurrence phis.
Definition VPlan.h:2368
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...
A recipe for widening select instructions.
Definition VPlan.h:1801
static void hoistPredicatedLoads(VPlan &Plan, ScalarEvolution &SE, const Loop *L)
Hoist predicated loads from the same address to the loop entry block, if they are guaranteed to execu...
static void sinkPredicatedStores(VPlan &Plan, ScalarEvolution &SE, const Loop *L)
Sink predicated stores to the same address with complementary predicates (P and NOT P) to an uncondit...
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 materializeBackedgeTakenCount(VPlan &Plan, VPBasicBlock *VectorPH)
Materialize the backedge-taken count to be computed explicitly using VPInstructions.
static void optimizeInductionExitUsers(VPlan &Plan, DenseMap< VPValue *, VPValue * > &EndValues, ScalarEvolution &SE)
If there's a single exit block, optimize its phi recipes that use exiting IV values by feeding them p...
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 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 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 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 addMinimumIterationCheck(VPlan &Plan, ElementCount VF, unsigned UF, ElementCount MinProfitableTripCount, bool RequiresScalarEpilogue, bool TailFolded, bool CheckNeededWithTailFolding, Loop *OrigLoop, const uint32_t *MinItersBypassWeights, DebugLoc DL, ScalarEvolution &SE)
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 LLVM_ABI_FOR_TEST bool tryToConvertVPInstructionsToVPRecipes(VPlan &Plan, function_ref< const InductionDescriptor *(PHINode *)> GetIntOrFpInductionDescriptor, const TargetLibraryInfo &TLI)
Replaces the VPInstructions in Plan with corresponding widen recipes.
static void addExitUsersForFirstOrderRecurrences(VPlan &Plan, VFRange &Range)
Handle users in the exit block for first order reductions in the original exit block.
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 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 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