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