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 <cstdint>
150#include <functional>
151#include <iterator>
152#include <limits>
153#include <memory>
154#include <string>
155#include <tuple>
156#include <utility>
157
158using namespace llvm;
159using namespace SCEVPatternMatch;
160
161#define LV_NAME "loop-vectorize"
162#define DEBUG_TYPE LV_NAME
163
164#ifndef NDEBUG
165const char VerboseDebug[] = DEBUG_TYPE "-verbose";
166#endif
167
168/// @{
169/// Metadata attribute names
170const char LLVMLoopVectorizeFollowupAll[] = "llvm.loop.vectorize.followup_all";
172 "llvm.loop.vectorize.followup_vectorized";
174 "llvm.loop.vectorize.followup_epilogue";
175/// @}
176
177STATISTIC(LoopsVectorized, "Number of loops vectorized");
178STATISTIC(LoopsAnalyzed, "Number of loops analyzed for vectorization");
179STATISTIC(LoopsEpilogueVectorized, "Number of epilogues vectorized");
180STATISTIC(LoopsEarlyExitVectorized, "Number of early exit loops vectorized");
181
183 "enable-epilogue-vectorization", cl::init(true), cl::Hidden,
184 cl::desc("Enable vectorization of epilogue loops."));
185
187 "epilogue-vectorization-force-VF", cl::init(1), cl::Hidden,
188 cl::desc("When epilogue vectorization is enabled, and a value greater than "
189 "1 is specified, forces the given VF for all applicable epilogue "
190 "loops."));
191
193 "epilogue-vectorization-minimum-VF", cl::Hidden,
194 cl::desc("Only loops with vectorization factor equal to or larger than "
195 "the specified value are considered for epilogue vectorization."));
196
197/// Loops with a known constant trip count below this number are vectorized only
198/// if no scalar iteration overheads are incurred.
200 "vectorizer-min-trip-count", cl::init(16), cl::Hidden,
201 cl::desc("Loops with a constant trip count that is smaller than this "
202 "value are vectorized only if no scalar iteration overheads "
203 "are incurred."));
204
206 "vectorize-memory-check-threshold", cl::init(128), cl::Hidden,
207 cl::desc("The maximum allowed number of runtime memory checks"));
208
209// Option prefer-predicate-over-epilogue indicates that an epilogue is undesired,
210// that predication is preferred, and this lists all options. I.e., the
211// vectorizer will try to fold the tail-loop (epilogue) into the vector body
212// and predicate the instructions accordingly. If tail-folding fails, there are
213// different fallback strategies depending on these values:
215 enum Option {
219 };
220} // namespace PreferPredicateTy
221
223 "prefer-predicate-over-epilogue",
226 cl::desc("Tail-folding and predication preferences over creating a scalar "
227 "epilogue loop."),
229 "scalar-epilogue",
230 "Don't tail-predicate loops, create scalar epilogue"),
232 "predicate-else-scalar-epilogue",
233 "prefer tail-folding, create scalar epilogue if tail "
234 "folding fails."),
236 "predicate-dont-vectorize",
237 "prefers tail-folding, don't attempt vectorization if "
238 "tail-folding fails.")));
239
241 "force-tail-folding-style", cl::desc("Force the tail folding style"),
242 cl::init(TailFoldingStyle::None),
244 clEnumValN(TailFoldingStyle::None, "none", "Disable tail folding"),
246 TailFoldingStyle::Data, "data",
247 "Create lane mask for data only, using active.lane.mask intrinsic"),
248 clEnumValN(TailFoldingStyle::DataWithoutLaneMask,
249 "data-without-lane-mask",
250 "Create lane mask with compare/stepvector"),
251 clEnumValN(TailFoldingStyle::DataAndControlFlow, "data-and-control",
252 "Create lane mask using active.lane.mask intrinsic, and use "
253 "it for both data and control flow"),
254 clEnumValN(TailFoldingStyle::DataAndControlFlowWithoutRuntimeCheck,
255 "data-and-control-without-rt-check",
256 "Similar to data-and-control, but remove the runtime check"),
257 clEnumValN(TailFoldingStyle::DataWithEVL, "data-with-evl",
258 "Use predicated EVL instructions for tail folding. If EVL "
259 "is unsupported, fallback to data-without-lane-mask.")));
260
262 "vectorizer-maximize-bandwidth", cl::init(false), cl::Hidden,
263 cl::desc("Maximize bandwidth when selecting vectorization factor which "
264 "will be determined by the smallest type in loop."));
265
267 "enable-interleaved-mem-accesses", cl::init(false), cl::Hidden,
268 cl::desc("Enable vectorization on interleaved memory accesses in a loop"));
269
270/// An interleave-group may need masking if it resides in a block that needs
271/// predication, or in order to mask away gaps.
273 "enable-masked-interleaved-mem-accesses", cl::init(false), cl::Hidden,
274 cl::desc("Enable vectorization on masked interleaved memory accesses in a loop"));
275
277 "force-target-num-scalar-regs", cl::init(0), cl::Hidden,
278 cl::desc("A flag that overrides the target's number of scalar registers."));
279
281 "force-target-num-vector-regs", cl::init(0), cl::Hidden,
282 cl::desc("A flag that overrides the target's number of vector registers."));
283
285 "force-target-max-scalar-interleave", cl::init(0), cl::Hidden,
286 cl::desc("A flag that overrides the target's max interleave factor for "
287 "scalar loops."));
288
290 "force-target-max-vector-interleave", cl::init(0), cl::Hidden,
291 cl::desc("A flag that overrides the target's max interleave factor for "
292 "vectorized loops."));
293
295 "force-target-instruction-cost", cl::init(0), cl::Hidden,
296 cl::desc("A flag that overrides the target's expected cost for "
297 "an instruction to a single constant value. Mostly "
298 "useful for getting consistent testing."));
299
301 "force-target-supports-scalable-vectors", cl::init(false), cl::Hidden,
302 cl::desc(
303 "Pretend that scalable vectors are supported, even if the target does "
304 "not support them. This flag should only be used for testing."));
305
307 "small-loop-cost", cl::init(20), cl::Hidden,
308 cl::desc(
309 "The cost of a loop that is considered 'small' by the interleaver."));
310
312 "loop-vectorize-with-block-frequency", cl::init(true), cl::Hidden,
313 cl::desc("Enable the use of the block frequency analysis to access PGO "
314 "heuristics minimizing code growth in cold regions and being more "
315 "aggressive in hot regions."));
316
317// Runtime interleave loops for load/store throughput.
319 "enable-loadstore-runtime-interleave", cl::init(true), cl::Hidden,
320 cl::desc(
321 "Enable runtime interleaving until load/store ports are saturated"));
322
323/// The number of stores in a loop that are allowed to need predication.
325 "vectorize-num-stores-pred", cl::init(1), cl::Hidden,
326 cl::desc("Max number of stores to be predicated behind an if."));
327
329 "enable-ind-var-reg-heur", cl::init(true), cl::Hidden,
330 cl::desc("Count the induction variable only once when interleaving"));
331
333 "enable-cond-stores-vec", cl::init(true), cl::Hidden,
334 cl::desc("Enable if predication of stores during vectorization."));
335
337 "max-nested-scalar-reduction-interleave", cl::init(2), cl::Hidden,
338 cl::desc("The maximum interleave count to use when interleaving a scalar "
339 "reduction in a nested loop."));
340
341static cl::opt<bool>
342 PreferInLoopReductions("prefer-inloop-reductions", cl::init(false),
344 cl::desc("Prefer in-loop vector reductions, "
345 "overriding the targets preference."));
346
348 "force-ordered-reductions", cl::init(false), cl::Hidden,
349 cl::desc("Enable the vectorisation of loops with in-order (strict) "
350 "FP reductions"));
351
353 "prefer-predicated-reduction-select", cl::init(false), cl::Hidden,
354 cl::desc(
355 "Prefer predicating a reduction operation over an after loop select."));
356
358 "enable-vplan-native-path", cl::Hidden,
359 cl::desc("Enable VPlan-native vectorization path with "
360 "support for outer loop vectorization."));
361
363 llvm::VerifyEachVPlan("vplan-verify-each",
364#ifdef EXPENSIVE_CHECKS
365 cl::init(true),
366#else
367 cl::init(false),
368#endif
370 cl::desc("Verfiy VPlans after VPlan transforms."));
371
372// This flag enables the stress testing of the VPlan H-CFG construction in the
373// VPlan-native vectorization path. It must be used in conjuction with
374// -enable-vplan-native-path. -vplan-verify-hcfg can also be used to enable the
375// verification of the H-CFGs built.
377 "vplan-build-stress-test", cl::init(false), cl::Hidden,
378 cl::desc(
379 "Build VPlan for every supported loop nest in the function and bail "
380 "out right after the build (stress test the VPlan H-CFG construction "
381 "in the VPlan-native vectorization path)."));
382
384 "interleave-loops", cl::init(true), cl::Hidden,
385 cl::desc("Enable loop interleaving in Loop vectorization passes"));
387 "vectorize-loops", cl::init(true), cl::Hidden,
388 cl::desc("Run the Loop vectorization passes"));
389
391 "force-widen-divrem-via-safe-divisor", cl::Hidden,
392 cl::desc(
393 "Override cost based safe divisor widening for div/rem instructions"));
394
396 "vectorizer-maximize-bandwidth-for-vector-calls", cl::init(true),
398 cl::desc("Try wider VFs if they enable the use of vector variants"));
399
401 "enable-early-exit-vectorization", cl::init(true), cl::Hidden,
402 cl::desc(
403 "Enable vectorization of early exit loops with uncountable exits."));
404
405// Likelyhood of bypassing the vectorized loop because there are zero trips left
406// after prolog. See `emitIterationCountCheck`.
407static constexpr uint32_t MinItersBypassWeights[] = {1, 127};
408
409/// A helper function that returns true if the given type is irregular. The
410/// type is irregular if its allocated size doesn't equal the store size of an
411/// element of the corresponding vector type.
412static bool hasIrregularType(Type *Ty, const DataLayout &DL) {
413 // Determine if an array of N elements of type Ty is "bitcast compatible"
414 // with a <N x Ty> vector.
415 // This is only true if there is no padding between the array elements.
416 return DL.getTypeAllocSizeInBits(Ty) != DL.getTypeSizeInBits(Ty);
417}
418
419/// A version of ScalarEvolution::getSmallConstantTripCount that returns an
420/// ElementCount to include loops whose trip count is a function of vscale.
422 const Loop *L) {
423 if (unsigned ExpectedTC = SE->getSmallConstantTripCount(L))
424 return ElementCount::getFixed(ExpectedTC);
425
426 const SCEV *BTC = SE->getBackedgeTakenCount(L);
427 if (isa<SCEVCouldNotCompute>(BTC))
428 return ElementCount::getFixed(0);
429
430 const SCEV *ExitCount = SE->getTripCountFromExitCount(BTC, BTC->getType(), L);
431 if (isa<SCEVVScale>(ExitCount))
433
434 const APInt *Scale;
435 if (match(ExitCount, m_scev_Mul(m_scev_APInt(Scale), m_SCEVVScale())))
436 if (cast<SCEVMulExpr>(ExitCount)->hasNoUnsignedWrap())
437 if (Scale->getActiveBits() <= 32)
439
440 return ElementCount::getFixed(0);
441}
442
443/// Returns "best known" trip count, which is either a valid positive trip count
444/// or std::nullopt when an estimate cannot be made (including when the trip
445/// count would overflow), for the specified loop \p L as defined by the
446/// following procedure:
447/// 1) Returns exact trip count if it is known.
448/// 2) Returns expected trip count according to profile data if any.
449/// 3) Returns upper bound estimate if known, and if \p CanUseConstantMax.
450/// 4) Returns std::nullopt if all of the above failed.
451static std::optional<ElementCount>
453 bool CanUseConstantMax = true) {
454 // Check if exact trip count is known.
455 if (auto ExpectedTC = getSmallConstantTripCount(PSE.getSE(), L))
456 return ExpectedTC;
457
458 // Check if there is an expected trip count available from profile data.
460 if (auto EstimatedTC = getLoopEstimatedTripCount(L))
461 return ElementCount::getFixed(*EstimatedTC);
462
463 if (!CanUseConstantMax)
464 return std::nullopt;
465
466 // Check if upper bound estimate is known.
467 if (unsigned ExpectedTC = PSE.getSmallConstantMaxTripCount())
468 return ElementCount::getFixed(ExpectedTC);
469
470 return std::nullopt;
471}
472
473namespace {
474// Forward declare GeneratedRTChecks.
475class GeneratedRTChecks;
476
477using SCEV2ValueTy = DenseMap<const SCEV *, Value *>;
478} // namespace
479
480namespace llvm {
481
483
484/// InnerLoopVectorizer vectorizes loops which contain only one basic
485/// block to a specified vectorization factor (VF).
486/// This class performs the widening of scalars into vectors, or multiple
487/// scalars. This class also implements the following features:
488/// * It inserts an epilogue loop for handling loops that don't have iteration
489/// counts that are known to be a multiple of the vectorization factor.
490/// * It handles the code generation for reduction variables.
491/// * Scalarization (implementation using scalars) of un-vectorizable
492/// instructions.
493/// InnerLoopVectorizer does not perform any vectorization-legality
494/// checks, and relies on the caller to check for the different legality
495/// aspects. The InnerLoopVectorizer relies on the
496/// LoopVectorizationLegality class to provide information about the induction
497/// and reduction variables that were found to a given vectorization factor.
499public:
503 ElementCount VecWidth, unsigned UnrollFactor,
505 ProfileSummaryInfo *PSI, GeneratedRTChecks &RTChecks,
506 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
535 /// Return the additional bypass block which targets the scalar loop by
536 /// skipping the epilogue loop after completing the main loop.
539 "Trying to access AdditionalBypassBlock but it has not been set");
541 }
542
543protected:
545
546 /// Create and return a new IR basic block for the scalar preheader whose name
547 /// is prefixed with \p Prefix.
549
550 /// Allow subclasses to override and print debug traces before/after vplan
551 /// execution, when trace information is requested.
552 virtual void printDebugTracesAtStart() {}
553 virtual void printDebugTracesAtEnd() {}
554
555 /// The original loop.
557
558 /// A wrapper around ScalarEvolution used to add runtime SCEV checks. Applies
559 /// dynamic knowledge to simplify SCEV expressions and converts them to a
560 /// more usable form.
562
563 /// Loop Info.
565
566 /// Dominator Tree.
568
569 /// Target Transform Info.
571
572 /// Assumption Cache.
574
575 /// The vectorization SIMD factor to use. Each vector will have this many
576 /// vector elements.
578
579 /// The vectorization unroll factor to use. Each scalar is vectorized to this
580 /// many different vector instructions.
581 unsigned UF;
582
583 /// The builder that we use
585
586 // --- Vectorization state ---
587
588 /// The vector-loop preheader.
590
591 /// Trip count of the original loop.
592 Value *TripCount = nullptr;
593
594 /// The profitablity analysis.
596
597 /// BFI and PSI are used to check for profile guided size optimizations.
600
601 /// Structure to hold information about generated runtime checks, responsible
602 /// for cleaning the checks, if vectorization turns out unprofitable.
603 GeneratedRTChecks &RTChecks;
604
605 /// The additional bypass block which conditionally skips over the epilogue
606 /// loop after executing the main loop. Needed to resume inductions and
607 /// reductions during epilogue vectorization.
609
611
612 /// The vector preheader block of \p Plan, used as target for check blocks
613 /// introduced during skeleton creation.
615};
616
617/// Encapsulate information regarding vectorization of a loop and its epilogue.
618/// This information is meant to be updated and used across two stages of
619/// epilogue vectorization.
622 unsigned MainLoopUF = 0;
624 unsigned EpilogueUF = 0;
627 Value *TripCount = nullptr;
630
632 ElementCount EVF, unsigned EUF,
634 : MainLoopVF(MVF), MainLoopUF(MUF), EpilogueVF(EVF), EpilogueUF(EUF),
636 assert(EUF == 1 &&
637 "A high UF for the epilogue loop is likely not beneficial.");
638 }
639};
640
641/// An extension of the inner loop vectorizer that creates a skeleton for a
642/// vectorized loop that has its epilogue (residual) also vectorized.
643/// The idea is to run the vplan on a given loop twice, firstly to setup the
644/// skeleton and vectorize the main loop, and secondly to complete the skeleton
645/// from the first step and vectorize the epilogue. This is achieved by
646/// deriving two concrete strategy classes from this base class and invoking
647/// them in succession from the loop vectorizer planner.
649public:
655 GeneratedRTChecks &Checks, VPlan &Plan, ElementCount VecWidth,
656 ElementCount MinProfitableTripCount, unsigned UnrollFactor)
657 : InnerLoopVectorizer(OrigLoop, PSE, LI, DT, TTI, AC, VecWidth,
658 UnrollFactor, CM, BFI, PSI, Checks, Plan),
660
661 /// Holds and updates state information required to vectorize the main loop
662 /// and its epilogue in two separate passes. This setup helps us avoid
663 /// regenerating and recomputing runtime safety checks. It also helps us to
664 /// shorten the iteration-count-check path length for the cases where the
665 /// iteration count of the loop is so small that the main vector loop is
666 /// completely skipped.
668
669protected:
671};
672
673/// A specialized derived class of inner loop vectorizer that performs
674/// vectorization of *main* loops in the process of vectorizing loops and their
675/// epilogues.
677public:
685 GeneratedRTChecks &Check, VPlan &Plan)
687 BFI, PSI, Check, Plan, EPI.MainLoopVF,
688 EPI.MainLoopVF, EPI.MainLoopUF) {}
689 /// Implements the interface for creating a vectorized skeleton using the
690 /// *main loop* strategy (i.e., the first pass of VPlan execution).
692
693protected:
694 /// Introduces a new VPIRBasicBlock for \p CheckIRBB to Plan between the
695 /// vector preheader and its predecessor, also connecting the new block to the
696 /// scalar preheader.
697 void introduceCheckBlockInVPlan(BasicBlock *CheckIRBB);
698
699 // Create a check to see if the main vector loop should be executed
701
702 /// Emits an iteration count bypass check once for the main loop (when \p
703 /// ForEpilogue is false) and once for the epilogue loop (when \p
704 /// ForEpilogue is true).
705 BasicBlock *emitIterationCountCheck(BasicBlock *Bypass, bool ForEpilogue);
706 void printDebugTracesAtStart() override;
707 void printDebugTracesAtEnd() override;
708};
709
710// A specialized derived class of inner loop vectorizer that performs
711// vectorization of *epilogue* loops in the process of vectorizing loops and
712// their epilogues.
714public:
720 GeneratedRTChecks &Checks, VPlan &Plan)
722 BFI, PSI, Checks, Plan, EPI.EpilogueVF,
723 EPI.EpilogueVF, EPI.EpilogueUF) {
725 }
726 /// Implements the interface for creating a vectorized skeleton using the
727 /// *epilogue loop* strategy (i.e., the second pass of VPlan execution).
729
730protected:
731 /// Emits an iteration count bypass check after the main vector loop has
732 /// finished to see if there are any iterations left to execute by either
733 /// the vector epilogue or the scalar epilogue.
734 BasicBlock *emitMinimumVectorEpilogueIterCountCheck(
735 BasicBlock *Bypass,
736 BasicBlock *Insert);
737 void printDebugTracesAtStart() override;
738 void printDebugTracesAtEnd() override;
739};
740} // end namespace llvm
741
742/// Look for a meaningful debug location on the instruction or its operands.
744 if (!I)
745 return DebugLoc::getUnknown();
746
747 DebugLoc Empty;
748 if (I->getDebugLoc() != Empty)
749 return I->getDebugLoc();
750
751 for (Use &Op : I->operands()) {
752 if (Instruction *OpInst = dyn_cast<Instruction>(Op))
753 if (OpInst->getDebugLoc() != Empty)
754 return OpInst->getDebugLoc();
755 }
756
757 return I->getDebugLoc();
758}
759
760/// Write a \p DebugMsg about vectorization to the debug output stream. If \p I
761/// is passed, the message relates to that particular instruction.
762#ifndef NDEBUG
763static void debugVectorizationMessage(const StringRef Prefix,
764 const StringRef DebugMsg,
765 Instruction *I) {
766 dbgs() << "LV: " << Prefix << DebugMsg;
767 if (I != nullptr)
768 dbgs() << " " << *I;
769 else
770 dbgs() << '.';
771 dbgs() << '\n';
772}
773#endif
774
775/// Create an analysis remark that explains why vectorization failed
776///
777/// \p PassName is the name of the pass (e.g. can be AlwaysPrint). \p
778/// RemarkName is the identifier for the remark. If \p I is passed it is an
779/// instruction that prevents vectorization. Otherwise \p TheLoop is used for
780/// the location of the remark. If \p DL is passed, use it as debug location for
781/// the remark. \return the remark object that can be streamed to.
783createLVAnalysis(const char *PassName, StringRef RemarkName, Loop *TheLoop,
784 Instruction *I, DebugLoc DL = {}) {
785 BasicBlock *CodeRegion = I ? I->getParent() : TheLoop->getHeader();
786 // If debug location is attached to the instruction, use it. Otherwise if DL
787 // was not provided, use the loop's.
788 if (I && I->getDebugLoc())
789 DL = I->getDebugLoc();
790 else if (!DL)
791 DL = TheLoop->getStartLoc();
792
793 return OptimizationRemarkAnalysis(PassName, RemarkName, DL, CodeRegion);
794}
795
796namespace llvm {
797
798/// Return a value for Step multiplied by VF.
800 int64_t Step) {
801 assert(Ty->isIntegerTy() && "Expected an integer step");
802 ElementCount VFxStep = VF.multiplyCoefficientBy(Step);
803 assert(isPowerOf2_64(VF.getKnownMinValue()) && "must pass power-of-2 VF");
804 if (VF.isScalable() && isPowerOf2_64(Step)) {
805 return B.CreateShl(
806 B.CreateVScale(Ty),
807 ConstantInt::get(Ty, Log2_64(VFxStep.getKnownMinValue())), "", true);
808 }
809 return B.CreateElementCount(Ty, VFxStep);
810}
811
812/// Return the runtime value for VF.
814 return B.CreateElementCount(Ty, VF);
815}
816
818 const StringRef OREMsg, const StringRef ORETag,
819 OptimizationRemarkEmitter *ORE, Loop *TheLoop,
820 Instruction *I) {
821 LLVM_DEBUG(debugVectorizationMessage("Not vectorizing: ", DebugMsg, I));
822 LoopVectorizeHints Hints(TheLoop, true /* doesn't matter */, *ORE);
823 ORE->emit(
824 createLVAnalysis(Hints.vectorizeAnalysisPassName(), ORETag, TheLoop, I)
825 << "loop not vectorized: " << OREMsg);
826}
827
828/// Reports an informative message: print \p Msg for debugging purposes as well
829/// as an optimization remark. Uses either \p I as location of the remark, or
830/// otherwise \p TheLoop. If \p DL is passed, use it as debug location for the
831/// remark. If \p DL is passed, use it as debug location for the remark.
832static void reportVectorizationInfo(const StringRef Msg, const StringRef ORETag,
834 Loop *TheLoop, Instruction *I = nullptr,
835 DebugLoc DL = {}) {
837 LoopVectorizeHints Hints(TheLoop, true /* doesn't matter */, *ORE);
838 ORE->emit(createLVAnalysis(Hints.vectorizeAnalysisPassName(), ORETag, TheLoop,
839 I, DL)
840 << Msg);
841}
842
843/// Report successful vectorization of the loop. In case an outer loop is
844/// vectorized, prepend "outer" to the vectorization remark.
846 VectorizationFactor VF, unsigned IC) {
848 "Vectorizing: ", TheLoop->isInnermost() ? "innermost loop" : "outer loop",
849 nullptr));
850 StringRef LoopType = TheLoop->isInnermost() ? "" : "outer ";
851 ORE->emit([&]() {
852 return OptimizationRemark(LV_NAME, "Vectorized", TheLoop->getStartLoc(),
853 TheLoop->getHeader())
854 << "vectorized " << LoopType << "loop (vectorization width: "
855 << ore::NV("VectorizationFactor", VF.Width)
856 << ", interleaved count: " << ore::NV("InterleaveCount", IC) << ")";
857 });
858}
859
860} // end namespace llvm
861
862namespace llvm {
863
864// Loop vectorization cost-model hints how the scalar epilogue loop should be
865// lowered.
867
868 // The default: allowing scalar epilogues.
870
871 // Vectorization with OptForSize: don't allow epilogues.
873
874 // A special case of vectorisation with OptForSize: loops with a very small
875 // trip count are considered for vectorization under OptForSize, thereby
876 // making sure the cost of their loop body is dominant, free of runtime
877 // guards and scalar iteration overheads.
879
880 // Loop hint predicate indicating an epilogue is undesired.
882
883 // Directive indicating we must either tail fold or not vectorize
886
887/// LoopVectorizationCostModel - estimates the expected speedups due to
888/// vectorization.
889/// In many cases vectorization is not profitable. This can happen because of
890/// a number of reasons. In this class we mainly attempt to predict the
891/// expected speedup/slowdowns due to the supported instruction set. We use the
892/// TargetTransformInfo to query the different backends for the cost of
893/// different operations.
896
897public:
902 const TargetLibraryInfo *TLI, DemandedBits *DB,
903 AssumptionCache *AC,
905 const LoopVectorizeHints *Hints,
908 : ScalarEpilogueStatus(SEL), TheLoop(L), PSE(PSE), LI(LI), Legal(Legal),
909 TTI(TTI), TLI(TLI), DB(DB), AC(AC), ORE(ORE), TheFunction(F),
910 Hints(Hints), InterleaveInfo(IAI) {
912 initializeVScaleForTuning();
914 // Query this against the original loop and save it here because the profile
915 // of the original loop header may change as the transformation happens.
916 OptForSize = llvm::shouldOptimizeForSize(L->getHeader(), PSI, BFI,
917 PGSOQueryType::IRPass);
918 }
919
920 /// \return An upper bound for the vectorization factors (both fixed and
921 /// scalable). If the factors are 0, vectorization and interleaving should be
922 /// avoided up front.
923 FixedScalableVFPair computeMaxVF(ElementCount UserVF, unsigned UserIC);
924
925 /// \return True if runtime checks are required for vectorization, and false
926 /// otherwise.
927 bool runtimeChecksRequired();
928
929 /// Setup cost-based decisions for user vectorization factor.
930 /// \return true if the UserVF is a feasible VF to be chosen.
932 collectNonVectorizedAndSetWideningDecisions(UserVF);
933 return expectedCost(UserVF).isValid();
934 }
935
936 /// \return True if maximizing vector bandwidth is enabled by the target or
937 /// user options, for the given register kind.
938 bool useMaxBandwidth(TargetTransformInfo::RegisterKind RegKind);
939
940 /// \return True if register pressure should be calculated for the given VF.
941 bool shouldCalculateRegPressureForVF(ElementCount VF);
942
943 /// \return The size (in bits) of the smallest and widest types in the code
944 /// that needs to be vectorized. We ignore values that remain scalar such as
945 /// 64 bit loop indices.
946 std::pair<unsigned, unsigned> getSmallestAndWidestTypes();
947
948 /// Memory access instruction may be vectorized in more than one way.
949 /// Form of instruction after vectorization depends on cost.
950 /// This function takes cost-based decisions for Load/Store instructions
951 /// and collects them in a map. This decisions map is used for building
952 /// the lists of loop-uniform and loop-scalar instructions.
953 /// The calculated cost is saved with widening decision in order to
954 /// avoid redundant calculations.
955 void setCostBasedWideningDecision(ElementCount VF);
956
957 /// A call may be vectorized in different ways depending on whether we have
958 /// vectorized variants available and whether the target supports masking.
959 /// This function analyzes all calls in the function at the supplied VF,
960 /// makes a decision based on the costs of available options, and stores that
961 /// decision in a map for use in planning and plan execution.
962 void setVectorizedCallDecision(ElementCount VF);
963
964 /// Collect values we want to ignore in the cost model.
965 void collectValuesToIgnore();
966
967 /// Collect all element types in the loop for which widening is needed.
968 void collectElementTypesForWidening();
969
970 /// Split reductions into those that happen in the loop, and those that happen
971 /// outside. In loop reductions are collected into InLoopReductions.
972 void collectInLoopReductions();
973
974 /// Returns true if we should use strict in-order reductions for the given
975 /// RdxDesc. This is true if the -enable-strict-reductions flag is passed,
976 /// the IsOrdered flag of RdxDesc is set and we do not allow reordering
977 /// of FP operations.
978 bool useOrderedReductions(const RecurrenceDescriptor &RdxDesc) const {
979 return !Hints->allowReordering() && RdxDesc.isOrdered();
980 }
981
982 /// \returns The smallest bitwidth each instruction can be represented with.
983 /// The vector equivalents of these instructions should be truncated to this
984 /// type.
986 return MinBWs;
987 }
988
989 /// \returns True if it is more profitable to scalarize instruction \p I for
990 /// vectorization factor \p VF.
992 assert(VF.isVector() &&
993 "Profitable to scalarize relevant only for VF > 1.");
994 assert(
995 TheLoop->isInnermost() &&
996 "cost-model should not be used for outer loops (in VPlan-native path)");
997
998 auto Scalars = InstsToScalarize.find(VF);
999 assert(Scalars != InstsToScalarize.end() &&
1000 "VF not yet analyzed for scalarization profitability");
1001 return Scalars->second.contains(I);
1002 }
1003
1004 /// Returns true if \p I is known to be uniform after vectorization.
1006 assert(
1007 TheLoop->isInnermost() &&
1008 "cost-model should not be used for outer loops (in VPlan-native path)");
1009 // Pseudo probe needs to be duplicated for each unrolled iteration and
1010 // vector lane so that profiled loop trip count can be accurately
1011 // accumulated instead of being under counted.
1012 if (isa<PseudoProbeInst>(I))
1013 return false;
1014
1015 if (VF.isScalar())
1016 return true;
1017
1018 auto UniformsPerVF = Uniforms.find(VF);
1019 assert(UniformsPerVF != Uniforms.end() &&
1020 "VF not yet analyzed for uniformity");
1021 return UniformsPerVF->second.count(I);
1022 }
1023
1024 /// Returns true if \p I is known to be scalar after vectorization.
1026 assert(
1027 TheLoop->isInnermost() &&
1028 "cost-model should not be used for outer loops (in VPlan-native path)");
1029 if (VF.isScalar())
1030 return true;
1031
1032 auto ScalarsPerVF = Scalars.find(VF);
1033 assert(ScalarsPerVF != Scalars.end() &&
1034 "Scalar values are not calculated for VF");
1035 return ScalarsPerVF->second.count(I);
1036 }
1037
1038 /// \returns True if instruction \p I can be truncated to a smaller bitwidth
1039 /// for vectorization factor \p VF.
1041 return VF.isVector() && MinBWs.contains(I) &&
1042 !isProfitableToScalarize(I, VF) &&
1043 !isScalarAfterVectorization(I, VF);
1044 }
1045
1046 /// Decision that was taken during cost calculation for memory instruction.
1049 CM_Widen, // For consecutive accesses with stride +1.
1050 CM_Widen_Reverse, // For consecutive accesses with stride -1.
1055 CM_IntrinsicCall
1057
1058 /// Save vectorization decision \p W and \p Cost taken by the cost model for
1059 /// instruction \p I and vector width \p VF.
1062 assert(VF.isVector() && "Expected VF >=2");
1063 WideningDecisions[{I, VF}] = {W, Cost};
1064 }
1065
1066 /// Save vectorization decision \p W and \p Cost taken by the cost model for
1067 /// interleaving group \p Grp and vector width \p VF.
1071 assert(VF.isVector() && "Expected VF >=2");
1072 /// Broadcast this decicion to all instructions inside the group.
1073 /// When interleaving, the cost will only be assigned one instruction, the
1074 /// insert position. For other cases, add the appropriate fraction of the
1075 /// total cost to each instruction. This ensures accurate costs are used,
1076 /// even if the insert position instruction is not used.
1077 InstructionCost InsertPosCost = Cost;
1078 InstructionCost OtherMemberCost = 0;
1079 if (W != CM_Interleave)
1080 OtherMemberCost = InsertPosCost = Cost / Grp->getNumMembers();
1081 ;
1082 for (unsigned Idx = 0; Idx < Grp->getFactor(); ++Idx) {
1083 if (auto *I = Grp->getMember(Idx)) {
1084 if (Grp->getInsertPos() == I)
1085 WideningDecisions[{I, VF}] = {W, InsertPosCost};
1086 else
1087 WideningDecisions[{I, VF}] = {W, OtherMemberCost};
1088 }
1089 }
1090 }
1091
1092 /// Return the cost model decision for the given instruction \p I and vector
1093 /// width \p VF. Return CM_Unknown if this instruction did not pass
1094 /// through the cost modeling.
1096 assert(VF.isVector() && "Expected VF to be a vector VF");
1097 assert(
1098 TheLoop->isInnermost() &&
1099 "cost-model should not be used for outer loops (in VPlan-native path)");
1100
1101 std::pair<Instruction *, ElementCount> InstOnVF(I, VF);
1102 auto Itr = WideningDecisions.find(InstOnVF);
1103 if (Itr == WideningDecisions.end())
1104 return CM_Unknown;
1105 return Itr->second.first;
1106 }
1107
1108 /// Return the vectorization cost for the given instruction \p I and vector
1109 /// width \p VF.
1111 assert(VF.isVector() && "Expected VF >=2");
1112 std::pair<Instruction *, ElementCount> InstOnVF(I, VF);
1113 assert(WideningDecisions.contains(InstOnVF) &&
1114 "The cost is not calculated");
1115 return WideningDecisions[InstOnVF].second;
1116 }
1117
1122 std::optional<unsigned> MaskPos;
1124 };
1125
1127 Function *Variant, Intrinsic::ID IID,
1128 std::optional<unsigned> MaskPos,
1130 assert(!VF.isScalar() && "Expected vector VF");
1131 CallWideningDecisions[{CI, VF}] = {Kind, Variant, IID, MaskPos, Cost};
1132 }
1133
1135 ElementCount VF) const {
1136 assert(!VF.isScalar() && "Expected vector VF");
1137 return CallWideningDecisions.at({CI, VF});
1138 }
1139
1140 /// Return True if instruction \p I is an optimizable truncate whose operand
1141 /// is an induction variable. Such a truncate will be removed by adding a new
1142 /// induction variable with the destination type.
1144 // If the instruction is not a truncate, return false.
1145 auto *Trunc = dyn_cast<TruncInst>(I);
1146 if (!Trunc)
1147 return false;
1148
1149 // Get the source and destination types of the truncate.
1150 Type *SrcTy = toVectorTy(Trunc->getSrcTy(), VF);
1151 Type *DestTy = toVectorTy(Trunc->getDestTy(), VF);
1152
1153 // If the truncate is free for the given types, return false. Replacing a
1154 // free truncate with an induction variable would add an induction variable
1155 // update instruction to each iteration of the loop. We exclude from this
1156 // check the primary induction variable since it will need an update
1157 // instruction regardless.
1158 Value *Op = Trunc->getOperand(0);
1159 if (Op != Legal->getPrimaryInduction() && TTI.isTruncateFree(SrcTy, DestTy))
1160 return false;
1161
1162 // If the truncated value is not an induction variable, return false.
1163 return Legal->isInductionPhi(Op);
1164 }
1165
1166 /// Collects the instructions to scalarize for each predicated instruction in
1167 /// the loop.
1168 void collectInstsToScalarize(ElementCount VF);
1169
1170 /// Collect values that will not be widened, including Uniforms, Scalars, and
1171 /// Instructions to Scalarize for the given \p VF.
1172 /// The sets depend on CM decision for Load/Store instructions
1173 /// that may be vectorized as interleave, gather-scatter or scalarized.
1174 /// Also make a decision on what to do about call instructions in the loop
1175 /// at that VF -- scalarize, call a known vector routine, or call a
1176 /// vector intrinsic.
1178 // Do the analysis once.
1179 if (VF.isScalar() || Uniforms.contains(VF))
1180 return;
1181 setCostBasedWideningDecision(VF);
1182 collectLoopUniforms(VF);
1183 setVectorizedCallDecision(VF);
1184 collectLoopScalars(VF);
1185 collectInstsToScalarize(VF);
1186 }
1187
1188 /// Returns true if the target machine supports masked store operation
1189 /// for the given \p DataType and kind of access to \p Ptr.
1190 bool isLegalMaskedStore(Type *DataType, Value *Ptr, Align Alignment,
1191 unsigned AddressSpace) const {
1192 return Legal->isConsecutivePtr(DataType, Ptr) &&
1193 TTI.isLegalMaskedStore(DataType, Alignment, AddressSpace);
1194 }
1195
1196 /// Returns true if the target machine supports masked load operation
1197 /// for the given \p DataType and kind of access to \p Ptr.
1198 bool isLegalMaskedLoad(Type *DataType, Value *Ptr, Align Alignment,
1199 unsigned AddressSpace) const {
1200 return Legal->isConsecutivePtr(DataType, Ptr) &&
1201 TTI.isLegalMaskedLoad(DataType, Alignment, AddressSpace);
1202 }
1203
1204 /// Returns true if the target machine can represent \p V as a masked gather
1205 /// or scatter operation.
1207 bool LI = isa<LoadInst>(V);
1208 bool SI = isa<StoreInst>(V);
1209 if (!LI && !SI)
1210 return false;
1211 auto *Ty = getLoadStoreType(V);
1213 if (VF.isVector())
1214 Ty = VectorType::get(Ty, VF);
1215 return (LI && TTI.isLegalMaskedGather(Ty, Align)) ||
1216 (SI && TTI.isLegalMaskedScatter(Ty, Align));
1217 }
1218
1219 /// Returns true if the target machine supports all of the reduction
1220 /// variables found for the given VF.
1222 return (all_of(Legal->getReductionVars(), [&](auto &Reduction) -> bool {
1223 const RecurrenceDescriptor &RdxDesc = Reduction.second;
1224 return TTI.isLegalToVectorizeReduction(RdxDesc, VF);
1225 }));
1226 }
1227
1228 /// Given costs for both strategies, return true if the scalar predication
1229 /// lowering should be used for div/rem. This incorporates an override
1230 /// option so it is not simply a cost comparison.
1232 InstructionCost SafeDivisorCost) const {
1233 switch (ForceSafeDivisor) {
1234 case cl::BOU_UNSET:
1235 return ScalarCost < SafeDivisorCost;
1236 case cl::BOU_TRUE:
1237 return false;
1238 case cl::BOU_FALSE:
1239 return true;
1240 }
1241 llvm_unreachable("impossible case value");
1242 }
1243
1244 /// Returns true if \p I is an instruction which requires predication and
1245 /// for which our chosen predication strategy is scalarization (i.e. we
1246 /// don't have an alternate strategy such as masking available).
1247 /// \p VF is the vectorization factor that will be used to vectorize \p I.
1248 bool isScalarWithPredication(Instruction *I, ElementCount VF) const;
1249
1250 /// Returns true if \p I is an instruction that needs to be predicated
1251 /// at runtime. The result is independent of the predication mechanism.
1252 /// Superset of instructions that return true for isScalarWithPredication.
1253 bool isPredicatedInst(Instruction *I) const;
1254
1255 /// Return the costs for our two available strategies for lowering a
1256 /// div/rem operation which requires speculating at least one lane.
1257 /// First result is for scalarization (will be invalid for scalable
1258 /// vectors); second is for the safe-divisor strategy.
1259 std::pair<InstructionCost, InstructionCost>
1260 getDivRemSpeculationCost(Instruction *I,
1261 ElementCount VF) const;
1262
1263 /// Returns true if \p I is a memory instruction with consecutive memory
1264 /// access that can be widened.
1265 bool memoryInstructionCanBeWidened(Instruction *I, ElementCount VF);
1266
1267 /// Returns true if \p I is a memory instruction in an interleaved-group
1268 /// of memory accesses that can be vectorized with wide vector loads/stores
1269 /// and shuffles.
1270 bool interleavedAccessCanBeWidened(Instruction *I, ElementCount VF) const;
1271
1272 /// Check if \p Instr belongs to any interleaved access group.
1274 return InterleaveInfo.isInterleaved(Instr);
1275 }
1276
1277 /// Get the interleaved access group that \p Instr belongs to.
1280 return InterleaveInfo.getInterleaveGroup(Instr);
1281 }
1282
1283 /// Returns true if we're required to use a scalar epilogue for at least
1284 /// the final iteration of the original loop.
1285 bool requiresScalarEpilogue(bool IsVectorizing) const {
1286 if (!isScalarEpilogueAllowed()) {
1287 LLVM_DEBUG(dbgs() << "LV: Loop does not require scalar epilogue\n");
1288 return false;
1289 }
1290 // If we might exit from anywhere but the latch and early exit vectorization
1291 // is disabled, we must run the exiting iteration in scalar form.
1292 if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch() &&
1293 !(EnableEarlyExitVectorization && Legal->hasUncountableEarlyExit())) {
1294 LLVM_DEBUG(dbgs() << "LV: Loop requires scalar epilogue: not exiting "
1295 "from latch block\n");
1296 return true;
1297 }
1298 if (IsVectorizing && InterleaveInfo.requiresScalarEpilogue()) {
1299 LLVM_DEBUG(dbgs() << "LV: Loop requires scalar epilogue: "
1300 "interleaved group requires scalar epilogue\n");
1301 return true;
1302 }
1303 LLVM_DEBUG(dbgs() << "LV: Loop does not require scalar epilogue\n");
1304 return false;
1305 }
1306
1307 /// Returns true if a scalar epilogue is not allowed due to optsize or a
1308 /// loop hint annotation.
1310 return ScalarEpilogueStatus == CM_ScalarEpilogueAllowed;
1311 }
1312
1313 /// Returns the TailFoldingStyle that is best for the current loop.
1314 TailFoldingStyle getTailFoldingStyle(bool IVUpdateMayOverflow = true) const {
1315 if (!ChosenTailFoldingStyle)
1316 return TailFoldingStyle::None;
1317 return IVUpdateMayOverflow ? ChosenTailFoldingStyle->first
1318 : ChosenTailFoldingStyle->second;
1319 }
1320
1321 /// Selects and saves TailFoldingStyle for 2 options - if IV update may
1322 /// overflow or not.
1323 /// \param IsScalableVF true if scalable vector factors enabled.
1324 /// \param UserIC User specific interleave count.
1325 void setTailFoldingStyles(bool IsScalableVF, unsigned UserIC) {
1326 assert(!ChosenTailFoldingStyle && "Tail folding must not be selected yet.");
1327 if (!Legal->canFoldTailByMasking()) {
1328 ChosenTailFoldingStyle = {TailFoldingStyle::None, TailFoldingStyle::None};
1329 return;
1330 }
1331
1332 // Default to TTI preference, but allow command line override.
1333 ChosenTailFoldingStyle = {
1334 TTI.getPreferredTailFoldingStyle(/*IVUpdateMayOverflow=*/true),
1335 TTI.getPreferredTailFoldingStyle(/*IVUpdateMayOverflow=*/false)};
1336 if (ForceTailFoldingStyle.getNumOccurrences())
1337 ChosenTailFoldingStyle = {ForceTailFoldingStyle.getValue(),
1338 ForceTailFoldingStyle.getValue()};
1339
1340 if (ChosenTailFoldingStyle->first != TailFoldingStyle::DataWithEVL &&
1341 ChosenTailFoldingStyle->second != TailFoldingStyle::DataWithEVL)
1342 return;
1343 // Override EVL styles if needed.
1344 // FIXME: Investigate opportunity for fixed vector factor.
1345 bool EVLIsLegal = UserIC <= 1 && IsScalableVF &&
1347 if (EVLIsLegal)
1348 return;
1349 // If for some reason EVL mode is unsupported, fallback to a scalar epilogue
1350 // if it's allowed, or DataWithoutLaneMask otherwise.
1351 if (ScalarEpilogueStatus == CM_ScalarEpilogueAllowed ||
1352 ScalarEpilogueStatus == CM_ScalarEpilogueNotNeededUsePredicate)
1353 ChosenTailFoldingStyle = {TailFoldingStyle::None, TailFoldingStyle::None};
1354 else
1355 ChosenTailFoldingStyle = {TailFoldingStyle::DataWithoutLaneMask,
1356 TailFoldingStyle::DataWithoutLaneMask};
1357
1358 LLVM_DEBUG(
1359 dbgs() << "LV: Preference for VP intrinsics indicated. Will "
1360 "not try to generate VP Intrinsics "
1361 << (UserIC > 1
1362 ? "since interleave count specified is greater than 1.\n"
1363 : "due to non-interleaving reasons.\n"));
1364 }
1365
1366 /// Returns true if all loop blocks should be masked to fold tail loop.
1367 bool foldTailByMasking() const {
1368 // TODO: check if it is possible to check for None style independent of
1369 // IVUpdateMayOverflow flag in getTailFoldingStyle.
1370 return getTailFoldingStyle() != TailFoldingStyle::None;
1371 }
1372
1373 /// Return maximum safe number of elements to be processed per vector
1374 /// iteration, which do not prevent store-load forwarding and are safe with
1375 /// regard to the memory dependencies. Required for EVL-based VPlans to
1376 /// correctly calculate AVL (application vector length) as min(remaining AVL,
1377 /// MaxSafeElements).
1378 /// TODO: need to consider adjusting cost model to use this value as a
1379 /// vectorization factor for EVL-based vectorization.
1380 std::optional<unsigned> getMaxSafeElements() const { return MaxSafeElements; }
1381
1382 /// Returns true if the instructions in this block requires predication
1383 /// for any reason, e.g. because tail folding now requires a predicate
1384 /// or because the block in the original loop was predicated.
1386 return foldTailByMasking() || Legal->blockNeedsPredication(BB);
1387 }
1388
1389 /// Returns true if VP intrinsics with explicit vector length support should
1390 /// be generated in the tail folded loop.
1391 bool foldTailWithEVL() const {
1392 return getTailFoldingStyle() == TailFoldingStyle::DataWithEVL;
1393 }
1394
1395 /// Returns true if the Phi is part of an inloop reduction.
1396 bool isInLoopReduction(PHINode *Phi) const {
1397 return InLoopReductions.contains(Phi);
1398 }
1399
1400 /// Returns true if the predicated reduction select should be used to set the
1401 /// incoming value for the reduction phi.
1403 // Force to use predicated reduction select since the EVL of the
1404 // second-to-last iteration might not be VF*UF.
1405 if (foldTailWithEVL())
1406 return true;
1409 }
1410
1411 /// Estimate cost of an intrinsic call instruction CI if it were vectorized
1412 /// with factor VF. Return the cost of the instruction, including
1413 /// scalarization overhead if it's needed.
1414 InstructionCost getVectorIntrinsicCost(CallInst *CI, ElementCount VF) const;
1415
1416 /// Estimate cost of a call instruction CI if it were vectorized with factor
1417 /// VF. Return the cost of the instruction, including scalarization overhead
1418 /// if it's needed.
1419 InstructionCost getVectorCallCost(CallInst *CI, ElementCount VF) const;
1420
1421 /// Invalidates decisions already taken by the cost model.
1423 WideningDecisions.clear();
1424 CallWideningDecisions.clear();
1425 Uniforms.clear();
1426 Scalars.clear();
1427 }
1428
1429 /// Returns the expected execution cost. The unit of the cost does
1430 /// not matter because we use the 'cost' units to compare different
1431 /// vector widths. The cost that is returned is *not* normalized by
1432 /// the factor width.
1433 InstructionCost expectedCost(ElementCount VF);
1434
1435 bool hasPredStores() const { return NumPredStores > 0; }
1436
1437 /// Returns true if epilogue vectorization is considered profitable, and
1438 /// false otherwise.
1439 /// \p VF is the vectorization factor chosen for the original loop.
1440 /// \p Multiplier is an aditional scaling factor applied to VF before
1441 /// comparing to EpilogueVectorizationMinVF.
1442 bool isEpilogueVectorizationProfitable(const ElementCount VF,
1443 const unsigned IC) const;
1444
1445 /// Returns the execution time cost of an instruction for a given vector
1446 /// width. Vector width of one means scalar.
1447 InstructionCost getInstructionCost(Instruction *I, ElementCount VF);
1448
1449 /// Return the cost of instructions in an inloop reduction pattern, if I is
1450 /// part of that pattern.
1451 std::optional<InstructionCost> getReductionPatternCost(Instruction *I,
1452 ElementCount VF,
1453 Type *VectorTy) const;
1454
1455 /// Returns true if \p Op should be considered invariant and if it is
1456 /// trivially hoistable.
1457 bool shouldConsiderInvariant(Value *Op);
1458
1459 /// Return the value of vscale used for tuning the cost model.
1460 std::optional<unsigned> getVScaleForTuning() const { return VScaleForTuning; }
1461
1462private:
1463 unsigned NumPredStores = 0;
1464
1465 /// Used to store the value of vscale used for tuning the cost model. It is
1466 /// initialized during object construction.
1467 std::optional<unsigned> VScaleForTuning;
1468
1469 /// Initializes the value of vscale used for tuning the cost model. If
1470 /// vscale_range.min == vscale_range.max then return vscale_range.max, else
1471 /// return the value returned by the corresponding TTI method.
1472 void initializeVScaleForTuning() {
1473 const Function *Fn = TheLoop->getHeader()->getParent();
1474 if (Fn->hasFnAttribute(Attribute::VScaleRange)) {
1475 auto Attr = Fn->getFnAttribute(Attribute::VScaleRange);
1476 auto Min = Attr.getVScaleRangeMin();
1477 auto Max = Attr.getVScaleRangeMax();
1478 if (Max && Min == Max) {
1479 VScaleForTuning = Max;
1480 return;
1481 }
1482 }
1483
1484 VScaleForTuning = TTI.getVScaleForTuning();
1485 }
1486
1487 /// \return An upper bound for the vectorization factors for both
1488 /// fixed and scalable vectorization, where the minimum-known number of
1489 /// elements is a power-of-2 larger than zero. If scalable vectorization is
1490 /// disabled or unsupported, then the scalable part will be equal to
1491 /// ElementCount::getScalable(0).
1492 FixedScalableVFPair computeFeasibleMaxVF(unsigned MaxTripCount,
1493 ElementCount UserVF,
1494 bool FoldTailByMasking);
1495
1496 /// If \p VF > MaxTripcount, clamps it to the next lower VF that is <=
1497 /// MaxTripCount.
1498 ElementCount clampVFByMaxTripCount(ElementCount VF, unsigned MaxTripCount,
1499 bool FoldTailByMasking) const;
1500
1501 /// \return the maximized element count based on the targets vector
1502 /// registers and the loop trip-count, but limited to a maximum safe VF.
1503 /// This is a helper function of computeFeasibleMaxVF.
1504 ElementCount getMaximizedVFForTarget(unsigned MaxTripCount,
1505 unsigned SmallestType,
1506 unsigned WidestType,
1507 ElementCount MaxSafeVF,
1508 bool FoldTailByMasking);
1509
1510 /// Checks if scalable vectorization is supported and enabled. Caches the
1511 /// result to avoid repeated debug dumps for repeated queries.
1512 bool isScalableVectorizationAllowed();
1513
1514 /// \return the maximum legal scalable VF, based on the safe max number
1515 /// of elements.
1516 ElementCount getMaxLegalScalableVF(unsigned MaxSafeElements);
1517
1518 /// Calculate vectorization cost of memory instruction \p I.
1519 InstructionCost getMemoryInstructionCost(Instruction *I, ElementCount VF);
1520
1521 /// The cost computation for scalarized memory instruction.
1522 InstructionCost getMemInstScalarizationCost(Instruction *I, ElementCount VF);
1523
1524 /// The cost computation for interleaving group of memory instructions.
1525 InstructionCost getInterleaveGroupCost(Instruction *I, ElementCount VF);
1526
1527 /// The cost computation for Gather/Scatter instruction.
1528 InstructionCost getGatherScatterCost(Instruction *I, ElementCount VF);
1529
1530 /// The cost computation for widening instruction \p I with consecutive
1531 /// memory access.
1532 InstructionCost getConsecutiveMemOpCost(Instruction *I, ElementCount VF);
1533
1534 /// The cost calculation for Load/Store instruction \p I with uniform pointer -
1535 /// Load: scalar load + broadcast.
1536 /// Store: scalar store + (loop invariant value stored? 0 : extract of last
1537 /// element)
1538 InstructionCost getUniformMemOpCost(Instruction *I, ElementCount VF);
1539
1540 /// Estimate the overhead of scalarizing an instruction. This is a
1541 /// convenience wrapper for the type-based getScalarizationOverhead API.
1543 ElementCount VF) const;
1544
1545 /// Returns true if an artificially high cost for emulated masked memrefs
1546 /// should be used.
1547 bool useEmulatedMaskMemRefHack(Instruction *I, ElementCount VF);
1548
1549 /// Map of scalar integer values to the smallest bitwidth they can be legally
1550 /// represented as. The vector equivalents of these values should be truncated
1551 /// to this type.
1553
1554 /// A type representing the costs for instructions if they were to be
1555 /// scalarized rather than vectorized. The entries are Instruction-Cost
1556 /// pairs.
1557 using ScalarCostsTy = MapVector<Instruction *, InstructionCost>;
1558
1559 /// A set containing all BasicBlocks that are known to present after
1560 /// vectorization as a predicated block.
1562 PredicatedBBsAfterVectorization;
1563
1564 /// Records whether it is allowed to have the original scalar loop execute at
1565 /// least once. This may be needed as a fallback loop in case runtime
1566 /// aliasing/dependence checks fail, or to handle the tail/remainder
1567 /// iterations when the trip count is unknown or doesn't divide by the VF,
1568 /// or as a peel-loop to handle gaps in interleave-groups.
1569 /// Under optsize and when the trip count is very small we don't allow any
1570 /// iterations to execute in the scalar loop.
1571 ScalarEpilogueLowering ScalarEpilogueStatus = CM_ScalarEpilogueAllowed;
1572
1573 /// Control finally chosen tail folding style. The first element is used if
1574 /// the IV update may overflow, the second element - if it does not.
1575 std::optional<std::pair<TailFoldingStyle, TailFoldingStyle>>
1576 ChosenTailFoldingStyle;
1577
1578 /// true if scalable vectorization is supported and enabled.
1579 std::optional<bool> IsScalableVectorizationAllowed;
1580
1581 /// Maximum safe number of elements to be processed per vector iteration,
1582 /// which do not prevent store-load forwarding and are safe with regard to the
1583 /// memory dependencies. Required for EVL-based veectorization, where this
1584 /// value is used as the upper bound of the safe AVL.
1585 std::optional<unsigned> MaxSafeElements;
1586
1587 /// A map holding scalar costs for different vectorization factors. The
1588 /// presence of a cost for an instruction in the mapping indicates that the
1589 /// instruction will be scalarized when vectorizing with the associated
1590 /// vectorization factor. The entries are VF-ScalarCostTy pairs.
1592
1593 /// Holds the instructions known to be uniform after vectorization.
1594 /// The data is collected per VF.
1596
1597 /// Holds the instructions known to be scalar after vectorization.
1598 /// The data is collected per VF.
1600
1601 /// Holds the instructions (address computations) that are forced to be
1602 /// scalarized.
1604
1605 /// PHINodes of the reductions that should be expanded in-loop.
1606 SmallPtrSet<PHINode *, 4> InLoopReductions;
1607
1608 /// A Map of inloop reduction operations and their immediate chain operand.
1609 /// FIXME: This can be removed once reductions can be costed correctly in
1610 /// VPlan. This was added to allow quick lookup of the inloop operations.
1611 DenseMap<Instruction *, Instruction *> InLoopReductionImmediateChains;
1612
1613 /// Returns the expected difference in cost from scalarizing the expression
1614 /// feeding a predicated instruction \p PredInst. The instructions to
1615 /// scalarize and their scalar costs are collected in \p ScalarCosts. A
1616 /// non-negative return value implies the expression will be scalarized.
1617 /// Currently, only single-use chains are considered for scalarization.
1618 InstructionCost computePredInstDiscount(Instruction *PredInst,
1619 ScalarCostsTy &ScalarCosts,
1620 ElementCount VF);
1621
1622 /// Collect the instructions that are uniform after vectorization. An
1623 /// instruction is uniform if we represent it with a single scalar value in
1624 /// the vectorized loop corresponding to each vector iteration. Examples of
1625 /// uniform instructions include pointer operands of consecutive or
1626 /// interleaved memory accesses. Note that although uniformity implies an
1627 /// instruction will be scalar, the reverse is not true. In general, a
1628 /// scalarized instruction will be represented by VF scalar values in the
1629 /// vectorized loop, each corresponding to an iteration of the original
1630 /// scalar loop.
1631 void collectLoopUniforms(ElementCount VF);
1632
1633 /// Collect the instructions that are scalar after vectorization. An
1634 /// instruction is scalar if it is known to be uniform or will be scalarized
1635 /// during vectorization. collectLoopScalars should only add non-uniform nodes
1636 /// to the list if they are used by a load/store instruction that is marked as
1637 /// CM_Scalarize. Non-uniform scalarized instructions will be represented by
1638 /// VF values in the vectorized loop, each corresponding to an iteration of
1639 /// the original scalar loop.
1640 void collectLoopScalars(ElementCount VF);
1641
1642 /// Keeps cost model vectorization decision and cost for instructions.
1643 /// Right now it is used for memory instructions only.
1645 std::pair<InstWidening, InstructionCost>>;
1646
1647 DecisionList WideningDecisions;
1648
1649 using CallDecisionList =
1650 DenseMap<std::pair<CallInst *, ElementCount>, CallWideningDecision>;
1651
1652 CallDecisionList CallWideningDecisions;
1653
1654 /// Returns true if \p V is expected to be vectorized and it needs to be
1655 /// extracted.
1656 bool needsExtract(Value *V, ElementCount VF) const {
1657 Instruction *I = dyn_cast<Instruction>(V);
1658 if (VF.isScalar() || !I || !TheLoop->contains(I) ||
1659 TheLoop->isLoopInvariant(I) ||
1660 getWideningDecision(I, VF) == CM_Scalarize)
1661 return false;
1662
1663 // Assume we can vectorize V (and hence we need extraction) if the
1664 // scalars are not computed yet. This can happen, because it is called
1665 // via getScalarizationOverhead from setCostBasedWideningDecision, before
1666 // the scalars are collected. That should be a safe assumption in most
1667 // cases, because we check if the operands have vectorizable types
1668 // beforehand in LoopVectorizationLegality.
1669 return !Scalars.contains(VF) || !isScalarAfterVectorization(I, VF);
1670 };
1671
1672 /// Returns a range containing only operands needing to be extracted.
1673 SmallVector<Value *, 4> filterExtractingOperands(Instruction::op_range Ops,
1674 ElementCount VF) const {
1675
1676 SmallPtrSet<const Value *, 4> UniqueOperands;
1678 for (Value *Op : Ops) {
1679 if (isa<Constant>(Op) || !UniqueOperands.insert(Op).second ||
1680 !needsExtract(Op, VF))
1681 continue;
1682 Res.push_back(Op);
1683 }
1684 return Res;
1685 }
1686
1687public:
1688 /// The loop that we evaluate.
1690
1691 /// Predicated scalar evolution analysis.
1693
1694 /// Loop Info analysis.
1696
1697 /// Vectorization legality.
1699
1700 /// Vector target information.
1702
1703 /// Target Library Info.
1705
1706 /// Demanded bits analysis.
1708
1709 /// Assumption cache.
1711
1712 /// Interface to emit optimization remarks.
1714
1716
1717 /// Loop Vectorize Hint.
1719
1720 /// The interleave access information contains groups of interleaved accesses
1721 /// with the same stride and close to each other.
1723
1724 /// Values to ignore in the cost model.
1726
1727 /// Values to ignore in the cost model when VF > 1.
1729
1730 /// All element types found in the loop.
1732
1733 /// The kind of cost that we are calculating
1735
1736 /// Whether this loop should be optimized for size based on function attribute
1737 /// or profile information.
1739
1740 /// The highest VF possible for this loop, without using MaxBandwidth.
1742};
1743} // end namespace llvm
1744
1745namespace {
1746/// Helper struct to manage generating runtime checks for vectorization.
1747///
1748/// The runtime checks are created up-front in temporary blocks to allow better
1749/// estimating the cost and un-linked from the existing IR. After deciding to
1750/// vectorize, the checks are moved back. If deciding not to vectorize, the
1751/// temporary blocks are completely removed.
1752class GeneratedRTChecks {
1753 /// Basic block which contains the generated SCEV checks, if any.
1754 BasicBlock *SCEVCheckBlock = nullptr;
1755
1756 /// The value representing the result of the generated SCEV checks. If it is
1757 /// nullptr no SCEV checks have been generated.
1758 Value *SCEVCheckCond = nullptr;
1759
1760 /// Basic block which contains the generated memory runtime checks, if any.
1761 BasicBlock *MemCheckBlock = nullptr;
1762
1763 /// The value representing the result of the generated memory runtime checks.
1764 /// If it is nullptr no memory runtime checks have been generated.
1765 Value *MemRuntimeCheckCond = nullptr;
1766
1767 DominatorTree *DT;
1768 LoopInfo *LI;
1770
1771 SCEVExpander SCEVExp;
1772 SCEVExpander MemCheckExp;
1773
1774 bool CostTooHigh = false;
1775
1776 Loop *OuterLoop = nullptr;
1777
1779
1780 /// The kind of cost that we are calculating
1782
1783public:
1784 GeneratedRTChecks(PredicatedScalarEvolution &PSE, DominatorTree *DT,
1787 : DT(DT), LI(LI), TTI(TTI), SCEVExp(*PSE.getSE(), DL, "scev.check"),
1788 MemCheckExp(*PSE.getSE(), DL, "scev.check"), PSE(PSE),
1789 CostKind(CostKind) {}
1790
1791 /// Generate runtime checks in SCEVCheckBlock and MemCheckBlock, so we can
1792 /// accurately estimate the cost of the runtime checks. The blocks are
1793 /// un-linked from the IR and are added back during vector code generation. If
1794 /// there is no vector code generation, the check blocks are removed
1795 /// completely.
1796 void create(Loop *L, const LoopAccessInfo &LAI,
1797 const SCEVPredicate &UnionPred, ElementCount VF, unsigned IC) {
1798
1799 // Hard cutoff to limit compile-time increase in case a very large number of
1800 // runtime checks needs to be generated.
1801 // TODO: Skip cutoff if the loop is guaranteed to execute, e.g. due to
1802 // profile info.
1803 CostTooHigh =
1805 if (CostTooHigh)
1806 return;
1807
1808 BasicBlock *LoopHeader = L->getHeader();
1809 BasicBlock *Preheader = L->getLoopPreheader();
1810
1811 // Use SplitBlock to create blocks for SCEV & memory runtime checks to
1812 // ensure the blocks are properly added to LoopInfo & DominatorTree. Those
1813 // may be used by SCEVExpander. The blocks will be un-linked from their
1814 // predecessors and removed from LI & DT at the end of the function.
1815 if (!UnionPred.isAlwaysTrue()) {
1816 SCEVCheckBlock = SplitBlock(Preheader, Preheader->getTerminator(), DT, LI,
1817 nullptr, "vector.scevcheck");
1818
1819 SCEVCheckCond = SCEVExp.expandCodeForPredicate(
1820 &UnionPred, SCEVCheckBlock->getTerminator());
1821 if (isa<Constant>(SCEVCheckCond)) {
1822 // Clean up directly after expanding the predicate to a constant, to
1823 // avoid further expansions re-using anything left over from SCEVExp.
1824 SCEVExpanderCleaner SCEVCleaner(SCEVExp);
1825 SCEVCleaner.cleanup();
1826 }
1827 }
1828
1829 const auto &RtPtrChecking = *LAI.getRuntimePointerChecking();
1830 if (RtPtrChecking.Need) {
1831 auto *Pred = SCEVCheckBlock ? SCEVCheckBlock : Preheader;
1832 MemCheckBlock = SplitBlock(Pred, Pred->getTerminator(), DT, LI, nullptr,
1833 "vector.memcheck");
1834
1835 auto DiffChecks = RtPtrChecking.getDiffChecks();
1836 if (DiffChecks) {
1837 Value *RuntimeVF = nullptr;
1838 MemRuntimeCheckCond = addDiffRuntimeChecks(
1839 MemCheckBlock->getTerminator(), *DiffChecks, MemCheckExp,
1840 [VF, &RuntimeVF](IRBuilderBase &B, unsigned Bits) {
1841 if (!RuntimeVF)
1842 RuntimeVF = getRuntimeVF(B, B.getIntNTy(Bits), VF);
1843 return RuntimeVF;
1844 },
1845 IC);
1846 } else {
1847 MemRuntimeCheckCond = addRuntimeChecks(
1848 MemCheckBlock->getTerminator(), L, RtPtrChecking.getChecks(),
1850 }
1851 assert(MemRuntimeCheckCond &&
1852 "no RT checks generated although RtPtrChecking "
1853 "claimed checks are required");
1854 }
1855
1856 if (!MemCheckBlock && !SCEVCheckBlock)
1857 return;
1858
1859 // Unhook the temporary block with the checks, update various places
1860 // accordingly.
1861 if (SCEVCheckBlock)
1862 SCEVCheckBlock->replaceAllUsesWith(Preheader);
1863 if (MemCheckBlock)
1864 MemCheckBlock->replaceAllUsesWith(Preheader);
1865
1866 if (SCEVCheckBlock) {
1867 SCEVCheckBlock->getTerminator()->moveBefore(
1868 Preheader->getTerminator()->getIterator());
1869 auto *UI = new UnreachableInst(Preheader->getContext(), SCEVCheckBlock);
1870 UI->setDebugLoc(DebugLoc::getTemporary());
1871 Preheader->getTerminator()->eraseFromParent();
1872 }
1873 if (MemCheckBlock) {
1874 MemCheckBlock->getTerminator()->moveBefore(
1875 Preheader->getTerminator()->getIterator());
1876 auto *UI = new UnreachableInst(Preheader->getContext(), MemCheckBlock);
1877 UI->setDebugLoc(DebugLoc::getTemporary());
1878 Preheader->getTerminator()->eraseFromParent();
1879 }
1880
1881 DT->changeImmediateDominator(LoopHeader, Preheader);
1882 if (MemCheckBlock) {
1883 DT->eraseNode(MemCheckBlock);
1884 LI->removeBlock(MemCheckBlock);
1885 }
1886 if (SCEVCheckBlock) {
1887 DT->eraseNode(SCEVCheckBlock);
1888 LI->removeBlock(SCEVCheckBlock);
1889 }
1890
1891 // Outer loop is used as part of the later cost calculations.
1892 OuterLoop = L->getParentLoop();
1893 }
1894
1896 if (SCEVCheckBlock || MemCheckBlock)
1897 LLVM_DEBUG(dbgs() << "Calculating cost of runtime checks:\n");
1898
1899 if (CostTooHigh) {
1901 Cost.setInvalid();
1902 LLVM_DEBUG(dbgs() << " number of checks exceeded threshold\n");
1903 return Cost;
1904 }
1905
1906 InstructionCost RTCheckCost = 0;
1907 if (SCEVCheckBlock)
1908 for (Instruction &I : *SCEVCheckBlock) {
1909 if (SCEVCheckBlock->getTerminator() == &I)
1910 continue;
1912 LLVM_DEBUG(dbgs() << " " << C << " for " << I << "\n");
1913 RTCheckCost += C;
1914 }
1915 if (MemCheckBlock) {
1916 InstructionCost MemCheckCost = 0;
1917 for (Instruction &I : *MemCheckBlock) {
1918 if (MemCheckBlock->getTerminator() == &I)
1919 continue;
1921 LLVM_DEBUG(dbgs() << " " << C << " for " << I << "\n");
1922 MemCheckCost += C;
1923 }
1924
1925 // If the runtime memory checks are being created inside an outer loop
1926 // we should find out if these checks are outer loop invariant. If so,
1927 // the checks will likely be hoisted out and so the effective cost will
1928 // reduce according to the outer loop trip count.
1929 if (OuterLoop) {
1930 ScalarEvolution *SE = MemCheckExp.getSE();
1931 // TODO: If profitable, we could refine this further by analysing every
1932 // individual memory check, since there could be a mixture of loop
1933 // variant and invariant checks that mean the final condition is
1934 // variant.
1935 const SCEV *Cond = SE->getSCEV(MemRuntimeCheckCond);
1936 if (SE->isLoopInvariant(Cond, OuterLoop)) {
1937 // It seems reasonable to assume that we can reduce the effective
1938 // cost of the checks even when we know nothing about the trip
1939 // count. Assume that the outer loop executes at least twice.
1940 unsigned BestTripCount = 2;
1941
1942 // Get the best known TC estimate.
1943 if (auto EstimatedTC = getSmallBestKnownTC(
1944 PSE, OuterLoop, /* CanUseConstantMax = */ false))
1945 if (EstimatedTC->isFixed())
1946 BestTripCount = EstimatedTC->getFixedValue();
1947
1948 InstructionCost NewMemCheckCost = MemCheckCost / BestTripCount;
1949
1950 // Let's ensure the cost is always at least 1.
1951 NewMemCheckCost = std::max(NewMemCheckCost.getValue(),
1953
1954 if (BestTripCount > 1)
1956 << "We expect runtime memory checks to be hoisted "
1957 << "out of the outer loop. Cost reduced from "
1958 << MemCheckCost << " to " << NewMemCheckCost << '\n');
1959
1960 MemCheckCost = NewMemCheckCost;
1961 }
1962 }
1963
1964 RTCheckCost += MemCheckCost;
1965 }
1966
1967 if (SCEVCheckBlock || MemCheckBlock)
1968 LLVM_DEBUG(dbgs() << "Total cost of runtime checks: " << RTCheckCost
1969 << "\n");
1970
1971 return RTCheckCost;
1972 }
1973
1974 /// Remove the created SCEV & memory runtime check blocks & instructions, if
1975 /// unused.
1976 ~GeneratedRTChecks() {
1977 SCEVExpanderCleaner SCEVCleaner(SCEVExp);
1978 SCEVExpanderCleaner MemCheckCleaner(MemCheckExp);
1979 bool SCEVChecksUsed = !SCEVCheckBlock || !pred_empty(SCEVCheckBlock);
1980 bool MemChecksUsed = !MemCheckBlock || !pred_empty(MemCheckBlock);
1981 if (SCEVChecksUsed)
1982 SCEVCleaner.markResultUsed();
1983
1984 if (MemChecksUsed) {
1985 MemCheckCleaner.markResultUsed();
1986 } else {
1987 auto &SE = *MemCheckExp.getSE();
1988 // Memory runtime check generation creates compares that use expanded
1989 // values. Remove them before running the SCEVExpanderCleaners.
1990 for (auto &I : make_early_inc_range(reverse(*MemCheckBlock))) {
1991 if (MemCheckExp.isInsertedInstruction(&I))
1992 continue;
1993 SE.forgetValue(&I);
1994 I.eraseFromParent();
1995 }
1996 }
1997 MemCheckCleaner.cleanup();
1998 SCEVCleaner.cleanup();
1999
2000 if (!SCEVChecksUsed)
2001 SCEVCheckBlock->eraseFromParent();
2002 if (!MemChecksUsed)
2003 MemCheckBlock->eraseFromParent();
2004 }
2005
2006 /// Retrieves the SCEVCheckCond and SCEVCheckBlock that were generated as IR
2007 /// outside VPlan.
2008 std::pair<Value *, BasicBlock *> getSCEVChecks() {
2009 using namespace llvm::PatternMatch;
2010 if (!SCEVCheckCond || match(SCEVCheckCond, m_ZeroInt()))
2011 return {nullptr, nullptr};
2012
2013 return {SCEVCheckCond, SCEVCheckBlock};
2014 }
2015
2016 /// Retrieves the MemCheckCond and MemCheckBlock that were generated as IR
2017 /// outside VPlan.
2018 std::pair<Value *, BasicBlock *> getMemRuntimeChecks() {
2019 using namespace llvm::PatternMatch;
2020 if (MemRuntimeCheckCond && match(MemRuntimeCheckCond, m_ZeroInt()))
2021 return {nullptr, nullptr};
2022 return {MemRuntimeCheckCond, MemCheckBlock};
2023 }
2024
2025 /// Return true if any runtime checks have been added
2026 bool hasChecks() const {
2027 using namespace llvm::PatternMatch;
2028 return (SCEVCheckCond && !match(SCEVCheckCond, m_ZeroInt())) ||
2029 MemRuntimeCheckCond;
2030 }
2031};
2032} // namespace
2033
2035 return Style == TailFoldingStyle::Data ||
2038}
2039
2041 return Style == TailFoldingStyle::DataAndControlFlow ||
2043}
2044
2045// Return true if \p OuterLp is an outer loop annotated with hints for explicit
2046// vectorization. The loop needs to be annotated with #pragma omp simd
2047// simdlen(#) or #pragma clang vectorize(enable) vectorize_width(#). If the
2048// vector length information is not provided, vectorization is not considered
2049// explicit. Interleave hints are not allowed either. These limitations will be
2050// relaxed in the future.
2051// Please, note that we are currently forced to abuse the pragma 'clang
2052// vectorize' semantics. This pragma provides *auto-vectorization hints*
2053// (i.e., LV must check that vectorization is legal) whereas pragma 'omp simd'
2054// provides *explicit vectorization hints* (LV can bypass legal checks and
2055// assume that vectorization is legal). However, both hints are implemented
2056// using the same metadata (llvm.loop.vectorize, processed by
2057// LoopVectorizeHints). This will be fixed in the future when the native IR
2058// representation for pragma 'omp simd' is introduced.
2059static bool isExplicitVecOuterLoop(Loop *OuterLp,
2061 assert(!OuterLp->isInnermost() && "This is not an outer loop");
2062 LoopVectorizeHints Hints(OuterLp, true /*DisableInterleaving*/, *ORE);
2063
2064 // Only outer loops with an explicit vectorization hint are supported.
2065 // Unannotated outer loops are ignored.
2067 return false;
2068
2069 Function *Fn = OuterLp->getHeader()->getParent();
2070 if (!Hints.allowVectorization(Fn, OuterLp,
2071 true /*VectorizeOnlyWhenForced*/)) {
2072 LLVM_DEBUG(dbgs() << "LV: Loop hints prevent outer loop vectorization.\n");
2073 return false;
2074 }
2075
2076 if (Hints.getInterleave() > 1) {
2077 // TODO: Interleave support is future work.
2078 LLVM_DEBUG(dbgs() << "LV: Not vectorizing: Interleave is not supported for "
2079 "outer loops.\n");
2080 Hints.emitRemarkWithHints();
2081 return false;
2082 }
2083
2084 return true;
2085}
2086
2090 // Collect inner loops and outer loops without irreducible control flow. For
2091 // now, only collect outer loops that have explicit vectorization hints. If we
2092 // are stress testing the VPlan H-CFG construction, we collect the outermost
2093 // loop of every loop nest.
2094 if (L.isInnermost() || VPlanBuildStressTest ||
2096 LoopBlocksRPO RPOT(&L);
2097 RPOT.perform(LI);
2098 if (!containsIrreducibleCFG<const BasicBlock *>(RPOT, *LI)) {
2099 V.push_back(&L);
2100 // TODO: Collect inner loops inside marked outer loops in case
2101 // vectorization fails for the outer loop. Do not invoke
2102 // 'containsIrreducibleCFG' again for inner loops when the outer loop is
2103 // already known to be reducible. We can use an inherited attribute for
2104 // that.
2105 return;
2106 }
2107 }
2108 for (Loop *InnerL : L)
2109 collectSupportedLoops(*InnerL, LI, ORE, V);
2110}
2111
2112//===----------------------------------------------------------------------===//
2113// Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
2114// LoopVectorizationCostModel and LoopVectorizationPlanner.
2115//===----------------------------------------------------------------------===//
2116
2117/// Compute the transformed value of Index at offset StartValue using step
2118/// StepValue.
2119/// For integer induction, returns StartValue + Index * StepValue.
2120/// For pointer induction, returns StartValue[Index * StepValue].
2121/// FIXME: The newly created binary instructions should contain nsw/nuw
2122/// flags, which can be found from the original scalar operations.
2123static Value *
2125 Value *Step,
2127 const BinaryOperator *InductionBinOp) {
2128 using namespace llvm::PatternMatch;
2129 Type *StepTy = Step->getType();
2130 Value *CastedIndex = StepTy->isIntegerTy()
2131 ? B.CreateSExtOrTrunc(Index, StepTy)
2132 : B.CreateCast(Instruction::SIToFP, Index, StepTy);
2133 if (CastedIndex != Index) {
2134 CastedIndex->setName(CastedIndex->getName() + ".cast");
2135 Index = CastedIndex;
2136 }
2137
2138 // Note: the IR at this point is broken. We cannot use SE to create any new
2139 // SCEV and then expand it, hoping that SCEV's simplification will give us
2140 // a more optimal code. Unfortunately, attempt of doing so on invalid IR may
2141 // lead to various SCEV crashes. So all we can do is to use builder and rely
2142 // on InstCombine for future simplifications. Here we handle some trivial
2143 // cases only.
2144 auto CreateAdd = [&B](Value *X, Value *Y) {
2145 assert(X->getType() == Y->getType() && "Types don't match!");
2146 if (match(X, m_ZeroInt()))
2147 return Y;
2148 if (match(Y, m_ZeroInt()))
2149 return X;
2150 return B.CreateAdd(X, Y);
2151 };
2152
2153 // We allow X to be a vector type, in which case Y will potentially be
2154 // splatted into a vector with the same element count.
2155 auto CreateMul = [&B](Value *X, Value *Y) {
2156 assert(X->getType()->getScalarType() == Y->getType() &&
2157 "Types don't match!");
2158 if (match(X, m_One()))
2159 return Y;
2160 if (match(Y, m_One()))
2161 return X;
2162 VectorType *XVTy = dyn_cast<VectorType>(X->getType());
2163 if (XVTy && !isa<VectorType>(Y->getType()))
2164 Y = B.CreateVectorSplat(XVTy->getElementCount(), Y);
2165 return B.CreateMul(X, Y);
2166 };
2167
2168 switch (InductionKind) {
2170 assert(!isa<VectorType>(Index->getType()) &&
2171 "Vector indices not supported for integer inductions yet");
2172 assert(Index->getType() == StartValue->getType() &&
2173 "Index type does not match StartValue type");
2174 if (isa<ConstantInt>(Step) && cast<ConstantInt>(Step)->isMinusOne())
2175 return B.CreateSub(StartValue, Index);
2176 auto *Offset = CreateMul(Index, Step);
2177 return CreateAdd(StartValue, Offset);
2178 }
2180 return B.CreatePtrAdd(StartValue, CreateMul(Index, Step));
2182 assert(!isa<VectorType>(Index->getType()) &&
2183 "Vector indices not supported for FP inductions yet");
2184 assert(Step->getType()->isFloatingPointTy() && "Expected FP Step value");
2185 assert(InductionBinOp &&
2186 (InductionBinOp->getOpcode() == Instruction::FAdd ||
2187 InductionBinOp->getOpcode() == Instruction::FSub) &&
2188 "Original bin op should be defined for FP induction");
2189
2190 Value *MulExp = B.CreateFMul(Step, Index);
2191 return B.CreateBinOp(InductionBinOp->getOpcode(), StartValue, MulExp,
2192 "induction");
2193 }
2195 return nullptr;
2196 }
2197 llvm_unreachable("invalid enum");
2198}
2199
2200static std::optional<unsigned> getMaxVScale(const Function &F,
2201 const TargetTransformInfo &TTI) {
2202 if (std::optional<unsigned> MaxVScale = TTI.getMaxVScale())
2203 return MaxVScale;
2204
2205 if (F.hasFnAttribute(Attribute::VScaleRange))
2206 return F.getFnAttribute(Attribute::VScaleRange).getVScaleRangeMax();
2207
2208 return std::nullopt;
2209}
2210
2211/// For the given VF and UF and maximum trip count computed for the loop, return
2212/// whether the induction variable might overflow in the vectorized loop. If not,
2213/// then we know a runtime overflow check always evaluates to false and can be
2214/// removed.
2217 ElementCount VF, std::optional<unsigned> UF = std::nullopt) {
2218 // Always be conservative if we don't know the exact unroll factor.
2219 unsigned MaxUF = UF ? *UF : Cost->TTI.getMaxInterleaveFactor(VF);
2220
2221 IntegerType *IdxTy = Cost->Legal->getWidestInductionType();
2222 APInt MaxUIntTripCount = IdxTy->getMask();
2223
2224 // We know the runtime overflow check is known false iff the (max) trip-count
2225 // is known and (max) trip-count + (VF * UF) does not overflow in the type of
2226 // the vector loop induction variable.
2227 if (unsigned TC = Cost->PSE.getSmallConstantMaxTripCount()) {
2228 uint64_t MaxVF = VF.getKnownMinValue();
2229 if (VF.isScalable()) {
2230 std::optional<unsigned> MaxVScale =
2231 getMaxVScale(*Cost->TheFunction, Cost->TTI);
2232 if (!MaxVScale)
2233 return false;
2234 MaxVF *= *MaxVScale;
2235 }
2236
2237 return (MaxUIntTripCount - TC).ugt(MaxVF * MaxUF);
2238 }
2239
2240 return false;
2241}
2242
2243// Return whether we allow using masked interleave-groups (for dealing with
2244// strided loads/stores that reside in predicated blocks, or for dealing
2245// with gaps).
2247 // If an override option has been passed in for interleaved accesses, use it.
2250
2252}
2253
2255 BasicBlock *CheckIRBB) {
2256 // Note: The block with the minimum trip-count check is already connected
2257 // during earlier VPlan construction.
2258 VPBlockBase *ScalarPH = Plan.getScalarPreheader();
2260 assert(PreVectorPH->getNumSuccessors() == 2 && "Expected 2 successors");
2261 assert(PreVectorPH->getSuccessors()[0] == ScalarPH && "Unexpected successor");
2262 VPIRBasicBlock *CheckVPIRBB = Plan.createVPIRBasicBlock(CheckIRBB);
2263 VPBlockUtils::insertOnEdge(PreVectorPH, VectorPHVPBB, CheckVPIRBB);
2264 PreVectorPH = CheckVPIRBB;
2265 VPBlockUtils::connectBlocks(PreVectorPH, ScalarPH);
2266 PreVectorPH->swapSuccessors();
2267
2268 // We just connected a new block to the scalar preheader. Update all
2269 // VPPhis by adding an incoming value for it, replicating the last value.
2270 unsigned NumPredecessors = ScalarPH->getNumPredecessors();
2271 for (VPRecipeBase &R : cast<VPBasicBlock>(ScalarPH)->phis()) {
2272 assert(isa<VPPhi>(&R) && "Phi expected to be VPPhi");
2273 assert(cast<VPPhi>(&R)->getNumIncoming() == NumPredecessors - 1 &&
2274 "must have incoming values for all operands");
2275 R.addOperand(R.getOperand(NumPredecessors - 2));
2276 }
2277}
2278
2279Value *
2281 unsigned UF) const {
2282 // Generate code to check if the loop's trip count is less than VF * UF, or
2283 // equal to it in case a scalar epilogue is required; this implies that the
2284 // vector trip count is zero. This check also covers the case where adding one
2285 // to the backedge-taken count overflowed leading to an incorrect trip count
2286 // of zero. In this case we will also jump to the scalar loop.
2287 auto P = Cost->requiresScalarEpilogue(VF.isVector()) ? ICmpInst::ICMP_ULE
2289
2290 // Reuse existing vector loop preheader for TC checks.
2291 // Note that new preheader block is generated for vector loop.
2292 BasicBlock *const TCCheckBlock = LoopVectorPreHeader;
2294 TCCheckBlock->getContext(),
2295 InstSimplifyFolder(TCCheckBlock->getDataLayout()));
2296 Builder.SetInsertPoint(TCCheckBlock->getTerminator());
2297
2298 // If tail is to be folded, vector loop takes care of all iterations.
2299 Value *Count = getTripCount();
2300 Type *CountTy = Count->getType();
2301 Value *CheckMinIters = Builder.getFalse();
2302 auto CreateStep = [&]() -> Value * {
2303 // Create step with max(MinProTripCount, UF * VF).
2305 return createStepForVF(Builder, CountTy, VF, UF);
2306
2307 Value *MinProfTC =
2309 if (!VF.isScalable())
2310 return MinProfTC;
2312 Intrinsic::umax, MinProfTC, createStepForVF(Builder, CountTy, VF, UF));
2313 };
2314
2315 TailFoldingStyle Style = Cost->getTailFoldingStyle();
2316 if (Style == TailFoldingStyle::None) {
2317 Value *Step = CreateStep();
2318 ScalarEvolution &SE = *PSE.getSE();
2319 // TODO: Emit unconditional branch to vector preheader instead of
2320 // conditional branch with known condition.
2321 const SCEV *TripCountSCEV = SE.applyLoopGuards(SE.getSCEV(Count), OrigLoop);
2322 // Check if the trip count is < the step.
2323 if (SE.isKnownPredicate(P, TripCountSCEV, SE.getSCEV(Step))) {
2324 // TODO: Ensure step is at most the trip count when determining max VF and
2325 // UF, w/o tail folding.
2326 CheckMinIters = Builder.getTrue();
2328 TripCountSCEV, SE.getSCEV(Step))) {
2329 // Generate the minimum iteration check only if we cannot prove the
2330 // check is known to be true, or known to be false.
2331 CheckMinIters = Builder.CreateICmp(P, Count, Step, "min.iters.check");
2332 } // else step known to be < trip count, use CheckMinIters preset to false.
2333 } else if (VF.isScalable() && !TTI->isVScaleKnownToBeAPowerOfTwo() &&
2336 // vscale is not necessarily a power-of-2, which means we cannot guarantee
2337 // an overflow to zero when updating induction variables and so an
2338 // additional overflow check is required before entering the vector loop.
2339
2340 // Get the maximum unsigned value for the type.
2341 Value *MaxUIntTripCount =
2342 ConstantInt::get(CountTy, cast<IntegerType>(CountTy)->getMask());
2343 Value *LHS = Builder.CreateSub(MaxUIntTripCount, Count);
2344
2345 // Don't execute the vector loop if (UMax - n) < (VF * UF).
2346 CheckMinIters = Builder.CreateICmp(ICmpInst::ICMP_ULT, LHS, CreateStep());
2347 }
2348 return CheckMinIters;
2349}
2350
2351/// Replace \p VPBB with a VPIRBasicBlock wrapping \p IRBB. All recipes from \p
2352/// VPBB are moved to the end of the newly created VPIRBasicBlock. VPBB must
2353/// have a single predecessor, which is rewired to the new VPIRBasicBlock. All
2354/// successors of VPBB, if any, are rewired to the new VPIRBasicBlock.
2356 BasicBlock *IRBB) {
2357 VPIRBasicBlock *IRVPBB = VPBB->getPlan()->createVPIRBasicBlock(IRBB);
2358 auto IP = IRVPBB->begin();
2359 for (auto &R : make_early_inc_range(VPBB->phis()))
2360 R.moveBefore(*IRVPBB, IP);
2361
2362 for (auto &R :
2364 R.moveBefore(*IRVPBB, IRVPBB->end());
2365
2366 VPBlockUtils::reassociateBlocks(VPBB, IRVPBB);
2367 // VPBB is now dead and will be cleaned up when the plan gets destroyed.
2368 return IRVPBB;
2369}
2370
2373 assert(LoopVectorPreHeader && "Invalid loop structure");
2375 Cost->requiresScalarEpilogue(VF.isVector())) &&
2376 "loops not exiting via the latch without required epilogue?");
2377
2378 // NOTE: The Plan's scalar preheader VPBB isn't replaced with a VPIRBasicBlock
2379 // wrapping the newly created scalar preheader here at the moment, because the
2380 // Plan's scalar preheader may be unreachable at this point. Instead it is
2381 // replaced in executePlan.
2383 DT, LI, nullptr, Twine(Prefix) + "scalar.ph");
2384}
2385
2386/// Return the expanded step for \p ID using \p ExpandedSCEVs to look up SCEV
2387/// expansion results.
2389 const SCEV2ValueTy &ExpandedSCEVs) {
2390 const SCEV *Step = ID.getStep();
2391 if (auto *C = dyn_cast<SCEVConstant>(Step))
2392 return C->getValue();
2393 if (auto *U = dyn_cast<SCEVUnknown>(Step))
2394 return U->getValue();
2395 Value *V = ExpandedSCEVs.lookup(Step);
2396 assert(V && "SCEV must be expanded at this point");
2397 return V;
2398}
2399
2400/// Knowing that loop \p L executes a single vector iteration, add instructions
2401/// that will get simplified and thus should not have any cost to \p
2402/// InstsToIgnore.
2405 SmallPtrSetImpl<Instruction *> &InstsToIgnore) {
2406 auto *Cmp = L->getLatchCmpInst();
2407 if (Cmp)
2408 InstsToIgnore.insert(Cmp);
2409 for (const auto &KV : IL) {
2410 // Extract the key by hand so that it can be used in the lambda below. Note
2411 // that captured structured bindings are a C++20 extension.
2412 const PHINode *IV = KV.first;
2413
2414 // Get next iteration value of the induction variable.
2415 Instruction *IVInst =
2416 cast<Instruction>(IV->getIncomingValueForBlock(L->getLoopLatch()));
2417 if (all_of(IVInst->users(),
2418 [&](const User *U) { return U == IV || U == Cmp; }))
2419 InstsToIgnore.insert(IVInst);
2420 }
2421}
2422
2424 // Create a new IR basic block for the scalar preheader.
2425 BasicBlock *ScalarPH = createScalarPreheader("");
2426 return ScalarPH->getSinglePredecessor();
2427}
2428
2429namespace {
2430
2431struct CSEDenseMapInfo {
2432 static bool canHandle(const Instruction *I) {
2433 return isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) ||
2434 isa<ShuffleVectorInst>(I) || isa<GetElementPtrInst>(I);
2435 }
2436
2437 static inline Instruction *getEmptyKey() {
2439 }
2440
2441 static inline Instruction *getTombstoneKey() {
2443 }
2444
2445 static unsigned getHashValue(const Instruction *I) {
2446 assert(canHandle(I) && "Unknown instruction!");
2447 return hash_combine(I->getOpcode(),
2448 hash_combine_range(I->operand_values()));
2449 }
2450
2451 static bool isEqual(const Instruction *LHS, const Instruction *RHS) {
2452 if (LHS == getEmptyKey() || RHS == getEmptyKey() ||
2453 LHS == getTombstoneKey() || RHS == getTombstoneKey())
2454 return LHS == RHS;
2455 return LHS->isIdenticalTo(RHS);
2456 }
2457};
2458
2459} // end anonymous namespace
2460
2461///Perform cse of induction variable instructions.
2462static void cse(BasicBlock *BB) {
2463 // Perform simple cse.
2465 for (Instruction &In : llvm::make_early_inc_range(*BB)) {
2466 if (!CSEDenseMapInfo::canHandle(&In))
2467 continue;
2468
2469 // Check if we can replace this instruction with any of the
2470 // visited instructions.
2471 if (Instruction *V = CSEMap.lookup(&In)) {
2472 In.replaceAllUsesWith(V);
2473 In.eraseFromParent();
2474 continue;
2475 }
2476
2477 CSEMap[&In] = &In;
2478 }
2479}
2480
2481/// This function attempts to return a value that represents the ElementCount
2482/// at runtime. For fixed-width VFs we know this precisely at compile
2483/// time, but for scalable VFs we calculate it based on an estimate of the
2484/// vscale value.
2486 std::optional<unsigned> VScale) {
2487 unsigned EstimatedVF = VF.getKnownMinValue();
2488 if (VF.isScalable())
2489 if (VScale)
2490 EstimatedVF *= *VScale;
2491 assert(EstimatedVF >= 1 && "Estimated VF shouldn't be less than 1");
2492 return EstimatedVF;
2493}
2494
2497 ElementCount VF) const {
2498 // We only need to calculate a cost if the VF is scalar; for actual vectors
2499 // we should already have a pre-calculated cost at each VF.
2500 if (!VF.isScalar())
2501 return getCallWideningDecision(CI, VF).Cost;
2502
2503 Type *RetTy = CI->getType();
2505 if (auto RedCost = getReductionPatternCost(CI, VF, RetTy))
2506 return *RedCost;
2507
2509 for (auto &ArgOp : CI->args())
2510 Tys.push_back(ArgOp->getType());
2511
2512 InstructionCost ScalarCallCost =
2514
2515 // If this is an intrinsic we may have a lower cost for it.
2516 if (getVectorIntrinsicIDForCall(CI, TLI)) {
2517 InstructionCost IntrinsicCost = getVectorIntrinsicCost(CI, VF);
2518 return std::min(ScalarCallCost, IntrinsicCost);
2519 }
2520 return ScalarCallCost;
2521}
2522
2524 if (VF.isScalar() || !canVectorizeTy(Ty))
2525 return Ty;
2526 return toVectorizedTy(Ty, VF);
2527}
2528
2531 ElementCount VF) const {
2533 assert(ID && "Expected intrinsic call!");
2535 FastMathFlags FMF;
2536 if (auto *FPMO = dyn_cast<FPMathOperator>(CI))
2537 FMF = FPMO->getFastMathFlags();
2538
2541 SmallVector<Type *> ParamTys;
2542 std::transform(FTy->param_begin(), FTy->param_end(),
2543 std::back_inserter(ParamTys),
2544 [&](Type *Ty) { return maybeVectorizeType(Ty, VF); });
2545
2546 IntrinsicCostAttributes CostAttrs(ID, RetTy, Arguments, ParamTys, FMF,
2547 dyn_cast<IntrinsicInst>(CI),
2549 return TTI.getIntrinsicInstrCost(CostAttrs, CostKind);
2550}
2551
2553 // Fix widened non-induction PHIs by setting up the PHI operands.
2554 fixNonInductionPHIs(State);
2555
2556 // Don't apply optimizations below when no (vector) loop remains, as they all
2557 // require one at the moment.
2558 VPBasicBlock *HeaderVPBB =
2559 vputils::getFirstLoopHeader(*State.Plan, State.VPDT);
2560 if (!HeaderVPBB)
2561 return;
2562
2563 BasicBlock *HeaderBB = State.CFG.VPBB2IRBB[HeaderVPBB];
2564
2565 // Remove redundant induction instructions.
2566 cse(HeaderBB);
2567
2568 // Set/update profile weights for the vector and remainder loops as original
2569 // loop iterations are now distributed among them. Note that original loop
2570 // becomes the scalar remainder loop after vectorization.
2571 //
2572 // For cases like foldTailByMasking() and requiresScalarEpiloque() we may
2573 // end up getting slightly roughened result but that should be OK since
2574 // profile is not inherently precise anyway. Note also possible bypass of
2575 // vector code caused by legality checks is ignored, assigning all the weight
2576 // to the vector loop, optimistically.
2577 //
2578 // For scalable vectorization we can't know at compile time how many
2579 // iterations of the loop are handled in one vector iteration, so instead
2580 // use the value of vscale used for tuning.
2581 Loop *VectorLoop = LI->getLoopFor(HeaderBB);
2582 unsigned EstimatedVFxUF =
2583 estimateElementCount(VF * UF, Cost->getVScaleForTuning());
2584 setProfileInfoAfterUnrolling(OrigLoop, VectorLoop, OrigLoop, EstimatedVFxUF);
2585}
2586
2588 auto Iter = vp_depth_first_shallow(Plan.getEntry());
2589 for (VPBasicBlock *VPBB : VPBlockUtils::blocksOnly<VPBasicBlock>(Iter)) {
2590 for (VPRecipeBase &P : VPBB->phis()) {
2591 VPWidenPHIRecipe *VPPhi = dyn_cast<VPWidenPHIRecipe>(&P);
2592 if (!VPPhi)
2593 continue;
2594 PHINode *NewPhi = cast<PHINode>(State.get(VPPhi));
2595 // Make sure the builder has a valid insert point.
2596 Builder.SetInsertPoint(NewPhi);
2597 for (const auto &[Inc, VPBB] : VPPhi->incoming_values_and_blocks())
2598 NewPhi->addIncoming(State.get(Inc), State.CFG.VPBB2IRBB[VPBB]);
2599 }
2600 }
2601}
2602
2603void LoopVectorizationCostModel::collectLoopScalars(ElementCount VF) {
2604 // We should not collect Scalars more than once per VF. Right now, this
2605 // function is called from collectUniformsAndScalars(), which already does
2606 // this check. Collecting Scalars for VF=1 does not make any sense.
2607 assert(VF.isVector() && !Scalars.contains(VF) &&
2608 "This function should not be visited twice for the same VF");
2609
2610 // This avoids any chances of creating a REPLICATE recipe during planning
2611 // since that would result in generation of scalarized code during execution,
2612 // which is not supported for scalable vectors.
2613 if (VF.isScalable()) {
2614 Scalars[VF].insert_range(Uniforms[VF]);
2615 return;
2616 }
2617
2619
2620 // These sets are used to seed the analysis with pointers used by memory
2621 // accesses that will remain scalar.
2623 SmallPtrSet<Instruction *, 8> PossibleNonScalarPtrs;
2624 auto *Latch = TheLoop->getLoopLatch();
2625
2626 // A helper that returns true if the use of Ptr by MemAccess will be scalar.
2627 // The pointer operands of loads and stores will be scalar as long as the
2628 // memory access is not a gather or scatter operation. The value operand of a
2629 // store will remain scalar if the store is scalarized.
2630 auto IsScalarUse = [&](Instruction *MemAccess, Value *Ptr) {
2631 InstWidening WideningDecision = getWideningDecision(MemAccess, VF);
2632 assert(WideningDecision != CM_Unknown &&
2633 "Widening decision should be ready at this moment");
2634 if (auto *Store = dyn_cast<StoreInst>(MemAccess))
2635 if (Ptr == Store->getValueOperand())
2636 return WideningDecision == CM_Scalarize;
2637 assert(Ptr == getLoadStorePointerOperand(MemAccess) &&
2638 "Ptr is neither a value or pointer operand");
2639 return WideningDecision != CM_GatherScatter;
2640 };
2641
2642 // A helper that returns true if the given value is a getelementptr
2643 // instruction contained in the loop.
2644 auto IsLoopVaryingGEP = [&](Value *V) {
2645 return isa<GetElementPtrInst>(V) && !TheLoop->isLoopInvariant(V);
2646 };
2647
2648 // A helper that evaluates a memory access's use of a pointer. If the use will
2649 // be a scalar use and the pointer is only used by memory accesses, we place
2650 // the pointer in ScalarPtrs. Otherwise, the pointer is placed in
2651 // PossibleNonScalarPtrs.
2652 auto EvaluatePtrUse = [&](Instruction *MemAccess, Value *Ptr) {
2653 // We only care about bitcast and getelementptr instructions contained in
2654 // the loop.
2655 if (!IsLoopVaryingGEP(Ptr))
2656 return;
2657
2658 // If the pointer has already been identified as scalar (e.g., if it was
2659 // also identified as uniform), there's nothing to do.
2660 auto *I = cast<Instruction>(Ptr);
2661 if (Worklist.count(I))
2662 return;
2663
2664 // If the use of the pointer will be a scalar use, and all users of the
2665 // pointer are memory accesses, place the pointer in ScalarPtrs. Otherwise,
2666 // place the pointer in PossibleNonScalarPtrs.
2667 if (IsScalarUse(MemAccess, Ptr) &&
2668 all_of(I->users(), IsaPred<LoadInst, StoreInst>))
2669 ScalarPtrs.insert(I);
2670 else
2671 PossibleNonScalarPtrs.insert(I);
2672 };
2673
2674 // We seed the scalars analysis with three classes of instructions: (1)
2675 // instructions marked uniform-after-vectorization and (2) bitcast,
2676 // getelementptr and (pointer) phi instructions used by memory accesses
2677 // requiring a scalar use.
2678 //
2679 // (1) Add to the worklist all instructions that have been identified as
2680 // uniform-after-vectorization.
2681 Worklist.insert_range(Uniforms[VF]);
2682
2683 // (2) Add to the worklist all bitcast and getelementptr instructions used by
2684 // memory accesses requiring a scalar use. The pointer operands of loads and
2685 // stores will be scalar unless the operation is a gather or scatter.
2686 // The value operand of a store will remain scalar if the store is scalarized.
2687 for (auto *BB : TheLoop->blocks())
2688 for (auto &I : *BB) {
2689 if (auto *Load = dyn_cast<LoadInst>(&I)) {
2690 EvaluatePtrUse(Load, Load->getPointerOperand());
2691 } else if (auto *Store = dyn_cast<StoreInst>(&I)) {
2692 EvaluatePtrUse(Store, Store->getPointerOperand());
2693 EvaluatePtrUse(Store, Store->getValueOperand());
2694 }
2695 }
2696 for (auto *I : ScalarPtrs)
2697 if (!PossibleNonScalarPtrs.count(I)) {
2698 LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *I << "\n");
2699 Worklist.insert(I);
2700 }
2701
2702 // Insert the forced scalars.
2703 // FIXME: Currently VPWidenPHIRecipe() often creates a dead vector
2704 // induction variable when the PHI user is scalarized.
2705 auto ForcedScalar = ForcedScalars.find(VF);
2706 if (ForcedScalar != ForcedScalars.end())
2707 for (auto *I : ForcedScalar->second) {
2708 LLVM_DEBUG(dbgs() << "LV: Found (forced) scalar instruction: " << *I << "\n");
2709 Worklist.insert(I);
2710 }
2711
2712 // Expand the worklist by looking through any bitcasts and getelementptr
2713 // instructions we've already identified as scalar. This is similar to the
2714 // expansion step in collectLoopUniforms(); however, here we're only
2715 // expanding to include additional bitcasts and getelementptr instructions.
2716 unsigned Idx = 0;
2717 while (Idx != Worklist.size()) {
2718 Instruction *Dst = Worklist[Idx++];
2719 if (!IsLoopVaryingGEP(Dst->getOperand(0)))
2720 continue;
2721 auto *Src = cast<Instruction>(Dst->getOperand(0));
2722 if (llvm::all_of(Src->users(), [&](User *U) -> bool {
2723 auto *J = cast<Instruction>(U);
2724 return !TheLoop->contains(J) || Worklist.count(J) ||
2725 ((isa<LoadInst>(J) || isa<StoreInst>(J)) &&
2726 IsScalarUse(J, Src));
2727 })) {
2728 Worklist.insert(Src);
2729 LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *Src << "\n");
2730 }
2731 }
2732
2733 // An induction variable will remain scalar if all users of the induction
2734 // variable and induction variable update remain scalar.
2735 for (const auto &Induction : Legal->getInductionVars()) {
2736 auto *Ind = Induction.first;
2737 auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
2738
2739 // If tail-folding is applied, the primary induction variable will be used
2740 // to feed a vector compare.
2741 if (Ind == Legal->getPrimaryInduction() && foldTailByMasking())
2742 continue;
2743
2744 // Returns true if \p Indvar is a pointer induction that is used directly by
2745 // load/store instruction \p I.
2746 auto IsDirectLoadStoreFromPtrIndvar = [&](Instruction *Indvar,
2747 Instruction *I) {
2748 return Induction.second.getKind() ==
2750 (isa<LoadInst>(I) || isa<StoreInst>(I)) &&
2751 Indvar == getLoadStorePointerOperand(I) && IsScalarUse(I, Indvar);
2752 };
2753
2754 // Determine if all users of the induction variable are scalar after
2755 // vectorization.
2756 bool ScalarInd = all_of(Ind->users(), [&](User *U) -> bool {
2757 auto *I = cast<Instruction>(U);
2758 return I == IndUpdate || !TheLoop->contains(I) || Worklist.count(I) ||
2759 IsDirectLoadStoreFromPtrIndvar(Ind, I);
2760 });
2761 if (!ScalarInd)
2762 continue;
2763
2764 // If the induction variable update is a fixed-order recurrence, neither the
2765 // induction variable or its update should be marked scalar after
2766 // vectorization.
2767 auto *IndUpdatePhi = dyn_cast<PHINode>(IndUpdate);
2768 if (IndUpdatePhi && Legal->isFixedOrderRecurrence(IndUpdatePhi))
2769 continue;
2770
2771 // Determine if all users of the induction variable update instruction are
2772 // scalar after vectorization.
2773 bool ScalarIndUpdate = all_of(IndUpdate->users(), [&](User *U) -> bool {
2774 auto *I = cast<Instruction>(U);
2775 return I == Ind || !TheLoop->contains(I) || Worklist.count(I) ||
2776 IsDirectLoadStoreFromPtrIndvar(IndUpdate, I);
2777 });
2778 if (!ScalarIndUpdate)
2779 continue;
2780
2781 // The induction variable and its update instruction will remain scalar.
2782 Worklist.insert(Ind);
2783 Worklist.insert(IndUpdate);
2784 LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *Ind << "\n");
2785 LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *IndUpdate
2786 << "\n");
2787 }
2788
2789 Scalars[VF].insert_range(Worklist);
2790}
2791
2793 Instruction *I, ElementCount VF) const {
2794 if (!isPredicatedInst(I))
2795 return false;
2796
2797 // Do we have a non-scalar lowering for this predicated
2798 // instruction? No - it is scalar with predication.
2799 switch(I->getOpcode()) {
2800 default:
2801 return true;
2802 case Instruction::Call:
2803 if (VF.isScalar())
2804 return true;
2805 return getCallWideningDecision(cast<CallInst>(I), VF).Kind == CM_Scalarize;
2806 case Instruction::Load:
2807 case Instruction::Store: {
2809 auto *Ty = getLoadStoreType(I);
2810 unsigned AS = getLoadStoreAddressSpace(I);
2811 Type *VTy = Ty;
2812 if (VF.isVector())
2813 VTy = VectorType::get(Ty, VF);
2814 const Align Alignment = getLoadStoreAlignment(I);
2815 return isa<LoadInst>(I) ? !(isLegalMaskedLoad(Ty, Ptr, Alignment, AS) ||
2816 TTI.isLegalMaskedGather(VTy, Alignment))
2817 : !(isLegalMaskedStore(Ty, Ptr, Alignment, AS) ||
2818 TTI.isLegalMaskedScatter(VTy, Alignment));
2819 }
2820 case Instruction::UDiv:
2821 case Instruction::SDiv:
2822 case Instruction::SRem:
2823 case Instruction::URem: {
2824 // We have the option to use the safe-divisor idiom to avoid predication.
2825 // The cost based decision here will always select safe-divisor for
2826 // scalable vectors as scalarization isn't legal.
2827 const auto [ScalarCost, SafeDivisorCost] = getDivRemSpeculationCost(I, VF);
2828 return isDivRemScalarWithPredication(ScalarCost, SafeDivisorCost);
2829 }
2830 }
2831}
2832
2833// TODO: Fold into LoopVectorizationLegality::isMaskRequired.
2835 // TODO: We can use the loop-preheader as context point here and get
2836 // context sensitive reasoning for isSafeToSpeculativelyExecute.
2838 (isa<LoadInst, StoreInst, CallInst>(I) && !Legal->isMaskRequired(I)) ||
2839 isa<BranchInst, SwitchInst, PHINode, AllocaInst>(I))
2840 return false;
2841
2842 // If the instruction was executed conditionally in the original scalar loop,
2843 // predication is needed with a mask whose lanes are all possibly inactive.
2844 if (Legal->blockNeedsPredication(I->getParent()))
2845 return true;
2846
2847 // If we're not folding the tail by masking, predication is unnecessary.
2848 if (!foldTailByMasking())
2849 return false;
2850
2851 // All that remain are instructions with side-effects originally executed in
2852 // the loop unconditionally, but now execute under a tail-fold mask (only)
2853 // having at least one active lane (the first). If the side-effects of the
2854 // instruction are invariant, executing it w/o (the tail-folding) mask is safe
2855 // - it will cause the same side-effects as when masked.
2856 switch(I->getOpcode()) {
2857 default:
2859 "instruction should have been considered by earlier checks");
2860 case Instruction::Call:
2861 // Side-effects of a Call are assumed to be non-invariant, needing a
2862 // (fold-tail) mask.
2863 assert(Legal->isMaskRequired(I) &&
2864 "should have returned earlier for calls not needing a mask");
2865 return true;
2866 case Instruction::Load:
2867 // If the address is loop invariant no predication is needed.
2868 return !Legal->isInvariant(getLoadStorePointerOperand(I));
2869 case Instruction::Store: {
2870 // For stores, we need to prove both speculation safety (which follows from
2871 // the same argument as loads), but also must prove the value being stored
2872 // is correct. The easiest form of the later is to require that all values
2873 // stored are the same.
2874 return !(Legal->isInvariant(getLoadStorePointerOperand(I)) &&
2875 TheLoop->isLoopInvariant(cast<StoreInst>(I)->getValueOperand()));
2876 }
2877 case Instruction::UDiv:
2878 case Instruction::SDiv:
2879 case Instruction::SRem:
2880 case Instruction::URem:
2881 // If the divisor is loop-invariant no predication is needed.
2882 return !Legal->isInvariant(I->getOperand(1));
2883 }
2884}
2885
2886std::pair<InstructionCost, InstructionCost>
2888 ElementCount VF) const {
2889 assert(I->getOpcode() == Instruction::UDiv ||
2890 I->getOpcode() == Instruction::SDiv ||
2891 I->getOpcode() == Instruction::SRem ||
2892 I->getOpcode() == Instruction::URem);
2894
2895 // Scalarization isn't legal for scalable vector types
2896 InstructionCost ScalarizationCost = InstructionCost::getInvalid();
2897 if (!VF.isScalable()) {
2898 // Get the scalarization cost and scale this amount by the probability of
2899 // executing the predicated block. If the instruction is not predicated,
2900 // we fall through to the next case.
2901 ScalarizationCost = 0;
2902
2903 // These instructions have a non-void type, so account for the phi nodes
2904 // that we will create. This cost is likely to be zero. The phi node
2905 // cost, if any, should be scaled by the block probability because it
2906 // models a copy at the end of each predicated block.
2907 ScalarizationCost +=
2908 VF.getFixedValue() * TTI.getCFInstrCost(Instruction::PHI, CostKind);
2909
2910 // The cost of the non-predicated instruction.
2911 ScalarizationCost +=
2912 VF.getFixedValue() *
2913 TTI.getArithmeticInstrCost(I->getOpcode(), I->getType(), CostKind);
2914
2915 // The cost of insertelement and extractelement instructions needed for
2916 // scalarization.
2917 ScalarizationCost += getScalarizationOverhead(I, VF);
2918
2919 // Scale the cost by the probability of executing the predicated blocks.
2920 // This assumes the predicated block for each vector lane is equally
2921 // likely.
2922 ScalarizationCost = ScalarizationCost / getPredBlockCostDivisor(CostKind);
2923 }
2924 InstructionCost SafeDivisorCost = 0;
2925
2926 auto *VecTy = toVectorTy(I->getType(), VF);
2927
2928 // The cost of the select guard to ensure all lanes are well defined
2929 // after we speculate above any internal control flow.
2930 SafeDivisorCost +=
2931 TTI.getCmpSelInstrCost(Instruction::Select, VecTy,
2932 toVectorTy(Type::getInt1Ty(I->getContext()), VF),
2934
2935 // Certain instructions can be cheaper to vectorize if they have a constant
2936 // second vector operand. One example of this are shifts on x86.
2937 Value *Op2 = I->getOperand(1);
2938 auto Op2Info = TTI.getOperandInfo(Op2);
2939 if (Op2Info.Kind == TargetTransformInfo::OK_AnyValue &&
2940 Legal->isInvariant(Op2))
2942
2943 SmallVector<const Value *, 4> Operands(I->operand_values());
2944 SafeDivisorCost += TTI.getArithmeticInstrCost(
2945 I->getOpcode(), VecTy, CostKind,
2946 {TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None},
2947 Op2Info, Operands, I);
2948 return {ScalarizationCost, SafeDivisorCost};
2949}
2950
2952 Instruction *I, ElementCount VF) const {
2953 assert(isAccessInterleaved(I) && "Expecting interleaved access.");
2954 assert(getWideningDecision(I, VF) == CM_Unknown &&
2955 "Decision should not be set yet.");
2956 auto *Group = getInterleavedAccessGroup(I);
2957 assert(Group && "Must have a group.");
2958 unsigned InterleaveFactor = Group->getFactor();
2959
2960 // If the instruction's allocated size doesn't equal its type size, it
2961 // requires padding and will be scalarized.
2962 auto &DL = I->getDataLayout();
2963 auto *ScalarTy = getLoadStoreType(I);
2964 if (hasIrregularType(ScalarTy, DL))
2965 return false;
2966
2967 // For scalable vectors, the interleave factors must be <= 8 since we require
2968 // the (de)interleaveN intrinsics instead of shufflevectors.
2969 if (VF.isScalable() && InterleaveFactor > 8)
2970 return false;
2971
2972 // If the group involves a non-integral pointer, we may not be able to
2973 // losslessly cast all values to a common type.
2974 bool ScalarNI = DL.isNonIntegralPointerType(ScalarTy);
2975 for (unsigned Idx = 0; Idx < InterleaveFactor; Idx++) {
2976 Instruction *Member = Group->getMember(Idx);
2977 if (!Member)
2978 continue;
2979 auto *MemberTy = getLoadStoreType(Member);
2980 bool MemberNI = DL.isNonIntegralPointerType(MemberTy);
2981 // Don't coerce non-integral pointers to integers or vice versa.
2982 if (MemberNI != ScalarNI)
2983 // TODO: Consider adding special nullptr value case here
2984 return false;
2985 if (MemberNI && ScalarNI &&
2986 ScalarTy->getPointerAddressSpace() !=
2987 MemberTy->getPointerAddressSpace())
2988 return false;
2989 }
2990
2991 // Check if masking is required.
2992 // A Group may need masking for one of two reasons: it resides in a block that
2993 // needs predication, or it was decided to use masking to deal with gaps
2994 // (either a gap at the end of a load-access that may result in a speculative
2995 // load, or any gaps in a store-access).
2996 bool PredicatedAccessRequiresMasking =
2997 blockNeedsPredicationForAnyReason(I->getParent()) &&
2998 Legal->isMaskRequired(I);
2999 bool LoadAccessWithGapsRequiresEpilogMasking =
3000 isa<LoadInst>(I) && Group->requiresScalarEpilogue() &&
3001 !isScalarEpilogueAllowed();
3002 bool StoreAccessWithGapsRequiresMasking =
3003 isa<StoreInst>(I) && !Group->isFull();
3004 if (!PredicatedAccessRequiresMasking &&
3005 !LoadAccessWithGapsRequiresEpilogMasking &&
3006 !StoreAccessWithGapsRequiresMasking)
3007 return true;
3008
3009 // If masked interleaving is required, we expect that the user/target had
3010 // enabled it, because otherwise it either wouldn't have been created or
3011 // it should have been invalidated by the CostModel.
3013 "Masked interleave-groups for predicated accesses are not enabled.");
3014
3015 if (Group->isReverse())
3016 return false;
3017
3018 // TODO: Support interleaved access that requires a gap mask for scalable VFs.
3019 bool NeedsMaskForGaps = LoadAccessWithGapsRequiresEpilogMasking ||
3020 StoreAccessWithGapsRequiresMasking;
3021 if (VF.isScalable() && NeedsMaskForGaps)
3022 return false;
3023
3024 auto *Ty = getLoadStoreType(I);
3025 const Align Alignment = getLoadStoreAlignment(I);
3026 unsigned AS = getLoadStoreAddressSpace(I);
3027 return isa<LoadInst>(I) ? TTI.isLegalMaskedLoad(Ty, Alignment, AS)
3028 : TTI.isLegalMaskedStore(Ty, Alignment, AS);
3029}
3030
3033 // Get and ensure we have a valid memory instruction.
3034 assert((isa<LoadInst, StoreInst>(I)) && "Invalid memory instruction");
3035
3037 auto *ScalarTy = getLoadStoreType(I);
3038
3039 // In order to be widened, the pointer should be consecutive, first of all.
3040 if (!Legal->isConsecutivePtr(ScalarTy, Ptr))
3041 return false;
3042
3043 // If the instruction is a store located in a predicated block, it will be
3044 // scalarized.
3045 if (isScalarWithPredication(I, VF))
3046 return false;
3047
3048 // If the instruction's allocated size doesn't equal it's type size, it
3049 // requires padding and will be scalarized.
3050 auto &DL = I->getDataLayout();
3051 if (hasIrregularType(ScalarTy, DL))
3052 return false;
3053
3054 return true;
3055}
3056
3057void LoopVectorizationCostModel::collectLoopUniforms(ElementCount VF) {
3058 // We should not collect Uniforms more than once per VF. Right now,
3059 // this function is called from collectUniformsAndScalars(), which
3060 // already does this check. Collecting Uniforms for VF=1 does not make any
3061 // sense.
3062
3063 assert(VF.isVector() && !Uniforms.contains(VF) &&
3064 "This function should not be visited twice for the same VF");
3065
3066 // Visit the list of Uniforms. If we find no uniform value, we won't
3067 // analyze again. Uniforms.count(VF) will return 1.
3068 Uniforms[VF].clear();
3069
3070 // Now we know that the loop is vectorizable!
3071 // Collect instructions inside the loop that will remain uniform after
3072 // vectorization.
3073
3074 // Global values, params and instructions outside of current loop are out of
3075 // scope.
3076 auto IsOutOfScope = [&](Value *V) -> bool {
3077 Instruction *I = dyn_cast<Instruction>(V);
3078 return (!I || !TheLoop->contains(I));
3079 };
3080
3081 // Worklist containing uniform instructions demanding lane 0.
3082 SetVector<Instruction *> Worklist;
3083
3084 // Add uniform instructions demanding lane 0 to the worklist. Instructions
3085 // that require predication must not be considered uniform after
3086 // vectorization, because that would create an erroneous replicating region
3087 // where only a single instance out of VF should be formed.
3088 auto AddToWorklistIfAllowed = [&](Instruction *I) -> void {
3089 if (IsOutOfScope(I)) {
3090 LLVM_DEBUG(dbgs() << "LV: Found not uniform due to scope: "
3091 << *I << "\n");
3092 return;
3093 }
3094 if (isPredicatedInst(I)) {
3095 LLVM_DEBUG(
3096 dbgs() << "LV: Found not uniform due to requiring predication: " << *I
3097 << "\n");
3098 return;
3099 }
3100 LLVM_DEBUG(dbgs() << "LV: Found uniform instruction: " << *I << "\n");
3101 Worklist.insert(I);
3102 };
3103
3104 // Start with the conditional branches exiting the loop. If the branch
3105 // condition is an instruction contained in the loop that is only used by the
3106 // branch, it is uniform. Note conditions from uncountable early exits are not
3107 // uniform.
3109 TheLoop->getExitingBlocks(Exiting);
3110 for (BasicBlock *E : Exiting) {
3111 if (Legal->hasUncountableEarlyExit() && TheLoop->getLoopLatch() != E)
3112 continue;
3113 auto *Cmp = dyn_cast<Instruction>(E->getTerminator()->getOperand(0));
3114 if (Cmp && TheLoop->contains(Cmp) && Cmp->hasOneUse())
3115 AddToWorklistIfAllowed(Cmp);
3116 }
3117
3118 auto PrevVF = VF.divideCoefficientBy(2);
3119 // Return true if all lanes perform the same memory operation, and we can
3120 // thus choose to execute only one.
3121 auto IsUniformMemOpUse = [&](Instruction *I) {
3122 // If the value was already known to not be uniform for the previous
3123 // (smaller VF), it cannot be uniform for the larger VF.
3124 if (PrevVF.isVector()) {
3125 auto Iter = Uniforms.find(PrevVF);
3126 if (Iter != Uniforms.end() && !Iter->second.contains(I))
3127 return false;
3128 }
3129 if (!Legal->isUniformMemOp(*I, VF))
3130 return false;
3131 if (isa<LoadInst>(I))
3132 // Loading the same address always produces the same result - at least
3133 // assuming aliasing and ordering which have already been checked.
3134 return true;
3135 // Storing the same value on every iteration.
3136 return TheLoop->isLoopInvariant(cast<StoreInst>(I)->getValueOperand());
3137 };
3138
3139 auto IsUniformDecision = [&](Instruction *I, ElementCount VF) {
3140 InstWidening WideningDecision = getWideningDecision(I, VF);
3141 assert(WideningDecision != CM_Unknown &&
3142 "Widening decision should be ready at this moment");
3143
3144 if (IsUniformMemOpUse(I))
3145 return true;
3146
3147 return (WideningDecision == CM_Widen ||
3148 WideningDecision == CM_Widen_Reverse ||
3149 WideningDecision == CM_Interleave);
3150 };
3151
3152 // Returns true if Ptr is the pointer operand of a memory access instruction
3153 // I, I is known to not require scalarization, and the pointer is not also
3154 // stored.
3155 auto IsVectorizedMemAccessUse = [&](Instruction *I, Value *Ptr) -> bool {
3156 if (isa<StoreInst>(I) && I->getOperand(0) == Ptr)
3157 return false;
3158 return getLoadStorePointerOperand(I) == Ptr &&
3159 (IsUniformDecision(I, VF) || Legal->isInvariant(Ptr));
3160 };
3161
3162 // Holds a list of values which are known to have at least one uniform use.
3163 // Note that there may be other uses which aren't uniform. A "uniform use"
3164 // here is something which only demands lane 0 of the unrolled iterations;
3165 // it does not imply that all lanes produce the same value (e.g. this is not
3166 // the usual meaning of uniform)
3167 SetVector<Value *> HasUniformUse;
3168
3169 // Scan the loop for instructions which are either a) known to have only
3170 // lane 0 demanded or b) are uses which demand only lane 0 of their operand.
3171 for (auto *BB : TheLoop->blocks())
3172 for (auto &I : *BB) {
3173 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I)) {
3174 switch (II->getIntrinsicID()) {
3175 case Intrinsic::sideeffect:
3176 case Intrinsic::experimental_noalias_scope_decl:
3177 case Intrinsic::assume:
3178 case Intrinsic::lifetime_start:
3179 case Intrinsic::lifetime_end:
3180 if (TheLoop->hasLoopInvariantOperands(&I))
3181 AddToWorklistIfAllowed(&I);
3182 break;
3183 default:
3184 break;
3185 }
3186 }
3187
3188 if (auto *EVI = dyn_cast<ExtractValueInst>(&I)) {
3189 if (IsOutOfScope(EVI->getAggregateOperand())) {
3190 AddToWorklistIfAllowed(EVI);
3191 continue;
3192 }
3193 // Only ExtractValue instructions where the aggregate value comes from a
3194 // call are allowed to be non-uniform.
3195 assert(isa<CallInst>(EVI->getAggregateOperand()) &&
3196 "Expected aggregate value to be call return value");
3197 }
3198
3199 // If there's no pointer operand, there's nothing to do.
3201 if (!Ptr)
3202 continue;
3203
3204 if (IsUniformMemOpUse(&I))
3205 AddToWorklistIfAllowed(&I);
3206
3207 if (IsVectorizedMemAccessUse(&I, Ptr))
3208 HasUniformUse.insert(Ptr);
3209 }
3210
3211 // Add to the worklist any operands which have *only* uniform (e.g. lane 0
3212 // demanding) users. Since loops are assumed to be in LCSSA form, this
3213 // disallows uses outside the loop as well.
3214 for (auto *V : HasUniformUse) {
3215 if (IsOutOfScope(V))
3216 continue;
3217 auto *I = cast<Instruction>(V);
3218 bool UsersAreMemAccesses = all_of(I->users(), [&](User *U) -> bool {
3219 auto *UI = cast<Instruction>(U);
3220 return TheLoop->contains(UI) && IsVectorizedMemAccessUse(UI, V);
3221 });
3222 if (UsersAreMemAccesses)
3223 AddToWorklistIfAllowed(I);
3224 }
3225
3226 // Expand Worklist in topological order: whenever a new instruction
3227 // is added , its users should be already inside Worklist. It ensures
3228 // a uniform instruction will only be used by uniform instructions.
3229 unsigned Idx = 0;
3230 while (Idx != Worklist.size()) {
3231 Instruction *I = Worklist[Idx++];
3232
3233 for (auto *OV : I->operand_values()) {
3234 // isOutOfScope operands cannot be uniform instructions.
3235 if (IsOutOfScope(OV))
3236 continue;
3237 // First order recurrence Phi's should typically be considered
3238 // non-uniform.
3239 auto *OP = dyn_cast<PHINode>(OV);
3240 if (OP && Legal->isFixedOrderRecurrence(OP))
3241 continue;
3242 // If all the users of the operand are uniform, then add the
3243 // operand into the uniform worklist.
3244 auto *OI = cast<Instruction>(OV);
3245 if (llvm::all_of(OI->users(), [&](User *U) -> bool {
3246 auto *J = cast<Instruction>(U);
3247 return Worklist.count(J) || IsVectorizedMemAccessUse(J, OI);
3248 }))
3249 AddToWorklistIfAllowed(OI);
3250 }
3251 }
3252
3253 // For an instruction to be added into Worklist above, all its users inside
3254 // the loop should also be in Worklist. However, this condition cannot be
3255 // true for phi nodes that form a cyclic dependence. We must process phi
3256 // nodes separately. An induction variable will remain uniform if all users
3257 // of the induction variable and induction variable update remain uniform.
3258 // The code below handles both pointer and non-pointer induction variables.
3259 BasicBlock *Latch = TheLoop->getLoopLatch();
3260 for (const auto &Induction : Legal->getInductionVars()) {
3261 auto *Ind = Induction.first;
3262 auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
3263
3264 // Determine if all users of the induction variable are uniform after
3265 // vectorization.
3266 bool UniformInd = all_of(Ind->users(), [&](User *U) -> bool {
3267 auto *I = cast<Instruction>(U);
3268 return I == IndUpdate || !TheLoop->contains(I) || Worklist.count(I) ||
3269 IsVectorizedMemAccessUse(I, Ind);
3270 });
3271 if (!UniformInd)
3272 continue;
3273
3274 // Determine if all users of the induction variable update instruction are
3275 // uniform after vectorization.
3276 bool UniformIndUpdate = all_of(IndUpdate->users(), [&](User *U) -> bool {
3277 auto *I = cast<Instruction>(U);
3278 return I == Ind || Worklist.count(I) ||
3279 IsVectorizedMemAccessUse(I, IndUpdate);
3280 });
3281 if (!UniformIndUpdate)
3282 continue;
3283
3284 // The induction variable and its update instruction will remain uniform.
3285 AddToWorklistIfAllowed(Ind);
3286 AddToWorklistIfAllowed(IndUpdate);
3287 }
3288
3289 Uniforms[VF].insert_range(Worklist);
3290}
3291
3293 LLVM_DEBUG(dbgs() << "LV: Performing code size checks.\n");
3294
3295 if (Legal->getRuntimePointerChecking()->Need) {
3296 reportVectorizationFailure("Runtime ptr check is required with -Os/-Oz",
3297 "runtime pointer checks needed. Enable vectorization of this "
3298 "loop with '#pragma clang loop vectorize(enable)' when "
3299 "compiling with -Os/-Oz",
3300 "CantVersionLoopWithOptForSize", ORE, TheLoop);
3301 return true;
3302 }
3303
3304 if (!PSE.getPredicate().isAlwaysTrue()) {
3305 reportVectorizationFailure("Runtime SCEV check is required with -Os/-Oz",
3306 "runtime SCEV checks needed. Enable vectorization of this "
3307 "loop with '#pragma clang loop vectorize(enable)' when "
3308 "compiling with -Os/-Oz",
3309 "CantVersionLoopWithOptForSize", ORE, TheLoop);
3310 return true;
3311 }
3312
3313 // FIXME: Avoid specializing for stride==1 instead of bailing out.
3314 if (!Legal->getLAI()->getSymbolicStrides().empty()) {
3315 reportVectorizationFailure("Runtime stride check for small trip count",
3316 "runtime stride == 1 checks needed. Enable vectorization of "
3317 "this loop without such check by compiling with -Os/-Oz",
3318 "CantVersionLoopWithOptForSize", ORE, TheLoop);
3319 return true;
3320 }
3321
3322 return false;
3323}
3324
3325bool LoopVectorizationCostModel::isScalableVectorizationAllowed() {
3326 if (IsScalableVectorizationAllowed)
3327 return *IsScalableVectorizationAllowed;
3328
3329 IsScalableVectorizationAllowed = false;
3331 return false;
3332
3333 if (Hints->isScalableVectorizationDisabled()) {
3334 reportVectorizationInfo("Scalable vectorization is explicitly disabled",
3335 "ScalableVectorizationDisabled", ORE, TheLoop);
3336 return false;
3337 }
3338
3339 LLVM_DEBUG(dbgs() << "LV: Scalable vectorization is available\n");
3340
3341 auto MaxScalableVF = ElementCount::getScalable(
3342 std::numeric_limits<ElementCount::ScalarTy>::max());
3343
3344 // Test that the loop-vectorizer can legalize all operations for this MaxVF.
3345 // FIXME: While for scalable vectors this is currently sufficient, this should
3346 // be replaced by a more detailed mechanism that filters out specific VFs,
3347 // instead of invalidating vectorization for a whole set of VFs based on the
3348 // MaxVF.
3349
3350 // Disable scalable vectorization if the loop contains unsupported reductions.
3351 if (!canVectorizeReductions(MaxScalableVF)) {
3353 "Scalable vectorization not supported for the reduction "
3354 "operations found in this loop.",
3355 "ScalableVFUnfeasible", ORE, TheLoop);
3356 return false;
3357 }
3358
3359 // Disable scalable vectorization if the loop contains any instructions
3360 // with element types not supported for scalable vectors.
3361 if (any_of(ElementTypesInLoop, [&](Type *Ty) {
3362 return !Ty->isVoidTy() &&
3364 })) {
3365 reportVectorizationInfo("Scalable vectorization is not supported "
3366 "for all element types found in this loop.",
3367 "ScalableVFUnfeasible", ORE, TheLoop);
3368 return false;
3369 }
3370
3371 if (!Legal->isSafeForAnyVectorWidth() && !getMaxVScale(*TheFunction, TTI)) {
3372 reportVectorizationInfo("The target does not provide maximum vscale value "
3373 "for safe distance analysis.",
3374 "ScalableVFUnfeasible", ORE, TheLoop);
3375 return false;
3376 }
3377
3378 IsScalableVectorizationAllowed = true;
3379 return true;
3380}
3381
3383LoopVectorizationCostModel::getMaxLegalScalableVF(unsigned MaxSafeElements) {
3384 if (!isScalableVectorizationAllowed())
3385 return ElementCount::getScalable(0);
3386
3387 auto MaxScalableVF = ElementCount::getScalable(
3388 std::numeric_limits<ElementCount::ScalarTy>::max());
3389 if (Legal->isSafeForAnyVectorWidth())
3390 return MaxScalableVF;
3391
3392 std::optional<unsigned> MaxVScale = getMaxVScale(*TheFunction, TTI);
3393 // Limit MaxScalableVF by the maximum safe dependence distance.
3394 MaxScalableVF = ElementCount::getScalable(MaxSafeElements / *MaxVScale);
3395
3396 if (!MaxScalableVF)
3398 "Max legal vector width too small, scalable vectorization "
3399 "unfeasible.",
3400 "ScalableVFUnfeasible", ORE, TheLoop);
3401
3402 return MaxScalableVF;
3403}
3404
3405FixedScalableVFPair LoopVectorizationCostModel::computeFeasibleMaxVF(
3406 unsigned MaxTripCount, ElementCount UserVF, bool FoldTailByMasking) {
3407 MinBWs = computeMinimumValueSizes(TheLoop->getBlocks(), *DB, &TTI);
3408 unsigned SmallestType, WidestType;
3409 std::tie(SmallestType, WidestType) = getSmallestAndWidestTypes();
3410
3411 // Get the maximum safe dependence distance in bits computed by LAA.
3412 // It is computed by MaxVF * sizeOf(type) * 8, where type is taken from
3413 // the memory accesses that is most restrictive (involved in the smallest
3414 // dependence distance).
3415 unsigned MaxSafeElementsPowerOf2 =
3416 bit_floor(Legal->getMaxSafeVectorWidthInBits() / WidestType);
3417 if (!Legal->isSafeForAnyStoreLoadForwardDistances()) {
3418 unsigned SLDist = Legal->getMaxStoreLoadForwardSafeDistanceInBits();
3419 MaxSafeElementsPowerOf2 =
3420 std::min(MaxSafeElementsPowerOf2, SLDist / WidestType);
3421 }
3422 auto MaxSafeFixedVF = ElementCount::getFixed(MaxSafeElementsPowerOf2);
3423 auto MaxSafeScalableVF = getMaxLegalScalableVF(MaxSafeElementsPowerOf2);
3424
3425 if (!Legal->isSafeForAnyVectorWidth())
3426 this->MaxSafeElements = MaxSafeElementsPowerOf2;
3427
3428 LLVM_DEBUG(dbgs() << "LV: The max safe fixed VF is: " << MaxSafeFixedVF
3429 << ".\n");
3430 LLVM_DEBUG(dbgs() << "LV: The max safe scalable VF is: " << MaxSafeScalableVF
3431 << ".\n");
3432
3433 // First analyze the UserVF, fall back if the UserVF should be ignored.
3434 if (UserVF) {
3435 auto MaxSafeUserVF =
3436 UserVF.isScalable() ? MaxSafeScalableVF : MaxSafeFixedVF;
3437
3438 if (ElementCount::isKnownLE(UserVF, MaxSafeUserVF)) {
3439 // If `VF=vscale x N` is safe, then so is `VF=N`
3440 if (UserVF.isScalable())
3441 return FixedScalableVFPair(
3442 ElementCount::getFixed(UserVF.getKnownMinValue()), UserVF);
3443
3444 return UserVF;
3445 }
3446
3447 assert(ElementCount::isKnownGT(UserVF, MaxSafeUserVF));
3448
3449 // Only clamp if the UserVF is not scalable. If the UserVF is scalable, it
3450 // is better to ignore the hint and let the compiler choose a suitable VF.
3451 if (!UserVF.isScalable()) {
3452 LLVM_DEBUG(dbgs() << "LV: User VF=" << UserVF
3453 << " is unsafe, clamping to max safe VF="
3454 << MaxSafeFixedVF << ".\n");
3455 ORE->emit([&]() {
3456 return OptimizationRemarkAnalysis(DEBUG_TYPE, "VectorizationFactor",
3457 TheLoop->getStartLoc(),
3458 TheLoop->getHeader())
3459 << "User-specified vectorization factor "
3460 << ore::NV("UserVectorizationFactor", UserVF)
3461 << " is unsafe, clamping to maximum safe vectorization factor "
3462 << ore::NV("VectorizationFactor", MaxSafeFixedVF);
3463 });
3464 return MaxSafeFixedVF;
3465 }
3466
3468 LLVM_DEBUG(dbgs() << "LV: User VF=" << UserVF
3469 << " is ignored because scalable vectors are not "
3470 "available.\n");
3471 ORE->emit([&]() {
3472 return OptimizationRemarkAnalysis(DEBUG_TYPE, "VectorizationFactor",
3473 TheLoop->getStartLoc(),
3474 TheLoop->getHeader())
3475 << "User-specified vectorization factor "
3476 << ore::NV("UserVectorizationFactor", UserVF)
3477 << " is ignored because the target does not support scalable "
3478 "vectors. The compiler will pick a more suitable value.";
3479 });
3480 } else {
3481 LLVM_DEBUG(dbgs() << "LV: User VF=" << UserVF
3482 << " is unsafe. Ignoring scalable UserVF.\n");
3483 ORE->emit([&]() {
3484 return OptimizationRemarkAnalysis(DEBUG_TYPE, "VectorizationFactor",
3485 TheLoop->getStartLoc(),
3486 TheLoop->getHeader())
3487 << "User-specified vectorization factor "
3488 << ore::NV("UserVectorizationFactor", UserVF)
3489 << " is unsafe. Ignoring the hint to let the compiler pick a "
3490 "more suitable value.";
3491 });
3492 }
3493 }
3494
3495 LLVM_DEBUG(dbgs() << "LV: The Smallest and Widest types: " << SmallestType
3496 << " / " << WidestType << " bits.\n");
3497
3500 if (auto MaxVF =
3501 getMaximizedVFForTarget(MaxTripCount, SmallestType, WidestType,
3502 MaxSafeFixedVF, FoldTailByMasking))
3503 Result.FixedVF = MaxVF;
3504
3505 if (auto MaxVF =
3506 getMaximizedVFForTarget(MaxTripCount, SmallestType, WidestType,
3507 MaxSafeScalableVF, FoldTailByMasking))
3508 if (MaxVF.isScalable()) {
3509 Result.ScalableVF = MaxVF;
3510 LLVM_DEBUG(dbgs() << "LV: Found feasible scalable VF = " << MaxVF
3511 << "\n");
3512 }
3513
3514 return Result;
3515}
3516
3519 if (Legal->getRuntimePointerChecking()->Need && TTI.hasBranchDivergence()) {
3520 // TODO: It may be useful to do since it's still likely to be dynamically
3521 // uniform if the target can skip.
3523 "Not inserting runtime ptr check for divergent target",
3524 "runtime pointer checks needed. Not enabled for divergent target",
3525 "CantVersionLoopWithDivergentTarget", ORE, TheLoop);
3527 }
3528
3529 ScalarEvolution *SE = PSE.getSE();
3530 ElementCount TC = getSmallConstantTripCount(SE, TheLoop);
3531 unsigned MaxTC = PSE.getSmallConstantMaxTripCount();
3532 LLVM_DEBUG(dbgs() << "LV: Found trip count: " << TC << '\n');
3533 if (TC != ElementCount::getFixed(MaxTC))
3534 LLVM_DEBUG(dbgs() << "LV: Found maximum trip count: " << MaxTC << '\n');
3535 if (TC.isScalar()) {
3536 reportVectorizationFailure("Single iteration (non) loop",
3537 "loop trip count is one, irrelevant for vectorization",
3538 "SingleIterationLoop", ORE, TheLoop);
3540 }
3541
3542 // If BTC matches the widest induction type and is -1 then the trip count
3543 // computation will wrap to 0 and the vector trip count will be 0. Do not try
3544 // to vectorize.
3545 const SCEV *BTC = SE->getBackedgeTakenCount(TheLoop);
3546 if (!isa<SCEVCouldNotCompute>(BTC) &&
3547 BTC->getType()->getScalarSizeInBits() >=
3548 Legal->getWidestInductionType()->getScalarSizeInBits() &&
3550 SE->getMinusOne(BTC->getType()))) {
3552 "Trip count computation wrapped",
3553 "backedge-taken count is -1, loop trip count wrapped to 0",
3554 "TripCountWrapped", ORE, TheLoop);
3556 }
3557
3558 switch (ScalarEpilogueStatus) {
3560 return computeFeasibleMaxVF(MaxTC, UserVF, false);
3562 [[fallthrough]];
3564 LLVM_DEBUG(
3565 dbgs() << "LV: vector predicate hint/switch found.\n"
3566 << "LV: Not allowing scalar epilogue, creating predicated "
3567 << "vector loop.\n");
3568 break;
3570 // fallthrough as a special case of OptForSize
3572 if (ScalarEpilogueStatus == CM_ScalarEpilogueNotAllowedOptSize)
3573 LLVM_DEBUG(
3574 dbgs() << "LV: Not allowing scalar epilogue due to -Os/-Oz.\n");
3575 else
3576 LLVM_DEBUG(dbgs() << "LV: Not allowing scalar epilogue due to low trip "
3577 << "count.\n");
3578
3579 // Bail if runtime checks are required, which are not good when optimising
3580 // for size.
3581 if (runtimeChecksRequired())
3583
3584 break;
3585 }
3586
3587 // Now try the tail folding
3588
3589 // Invalidate interleave groups that require an epilogue if we can't mask
3590 // the interleave-group.
3592 assert(WideningDecisions.empty() && Uniforms.empty() && Scalars.empty() &&
3593 "No decisions should have been taken at this point");
3594 // Note: There is no need to invalidate any cost modeling decisions here, as
3595 // none were taken so far.
3596 InterleaveInfo.invalidateGroupsRequiringScalarEpilogue();
3597 }
3598
3599 FixedScalableVFPair MaxFactors = computeFeasibleMaxVF(MaxTC, UserVF, true);
3600
3601 // Avoid tail folding if the trip count is known to be a multiple of any VF
3602 // we choose.
3603 std::optional<unsigned> MaxPowerOf2RuntimeVF =
3604 MaxFactors.FixedVF.getFixedValue();
3605 if (MaxFactors.ScalableVF) {
3606 std::optional<unsigned> MaxVScale = getMaxVScale(*TheFunction, TTI);
3607 if (MaxVScale && TTI.isVScaleKnownToBeAPowerOfTwo()) {
3608 MaxPowerOf2RuntimeVF = std::max<unsigned>(
3609 *MaxPowerOf2RuntimeVF,
3610 *MaxVScale * MaxFactors.ScalableVF.getKnownMinValue());
3611 } else
3612 MaxPowerOf2RuntimeVF = std::nullopt; // Stick with tail-folding for now.
3613 }
3614
3615 auto NoScalarEpilogueNeeded = [this, &UserIC](unsigned MaxVF) {
3616 // Return false if the loop is neither a single-latch-exit loop nor an
3617 // early-exit loop as tail-folding is not supported in that case.
3618 if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch() &&
3619 !Legal->hasUncountableEarlyExit())
3620 return false;
3621 unsigned MaxVFtimesIC = UserIC ? MaxVF * UserIC : MaxVF;
3622 ScalarEvolution *SE = PSE.getSE();
3623 // Calling getSymbolicMaxBackedgeTakenCount enables support for loops
3624 // with uncountable exits. For countable loops, the symbolic maximum must
3625 // remain identical to the known back-edge taken count.
3626 const SCEV *BackedgeTakenCount = PSE.getSymbolicMaxBackedgeTakenCount();
3627 assert((Legal->hasUncountableEarlyExit() ||
3628 BackedgeTakenCount == PSE.getBackedgeTakenCount()) &&
3629 "Invalid loop count");
3630 const SCEV *ExitCount = SE->getAddExpr(
3631 BackedgeTakenCount, SE->getOne(BackedgeTakenCount->getType()));
3632 const SCEV *Rem = SE->getURemExpr(
3633 SE->applyLoopGuards(ExitCount, TheLoop),
3634 SE->getConstant(BackedgeTakenCount->getType(), MaxVFtimesIC));
3635 return Rem->isZero();
3636 };
3637
3638 if (MaxPowerOf2RuntimeVF > 0u) {
3639 assert((UserVF.isNonZero() || isPowerOf2_32(*MaxPowerOf2RuntimeVF)) &&
3640 "MaxFixedVF must be a power of 2");
3641 if (NoScalarEpilogueNeeded(*MaxPowerOf2RuntimeVF)) {
3642 // Accept MaxFixedVF if we do not have a tail.
3643 LLVM_DEBUG(dbgs() << "LV: No tail will remain for any chosen VF.\n");
3644 return MaxFactors;
3645 }
3646 }
3647
3648 auto ExpectedTC = getSmallBestKnownTC(PSE, TheLoop);
3649 if (ExpectedTC && ExpectedTC->isFixed() &&
3650 ExpectedTC->getFixedValue() <=
3652 if (MaxPowerOf2RuntimeVF > 0u) {
3653 // If we have a low-trip-count, and the fixed-width VF is known to divide
3654 // the trip count but the scalable factor does not, use the fixed-width
3655 // factor in preference to allow the generation of a non-predicated loop.
3656 if (ScalarEpilogueStatus == CM_ScalarEpilogueNotAllowedLowTripLoop &&
3657 NoScalarEpilogueNeeded(MaxFactors.FixedVF.getFixedValue())) {
3658 LLVM_DEBUG(dbgs() << "LV: Picking a fixed-width so that no tail will "
3659 "remain for any chosen VF.\n");
3660 MaxFactors.ScalableVF = ElementCount::getScalable(0);
3661 return MaxFactors;
3662 }
3663 }
3664
3666 "The trip count is below the minial threshold value.",
3667 "loop trip count is too low, avoiding vectorization", "LowTripCount",
3668 ORE, TheLoop);
3670 }
3671
3672 // If we don't know the precise trip count, or if the trip count that we
3673 // found modulo the vectorization factor is not zero, try to fold the tail
3674 // by masking.
3675 // FIXME: look for a smaller MaxVF that does divide TC rather than masking.
3676 bool ContainsScalableVF = MaxFactors.ScalableVF.isNonZero();
3677 setTailFoldingStyles(ContainsScalableVF, UserIC);
3678 if (foldTailByMasking()) {
3679 if (getTailFoldingStyle() == TailFoldingStyle::DataWithEVL) {
3680 LLVM_DEBUG(
3681 dbgs()
3682 << "LV: tail is folded with EVL, forcing unroll factor to be 1. Will "
3683 "try to generate VP Intrinsics with scalable vector "
3684 "factors only.\n");
3685 // Tail folded loop using VP intrinsics restricts the VF to be scalable
3686 // for now.
3687 // TODO: extend it for fixed vectors, if required.
3688 assert(ContainsScalableVF && "Expected scalable vector factor.");
3689
3690 MaxFactors.FixedVF = ElementCount::getFixed(1);
3691 }
3692 return MaxFactors;
3693 }
3694
3695 // If there was a tail-folding hint/switch, but we can't fold the tail by
3696 // masking, fallback to a vectorization with a scalar epilogue.
3697 if (ScalarEpilogueStatus == CM_ScalarEpilogueNotNeededUsePredicate) {
3698 LLVM_DEBUG(dbgs() << "LV: Cannot fold tail by masking: vectorize with a "
3699 "scalar epilogue instead.\n");
3700 ScalarEpilogueStatus = CM_ScalarEpilogueAllowed;
3701 return MaxFactors;
3702 }
3703
3704 if (ScalarEpilogueStatus == CM_ScalarEpilogueNotAllowedUsePredicate) {
3705 LLVM_DEBUG(dbgs() << "LV: Can't fold tail by masking: don't vectorize\n");
3707 }
3708
3709 if (TC.isZero()) {
3711 "unable to calculate the loop count due to complex control flow",
3712 "UnknownLoopCountComplexCFG", ORE, TheLoop);
3714 }
3715
3717 "Cannot optimize for size and vectorize at the same time.",
3718 "cannot optimize for size and vectorize at the same time. "
3719 "Enable vectorization of this loop with '#pragma clang loop "
3720 "vectorize(enable)' when compiling with -Os/-Oz",
3721 "NoTailLoopWithOptForSize", ORE, TheLoop);
3723}
3724
3726 ElementCount VF) {
3727 if (!useMaxBandwidth(VF.isScalable()
3730 return false;
3731 // Only calculate register pressure for VFs enabled by MaxBandwidth.
3733 VF, VF.isScalable() ? MaxPermissibleVFWithoutMaxBW.ScalableVF
3734 : MaxPermissibleVFWithoutMaxBW.FixedVF);
3735}
3736
3742 Legal->hasVectorCallVariants())));
3743}
3744
3745ElementCount LoopVectorizationCostModel::clampVFByMaxTripCount(
3746 ElementCount VF, unsigned MaxTripCount, bool FoldTailByMasking) const {
3747 unsigned EstimatedVF = VF.getKnownMinValue();
3748 if (VF.isScalable() && TheFunction->hasFnAttribute(Attribute::VScaleRange)) {
3749 auto Attr = TheFunction->getFnAttribute(Attribute::VScaleRange);
3750 auto Min = Attr.getVScaleRangeMin();
3751 EstimatedVF *= Min;
3752 }
3753
3754 // When a scalar epilogue is required, at least one iteration of the scalar
3755 // loop has to execute. Adjust MaxTripCount accordingly to avoid picking a
3756 // max VF that results in a dead vector loop.
3757 if (MaxTripCount > 0 && requiresScalarEpilogue(true))
3758 MaxTripCount -= 1;
3759
3760 if (MaxTripCount && MaxTripCount <= EstimatedVF &&
3761 (!FoldTailByMasking || isPowerOf2_32(MaxTripCount))) {
3762 // If upper bound loop trip count (TC) is known at compile time there is no
3763 // point in choosing VF greater than TC (as done in the loop below). Select
3764 // maximum power of two which doesn't exceed TC. If VF is
3765 // scalable, we only fall back on a fixed VF when the TC is less than or
3766 // equal to the known number of lanes.
3767 auto ClampedUpperTripCount = llvm::bit_floor(MaxTripCount);
3768 LLVM_DEBUG(dbgs() << "LV: Clamping the MaxVF to maximum power of two not "
3769 "exceeding the constant trip count: "
3770 << ClampedUpperTripCount << "\n");
3771 return ElementCount::get(ClampedUpperTripCount,
3772 FoldTailByMasking ? VF.isScalable() : false);
3773 }
3774 return VF;
3775}
3776
3777ElementCount LoopVectorizationCostModel::getMaximizedVFForTarget(
3778 unsigned MaxTripCount, unsigned SmallestType, unsigned WidestType,
3779 ElementCount MaxSafeVF, bool FoldTailByMasking) {
3780 bool ComputeScalableMaxVF = MaxSafeVF.isScalable();
3781 const TypeSize WidestRegister = TTI.getRegisterBitWidth(
3782 ComputeScalableMaxVF ? TargetTransformInfo::RGK_ScalableVector
3784
3785 // Convenience function to return the minimum of two ElementCounts.
3786 auto MinVF = [](const ElementCount &LHS, const ElementCount &RHS) {
3787 assert((LHS.isScalable() == RHS.isScalable()) &&
3788 "Scalable flags must match");
3789 return ElementCount::isKnownLT(LHS, RHS) ? LHS : RHS;
3790 };
3791
3792 // Ensure MaxVF is a power of 2; the dependence distance bound may not be.
3793 // Note that both WidestRegister and WidestType may not be a powers of 2.
3794 auto MaxVectorElementCount = ElementCount::get(
3795 llvm::bit_floor(WidestRegister.getKnownMinValue() / WidestType),
3796 ComputeScalableMaxVF);
3797 MaxVectorElementCount = MinVF(MaxVectorElementCount, MaxSafeVF);
3798 LLVM_DEBUG(dbgs() << "LV: The Widest register safe to use is: "
3799 << (MaxVectorElementCount * WidestType) << " bits.\n");
3800
3801 if (!MaxVectorElementCount) {
3802 LLVM_DEBUG(dbgs() << "LV: The target has no "
3803 << (ComputeScalableMaxVF ? "scalable" : "fixed")
3804 << " vector registers.\n");
3805 return ElementCount::getFixed(1);
3806 }
3807
3808 ElementCount MaxVF = clampVFByMaxTripCount(MaxVectorElementCount,
3809 MaxTripCount, FoldTailByMasking);
3810 // If the MaxVF was already clamped, there's no point in trying to pick a
3811 // larger one.
3812 if (MaxVF != MaxVectorElementCount)
3813 return MaxVF;
3814
3816 ComputeScalableMaxVF ? TargetTransformInfo::RGK_ScalableVector
3818
3819 if (MaxVF.isScalable())
3820 MaxPermissibleVFWithoutMaxBW.ScalableVF = MaxVF;
3821 else
3822 MaxPermissibleVFWithoutMaxBW.FixedVF = MaxVF;
3823
3824 if (useMaxBandwidth(RegKind)) {
3825 auto MaxVectorElementCountMaxBW = ElementCount::get(
3826 llvm::bit_floor(WidestRegister.getKnownMinValue() / SmallestType),
3827 ComputeScalableMaxVF);
3828 MaxVF = MinVF(MaxVectorElementCountMaxBW, MaxSafeVF);
3829
3830 if (ElementCount MinVF =
3831 TTI.getMinimumVF(SmallestType, ComputeScalableMaxVF)) {
3832 if (ElementCount::isKnownLT(MaxVF, MinVF)) {
3833 LLVM_DEBUG(dbgs() << "LV: Overriding calculated MaxVF(" << MaxVF
3834 << ") with target's minimum: " << MinVF << '\n');
3835 MaxVF = MinVF;
3836 }
3837 }
3838
3839 MaxVF = clampVFByMaxTripCount(MaxVF, MaxTripCount, FoldTailByMasking);
3840
3841 if (MaxVectorElementCount != MaxVF) {
3842 // Invalidate any widening decisions we might have made, in case the loop
3843 // requires prediction (decided later), but we have already made some
3844 // load/store widening decisions.
3845 invalidateCostModelingDecisions();
3846 }
3847 }
3848 return MaxVF;
3849}
3850
3851bool LoopVectorizationPlanner::isMoreProfitable(const VectorizationFactor &A,
3852 const VectorizationFactor &B,
3853 const unsigned MaxTripCount,
3854 bool HasTail) const {
3855 InstructionCost CostA = A.Cost;
3856 InstructionCost CostB = B.Cost;
3857
3858 // Improve estimate for the vector width if it is scalable.
3859 unsigned EstimatedWidthA = A.Width.getKnownMinValue();
3860 unsigned EstimatedWidthB = B.Width.getKnownMinValue();
3861 if (std::optional<unsigned> VScale = CM.getVScaleForTuning()) {
3862 if (A.Width.isScalable())
3863 EstimatedWidthA *= *VScale;
3864 if (B.Width.isScalable())
3865 EstimatedWidthB *= *VScale;
3866 }
3867
3868 // When optimizing for size choose whichever is smallest, which will be the
3869 // one with the smallest cost for the whole loop. On a tie pick the larger
3870 // vector width, on the assumption that throughput will be greater.
3871 if (CM.CostKind == TTI::TCK_CodeSize)
3872 return CostA < CostB ||
3873 (CostA == CostB && EstimatedWidthA > EstimatedWidthB);
3874
3875 // Assume vscale may be larger than 1 (or the value being tuned for),
3876 // so that scalable vectorization is slightly favorable over fixed-width
3877 // vectorization.
3878 bool PreferScalable = !TTI.preferFixedOverScalableIfEqualCost() &&
3879 A.Width.isScalable() && !B.Width.isScalable();
3880
3881 auto CmpFn = [PreferScalable](const InstructionCost &LHS,
3882 const InstructionCost &RHS) {
3883 return PreferScalable ? LHS <= RHS : LHS < RHS;
3884 };
3885
3886 // To avoid the need for FP division:
3887 // (CostA / EstimatedWidthA) < (CostB / EstimatedWidthB)
3888 // <=> (CostA * EstimatedWidthB) < (CostB * EstimatedWidthA)
3889 if (!MaxTripCount)
3890 return CmpFn(CostA * EstimatedWidthB, CostB * EstimatedWidthA);
3891
3892 auto GetCostForTC = [MaxTripCount, HasTail](unsigned VF,
3893 InstructionCost VectorCost,
3894 InstructionCost ScalarCost) {
3895 // If the trip count is a known (possibly small) constant, the trip count
3896 // will be rounded up to an integer number of iterations under
3897 // FoldTailByMasking. The total cost in that case will be
3898 // VecCost*ceil(TripCount/VF). When not folding the tail, the total
3899 // cost will be VecCost*floor(TC/VF) + ScalarCost*(TC%VF). There will be
3900 // some extra overheads, but for the purpose of comparing the costs of
3901 // different VFs we can use this to compare the total loop-body cost
3902 // expected after vectorization.
3903 if (HasTail)
3904 return VectorCost * (MaxTripCount / VF) +
3905 ScalarCost * (MaxTripCount % VF);
3906 return VectorCost * divideCeil(MaxTripCount, VF);
3907 };
3908
3909 auto RTCostA = GetCostForTC(EstimatedWidthA, CostA, A.ScalarCost);
3910 auto RTCostB = GetCostForTC(EstimatedWidthB, CostB, B.ScalarCost);
3911 return CmpFn(RTCostA, RTCostB);
3912}
3913
3914bool LoopVectorizationPlanner::isMoreProfitable(const VectorizationFactor &A,
3915 const VectorizationFactor &B,
3916 bool HasTail) const {
3917 const unsigned MaxTripCount = PSE.getSmallConstantMaxTripCount();
3918 return LoopVectorizationPlanner::isMoreProfitable(A, B, MaxTripCount,
3919 HasTail);
3920}
3921
3924 using RecipeVFPair = std::pair<VPRecipeBase *, ElementCount>;
3925 SmallVector<RecipeVFPair> InvalidCosts;
3926 for (const auto &Plan : VPlans) {
3927 for (ElementCount VF : Plan->vectorFactors()) {
3928 // The VPlan-based cost model is designed for computing vector cost.
3929 // Querying VPlan-based cost model with a scarlar VF will cause some
3930 // errors because we expect the VF is vector for most of the widen
3931 // recipes.
3932 if (VF.isScalar())
3933 continue;
3934
3935 VPCostContext CostCtx(CM.TTI, *CM.TLI, *Plan, CM, CM.CostKind);
3936 precomputeCosts(*Plan, VF, CostCtx);
3938 for (VPBasicBlock *VPBB : VPBlockUtils::blocksOnly<VPBasicBlock>(Iter)) {
3939 for (auto &R : *VPBB) {
3940 if (!R.cost(VF, CostCtx).isValid())
3941 InvalidCosts.emplace_back(&R, VF);
3942 }
3943 }
3944 }
3945 }
3946 if (InvalidCosts.empty())
3947 return;
3948
3949 // Emit a report of VFs with invalid costs in the loop.
3950
3951 // Group the remarks per recipe, keeping the recipe order from InvalidCosts.
3953 unsigned I = 0;
3954 for (auto &Pair : InvalidCosts)
3955 if (Numbering.try_emplace(Pair.first, I).second)
3956 ++I;
3957
3958 // Sort the list, first on recipe(number) then on VF.
3959 sort(InvalidCosts, [&Numbering](RecipeVFPair &A, RecipeVFPair &B) {
3960 unsigned NA = Numbering[A.first];
3961 unsigned NB = Numbering[B.first];
3962 if (NA != NB)
3963 return NA < NB;
3964 return ElementCount::isKnownLT(A.second, B.second);
3965 });
3966
3967 // For a list of ordered recipe-VF pairs:
3968 // [(load, VF1), (load, VF2), (store, VF1)]
3969 // group the recipes together to emit separate remarks for:
3970 // load (VF1, VF2)
3971 // store (VF1)
3972 auto Tail = ArrayRef<RecipeVFPair>(InvalidCosts);
3973 auto Subset = ArrayRef<RecipeVFPair>();
3974 do {
3975 if (Subset.empty())
3976 Subset = Tail.take_front(1);
3977
3978 VPRecipeBase *R = Subset.front().first;
3979
3980 unsigned Opcode =
3983 [](const auto *R) { return Instruction::PHI; })
3984 .Case<VPWidenSelectRecipe>(
3985 [](const auto *R) { return Instruction::Select; })
3986 .Case<VPWidenStoreRecipe>(
3987 [](const auto *R) { return Instruction::Store; })
3988 .Case<VPWidenLoadRecipe>(
3989 [](const auto *R) { return Instruction::Load; })
3990 .Case<VPWidenCallRecipe, VPWidenIntrinsicRecipe>(
3991 [](const auto *R) { return Instruction::Call; })
3994 [](const auto *R) { return R->getOpcode(); })
3995 .Case<VPInterleaveRecipe>([](const VPInterleaveRecipe *R) {
3996 return R->getStoredValues().empty() ? Instruction::Load
3997 : Instruction::Store;
3998 });
3999
4000 // If the next recipe is different, or if there are no other pairs,
4001 // emit a remark for the collated subset. e.g.
4002 // [(load, VF1), (load, VF2))]
4003 // to emit:
4004 // remark: invalid costs for 'load' at VF=(VF1, VF2)
4005 if (Subset == Tail || Tail[Subset.size()].first != R) {
4006 std::string OutString;
4007 raw_string_ostream OS(OutString);
4008 assert(!Subset.empty() && "Unexpected empty range");
4009 OS << "Recipe with invalid costs prevented vectorization at VF=(";
4010 for (const auto &Pair : Subset)
4011 OS << (Pair.second == Subset.front().second ? "" : ", ") << Pair.second;
4012 OS << "):";
4013 if (Opcode == Instruction::Call) {
4014 StringRef Name = "";
4015 if (auto *Int = dyn_cast<VPWidenIntrinsicRecipe>(R)) {
4016 Name = Int->getIntrinsicName();
4017 } else {
4018 auto *WidenCall = dyn_cast<VPWidenCallRecipe>(R);
4019 Function *CalledFn =
4020 WidenCall ? WidenCall->getCalledScalarFunction()
4021 : cast<Function>(R->getOperand(R->getNumOperands() - 1)
4022 ->getLiveInIRValue());
4023 Name = CalledFn->getName();
4024 }
4025 OS << " call to " << Name;
4026 } else
4027 OS << " " << Instruction::getOpcodeName(Opcode);
4028 reportVectorizationInfo(OutString, "InvalidCost", ORE, OrigLoop, nullptr,
4029 R->getDebugLoc());
4030 Tail = Tail.drop_front(Subset.size());
4031 Subset = {};
4032 } else
4033 // Grow the subset by one element
4034 Subset = Tail.take_front(Subset.size() + 1);
4035 } while (!Tail.empty());
4036}
4037
4038/// Check if any recipe of \p Plan will generate a vector value, which will be
4039/// assigned a vector register.
4041 const TargetTransformInfo &TTI) {
4042 assert(VF.isVector() && "Checking a scalar VF?");
4043 VPTypeAnalysis TypeInfo(Plan);
4044 DenseSet<VPRecipeBase *> EphemeralRecipes;
4045 collectEphemeralRecipesForVPlan(Plan, EphemeralRecipes);
4046 // Set of already visited types.
4047 DenseSet<Type *> Visited;
4048 for (VPBasicBlock *VPBB : VPBlockUtils::blocksOnly<VPBasicBlock>(
4050 for (VPRecipeBase &R : *VPBB) {
4051 if (EphemeralRecipes.contains(&R))
4052 continue;
4053 // Continue early if the recipe is considered to not produce a vector
4054 // result. Note that this includes VPInstruction where some opcodes may
4055 // produce a vector, to preserve existing behavior as VPInstructions model
4056 // aspects not directly mapped to existing IR instructions.
4057 switch (R.getVPDefID()) {
4058 case VPDef::VPDerivedIVSC:
4059 case VPDef::VPScalarIVStepsSC:
4060 case VPDef::VPReplicateSC:
4061 case VPDef::VPInstructionSC:
4062 case VPDef::VPCanonicalIVPHISC:
4063 case VPDef::VPVectorPointerSC:
4064 case VPDef::VPVectorEndPointerSC:
4065 case VPDef::VPExpandSCEVSC:
4066 case VPDef::VPEVLBasedIVPHISC:
4067 case VPDef::VPPredInstPHISC:
4068 case VPDef::VPBranchOnMaskSC:
4069 continue;
4070 case VPDef::VPReductionSC:
4071 case VPDef::VPActiveLaneMaskPHISC:
4072 case VPDef::VPWidenCallSC:
4073 case VPDef::VPWidenCanonicalIVSC:
4074 case VPDef::VPWidenCastSC:
4075 case VPDef::VPWidenGEPSC:
4076 case VPDef::VPWidenIntrinsicSC:
4077 case VPDef::VPWidenSC:
4078 case VPDef::VPWidenSelectSC:
4079 case VPDef::VPBlendSC:
4080 case VPDef::VPFirstOrderRecurrencePHISC:
4081 case VPDef::VPHistogramSC:
4082 case VPDef::VPWidenPHISC:
4083 case VPDef::VPWidenIntOrFpInductionSC:
4084 case VPDef::VPWidenPointerInductionSC:
4085 case VPDef::VPReductionPHISC:
4086 case VPDef::VPInterleaveSC:
4087 case VPDef::VPWidenLoadEVLSC:
4088 case VPDef::VPWidenLoadSC:
4089 case VPDef::VPWidenStoreEVLSC:
4090 case VPDef::VPWidenStoreSC:
4091 break;
4092 default:
4093 llvm_unreachable("unhandled recipe");
4094 }
4095
4096 auto WillGenerateTargetVectors = [&TTI, VF](Type *VectorTy) {
4097 unsigned NumLegalParts = TTI.getNumberOfParts(VectorTy);
4098 if (!NumLegalParts)
4099 return false;
4100 if (VF.isScalable()) {
4101 // <vscale x 1 x iN> is assumed to be profitable over iN because
4102 // scalable registers are a distinct register class from scalar
4103 // ones. If we ever find a target which wants to lower scalable
4104 // vectors back to scalars, we'll need to update this code to
4105 // explicitly ask TTI about the register class uses for each part.
4106 return NumLegalParts <= VF.getKnownMinValue();
4107 }
4108 // Two or more elements that share a register - are vectorized.
4109 return NumLegalParts < VF.getFixedValue();
4110 };
4111
4112 // If no def nor is a store, e.g., branches, continue - no value to check.
4113 if (R.getNumDefinedValues() == 0 &&
4114 !isa<VPWidenStoreRecipe, VPWidenStoreEVLRecipe, VPInterleaveRecipe>(
4115 &R))
4116 continue;
4117 // For multi-def recipes, currently only interleaved loads, suffice to
4118 // check first def only.
4119 // For stores check their stored value; for interleaved stores suffice
4120 // the check first stored value only. In all cases this is the second
4121 // operand.
4122 VPValue *ToCheck =
4123 R.getNumDefinedValues() >= 1 ? R.getVPValue(0) : R.getOperand(1);
4124 Type *ScalarTy = TypeInfo.inferScalarType(ToCheck);
4125 if (!Visited.insert({ScalarTy}).second)
4126 continue;
4127 Type *WideTy = toVectorizedTy(ScalarTy, VF);
4128 if (any_of(getContainedTypes(WideTy), WillGenerateTargetVectors))
4129 return true;
4130 }
4131 }
4132
4133 return false;
4134}
4135
4137 return any_of(VPBlockUtils::blocksOnly<VPRegionBlock>(vp_depth_first_shallow(
4139 [](auto *VPRB) { return VPRB->isReplicator(); });
4140}
4141
4142#ifndef NDEBUG
4143VectorizationFactor LoopVectorizationPlanner::selectVectorizationFactor() {
4144 InstructionCost ExpectedCost = CM.expectedCost(ElementCount::getFixed(1));
4145 LLVM_DEBUG(dbgs() << "LV: Scalar loop costs: " << ExpectedCost << ".\n");
4146 assert(ExpectedCost.isValid() && "Unexpected invalid cost for scalar loop");
4147 assert(
4148 any_of(VPlans,
4149 [](std::unique_ptr<VPlan> &P) { return P->hasScalarVFOnly(); }) &&
4150 "Expected Scalar VF to be a candidate");
4151
4152 const VectorizationFactor ScalarCost(ElementCount::getFixed(1), ExpectedCost,
4153 ExpectedCost);
4154 VectorizationFactor ChosenFactor = ScalarCost;
4155
4156 bool ForceVectorization = Hints.getForce() == LoopVectorizeHints::FK_Enabled;
4157 if (ForceVectorization &&
4158 (VPlans.size() > 1 || !VPlans[0]->hasScalarVFOnly())) {
4159 // Ignore scalar width, because the user explicitly wants vectorization.
4160 // Initialize cost to max so that VF = 2 is, at least, chosen during cost
4161 // evaluation.
4162 ChosenFactor.Cost = InstructionCost::getMax();
4163 }
4164
4165 for (auto &P : VPlans) {
4166 ArrayRef<ElementCount> VFs(P->vectorFactors().begin(),
4167 P->vectorFactors().end());
4168
4170 if (CM.useMaxBandwidth(TargetTransformInfo::RGK_ScalableVector) ||
4172 RUs = calculateRegisterUsageForPlan(*P, VFs, TTI, CM.ValuesToIgnore);
4173
4174 for (unsigned I = 0; I < VFs.size(); I++) {
4175 ElementCount VF = VFs[I];
4176 // The cost for scalar VF=1 is already calculated, so ignore it.
4177 if (VF.isScalar())
4178 continue;
4179
4180 /// If the register pressure needs to be considered for VF,
4181 /// don't consider the VF as valid if it exceeds the number
4182 /// of registers for the target.
4183 if (CM.shouldCalculateRegPressureForVF(VF) &&
4184 RUs[I].exceedsMaxNumRegs(TTI, ForceTargetNumVectorRegs))
4185 continue;
4186
4187 InstructionCost C = CM.expectedCost(VF);
4188
4189 // Add on other costs that are modelled in VPlan, but not in the legacy
4190 // cost model.
4191 VPCostContext CostCtx(CM.TTI, *CM.TLI, *P, CM, CM.CostKind);
4192 VPRegionBlock *VectorRegion = P->getVectorLoopRegion();
4193 assert(VectorRegion && "Expected to have a vector region!");
4194 for (VPBasicBlock *VPBB : VPBlockUtils::blocksOnly<VPBasicBlock>(
4195 vp_depth_first_shallow(VectorRegion->getEntry()))) {
4196 for (VPRecipeBase &R : *VPBB) {
4197 auto *VPI = dyn_cast<VPInstruction>(&R);
4198 if (!VPI)
4199 continue;
4200 switch (VPI->getOpcode()) {
4201 // Selects are only modelled in the legacy cost model for safe
4202 // divisors.
4203 case Instruction::Select: {
4204 VPValue *VPV = VPI->getVPSingleValue();
4205 if (VPV->getNumUsers() == 1) {
4206 if (auto *WR = dyn_cast<VPWidenRecipe>(*VPV->user_begin())) {
4207 switch (WR->getOpcode()) {
4208 case Instruction::UDiv:
4209 case Instruction::SDiv:
4210 case Instruction::URem:
4211 case Instruction::SRem:
4212 continue;
4213 default:
4214 break;
4215 }
4216 }
4217 }
4218 [[fallthrough]];
4219 }
4222 C += VPI->cost(VF, CostCtx);
4223 break;
4224 default:
4225 break;
4226 }
4227 }
4228 }
4229
4230 VectorizationFactor Candidate(VF, C, ScalarCost.ScalarCost);
4231 unsigned Width =
4232 estimateElementCount(Candidate.Width, CM.getVScaleForTuning());
4233 LLVM_DEBUG(dbgs() << "LV: Vector loop of width " << VF
4234 << " costs: " << (Candidate.Cost / Width));
4235 if (VF.isScalable())
4236 LLVM_DEBUG(dbgs() << " (assuming a minimum vscale of "
4237 << CM.getVScaleForTuning().value_or(1) << ")");
4238 LLVM_DEBUG(dbgs() << ".\n");
4239
4240 if (!ForceVectorization && !willGenerateVectors(*P, VF, TTI)) {
4241 LLVM_DEBUG(
4242 dbgs()
4243 << "LV: Not considering vector loop of width " << VF
4244 << " because it will not generate any vector instructions.\n");
4245 continue;
4246 }
4247
4248 if (CM.OptForSize && !ForceVectorization && hasReplicatorRegion(*P)) {
4249 LLVM_DEBUG(
4250 dbgs()
4251 << "LV: Not considering vector loop of width " << VF
4252 << " because it would cause replicated blocks to be generated,"
4253 << " which isn't allowed when optimizing for size.\n");
4254 continue;
4255 }
4256
4257 if (isMoreProfitable(Candidate, ChosenFactor, P->hasScalarTail()))
4258 ChosenFactor = Candidate;
4259 }
4260 }
4261
4262 if (!EnableCondStoresVectorization && CM.hasPredStores()) {
4264 "There are conditional stores.",
4265 "store that is conditionally executed prevents vectorization",
4266 "ConditionalStore", ORE, OrigLoop);
4267 ChosenFactor = ScalarCost;
4268 }
4269
4270 LLVM_DEBUG(if (ForceVectorization && !ChosenFactor.Width.isScalar() &&
4271 !isMoreProfitable(ChosenFactor, ScalarCost,
4272 !CM.foldTailByMasking())) dbgs()
4273 << "LV: Vectorization seems to be not beneficial, "
4274 << "but was forced by a user.\n");
4275 return ChosenFactor;
4276}
4277#endif
4278
4279bool LoopVectorizationPlanner::isCandidateForEpilogueVectorization(
4280 ElementCount VF) const {
4281 // Cross iteration phis such as fixed-order recurrences and FMaxNum/FMinNum
4282 // reductions need special handling and are currently unsupported.
4283 if (any_of(OrigLoop->getHeader()->phis(), [&](PHINode &Phi) {
4284 if (!Legal->isReductionVariable(&Phi))
4285 return Legal->isFixedOrderRecurrence(&Phi);
4286 RecurKind RK = Legal->getRecurrenceDescriptor(&Phi).getRecurrenceKind();
4287 return RK == RecurKind::FMinNum || RK == RecurKind::FMaxNum;
4288 }))
4289 return false;
4290
4291 // Phis with uses outside of the loop require special handling and are
4292 // currently unsupported.
4293 for (const auto &Entry : Legal->getInductionVars()) {
4294 // Look for uses of the value of the induction at the last iteration.
4295 Value *PostInc =
4296 Entry.first->getIncomingValueForBlock(OrigLoop->getLoopLatch());
4297 for (User *U : PostInc->users())
4298 if (!OrigLoop->contains(cast<Instruction>(U)))
4299 return false;
4300 // Look for uses of penultimate value of the induction.
4301 for (User *U : Entry.first->users())
4302 if (!OrigLoop->contains(cast<Instruction>(U)))
4303 return false;
4304 }
4305
4306 // Epilogue vectorization code has not been auditted to ensure it handles
4307 // non-latch exits properly. It may be fine, but it needs auditted and
4308 // tested.
4309 // TODO: Add support for loops with an early exit.
4311 return false;
4312
4313 return true;
4314}
4315
4317 const ElementCount VF, const unsigned IC) const {
4318 // FIXME: We need a much better cost-model to take different parameters such
4319 // as register pressure, code size increase and cost of extra branches into
4320 // account. For now we apply a very crude heuristic and only consider loops
4321 // with vectorization factors larger than a certain value.
4322
4323 // Allow the target to opt out entirely.
4325 return false;
4326
4327 // We also consider epilogue vectorization unprofitable for targets that don't
4328 // consider interleaving beneficial (eg. MVE).
4329 if (TTI.getMaxInterleaveFactor(VF) <= 1)
4330 return false;
4331
4332 // TODO: PR #108190 introduced a discrepancy between fixed-width and scalable
4333 // VFs when deciding profitability.
4334 // See related "TODO: extend to support scalable VFs." in
4335 // selectEpilogueVectorizationFactor.
4336 unsigned Multiplier = VF.isFixed() ? IC : 1;
4337 unsigned MinVFThreshold = EpilogueVectorizationMinVF.getNumOccurrences() > 0
4340 return estimateElementCount(VF * Multiplier, VScaleForTuning) >=
4341 MinVFThreshold;
4342}
4343
4345 const ElementCount MainLoopVF, unsigned IC) {
4348 LLVM_DEBUG(dbgs() << "LEV: Epilogue vectorization is disabled.\n");
4349 return Result;
4350 }
4351
4352 if (!CM.isScalarEpilogueAllowed()) {
4353 LLVM_DEBUG(dbgs() << "LEV: Unable to vectorize epilogue because no "
4354 "epilogue is allowed.\n");
4355 return Result;
4356 }
4357
4358 // Not really a cost consideration, but check for unsupported cases here to
4359 // simplify the logic.
4360 if (!isCandidateForEpilogueVectorization(MainLoopVF)) {
4361 LLVM_DEBUG(dbgs() << "LEV: Unable to vectorize epilogue because the loop "
4362 "is not a supported candidate.\n");
4363 return Result;
4364 }
4365
4367 LLVM_DEBUG(dbgs() << "LEV: Epilogue vectorization factor is forced.\n");
4369 if (hasPlanWithVF(ForcedEC))
4370 return {ForcedEC, 0, 0};
4371
4372 LLVM_DEBUG(dbgs() << "LEV: Epilogue vectorization forced factor is not "
4373 "viable.\n");
4374 return Result;
4375 }
4376
4377 if (OrigLoop->getHeader()->getParent()->hasOptSize()) {
4378 LLVM_DEBUG(
4379 dbgs() << "LEV: Epilogue vectorization skipped due to opt for size.\n");
4380 return Result;
4381 }
4382
4383 if (!CM.isEpilogueVectorizationProfitable(MainLoopVF, IC)) {
4384 LLVM_DEBUG(dbgs() << "LEV: Epilogue vectorization is not profitable for "
4385 "this loop\n");
4386 return Result;
4387 }
4388
4389 // If MainLoopVF = vscale x 2, and vscale is expected to be 4, then we know
4390 // the main loop handles 8 lanes per iteration. We could still benefit from
4391 // vectorizing the epilogue loop with VF=4.
4392 ElementCount EstimatedRuntimeVF = ElementCount::getFixed(
4393 estimateElementCount(MainLoopVF, CM.getVScaleForTuning()));
4394
4395 ScalarEvolution &SE = *PSE.getSE();
4396 Type *TCType = Legal->getWidestInductionType();
4397 const SCEV *RemainingIterations = nullptr;
4398 unsigned MaxTripCount = 0;
4399 const SCEV *TC =
4400 vputils::getSCEVExprForVPValue(getPlanFor(MainLoopVF).getTripCount(), SE);
4401 assert(!isa<SCEVCouldNotCompute>(TC) && "Trip count SCEV must be computable");
4402 RemainingIterations =
4403 SE.getURemExpr(TC, SE.getElementCount(TCType, MainLoopVF * IC));
4404
4405 // No iterations left to process in the epilogue.
4406 if (RemainingIterations->isZero())
4407 return Result;
4408
4409 if (MainLoopVF.isFixed()) {
4410 MaxTripCount = MainLoopVF.getFixedValue() * IC - 1;
4411 if (SE.isKnownPredicate(CmpInst::ICMP_ULT, RemainingIterations,
4412 SE.getConstant(TCType, MaxTripCount))) {
4413 MaxTripCount = SE.getUnsignedRangeMax(RemainingIterations).getZExtValue();
4414 }
4415 LLVM_DEBUG(dbgs() << "LEV: Maximum Trip Count for Epilogue: "
4416 << MaxTripCount << "\n");
4417 }
4418
4419 for (auto &NextVF : ProfitableVFs) {
4420 // Skip candidate VFs without a corresponding VPlan.
4421 if (!hasPlanWithVF(NextVF.Width))
4422 continue;
4423
4424 // Skip candidate VFs with widths >= the (estimated) runtime VF (scalable
4425 // vectors) or > the VF of the main loop (fixed vectors).
4426 if ((!NextVF.Width.isScalable() && MainLoopVF.isScalable() &&
4427 ElementCount::isKnownGE(NextVF.Width, EstimatedRuntimeVF)) ||
4428 (NextVF.Width.isScalable() &&
4429 ElementCount::isKnownGE(NextVF.Width, MainLoopVF)) ||
4430 (!NextVF.Width.isScalable() && !MainLoopVF.isScalable() &&
4431 ElementCount::isKnownGT(NextVF.Width, MainLoopVF)))
4432 continue;
4433
4434 // If NextVF is greater than the number of remaining iterations, the
4435 // epilogue loop would be dead. Skip such factors.
4436 if (RemainingIterations && !NextVF.Width.isScalable()) {
4437 if (SE.isKnownPredicate(
4439 SE.getConstant(TCType, NextVF.Width.getFixedValue()),
4440 RemainingIterations))
4441 continue;
4442 }
4443
4444 if (Result.Width.isScalar() ||
4445 isMoreProfitable(NextVF, Result, MaxTripCount, !CM.foldTailByMasking()))
4446 Result = NextVF;
4447 }
4448
4449 if (Result != VectorizationFactor::Disabled())
4450 LLVM_DEBUG(dbgs() << "LEV: Vectorizing epilogue loop with VF = "
4451 << Result.Width << "\n");
4452 return Result;
4453}
4454
4455std::pair<unsigned, unsigned>
4457 unsigned MinWidth = -1U;
4458 unsigned MaxWidth = 8;
4459 const DataLayout &DL = TheFunction->getDataLayout();
4460 // For in-loop reductions, no element types are added to ElementTypesInLoop
4461 // if there are no loads/stores in the loop. In this case, check through the
4462 // reduction variables to determine the maximum width.
4463 if (ElementTypesInLoop.empty() && !Legal->getReductionVars().empty()) {
4464 for (const auto &PhiDescriptorPair : Legal->getReductionVars()) {
4465 const RecurrenceDescriptor &RdxDesc = PhiDescriptorPair.second;
4466 // When finding the min width used by the recurrence we need to account
4467 // for casts on the input operands of the recurrence.
4468 MinWidth = std::min(
4469 MinWidth,
4470 std::min(RdxDesc.getMinWidthCastToRecurrenceTypeInBits(),
4472 MaxWidth = std::max(MaxWidth,
4474 }
4475 } else {
4476 for (Type *T : ElementTypesInLoop) {
4477 MinWidth = std::min<unsigned>(
4478 MinWidth, DL.getTypeSizeInBits(T->getScalarType()).getFixedValue());
4479 MaxWidth = std::max<unsigned>(
4480 MaxWidth, DL.getTypeSizeInBits(T->getScalarType()).getFixedValue());
4481 }
4482 }
4483 return {MinWidth, MaxWidth};
4484}
4485
4487 ElementTypesInLoop.clear();
4488 // For each block.
4489 for (BasicBlock *BB : TheLoop->blocks()) {
4490 // For each instruction in the loop.
4491 for (Instruction &I : BB->instructionsWithoutDebug()) {
4492 Type *T = I.getType();
4493
4494 // Skip ignored values.
4495 if (ValuesToIgnore.count(&I))
4496 continue;
4497
4498 // Only examine Loads, Stores and PHINodes.
4499 if (!isa<LoadInst>(I) && !isa<StoreInst>(I) && !isa<PHINode>(I))
4500 continue;
4501
4502 // Examine PHI nodes that are reduction variables. Update the type to
4503 // account for the recurrence type.
4504 if (auto *PN = dyn_cast<PHINode>(&I)) {
4505 if (!Legal->isReductionVariable(PN))
4506 continue;
4507 const RecurrenceDescriptor &RdxDesc =
4508 Legal->getRecurrenceDescriptor(PN);
4509 if (PreferInLoopReductions || useOrderedReductions(RdxDesc) ||
4511 RdxDesc.getRecurrenceType()))
4512 continue;
4513 T = RdxDesc.getRecurrenceType();
4514 }
4515
4516 // Examine the stored values.
4517 if (auto *ST = dyn_cast<StoreInst>(&I))
4518 T = ST->getValueOperand()->getType();
4519
4520 assert(T->isSized() &&
4521 "Expected the load/store/recurrence type to be sized");
4522
4523 ElementTypesInLoop.insert(T);
4524 }
4525 }
4526}
4527
4528unsigned
4530 InstructionCost LoopCost) {
4531 // -- The interleave heuristics --
4532 // We interleave the loop in order to expose ILP and reduce the loop overhead.
4533 // There are many micro-architectural considerations that we can't predict
4534 // at this level. For example, frontend pressure (on decode or fetch) due to
4535 // code size, or the number and capabilities of the execution ports.
4536 //
4537 // We use the following heuristics to select the interleave count:
4538 // 1. If the code has reductions, then we interleave to break the cross
4539 // iteration dependency.
4540 // 2. If the loop is really small, then we interleave to reduce the loop
4541 // overhead.
4542 // 3. We don't interleave if we think that we will spill registers to memory
4543 // due to the increased register pressure.
4544
4545 if (!CM.isScalarEpilogueAllowed())
4546 return 1;
4547
4549 IsaPred<VPEVLBasedIVPHIRecipe>)) {
4550 LLVM_DEBUG(dbgs() << "LV: Preference for VP intrinsics indicated. "
4551 "Unroll factor forced to be 1.\n");
4552 return 1;
4553 }
4554
4555 // We used the distance for the interleave count.
4556 if (!Legal->isSafeForAnyVectorWidth())
4557 return 1;
4558
4559 // We don't attempt to perform interleaving for loops with uncountable early
4560 // exits because the VPInstruction::AnyOf code cannot currently handle
4561 // multiple parts.
4562 if (Plan.hasEarlyExit())
4563 return 1;
4564
4565 const bool HasReductions =
4567 IsaPred<VPReductionPHIRecipe>);
4568
4569 // If we did not calculate the cost for VF (because the user selected the VF)
4570 // then we calculate the cost of VF here.
4571 if (LoopCost == 0) {
4572 if (VF.isScalar())
4573 LoopCost = CM.expectedCost(VF);
4574 else
4575 LoopCost = cost(Plan, VF);
4576 assert(LoopCost.isValid() && "Expected to have chosen a VF with valid cost");
4577
4578 // Loop body is free and there is no need for interleaving.
4579 if (LoopCost == 0)
4580 return 1;
4581 }
4582
4583 VPRegisterUsage R =
4584 calculateRegisterUsageForPlan(Plan, {VF}, TTI, CM.ValuesToIgnore)[0];
4585 // We divide by these constants so assume that we have at least one
4586 // instruction that uses at least one register.
4587 for (auto &Pair : R.MaxLocalUsers) {
4588 Pair.second = std::max(Pair.second, 1U);
4589 }
4590
4591 // We calculate the interleave count using the following formula.
4592 // Subtract the number of loop invariants from the number of available
4593 // registers. These registers are used by all of the interleaved instances.
4594 // Next, divide the remaining registers by the number of registers that is
4595 // required by the loop, in order to estimate how many parallel instances
4596 // fit without causing spills. All of this is rounded down if necessary to be
4597 // a power of two. We want power of two interleave count to simplify any
4598 // addressing operations or alignment considerations.
4599 // We also want power of two interleave counts to ensure that the induction
4600 // variable of the vector loop wraps to zero, when tail is folded by masking;
4601 // this currently happens when OptForSize, in which case IC is set to 1 above.
4602 unsigned IC = UINT_MAX;
4603
4604 for (const auto &Pair : R.MaxLocalUsers) {
4605 unsigned TargetNumRegisters = TTI.getNumberOfRegisters(Pair.first);
4606 LLVM_DEBUG(dbgs() << "LV: The target has " << TargetNumRegisters
4607 << " registers of "
4608 << TTI.getRegisterClassName(Pair.first)
4609 << " register class\n");
4610 if (VF.isScalar()) {
4611 if (ForceTargetNumScalarRegs.getNumOccurrences() > 0)
4612 TargetNumRegisters = ForceTargetNumScalarRegs;
4613 } else {
4614 if (ForceTargetNumVectorRegs.getNumOccurrences() > 0)
4615 TargetNumRegisters = ForceTargetNumVectorRegs;
4616 }
4617 unsigned MaxLocalUsers = Pair.second;
4618 unsigned LoopInvariantRegs = 0;
4619 if (R.LoopInvariantRegs.contains(Pair.first))
4620 LoopInvariantRegs = R.LoopInvariantRegs[Pair.first];
4621
4622 unsigned TmpIC = llvm::bit_floor((TargetNumRegisters - LoopInvariantRegs) /
4623 MaxLocalUsers);
4624 // Don't count the induction variable as interleaved.
4626 TmpIC = llvm::bit_floor((TargetNumRegisters - LoopInvariantRegs - 1) /
4627 std::max(1U, (MaxLocalUsers - 1)));
4628 }
4629
4630 IC = std::min(IC, TmpIC);
4631 }
4632
4633 // Clamp the interleave ranges to reasonable counts.
4634 unsigned MaxInterleaveCount = TTI.getMaxInterleaveFactor(VF);
4635
4636 // Check if the user has overridden the max.
4637 if (VF.isScalar()) {
4638 if (ForceTargetMaxScalarInterleaveFactor.getNumOccurrences() > 0)
4639 MaxInterleaveCount = ForceTargetMaxScalarInterleaveFactor;
4640 } else {
4641 if (ForceTargetMaxVectorInterleaveFactor.getNumOccurrences() > 0)
4642 MaxInterleaveCount = ForceTargetMaxVectorInterleaveFactor;
4643 }
4644
4645 // Try to get the exact trip count, or an estimate based on profiling data or
4646 // ConstantMax from PSE, failing that.
4647 auto BestKnownTC = getSmallBestKnownTC(PSE, OrigLoop);
4648
4649 // For fixed length VFs treat a scalable trip count as unknown.
4650 if (BestKnownTC && (BestKnownTC->isFixed() || VF.isScalable())) {
4651 // Re-evaluate trip counts and VFs to be in the same numerical space.
4652 unsigned AvailableTC =
4653 estimateElementCount(*BestKnownTC, CM.getVScaleForTuning());
4654 unsigned EstimatedVF = estimateElementCount(VF, CM.getVScaleForTuning());
4655
4656 // At least one iteration must be scalar when this constraint holds. So the
4657 // maximum available iterations for interleaving is one less.
4658 if (CM.requiresScalarEpilogue(VF.isVector()))
4659 --AvailableTC;
4660
4661 unsigned InterleaveCountLB = bit_floor(std::max(
4662 1u, std::min(AvailableTC / (EstimatedVF * 2), MaxInterleaveCount)));
4663
4665 // If the best known trip count is exact, we select between two
4666 // prospective ICs, where
4667 //
4668 // 1) the aggressive IC is capped by the trip count divided by VF
4669 // 2) the conservative IC is capped by the trip count divided by (VF * 2)
4670 //
4671 // The final IC is selected in a way that the epilogue loop trip count is
4672 // minimized while maximizing the IC itself, so that we either run the
4673 // vector loop at least once if it generates a small epilogue loop, or
4674 // else we run the vector loop at least twice.
4675
4676 unsigned InterleaveCountUB = bit_floor(std::max(
4677 1u, std::min(AvailableTC / EstimatedVF, MaxInterleaveCount)));
4678 MaxInterleaveCount = InterleaveCountLB;
4679
4680 if (InterleaveCountUB != InterleaveCountLB) {
4681 unsigned TailTripCountUB =
4682 (AvailableTC % (EstimatedVF * InterleaveCountUB));
4683 unsigned TailTripCountLB =
4684 (AvailableTC % (EstimatedVF * InterleaveCountLB));
4685 // If both produce same scalar tail, maximize the IC to do the same work
4686 // in fewer vector loop iterations
4687 if (TailTripCountUB == TailTripCountLB)
4688 MaxInterleaveCount = InterleaveCountUB;
4689 }
4690 } else {
4691 // If trip count is an estimated compile time constant, limit the
4692 // IC to be capped by the trip count divided by VF * 2, such that the
4693 // vector loop runs at least twice to make interleaving seem profitable
4694 // when there is an epilogue loop present. Since exact Trip count is not
4695 // known we choose to be conservative in our IC estimate.
4696 MaxInterleaveCount = InterleaveCountLB;
4697 }
4698 }
4699
4700 assert(MaxInterleaveCount > 0 &&
4701 "Maximum interleave count must be greater than 0");
4702
4703 // Clamp the calculated IC to be between the 1 and the max interleave count
4704 // that the target and trip count allows.
4705 if (IC > MaxInterleaveCount)
4706 IC = MaxInterleaveCount;
4707 else
4708 // Make sure IC is greater than 0.
4709 IC = std::max(1u, IC);
4710
4711 assert(IC > 0 && "Interleave count must be greater than 0.");
4712
4713 // Interleave if we vectorized this loop and there is a reduction that could
4714 // benefit from interleaving.
4715 if (VF.isVector() && HasReductions) {
4716 LLVM_DEBUG(dbgs() << "LV: Interleaving because of reductions.\n");
4717 return IC;
4718 }
4719
4720 // For any scalar loop that either requires runtime checks or predication we
4721 // are better off leaving this to the unroller. Note that if we've already
4722 // vectorized the loop we will have done the runtime check and so interleaving
4723 // won't require further checks.
4724 bool ScalarInterleavingRequiresPredication =
4725 (VF.isScalar() && any_of(OrigLoop->blocks(), [this](BasicBlock *BB) {
4726 return Legal->blockNeedsPredication(BB);
4727 }));
4728 bool ScalarInterleavingRequiresRuntimePointerCheck =
4729 (VF.isScalar() && Legal->getRuntimePointerChecking()->Need);
4730
4731 // We want to interleave small loops in order to reduce the loop overhead and
4732 // potentially expose ILP opportunities.
4733 LLVM_DEBUG(dbgs() << "LV: Loop cost is " << LoopCost << '\n'
4734 << "LV: IC is " << IC << '\n'
4735 << "LV: VF is " << VF << '\n');
4736 const bool AggressivelyInterleaveReductions =
4737 TTI.enableAggressiveInterleaving(HasReductions);
4738 if (!ScalarInterleavingRequiresRuntimePointerCheck &&
4739 !ScalarInterleavingRequiresPredication && LoopCost < SmallLoopCost) {
4740 // We assume that the cost overhead is 1 and we use the cost model
4741 // to estimate the cost of the loop and interleave until the cost of the
4742 // loop overhead is about 5% of the cost of the loop.
4743 unsigned SmallIC = std::min(IC, (unsigned)llvm::bit_floor<uint64_t>(
4744 SmallLoopCost / LoopCost.getValue()));
4745
4746 // Interleave until store/load ports (estimated by max interleave count) are
4747 // saturated.
4748 unsigned NumStores = 0;
4749 unsigned NumLoads = 0;
4750 for (VPBasicBlock *VPBB : VPBlockUtils::blocksOnly<VPBasicBlock>(
4752 for (VPRecipeBase &R : *VPBB) {
4753 if (isa<VPWidenLoadRecipe, VPWidenLoadEVLRecipe>(&R)) {
4754 NumLoads++;
4755 continue;
4756 }
4757 if (isa<VPWidenStoreRecipe, VPWidenStoreEVLRecipe>(&R)) {
4758 NumStores++;
4759 continue;
4760 }
4761
4762 if (auto *InterleaveR = dyn_cast<VPInterleaveRecipe>(&R)) {
4763 if (unsigned StoreOps = InterleaveR->getNumStoreOperands())
4764 NumStores += StoreOps;
4765 else
4766 NumLoads += InterleaveR->getNumDefinedValues();
4767 continue;
4768 }
4769 if (auto *RepR = dyn_cast<VPReplicateRecipe>(&R)) {
4770 NumLoads += isa<LoadInst>(RepR->getUnderlyingInstr());
4771 NumStores += isa<StoreInst>(RepR->getUnderlyingInstr());
4772 continue;
4773 }
4774 if (isa<VPHistogramRecipe>(&R)) {
4775 NumLoads++;
4776 NumStores++;
4777 continue;
4778 }
4779 }
4780 }
4781 unsigned StoresIC = IC / (NumStores ? NumStores : 1);
4782 unsigned LoadsIC = IC / (NumLoads ? NumLoads : 1);
4783
4784 // There is little point in interleaving for reductions containing selects
4785 // and compares when VF=1 since it may just create more overhead than it's
4786 // worth for loops with small trip counts. This is because we still have to
4787 // do the final reduction after the loop.
4788 bool HasSelectCmpReductions =
4789 HasReductions &&
4791 [](VPRecipeBase &R) {
4792 auto *RedR = dyn_cast<VPReductionPHIRecipe>(&R);
4793 return RedR && (RecurrenceDescriptor::isAnyOfRecurrenceKind(
4794 RedR->getRecurrenceKind()) ||
4795 RecurrenceDescriptor::isFindIVRecurrenceKind(
4796 RedR->getRecurrenceKind()));
4797 });
4798 if (HasSelectCmpReductions) {
4799 LLVM_DEBUG(dbgs() << "LV: Not interleaving select-cmp reductions.\n");
4800 return 1;
4801 }
4802
4803 // If we have a scalar reduction (vector reductions are already dealt with
4804 // by this point), we can increase the critical path length if the loop
4805 // we're interleaving is inside another loop. For tree-wise reductions
4806 // set the limit to 2, and for ordered reductions it's best to disable
4807 // interleaving entirely.
4808 if (HasReductions && OrigLoop->getLoopDepth() > 1) {
4809 bool HasOrderedReductions =
4811 [](VPRecipeBase &R) {
4812 auto *RedR = dyn_cast<VPReductionPHIRecipe>(&R);
4813
4814 return RedR && RedR->isOrdered();
4815 });
4816 if (HasOrderedReductions) {
4817 LLVM_DEBUG(
4818 dbgs() << "LV: Not interleaving scalar ordered reductions.\n");
4819 return 1;
4820 }
4821
4822 unsigned F = MaxNestedScalarReductionIC;
4823 SmallIC = std::min(SmallIC, F);
4824 StoresIC = std::min(StoresIC, F);
4825 LoadsIC = std::min(LoadsIC, F);
4826 }
4827
4829 std::max(StoresIC, LoadsIC) > SmallIC) {
4830 LLVM_DEBUG(
4831 dbgs() << "LV: Interleaving to saturate store or load ports.\n");
4832 return std::max(StoresIC, LoadsIC);
4833 }
4834
4835 // If there are scalar reductions and TTI has enabled aggressive
4836 // interleaving for reductions, we will interleave to expose ILP.
4837 if (VF.isScalar() && AggressivelyInterleaveReductions) {
4838 LLVM_DEBUG(dbgs() << "LV: Interleaving to expose ILP.\n");
4839 // Interleave no less than SmallIC but not as aggressive as the normal IC
4840 // to satisfy the rare situation when resources are too limited.
4841 return std::max(IC / 2, SmallIC);
4842 }
4843
4844 LLVM_DEBUG(dbgs() << "LV: Interleaving to reduce branch cost.\n");
4845 return SmallIC;
4846 }
4847
4848 // Interleave if this is a large loop (small loops are already dealt with by
4849 // this point) that could benefit from interleaving.
4850 if (AggressivelyInterleaveReductions) {
4851 LLVM_DEBUG(dbgs() << "LV: Interleaving to expose ILP.\n");
4852 return IC;
4853 }
4854
4855 LLVM_DEBUG(dbgs() << "LV: Not Interleaving.\n");
4856 return 1;
4857}
4858
4859bool LoopVectorizationCostModel::useEmulatedMaskMemRefHack(Instruction *I,
4860 ElementCount VF) {
4861 // TODO: Cost model for emulated masked load/store is completely
4862 // broken. This hack guides the cost model to use an artificially
4863 // high enough value to practically disable vectorization with such
4864 // operations, except where previously deployed legality hack allowed
4865 // using very low cost values. This is to avoid regressions coming simply
4866 // from moving "masked load/store" check from legality to cost model.
4867 // Masked Load/Gather emulation was previously never allowed.
4868 // Limited number of Masked Store/Scatter emulation was allowed.
4869 assert((isPredicatedInst(I)) &&
4870 "Expecting a scalar emulated instruction");
4871 return isa<LoadInst>(I) ||
4872 (isa<StoreInst>(I) &&
4873 NumPredStores > NumberOfStoresToPredicate);
4874}
4875
4877 assert(VF.isVector() && "Expected VF >= 2");
4878
4879 // If we've already collected the instructions to scalarize or the predicated
4880 // BBs after vectorization, there's nothing to do. Collection may already have
4881 // occurred if we have a user-selected VF and are now computing the expected
4882 // cost for interleaving.
4883 if (InstsToScalarize.contains(VF) ||
4884 PredicatedBBsAfterVectorization.contains(VF))
4885 return;
4886
4887 // Initialize a mapping for VF in InstsToScalalarize. If we find that it's
4888 // not profitable to scalarize any instructions, the presence of VF in the
4889 // map will indicate that we've analyzed it already.
4890 ScalarCostsTy &ScalarCostsVF = InstsToScalarize[VF];
4891
4892 // Find all the instructions that are scalar with predication in the loop and
4893 // determine if it would be better to not if-convert the blocks they are in.
4894 // If so, we also record the instructions to scalarize.
4895 for (BasicBlock *BB : TheLoop->blocks()) {
4896 if (!blockNeedsPredicationForAnyReason(BB))
4897 continue;
4898 for (Instruction &I : *BB)
4899 if (isScalarWithPredication(&I, VF)) {
4900 ScalarCostsTy ScalarCosts;
4901 // Do not apply discount logic for:
4902 // 1. Scalars after vectorization, as there will only be a single copy
4903 // of the instruction.
4904 // 2. Scalable VF, as that would lead to invalid scalarization costs.
4905 // 3. Emulated masked memrefs, if a hacked cost is needed.
4906 if (!isScalarAfterVectorization(&I, VF) && !VF.isScalable() &&
4907 !useEmulatedMaskMemRefHack(&I, VF) &&
4908 computePredInstDiscount(&I, ScalarCosts, VF) >= 0) {
4909 for (const auto &[I, IC] : ScalarCosts)
4910 ScalarCostsVF.insert({I, IC});
4911 // Check if we decided to scalarize a call. If so, update the widening
4912 // decision of the call to CM_Scalarize with the computed scalar cost.
4913 for (const auto &[I, Cost] : ScalarCosts) {
4914 auto *CI = dyn_cast<CallInst>(I);
4915 if (!CI || !CallWideningDecisions.contains({CI, VF}))
4916 continue;
4917 CallWideningDecisions[{CI, VF}].Kind = CM_Scalarize;
4918 CallWideningDecisions[{CI, VF}].Cost = Cost;
4919 }
4920 }
4921 // Remember that BB will remain after vectorization.
4922 PredicatedBBsAfterVectorization[VF].insert(BB);
4923 for (auto *Pred : predecessors(BB)) {
4924 if (Pred->getSingleSuccessor() == BB)
4925 PredicatedBBsAfterVectorization[VF].insert(Pred);
4926 }
4927 }
4928 }
4929}
4930
4931InstructionCost LoopVectorizationCostModel::computePredInstDiscount(
4932 Instruction *PredInst, ScalarCostsTy &ScalarCosts, ElementCount VF) {
4933 assert(!isUniformAfterVectorization(PredInst, VF) &&
4934 "Instruction marked uniform-after-vectorization will be predicated");
4935
4936 // Initialize the discount to zero, meaning that the scalar version and the
4937 // vector version cost the same.
4938 InstructionCost Discount = 0;
4939
4940 // Holds instructions to analyze. The instructions we visit are mapped in
4941 // ScalarCosts. Those instructions are the ones that would be scalarized if
4942 // we find that the scalar version costs less.
4944
4945 // Returns true if the given instruction can be scalarized.
4946 auto CanBeScalarized = [&](Instruction *I) -> bool {
4947 // We only attempt to scalarize instructions forming a single-use chain
4948 // from the original predicated block that would otherwise be vectorized.
4949 // Although not strictly necessary, we give up on instructions we know will
4950 // already be scalar to avoid traversing chains that are unlikely to be
4951 // beneficial.
4952 if (!I->hasOneUse() || PredInst->getParent() != I->getParent() ||
4953 isScalarAfterVectorization(I, VF))
4954 return false;
4955
4956 // If the instruction is scalar with predication, it will be analyzed
4957 // separately. We ignore it within the context of PredInst.
4958 if (isScalarWithPredication(I, VF))
4959 return false;
4960
4961 // If any of the instruction's operands are uniform after vectorization,
4962 // the instruction cannot be scalarized. This prevents, for example, a
4963 // masked load from being scalarized.
4964 //
4965 // We assume we will only emit a value for lane zero of an instruction
4966 // marked uniform after vectorization, rather than VF identical values.
4967 // Thus, if we scalarize an instruction that uses a uniform, we would
4968 // create uses of values corresponding to the lanes we aren't emitting code
4969 // for. This behavior can be changed by allowing getScalarValue to clone
4970 // the lane zero values for uniforms rather than asserting.
4971 for (Use &U : I->operands())
4972 if (auto *J = dyn_cast<Instruction>(U.get()))
4973 if (isUniformAfterVectorization(J, VF))
4974 return false;
4975
4976 // Otherwise, we can scalarize the instruction.
4977 return true;
4978 };
4979
4980 // Compute the expected cost discount from scalarizing the entire expression
4981 // feeding the predicated instruction. We currently only consider expressions
4982 // that are single-use instruction chains.
4983 Worklist.push_back(PredInst);
4984 while (!Worklist.empty()) {
4985 Instruction *I = Worklist.pop_back_val();
4986
4987 // If we've already analyzed the instruction, there's nothing to do.
4988 if (ScalarCosts.contains(I))
4989 continue;
4990
4991 // Cannot scalarize fixed-order recurrence phis at the moment.
4992 if (isa<PHINode>(I) && Legal->isFixedOrderRecurrence(cast<PHINode>(I)))
4993 continue;
4994
4995 // Compute the cost of the vector instruction. Note that this cost already
4996 // includes the scalarization overhead of the predicated instruction.
4997 InstructionCost VectorCost = getInstructionCost(I, VF);
4998
4999 // Compute the cost of the scalarized instruction. This cost is the cost of
5000 // the instruction as if it wasn't if-converted and instead remained in the
5001 // predicated block. We will scale this cost by block probability after
5002 // computing the scalarization overhead.
5003 InstructionCost ScalarCost =
5004 VF.getFixedValue() * getInstructionCost(I, ElementCount::getFixed(1));
5005
5006 // Compute the scalarization overhead of needed insertelement instructions
5007 // and phi nodes.
5008 if (isScalarWithPredication(I, VF) && !I->getType()->isVoidTy()) {
5009 Type *WideTy = toVectorizedTy(I->getType(), VF);
5010 for (Type *VectorTy : getContainedTypes(WideTy)) {
5011 ScalarCost += TTI.getScalarizationOverhead(
5012 cast<VectorType>(VectorTy), APInt::getAllOnes(VF.getFixedValue()),
5013 /*Insert=*/true,
5014 /*Extract=*/false, CostKind);
5015 }
5016 ScalarCost +=
5017 VF.getFixedValue() * TTI.getCFInstrCost(Instruction::PHI, CostKind);
5018 }
5019
5020 // Compute the scalarization overhead of needed extractelement
5021 // instructions. For each of the instruction's operands, if the operand can
5022 // be scalarized, add it to the worklist; otherwise, account for the
5023 // overhead.
5024 for (Use &U : I->operands())
5025 if (auto *J = dyn_cast<Instruction>(U.get())) {
5026 assert(canVectorizeTy(J->getType()) &&
5027 "Instruction has non-scalar type");
5028 if (CanBeScalarized(J))
5029 Worklist.push_back(J);
5030 else if (needsExtract(J, VF)) {
5031 Type *WideTy = toVectorizedTy(J->getType(), VF);
5032 for (Type *VectorTy : getContainedTypes(WideTy)) {
5033 ScalarCost += TTI.getScalarizationOverhead(
5034 cast<VectorType>(VectorTy),
5035 APInt::getAllOnes(VF.getFixedValue()), /*Insert*/ false,
5036 /*Extract*/ true, CostKind);
5037 }
5038 }
5039 }
5040
5041 // Scale the total scalar cost by block probability.
5042 ScalarCost /= getPredBlockCostDivisor(CostKind);
5043
5044 // Compute the discount. A non-negative discount means the vector version
5045 // of the instruction costs more, and scalarizing would be beneficial.
5046 Discount += VectorCost - ScalarCost;
5047 ScalarCosts[I] = ScalarCost;
5048 }
5049
5050 return Discount;
5051}
5052
5055
5056 // If the vector loop gets executed exactly once with the given VF, ignore the
5057 // costs of comparison and induction instructions, as they'll get simplified
5058 // away.
5059 SmallPtrSet<Instruction *, 2> ValuesToIgnoreForVF;
5060 auto TC = getSmallConstantTripCount(PSE.getSE(), TheLoop);
5061 if (TC == VF && !foldTailByMasking())
5062 addFullyUnrolledInstructionsToIgnore(TheLoop, Legal->getInductionVars(),
5063 ValuesToIgnoreForVF);
5064
5065 // For each block.
5066 for (BasicBlock *BB : TheLoop->blocks()) {
5067 InstructionCost BlockCost;
5068
5069 // For each instruction in the old loop.
5070 for (Instruction &I : BB->instructionsWithoutDebug()) {
5071 // Skip ignored values.
5072 if (ValuesToIgnore.count(&I) || ValuesToIgnoreForVF.count(&I) ||
5073 (VF.isVector() && VecValuesToIgnore.count(&I)))
5074 continue;
5075
5076 InstructionCost C = getInstructionCost(&I, VF);
5077
5078 // Check if we should override the cost.
5079 if (C.isValid() && ForceTargetInstructionCost.getNumOccurrences() > 0)
5081
5082 BlockCost += C;
5083 LLVM_DEBUG(dbgs() << "LV: Found an estimated cost of " << C << " for VF "
5084 << VF << " For instruction: " << I << '\n');
5085 }
5086
5087 // If we are vectorizing a predicated block, it will have been
5088 // if-converted. This means that the block's instructions (aside from
5089 // stores and instructions that may divide by zero) will now be
5090 // unconditionally executed. For the scalar case, we may not always execute
5091 // the predicated block, if it is an if-else block. Thus, scale the block's
5092 // cost by the probability of executing it. blockNeedsPredication from
5093 // Legal is used so as to not include all blocks in tail folded loops.
5094 if (VF.isScalar() && Legal->blockNeedsPredication(BB))
5095 BlockCost /= getPredBlockCostDivisor(CostKind);
5096
5097 Cost += BlockCost;
5098 }
5099
5100 return Cost;
5101}
5102
5103/// Gets Address Access SCEV after verifying that the access pattern
5104/// is loop invariant except the induction variable dependence.
5105///
5106/// This SCEV can be sent to the Target in order to estimate the address
5107/// calculation cost.
5109 Value *Ptr,
5112 const Loop *TheLoop) {
5113
5114 auto *Gep = dyn_cast<GetElementPtrInst>(Ptr);
5115 if (!Gep)
5116 return nullptr;
5117
5118 // We are looking for a gep with all loop invariant indices except for one
5119 // which should be an induction variable.
5120 auto *SE = PSE.getSE();
5121 unsigned NumOperands = Gep->getNumOperands();
5122 for (unsigned Idx = 1; Idx < NumOperands; ++Idx) {
5123 Value *Opd = Gep->getOperand(Idx);
5124 if (!SE->isLoopInvariant(SE->getSCEV(Opd), TheLoop) &&
5125 !Legal->isInductionVariable(Opd))
5126 return nullptr;
5127 }
5128
5129 // Now we know we have a GEP ptr, %inv, %ind, %inv. return the Ptr SCEV.
5130 return PSE.getSCEV(Ptr);
5131}
5132
5134LoopVectorizationCostModel::getMemInstScalarizationCost(Instruction *I,
5135 ElementCount VF) {
5136 assert(VF.isVector() &&
5137 "Scalarization cost of instruction implies vectorization.");
5138 if (VF.isScalable())
5140
5141 Type *ValTy = getLoadStoreType(I);
5142 auto *SE = PSE.getSE();
5143
5144 unsigned AS = getLoadStoreAddressSpace(I);
5146 Type *PtrTy = toVectorTy(Ptr->getType(), VF);
5147 // NOTE: PtrTy is a vector to signal `TTI::getAddressComputationCost`
5148 // that it is being called from this specific place.
5149
5150 // Figure out whether the access is strided and get the stride value
5151 // if it's known in compile time
5152 const SCEV *PtrSCEV = getAddressAccessSCEV(Ptr, Legal, PSE, TheLoop);
5153
5154 // Get the cost of the scalar memory instruction and address computation.
5156 PtrTy, SE, PtrSCEV, CostKind);
5157
5158 // Don't pass *I here, since it is scalar but will actually be part of a
5159 // vectorized loop where the user of it is a vectorized instruction.
5160 const Align Alignment = getLoadStoreAlignment(I);
5161 Cost += VF.getFixedValue() * TTI.getMemoryOpCost(I->getOpcode(),
5162 ValTy->getScalarType(),
5163 Alignment, AS, CostKind);
5164
5165 // Get the overhead of the extractelement and insertelement instructions
5166 // we might create due to scalarization.
5168
5169 // If we have a predicated load/store, it will need extra i1 extracts and
5170 // conditional branches, but may not be executed for each vector lane. Scale
5171 // the cost by the probability of executing the predicated block.
5172 if (isPredicatedInst(I)) {
5174
5175 // Add the cost of an i1 extract and a branch
5176 auto *VecI1Ty =
5180 /*Insert=*/false, /*Extract=*/true, CostKind);
5181 Cost += TTI.getCFInstrCost(Instruction::Br, CostKind);
5182
5183 if (useEmulatedMaskMemRefHack(I, VF))
5184 // Artificially setting to a high enough value to practically disable
5185 // vectorization with such operations.
5186 Cost = 3000000;
5187 }
5188
5189 return Cost;
5190}
5191
5193LoopVectorizationCostModel::getConsecutiveMemOpCost(Instruction *I,
5194 ElementCount VF) {
5195 Type *ValTy = getLoadStoreType(I);
5196 auto *VectorTy = cast<VectorType>(toVectorTy(ValTy, VF));
5198 unsigned AS = getLoadStoreAddressSpace(I);
5199 int ConsecutiveStride = Legal->isConsecutivePtr(ValTy, Ptr);
5200
5201 assert((ConsecutiveStride == 1 || ConsecutiveStride == -1) &&
5202 "Stride should be 1 or -1 for consecutive memory access");
5203 const Align Alignment = getLoadStoreAlignment(I);
5205 if (Legal->isMaskRequired(I)) {
5206 Cost += TTI.getMaskedMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS,
5207 CostKind);
5208 } else {
5209 TTI::OperandValueInfo OpInfo = TTI::getOperandInfo(I->getOperand(0));
5210 Cost += TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS,
5211 CostKind, OpInfo, I);
5212 }
5213
5214 bool Reverse = ConsecutiveStride < 0;
5215 if (Reverse)
5217 VectorTy, {}, CostKind, 0);
5218 return Cost;
5219}
5220
5222LoopVectorizationCostModel::getUniformMemOpCost(Instruction *I,
5223 ElementCount VF) {
5224 assert(Legal->isUniformMemOp(*I, VF));
5225
5226 Type *ValTy = getLoadStoreType(I);
5228 auto *VectorTy = cast<VectorType>(toVectorTy(ValTy, VF));
5229 const Align Alignment = getLoadStoreAlignment(I);
5230 unsigned AS = getLoadStoreAddressSpace(I);
5231 if (isa<LoadInst>(I)) {
5232 return TTI.getAddressComputationCost(PtrTy, nullptr, nullptr, CostKind) +
5233 TTI.getMemoryOpCost(Instruction::Load, ValTy, Alignment, AS,
5234 CostKind) +
5236 VectorTy, {}, CostKind);
5237 }
5238 StoreInst *SI = cast<StoreInst>(I);
5239
5240 bool IsLoopInvariantStoreValue = Legal->isInvariant(SI->getValueOperand());
5241 // TODO: We have existing tests that request the cost of extracting element
5242 // VF.getKnownMinValue() - 1 from a scalable vector. This does not represent
5243 // the actual generated code, which involves extracting the last element of
5244 // a scalable vector where the lane to extract is unknown at compile time.
5246 TTI.getAddressComputationCost(PtrTy, nullptr, nullptr, CostKind) +
5247 TTI.getMemoryOpCost(Instruction::Store, ValTy, Alignment, AS, CostKind);
5248 if (!IsLoopInvariantStoreValue)
5249 Cost += TTI.getIndexedVectorInstrCostFromEnd(Instruction::ExtractElement,
5250 VectorTy, CostKind, 0);
5251 return Cost;
5252}
5253
5255LoopVectorizationCostModel::getGatherScatterCost(Instruction *I,
5256 ElementCount VF) {
5257 Type *ValTy = getLoadStoreType(I);
5258 auto *VectorTy = cast<VectorType>(toVectorTy(ValTy, VF));
5259 const Align Alignment = getLoadStoreAlignment(I);
5261 Type *PtrTy = toVectorTy(Ptr->getType(), VF);
5262
5263 return TTI.getAddressComputationCost(PtrTy, nullptr, nullptr, CostKind) +
5264 TTI.getGatherScatterOpCost(I->getOpcode(), VectorTy, Ptr,
5265 Legal->isMaskRequired(I), Alignment,
5266 CostKind, I);
5267}
5268
5270LoopVectorizationCostModel::getInterleaveGroupCost(Instruction *I,
5271 ElementCount VF) {
5272 const auto *Group = getInterleavedAccessGroup(I);
5273 assert(Group && "Fail to get an interleaved access group.");
5274
5275 Instruction *InsertPos = Group->getInsertPos();
5276 Type *ValTy = getLoadStoreType(InsertPos);
5277 auto *VectorTy = cast<VectorType>(toVectorTy(ValTy, VF));
5278 unsigned AS = getLoadStoreAddressSpace(InsertPos);
5279
5280 unsigned InterleaveFactor = Group->getFactor();
5281 auto *WideVecTy = VectorType::get(ValTy, VF * InterleaveFactor);
5282
5283 // Holds the indices of existing members in the interleaved group.
5285 for (unsigned IF = 0; IF < InterleaveFactor; IF++)
5286 if (Group->getMember(IF))
5287 Indices.push_back(IF);
5288
5289 // Calculate the cost of the whole interleaved group.
5290 bool UseMaskForGaps =
5291 (Group->requiresScalarEpilogue() && !isScalarEpilogueAllowed()) ||
5292 (isa<StoreInst>(I) && !Group->isFull());
5294 InsertPos->getOpcode(), WideVecTy, Group->getFactor(), Indices,
5295 Group->getAlign(), AS, CostKind, Legal->isMaskRequired(I),
5296 UseMaskForGaps);
5297
5298 if (Group->isReverse()) {
5299 // TODO: Add support for reversed masked interleaved access.
5300 assert(!Legal->isMaskRequired(I) &&
5301 "Reverse masked interleaved access not supported.");
5302 Cost += Group->getNumMembers() *
5304 VectorTy, {}, CostKind, 0);
5305 }
5306 return Cost;
5307}
5308
5309std::optional<InstructionCost>
5312 Type *Ty) const {
5313 using namespace llvm::PatternMatch;
5314 // Early exit for no inloop reductions
5315 if (InLoopReductions.empty() || VF.isScalar() || !isa<VectorType>(Ty))
5316 return std::nullopt;
5317 auto *VectorTy = cast<VectorType>(Ty);
5318
5319 // We are looking for a pattern of, and finding the minimal acceptable cost:
5320 // reduce(mul(ext(A), ext(B))) or
5321 // reduce(mul(A, B)) or
5322 // reduce(ext(A)) or
5323 // reduce(A).
5324 // The basic idea is that we walk down the tree to do that, finding the root
5325 // reduction instruction in InLoopReductionImmediateChains. From there we find
5326 // the pattern of mul/ext and test the cost of the entire pattern vs the cost
5327 // of the components. If the reduction cost is lower then we return it for the
5328 // reduction instruction and 0 for the other instructions in the pattern. If
5329 // it is not we return an invalid cost specifying the orignal cost method
5330 // should be used.
5331 Instruction *RetI = I;
5332 if (match(RetI, m_ZExtOrSExt(m_Value()))) {
5333 if (!RetI->hasOneUser())
5334 return std::nullopt;
5335 RetI = RetI->user_back();
5336 }
5337
5338 if (match(RetI, m_OneUse(m_Mul(m_Value(), m_Value()))) &&
5339 RetI->user_back()->getOpcode() == Instruction::Add) {
5340 RetI = RetI->user_back();
5341 }
5342
5343 // Test if the found instruction is a reduction, and if not return an invalid
5344 // cost specifying the parent to use the original cost modelling.
5345 Instruction *LastChain = InLoopReductionImmediateChains.lookup(RetI);
5346 if (!LastChain)
5347 return std::nullopt;
5348
5349 // Find the reduction this chain is a part of and calculate the basic cost of
5350 // the reduction on its own.
5351 Instruction *ReductionPhi = LastChain;
5352 while (!isa<PHINode>(ReductionPhi))
5353 ReductionPhi = InLoopReductionImmediateChains.at(ReductionPhi);
5354
5355 const RecurrenceDescriptor &RdxDesc =
5356 Legal->getRecurrenceDescriptor(cast<PHINode>(ReductionPhi));
5357
5358 InstructionCost BaseCost;
5359 RecurKind RK = RdxDesc.getRecurrenceKind();
5362 BaseCost = TTI.getMinMaxReductionCost(MinMaxID, VectorTy,
5363 RdxDesc.getFastMathFlags(), CostKind);
5364 } else {
5366 RdxDesc.getOpcode(), VectorTy, RdxDesc.getFastMathFlags(), CostKind);
5367 }
5368
5369 // For a call to the llvm.fmuladd intrinsic we need to add the cost of a
5370 // normal fmul instruction to the cost of the fadd reduction.
5371 if (RK == RecurKind::FMulAdd)
5372 BaseCost +=
5373 TTI.getArithmeticInstrCost(Instruction::FMul, VectorTy, CostKind);
5374
5375 // If we're using ordered reductions then we can just return the base cost
5376 // here, since getArithmeticReductionCost calculates the full ordered
5377 // reduction cost when FP reassociation is not allowed.
5378 if (useOrderedReductions(RdxDesc))
5379 return BaseCost;
5380
5381 // Get the operand that was not the reduction chain and match it to one of the
5382 // patterns, returning the better cost if it is found.
5383 Instruction *RedOp = RetI->getOperand(1) == LastChain
5384 ? dyn_cast<Instruction>(RetI->getOperand(0))
5385 : dyn_cast<Instruction>(RetI->getOperand(1));
5386
5387 VectorTy = VectorType::get(I->getOperand(0)->getType(), VectorTy);
5388
5389 Instruction *Op0, *Op1;
5390 if (RedOp && RdxDesc.getOpcode() == Instruction::Add &&
5391 match(RedOp,
5393 match(Op0, m_ZExtOrSExt(m_Value())) &&
5394 Op0->getOpcode() == Op1->getOpcode() &&
5395 Op0->getOperand(0)->getType() == Op1->getOperand(0)->getType() &&
5396 !TheLoop->isLoopInvariant(Op0) && !TheLoop->isLoopInvariant(Op1) &&
5397 (Op0->getOpcode() == RedOp->getOpcode() || Op0 == Op1)) {
5398
5399 // Matched reduce.add(ext(mul(ext(A), ext(B)))
5400 // Note that the extend opcodes need to all match, or if A==B they will have
5401 // been converted to zext(mul(sext(A), sext(A))) as it is known positive,
5402 // which is equally fine.
5403 bool IsUnsigned = isa<ZExtInst>(Op0);
5404 auto *ExtType = VectorType::get(Op0->getOperand(0)->getType(), VectorTy);
5405 auto *MulType = VectorType::get(Op0->getType(), VectorTy);
5406
5407 InstructionCost ExtCost =
5408 TTI.getCastInstrCost(Op0->getOpcode(), MulType, ExtType,
5410 InstructionCost MulCost =
5411 TTI.getArithmeticInstrCost(Instruction::Mul, MulType, CostKind);
5412 InstructionCost Ext2Cost =
5413 TTI.getCastInstrCost(RedOp->getOpcode(), VectorTy, MulType,
5415
5417 IsUnsigned, RdxDesc.getRecurrenceType(), ExtType, CostKind);
5418
5419 if (RedCost.isValid() &&
5420 RedCost < ExtCost * 2 + MulCost + Ext2Cost + BaseCost)
5421 return I == RetI ? RedCost : 0;
5422 } else if (RedOp && match(RedOp, m_ZExtOrSExt(m_Value())) &&
5423 !TheLoop->isLoopInvariant(RedOp)) {
5424 // Matched reduce(ext(A))
5425 bool IsUnsigned = isa<ZExtInst>(RedOp);
5426 auto *ExtType = VectorType::get(RedOp->getOperand(0)->getType(), VectorTy);
5428 RdxDesc.getOpcode(), IsUnsigned, RdxDesc.getRecurrenceType(), ExtType,
5429 RdxDesc.getFastMathFlags(), CostKind);
5430
5431 InstructionCost ExtCost =
5432 TTI.getCastInstrCost(RedOp->getOpcode(), VectorTy, ExtType,
5434 if (RedCost.isValid() && RedCost < BaseCost + ExtCost)
5435 return I == RetI ? RedCost : 0;
5436 } else if (RedOp && RdxDesc.getOpcode() == Instruction::Add &&
5437 match(RedOp, m_Mul(m_Instruction(Op0), m_Instruction(Op1)))) {
5438 if (match(Op0, m_ZExtOrSExt(m_Value())) &&
5439 Op0->getOpcode() == Op1->getOpcode() &&
5440 !TheLoop->isLoopInvariant(Op0) && !TheLoop->isLoopInvariant(Op1)) {
5441 bool IsUnsigned = isa<ZExtInst>(Op0);
5442 Type *Op0Ty = Op0->getOperand(0)->getType();
5443 Type *Op1Ty = Op1->getOperand(0)->getType();
5444 Type *LargestOpTy =
5445 Op0Ty->getIntegerBitWidth() < Op1Ty->getIntegerBitWidth() ? Op1Ty
5446 : Op0Ty;
5447 auto *ExtType = VectorType::get(LargestOpTy, VectorTy);
5448
5449 // Matched reduce.add(mul(ext(A), ext(B))), where the two ext may be of
5450 // different sizes. We take the largest type as the ext to reduce, and add
5451 // the remaining cost as, for example reduce(mul(ext(ext(A)), ext(B))).
5453 Op0->getOpcode(), VectorTy, VectorType::get(Op0Ty, VectorTy),
5456 Op1->getOpcode(), VectorTy, VectorType::get(Op1Ty, VectorTy),
5458 InstructionCost MulCost =
5459 TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy, CostKind);
5460
5462 IsUnsigned, RdxDesc.getRecurrenceType(), ExtType, CostKind);
5463 InstructionCost ExtraExtCost = 0;
5464 if (Op0Ty != LargestOpTy || Op1Ty != LargestOpTy) {
5465 Instruction *ExtraExtOp = (Op0Ty != LargestOpTy) ? Op0 : Op1;
5466 ExtraExtCost = TTI.getCastInstrCost(
5467 ExtraExtOp->getOpcode(), ExtType,
5468 VectorType::get(ExtraExtOp->getOperand(0)->getType(), VectorTy),
5470 }
5471
5472 if (RedCost.isValid() &&
5473 (RedCost + ExtraExtCost) < (ExtCost0 + ExtCost1 + MulCost + BaseCost))
5474 return I == RetI ? RedCost : 0;
5475 } else if (!match(I, m_ZExtOrSExt(m_Value()))) {
5476 // Matched reduce.add(mul())
5477 InstructionCost MulCost =
5478 TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy, CostKind);
5479
5481 true, RdxDesc.getRecurrenceType(), VectorTy, CostKind);
5482
5483 if (RedCost.isValid() && RedCost < MulCost + BaseCost)
5484 return I == RetI ? RedCost : 0;
5485 }
5486 }
5487
5488 return I == RetI ? std::optional<InstructionCost>(BaseCost) : std::nullopt;
5489}
5490
5492LoopVectorizationCostModel::getMemoryInstructionCost(Instruction *I,
5493 ElementCount VF) {
5494 // Calculate scalar cost only. Vectorization cost should be ready at this
5495 // moment.
5496 if (VF.isScalar()) {
5497 Type *ValTy = getLoadStoreType(I);
5499 const Align Alignment = getLoadStoreAlignment(I);
5500 unsigned AS = getLoadStoreAddressSpace(I);
5501
5502 TTI::OperandValueInfo OpInfo = TTI::getOperandInfo(I->getOperand(0));
5503 return TTI.getAddressComputationCost(PtrTy, nullptr, nullptr, CostKind) +
5504 TTI.getMemoryOpCost(I->getOpcode(), ValTy, Alignment, AS, CostKind,
5505 OpInfo, I);
5506 }
5507 return getWideningCost(I, VF);
5508}
5509
5511LoopVectorizationCostModel::getScalarizationOverhead(Instruction *I,
5512 ElementCount VF) const {
5513
5514 // There is no mechanism yet to create a scalable scalarization loop,
5515 // so this is currently Invalid.
5516 if (VF.isScalable())
5518
5519 if (VF.isScalar())
5520 return 0;
5521
5523 Type *RetTy = toVectorizedTy(I->getType(), VF);
5524 if (!RetTy->isVoidTy() &&
5525 (!isa<LoadInst>(I) || !TTI.supportsEfficientVectorElementLoadStore())) {
5526
5527 for (Type *VectorTy : getContainedTypes(RetTy)) {
5529 cast<VectorType>(VectorTy), APInt::getAllOnes(VF.getFixedValue()),
5530 /*Insert=*/true,
5531 /*Extract=*/false, CostKind);
5532 }
5533 }
5534
5535 // Some targets keep addresses scalar.
5536 if (isa<LoadInst>(I) && !TTI.prefersVectorizedAddressing())
5537 return Cost;
5538
5539 // Some targets support efficient element stores.
5540 if (isa<StoreInst>(I) && TTI.supportsEfficientVectorElementLoadStore())
5541 return Cost;
5542
5543 // Collect operands to consider.
5544 CallInst *CI = dyn_cast<CallInst>(I);
5545 Instruction::op_range Ops = CI ? CI->args() : I->operands();
5546
5547 // Skip operands that do not require extraction/scalarization and do not incur
5548 // any overhead.
5550 for (auto *V : filterExtractingOperands(Ops, VF))
5551 Tys.push_back(maybeVectorizeType(V->getType(), VF));
5553}
5554
5556 if (VF.isScalar())
5557 return;
5558 NumPredStores = 0;
5559 for (BasicBlock *BB : TheLoop->blocks()) {
5560 // For each instruction in the old loop.
5561 for (Instruction &I : *BB) {
5563 if (!Ptr)
5564 continue;
5565
5566 // TODO: We should generate better code and update the cost model for
5567 // predicated uniform stores. Today they are treated as any other
5568 // predicated store (see added test cases in
5569 // invariant-store-vectorization.ll).
5570 if (isa<StoreInst>(&I) && isScalarWithPredication(&I, VF))
5571 NumPredStores++;
5572
5573 if (Legal->isUniformMemOp(I, VF)) {
5574 auto IsLegalToScalarize = [&]() {
5575 if (!VF.isScalable())
5576 // Scalarization of fixed length vectors "just works".
5577 return true;
5578
5579 // We have dedicated lowering for unpredicated uniform loads and
5580 // stores. Note that even with tail folding we know that at least
5581 // one lane is active (i.e. generalized predication is not possible
5582 // here), and the logic below depends on this fact.
5583 if (!foldTailByMasking())
5584 return true;
5585
5586 // For scalable vectors, a uniform memop load is always
5587 // uniform-by-parts and we know how to scalarize that.
5588 if (isa<LoadInst>(I))
5589 return true;
5590
5591 // A uniform store isn't neccessarily uniform-by-part
5592 // and we can't assume scalarization.
5593 auto &SI = cast<StoreInst>(I);
5594 return TheLoop->isLoopInvariant(SI.getValueOperand());
5595 };
5596
5597 const InstructionCost GatherScatterCost =
5598 isLegalGatherOrScatter(&I, VF) ?
5599 getGatherScatterCost(&I, VF) : InstructionCost::getInvalid();
5600
5601 // Load: Scalar load + broadcast
5602 // Store: Scalar store + isLoopInvariantStoreValue ? 0 : extract
5603 // FIXME: This cost is a significant under-estimate for tail folded
5604 // memory ops.
5605 const InstructionCost ScalarizationCost =
5606 IsLegalToScalarize() ? getUniformMemOpCost(&I, VF)
5608
5609 // Choose better solution for the current VF, Note that Invalid
5610 // costs compare as maximumal large. If both are invalid, we get
5611 // scalable invalid which signals a failure and a vectorization abort.
5612 if (GatherScatterCost < ScalarizationCost)
5613 setWideningDecision(&I, VF, CM_GatherScatter, GatherScatterCost);
5614 else
5615 setWideningDecision(&I, VF, CM_Scalarize, ScalarizationCost);
5616 continue;
5617 }
5618
5619 // We assume that widening is the best solution when possible.
5620 if (memoryInstructionCanBeWidened(&I, VF)) {
5621 InstructionCost Cost = getConsecutiveMemOpCost(&I, VF);
5622 int ConsecutiveStride = Legal->isConsecutivePtr(
5624 assert((ConsecutiveStride == 1 || ConsecutiveStride == -1) &&
5625 "Expected consecutive stride.");
5626 InstWidening Decision =
5627 ConsecutiveStride == 1 ? CM_Widen : CM_Widen_Reverse;
5628 setWideningDecision(&I, VF, Decision, Cost);
5629 continue;
5630 }
5631
5632 // Choose between Interleaving, Gather/Scatter or Scalarization.
5634 unsigned NumAccesses = 1;
5635 if (isAccessInterleaved(&I)) {
5636 const auto *Group = getInterleavedAccessGroup(&I);
5637 assert(Group && "Fail to get an interleaved access group.");
5638
5639 // Make one decision for the whole group.
5640 if (getWideningDecision(&I, VF) != CM_Unknown)
5641 continue;
5642
5643 NumAccesses = Group->getNumMembers();
5644 if (interleavedAccessCanBeWidened(&I, VF))
5645 InterleaveCost = getInterleaveGroupCost(&I, VF);
5646 }
5647
5648 InstructionCost GatherScatterCost =
5649 isLegalGatherOrScatter(&I, VF)
5650 ? getGatherScatterCost(&I, VF) * NumAccesses
5652
5653 InstructionCost ScalarizationCost =
5654 getMemInstScalarizationCost(&I, VF) * NumAccesses;
5655
5656 // Choose better solution for the current VF,
5657 // write down this decision and use it during vectorization.
5659 InstWidening Decision;
5660 if (InterleaveCost <= GatherScatterCost &&
5661 InterleaveCost < ScalarizationCost) {
5662 Decision = CM_Interleave;
5663 Cost = InterleaveCost;
5664 } else if (GatherScatterCost < ScalarizationCost) {
5665 Decision = CM_GatherScatter;
5666 Cost = GatherScatterCost;
5667 } else {
5668 Decision = CM_Scalarize;
5669 Cost = ScalarizationCost;
5670 }
5671 // If the instructions belongs to an interleave group, the whole group
5672 // receives the same decision. The whole group receives the cost, but
5673 // the cost will actually be assigned to one instruction.
5674 if (const auto *Group = getInterleavedAccessGroup(&I))
5675 setWideningDecision(Group, VF, Decision, Cost);
5676 else
5677 setWideningDecision(&I, VF, Decision, Cost);
5678 }
5679 }
5680
5681 // Make sure that any load of address and any other address computation
5682 // remains scalar unless there is gather/scatter support. This avoids
5683 // inevitable extracts into address registers, and also has the benefit of
5684 // activating LSR more, since that pass can't optimize vectorized
5685 // addresses.
5687 return;
5688
5689 // Start with all scalar pointer uses.
5691 for (BasicBlock *BB : TheLoop->blocks())
5692 for (Instruction &I : *BB) {
5693 Instruction *PtrDef =
5694 dyn_cast_or_null<Instruction>(getLoadStorePointerOperand(&I));
5695 if (PtrDef && TheLoop->contains(PtrDef) &&
5696 getWideningDecision(&I, VF) != CM_GatherScatter)
5697 AddrDefs.insert(PtrDef);
5698 }
5699
5700 // Add all instructions used to generate the addresses.
5702 append_range(Worklist, AddrDefs);
5703 while (!Worklist.empty()) {
5704 Instruction *I = Worklist.pop_back_val();
5705 for (auto &Op : I->operands())
5706 if (auto *InstOp = dyn_cast<Instruction>(Op))
5707 if ((InstOp->getParent() == I->getParent()) && !isa<PHINode>(InstOp) &&
5708 AddrDefs.insert(InstOp).second)
5709 Worklist.push_back(InstOp);
5710 }
5711
5712 for (auto *I : AddrDefs) {
5713 if (isa<LoadInst>(I)) {
5714 // Setting the desired widening decision should ideally be handled in
5715 // by cost functions, but since this involves the task of finding out
5716 // if the loaded register is involved in an address computation, it is
5717 // instead changed here when we know this is the case.
5718 InstWidening Decision = getWideningDecision(I, VF);
5719 if (Decision == CM_Widen || Decision == CM_Widen_Reverse)
5720 // Scalarize a widened load of address.
5721 setWideningDecision(
5722 I, VF, CM_Scalarize,
5723 (VF.getKnownMinValue() *
5724 getMemoryInstructionCost(I, ElementCount::getFixed(1))));
5725 else if (const auto *Group = getInterleavedAccessGroup(I)) {
5726 // Scalarize an interleave group of address loads.
5727 for (unsigned I = 0; I < Group->getFactor(); ++I) {
5728 if (Instruction *Member = Group->getMember(I))
5729 setWideningDecision(
5730 Member, VF, CM_Scalarize,
5731 (VF.getKnownMinValue() *
5732 getMemoryInstructionCost(Member, ElementCount::getFixed(1))));
5733 }
5734 }
5735 } else {
5736 // Cannot scalarize fixed-order recurrence phis at the moment.
5737 if (isa<PHINode>(I) && Legal->isFixedOrderRecurrence(cast<PHINode>(I)))
5738 continue;
5739
5740 // Make sure I gets scalarized and a cost estimate without
5741 // scalarization overhead.
5742 ForcedScalars[VF].insert(I);
5743 }
5744 }
5745}
5746
5748 assert(!VF.isScalar() &&
5749 "Trying to set a vectorization decision for a scalar VF");
5750
5751 auto ForcedScalar = ForcedScalars.find(VF);
5752 for (BasicBlock *BB : TheLoop->blocks()) {
5753 // For each instruction in the old loop.
5754 for (Instruction &I : *BB) {
5755 CallInst *CI = dyn_cast<CallInst>(&I);
5756
5757 if (!CI)
5758 continue;
5759
5763 Function *ScalarFunc = CI->getCalledFunction();
5764 Type *ScalarRetTy = CI->getType();
5765 SmallVector<Type *, 4> Tys, ScalarTys;
5766 for (auto &ArgOp : CI->args())
5767 ScalarTys.push_back(ArgOp->getType());
5768
5769 // Estimate cost of scalarized vector call. The source operands are
5770 // assumed to be vectors, so we need to extract individual elements from
5771 // there, execute VF scalar calls, and then gather the result into the
5772 // vector return value.
5773 if (VF.isFixed()) {
5774 InstructionCost ScalarCallCost =
5775 TTI.getCallInstrCost(ScalarFunc, ScalarRetTy, ScalarTys, CostKind);
5776
5777 // Compute costs of unpacking argument values for the scalar calls and
5778 // packing the return values to a vector.
5779 InstructionCost ScalarizationCost = getScalarizationOverhead(CI, VF);
5780 ScalarCost = ScalarCallCost * VF.getKnownMinValue() + ScalarizationCost;
5781 } else {
5782 // There is no point attempting to calculate the scalar cost for a
5783 // scalable VF as we know it will be Invalid.
5785 "Unexpected valid cost for scalarizing scalable vectors");
5786 ScalarCost = InstructionCost::getInvalid();
5787 }
5788
5789 // Honor ForcedScalars and UniformAfterVectorization decisions.
5790 // TODO: For calls, it might still be more profitable to widen. Use
5791 // VPlan-based cost model to compare different options.
5792 if (VF.isVector() && ((ForcedScalar != ForcedScalars.end() &&
5793 ForcedScalar->second.contains(CI)) ||
5794 isUniformAfterVectorization(CI, VF))) {
5795 setCallWideningDecision(CI, VF, CM_Scalarize, nullptr,
5796 Intrinsic::not_intrinsic, std::nullopt,
5797 ScalarCost);
5798 continue;
5799 }
5800
5801 bool MaskRequired = Legal->isMaskRequired(CI);
5802 // Compute corresponding vector type for return value and arguments.
5803 Type *RetTy = toVectorizedTy(ScalarRetTy, VF);
5804 for (Type *ScalarTy : ScalarTys)
5805 Tys.push_back(toVectorizedTy(ScalarTy, VF));
5806
5807 // An in-loop reduction using an fmuladd intrinsic is a special case;
5808 // we don't want the normal cost for that intrinsic.
5810 if (auto RedCost = getReductionPatternCost(CI, VF, RetTy)) {
5811 setCallWideningDecision(CI, VF, CM_IntrinsicCall, nullptr,
5813 std::nullopt, *RedCost);
5814 continue;
5815 }
5816
5817 // Find the cost of vectorizing the call, if we can find a suitable
5818 // vector variant of the function.
5819 VFInfo FuncInfo;
5820 Function *VecFunc = nullptr;
5821 // Search through any available variants for one we can use at this VF.
5822 for (VFInfo &Info : VFDatabase::getMappings(*CI)) {
5823 // Must match requested VF.
5824 if (Info.Shape.VF != VF)
5825 continue;
5826
5827 // Must take a mask argument if one is required
5828 if (MaskRequired && !Info.isMasked())
5829 continue;
5830
5831 // Check that all parameter kinds are supported
5832 bool ParamsOk = true;
5833 for (VFParameter Param : Info.Shape.Parameters) {
5834 switch (Param.ParamKind) {
5836 break;
5838 Value *ScalarParam = CI->getArgOperand(Param.ParamPos);
5839 // Make sure the scalar parameter in the loop is invariant.
5840 if (!PSE.getSE()->isLoopInvariant(PSE.getSCEV(ScalarParam),
5841 TheLoop))
5842 ParamsOk = false;
5843 break;
5844 }
5846 Value *ScalarParam = CI->getArgOperand(Param.ParamPos);
5847 // Find the stride for the scalar parameter in this loop and see if
5848 // it matches the stride for the variant.
5849 // TODO: do we need to figure out the cost of an extract to get the
5850 // first lane? Or do we hope that it will be folded away?
5851 ScalarEvolution *SE = PSE.getSE();
5852 if (!match(SE->getSCEV(ScalarParam),
5854 m_SCEV(), m_scev_SpecificSInt(Param.LinearStepOrPos),
5855 m_SpecificLoop(TheLoop))))
5856 ParamsOk = false;
5857 break;
5858 }
5860 break;
5861 default:
5862 ParamsOk = false;
5863 break;
5864 }
5865 }
5866
5867 if (!ParamsOk)
5868 continue;
5869
5870 // Found a suitable candidate, stop here.
5871 VecFunc = CI->getModule()->getFunction(Info.VectorName);
5872 FuncInfo = Info;
5873 break;
5874 }
5875
5876 if (TLI && VecFunc && !CI->isNoBuiltin())
5877 VectorCost = TTI.getCallInstrCost(nullptr, RetTy, Tys, CostKind);
5878
5879 // Find the cost of an intrinsic; some targets may have instructions that
5880 // perform the operation without needing an actual call.
5882 if (IID != Intrinsic::not_intrinsic)
5883 IntrinsicCost = getVectorIntrinsicCost(CI, VF);
5884
5885 InstructionCost Cost = ScalarCost;
5886 InstWidening Decision = CM_Scalarize;
5887
5888 if (VectorCost <= Cost) {
5889 Cost = VectorCost;
5890 Decision = CM_VectorCall;
5891 }
5892
5893 if (IntrinsicCost <= Cost) {
5895 Decision = CM_IntrinsicCall;
5896 }
5897
5898 setCallWideningDecision(CI, VF, Decision, VecFunc, IID,
5900 }
5901 }
5902}
5903
5905 if (!Legal->isInvariant(Op))
5906 return false;
5907 // Consider Op invariant, if it or its operands aren't predicated
5908 // instruction in the loop. In that case, it is not trivially hoistable.
5909 auto *OpI = dyn_cast<Instruction>(Op);
5910 return !OpI || !TheLoop->contains(OpI) ||
5911 (!isPredicatedInst(OpI) &&
5912 (!isa<PHINode>(OpI) || OpI->getParent() != TheLoop->getHeader()) &&
5913 all_of(OpI->operands(),
5914 [this](Value *Op) { return shouldConsiderInvariant(Op); }));
5915}
5916
5919 ElementCount VF) {
5920 // If we know that this instruction will remain uniform, check the cost of
5921 // the scalar version.
5922 if (isUniformAfterVectorization(I, VF))
5924
5925 if (VF.isVector() && isProfitableToScalarize(I, VF))
5926 return InstsToScalarize[VF][I];
5927
5928 // Forced scalars do not have any scalarization overhead.
5929 auto ForcedScalar = ForcedScalars.find(VF);
5930 if (VF.isVector() && ForcedScalar != ForcedScalars.end()) {
5931 auto InstSet = ForcedScalar->second;
5932 if (InstSet.count(I))
5933 return getInstructionCost(I, ElementCount::getFixed(1)) *
5935 }
5936
5937 Type *RetTy = I->getType();
5938 if (canTruncateToMinimalBitwidth(I, VF))
5939 RetTy = IntegerType::get(RetTy->getContext(), MinBWs[I]);
5940 auto *SE = PSE.getSE();
5941
5942 Type *VectorTy;
5943 if (isScalarAfterVectorization(I, VF)) {
5944 [[maybe_unused]] auto HasSingleCopyAfterVectorization =
5945 [this](Instruction *I, ElementCount VF) -> bool {
5946 if (VF.isScalar())
5947 return true;
5948
5949 auto Scalarized = InstsToScalarize.find(VF);
5950 assert(Scalarized != InstsToScalarize.end() &&
5951 "VF not yet analyzed for scalarization profitability");
5952 return !Scalarized->second.count(I) &&
5953 llvm::all_of(I->users(), [&](User *U) {
5954 auto *UI = cast<Instruction>(U);
5955 return !Scalarized->second.count(UI);
5956 });
5957 };
5958
5959 // With the exception of GEPs and PHIs, after scalarization there should
5960 // only be one copy of the instruction generated in the loop. This is
5961 // because the VF is either 1, or any instructions that need scalarizing
5962 // have already been dealt with by the time we get here. As a result,
5963 // it means we don't have to multiply the instruction cost by VF.
5964 assert(I->getOpcode() == Instruction::GetElementPtr ||
5965 I->getOpcode() == Instruction::PHI ||
5966 (I->getOpcode() == Instruction::BitCast &&
5967 I->getType()->isPointerTy()) ||
5968 HasSingleCopyAfterVectorization(I, VF));
5969 VectorTy = RetTy;
5970 } else
5971 VectorTy = toVectorizedTy(RetTy, VF);
5972
5973 if (VF.isVector() && VectorTy->isVectorTy() &&
5974 !TTI.getNumberOfParts(VectorTy))
5976
5977 // TODO: We need to estimate the cost of intrinsic calls.
5978 switch (I->getOpcode()) {
5979 case Instruction::GetElementPtr:
5980 // We mark this instruction as zero-cost because the cost of GEPs in
5981 // vectorized code depends on whether the corresponding memory instruction
5982 // is scalarized or not. Therefore, we handle GEPs with the memory
5983 // instruction cost.
5984 return 0;
5985 case Instruction::Br: {
5986 // In cases of scalarized and predicated instructions, there will be VF
5987 // predicated blocks in the vectorized loop. Each branch around these
5988 // blocks requires also an extract of its vector compare i1 element.
5989 // Note that the conditional branch from the loop latch will be replaced by
5990 // a single branch controlling the loop, so there is no extra overhead from
5991 // scalarization.
5992 bool ScalarPredicatedBB = false;
5993 BranchInst *BI = cast<BranchInst>(I);
5994 if (VF.isVector() && BI->isConditional() &&
5995 (PredicatedBBsAfterVectorization[VF].count(BI->getSuccessor(0)) ||
5996 PredicatedBBsAfterVectorization[VF].count(BI->getSuccessor(1))) &&
5997 BI->getParent() != TheLoop->getLoopLatch())
5998 ScalarPredicatedBB = true;
5999
6000 if (ScalarPredicatedBB) {
6001 // Not possible to scalarize scalable vector with predicated instructions.
6002 if (VF.isScalable())
6004 // Return cost for branches around scalarized and predicated blocks.
6005 auto *VecI1Ty =
6007 return (
6010 /*Insert*/ false, /*Extract*/ true, CostKind) +
6011 (TTI.getCFInstrCost(Instruction::Br, CostKind) * VF.getFixedValue()));
6012 }
6013
6014 if (I->getParent() == TheLoop->getLoopLatch() || VF.isScalar())
6015 // The back-edge branch will remain, as will all scalar branches.
6016 return TTI.getCFInstrCost(Instruction::Br, CostKind);
6017
6018 // This branch will be eliminated by if-conversion.
6019 return 0;
6020 // Note: We currently assume zero cost for an unconditional branch inside
6021 // a predicated block since it will become a fall-through, although we
6022 // may decide in the future to call TTI for all branches.
6023 }
6024 case Instruction::Switch: {
6025 if (VF.isScalar())
6026 return TTI.getCFInstrCost(Instruction::Switch, CostKind);
6027 auto *Switch = cast<SwitchInst>(I);
6028 return Switch->getNumCases() *
6030 Instruction::ICmp,
6031 toVectorTy(Switch->getCondition()->getType(), VF),
6032 toVectorTy(Type::getInt1Ty(I->getContext()), VF),
6034 }
6035 case Instruction::PHI: {
6036 auto *Phi = cast<PHINode>(I);
6037
6038 // First-order recurrences are replaced by vector shuffles inside the loop.
6039 if (VF.isVector() && Legal->isFixedOrderRecurrence(Phi)) {
6041 std::iota(Mask.begin(), Mask.end(), VF.getKnownMinValue() - 1);
6043 cast<VectorType>(VectorTy),
6044 cast<VectorType>(VectorTy), Mask, CostKind,
6045 VF.getKnownMinValue() - 1);
6046 }
6047
6048 // Phi nodes in non-header blocks (not inductions, reductions, etc.) are
6049 // converted into select instructions. We require N - 1 selects per phi
6050 // node, where N is the number of incoming values.
6051 if (VF.isVector() && Phi->getParent() != TheLoop->getHeader()) {
6052 Type *ResultTy = Phi->getType();
6053
6054 // All instructions in an Any-of reduction chain are narrowed to bool.
6055 // Check if that is the case for this phi node.
6056 auto *HeaderUser = cast_if_present<PHINode>(
6057 find_singleton<User>(Phi->users(), [this](User *U, bool) -> User * {
6058 auto *Phi = dyn_cast<PHINode>(U);
6059 if (Phi && Phi->getParent() == TheLoop->getHeader())
6060 return Phi;
6061 return nullptr;
6062 }));
6063 if (HeaderUser) {
6064 auto &ReductionVars = Legal->getReductionVars();
6065 auto Iter = ReductionVars.find(HeaderUser);
6066 if (Iter != ReductionVars.end() &&
6068 Iter->second.getRecurrenceKind()))
6069 ResultTy = Type::getInt1Ty(Phi->getContext());
6070 }
6071 return (Phi->getNumIncomingValues() - 1) *
6073 Instruction::Select, toVectorTy(ResultTy, VF),
6074 toVectorTy(Type::getInt1Ty(Phi->getContext()), VF),
6076 }
6077
6078 // When tail folding with EVL, if the phi is part of an out of loop
6079 // reduction then it will be transformed into a wide vp_merge.
6080 if (VF.isVector() && foldTailWithEVL() &&
6081 Legal->getReductionVars().contains(Phi) && !isInLoopReduction(Phi)) {
6083 Intrinsic::vp_merge, toVectorTy(Phi->getType(), VF),
6084 {toVectorTy(Type::getInt1Ty(Phi->getContext()), VF)});
6085 return TTI.getIntrinsicInstrCost(ICA, CostKind);
6086 }
6087
6088 return TTI.getCFInstrCost(Instruction::PHI, CostKind);
6089 }
6090 case Instruction::UDiv:
6091 case Instruction::SDiv:
6092 case Instruction::URem:
6093 case Instruction::SRem:
6094 if (VF.isVector() && isPredicatedInst(I)) {
6095 const auto [ScalarCost, SafeDivisorCost] = getDivRemSpeculationCost(I, VF);
6096 return isDivRemScalarWithPredication(ScalarCost, SafeDivisorCost) ?
6097 ScalarCost : SafeDivisorCost;
6098 }
6099 // We've proven all lanes safe to speculate, fall through.
6100 [[fallthrough]];
6101 case Instruction::Add:
6102 case Instruction::Sub: {
6103 auto Info = Legal->getHistogramInfo(I);
6104 if (Info && VF.isVector()) {
6105 const HistogramInfo *HGram = Info.value();
6106 // Assume that a non-constant update value (or a constant != 1) requires
6107 // a multiply, and add that into the cost.
6109 ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1));
6110 if (!RHS || RHS->getZExtValue() != 1)
6111 MulCost =
6112 TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy, CostKind);
6113
6114 // Find the cost of the histogram operation itself.
6115 Type *PtrTy = VectorType::get(HGram->Load->getPointerOperandType(), VF);
6116 Type *ScalarTy = I->getType();
6117 Type *MaskTy = VectorType::get(Type::getInt1Ty(I->getContext()), VF);
6118 IntrinsicCostAttributes ICA(Intrinsic::experimental_vector_histogram_add,
6119 Type::getVoidTy(I->getContext()),
6120 {PtrTy, ScalarTy, MaskTy});
6121
6122 // Add the costs together with the add/sub operation.
6123 return TTI.getIntrinsicInstrCost(ICA, CostKind) + MulCost +
6124 TTI.getArithmeticInstrCost(I->getOpcode(), VectorTy, CostKind);
6125 }
6126 [[fallthrough]];
6127 }
6128 case Instruction::FAdd:
6129 case Instruction::FSub:
6130 case Instruction::Mul:
6131 case Instruction::FMul:
6132 case Instruction::FDiv:
6133 case Instruction::FRem:
6134 case Instruction::Shl:
6135 case Instruction::LShr:
6136 case Instruction::AShr:
6137 case Instruction::And:
6138 case Instruction::Or:
6139 case Instruction::Xor: {
6140 // If we're speculating on the stride being 1, the multiplication may
6141 // fold away. We can generalize this for all operations using the notion
6142 // of neutral elements. (TODO)
6143 if (I->getOpcode() == Instruction::Mul &&
6144 ((TheLoop->isLoopInvariant(I->getOperand(0)) &&
6145 PSE.getSCEV(I->getOperand(0))->isOne()) ||
6146 (TheLoop->isLoopInvariant(I->getOperand(1)) &&
6147 PSE.getSCEV(I->getOperand(1))->isOne())))
6148 return 0;
6149
6150 // Detect reduction patterns
6151 if (auto RedCost = getReductionPatternCost(I, VF, VectorTy))
6152 return *RedCost;
6153
6154 // Certain instructions can be cheaper to vectorize if they have a constant
6155 // second vector operand. One example of this are shifts on x86.
6156 Value *Op2 = I->getOperand(1);
6157 if (!isa<Constant>(Op2) && TheLoop->isLoopInvariant(Op2) &&
6158 PSE.getSE()->isSCEVable(Op2->getType()) &&
6159 isa<SCEVConstant>(PSE.getSCEV(Op2))) {
6160 Op2 = cast<SCEVConstant>(PSE.getSCEV(Op2))->getValue();
6161 }
6162 auto Op2Info = TTI.getOperandInfo(Op2);
6163 if (Op2Info.Kind == TargetTransformInfo::OK_AnyValue &&
6164 shouldConsiderInvariant(Op2))
6166
6167 SmallVector<const Value *, 4> Operands(I->operand_values());
6169 I->getOpcode(), VectorTy, CostKind,
6170 {TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None},
6171 Op2Info, Operands, I, TLI);
6172 }
6173 case Instruction::FNeg: {
6175 I->getOpcode(), VectorTy, CostKind,
6176 {TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None},
6177 {TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None},
6178 I->getOperand(0), I);
6179 }
6180 case Instruction::Select: {
6181 SelectInst *SI = cast<SelectInst>(I);
6182 const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
6183 bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
6184
6185 const Value *Op0, *Op1;
6186 using namespace llvm::PatternMatch;
6187 if (!ScalarCond && (match(I, m_LogicalAnd(m_Value(Op0), m_Value(Op1))) ||
6188 match(I, m_LogicalOr(m_Value(Op0), m_Value(Op1))))) {
6189 // select x, y, false --> x & y
6190 // select x, true, y --> x | y
6191 const auto [Op1VK, Op1VP] = TTI::getOperandInfo(Op0);
6192 const auto [Op2VK, Op2VP] = TTI::getOperandInfo(Op1);
6193 assert(Op0->getType()->getScalarSizeInBits() == 1 &&
6194 Op1->getType()->getScalarSizeInBits() == 1);
6195
6198 match(I, m_LogicalOr()) ? Instruction::Or : Instruction::And, VectorTy,
6199 CostKind, {Op1VK, Op1VP}, {Op2VK, Op2VP}, Operands, I);
6200 }
6201
6202 Type *CondTy = SI->getCondition()->getType();
6203 if (!ScalarCond)
6204 CondTy = VectorType::get(CondTy, VF);
6205
6207 if (auto *Cmp = dyn_cast<CmpInst>(SI->getCondition()))
6208 Pred = Cmp->getPredicate();
6209 return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy, Pred,
6210 CostKind, {TTI::OK_AnyValue, TTI::OP_None},
6211 {TTI::OK_AnyValue, TTI::OP_None}, I);
6212 }
6213 case Instruction::ICmp:
6214 case Instruction::FCmp: {
6215 Type *ValTy = I->getOperand(0)->getType();
6216
6217 if (canTruncateToMinimalBitwidth(I, VF)) {
6218 [[maybe_unused]] Instruction *Op0AsInstruction =
6219 dyn_cast<Instruction>(I->getOperand(0));
6220 assert((!canTruncateToMinimalBitwidth(Op0AsInstruction, VF) ||
6221 MinBWs[I] == MinBWs[Op0AsInstruction]) &&
6222 "if both the operand and the compare are marked for "
6223 "truncation, they must have the same bitwidth");
6224 ValTy = IntegerType::get(ValTy->getContext(), MinBWs[I]);
6225 }
6226
6227 VectorTy = toVectorTy(ValTy, VF);
6228 return TTI.getCmpSelInstrCost(
6229 I->getOpcode(), VectorTy, CmpInst::makeCmpResultType(VectorTy),
6230 cast<CmpInst>(I)->getPredicate(), CostKind,
6231 {TTI::OK_AnyValue, TTI::OP_None}, {TTI::OK_AnyValue, TTI::OP_None}, I);
6232 }
6233 case Instruction::Store:
6234 case Instruction::Load: {
6235 ElementCount Width = VF;
6236 if (Width.isVector()) {
6237 InstWidening Decision = getWideningDecision(I, Width);
6238 assert(Decision != CM_Unknown &&
6239 "CM decision should be taken at this point");
6240 if (getWideningCost(I, VF) == InstructionCost::getInvalid())
6242 if (Decision == CM_Scalarize)
6243 Width = ElementCount::getFixed(1);
6244 }
6245 VectorTy = toVectorTy(getLoadStoreType(I), Width);
6246 return getMemoryInstructionCost(I, VF);
6247 }
6248 case Instruction::BitCast:
6249 if (I->getType()->isPointerTy())
6250 return 0;
6251 [[fallthrough]];
6252 case Instruction::ZExt:
6253 case Instruction::SExt:
6254 case Instruction::FPToUI:
6255 case Instruction::FPToSI:
6256 case Instruction::FPExt:
6257 case Instruction::PtrToInt:
6258 case Instruction::IntToPtr:
6259 case Instruction::SIToFP:
6260 case Instruction::UIToFP:
6261 case Instruction::Trunc:
6262 case Instruction::FPTrunc: {
6263 // Computes the CastContextHint from a Load/Store instruction.
6264 auto ComputeCCH = [&](Instruction *I) -> TTI::CastContextHint {
6265 assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&
6266 "Expected a load or a store!");
6267
6268 if (VF.isScalar() || !TheLoop->contains(I))
6270
6271 switch (getWideningDecision(I, VF)) {
6278 return isPredicatedInst(I) ? TTI::CastContextHint::Masked
6283 llvm_unreachable("Instr did not go through cost modelling?");
6286 llvm_unreachable_internal("Instr has invalid widening decision");
6287 }
6288
6289 llvm_unreachable("Unhandled case!");
6290 };
6291
6292 unsigned Opcode = I->getOpcode();
6294 // For Trunc, the context is the only user, which must be a StoreInst.
6295 if (Opcode == Instruction::Trunc || Opcode == Instruction::FPTrunc) {
6296 if (I->hasOneUse())
6297 if (StoreInst *Store = dyn_cast<StoreInst>(*I->user_begin()))
6298 CCH = ComputeCCH(Store);
6299 }
6300 // For Z/Sext, the context is the operand, which must be a LoadInst.
6301 else if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt ||
6302 Opcode == Instruction::FPExt) {
6303 if (LoadInst *Load = dyn_cast<LoadInst>(I->getOperand(0)))
6304 CCH = ComputeCCH(Load);
6305 }
6306
6307 // We optimize the truncation of induction variables having constant
6308 // integer steps. The cost of these truncations is the same as the scalar
6309 // operation.
6310 if (isOptimizableIVTruncate(I, VF)) {
6311 auto *Trunc = cast<TruncInst>(I);
6312 return TTI.getCastInstrCost(Instruction::Trunc, Trunc->getDestTy(),
6313 Trunc->getSrcTy(), CCH, CostKind, Trunc);
6314 }
6315
6316 // Detect reduction patterns
6317 if (auto RedCost = getReductionPatternCost(I, VF, VectorTy))
6318 return *RedCost;
6319
6320 Type *SrcScalarTy = I->getOperand(0)->getType();
6321 Instruction *Op0AsInstruction = dyn_cast<Instruction>(I->getOperand(0));
6322 if (canTruncateToMinimalBitwidth(Op0AsInstruction, VF))
6323 SrcScalarTy =
6324 IntegerType::get(SrcScalarTy->getContext(), MinBWs[Op0AsInstruction]);
6325 Type *SrcVecTy =
6326 VectorTy->isVectorTy() ? toVectorTy(SrcScalarTy, VF) : SrcScalarTy;
6327
6328 if (canTruncateToMinimalBitwidth(I, VF)) {
6329 // If the result type is <= the source type, there will be no extend
6330 // after truncating the users to the minimal required bitwidth.
6331 if (VectorTy->getScalarSizeInBits() <= SrcVecTy->getScalarSizeInBits() &&
6332 (I->getOpcode() == Instruction::ZExt ||
6333 I->getOpcode() == Instruction::SExt))
6334 return 0;
6335 }
6336
6337 return TTI.getCastInstrCost(Opcode, VectorTy, SrcVecTy, CCH, CostKind, I);
6338 }
6339 case Instruction::Call:
6340 return getVectorCallCost(cast<CallInst>(I), VF);
6341 case Instruction::ExtractValue:
6343 case Instruction::Alloca:
6344 // We cannot easily widen alloca to a scalable alloca, as
6345 // the result would need to be a vector of pointers.
6346 if (VF.isScalable())
6348 [[fallthrough]];
6349 default:
6350 // This opcode is unknown. Assume that it is the same as 'mul'.
6351 return TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy, CostKind);
6352 } // end of switch.
6353}
6354
6356 // Ignore ephemeral values.
6357 CodeMetrics::collectEphemeralValues(TheLoop, AC, ValuesToIgnore);
6358
6359 SmallVector<Value *, 4> DeadInterleavePointerOps;
6361
6362 // If a scalar epilogue is required, users outside the loop won't use
6363 // live-outs from the vector loop but from the scalar epilogue. Ignore them if
6364 // that is the case.
6365 bool RequiresScalarEpilogue = requiresScalarEpilogue(true);
6366 auto IsLiveOutDead = [this, RequiresScalarEpilogue](User *U) {
6367 return RequiresScalarEpilogue &&
6368 !TheLoop->contains(cast<Instruction>(U)->getParent());
6369 };
6370
6371 LoopBlocksDFS DFS(TheLoop);
6372 DFS.perform(LI);
6373 MapVector<Value *, SmallVector<Value *>> DeadInvariantStoreOps;
6374 for (BasicBlock *BB : reverse(make_range(DFS.beginRPO(), DFS.endRPO())))
6375 for (Instruction &I : reverse(*BB)) {
6376 // Find all stores to invariant variables. Since they are going to sink
6377 // outside the loop we do not need calculate cost for them.
6378 StoreInst *SI;
6379 if ((SI = dyn_cast<StoreInst>(&I)) &&
6380 Legal->isInvariantAddressOfReduction(SI->getPointerOperand())) {
6381 ValuesToIgnore.insert(&I);
6382 DeadInvariantStoreOps[SI->getPointerOperand()].push_back(
6383 SI->getValueOperand());
6384 }
6385
6386 if (VecValuesToIgnore.contains(&I) || ValuesToIgnore.contains(&I))
6387 continue;
6388
6389 // Add instructions that would be trivially dead and are only used by
6390 // values already ignored to DeadOps to seed worklist.
6392 all_of(I.users(), [this, IsLiveOutDead](User *U) {
6393 return VecValuesToIgnore.contains(U) ||
6394 ValuesToIgnore.contains(U) || IsLiveOutDead(U);
6395 }))
6396 DeadOps.push_back(&I);
6397
6398 // For interleave groups, we only create a pointer for the start of the
6399 // interleave group. Queue up addresses of group members except the insert
6400 // position for further processing.
6401 if (isAccessInterleaved(&I)) {
6402 auto *Group = getInterleavedAccessGroup(&I);
6403 if (Group->getInsertPos() == &I)
6404 continue;
6405 Value *PointerOp = getLoadStorePointerOperand(&I);
6406 DeadInterleavePointerOps.push_back(PointerOp);
6407 }
6408
6409 // Queue branches for analysis. They are dead, if their successors only
6410 // contain dead instructions.
6411 if (auto *Br = dyn_cast<BranchInst>(&I)) {
6412 if (Br->isConditional())
6413 DeadOps.push_back(&I);
6414 }
6415 }
6416
6417 // Mark ops feeding interleave group members as free, if they are only used
6418 // by other dead computations.
6419 for (unsigned I = 0; I != DeadInterleavePointerOps.size(); ++I) {
6420 auto *Op = dyn_cast<Instruction>(DeadInterleavePointerOps[I]);
6421 if (!Op || !TheLoop->contains(Op) || any_of(Op->users(), [this](User *U) {
6422 Instruction *UI = cast<Instruction>(U);
6423 return !VecValuesToIgnore.contains(U) &&
6424 (!isAccessInterleaved(UI) ||
6425 getInterleavedAccessGroup(UI)->getInsertPos() == UI);
6426 }))
6427 continue;
6428 VecValuesToIgnore.insert(Op);
6429 DeadInterleavePointerOps.append(Op->op_begin(), Op->op_end());
6430 }
6431
6432 for (const auto &[_, Ops] : DeadInvariantStoreOps)
6433 llvm::append_range(DeadOps, drop_end(Ops));
6434
6435 // Mark ops that would be trivially dead and are only used by ignored
6436 // instructions as free.
6437 BasicBlock *Header = TheLoop->getHeader();
6438
6439 // Returns true if the block contains only dead instructions. Such blocks will
6440 // be removed by VPlan-to-VPlan transforms and won't be considered by the
6441 // VPlan-based cost model, so skip them in the legacy cost-model as well.
6442 auto IsEmptyBlock = [this](BasicBlock *BB) {
6443 return all_of(*BB, [this](Instruction &I) {
6444 return ValuesToIgnore.contains(&I) || VecValuesToIgnore.contains(&I) ||
6445 (isa<BranchInst>(&I) && !cast<BranchInst>(&I)->isConditional());
6446 });
6447 };
6448 for (unsigned I = 0; I != DeadOps.size(); ++I) {
6449 auto *Op = dyn_cast<Instruction>(DeadOps[I]);
6450
6451 // Check if the branch should be considered dead.
6452 if (auto *Br = dyn_cast_or_null<BranchInst>(Op)) {
6453 BasicBlock *ThenBB = Br->getSuccessor(0);
6454 BasicBlock *ElseBB = Br->getSuccessor(1);
6455 // Don't considers branches leaving the loop for simplification.
6456 if (!TheLoop->contains(ThenBB) || !TheLoop->contains(ElseBB))
6457 continue;
6458 bool ThenEmpty = IsEmptyBlock(ThenBB);
6459 bool ElseEmpty = IsEmptyBlock(ElseBB);
6460 if ((ThenEmpty && ElseEmpty) ||
6461 (ThenEmpty && ThenBB->getSingleSuccessor() == ElseBB &&
6462 ElseBB->phis().empty()) ||
6463 (ElseEmpty && ElseBB->getSingleSuccessor() == ThenBB &&
6464 ThenBB->phis().empty())) {
6465 VecValuesToIgnore.insert(Br);
6466 DeadOps.push_back(Br->getCondition());
6467 }
6468 continue;
6469 }
6470
6471 // Skip any op that shouldn't be considered dead.
6472 if (!Op || !TheLoop->contains(Op) ||
6473 (isa<PHINode>(Op) && Op->getParent() == Header) ||
6475 any_of(Op->users(), [this, IsLiveOutDead](User *U) {
6476 return !VecValuesToIgnore.contains(U) &&
6477 !ValuesToIgnore.contains(U) && !IsLiveOutDead(U);
6478 }))
6479 continue;
6480
6481 // If all of Op's users are in ValuesToIgnore, add it to ValuesToIgnore
6482 // which applies for both scalar and vector versions. Otherwise it is only
6483 // dead in vector versions, so only add it to VecValuesToIgnore.
6484 if (all_of(Op->users(),
6485 [this](User *U) { return ValuesToIgnore.contains(U); }))
6486 ValuesToIgnore.insert(Op);
6487
6488 VecValuesToIgnore.insert(Op);
6489 DeadOps.append(Op->op_begin(), Op->op_end());
6490 }
6491
6492 // Ignore type-promoting instructions we identified during reduction
6493 // detection.
6494 for (const auto &Reduction : Legal->getReductionVars()) {
6495 const RecurrenceDescriptor &RedDes = Reduction.second;
6496 const SmallPtrSetImpl<Instruction *> &Casts = RedDes.getCastInsts();
6497 VecValuesToIgnore.insert_range(Casts);
6498 }
6499 // Ignore type-casting instructions we identified during induction
6500 // detection.
6501 for (const auto &Induction : Legal->getInductionVars()) {
6502 const InductionDescriptor &IndDes = Induction.second;
6503 const SmallVectorImpl<Instruction *> &Casts = IndDes.getCastInsts();
6504 VecValuesToIgnore.insert_range(Casts);
6505 }
6506}
6507
6509 // Avoid duplicating work finding in-loop reductions.
6510 if (!InLoopReductions.empty())
6511 return;
6512
6513 for (const auto &Reduction : Legal->getReductionVars()) {
6514 PHINode *Phi = Reduction.first;
6515 const RecurrenceDescriptor &RdxDesc = Reduction.second;
6516
6517 // We don't collect reductions that are type promoted (yet).
6518 if (RdxDesc.getRecurrenceType() != Phi->getType())
6519 continue;
6520
6521 // If the target would prefer this reduction to happen "in-loop", then we
6522 // want to record it as such.
6523 RecurKind Kind = RdxDesc.getRecurrenceKind();
6524 if (!PreferInLoopReductions && !useOrderedReductions(RdxDesc) &&
6525 !TTI.preferInLoopReduction(Kind, Phi->getType()))
6526 continue;
6527
6528 // Check that we can correctly put the reductions into the loop, by
6529 // finding the chain of operations that leads from the phi to the loop
6530 // exit value.
6531 SmallVector<Instruction *, 4> ReductionOperations =
6532 RdxDesc.getReductionOpChain(Phi, TheLoop);
6533 bool InLoop = !ReductionOperations.empty();
6534
6535 if (InLoop) {
6536 InLoopReductions.insert(Phi);
6537 // Add the elements to InLoopReductionImmediateChains for cost modelling.
6538 Instruction *LastChain = Phi;
6539 for (auto *I : ReductionOperations) {
6540 InLoopReductionImmediateChains[I] = LastChain;
6541 LastChain = I;
6542 }
6543 }
6544 LLVM_DEBUG(dbgs() << "LV: Using " << (InLoop ? "inloop" : "out of loop")
6545 << " reduction for phi: " << *Phi << "\n");
6546 }
6547}
6548
6549// This function will select a scalable VF if the target supports scalable
6550// vectors and a fixed one otherwise.
6551// TODO: we could return a pair of values that specify the max VF and
6552// min VF, to be used in `buildVPlans(MinVF, MaxVF)` instead of
6553// `buildVPlans(VF, VF)`. We cannot do it because VPLAN at the moment
6554// doesn't have a cost model that can choose which plan to execute if
6555// more than one is generated.
6558 unsigned WidestType;
6559 std::tie(std::ignore, WidestType) = CM.getSmallestAndWidestTypes();
6560
6565
6567 unsigned N = RegSize.getKnownMinValue() / WidestType;
6568 return ElementCount::get(N, RegSize.isScalable());
6569}
6570
6573 ElementCount VF = UserVF;
6574 // Outer loop handling: They may require CFG and instruction level
6575 // transformations before even evaluating whether vectorization is profitable.
6576 // Since we cannot modify the incoming IR, we need to build VPlan upfront in
6577 // the vectorization pipeline.
6578 if (!OrigLoop->isInnermost()) {
6579 // If the user doesn't provide a vectorization factor, determine a
6580 // reasonable one.
6581 if (UserVF.isZero()) {
6582 VF = determineVPlanVF(TTI, CM);
6583 LLVM_DEBUG(dbgs() << "LV: VPlan computed VF " << VF << ".\n");
6584
6585 // Make sure we have a VF > 1 for stress testing.
6586 if (VPlanBuildStressTest && (VF.isScalar() || VF.isZero())) {
6587 LLVM_DEBUG(dbgs() << "LV: VPlan stress testing: "
6588 << "overriding computed VF.\n");
6590 }
6591 } else if (UserVF.isScalable() && !TTI.supportsScalableVectors() &&
6593 LLVM_DEBUG(dbgs() << "LV: Not vectorizing. Scalable VF requested, but "
6594 << "not supported by the target.\n");
6596 "Scalable vectorization requested but not supported by the target",
6597 "the scalable user-specified vectorization width for outer-loop "
6598 "vectorization cannot be used because the target does not support "
6599 "scalable vectors.",
6600 "ScalableVFUnfeasible", ORE, OrigLoop);
6602 }
6603 assert(EnableVPlanNativePath && "VPlan-native path is not enabled.");
6605 "VF needs to be a power of two");
6606 LLVM_DEBUG(dbgs() << "LV: Using " << (!UserVF.isZero() ? "user " : "")
6607 << "VF " << VF << " to build VPlans.\n");
6608 buildVPlans(VF, VF);
6609
6610 if (VPlans.empty())
6612
6613 // For VPlan build stress testing, we bail out after VPlan construction.
6616
6617 return {VF, 0 /*Cost*/, 0 /* ScalarCost */};
6618 }
6619
6620 LLVM_DEBUG(
6621 dbgs() << "LV: Not vectorizing. Inner loops aren't supported in the "
6622 "VPlan-native path.\n");
6624}
6625
6626void LoopVectorizationPlanner::plan(ElementCount UserVF, unsigned UserIC) {
6627 assert(OrigLoop->isInnermost() && "Inner loop expected.");
6628 CM.collectValuesToIgnore();
6629 CM.collectElementTypesForWidening();
6630
6631 FixedScalableVFPair MaxFactors = CM.computeMaxVF(UserVF, UserIC);
6632 if (!MaxFactors) // Cases that should not to be vectorized nor interleaved.
6633 return;
6634
6635 // Invalidate interleave groups if all blocks of loop will be predicated.
6636 if (CM.blockNeedsPredicationForAnyReason(OrigLoop->getHeader()) &&
6638 LLVM_DEBUG(
6639 dbgs()
6640 << "LV: Invalidate all interleaved groups due to fold-tail by masking "
6641 "which requires masked-interleaved support.\n");
6642 if (CM.InterleaveInfo.invalidateGroups())
6643 // Invalidating interleave groups also requires invalidating all decisions
6644 // based on them, which includes widening decisions and uniform and scalar
6645 // values.
6646 CM.invalidateCostModelingDecisions();
6647 }
6648
6649 if (CM.foldTailByMasking())
6650 Legal->prepareToFoldTailByMasking();
6651
6652 ElementCount MaxUserVF =
6653 UserVF.isScalable() ? MaxFactors.ScalableVF : MaxFactors.FixedVF;
6654 if (UserVF) {
6655 if (!ElementCount::isKnownLE(UserVF, MaxUserVF)) {
6657 "UserVF ignored because it may be larger than the maximal safe VF",
6658 "InvalidUserVF", ORE, OrigLoop);
6659 } else {
6661 "VF needs to be a power of two");
6662 // Collect the instructions (and their associated costs) that will be more
6663 // profitable to scalarize.
6664 CM.collectInLoopReductions();
6665 if (CM.selectUserVectorizationFactor(UserVF)) {
6666 LLVM_DEBUG(dbgs() << "LV: Using user VF " << UserVF << ".\n");
6667 buildVPlansWithVPRecipes(UserVF, UserVF);
6668 LLVM_DEBUG(printPlans(dbgs()));
6669 return;
6670 }
6671 reportVectorizationInfo("UserVF ignored because of invalid costs.",
6672 "InvalidCost", ORE, OrigLoop);
6673 }
6674 }
6675
6676 // Collect the Vectorization Factor Candidates.
6677 SmallVector<ElementCount> VFCandidates;
6678 for (auto VF = ElementCount::getFixed(1);
6679 ElementCount::isKnownLE(VF, MaxFactors.FixedVF); VF *= 2)
6680 VFCandidates.push_back(VF);
6681 for (auto VF = ElementCount::getScalable(1);
6682 ElementCount::isKnownLE(VF, MaxFactors.ScalableVF); VF *= 2)
6683 VFCandidates.push_back(VF);
6684
6685 CM.collectInLoopReductions();
6686 for (const auto &VF : VFCandidates) {
6687 // Collect Uniform and Scalar instructions after vectorization with VF.
6688 CM.collectNonVectorizedAndSetWideningDecisions(VF);
6689 }
6690
6691 buildVPlansWithVPRecipes(ElementCount::getFixed(1), MaxFactors.FixedVF);
6692 buildVPlansWithVPRecipes(ElementCount::getScalable(1), MaxFactors.ScalableVF);
6693
6694 LLVM_DEBUG(printPlans(dbgs()));
6695}
6696
6698 ElementCount VF) const {
6699 InstructionCost Cost = CM.getInstructionCost(UI, VF);
6700 if (Cost.isValid() && ForceTargetInstructionCost.getNumOccurrences())
6702 return Cost;
6703}
6704
6706 ElementCount VF) const {
6707 return CM.isUniformAfterVectorization(I, VF);
6708}
6709
6710bool VPCostContext::skipCostComputation(Instruction *UI, bool IsVector) const {
6711 return CM.ValuesToIgnore.contains(UI) ||
6712 (IsVector && CM.VecValuesToIgnore.contains(UI)) ||
6713 SkipCostComputation.contains(UI);
6714}
6715
6717LoopVectorizationPlanner::precomputeCosts(VPlan &Plan, ElementCount VF,
6718 VPCostContext &CostCtx) const {
6720 // Cost modeling for inductions is inaccurate in the legacy cost model
6721 // compared to the recipes that are generated. To match here initially during
6722 // VPlan cost model bring up directly use the induction costs from the legacy
6723 // cost model. Note that we do this as pre-processing; the VPlan may not have
6724 // any recipes associated with the original induction increment instruction
6725 // and may replace truncates with VPWidenIntOrFpInductionRecipe. We precompute
6726 // the cost of induction phis and increments (both that are represented by
6727 // recipes and those that are not), to avoid distinguishing between them here,
6728 // and skip all recipes that represent induction phis and increments (the
6729 // former case) later on, if they exist, to avoid counting them twice.
6730 // Similarly we pre-compute the cost of any optimized truncates.
6731 // TODO: Switch to more accurate costing based on VPlan.
6732 for (const auto &[IV, IndDesc] : Legal->getInductionVars()) {
6733 Instruction *IVInc = cast<Instruction>(
6734 IV->getIncomingValueForBlock(OrigLoop->getLoopLatch()));
6735 SmallVector<Instruction *> IVInsts = {IVInc};
6736 for (unsigned I = 0; I != IVInsts.size(); I++) {
6737 for (Value *Op : IVInsts[I]->operands()) {
6738 auto *OpI = dyn_cast<Instruction>(Op);
6739 if (Op == IV || !OpI || !OrigLoop->contains(OpI) || !Op->hasOneUse())
6740 continue;
6741 IVInsts.push_back(OpI);
6742 }
6743 }
6744 IVInsts.push_back(IV);
6745 for (User *U : IV->users()) {
6746 auto *CI = cast<Instruction>(U);
6747 if (!CostCtx.CM.isOptimizableIVTruncate(CI, VF))
6748 continue;
6749 IVInsts.push_back(CI);
6750 }
6751
6752 // If the vector loop gets executed exactly once with the given VF, ignore
6753 // the costs of comparison and induction instructions, as they'll get
6754 // simplified away.
6755 // TODO: Remove this code after stepping away from the legacy cost model and
6756 // adding code to simplify VPlans before calculating their costs.
6758 if (TC == VF && !CM.foldTailByMasking())
6760 CostCtx.SkipCostComputation);
6761
6762 for (Instruction *IVInst : IVInsts) {
6763 if (CostCtx.skipCostComputation(IVInst, VF.isVector()))
6764 continue;
6765 InstructionCost InductionCost = CostCtx.getLegacyCost(IVInst, VF);
6766 LLVM_DEBUG({
6767 dbgs() << "Cost of " << InductionCost << " for VF " << VF
6768 << ": induction instruction " << *IVInst << "\n";
6769 });
6770 Cost += InductionCost;
6771 CostCtx.SkipCostComputation.insert(IVInst);
6772 }
6773 }
6774
6775 /// Compute the cost of all exiting conditions of the loop using the legacy
6776 /// cost model. This is to match the legacy behavior, which adds the cost of
6777 /// all exit conditions. Note that this over-estimates the cost, as there will
6778 /// be a single condition to control the vector loop.
6780 CM.TheLoop->getExitingBlocks(Exiting);
6781 SetVector<Instruction *> ExitInstrs;
6782 // Collect all exit conditions.
6783 for (BasicBlock *EB : Exiting) {
6784 auto *Term = dyn_cast<BranchInst>(EB->getTerminator());
6785 if (!Term || CostCtx.skipCostComputation(Term, VF.isVector()))
6786 continue;
6787 if (auto *CondI = dyn_cast<Instruction>(Term->getOperand(0))) {
6788 ExitInstrs.insert(CondI);
6789 }
6790 }
6791 // Compute the cost of all instructions only feeding the exit conditions.
6792 for (unsigned I = 0; I != ExitInstrs.size(); ++I) {
6793 Instruction *CondI = ExitInstrs[I];
6794 if (!OrigLoop->contains(CondI) ||
6795 !CostCtx.SkipCostComputation.insert(CondI).second)
6796 continue;
6797 InstructionCost CondICost = CostCtx.getLegacyCost(CondI, VF);
6798 LLVM_DEBUG({
6799 dbgs() << "Cost of " << CondICost << " for VF " << VF
6800 << ": exit condition instruction " << *CondI << "\n";
6801 });
6802 Cost += CondICost;
6803 for (Value *Op : CondI->operands()) {
6804 auto *OpI = dyn_cast<Instruction>(Op);
6805 if (!OpI || CostCtx.skipCostComputation(OpI, VF.isVector()) ||
6806 any_of(OpI->users(), [&ExitInstrs, this](User *U) {
6807 return OrigLoop->contains(cast<Instruction>(U)->getParent()) &&
6808 !ExitInstrs.contains(cast<Instruction>(U));
6809 }))
6810 continue;
6811 ExitInstrs.insert(OpI);
6812 }
6813 }
6814
6815 // Pre-compute the costs for branches except for the backedge, as the number
6816 // of replicate regions in a VPlan may not directly match the number of
6817 // branches, which would lead to different decisions.
6818 // TODO: Compute cost of branches for each replicate region in the VPlan,
6819 // which is more accurate than the legacy cost model.
6820 for (BasicBlock *BB : OrigLoop->blocks()) {
6821 if (CostCtx.skipCostComputation(BB->getTerminator(), VF.isVector()))
6822 continue;
6823 CostCtx.SkipCostComputation.insert(BB->getTerminator());
6824 if (BB == OrigLoop->getLoopLatch())
6825 continue;
6826 auto BranchCost = CostCtx.getLegacyCost(BB->getTerminator(), VF);
6827 Cost += BranchCost;
6828 }
6829
6830 // Pre-compute costs for instructions that are forced-scalar or profitable to
6831 // scalarize. Their costs will be computed separately in the legacy cost
6832 // model.
6833 for (Instruction *ForcedScalar : CM.ForcedScalars[VF]) {
6834 if (CostCtx.skipCostComputation(ForcedScalar, VF.isVector()))
6835 continue;
6836 CostCtx.SkipCostComputation.insert(ForcedScalar);
6837 InstructionCost ForcedCost = CostCtx.getLegacyCost(ForcedScalar, VF);
6838 LLVM_DEBUG({
6839 dbgs() << "Cost of " << ForcedCost << " for VF " << VF
6840 << ": forced scalar " << *ForcedScalar << "\n";
6841 });
6842 Cost += ForcedCost;
6843 }
6844 for (const auto &[Scalarized, ScalarCost] : CM.InstsToScalarize[VF]) {
6845 if (CostCtx.skipCostComputation(Scalarized, VF.isVector()))
6846 continue;
6847 CostCtx.SkipCostComputation.insert(Scalarized);
6848 LLVM_DEBUG({
6849 dbgs() << "Cost of " << ScalarCost << " for VF " << VF
6850 << ": profitable to scalarize " << *Scalarized << "\n";
6851 });
6852 Cost += ScalarCost;
6853 }
6854
6855 return Cost;
6856}
6857
6858InstructionCost LoopVectorizationPlanner::cost(VPlan &Plan,
6859 ElementCount VF) const {
6860 VPCostContext CostCtx(CM.TTI, *CM.TLI, Plan, CM, CM.CostKind);
6861 InstructionCost Cost = precomputeCosts(Plan, VF, CostCtx);
6862
6863 // Now compute and add the VPlan-based cost.
6864 Cost += Plan.cost(VF, CostCtx);
6865#ifndef NDEBUG
6866 unsigned EstimatedWidth = estimateElementCount(VF, CM.getVScaleForTuning());
6867 LLVM_DEBUG(dbgs() << "Cost for VF " << VF << ": " << Cost
6868 << " (Estimated cost per lane: ");
6869 if (Cost.isValid()) {
6870 double CostPerLane = double(Cost.getValue()) / EstimatedWidth;
6871 LLVM_DEBUG(dbgs() << format("%.1f", CostPerLane));
6872 } else /* No point dividing an invalid cost - it will still be invalid */
6873 LLVM_DEBUG(dbgs() << "Invalid");
6874 LLVM_DEBUG(dbgs() << ")\n");
6875#endif
6876 return Cost;
6877}
6878
6879#ifndef NDEBUG
6880/// Return true if the original loop \ TheLoop contains any instructions that do
6881/// not have corresponding recipes in \p Plan and are not marked to be ignored
6882/// in \p CostCtx. This means the VPlan contains simplification that the legacy
6883/// cost-model did not account for.
6885 VPCostContext &CostCtx,
6886 Loop *TheLoop,
6887 ElementCount VF) {
6888 // First collect all instructions for the recipes in Plan.
6889 auto GetInstructionForCost = [](const VPRecipeBase *R) -> Instruction * {
6890 if (auto *S = dyn_cast<VPSingleDefRecipe>(R))
6891 return dyn_cast_or_null<Instruction>(S->getUnderlyingValue());
6892 if (auto *WidenMem = dyn_cast<VPWidenMemoryRecipe>(R))
6893 return &WidenMem->getIngredient();
6894 return nullptr;
6895 };
6896
6897 DenseSet<Instruction *> SeenInstrs;
6899 for (VPBasicBlock *VPBB : VPBlockUtils::blocksOnly<VPBasicBlock>(Iter)) {
6900 for (VPRecipeBase &R : *VPBB) {
6901 if (auto *IR = dyn_cast<VPInterleaveRecipe>(&R)) {
6902 auto *IG = IR->getInterleaveGroup();
6903 unsigned NumMembers = IG->getNumMembers();
6904 for (unsigned I = 0; I != NumMembers; ++I) {
6905 if (Instruction *M = IG->getMember(I))
6906 SeenInstrs.insert(M);
6907 }
6908 continue;
6909 }
6910 // Unused FOR splices are removed by VPlan transforms, so the VPlan-based
6911 // cost model won't cost it whilst the legacy will.
6912 if (auto *FOR = dyn_cast<VPFirstOrderRecurrencePHIRecipe>(&R)) {
6913 if (none_of(FOR->users(), [](VPUser *U) {
6914 auto *VPI = dyn_cast<VPInstruction>(U);
6915 return VPI && VPI->getOpcode() ==
6916 VPInstruction::FirstOrderRecurrenceSplice;
6917 }))
6918 return true;
6919 }
6920 // The VPlan-based cost model is more accurate for partial reduction and
6921 // comparing against the legacy cost isn't desirable.
6922 if (isa<VPPartialReductionRecipe>(&R))
6923 return true;
6924
6925 /// If a VPlan transform folded a recipe to one producing a single-scalar,
6926 /// but the original instruction wasn't uniform-after-vectorization in the
6927 /// legacy cost model, the legacy cost overestimates the actual cost.
6928 if (auto *RepR = dyn_cast<VPReplicateRecipe>(&R)) {
6929 if (RepR->isSingleScalar() &&
6931 RepR->getUnderlyingInstr(), VF))
6932 return true;
6933 }
6934 if (Instruction *UI = GetInstructionForCost(&R)) {
6935 // If we adjusted the predicate of the recipe, the cost in the legacy
6936 // cost model may be different.
6937 using namespace VPlanPatternMatch;
6938 CmpPredicate Pred;
6939 if (match(&R, m_Cmp(Pred, m_VPValue(), m_VPValue())) &&
6940 cast<VPRecipeWithIRFlags>(R).getPredicate() !=
6941 cast<CmpInst>(UI)->getPredicate())
6942 return true;
6943 SeenInstrs.insert(UI);
6944 }
6945 }
6946 }
6947
6948 // Return true if the loop contains any instructions that are not also part of
6949 // the VPlan or are skipped for VPlan-based cost computations. This indicates
6950 // that the VPlan contains extra simplifications.
6951 return any_of(TheLoop->blocks(), [&SeenInstrs, &CostCtx,
6952 TheLoop](BasicBlock *BB) {
6953 return any_of(*BB, [&SeenInstrs, &CostCtx, TheLoop, BB](Instruction &I) {
6954 // Skip induction phis when checking for simplifications, as they may not
6955 // be lowered directly be lowered to a corresponding PHI recipe.
6956 if (isa<PHINode>(&I) && BB == TheLoop->getHeader() &&
6957 CostCtx.CM.Legal->isInductionPhi(cast<PHINode>(&I)))
6958 return false;
6959 return !SeenInstrs.contains(&I) && !CostCtx.skipCostComputation(&I, true);
6960 });
6961 });
6962}
6963#endif
6964
6966 if (VPlans.empty())
6968 // If there is a single VPlan with a single VF, return it directly.
6969 VPlan &FirstPlan = *VPlans[0];
6970 if (VPlans.size() == 1 && size(FirstPlan.vectorFactors()) == 1)
6971 return {*FirstPlan.vectorFactors().begin(), 0, 0};
6972
6973 LLVM_DEBUG(dbgs() << "LV: Computing best VF using cost kind: "
6974 << (CM.CostKind == TTI::TCK_RecipThroughput
6975 ? "Reciprocal Throughput\n"
6976 : CM.CostKind == TTI::TCK_Latency
6977 ? "Instruction Latency\n"
6978 : CM.CostKind == TTI::TCK_CodeSize ? "Code Size\n"
6979 : CM.CostKind == TTI::TCK_SizeAndLatency
6980 ? "Code Size and Latency\n"
6981 : "Unknown\n"));
6982
6984 assert(hasPlanWithVF(ScalarVF) &&
6985 "More than a single plan/VF w/o any plan having scalar VF");
6986
6987 // TODO: Compute scalar cost using VPlan-based cost model.
6988 InstructionCost ScalarCost = CM.expectedCost(ScalarVF);
6989 LLVM_DEBUG(dbgs() << "LV: Scalar loop costs: " << ScalarCost << ".\n");
6990 VectorizationFactor ScalarFactor(ScalarVF, ScalarCost, ScalarCost);
6991 VectorizationFactor BestFactor = ScalarFactor;
6992
6993 bool ForceVectorization = Hints.getForce() == LoopVectorizeHints::FK_Enabled;
6994 if (ForceVectorization) {
6995 // Ignore scalar width, because the user explicitly wants vectorization.
6996 // Initialize cost to max so that VF = 2 is, at least, chosen during cost
6997 // evaluation.
6998 BestFactor.Cost = InstructionCost::getMax();
6999 }
7000
7001 for (auto &P : VPlans) {
7002 ArrayRef<ElementCount> VFs(P->vectorFactors().begin(),
7003 P->vectorFactors().end());
7004
7006 if (CM.useMaxBandwidth(TargetTransformInfo::RGK_ScalableVector) ||
7008 RUs = calculateRegisterUsageForPlan(*P, VFs, TTI, CM.ValuesToIgnore);
7009
7010 for (unsigned I = 0; I < VFs.size(); I++) {
7011 ElementCount VF = VFs[I];
7012 if (VF.isScalar())
7013 continue;
7014 if (!ForceVectorization && !willGenerateVectors(*P, VF, TTI)) {
7015 LLVM_DEBUG(
7016 dbgs()
7017 << "LV: Not considering vector loop of width " << VF
7018 << " because it will not generate any vector instructions.\n");
7019 continue;
7020 }
7021 if (CM.OptForSize && !ForceVectorization && hasReplicatorRegion(*P)) {
7022 LLVM_DEBUG(
7023 dbgs()
7024 << "LV: Not considering vector loop of width " << VF
7025 << " because it would cause replicated blocks to be generated,"
7026 << " which isn't allowed when optimizing for size.\n");
7027 continue;
7028 }
7029
7030 InstructionCost Cost = cost(*P, VF);
7031 VectorizationFactor CurrentFactor(VF, Cost, ScalarCost);
7032
7033 if (CM.shouldCalculateRegPressureForVF(VF) &&
7034 RUs[I].exceedsMaxNumRegs(TTI, ForceTargetNumVectorRegs)) {
7035 LLVM_DEBUG(dbgs() << "LV(REG): Not considering vector loop of width "
7036 << VF << " because it uses too many registers\n");
7037 continue;
7038 }
7039
7040 if (isMoreProfitable(CurrentFactor, BestFactor, P->hasScalarTail()))
7041 BestFactor = CurrentFactor;
7042
7043 // If profitable add it to ProfitableVF list.
7044 if (isMoreProfitable(CurrentFactor, ScalarFactor, P->hasScalarTail()))
7045 ProfitableVFs.push_back(CurrentFactor);
7046 }
7047 }
7048
7049#ifndef NDEBUG
7050 // Select the optimal vectorization factor according to the legacy cost-model.
7051 // This is now only used to verify the decisions by the new VPlan-based
7052 // cost-model and will be retired once the VPlan-based cost-model is
7053 // stabilized.
7054 VectorizationFactor LegacyVF = selectVectorizationFactor();
7055 VPlan &BestPlan = getPlanFor(BestFactor.Width);
7056
7057 // Pre-compute the cost and use it to check if BestPlan contains any
7058 // simplifications not accounted for in the legacy cost model. If that's the
7059 // case, don't trigger the assertion, as the extra simplifications may cause a
7060 // different VF to be picked by the VPlan-based cost model.
7061 VPCostContext CostCtx(CM.TTI, *CM.TLI, BestPlan, CM, CM.CostKind);
7062 precomputeCosts(BestPlan, BestFactor.Width, CostCtx);
7063 // Verify that the VPlan-based and legacy cost models agree, except for VPlans
7064 // with early exits and plans with additional VPlan simplifications. The
7065 // legacy cost model doesn't properly model costs for such loops.
7066 assert((BestFactor.Width == LegacyVF.Width || BestPlan.hasEarlyExit() ||
7067 planContainsAdditionalSimplifications(getPlanFor(BestFactor.Width),
7068 CostCtx, OrigLoop,
7069 BestFactor.Width) ||
7071 getPlanFor(LegacyVF.Width), CostCtx, OrigLoop, LegacyVF.Width)) &&
7072 " VPlan cost model and legacy cost model disagreed");
7073 assert((BestFactor.Width.isScalar() || BestFactor.ScalarCost > 0) &&
7074 "when vectorizing, the scalar cost must be computed.");
7075#endif
7076
7077 LLVM_DEBUG(dbgs() << "LV: Selecting VF: " << BestFactor.Width << ".\n");
7078 return BestFactor;
7079}
7080
7083 // Reserve first location for self reference to the LoopID metadata node.
7084 MDs.push_back(nullptr);
7085 bool IsUnrollMetadata = false;
7086 MDNode *LoopID = L->getLoopID();
7087 if (LoopID) {
7088 // First find existing loop unrolling disable metadata.
7089 for (unsigned I = 1, IE = LoopID->getNumOperands(); I < IE; ++I) {
7090 auto *MD = dyn_cast<MDNode>(LoopID->getOperand(I));
7091 if (MD) {
7092 const auto *S = dyn_cast<MDString>(MD->getOperand(0));
7093 IsUnrollMetadata =
7094 S && S->getString().starts_with("llvm.loop.unroll.disable");
7095 }
7096 MDs.push_back(LoopID->getOperand(I));
7097 }
7098 }
7099
7100 if (!IsUnrollMetadata) {
7101 // Add runtime unroll disable metadata.
7102 LLVMContext &Context = L->getHeader()->getContext();
7103 SmallVector<Metadata *, 1> DisableOperands;
7104 DisableOperands.push_back(
7105 MDString::get(Context, "llvm.loop.unroll.runtime.disable"));
7106 MDNode *DisableNode = MDNode::get(Context, DisableOperands);
7107 MDs.push_back(DisableNode);
7108 MDNode *NewLoopID = MDNode::get(Context, MDs);
7109 // Set operand 0 to refer to the loop id itself.
7110 NewLoopID->replaceOperandWith(0, NewLoopID);
7111 L->setLoopID(NewLoopID);
7112 }
7113}
7114
7116 using namespace VPlanPatternMatch;
7118 "RdxResult must be ComputeFindIVResult");
7119 VPValue *StartVPV = RdxResult->getOperand(1);
7120 match(StartVPV, m_Freeze(m_VPValue(StartVPV)));
7121 return StartVPV->getLiveInIRValue();
7122}
7123
7124// If \p EpiResumePhiR is resume VPPhi for a reduction when vectorizing the
7125// epilog loop, fix the reduction's scalar PHI node by adding the incoming value
7126// from the main vector loop.
7128 VPPhi *EpiResumePhiR, VPTransformState &State, BasicBlock *BypassBlock) {
7129 // Get the VPInstruction computing the reduction result in the middle block.
7130 // The first operand may not be from the middle block if it is not connected
7131 // to the scalar preheader. In that case, there's nothing to fix.
7132 VPValue *Incoming = EpiResumePhiR->getOperand(0);
7135 auto *EpiRedResult = dyn_cast<VPInstruction>(Incoming);
7136 if (!EpiRedResult ||
7137 (EpiRedResult->getOpcode() != VPInstruction::ComputeAnyOfResult &&
7138 EpiRedResult->getOpcode() != VPInstruction::ComputeReductionResult &&
7139 EpiRedResult->getOpcode() != VPInstruction::ComputeFindIVResult))
7140 return;
7141
7142 auto *EpiRedHeaderPhi =
7143 cast<VPReductionPHIRecipe>(EpiRedResult->getOperand(0));
7144 RecurKind Kind = EpiRedHeaderPhi->getRecurrenceKind();
7145 Value *MainResumeValue;
7146 if (auto *VPI = dyn_cast<VPInstruction>(EpiRedHeaderPhi->getStartValue())) {
7147 assert((VPI->getOpcode() == VPInstruction::Broadcast ||
7148 VPI->getOpcode() == VPInstruction::ReductionStartVector) &&
7149 "unexpected start recipe");
7150 MainResumeValue = VPI->getOperand(0)->getUnderlyingValue();
7151 } else
7152 MainResumeValue = EpiRedHeaderPhi->getStartValue()->getUnderlyingValue();
7154 [[maybe_unused]] Value *StartV =
7155 EpiRedResult->getOperand(1)->getLiveInIRValue();
7156 auto *Cmp = cast<ICmpInst>(MainResumeValue);
7157 assert(Cmp->getPredicate() == CmpInst::ICMP_NE &&
7158 "AnyOf expected to start with ICMP_NE");
7159 assert(Cmp->getOperand(1) == StartV &&
7160 "AnyOf expected to start by comparing main resume value to original "
7161 "start value");
7162 MainResumeValue = Cmp->getOperand(0);
7164 Value *StartV = getStartValueFromReductionResult(EpiRedResult);
7165 Value *SentinelV = EpiRedResult->getOperand(2)->getLiveInIRValue();
7166 using namespace llvm::PatternMatch;
7167 Value *Cmp, *OrigResumeV, *CmpOp;
7168 [[maybe_unused]] bool IsExpectedPattern =
7169 match(MainResumeValue,
7170 m_Select(m_OneUse(m_Value(Cmp)), m_Specific(SentinelV),
7171 m_Value(OrigResumeV))) &&
7173 m_Value(CmpOp))) &&
7174 ((CmpOp == StartV && isGuaranteedNotToBeUndefOrPoison(CmpOp))));
7175 assert(IsExpectedPattern && "Unexpected reduction resume pattern");
7176 MainResumeValue = OrigResumeV;
7177 }
7178 PHINode *MainResumePhi = cast<PHINode>(MainResumeValue);
7179
7180 // When fixing reductions in the epilogue loop we should already have
7181 // created a bc.merge.rdx Phi after the main vector body. Ensure that we carry
7182 // over the incoming values correctly.
7183 auto *EpiResumePhi = cast<PHINode>(State.get(EpiResumePhiR, true));
7184 EpiResumePhi->setIncomingValueForBlock(
7185 BypassBlock, MainResumePhi->getIncomingValueForBlock(BypassBlock));
7186}
7187
7189 ElementCount BestVF, unsigned BestUF, VPlan &BestVPlan,
7190 InnerLoopVectorizer &ILV, DominatorTree *DT, bool VectorizingEpilogue) {
7191 assert(BestVPlan.hasVF(BestVF) &&
7192 "Trying to execute plan with unsupported VF");
7193 assert(BestVPlan.hasUF(BestUF) &&
7194 "Trying to execute plan with unsupported UF");
7195 if (BestVPlan.hasEarlyExit())
7196 ++LoopsEarlyExitVectorized;
7197 // TODO: Move to VPlan transform stage once the transition to the VPlan-based
7198 // cost model is complete for better cost estimates.
7203 bool HasBranchWeights =
7205 if (HasBranchWeights) {
7206 std::optional<unsigned> VScale = CM.getVScaleForTuning();
7208 BestVPlan, BestVF, VScale);
7209 }
7210
7211 if (!VectorizingEpilogue) {
7212 // Checks are the same for all VPlans, added to BestVPlan only for
7213 // compactness.
7214 attachRuntimeChecks(BestVPlan, ILV.RTChecks, HasBranchWeights);
7215 }
7216
7217 // Retrieving VectorPH now when it's easier while VPlan still has Regions.
7218 VPBasicBlock *VectorPH = cast<VPBasicBlock>(BestVPlan.getVectorPreheader());
7219
7220 VPlanTransforms::optimizeForVFAndUF(BestVPlan, BestVF, BestUF, PSE);
7224 BestVPlan, BestVF,
7227
7229 // Regions are dissolved after optimizing for VF and UF, which completely
7230 // removes unneeded loop regions first.
7232 // Canonicalize EVL loops after regions are dissolved.
7236 BestVPlan, VectorPH, CM.foldTailByMasking(),
7237 CM.requiresScalarEpilogue(BestVF.isVector()));
7238 VPlanTransforms::materializeVFAndVFxUF(BestVPlan, VectorPH, BestVF);
7240
7241 // 0. Generate SCEV-dependent code in the entry, including TripCount, before
7242 // making any changes to the CFG.
7243 DenseMap<const SCEV *, Value *> ExpandedSCEVs =
7244 VPlanTransforms::expandSCEVs(BestVPlan, *PSE.getSE());
7245 if (!ILV.getTripCount())
7246 ILV.setTripCount(BestVPlan.getTripCount()->getLiveInIRValue());
7247 else
7248 assert(VectorizingEpilogue && "should only re-use the existing trip "
7249 "count during epilogue vectorization");
7250
7251 // Perform the actual loop transformation.
7252 VPTransformState State(&TTI, BestVF, LI, DT, ILV.AC, ILV.Builder, &BestVPlan,
7254 Legal->getWidestInductionType());
7255
7256#ifdef EXPENSIVE_CHECKS
7257 assert(DT->verify(DominatorTree::VerificationLevel::Fast));
7258#endif
7259
7260 // 1. Set up the skeleton for vectorization, including vector pre-header and
7261 // middle block. The vector loop is created during VPlan execution.
7262 BasicBlock *EntryBB =
7263 cast<VPIRBasicBlock>(BestVPlan.getEntry())->getIRBasicBlock();
7266 State.CFG.PrevBB->getSingleSuccessor());
7268
7269 assert(verifyVPlanIsValid(BestVPlan, true /*VerifyLate*/) &&
7270 "final VPlan is invalid");
7271
7272 // After vectorization, the exit blocks of the original loop will have
7273 // additional predecessors. Invalidate SCEVs for the exit phis in case SE
7274 // looked through single-entry phis.
7275 ScalarEvolution &SE = *PSE.getSE();
7276 for (VPIRBasicBlock *Exit : BestVPlan.getExitBlocks()) {
7277 if (Exit->getNumPredecessors() == 0)
7278 continue;
7279 for (VPRecipeBase &PhiR : Exit->phis())
7281 OrigLoop, cast<PHINode>(&cast<VPIRPhi>(PhiR).getInstruction()));
7282 }
7283 // Forget the original loop and block dispositions.
7284 SE.forgetLoop(OrigLoop);
7286
7288
7289 //===------------------------------------------------===//
7290 //
7291 // Notice: any optimization or new instruction that go
7292 // into the code below should also be implemented in
7293 // the cost-model.
7294 //
7295 //===------------------------------------------------===//
7296
7297 // Move check blocks to their final position.
7298 // TODO: Move as part of VPIRBB execute and update impacted tests.
7299 if (BasicBlock *MemCheckBlock = ILV.RTChecks.getMemRuntimeChecks().second)
7300 MemCheckBlock->moveAfter(EntryBB);
7301 if (BasicBlock *SCEVCheckBlock = ILV.RTChecks.getSCEVChecks().second)
7302 SCEVCheckBlock->moveAfter(EntryBB);
7303
7304 BestVPlan.execute(&State);
7305
7306 // 2.5 When vectorizing the epilogue, fix reduction resume values from the
7307 // additional bypass block.
7308 if (VectorizingEpilogue) {
7309 assert(!BestVPlan.hasEarlyExit() &&
7310 "Epilogue vectorisation not yet supported with early exits");
7312 BasicBlock *BypassBlock = ILV.getAdditionalBypassBlock();
7313 for (auto *Pred : predecessors(PH)) {
7314 for (PHINode &Phi : PH->phis()) {
7315 if (Phi.getBasicBlockIndex(Pred) != -1)
7316 continue;
7317 Phi.addIncoming(Phi.getIncomingValueForBlock(BypassBlock), Pred);
7318 }
7319 }
7320 VPBasicBlock *ScalarPH = BestVPlan.getScalarPreheader();
7321 if (ScalarPH->getNumPredecessors() > 0) {
7322 // If ScalarPH has predecessors, we may need to update its reduction
7323 // resume values.
7324 for (VPRecipeBase &R : ScalarPH->phis()) {
7325 fixReductionScalarResumeWhenVectorizingEpilog(cast<VPPhi>(&R), State,
7326 BypassBlock);
7327 }
7328 }
7329 }
7330
7331 // 2.6. Maintain Loop Hints
7332 // Keep all loop hints from the original loop on the vector loop (we'll
7333 // replace the vectorizer-specific hints below).
7334 VPBasicBlock *HeaderVPBB = vputils::getFirstLoopHeader(BestVPlan, State.VPDT);
7335 if (HeaderVPBB) {
7336 MDNode *OrigLoopID = OrigLoop->getLoopID();
7337
7338 std::optional<MDNode *> VectorizedLoopID =
7341
7342 Loop *L = LI->getLoopFor(State.CFG.VPBB2IRBB[HeaderVPBB]);
7343 if (VectorizedLoopID) {
7344 L->setLoopID(*VectorizedLoopID);
7345 } else {
7346 // Keep all loop hints from the original loop on the vector loop (we'll
7347 // replace the vectorizer-specific hints below).
7348 if (MDNode *LID = OrigLoop->getLoopID())
7349 L->setLoopID(LID);
7350
7351 LoopVectorizeHints Hints(L, true, *ORE);
7352 Hints.setAlreadyVectorized();
7353
7354 // Check if it's EVL-vectorized and mark the corresponding metadata.
7355 bool IsEVLVectorized =
7356 llvm::any_of(*HeaderVPBB, [](const VPRecipeBase &Recipe) {
7357 // Looking for the ExplictVectorLength VPInstruction.
7358 if (const auto *VI = dyn_cast<VPInstruction>(&Recipe))
7359 return VI->getOpcode() == VPInstruction::ExplicitVectorLength;
7360 return false;
7361 });
7362 if (IsEVLVectorized) {
7363 LLVMContext &Context = L->getHeader()->getContext();
7364 MDNode *LoopID = L->getLoopID();
7365 auto *IsEVLVectorizedMD = MDNode::get(
7366 Context,
7367 {MDString::get(Context, "llvm.loop.isvectorized.tailfoldingstyle"),
7368 MDString::get(Context, "evl")});
7369 MDNode *NewLoopID = makePostTransformationMetadata(Context, LoopID, {},
7370 {IsEVLVectorizedMD});
7371 L->setLoopID(NewLoopID);
7372 }
7373 }
7375 TTI.getUnrollingPreferences(L, *PSE.getSE(), UP, ORE);
7376 if (!UP.UnrollVectorizedLoop || VectorizingEpilogue)
7378 }
7379
7380 // 3. Fix the vectorized code: take care of header phi's, live-outs,
7381 // predication, updating analyses.
7382 ILV.fixVectorizedLoop(State);
7383
7385
7386 return ExpandedSCEVs;
7387}
7388
7389//===--------------------------------------------------------------------===//
7390// EpilogueVectorizerMainLoop
7391//===--------------------------------------------------------------------===//
7392
7393/// This function is partially responsible for generating the control flow
7394/// depicted in https://llvm.org/docs/Vectorizers.html#epilogue-vectorization.
7396 BasicBlock *ScalarPH = createScalarPreheader("");
7397
7398 // Generate the code to check the minimum iteration count of the vector
7399 // epilogue (see below).
7402
7403 // Generate the iteration count check for the main loop, *after* the check
7404 // for the epilogue loop, so that the path-length is shorter for the case
7405 // that goes directly through the vector epilogue. The longer-path length for
7406 // the main loop is compensated for, by the gain from vectorizing the larger
7407 // trip count. Note: the branch will get updated later on when we vectorize
7408 // the epilogue.
7410
7411 return LoopVectorPreHeader;
7412}
7413
7415 LLVM_DEBUG({
7416 dbgs() << "Create Skeleton for epilogue vectorized loop (first pass)\n"
7417 << "Main Loop VF:" << EPI.MainLoopVF
7418 << ", Main Loop UF:" << EPI.MainLoopUF
7419 << ", Epilogue Loop VF:" << EPI.EpilogueVF
7420 << ", Epilogue Loop UF:" << EPI.EpilogueUF << "\n";
7421 });
7422}
7423
7426 dbgs() << "intermediate fn:\n"
7427 << *OrigLoop->getHeader()->getParent() << "\n";
7428 });
7429}
7430
7431BasicBlock *
7433 bool ForEpilogue) {
7434 assert(Bypass && "Expected valid bypass basic block.");
7435 Value *Count = getTripCount();
7437 Value *CheckMinIters =
7439 ForEpilogue ? EPI.EpilogueUF : EPI.MainLoopUF);
7440
7441 BasicBlock *const TCCheckBlock = LoopVectorPreHeader;
7442 if (!ForEpilogue)
7443 TCCheckBlock->setName("vector.main.loop.iter.check");
7444
7445 // Create new preheader for vector loop.
7446 LoopVectorPreHeader = SplitBlock(TCCheckBlock, TCCheckBlock->getTerminator(),
7447 static_cast<DominatorTree *>(nullptr), LI,
7448 nullptr, "vector.ph");
7449 if (ForEpilogue) {
7450 // Save the trip count so we don't have to regenerate it in the
7451 // vec.epilog.iter.check. This is safe to do because the trip count
7452 // generated here dominates the vector epilog iter check.
7453 EPI.TripCount = Count;
7454 } else {
7456 }
7457
7458 BranchInst &BI =
7459 *BranchInst::Create(Bypass, LoopVectorPreHeader, CheckMinIters);
7461 setBranchWeights(BI, MinItersBypassWeights, /*IsExpected=*/false);
7462 ReplaceInstWithInst(TCCheckBlock->getTerminator(), &BI);
7463
7464 // When vectorizing the main loop, its trip-count check is placed in a new
7465 // block, whereas the overall trip-count check is placed in the VPlan entry
7466 // block. When vectorizing the epilogue loop, its trip-count check is placed
7467 // in the VPlan entry block.
7468 if (!ForEpilogue)
7469 introduceCheckBlockInVPlan(TCCheckBlock);
7470 return TCCheckBlock;
7471}
7472
7473//===--------------------------------------------------------------------===//
7474// EpilogueVectorizerEpilogueLoop
7475//===--------------------------------------------------------------------===//
7476
7477/// This function is partially responsible for generating the control flow
7478/// depicted in https://llvm.org/docs/Vectorizers.html#epilogue-vectorization.
7480 BasicBlock *ScalarPH = createScalarPreheader("vec.epilog.");
7481
7482 // Now, compare the remaining count and if there aren't enough iterations to
7483 // execute the vectorized epilogue skip to the scalar part.
7484 LoopVectorPreHeader->setName("vec.epilog.ph");
7485 BasicBlock *VecEpilogueIterationCountCheck =
7487 nullptr, "vec.epilog.iter.check", true);
7489
7490 emitMinimumVectorEpilogueIterCountCheck(ScalarPH,
7491 VecEpilogueIterationCountCheck);
7492 AdditionalBypassBlock = VecEpilogueIterationCountCheck;
7493
7494 // Adjust the control flow taking the state info from the main loop
7495 // vectorization into account.
7497 "expected this to be saved from the previous pass.");
7499 VecEpilogueIterationCountCheck, LoopVectorPreHeader);
7500
7502 VecEpilogueIterationCountCheck, ScalarPH);
7503
7504 // Adjust the terminators of runtime check blocks and phis using them.
7505 BasicBlock *SCEVCheckBlock = RTChecks.getSCEVChecks().second;
7506 BasicBlock *MemCheckBlock = RTChecks.getMemRuntimeChecks().second;
7507 if (SCEVCheckBlock)
7508 SCEVCheckBlock->getTerminator()->replaceUsesOfWith(
7509 VecEpilogueIterationCountCheck, ScalarPH);
7510 if (MemCheckBlock)
7511 MemCheckBlock->getTerminator()->replaceUsesOfWith(
7512 VecEpilogueIterationCountCheck, ScalarPH);
7513
7515
7516 // The vec.epilog.iter.check block may contain Phi nodes from inductions or
7517 // reductions which merge control-flow from the latch block and the middle
7518 // block. Update the incoming values here and move the Phi into the preheader.
7519 SmallVector<PHINode *, 4> PhisInBlock(
7520 llvm::make_pointer_range(VecEpilogueIterationCountCheck->phis()));
7521
7522 for (PHINode *Phi : PhisInBlock) {
7523 Phi->moveBefore(LoopVectorPreHeader->getFirstNonPHIIt());
7524 Phi->replaceIncomingBlockWith(
7525 VecEpilogueIterationCountCheck->getSinglePredecessor(),
7526 VecEpilogueIterationCountCheck);
7527
7528 // If the phi doesn't have an incoming value from the
7529 // EpilogueIterationCountCheck, we are done. Otherwise remove the incoming
7530 // value and also those from other check blocks. This is needed for
7531 // reduction phis only.
7532 if (none_of(Phi->blocks(), [&](BasicBlock *IncB) {
7533 return EPI.EpilogueIterationCountCheck == IncB;
7534 }))
7535 continue;
7536 Phi->removeIncomingValue(EPI.EpilogueIterationCountCheck);
7537 if (SCEVCheckBlock)
7538 Phi->removeIncomingValue(SCEVCheckBlock);
7539 if (MemCheckBlock)
7540 Phi->removeIncomingValue(MemCheckBlock);
7541 }
7542
7543 return LoopVectorPreHeader;
7544}
7545
7546BasicBlock *
7548 BasicBlock *Bypass, BasicBlock *Insert) {
7549
7551 "Expected trip count to have been saved in the first pass.");
7552 Value *TC = EPI.TripCount;
7553 IRBuilder<> Builder(Insert->getTerminator());
7554 Value *Count = Builder.CreateSub(TC, EPI.VectorTripCount, "n.vec.remaining");
7555
7556 // Generate code to check if the loop's trip count is less than VF * UF of the
7557 // vector epilogue loop.
7558 auto P = Cost->requiresScalarEpilogue(EPI.EpilogueVF.isVector())
7561
7562 Value *CheckMinIters =
7563 Builder.CreateICmp(P, Count,
7566 "min.epilog.iters.check");
7567
7568 BranchInst &BI =
7569 *BranchInst::Create(Bypass, LoopVectorPreHeader, CheckMinIters);
7571 auto VScale = Cost->getVScaleForTuning();
7572 unsigned MainLoopStep =
7574 unsigned EpilogueLoopStep =
7576 // We assume the remaining `Count` is equally distributed in
7577 // [0, MainLoopStep)
7578 // So the probability for `Count < EpilogueLoopStep` should be
7579 // min(MainLoopStep, EpilogueLoopStep) / MainLoopStep
7580 unsigned EstimatedSkipCount = std::min(MainLoopStep, EpilogueLoopStep);
7581 const uint32_t Weights[] = {EstimatedSkipCount,
7582 MainLoopStep - EstimatedSkipCount};
7583 setBranchWeights(BI, Weights, /*IsExpected=*/false);
7584 }
7585 ReplaceInstWithInst(Insert->getTerminator(), &BI);
7586
7587 // A new entry block has been created for the epilogue VPlan. Hook it in, as
7588 // otherwise we would try to modify the entry to the main vector loop.
7589 VPIRBasicBlock *NewEntry = Plan.createVPIRBasicBlock(Insert);
7590 VPBasicBlock *OldEntry = Plan.getEntry();
7591 VPBlockUtils::reassociateBlocks(OldEntry, NewEntry);
7592 Plan.setEntry(NewEntry);
7593 // OldEntry is now dead and will be cleaned up when the plan gets destroyed.
7594
7595 return Insert;
7596}
7597
7599 LLVM_DEBUG({
7600 dbgs() << "Create Skeleton for epilogue vectorized loop (second pass)\n"
7601 << "Epilogue Loop VF:" << EPI.EpilogueVF
7602 << ", Epilogue Loop UF:" << EPI.EpilogueUF << "\n";
7603 });
7604}
7605
7608 dbgs() << "final fn:\n" << *OrigLoop->getHeader()->getParent() << "\n";
7609 });
7610}
7611
7613VPRecipeBuilder::tryToWidenMemory(Instruction *I, ArrayRef<VPValue *> Operands,
7614 VFRange &Range) {
7615 assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&
7616 "Must be called with either a load or store");
7617
7618 auto WillWiden = [&](ElementCount VF) -> bool {
7620 CM.getWideningDecision(I, VF);
7622 "CM decision should be taken at this point.");
7624 return true;
7625 if (CM.isScalarAfterVectorization(I, VF) ||
7626 CM.isProfitableToScalarize(I, VF))
7627 return false;
7629 };
7630
7632 return nullptr;
7633
7634 VPValue *Mask = nullptr;
7635 if (Legal->isMaskRequired(I))
7636 Mask = getBlockInMask(Builder.getInsertBlock());
7637
7638 // Determine if the pointer operand of the access is either consecutive or
7639 // reverse consecutive.
7641 CM.getWideningDecision(I, Range.Start);
7643 bool Consecutive =
7645
7646 VPValue *Ptr = isa<LoadInst>(I) ? Operands[0] : Operands[1];
7647 if (Consecutive) {
7648 auto *GEP = dyn_cast<GetElementPtrInst>(
7649 Ptr->getUnderlyingValue()->stripPointerCasts());
7650 VPSingleDefRecipe *VectorPtr;
7651 if (Reverse) {
7652 // When folding the tail, we may compute an address that we don't in the
7653 // original scalar loop and it may not be inbounds. Drop Inbounds in that
7654 // case.
7655 GEPNoWrapFlags Flags =
7656 (CM.foldTailByMasking() || !GEP || !GEP->isInBounds())
7659 VectorPtr =
7661 /*Stride*/ -1, Flags, I->getDebugLoc());
7662 } else {
7663 VectorPtr = new VPVectorPointerRecipe(Ptr, getLoadStoreType(I),
7664 GEP ? GEP->getNoWrapFlags()
7666 I->getDebugLoc());
7667 }
7668 Builder.insert(VectorPtr);
7669 Ptr = VectorPtr;
7670 }
7671 if (LoadInst *Load = dyn_cast<LoadInst>(I))
7672 return new VPWidenLoadRecipe(*Load, Ptr, Mask, Consecutive, Reverse,
7673 VPIRMetadata(*Load, LVer), I->getDebugLoc());
7674
7675 StoreInst *Store = cast<StoreInst>(I);
7676 return new VPWidenStoreRecipe(*Store, Ptr, Operands[0], Mask, Consecutive,
7677 Reverse, VPIRMetadata(*Store, LVer),
7678 I->getDebugLoc());
7679}
7680
7681/// Creates a VPWidenIntOrFpInductionRecpipe for \p Phi. If needed, it will also
7682/// insert a recipe to expand the step for the induction recipe.
7685 VPValue *Start, const InductionDescriptor &IndDesc,
7687 assert(IndDesc.getStartValue() ==
7688 Phi->getIncomingValueForBlock(OrigLoop.getLoopPreheader()));
7689 assert(SE.isLoopInvariant(IndDesc.getStep(), &OrigLoop) &&
7690 "step must be loop invariant");
7691
7692 VPValue *Step =
7694 if (auto *TruncI = dyn_cast<TruncInst>(PhiOrTrunc)) {
7695 return new VPWidenIntOrFpInductionRecipe(Phi, Start, Step, &Plan.getVF(),
7696 IndDesc, TruncI,
7697 TruncI->getDebugLoc());
7698 }
7699 assert(isa<PHINode>(PhiOrTrunc) && "must be a phi node here");
7700 return new VPWidenIntOrFpInductionRecipe(Phi, Start, Step, &Plan.getVF(),
7701 IndDesc, Phi->getDebugLoc());
7702}
7703
7704VPHeaderPHIRecipe *VPRecipeBuilder::tryToOptimizeInductionPHI(
7706
7707 // Check if this is an integer or fp induction. If so, build the recipe that
7708 // produces its scalar and vector values.
7709 if (auto *II = Legal->getIntOrFpInductionDescriptor(Phi))
7710 return createWidenInductionRecipes(Phi, Phi, Operands[0], *II, Plan,
7711 *PSE.getSE(), *OrigLoop);
7712
7713 // Check if this is pointer induction. If so, build the recipe for it.
7714 if (auto *II = Legal->getPointerInductionDescriptor(Phi)) {
7717 Phi, Operands[0], Step, &Plan.getVFxUF(), *II,
7719 [&](ElementCount VF) {
7720 return CM.isScalarAfterVectorization(Phi, VF);
7721 },
7722 Range),
7723 Phi->getDebugLoc());
7724 }
7725 return nullptr;
7726}
7727
7728VPWidenIntOrFpInductionRecipe *VPRecipeBuilder::tryToOptimizeInductionTruncate(
7730 // Optimize the special case where the source is a constant integer
7731 // induction variable. Notice that we can only optimize the 'trunc' case
7732 // because (a) FP conversions lose precision, (b) sext/zext may wrap, and
7733 // (c) other casts depend on pointer size.
7734
7735 // Determine whether \p K is a truncation based on an induction variable that
7736 // can be optimized.
7737 auto IsOptimizableIVTruncate =
7738 [&](Instruction *K) -> std::function<bool(ElementCount)> {
7739 return [=](ElementCount VF) -> bool {
7740 return CM.isOptimizableIVTruncate(K, VF);
7741 };
7742 };
7743
7745 IsOptimizableIVTruncate(I), Range)) {
7746
7747 auto *Phi = cast<PHINode>(I->getOperand(0));
7748 const InductionDescriptor &II = *Legal->getIntOrFpInductionDescriptor(Phi);
7749 VPValue *Start = Plan.getOrAddLiveIn(II.getStartValue());
7750 return createWidenInductionRecipes(Phi, I, Start, II, Plan, *PSE.getSE(),
7751 *OrigLoop);
7752 }
7753 return nullptr;
7754}
7755
7756VPSingleDefRecipe *VPRecipeBuilder::tryToWidenCall(CallInst *CI,
7758 VFRange &Range) {
7760 [this, CI](ElementCount VF) {
7761 return CM.isScalarWithPredication(CI, VF);
7762 },
7763 Range);
7764
7765 if (IsPredicated)
7766 return nullptr;
7767
7769 if (ID && (ID == Intrinsic::assume || ID == Intrinsic::lifetime_end ||
7770 ID == Intrinsic::lifetime_start || ID == Intrinsic::sideeffect ||
7771 ID == Intrinsic::pseudoprobe ||
7772 ID == Intrinsic::experimental_noalias_scope_decl))
7773 return nullptr;
7774
7775 SmallVector<VPValue *, 4> Ops(Operands.take_front(CI->arg_size()));
7776
7777 // Is it beneficial to perform intrinsic call compared to lib call?
7778 bool ShouldUseVectorIntrinsic =
7780 [&](ElementCount VF) -> bool {
7781 return CM.getCallWideningDecision(CI, VF).Kind ==
7783 },
7784 Range);
7785 if (ShouldUseVectorIntrinsic)
7786 return new VPWidenIntrinsicRecipe(*CI, ID, Ops, CI->getType(),
7787 CI->getDebugLoc());
7788
7789 Function *Variant = nullptr;
7790 std::optional<unsigned> MaskPos;
7791 // Is better to call a vectorized version of the function than to to scalarize
7792 // the call?
7793 auto ShouldUseVectorCall = LoopVectorizationPlanner::getDecisionAndClampRange(
7794 [&](ElementCount VF) -> bool {
7795 // The following case may be scalarized depending on the VF.
7796 // The flag shows whether we can use a usual Call for vectorized
7797 // version of the instruction.
7798
7799 // If we've found a variant at a previous VF, then stop looking. A
7800 // vectorized variant of a function expects input in a certain shape
7801 // -- basically the number of input registers, the number of lanes
7802 // per register, and whether there's a mask required.
7803 // We store a pointer to the variant in the VPWidenCallRecipe, so
7804 // once we have an appropriate variant it's only valid for that VF.
7805 // This will force a different vplan to be generated for each VF that
7806 // finds a valid variant.
7807 if (Variant)
7808 return false;
7810 CM.getCallWideningDecision(CI, VF);
7812 Variant = Decision.Variant;
7813 MaskPos = Decision.MaskPos;
7814 return true;
7815 }
7816
7817 return false;
7818 },
7819 Range);
7820 if (ShouldUseVectorCall) {
7821 if (MaskPos.has_value()) {
7822 // We have 2 cases that would require a mask:
7823 // 1) The block needs to be predicated, either due to a conditional
7824 // in the scalar loop or use of an active lane mask with
7825 // tail-folding, and we use the appropriate mask for the block.
7826 // 2) No mask is required for the block, but the only available
7827 // vector variant at this VF requires a mask, so we synthesize an
7828 // all-true mask.
7829 VPValue *Mask = nullptr;
7830 if (Legal->isMaskRequired(CI))
7831 Mask = getBlockInMask(Builder.getInsertBlock());
7832 else
7835
7836 Ops.insert(Ops.begin() + *MaskPos, Mask);
7837 }
7838
7839 Ops.push_back(Operands.back());
7840 return new VPWidenCallRecipe(CI, Variant, Ops, CI->getDebugLoc());
7841 }
7842
7843 return nullptr;
7844}
7845
7846bool VPRecipeBuilder::shouldWiden(Instruction *I, VFRange &Range) const {
7847 assert(!isa<BranchInst>(I) && !isa<PHINode>(I) && !isa<LoadInst>(I) &&
7848 !isa<StoreInst>(I) && "Instruction should have been handled earlier");
7849 // Instruction should be widened, unless it is scalar after vectorization,
7850 // scalarization is profitable or it is predicated.
7851 auto WillScalarize = [this, I](ElementCount VF) -> bool {
7852 return CM.isScalarAfterVectorization(I, VF) ||
7853 CM.isProfitableToScalarize(I, VF) ||
7854 CM.isScalarWithPredication(I, VF);
7855 };
7857 Range);
7858}
7859
7860VPWidenRecipe *VPRecipeBuilder::tryToWiden(Instruction *I,
7862 switch (I->getOpcode()) {
7863 default:
7864 return nullptr;
7865 case Instruction::SDiv:
7866 case Instruction::UDiv:
7867 case Instruction::SRem:
7868 case Instruction::URem: {
7869 // If not provably safe, use a select to form a safe divisor before widening the
7870 // div/rem operation itself. Otherwise fall through to general handling below.
7871 if (CM.isPredicatedInst(I)) {
7873 VPValue *Mask = getBlockInMask(Builder.getInsertBlock());
7874 VPValue *One =
7875 Plan.getOrAddLiveIn(ConstantInt::get(I->getType(), 1u, false));
7876 auto *SafeRHS = Builder.createSelect(Mask, Ops[1], One, I->getDebugLoc());
7877 Ops[1] = SafeRHS;
7878 return new VPWidenRecipe(*I, Ops);
7879 }
7880 [[fallthrough]];
7881 }
7882 case Instruction::Add:
7883 case Instruction::And:
7884 case Instruction::AShr:
7885 case Instruction::FAdd:
7886 case Instruction::FCmp:
7887 case Instruction::FDiv:
7888 case Instruction::FMul:
7889 case Instruction::FNeg:
7890 case Instruction::FRem:
7891 case Instruction::FSub:
7892 case Instruction::ICmp:
7893 case Instruction::LShr:
7894 case Instruction::Mul:
7895 case Instruction::Or:
7896 case Instruction::Select:
7897 case Instruction::Shl:
7898 case Instruction::Sub:
7899 case Instruction::Xor:
7900 case Instruction::Freeze: {
7902 if (Instruction::isBinaryOp(I->getOpcode())) {
7903 // The legacy cost model uses SCEV to check if some of the operands are
7904 // constants. To match the legacy cost model's behavior, use SCEV to try
7905 // to replace operands with constants.
7906 ScalarEvolution &SE = *PSE.getSE();
7907 auto GetConstantViaSCEV = [this, &SE](VPValue *Op) {
7908 if (!Op->isLiveIn())
7909 return Op;
7910 Value *V = Op->getUnderlyingValue();
7911 if (isa<Constant>(V) || !SE.isSCEVable(V->getType()))
7912 return Op;
7913 auto *C = dyn_cast<SCEVConstant>(SE.getSCEV(V));
7914 if (!C)
7915 return Op;
7916 return Plan.getOrAddLiveIn(C->getValue());
7917 };
7918 // For Mul, the legacy cost model checks both operands.
7919 if (I->getOpcode() == Instruction::Mul)
7920 NewOps[0] = GetConstantViaSCEV(NewOps[0]);
7921 // For other binops, the legacy cost model only checks the second operand.
7922 NewOps[1] = GetConstantViaSCEV(NewOps[1]);
7923 }
7924 return new VPWidenRecipe(*I, NewOps);
7925 }
7926 case Instruction::ExtractValue: {
7928 Type *I32Ty = IntegerType::getInt32Ty(I->getContext());
7929 auto *EVI = cast<ExtractValueInst>(I);
7930 assert(EVI->getNumIndices() == 1 && "Expected one extractvalue index");
7931 unsigned Idx = EVI->getIndices()[0];
7932 NewOps.push_back(Plan.getOrAddLiveIn(ConstantInt::get(I32Ty, Idx, false)));
7933 return new VPWidenRecipe(*I, NewOps);
7934 }
7935 };
7936}
7937
7939VPRecipeBuilder::tryToWidenHistogram(const HistogramInfo *HI,
7941 // FIXME: Support other operations.
7942 unsigned Opcode = HI->Update->getOpcode();
7943 assert((Opcode == Instruction::Add || Opcode == Instruction::Sub) &&
7944 "Histogram update operation must be an Add or Sub");
7945
7947 // Bucket address.
7948 HGramOps.push_back(Operands[1]);
7949 // Increment value.
7950 HGramOps.push_back(getVPValueOrAddLiveIn(HI->Update->getOperand(1)));
7951
7952 // In case of predicated execution (due to tail-folding, or conditional
7953 // execution, or both), pass the relevant mask.
7954 if (Legal->isMaskRequired(HI->Store))
7955 HGramOps.push_back(getBlockInMask(Builder.getInsertBlock()));
7956
7957 return new VPHistogramRecipe(Opcode, HGramOps, HI->Store->getDebugLoc());
7958}
7959
7962 VFRange &Range) {
7964 [&](ElementCount VF) { return CM.isUniformAfterVectorization(I, VF); },
7965 Range);
7966
7967 bool IsPredicated = CM.isPredicatedInst(I);
7968
7969 // Even if the instruction is not marked as uniform, there are certain
7970 // intrinsic calls that can be effectively treated as such, so we check for
7971 // them here. Conservatively, we only do this for scalable vectors, since
7972 // for fixed-width VFs we can always fall back on full scalarization.
7973 if (!IsUniform && Range.Start.isScalable() && isa<IntrinsicInst>(I)) {
7974 switch (cast<IntrinsicInst>(I)->getIntrinsicID()) {
7975 case Intrinsic::assume:
7976 case Intrinsic::lifetime_start:
7977 case Intrinsic::lifetime_end:
7978 // For scalable vectors if one of the operands is variant then we still
7979 // want to mark as uniform, which will generate one instruction for just
7980 // the first lane of the vector. We can't scalarize the call in the same
7981 // way as for fixed-width vectors because we don't know how many lanes
7982 // there are.
7983 //
7984 // The reasons for doing it this way for scalable vectors are:
7985 // 1. For the assume intrinsic generating the instruction for the first
7986 // lane is still be better than not generating any at all. For
7987 // example, the input may be a splat across all lanes.
7988 // 2. For the lifetime start/end intrinsics the pointer operand only
7989 // does anything useful when the input comes from a stack object,
7990 // which suggests it should always be uniform. For non-stack objects
7991 // the effect is to poison the object, which still allows us to
7992 // remove the call.
7993 IsUniform = true;
7994 break;
7995 default:
7996 break;
7997 }
7998 }
7999 VPValue *BlockInMask = nullptr;
8000 if (!IsPredicated) {
8001 // Finalize the recipe for Instr, first if it is not predicated.
8002 LLVM_DEBUG(dbgs() << "LV: Scalarizing:" << *I << "\n");
8003 } else {
8004 LLVM_DEBUG(dbgs() << "LV: Scalarizing and predicating:" << *I << "\n");
8005 // Instructions marked for predication are replicated and a mask operand is
8006 // added initially. Masked replicate recipes will later be placed under an
8007 // if-then construct to prevent side-effects. Generate recipes to compute
8008 // the block mask for this region.
8009 BlockInMask = getBlockInMask(Builder.getInsertBlock());
8010 }
8011
8012 // Note that there is some custom logic to mark some intrinsics as uniform
8013 // manually above for scalable vectors, which this assert needs to account for
8014 // as well.
8015 assert((Range.Start.isScalar() || !IsUniform || !IsPredicated ||
8016 (Range.Start.isScalable() && isa<IntrinsicInst>(I))) &&
8017 "Should not predicate a uniform recipe");
8018 auto *Recipe = new VPReplicateRecipe(I, Operands, IsUniform, BlockInMask,
8019 VPIRMetadata(*I, LVer));
8020 return Recipe;
8021}
8022
8023/// Find all possible partial reductions in the loop and track all of those that
8024/// are valid so recipes can be formed later.
8026 // Find all possible partial reductions.
8028 PartialReductionChains;
8029 for (const auto &[Phi, RdxDesc] : Legal->getReductionVars()) {
8030 getScaledReductions(Phi, RdxDesc.getLoopExitInstr(), Range,
8031 PartialReductionChains);
8032 }
8033
8034 // A partial reduction is invalid if any of its extends are used by
8035 // something that isn't another partial reduction. This is because the
8036 // extends are intended to be lowered along with the reduction itself.
8037
8038 // Build up a set of partial reduction ops for efficient use checking.
8039 SmallPtrSet<User *, 4> PartialReductionOps;
8040 for (const auto &[PartialRdx, _] : PartialReductionChains)
8041 PartialReductionOps.insert(PartialRdx.ExtendUser);
8042
8043 auto ExtendIsOnlyUsedByPartialReductions =
8044 [&PartialReductionOps](Instruction *Extend) {
8045 return all_of(Extend->users(), [&](const User *U) {
8046 return PartialReductionOps.contains(U);
8047 });
8048 };
8049
8050 // Check if each use of a chain's two extends is a partial reduction
8051 // and only add those that don't have non-partial reduction users.
8052 for (auto Pair : PartialReductionChains) {
8053 PartialReductionChain Chain = Pair.first;
8054 if (ExtendIsOnlyUsedByPartialReductions(Chain.ExtendA) &&
8055 (!Chain.ExtendB || ExtendIsOnlyUsedByPartialReductions(Chain.ExtendB)))
8056 ScaledReductionMap.try_emplace(Chain.Reduction, Pair.second);
8057 }
8058}
8059
8060bool VPRecipeBuilder::getScaledReductions(
8061 Instruction *PHI, Instruction *RdxExitInstr, VFRange &Range,
8062 SmallVectorImpl<std::pair<PartialReductionChain, unsigned>> &Chains) {
8063 if (!CM.TheLoop->contains(RdxExitInstr))
8064 return false;
8065
8066 auto *Update = dyn_cast<BinaryOperator>(RdxExitInstr);
8067 if (!Update)
8068 return false;
8069
8070 Value *Op = Update->getOperand(0);
8071 Value *PhiOp = Update->getOperand(1);
8072 if (Op == PHI)
8073 std::swap(Op, PhiOp);
8074
8075 // Try and get a scaled reduction from the first non-phi operand.
8076 // If one is found, we use the discovered reduction instruction in
8077 // place of the accumulator for costing.
8078 if (auto *OpInst = dyn_cast<Instruction>(Op)) {
8079 if (getScaledReductions(PHI, OpInst, Range, Chains)) {
8080 PHI = Chains.rbegin()->first.Reduction;
8081
8082 Op = Update->getOperand(0);
8083 PhiOp = Update->getOperand(1);
8084 if (Op == PHI)
8085 std::swap(Op, PhiOp);
8086 }
8087 }
8088 if (PhiOp != PHI)
8089 return false;
8090
8091 using namespace llvm::PatternMatch;
8092
8093 // If the update is a binary operator, check both of its operands to see if
8094 // they are extends. Otherwise, see if the update comes directly from an
8095 // extend.
8096 Instruction *Exts[2] = {nullptr};
8097 BinaryOperator *ExtendUser = dyn_cast<BinaryOperator>(Op);
8098 std::optional<unsigned> BinOpc;
8099 Type *ExtOpTypes[2] = {nullptr};
8100
8101 auto CollectExtInfo = [this, &Exts,
8102 &ExtOpTypes](SmallVectorImpl<Value *> &Ops) -> bool {
8103 unsigned I = 0;
8104 for (Value *OpI : Ops) {
8105 Value *ExtOp;
8106 if (!match(OpI, m_ZExtOrSExt(m_Value(ExtOp))))
8107 return false;
8108 Exts[I] = cast<Instruction>(OpI);
8109
8110 // TODO: We should be able to support live-ins.
8111 if (!CM.TheLoop->contains(Exts[I]))
8112 return false;
8113
8114 ExtOpTypes[I] = ExtOp->getType();
8115 I++;
8116 }
8117 return true;
8118 };
8119
8120 if (ExtendUser) {
8121 if (!ExtendUser->hasOneUse())
8122 return false;
8123
8124 // Use the side-effect of match to replace BinOp only if the pattern is
8125 // matched, we don't care at this point whether it actually matched.
8126 match(ExtendUser, m_Neg(m_BinOp(ExtendUser)));
8127
8128 SmallVector<Value *> Ops(ExtendUser->operands());
8129 if (!CollectExtInfo(Ops))
8130 return false;
8131
8132 BinOpc = std::make_optional(ExtendUser->getOpcode());
8133 } else if (match(Update, m_Add(m_Value(), m_Value()))) {
8134 // We already know the operands for Update are Op and PhiOp.
8135 SmallVector<Value *> Ops({Op});
8136 if (!CollectExtInfo(Ops))
8137 return false;
8138
8139 ExtendUser = Update;
8140 BinOpc = std::nullopt;
8141 } else
8142 return false;
8143
8147 Exts[1] ? TTI::getPartialReductionExtendKind(Exts[1]) : TTI::PR_None;
8148 PartialReductionChain Chain(RdxExitInstr, Exts[0], Exts[1], ExtendUser);
8149
8150 TypeSize PHISize = PHI->getType()->getPrimitiveSizeInBits();
8151 TypeSize ASize = ExtOpTypes[0]->getPrimitiveSizeInBits();
8152 if (!PHISize.hasKnownScalarFactor(ASize))
8153 return false;
8154 unsigned TargetScaleFactor = PHISize.getKnownScalarFactor(ASize);
8155
8157 [&](ElementCount VF) {
8159 Update->getOpcode(), ExtOpTypes[0], ExtOpTypes[1],
8160 PHI->getType(), VF, OpAExtend, OpBExtend, BinOpc, CM.CostKind);
8161 return Cost.isValid();
8162 },
8163 Range)) {
8164 Chains.emplace_back(Chain, TargetScaleFactor);
8165 return true;
8166 }
8167
8168 return false;
8169}
8170
8172 VFRange &Range) {
8173 // First, check for specific widening recipes that deal with inductions, Phi
8174 // nodes, calls and memory operations.
8175 VPRecipeBase *Recipe;
8176 Instruction *Instr = R->getUnderlyingInstr();
8177 SmallVector<VPValue *, 4> Operands(R->operands());
8178 if (auto *PhiR = dyn_cast<VPPhi>(R)) {
8179 VPBasicBlock *Parent = PhiR->getParent();
8180 [[maybe_unused]] VPRegionBlock *LoopRegionOf =
8181 Parent->getEnclosingLoopRegion();
8182 assert(LoopRegionOf && LoopRegionOf->getEntry() == Parent &&
8183 "Non-header phis should have been handled during predication");
8184 auto *Phi = cast<PHINode>(R->getUnderlyingInstr());
8185 assert(Operands.size() == 2 && "Must have 2 operands for header phis");
8186 if ((Recipe = tryToOptimizeInductionPHI(Phi, Operands, Range)))
8187 return Recipe;
8188
8189 VPHeaderPHIRecipe *PhiRecipe = nullptr;
8190 assert((Legal->isReductionVariable(Phi) ||
8191 Legal->isFixedOrderRecurrence(Phi)) &&
8192 "can only widen reductions and fixed-order recurrences here");
8193 VPValue *StartV = Operands[0];
8194 if (Legal->isReductionVariable(Phi)) {
8195 const RecurrenceDescriptor &RdxDesc = Legal->getRecurrenceDescriptor(Phi);
8196 assert(RdxDesc.getRecurrenceStartValue() ==
8197 Phi->getIncomingValueForBlock(OrigLoop->getLoopPreheader()));
8198
8199 // If the PHI is used by a partial reduction, set the scale factor.
8200 unsigned ScaleFactor =
8201 getScalingForReduction(RdxDesc.getLoopExitInstr()).value_or(1);
8202 PhiRecipe = new VPReductionPHIRecipe(
8203 Phi, RdxDesc.getRecurrenceKind(), *StartV, CM.isInLoopReduction(Phi),
8204 CM.useOrderedReductions(RdxDesc), ScaleFactor);
8205 } else {
8206 // TODO: Currently fixed-order recurrences are modeled as chains of
8207 // first-order recurrences. If there are no users of the intermediate
8208 // recurrences in the chain, the fixed order recurrence should be modeled
8209 // directly, enabling more efficient codegen.
8210 PhiRecipe = new VPFirstOrderRecurrencePHIRecipe(Phi, *StartV);
8211 }
8212 // Add backedge value.
8213 PhiRecipe->addOperand(Operands[1]);
8214 return PhiRecipe;
8215 }
8216 assert(!R->isPhi() && "only VPPhi nodes expected at this point");
8217
8218 if (isa<TruncInst>(Instr) && (Recipe = tryToOptimizeInductionTruncate(
8219 cast<TruncInst>(Instr), Operands, Range)))
8220 return Recipe;
8221
8222 // All widen recipes below deal only with VF > 1.
8224 [&](ElementCount VF) { return VF.isScalar(); }, Range))
8225 return nullptr;
8226
8227 if (auto *CI = dyn_cast<CallInst>(Instr))
8228 return tryToWidenCall(CI, Operands, Range);
8229
8230 if (StoreInst *SI = dyn_cast<StoreInst>(Instr))
8231 if (auto HistInfo = Legal->getHistogramInfo(SI))
8232 return tryToWidenHistogram(*HistInfo, Operands);
8233
8234 if (isa<LoadInst>(Instr) || isa<StoreInst>(Instr))
8235 return tryToWidenMemory(Instr, Operands, Range);
8236
8237 if (std::optional<unsigned> ScaleFactor = getScalingForReduction(Instr))
8238 return tryToCreatePartialReduction(Instr, Operands, ScaleFactor.value());
8239
8240 if (!shouldWiden(Instr, Range))
8241 return nullptr;
8242
8243 if (auto *GEP = dyn_cast<GetElementPtrInst>(Instr))
8244 return new VPWidenGEPRecipe(GEP, Operands);
8245
8246 if (auto *SI = dyn_cast<SelectInst>(Instr)) {
8247 return new VPWidenSelectRecipe(*SI, Operands);
8248 }
8249
8250 if (auto *CI = dyn_cast<CastInst>(Instr)) {
8251 return new VPWidenCastRecipe(CI->getOpcode(), Operands[0], CI->getType(),
8252 *CI);
8253 }
8254
8255 return tryToWiden(Instr, Operands);
8256}
8257
8261 unsigned ScaleFactor) {
8262 assert(Operands.size() == 2 &&
8263 "Unexpected number of operands for partial reduction");
8264
8265 VPValue *BinOp = Operands[0];
8267 VPRecipeBase *BinOpRecipe = BinOp->getDefiningRecipe();
8268 if (isa<VPReductionPHIRecipe>(BinOpRecipe) ||
8269 isa<VPPartialReductionRecipe>(BinOpRecipe))
8270 std::swap(BinOp, Accumulator);
8271
8272 unsigned ReductionOpcode = Reduction->getOpcode();
8273 if (ReductionOpcode == Instruction::Sub) {
8274 auto *const Zero = ConstantInt::get(Reduction->getType(), 0);
8276 Ops.push_back(Plan.getOrAddLiveIn(Zero));
8277 Ops.push_back(BinOp);
8278 BinOp = new VPWidenRecipe(*Reduction, Ops);
8279 Builder.insert(BinOp->getDefiningRecipe());
8280 ReductionOpcode = Instruction::Add;
8281 }
8282
8283 VPValue *Cond = nullptr;
8284 if (CM.blockNeedsPredicationForAnyReason(Reduction->getParent())) {
8285 assert((ReductionOpcode == Instruction::Add ||
8286 ReductionOpcode == Instruction::Sub) &&
8287 "Expected an ADD or SUB operation for predicated partial "
8288 "reductions (because the neutral element in the mask is zero)!");
8289 Cond = getBlockInMask(Builder.getInsertBlock());
8290 VPValue *Zero =
8291 Plan.getOrAddLiveIn(ConstantInt::get(Reduction->getType(), 0));
8292 BinOp = Builder.createSelect(Cond, BinOp, Zero, Reduction->getDebugLoc());
8293 }
8294 return new VPPartialReductionRecipe(ReductionOpcode, Accumulator, BinOp, Cond,
8295 ScaleFactor, Reduction);
8296}
8297
8298void LoopVectorizationPlanner::buildVPlansWithVPRecipes(ElementCount MinVF,
8299 ElementCount MaxVF) {
8300 if (ElementCount::isKnownGT(MinVF, MaxVF))
8301 return;
8302
8303 assert(OrigLoop->isInnermost() && "Inner loop expected.");
8304
8305 const LoopAccessInfo *LAI = Legal->getLAI();
8307 OrigLoop, LI, DT, PSE.getSE());
8308 if (!LAI->getRuntimePointerChecking()->getChecks().empty() &&
8310 // Only use noalias metadata when using memory checks guaranteeing no
8311 // overlap across all iterations.
8312 LVer.prepareNoAliasMetadata();
8313 }
8314
8315 // Create initial base VPlan0, to serve as common starting point for all
8316 // candidates built later for specific VF ranges.
8317 auto VPlan0 = VPlanTransforms::buildVPlan0(
8318 OrigLoop, *LI, Legal->getWidestInductionType(),
8319 getDebugLocFromInstOrOperands(Legal->getPrimaryInduction()), PSE);
8320
8321 auto MaxVFTimes2 = MaxVF * 2;
8322 for (ElementCount VF = MinVF; ElementCount::isKnownLT(VF, MaxVFTimes2);) {
8323 VFRange SubRange = {VF, MaxVFTimes2};
8324 if (auto Plan = tryToBuildVPlanWithVPRecipes(
8325 std::unique_ptr<VPlan>(VPlan0->duplicate()), SubRange, &LVer)) {
8326 bool HasScalarVF = Plan->hasScalarVFOnly();
8327 // Now optimize the initial VPlan.
8328 if (!HasScalarVF)
8330 *Plan, CM.getMinimalBitwidths());
8332 // TODO: try to put it close to addActiveLaneMask().
8333 if (CM.foldTailWithEVL() && !HasScalarVF)
8335 *Plan, CM.getMaxSafeElements());
8336 assert(verifyVPlanIsValid(*Plan) && "VPlan is invalid");
8337 VPlans.push_back(std::move(Plan));
8338 }
8339 VF = SubRange.End;
8340 }
8341}
8342
8343/// Create and return a ResumePhi for \p WideIV, unless it is truncated. If the
8344/// induction recipe is not canonical, creates a VPDerivedIVRecipe to compute
8345/// the end value of the induction.
8347 VPWidenInductionRecipe *WideIV, VPBuilder &VectorPHBuilder,
8348 VPBuilder &ScalarPHBuilder, VPTypeAnalysis &TypeInfo, VPValue *VectorTC) {
8349 auto *WideIntOrFp = dyn_cast<VPWidenIntOrFpInductionRecipe>(WideIV);
8350 // Truncated wide inductions resume from the last lane of their vector value
8351 // in the last vector iteration which is handled elsewhere.
8352 if (WideIntOrFp && WideIntOrFp->getTruncInst())
8353 return nullptr;
8354
8355 VPValue *Start = WideIV->getStartValue();
8356 VPValue *Step = WideIV->getStepValue();
8358 VPValue *EndValue = VectorTC;
8359 if (!WideIntOrFp || !WideIntOrFp->isCanonical()) {
8360 EndValue = VectorPHBuilder.createDerivedIV(
8361 ID.getKind(), dyn_cast_or_null<FPMathOperator>(ID.getInductionBinOp()),
8362 Start, VectorTC, Step);
8363 }
8364
8365 // EndValue is derived from the vector trip count (which has the same type as
8366 // the widest induction) and thus may be wider than the induction here.
8367 Type *ScalarTypeOfWideIV = TypeInfo.inferScalarType(WideIV);
8368 if (ScalarTypeOfWideIV != TypeInfo.inferScalarType(EndValue)) {
8369 EndValue = VectorPHBuilder.createScalarCast(Instruction::Trunc, EndValue,
8370 ScalarTypeOfWideIV,
8371 WideIV->getDebugLoc());
8372 }
8373
8374 auto *ResumePhiRecipe = ScalarPHBuilder.createScalarPhi(
8375 {EndValue, Start}, WideIV->getDebugLoc(), "bc.resume.val");
8376 return ResumePhiRecipe;
8377}
8378
8379/// Create resume phis in the scalar preheader for first-order recurrences,
8380/// reductions and inductions, and update the VPIRInstructions wrapping the
8381/// original phis in the scalar header. End values for inductions are added to
8382/// \p IVEndValues.
8384 DenseMap<VPValue *, VPValue *> &IVEndValues) {
8385 VPTypeAnalysis TypeInfo(Plan);
8386 auto *ScalarPH = Plan.getScalarPreheader();
8387 auto *MiddleVPBB = cast<VPBasicBlock>(ScalarPH->getPredecessors()[0]);
8388 VPRegionBlock *VectorRegion = Plan.getVectorLoopRegion();
8389 VPBuilder VectorPHBuilder(
8390 cast<VPBasicBlock>(VectorRegion->getSinglePredecessor()));
8391 VPBuilder MiddleBuilder(MiddleVPBB, MiddleVPBB->getFirstNonPhi());
8392 VPBuilder ScalarPHBuilder(ScalarPH);
8393 for (VPRecipeBase &ScalarPhiR : Plan.getScalarHeader()->phis()) {
8394 auto *ScalarPhiIRI = cast<VPIRPhi>(&ScalarPhiR);
8395
8396 // TODO: Extract final value from induction recipe initially, optimize to
8397 // pre-computed end value together in optimizeInductionExitUsers.
8398 auto *VectorPhiR =
8399 cast<VPHeaderPHIRecipe>(Builder.getRecipe(&ScalarPhiIRI->getIRPhi()));
8400 if (auto *WideIVR = dyn_cast<VPWidenInductionRecipe>(VectorPhiR)) {
8402 WideIVR, VectorPHBuilder, ScalarPHBuilder, TypeInfo,
8404 assert(isa<VPPhi>(ResumePhi) && "Expected a phi");
8405 IVEndValues[WideIVR] = ResumePhi->getOperand(0);
8406 ScalarPhiIRI->addOperand(ResumePhi);
8407 continue;
8408 }
8409 // TODO: Also handle truncated inductions here. Computing end-values
8410 // separately should be done as VPlan-to-VPlan optimization, after
8411 // legalizing all resume values to use the last lane from the loop.
8412 assert(cast<VPWidenIntOrFpInductionRecipe>(VectorPhiR)->getTruncInst() &&
8413 "should only skip truncated wide inductions");
8414 continue;
8415 }
8416
8417 // The backedge value provides the value to resume coming out of a loop,
8418 // which for FORs is a vector whose last element needs to be extracted. The
8419 // start value provides the value if the loop is bypassed.
8420 bool IsFOR = isa<VPFirstOrderRecurrencePHIRecipe>(VectorPhiR);
8421 auto *ResumeFromVectorLoop = VectorPhiR->getBackedgeValue();
8422 assert(VectorRegion->getSingleSuccessor() == Plan.getMiddleBlock() &&
8423 "Cannot handle loops with uncountable early exits");
8424 if (IsFOR)
8425 ResumeFromVectorLoop = MiddleBuilder.createNaryOp(
8426 VPInstruction::ExtractLastElement, {ResumeFromVectorLoop}, {},
8427 "vector.recur.extract");
8428 StringRef Name = IsFOR ? "scalar.recur.init" : "bc.merge.rdx";
8429 auto *ResumePhiR = ScalarPHBuilder.createScalarPhi(
8430 {ResumeFromVectorLoop, VectorPhiR->getStartValue()}, {}, Name);
8431 ScalarPhiIRI->addOperand(ResumePhiR);
8432 }
8433}
8434
8435/// Handle users in the exit block for first order reductions in the original
8436/// exit block. The penultimate value of recurrences is fed to their LCSSA phi
8437/// users in the original exit block using the VPIRInstruction wrapping to the
8438/// LCSSA phi.
8440 VPRegionBlock *VectorRegion = Plan.getVectorLoopRegion();
8441 auto *ScalarPHVPBB = Plan.getScalarPreheader();
8442 auto *MiddleVPBB = Plan.getMiddleBlock();
8443 VPBuilder ScalarPHBuilder(ScalarPHVPBB);
8444 VPBuilder MiddleBuilder(MiddleVPBB, MiddleVPBB->getFirstNonPhi());
8445
8446 auto IsScalableOne = [](ElementCount VF) -> bool {
8447 return VF == ElementCount::getScalable(1);
8448 };
8449
8450 for (auto &HeaderPhi : VectorRegion->getEntryBasicBlock()->phis()) {
8451 auto *FOR = dyn_cast<VPFirstOrderRecurrencePHIRecipe>(&HeaderPhi);
8452 if (!FOR)
8453 continue;
8454
8455 assert(VectorRegion->getSingleSuccessor() == Plan.getMiddleBlock() &&
8456 "Cannot handle loops with uncountable early exits");
8457
8458 // This is the second phase of vectorizing first-order recurrences, creating
8459 // extract for users outside the loop. An overview of the transformation is
8460 // described below. Suppose we have the following loop with some use after
8461 // the loop of the last a[i-1],
8462 //
8463 // for (int i = 0; i < n; ++i) {
8464 // t = a[i - 1];
8465 // b[i] = a[i] - t;
8466 // }
8467 // use t;
8468 //
8469 // There is a first-order recurrence on "a". For this loop, the shorthand
8470 // scalar IR looks like:
8471 //
8472 // scalar.ph:
8473 // s.init = a[-1]
8474 // br scalar.body
8475 //
8476 // scalar.body:
8477 // i = phi [0, scalar.ph], [i+1, scalar.body]
8478 // s1 = phi [s.init, scalar.ph], [s2, scalar.body]
8479 // s2 = a[i]
8480 // b[i] = s2 - s1
8481 // br cond, scalar.body, exit.block
8482 //
8483 // exit.block:
8484 // use = lcssa.phi [s1, scalar.body]
8485 //
8486 // In this example, s1 is a recurrence because it's value depends on the
8487 // previous iteration. In the first phase of vectorization, we created a
8488 // VPFirstOrderRecurrencePHIRecipe v1 for s1. Now we create the extracts
8489 // for users in the scalar preheader and exit block.
8490 //
8491 // vector.ph:
8492 // v_init = vector(..., ..., ..., a[-1])
8493 // br vector.body
8494 //
8495 // vector.body
8496 // i = phi [0, vector.ph], [i+4, vector.body]
8497 // v1 = phi [v_init, vector.ph], [v2, vector.body]
8498 // v2 = a[i, i+1, i+2, i+3]
8499 // b[i] = v2 - v1
8500 // // Next, third phase will introduce v1' = splice(v1(3), v2(0, 1, 2))
8501 // b[i, i+1, i+2, i+3] = v2 - v1
8502 // br cond, vector.body, middle.block
8503 //
8504 // middle.block:
8505 // vector.recur.extract.for.phi = v2(2)
8506 // vector.recur.extract = v2(3)
8507 // br cond, scalar.ph, exit.block
8508 //
8509 // scalar.ph:
8510 // scalar.recur.init = phi [vector.recur.extract, middle.block],
8511 // [s.init, otherwise]
8512 // br scalar.body
8513 //
8514 // scalar.body:
8515 // i = phi [0, scalar.ph], [i+1, scalar.body]
8516 // s1 = phi [scalar.recur.init, scalar.ph], [s2, scalar.body]
8517 // s2 = a[i]
8518 // b[i] = s2 - s1
8519 // br cond, scalar.body, exit.block
8520 //
8521 // exit.block:
8522 // lo = lcssa.phi [s1, scalar.body],
8523 // [vector.recur.extract.for.phi, middle.block]
8524 //
8525 // Now update VPIRInstructions modeling LCSSA phis in the exit block.
8526 // Extract the penultimate value of the recurrence and use it as operand for
8527 // the VPIRInstruction modeling the phi.
8528 for (VPUser *U : FOR->users()) {
8529 using namespace llvm::VPlanPatternMatch;
8530 if (!match(U, m_ExtractLastElement(m_Specific(FOR))))
8531 continue;
8532 // For VF vscale x 1, if vscale = 1, we are unable to extract the
8533 // penultimate value of the recurrence. Instead we rely on the existing
8534 // extract of the last element from the result of
8535 // VPInstruction::FirstOrderRecurrenceSplice.
8536 // TODO: Consider vscale_range info and UF.
8538 Range))
8539 return;
8540 VPValue *PenultimateElement = MiddleBuilder.createNaryOp(
8541 VPInstruction::ExtractPenultimateElement, {FOR->getBackedgeValue()},
8542 {}, "vector.recur.extract.for.phi");
8543 cast<VPInstruction>(U)->replaceAllUsesWith(PenultimateElement);
8544 }
8545 }
8546}
8547
8548VPlanPtr LoopVectorizationPlanner::tryToBuildVPlanWithVPRecipes(
8550
8551 using namespace llvm::VPlanPatternMatch;
8553
8554 // ---------------------------------------------------------------------------
8555 // Build initial VPlan: Scan the body of the loop in a topological order to
8556 // visit each basic block after having visited its predecessor basic blocks.
8557 // ---------------------------------------------------------------------------
8558
8559 bool RequiresScalarEpilogueCheck =
8561 [this](ElementCount VF) {
8562 return !CM.requiresScalarEpilogue(VF.isVector());
8563 },
8564 Range);
8565 VPlanTransforms::handleEarlyExits(*Plan, Legal->hasUncountableEarlyExit());
8566 VPlanTransforms::addMiddleCheck(*Plan, RequiresScalarEpilogueCheck,
8567 CM.foldTailByMasking());
8568
8570
8571 // Don't use getDecisionAndClampRange here, because we don't know the UF
8572 // so this function is better to be conservative, rather than to split
8573 // it up into different VPlans.
8574 // TODO: Consider using getDecisionAndClampRange here to split up VPlans.
8575 bool IVUpdateMayOverflow = false;
8576 for (ElementCount VF : Range)
8577 IVUpdateMayOverflow |= !isIndvarOverflowCheckKnownFalse(&CM, VF);
8578
8579 TailFoldingStyle Style = CM.getTailFoldingStyle(IVUpdateMayOverflow);
8580 // Use NUW for the induction increment if we proved that it won't overflow in
8581 // the vector loop or when not folding the tail. In the later case, we know
8582 // that the canonical induction increment will not overflow as the vector trip
8583 // count is >= increment and a multiple of the increment.
8584 bool HasNUW = !IVUpdateMayOverflow || Style == TailFoldingStyle::None;
8585 if (!HasNUW) {
8586 auto *IVInc = Plan->getVectorLoopRegion()
8588 ->getTerminator()
8589 ->getOperand(0);
8590 assert(match(IVInc, m_VPInstruction<Instruction::Add>(
8592 "Did not find the canonical IV increment");
8593 cast<VPRecipeWithIRFlags>(IVInc)->dropPoisonGeneratingFlags();
8594 }
8595
8596 // ---------------------------------------------------------------------------
8597 // Pre-construction: record ingredients whose recipes we'll need to further
8598 // process after constructing the initial VPlan.
8599 // ---------------------------------------------------------------------------
8600
8601 // For each interleave group which is relevant for this (possibly trimmed)
8602 // Range, add it to the set of groups to be later applied to the VPlan and add
8603 // placeholders for its members' Recipes which we'll be replacing with a
8604 // single VPInterleaveRecipe.
8605 for (InterleaveGroup<Instruction> *IG : IAI.getInterleaveGroups()) {
8606 auto ApplyIG = [IG, this](ElementCount VF) -> bool {
8607 bool Result = (VF.isVector() && // Query is illegal for VF == 1
8608 CM.getWideningDecision(IG->getInsertPos(), VF) ==
8610 // For scalable vectors, the interleave factors must be <= 8 since we
8611 // require the (de)interleaveN intrinsics instead of shufflevectors.
8612 assert((!Result || !VF.isScalable() || IG->getFactor() <= 8) &&
8613 "Unsupported interleave factor for scalable vectors");
8614 return Result;
8615 };
8616 if (!getDecisionAndClampRange(ApplyIG, Range))
8617 continue;
8618 InterleaveGroups.insert(IG);
8619 }
8620
8621 // ---------------------------------------------------------------------------
8622 // Predicate and linearize the top-level loop region.
8623 // ---------------------------------------------------------------------------
8624 auto BlockMaskCache = VPlanTransforms::introduceMasksAndLinearize(
8625 *Plan, CM.foldTailByMasking());
8626
8627 // ---------------------------------------------------------------------------
8628 // Construct wide recipes and apply predication for original scalar
8629 // VPInstructions in the loop.
8630 // ---------------------------------------------------------------------------
8631 VPRecipeBuilder RecipeBuilder(*Plan, OrigLoop, TLI, &TTI, Legal, CM, PSE,
8632 Builder, BlockMaskCache, LVer);
8633 RecipeBuilder.collectScaledReductions(Range);
8634
8635 // Scan the body of the loop in a topological order to visit each basic block
8636 // after having visited its predecessor basic blocks.
8637 VPRegionBlock *LoopRegion = Plan->getVectorLoopRegion();
8638 VPBasicBlock *HeaderVPBB = LoopRegion->getEntryBasicBlock();
8640 HeaderVPBB);
8641
8642 auto *MiddleVPBB = Plan->getMiddleBlock();
8643 VPBasicBlock::iterator MBIP = MiddleVPBB->getFirstNonPhi();
8644 // Mapping from VPValues in the initial plan to their widened VPValues. Needed
8645 // temporarily to update created block masks.
8647 for (VPBasicBlock *VPBB : VPBlockUtils::blocksOnly<VPBasicBlock>(RPOT)) {
8648 // Convert input VPInstructions to widened recipes.
8649 for (VPRecipeBase &R : make_early_inc_range(*VPBB)) {
8650 auto *SingleDef = cast<VPSingleDefRecipe>(&R);
8651 auto *UnderlyingValue = SingleDef->getUnderlyingValue();
8652 // Skip recipes that do not need transforming, including canonical IV,
8653 // wide canonical IV and VPInstructions without underlying values. The
8654 // latter are added above for masking.
8655 // FIXME: Migrate code relying on the underlying instruction from VPlan0
8656 // to construct recipes below to not use the underlying instruction.
8657 if (isa<VPCanonicalIVPHIRecipe, VPWidenCanonicalIVRecipe, VPBlendRecipe>(
8658 &R) ||
8659 (isa<VPInstruction>(&R) && !UnderlyingValue))
8660 continue;
8661
8662 // FIXME: VPlan0, which models a copy of the original scalar loop, should
8663 // not use VPWidenPHIRecipe to model the phis.
8664 assert((isa<VPWidenPHIRecipe>(&R) || isa<VPInstruction>(&R)) &&
8665 UnderlyingValue && "unsupported recipe");
8666
8667 // TODO: Gradually replace uses of underlying instruction by analyses on
8668 // VPlan.
8669 Instruction *Instr = cast<Instruction>(UnderlyingValue);
8670 Builder.setInsertPoint(SingleDef);
8671
8672 // The stores with invariant address inside the loop will be deleted, and
8673 // in the exit block, a uniform store recipe will be created for the final
8674 // invariant store of the reduction.
8675 StoreInst *SI;
8676 if ((SI = dyn_cast<StoreInst>(Instr)) &&
8677 Legal->isInvariantAddressOfReduction(SI->getPointerOperand())) {
8678 // Only create recipe for the final invariant store of the reduction.
8679 if (Legal->isInvariantStoreOfReduction(SI)) {
8680 auto *Recipe =
8681 new VPReplicateRecipe(SI, R.operands(), true /* IsUniform */,
8682 nullptr /*Mask*/, VPIRMetadata(*SI, LVer));
8683 Recipe->insertBefore(*MiddleVPBB, MBIP);
8684 }
8685 R.eraseFromParent();
8686 continue;
8687 }
8688
8689 VPRecipeBase *Recipe =
8690 RecipeBuilder.tryToCreateWidenRecipe(SingleDef, Range);
8691 if (!Recipe) {
8693 Recipe = RecipeBuilder.handleReplication(Instr, Operands, Range);
8694 }
8695
8696 RecipeBuilder.setRecipe(Instr, Recipe);
8697 if (isa<VPWidenIntOrFpInductionRecipe>(Recipe) && isa<TruncInst>(Instr)) {
8698 // Optimized a truncate to VPWidenIntOrFpInductionRecipe. It needs to be
8699 // moved to the phi section in the header.
8700 Recipe->insertBefore(*HeaderVPBB, HeaderVPBB->getFirstNonPhi());
8701 } else {
8702 Builder.insert(Recipe);
8703 }
8704 if (Recipe->getNumDefinedValues() == 1) {
8705 SingleDef->replaceAllUsesWith(Recipe->getVPSingleValue());
8706 Old2New[SingleDef] = Recipe->getVPSingleValue();
8707 } else {
8708 assert(Recipe->getNumDefinedValues() == 0 &&
8709 "Unexpected multidef recipe");
8710 R.eraseFromParent();
8711 }
8712 }
8713 }
8714
8715 // replaceAllUsesWith above may invalidate the block masks. Update them here.
8716 // TODO: Include the masks as operands in the predicated VPlan directly
8717 // to remove the need to keep a map of masks beyond the predication
8718 // transform.
8719 RecipeBuilder.updateBlockMaskCache(Old2New);
8720 for (VPValue *Old : Old2New.keys())
8721 Old->getDefiningRecipe()->eraseFromParent();
8722
8723 assert(isa<VPRegionBlock>(Plan->getVectorLoopRegion()) &&
8725 "entry block must be set to a VPRegionBlock having a non-empty entry "
8726 "VPBasicBlock");
8727
8728 // Update wide induction increments to use the same step as the corresponding
8729 // wide induction. This enables detecting induction increments directly in
8730 // VPlan and removes redundant splats.
8731 for (const auto &[Phi, ID] : Legal->getInductionVars()) {
8732 auto *IVInc = cast<Instruction>(
8733 Phi->getIncomingValueForBlock(OrigLoop->getLoopLatch()));
8734 if (IVInc->getOperand(0) != Phi || IVInc->getOpcode() != Instruction::Add)
8735 continue;
8736 VPWidenInductionRecipe *WideIV =
8737 cast<VPWidenInductionRecipe>(RecipeBuilder.getRecipe(Phi));
8738 VPRecipeBase *R = RecipeBuilder.getRecipe(IVInc);
8739 R->setOperand(1, WideIV->getStepValue());
8740 }
8741
8744 addScalarResumePhis(RecipeBuilder, *Plan, IVEndValues);
8745
8746 // ---------------------------------------------------------------------------
8747 // Transform initial VPlan: Apply previously taken decisions, in order, to
8748 // bring the VPlan to its final state.
8749 // ---------------------------------------------------------------------------
8750
8751 // Adjust the recipes for any inloop reductions.
8752 adjustRecipesForReductions(Plan, RecipeBuilder, Range.Start);
8753
8754 // Apply mandatory transformation to handle FP maxnum/minnum reduction with
8755 // NaNs if possible, bail out otherwise.
8757 *Plan))
8758 return nullptr;
8759
8760 // Transform recipes to abstract recipes if it is legal and beneficial and
8761 // clamp the range for better cost estimation.
8762 // TODO: Enable following transform when the EVL-version of extended-reduction
8763 // and mulacc-reduction are implemented.
8764 if (!CM.foldTailWithEVL()) {
8765 VPCostContext CostCtx(CM.TTI, *CM.TLI, *Plan, CM, CM.CostKind);
8767 CostCtx, Range);
8768 }
8769
8770 for (ElementCount VF : Range)
8771 Plan->addVF(VF);
8772 Plan->setName("Initial VPlan");
8773
8774 // Interleave memory: for each Interleave Group we marked earlier as relevant
8775 // for this VPlan, replace the Recipes widening its memory instructions with a
8776 // single VPInterleaveRecipe at its insertion point.
8778 InterleaveGroups, RecipeBuilder,
8779 CM.isScalarEpilogueAllowed());
8780
8781 // Replace VPValues for known constant strides guaranteed by predicate scalar
8782 // evolution.
8783 auto CanUseVersionedStride = [&Plan](VPUser &U, unsigned) {
8784 auto *R = cast<VPRecipeBase>(&U);
8785 return R->getParent()->getParent() ||
8786 R->getParent() ==
8788 };
8789 for (auto [_, Stride] : Legal->getLAI()->getSymbolicStrides()) {
8790 auto *StrideV = cast<SCEVUnknown>(Stride)->getValue();
8791 auto *ScevStride = dyn_cast<SCEVConstant>(PSE.getSCEV(StrideV));
8792 // Only handle constant strides for now.
8793 if (!ScevStride)
8794 continue;
8795
8796 auto *CI = Plan->getOrAddLiveIn(
8797 ConstantInt::get(Stride->getType(), ScevStride->getAPInt()));
8798 if (VPValue *StrideVPV = Plan->getLiveIn(StrideV))
8799 StrideVPV->replaceUsesWithIf(CI, CanUseVersionedStride);
8800
8801 // The versioned value may not be used in the loop directly but through a
8802 // sext/zext. Add new live-ins in those cases.
8803 for (Value *U : StrideV->users()) {
8804 if (!isa<SExtInst, ZExtInst>(U))
8805 continue;
8806 VPValue *StrideVPV = Plan->getLiveIn(U);
8807 if (!StrideVPV)
8808 continue;
8809 unsigned BW = U->getType()->getScalarSizeInBits();
8810 APInt C = isa<SExtInst>(U) ? ScevStride->getAPInt().sext(BW)
8811 : ScevStride->getAPInt().zext(BW);
8812 VPValue *CI = Plan->getOrAddLiveIn(ConstantInt::get(U->getType(), C));
8813 StrideVPV->replaceUsesWithIf(CI, CanUseVersionedStride);
8814 }
8815 }
8816
8817 auto BlockNeedsPredication = [this](BasicBlock *BB) {
8818 return Legal->blockNeedsPredication(BB);
8819 };
8821 BlockNeedsPredication);
8822
8823 // Sink users of fixed-order recurrence past the recipe defining the previous
8824 // value and introduce FirstOrderRecurrenceSplice VPInstructions.
8826 *Plan, Builder))
8827 return nullptr;
8828
8829 if (useActiveLaneMask(Style)) {
8830 // TODO: Move checks to VPlanTransforms::addActiveLaneMask once
8831 // TailFoldingStyle is visible there.
8832 bool ForControlFlow = useActiveLaneMaskForControlFlow(Style);
8833 bool WithoutRuntimeCheck =
8836 WithoutRuntimeCheck);
8837 }
8839
8840 assert(verifyVPlanIsValid(*Plan) && "VPlan is invalid");
8841 return Plan;
8842}
8843
8844VPlanPtr LoopVectorizationPlanner::tryToBuildVPlan(VFRange &Range) {
8845 // Outer loop handling: They may require CFG and instruction level
8846 // transformations before even evaluating whether vectorization is profitable.
8847 // Since we cannot modify the incoming IR, we need to build VPlan upfront in
8848 // the vectorization pipeline.
8850 assert(EnableVPlanNativePath && "VPlan-native path is not enabled.");
8851
8853 OrigLoop, *LI, Legal->getWidestInductionType(),
8854 getDebugLocFromInstOrOperands(Legal->getPrimaryInduction()), PSE);
8856 /*HasUncountableExit*/ false);
8857 VPlanTransforms::addMiddleCheck(*Plan, /*RequiresScalarEpilogue*/ true,
8858 /*TailFolded*/ false);
8859
8861
8862 for (ElementCount VF : Range)
8863 Plan->addVF(VF);
8864
8866 Plan,
8867 [this](PHINode *P) {
8868 return Legal->getIntOrFpInductionDescriptor(P);
8869 },
8870 *TLI))
8871 return nullptr;
8872
8873 // Collect mapping of IR header phis to header phi recipes, to be used in
8874 // addScalarResumePhis.
8876 VPRecipeBuilder RecipeBuilder(*Plan, OrigLoop, TLI, &TTI, Legal, CM, PSE,
8877 Builder, BlockMaskCache, nullptr /*LVer*/);
8878 for (auto &R : Plan->getVectorLoopRegion()->getEntryBasicBlock()->phis()) {
8879 if (isa<VPCanonicalIVPHIRecipe>(&R))
8880 continue;
8881 auto *HeaderR = cast<VPHeaderPHIRecipe>(&R);
8882 RecipeBuilder.setRecipe(HeaderR->getUnderlyingInstr(), HeaderR);
8883 }
8885 // TODO: IVEndValues are not used yet in the native path, to optimize exit
8886 // values.
8887 addScalarResumePhis(RecipeBuilder, *Plan, IVEndValues);
8888
8889 assert(verifyVPlanIsValid(*Plan) && "VPlan is invalid");
8890 return Plan;
8891}
8892
8893// Adjust the recipes for reductions. For in-loop reductions the chain of
8894// instructions leading from the loop exit instr to the phi need to be converted
8895// to reductions, with one operand being vector and the other being the scalar
8896// reduction chain. For other reductions, a select is introduced between the phi
8897// and users outside the vector region when folding the tail.
8898//
8899// A ComputeReductionResult recipe is added to the middle block, also for
8900// in-loop reductions which compute their result in-loop, because generating
8901// the subsequent bc.merge.rdx phi is driven by ComputeReductionResult recipes.
8902//
8903// Adjust AnyOf reductions; replace the reduction phi for the selected value
8904// with a boolean reduction phi node to check if the condition is true in any
8905// iteration. The final value is selected by the final ComputeReductionResult.
8906void LoopVectorizationPlanner::adjustRecipesForReductions(
8907 VPlanPtr &Plan, VPRecipeBuilder &RecipeBuilder, ElementCount MinVF) {
8908 using namespace VPlanPatternMatch;
8909 VPRegionBlock *VectorLoopRegion = Plan->getVectorLoopRegion();
8910 VPBasicBlock *Header = VectorLoopRegion->getEntryBasicBlock();
8911 VPBasicBlock *MiddleVPBB = Plan->getMiddleBlock();
8913
8914 for (VPRecipeBase &R : Header->phis()) {
8915 auto *PhiR = dyn_cast<VPReductionPHIRecipe>(&R);
8916 if (!PhiR || !PhiR->isInLoop() || (MinVF.isScalar() && !PhiR->isOrdered()))
8917 continue;
8918
8919 RecurKind Kind = PhiR->getRecurrenceKind();
8920 assert(
8923 "AnyOf and FindIV reductions are not allowed for in-loop reductions");
8924
8925 // Collect the chain of "link" recipes for the reduction starting at PhiR.
8927 Worklist.insert(PhiR);
8928 for (unsigned I = 0; I != Worklist.size(); ++I) {
8929 VPSingleDefRecipe *Cur = Worklist[I];
8930 for (VPUser *U : Cur->users()) {
8931 auto *UserRecipe = cast<VPSingleDefRecipe>(U);
8932 if (!UserRecipe->getParent()->getEnclosingLoopRegion()) {
8933 assert((UserRecipe->getParent() == MiddleVPBB ||
8934 UserRecipe->getParent() == Plan->getScalarPreheader()) &&
8935 "U must be either in the loop region, the middle block or the "
8936 "scalar preheader.");
8937 continue;
8938 }
8939 Worklist.insert(UserRecipe);
8940 }
8941 }
8942
8943 // Visit operation "Links" along the reduction chain top-down starting from
8944 // the phi until LoopExitValue. We keep track of the previous item
8945 // (PreviousLink) to tell which of the two operands of a Link will remain
8946 // scalar and which will be reduced. For minmax by select(cmp), Link will be
8947 // the select instructions. Blend recipes of in-loop reduction phi's will
8948 // get folded to their non-phi operand, as the reduction recipe handles the
8949 // condition directly.
8950 VPSingleDefRecipe *PreviousLink = PhiR; // Aka Worklist[0].
8951 for (VPSingleDefRecipe *CurrentLink : drop_begin(Worklist)) {
8952 if (auto *Blend = dyn_cast<VPBlendRecipe>(CurrentLink)) {
8953 assert(Blend->getNumIncomingValues() == 2 &&
8954 "Blend must have 2 incoming values");
8955 if (Blend->getIncomingValue(0) == PhiR) {
8956 Blend->replaceAllUsesWith(Blend->getIncomingValue(1));
8957 } else {
8958 assert(Blend->getIncomingValue(1) == PhiR &&
8959 "PhiR must be an operand of the blend");
8960 Blend->replaceAllUsesWith(Blend->getIncomingValue(0));
8961 }
8962 continue;
8963 }
8964
8965 Instruction *CurrentLinkI = CurrentLink->getUnderlyingInstr();
8966
8967 // Index of the first operand which holds a non-mask vector operand.
8968 unsigned IndexOfFirstOperand;
8969 // Recognize a call to the llvm.fmuladd intrinsic.
8970 bool IsFMulAdd = (Kind == RecurKind::FMulAdd);
8971 VPValue *VecOp;
8972 VPBasicBlock *LinkVPBB = CurrentLink->getParent();
8973 if (IsFMulAdd) {
8974 assert(
8976 "Expected instruction to be a call to the llvm.fmuladd intrinsic");
8977 assert(((MinVF.isScalar() && isa<VPReplicateRecipe>(CurrentLink)) ||
8978 isa<VPWidenIntrinsicRecipe>(CurrentLink)) &&
8979 CurrentLink->getOperand(2) == PreviousLink &&
8980 "expected a call where the previous link is the added operand");
8981
8982 // If the instruction is a call to the llvm.fmuladd intrinsic then we
8983 // need to create an fmul recipe (multiplying the first two operands of
8984 // the fmuladd together) to use as the vector operand for the fadd
8985 // reduction.
8986 VPInstruction *FMulRecipe = new VPInstruction(
8987 Instruction::FMul,
8988 {CurrentLink->getOperand(0), CurrentLink->getOperand(1)},
8989 CurrentLinkI->getFastMathFlags());
8990 LinkVPBB->insert(FMulRecipe, CurrentLink->getIterator());
8991 VecOp = FMulRecipe;
8992 } else if (PhiR->isInLoop() && Kind == RecurKind::AddChainWithSubs &&
8993 CurrentLinkI->getOpcode() == Instruction::Sub) {
8994 Type *PhiTy = PhiR->getUnderlyingValue()->getType();
8995 auto *Zero = Plan->getOrAddLiveIn(ConstantInt::get(PhiTy, 0));
8997 Instruction::Sub, {Zero, CurrentLink->getOperand(1)}, {},
8998 VPIRMetadata(), CurrentLinkI->getDebugLoc());
8999 Sub->setUnderlyingValue(CurrentLinkI);
9000 LinkVPBB->insert(Sub, CurrentLink->getIterator());
9001 VecOp = Sub;
9002 } else {
9004 if (isa<VPWidenRecipe>(CurrentLink)) {
9005 assert(isa<CmpInst>(CurrentLinkI) &&
9006 "need to have the compare of the select");
9007 continue;
9008 }
9009 assert(isa<VPWidenSelectRecipe>(CurrentLink) &&
9010 "must be a select recipe");
9011 IndexOfFirstOperand = 1;
9012 } else {
9013 assert((MinVF.isScalar() || isa<VPWidenRecipe>(CurrentLink)) &&
9014 "Expected to replace a VPWidenSC");
9015 IndexOfFirstOperand = 0;
9016 }
9017 // Note that for non-commutable operands (cmp-selects), the semantics of
9018 // the cmp-select are captured in the recurrence kind.
9019 unsigned VecOpId =
9020 CurrentLink->getOperand(IndexOfFirstOperand) == PreviousLink
9021 ? IndexOfFirstOperand + 1
9022 : IndexOfFirstOperand;
9023 VecOp = CurrentLink->getOperand(VecOpId);
9024 assert(VecOp != PreviousLink &&
9025 CurrentLink->getOperand(CurrentLink->getNumOperands() - 1 -
9026 (VecOpId - IndexOfFirstOperand)) ==
9027 PreviousLink &&
9028 "PreviousLink must be the operand other than VecOp");
9029 }
9030
9031 VPValue *CondOp = nullptr;
9032 if (CM.blockNeedsPredicationForAnyReason(CurrentLinkI->getParent()))
9033 CondOp = RecipeBuilder.getBlockInMask(CurrentLink->getParent());
9034
9035 // TODO: Retrieve FMFs from recipes directly.
9036 RecurrenceDescriptor RdxDesc = Legal->getRecurrenceDescriptor(
9037 cast<PHINode>(PhiR->getUnderlyingInstr()));
9038 // Non-FP RdxDescs will have all fast math flags set, so clear them.
9039 FastMathFlags FMFs = isa<FPMathOperator>(CurrentLinkI)
9040 ? RdxDesc.getFastMathFlags()
9041 : FastMathFlags();
9042 auto *RedRecipe = new VPReductionRecipe(
9043 Kind, FMFs, CurrentLinkI, PreviousLink, VecOp, CondOp,
9044 PhiR->isOrdered(), CurrentLinkI->getDebugLoc());
9045 // Append the recipe to the end of the VPBasicBlock because we need to
9046 // ensure that it comes after all of it's inputs, including CondOp.
9047 // Delete CurrentLink as it will be invalid if its operand is replaced
9048 // with a reduction defined at the bottom of the block in the next link.
9049 if (LinkVPBB->getNumSuccessors() == 0)
9050 RedRecipe->insertBefore(&*std::prev(std::prev(LinkVPBB->end())));
9051 else
9052 LinkVPBB->appendRecipe(RedRecipe);
9053
9054 CurrentLink->replaceAllUsesWith(RedRecipe);
9055 ToDelete.push_back(CurrentLink);
9056 PreviousLink = RedRecipe;
9057 }
9058 }
9059 VPBasicBlock *LatchVPBB = VectorLoopRegion->getExitingBasicBlock();
9060 Builder.setInsertPoint(&*std::prev(std::prev(LatchVPBB->end())));
9061 VPBasicBlock::iterator IP = MiddleVPBB->getFirstNonPhi();
9062 for (VPRecipeBase &R :
9064 VPReductionPHIRecipe *PhiR = dyn_cast<VPReductionPHIRecipe>(&R);
9065 if (!PhiR)
9066 continue;
9067
9068 const RecurrenceDescriptor &RdxDesc = Legal->getRecurrenceDescriptor(
9069 cast<PHINode>(PhiR->getUnderlyingInstr()));
9070 Type *PhiTy = PhiR->getUnderlyingValue()->getType();
9071 // If tail is folded by masking, introduce selects between the phi
9072 // and the users outside the vector region of each reduction, at the
9073 // beginning of the dedicated latch block.
9074 auto *OrigExitingVPV = PhiR->getBackedgeValue();
9075 auto *NewExitingVPV = PhiR->getBackedgeValue();
9076 // Don't output selects for partial reductions because they have an output
9077 // with fewer lanes than the VF. So the operands of the select would have
9078 // different numbers of lanes. Partial reductions mask the input instead.
9079 if (!PhiR->isInLoop() && CM.foldTailByMasking() &&
9080 !isa<VPPartialReductionRecipe>(OrigExitingVPV->getDefiningRecipe())) {
9081 VPValue *Cond = RecipeBuilder.getBlockInMask(PhiR->getParent());
9082 std::optional<FastMathFlags> FMFs =
9083 PhiTy->isFloatingPointTy()
9084 ? std::make_optional(RdxDesc.getFastMathFlags())
9085 : std::nullopt;
9086 NewExitingVPV =
9087 Builder.createSelect(Cond, OrigExitingVPV, PhiR, {}, "", FMFs);
9088 OrigExitingVPV->replaceUsesWithIf(NewExitingVPV, [](VPUser &U, unsigned) {
9089 return isa<VPInstruction>(&U) &&
9090 (cast<VPInstruction>(&U)->getOpcode() ==
9092 cast<VPInstruction>(&U)->getOpcode() ==
9094 cast<VPInstruction>(&U)->getOpcode() ==
9096 });
9097 if (CM.usePredicatedReductionSelect())
9098 PhiR->setOperand(1, NewExitingVPV);
9099 }
9100
9101 // We want code in the middle block to appear to execute on the location of
9102 // the scalar loop's latch terminator because: (a) it is all compiler
9103 // generated, (b) these instructions are always executed after evaluating
9104 // the latch conditional branch, and (c) other passes may add new
9105 // predecessors which terminate on this line. This is the easiest way to
9106 // ensure we don't accidentally cause an extra step back into the loop while
9107 // debugging.
9109
9110 // TODO: At the moment ComputeReductionResult also drives creation of the
9111 // bc.merge.rdx phi nodes, hence it needs to be created unconditionally here
9112 // even for in-loop reductions, until the reduction resume value handling is
9113 // also modeled in VPlan.
9114 VPInstruction *FinalReductionResult;
9116 Builder.setInsertPoint(MiddleVPBB, IP);
9117 RecurKind RecurrenceKind = PhiR->getRecurrenceKind();
9119 VPValue *Start = PhiR->getStartValue();
9121 FinalReductionResult =
9123 {PhiR, Start, Sentinel, NewExitingVPV}, ExitDL);
9124 } else if (RecurrenceDescriptor::isAnyOfRecurrenceKind(RecurrenceKind)) {
9125 VPValue *Start = PhiR->getStartValue();
9126 FinalReductionResult =
9128 {PhiR, Start, NewExitingVPV}, ExitDL);
9129 } else {
9132 ? VPIRFlags(RdxDesc.getFastMathFlags())
9133 : VPIRFlags();
9134 FinalReductionResult =
9136 {PhiR, NewExitingVPV}, Flags, ExitDL);
9137 }
9138 // If the vector reduction can be performed in a smaller type, we truncate
9139 // then extend the loop exit value to enable InstCombine to evaluate the
9140 // entire expression in the smaller type.
9141 if (MinVF.isVector() && PhiTy != RdxDesc.getRecurrenceType() &&
9143 assert(!PhiR->isInLoop() && "Unexpected truncated inloop reduction!");
9145 "Unexpected truncated min-max recurrence!");
9146 Type *RdxTy = RdxDesc.getRecurrenceType();
9147 auto *Trunc =
9148 new VPWidenCastRecipe(Instruction::Trunc, NewExitingVPV, RdxTy);
9149 Instruction::CastOps ExtendOpc =
9150 RdxDesc.isSigned() ? Instruction::SExt : Instruction::ZExt;
9151 auto *Extnd = new VPWidenCastRecipe(ExtendOpc, Trunc, PhiTy);
9152 Trunc->insertAfter(NewExitingVPV->getDefiningRecipe());
9153 Extnd->insertAfter(Trunc);
9154 if (PhiR->getOperand(1) == NewExitingVPV)
9155 PhiR->setOperand(1, Extnd->getVPSingleValue());
9156
9157 // Update ComputeReductionResult with the truncated exiting value and
9158 // extend its result.
9159 FinalReductionResult->setOperand(1, Trunc);
9160 FinalReductionResult =
9161 Builder.createScalarCast(ExtendOpc, FinalReductionResult, PhiTy, {});
9162 }
9163
9164 // Update all users outside the vector region. Also replace redundant
9165 // ExtractLastElement.
9166 for (auto *U : to_vector(OrigExitingVPV->users())) {
9167 auto *Parent = cast<VPRecipeBase>(U)->getParent();
9168 if (FinalReductionResult == U || Parent->getParent())
9169 continue;
9170 U->replaceUsesOfWith(OrigExitingVPV, FinalReductionResult);
9172 cast<VPInstruction>(U)->replaceAllUsesWith(FinalReductionResult);
9173 }
9174
9175 // Adjust AnyOf reductions; replace the reduction phi for the selected value
9176 // with a boolean reduction phi node to check if the condition is true in
9177 // any iteration. The final value is selected by the final
9178 // ComputeReductionResult.
9179 if (RecurrenceDescriptor::isAnyOfRecurrenceKind(RecurrenceKind)) {
9180 auto *Select = cast<VPRecipeBase>(*find_if(PhiR->users(), [](VPUser *U) {
9181 return isa<VPWidenSelectRecipe>(U) ||
9182 (isa<VPReplicateRecipe>(U) &&
9183 cast<VPReplicateRecipe>(U)->getUnderlyingInstr()->getOpcode() ==
9184 Instruction::Select);
9185 }));
9186 VPValue *Cmp = Select->getOperand(0);
9187 // If the compare is checking the reduction PHI node, adjust it to check
9188 // the start value.
9189 if (VPRecipeBase *CmpR = Cmp->getDefiningRecipe())
9190 CmpR->replaceUsesOfWith(PhiR, PhiR->getStartValue());
9191 Builder.setInsertPoint(Select);
9192
9193 // If the true value of the select is the reduction phi, the new value is
9194 // selected if the negated condition is true in any iteration.
9195 if (Select->getOperand(1) == PhiR)
9196 Cmp = Builder.createNot(Cmp);
9197 VPValue *Or = Builder.createOr(PhiR, Cmp);
9198 Select->getVPSingleValue()->replaceAllUsesWith(Or);
9199 // Delete Select now that it has invalid types.
9200 ToDelete.push_back(Select);
9201
9202 // Convert the reduction phi to operate on bools.
9204 OrigLoop->getHeader()->getContext())));
9205 continue;
9206 }
9207
9209 RdxDesc.getRecurrenceKind())) {
9210 // Adjust the start value for FindFirstIV/FindLastIV recurrences to use
9211 // the sentinel value after generating the ResumePhi recipe, which uses
9212 // the original start value.
9213 PhiR->setOperand(0, Plan->getOrAddLiveIn(RdxDesc.getSentinelValue()));
9214 }
9215 RecurKind RK = RdxDesc.getRecurrenceKind();
9219 VPBuilder PHBuilder(Plan->getVectorPreheader());
9220 VPValue *Iden = Plan->getOrAddLiveIn(
9221 getRecurrenceIdentity(RK, PhiTy, RdxDesc.getFastMathFlags()));
9222 // If the PHI is used by a partial reduction, set the scale factor.
9223 unsigned ScaleFactor =
9224 RecipeBuilder.getScalingForReduction(RdxDesc.getLoopExitInstr())
9225 .value_or(1);
9226 Type *I32Ty = IntegerType::getInt32Ty(PhiTy->getContext());
9227 auto *ScaleFactorVPV =
9228 Plan->getOrAddLiveIn(ConstantInt::get(I32Ty, ScaleFactor));
9229 VPValue *StartV = PHBuilder.createNaryOp(
9231 {PhiR->getStartValue(), Iden, ScaleFactorVPV},
9232 PhiTy->isFloatingPointTy() ? RdxDesc.getFastMathFlags()
9233 : FastMathFlags());
9234 PhiR->setOperand(0, StartV);
9235 }
9236 }
9237 for (VPRecipeBase *R : ToDelete)
9238 R->eraseFromParent();
9239
9241}
9242
9243void LoopVectorizationPlanner::attachRuntimeChecks(
9244 VPlan &Plan, GeneratedRTChecks &RTChecks, bool HasBranchWeights) const {
9245 const auto &[SCEVCheckCond, SCEVCheckBlock] = RTChecks.getSCEVChecks();
9246 if (SCEVCheckBlock) {
9247 assert((!CM.OptForSize ||
9248 CM.Hints->getForce() == LoopVectorizeHints::FK_Enabled) &&
9249 "Cannot SCEV check stride or overflow when optimizing for size");
9250 VPlanTransforms::attachCheckBlock(Plan, SCEVCheckCond, SCEVCheckBlock,
9251 HasBranchWeights);
9252 }
9253 const auto &[MemCheckCond, MemCheckBlock] = RTChecks.getMemRuntimeChecks();
9254 if (MemCheckBlock) {
9255 // VPlan-native path does not do any analysis for runtime checks
9256 // currently.
9258 "Runtime checks are not supported for outer loops yet");
9259
9260 if (CM.OptForSize) {
9261 assert(
9262 CM.Hints->getForce() == LoopVectorizeHints::FK_Enabled &&
9263 "Cannot emit memory checks when optimizing for size, unless forced "
9264 "to vectorize.");
9265 ORE->emit([&]() {
9266 return OptimizationRemarkAnalysis(DEBUG_TYPE, "VectorizationCodeSize",
9269 << "Code-size may be reduced by not forcing "
9270 "vectorization, or by source-code modifications "
9271 "eliminating the need for runtime checks "
9272 "(e.g., adding 'restrict').";
9273 });
9274 }
9275 VPlanTransforms::attachCheckBlock(Plan, MemCheckCond, MemCheckBlock,
9276 HasBranchWeights);
9277 }
9278}
9279
9281 VPlan &Plan, ElementCount VF, unsigned UF,
9283 // vscale is not necessarily a power-of-2, which means we cannot guarantee
9284 // an overflow to zero when updating induction variables and so an
9285 // additional overflow check is required before entering the vector loop.
9286 bool IsIndvarOverflowCheckNeededForVF =
9289 CM.getTailFoldingStyle() !=
9291 const uint32_t *BranchWeigths =
9294 : nullptr;
9297 CM.requiresScalarEpilogue(VF.isVector()), CM.foldTailByMasking(),
9298 IsIndvarOverflowCheckNeededForVF, OrigLoop, BranchWeigths,
9300 *PSE.getSE());
9301}
9302
9304 assert(!State.Lane && "VPDerivedIVRecipe being replicated.");
9305
9306 // Fast-math-flags propagate from the original induction instruction.
9308 if (FPBinOp)
9309 State.Builder.setFastMathFlags(FPBinOp->getFastMathFlags());
9310
9311 Value *Step = State.get(getStepValue(), VPLane(0));
9312 Value *Index = State.get(getOperand(1), VPLane(0));
9313 Value *DerivedIV = emitTransformedIndex(
9314 State.Builder, Index, getStartValue()->getLiveInIRValue(), Step, Kind,
9315 cast_if_present<BinaryOperator>(FPBinOp));
9316 DerivedIV->setName(Name);
9317 State.set(this, DerivedIV, VPLane(0));
9318}
9319
9320// Determine how to lower the scalar epilogue, which depends on 1) optimising
9321// for minimum code-size, 2) predicate compiler options, 3) loop hints forcing
9322// predication, and 4) a TTI hook that analyses whether the loop is suitable
9323// for predication.
9328 // 1) OptSize takes precedence over all other options, i.e. if this is set,
9329 // don't look at hints or options, and don't request a scalar epilogue.
9330 // (For PGSO, as shouldOptimizeForSize isn't currently accessible from
9331 // LoopAccessInfo (due to code dependency and not being able to reliably get
9332 // PSI/BFI from a loop analysis under NPM), we cannot suppress the collection
9333 // of strides in LoopAccessInfo::analyzeLoop() and vectorize without
9334 // versioning when the vectorization is forced, unlike hasOptSize. So revert
9335 // back to the old way and vectorize with versioning when forced. See D81345.)
9336 if (F->hasOptSize() || (llvm::shouldOptimizeForSize(L->getHeader(), PSI, BFI,
9340
9341 // 2) If set, obey the directives
9342 if (PreferPredicateOverEpilogue.getNumOccurrences()) {
9350 };
9351 }
9352
9353 // 3) If set, obey the hints
9354 switch (Hints.getPredicate()) {
9359 };
9360
9361 // 4) if the TTI hook indicates this is profitable, request predication.
9362 TailFoldingInfo TFI(TLI, &LVL, IAI);
9365
9367}
9368
9369// Process the loop in the VPlan-native vectorization path. This path builds
9370// VPlan upfront in the vectorization pipeline, which allows to apply
9371// VPlan-to-VPlan transformations from the very beginning without modifying the
9372// input LLVM IR.
9379 LoopVectorizationRequirements &Requirements) {
9380
9381 if (isa<SCEVCouldNotCompute>(PSE.getBackedgeTakenCount())) {
9382 LLVM_DEBUG(dbgs() << "LV: cannot compute the outer-loop trip count\n");
9383 return false;
9384 }
9385 assert(EnableVPlanNativePath && "VPlan-native path is disabled.");
9386 Function *F = L->getHeader()->getParent();
9387 InterleavedAccessInfo IAI(PSE, L, DT, LI, LVL->getLAI());
9388
9390 getScalarEpilogueLowering(F, L, Hints, PSI, BFI, TTI, TLI, *LVL, &IAI);
9391
9392 LoopVectorizationCostModel CM(SEL, L, PSE, LI, LVL, *TTI, TLI, DB, AC, ORE, F,
9393 &Hints, IAI, PSI, BFI);
9394 // Use the planner for outer loop vectorization.
9395 // TODO: CM is not used at this point inside the planner. Turn CM into an
9396 // optional argument if we don't need it in the future.
9397 LoopVectorizationPlanner LVP(L, LI, DT, TLI, *TTI, LVL, CM, IAI, PSE, Hints,
9398 ORE);
9399
9400 // Get user vectorization factor.
9401 ElementCount UserVF = Hints.getWidth();
9402
9404
9405 // Plan how to best vectorize, return the best VF and its cost.
9406 const VectorizationFactor VF = LVP.planInVPlanNativePath(UserVF);
9407
9408 // If we are stress testing VPlan builds, do not attempt to generate vector
9409 // code. Masked vector code generation support will follow soon.
9410 // Also, do not attempt to vectorize if no vector code will be produced.
9412 return false;
9413
9414 VPlan &BestPlan = LVP.getPlanFor(VF.Width);
9415
9416 {
9417 GeneratedRTChecks Checks(PSE, DT, LI, TTI, F->getDataLayout(), CM.CostKind);
9418 InnerLoopVectorizer LB(L, PSE, LI, DT, TTI, AC, VF.Width, /*UF=*/1, &CM,
9419 BFI, PSI, Checks, BestPlan);
9420 LLVM_DEBUG(dbgs() << "Vectorizing outer loop in \""
9421 << L->getHeader()->getParent()->getName() << "\"\n");
9422 LVP.addMinimumIterationCheck(BestPlan, VF.Width, /*UF=*/1,
9423 VF.MinProfitableTripCount);
9424
9425 LVP.executePlan(VF.Width, /*UF=*/1, BestPlan, LB, DT, false);
9426 }
9427
9428 reportVectorization(ORE, L, VF, 1);
9429
9430 // Mark the loop as already vectorized to avoid vectorizing again.
9431 Hints.setAlreadyVectorized();
9432 assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()));
9433 return true;
9434}
9435
9436// Emit a remark if there are stores to floats that required a floating point
9437// extension. If the vectorized loop was generated with floating point there
9438// will be a performance penalty from the conversion overhead and the change in
9439// the vector width.
9442 for (BasicBlock *BB : L->getBlocks()) {
9443 for (Instruction &Inst : *BB) {
9444 if (auto *S = dyn_cast<StoreInst>(&Inst)) {
9445 if (S->getValueOperand()->getType()->isFloatTy())
9446 Worklist.push_back(S);
9447 }
9448 }
9449 }
9450
9451 // Traverse the floating point stores upwards searching, for floating point
9452 // conversions.
9455 while (!Worklist.empty()) {
9456 auto *I = Worklist.pop_back_val();
9457 if (!L->contains(I))
9458 continue;
9459 if (!Visited.insert(I).second)
9460 continue;
9461
9462 // Emit a remark if the floating point store required a floating
9463 // point conversion.
9464 // TODO: More work could be done to identify the root cause such as a
9465 // constant or a function return type and point the user to it.
9466 if (isa<FPExtInst>(I) && EmittedRemark.insert(I).second)
9467 ORE->emit([&]() {
9468 return OptimizationRemarkAnalysis(LV_NAME, "VectorMixedPrecision",
9469 I->getDebugLoc(), L->getHeader())
9470 << "floating point conversion changes vector width. "
9471 << "Mixed floating point precision requires an up/down "
9472 << "cast that will negatively impact performance.";
9473 });
9474
9475 for (Use &Op : I->operands())
9476 if (auto *OpI = dyn_cast<Instruction>(Op))
9477 Worklist.push_back(OpI);
9478 }
9479}
9480
9481/// For loops with uncountable early exits, find the cost of doing work when
9482/// exiting the loop early, such as calculating the final exit values of
9483/// variables used outside the loop.
9484/// TODO: This is currently overly pessimistic because the loop may not take
9485/// the early exit, but better to keep this conservative for now. In future,
9486/// it might be possible to relax this by using branch probabilities.
9490 for (auto *ExitVPBB : Plan.getExitBlocks()) {
9491 for (auto *PredVPBB : ExitVPBB->getPredecessors()) {
9492 // If the predecessor is not the middle.block, then it must be the
9493 // vector.early.exit block, which may contain work to calculate the exit
9494 // values of variables used outside the loop.
9495 if (PredVPBB != Plan.getMiddleBlock()) {
9496 LLVM_DEBUG(dbgs() << "Calculating cost of work in exit block "
9497 << PredVPBB->getName() << ":\n");
9498 Cost += PredVPBB->cost(VF, CostCtx);
9499 }
9500 }
9501 }
9502 return Cost;
9503}
9504
9505/// This function determines whether or not it's still profitable to vectorize
9506/// the loop given the extra work we have to do outside of the loop:
9507/// 1. Perform the runtime checks before entering the loop to ensure it's safe
9508/// to vectorize.
9509/// 2. In the case of loops with uncountable early exits, we may have to do
9510/// extra work when exiting the loop early, such as calculating the final
9511/// exit values of variables used outside the loop.
9512static bool isOutsideLoopWorkProfitable(GeneratedRTChecks &Checks,
9515 VPCostContext &CostCtx, VPlan &Plan,
9517 std::optional<unsigned> VScale) {
9518 InstructionCost TotalCost = Checks.getCost();
9519 if (!TotalCost.isValid())
9520 return false;
9521
9522 // Add on the cost of any work required in the vector early exit block, if
9523 // one exists.
9524 TotalCost += calculateEarlyExitCost(CostCtx, Plan, VF.Width);
9525
9526 // When interleaving only scalar and vector cost will be equal, which in turn
9527 // would lead to a divide by 0. Fall back to hard threshold.
9528 if (VF.Width.isScalar()) {
9529 // TODO: Should we rename VectorizeMemoryCheckThreshold?
9530 if (TotalCost > VectorizeMemoryCheckThreshold) {
9531 LLVM_DEBUG(
9532 dbgs()
9533 << "LV: Interleaving only is not profitable due to runtime checks\n");
9534 return false;
9535 }
9536 return true;
9537 }
9538
9539 // The scalar cost should only be 0 when vectorizing with a user specified
9540 // VF/IC. In those cases, runtime checks should always be generated.
9541 uint64_t ScalarC = VF.ScalarCost.getValue();
9542 if (ScalarC == 0)
9543 return true;
9544
9545 // First, compute the minimum iteration count required so that the vector
9546 // loop outperforms the scalar loop.
9547 // The total cost of the scalar loop is
9548 // ScalarC * TC
9549 // where
9550 // * TC is the actual trip count of the loop.
9551 // * ScalarC is the cost of a single scalar iteration.
9552 //
9553 // The total cost of the vector loop is
9554 // RtC + VecC * (TC / VF) + EpiC
9555 // where
9556 // * RtC is the cost of the generated runtime checks plus the cost of
9557 // performing any additional work in the vector.early.exit block for loops
9558 // with uncountable early exits.
9559 // * VecC is the cost of a single vector iteration.
9560 // * TC is the actual trip count of the loop
9561 // * VF is the vectorization factor
9562 // * EpiCost is the cost of the generated epilogue, including the cost
9563 // of the remaining scalar operations.
9564 //
9565 // Vectorization is profitable once the total vector cost is less than the
9566 // total scalar cost:
9567 // RtC + VecC * (TC / VF) + EpiC < ScalarC * TC
9568 //
9569 // Now we can compute the minimum required trip count TC as
9570 // VF * (RtC + EpiC) / (ScalarC * VF - VecC) < TC
9571 //
9572 // For now we assume the epilogue cost EpiC = 0 for simplicity. Note that
9573 // the computations are performed on doubles, not integers and the result
9574 // is rounded up, hence we get an upper estimate of the TC.
9575 unsigned IntVF = estimateElementCount(VF.Width, VScale);
9576 uint64_t RtC = TotalCost.getValue();
9577 uint64_t Div = ScalarC * IntVF - VF.Cost.getValue();
9578 uint64_t MinTC1 = Div == 0 ? 0 : divideCeil(RtC * IntVF, Div);
9579
9580 // Second, compute a minimum iteration count so that the cost of the
9581 // runtime checks is only a fraction of the total scalar loop cost. This
9582 // adds a loop-dependent bound on the overhead incurred if the runtime
9583 // checks fail. In case the runtime checks fail, the cost is RtC + ScalarC
9584 // * TC. To bound the runtime check to be a fraction 1/X of the scalar
9585 // cost, compute
9586 // RtC < ScalarC * TC * (1 / X) ==> RtC * X / ScalarC < TC
9587 uint64_t MinTC2 = divideCeil(RtC * 10, ScalarC);
9588
9589 // Now pick the larger minimum. If it is not a multiple of VF and a scalar
9590 // epilogue is allowed, choose the next closest multiple of VF. This should
9591 // partly compensate for ignoring the epilogue cost.
9592 uint64_t MinTC = std::max(MinTC1, MinTC2);
9593 if (SEL == CM_ScalarEpilogueAllowed)
9594 MinTC = alignTo(MinTC, IntVF);
9595 VF.MinProfitableTripCount = ElementCount::getFixed(MinTC);
9596
9597 LLVM_DEBUG(
9598 dbgs() << "LV: Minimum required TC for runtime checks to be profitable:"
9599 << VF.MinProfitableTripCount << "\n");
9600
9601 // Skip vectorization if the expected trip count is less than the minimum
9602 // required trip count.
9603 if (auto ExpectedTC = getSmallBestKnownTC(PSE, L)) {
9604 if (ElementCount::isKnownLT(*ExpectedTC, VF.MinProfitableTripCount)) {
9605 LLVM_DEBUG(dbgs() << "LV: Vectorization is not beneficial: expected "
9606 "trip count < minimum profitable VF ("
9607 << *ExpectedTC << " < " << VF.MinProfitableTripCount
9608 << ")\n");
9609
9610 return false;
9611 }
9612 }
9613 return true;
9614}
9615
9617 : InterleaveOnlyWhenForced(Opts.InterleaveOnlyWhenForced ||
9619 VectorizeOnlyWhenForced(Opts.VectorizeOnlyWhenForced ||
9621
9622/// Prepare \p MainPlan for vectorizing the main vector loop during epilogue
9623/// vectorization. Remove ResumePhis from \p MainPlan for inductions that
9624/// don't have a corresponding wide induction in \p EpiPlan.
9625static void preparePlanForMainVectorLoop(VPlan &MainPlan, VPlan &EpiPlan) {
9626 // Collect PHI nodes of widened phis in the VPlan for the epilogue. Those
9627 // will need their resume-values computed in the main vector loop. Others
9628 // can be removed from the main VPlan.
9629 SmallPtrSet<PHINode *, 2> EpiWidenedPhis;
9630 for (VPRecipeBase &R :
9632 if (isa<VPCanonicalIVPHIRecipe>(&R))
9633 continue;
9634 EpiWidenedPhis.insert(
9635 cast<PHINode>(R.getVPSingleValue()->getUnderlyingValue()));
9636 }
9637 for (VPRecipeBase &R :
9638 make_early_inc_range(MainPlan.getScalarHeader()->phis())) {
9639 auto *VPIRInst = cast<VPIRPhi>(&R);
9640 if (EpiWidenedPhis.contains(&VPIRInst->getIRPhi()))
9641 continue;
9642 // There is no corresponding wide induction in the epilogue plan that would
9643 // need a resume value. Remove the VPIRInst wrapping the scalar header phi
9644 // together with the corresponding ResumePhi. The resume values for the
9645 // scalar loop will be created during execution of EpiPlan.
9646 VPRecipeBase *ResumePhi = VPIRInst->getOperand(0)->getDefiningRecipe();
9647 VPIRInst->eraseFromParent();
9648 ResumePhi->eraseFromParent();
9649 }
9651
9652 using namespace VPlanPatternMatch;
9653 // When vectorizing the epilogue, FindFirstIV & FindLastIV reductions can
9654 // introduce multiple uses of undef/poison. If the reduction start value may
9655 // be undef or poison it needs to be frozen and the frozen start has to be
9656 // used when computing the reduction result. We also need to use the frozen
9657 // value in the resume phi generated by the main vector loop, as this is also
9658 // used to compute the reduction result after the epilogue vector loop.
9659 auto AddFreezeForFindLastIVReductions = [](VPlan &Plan,
9660 bool UpdateResumePhis) {
9661 VPBuilder Builder(Plan.getEntry());
9662 for (VPRecipeBase &R : *Plan.getMiddleBlock()) {
9663 auto *VPI = dyn_cast<VPInstruction>(&R);
9664 if (!VPI || VPI->getOpcode() != VPInstruction::ComputeFindIVResult)
9665 continue;
9666 VPValue *OrigStart = VPI->getOperand(1);
9668 continue;
9669 VPInstruction *Freeze =
9670 Builder.createNaryOp(Instruction::Freeze, {OrigStart}, {}, "fr");
9671 VPI->setOperand(1, Freeze);
9672 if (UpdateResumePhis)
9673 OrigStart->replaceUsesWithIf(Freeze, [Freeze](VPUser &U, unsigned) {
9674 return Freeze != &U && isa<VPPhi>(&U);
9675 });
9676 }
9677 };
9678 AddFreezeForFindLastIVReductions(MainPlan, true);
9679 AddFreezeForFindLastIVReductions(EpiPlan, false);
9680
9681 VPBasicBlock *MainScalarPH = MainPlan.getScalarPreheader();
9682 VPValue *VectorTC = &MainPlan.getVectorTripCount();
9683 // If there is a suitable resume value for the canonical induction in the
9684 // scalar (which will become vector) epilogue loop, use it and move it to the
9685 // beginning of the scalar preheader. Otherwise create it below.
9686 auto ResumePhiIter =
9687 find_if(MainScalarPH->phis(), [VectorTC](VPRecipeBase &R) {
9688 return match(&R, m_VPInstruction<Instruction::PHI>(m_Specific(VectorTC),
9689 m_SpecificInt(0)));
9690 });
9691 VPPhi *ResumePhi = nullptr;
9692 if (ResumePhiIter == MainScalarPH->phis().end()) {
9693 VPBuilder ScalarPHBuilder(MainScalarPH, MainScalarPH->begin());
9694 ResumePhi = ScalarPHBuilder.createScalarPhi(
9695 {VectorTC, MainPlan.getCanonicalIV()->getStartValue()}, {},
9696 "vec.epilog.resume.val");
9697 } else {
9698 ResumePhi = cast<VPPhi>(&*ResumePhiIter);
9699 if (MainScalarPH->begin() == MainScalarPH->end())
9700 ResumePhi->moveBefore(*MainScalarPH, MainScalarPH->end());
9701 else if (&*MainScalarPH->begin() != ResumePhi)
9702 ResumePhi->moveBefore(*MainScalarPH, MainScalarPH->begin());
9703 }
9704 // Add a user to to make sure the resume phi won't get removed.
9705 VPBuilder(MainScalarPH)
9707}
9708
9709/// Prepare \p Plan for vectorizing the epilogue loop. That is, re-use expanded
9710/// SCEVs from \p ExpandedSCEVs and set resume values for header recipes.
9711static void
9713 const SCEV2ValueTy &ExpandedSCEVs,
9715 VPRegionBlock *VectorLoop = Plan.getVectorLoopRegion();
9716 VPBasicBlock *Header = VectorLoop->getEntryBasicBlock();
9717 Header->setName("vec.epilog.vector.body");
9718
9720 // Ensure that the start values for all header phi recipes are updated before
9721 // vectorizing the epilogue loop.
9722 for (VPRecipeBase &R : Header->phis()) {
9723 if (auto *IV = dyn_cast<VPCanonicalIVPHIRecipe>(&R)) {
9724 // When vectorizing the epilogue loop, the canonical induction start
9725 // value needs to be changed from zero to the value after the main
9726 // vector loop. Find the resume value created during execution of the main
9727 // VPlan. It must be the first phi in the loop preheader.
9728 // FIXME: Improve modeling for canonical IV start values in the epilogue
9729 // loop.
9730 using namespace llvm::PatternMatch;
9731 PHINode *EPResumeVal = &*L->getLoopPreheader()->phis().begin();
9732 for (Value *Inc : EPResumeVal->incoming_values()) {
9733 if (match(Inc, m_SpecificInt(0)))
9734 continue;
9735 assert(!EPI.VectorTripCount &&
9736 "Must only have a single non-zero incoming value");
9737 EPI.VectorTripCount = Inc;
9738 }
9739 // If we didn't find a non-zero vector trip count, all incoming values
9740 // must be zero, which also means the vector trip count is zero. Pick the
9741 // first zero as vector trip count.
9742 // TODO: We should not choose VF * UF so the main vector loop is known to
9743 // be dead.
9744 if (!EPI.VectorTripCount) {
9745 assert(
9746 EPResumeVal->getNumIncomingValues() > 0 &&
9747 all_of(EPResumeVal->incoming_values(),
9748 [](Value *Inc) { return match(Inc, m_SpecificInt(0)); }) &&
9749 "all incoming values must be 0");
9750 EPI.VectorTripCount = EPResumeVal->getOperand(0);
9751 }
9752 VPValue *VPV = Plan.getOrAddLiveIn(EPResumeVal);
9753 assert(all_of(IV->users(),
9754 [](const VPUser *U) {
9755 return isa<VPScalarIVStepsRecipe>(U) ||
9756 isa<VPDerivedIVRecipe>(U) ||
9757 cast<VPRecipeBase>(U)->isScalarCast() ||
9758 cast<VPInstruction>(U)->getOpcode() ==
9759 Instruction::Add;
9760 }) &&
9761 "the canonical IV should only be used by its increment or "
9762 "ScalarIVSteps when resetting the start value");
9763 IV->setOperand(0, VPV);
9764 continue;
9765 }
9766
9767 Value *ResumeV = nullptr;
9768 // TODO: Move setting of resume values to prepareToExecute.
9769 if (auto *ReductionPhi = dyn_cast<VPReductionPHIRecipe>(&R)) {
9770 auto *RdxResult =
9771 cast<VPInstruction>(*find_if(ReductionPhi->users(), [](VPUser *U) {
9772 auto *VPI = dyn_cast<VPInstruction>(U);
9773 return VPI &&
9774 (VPI->getOpcode() == VPInstruction::ComputeAnyOfResult ||
9775 VPI->getOpcode() == VPInstruction::ComputeReductionResult ||
9776 VPI->getOpcode() == VPInstruction::ComputeFindIVResult);
9777 }));
9778 ResumeV = cast<PHINode>(ReductionPhi->getUnderlyingInstr())
9779 ->getIncomingValueForBlock(L->getLoopPreheader());
9780 RecurKind RK = ReductionPhi->getRecurrenceKind();
9782 Value *StartV = RdxResult->getOperand(1)->getLiveInIRValue();
9783 // VPReductionPHIRecipes for AnyOf reductions expect a boolean as
9784 // start value; compare the final value from the main vector loop
9785 // to the start value.
9786 BasicBlock *PBB = cast<Instruction>(ResumeV)->getParent();
9787 IRBuilder<> Builder(PBB, PBB->getFirstNonPHIIt());
9788 ResumeV = Builder.CreateICmpNE(ResumeV, StartV);
9790 Value *StartV = getStartValueFromReductionResult(RdxResult);
9791 ToFrozen[StartV] = cast<PHINode>(ResumeV)->getIncomingValueForBlock(
9793
9794 // VPReductionPHIRecipe for FindFirstIV/FindLastIV reductions requires
9795 // an adjustment to the resume value. The resume value is adjusted to
9796 // the sentinel value when the final value from the main vector loop
9797 // equals the start value. This ensures correctness when the start value
9798 // might not be less than the minimum value of a monotonically
9799 // increasing induction variable.
9800 BasicBlock *ResumeBB = cast<Instruction>(ResumeV)->getParent();
9801 IRBuilder<> Builder(ResumeBB, ResumeBB->getFirstNonPHIIt());
9802 Value *Cmp = Builder.CreateICmpEQ(ResumeV, ToFrozen[StartV]);
9803 Value *Sentinel = RdxResult->getOperand(2)->getLiveInIRValue();
9804 ResumeV = Builder.CreateSelect(Cmp, Sentinel, ResumeV);
9805 } else {
9806 VPValue *StartVal = Plan.getOrAddLiveIn(ResumeV);
9807 auto *PhiR = dyn_cast<VPReductionPHIRecipe>(&R);
9808 if (auto *VPI = dyn_cast<VPInstruction>(PhiR->getStartValue())) {
9809 assert(VPI->getOpcode() == VPInstruction::ReductionStartVector &&
9810 "unexpected start value");
9811 VPI->setOperand(0, StartVal);
9812 continue;
9813 }
9814 }
9815 } else {
9816 // Retrieve the induction resume values for wide inductions from
9817 // their original phi nodes in the scalar loop.
9818 PHINode *IndPhi = cast<VPWidenInductionRecipe>(&R)->getPHINode();
9819 // Hook up to the PHINode generated by a ResumePhi recipe of main
9820 // loop VPlan, which feeds the scalar loop.
9821 ResumeV = IndPhi->getIncomingValueForBlock(L->getLoopPreheader());
9822 }
9823 assert(ResumeV && "Must have a resume value");
9824 VPValue *StartVal = Plan.getOrAddLiveIn(ResumeV);
9825 cast<VPHeaderPHIRecipe>(&R)->setStartValue(StartVal);
9826 }
9827
9828 // For some VPValues in the epilogue plan we must re-use the generated IR
9829 // values from the main plan. Replace them with live-in VPValues.
9830 // TODO: This is a workaround needed for epilogue vectorization and it
9831 // should be removed once induction resume value creation is done
9832 // directly in VPlan.
9833 for (auto &R : make_early_inc_range(*Plan.getEntry())) {
9834 // Re-use frozen values from the main plan for Freeze VPInstructions in the
9835 // epilogue plan. This ensures all users use the same frozen value.
9836 auto *VPI = dyn_cast<VPInstruction>(&R);
9837 if (VPI && VPI->getOpcode() == Instruction::Freeze) {
9838 VPI->replaceAllUsesWith(Plan.getOrAddLiveIn(
9839 ToFrozen.lookup(VPI->getOperand(0)->getLiveInIRValue())));
9840 continue;
9841 }
9842
9843 // Re-use the trip count and steps expanded for the main loop, as
9844 // skeleton creation needs it as a value that dominates both the scalar
9845 // and vector epilogue loops
9846 auto *ExpandR = dyn_cast<VPExpandSCEVRecipe>(&R);
9847 if (!ExpandR)
9848 continue;
9849 VPValue *ExpandedVal =
9850 Plan.getOrAddLiveIn(ExpandedSCEVs.lookup(ExpandR->getSCEV()));
9851 ExpandR->replaceAllUsesWith(ExpandedVal);
9852 if (Plan.getTripCount() == ExpandR)
9853 Plan.resetTripCount(ExpandedVal);
9854 ExpandR->eraseFromParent();
9855 }
9856}
9857
9858// Generate bypass values from the additional bypass block. Note that when the
9859// vectorized epilogue is skipped due to iteration count check, then the
9860// resume value for the induction variable comes from the trip count of the
9861// main vector loop, passed as the second argument.
9863 PHINode *OrigPhi, const InductionDescriptor &II, IRBuilder<> &BypassBuilder,
9864 const SCEV2ValueTy &ExpandedSCEVs, Value *MainVectorTripCount,
9865 Instruction *OldInduction) {
9866 Value *Step = getExpandedStep(II, ExpandedSCEVs);
9867 // For the primary induction the additional bypass end value is known.
9868 // Otherwise it is computed.
9869 Value *EndValueFromAdditionalBypass = MainVectorTripCount;
9870 if (OrigPhi != OldInduction) {
9871 auto *BinOp = II.getInductionBinOp();
9872 // Fast-math-flags propagate from the original induction instruction.
9873 if (isa_and_nonnull<FPMathOperator>(BinOp))
9874 BypassBuilder.setFastMathFlags(BinOp->getFastMathFlags());
9875
9876 // Compute the end value for the additional bypass.
9877 EndValueFromAdditionalBypass =
9878 emitTransformedIndex(BypassBuilder, MainVectorTripCount,
9879 II.getStartValue(), Step, II.getKind(), BinOp);
9880 EndValueFromAdditionalBypass->setName("ind.end");
9881 }
9882 return EndValueFromAdditionalBypass;
9883}
9884
9886 assert((EnableVPlanNativePath || L->isInnermost()) &&
9887 "VPlan-native path is not enabled. Only process inner loops.");
9888
9889 LLVM_DEBUG(dbgs() << "\nLV: Checking a loop in '"
9890 << L->getHeader()->getParent()->getName() << "' from "
9891 << L->getLocStr() << "\n");
9892
9893 LoopVectorizeHints Hints(L, InterleaveOnlyWhenForced, *ORE, TTI);
9894
9895 LLVM_DEBUG(
9896 dbgs() << "LV: Loop hints:"
9897 << " force="
9899 ? "disabled"
9901 ? "enabled"
9902 : "?"))
9903 << " width=" << Hints.getWidth()
9904 << " interleave=" << Hints.getInterleave() << "\n");
9905
9906 // Function containing loop
9907 Function *F = L->getHeader()->getParent();
9908
9909 // Looking at the diagnostic output is the only way to determine if a loop
9910 // was vectorized (other than looking at the IR or machine code), so it
9911 // is important to generate an optimization remark for each loop. Most of
9912 // these messages are generated as OptimizationRemarkAnalysis. Remarks
9913 // generated as OptimizationRemark and OptimizationRemarkMissed are
9914 // less verbose reporting vectorized loops and unvectorized loops that may
9915 // benefit from vectorization, respectively.
9916
9917 if (!Hints.allowVectorization(F, L, VectorizeOnlyWhenForced)) {
9918 LLVM_DEBUG(dbgs() << "LV: Loop hints prevent vectorization.\n");
9919 return false;
9920 }
9921
9922 PredicatedScalarEvolution PSE(*SE, *L);
9923
9924 // Check if it is legal to vectorize the loop.
9925 LoopVectorizationRequirements Requirements;
9926 LoopVectorizationLegality LVL(L, PSE, DT, TTI, TLI, F, *LAIs, LI, ORE,
9927 &Requirements, &Hints, DB, AC, BFI, PSI);
9929 LLVM_DEBUG(dbgs() << "LV: Not vectorizing: Cannot prove legality.\n");
9930 Hints.emitRemarkWithHints();
9931 return false;
9932 }
9933
9935 reportVectorizationFailure("Auto-vectorization of loops with uncountable "
9936 "early exit is not enabled",
9937 "UncountableEarlyExitLoopsDisabled", ORE, L);
9938 return false;
9939 }
9940
9941 // Entrance to the VPlan-native vectorization path. Outer loops are processed
9942 // here. They may require CFG and instruction level transformations before
9943 // even evaluating whether vectorization is profitable. Since we cannot modify
9944 // the incoming IR, we need to build VPlan upfront in the vectorization
9945 // pipeline.
9946 if (!L->isInnermost())
9947 return processLoopInVPlanNativePath(L, PSE, LI, DT, &LVL, TTI, TLI, DB, AC,
9948 ORE, BFI, PSI, Hints, Requirements);
9949
9950 assert(L->isInnermost() && "Inner loop expected.");
9951
9952 InterleavedAccessInfo IAI(PSE, L, DT, LI, LVL.getLAI());
9953 bool UseInterleaved = TTI->enableInterleavedAccessVectorization();
9954
9955 // If an override option has been passed in for interleaved accesses, use it.
9957 UseInterleaved = EnableInterleavedMemAccesses;
9958
9959 // Analyze interleaved memory accesses.
9960 if (UseInterleaved)
9962
9963 if (LVL.hasUncountableEarlyExit()) {
9964 BasicBlock *LoopLatch = L->getLoopLatch();
9965 if (IAI.requiresScalarEpilogue() ||
9967 [LoopLatch](BasicBlock *BB) { return BB != LoopLatch; })) {
9968 reportVectorizationFailure("Auto-vectorization of early exit loops "
9969 "requiring a scalar epilogue is unsupported",
9970 "UncountableEarlyExitUnsupported", ORE, L);
9971 return false;
9972 }
9973 }
9974
9975 // Check the function attributes and profiles to find out if this function
9976 // should be optimized for size.
9978 getScalarEpilogueLowering(F, L, Hints, PSI, BFI, TTI, TLI, LVL, &IAI);
9979
9980 // Check the loop for a trip count threshold: vectorize loops with a tiny trip
9981 // count by optimizing for size, to minimize overheads.
9982 auto ExpectedTC = getSmallBestKnownTC(PSE, L);
9983 if (ExpectedTC && ExpectedTC->isFixed() &&
9984 ExpectedTC->getFixedValue() < TinyTripCountVectorThreshold) {
9985 LLVM_DEBUG(dbgs() << "LV: Found a loop with a very small trip count. "
9986 << "This loop is worth vectorizing only if no scalar "
9987 << "iteration overheads are incurred.");
9989 LLVM_DEBUG(dbgs() << " But vectorizing was explicitly forced.\n");
9990 else {
9991 LLVM_DEBUG(dbgs() << "\n");
9992 // Predicate tail-folded loops are efficient even when the loop
9993 // iteration count is low. However, setting the epilogue policy to
9994 // `CM_ScalarEpilogueNotAllowedLowTripLoop` prevents vectorizing loops
9995 // with runtime checks. It's more effective to let
9996 // `isOutsideLoopWorkProfitable` determine if vectorization is
9997 // beneficial for the loop.
10000 }
10001 }
10002
10003 // Check the function attributes to see if implicit floats or vectors are
10004 // allowed.
10005 if (F->hasFnAttribute(Attribute::NoImplicitFloat)) {
10007 "Can't vectorize when the NoImplicitFloat attribute is used",
10008 "loop not vectorized due to NoImplicitFloat attribute",
10009 "NoImplicitFloat", ORE, L);
10010 Hints.emitRemarkWithHints();
10011 return false;
10012 }
10013
10014 // Check if the target supports potentially unsafe FP vectorization.
10015 // FIXME: Add a check for the type of safety issue (denormal, signaling)
10016 // for the target we're vectorizing for, to make sure none of the
10017 // additional fp-math flags can help.
10018 if (Hints.isPotentiallyUnsafe() &&
10021 "Potentially unsafe FP op prevents vectorization",
10022 "loop not vectorized due to unsafe FP support.",
10023 "UnsafeFP", ORE, L);
10024 Hints.emitRemarkWithHints();
10025 return false;
10026 }
10027
10028 bool AllowOrderedReductions;
10029 // If the flag is set, use that instead and override the TTI behaviour.
10031 AllowOrderedReductions = ForceOrderedReductions;
10032 else
10033 AllowOrderedReductions = TTI->enableOrderedReductions();
10034 if (!LVL.canVectorizeFPMath(AllowOrderedReductions)) {
10035 ORE->emit([&]() {
10036 auto *ExactFPMathInst = Requirements.getExactFPInst();
10037 return OptimizationRemarkAnalysisFPCommute(DEBUG_TYPE, "CantReorderFPOps",
10038 ExactFPMathInst->getDebugLoc(),
10039 ExactFPMathInst->getParent())
10040 << "loop not vectorized: cannot prove it is safe to reorder "
10041 "floating-point operations";
10042 });
10043 LLVM_DEBUG(dbgs() << "LV: loop not vectorized: cannot prove it is safe to "
10044 "reorder floating-point operations\n");
10045 Hints.emitRemarkWithHints();
10046 return false;
10047 }
10048
10049 // Use the cost model.
10050 LoopVectorizationCostModel CM(SEL, L, PSE, LI, &LVL, *TTI, TLI, DB, AC, ORE,
10051 F, &Hints, IAI, PSI, BFI);
10052 // Use the planner for vectorization.
10053 LoopVectorizationPlanner LVP(L, LI, DT, TLI, *TTI, &LVL, CM, IAI, PSE, Hints,
10054 ORE);
10055
10056 // Get user vectorization factor and interleave count.
10057 ElementCount UserVF = Hints.getWidth();
10058 unsigned UserIC = Hints.getInterleave();
10059
10060 // Plan how to best vectorize.
10061 LVP.plan(UserVF, UserIC);
10063 unsigned IC = 1;
10064
10067
10068 GeneratedRTChecks Checks(PSE, DT, LI, TTI, F->getDataLayout(), CM.CostKind);
10069 if (LVP.hasPlanWithVF(VF.Width)) {
10070 // Select the interleave count.
10071 IC = LVP.selectInterleaveCount(LVP.getPlanFor(VF.Width), VF.Width, VF.Cost);
10072
10073 unsigned SelectedIC = std::max(IC, UserIC);
10074 // Optimistically generate runtime checks if they are needed. Drop them if
10075 // they turn out to not be profitable.
10076 if (VF.Width.isVector() || SelectedIC > 1) {
10077 Checks.create(L, *LVL.getLAI(), PSE.getPredicate(), VF.Width, SelectedIC);
10078
10079 // Bail out early if either the SCEV or memory runtime checks are known to
10080 // fail. In that case, the vector loop would never execute.
10081 using namespace llvm::PatternMatch;
10082 if (Checks.getSCEVChecks().first &&
10083 match(Checks.getSCEVChecks().first, m_One()))
10084 return false;
10085 if (Checks.getMemRuntimeChecks().first &&
10086 match(Checks.getMemRuntimeChecks().first, m_One()))
10087 return false;
10088 }
10089
10090 // Check if it is profitable to vectorize with runtime checks.
10091 bool ForceVectorization =
10093 VPCostContext CostCtx(CM.TTI, *CM.TLI, LVP.getPlanFor(VF.Width), CM,
10094 CM.CostKind);
10095 if (!ForceVectorization &&
10096 !isOutsideLoopWorkProfitable(Checks, VF, L, PSE, CostCtx,
10097 LVP.getPlanFor(VF.Width), SEL,
10098 CM.getVScaleForTuning())) {
10099 ORE->emit([&]() {
10101 DEBUG_TYPE, "CantReorderMemOps", L->getStartLoc(),
10102 L->getHeader())
10103 << "loop not vectorized: cannot prove it is safe to reorder "
10104 "memory operations";
10105 });
10106 LLVM_DEBUG(dbgs() << "LV: Too many memory checks needed.\n");
10107 Hints.emitRemarkWithHints();
10108 return false;
10109 }
10110 }
10111
10112 // Identify the diagnostic messages that should be produced.
10113 std::pair<StringRef, std::string> VecDiagMsg, IntDiagMsg;
10114 bool VectorizeLoop = true, InterleaveLoop = true;
10115 if (VF.Width.isScalar()) {
10116 LLVM_DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n");
10117 VecDiagMsg = {
10118 "VectorizationNotBeneficial",
10119 "the cost-model indicates that vectorization is not beneficial"};
10120 VectorizeLoop = false;
10121 }
10122
10123 if (!LVP.hasPlanWithVF(VF.Width) && UserIC > 1) {
10124 // Tell the user interleaving was avoided up-front, despite being explicitly
10125 // requested.
10126 LLVM_DEBUG(dbgs() << "LV: Ignoring UserIC, because vectorization and "
10127 "interleaving should be avoided up front\n");
10128 IntDiagMsg = {"InterleavingAvoided",
10129 "Ignoring UserIC, because interleaving was avoided up front"};
10130 InterleaveLoop = false;
10131 } else if (IC == 1 && UserIC <= 1) {
10132 // Tell the user interleaving is not beneficial.
10133 LLVM_DEBUG(dbgs() << "LV: Interleaving is not beneficial.\n");
10134 IntDiagMsg = {
10135 "InterleavingNotBeneficial",
10136 "the cost-model indicates that interleaving is not beneficial"};
10137 InterleaveLoop = false;
10138 if (UserIC == 1) {
10139 IntDiagMsg.first = "InterleavingNotBeneficialAndDisabled";
10140 IntDiagMsg.second +=
10141 " and is explicitly disabled or interleave count is set to 1";
10142 }
10143 } else if (IC > 1 && UserIC == 1) {
10144 // Tell the user interleaving is beneficial, but it explicitly disabled.
10145 LLVM_DEBUG(dbgs() << "LV: Interleaving is beneficial but is explicitly "
10146 "disabled.\n");
10147 IntDiagMsg = {"InterleavingBeneficialButDisabled",
10148 "the cost-model indicates that interleaving is beneficial "
10149 "but is explicitly disabled or interleave count is set to 1"};
10150 InterleaveLoop = false;
10151 }
10152
10153 // If there is a histogram in the loop, do not just interleave without
10154 // vectorizing. The order of operations will be incorrect without the
10155 // histogram intrinsics, which are only used for recipes with VF > 1.
10156 if (!VectorizeLoop && InterleaveLoop && LVL.hasHistograms()) {
10157 LLVM_DEBUG(dbgs() << "LV: Not interleaving without vectorization due "
10158 << "to histogram operations.\n");
10159 IntDiagMsg = {
10160 "HistogramPreventsScalarInterleaving",
10161 "Unable to interleave without vectorization due to constraints on "
10162 "the order of histogram operations"};
10163 InterleaveLoop = false;
10164 }
10165
10166 // Override IC if user provided an interleave count.
10167 IC = UserIC > 0 ? UserIC : IC;
10168
10169 // Emit diagnostic messages, if any.
10170 const char *VAPassName = Hints.vectorizeAnalysisPassName();
10171 if (!VectorizeLoop && !InterleaveLoop) {
10172 // Do not vectorize or interleaving the loop.
10173 ORE->emit([&]() {
10174 return OptimizationRemarkMissed(VAPassName, VecDiagMsg.first,
10175 L->getStartLoc(), L->getHeader())
10176 << VecDiagMsg.second;
10177 });
10178 ORE->emit([&]() {
10179 return OptimizationRemarkMissed(LV_NAME, IntDiagMsg.first,
10180 L->getStartLoc(), L->getHeader())
10181 << IntDiagMsg.second;
10182 });
10183 return false;
10184 }
10185
10186 if (!VectorizeLoop && InterleaveLoop) {
10187 LLVM_DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n');
10188 ORE->emit([&]() {
10189 return OptimizationRemarkAnalysis(VAPassName, VecDiagMsg.first,
10190 L->getStartLoc(), L->getHeader())
10191 << VecDiagMsg.second;
10192 });
10193 } else if (VectorizeLoop && !InterleaveLoop) {
10194 LLVM_DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width
10195 << ") in " << L->getLocStr() << '\n');
10196 ORE->emit([&]() {
10197 return OptimizationRemarkAnalysis(LV_NAME, IntDiagMsg.first,
10198 L->getStartLoc(), L->getHeader())
10199 << IntDiagMsg.second;
10200 });
10201 } else if (VectorizeLoop && InterleaveLoop) {
10202 LLVM_DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width
10203 << ") in " << L->getLocStr() << '\n');
10204 LLVM_DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n');
10205 }
10206
10207 bool DisableRuntimeUnroll = false;
10208 MDNode *OrigLoopID = L->getLoopID();
10209 // If we decided that it is *legal* to interleave or vectorize the loop, then
10210 // do it.
10211
10212 VPlan &BestPlan = LVP.getPlanFor(VF.Width);
10213 // Consider vectorizing the epilogue too if it's profitable.
10214 VectorizationFactor EpilogueVF =
10216 if (EpilogueVF.Width.isVector()) {
10217 std::unique_ptr<VPlan> BestMainPlan(BestPlan.duplicate());
10218
10219 // The first pass vectorizes the main loop and creates a scalar epilogue
10220 // to be vectorized by executing the plan (potentially with a different
10221 // factor) again shortly afterwards.
10222 VPlan &BestEpiPlan = LVP.getPlanFor(EpilogueVF.Width);
10223 BestEpiPlan.getMiddleBlock()->setName("vec.epilog.middle.block");
10224 preparePlanForMainVectorLoop(*BestMainPlan, BestEpiPlan);
10225 EpilogueLoopVectorizationInfo EPI(VF.Width, IC, EpilogueVF.Width, 1,
10226 BestEpiPlan);
10227 EpilogueVectorizerMainLoop MainILV(L, PSE, LI, DT, TTI, AC, EPI, &CM, BFI,
10228 PSI, Checks, *BestMainPlan);
10229 auto ExpandedSCEVs = LVP.executePlan(EPI.MainLoopVF, EPI.MainLoopUF,
10230 *BestMainPlan, MainILV, DT, false);
10231 ++LoopsVectorized;
10232
10233 // Second pass vectorizes the epilogue and adjusts the control flow
10234 // edges from the first pass.
10235 EpilogueVectorizerEpilogueLoop EpilogILV(L, PSE, LI, DT, TTI, AC, EPI, &CM,
10236 BFI, PSI, Checks, BestEpiPlan);
10237 EpilogILV.setTripCount(MainILV.getTripCount());
10238 preparePlanForEpilogueVectorLoop(BestEpiPlan, L, ExpandedSCEVs, EPI);
10239
10240 LVP.executePlan(EPI.EpilogueVF, EPI.EpilogueUF, BestEpiPlan, EpilogILV, DT,
10241 true);
10242
10243 // Fix induction resume values from the additional bypass block.
10244 BasicBlock *BypassBlock = EpilogILV.getAdditionalBypassBlock();
10245 IRBuilder<> BypassBuilder(BypassBlock, BypassBlock->getFirstInsertionPt());
10246 BasicBlock *PH = L->getLoopPreheader();
10247 for (const auto &[IVPhi, II] : LVL.getInductionVars()) {
10248 auto *Inc = cast<PHINode>(IVPhi->getIncomingValueForBlock(PH));
10250 IVPhi, II, BypassBuilder, ExpandedSCEVs, EPI.VectorTripCount,
10251 LVL.getPrimaryInduction());
10252 // TODO: Directly add as extra operand to the VPResumePHI recipe.
10253 Inc->setIncomingValueForBlock(BypassBlock, V);
10254 }
10255 ++LoopsEpilogueVectorized;
10256
10257 if (!Checks.hasChecks())
10258 DisableRuntimeUnroll = true;
10259 } else {
10260 InnerLoopVectorizer LB(L, PSE, LI, DT, TTI, AC, VF.Width, IC, &CM, BFI, PSI,
10261 Checks, BestPlan);
10262 // TODO: Move to general VPlan pipeline once epilogue loops are also
10263 // supported.
10266 IC, PSE);
10267 LVP.addMinimumIterationCheck(BestPlan, VF.Width, IC,
10269
10270 LVP.executePlan(VF.Width, IC, BestPlan, LB, DT, false);
10271 ++LoopsVectorized;
10272
10273 // Add metadata to disable runtime unrolling a scalar loop when there
10274 // are no runtime checks about strides and memory. A scalar loop that is
10275 // rarely used is not worth unrolling.
10276 if (!Checks.hasChecks() && !VF.Width.isScalar())
10277 DisableRuntimeUnroll = true;
10278 }
10279 if (VF.Width.isScalar()) {
10280 using namespace ore;
10281 assert(IC > 1);
10282 ORE->emit([&]() {
10283 return OptimizationRemark(LV_NAME, "Interleaved", L->getStartLoc(),
10284 L->getHeader())
10285 << "interleaved loop (interleaved count: "
10286 << NV("InterleaveCount", IC) << ")";
10287 });
10288 } else {
10289 // Report the vectorization decision.
10290 reportVectorization(ORE, L, VF, IC);
10291 }
10292
10295
10296 assert(DT->verify(DominatorTree::VerificationLevel::Fast) &&
10297 "DT not preserved correctly");
10298
10299 std::optional<MDNode *> RemainderLoopID =
10302 if (RemainderLoopID) {
10303 L->setLoopID(*RemainderLoopID);
10304 } else {
10305 if (DisableRuntimeUnroll)
10307
10308 // Mark the loop as already vectorized to avoid vectorizing again.
10309 Hints.setAlreadyVectorized();
10310 }
10311
10312 assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()));
10313 return true;
10314}
10315
10317
10318 // Don't attempt if
10319 // 1. the target claims to have no vector registers, and
10320 // 2. interleaving won't help ILP.
10321 //
10322 // The second condition is necessary because, even if the target has no
10323 // vector registers, loop vectorization may still enable scalar
10324 // interleaving.
10327 return LoopVectorizeResult(false, false);
10328
10329 bool Changed = false, CFGChanged = false;
10330
10331 // The vectorizer requires loops to be in simplified form.
10332 // Since simplification may add new inner loops, it has to run before the
10333 // legality and profitability checks. This means running the loop vectorizer
10334 // will simplify all loops, regardless of whether anything end up being
10335 // vectorized.
10336 for (const auto &L : *LI)
10337 Changed |= CFGChanged |=
10338 simplifyLoop(L, DT, LI, SE, AC, nullptr, false /* PreserveLCSSA */);
10339
10340 // Build up a worklist of inner-loops to vectorize. This is necessary as
10341 // the act of vectorizing or partially unrolling a loop creates new loops
10342 // and can invalidate iterators across the loops.
10343 SmallVector<Loop *, 8> Worklist;
10344
10345 for (Loop *L : *LI)
10346 collectSupportedLoops(*L, LI, ORE, Worklist);
10347
10348 LoopsAnalyzed += Worklist.size();
10349
10350 // Now walk the identified inner loops.
10351 while (!Worklist.empty()) {
10352 Loop *L = Worklist.pop_back_val();
10353
10354 // For the inner loops we actually process, form LCSSA to simplify the
10355 // transform.
10356 Changed |= formLCSSARecursively(*L, *DT, LI, SE);
10357
10358 Changed |= CFGChanged |= processLoop(L);
10359
10360 if (Changed) {
10361 LAIs->clear();
10362
10363#ifndef NDEBUG
10364 if (VerifySCEV)
10365 SE->verify();
10366#endif
10367 }
10368 }
10369
10370 // Process each loop nest in the function.
10371 return LoopVectorizeResult(Changed, CFGChanged);
10372}
10373
10376 LI = &AM.getResult<LoopAnalysis>(F);
10377 // There are no loops in the function. Return before computing other
10378 // expensive analyses.
10379 if (LI->empty())
10380 return PreservedAnalyses::all();
10389
10390 auto &MAMProxy = AM.getResult<ModuleAnalysisManagerFunctionProxy>(F);
10391 PSI = MAMProxy.getCachedResult<ProfileSummaryAnalysis>(*F.getParent());
10392 BFI = nullptr;
10393 if (PSI && PSI->hasProfileSummary())
10395 LoopVectorizeResult Result = runImpl(F);
10396 if (!Result.MadeAnyChange)
10397 return PreservedAnalyses::all();
10399
10400 if (isAssignmentTrackingEnabled(*F.getParent())) {
10401 for (auto &BB : F)
10403 }
10404
10405 PA.preserve<LoopAnalysis>();
10409
10410 if (Result.MadeCFGChange) {
10411 // Making CFG changes likely means a loop got vectorized. Indicate that
10412 // extra simplification passes should be run.
10413 // TODO: MadeCFGChanges is not a prefect proxy. Extra passes should only
10414 // be run if runtime checks have been added.
10417 } else {
10419 }
10420 return PA;
10421}
10422
10424 raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
10425 static_cast<PassInfoMixin<LoopVectorizePass> *>(this)->printPipeline(
10426 OS, MapClassName2PassName);
10427
10428 OS << '<';
10429 OS << (InterleaveOnlyWhenForced ? "" : "no-") << "interleave-forced-only;";
10430 OS << (VectorizeOnlyWhenForced ? "" : "no-") << "vectorize-forced-only;";
10431 OS << '>';
10432}
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...
This is the interface for LLVM's primary stateless and local alias analysis.
static bool IsEmptyBlock(MachineBasicBlock *MBB)
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
Analysis containing CSE Info
Definition: CSEInfo.cpp:27
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
Definition: CommandLine.h:687
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
return RetTy
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
This file defines DenseMapInfo traits for DenseMap.
This file defines the DenseMap class.
std::string Name
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
#define Check(C,...)
#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)
Legalize the Machine IR a function s Machine IR
Definition: Legalizer.cpp:80
This header provides classes for managing per-loop analyses.
static const char * VerboseDebug
loop Loop Strength Reduction
#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 void addScalarResumePhis(VPRecipeBuilder &Builder, VPlan &Plan, DenseMap< VPValue *, VPValue * > &IVEndValues)
Create resume phis in the scalar preheader for first-order recurrences, reductions and inductions,...
static void addRuntimeUnrollDisableMetaData(Loop *L)
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 VPInstruction * addResumePhiRecipeForInduction(VPWidenInductionRecipe *WideIV, VPBuilder &VectorPHBuilder, VPBuilder &ScalarPHBuilder, VPTypeAnalysis &TypeInfo, VPValue *VectorTC)
Create and return a ResumePhi for WideIV, unless it is truncated.
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 VPIRBasicBlock * replaceVPBBWithIRVPBB(VPBasicBlock *VPBB, BasicBlock *IRBB)
Replace VPBB with a VPIRBasicBlock wrapping IRBB.
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 Value * getStartValueFromReductionResult(VPInstruction *RdxResult)
const char LLVMLoopVectorizeFollowupAll[]
static cl::opt< bool > ForceTargetSupportsScalableVectors("force-target-supports-scalable-vectors", cl::init(false), cl::Hidden, cl::desc("Pretend that scalable vectors are supported, even if the target does " "not support them. This flag should only be used for testing."))
static bool useActiveLaneMaskForControlFlow(TailFoldingStyle Style)
static cl::opt< bool > EnableEarlyExitVectorization("enable-early-exit-vectorization", cl::init(true), cl::Hidden, cl::desc("Enable vectorization of early exit loops with uncountable exits."))
static 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 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 cl::opt< bool > EnableEpilogueVectorization("enable-epilogue-vectorization", cl::init(true), cl::Hidden, cl::desc("Enable vectorization of epilogue loops."))
static ScalarEpilogueLowering getScalarEpilogueLowering(Function *F, Loop *L, LoopVectorizeHints &Hints, ProfileSummaryInfo *PSI, BlockFrequencyInfo *BFI, TargetTransformInfo *TTI, TargetLibraryInfo *TLI, LoopVectorizationLegality &LVL, InterleavedAccessInfo *IAI)
static void preparePlanForEpilogueVectorLoop(VPlan &Plan, Loop *L, const SCEV2ValueTy &ExpandedSCEVs, EpilogueLoopVectorizationInfo &EPI)
Prepare Plan for vectorizing the epilogue loop.
const char VerboseDebug[]
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 VPWidenIntOrFpInductionRecipe * createWidenInductionRecipes(PHINode *Phi, Instruction *PhiOrTrunc, VPValue *Start, const InductionDescriptor &IndDesc, VPlan &Plan, ScalarEvolution &SE, Loop &OrigLoop)
Creates a VPWidenIntOrFpInductionRecpipe for Phi.
static cl::opt< bool > PreferInLoopReductions("prefer-inloop-reductions", cl::init(false), cl::Hidden, cl::desc("Prefer in-loop vector reductions, " "overriding the targets preference."))
const char LLVMLoopVectorizeFollowupVectorized[]
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.
const char LLVMLoopVectorizeFollowupEpilogue[]
static bool useActiveLaneMask(TailFoldingStyle Style)
static bool hasReplicatorRegion(VPlan &Plan)
static void fixReductionScalarResumeWhenVectorizingEpilog(VPPhi *EpiResumePhiR, VPTransformState &State, BasicBlock *BypassBlock)
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 void cse(BasicBlock *BB)
Perform cse of induction variable instructions.
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,...
#define DEBUG_TYPE
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 processLoopInVPlanNativePath(Loop *L, PredicatedScalarEvolution &PSE, LoopInfo *LI, DominatorTree *DT, LoopVectorizationLegality *LVL, TargetTransformInfo *TTI, TargetLibraryInfo *TLI, DemandedBits *DB, AssumptionCache *AC, OptimizationRemarkEmitter *ORE, BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI, LoopVectorizeHints &Hints, LoopVectorizationRequirements &Requirements)
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 addExitUsersForFirstOrderRecurrences(VPlan &Plan, VFRange &Range)
Handle users in the exit block for first order reductions in the original exit block.
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:55
#define I(x, y, z)
Definition: MD5.cpp:58
mir Rename Register Operands
This file implements a map that provides insertion order iteration.
This file contains the declarations for metadata subclasses.
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
static GCMetadataPrinterRegistry::Add< OcamlGCMetadataPrinter > Y("ocaml", "ocaml 3.10-compatible collector")
#define P(N)
if(PassOpts->AAPipeline)
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.
raw_pwrite_stream & OS
#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:167
#define LLVM_DEBUG(...)
Definition: Debug.h:119
#define DEBUG_WITH_TYPE(TYPE,...)
DEBUG_WITH_TYPE macro - This macro should be used by passes to emit debug information.
Definition: Debug.h:77
This pass exposes codegen information to IR-level passes.
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
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:234
uint64_t getZExtValue() const
Get zero extended value.
Definition: APInt.h:1540
unsigned getActiveBits() const
Compute the number of active bits in the value.
Definition: APInt.h:1512
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:255
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:412
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:147
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.
Definition: Attributes.cpp:468
LLVM Basic Block Representation.
Definition: BasicBlock.h:62
iterator begin()
Instruction iterator methods.
Definition: BasicBlock.h:459
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...
Definition: BasicBlock.cpp:393
LLVM_ABI InstListType::const_iterator getFirstNonPHIIt() const
Returns an iterator to the first instruction in this block that is not a PHINode instruction.
Definition: BasicBlock.cpp:337
LLVM_ABI const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
Definition: BasicBlock.cpp:437
LLVM_ABI const BasicBlock * getSingleSuccessor() const
Return the successor of this block if it has a single successor.
Definition: BasicBlock.cpp:467
const Function * getParent() const
Return the enclosing method, or null if none.
Definition: BasicBlock.h:213
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this basic block belongs to.
Definition: BasicBlock.cpp:252
LLVM_ABI LLVMContext & getContext() const
Get the context in which this basic block lives.
Definition: BasicBlock.cpp:131
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.
Definition: InstrTypes.h:1905
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
Definition: InstrTypes.h:1348
Value * getArgOperand(unsigned i) const
Definition: InstrTypes.h:1292
iterator_range< User::op_iterator > args()
Iteration adapter for range-for loops.
Definition: InstrTypes.h:1283
unsigned arg_size() const
Definition: InstrTypes.h:1290
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:984
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition: InstrTypes.h:678
@ ICMP_UGT
unsigned greater than
Definition: InstrTypes.h:701
@ ICMP_ULT
unsigned less than
Definition: InstrTypes.h:703
@ ICMP_EQ
equal
Definition: InstrTypes.h:699
@ ICMP_NE
not equal
Definition: InstrTypes.h:700
@ ICMP_ULE
unsigned less or equal
Definition: InstrTypes.h:704
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE,...
Definition: InstrTypes.h:791
An abstraction over a floating-point predicate, and a pack of an integer predicate with samesign info...
Definition: CmpPredicate.h:23
This is the shared class of boolean and integer constants.
Definition: Constants.h:87
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
Definition: Constants.cpp:868
static LLVM_ABI ConstantInt * getFalse(LLVMContext &Context)
Definition: Constants.cpp:875
This class represents an Operation in the Expression.
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:124
static DebugLoc getTemporary()
Definition: DebugLoc.h:161
static DebugLoc getUnknown()
Definition: DebugLoc.h:162
An analysis that produces DemandedBits for a function.
Definition: DemandedBits.h:104
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:203
iterator find(const_arg_type_t< KeyT > Val)
Definition: DenseMap.h:177
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition: DenseMap.h:245
bool empty() const
Definition: DenseMap.h:119
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Definition: DenseMap.h:173
iterator end()
Definition: DenseMap.h:87
const ValueT & at(const_arg_type_t< KeyT > Val) const
at - Return the entry for the specified key, or abort if no such entry exists.
Definition: DenseMap.h:221
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
Definition: DenseMap.h:168
void insert_range(Range &&R)
Inserts range of 'std::pair<KeyT, ValueT>' values into the map.
Definition: DenseMap.h:283
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition: DenseMap.h:230
Implements a dense probed hash-table based set.
Definition: DenseSet.h:263
Analysis pass which computes a DominatorTree.
Definition: Dominators.h:284
bool verify(VerificationLevel VL=VerificationLevel::Full) const
verify - checks if the tree is correct.
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:165
constexpr bool isVector() const
One or more elements.
Definition: TypeSize.h:327
static constexpr ElementCount getScalable(ScalarTy MinVal)
Definition: TypeSize.h:315
static constexpr ElementCount getFixed(ScalarTy MinVal)
Definition: TypeSize.h:312
static constexpr ElementCount get(ScalarTy MinVal, bool Scalable)
Definition: TypeSize.h:318
constexpr bool isScalar() const
Exactly one element.
Definition: TypeSize.h:323
BasicBlock * emitMinimumVectorEpilogueIterCountCheck(BasicBlock *Bypass, BasicBlock *Insert)
Emits an iteration count bypass check after the main vector loop has finished to see if there are any...
BasicBlock * createVectorizedLoopSkeleton() final
Implements the interface for creating a vectorized skeleton using the epilogue loop strategy (i....
EpilogueVectorizerEpilogueLoop(Loop *OrigLoop, PredicatedScalarEvolution &PSE, LoopInfo *LI, DominatorTree *DT, const TargetTransformInfo *TTI, AssumptionCache *AC, EpilogueLoopVectorizationInfo &EPI, LoopVectorizationCostModel *CM, BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI, GeneratedRTChecks &Checks, VPlan &Plan)
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...
Value * createIterationCountCheck(ElementCount VF, unsigned UF) const
EpilogueVectorizerMainLoop(Loop *OrigLoop, PredicatedScalarEvolution &PSE, LoopInfo *LI, DominatorTree *DT, const TargetTransformInfo *TTI, AssumptionCache *AC, EpilogueLoopVectorizationInfo &EPI, LoopVectorizationCostModel *CM, BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI, GeneratedRTChecks &Check, VPlan &Plan)
void printDebugTracesAtStart() override
Allow subclasses to override and print debug traces before/after vplan execution, when trace informat...
BasicBlock * emitIterationCountCheck(BasicBlock *Bypass, bool ForEpilogue)
Emits an iteration count bypass check once for the main loop (when ForEpilogue is false) and once for...
BasicBlock * createVectorizedLoopSkeleton() final
Implements the interface for creating a vectorized skeleton using the main loop strategy (i....
Convenience struct for specifying and reasoning about fast-math flags.
Definition: FMF.h:22
Class to represent function types.
Definition: DerivedTypes.h:105
param_iterator param_begin() const
Definition: DerivedTypes.h:130
param_iterator param_end() const
Definition: DerivedTypes.h:131
bool hasOptSize() const
Optimize this function for size (-Os) or minimum size (-Oz).
Definition: Function.h:706
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:762
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Definition: Function.cpp:727
Represents flags for the getelementptr instruction/expression.
static GEPNoWrapFlags inBounds()
static GEPNoWrapFlags none()
Common base class shared among various IRBuilders.
Definition: IRBuilder.h:114
ConstantInt * getTrue()
Get the constant value for i1 true.
Definition: IRBuilder.h:502
LLVM_ABI Value * CreateSelect(Value *C, Value *True, Value *False, const Twine &Name="", Instruction *MDFrom=nullptr)
Definition: IRBuilder.cpp:1005
void setFastMathFlags(FastMathFlags NewFMF)
Set the fast-math flags to be used with generated fp-math operators.
Definition: IRBuilder.h:345
Value * CreateICmpNE(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:2333
LLVM_ABI Value * CreateBinaryIntrinsic(Intrinsic::ID ID, Value *LHS, Value *RHS, FMFSource FMFSource={}, const Twine &Name="")
Create a call to intrinsic ID with 2 operands which is mangled on the first type.
Definition: IRBuilder.cpp:823
Value * CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:2329
Value * CreateSub(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:1420
ConstantInt * getFalse()
Get the constant value for i1 false.
Definition: IRBuilder.h:507
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Definition: IRBuilder.h:207
Value * CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:2439
LLVM_ABI Value * CreateElementCount(Type *Ty, ElementCount EC)
Create an expression which evaluates to the number of elements in EC at runtime.
Definition: IRBuilder.cpp:123
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:2780
A struct for saving information about induction variables.
const SCEV * getStep() const
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.
const SmallVectorImpl< Instruction * > & getCastInsts() const
Returns a reference to the type cast instructions in the induction update chain, that are redundant w...
Value * getStartValue() const
An extension of the inner loop vectorizer that creates a skeleton for a vectorized loop that has its ...
InnerLoopAndEpilogueVectorizer(Loop *OrigLoop, PredicatedScalarEvolution &PSE, LoopInfo *LI, DominatorTree *DT, const TargetTransformInfo *TTI, AssumptionCache *AC, EpilogueLoopVectorizationInfo &EPI, LoopVectorizationCostModel *CM, BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI, 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.
BasicBlock * AdditionalBypassBlock
The additional bypass block which conditionally skips over the epilogue loop after executing the main...
BlockFrequencyInfo * BFI
BFI and PSI are used to check for profile guided size optimizations.
Value * getTripCount() const
Returns the original loop trip count.
PredicatedScalarEvolution & PSE
A wrapper around ScalarEvolution used to add runtime SCEV checks.
LoopInfo * LI
Loop Info.
ProfileSummaryInfo * PSI
BasicBlock * getAdditionalBypassBlock() const
Return the additional bypass block which targets the scalar loop by skipping the epilogue loop after ...
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.
BasicBlock * LoopVectorPreHeader
The vector-loop preheader.
virtual void printDebugTracesAtEnd()
AssumptionCache * AC
Assumption Cache.
InnerLoopVectorizer(Loop *OrigLoop, PredicatedScalarEvolution &PSE, LoopInfo *LI, DominatorTree *DT, const TargetTransformInfo *TTI, AssumptionCache *AC, ElementCount VecWidth, unsigned UnrollFactor, LoopVectorizationCostModel *CM, BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI, GeneratedRTChecks &RTChecks, VPlan &Plan)
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...
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
Definition: Instruction.h:513
LLVM_ABI const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
Definition: Instruction.cpp:78
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
Definition: Instruction.h:317
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...
Definition: Instruction.h:171
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
Definition: Instruction.h:314
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
Definition: Instruction.h:312
Class to represent integer types.
Definition: DerivedTypes.h:42
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition: Type.cpp:319
LLVM_ABI APInt getMask() const
For example, this is 0xFF for an 8 bit integer, 0xFFFF for i16, etc.
Definition: Type.cpp:343
The group of interleaved loads/stores sharing the same stride and close to each other.
Definition: VectorUtils.h:524
uint32_t getFactor() const
Definition: VectorUtils.h:540
InstTy * getMember(uint32_t Index) const
Get the member with the given index Index.
Definition: VectorUtils.h:594
InstTy * getInsertPos() const
Definition: VectorUtils.h:610
uint32_t getNumMembers() const
Definition: VectorUtils.h:542
Drive the analysis of interleaved memory accesses in the loop.
Definition: VectorUtils.h:669
bool requiresScalarEpilogue() const
Returns true if an interleaved group that may access memory out-of-bounds requires a scalar epilogue ...
Definition: VectorUtils.h:725
LLVM_ABI void analyzeInterleaving(bool EnableMaskedInterleavedGroup)
Analyze the interleaved accesses and collect them in interleave groups.
A wrapper class for inspecting calls to intrinsic functions.
Definition: IntrinsicInst.h:49
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:68
An instruction for reading from memory.
Definition: Instructions.h:180
Type * getPointerOperandType() const
Definition: Instructions.h:262
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:570
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
BlockT * getLoopLatch() const
If there is a single latch block for this loop, return it.
bool isInnermost() const
Return true if the loop does not contain any (natural) loops.
BlockT * getUniqueLatchExitBlock() const
Return the unique exit block for the latch, or null if there are multiple different exit blocks or th...
void getExitingBlocks(SmallVectorImpl< BlockT * > &ExitingBlocks) const
Return all blocks inside the loop that have successors outside of the loop.
BlockT * getHeader() const
unsigned getLoopDepth() const
Return the nesting level of this loop.
iterator_range< block_iterator > blocks() const
BlockT * getLoopPredecessor() const
If the given loop's header has exactly one unique predecessor outside the loop, return it.
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
ArrayRef< BlockT * > getBlocks() const
Get a list of the basic blocks which make up this loop.
BlockT * getExitingBlock() const
If getExitingBlocks would return exactly one block, return that block.
LoopT * getParentLoop() const
Return the parent loop if it exists or nullptr for top level loops.
Store the result of a depth first search within basic blocks contained by a single loop.
Definition: LoopIterator.h:97
RPOIterator beginRPO() const
Reverse iterate over the cached postorder blocks.
Definition: LoopIterator.h:136
void perform(const LoopInfo *LI)
Traverse the loop blocks and store the DFS result.
Definition: LoopInfo.cpp:1276
RPOIterator endRPO() const
Definition: LoopIterator.h:140
Wrapper class to LoopBlocksDFS that provides a standard begin()/end() interface for the DFS reverse p...
Definition: LoopIterator.h:172
void perform(const LoopInfo *LI)
Traverse the loop blocks and store the DFS result.
Definition: LoopIterator.h:180
void removeBlock(BlockT *BB)
This method completely removes BB from all data structures, including all of the Loop objects it is n...
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
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 ...
LoopVectorizationCostModel(ScalarEpilogueLowering SEL, Loop *L, PredicatedScalarEvolution &PSE, LoopInfo *LI, LoopVectorizationLegality *Legal, const TargetTransformInfo &TTI, const TargetLibraryInfo *TLI, DemandedBits *DB, AssumptionCache *AC, OptimizationRemarkEmitter *ORE, const Function *F, const LoopVectorizeHints *Hints, InterleavedAccessInfo &IAI, ProfileSummaryInfo *PSI, BlockFrequencyInfo *BFI)
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 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.
void collectInLoopReductions()
Split reductions into those that happen in the loop, and those that happen outside.
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.
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)
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.
LoopInfo * LI
Loop Info analysis.
bool shouldCalculateRegPressureForVF(ElementCount VF)
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.
bool isScalarWithPredication(Instruction *I, ElementCount VF) const
Returns true if I is an instruction which requires predication and for which our chosen predication s...
InstructionCost getVectorCallCost(CallInst *CI, ElementCount VF) const
Estimate cost of a call instruction CI if it were vectorized with factor VF.
bool useOrderedReductions(const RecurrenceDescriptor &RdxDesc) const
Returns true if we should use strict in-order reductions for the given RdxDesc.
std::pair< InstructionCost, InstructionCost > getDivRemSpeculationCost(Instruction *I, ElementCount VF) const
Return the costs for our two available strategies for lowering a div/rem operation which requires spe...
bool isDivRemScalarWithPredication(InstructionCost ScalarCost, InstructionCost SafeDivisorCost) const
Given costs for both strategies, return true if the scalar predication lowering should be used for di...
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...
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:1602
VectorizationFactor planInVPlanNativePath(ElementCount UserVF)
Use the VPlan-native path to plan how to best vectorize, return the best VF and its cost.
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:1567
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.
void setAlreadyVectorized()
Mark the loop L as already vectorized by setting the width to 1.
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 isLoopInvariant(const Value *V, bool HasCoroSuspendInst=false) const
Return true if the specified value is loop invariant.
Definition: LoopInfo.cpp:61
DebugLoc getStartLoc() const
Return the debug location of the start of this loop.
Definition: LoopInfo.cpp:644
bool hasLoopInvariantOperands(const Instruction *I, bool HasCoroSuspendInst=false) const
Return true if all the operands of the specified instruction are loop invariant.
Definition: LoopInfo.cpp:76
MDNode * getLoopID() const
Return the llvm.loop loop id metadata node for this loop if it is present.
Definition: LoopInfo.cpp:514
Metadata node.
Definition: Metadata.h:1077
LLVM_ABI void replaceOperandWith(unsigned I, Metadata *New)
Replace a specific operand.
Definition: Metadata.cpp:1078
const MDOperand & getOperand(unsigned I) const
Definition: Metadata.h:1445
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition: Metadata.h:1565
unsigned getNumOperands() const
Return number of MDNode operands.
Definition: Metadata.h:1451
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
Definition: Metadata.cpp:607
This class implements a map that also provides access to all stored values in a deterministic order.
Definition: MapVector.h:36
iterator end()
Definition: MapVector.h:67
iterator find(const KeyT &Key)
Definition: MapVector.h:141
bool contains(const KeyT &Key) const
Definition: MapVector.h:137
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition: MapVector.h:115
Function * getFunction(StringRef Name) const
Look up the specified function in the module symbol table.
Definition: Module.cpp:229
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.
bool allowExtraAnalysis(StringRef PassName) const
Whether we allow for extra compile-time budget to perform more analysis to produce fewer false positi...
LLVM_ABI void emit(DiagnosticInfoOptimizationBase &OptDiag)
Output the remark via the diagnostic handler and to the optimization record file.
Diagnostic information for missed-optimization remarks.
Diagnostic information for applied optimization remarks.
An analysis over an "inner" IR unit that provides access to an analysis manager over a "outer" IR uni...
Definition: PassManager.h:716
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
op_range incoming_values()
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 * getSymbolicMaxBackedgeTakenCount()
Get the (predicated) symbolic max 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.
Analysis providing profile information.
bool hasProfileSummary() const
Returns true if profile summary is available.
The RecurrenceDescriptor is used to identify recurrences variables in a loop.
Definition: IVDescriptors.h:90
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.
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.
Helper to remove instructions inserted during SCEV expansion, unless they are marked as used.
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.
This class represents an assumption made using SCEV expressions which can be checked at run-time.
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 isOne() const
Return true if the expression is a constant one.
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 * 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,...
LLVM_ABI void verify() const
This class represents the LLVM 'select' instruction.
A vector that has set insertion semantics.
Definition: SetVector.h:59
size_type size() const
Determine the number of elements in the SetVector.
Definition: SetVector.h:104
void insert_range(Range &&R)
Definition: SetVector.h:193
size_type count(const key_type &key) const
Count the number of elements of a given key in the SetVector.
Definition: SetVector.h:279
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition: SetVector.h:168
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
Definition: SmallPtrSet.h:380
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
Definition: SmallPtrSet.h:470
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:401
bool contains(ConstPtrType Ptr) const
Definition: SmallPtrSet.h:476
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
Definition: SmallPtrSet.h:541
A SetVector that performs no allocations if smaller than a certain size.
Definition: SetVector.h:356
bool empty() const
Definition: SmallVector.h:82
size_t size() const
Definition: SmallVector.h:79
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:574
reference emplace_back(ArgTypes &&... Args)
Definition: SmallVector.h:938
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
Definition: SmallVector.h:684
void push_back(const T &Elt)
Definition: SmallVector.h:414
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1197
An instruction for storing to memory.
Definition: Instructions.h:296
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 bool isLegalMaskedScatter(Type *DataType, Align Alignment) const
Return true if the target supports masked scatter.
LLVM_ABI bool enableAggressiveInterleaving(bool LoopHasReductions) const
Don't restrict interleaved unrolling to small loops.
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 isLegalMaskedLoad(Type *DataType, Align Alignment, unsigned AddressSpace) const
Return true if the target supports masked load.
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 InstructionCost getCmpSelInstrCost(unsigned Opcode, Type *ValTy, Type *CondTy, CmpInst::Predicate VecPred, TTI::TargetCostKind CostKind=TTI::TCK_RecipThroughput, OperandValueInfo Op1Info={OK_AnyValue, OP_None}, OperandValueInfo Op2Info={OK_AnyValue, OP_None}, const Instruction *I=nullptr) const
LLVM_ABI bool hasBranchDivergence(const Function *F=nullptr) const
Return true if branch divergence exists.
LLVM_ABI void getUnrollingPreferences(Loop *L, ScalarEvolution &, UnrollingPreferences &UP, OptimizationRemarkEmitter *ORE) const
Get target-customized preferences for the generic loop unrolling transformation.
LLVM_ABI TypeSize getRegisterBitWidth(RegisterKind K) const
LLVM_ABI bool hasActiveVectorLength() const
LLVM_ABI bool isLegalMaskedGather(Type *DataType, Align Alignment) const
Return true if the target supports masked gather.
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 std::optional< unsigned > getMaxVScale() 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 bool enableOrderedReductions() const
Return true if we should be enabling ordered reductions for the target.
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
LLVM_ABI InstructionCost getIntrinsicInstrCost(const IntrinsicCostAttributes &ICA, TTI::TargetCostKind CostKind) const
LLVM_ABI InstructionCost getArithmeticReductionCost(unsigned Opcode, VectorType *Ty, std::optional< FastMathFlags > FMF, TTI::TargetCostKind CostKind=TTI::TCK_RecipThroughput) const
Calculate the cost of vector reduction intrinsics.
LLVM_ABI InstructionCost getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src, TTI::CastContextHint CCH, TTI::TargetCostKind CostKind=TTI::TCK_SizeAndLatency, const Instruction *I=nullptr) const
static LLVM_ABI PartialReductionExtendKind getPartialReductionExtendKind(Instruction *I)
Get the kind of extension that an instruction represents.
LLVM_ABI bool shouldMaximizeVectorBandwidth(TargetTransformInfo::RegisterKind K) const
LLVM_ABI TailFoldingStyle getPreferredTailFoldingStyle(bool IVUpdateMayOverflow=true) const
Query the target what the preferred style of tail folding is.
LLVM_ABI InstructionCost getExtendedReductionCost(unsigned Opcode, bool IsUnsigned, Type *ResTy, VectorType *Ty, std::optional< FastMathFlags > FMF, TTI::TargetCostKind CostKind=TTI::TCK_RecipThroughput) const
Calculate the cost of an extended reduction pattern, similar to getArithmeticReductionCost of a reduc...
static LLVM_ABI OperandValueInfo getOperandInfo(const Value *V)
Collect properties of V used in cost analysis, e.g. OP_PowerOf2.
LLVM_ABI InstructionCost getMulAccReductionCost(bool IsUnsigned, Type *ResTy, VectorType *Ty, TTI::TargetCostKind CostKind=TTI::TCK_RecipThroughput) const
Calculate the cost of an extended reduction pattern, similar to getArithmeticReductionCost of an Add ...
LLVM_ABI unsigned getRegisterClassForType(bool Vector, Type *Ty=nullptr) const
LLVM_ABI bool isElementTypeLegalForScalableVector(Type *Ty) const
LLVM_ABI ElementCount getMinimumVF(unsigned ElemWidth, bool IsScalable) const
LLVM_ABI bool enableMaskedInterleavedAccessVectorization() const
Enable matching of interleaved access groups that contain predicated accesses or gaps and therefore v...
LLVM_ABI InstructionCost getMinMaxReductionCost(Intrinsic::ID IID, VectorType *Ty, FastMathFlags FMF=FastMathFlags(), TTI::TargetCostKind CostKind=TTI::TCK_RecipThroughput) 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 getArithmeticInstrCost(unsigned Opcode, Type *Ty, TTI::TargetCostKind CostKind=TTI::TCK_RecipThroughput, TTI::OperandValueInfo Opd1Info={TTI::OK_AnyValue, TTI::OP_None}, TTI::OperandValueInfo Opd2Info={TTI::OK_AnyValue, TTI::OP_None}, ArrayRef< const Value * > Args={}, const Instruction *CxtI=nullptr, const TargetLibraryInfo *TLibInfo=nullptr) const
This is an approximation of reciprocal throughput of a math/logic op.
LLVM_ABI bool isVScaleKnownToBeAPowerOfTwo() const
LLVM_ABI InstructionCost getMaskedMemoryOpCost(unsigned Opcode, Type *Src, Align Alignment, unsigned AddressSpace, TTI::TargetCostKind CostKind=TTI::TCK_RecipThroughput) const
LLVM_ABI InstructionCost getAddressComputationCost(Type *PtrTy, ScalarEvolution *SE, const SCEV *Ptr, TTI::TargetCostKind CostKind) const
LLVM_ABI InstructionCost getPartialReductionCost(unsigned Opcode, Type *InputTypeA, Type *InputTypeB, Type *AccumType, ElementCount VF, PartialReductionExtendKind OpAExtend, PartialReductionExtendKind OpBExtend, std::optional< unsigned > BinOp, TTI::TargetCostKind CostKind) const
LLVM_ABI const char * getRegisterClassName(unsigned ClassID) const
LLVM_ABI bool preferEpilogueVectorization() const
Return true if the loop vectorizer should consider vectorizing an otherwise scalar epilogue loop.
LLVM_ABI bool preferInLoopReduction(RecurKind Kind, Type *Ty) const
LLVM_ABI InstructionCost getGatherScatterOpCost(unsigned Opcode, Type *DataTy, const Value *Ptr, bool VariableMask, Align Alignment, TTI::TargetCostKind CostKind=TTI::TCK_RecipThroughput, const Instruction *I=nullptr) const
LLVM_ABI unsigned getEpilogueVectorizationMinVF() const
LLVM_ABI bool preferPredicatedReductionSelect() const
LLVM_ABI bool isLegalMaskedStore(Type *DataType, Align Alignment, unsigned AddressSpace) const
Return true if the target supports masked store.
LLVM_ABI unsigned getNumberOfRegisters(unsigned ClassID) const
LLVM_ABI bool supportsScalableVectors() const
LLVM_ABI bool isFPVectorizationPotentiallyUnsafe() const
Indicate that it is potentially unsafe to automatically vectorize floating-point operations because t...
@ TCC_Free
Expected to fold away in lowering.
LLVM_ABI bool enableInterleavedAccessVectorization() const
Enable matching of interleaved access groups.
LLVM_ABI unsigned getMinTripCountTailFoldingThreshold() const
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 unsigned getMaxInterleaveFactor(ElementCount VF) const
LLVM_ABI bool enableScalableVectorization() const
LLVM_ABI InstructionCost getIndexedVectorInstrCostFromEnd(unsigned Opcode, Type *Val, TTI::TargetCostKind CostKind, unsigned Index) const
LLVM_ABI unsigned getNumberOfParts(Type *Tp) const
LLVM_ABI InstructionCost getOperandsScalarizationOverhead(ArrayRef< Type * > Tys, TTI::TargetCostKind CostKind) const
Estimate the overhead of scalarizing operands with the given types.
LLVM_ABI bool isTruncateFree(Type *Ty1, Type *Ty2) const
Return true if it's free to truncate a value of type Ty1 to type Ty2.
LLVM_ABI bool preferPredicateOverEpilogue(TailFoldingInfo *TFI) const
Query the target whether it would be prefered to create a predicated vector loop, which can avoid the...
@ 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 getCallInstrCost(Function *F, Type *RetTy, ArrayRef< Type * > Tys, TTI::TargetCostKind CostKind=TTI::TCK_SizeAndLatency) const
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.
LLVM_ABI bool preferFixedOverScalableIfEqualCost() const
This class represents a truncation of integer types.
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:87
TypeSwitch< T, ResultT > & Case(CallableT &&caseFn)
Add a case on the given type.
Definition: TypeSwitch.h:96
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
bool isVectorTy() const
True if this is an instance of VectorType.
Definition: Type.h:273
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
static LLVM_ABI Type * getVoidTy(LLVMContext &C)
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition: Type.h:128
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition: Type.h:184
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
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
LLVM_ABI unsigned getIntegerBitWidth() const
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition: Type.h:352
This function has undefined behavior.
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:21
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:3639
void appendRecipe(VPRecipeBase *Recipe)
Augment the existing recipes of a VPBasicBlock with an additional Recipe as the last recipe.
Definition: VPlan.h:3714
RecipeListTy::iterator iterator
Instruction iterators...
Definition: VPlan.h:3666
iterator end()
Definition: VPlan.h:3676
iterator begin()
Recipe iterator methods.
Definition: VPlan.h:3674
iterator_range< iterator > phis()
Returns an iterator range over the PHI-like recipes in the block.
Definition: VPlan.h:3727
iterator getFirstNonPhi()
Return the position of the first non-phi node recipe in the block.
Definition: VPlan.cpp:236
VPRegionBlock * getEnclosingLoopRegion()
Definition: VPlan.cpp:622
VPRecipeBase * getTerminator()
If the block has multiple successors, return the branch recipe terminating the block.
Definition: VPlan.cpp:667
void insert(VPRecipeBase *Recipe, iterator InsertPt)
Definition: VPlan.h:3705
bool empty() const
Definition: VPlan.h:3685
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:180
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:319
size_t getNumPredecessors() const
Definition: VPlan.h:220
VPlan * getPlan()
Definition: VPlan.cpp:155
VPBlockBase * getSinglePredecessor() const
Definition: VPlan.h:215
const VPBasicBlock * getEntryBasicBlock() const
Definition: VPlan.cpp:160
VPBlockBase * getSingleSuccessor() const
Definition: VPlan.h:209
const VPBlocksTy & getSuccessors() const
Definition: VPlan.h:198
static void insertOnEdge(VPBlockBase *From, VPBlockBase *To, VPBlockBase *BlockPtr)
Inserts BlockPtr on the edge between From and To.
Definition: VPlanUtils.h:237
static void connectBlocks(VPBlockBase *From, VPBlockBase *To, unsigned PredIdx=-1u, unsigned SuccIdx=-1u)
Connect VPBlockBases From and To bi-directionally.
Definition: VPlanUtils.h:175
static void reassociateBlocks(VPBlockBase *Old, VPBlockBase *New)
Reassociate all the blocks connected to Old so that they now point to New.
Definition: VPlanUtils.h:202
RAII object that stores the current insertion point and restores it when the object is destroyed.
VPlan-based builder utility analogous to IRBuilder.
VPDerivedIVRecipe * createDerivedIV(InductionDescriptor::InductionKind Kind, FPMathOperator *FPBinOp, VPValue *Start, VPValue *Current, VPValue *Step, const Twine &Name="")
Convert the input value Current to the corresponding value of an induction with Start and Step values...
VPPhi * createScalarPhi(ArrayRef< VPValue * > IncomingValues, DebugLoc DL, const Twine &Name="")
VPInstruction * createNaryOp(unsigned Opcode, ArrayRef< VPValue * > Operands, Instruction *Inst=nullptr, const Twine &Name="")
Create an N-ary operation with Opcode, Operands and set Inst as its underlying Instruction.
VPInstruction * createScalarCast(Instruction::CastOps Opcode, VPValue *Op, Type *ResultTy, DebugLoc DL)
unsigned getNumDefinedValues() const
Returns the number of values defined by the VPDef.
Definition: VPlanValue.h:421
VPValue * getVPSingleValue()
Returns the only VPValue defined by the VPDef.
Definition: VPlanValue.h:394
void execute(VPTransformState &State) override
Generate the transformed value of the induction at offset StartValue (1.
A pure virtual base class for all recipes modeling header phis, including phis for first order recurr...
Definition: VPlan.h:1951
virtual VPValue * getBackedgeValue()
Returns the incoming value from the loop backedge.
Definition: VPlan.h:1999
VPValue * getStartValue()
Returns the start value of the phi, if one is set.
Definition: VPlan.h:1988
A recipe representing a sequence of load -> update -> store as part of a histogram operation.
Definition: VPlan.h:1666
A special type of VPBasicBlock that wraps an existing IR basic block.
Definition: VPlan.h:3792
Class to record and manage LLVM IR flags.
Definition: VPlan.h:596
Helper to manage IR metadata for recipes.
Definition: VPlan.h:926
This is a concrete Recipe that models a single VPlan-level instruction.
Definition: VPlan.h:967
@ ComputeAnyOfResult
Compute the final result of a AnyOf reduction with select(cmp(),x,y), where one of (x,...
Definition: VPlan.h:996
@ ExtractPenultimateElement
Definition: VPlan.h:1006
@ ResumeForEpilogue
Explicit user for the resume phi of the canonical induction in the main VPlan, used by the epilogue v...
Definition: VPlan.h:1043
@ ReductionStartVector
Start vector for reductions with 3 operands: the original start value, the identity value for the red...
Definition: VPlan.h:1034
@ ComputeReductionResult
Definition: VPlan.h:998
unsigned getOpcode() const
Definition: VPlan.h:1104
VPInterleaveRecipe is a recipe for transforming an interleave group of load or stores into one wide l...
Definition: VPlan.h:2443
In what follows, the term "input IR" refers to code that is fed into the vectorizer whereas the term ...
Definition: VPlanHelpers.h:125
A recipe for forming partial reductions.
Definition: VPlan.h:2628
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:1275
VPRecipeBase is a base class modeling a sequence of one or more output IR instructions.
Definition: VPlan.h:391
VPBasicBlock * getParent()
Definition: VPlan.h:412
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.
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(Instruction *I, ArrayRef< VPValue * > Operands, VFRange &Range)
Build a VPReplicationRecipe for I using Operands.
VPRecipeBase * tryToCreatePartialReduction(Instruction *Reduction, ArrayRef< VPValue * > Operands, unsigned ScaleFactor)
Create and return a partial reduction recipe for a reduction instruction along with binary operation ...
A recipe for handling reduction phis.
Definition: VPlan.h:2302
bool isInLoop() const
Returns true, if the phi is part of an in-loop reduction.
Definition: VPlan.h:2362
RecurKind getRecurrenceKind() const
Returns the recurrence kind of the reduction.
Definition: VPlan.h:2356
A recipe to represent inloop reduction operations, performing a reduction on a vector operand into a ...
Definition: VPlan.h:2541
VPRegionBlock represents a collection of VPBasicBlocks and VPRegionBlocks which form a Single-Entry-S...
Definition: VPlan.h:3827
const VPBlockBase * getEntry() const
Definition: VPlan.h:3863
VPReplicateRecipe replicates a given instruction producing multiple scalar copies of the original sca...
Definition: VPlan.h:2731
VPSingleDef is a base class for recipes for modeling a sequence of one or more output IR that define ...
Definition: VPlan.h:518
Instruction * getUnderlyingInstr()
Returns the underlying instruction.
Definition: VPlan.h:582
An analysis for type-inference for VPValues.
Definition: VPlanAnalysis.h:43
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:197
void setOperand(unsigned I, VPValue *New)
Definition: VPlanValue.h:241
VPValue * getOperand(unsigned N) const
Definition: VPlanValue.h:236
void addOperand(VPValue *Operand)
Definition: VPlanValue.h:230
VPRecipeBase * getDefiningRecipe()
Returns the recipe defining this VPValue or nullptr if it is not defined by a recipe,...
Definition: VPlan.cpp:125
Value * getLiveInIRValue() const
Returns the underlying IR value, if this VPValue is defined outside the scope of VPlan.
Definition: VPlanValue.h:174
Value * getUnderlyingValue() const
Return the underlying Value attached to this VPValue.
Definition: VPlanValue.h:85
void replaceAllUsesWith(VPValue *New)
Definition: VPlan.cpp:1403
user_iterator user_begin()
Definition: VPlanValue.h:130
unsigned getNumUsers() const
Definition: VPlanValue.h:113
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:1407
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:1817
A recipe to compute the pointers for widened memory accesses of IndexTy.
Definition: VPlan.h:1876
A recipe for widening Call instructions using library calls.
Definition: VPlan.h:1613
VPWidenCastRecipe is a recipe to create vector cast instructions.
Definition: VPlan.h:1467
A recipe for handling GEP instructions.
Definition: VPlan.h:1753
Base class for widened induction (VPWidenIntOrFpInductionRecipe and VPWidenPointerInductionRecipe),...
Definition: VPlan.h:2013
VPValue * getStepValue()
Returns the step value of the induction.
Definition: VPlan.h:2041
const InductionDescriptor & getInductionDescriptor() const
Returns the induction descriptor for the recipe.
Definition: VPlan.h:2058
A recipe for handling phi nodes of integer and floating-point inductions, producing their vector valu...
Definition: VPlan.h:2088
A recipe for widening vector intrinsics.
Definition: VPlan.h:1524
A common base class for widening memory operations.
Definition: VPlan.h:3008
A recipe for widened phis.
Definition: VPlan.h:2224
VPWidenRecipe is a recipe for producing a widened instruction using the opcode and operands of the re...
Definition: VPlan.h:1424
VPlan models a candidate for vectorization, encoding various decisions take to produce efficient outp...
Definition: VPlan.h:3930
bool hasVF(ElementCount VF) const
Definition: VPlan.h:4139
VPBasicBlock * getEntry()
Definition: VPlan.h:4029
VPValue & getVectorTripCount()
The vector trip count.
Definition: VPlan.h:4119
void setName(const Twine &newName)
Definition: VPlan.h:4177
VPValue & getVFxUF()
Returns VF * UF of the vector loop region.
Definition: VPlan.h:4125
VPValue & getVF()
Returns the VF of the vector loop region.
Definition: VPlan.h:4122
VPValue * getTripCount() const
The trip count of the original loop.
Definition: VPlan.h:4091
iterator_range< SmallSetVector< ElementCount, 2 >::iterator > vectorFactors() const
Returns an iterator range over all VFs of the plan.
Definition: VPlan.h:4146
bool hasUF(unsigned UF) const
Definition: VPlan.h:4157
ArrayRef< VPIRBasicBlock * > getExitBlocks() const
Return an ArrayRef containing VPIRBasicBlocks wrapping the exit blocks of the original scalar loop.
Definition: VPlan.h:4081
LLVM_ABI_FOR_TEST VPRegionBlock * getVectorLoopRegion()
Returns the VPRegionBlock of the vector loop.
Definition: VPlan.cpp:1037
bool hasEarlyExit() const
Returns true if the VPlan is based on a loop with an early exit.
Definition: VPlan.h:4302
InstructionCost cost(ElementCount VF, VPCostContext &Ctx)
Return the cost of this plan.
Definition: VPlan.cpp:1019
void resetTripCount(VPValue *NewTripCount)
Resets the trip count for the VPlan.
Definition: VPlan.h:4105
VPBasicBlock * getMiddleBlock()
Returns the 'middle' block of the plan, that is the block that selects whether to execute the scalar ...
Definition: VPlan.h:4054
void setEntry(VPBasicBlock *VPBB)
Definition: VPlan.h:4018
LLVM_ABI_FOR_TEST VPIRBasicBlock * createVPIRBasicBlock(BasicBlock *IRBB)
Create a VPIRBasicBlock from IRBB containing VPIRInstructions for all instructions in IRBB,...
Definition: VPlan.cpp:1252
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:4181
bool hasScalarVFOnly() const
Definition: VPlan.h:4150
VPBasicBlock * getScalarPreheader() const
Return the VPBasicBlock for the preheader of the scalar loop.
Definition: VPlan.h:4072
void execute(VPTransformState *State)
Generate the IR code for this VPlan.
Definition: VPlan.cpp:955
VPCanonicalIVPHIRecipe * getCanonicalIV()
Returns the canonical induction recipe of the vector loop.
Definition: VPlan.h:4235
void addVF(ElementCount VF)
Definition: VPlan.h:4131
VPIRBasicBlock * getScalarHeader() const
Return the VPIRBasicBlock wrapping the header of the scalar loop.
Definition: VPlan.h:4077
VPValue * getLiveIn(Value *V) const
Return the live-in VPValue for V, if there is one or nullptr otherwise.
Definition: VPlan.h:4208
VPBasicBlock * getVectorPreheader()
Returns the preheader of the vector loop region, if one exists, or null otherwise.
Definition: VPlan.h:4034
VPlan * duplicate()
Clone the current VPlan, update all VPValues of the new VPlan and cloned recipes to refer to the clon...
Definition: VPlan.cpp:1179
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 LLVMContext & getContext() const
All values hold a context through their type.
Definition: Value.cpp:1098
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.
int getNumOccurrences() const
Definition: CommandLine.h:400
std::pair< iterator, bool > insert(const ValueT &V)
Definition: DenseSet.h:194
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
Definition: DenseSet.h:169
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:272
constexpr ScalarTy getFixedValue() const
Definition: TypeSize.h:203
static constexpr bool isKnownLE(const FixedOrScalableQuantity &LHS, const FixedOrScalableQuantity &RHS)
Definition: TypeSize.h:233
constexpr bool isNonZero() const
Definition: TypeSize.h:159
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:280
static constexpr bool isKnownLT(const FixedOrScalableQuantity &LHS, const FixedOrScalableQuantity &RHS)
Definition: TypeSize.h:219
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition: TypeSize.h:172
constexpr LeafTy multiplyCoefficientBy(ScalarTy RHS) const
Definition: TypeSize.h:259
constexpr bool isFixed() const
Returns true if the quantity is not scaled by vscale.
Definition: TypeSize.h:175
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition: TypeSize.h:169
constexpr bool isZero() const
Definition: TypeSize.h:157
static constexpr bool isKnownGT(const FixedOrScalableQuantity &LHS, const FixedOrScalableQuantity &RHS)
Definition: TypeSize.h:226
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:255
static constexpr bool isKnownGE(const FixedOrScalableQuantity &LHS, const FixedOrScalableQuantity &RHS)
Definition: TypeSize.h:240
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:134
A range adaptor for a pair of iterators.
IteratorT begin() 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.
Definition: raw_ostream.h:662
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 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.
Definition: BitmaskEnum.h:126
@ Entry
Definition: COFF.h:862
@ 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
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:190
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.
Definition: PatternMatch.h:100
OneOps_match< OpTy, Instruction::Freeze > m_Freeze(const OpTy &Op)
Matches FreezeInst.
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)
Definition: PatternMatch.h:49
bind_ty< Instruction > m_Instruction(Instruction *&I)
Match an instruction, capturing it if we match.
Definition: PatternMatch.h:862
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
Definition: PatternMatch.h:962
cst_pred_ty< is_one > m_One()
Match an integer 1 or a vector with all elements equal to 1.
Definition: PatternMatch.h:592
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.
Definition: PatternMatch.h:105
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
Definition: PatternMatch.h:92
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.
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)
SCEVBinaryExpr_match< SCEVMulExpr, Op0_t, Op1_t > m_scev_Mul(const Op0_t &Op0, const Op1_t &Op1)
bool match(const SCEV *S, const Pattern &P)
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::ExtractLastElement, Op0_t > m_ExtractLastElement(const Op0_t &Op0)
class_match< VPValue > m_VPValue()
Match an arbitrary VPValue and ignore it.
ValuesClass values(OptsTy... Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
Definition: CommandLine.h:712
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:444
DiagnosticInfoOptimizationBase::Argument NV
NodeAddr< InstrNode * > Instr
Definition: RDFGraph.h:389
NodeAddr< PhiNode * > Phi
Definition: RDFGraph.h:390
VPValue * getOrCreateVPValueForSCEVExpr(VPlan &Plan, const SCEV *Expr)
Get or create a VPValue that corresponds to the expansion of Expr.
Definition: VPlanUtils.cpp:32
VPBasicBlock * getFirstLoopHeader(VPlan &Plan, VPDominatorTree &VPDT)
Returns the header block of the first, top-level loop, or null if none exist.
Definition: VPlanUtils.cpp:138
const SCEV * getSCEVExprForVPValue(VPValue *V, ScalarEvolution &SE)
Return the SCEV expression for V.
Definition: VPlanUtils.cpp:79
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
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:338
@ Offset
Definition: DWP.cpp:477
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.
Definition: LoopUtils.cpp:1980
LLVM_ABI bool RemoveRedundantDbgInstrs(BasicBlock *BB)
Try to remove redundant dbg.value instructions from given basic block.
cl::opt< bool > VerifyEachVPlan
LLVM_ABI std::optional< unsigned > getLoopEstimatedTripCount(Loop *L, unsigned *EstimatedLoopInvocationWeight=nullptr)
Returns a loop's estimated trip count based on branch weight metadata.
Definition: LoopUtils.cpp:841
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:1744
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.
Definition: LoopUtils.cpp:1023
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:1702
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.
LLVM_ABI bool verifyFunction(const Function &F, raw_ostream *OS=nullptr)
Check a function for errors, useful for use when debugging a pass.
Definition: Verifier.cpp:7502
const Value * getLoadStorePointerOperand(const Value *V)
A helper function that returns the pointer operand of a load or store instruction.
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.
LLVM_ABI std::optional< MDNode * > makeFollowupLoopID(MDNode *OrigLoopID, ArrayRef< StringRef > FollowupAttrs, const char *InheritOptionsAttrsPrefix="", bool AlwaysNew=false)
Create a new loop identifier for a loop created from a loop transformation.
Definition: LoopUtils.cpp:264
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition: STLExtras.h:2155
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:663
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
Definition: MathExtras.h:293
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 ...
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:342
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:1751
void collectEphemeralRecipesForVPlan(VPlan &Plan, DenseSet< VPRecipeBase * > &EphRecipes)
auto reverse(ContainerTy &&C)
Definition: STLExtras.h:428
LLVM_ABI void setBranchWeights(Instruction &I, ArrayRef< uint32_t > Weights, bool IsExpected)
Create a new branch_weights metadata node and add or overwrite a prof metadata reference to instructi...
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition: MathExtras.h:288
void sort(IteratorTy Start, IteratorTy End)
Definition: STLExtras.h:1669
std::unique_ptr< VPlan > VPlanPtr
Definition: VPlan.h:77
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:1758
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
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...
Definition: SmallVector.h:1300
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.
cl::opt< unsigned > ForceTargetInstructionCost
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
Definition: Format.h:126
auto drop_end(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the last N elements excluded.
Definition: STLExtras.h:345
constexpr T divideCeil(U Numerator, V Denominator)
Returns the integer ceil(Numerator / Denominator).
Definition: MathExtras.h:399
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.
Definition: DebugInfo.cpp:2259
RecurKind
These are the kinds of recurrences that we support.
Definition: IVDescriptors.h:34
@ FMulAdd
Sum of float products with llvm.fmuladd(a * b + sum).
@ Sub
Subtraction 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....
Definition: LoopUtils.cpp:1305
LLVM_ABI void setProfileInfoAfterUnrolling(Loop *OrigLoop, Loop *UnrolledLoop, Loop *RemainderLoop, uint64_t UF)
Set weights for UnrolledLoop and RemainderLoop based on weights for OrigLoop and the following distri...
Definition: LoopUtils.cpp:1786
uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition: Alignment.h:155
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.
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:565
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:1777
LLVM_ABI llvm::MDNode * makePostTransformationMetadata(llvm::LLVMContext &Context, MDNode *OrigLoopID, llvm::ArrayRef< llvm::StringRef > RemovePrefixes, llvm::ArrayRef< llvm::MDNode * > AddAttrs)
Create a new LoopID after the loop has been transformed.
Definition: LoopInfo.cpp:1182
auto predecessors(const MachineBasicBlock *BB)
iterator_range< pointer_iterator< WrappedIteratorT > > make_pointer_range(RangeT &&Range)
Definition: iterator.h:363
cl::opt< bool > EnableVPlanNativePath
Definition: VPlan.cpp:55
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)
Definition: LoopUtils.cpp:2038
bool pred_empty(const BasicBlock *BB)
Definition: CFG.h:119
InstructionCost Cost
@ 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.
@ Data
Use predicate only to mask operations on data in the loop.
unsigned getPredBlockCostDivisor(TargetTransformInfo::TargetCostKind CostKind)
A helper function that returns how much we should divide the cost of a predicated block by.
Definition: VPlanHelpers.h:64
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:595
T bit_floor(T Value)
Returns the largest integral power of two no greater than Value if Value is nonzero.
Definition: bit.h:280
Type * toVectorTy(Type *Scalar, ElementCount EC)
A helper function for converting Scalar types to vector types.
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:469
LLVM_ABI cl::opt< bool > EnableLoopInterleaving
Implement std::hash so that hash_code can be used in STL containers.
Definition: BitVector.h:856
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition: BitVector.h:858
#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).
Definition: CodeMetrics.cpp:71
An information struct used to provide DenseMap with the various necessary components for a given valu...
Definition: DenseMapInfo.h:54
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={})
BlockFrequencyInfo * BFI
ScalarEvolution * SE
AssumptionCache * AC
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
OptimizationRemarkEmitter * ORE
Storage for information about made changes.
A chain of instructions that form a partial reduction.
Instruction * Reduction
The top-level binary operation that forms the reduction to a scalar after the loop body.
Instruction * ExtendA
The extension of each of the inner binary operation's operands.
A CRTP mix-in to automatically provide informational APIs needed for passes.
Definition: PassManager.h:70
A marker analysis to determine if extra passes should be run after loop vectorization.
static LLVM_ABI AnalysisKey Key
Parameters that control the generic loop unrolling transformation.
bool UnrollVectorizedLoop
Don't disable runtime unroll for the loops which were vectorized.
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.
Definition: VPlanHelpers.h:71
ElementCount End
Definition: VPlanHelpers.h:76
Struct to hold various analysis needed for cost computations.
Definition: VPlanHelpers.h:344
LoopVectorizationCostModel & CM
Definition: VPlanHelpers.h:349
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...
SmallPtrSet< Instruction *, 8 > SkipCostComputation
Definition: VPlanHelpers.h:350
A recipe for handling first-order recurrence phis.
Definition: VPlan.h:2267
A struct that represents some properties of the register usage of a loop.
Definition: VPlanAnalysis.h:76
BasicBlock * PrevBB
The previous IR BasicBlock created or used.
Definition: VPlanHelpers.h:303
SmallDenseMap< const VPBasicBlock *, BasicBlock * > VPBB2IRBB
A mapping of each VPBasicBlock to the corresponding BasicBlock.
Definition: VPlanHelpers.h:311
VPTransformState holds information passed down when "executing" a VPlan, needed for generating the ou...
Definition: VPlanHelpers.h:205
struct llvm::VPTransformState::CFGState CFG
Value * get(const VPValue *Def, bool IsScalar=false)
Get the generated vector Value for a given VPValue Def if IsScalar is false, otherwise return the gen...
Definition: VPlan.cpp:283
std::optional< VPLane > Lane
Hold the index to generate specific scalar instructions.
Definition: VPlanHelpers.h:219
IRBuilderBase & Builder
Hold a reference to the IRBuilder used to generate output IR code.
Definition: VPlanHelpers.h:328
VPlan * Plan
Pointer to the VPlan code is generated for.
Definition: VPlanHelpers.h:331
void set(const VPValue *Def, Value *V, bool IsScalar=false)
Set the generated vector Value for a given VPValue, if IsScalar is false.
Definition: VPlanHelpers.h:250
VPDominatorTree VPDT
VPlan-based dominator tree.
Definition: VPlanHelpers.h:340
A recipe for widening load operations, using the address to load from and an optional mask.
Definition: VPlan.h:3090
A recipe for widening select instructions.
Definition: VPlan.h:1707
A recipe for widening store operations, using the stored value, the address to store to and an option...
Definition: VPlan.h:3170
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 materializeBackedgeTakenCount(VPlan &Plan, VPBasicBlock *VectorPH)
Materialize the backedge-taken count to be computed explicitly using VPInstructions.
static LLVM_ABI_FOR_TEST std::unique_ptr< VPlan > buildVPlan0(Loop *TheLoop, LoopInfo &LI, Type *InductionTy, DebugLoc IVDL, PredicatedScalarEvolution &PSE)
Create a base VPlan0, serving as the common starting point for all later candidates.
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 materializeBuildVectors(VPlan &Plan)
Add explicit Build[Struct]Vector recipes that combine multiple scalar values into single vectors.
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 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 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 LLVM_ABI_FOR_TEST bool tryToConvertVPInstructionsToVPRecipes(VPlanPtr &Plan, function_ref< const InductionDescriptor *(PHINode *)> GetIntOrFpInductionDescriptor, const TargetLibraryInfo &TLI)
Replaces the VPInstructions in Plan with corresponding widen recipes.
static void replicateByVF(VPlan &Plan, ElementCount VF)
Replace each VPReplicateRecipe outside on any replicate region in Plan with VF single-scalar recipes.
static void clearReductionWrapFlags(VPlan &Plan)
Clear NSW/NUW flags from reduction instructions if necessary.
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 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 narrowInterleaveGroups(VPlan &Plan, ElementCount VF, unsigned VectorRegWidth)
Try to convert a plan with interleave groups with VF elements to a plan with the interleave groups re...
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 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