LLVM 24.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 four 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. LoopVectorizationPlanner - A unit that builds VPlans for the candidate
23// vectorization factors, selects the best one and executes it to generate
24// the vector code.
25// 4. LoopVectorizationCostModel - A unit that checks for the profitability
26// of vectorization. It decides on the optimal vector width, which
27// can be one, if vectorization is not profitable.
28//
29// There is a development effort going on to migrate loop vectorizer to the
30// VPlan infrastructure and to introduce outer loop vectorization support (see
31// docs/VectorizationPlan.rst and
32// http://lists.llvm.org/pipermail/llvm-dev/2017-December/119523.html). For this
33// purpose, we temporarily introduced the VPlan-native vectorization path: an
34// alternative vectorization path that is natively implemented on top of the
35// VPlan infrastructure. See EnableVPlanNativePath for enabling.
36//
37//===----------------------------------------------------------------------===//
38//
39// The reduction-variable vectorization is based on the paper:
40// D. Nuzman and R. Henderson. Multi-platform Auto-vectorization.
41//
42// Variable uniformity checks are inspired by:
43// Karrenberg, R. and Hack, S. Whole Function Vectorization.
44//
45// The interleaved access vectorization is based on the paper:
46// Dorit Nuzman, Ira Rosen and Ayal Zaks. Auto-Vectorization of Interleaved
47// Data for SIMD
48//
49// Other ideas/concepts are from:
50// A. Zaks and D. Nuzman. Autovectorization in GCC-two years later.
51//
52// S. Maleki, Y. Gao, M. Garzaran, T. Wong and D. Padua. An Evaluation of
53// Vectorizing Compilers.
54//
55//===----------------------------------------------------------------------===//
56
59#include "VPRecipeBuilder.h"
60#include "VPlan.h"
61#include "VPlanAnalysis.h"
62#include "VPlanCFG.h"
63#include "VPlanHelpers.h"
64#include "VPlanPatternMatch.h"
65#include "VPlanTransforms.h"
66#include "VPlanUtils.h"
67#include "VPlanVerifier.h"
68#include "VectorizeOptions.h"
69#include "llvm/ADT/APInt.h"
70#include "llvm/ADT/ArrayRef.h"
71#include "llvm/ADT/DenseMap.h"
72#include "llvm/ADT/Hashing.h"
73#include "llvm/ADT/MapVector.h"
74#include "llvm/ADT/STLExtras.h"
77#include "llvm/ADT/Statistic.h"
78#include "llvm/ADT/StringRef.h"
79#include "llvm/ADT/Twine.h"
80#include "llvm/ADT/TypeSwitch.h"
86#include "llvm/Analysis/CFG.h"
104#include "llvm/IR/Attributes.h"
105#include "llvm/IR/BasicBlock.h"
106#include "llvm/IR/CFG.h"
107#include "llvm/IR/Constant.h"
108#include "llvm/IR/Constants.h"
109#include "llvm/IR/DataLayout.h"
110#include "llvm/IR/DebugInfo.h"
111#include "llvm/IR/DebugLoc.h"
112#include "llvm/IR/DerivedTypes.h"
114#include "llvm/IR/Dominators.h"
115#include "llvm/IR/Function.h"
116#include "llvm/IR/IRBuilder.h"
117#include "llvm/IR/InstrTypes.h"
118#include "llvm/IR/Instruction.h"
119#include "llvm/IR/Instructions.h"
121#include "llvm/IR/Intrinsics.h"
122#include "llvm/IR/MDBuilder.h"
123#include "llvm/IR/Metadata.h"
124#include "llvm/IR/Module.h"
125#include "llvm/IR/Operator.h"
126#include "llvm/IR/PatternMatch.h"
128#include "llvm/IR/Type.h"
129#include "llvm/IR/Use.h"
130#include "llvm/IR/User.h"
131#include "llvm/IR/Value.h"
132#include "llvm/IR/Verifier.h"
133#include "llvm/Support/Casting.h"
135#include "llvm/Support/Debug.h"
150#include <algorithm>
151#include <cassert>
152#include <cmath>
153#include <cstdint>
154#include <functional>
155#include <iterator>
156#include <memory>
157#include <string>
158#include <tuple>
159#include <utility>
160
161using namespace llvm;
162using namespace SCEVPatternMatch;
163using namespace LoopVectorizationUtils;
164
165#define LV_NAME "loop-vectorize"
166#define DEBUG_TYPE LV_NAME
167
168#ifndef NDEBUG
169const char VerboseDebug[] = DEBUG_TYPE "-verbose";
170#endif
171
172STATISTIC(LoopsVectorized, "Number of loops vectorized");
173STATISTIC(LoopsAnalyzed, "Number of loops analyzed for vectorization");
174STATISTIC(LoopsEpilogueVectorized, "Number of epilogues vectorized");
175STATISTIC(LoopsEarlyExitVectorized, "Number of early exit loops vectorized");
176STATISTIC(LoopsPartialAliasVectorized,
177 "Number of partial aliasing loops vectorized");
178
180 "epilogue-vectorization-force-VF", cl::init(ElementCount::getFixed(1)),
182 cl::desc("When epilogue vectorization is enabled, and a value greater than "
183 "1 is specified, forces the given VF for all applicable epilogue "
184 "loops. Note: This allows all scalable VFs >= vscale x 1."));
185
186// Returns true if the epilogue VF has been set to a non-zero value other than
187// VF=1 (scalar).
192
193// Likelyhood of bypassing the vectorized loop because there are zero trips left
194// after prolog. See `emitIterationCountCheck`.
195static constexpr uint32_t MinItersBypassWeights[] = {1, 127};
196
197/// A version of ScalarEvolution::getSmallConstantTripCount that returns an
198/// ElementCount to include loops whose trip count is a function of vscale.
200 const Loop *L) {
201 if (unsigned ExpectedTC = SE->getSmallConstantTripCount(L))
202 return ElementCount::getFixed(ExpectedTC);
203
204 const SCEV *BTC = SE->getBackedgeTakenCount(L);
206 return ElementCount::getFixed(0);
207
208 const SCEV *ExitCount = SE->getTripCountFromExitCount(BTC, BTC->getType(), L);
209 if (isa<SCEVVScale>(ExitCount))
211
212 const APInt *Scale;
213 if (match(ExitCount, m_scev_Mul(m_scev_APInt(Scale), m_SCEVVScale())))
214 if (cast<SCEVMulExpr>(ExitCount)->hasNoUnsignedWrap())
215 if (Scale->getActiveBits() <= 32)
217
218 return ElementCount::getFixed(0);
219}
220
221/// Get the maximum trip count for \p L from the SCEV unsigned range, excluding
222/// zero from the range. Only valid when not folding the tail, as the minimum
223/// iteration count check guards against a zero trip count. Returns 0 if
224/// unknown.
226 Loop *L) {
227 const SCEV *BTC = PSE.getBackedgeTakenCount();
229 return 0;
230 ScalarEvolution *SE = PSE.getSE();
231 const SCEV *TripCount = SE->getTripCountFromExitCount(BTC, BTC->getType(), L);
232 ConstantRange TCRange =
233 SE->getUnsignedRange(SE->applyLoopGuards(TripCount, L));
234 APInt MaxTCFromRange = TCRange.getUnsignedMax();
235 if (!MaxTCFromRange.isZero() && MaxTCFromRange.getActiveBits() <= 32)
236 return MaxTCFromRange.getZExtValue();
237 return 0;
238}
239
240/// Returns "best known" trip count, which is either a valid positive trip count
241/// or std::nullopt when an estimate cannot be made (including when the trip
242/// count would overflow), for the specified loop \p L as defined by the
243/// following procedure:
244/// 1) Returns exact trip count if it is known.
245/// 2) Returns expected trip count according to profile data if any.
246/// 3) Returns upper bound estimate if known, if \p CanUseConstantMax, and
247/// if \p ComputeUpperBoundOnly is false.
248/// 4) Returns the maximum trip count from the SCEV range excluding zero,
249/// if \p CanUseConstantMax and \p CanExcludeZeroTrips.
250/// 5) Returns std::nullopt if all of the above failed.
251static std::optional<ElementCount> getSmallBestKnownTC(
252 const VectorizeOptions &Opts, PredicatedScalarEvolution &PSE, Loop *L,
253 bool CanUseConstantMax = true, bool CanExcludeZeroTrips = false,
254 bool ComputeUpperBoundOnly = false) {
255 // Check if exact trip count is known.
256 if (auto ExpectedTC = getSmallConstantTripCount(PSE.getSE(), L))
257 return ExpectedTC;
258
259 // Check if there is an expected trip count available from profile data.
260 // An estimate of zero means the loop is estimated not to be entered; it is
261 // not a usable trip count for the profitability decisions below (and would
262 // e.g. divide by zero when scaling runtime check cost), so treat it as
263 // unknown.
264 if (Opts.loop_vectorize_with_block_frequency && !ComputeUpperBoundOnly)
265 if (unsigned EstimatedTC = getLoopEstimatedTripCount(L).value_or(0))
266 return ElementCount::getFixed(EstimatedTC);
267
268 if (!CanUseConstantMax)
269 return std::nullopt;
270
271 // Check if upper bound estimate is known.
272 if (unsigned ExpectedTC = PSE.getSmallConstantMaxTripCount())
273 return ElementCount::getFixed(ExpectedTC);
274
275 // Get the maximum trip count from the SCEV range excluding zero. This is
276 // only safe when not folding the tail, as the minimum iteration count check
277 // prevents entering the vector loop with a zero trip count.
278 if (CanUseConstantMax && CanExcludeZeroTrips)
279 if (unsigned RefinedTC = getMaxTCFromNonZeroRange(PSE, L))
280 return ElementCount::getFixed(RefinedTC);
281
282 return std::nullopt;
283}
284
285namespace {
286using SCEV2ValueTy = DenseMap<const SCEV *, Value *>;
287} // namespace
288
289namespace llvm {
290
292
293} // end namespace llvm
294
295/// Look for a meaningful debug location on the instruction or its operands.
297 if (!I)
298 return DebugLoc::getUnknown();
299
301 if (I->getDebugLoc() != Empty)
302 return I->getDebugLoc();
303
304 for (Use &Op : I->operands()) {
305 if (Instruction *OpInst = dyn_cast<Instruction>(Op))
306 if (OpInst->getDebugLoc() != Empty)
307 return OpInst->getDebugLoc();
308 }
309
310 return I->getDebugLoc();
311}
312
313namespace llvm {
314
315/// Return the runtime value for VF.
317 return B.CreateElementCount(Ty, VF);
318}
319
320} // end namespace llvm
321
322namespace llvm {
323
324// Loop vectorization cost-model hints how the epilogue/tail loop should be
325// lowered.
327
328 // The default: allowing epilogues.
330
331 // Vectorization with OptForSize: don't allow epilogues.
333
334 // A special case for loops with a very small trip count: they are vectorized
335 // only if no scalar epilogue is required, ensuring the vectorized loop body
336 // is the dominant cost without scalar epilogue overheads.
338
339 // Loop hint indicating an epilogue is undesired, apply tail folding.
341
342 // Directive indicating we must either fold the epilogue/tail or not vectorize
344};
345
347
348/// LoopVectorizationCostModel - estimates the expected speedups due to
349/// vectorization.
350/// In many cases vectorization is not profitable. This can happen because of
351/// a number of reasons. In this class we mainly attempt to predict the
352/// expected speedup/slowdowns due to the supported instruction set. We use the
353/// TargetTransformInfo to query the different backends for the cost of
354/// different operations.
357
358public:
365 std::function<BlockFrequencyInfo &()> GetBFI,
366 const Function *F, InterleavedAccessInfo &IAI,
367 VFSelectionContext &Config)
368 : Opts(Config.getOpts()), Config(Config), EpilogueLoweringStatus(SEL),
369 TheLoop(L), PSE(PSE), LI(LI), Legal(Legal), TTI(TTI), TLI(TLI), AC(AC),
371
372 /// \return An upper bound for the vectorization factors (both fixed and
373 /// scalable). If the factors are 0, vectorization and interleaving should be
374 /// avoided up front.
375 FixedScalableVFPair computeMaxVF(ElementCount UserVF, unsigned UserIC);
376
377 /// Memory access instruction may be vectorized in more than one way.
378 /// Form of instruction after vectorization depends on cost.
379 /// This function takes cost-based decisions for Load/Store instructions
380 /// and collects them in a map. This decisions map is used for building
381 /// the lists of loop-uniform and loop-scalar instructions.
382 /// The calculated cost is saved with widening decision in order to
383 /// avoid redundant calculations.
385
386 /// Collect values we want to ignore in the cost model.
388
389 /// \returns True if it is more profitable to scalarize instruction \p I for
390 /// vectorization factor \p VF.
392 assert(VF.isVector() &&
393 "Profitable to scalarize relevant only for VF > 1.");
394 assert(
395 TheLoop->isInnermost() &&
396 "cost-model should not be used for outer loops (in VPlan-native path)");
397
398 auto Scalars = InstsToScalarize.find(VF);
399 assert(Scalars != InstsToScalarize.end() &&
400 "VF not yet analyzed for scalarization profitability");
401 return Scalars->second.contains(I);
402 }
403
404 /// Returns true if \p I is known to be uniform after vectorization.
406 assert(
407 TheLoop->isInnermost() &&
408 "cost-model should not be used for outer loops (in VPlan-native path)");
409
410 // If VF is scalar, then all instructions are trivially uniform.
411 if (VF.isScalar())
412 return true;
413
414 // Pseudo probes must be duplicated per vector lane so that the
415 // profiled loop trip count is not undercounted.
417 return false;
418
419 auto UniformsPerVF = Uniforms.find(VF);
420 assert(UniformsPerVF != Uniforms.end() &&
421 "VF not yet analyzed for uniformity");
422 return UniformsPerVF->second.count(I);
423 }
424
425 /// Returns true if \p I is known to be scalar after vectorization.
427 assert(
428 TheLoop->isInnermost() &&
429 "cost-model should not be used for outer loops (in VPlan-native path)");
430 if (VF.isScalar())
431 return true;
432
433 auto ScalarsPerVF = Scalars.find(VF);
434 assert(ScalarsPerVF != Scalars.end() &&
435 "Scalar values are not calculated for VF");
436 return ScalarsPerVF->second.count(I);
437 }
438
439 /// \returns True if instruction \p I can be truncated to a smaller bitwidth
440 /// for vectorization factor \p VF.
442 const auto &MinBWs = Config.getMinimalBitwidths();
443 // Truncs must truncate at most to their destination type.
444 if (isa_and_nonnull<TruncInst>(I) && MinBWs.contains(I) &&
445 I->getType()->getScalarSizeInBits() < MinBWs.lookup(I))
446 return false;
447 return VF.isVector() && MinBWs.contains(I) &&
450 }
451
452 /// Decision that was taken during cost calculation for memory instruction.
455 CM_Widen, // For consecutive accesses with stride +1.
456 CM_Widen_Reverse, // For consecutive accesses with stride -1.
460 /// A widening decision that has been invalidated after replacing the
461 /// corresponding recipe during VPlan transforms.
462 /// TODO: Remove once the legacy exit cost computation is retired.
464 };
465
466#ifndef NDEBUG
468 constexpr StringLiteral WideningStr[] = {
469 "Unknown", "Widen", "Widen_Reverse", "Interleave",
470 "GatherScatter", "Scalarize", "InvalidatedDecision"};
471 return WideningStr[W];
472 }
473#endif
474
475 /// Save vectorization decision \p W and \p Cost taken by the cost model for
476 /// instruction \p I and vector width \p VF.
479 assert(VF.isVector() && "Expected VF >=2");
480 LLVM_DEBUG(dbgs() << "LV: Setting widening decision to "
481 << getInstWideningStr(W) << " for VF " << VF
482 << " and instruction: " << *I << '\n');
483 WideningDecisions[{I, VF}] = {W, Cost};
484 }
485
486 /// Save vectorization decision \p W and \p Cost taken by the cost model for
487 /// interleaving group \p Grp and vector width \p VF.
491 assert(VF.isVector() && "Expected VF >=2");
492 /// Broadcast this decicion to all instructions inside the group.
493 /// When interleaving, the cost will only be assigned one instruction, the
494 /// insert position. For other cases, add the appropriate fraction of the
495 /// total cost to each instruction. This ensures accurate costs are used,
496 /// even if the insert position instruction is not used.
497 InstructionCost InsertPosCost = Cost;
498 InstructionCost OtherMemberCost = 0;
499 if (W != CM_Interleave)
500 OtherMemberCost = InsertPosCost = Cost / Grp->getNumMembers();
501 ;
502 for (auto *I : Grp->members()) {
503 LLVM_DEBUG(dbgs() << "LV: Setting widening decision to "
504 << getInstWideningStr(W) << " for VF " << VF
505 << " and instruction: " << *I << '\n');
506 if (Grp->getInsertPos() == I)
507 WideningDecisions[{I, VF}] = {W, InsertPosCost};
508 else
509 WideningDecisions[{I, VF}] = {W, OtherMemberCost};
510 }
511 }
512
513 /// Return the cost model decision for the given instruction \p I and vector
514 /// width \p VF. Return CM_Unknown if this instruction did not pass
515 /// through the cost modeling.
517 assert(VF.isVector() && "Expected VF to be a vector VF");
518 assert(
519 TheLoop->isInnermost() &&
520 "cost-model should not be used for outer loops (in VPlan-native path)");
521
522 std::pair<Instruction *, ElementCount> InstOnVF(I, VF);
523 auto Itr = WideningDecisions.find(InstOnVF);
524 if (Itr == WideningDecisions.end())
525 return CM_Unknown;
526 return Itr->second.first;
527 }
528
529 /// Return the vectorization cost for the given instruction \p I and vector
530 /// width \p VF.
532 assert(VF.isVector() && "Expected VF >=2");
533 std::pair<Instruction *, ElementCount> InstOnVF(I, VF);
534 assert(WideningDecisions.contains(InstOnVF) &&
535 "The cost is not calculated");
536 return WideningDecisions[InstOnVF].second;
537 }
538
539 /// Return True if instruction \p I is an optimizable truncate whose operand
540 /// is an induction variable. Such a truncate will be removed by adding a new
541 /// induction variable with the destination type.
543 // If the instruction is not a truncate, return false.
544 auto *Trunc = dyn_cast<TruncInst>(I);
545 if (!Trunc)
546 return false;
547
548 // Get the source and destination types of the truncate.
549 Type *SrcTy = toVectorTy(Trunc->getSrcTy(), VF);
550 Type *DestTy = toVectorTy(Trunc->getDestTy(), VF);
551
552 // If the truncate is free for the given types, return false. Replacing a
553 // free truncate with an induction variable would add an induction variable
554 // update instruction to each iteration of the loop. We exclude from this
555 // check the primary induction variable since it will need an update
556 // instruction regardless.
557 Value *Op = Trunc->getOperand(0);
558 if (Op != Legal->getPrimaryInduction() && TTI.isTruncateFree(SrcTy, DestTy))
559 return false;
560
561 // If the truncated value is not an induction variable, return false.
562 return Legal->isInductionPhi(Op);
563 }
564
565 /// Collects the instructions to scalarize for each predicated instruction in
566 /// the loop.
568
569 /// Collect values that will not be widened, including Uniforms, Scalars, and
570 /// Instructions to Scalarize for the given \p VF.
571 /// The sets depend on CM decision for Load/Store instructions
572 /// that may be vectorized as interleave, gather-scatter or scalarized.
573 /// Also make a decision on what to do about call instructions in the loop
574 /// at that VF -- scalarize, call a known vector routine, or call a
575 /// vector intrinsic.
577 // Do the analysis once.
578 if (VF.isScalar() || Uniforms.contains(VF))
579 return;
581 collectLoopUniforms(VF);
582 collectLoopScalars(VF);
584 }
585
586 /// Given costs for both strategies, return true if the scalar predication
587 /// lowering should be used for div/rem. This incorporates an override
588 /// option so it is not simply a cost comparison.
590 InstructionCost MaskedCost) const {
591 return !valueOr(Opts.force_widen_divrem_via_masked_intrinsic,
592 !(ScalarCost < MaskedCost));
593 }
594
595 /// Returns true if \p I is an instruction which requires predication and
596 /// for which our chosen predication strategy is scalarization (i.e. we
597 /// don't have an alternate strategy such as masking available).
598 /// \p VF is the vectorization factor that will be used to vectorize \p I.
600
601 /// Wrapper function for LoopVectorizationLegality::isMaskRequired,
602 /// that passes the Instruction \p I and if we fold tail.
603 bool isMaskRequired(Instruction *I) const;
604
605 /// Returns true if \p I is an instruction that needs to be predicated
606 /// at runtime. The result is independent of the predication mechanism.
607 /// Superset of instructions that return true for isScalarWithPredication.
608 bool isPredicatedInst(Instruction *I) const;
609
610 /// A helper function that returns how much we should divide the cost of a
611 /// predicated block by. Typically this is the reciprocal of the block
612 /// probability, i.e. if we return X we are assuming the predicated block will
613 /// execute once for every X iterations of the loop header so the block should
614 /// only contribute 1/X of its cost to the total cost calculation, but when
615 /// optimizing for code size it will just be 1 as code size costs don't depend
616 /// on execution probabilities.
617 ///
618 /// Note that if a block wasn't originally predicated but was predicated due
619 /// to tail folding, the divisor will still be 1 because it will execute for
620 /// every iteration of the loop header.
621 inline uint64_t
623 const BasicBlock *BB);
624
625 /// Returns true if an artificially high cost for emulated masked memrefs
626 /// should be used.
628
629 /// Return the costs for our two available strategies for lowering a
630 /// div/rem operation which requires speculating at least one lane.
631 /// First result is for scalarization (will be invalid for scalable
632 /// vectors); second is for the masked intrinsic strategy.
633 std::pair<InstructionCost, InstructionCost>
635
636 /// If \p I is a memory instruction with a consecutive pointer that can be
637 /// widened, returns the widening kind (CM_Widen or CM_Widen_Reverse) and
638 /// std::nullopt otherwise.
639 std::optional<InstWidening> memoryInstructionCanBeWidened(Instruction *I,
640 ElementCount VF);
641
642 /// Returns true if \p I is a memory instruction in an interleaved-group
643 /// of memory accesses that can be vectorized with wide vector loads/stores
644 /// and shuffles.
646
647 /// Returns true if the target machine supports masked loads or stores
648 /// for \p I's data type and alignment. The caller must ensure the access is
649 /// consecutive or part of an interleave group.
651
652 /// Returns true if the target machine supports gather or scatter for \p I's
653 /// data type and alignment.
655
656 /// Check if \p Instr belongs to any interleaved access group.
657 bool isAccessInterleaved(Instruction *Instr) const {
658 return InterleaveInfo.isInterleaved(Instr);
659 }
660
661 /// Get the interleaved access group that \p Instr belongs to.
664 return InterleaveInfo.getInterleaveGroup(Instr);
665 }
666
667 /// Returns true if we're required to use a scalar epilogue for at least
668 /// the final iteration of the original loop.
669 bool requiresScalarEpilogue(bool IsVectorizing) const {
670 if (!isEpilogueAllowed()) {
671 LLVM_DEBUG(dbgs() << "LV: Loop does not require scalar epilogue\n");
672 return false;
673 }
674 // If we might exit from anywhere but the latch and early exit vectorization
675 // is disabled, we must run the exiting iteration in scalar form.
676 if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch() &&
677 !(Opts.enable_early_exit_vectorization &&
678 Legal->hasUncountableEarlyExit())) {
679 LLVM_DEBUG(dbgs() << "LV: Loop requires scalar epilogue: not exiting "
680 "from latch block\n");
681 return true;
682 }
683 if (IsVectorizing && InterleaveInfo.requiresScalarEpilogue()) {
684 LLVM_DEBUG(dbgs() << "LV: Loop requires scalar epilogue: "
685 "interleaved group requires scalar epilogue\n");
686 return true;
687 }
688 LLVM_DEBUG(dbgs() << "LV: Loop does not require scalar epilogue\n");
689 return false;
690 }
691
692 /// Returns true if an epilogue is allowed (e.g., not prevented by
693 /// optsize or a loop hint annotation).
694 bool isEpilogueAllowed() const {
695 return EpilogueLoweringStatus == CM_EpilogueAllowed;
696 }
697
698 /// Returns the TailFoldingStyle that is best for the current loop.
700 return ChosenTailFoldingStyle;
701 }
702
703 /// Selects and saves TailFoldingStyle.
704 /// \param IsScalableVF true if scalable vector factors enabled.
705 /// \param UserIC User specific interleave count.
706 void setTailFoldingStyle(bool IsScalableVF, unsigned UserIC) {
707 assert(ChosenTailFoldingStyle == TailFoldingStyle::None &&
708 "Tail folding must not be selected yet.");
709 if (!Legal->canFoldTailByMasking()) {
710 ChosenTailFoldingStyle = TailFoldingStyle::None;
711 return;
712 }
713
714 // Default to TTI preference, but allow command line override.
715 ChosenTailFoldingStyle = Opts.force_tail_folding_style.value_or(
716 TTI.getPreferredTailFoldingStyle());
717
718 if (ChosenTailFoldingStyle != TailFoldingStyle::DataWithEVL)
719 return;
720 // Override EVL styles if needed.
721 // FIXME: Investigate opportunity for fixed vector factor.
722 bool EVLIsLegal = UserIC <= 1 && IsScalableVF &&
723 TTI.hasActiveVectorLength() &&
724 !Opts.enable_vplan_native_path;
725 if (EVLIsLegal)
726 return;
727 // If for some reason EVL mode is unsupported, fallback to an epilogue
728 // if it's allowed, or DataWithoutLaneMask otherwise.
729 if (EpilogueLoweringStatus == CM_EpilogueAllowed ||
730 EpilogueLoweringStatus == CM_EpilogueNotNeededFoldTail)
731 ChosenTailFoldingStyle = TailFoldingStyle::None;
732 else
733 ChosenTailFoldingStyle = TailFoldingStyle::DataWithoutLaneMask;
734
736 dbgs() << "LV: Preference for VP intrinsics indicated. Will "
737 "not try to generate VP Intrinsics "
738 << (UserIC > 1
739 ? "since interleave count specified is greater than 1.\n"
740 : "due to non-interleaving reasons.\n"));
741 }
742
743 /// Returns true if all loop blocks should be masked to fold tail loop.
744 bool foldTailByMasking() const {
746 }
747
749 assert(foldTailByMasking() && "Expected tail folding to be enabled!");
751 "Did not expect to enable alias masking with EVL!");
752 assert(PartialAliasMaskingStatus == AliasMaskingStatus::NotDecided);
753
754 // Assume we fail to enable alias masking (in case we early exit).
755 PartialAliasMaskingStatus = AliasMaskingStatus::Disabled;
756
757 // Note: FixedOrderRecurrences are not supported yet as we cannot handle
758 // the required `splice.right` with the alias-mask.
759 if (!Opts.force_partial_aliasing_vectorization ||
760 !Legal->getFixedOrderRecurrences().empty())
761 return;
762
763 const RuntimePointerChecking *Checks = Legal->getRuntimePointerChecking();
764 if (!Checks)
765 return;
766
767 auto DiffChecks = Checks->getDiffChecks();
768 if (!DiffChecks || DiffChecks->empty())
769 return;
770
771 [[maybe_unused]] auto HasPointerArgs = [](CallBase *CB) {
772 return any_of(CB->args(), [](Value const *Arg) {
773 return Arg->getType()->isPointerTy();
774 });
775 };
776
777 for (BasicBlock *BB : TheLoop->blocks()) {
778 for (Instruction &I : *BB) {
780 [[maybe_unused]] auto *Call = dyn_cast<CallInst>(&I);
781 assert(
782 (!I.mayReadOrWriteMemory() || (Call && !HasPointerArgs(Call))) &&
783 "Skipped unexpected memory access");
784 continue;
785 }
786
787 Type *ScalarTy = getLoadStoreType(&I);
789
790 // Currently, we can't handle alias masking in reverse. Reversing the
791 // alias mask is not correct (or necessary). When combined with
792 // tail-folding the active lane mask should only be reversed where the
793 // alias-mask is true.
794 if (Legal->isConsecutivePtr(ScalarTy, Ptr) == -1)
795 return;
796 }
797 }
798
799 PartialAliasMaskingStatus = AliasMaskingStatus::Enabled;
800 }
801
802 /// Returns true if all loop blocks should have partial aliases masked.
803 bool maskPartialAliasing() const {
804 return PartialAliasMaskingStatus == AliasMaskingStatus::Enabled;
805 }
806
807 /// Returns true if the instructions in this block requires predication
808 /// for any reason, e.g. because tail folding now requires a predicate,
809 /// because memory accesses are masked due to an uncountable exit with side
810 /// effects, or because the block in the original loop was predicated.
812 return foldTailByMasking() || Legal->hasUncountableExitWithSideEffects() ||
813 Legal->blockNeedsPredication(BB);
814 }
815
816 /// Returns true if VP intrinsics with explicit vector length support should
817 /// be generated in the tail folded loop.
821
822 /// Returns true if the predicated reduction select should be used to set the
823 /// incoming value for the reduction phi.
825 bool HasUsesOutsideReductionChain) const {
826 // Force to use predicated reduction select since the EVL of the
827 // second-to-last iteration might not be VF*UF.
828 if (foldTailWithEVL())
829 return true;
830
831 // Force a predicated select with alias-masking to avoid propagating poison
832 // values to the header phi for lanes outside the alias-mask.
834 return true;
835
836 // Note: For FindLast recurrences and multi-use reductions we prefer a
837 // predicated select to simplify matching in handleFindLastReductions() and
838 // handleMultiUseReductions() respectively, rather than handle multiple
839 // cases.
841 HasUsesOutsideReductionChain)
842 return true;
843
844 return Opts.prefer_predicated_reduction_select ||
845 TTI.preferPredicatedReductionSelect();
846 }
847
848 /// Estimate cost of an intrinsic call instruction CI if it were vectorized
849 /// with factor VF. Return the cost of the instruction, including
850 /// scalarization overhead if it's needed.
852
853 /// Estimate cost of a call instruction CI if it were vectorized with factor
854 /// VF. Return the cost of the instruction, including scalarization overhead
855 /// if it's needed.
857
858 /// Invalidates decisions already taken by the cost model.
860 WideningDecisions.clear();
861 Uniforms.clear();
862 Scalars.clear();
863 }
864
865 /// Returns the expected execution cost. The unit of the cost does
866 /// not matter because we use the 'cost' units to compare different
867 /// vector widths. The cost that is returned is *not* normalized by
868 /// the factor width.
870
871 /// Returns the execution time cost of an instruction for a given vector
872 /// width. Vector width of one means scalar.
874
875 /// Returns true if \p Op should be considered invariant and if it is
876 /// trivially hoistable.
878
879 /// Returns true if \p I has been forced to be scalarized at \p VF.
881 auto FS = ForcedScalars.find(VF);
882 return FS != ForcedScalars.end() && FS->second.contains(I);
883 }
884
885private:
886 const VectorizeOptions &Opts;
887
888 unsigned NumPredStores = 0;
889
890 /// VF selection state independent of cost-modeling decisions.
891 VFSelectionContext &Config;
892
893 /// Wrapper around LoopVectorizationLegality::isUniform() that takes into
894 /// account if alias-masking is enabled. We consider the VF to be unknown when
895 /// alias masking.
896 bool isUniform(Value *V, ElementCount VF) const {
897 // With alias-masking our runtime VF is [2, VF] (and not necessarily a
898 // power-of-two). Something that is uniform for VF may not be for the full
899 // range.
900 assert(PartialAliasMaskingStatus != AliasMaskingStatus::NotDecided &&
901 "alias-mask status must be decided already");
902 return Legal->isUniform(V, PartialAliasMaskingStatus ==
904 ? std::optional(VF)
905 : std::nullopt);
906 }
907
908 /// Wrapper around LoopVectorizationLegality::isUniformMemOp() that takes into
909 /// account if alias-masking is enabled. We consider the VF to be unknown when
910 /// alias masking.
911 bool isUniformMemOp(Instruction &I, ElementCount VF) const {
912 assert(PartialAliasMaskingStatus != AliasMaskingStatus::NotDecided &&
913 "alias-mask status must be decided already");
914 return Legal->isUniformMemOp(I, PartialAliasMaskingStatus ==
916 ? std::optional(VF)
917 : std::nullopt);
918 }
919
920 /// Calculate vectorization cost of memory instruction \p I.
921 InstructionCost getMemoryInstructionCost(Instruction *I, ElementCount VF);
922
923 /// The cost computation for scalarized memory instruction.
924 InstructionCost getMemInstScalarizationCost(Instruction *I, ElementCount VF);
925
926 /// The cost computation for interleaving group of memory instructions.
927 InstructionCost getInterleaveGroupCost(Instruction *I, ElementCount VF) const;
928
929 /// The cost computation for Gather/Scatter instruction.
930 InstructionCost getGatherScatterCost(Instruction *I, ElementCount VF) const;
931
932 /// The cost computation for widening instruction \p I with consecutive
933 /// memory access.
934 InstructionCost getConsecutiveMemOpCost(Instruction *I, ElementCount VF,
935 InstWidening Kind);
936
937 /// The cost calculation for Load/Store instruction \p I with uniform pointer -
938 /// Load: scalar load + broadcast.
939 /// Store: scalar store + (loop invariant value stored? 0 : extract of last
940 /// element)
941 InstructionCost getUniformMemOpCost(Instruction *I, ElementCount VF) const;
942
943 /// Estimate the overhead of scalarizing an instruction. This is a
944 /// convenience wrapper for the type-based getScalarizationOverhead API.
945 InstructionCost getScalarizationOverhead(Instruction *I,
946 ElementCount VF) const;
947
948 /// A type representing the costs for instructions if they were to be
949 /// scalarized rather than vectorized. The entries are Instruction-Cost
950 /// pairs.
951 using ScalarCostsTy = MapVector<Instruction *, InstructionCost>;
952
953 /// A set containing all BasicBlocks that are known to present after
954 /// vectorization as a predicated block.
955 DenseMap<ElementCount, SmallPtrSet<BasicBlock *, 4>>
956 PredicatedBBsAfterVectorization;
957
958 /// Records whether it is allowed to have the original scalar loop execute at
959 /// least once. This may be needed as a fallback loop in case runtime
960 /// aliasing/dependence checks fail, or to handle the tail/remainder
961 /// iterations when the trip count is unknown or doesn't divide by the VF,
962 /// or as a peel-loop to handle gaps in interleave-groups.
963 /// Under optsize and when the trip count is very small we don't allow any
964 /// iterations to execute in the scalar loop.
965 EpilogueLowering EpilogueLoweringStatus = CM_EpilogueAllowed;
966
967 /// Control finally chosen tail folding style.
968 TailFoldingStyle ChosenTailFoldingStyle = TailFoldingStyle::None;
969
970 /// If partial alias masking is enabled/disabled or not decided.
971 AliasMaskingStatus PartialAliasMaskingStatus = AliasMaskingStatus::NotDecided;
972
973 /// A map holding scalar costs for different vectorization factors. The
974 /// presence of a cost for an instruction in the mapping indicates that the
975 /// instruction will be scalarized when vectorizing with the associated
976 /// vectorization factor. The entries are VF-ScalarCostTy pairs.
977 DenseMap<ElementCount, ScalarCostsTy> InstsToScalarize;
978
979 /// Holds the instructions known to be uniform after vectorization.
980 /// The data is collected per VF.
981 DenseMap<ElementCount, SmallPtrSet<Instruction *, 4>> Uniforms;
982
983 /// Holds the instructions known to be scalar after vectorization.
984 /// The data is collected per VF.
985 DenseMap<ElementCount, SmallPtrSet<Instruction *, 4>> Scalars;
986
987 /// Holds the instructions (address computations) that are forced to be
988 /// scalarized.
989 DenseMap<ElementCount, SmallSetVector<Instruction *, 4>> ForcedScalars;
990
991 /// Returns the expected difference in cost from scalarizing the expression
992 /// feeding a predicated instruction \p PredInst. The instructions to
993 /// scalarize and their scalar costs are collected in \p ScalarCosts. A
994 /// non-negative return value implies the expression will be scalarized.
995 /// Currently, only single-use chains are considered for scalarization.
996 InstructionCost computePredInstDiscount(Instruction *PredInst,
997 ScalarCostsTy &ScalarCosts,
998 ElementCount VF);
999
1000 /// Collect the instructions that are uniform after vectorization. An
1001 /// instruction is uniform if we represent it with a single scalar value in
1002 /// the vectorized loop corresponding to each vector iteration. Examples of
1003 /// uniform instructions include pointer operands of consecutive or
1004 /// interleaved memory accesses. Note that although uniformity implies an
1005 /// instruction will be scalar, the reverse is not true. In general, a
1006 /// scalarized instruction will be represented by VF scalar values in the
1007 /// vectorized loop, each corresponding to an iteration of the original
1008 /// scalar loop.
1009 void collectLoopUniforms(ElementCount VF);
1010
1011 /// Collect the instructions that are scalar after vectorization. An
1012 /// instruction is scalar if it is known to be uniform or will be scalarized
1013 /// during vectorization. collectLoopScalars should only add non-uniform nodes
1014 /// to the list if they are used by a load/store instruction that is marked as
1015 /// CM_Scalarize. Non-uniform scalarized instructions will be represented by
1016 /// VF values in the vectorized loop, each corresponding to an iteration of
1017 /// the original scalar loop.
1018 void collectLoopScalars(ElementCount VF);
1019
1020 /// Keeps cost model vectorization decision and cost for instructions.
1021 /// Right now it is used for memory instructions only.
1022 using DecisionList = DenseMap<std::pair<Instruction *, ElementCount>,
1023 std::pair<InstWidening, InstructionCost>>;
1024
1025 DecisionList WideningDecisions;
1026
1027 /// Returns true if \p V is expected to be vectorized and it needs to be
1028 /// extracted.
1029 bool needsExtract(Value *V, ElementCount VF) const {
1031 if (VF.isScalar() || !I || !TheLoop->contains(I) ||
1032 TheLoop->isLoopInvariant(I) ||
1034 return false;
1035
1036 // Assume we can vectorize V (and hence we need extraction) if the
1037 // scalars are not computed yet. This can happen, because it is called
1038 // via getScalarizationOverhead from setCostBasedWideningDecision, before
1039 // the scalars are collected. That should be a safe assumption in most
1040 // cases, because we check if the operands have vectorizable types
1041 // beforehand in LoopVectorizationLegality.
1042 return !Scalars.contains(VF) || !isScalarAfterVectorization(I, VF);
1043 };
1044
1045public:
1046 /// The loop that we evaluate.
1048
1049 /// Predicated scalar evolution analysis.
1051
1052 /// Loop Info analysis.
1054
1055 /// Vectorization legality.
1057
1058 /// Vector target information.
1060
1061 /// Target Library Info.
1063
1064 /// Assumption cache.
1066
1067 /// Interface to emit optimization remarks.
1069
1070 /// A function to lazily fetch BlockFrequencyInfo. This avoids computing it
1071 /// unless necessary, e.g. when the loop isn't legal to vectorize or when
1072 /// there is no predication.
1073 std::function<BlockFrequencyInfo &()> GetBFI;
1074 /// The BlockFrequencyInfo returned from GetBFI.
1076 /// Returns the BlockFrequencyInfo for the function if cached, otherwise
1077 /// fetches it via GetBFI. Avoids an indirect call to the std::function.
1079 if (!BFI)
1080 BFI = &GetBFI();
1081 return *BFI;
1082 }
1083
1085
1086 /// The interleave access information contains groups of interleaved accesses
1087 /// with the same stride and close to each other.
1089
1090 /// Values to ignore in the cost model.
1092
1093 /// Values to ignore in the cost model when VF > 1.
1095};
1096} // end namespace llvm
1097
1098namespace {
1099/// Helper struct to manage generating runtime checks for vectorization.
1100///
1101/// The runtime checks are created up-front in temporary blocks to allow better
1102/// estimating the cost and un-linked from the existing IR. After deciding to
1103/// vectorize, the checks are attached to VPlan as IR or recipes. If deciding
1104/// not to vectorize, the temporary blocks are completely removed.
1105class GeneratedRTChecks {
1106 const VectorizeOptions &Opts;
1107
1108 /// Basic block which contains the generated SCEV checks, if any.
1109 BasicBlock *SCEVCheckBlock = nullptr;
1110
1111 /// The value representing the result of the generated SCEV checks. If it is
1112 /// nullptr no SCEV checks have been generated.
1113 Value *SCEVCheckCond = nullptr;
1114
1115 /// Basic block which contains the generated memory runtime checks, if any.
1116 BasicBlock *MemCheckBlock = nullptr;
1117
1118 /// The value representing the result of the generated memory runtime checks.
1119 /// If it is nullptr no memory runtime checks have been generated.
1120 Value *MemRuntimeCheckCond = nullptr;
1121
1122 /// Whether checks were generated, retained after their IR is replaced or
1123 /// removed during VPlan execution.
1124 bool HasChecks = false;
1125
1126 DominatorTree *DT;
1127 LoopInfo *LI;
1129
1130 SCEVExpander SCEVExp;
1131 SCEVExpander MemCheckExp;
1132
1133 bool CostTooHigh = false;
1134
1135 Loop *OuterLoop = nullptr;
1136
1138
1139 /// The kind of cost that we are calculating
1140 TTI::TargetCostKind CostKind;
1141
1142 /// True if the loop is alias-masked (which allows us to omit diff checks).
1143 bool LoopUsesPartialAliasMasking = false;
1144
1145public:
1146 GeneratedRTChecks(const VectorizeOptions &Opts,
1149 TTI::TargetCostKind CostKind,
1150 bool LoopUsesPartialAliasMasking)
1151 : Opts(Opts), DT(DT), LI(LI), TTI(TTI),
1152 SCEVExp(*PSE.getSE(), "scev.check", /*PreserveLCSSA=*/false),
1153 MemCheckExp(*PSE.getSE(), "scev.check", /*PreserveLCSSA=*/false),
1154 PSE(PSE), CostKind(CostKind),
1155 LoopUsesPartialAliasMasking(LoopUsesPartialAliasMasking) {}
1156
1157 /// Generate runtime checks in SCEVCheckBlock and MemCheckBlock, so we can
1158 /// accurately estimate the cost of the runtime checks. The blocks are
1159 /// un-linked from the IR and attached to VPlan as IR or recipes if
1160 /// profitable. Otherwise, the check blocks are removed completely. If \p LAI
1161 /// is nullptr (outer loops have no LoopAccessInfo), no memory runtime checks
1162 /// are generated.
1163 void create(Loop *L, const LoopAccessInfo *LAI,
1164 const SCEVPredicate &UnionPred, ElementCount VF, unsigned IC,
1165 OptimizationRemarkEmitter &ORE) {
1166
1167 // Hard cutoff to limit compile-time increase in case a very large number of
1168 // runtime checks needs to be generated.
1169 // TODO: Skip cutoff if the loop is guaranteed to execute, e.g. due to
1170 // profile info.
1171 CostTooHigh = LAI && LAI->getNumRuntimePointerChecks() >
1173 if (CostTooHigh) {
1174 // Mark runtime checks as never succeeding when they exceed the threshold.
1175 MemRuntimeCheckCond = ConstantInt::getTrue(L->getHeader()->getContext());
1176 SCEVCheckCond = ConstantInt::getTrue(L->getHeader()->getContext());
1177 ORE.emit([&]() {
1178 return OptimizationRemarkAnalysisAliasing(
1179 DEBUG_TYPE, "TooManyMemoryRuntimeChecks", L->getStartLoc(),
1180 L->getHeader())
1181 << "loop not vectorized: too many memory checks needed";
1182 });
1183 LLVM_DEBUG(dbgs() << "LV: Too many memory checks needed.\n");
1184 return;
1185 }
1186
1187 BasicBlock *LoopHeader = L->getHeader();
1188 BasicBlock *Preheader = L->getLoopPreheader();
1189
1190 // Use SplitBlock to create blocks for SCEV & memory runtime checks to
1191 // ensure the blocks are properly added to LoopInfo & DominatorTree. Those
1192 // may be used by SCEVExpander. The blocks will be un-linked from their
1193 // predecessors and removed from LI & DT at the end of the function.
1194 if (!UnionPred.isAlwaysTrue()) {
1195 SCEVCheckBlock = SplitBlock(Preheader, Preheader->getTerminator(), DT, LI,
1196 nullptr, "vector.scevcheck");
1197
1198 SCEVCheckCond = SCEVExp.expandCodeForPredicate(
1199 &UnionPred, SCEVCheckBlock->getTerminator());
1200 if (isa<Constant>(SCEVCheckCond)) {
1201 // Clean up directly after expanding the predicate to a constant, to
1202 // avoid further expansions re-using anything left over from SCEVExp.
1203 SCEVExpanderCleaner SCEVCleaner(SCEVExp);
1204 SCEVCleaner.cleanup();
1205 }
1206 }
1207
1208 // TODO: We need to estimate the cost of alias-masking in
1209 // GeneratedRTChecks::getCost(). We can't check the MemCheckBlock as the
1210 // alias-mask is generated later in VPlan.
1211 if (LAI && LAI->getRuntimePointerChecking()->Need &&
1212 !LoopUsesPartialAliasMasking) {
1213 const auto &RtPtrChecking = *LAI->getRuntimePointerChecking();
1214 auto *Pred = SCEVCheckBlock ? SCEVCheckBlock : Preheader;
1215 MemCheckBlock = SplitBlock(Pred, Pred->getTerminator(), DT, LI, nullptr,
1216 "vector.memcheck");
1217
1218 auto DiffChecks = RtPtrChecking.getDiffChecks();
1219 if (DiffChecks) {
1220 MemRuntimeCheckCond = addDiffRuntimeChecks(
1221 MemCheckBlock->getTerminator(), *DiffChecks, MemCheckExp, VF, IC);
1222 } else {
1223 MemRuntimeCheckCond = addRuntimeChecks(
1224 MemCheckBlock->getTerminator(), L, RtPtrChecking.getChecks(),
1226 }
1227 assert(MemRuntimeCheckCond &&
1228 "no RT checks generated although RtPtrChecking "
1229 "claimed checks are required");
1230 }
1231
1232 SCEVExp.eraseDeadInstructions(SCEVCheckCond);
1233 HasChecks = getSCEVChecks().first || getMemRuntimeChecks().first;
1234
1235 if (!MemCheckBlock && !SCEVCheckBlock)
1236 return;
1237
1238 // Unhook the temporary block with the checks, update various places
1239 // accordingly.
1240 if (SCEVCheckBlock)
1241 SCEVCheckBlock->replaceAllUsesWith(Preheader);
1242 if (MemCheckBlock)
1243 MemCheckBlock->replaceAllUsesWith(Preheader);
1244
1245 if (SCEVCheckBlock) {
1246 SCEVCheckBlock->getTerminator()->moveBefore(
1247 Preheader->getTerminator()->getIterator());
1248 auto *UI = new UnreachableInst(Preheader->getContext(), SCEVCheckBlock);
1249 UI->setDebugLoc(DebugLoc::getTemporary());
1250 Preheader->getTerminator()->eraseFromParent();
1251 }
1252 if (MemCheckBlock) {
1253 MemCheckBlock->getTerminator()->moveBefore(
1254 Preheader->getTerminator()->getIterator());
1255 auto *UI = new UnreachableInst(Preheader->getContext(), MemCheckBlock);
1256 UI->setDebugLoc(DebugLoc::getTemporary());
1257 Preheader->getTerminator()->eraseFromParent();
1258 }
1259
1260 DT->changeImmediateDominator(LoopHeader, Preheader);
1261 if (MemCheckBlock) {
1262 DT->eraseNode(MemCheckBlock);
1263 LI->removeBlock(MemCheckBlock);
1264 }
1265 if (SCEVCheckBlock) {
1266 DT->eraseNode(SCEVCheckBlock);
1267 LI->removeBlock(SCEVCheckBlock);
1268 }
1269
1270 // Clean up directly if the memory checks folded to false, to avoid further
1271 // expansions re-using anything left over from MemCheckExp.
1272 if (MemCheckBlock && !getMemRuntimeChecks().first)
1273 eraseMemCheckBlock();
1274
1275 // Outer loop is used as part of the later cost calculations.
1276 OuterLoop = L->getParentLoop();
1277 }
1278
1280 if (SCEVCheckBlock || MemCheckBlock)
1281 LLVM_DEBUG(dbgs() << "Calculating cost of runtime checks:\n");
1282
1283 if (CostTooHigh) {
1285 Cost.setInvalid();
1286 LLVM_DEBUG(dbgs() << " number of checks exceeded threshold\n");
1287 return Cost;
1288 }
1289
1290 InstructionCost RTCheckCost = 0;
1291 if (SCEVCheckBlock)
1292 for (Instruction &I : *SCEVCheckBlock) {
1293 if (SCEVCheckBlock->getTerminator() == &I)
1294 continue;
1295 InstructionCost C = TTI->getInstructionCost(&I, CostKind);
1296 LLVM_DEBUG(dbgs() << " " << C << " for " << I << "\n");
1297 RTCheckCost += C;
1298 }
1299 if (MemCheckBlock) {
1300 InstructionCost MemCheckCost = 0;
1301 for (Instruction &I : *MemCheckBlock) {
1302 if (MemCheckBlock->getTerminator() == &I)
1303 continue;
1304 InstructionCost C = TTI->getInstructionCost(&I, CostKind);
1305 LLVM_DEBUG(dbgs() << " " << C << " for " << I << "\n");
1306 MemCheckCost += C;
1307 }
1308
1309 // If the runtime memory checks are being created inside an outer loop
1310 // we should find out if these checks are outer loop invariant. If so,
1311 // the checks will likely be hoisted out and so the effective cost will
1312 // reduce according to the outer loop trip count.
1313 if (OuterLoop) {
1314 ScalarEvolution *SE = MemCheckExp.getSE();
1315 // TODO: If profitable, we could refine this further by analysing every
1316 // individual memory check, since there could be a mixture of loop
1317 // variant and invariant checks that mean the final condition is
1318 // variant.
1319 const SCEV *Cond = SE->getSCEV(MemRuntimeCheckCond);
1320 if (SE->isLoopInvariant(Cond, OuterLoop)) {
1321 // It seems reasonable to assume that we can reduce the effective
1322 // cost of the checks even when we know nothing about the trip
1323 // count. Assume that the outer loop executes at least twice.
1324 unsigned BestTripCount = 2;
1325
1326 // Get the best known TC estimate.
1327 if (auto EstimatedTC = getSmallBestKnownTC(
1328 Opts, PSE, OuterLoop, /* CanUseConstantMax = */ false))
1329 if (EstimatedTC->isFixed())
1330 BestTripCount = EstimatedTC->getFixedValue();
1331
1332 InstructionCost NewMemCheckCost = MemCheckCost / BestTripCount;
1333
1334 // Let's ensure the cost is always at least 1.
1335 NewMemCheckCost = std::max(NewMemCheckCost, InstructionCost(1));
1336
1337 if (BestTripCount > 1)
1339 << "We expect runtime memory checks to be hoisted "
1340 << "out of the outer loop. Cost reduced from "
1341 << MemCheckCost << " to " << NewMemCheckCost << '\n');
1342
1343 MemCheckCost = NewMemCheckCost;
1344 }
1345 }
1346
1347 RTCheckCost += MemCheckCost;
1348 }
1349
1350 if (SCEVCheckBlock || MemCheckBlock)
1351 LLVM_DEBUG(dbgs() << "Total cost of runtime checks: " << RTCheckCost
1352 << "\n");
1353
1354 return RTCheckCost;
1355 }
1356
1357 /// Remove the created SCEV & memory runtime check blocks & instructions, if
1358 /// unused.
1359 ~GeneratedRTChecks() {
1360 SCEVExpanderCleaner SCEVCleaner(SCEVExp);
1361 bool SCEVChecksUsed = !SCEVCheckBlock || !pred_empty(SCEVCheckBlock);
1362 if (SCEVChecksUsed)
1363 SCEVCleaner.markResultUsed();
1364
1365 if (MemCheckBlock && pred_empty(MemCheckBlock))
1366 eraseMemCheckBlock();
1367
1368 SCEVCleaner.cleanup();
1369
1370 if (!SCEVChecksUsed)
1371 SCEVCheckBlock->eraseFromParent();
1372 }
1373
1374 /// Retrieves the SCEVCheckCond and SCEVCheckBlock that were generated as IR
1375 /// outside VPlan.
1376 std::pair<Value *, BasicBlock *> getSCEVChecks() const {
1377 using namespace llvm::PatternMatch;
1378 if (!SCEVCheckCond || match(SCEVCheckCond, m_ZeroInt()))
1379 return {nullptr, nullptr};
1380
1381 return {SCEVCheckCond, SCEVCheckBlock};
1382 }
1383
1384 /// Retrieves the MemCheckCond and MemCheckBlock that were generated as IR
1385 /// outside VPlan.
1386 std::pair<Value *, BasicBlock *> getMemRuntimeChecks() const {
1387 using namespace llvm::PatternMatch;
1388 if (MemRuntimeCheckCond && match(MemRuntimeCheckCond, m_ZeroInt()))
1389 return {nullptr, nullptr};
1390 return {MemRuntimeCheckCond, MemCheckBlock};
1391 }
1392
1393 /// Return true if any runtime checks have been added
1394 bool hasChecks() const { return HasChecks; }
1395
1396 /// Erase the memory check block, its instructions and their SCEV expansions.
1397 void eraseMemCheckBlock() {
1398 SCEVExpanderCleaner MemCheckCleaner(MemCheckExp);
1399 auto &SE = *MemCheckExp.getSE();
1400 // Memory runtime check generation creates compares that use expanded
1401 // values. Remove them before running the SCEVExpanderCleaner.
1402 for (auto &I : make_early_inc_range(reverse(*MemCheckBlock))) {
1403 if (MemCheckExp.isInsertedInstruction(&I))
1404 continue;
1405 SE.forgetValue(&I);
1406 I.eraseFromParent();
1407 }
1408 MemCheckCleaner.cleanup();
1409 MemCheckBlock->eraseFromParent();
1410 MemCheckBlock = nullptr;
1411 MemRuntimeCheckCond = nullptr;
1412 }
1413};
1414} // namespace
1415
1417 return Style == TailFoldingStyle::Data ||
1419}
1420
1424
1425// Return true if \p OuterLp is an outer loop annotated with hints for explicit
1426// vectorization. The loop needs to be annotated with #pragma omp simd
1427// simdlen(#) or #pragma clang vectorize(enable) vectorize_width(#). If the
1428// vector length information is not provided, vectorization is not considered
1429// explicit. Interleave hints are not allowed either. These limitations will be
1430// relaxed in the future.
1431// Please, note that we are currently forced to abuse the pragma 'clang
1432// vectorize' semantics. This pragma provides *auto-vectorization hints*
1433// (i.e., LV must check that vectorization is legal) whereas pragma 'omp simd'
1434// provides *explicit vectorization hints* (LV can bypass legal checks and
1435// assume that vectorization is legal). However, both hints are implemented
1436// using the same metadata (llvm.loop.vectorize, processed by
1437// LoopVectorizeHints). This will be fixed in the future when the native IR
1438// representation for pragma 'omp simd' is introduced.
1439static bool isExplicitVecOuterLoop(const VectorizeOptions &Opts, Loop *OuterLp,
1441 assert(!OuterLp->isInnermost() && "This is not an outer loop");
1442 LoopVectorizeHints Hints(Opts, OuterLp, true /*DisableInterleaving*/, *ORE);
1443
1444 // Only outer loops with an explicit vectorization hint are supported.
1445 // Unannotated outer loops are ignored.
1447 return false;
1448
1449 if (!Hints.allowVectorization(OuterLp, true /*VectorizeOnlyWhenForced*/)) {
1450 LLVM_DEBUG(dbgs() << "LV: Loop hints prevent outer loop vectorization.\n");
1451 return false;
1452 }
1453
1454 if (Hints.getInterleave() > 1) {
1455 // TODO: Interleave support is future work.
1456 LLVM_DEBUG(dbgs() << "LV: Not vectorizing: Interleave is not supported for "
1457 "outer loops.\n");
1458 Hints.emitRemarkWithHints();
1459 return false;
1460 }
1461
1462 return true;
1463}
1464
1465static void collectSupportedLoops(const VectorizeOptions &Opts, Loop &L,
1468 // Collect inner loops and outer loops without irreducible control flow. For
1469 // now, only collect outer loops that have explicit vectorization hints. If we
1470 // are stress testing the VPlan H-CFG construction, we collect the outermost
1471 // loop of every loop nest.
1472 if (L.isInnermost() || Opts.vplan_build_outerloop_stress_test ||
1473 (Opts.enable_vplan_native_path &&
1474 isExplicitVecOuterLoop(Opts, &L, ORE))) {
1475 LoopBlocksRPO RPOT(&L);
1476 RPOT.perform(LI);
1478 V.push_back(&L);
1479 // TODO: Collect inner loops inside marked outer loops in case
1480 // vectorization fails for the outer loop. Do not invoke
1481 // 'containsIrreducibleCFG' again for inner loops when the outer loop is
1482 // already known to be reducible. We can use an inherited attribute for
1483 // that.
1484 return;
1485 }
1486 }
1487 for (Loop *InnerL : L)
1488 collectSupportedLoops(Opts, *InnerL, LI, ORE, V);
1489}
1490
1491//===----------------------------------------------------------------------===//
1492// Implementation of LoopVectorizationCostModel and LoopVectorizationPlanner.
1493//===----------------------------------------------------------------------===//
1494
1495/// For the given VF and UF and maximum trip count computed for the loop, return
1496/// whether the induction variable might overflow in the vectorized loop. If not,
1497/// then we know a runtime overflow check always evaluates to false and can be
1498/// removed.
1500 const VectorizeOptions &Opts, const LoopVectorizationCostModel *Cost,
1501 ElementCount VF, std::optional<unsigned> UF = std::nullopt) {
1502 // Always be conservative if we don't know the exact unroll factor.
1503 uint64_t MaxUF = UF ? *UF
1504 : std::max(Cost->TTI.getMaxInterleaveFactor(VF, false),
1505 Cost->TTI.getMaxInterleaveFactor(VF, true));
1506
1507 IntegerType *IdxTy = Cost->Legal->getWidestInductionType();
1508 APInt MaxUIntTripCount = IdxTy->getMask();
1509
1510 // We know the runtime overflow check is known false iff the (max) trip-count
1511 // is known and (max) trip-count + (VF * UF) does not overflow in the type of
1512 // the vector loop induction variable.
1513 if (std::optional<ElementCount> TC = getSmallBestKnownTC(
1514 Opts, Cost->PSE, Cost->TheLoop,
1515 /*CanUseConstantMax=*/true, /*CanExcludeZeroTrips=*/false,
1516 /*ComputeUpperBoundOnly=*/true)) {
1517 // Compute the maximum runtime values of VF and the trip count.
1518 std::optional<uint64_t> MaxStep =
1519 getMaxRuntimeElementCount(VF * MaxUF, *Cost->TheFunction);
1520 std::optional<uint64_t> MaxTC =
1521 getMaxRuntimeElementCount(*TC, *Cost->TheFunction);
1522 if (!MaxStep || !MaxTC)
1523 return false;
1524
1525 // Bail out if the maximum trip count is not representable in the induction
1526 // variable's type.
1527 if (MaxUIntTripCount.ult(*MaxTC))
1528 return false;
1529
1530 return (MaxUIntTripCount - *MaxTC).ugt(*MaxStep);
1531 }
1532
1533 return false;
1534}
1535
1536// Return whether we allow using masked interleave-groups (for dealing with
1537// strided loads/stores that reside in predicated blocks, or for dealing
1538// with gaps).
1539static bool useMaskedInterleavedAccesses(const VectorizeOptions &Opts,
1540 const TargetTransformInfo &TTI) {
1541 // If an override option has been passed in for interleaved accesses, use it.
1542 return valueOr(Opts.enable_masked_interleaved_mem_accesses,
1543 TTI.enableMaskedInterleavedAccessVectorization());
1544}
1545
1546/// Replace \p VPBB with a VPIRBasicBlock wrapping \p IRBB. All recipes from \p
1547/// VPBB are moved to the end of the newly created VPIRBasicBlock. All
1548/// predecessors and successors of VPBB, if any, are rewired to the new
1549/// VPIRBasicBlock. If \p VPBB may be unreachable, \p Plan must be passed.
1551 BasicBlock *IRBB,
1552 VPlan *Plan = nullptr) {
1553 if (!Plan)
1554 Plan = VPBB->getPlan();
1555 VPIRBasicBlock *IRVPBB = Plan->createEmptyVPIRBasicBlock(IRBB);
1556 auto IP = IRVPBB->begin();
1557 for (auto &R : make_early_inc_range(VPBB->phis()))
1558 R.moveBefore(IP);
1559
1560 for (auto &R :
1562 R.moveBefore(IRVPBB->end());
1563
1564 VPBlockUtils::reassociateBlocks(VPBB, IRVPBB);
1565 // VPBB is now dead and will be cleaned up when the plan gets destroyed.
1566 return IRVPBB;
1567}
1568
1569/// Knowing that loop \p L executes a single vector iteration, add instructions
1570/// that will get simplified and thus should not have any cost to \p
1571/// InstsToIgnore.
1574 SmallPtrSetImpl<Instruction *> &InstsToIgnore) {
1575 auto *Cmp = L->getLatchCmpInst();
1576 if (Cmp)
1577 InstsToIgnore.insert(Cmp);
1578 for (PHINode *IV : IL.keys()) {
1579 // The induction is free: a widened induction generates a vector phi with
1580 // its start value and an increment that is dead without a backedge.
1581 InstsToIgnore.insert(IV);
1582
1583 // Get next iteration value of the induction variable.
1584 Instruction *IVInst =
1585 cast<Instruction>(IV->getIncomingValueForBlock(L->getLoopLatch()));
1586 if (all_of(IVInst->users(),
1587 [&](const User *U) { return U == IV || U == Cmp; }))
1588 InstsToIgnore.insert(IVInst);
1589 }
1590}
1591
1592namespace {
1593
1594struct CSEDenseMapInfo {
1595 static bool canHandle(const Instruction *I) {
1598 }
1599
1600 static unsigned getHashValue(const Instruction *I) {
1601 assert(canHandle(I) && "Unknown instruction!");
1602 return hash_combine(I->getOpcode(),
1603 hash_combine_range(I->operand_values()));
1604 }
1605
1606 static bool isEqual(const Instruction *LHS, const Instruction *RHS) {
1607 return LHS->isIdenticalTo(RHS);
1608 }
1609};
1610
1611} // end anonymous namespace
1612
1613/// FIXME: This legacy common-subexpression-elimination routine is scheduled for
1614/// removal, in favor of the VPlan-based one.
1615static void legacyCSE(BasicBlock *BB) {
1616 // Perform simple cse.
1618 for (Instruction &In : llvm::make_early_inc_range(*BB)) {
1619 if (!CSEDenseMapInfo::canHandle(&In))
1620 continue;
1621
1622 // Check if we can replace this instruction with any of the
1623 // visited instructions.
1624 if (Instruction *V = CSEMap.lookup(&In)) {
1625 In.replaceAllUsesWith(V);
1626 In.eraseFromParent();
1627 continue;
1628 }
1629
1630 CSEMap[&In] = &In;
1631 }
1632}
1633
1634/// This function attempts to return a value that represents the ElementCount
1635/// at runtime. For fixed-width VFs we know this precisely at compile
1636/// time, but for scalable VFs we calculate it based on an estimate of the
1637/// vscale value.
1639 std::optional<unsigned> VScale) {
1640 unsigned EstimatedVF = VF.getKnownMinValue();
1641 if (VF.isScalable())
1642 if (VScale)
1643 EstimatedVF *= *VScale;
1644 assert(EstimatedVF >= 1 && "Estimated VF shouldn't be less than 1");
1645 return EstimatedVF;
1646}
1647
1648/// Returns the vector library variant function of \p CI usable at \p VF,
1649/// respecting \p MaskRequired, or nullptr if none is found: a mapping with
1650/// matching VF, masked if required, whose vector function is declared in the
1651/// module.
1653 bool MaskRequired,
1654 const TargetLibraryInfo *TLI) {
1655 if (!TLI || CI.isNoBuiltin())
1656 return nullptr;
1657 for (const VFInfo &Info : VFDatabase::getMappings(CI))
1658 if (Info.Shape.VF == VF && (!MaskRequired || Info.isMasked()))
1659 if (Function *F = CI.getModule()->getFunction(Info.VectorName))
1660 return F;
1661 return nullptr;
1662}
1663
1664/// Returns true iff \p CI has a library vector variant usable at \p VF.
1666 bool MaskRequired,
1667 const TargetLibraryInfo *TLI) {
1668 return getVectorLibraryVariantFor(CI, VF, MaskRequired, TLI) != nullptr;
1669}
1670
1673 ElementCount VF) const {
1674 Type *RetTy = CI->getType();
1676 for (auto &ArgOp : CI->args())
1677 Tys.push_back(ArgOp->getType());
1678
1679 InstructionCost ScalarCallCost = TTI.getCallInstrCost(
1680 CI->getCalledFunction(), RetTy, Tys, Config.CostKind);
1681
1682 // Cost of the scalar call (scalar VF) or its scalarization (vector VF). The
1683 // scalarization cost is only meaningful for fixed VFs.
1686 : ScalarCallCost * VF.getKnownMinValue() +
1687 getScalarizationOverhead(CI, VF);
1688
1689 // The call may be vectorized at this VF, via a vector intrinsic or a vector
1690 // library variant.
1692 Cost = std::min(Cost, getVectorIntrinsicCost(CI, VF));
1693
1694 if (Function *Variant =
1696 Cost = std::min(Cost,
1697 TTI.getCallInstrCost(
1698 /*F=*/nullptr, Variant->getReturnType(),
1699 Variant->getFunctionType()->params(), Config.CostKind));
1700
1701 return Cost;
1702}
1703
1705 if (VF.isScalar() || !canVectorizeTy(Ty))
1706 return Ty;
1707 return toVectorizedTy(Ty, VF);
1708}
1709
1712 ElementCount VF) const {
1714 assert(ID && "Expected intrinsic call!");
1715 Type *RetTy = maybeVectorizeType(CI->getType(), VF);
1716 FastMathFlags FMF;
1717 if (auto *FPMO = dyn_cast<FPMathOperator>(CI))
1718 FMF = FPMO->getFastMathFlags();
1719
1722 SmallVector<Type *> ParamTys;
1723 std::transform(FTy->param_begin(), FTy->param_end(),
1724 std::back_inserter(ParamTys),
1725 [&](Type *Ty) { return maybeVectorizeType(Ty, VF); });
1726
1727 IntrinsicCostAttributes CostAttrs(ID, RetTy, Arguments, ParamTys, FMF,
1730 return TTI.getIntrinsicInstrCost(CostAttrs, Config.CostKind);
1731}
1732
1733void LoopVectorizationCostModel::collectLoopScalars(ElementCount VF) {
1734 // We should not collect Scalars more than once per VF. Right now, this
1735 // function is called from collectUniformsAndScalars(), which already does
1736 // this check. Collecting Scalars for VF=1 does not make any sense.
1737 assert(VF.isVector() && !Scalars.contains(VF) &&
1738 "This function should not be visited twice for the same VF");
1739
1740 // This avoids any chances of creating a REPLICATE recipe during planning
1741 // since that would result in generation of scalarized code during execution,
1742 // which is not supported for scalable vectors.
1743 if (VF.isScalable()) {
1744 Scalars[VF].insert_range(Uniforms[VF]);
1745 return;
1746 }
1747
1749
1750 // These sets are used to seed the analysis with pointers used by memory
1751 // accesses that will remain scalar.
1753 SmallPtrSet<Instruction *, 8> PossibleNonScalarPtrs;
1754 auto *Latch = TheLoop->getLoopLatch();
1755
1756 // A helper that returns true if the use of Ptr by MemAccess will be scalar.
1757 // The pointer operands of loads and stores will be scalar as long as the
1758 // memory access is not a gather/scatter or histogram operation. The value
1759 // operand of a store will remain scalar if the store is scalarized.
1760 auto IsScalarUse = [&](Instruction *MemAccess, Value *Ptr) {
1761 InstWidening WideningDecision = getWideningDecision(MemAccess, VF);
1762 assert(WideningDecision != CM_Unknown &&
1763 "Widening decision should be ready at this moment");
1764 auto *Store = dyn_cast<StoreInst>(MemAccess);
1765 if (Store && Ptr == Store->getValueOperand())
1766 return WideningDecision == CM_Scalarize;
1767 assert(Ptr == getLoadStorePointerOperand(MemAccess) &&
1768 "Ptr is neither a value or pointer operand");
1769 return WideningDecision != CM_GatherScatter &&
1771 };
1772
1773 // A helper that returns true if the given value is a getelementptr
1774 // instruction contained in the loop.
1775 auto IsLoopVaryingGEP = [&](Value *V) {
1776 return isa<GetElementPtrInst>(V) && !TheLoop->isLoopInvariant(V);
1777 };
1778
1779 // A helper that evaluates a memory access's use of a pointer. If the use will
1780 // be a scalar use and the pointer is only used by memory accesses, we place
1781 // the pointer in ScalarPtrs. Otherwise, the pointer is placed in
1782 // PossibleNonScalarPtrs.
1783 auto EvaluatePtrUse = [&](Instruction *MemAccess, Value *Ptr) {
1784 // We only care about bitcast and getelementptr instructions contained in
1785 // the loop.
1786 if (!IsLoopVaryingGEP(Ptr))
1787 return;
1788
1789 // If the pointer has already been identified as scalar (e.g., if it was
1790 // also identified as uniform), there's nothing to do.
1791 auto *I = cast<Instruction>(Ptr);
1792 if (Worklist.count(I))
1793 return;
1794
1795 // If the use of the pointer will be a scalar use, and all users of the
1796 // pointer are memory accesses, place the pointer in ScalarPtrs. Otherwise,
1797 // place the pointer in PossibleNonScalarPtrs.
1798 if (IsScalarUse(MemAccess, Ptr) &&
1800 ScalarPtrs.insert(I);
1801 else
1802 PossibleNonScalarPtrs.insert(I);
1803 };
1804
1805 // We seed the scalars analysis with three classes of instructions: (1)
1806 // instructions marked uniform-after-vectorization and (2) bitcast,
1807 // getelementptr and (pointer) phi instructions used by memory accesses
1808 // requiring a scalar use.
1809 //
1810 // (1) Add to the worklist all instructions that have been identified as
1811 // uniform-after-vectorization.
1812 Worklist.insert_range(Uniforms[VF]);
1813
1814 // (2) Add to the worklist all bitcast and getelementptr instructions used by
1815 // memory accesses requiring a scalar use. The pointer operands of loads and
1816 // stores will be scalar unless the operation is a gather or scatter.
1817 // The value operand of a store will remain scalar if the store is scalarized.
1818 for (auto *BB : TheLoop->blocks())
1819 for (auto &I : *BB) {
1820 if (auto *Load = dyn_cast<LoadInst>(&I)) {
1821 EvaluatePtrUse(Load, Load->getPointerOperand());
1822 } else if (auto *Store = dyn_cast<StoreInst>(&I)) {
1823 EvaluatePtrUse(Store, Store->getPointerOperand());
1824 EvaluatePtrUse(Store, Store->getValueOperand());
1825 }
1826 }
1827 for (auto *I : ScalarPtrs)
1828 if (!PossibleNonScalarPtrs.count(I)) {
1829 LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *I << "\n");
1830 Worklist.insert(I);
1831 }
1832
1833 // Insert the forced scalars.
1834 // FIXME: Currently VPWidenPHIRecipe() often creates a dead vector
1835 // induction variable when the PHI user is scalarized.
1836 auto ForcedScalar = ForcedScalars.find(VF);
1837 if (ForcedScalar != ForcedScalars.end())
1838 for (auto *I : ForcedScalar->second) {
1839 LLVM_DEBUG(dbgs() << "LV: Found (forced) scalar instruction: " << *I << "\n");
1840 Worklist.insert(I);
1841 }
1842
1843 // Expand the worklist by looking through any bitcasts and getelementptr
1844 // instructions we've already identified as scalar. This is similar to the
1845 // expansion step in collectLoopUniforms(); however, here we're only
1846 // expanding to include additional bitcasts and getelementptr instructions.
1847 unsigned Idx = 0;
1848 while (Idx != Worklist.size()) {
1849 Instruction *Dst = Worklist[Idx++];
1850 if (!IsLoopVaryingGEP(Dst->getOperand(0)))
1851 continue;
1852 auto *Src = cast<Instruction>(Dst->getOperand(0));
1853 if (llvm::all_of(Src->users(), [&](User *U) -> bool {
1854 auto *J = cast<Instruction>(U);
1855 return !TheLoop->contains(J) || Worklist.count(J) ||
1856 ((isa<LoadInst>(J) || isa<StoreInst>(J)) &&
1857 IsScalarUse(J, Src));
1858 })) {
1859 Worklist.insert(Src);
1860 LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *Src << "\n");
1861 }
1862 }
1863
1864 // An induction variable will remain scalar if all users of the induction
1865 // variable and induction variable update remain scalar.
1866 for (const auto &Induction : Legal->getInductionVars()) {
1867 auto *Ind = Induction.first;
1868 auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
1869
1870 // If tail-folding is applied, the primary induction variable will be used
1871 // to feed a vector compare.
1872 if (Ind == Legal->getPrimaryInduction() && foldTailByMasking())
1873 continue;
1874
1875 // Returns true if \p Indvar is a pointer induction that is used directly by
1876 // load/store instruction \p I.
1877 auto IsDirectLoadStoreFromPtrIndvar = [&](Instruction *Indvar,
1878 Instruction *I) {
1879 return Induction.second.getKind() ==
1882 Indvar == getLoadStorePointerOperand(I) && IsScalarUse(I, Indvar);
1883 };
1884
1885 // Determine if all users of the induction variable are scalar after
1886 // vectorization.
1887 bool ScalarInd = all_of(Ind->users(), [&](User *U) -> bool {
1888 auto *I = cast<Instruction>(U);
1889 return I == IndUpdate || !TheLoop->contains(I) || Worklist.count(I) ||
1890 IsDirectLoadStoreFromPtrIndvar(Ind, I);
1891 });
1892 if (!ScalarInd)
1893 continue;
1894
1895 // If the induction variable update is a fixed-order recurrence, neither the
1896 // induction variable or its update should be marked scalar after
1897 // vectorization.
1898 auto *IndUpdatePhi = dyn_cast<PHINode>(IndUpdate);
1899 if (IndUpdatePhi && Legal->isFixedOrderRecurrence(IndUpdatePhi))
1900 continue;
1901
1902 // Determine if all users of the induction variable update instruction are
1903 // scalar after vectorization.
1904 bool ScalarIndUpdate = all_of(IndUpdate->users(), [&](User *U) -> bool {
1905 auto *I = cast<Instruction>(U);
1906 return I == Ind || !TheLoop->contains(I) || Worklist.count(I) ||
1907 IsDirectLoadStoreFromPtrIndvar(IndUpdate, I);
1908 });
1909 if (!ScalarIndUpdate)
1910 continue;
1911
1912 // The induction variable and its update instruction will remain scalar.
1913 Worklist.insert(Ind);
1914 Worklist.insert(IndUpdate);
1915 LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *Ind << "\n");
1916 LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *IndUpdate
1917 << "\n");
1918 }
1919
1920 Scalars[VF].insert_range(Worklist);
1921}
1922
1930
1932 ElementCount VF) const {
1934 return Config.isLegalGatherOrScatter(isa<LoadInst>(I), getLoadStoreType(I),
1936}
1937
1939 ElementCount VF) {
1940 if (!isPredicatedInst(I))
1941 return false;
1942
1943 // Do we have a non-scalar lowering for this predicated
1944 // instruction? No - it is scalar with predication.
1945 switch(I->getOpcode()) {
1946 default:
1947 return true;
1948 case Instruction::Call: {
1949 if (VF.isScalar())
1950 return true;
1951 auto *CI = cast<CallInst>(I);
1952 // A vector intrinsic or library variant lowering avoids scalarization.
1953 return !getVectorIntrinsicIDForCall(CI, TLI) &&
1955 }
1956 case Instruction::Load:
1957 case Instruction::Store: {
1958 Type *ScalarTy = getLoadStoreType(I);
1960 if (Legal->isCompressedLoadOrStore(I))
1961 return false; // We can't scalarize compressed loads/stores.
1962 bool IsConsecutive = Legal->isConsecutivePtr(ScalarTy, Ptr);
1963 return !(IsConsecutive && isLegalMaskedLoadOrStore(I, VF)) &&
1965 }
1966 case Instruction::UDiv:
1967 case Instruction::SDiv:
1968 case Instruction::SRem:
1969 case Instruction::URem: {
1970 // We have the option to use the llvm.masked.udiv intrinsics to avoid
1971 // predication. The cost based decision here will always select the masked
1972 // intrinsics for scalable vectors as scalarization isn't legal.
1973 const auto [ScalarCost, MaskedCost] = getDivRemSpeculationCost(I, VF);
1974 return isDivRemScalarWithPredication(ScalarCost, MaskedCost);
1975 }
1976 }
1977}
1978
1980 return Legal->isMaskRequired(I, foldTailByMasking());
1981}
1982
1983// TODO: Fold into LoopVectorizationLegality::isMaskRequired.
1985 // TODO: We can use the loop-preheader as context point here and get
1986 // context sensitive reasoning for isSafeToSpeculativelyExecute.
1990 return false;
1991
1992 // If the instruction was executed conditionally in the original scalar loop,
1993 // predication is needed with a mask whose lanes are all possibly inactive.
1994 if (Legal->blockNeedsPredication(I->getParent()))
1995 return true;
1996
1997 // If we're not folding the tail by masking and not vectorizing a loop with
1998 // uncountable exits and side effects, predication is unnecessary.
1999 if (!foldTailByMasking() && !Legal->hasUncountableExitWithSideEffects())
2000 return false;
2001
2002 // All that remain are instructions with side-effects originally executed in
2003 // the loop unconditionally, but now execute under a tail-fold mask (only)
2004 // having at least one active lane (the first). If the side-effects of the
2005 // instruction are invariant, executing it w/o (the tail-folding) mask is safe
2006 // - it will cause the same side-effects as when masked.
2007 switch(I->getOpcode()) {
2008 default:
2010 "instruction should have been considered by earlier checks");
2011 case Instruction::Call:
2012 // Side-effects of a Call are assumed to be non-invariant, needing a
2013 // (fold-tail) mask.
2015 "should have returned earlier for calls not needing a mask");
2016 return true;
2017 case Instruction::Load:
2018 // If the address is loop invariant no predication is needed.
2019 return !Legal->isInvariant(getLoadStorePointerOperand(I));
2020 case Instruction::Store: {
2021 // For stores, we need to prove both speculation safety (which follows from
2022 // the same argument as loads), but also must prove the value being stored
2023 // is correct. The easiest form of the later is to require that all values
2024 // stored are the same.
2025 return !(Legal->isInvariant(getLoadStorePointerOperand(I)) &&
2026 TheLoop->isLoopInvariant(cast<StoreInst>(I)->getValueOperand()));
2027 }
2028 case Instruction::UDiv:
2029 case Instruction::URem:
2030 // If the divisor is loop-invariant no predication is needed.
2031 return !Legal->isInvariant(I->getOperand(1));
2032 case Instruction::SDiv:
2033 case Instruction::SRem:
2034 // Conservative for now, since masked-off lanes may be poison and could
2035 // trigger signed overflow.
2036 return true;
2037 }
2038}
2039
2041 TargetTransformInfo::TargetCostKind CostKind, const BasicBlock *BB) {
2042 if (CostKind == TTI::TCK_CodeSize)
2043 return 1;
2044 // If the block wasn't originally predicated then return early to avoid
2045 // computing BlockFrequencyInfo unnecessarily.
2046 if (!Legal->blockNeedsPredication(BB))
2047 return 1;
2048
2049 uint64_t HeaderFreq =
2050 getBFI().getBlockFreq(TheLoop->getHeader()).getFrequency();
2051 uint64_t BBFreq = getBFI().getBlockFreq(BB).getFrequency();
2052 assert(HeaderFreq >= BBFreq &&
2053 "Header has smaller block freq than dominated BB?");
2054 return std::round((double)HeaderFreq / BBFreq);
2055}
2056
2058 switch (Opcode) {
2059 case Instruction::UDiv:
2060 return Intrinsic::masked_udiv;
2061 case Instruction::SDiv:
2062 return Intrinsic::masked_sdiv;
2063 case Instruction::URem:
2064 return Intrinsic::masked_urem;
2065 case Instruction::SRem:
2066 return Intrinsic::masked_srem;
2067 default:
2068 llvm_unreachable("Unexpected opcode");
2069 }
2070}
2071
2072std::pair<InstructionCost, InstructionCost>
2074 ElementCount VF) {
2075 assert(I->getOpcode() == Instruction::UDiv ||
2076 I->getOpcode() == Instruction::SDiv ||
2077 I->getOpcode() == Instruction::SRem ||
2078 I->getOpcode() == Instruction::URem);
2080
2081 // Scalarization isn't legal for scalable vector types
2082 InstructionCost ScalarizationCost = InstructionCost::getInvalid();
2083 if (!VF.isScalable()) {
2084 // Get the scalarization cost and scale this amount by the probability of
2085 // executing the predicated block. If the instruction is not predicated,
2086 // we fall through to the next case.
2087 ScalarizationCost = 0;
2088
2089 // These instructions have a non-void type, so account for the phi nodes
2090 // that we will create. This cost is likely to be zero. The phi node
2091 // cost, if any, should be scaled by the block probability because it
2092 // models a copy at the end of each predicated block.
2093 ScalarizationCost += VF.getFixedValue() *
2094 TTI.getCFInstrCost(Instruction::PHI, Config.CostKind);
2095
2096 // The cost of the non-predicated instruction.
2097 ScalarizationCost +=
2098 VF.getFixedValue() * TTI.getArithmeticInstrCost(
2099 I->getOpcode(), I->getType(), Config.CostKind);
2100
2101 // The cost of insertelement and extractelement instructions needed for
2102 // scalarization.
2103 ScalarizationCost += getScalarizationOverhead(I, VF);
2104
2105 // Scale the cost by the probability of executing the predicated blocks.
2106 // This assumes the predicated block for each vector lane is equally
2107 // likely.
2108 ScalarizationCost =
2109 ScalarizationCost /
2110 getPredBlockCostDivisor(Config.CostKind, I->getParent());
2111 }
2112
2113 auto *VecTy = toVectorTy(I->getType(), VF);
2114 auto *MaskTy = toVectorTy(Type::getInt1Ty(I->getContext()), VF);
2115 IntrinsicCostAttributes ICA(getMaskedDivRemIntrinsic(I->getOpcode()), VecTy,
2116 {VecTy, VecTy, MaskTy});
2117 InstructionCost MaskedCost = TTI.getIntrinsicInstrCost(ICA, Config.CostKind);
2118 return {ScalarizationCost, MaskedCost};
2119}
2120
2122 Instruction *I, ElementCount VF) const {
2123 assert(isAccessInterleaved(I) && "Expecting interleaved access.");
2125 "Decision should not be set yet.");
2126 auto *Group = getInterleavedAccessGroup(I);
2127 assert(Group && "Must have a group.");
2128 unsigned InterleaveFactor = Group->getFactor();
2129
2130 // If the instruction's allocated size doesn't equal its type size, it
2131 // requires padding and will be scalarized.
2132 auto &DL = I->getDataLayout();
2133 auto *ScalarTy = getLoadStoreType(I);
2134 if (hasIrregularType(ScalarTy, DL))
2135 return false;
2136
2137 // For scalable vectors, the interleave factors must be <= 8 since we require
2138 // the (de)interleaveN intrinsics instead of shufflevectors.
2139 if (VF.isScalable() && InterleaveFactor > 8)
2140 return false;
2141
2142 // If the group involves a non-integral pointer, we may not be able to
2143 // losslessly cast all values to a common type.
2144 bool ScalarNI = DL.isNonIntegralPointerType(ScalarTy);
2145 for (Instruction *Member : Group->members()) {
2146 auto *MemberTy = getLoadStoreType(Member);
2147 bool MemberNI = DL.isNonIntegralPointerType(MemberTy);
2148 // Don't coerce non-integral pointers to integers or vice versa.
2149 if (MemberNI != ScalarNI)
2150 // TODO: Consider adding special nullptr value case here
2151 return false;
2152 if (MemberNI && ScalarNI &&
2153 ScalarTy->getPointerAddressSpace() !=
2154 MemberTy->getPointerAddressSpace())
2155 return false;
2156 }
2157
2158 // Check if masking is required.
2159 // A Group may need masking for one of two reasons: it resides in a block that
2160 // needs predication, or it was decided to use masking to deal with gaps
2161 // (either a gap at the end of a load-access that may result in a speculative
2162 // load, or any gaps in a store-access).
2163 bool PredicatedAccessRequiresMasking =
2165 bool LoadAccessWithGapsRequiresEpilogMasking =
2166 isa<LoadInst>(I) && Group->requiresScalarEpilogue() &&
2168 bool StoreAccessWithGapsRequiresMasking =
2169 isa<StoreInst>(I) && !Group->isFull();
2170 if (!PredicatedAccessRequiresMasking &&
2171 !LoadAccessWithGapsRequiresEpilogMasking &&
2172 !StoreAccessWithGapsRequiresMasking)
2173 return true;
2174
2175 // If masked interleaving is required, we expect that the user/target had
2176 // enabled it, because otherwise it either wouldn't have been created or
2177 // it should have been invalidated by the CostModel.
2179 "Masked interleave-groups for predicated accesses are not enabled.");
2180
2181 if (Group->isReverse())
2182 return false;
2183
2184 // TODO: Support interleaved access that requires a gap mask for scalable VFs.
2185 bool NeedsMaskForGaps = LoadAccessWithGapsRequiresEpilogMasking ||
2186 StoreAccessWithGapsRequiresMasking;
2187 if (VF.isScalable() && NeedsMaskForGaps)
2188 return false;
2189
2190 return isLegalMaskedLoadOrStore(I, VF);
2191}
2192
2193std::optional<LoopVectorizationCostModel::InstWidening>
2195 ElementCount VF) {
2196 // Get and ensure we have a valid memory instruction.
2197 assert((isa<LoadInst, StoreInst>(I)) && "Invalid memory instruction");
2198
2199 auto *Ptr = getLoadStorePointerOperand(I);
2200 auto *ScalarTy = getLoadStoreType(I);
2201
2202 // In order to be widened, the pointer should be consecutive or compressed.
2203 int Stride = Legal->isConsecutivePtr(ScalarTy, Ptr);
2204
2205 // Check if the pointer is derived from a conditional induction PHI, which
2206 // can be widened as a compressstore/expandload.
2207 if (std::optional<CompressedPtrInfo> PtrInfo =
2208 Legal->getCompressedPtrInfo(Ptr)) {
2209 Stride = getStrideFromAddRec(PtrInfo->PtrSCEV, TheLoop, ScalarTy, Ptr, PSE)
2210 .value_or(0);
2211 assert(Stride == 1 && "Compressed memory ops must be consecutive");
2212 }
2213
2214 if (!Stride)
2215 return std::nullopt;
2216
2217 // If the instruction is a store located in a predicated block, it will be
2218 // scalarized.
2219 if (isScalarWithPredication(I, VF))
2220 return std::nullopt;
2221
2222 // If the instruction's allocated size doesn't equal it's type size, it
2223 // requires padding and will be scalarized.
2224 auto &DL = I->getDataLayout();
2225 if (hasIrregularType(ScalarTy, DL))
2226 return std::nullopt;
2227
2228 return Stride == 1 ? CM_Widen : CM_Widen_Reverse;
2229}
2230
2231void LoopVectorizationCostModel::collectLoopUniforms(ElementCount VF) {
2232 // We should not collect Uniforms more than once per VF. Right now,
2233 // this function is called from collectUniformsAndScalars(), which
2234 // already does this check. Collecting Uniforms for VF=1 does not make any
2235 // sense.
2236
2237 assert(VF.isVector() && !Uniforms.contains(VF) &&
2238 "This function should not be visited twice for the same VF");
2239
2240 // Visit the list of Uniforms. If we find no uniform value, we won't
2241 // analyze again. Uniforms.count(VF) will return 1.
2242 Uniforms[VF].clear();
2243
2244 // Now we know that the loop is vectorizable!
2245 // Collect instructions inside the loop that will remain uniform after
2246 // vectorization.
2247
2248 // Global values, params and instructions outside of current loop are out of
2249 // scope.
2250 auto IsOutOfScope = [&](Value *V) -> bool {
2252 return (!I || !TheLoop->contains(I));
2253 };
2254
2255 // Worklist containing uniform instructions demanding lane 0.
2256 SetVector<Instruction *> Worklist;
2257
2258 // Add uniform instructions demanding lane 0 to the worklist. Instructions
2259 // that require predication must not be considered uniform after
2260 // vectorization, because that would create an erroneous replicating region
2261 // where only a single instance out of VF should be formed.
2262 auto AddToWorklistIfAllowed = [&](Instruction *I) -> void {
2263 if (IsOutOfScope(I)) {
2264 LLVM_DEBUG(dbgs() << "LV: Found not uniform due to scope: "
2265 << *I << "\n");
2266 return;
2267 }
2268 if (isPredicatedInst(I)) {
2269 LLVM_DEBUG(
2270 dbgs() << "LV: Found not uniform due to requiring predication: " << *I
2271 << "\n");
2272 return;
2273 }
2274 LLVM_DEBUG(dbgs() << "LV: Found uniform instruction: " << *I << "\n");
2275 Worklist.insert(I);
2276 };
2277
2278 // Start with the conditional branches exiting the loop. If the branch
2279 // condition is an instruction contained in the loop that is only used by the
2280 // branch, it is uniform. Note conditions from uncountable early exits are not
2281 // uniform.
2283 TheLoop->getExitingBlocks(Exiting);
2284 for (BasicBlock *E : Exiting) {
2285 if (Legal->hasUncountableEarlyExit() && TheLoop->getLoopLatch() != E)
2286 continue;
2287 auto *Cmp = dyn_cast<Instruction>(E->getTerminator()->getOperand(0));
2288 if (!Cmp || !TheLoop->contains(Cmp) || !Cmp->hasOneUse())
2289 continue;
2290
2291 // If we have an exit condition that is actually two conditions (one
2292 // countable and the other uncountable) combined via an or, only add the
2293 // countable comparison as a uniform value.
2294 if (Legal->hasUncountableExitWithSideEffects() &&
2295 TheLoop->getLoopLatch() == E) {
2296 if (Instruction *Countable =
2297 Legal->findCountableComparisonInCombinedCondition(Cmp)) {
2298 if (Countable->hasOneUse())
2299 AddToWorklistIfAllowed(Countable);
2300 continue;
2301 }
2302 }
2303
2304 // Normal exit comparisons are uniform.
2305 AddToWorklistIfAllowed(Cmp);
2306 }
2307
2308 auto PrevVF = VF.divideCoefficientBy(2);
2309 // Return true if all lanes perform the same memory operation, and we can
2310 // thus choose to execute only one.
2311 auto IsUniformMemOpUse = [&](Instruction *I) {
2312 // If the value was already known to not be uniform for the previous
2313 // (smaller VF), it cannot be uniform for the larger VF.
2314 if (PrevVF.isVector()) {
2315 auto Iter = Uniforms.find(PrevVF);
2316 if (Iter != Uniforms.end() && !Iter->second.contains(I))
2317 return false;
2318 }
2319 if (!isUniformMemOp(*I, VF))
2320 return false;
2321 if (isa<LoadInst>(I))
2322 // Loading the same address always produces the same result - at least
2323 // assuming aliasing and ordering which have already been checked.
2324 return true;
2325 // Storing the same value on every iteration.
2326 return TheLoop->isLoopInvariant(cast<StoreInst>(I)->getValueOperand());
2327 };
2328
2329 auto IsUniformDecision = [&](Instruction *I, ElementCount VF) {
2330 InstWidening WideningDecision = getWideningDecision(I, VF);
2331 assert(WideningDecision != CM_Unknown &&
2332 "Widening decision should be ready at this moment");
2333
2334 if (IsUniformMemOpUse(I))
2335 return true;
2336
2337 return (WideningDecision == CM_Widen ||
2338 WideningDecision == CM_Widen_Reverse ||
2339 WideningDecision == CM_Interleave);
2340 };
2341
2342 // Returns true if Ptr is the pointer operand of a memory access instruction
2343 // I, I is known to not require scalarization, and the pointer is not also
2344 // stored.
2345 auto IsVectorizedMemAccessUse = [&](Instruction *I, Value *Ptr) -> bool {
2346 if (isa<StoreInst>(I) && I->getOperand(0) == Ptr)
2347 return false;
2348 return getLoadStorePointerOperand(I) == Ptr &&
2349 (IsUniformDecision(I, VF) || Legal->isInvariant(Ptr));
2350 };
2351
2352 // Holds a list of values which are known to have at least one uniform use.
2353 // Note that there may be other uses which aren't uniform. A "uniform use"
2354 // here is something which only demands lane 0 of the unrolled iterations;
2355 // it does not imply that all lanes produce the same value (e.g. this is not
2356 // the usual meaning of uniform)
2357 SetVector<Value *> HasUniformUse;
2358
2359 // Scan the loop for instructions which are either a) known to have only
2360 // lane 0 demanded or b) are uses which demand only lane 0 of their operand.
2361 for (auto *BB : TheLoop->blocks())
2362 for (auto &I : *BB) {
2363 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I)) {
2364 switch (II->getIntrinsicID()) {
2365 case Intrinsic::sideeffect:
2366 case Intrinsic::experimental_noalias_scope_decl:
2367 case Intrinsic::assume:
2368 case Intrinsic::lifetime_start:
2369 case Intrinsic::lifetime_end:
2370 if (TheLoop->hasLoopInvariantOperands(&I))
2371 AddToWorklistIfAllowed(&I);
2372 break;
2373 default:
2374 break;
2375 }
2376 }
2377
2378 if (auto *EVI = dyn_cast<ExtractValueInst>(&I)) {
2379 if (IsOutOfScope(EVI->getAggregateOperand())) {
2380 AddToWorklistIfAllowed(EVI);
2381 continue;
2382 }
2383 // Only ExtractValue instructions where the aggregate value comes from a
2384 // call are allowed to be non-uniform.
2385 assert(isa<CallInst>(EVI->getAggregateOperand()) &&
2386 "Expected aggregate value to be call return value");
2387 }
2388
2389 // If there's no pointer operand, there's nothing to do.
2390 auto *Ptr = getLoadStorePointerOperand(&I);
2391 if (!Ptr)
2392 continue;
2393
2394 // If the pointer can be proven to be uniform, always add it to the
2395 // worklist.
2396 if (isa<Instruction>(Ptr) && isUniform(Ptr, VF))
2397 AddToWorklistIfAllowed(cast<Instruction>(Ptr));
2398
2399 if (IsUniformMemOpUse(&I))
2400 AddToWorklistIfAllowed(&I);
2401
2402 if (IsVectorizedMemAccessUse(&I, Ptr))
2403 HasUniformUse.insert(Ptr);
2404 }
2405
2406 // Add to the worklist any operands which have *only* uniform (e.g. lane 0
2407 // demanding) users. Since loops are assumed to be in LCSSA form, this
2408 // disallows uses outside the loop as well.
2409 for (auto *V : HasUniformUse) {
2410 if (IsOutOfScope(V))
2411 continue;
2412 auto *I = cast<Instruction>(V);
2413 bool UsersAreMemAccesses = all_of(I->users(), [&](User *U) -> bool {
2414 auto *UI = cast<Instruction>(U);
2415 return TheLoop->contains(UI) && IsVectorizedMemAccessUse(UI, V);
2416 });
2417 if (UsersAreMemAccesses)
2418 AddToWorklistIfAllowed(I);
2419 }
2420
2421 // Expand Worklist in topological order: whenever a new instruction
2422 // is added , its users should be already inside Worklist. It ensures
2423 // a uniform instruction will only be used by uniform instructions.
2424 unsigned Idx = 0;
2425 while (Idx != Worklist.size()) {
2426 Instruction *I = Worklist[Idx++];
2427
2428 for (auto *OV : I->operand_values()) {
2429 // isOutOfScope operands cannot be uniform instructions.
2430 if (IsOutOfScope(OV))
2431 continue;
2432 // First order recurrence Phi's should typically be considered
2433 // non-uniform.
2434 auto *OP = dyn_cast<PHINode>(OV);
2435 if (OP && Legal->isFixedOrderRecurrence(OP))
2436 continue;
2437 // If all the users of the operand are uniform, then add the
2438 // operand into the uniform worklist.
2439 auto *OI = cast<Instruction>(OV);
2440 if (llvm::all_of(OI->users(), [&](User *U) -> bool {
2441 auto *J = cast<Instruction>(U);
2442 return Worklist.count(J) || IsVectorizedMemAccessUse(J, OI);
2443 }))
2444 AddToWorklistIfAllowed(OI);
2445 }
2446 }
2447
2448 // For an instruction to be added into Worklist above, all its users inside
2449 // the loop should also be in Worklist. However, this condition cannot be
2450 // true for phi nodes that form a cyclic dependence. We must process phi
2451 // nodes separately. An induction variable will remain uniform if all users
2452 // of the induction variable and induction variable update remain uniform.
2453 // The code below handles both pointer and non-pointer induction variables.
2454 BasicBlock *Latch = TheLoop->getLoopLatch();
2455 for (PHINode *Ind : Legal->getInductionVars().keys()) {
2456 auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
2457
2458 // Determine if all users of the induction variable are uniform after
2459 // vectorization.
2460 bool UniformInd = all_of(Ind->users(), [&](User *U) -> bool {
2461 auto *I = cast<Instruction>(U);
2462 return I == IndUpdate || !TheLoop->contains(I) || Worklist.count(I) ||
2463 IsVectorizedMemAccessUse(I, Ind);
2464 });
2465 if (!UniformInd)
2466 continue;
2467
2468 // Determine if all users of the induction variable update instruction are
2469 // uniform after vectorization.
2470 bool UniformIndUpdate = all_of(IndUpdate->users(), [&](User *U) -> bool {
2471 auto *I = cast<Instruction>(U);
2472 return I == Ind || Worklist.count(I) ||
2473 IsVectorizedMemAccessUse(I, IndUpdate);
2474 });
2475 if (!UniformIndUpdate)
2476 continue;
2477
2478 // The induction variable and its update instruction will remain uniform.
2479 AddToWorklistIfAllowed(Ind);
2480 AddToWorklistIfAllowed(IndUpdate);
2481 }
2482
2483 Uniforms[VF].insert_range(Worklist);
2484}
2485
2488 // Make sure once we return PartialAliasMaskingStatus is not "NotDecided".
2489 scope_exit EnsureAliasMaskingStatusIsDecidedOnReturn([this] {
2490 if (PartialAliasMaskingStatus == AliasMaskingStatus::NotDecided)
2491 PartialAliasMaskingStatus = AliasMaskingStatus::Disabled;
2492 });
2493
2494 // For outer loops, use simple type-based heuristic VF. No cost model or
2495 // memory dependence analysis is available.
2496 if (!TheLoop->isInnermost()) {
2497 return Config.computeVPlanOuterloopVF(UserVF);
2498 }
2499
2500 if (Legal->getRuntimePointerChecking()->Need && TTI.hasBranchDivergence()) {
2501 // TODO: It may be useful to do since it's still likely to be dynamically
2502 // uniform if the target can skip.
2504 "Not inserting runtime ptr check for divergent target",
2505 "runtime pointer checks needed. Not enabled for divergent target",
2506 "CantVersionLoopWithDivergentTarget", ORE, TheLoop);
2508 }
2509
2510 ScalarEvolution *SE = PSE.getSE();
2512 unsigned MaxTC = PSE.getSmallConstantMaxTripCount();
2513 if (!MaxTC && EpilogueLoweringStatus == CM_EpilogueAllowed)
2515 LLVM_DEBUG(dbgs() << "LV: Found trip count: " << TC << '\n');
2516 if (TC != ElementCount::getFixed(MaxTC))
2517 LLVM_DEBUG(dbgs() << "LV: Found maximum trip count: " << MaxTC << '\n');
2518 if (TC.isScalar()) {
2520 "Single iteration (non) loop",
2521 "loop trip count is one, irrelevant for vectorization",
2522 "SingleIterationLoop", ORE, TheLoop);
2524 }
2525
2526 // If BTC matches the widest induction type and is -1 then the trip count
2527 // computation will wrap to 0 and the vector trip count will be 0. Do not try
2528 // to vectorize.
2529 const SCEV *BTC = SE->getBackedgeTakenCount(TheLoop);
2530 if (!isa<SCEVCouldNotCompute>(BTC) &&
2531 BTC->getType()->getScalarSizeInBits() >=
2532 Legal->getWidestInductionType()->getScalarSizeInBits() &&
2534 SE->getMinusOne(BTC->getType()))) {
2536 "Trip count computation wrapped",
2537 "backedge-taken count is -1, loop trip count wrapped to 0",
2538 "TripCountWrapped", ORE, TheLoop);
2540 }
2541
2542 assert(WideningDecisions.empty() && Uniforms.empty() && Scalars.empty() &&
2543 "No cost-modeling decisions should have been taken at this point");
2544
2545 switch (EpilogueLoweringStatus) {
2546 case CM_EpilogueAllowed:
2547 return Config.computeFeasibleMaxVF(MaxTC, UserVF, UserIC, false,
2550 [[fallthrough]];
2552 LLVM_DEBUG(dbgs() << "LV: tail-folding hint/switch found.\n"
2553 << "LV: Not allowing epilogue, creating tail-folded "
2554 << "vector loop.\n");
2555 break;
2557 LLVM_DEBUG(dbgs() << "LV: Not allowing epilogue due to low trip "
2558 << "count.\n");
2559 break;
2561 LLVM_DEBUG(dbgs() << "LV: Not allowing epilogue due to -Os/-Oz.\n");
2562
2563 // Bail if runtime checks are required, which are not good when optimising
2564 // for size.
2565 if (Config.runtimeChecksRequired())
2567
2568 break;
2569 }
2570
2571 // Now try the tail folding
2572
2573 // Invalidate interleave groups that require an epilogue if we can't mask
2574 // the interleave-group.
2575 if (!useMaskedInterleavedAccesses(Opts, TTI)) {
2576 // Note: There is no need to invalidate any cost modeling decisions here, as
2577 // none were taken so far (see assertion above).
2578 InterleaveInfo.invalidateGroupsRequiringScalarEpilogue();
2579 }
2580
2581 FixedScalableVFPair MaxFactors = Config.computeFeasibleMaxVF(
2582 MaxTC, UserVF, UserIC, true, requiresScalarEpilogue(true));
2583
2584 // Avoid tail folding if the trip count is known to be a multiple of any VF
2585 // we choose.
2586 std::optional<uint64_t> MaxPowerOf2RuntimeVF =
2587 MaxFactors.FixedVF.getFixedValue();
2588 if (MaxFactors.ScalableVF) {
2589 if (std::optional<uint64_t> MaxRuntimeScalableVF =
2591 MaxPowerOf2RuntimeVF =
2592 std::max(*MaxPowerOf2RuntimeVF, *MaxRuntimeScalableVF);
2593 else
2594 MaxPowerOf2RuntimeVF = std::nullopt; // Stick with tail-folding for now.
2595 }
2596
2597 // TODO: Make NoScalarEpilogueNeeded lambda a separate function to be used
2598 // only for main loop VF not also epilogueVF. Using it for epilogueVF against
2599 // full TC is inaccurate.
2600 auto NoScalarEpilogueNeeded = [this, &UserIC](uint64_t MaxRuntimeVF) {
2601 // Return false if the loop is neither a single-latch-exit loop nor an
2602 // early-exit loop as tail-folding is not supported in that case.
2603 if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch() &&
2604 !Legal->hasUncountableEarlyExit())
2605 return false;
2606 uint64_t MaxVFtimesIC = MaxRuntimeVF * std::max<uint64_t>(UserIC, 1);
2607 ScalarEvolution *SE = PSE.getSE();
2608 // Calling getSymbolicMaxBackedgeTakenCount enables support for loops
2609 // with uncountable exits. For countable loops, the symbolic maximum must
2610 // remain identical to the known back-edge taken count.
2611 const SCEV *BackedgeTakenCount = PSE.getSymbolicMaxBackedgeTakenCount();
2612 assert((Legal->hasUncountableEarlyExit() ||
2613 BackedgeTakenCount == PSE.getBackedgeTakenCount()) &&
2614 "Invalid loop count");
2615 const SCEV *ExitCount = SE->getAddExpr(
2616 BackedgeTakenCount, SE->getOne(BackedgeTakenCount->getType()));
2617 const SCEV *Rem = SE->getURemExpr(
2618 SE->applyLoopGuards(ExitCount, TheLoop),
2619 SE->getConstant(BackedgeTakenCount->getType(), MaxVFtimesIC));
2620 return Rem->isZero();
2621 };
2622
2623 if (MaxPowerOf2RuntimeVF > 0u) {
2624 assert((UserVF.isNonZero() || isPowerOf2_64(*MaxPowerOf2RuntimeVF)) &&
2625 "MaxFixedVF must be a power of 2");
2626 if (NoScalarEpilogueNeeded(*MaxPowerOf2RuntimeVF)) {
2627 // Accept MaxFixedVF if we do not have a tail.
2628 LLVM_DEBUG(dbgs() << "LV: No tail will remain for any chosen VF.\n");
2629 return MaxFactors;
2630 }
2631 }
2632
2633 auto ExpectedTC = getSmallBestKnownTC(Opts, PSE, TheLoop);
2634 if (ExpectedTC && ExpectedTC->isFixed() &&
2635 ExpectedTC->getFixedValue() <=
2636 TTI.getMinTripCountTailFoldingThreshold()) {
2637 // If we have a low-trip-count, or optimize for code size, and the
2638 // fixed-width VF is known to divide the trip count the fixed-width factor
2639 // in preference to allow the generation of a non-predicated loop.
2640 if ((EpilogueLoweringStatus == CM_EpilogueNotAllowedLowTripLoop ||
2641 EpilogueLoweringStatus == CM_EpilogueNotAllowedOptSize) &&
2642 NoScalarEpilogueNeeded(MaxFactors.FixedVF.getFixedValue())) {
2643 LLVM_DEBUG(dbgs() << "LV: Picking a fixed-width so that no tail will "
2644 "remain for any chosen VF.\n");
2645 MaxFactors.ScalableVF = ElementCount::getScalable(0);
2646 return MaxFactors;
2647 }
2648
2649 // Allow cases where the ExactTC == (VF * IC) + 1.
2650 //
2651 // This produces 1 vector iteration, and 1 scalar iteration with no
2652 // remainder. Later passes will eliminate the loop and leave straight-line
2653 // code as the both iteration counts are statically known.
2654 //
2655 // If a function is marked as minsize/optsize or OptForSize is set, do not
2656 // allow this form of transformation as this will increase CodeSize.
2657 //
2658 // For loops with small bodies, the cost model is not currently reliable
2659 // enough to accurately determine if vectorization is beneficial.
2660 unsigned EffectiveIC = UserIC > 0 ? UserIC : 1;
2661 unsigned MaxVFForTC = llvm::bit_floor(TC.getFixedValue());
2662 if (TC.getFixedValue() - MaxVFForTC == 1 && MaxVFForTC / EffectiveIC > 1 &&
2663 MaxVFForTC <= (MaxFactors.FixedVF.getFixedValue() * EffectiveIC) &&
2664 !Config.OptForSize) {
2665 unsigned NumOfInstructions = llvm::sum_of(
2666 llvm::map_range(TheLoop->blocks(),
2667 [](BasicBlock *BB) { return BB->size(); }),
2668 unsigned(0));
2669 if (NumOfInstructions > Opts.low_trip_count_loop_body_size_limit) {
2670 unsigned VF = MaxVFForTC / EffectiveIC;
2671 LLVM_DEBUG(dbgs() << "LV: Picking MaxVF=" << VF
2672 << " with 1 scalar iteration remaining.\n");
2673 MaxFactors.FixedVF = ElementCount::getFixed(VF);
2674 MaxFactors.ScalableVF = ElementCount::getScalable(0);
2675 return MaxFactors;
2676 }
2677 }
2678
2680 "The trip count is below the minial threshold value.",
2681 "loop trip count is too low, avoiding vectorization", "LowTripCount",
2682 ORE, TheLoop);
2684 }
2685
2686 // If we don't know the precise trip count, or if the trip count that we
2687 // found modulo the vectorization factor is not zero, try to fold the tail
2688 // by masking.
2689 // FIXME: look for a smaller MaxVF that does divide TC rather than masking.
2690 bool ContainsScalableVF = MaxFactors.ScalableVF.isNonZero();
2691 setTailFoldingStyle(ContainsScalableVF, UserIC);
2692 if (foldTailByMasking()) {
2693 if (foldTailWithEVL()) {
2694 LLVM_DEBUG(
2695 dbgs()
2696 << "LV: tail is folded with EVL, forcing unroll factor to be 1. Will "
2697 "try to generate VP Intrinsics with scalable vector "
2698 "factors only.\n");
2699 // Tail folded loop using VP intrinsics restricts the VF to be scalable
2700 // for now.
2701 // TODO: extend it for fixed vectors, if required.
2702 assert(ContainsScalableVF && "Expected scalable vector factor.");
2703
2704 MaxFactors.FixedVF = ElementCount::getFixed(1);
2705 } else {
2707 }
2708 return MaxFactors;
2709 }
2710
2711 // If there was a tail-folding hint/switch, but we can't fold the tail by
2712 // masking, fallback to a vectorization with an epilogue.
2713 if (EpilogueLoweringStatus == CM_EpilogueNotNeededFoldTail) {
2714 LLVM_DEBUG(dbgs() << "LV: Cannot fold tail by masking: vectorize with an "
2715 "epilogue instead.\n");
2716 EpilogueLoweringStatus = CM_EpilogueAllowed;
2717 return MaxFactors;
2718 }
2719
2720 if (EpilogueLoweringStatus == CM_EpilogueNotAllowedFoldTail) {
2721 LLVM_DEBUG(dbgs() << "LV: Can't fold tail by masking: don't vectorize\n");
2723 }
2724
2725 if (TC.isZero()) {
2727 "unable to calculate the loop count due to complex control flow",
2728 "UnknownLoopCountComplexCFG", ORE, TheLoop);
2730 }
2731
2733 "Cannot optimize for size and vectorize at the same time.",
2734 "cannot optimize for size and vectorize at the same time. "
2735 "Enable vectorization of this loop with '#pragma clang loop "
2736 "vectorize(enable)' when compiling with -Os/-Oz",
2737 "NoTailLoopWithOptForSize", ORE, TheLoop);
2739}
2740
2743 using RecipeVFPair = std::pair<VPRecipeBase *, ElementCount>;
2744 SmallVector<RecipeVFPair> InvalidCosts;
2745 for (const auto &Plan : VPlans) {
2746 // Skip cost remarks when Plan is not compatible with the CM.
2747 // Specifically for the case of epilogue tail-folded Plans.
2748 if (Plan->hasTailFolded() != CM->foldTailByMasking())
2749 continue;
2750 for (ElementCount VF : Plan->vectorFactors()) {
2751 // The VPlan-based cost model is designed for computing vector cost.
2752 // Querying VPlan-based cost model with a scalar VF will cause some
2753 // errors because we expect the VF is vector for most of the widen
2754 // recipes.
2755 if (VF.isScalar())
2756 continue;
2757
2758 VPCostContext CostCtx(*TLI, *Plan, *CM, Config,
2759 /*ReusePrintingSlotTracker=*/true);
2760 precomputeCosts(*Plan, VF, CostCtx);
2761 auto Iter = vp_depth_first_deep(Plan->getVectorLoopRegion()->getEntry());
2763 for (auto &R : *VPBB) {
2764 if (!R.cost(VF, CostCtx).isValid())
2765 InvalidCosts.emplace_back(&R, VF);
2766 }
2767 }
2768 }
2769 }
2770 if (InvalidCosts.empty())
2771 return;
2772
2773 // Emit a report of VFs with invalid costs in the loop.
2774
2775 // Group the remarks per recipe, keeping the recipe order from InvalidCosts.
2777 unsigned I = 0;
2778 for (auto &Pair : InvalidCosts)
2779 if (Numbering.try_emplace(Pair.first, I).second)
2780 ++I;
2781
2782 // Sort the list, first on recipe(number) then on VF.
2783 sort(InvalidCosts, [&Numbering](RecipeVFPair &A, RecipeVFPair &B) {
2784 unsigned NA = Numbering[A.first];
2785 unsigned NB = Numbering[B.first];
2786 if (NA != NB)
2787 return NA < NB;
2788 return ElementCount::isKnownLT(A.second, B.second);
2789 });
2790
2791 // For a list of ordered recipe-VF pairs:
2792 // [(load, VF1), (load, VF2), (store, VF1)]
2793 // group the recipes together to emit separate remarks for:
2794 // load (VF1, VF2)
2795 // store (VF1)
2796 auto Tail = ArrayRef<RecipeVFPair>(InvalidCosts);
2797 auto Subset = ArrayRef<RecipeVFPair>();
2798 do {
2799 if (Subset.empty())
2800 Subset = Tail.take_front(1);
2801
2802 VPRecipeBase *R = Subset.front().first;
2803
2804 unsigned Opcode =
2806 .Case([](const VPHeaderPHIRecipe *R) { return Instruction::PHI; })
2807 .Case(
2808 [](const VPWidenStoreRecipe *R) { return Instruction::Store; })
2809 .Case([](const VPWidenLoadRecipe *R) { return Instruction::Load; })
2810 .Case([](const VPWidenStoreEVLRecipe *R) {
2811 return Instruction::Store;
2812 })
2813 .Case(
2814 [](const VPWidenLoadEVLRecipe *R) { return Instruction::Load; })
2815 .Case<VPWidenCallRecipe, VPWidenIntrinsicRecipe>(
2816 [](const auto *R) { return Instruction::Call; })
2819 [](const auto *R) { return R->getOpcode(); })
2820 .Case([](const VPInterleaveRecipe *R) {
2821 return R->getStoredValues().empty() ? Instruction::Load
2822 : Instruction::Store;
2823 })
2824 .Case([](const VPReductionRecipe *R) {
2825 return RecurrenceDescriptor::getOpcode(R->getRecurrenceKind());
2826 })
2827 .Case([](const VPBranchOnMaskRecipe *) {
2828 return Instruction::CondBr;
2829 });
2830
2831 // If the next recipe is different, or if there are no other pairs,
2832 // emit a remark for the collated subset. e.g.
2833 // [(load, VF1), (load, VF2))]
2834 // to emit:
2835 // remark: invalid costs for 'load' at VF=(VF1, VF2)
2836 if (Subset == Tail || Tail[Subset.size()].first != R) {
2837 std::string OutString;
2838 raw_string_ostream OS(OutString);
2839 assert(!Subset.empty() && "Unexpected empty range");
2840 OS << "Recipe with invalid costs prevented vectorization at VF=(";
2841 for (const auto &Pair : Subset)
2842 OS << (Pair.second == Subset.front().second ? "" : ", ") << Pair.second;
2843 OS << "):";
2844 if (Opcode == Instruction::Call) {
2845 StringRef Name = "";
2846 if (auto *Int = dyn_cast<VPWidenIntrinsicRecipe>(R)) {
2847 Name = Int->getIntrinsicName();
2848 } else {
2849 auto *WidenCall = dyn_cast<VPWidenCallRecipe>(R);
2850 Function *CalledFn =
2851 WidenCall
2852 ? WidenCall->getCalledScalarFunction()
2853 : cast<Function>(R->getLastOperand()->getLiveInIRValue());
2854 Name = CalledFn->getName();
2855 }
2856 OS << " call to " << Name;
2857 } else
2858 OS << " " << Instruction::getOpcodeName(Opcode);
2859 reportVectorizationInfo(OutString, "InvalidCost", ORE, OrigLoop, nullptr,
2860 R->getDebugLoc());
2861 Tail = Tail.drop_front(Subset.size());
2862 Subset = {};
2863 } else
2864 // Grow the subset by one element
2865 Subset = Tail.take_front(Subset.size() + 1);
2866 } while (!Tail.empty());
2867}
2868
2869/// Check if any recipe of \p Plan will generate a vector value, which will be
2870/// assigned a vector register.
2872 const TargetTransformInfo &TTI) {
2873 assert(VF.isVector() && "Checking a scalar VF?");
2874 DenseSet<VPRecipeBase *> EphemeralRecipes;
2875 collectEphemeralRecipesForVPlan(Plan, EphemeralRecipes);
2876 // Set of already visited types.
2877 DenseSet<Type *> Visited;
2880 for (VPRecipeBase &R : *VPBB) {
2881 if (EphemeralRecipes.contains(&R))
2882 continue;
2883 // Continue early if the recipe is considered to not produce a vector
2884 // result. Note that this includes VPInstruction where some opcodes may
2885 // produce a vector, to preserve existing behavior as VPInstructions model
2886 // aspects not directly mapped to existing IR instructions.
2887 switch (R.getVPRecipeID()) {
2888 case VPRecipeBase::VPDerivedIVSC:
2889 case VPRecipeBase::VPScalarIVStepsSC:
2890 case VPRecipeBase::VPReplicateSC:
2891 case VPRecipeBase::VPInstructionSC:
2892 case VPRecipeBase::VPCurrentIterationPHISC:
2893 case VPRecipeBase::VPVectorPointerSC:
2894 case VPRecipeBase::VPVectorEndPointerSC:
2895 case VPRecipeBase::VPExpandSCEVSC:
2896 case VPRecipeBase::VPPredInstPHISC:
2897 case VPRecipeBase::VPBranchOnMaskSC:
2898 case VPRecipeBase::VPConditionalInductionPHISC:
2899 continue;
2900 case VPRecipeBase::VPReductionSC:
2901 case VPRecipeBase::VPActiveLaneMaskPHISC:
2902 case VPRecipeBase::VPWidenCallSC:
2903 case VPRecipeBase::VPWidenCanonicalIVSC:
2904 case VPRecipeBase::VPWidenCastSC:
2905 case VPRecipeBase::VPWidenGEPSC:
2906 case VPRecipeBase::VPWidenIntrinsicSC:
2907 case VPRecipeBase::VPWidenMemIntrinsicSC:
2908 case VPRecipeBase::VPWidenSC:
2909 case VPRecipeBase::VPBlendSC:
2910 case VPRecipeBase::VPFirstOrderRecurrencePHISC:
2911 case VPRecipeBase::VPHistogramSC:
2912 case VPRecipeBase::VPWidenPHISC:
2913 case VPRecipeBase::VPWidenIntOrFpInductionSC:
2914 case VPRecipeBase::VPWidenPointerInductionSC:
2915 case VPRecipeBase::VPReductionPHISC:
2916 case VPRecipeBase::VPInterleaveEVLSC:
2917 case VPRecipeBase::VPInterleaveSC:
2918 case VPRecipeBase::VPWidenLoadEVLSC:
2919 case VPRecipeBase::VPWidenLoadSC:
2920 case VPRecipeBase::VPWidenStoreEVLSC:
2921 case VPRecipeBase::VPWidenStoreSC:
2922 break;
2923 default:
2924 llvm_unreachable("unhandled recipe");
2925 }
2926
2927 auto WillGenerateTargetVectors = [&TTI, VF](Type *VectorTy) {
2928 unsigned NumLegalParts = TTI.getNumberOfParts(VectorTy);
2929 if (!NumLegalParts)
2930 return false;
2931 if (VF.isScalable()) {
2932 // <vscale x 1 x iN> is assumed to be profitable over iN because
2933 // scalable registers are a distinct register class from scalar
2934 // ones. If we ever find a target which wants to lower scalable
2935 // vectors back to scalars, we'll need to update this code to
2936 // explicitly ask TTI about the register class uses for each part.
2937 return NumLegalParts <= VF.getKnownMinValue();
2938 }
2939 // Two or more elements that share a register - are vectorized.
2940 return NumLegalParts < VF.getFixedValue();
2941 };
2942
2943 // If no def nor is a store, e.g., branches, continue - no value to check.
2944 if (R.getNumDefinedValues() == 0 &&
2946 continue;
2947 // For multi-def recipes, currently only interleaved loads, suffice to
2948 // check first def only.
2949 // For stores check their stored value; for interleaved stores suffice
2950 // the check first stored value only. In all cases this is the second
2951 // operand.
2952 VPValue *ToCheck =
2953 R.getNumDefinedValues() >= 1 ? R.getVPValue(0) : R.getOperand(1);
2954 Type *ScalarTy = ToCheck->getScalarType();
2955 if (!Visited.insert({ScalarTy}).second)
2956 continue;
2957 Type *WideTy = toVectorizedTy(ScalarTy, VF);
2958 if (any_of(getContainedTypes(WideTy), WillGenerateTargetVectors))
2959 return true;
2960 }
2961 }
2962
2963 return false;
2964}
2965
2966static bool hasReplicatorRegion(VPlan &Plan) {
2968 Plan.getVectorLoopRegion()->getEntry())),
2969 [](auto *VPRB) { return VPRB->isReplicator(); });
2970}
2971
2972/// Returns true if the VPlan contains a VPReductionPHIRecipe with
2973/// FindLast recurrence kind.
2974static bool hasFindLastReductionPhi(VPlan &Plan) {
2977 [](VPReductionPHIRecipe &RedPhi) {
2978 return RecurrenceDescriptor::isFindLastRecurrenceKind(
2979 RedPhi.getRecurrenceKind());
2980 });
2981}
2982
2983/// Returns true if the VPlan contains a VPConditionalInductionPHIRecipe.
2988
2989/// Determine how to lower the epilogue for the vector epilogue loop.
2990/// Check if there are any conflicts that prevent tail-folding the epilogue.
2991/// \return CM_EpilogueNotNeededFoldTail if epilogue tail-folding is possible,
2992/// otherwise CM_EpilogueAllowed.
2994 const VectorizeOptions &Opts, const LoopVectorizationCostModel &MainCM,
2995 const Loop *L, OptimizationRemarkEmitter *ORE,
2997 const TargetTransformInfo *TTI) {
2998 // Epilogue TF is only enabled when explicitly requested via command line.
2999 if (Opts.epilogue_tail_folding_policy != TailFoldingPolicyTy::PreferFoldTail)
3000 return CM_EpilogueAllowed;
3001
3002 if (!Opts.enable_epilogue_vectorization) {
3004 "Options conflict, epilogue vectorization is disallowed while "
3005 "epilogue tail-folding allowed!",
3006 "UnsupportedEpilogueTailFoldingPolicy", ORE, L);
3007 return CM_EpilogueAllowed;
3008 }
3009
3010 if (!Hints.getWidth() || !hasForcedEpilogueVF()) {
3011 reportVectorizationInfo("For now, epilogue tail-folding can't be "
3012 "applied without forced main/epilogue loop VF",
3013 "UnsupportedEpilogueTailFoldingPolicy", ORE, L);
3014 return CM_EpilogueAllowed;
3015 }
3016
3018 reportVectorizationInfo("For now, epilogue tail-folding can't be applied "
3019 "when VF of the main loop <= VF of the epilogue",
3020 "UnsupportedEpilogueTailFoldingPolicy", ORE, L);
3021 return CM_EpilogueAllowed;
3022 }
3023
3024 if (!L->isInnermost()) {
3026 "Epilogue tail-folding is not supported for outer loop",
3027 "InvalidTailFoldedEpilogue", ORE, L);
3028 return CM_EpilogueAllowed;
3029 }
3030
3031 // If scalar epilogue is explicitly required, we can't apply TF.
3032 if (MainCM.requiresScalarEpilogue(/*IsVectorizing*/ true)) {
3034 "Epilogue tail-folding can't be applied because scalar epilogue is "
3035 "required. Fall back to a normal epilogue",
3036 "InvalidTailFoldedEpilogue", ORE, L);
3037 return CM_EpilogueAllowed;
3038 }
3039
3040 // If having epilogue is NOT allowed, then no epilogue to apply TF for.
3041 if (!MainCM.isEpilogueAllowed()) {
3042 reportVectorizationInfo("Not applying tail-folding to the epilogue, since "
3043 "no epilogue is allowed.",
3044 "InvalidTailFoldedEpilogue", ORE, L);
3045 return CM_EpilogueAllowed;
3046 }
3047
3048 if (L->getExitingBlock() != L->getLoopLatch() ||
3051 "Epilogue tail-folding is not supported yet for early-exit loops",
3052 "InvalidTailFoldedEpilogue", ORE, L);
3053 return CM_EpilogueAllowed;
3054 }
3055
3056 // The epilogue reuses the main loop's interleave groups, so it can't be
3057 // tail-folded if the target can't mask interleaved accesses.
3058 // TODO: Add support once the epilogue has its own IAI, separate from the main
3059 // loop's.
3060 if (MainCM.InterleaveInfo.hasGroups() &&
3063 "Epilogue tail-folding is not supported with interleaved accesses "
3064 "when masking them isn't supported",
3065 "InvalidTailFoldedEpilogue", ORE, L);
3066 return CM_EpilogueAllowed;
3067 }
3068
3069 if (Opts.force_partial_aliasing_vectorization) {
3071 "Epilogue tail-folding is not supported with alias masking",
3072 "InvalidTailFoldedEpilogue", ORE, L);
3073 return CM_EpilogueAllowed;
3074 }
3075
3076 if (!LVL.getReductionVars().empty()) {
3078 "Epilogue tail-folding is not supported with reductions",
3079 "InvalidTailFoldedEpilogue", ORE, L);
3080 return CM_EpilogueAllowed;
3081 }
3082
3083 if (!LVL.getFixedOrderRecurrences().empty()) {
3085 "Epilogue tail-folding is not supported with fixed-order recurrence",
3086 "InvalidTailFoldedEpilogue", ORE, L);
3087 return CM_EpilogueAllowed;
3088 }
3089
3090 // TODO: This is conservative: it rejects any target that prefers EVL, even
3091 // for fixed-width epilogue VFs where EVL won't be chosen. Move this check to
3092 // where the epilogue's TF style is known once epilogue TF is supported.
3093 TailFoldingStyle TFStyle = Opts.force_tail_folding_style.value_or(
3094 TTI->getPreferredTailFoldingStyle());
3095 // TODO: Remove once EVL recipes support cloning.
3096 if (TFStyle == TailFoldingStyle::DataWithEVL) {
3097 reportVectorizationInfo("Epilogue tail-folding is not supported yet with "
3098 "EVL-based tail-folding",
3099 "UnsupportedEpilogueTailFoldingPolicy", ORE, L);
3100 return CM_EpilogueAllowed;
3101 }
3102
3103 // We can apply tail-folding on the vectorized epilogue loop.
3105}
3106
3108 const ElementCount VF, const unsigned IC) const {
3109 // FIXME: We need a much better cost-model to take different parameters such
3110 // as register pressure, code size increase and cost of extra branches into
3111 // account. For now we apply a very crude heuristic and only consider loops
3112 // with vectorization factors larger than a certain value.
3113
3114 // Allow the target to opt out.
3115 if (!TTI.preferEpilogueVectorization(VF * IC))
3116 return false;
3117
3118 unsigned MinVFThreshold = Opts.epilogue_vectorization_minimum_VF.value_or(
3119 TTI.getEpilogueVectorizationMinVF());
3120 return estimateElementCount(VF * IC, getVScaleForTuning()) >= MinVFThreshold;
3121}
3122
3124 VPlan &MainPlan, ElementCount MainLoopVF, unsigned IC,
3125 bool ScalarEpilogueAllowed) {
3126 if (!Opts.enable_epilogue_vectorization) {
3127 LLVM_DEBUG(dbgs() << "LEV: Epilogue vectorization is disabled.\n");
3128 return nullptr;
3129 }
3130
3131 if (!ScalarEpilogueAllowed) {
3132 LLVM_DEBUG(dbgs() << "LEV: Unable to vectorize epilogue because no "
3133 "epilogue is allowed.\n");
3134 return nullptr;
3135 }
3136
3137 if (vputils::findIncomingAliasMask(MainPlan)) {
3138 LLVM_DEBUG(
3139 dbgs()
3140 << "LEV: Epilogue vectorization not supported with alias masking.\n");
3141 return nullptr;
3142 }
3143
3144 // Not really a cost consideration, but check for unsupported cases here to
3145 // simplify the logic.
3146 if (!isCandidateForEpilogueVectorization(MainPlan)) {
3147 LLVM_DEBUG(dbgs() << "LEV: Unable to vectorize epilogue because the loop "
3148 "is not a supported candidate.\n");
3149 return nullptr;
3150 }
3151
3152 if (hasForcedEpilogueVF()) {
3154 Config.getVScaleForTuning()) >=
3155 IC * estimateElementCount(MainLoopVF, Config.getVScaleForTuning())) {
3156 // Note that the main loop leaves IC * MainLoopVF iterations iff a scalar
3157 // epilogue is required, but then the epilogue loop also requires a scalar
3158 // epilogue.
3159 LLVM_DEBUG(dbgs() << "LEV: Forced epilogue VF results in dead epilogue "
3160 "vector loop, skipping vectorizing epilogue.\n");
3161 return nullptr;
3162 }
3163
3164 LLVM_DEBUG(dbgs() << "LEV: Epilogue vectorization factor is forced.\n");
3166 std::unique_ptr<VPlan> Clone(
3168 Clone->setVF(EpilogueVectorizationForceVF);
3169 return Clone;
3170 }
3171
3172 LLVM_DEBUG(dbgs() << "LEV: Epilogue vectorization forced factor is not "
3173 "viable.\n");
3174 return nullptr;
3175 }
3176
3177 if (OrigLoop->getHeader()->getParent()->hasOptSize()) {
3178 LLVM_DEBUG(
3179 dbgs() << "LEV: Epilogue vectorization skipped due to opt for size.\n");
3180 return nullptr;
3181 }
3182
3183 if (!Config.isEpilogueVectorizationProfitable(MainLoopVF, IC)) {
3184 LLVM_DEBUG(dbgs() << "LEV: Epilogue vectorization is not profitable for "
3185 "this loop\n");
3186 return nullptr;
3187 }
3188
3189 // Check if a plan's vector loop processes fewer iterations than VF (e.g. when
3190 // interleave groups have been narrowed) narrowInterleaveGroups) and return
3191 // the adjusted, effective VF.
3192 using namespace VPlanPatternMatch;
3193 auto GetEffectiveVF = [](VPlan &Plan, ElementCount VF) -> ElementCount {
3194 auto *Exiting = Plan.getVectorLoopRegion()->getExitingBasicBlock();
3195 if (match(&Exiting->back(),
3196 m_BranchOnCount(m_Add(m_CanonicalIV(), m_Specific(&Plan.getUF())),
3197 m_VPValue())))
3198 return ElementCount::get(1, VF.isScalable());
3199 return VF;
3200 };
3201
3202 // Check if the main loop processes fewer than MainLoopVF elements per
3203 // iteration (e.g. due to narrowing interleave groups). Adjust MainLoopVF
3204 // as needed.
3205 MainLoopVF = GetEffectiveVF(MainPlan, MainLoopVF);
3206
3207 // If MainLoopVF = vscale x 2, and vscale is expected to be 4, then we know
3208 // the main loop handles 8 lanes per iteration. We could still benefit from
3209 // vectorizing the epilogue loop with VF=4.
3210 ElementCount EstimatedRuntimeVF = ElementCount::getFixed(
3211 estimateElementCount(MainLoopVF, Config.getVScaleForTuning()));
3212
3213 Type *TCType = Legal->getWidestInductionType();
3214 const SCEV *RemainingIterations = nullptr;
3215 unsigned MaxTripCount = 0;
3216 const SCEV *TC = vputils::getSCEVExprForVPValue(MainPlan.getTripCount(), PSE);
3217 assert(!isa<SCEVCouldNotCompute>(TC) && "Trip count SCEV must be computable");
3218 const SCEV *KnownMinTC;
3219 bool ScalableTC = match(TC, m_scev_c_Mul(m_SCEV(KnownMinTC), m_SCEVVScale()));
3220 bool ScalableRemIter = false;
3221 ScalarEvolution &SE = *PSE.getSE();
3222 // Use versions of TC and VF in which both are either scalable or fixed.
3223 if (ScalableTC == MainLoopVF.isScalable()) {
3224 ScalableRemIter = ScalableTC;
3225 RemainingIterations =
3226 SE.getURemExpr(TC, SE.getElementCount(TCType, MainLoopVF * IC));
3227 } else if (ScalableTC) {
3228 const SCEV *EstimatedTC = SE.getMulExpr(
3229 KnownMinTC,
3230 SE.getConstant(TCType, Config.getVScaleForTuning().value_or(1)));
3231 RemainingIterations = SE.getURemExpr(
3232 EstimatedTC, SE.getElementCount(TCType, MainLoopVF * IC));
3233 } else
3234 RemainingIterations =
3235 SE.getURemExpr(TC, SE.getElementCount(TCType, EstimatedRuntimeVF * IC));
3236
3237 // No iterations left to process in the epilogue.
3238 if (RemainingIterations->isZero())
3239 return nullptr;
3240
3241 if (MainLoopVF.isFixed()) {
3242 MaxTripCount = MainLoopVF.getFixedValue() * IC - 1;
3243 if (SE.isKnownPredicate(CmpInst::ICMP_ULT, RemainingIterations,
3244 SE.getConstant(TCType, MaxTripCount))) {
3245 MaxTripCount = SE.getUnsignedRangeMax(RemainingIterations).getZExtValue();
3246 }
3247 LLVM_DEBUG(dbgs() << "LEV: Maximum Trip Count for Epilogue: "
3248 << MaxTripCount << "\n");
3249 }
3250
3251 auto SkipVF = [&](const SCEV *VF, const SCEV *RemIter) -> bool {
3252 return SE.isKnownPredicate(CmpInst::ICMP_UGT, VF, RemIter);
3253 };
3255 VPlan *BestPlan = nullptr;
3256 for (auto &NextVF : ProfitableVFs) {
3257 // Skip candidate VFs without a corresponding VPlan.
3258 if (!hasPlanWithVF(NextVF.Width))
3259 continue;
3260
3261 VPlan &CurrentPlan = getPlanFor(NextVF.Width);
3262 ElementCount EffectiveVF = GetEffectiveVF(CurrentPlan, NextVF.Width);
3263 // Skip fixed vector VFs > than the estimated runtime VF, or any VF > than
3264 // the VF of the main loop.
3265 if ((!EffectiveVF.isScalable() && MainLoopVF.isScalable() &&
3266 ElementCount::isKnownGT(EffectiveVF, EstimatedRuntimeVF)) ||
3267 ElementCount::isKnownGT(EffectiveVF, MainLoopVF))
3268 continue;
3269
3270 // If EffectiveVF is greater than the number of remaining iterations, the
3271 // epilogue loop would be dead. Skip such factors. If the epilogue plan
3272 // also has narrowed interleave groups, use the effective VF since
3273 // the epilogue step will be reduced to its IC.
3274 // TODO: We should also consider comparing against a scalable
3275 // RemainingIterations when SCEV be able to evaluate non-canonical
3276 // vscale-based expressions.
3277 if (!ScalableRemIter) {
3278 // Handle the case where EffectiveVF and RemainingIterations are in
3279 // different numerical spaces.
3280 if (EffectiveVF.isScalable())
3281 EffectiveVF = ElementCount::getFixed(
3282 estimateElementCount(EffectiveVF, Config.getVScaleForTuning()));
3283 if (SkipVF(SE.getElementCount(TCType, EffectiveVF), RemainingIterations))
3284 continue;
3285 }
3286
3287 if (Result.Width.isScalar() ||
3288 isMoreProfitable(NextVF, Result, MaxTripCount,
3289 !MainPlan.hasTailFolded(),
3290 /*IsEpilogue*/ true)) {
3291 Result = NextVF;
3292 BestPlan = &CurrentPlan;
3293 }
3294 }
3295
3296 if (!BestPlan)
3297 return nullptr;
3298
3299 LLVM_DEBUG(dbgs() << "LEV: Vectorizing epilogue loop with VF = "
3300 << Result.Width << "\n");
3301 std::unique_ptr<VPlan> Clone(BestPlan->duplicate());
3302 Clone->setVF(Result.Width);
3303 return Clone;
3304}
3305
3306unsigned
3308 InstructionCost LoopCost) {
3309 // -- The interleave heuristics --
3310 // We interleave the loop in order to expose ILP and reduce the loop overhead.
3311 // There are many micro-architectural considerations that we can't predict
3312 // at this level. For example, frontend pressure (on decode or fetch) due to
3313 // code size, or the number and capabilities of the execution ports.
3314 //
3315 // We use the following heuristics to select the interleave count:
3316 // 1. If the code has reductions, then we interleave to break the cross
3317 // iteration dependency.
3318 // 2. If the loop is really small, then we interleave to reduce the loop
3319 // overhead.
3320 // 3. We don't interleave if we think that we will spill registers to memory
3321 // due to the increased register pressure.
3322
3323 // Do not interleave tail-folded loops, as the overhead of multiple
3324 // instructions to calculate the predicate is likely not beneficial.
3325 // If an epilogue is not allowed for any other reason, do not interleave.
3326 if (!CM->isEpilogueAllowed())
3327 return 1;
3328
3331 LLVM_DEBUG(dbgs() << "LV: Loop requires variable-length step. "
3332 "Unroll factor forced to be 1.\n");
3333 return 1;
3334 }
3335
3336 // We used the distance for the interleave count.
3337 if (!Legal->isSafeForAnyVectorWidth())
3338 return 1;
3339
3340 // We don't attempt to perform interleaving for loops with uncountable early
3341 // exits because the VPInstruction::AnyOf code cannot currently handle
3342 // multiple parts.
3343 if (Plan.hasEarlyExit())
3344 return 1;
3345
3346 // TODO: Conditional inductions don't support interleaving yet.
3348 return 1;
3349
3350 const bool HasReductions =
3353
3354 // FIXME: implement interleaving for FindLast transform correctly.
3355 if (hasFindLastReductionPhi(Plan))
3356 return 1;
3357
3358 VPRegisterUsage R = calculateRegisterUsageForPlan(Plan, {VF}, TTI)[0];
3359
3360 // If we did not calculate the cost for VF (because the user selected the VF)
3361 // then we calculate the cost of VF here.
3362 if (LoopCost == 0) {
3363 if (VF.isScalar())
3364 LoopCost = CM->expectedCost(VF);
3365 else
3366 LoopCost = cost(Plan, VF, &R, *CM);
3367 assert(LoopCost.isValid() && "Expected to have chosen a VF with valid cost");
3368
3369 // Loop body is free and there is no need for interleaving.
3370 if (LoopCost == 0)
3371 return 1;
3372 }
3373
3374 // We divide by these constants so assume that we have at least one
3375 // instruction that uses at least one register.
3376 for (auto &Pair : R.MaxLocalUsers) {
3377 Pair.second = std::max(Pair.second, 1U);
3378 }
3379
3380 // We calculate the interleave count using the following formula.
3381 // Subtract the number of loop invariants from the number of available
3382 // registers. These registers are used by all of the interleaved instances.
3383 // Next, divide the remaining registers by the number of registers that is
3384 // required by the loop, in order to estimate how many parallel instances
3385 // fit without causing spills. All of this is rounded down if necessary to be
3386 // a power of two. We want power of two interleave count to simplify any
3387 // addressing operations or alignment considerations.
3388 // We also want power of two interleave counts to ensure that the induction
3389 // variable of the vector loop wraps to zero, when tail is folded by masking;
3390 // this currently happens when OptForSize, in which case IC is set to 1 above.
3391 unsigned IC = UINT_MAX;
3392
3393 for (const auto &Pair : R.MaxLocalUsers) {
3394 unsigned TargetNumRegisters = TTI.getNumberOfRegisters(Pair.first);
3395 LLVM_DEBUG(dbgs() << "LV: The target has " << TargetNumRegisters
3396 << " registers of "
3397 << TTI.getRegisterClassName(Pair.first)
3398 << " register class\n");
3399 TargetNumRegisters = (VF.isScalar() ? Opts.force_target_num_scalar_regs
3400 : Opts.force_target_num_vector_regs)
3401 .value_or(TargetNumRegisters);
3402 unsigned MaxLocalUsers = Pair.second;
3403 unsigned LoopInvariantRegs = 0;
3404 if (R.LoopInvariantRegs.contains(Pair.first))
3405 LoopInvariantRegs = R.LoopInvariantRegs[Pair.first];
3406
3407 unsigned TmpIC = llvm::bit_floor((TargetNumRegisters - LoopInvariantRegs) /
3408 MaxLocalUsers);
3409 // Don't count the induction variable as interleaved.
3410 if (Opts.enable_ind_var_reg_heur) {
3411 TmpIC = llvm::bit_floor((TargetNumRegisters - LoopInvariantRegs - 1) /
3412 std::max(1U, (MaxLocalUsers - 1)));
3413 }
3414
3415 IC = std::min(IC, TmpIC);
3416 }
3417
3418 // Clamp the interleave ranges to reasonable counts.
3419 bool HasUnorderedReductions =
3420 HasReductions &&
3423 [](VPReductionPHIRecipe &RedR) { return RedR.isOrdered(); });
3424 unsigned MaxInterleaveCount =
3425 TTI.getMaxInterleaveFactor(VF, HasUnorderedReductions);
3426 LLVM_DEBUG(dbgs() << "LV: MaxInterleaveFactor for the target is "
3427 << MaxInterleaveCount << "\n");
3428
3429 // Check if the user has overridden the max.
3430 MaxInterleaveCount = (VF.isScalar() ? Opts.force_target_max_scalar_interleave
3431 : Opts.force_target_max_vector_interleave)
3432 .value_or(MaxInterleaveCount);
3433
3434 // Try to get the exact trip count, or an estimate based on profiling data or
3435 // ConstantMax from PSE, failing that.
3436 auto BestKnownTC =
3437 getSmallBestKnownTC(Opts, PSE, OrigLoop,
3438 /*CanUseConstantMax=*/true,
3439 /*CanExcludeZeroTrips=*/CM->isEpilogueAllowed());
3440
3441 // For fixed length VFs treat a scalable trip count as unknown.
3442 if (BestKnownTC && (BestKnownTC->isFixed() || VF.isScalable())) {
3443 // Re-evaluate trip counts and VFs to be in the same numerical space.
3444 unsigned AvailableTC =
3445 estimateElementCount(*BestKnownTC, Config.getVScaleForTuning());
3446 unsigned EstimatedVF =
3447 estimateElementCount(VF, Config.getVScaleForTuning());
3448
3449 // At least one iteration must be scalar when this constraint holds. So the
3450 // maximum available iterations for interleaving is one less.
3451 if (Plan.requiresScalarEpilogue())
3452 --AvailableTC;
3453
3454 unsigned InterleaveCountLB = bit_floor(std::max(
3455 1u, std::min(AvailableTC / (EstimatedVF * 2), MaxInterleaveCount)));
3456
3457 if (getSmallConstantTripCount(PSE.getSE(), OrigLoop).isNonZero()) {
3458 // If the best known trip count is exact, we select between two
3459 // prospective ICs, where
3460 //
3461 // 1) the aggressive IC is capped by the trip count divided by VF
3462 // 2) the conservative IC is capped by the trip count divided by (VF * 2)
3463 //
3464 // The final IC is selected in a way that the epilogue loop trip count is
3465 // minimized while maximizing the IC itself, so that we either run the
3466 // vector loop at least once if it generates a small epilogue loop, or
3467 // else we run the vector loop at least twice.
3468
3469 unsigned InterleaveCountUB = bit_floor(std::max(
3470 1u, std::min(AvailableTC / EstimatedVF, MaxInterleaveCount)));
3471 MaxInterleaveCount = InterleaveCountLB;
3472
3473 if (InterleaveCountUB != InterleaveCountLB) {
3474 unsigned TailTripCountUB =
3475 (AvailableTC % (EstimatedVF * InterleaveCountUB));
3476 unsigned TailTripCountLB =
3477 (AvailableTC % (EstimatedVF * InterleaveCountLB));
3478 // If both produce same scalar tail, maximize the IC to do the same work
3479 // in fewer vector loop iterations
3480 if (TailTripCountUB == TailTripCountLB)
3481 MaxInterleaveCount = InterleaveCountUB;
3482 }
3483 } else {
3484 // If trip count is an estimated compile time constant, limit the
3485 // IC to be capped by the trip count divided by VF * 2, such that the
3486 // vector loop runs at least twice to make interleaving seem profitable
3487 // when there is an epilogue loop present. Since exact Trip count is not
3488 // known we choose to be conservative in our IC estimate.
3489 MaxInterleaveCount = InterleaveCountLB;
3490 }
3491 }
3492
3493 assert(MaxInterleaveCount > 0 &&
3494 "Maximum interleave count must be greater than 0");
3495
3496 // Clamp the calculated IC to be between the 1 and the max interleave count
3497 // that the target and trip count allows.
3498 if (IC > MaxInterleaveCount)
3499 IC = MaxInterleaveCount;
3500 else
3501 // Make sure IC is greater than 0.
3502 IC = std::max(1u, IC);
3503
3504 assert(IC > 0 && "Interleave count must be greater than 0.");
3505
3506 // FIXME: VF is required to be a vector only because there are several recipes
3507 // whose computeCost function asserts that the VF is a vector.
3508 if (Opts.enable_interleave_to_reduce_stalls && VF.isVector()) {
3509 LLVM_DEBUG(dbgs() << "LV: Interleaving to reduce stall cycles due to "
3510 "instruction latency.\n");
3511 // Interleaving a replicator region means we get extra copies of the blocks
3512 // in the region. Vector values used in those blocks are expected to later
3513 // be sunk to just before them, negating any reduction in stalls. Therefore
3514 // there's no gain to be had from interleaving.
3515 if (hasReplicatorRegion(Plan)) {
3516 LLVM_DEBUG(dbgs() << "LV: Not interleaving due to replicator region.\n");
3517 return 1;
3518 }
3519 VPCostContext LatencyCtx(*TLI, Plan, *CM, Config,
3520 /*ReusePrintingSlotTracker=*/true);
3521 LatencyCtx.CostKind = TTI::TCK_Latency;
3522 VPCostContext ThroughputCtx(*TLI, Plan, *CM, Config,
3523 /*ReusePrintingSlotTracker=*/true);
3524 ThroughputCtx.CostKind = TTI::TCK_RecipThroughput;
3525 // Find the largest interleave count that will help with reducing stalls.
3526 unsigned StallsIC = 1;
3529 for (VPRecipeBase &R : *VPBB) {
3530 // Assuming that each value will be needed as soon as it's generated the
3531 // number of stall cycles is one less than the latency.
3532 InstructionCost StallCycles = R.cost(VF, LatencyCtx) - 1;
3533 if (Opts.force_target_load_latency > 0 && R.mayReadFromMemory())
3534 StallCycles = Opts.force_target_load_latency - 1;
3535 // Each interleaving above 1 will reduce the stalls by RecipThroughput,
3536 // so pick the interleaving that will reduce stalls to zero.
3537 InstructionCost RecipThroughput = R.cost(VF, ThroughputCtx);
3538 if (StallCycles.isValid() && RecipThroughput.isValid() &&
3539 StallCycles > 0 && RecipThroughput > 0) {
3540 InstructionCost ModifiedCycles = (StallCycles / RecipThroughput) + 1;
3541 unsigned ThisIC = bit_floor<uint64_t>(ModifiedCycles.getValue());
3542 StallsIC = std::max(StallsIC, ThisIC);
3543 }
3544 }
3545 }
3546 if (StallsIC <= 1) {
3547 LLVM_DEBUG(
3548 dbgs() << "LV: Not interleaving as it wouldn't reduce stalls.\n");
3549 return 1;
3550 }
3551 IC = std::min(IC, StallsIC);
3552 return IC;
3553 }
3554
3555 // Interleave if we vectorized this loop and there is a reduction that could
3556 // benefit from interleaving.
3557 if (VF.isVector() && HasReductions) {
3558 LLVM_DEBUG(dbgs() << "LV: Interleaving because of reductions.\n");
3559 return IC;
3560 }
3561
3562 // For any scalar loop that either requires runtime checks or tail-folding we
3563 // are better off leaving this to the unroller. Note that if we've already
3564 // vectorized the loop we will have done the runtime check and so interleaving
3565 // won't require further checks.
3566 bool ScalarInterleavingRequiresPredication =
3567 (VF.isScalar() && any_of(OrigLoop->blocks(), [this](BasicBlock *BB) {
3568 return Legal->blockNeedsPredication(BB);
3569 }));
3570 bool ScalarInterleavingRequiresRuntimePointerCheck =
3571 (VF.isScalar() && Legal->getRuntimePointerChecking()->Need);
3572
3573 // We want to interleave small loops in order to reduce the loop overhead and
3574 // potentially expose ILP opportunities.
3575 LLVM_DEBUG(dbgs() << "LV: Loop cost is " << LoopCost << '\n'
3576 << "LV: IC is " << IC << '\n'
3577 << "LV: VF is " << VF << '\n');
3578 const bool AggressivelyInterleave =
3579 TTI.enableAggressiveInterleaving(HasReductions);
3580 if (!ScalarInterleavingRequiresRuntimePointerCheck &&
3581 !ScalarInterleavingRequiresPredication &&
3582 LoopCost < Opts.small_loop_cost) {
3583 // We assume that the cost overhead is 1 and we use the cost model
3584 // to estimate the cost of the loop and interleave until the cost of the
3585 // loop overhead is about 5% of the cost of the loop.
3586 InstructionCost NumLoops = InstructionCost(Opts.small_loop_cost) / LoopCost;
3587 unsigned SmallIC =
3588 std::min(IC, (unsigned)llvm::bit_floor<uint64_t>(NumLoops.getValue()));
3589
3590 // Interleave until store/load ports (estimated by max interleave count) are
3591 // saturated.
3592 unsigned NumStores = 0;
3593 unsigned NumLoads = 0;
3596 for (VPRecipeBase &R : *VPBB) {
3598 NumLoads++;
3599 continue;
3600 }
3602 NumStores++;
3603 continue;
3604 }
3605
3606 if (auto *InterleaveR = dyn_cast<VPInterleaveRecipe>(&R)) {
3607 if (unsigned StoreOps = InterleaveR->getNumStoreOperands())
3608 NumStores += StoreOps;
3609 else
3610 NumLoads += InterleaveR->getNumDefinedValues();
3611 continue;
3612 }
3613 if (auto *RepR = dyn_cast<VPReplicateRecipe>(&R)) {
3614 NumLoads += isa<LoadInst>(RepR->getUnderlyingInstr());
3615 NumStores += isa<StoreInst>(RepR->getUnderlyingInstr());
3616 continue;
3617 }
3618 if (isa<VPHistogramRecipe>(&R)) {
3619 NumLoads++;
3620 NumStores++;
3621 continue;
3622 }
3623 }
3624 }
3625 unsigned StoresIC = IC / (NumStores ? NumStores : 1);
3626 unsigned LoadsIC = IC / (NumLoads ? NumLoads : 1);
3627
3628 // There is little point in interleaving for reductions containing selects
3629 // and compares when VF=1 since it may just create more overhead than it's
3630 // worth for loops with small trip counts. This is because we still have to
3631 // do the final reduction after the loop.
3632 bool HasSelectCmpReductions =
3633 HasReductions &&
3636 [](VPReductionPHIRecipe &RedR) {
3637 return RecurrenceDescriptor::isAnyOfRecurrenceKind(
3638 RedR.getRecurrenceKind()) ||
3639 RecurrenceDescriptor::isFindIVRecurrenceKind(
3640 RedR.getRecurrenceKind());
3641 });
3642 if (HasSelectCmpReductions) {
3643 LLVM_DEBUG(dbgs() << "LV: Not interleaving select-cmp reductions.\n");
3644 return 1;
3645 }
3646
3647 // If we have a scalar reduction (vector reductions are already dealt with
3648 // by this point), we can increase the critical path length if the loop
3649 // we're interleaving is inside another loop. For tree-wise reductions
3650 // set the limit to 2, and for ordered reductions it's best to disable
3651 // interleaving entirely.
3652 if (HasReductions && OrigLoop->getLoopDepth() > 1) {
3653 bool HasOrderedReductions =
3656 [](VPReductionPHIRecipe &RedR) { return RedR.isOrdered(); });
3657 if (HasOrderedReductions) {
3658 LLVM_DEBUG(
3659 dbgs() << "LV: Not interleaving scalar ordered reductions.\n");
3660 return 1;
3661 }
3662
3663 unsigned F = Opts.max_nested_scalar_reduction_interleave;
3664 SmallIC = std::min(SmallIC, F);
3665 StoresIC = std::min(StoresIC, F);
3666 LoadsIC = std::min(LoadsIC, F);
3667 }
3668
3669 if (Opts.enable_loadstore_runtime_interleave &&
3670 std::max(StoresIC, LoadsIC) > SmallIC) {
3671 LLVM_DEBUG(
3672 dbgs() << "LV: Interleaving to saturate store or load ports.\n");
3673 return std::max(StoresIC, LoadsIC);
3674 }
3675
3676 // If there are scalar reductions and TTI has enabled aggressive
3677 // interleaving for reductions, we will interleave to expose ILP.
3678 if (VF.isScalar() && AggressivelyInterleave) {
3679 LLVM_DEBUG(dbgs() << "LV: Interleaving to expose ILP.\n");
3680 // Interleave no less than SmallIC but not as aggressive as the normal IC
3681 // to satisfy the rare situation when resources are too limited.
3682 return std::max(IC / 2, SmallIC);
3683 }
3684
3685 LLVM_DEBUG(dbgs() << "LV: Interleaving to reduce branch cost.\n");
3686 return SmallIC;
3687 }
3688
3689 // Interleave if this is a large loop (small loops are already dealt with by
3690 // this point) that could benefit from interleaving.
3691 if (AggressivelyInterleave) {
3692 LLVM_DEBUG(dbgs() << "LV: Interleaving to expose ILP.\n");
3693 return IC;
3694 }
3695
3696 LLVM_DEBUG(dbgs() << "LV: Not Interleaving.\n");
3697 return 1;
3698}
3699
3701 Instruction *I, ElementCount VF) const {
3702 // TODO: Cost model for emulated masked load/store is completely
3703 // broken. This hack guides the cost model to use an artificially
3704 // high enough value to practically disable vectorization with such
3705 // operations, except where previously deployed legality hack allowed
3706 // using very low cost values. This is to avoid regressions coming simply
3707 // from moving "masked load/store" check from legality to cost model.
3708 // Masked Load/Gather emulation was previously never allowed.
3709 // Limited number of Masked Store/Scatter emulation was allowed.
3711 "Expecting a scalar emulated instruction");
3712 return isa<LoadInst>(I) ||
3713 (isa<StoreInst>(I) && NumPredStores > Opts.vectorize_num_stores_pred);
3714}
3715
3717 assert(VF.isVector() && "Expected VF >= 2");
3718 assert(!InstsToScalarize.contains(VF) &&
3719 !PredicatedBBsAfterVectorization.contains(VF) &&
3720 "Routine expected to be called once per VF");
3721
3722 // Initialize a mapping for VF in InstsToScalalarize. If we find that it's
3723 // not profitable to scalarize any instructions, the presence of VF in the
3724 // map will indicate that we've analyzed it already.
3725 ScalarCostsTy &ScalarCostsVF = InstsToScalarize[VF];
3726
3727 // Find all the instructions that are scalar with predication in the loop and
3728 // determine if it would be better to not if-convert the blocks they are in.
3729 // If so, we also record the instructions to scalarize.
3730 for (BasicBlock *BB : TheLoop->blocks()) {
3732 continue;
3733 for (Instruction &I : *BB)
3734 if (isScalarWithPredication(&I, VF)) {
3735 ScalarCostsTy ScalarCosts;
3736 // Do not apply discount logic for:
3737 // 1. Scalars after vectorization, as there will only be a single copy
3738 // of the instruction.
3739 // 2. Scalable VF, as that would lead to invalid scalarization costs.
3740 // 3. Emulated masked memrefs, if a hacked cost is needed.
3741 // 4. Compressed loads/stores (which do not support scalarization)
3742 if (!isScalarAfterVectorization(&I, VF) && !VF.isScalable() &&
3744 !Legal->isCompressedLoadOrStore(&I) &&
3745 computePredInstDiscount(&I, ScalarCosts, VF) >= 0) {
3746 for (const auto &[I, IC] : ScalarCosts)
3747 ScalarCostsVF.insert({I, IC});
3748 }
3749 // Remember that BB will remain after vectorization.
3750 PredicatedBBsAfterVectorization[VF].insert(BB);
3751 for (auto *Pred : predecessors(BB)) {
3752 if (Pred->getSingleSuccessor() == BB)
3753 PredicatedBBsAfterVectorization[VF].insert(Pred);
3754 }
3755 }
3756 }
3757}
3758
3759InstructionCost LoopVectorizationCostModel::computePredInstDiscount(
3760 Instruction *PredInst, ScalarCostsTy &ScalarCosts, ElementCount VF) {
3761 assert(!isUniformAfterVectorization(PredInst, VF) &&
3762 "Instruction marked uniform-after-vectorization will be predicated");
3763
3764 // Initialize the discount to zero, meaning that the scalar version and the
3765 // vector version cost the same.
3766 InstructionCost Discount = 0;
3767
3768 // Holds instructions to analyze. The instructions we visit are mapped in
3769 // ScalarCosts. Those instructions are the ones that would be scalarized if
3770 // we find that the scalar version costs less.
3772
3773 // Returns true if the given instruction can be scalarized.
3774 auto CanBeScalarized = [&](Instruction *I) -> bool {
3775 // We only attempt to scalarize instructions forming a single-use chain
3776 // from the original predicated block that would otherwise be vectorized.
3777 // Although not strictly necessary, we give up on instructions we know will
3778 // already be scalar to avoid traversing chains that are unlikely to be
3779 // beneficial.
3780 if (!I->hasOneUse() || PredInst->getParent() != I->getParent() ||
3782 return false;
3783
3784 // If the instruction is scalar with predication, it will be analyzed
3785 // separately. We ignore it within the context of PredInst.
3786 if (isScalarWithPredication(I, VF))
3787 return false;
3788
3789 // If any of the instruction's operands are uniform after vectorization,
3790 // the instruction cannot be scalarized. This prevents, for example, a
3791 // masked load from being scalarized.
3792 //
3793 // We assume we will only emit a value for lane zero of an instruction
3794 // marked uniform after vectorization, rather than VF identical values.
3795 // Thus, if we scalarize an instruction that uses a uniform, we would
3796 // create uses of values corresponding to the lanes we aren't emitting code
3797 // for. This behavior can be changed by allowing getScalarValue to clone
3798 // the lane zero values for uniforms rather than asserting.
3799 for (Use &U : I->operands())
3800 if (auto *J = dyn_cast<Instruction>(U.get()))
3801 if (isUniformAfterVectorization(J, VF))
3802 return false;
3803
3804 // Otherwise, we can scalarize the instruction.
3805 return true;
3806 };
3807
3808 // Compute the expected cost discount from scalarizing the entire expression
3809 // feeding the predicated instruction. We currently only consider expressions
3810 // that are single-use instruction chains.
3811 Worklist.push_back(PredInst);
3812 while (!Worklist.empty()) {
3813 Instruction *I = Worklist.pop_back_val();
3814
3815 // If we've already analyzed the instruction, there's nothing to do.
3816 if (ScalarCosts.contains(I))
3817 continue;
3818
3819 // Cannot scalarize fixed-order recurrence phis at the moment.
3821 continue;
3822
3823 // Compute the cost of the vector instruction. Note that this cost already
3824 // includes the scalarization overhead of the predicated instruction.
3825 InstructionCost VectorCost = getInstructionCost(I, VF);
3826
3827 // Compute the cost of the scalarized instruction. This cost is the cost of
3828 // the instruction as if it wasn't if-converted and instead remained in the
3829 // predicated block. We will scale this cost by block probability after
3830 // computing the scalarization overhead.
3831 InstructionCost ScalarCost =
3833
3834 // Compute the scalarization overhead of needed insertelement instructions
3835 // and phi nodes.
3836 if (isScalarWithPredication(I, VF) && !I->getType()->isVoidTy()) {
3837 Type *WideTy = toVectorizedTy(I->getType(), VF);
3838 for (Type *VectorTy : getContainedTypes(WideTy)) {
3839 ScalarCost += TTI.getScalarizationOverhead(
3841 /*Insert=*/true,
3842 /*Extract=*/false, Config.CostKind);
3843 }
3844 ScalarCost += VF.getFixedValue() *
3845 TTI.getCFInstrCost(Instruction::PHI, Config.CostKind);
3846 }
3847
3848 // Compute the scalarization overhead of needed extractelement
3849 // instructions. For each of the instruction's operands, if the operand can
3850 // be scalarized, add it to the worklist; otherwise, account for the
3851 // overhead.
3852 for (Use &U : I->operands())
3853 if (auto *J = dyn_cast<Instruction>(U.get())) {
3854 assert(canVectorizeTy(J->getType()) &&
3855 "Instruction has non-scalar type");
3856 if (CanBeScalarized(J))
3857 Worklist.push_back(J);
3858 else if (needsExtract(J, VF)) {
3859 Type *WideTy = toVectorizedTy(J->getType(), VF);
3860 for (Type *VectorTy : getContainedTypes(WideTy)) {
3861 ScalarCost += TTI.getScalarizationOverhead(
3862 cast<VectorType>(VectorTy),
3863 APInt::getAllOnes(VF.getFixedValue()), /*Insert*/ false,
3864 /*Extract*/ true, Config.CostKind);
3865 }
3866 }
3867 }
3868
3869 // Scale the total scalar cost by block probability.
3870 ScalarCost /= getPredBlockCostDivisor(Config.CostKind, I->getParent());
3871
3872 // Compute the discount. A non-negative discount means the vector version
3873 // of the instruction costs more, and scalarizing would be beneficial.
3874 Discount += VectorCost - ScalarCost;
3875 ScalarCosts[I] = ScalarCost;
3876 }
3877
3878 return Discount;
3879}
3880
3883 assert(VF.isScalar() && "must only be called for scalar VFs");
3884
3885 // For each block.
3886 for (BasicBlock *BB : TheLoop->blocks()) {
3887 InstructionCost BlockCost;
3888
3889 // For each instruction in the old loop.
3890 for (Instruction &I : *BB) {
3891 // Skip ignored values.
3892 if (ValuesToIgnore.count(&I) ||
3893 (VF.isVector() && VecValuesToIgnore.count(&I)))
3894 continue;
3895
3897
3898 // Check if we should override the cost.
3899 if (C.isValid() && Opts.force_target_instruction_cost)
3900 C = InstructionCost(*Opts.force_target_instruction_cost);
3901
3902 BlockCost += C;
3903 LLVM_DEBUG(dbgs() << "LV: Found an estimated cost of " << C << " for VF "
3904 << VF << " For instruction: " << I << '\n');
3905 }
3906
3907 // In the scalar loop, we may not always execute the predicated block, if it
3908 // is an if-else block. Thus, scale the block's cost by the probability of
3909 // executing it. getPredBlockCostDivisor will return 1 for blocks that are
3910 // only predicated by the header mask when folding the tail.
3911 Cost += BlockCost / getPredBlockCostDivisor(Config.CostKind, BB);
3912 }
3913
3914 return Cost;
3915}
3916
3917/// Gets the address access SCEV for Ptr, if it should be used for cost modeling
3918/// according to isAddressSCEVForCost.
3919///
3920/// This SCEV can be sent to the Target in order to estimate the address
3921/// calculation cost.
3923 Value *Ptr,
3925 const Loop *TheLoop) {
3926 const SCEV *Addr = PSE.getSCEV(Ptr);
3927 return vputils::isAddressSCEVForCost(Addr, *PSE.getSE(), TheLoop) ? Addr
3928 : nullptr;
3929}
3930
3932LoopVectorizationCostModel::getMemInstScalarizationCost(Instruction *I,
3933 ElementCount VF) {
3934 assert(VF.isVector() &&
3935 "Scalarization cost of instruction implies vectorization.");
3936 if (VF.isScalable())
3938
3939 Type *ValTy = getLoadStoreType(I);
3940 auto *SE = PSE.getSE();
3941
3942 unsigned AS = getLoadStoreAddressSpace(I);
3944 Type *PtrTy = toVectorTy(Ptr->getType(), VF);
3945 // NOTE: PtrTy is a vector to signal `TTI::getAddressComputationCost`
3946 // that it is being called from this specific place.
3947
3948 // Figure out whether the access is strided and get the stride value
3949 // if it's known in compile time
3950 const SCEV *PtrSCEV = getAddressAccessSCEV(Ptr, PSE, TheLoop);
3951
3952 // Get the cost of the scalar memory instruction and address computation.
3954 VF.getFixedValue() *
3955 TTI.getAddressComputationCost(PtrTy, SE, PtrSCEV, Config.CostKind);
3956
3957 // Don't pass *I here, since it is scalar but will actually be part of a
3958 // vectorized loop where the user of it is a vectorized instruction.
3960 TTI::OperandValueInfo OpInfo = TTI::getOperandInfo(I->getOperand(0));
3961 Cost += VF.getFixedValue() *
3962 TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(), Alignment,
3963 AS, Config.CostKind, OpInfo);
3964
3965 // Get the overhead of the extractelement and insertelement instructions
3966 // we might create due to scalarization.
3967 Cost += getScalarizationOverhead(I, VF);
3968
3969 // If we have a predicated load/store, it will need extra i1 extracts and
3970 // conditional branches, but may not be executed for each vector lane. Scale
3971 // the cost by the probability of executing the predicated block.
3972 if (isPredicatedInst(I)) {
3973 Cost /= getPredBlockCostDivisor(Config.CostKind, I->getParent());
3974
3975 // Add the cost of an i1 extract and a branch
3976 auto *VecI1Ty =
3978 Cost += TTI.getScalarizationOverhead(
3979 VecI1Ty, APInt::getAllOnes(VF.getFixedValue()),
3980 /*Insert=*/false, /*Extract=*/true, Config.CostKind);
3981 Cost += TTI.getCFInstrCost(Instruction::CondBr, Config.CostKind);
3982
3984 // Artificially setting to a high enough value to practically disable
3985 // vectorization with such operations.
3986 Cost = 3000000;
3987 }
3988
3989 return Cost;
3990}
3991
3992InstructionCost LoopVectorizationCostModel::getConsecutiveMemOpCost(
3993 Instruction *I, ElementCount VF, InstWidening Kind) {
3994 assert((Kind == CM_Widen || Kind == CM_Widen_Reverse) &&
3995 "Expected a consecutive widening decision");
3996 Type *ValTy = getLoadStoreType(I);
3997 auto *VectorTy = cast<VectorType>(toVectorTy(ValTy, VF));
3998 unsigned AS = getLoadStoreAddressSpace(I);
3999
4002 if (isMaskRequired(I)) {
4003 Intrinsic::ID LoadIID = Intrinsic::masked_load;
4004 Intrinsic::ID StoreIID = Intrinsic::masked_store;
4005 if (Legal->isCompressedLoadOrStore(I)) {
4006 LoadIID = Intrinsic::masked_expandload;
4007 StoreIID = Intrinsic::masked_compressstore;
4008 }
4009
4010 unsigned IID = I->getOpcode() == Instruction::Load ? LoadIID : StoreIID;
4011 Cost += TTI.getMemIntrinsicInstrCost(
4012 MemIntrinsicCostAttributes(IID, VectorTy, Alignment, AS),
4013 Config.CostKind);
4014 } else {
4015 TTI::OperandValueInfo OpInfo = TTI::getOperandInfo(I->getOperand(0));
4016 Cost += TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS,
4017 Config.CostKind, OpInfo, I);
4018 }
4019
4020 if (Kind == CM_Widen_Reverse)
4021 Cost += TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy,
4022 VectorTy, Config.CostKind, {}, 0);
4023 return Cost;
4024}
4025
4027LoopVectorizationCostModel::getUniformMemOpCost(Instruction *I,
4028 ElementCount VF) const {
4029 assert(isUniformMemOp(*I, VF));
4030
4031 Type *ValTy = getLoadStoreType(I);
4033 auto *VectorTy = cast<VectorType>(toVectorTy(ValTy, VF));
4035 unsigned AS = getLoadStoreAddressSpace(I);
4036 if (isa<LoadInst>(I)) {
4037 return TTI.getAddressComputationCost(PtrTy, nullptr, nullptr,
4038 Config.CostKind) +
4039 TTI.getMemoryOpCost(Instruction::Load, ValTy, Alignment, AS,
4040 Config.CostKind) +
4041 TTI.getShuffleCost(TargetTransformInfo::SK_Broadcast, VectorTy,
4042 VectorTy, Config.CostKind);
4043 }
4044 StoreInst *SI = cast<StoreInst>(I);
4045
4046 bool IsLoopInvariantStoreValue = Legal->isInvariant(SI->getValueOperand());
4047 // TODO: We have existing tests that request the cost of extracting element
4048 // VF.getKnownMinValue() - 1 from a scalable vector. This does not represent
4049 // the actual generated code, which involves extracting the last element of
4050 // a scalable vector where the lane to extract is unknown at compile time.
4052 TTI.getAddressComputationCost(PtrTy, nullptr, nullptr, Config.CostKind) +
4053 TTI.getMemoryOpCost(Instruction::Store, ValTy, Alignment, AS,
4054 Config.CostKind);
4055 if (!IsLoopInvariantStoreValue)
4056 Cost += TTI.getIndexedVectorInstrCostFromEnd(Instruction::ExtractElement,
4057 VectorTy, Config.CostKind, 0);
4058 return Cost;
4059}
4060
4062LoopVectorizationCostModel::getGatherScatterCost(Instruction *I,
4063 ElementCount VF) const {
4064 Type *ValTy = getLoadStoreType(I);
4065 auto *VectorTy = cast<VectorType>(toVectorTy(ValTy, VF));
4068 Type *PtrTy = Ptr->getType();
4069
4070 if (!isUniform(Ptr, VF))
4071 PtrTy = toVectorTy(PtrTy, VF);
4072
4073 unsigned IID = I->getOpcode() == Instruction::Load
4074 ? Intrinsic::masked_gather
4075 : Intrinsic::masked_scatter;
4076 return TTI.getAddressComputationCost(PtrTy, nullptr, nullptr,
4077 Config.CostKind) +
4078 TTI.getMemIntrinsicInstrCost(
4079 MemIntrinsicCostAttributes(IID, VectorTy, Ptr, isMaskRequired(I),
4080 Alignment, I),
4081 Config.CostKind);
4082}
4083
4085LoopVectorizationCostModel::getInterleaveGroupCost(Instruction *I,
4086 ElementCount VF) const {
4087 const auto *Group = getInterleavedAccessGroup(I);
4088 assert(Group && "Fail to get an interleaved access group.");
4089
4090 Instruction *InsertPos = Group->getInsertPos();
4091 Type *ValTy = getLoadStoreType(InsertPos);
4092 auto *VectorTy = cast<VectorType>(toVectorTy(ValTy, VF));
4093 unsigned AS = getLoadStoreAddressSpace(InsertPos);
4094
4095 unsigned InterleaveFactor = Group->getFactor();
4096 auto *WideVecTy = VectorType::get(ValTy, VF * InterleaveFactor);
4097
4098 // Holds the indices of existing members in the interleaved group.
4099 SmallVector<unsigned, 4> Indices;
4100 for (unsigned IF = 0; IF < InterleaveFactor; IF++)
4101 if (Group->getMember(IF))
4102 Indices.push_back(IF);
4103
4104 // Calculate the cost of the whole interleaved group.
4105 bool UseMaskForGaps =
4106 (Group->requiresScalarEpilogue() && !isEpilogueAllowed()) ||
4107 (isa<StoreInst>(I) && !Group->isFull());
4108 InstructionCost Cost = TTI.getInterleavedMemoryOpCost(
4109 InsertPos->getOpcode(), WideVecTy, Group->getFactor(), Indices,
4110 Group->getAlign(), AS, Config.CostKind, isMaskRequired(I),
4111 UseMaskForGaps);
4112
4113 if (Group->isReverse()) {
4114 // TODO: Add support for reversed masked interleaved access.
4116 "Reverse masked interleaved access not supported.");
4117 Cost += Group->getNumMembers() *
4118 TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy,
4119 VectorTy, Config.CostKind, {}, 0);
4120 }
4121 return Cost;
4122}
4123
4125LoopVectorizationCostModel::getMemoryInstructionCost(Instruction *I,
4126 ElementCount VF) {
4127 // Calculate scalar cost only. Vectorization cost should be ready at this
4128 // moment.
4129 if (VF.isScalar()) {
4130 Type *ValTy = getLoadStoreType(I);
4133 unsigned AS = getLoadStoreAddressSpace(I);
4134
4135 TTI::OperandValueInfo OpInfo = TTI::getOperandInfo(I->getOperand(0));
4136 return TTI.getAddressComputationCost(PtrTy, nullptr, nullptr,
4137 Config.CostKind) +
4138 TTI.getMemoryOpCost(I->getOpcode(), ValTy, Alignment, AS,
4139 Config.CostKind, OpInfo, I);
4140 }
4141 return getWideningCost(I, VF);
4142}
4143
4145LoopVectorizationCostModel::getScalarizationOverhead(Instruction *I,
4146 ElementCount VF) const {
4147
4148 // There is no mechanism yet to create a scalable scalarization loop,
4149 // so this is currently Invalid.
4150 if (VF.isScalable())
4152
4153 if (VF.isScalar())
4154 return 0;
4155
4157 Type *RetTy = toVectorizedTy(I->getType(), VF);
4158 if (!RetTy->isVoidTy() &&
4159 (!isa<LoadInst>(I) || !TTI.supportsEfficientVectorElementLoadStore())) {
4160
4162 if (isa<LoadInst>(I))
4163 VIC = TTI::VectorInstrContext::Load;
4164 else if (isa<StoreInst>(I))
4165 VIC = TTI::VectorInstrContext::Store;
4166
4167 for (Type *VectorTy : getContainedTypes(RetTy)) {
4168 Cost += TTI.getScalarizationOverhead(
4170 /*Insert=*/true, /*Extract=*/false, Config.CostKind,
4171 /*ForPoisonSrc=*/true, {}, VIC);
4172 }
4173 }
4174
4175 // Some targets keep addresses scalar.
4176 if (isa<LoadInst>(I) && !TTI.prefersVectorizedAddressing())
4177 return Cost;
4178
4179 // Some targets support efficient element stores.
4180 if (isa<StoreInst>(I) && TTI.supportsEfficientVectorElementLoadStore())
4181 return Cost;
4182
4183 // Collect operands to consider.
4184 CallInst *CI = dyn_cast<CallInst>(I);
4185 Instruction::op_range Ops = CI ? CI->args() : I->operands();
4186
4187 // Skip operands that do not require extraction/scalarization and do not incur
4188 // any overhead.
4190 SmallPtrSet<Value *, 4> SeenOps;
4191 for (Value *Op : Ops)
4192 if (needsExtract(Op, VF) && SeenOps.insert(Op).second)
4193 Tys.push_back(maybeVectorizeType(Op->getType(), VF));
4194
4196 ? TTI::VectorInstrContext::Store
4198 return Cost +
4199 TTI.getOperandsScalarizationOverhead(Tys, Config.CostKind, OperandVIC);
4200}
4201
4203 if (VF.isScalar())
4204 return;
4205
4206 // TODO: We should generate better code and update the cost model for
4207 // predicated uniform stores. Today they are treated as any other
4208 // predicated store (see added test cases in
4209 // invariant-store-vectorization.ll).
4210 NumPredStores = 0;
4211 for (BasicBlock *BB : TheLoop->blocks())
4212 for (Instruction &I : *BB)
4214 ++NumPredStores;
4215
4216 for (BasicBlock *BB : TheLoop->blocks()) {
4217 // For each instruction in the old loop.
4218 for (Instruction &I : *BB) {
4220
4221 // Ignore if no pointer found or a widening decision has already been
4222 // made.
4223 if (!Ptr || (getWideningDecision(&I, VF) != CM_Unknown))
4224 continue;
4225
4226 LLVM_DEBUG(dbgs() << "LV: Memory widening: calculating best strategy for "
4227 << I << '\n');
4228 if (isUniformMemOp(I, VF)) {
4229 auto IsLegalToScalarize = [&]() {
4230 if (!VF.isScalable())
4231 // Scalarization of fixed length vectors "just works".
4232 return true;
4233
4234 // We have dedicated lowering for unpredicated uniform loads and
4235 // stores. Note that even with tail folding we know that at least
4236 // one lane is active (i.e. generalized predication is not possible
4237 // here), and the logic below depends on this fact.
4238 if (!foldTailByMasking())
4239 return true;
4240
4241 // For scalable vectors, a uniform memop load is always
4242 // uniform-by-parts and we know how to scalarize that.
4243 if (isa<LoadInst>(I))
4244 return true;
4245
4246 // A uniform store isn't neccessarily uniform-by-part
4247 // and we can't assume scalarization.
4248 auto &SI = cast<StoreInst>(I);
4249 return TheLoop->isLoopInvariant(SI.getValueOperand());
4250 };
4251
4252 const InstructionCost GatherScatterCost =
4253 isLegalGatherOrScatter(&I, VF) ? getGatherScatterCost(&I, VF)
4255
4256 // Load: Scalar load + broadcast
4257 // Store: Scalar store + isLoopInvariantStoreValue ? 0 : extract
4258 // FIXME: This cost is a significant under-estimate for tail folded
4259 // memory ops.
4260 const InstructionCost ScalarizationCost =
4261 IsLegalToScalarize() ? getUniformMemOpCost(&I, VF)
4263
4264 // Choose better solution for the current VF, Note that Invalid
4265 // costs compare as maximumal large. If both are invalid, we get
4266 // scalable invalid which signals a failure and a vectorization abort.
4267 LLVM_DEBUG(dbgs() << "LV: Memory widening: uniform memory op has "
4268 "GatherScatterCost = "
4269 << GatherScatterCost << ", ScalarizationCost = "
4270 << ScalarizationCost << '\n');
4271 if (GatherScatterCost < ScalarizationCost)
4272 setWideningDecision(&I, VF, CM_GatherScatter, GatherScatterCost);
4273 else
4274 setWideningDecision(&I, VF, CM_Scalarize, ScalarizationCost);
4275 continue;
4276 }
4277
4278 // We assume that widening is the best solution when possible.
4279 if (std::optional<InstWidening> Decision =
4281 InstructionCost WidenCost = getConsecutiveMemOpCost(&I, VF, *Decision);
4282 LLVM_DEBUG(
4283 dbgs() << "LV: Memory widening: can be widened normally with cost "
4284 << WidenCost << '\n');
4285 setWideningDecision(&I, VF, *Decision, WidenCost);
4286 continue;
4287 }
4288
4289 assert(!Legal->isCompressedLoadOrStore(&I) &&
4290 "compressed loads/stores should be handled in "
4291 "memoryInstructionCanBeWidened");
4292
4293 // Choose between Interleaving, Gather/Scatter or Scalarization.
4295 unsigned NumAccesses = 1;
4296 if (isAccessInterleaved(&I)) {
4297 const auto *Group = getInterleavedAccessGroup(&I);
4298 assert(Group && "Fail to get an interleaved access group.");
4299
4300 NumAccesses = Group->getNumMembers();
4302 InterleaveCost = getInterleaveGroupCost(&I, VF);
4303 }
4304
4305 InstructionCost GatherScatterCost =
4307 ? getGatherScatterCost(&I, VF) * NumAccesses
4309
4310 InstructionCost ScalarizationCost =
4311 getMemInstScalarizationCost(&I, VF) * NumAccesses;
4312
4313 // Choose better solution for the current VF,
4314 // write down this decision and use it during vectorization.
4316 InstWidening Decision;
4317 if (InterleaveCost <= GatherScatterCost &&
4318 InterleaveCost < ScalarizationCost) {
4319 Decision = CM_Interleave;
4320 Cost = InterleaveCost;
4321 } else if (GatherScatterCost < ScalarizationCost) {
4322 Decision = CM_GatherScatter;
4323 Cost = GatherScatterCost;
4324 } else {
4325 Decision = CM_Scalarize;
4326 Cost = ScalarizationCost;
4327 }
4328 LLVM_DEBUG(
4329 dbgs() << "LV: Memory widening: InterleaveCost = " << InterleaveCost
4330 << ", GatherScatterCost = " << GatherScatterCost
4331 << ", ScalarizationCost = " << ScalarizationCost << '\n');
4332
4333 // If the instructions belongs to an interleave group, the whole group
4334 // receives the same decision. The whole group receives the cost, but
4335 // the cost will actually be assigned to one instruction.
4336 if (const auto *Group = getInterleavedAccessGroup(&I)) {
4337 if (Decision == CM_Scalarize) {
4338 for (Instruction *I : Group->members())
4339 setWideningDecision(I, VF, Decision,
4340 getMemInstScalarizationCost(I, VF));
4341 } else {
4342 setWideningDecision(Group, VF, Decision, Cost);
4343 }
4344 } else
4345 setWideningDecision(&I, VF, Decision, Cost);
4346 }
4347 }
4348
4349 // Make sure that any load of address and any other address computation
4350 // remains scalar unless there is gather/scatter support. This avoids
4351 // inevitable extracts into address registers, and also has the benefit of
4352 // activating LSR more, since that pass can't optimize vectorized
4353 // addresses.
4354 if (TTI.prefersVectorizedAddressing())
4355 return;
4356
4357 // Start with all scalar pointer uses.
4359 for (BasicBlock *BB : TheLoop->blocks())
4360 for (Instruction &I : *BB) {
4361 Instruction *PtrDef =
4363 if (PtrDef && TheLoop->contains(PtrDef) &&
4365 AddrDefs.insert(PtrDef);
4366 }
4367
4368 // Add all instructions used to generate the addresses.
4370 append_range(Worklist, AddrDefs);
4371 while (!Worklist.empty()) {
4372 Instruction *I = Worklist.pop_back_val();
4373 for (auto &Op : I->operands())
4374 if (auto *InstOp = dyn_cast<Instruction>(Op))
4375 if (TheLoop->contains(InstOp) && !isa<PHINode>(InstOp) &&
4376 AddrDefs.insert(InstOp))
4377 Worklist.push_back(InstOp);
4378 }
4379
4380 auto UpdateMemOpUserCost = [this, VF](LoadInst *LI) {
4381 // If there are direct memory op users of the newly scalarized load,
4382 // their cost may have changed because there's no scalarization
4383 // overhead for the operand. Update it.
4384 for (User *U : LI->users()) {
4386 continue;
4388 continue;
4389 auto UI = cast<Instruction>(U);
4390 LLVM_DEBUG(
4391 dbgs() << "LV: Memory widening: updating decision for load user "
4392 << *UI << '\n');
4394 UI, VF, CM_Scalarize,
4395 getMemInstScalarizationCost(cast<Instruction>(U), VF));
4396 }
4397 };
4398 for (auto *I : AddrDefs) {
4399 if (isa<LoadInst>(I)) {
4400 // Setting the desired widening decision should ideally be handled in
4401 // by cost functions, but since this involves the task of finding out
4402 // if the loaded register is involved in an address computation, it is
4403 // instead changed here when we know this is the case.
4404 InstWidening Decision = getWideningDecision(I, VF);
4405 if (!isPredicatedInst(I) &&
4406 (Decision == CM_Widen || Decision == CM_Widen_Reverse ||
4407 (!isUniformMemOp(*I, VF) && Decision == CM_Scalarize))) {
4408 // Scalarize a widened load of address or update the cost of a scalar
4409 // load of an address.
4410 LLVM_DEBUG(dbgs() << "LV: Memory widening: updating decision for load "
4411 << *I << '\n');
4413 I, VF, CM_Scalarize,
4414 (VF.getKnownMinValue() *
4415 getMemoryInstructionCost(I, ElementCount::getFixed(1))));
4416 UpdateMemOpUserCost(cast<LoadInst>(I));
4417 } else if (const auto *Group = getInterleavedAccessGroup(I)) {
4418 // Scalarize all members of this interleaved group when any member
4419 // is used as an address. The address-used load skips scalarization
4420 // overhead, other members include it.
4421 for (Instruction *Member : Group->members()) {
4422 InstructionCost Cost = AddrDefs.contains(Member)
4423 ? (VF.getKnownMinValue() *
4424 getMemoryInstructionCost(
4425 Member, ElementCount::getFixed(1)))
4426 : getMemInstScalarizationCost(Member, VF);
4427 LLVM_DEBUG(
4428 dbgs()
4429 << "LV: Memory widening: updating decision for interleave member "
4430 << *Member << '\n');
4432 UpdateMemOpUserCost(cast<LoadInst>(Member));
4433 }
4434 }
4435 } else {
4436 // Cannot scalarize fixed-order recurrence phis at the moment.
4437 if (isa<PHINode>(I) && Legal->isFixedOrderRecurrence(cast<PHINode>(I)))
4438 continue;
4439
4440 // Make sure I gets scalarized and a cost estimate without
4441 // scalarization overhead.
4442 ForcedScalars[VF].insert(I);
4443 }
4444 }
4445}
4446
4448 if (!Legal->isInvariant(Op))
4449 return false;
4450 // Consider Op invariant, if it or its operands aren't predicated
4451 // instruction in the loop. In that case, it is not trivially hoistable.
4452 auto *OpI = dyn_cast<Instruction>(Op);
4453 return !OpI || !TheLoop->contains(OpI) ||
4454 (!isPredicatedInst(OpI) &&
4455 (!isa<PHINode>(OpI) || OpI->getParent() != TheLoop->getHeader()) &&
4456 all_of(OpI->operands(),
4457 [this](Value *Op) { return shouldConsiderInvariant(Op); }));
4458}
4459
4462 ElementCount VF) {
4463 // If we know that this instruction will remain uniform, check the cost of
4464 // the scalar version.
4466 VF = ElementCount::getFixed(1);
4467
4468 if (VF.isVector() && isProfitableToScalarize(I, VF))
4469 return InstsToScalarize[VF][I];
4470
4471 // Forced scalars do not have any scalarization overhead.
4472 auto ForcedScalar = ForcedScalars.find(VF);
4473 if (VF.isVector() && ForcedScalar != ForcedScalars.end()) {
4474 auto InstSet = ForcedScalar->second;
4475 if (InstSet.count(I))
4477 VF.getKnownMinValue();
4478 }
4479
4480 const auto &MinBWs = Config.getMinimalBitwidths();
4481 uint64_t InstrMinBWs = MinBWs.lookup(I);
4482 Type *RetTy = I->getType();
4484 RetTy = IntegerType::get(RetTy->getContext(), InstrMinBWs);
4485 auto *SE = PSE.getSE();
4486
4487 Type *VectorTy;
4488 if (isScalarAfterVectorization(I, VF)) {
4489 [[maybe_unused]] auto HasSingleCopyAfterVectorization =
4490 [this](Instruction *I, ElementCount VF) -> bool {
4491 if (VF.isScalar())
4492 return true;
4493
4494 auto Scalarized = InstsToScalarize.find(VF);
4495 assert(Scalarized != InstsToScalarize.end() &&
4496 "VF not yet analyzed for scalarization profitability");
4497 return !Scalarized->second.count(I) &&
4498 llvm::all_of(I->users(), [&](User *U) {
4499 auto *UI = cast<Instruction>(U);
4500 return !Scalarized->second.count(UI);
4501 });
4502 };
4503
4504 // With the exception of GEPs and PHIs, after scalarization there should
4505 // only be one copy of the instruction generated in the loop. This is
4506 // because the VF is either 1, or any instructions that need scalarizing
4507 // have already been dealt with by the time we get here. As a result,
4508 // it means we don't have to multiply the instruction cost by VF.
4509 assert(I->getOpcode() == Instruction::GetElementPtr ||
4510 I->getOpcode() == Instruction::PHI ||
4511 (I->getOpcode() == Instruction::BitCast &&
4512 I->getType()->isPointerTy()) ||
4513 HasSingleCopyAfterVectorization(I, VF));
4514 VectorTy = RetTy;
4515 } else
4516 VectorTy = toVectorizedTy(RetTy, VF);
4517
4518 if (VF.isVector() && VectorTy->isVectorTy() &&
4519 !TTI.getNumberOfParts(VectorTy))
4521
4522 // TODO: We need to estimate the cost of intrinsic calls.
4523 switch (I->getOpcode()) {
4524 case Instruction::GetElementPtr:
4525 // We mark this instruction as zero-cost because the cost of GEPs in
4526 // vectorized code depends on whether the corresponding memory instruction
4527 // is scalarized or not. Therefore, we handle GEPs with the memory
4528 // instruction cost.
4529 return 0;
4530 case Instruction::UncondBr:
4531 case Instruction::CondBr: {
4532 // In cases of scalarized and predicated instructions, there will be VF
4533 // predicated blocks in the vectorized loop. Each branch around these
4534 // blocks requires also an extract of its vector compare i1 element.
4535 // Note that the conditional branch from the loop latch will be replaced by
4536 // a single branch controlling the loop, so there is no extra overhead from
4537 // scalarization.
4538 bool ScalarPredicatedBB = false;
4540 if (VF.isVector() && BI &&
4541 (PredicatedBBsAfterVectorization[VF].count(BI->getSuccessor(0)) ||
4542 PredicatedBBsAfterVectorization[VF].count(BI->getSuccessor(1))) &&
4543 BI->getParent() != TheLoop->getLoopLatch())
4544 ScalarPredicatedBB = true;
4545
4546 if (ScalarPredicatedBB) {
4547 // Not possible to scalarize scalable vector with predicated instructions.
4548 if (VF.isScalable())
4550 // Return cost for branches around scalarized and predicated blocks.
4551 auto *VecI1Ty =
4553 return (TTI.getScalarizationOverhead(
4554 VecI1Ty, APInt::getAllOnes(VF.getFixedValue()),
4555 /*Insert*/ false, /*Extract*/ true, Config.CostKind) +
4556 (TTI.getCFInstrCost(Instruction::CondBr, Config.CostKind) *
4557 VF.getFixedValue()));
4558 }
4559
4560 if (I->getParent() == TheLoop->getLoopLatch() || VF.isScalar())
4561 // The back-edge branch will remain, as will all scalar branches.
4562 return TTI.getCFInstrCost(Instruction::UncondBr, Config.CostKind);
4563
4564 // This branch will be eliminated by if-conversion.
4565 return 0;
4566 // Note: We currently assume zero cost for an unconditional branch inside
4567 // a predicated block since it will become a fall-through, although we
4568 // may decide in the future to call TTI for all branches.
4569 }
4570 case Instruction::Switch: {
4571 if (VF.isScalar())
4572 return TTI.getCFInstrCost(Instruction::Switch, Config.CostKind);
4573 auto *Switch = cast<SwitchInst>(I);
4574 return Switch->getNumCases() *
4575 TTI.getCmpSelInstrCost(
4576 Instruction::ICmp,
4577 toVectorTy(Switch->getCondition()->getType(), VF),
4578 toVectorTy(Type::getInt1Ty(I->getContext()), VF),
4579 CmpInst::ICMP_EQ, Config.CostKind);
4580 }
4581 case Instruction::PHI: {
4582 auto *Phi = cast<PHINode>(I);
4583
4584 // First-order recurrences are replaced by vector shuffles inside the loop.
4585 if (VF.isVector() && Legal->isFixedOrderRecurrence(Phi)) {
4586 return TTI.getShuffleCost(
4588 cast<VectorType>(VectorTy), Config.CostKind, {}, -1);
4589 }
4590
4591 // Phi nodes in non-header blocks (not inductions, reductions, etc.) are
4592 // converted into select instructions. We require N - 1 selects per phi
4593 // node, where N is the number of incoming values.
4594 if (VF.isVector() && Phi->getParent() != TheLoop->getHeader()) {
4595 Type *ResultTy = Phi->getType();
4596
4597 // All instructions in an Any-of reduction chain are narrowed to bool.
4598 // Check if that is the case for this phi node.
4599 auto *HeaderUser = find_singleton<PHINode>(
4600 Phi->users(), [this](User *U, bool) -> PHINode * {
4601 auto *Phi = dyn_cast<PHINode>(U);
4602 if (Phi && Phi->getParent() == TheLoop->getHeader())
4603 return Phi;
4604 return nullptr;
4605 });
4606 if (HeaderUser) {
4607 auto &ReductionVars = Legal->getReductionVars();
4608 auto Iter = ReductionVars.find(HeaderUser);
4609 if (Iter != ReductionVars.end() &&
4611 Iter->second.getRecurrenceKind()))
4612 ResultTy = Type::getInt1Ty(Phi->getContext());
4613 }
4614 return (Phi->getNumIncomingValues() - 1) *
4615 TTI.getCmpSelInstrCost(
4616 Instruction::Select, toVectorTy(ResultTy, VF),
4617 toVectorTy(Type::getInt1Ty(Phi->getContext()), VF),
4618 CmpInst::BAD_ICMP_PREDICATE, Config.CostKind);
4619 }
4620
4621 // When tail folding with EVL, if the phi is part of an out of loop
4622 // reduction then it will be transformed into a wide vp_merge.
4623 if (VF.isVector() && foldTailWithEVL() &&
4624 Legal->getReductionVars().contains(Phi) &&
4625 !Config.isInLoopReduction(Phi)) {
4627 Intrinsic::vp_merge, toVectorTy(Phi->getType(), VF),
4628 {toVectorTy(Type::getInt1Ty(Phi->getContext()), VF)});
4629 return TTI.getIntrinsicInstrCost(ICA, Config.CostKind);
4630 }
4631
4632 return TTI.getCFInstrCost(Instruction::PHI, Config.CostKind);
4633 }
4634 case Instruction::UDiv:
4635 case Instruction::SDiv:
4636 case Instruction::URem:
4637 case Instruction::SRem:
4638 if (VF.isVector() && isPredicatedInst(I)) {
4639 const auto [ScalarCost, MaskedCost] = getDivRemSpeculationCost(I, VF);
4640 return isDivRemScalarWithPredication(ScalarCost, MaskedCost) ? ScalarCost
4641 : MaskedCost;
4642 }
4643 // We've proven all lanes safe to speculate, fall through.
4644 [[fallthrough]];
4645 case Instruction::Add:
4646 case Instruction::Sub: {
4647 const HistogramInfo *HGram = Legal->getHistogramInfo(I);
4648 if (HGram && VF.isVector()) {
4649 // Assume that a non-constant update value (or a constant != 1) requires
4650 // a multiply, and add that into the cost.
4652 ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1));
4653 if (!RHS || RHS->getZExtValue() != 1)
4654 MulCost = TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy,
4655 Config.CostKind);
4656
4657 // Find the cost of the histogram operation itself.
4658 Type *PtrTy = VectorType::get(HGram->Load->getPointerOperandType(), VF);
4659 Type *ScalarTy = I->getType();
4660 Type *MaskTy = VectorType::get(Type::getInt1Ty(I->getContext()), VF);
4661 IntrinsicCostAttributes ICA(Intrinsic::experimental_vector_histogram_add,
4662 Type::getVoidTy(I->getContext()),
4663 {PtrTy, ScalarTy, MaskTy});
4664
4665 // Add the costs together with the add/sub operation.
4666 return TTI.getIntrinsicInstrCost(ICA, Config.CostKind) + MulCost +
4667 TTI.getArithmeticInstrCost(I->getOpcode(), VectorTy,
4668 Config.CostKind);
4669 }
4670 [[fallthrough]];
4671 }
4672 case Instruction::FAdd:
4673 case Instruction::FSub:
4674 case Instruction::Mul:
4675 case Instruction::FMul:
4676 case Instruction::FDiv:
4677 case Instruction::FRem:
4678 case Instruction::Shl:
4679 case Instruction::LShr:
4680 case Instruction::AShr:
4681 case Instruction::And:
4682 case Instruction::Or:
4683 case Instruction::Xor: {
4684 // If we're speculating on the stride being 1, the multiplication may
4685 // fold away. We can generalize this for all operations using the notion
4686 // of neutral elements. (TODO)
4687 if (I->getOpcode() == Instruction::Mul &&
4688 ((TheLoop->isLoopInvariant(I->getOperand(0)) &&
4689 PSE.getSCEV(I->getOperand(0))->isOne()) ||
4690 (TheLoop->isLoopInvariant(I->getOperand(1)) &&
4691 PSE.getSCEV(I->getOperand(1))->isOne())))
4692 return 0;
4693
4694 // Certain instructions can be cheaper to vectorize if they have a constant
4695 // second vector operand. One example of this are shifts on x86.
4696 Value *Op2 = I->getOperand(1);
4697 if (!isa<Constant>(Op2) && TheLoop->isLoopInvariant(Op2) &&
4698 PSE.getSE()->isSCEVable(Op2->getType()) &&
4699 isa<SCEVConstant>(PSE.getSCEV(Op2))) {
4700 Op2 = cast<SCEVConstant>(PSE.getSCEV(Op2))->getValue();
4701 }
4702 auto Op2Info = TTI.getOperandInfo(Op2);
4703 if (Op2Info.Kind == TargetTransformInfo::OK_AnyValue &&
4706
4707 SmallVector<const Value *, 4> Operands(I->operand_values());
4708 return TTI.getArithmeticInstrCost(
4709 I->getOpcode(), VectorTy, Config.CostKind,
4710 {TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None},
4711 Op2Info, Operands, I, TLI);
4712 }
4713 case Instruction::FNeg: {
4714 return TTI.getArithmeticInstrCost(
4715 I->getOpcode(), VectorTy, Config.CostKind,
4716 {TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None},
4717 {TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None},
4718 I->getOperand(0), I);
4719 }
4720 case Instruction::Select: {
4722 const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
4723 bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
4724
4725 const Value *Op0, *Op1;
4726 using namespace llvm::PatternMatch;
4727 if (!ScalarCond && (match(I, m_LogicalAnd(m_Value(Op0), m_Value(Op1))) ||
4728 match(I, m_LogicalOr(m_Value(Op0), m_Value(Op1))))) {
4729 // select x, y, false --> x & y
4730 // select x, true, y --> x | y
4731 const auto [Op1VK, Op1VP] = TTI::getOperandInfo(Op0);
4732 const auto [Op2VK, Op2VP] = TTI::getOperandInfo(Op1);
4733 assert(Op0->getType()->getScalarSizeInBits() == 1 &&
4734 Op1->getType()->getScalarSizeInBits() == 1);
4735
4736 return TTI.getArithmeticInstrCost(
4737 match(I, m_LogicalOr()) ? Instruction::Or : Instruction::And,
4738 VectorTy, Config.CostKind, {Op1VK, Op1VP}, {Op2VK, Op2VP}, {Op0, Op1},
4739 I);
4740 }
4741
4742 Type *CondTy = SI->getCondition()->getType();
4743 if (!ScalarCond)
4744 CondTy = VectorType::get(CondTy, VF);
4745
4747 if (auto *Cmp = dyn_cast<CmpInst>(SI->getCondition()))
4748 Pred = Cmp->getPredicate();
4749 return TTI.getCmpSelInstrCost(
4750 I->getOpcode(), VectorTy, CondTy, Pred, Config.CostKind,
4751 {TTI::OK_AnyValue, TTI::OP_None}, {TTI::OK_AnyValue, TTI::OP_None}, I);
4752 }
4753 case Instruction::ICmp:
4754 case Instruction::FCmp: {
4755 Type *ValTy = I->getOperand(0)->getType();
4756
4758 [[maybe_unused]] Instruction *Op0AsInstruction =
4759 dyn_cast<Instruction>(I->getOperand(0));
4760 assert((!canTruncateToMinimalBitwidth(Op0AsInstruction, VF) ||
4761 InstrMinBWs == MinBWs.lookup(Op0AsInstruction)) &&
4762 "if both the operand and the compare are marked for "
4763 "truncation, they must have the same bitwidth");
4764 ValTy = IntegerType::get(ValTy->getContext(), InstrMinBWs);
4765 }
4766
4767 VectorTy = toVectorTy(ValTy, VF);
4768 return TTI.getCmpSelInstrCost(
4769 I->getOpcode(), VectorTy, CmpInst::makeCmpResultType(VectorTy),
4770 cast<CmpInst>(I)->getPredicate(), Config.CostKind,
4771 {TTI::OK_AnyValue, TTI::OP_None}, {TTI::OK_AnyValue, TTI::OP_None}, I);
4772 }
4773 case Instruction::Store:
4774 case Instruction::Load: {
4775 ElementCount Width = VF;
4776 if (Width.isVector()) {
4777 InstWidening Decision = getWideningDecision(I, Width);
4778 assert(Decision != CM_Unknown &&
4779 "CM decision should be taken at this point");
4782 if (Decision == CM_Scalarize)
4783 Width = ElementCount::getFixed(1);
4784 }
4785 VectorTy = toVectorTy(getLoadStoreType(I), Width);
4786 return getMemoryInstructionCost(I, VF);
4787 }
4788 case Instruction::BitCast:
4789 if (I->getType()->isPointerTy())
4790 return 0;
4791 [[fallthrough]];
4792 case Instruction::ZExt:
4793 case Instruction::SExt:
4794 case Instruction::FPToUI:
4795 case Instruction::FPToSI:
4796 case Instruction::FPExt:
4797 case Instruction::PtrToInt:
4798 case Instruction::IntToPtr:
4799 case Instruction::SIToFP:
4800 case Instruction::UIToFP:
4801 case Instruction::Trunc:
4802 case Instruction::FPTrunc: {
4803 // Computes the CastContextHint from a Load/Store instruction.
4804 auto ComputeCCH = [&](Instruction *I) -> TTI::CastContextHint {
4806 "Expected a load or a store!");
4807
4808 if (VF.isScalar() || !TheLoop->contains(I))
4810
4811 switch (getWideningDecision(I, VF)) {
4818 // TODO: Add 'Compressed' hint (not needed for any targets yet).
4819 if (Legal->isCompressedLoadOrStore(I))
4826 llvm_unreachable("Instr did not go through cost modelling?");
4829 }
4830
4831 llvm_unreachable("Unhandled case!");
4832 };
4833
4834 unsigned Opcode = I->getOpcode();
4836 // For Trunc, the context is the only user, which must be a StoreInst.
4837 if (Opcode == Instruction::Trunc || Opcode == Instruction::FPTrunc) {
4838 if (I->hasOneUse())
4839 if (StoreInst *Store = dyn_cast<StoreInst>(*I->user_begin()))
4840 CCH = ComputeCCH(Store);
4841 }
4842 // For Z/Sext, the context is the operand, which must be a LoadInst.
4843 else if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt ||
4844 Opcode == Instruction::FPExt) {
4845 if (LoadInst *Load = dyn_cast<LoadInst>(I->getOperand(0)))
4846 CCH = ComputeCCH(Load);
4847 }
4848
4849 // We optimize the truncation of induction variables having constant
4850 // integer steps. The cost of these truncations is the same as the scalar
4851 // operation.
4852 if (isOptimizableIVTruncate(I, VF)) {
4853 auto *Trunc = cast<TruncInst>(I);
4854 return TTI.getCastInstrCost(Instruction::Trunc, Trunc->getDestTy(),
4855 Trunc->getSrcTy(), CCH, Config.CostKind,
4856 Trunc);
4857 }
4858
4859 Type *SrcScalarTy = I->getOperand(0)->getType();
4860 Instruction *Op0AsInstruction = dyn_cast<Instruction>(I->getOperand(0));
4861 if (canTruncateToMinimalBitwidth(Op0AsInstruction, VF))
4862 SrcScalarTy = IntegerType::get(SrcScalarTy->getContext(),
4863 MinBWs.lookup(Op0AsInstruction));
4864 Type *SrcVecTy =
4865 VectorTy->isVectorTy() ? toVectorTy(SrcScalarTy, VF) : SrcScalarTy;
4866
4868 // If the result type is <= the source type, there will be no extend
4869 // after truncating the users to the minimal required bitwidth.
4870 if (VectorTy->getScalarSizeInBits() <= SrcVecTy->getScalarSizeInBits() &&
4871 (I->getOpcode() == Instruction::ZExt ||
4872 I->getOpcode() == Instruction::SExt))
4873 return 0;
4874 }
4875
4876 return TTI.getCastInstrCost(Opcode, VectorTy, SrcVecTy, CCH,
4877 Config.CostKind, I);
4878 }
4879 case Instruction::Call:
4880 return getVectorCallCost(cast<CallInst>(I), VF);
4881 case Instruction::ExtractValue:
4882 return TTI.getInstructionCost(I, Config.CostKind);
4883 case Instruction::Alloca:
4884 // We cannot easily widen alloca to a scalable alloca, as
4885 // the result would need to be a vector of pointers.
4886 if (VF.isScalable())
4888 return TTI.getArithmeticInstrCost(Instruction::Mul, RetTy, Config.CostKind);
4889 case Instruction::Freeze:
4890 return TTI::TCC_Free;
4891 default:
4892 // This opcode is unknown. Assume that it is the same as 'mul'.
4893 return TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy,
4894 Config.CostKind);
4895 } // end of switch.
4896}
4897
4899 // Ignore ephemeral values.
4901
4902 SmallVector<Value *, 4> DeadInterleavePointerOps;
4904
4905 // If a scalar epilogue is required, users outside the loop won't use
4906 // live-outs from the vector loop but from the scalar epilogue. Ignore them if
4907 // that is the case.
4908 bool RequiresScalarEpilogue = requiresScalarEpilogue(true);
4909 auto IsLiveOutDead = [this, RequiresScalarEpilogue](User *U) {
4910 return RequiresScalarEpilogue &&
4911 !TheLoop->contains(cast<Instruction>(U)->getParent());
4912 };
4913
4914 // Returns true if the address of interleaved access I is used by its group.
4915 // VPlan uses the address of member 0 for store groups. For load groups, it
4916 // may use the address of the insert position instead.
4917 auto IsGroupAddress = [this](Instruction *I) {
4918 auto *Group = getInterleavedAccessGroup(I);
4919 return isa<StoreInst>(I) ? Group->getMember(0) == I
4920 : Group->getInsertPos() == I;
4921 };
4922
4924 DFS.perform(LI);
4925 for (BasicBlock *BB : reverse(make_range(DFS.beginRPO(), DFS.endRPO())))
4926 for (Instruction &I : reverse(*BB)) {
4927 if (VecValuesToIgnore.contains(&I) || ValuesToIgnore.contains(&I))
4928 continue;
4929
4930 // Add instructions that would be trivially dead and are only used by
4931 // values already ignored to DeadOps to seed worklist.
4933 all_of(I.users(), [this, IsLiveOutDead](User *U) {
4934 return VecValuesToIgnore.contains(U) ||
4935 ValuesToIgnore.contains(U) || IsLiveOutDead(U);
4936 }))
4937 DeadOps.push_back(&I);
4938
4939 // For interleave groups, we only create a pointer for the start of the
4940 // interleave group. Queue up addresses of group members not used by the
4941 // group for further processing.
4942 if (isAccessInterleaved(&I)) {
4943 if (IsGroupAddress(&I))
4944 continue;
4945 Value *PointerOp = getLoadStorePointerOperand(&I);
4946 DeadInterleavePointerOps.push_back(PointerOp);
4947 }
4948
4949 // Queue branches for analysis. They are dead, if their successors only
4950 // contain dead instructions.
4951 if (isa<CondBrInst>(&I))
4952 DeadOps.push_back(&I);
4953 }
4954
4955 // Mark ops feeding interleave group members as free, if they are only used
4956 // by other dead computations.
4957 for (unsigned I = 0; I != DeadInterleavePointerOps.size(); ++I) {
4958 auto *Op = dyn_cast<Instruction>(DeadInterleavePointerOps[I]);
4959 if (!Op || !TheLoop->contains(Op) ||
4960 any_of(Op->users(), [this, &IsGroupAddress](User *U) {
4961 Instruction *UI = cast<Instruction>(U);
4962 return !VecValuesToIgnore.contains(U) &&
4963 (!isAccessInterleaved(UI) || IsGroupAddress(UI));
4964 }))
4965 continue;
4966 VecValuesToIgnore.insert(Op);
4967 append_range(DeadInterleavePointerOps, Op->operands());
4968 }
4969
4970 // Mark ops that would be trivially dead and are only used by ignored
4971 // instructions as free.
4972 BasicBlock *Header = TheLoop->getHeader();
4973
4974 // Returns true if the block contains only dead instructions. Such blocks will
4975 // be removed by VPlan-to-VPlan transforms and won't be considered by the
4976 // VPlan-based cost model, so skip them in the legacy cost-model as well.
4977 auto IsEmptyBlock = [this](BasicBlock *BB) {
4978 return all_of(*BB, [this](Instruction &I) {
4979 return ValuesToIgnore.contains(&I) || VecValuesToIgnore.contains(&I) ||
4981 });
4982 };
4983 SmallPtrSet<Instruction *, 16> ProcessedDeadOps;
4984 for (unsigned I = 0; I != DeadOps.size(); ++I) {
4985 auto *Op = dyn_cast<Instruction>(DeadOps[I]);
4986
4987 // Check if the branch should be considered dead.
4988 if (auto *Br = dyn_cast_or_null<CondBrInst>(Op)) {
4989 BasicBlock *ThenBB = Br->getSuccessor(0);
4990 BasicBlock *ElseBB = Br->getSuccessor(1);
4991 // Don't considers branches leaving the loop for simplification.
4992 if (!TheLoop->contains(ThenBB) || !TheLoop->contains(ElseBB))
4993 continue;
4994 bool ThenEmpty = IsEmptyBlock(ThenBB);
4995 bool ElseEmpty = IsEmptyBlock(ElseBB);
4996 if ((ThenEmpty && ElseEmpty) ||
4997 (ThenEmpty && ThenBB->getSingleSuccessor() == ElseBB &&
4998 ElseBB->phis().empty()) ||
4999 (ElseEmpty && ElseBB->getSingleSuccessor() == ThenBB &&
5000 ThenBB->phis().empty())) {
5001 VecValuesToIgnore.insert(Br);
5002 DeadOps.push_back(Br->getCondition());
5003 }
5004 continue;
5005 }
5006
5007 // Skip any op that shouldn't be considered dead.
5008 if (!Op || !TheLoop->contains(Op) ||
5009 (isa<PHINode>(Op) && Op->getParent() == Header) ||
5011 any_of(Op->users(), [this, IsLiveOutDead](User *U) {
5012 return !VecValuesToIgnore.contains(U) &&
5013 !ValuesToIgnore.contains(U) && !IsLiveOutDead(U);
5014 }))
5015 continue;
5016
5017 // If all of Op's users are in ValuesToIgnore, add it to ValuesToIgnore
5018 // which applies for both scalar and vector versions. Otherwise it is only
5019 // dead in vector versions, so only add it to VecValuesToIgnore.
5020 bool BecameScalarDead = false;
5021 if (all_of(Op->users(),
5022 [this](User *U) { return ValuesToIgnore.contains(U); }))
5023 BecameScalarDead = ValuesToIgnore.insert(Op).second;
5024
5025 VecValuesToIgnore.insert(Op);
5026 // Shared operands may be queued more than once. Propagate deadness once,
5027 // and again if an instruction previously dead only in the vector loop
5028 // becomes dead in the scalar loop too.
5029 if (ProcessedDeadOps.insert(Op).second || BecameScalarDead)
5030 append_range(DeadOps, Op->operands());
5031 }
5032
5033 // Ignore type-promoting instructions we identified during reduction
5034 // detection.
5035 for (const RecurrenceDescriptor &RedDes :
5036 Legal->getReductionVars().values()) {
5037 VecValuesToIgnore.insert_range(RedDes.getCastInsts());
5038 }
5039 // Ignore type-casting instructions we identified during induction
5040 // detection.
5041 for (const InductionDescriptor &IndDes : Legal->getInductionVars().values())
5042 VecValuesToIgnore.insert_range(IndDes.getCastInsts());
5043}
5044
5045void LoopVectorizationPlanner::plan(ElementCount UserVF, unsigned UserIC) {
5046 CM->collectValuesToIgnore();
5047 Config.collectElementTypesForWidening(&CM->ValuesToIgnore);
5048
5049 FixedScalableVFPair MaxFactors = CM->computeMaxVF(UserVF, UserIC);
5050 if (!MaxFactors) // Cases that should not to be vectorized nor interleaved.
5051 return;
5052
5053 Config.collectInLoopReductions();
5054 // Cases that may be vectorized may be optimized by unit stride predicates.
5055 // TODO: Currently unit stride predicates are added unconditionally, even if
5056 // they are not used for the selected VF (e.g. when only interleaving).
5057 if (MaxFactors.FixedVF.isVector() || MaxFactors.ScalableVF.isVector())
5058 Legal->collectUnitStridePredicates();
5059
5060 auto VPlan1 = tryToBuildVPlan1(*CM);
5061 if (!VPlan1)
5062 return;
5063
5064 LLVM_DEBUG(dbgs() << "LV: VPlan created successfully. Loop can be "
5065 "vectorized.\n");
5066
5067 if (!OrigLoop->isInnermost()) {
5068 // For outer loops, computeMaxVF returns a single non-scalar VF; build a
5069 // plan for that VF only.
5070 ElementCount VF =
5071 MaxFactors.FixedVF ? MaxFactors.FixedVF : MaxFactors.ScalableVF;
5072 buildVPlans(*VPlan1, VF, VF, *CM);
5074 return;
5075 }
5076
5077 // Compute the minimal bitwidths required for integer operations in the loop
5078 // for later use by the cost model.
5079 Config.computeMinimalBitwidths();
5080
5081 // Invalidate interleave groups if all blocks of loop will be predicated.
5082 if (CM->blockNeedsPredicationForAnyReason(OrigLoop->getHeader()) &&
5083 !useMaskedInterleavedAccesses(Opts, TTI)) {
5084 LLVM_DEBUG(dbgs() << "LV: Invalidate all interleaved groups due to "
5085 "predication which requires masked-interleaved "
5086 "support.\n");
5087 if (CM->InterleaveInfo.invalidateGroups())
5088 // Invalidating interleave groups also requires invalidating all decisions
5089 // based on them, which includes widening decisions and uniform and scalar
5090 // values.
5091 CM->invalidateCostModelingDecisions();
5092 }
5093
5094 if (CM->foldTailByMasking())
5095 Legal->prepareToFoldTailByMasking();
5096
5097 ElementCount MaxUserVF =
5098 UserVF.isScalable() ? MaxFactors.ScalableVF : MaxFactors.FixedVF;
5099 if (UserVF) {
5100 if (!ElementCount::isKnownLE(UserVF, MaxUserVF)) {
5102 "UserVF ignored because it may be larger than the maximal safe VF",
5103 "InvalidUserVF", ORE, OrigLoop);
5104 } else {
5105 assert(UserVF.isPowerOf2() && "VF needs to be a power of two");
5106 // Collect the instructions (and their associated costs) that will be more
5107 // profitable to scalarize.
5108 CM->collectNonVectorizedAndSetWideningDecisions(UserVF);
5109 buildVPlans(*VPlan1, UserVF, UserVF, *CM);
5110
5111 // For scalar VF, skip VPlan cost check as VPlan cost is designed for
5112 // vector VFs only.
5113 if (!VPlans.empty() && (VPlans.front()->getSingleVF() == UserVF) &&
5114 (UserVF.isScalar() ||
5115 cost(*VPlans.front(), UserVF, /*RU=*/nullptr, *CM).isValid())) {
5116 // Plan for epilogue only if we succeeded in building the Vplan for the
5117 // main loop.
5118 // Try to build a tail-folded epilogue Vplan. Otherwise build a regular
5119 // plan for the epilogue:
5120 if (!planForEpilogueTF()) {
5122 if (EpilogueUserVF.isVector() &&
5123 ElementCount::isKnownLT(EpilogueUserVF, UserVF)) {
5124 CM->collectNonVectorizedAndSetWideningDecisions(EpilogueUserVF);
5125 buildVPlans(*VPlan1, EpilogueUserVF, EpilogueUserVF, *CM);
5126 }
5127 }
5128 LLVM_DEBUG(dbgs() << "LV: Using user VF " << UserVF << ".\n");
5130 return;
5131 }
5132 VPlans.clear();
5133 reportVectorizationInfo("UserVF ignored because of invalid costs.",
5134 "InvalidCost", ORE, OrigLoop);
5135 }
5136 }
5137
5138 // Collect the Vectorization Factor Candidates.
5139 SmallVector<ElementCount> VFCandidates;
5140 for (auto VF = ElementCount::getFixed(1);
5141 ElementCount::isKnownLE(VF, MaxFactors.FixedVF); VF *= 2)
5142 VFCandidates.push_back(VF);
5143 for (auto VF = ElementCount::getScalable(1);
5144 ElementCount::isKnownLE(VF, MaxFactors.ScalableVF); VF *= 2)
5145 VFCandidates.push_back(VF);
5146
5147 for (const auto &VF : VFCandidates) {
5148 // Collect Uniform and Scalar instructions after vectorization with VF.
5149 CM->collectNonVectorizedAndSetWideningDecisions(VF);
5150 }
5151
5152 buildVPlans(*VPlan1, ElementCount::getFixed(1), MaxFactors.FixedVF, *CM);
5153 buildVPlans(*VPlan1, ElementCount::getScalable(1), MaxFactors.ScalableVF,
5154 *CM);
5155
5157}
5158
5159bool LoopVectorizationPlanner::planForEpilogueTF() {
5160 EpilogueLowering EpilogueTailLoweringStatus = getEpilogueTailLowering(
5161 Opts, *CM, OrigLoop, ORE, *Legal, Config.getHints(), &TTI);
5162 if (EpilogueTailLoweringStatus !=
5164 return false;
5165 LLVM_DEBUG(dbgs() << "LV: epilogue tail-folding is enabled\n");
5166
5167 LoopVectorizationCostModel EpilogueTfCM(
5168 EpilogueTailLoweringStatus, OrigLoop, PSE, LI, Legal, TTI, TLI, CM->AC,
5169 ORE, CM->GetBFI, CM->TheFunction, CM->InterleaveInfo, Config);
5170
5171 assert(!EpilogueTfCM.isEpilogueAllowed() &&
5172 "Epilogue tail-folding is expected to be enabled");
5173
5174 LLVM_DEBUG(dbgs() << "LV: plan for tail-folded epilogue\n");
5175
5176 EpilogueTfCM.ValuesToIgnore.insert_range(CM->ValuesToIgnore);
5177 EpilogueTfCM.VecValuesToIgnore.insert_range(CM->VecValuesToIgnore);
5178
5179 FixedScalableVFPair MaxFactors =
5180 EpilogueTfCM.computeMaxVF(EpilogueVectorizationForceVF, /*UserIC*/ 1);
5181 // TODO: Validate the epilogue VF against MaxFactors.
5182 // That validation is ignored for now because computeMaxVF returns 0 for
5183 // max safe scalable VF when UserVF is not scalable, and at that case having
5184 // scalable epilogue VF is considered unsafe which is inaccurate.
5185 if (!MaxFactors || !EpilogueTfCM.foldTailByMasking()) {
5186 // Cases that should not be vectorized or tail-folded.
5187 reportVectorizationInfo("This case of epilogue loop can't be tail-folded",
5188 "InvalidTailFoldedEpilogue", ORE, OrigLoop);
5189 return false;
5190 }
5191
5192 if (EpilogueTfCM.getTailFoldingStyle() !=
5194 reportVectorizationInfo("Right now tail-folded epilogue is supported only "
5195 "for DataAndControlFlow tail-folding style.",
5196 "InvalidTailFoldedEpilogue", ORE, OrigLoop);
5197 return false;
5198 }
5199
5200 auto VPlan1 = tryToBuildVPlan1(EpilogueTfCM);
5201
5202 if (!VPlan1) {
5204 "Failed to build initial tail-folded epilogue VPlan",
5205 "InvalidTailFoldedEpilogue", ORE, OrigLoop);
5206 return false;
5207 }
5208
5209 Legal->prepareToFoldTailByMasking();
5210
5211 // Collect the instructions (and their associated costs) that will be more
5212 // profitable to scalarize.
5213 EpilogueTfCM.collectNonVectorizedAndSetWideningDecisions(
5215
5216 [[maybe_unused]] size_t NumPlansBefore = VPlans.size();
5217 buildVPlans(*VPlan1, EpilogueVectorizationForceVF,
5218 EpilogueVectorizationForceVF, EpilogueTfCM);
5219
5220 // Check that a Vplan is successfully built:
5221 assert(VPlans.size() == NumPlansBefore + 1 &&
5222 "Expected to build a single tail-folded VPlan");
5223 VPlan &Plan = *VPlans.back();
5225 Plan.hasTailFolded() &&
5226 "Expected to build a valid tail-folded VPlan with epilogue VF");
5227
5228 // Validate that VPlan has a mask to make sure that the epilogue loop
5229 // terminates correctly:
5233 "Tail-folded epilogue has no active-lane-mask exit, so it may not "
5234 "terminate, can't apply tail-folded epilogue",
5235 "InvalidTailFoldedEpilogue", ORE, OrigLoop);
5236 VPlans.pop_back();
5237 return false;
5238 }
5239
5240 if (!cost(Plan, EpilogueVectorizationForceVF, /*RU=*/nullptr, EpilogueTfCM)
5241 .isValid()) {
5242 VPlans.pop_back();
5243 reportVectorizationInfo("This case of epilogue loop can't be tail-folded "
5244 "- Invalid costs",
5245 "InvalidTailFoldedEpilogue", ORE, OrigLoop);
5246 return false;
5247 }
5248 LLVM_DEBUG(dbgs() << "LV: Tail-folded epilogue VPlan is created\n");
5249 return true;
5250}
5251
5255 bool ReusePrintingSlotTracker)
5256 : Opts(Config.getOpts()), TTI(Config.getTTI()), TLI(TLI),
5257 LLVMCtx(Plan.getContext()), CM(CM), Config(Config),
5258 CostKind(Config.CostKind), PSE(Config.getPSE()), L(Config.getLoop()) {
5259#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
5260 if (ReusePrintingSlotTracker)
5261 PlanForSlotTracker = &Plan;
5262#endif
5263}
5264
5266 ElementCount VF) const {
5267 InstructionCost Cost = CM.getInstructionCost(UI, VF);
5268 if (Cost.isValid() && Opts.force_target_instruction_cost)
5269 return InstructionCost(*Opts.force_target_instruction_cost);
5270 return Cost;
5271}
5272
5273bool VPCostContext::skipCostComputation(Instruction *UI, bool IsVector) const {
5274 return CM.ValuesToIgnore.contains(UI) ||
5275 (IsVector && CM.VecValuesToIgnore.contains(UI)) ||
5276 SkipCostComputation.contains(UI);
5277}
5278
5284
5286 return CM.isScalarWithPredication(I, VF) ||
5287 CM.isUniformAfterVectorization(I, VF) || CM.isForcedScalar(I, VF) ||
5288 (VF.isVector() && CM.isProfitableToScalarize(I, VF));
5289}
5290
5292 return CM.isMaskRequired(I);
5293}
5294
5298 return TC && TC->getValue().ule(VF.getKnownMinValue());
5299}
5300
5302LoopVectorizationPlanner::precomputeCosts(VPlan &Plan, ElementCount VF,
5303 VPCostContext &CostCtx) const {
5305
5306 // If the vector loop gets executed exactly once with the given VF, ignore the
5307 // costs of comparison and induction instructions, as they'll get simplified
5308 // away.
5309 // TODO: Remove this code after stepping away from the legacy cost model and
5310 // adding code to simplify VPlans before calculating their costs.
5311 auto TC = getSmallConstantTripCount(PSE.getSE(), OrigLoop);
5312 if (TC == VF && !Plan.hasTailFolded())
5313 addFullyUnrolledInstructionsToIgnore(OrigLoop, Legal->getInductionVars(),
5314 CostCtx.SkipCostComputation);
5315
5316 // Don't apply special costs when instruction cost is forced to make sure the
5317 // forced cost is used for each recipe.
5318 if (Opts.force_target_instruction_cost)
5319 return Cost;
5320
5321 // Only charge legacy scalarization costs for instructions VPlan replicates,
5322 // and for forced scalars only if VPlan replicates them per lane.
5323 SmallPtrSet<Instruction *, 8> Replicated, ReplicatedPerLane;
5327 Replicated.insert(RepR.getUnderlyingInstr());
5328 if (!RepR.isSingleScalar())
5329 ReplicatedPerLane.insert(RepR.getUnderlyingInstr());
5330 }
5331
5332 // Pre-compute costs for instructions that are forced-scalar or profitable to
5333 // scalarize. For most such instructions, their scalarization costs are
5334 // accounted for here using the legacy cost model. However, some opcodes
5335 // (see UseVPlanCostModel below) and instructions VPlan does not replicate
5336 // are excluded and instead modeled by the VPlan cost model.
5337 for (Instruction *ForcedScalar : CostCtx.CM.ForcedScalars[VF]) {
5338 if (!ReplicatedPerLane.contains(ForcedScalar) ||
5339 CostCtx.skipCostComputation(ForcedScalar, VF.isVector()))
5340 continue;
5341 CostCtx.SkipCostComputation.insert(ForcedScalar);
5342 InstructionCost ForcedCost = CostCtx.getLegacyCost(ForcedScalar, VF);
5343 LLVM_DEBUG({
5344 dbgs() << "Cost of " << ForcedCost << " for VF " << VF
5345 << ": forced scalar " << *ForcedScalar << "\n";
5346 });
5347 Cost += ForcedCost;
5348 }
5349
5350 // Don't apply legacy scalarization costs if nothing remains scalar &
5351 // predicated.
5352 if (!hasReplicatorRegion(Plan))
5353 return Cost;
5354
5355 auto UseVPlanCostModel = [](Instruction *I) -> bool {
5356 switch (I->getOpcode()) {
5357 case Instruction::SDiv:
5358 case Instruction::UDiv:
5359 case Instruction::SRem:
5360 case Instruction::URem:
5361 return true;
5362 default:
5363 return false;
5364 }
5365 };
5366 for (const auto &[Scalarized, ScalarCost] : CostCtx.CM.InstsToScalarize[VF]) {
5367 if (!Replicated.contains(Scalarized) || UseVPlanCostModel(Scalarized) ||
5368 CostCtx.skipCostComputation(Scalarized, VF.isVector()))
5369 continue;
5370 CostCtx.SkipCostComputation.insert(Scalarized);
5371 LLVM_DEBUG({
5372 dbgs() << "Cost of " << ScalarCost << " for VF " << VF
5373 << ": profitable to scalarize " << *Scalarized << "\n";
5374 });
5375 Cost += ScalarCost;
5376 }
5377
5378 return Cost;
5379}
5380
5381#ifndef NDEBUG
5382/// Returns the frequency with which \p VPBB executes, as recorded on its
5383/// recipes. All recipes of a block share the same frequency.
5384static std::optional<VPExecutionFrequency>
5386 if (VPBB->empty())
5387 return std::nullopt;
5388 return cast<VPInstruction>(&VPBB->front())->getExecutionFrequency();
5389}
5390#endif
5391
5393LoopVectorizationPlanner::cost(VPlan &Plan, ElementCount VF,
5394 VPRegisterUsage *RU,
5395 LoopVectorizationCostModel &PlanCM) const {
5396 VPCostContext CostCtx(*TLI, Plan, PlanCM, Config,
5397 /*ReusePrintingSlotTracker=*/true);
5398 InstructionCost Cost = precomputeCosts(Plan, VF, CostCtx);
5399 LLVM_DEBUG(dbgs() << "Precomputed costs for VF " << VF << ": " << Cost
5400 << '\n');
5401
5402 // Now compute and add the VPlan-based cost.
5403 Cost += Plan.cost(VF, CostCtx);
5404
5405 // Add the cost of spills due to excess register usage
5406 if (RU && Config.shouldConsiderRegPressureForVF(VF)) {
5407 InstructionCost SpillCost = RU->spillCost(
5408 TTI, Config.CostKind, Opts.force_target_num_vector_regs.value_or(0));
5409 LLVM_DEBUG(dbgs() << "Spill costs for VF " << VF << ": " << SpillCost
5410 << '\n');
5411 Cost += SpillCost;
5412 }
5413
5414#ifndef NDEBUG
5415 unsigned EstimatedWidth =
5416 estimateElementCount(VF, Config.getVScaleForTuning());
5417 LLVM_DEBUG(dbgs() << "Cost for VF " << VF << ": " << Cost
5418 << " (Estimated cost per lane: ");
5419 if (Cost.isValid()) {
5420 APFloat CostPerLane(APFloat::IEEEdouble());
5421 APFloat EstimatedWidthAsAPFloat(APFloat::IEEEdouble());
5422 (void)CostPerLane.convertFromAPInt(APInt(64, (uint64_t)Cost.getValue()),
5423 false, APFloat::rmTowardZero);
5424 (void)EstimatedWidthAsAPFloat.convertFromAPInt(
5425 APInt(64, (uint64_t)EstimatedWidth), false, APFloat::rmTowardZero);
5426 (void)CostPerLane.divide(EstimatedWidthAsAPFloat, APFloat::rmTowardZero);
5427
5428 SmallString<16> Str;
5429 CostPerLane.toString(Str, 3);
5430 LLVM_DEBUG(dbgs() << Str);
5431 } else /* No point dividing an invalid cost - it will still be invalid */
5432 LLVM_DEBUG(dbgs() << "Invalid");
5433 LLVM_DEBUG(dbgs() << ")\n");
5434#endif
5435 return Cost;
5436}
5437
5438std::pair<VectorizationFactor, VPlan *>
5440 if (VPlans.empty())
5441 return {VectorizationFactor::Disabled(), nullptr};
5442 // If there is a single VPlan with a single VF, return it directly.
5443 VPlan &FirstPlan = *VPlans[0];
5444
5445 ElementCount UserVF = Config.getHints().getWidth();
5446 if (VPlans.size() == 1) {
5447 // For outer loops, the plan has a single vector VF determined by the
5448 // heuristic.
5449 assert((FirstPlan.hasScalarVFOnly() || hasPlanWithVF(UserVF) ||
5450 FirstPlan.isOuterLoop()) &&
5451 "must have a single scalar VF, UserVF or an outer loop");
5452 return {VectorizationFactor(FirstPlan.getSingleVF(), 0, 0), &FirstPlan};
5453 }
5454
5455 if (hasPlanWithVF(UserVF) && hasForcedEpilogueVF() && VPlans.size() == 2) {
5456 assert(VPlans[0]->getSingleVF() == UserVF &&
5457 "expected second plan to be for the forced UserVF");
5458 assert(VPlans[1]->getSingleVF() == EpilogueVectorizationForceVF &&
5459 "expected first plan to be for the forced epilogue VF");
5460 return {VectorizationFactor(UserVF, 0, 0), VPlans[0].get()};
5461 }
5462
5463 LLVM_DEBUG(dbgs() << "LV: Computing best VF using cost kind: "
5464 << (Config.CostKind == TTI::TCK_RecipThroughput
5465 ? "Reciprocal Throughput\n"
5466 : Config.CostKind == TTI::TCK_Latency
5467 ? "Instruction Latency\n"
5468 : Config.CostKind == TTI::TCK_CodeSize ? "Code Size\n"
5469 : Config.CostKind == TTI::TCK_SizeAndLatency
5470 ? "Code Size and Latency\n"
5471 : "Unknown\n"));
5472
5474 assert(FirstPlan.hasVF(ScalarVF) &&
5475 "More than a single plan/VF w/o any plan having scalar VF");
5476
5477 // TODO: Compute scalar cost using VPlan-based cost model.
5478 InstructionCost ScalarCost = CM->expectedCost(ScalarVF);
5479 LLVM_DEBUG(dbgs() << "LV: Scalar loop costs: " << ScalarCost << ".\n");
5480 VectorizationFactor ScalarFactor(ScalarVF, ScalarCost, ScalarCost);
5481 VectorizationFactor BestFactor = ScalarFactor;
5482
5483 bool ForceVectorization =
5484 Config.getHints().getForce() == LoopVectorizeHints::FK_Enabled;
5485 if (ForceVectorization) {
5486 // Ignore scalar width, because the user explicitly wants vectorization.
5487 // Initialize cost to max so that VF = 2 is, at least, chosen during cost
5488 // evaluation.
5489 BestFactor.Cost = InstructionCost::getMax();
5490 }
5491
5492 VPlan *PlanForBestVF = &FirstPlan;
5493 ElementCount ExactTC = getSmallConstantTripCount(PSE.getSE(), OrigLoop);
5494
5495 for (auto &P : VPlans) {
5496 ArrayRef<ElementCount> VFs(P->vectorFactors().begin(),
5497 P->vectorFactors().end());
5498
5499 // For loops where the Trip Count is below the TailFoldingThreshold, only
5500 // consider the largest VF to result in at most one vector iteration, and at
5501 // most one scalar iteration.
5502 // FIXME: Encode this decision directly in LVPlanner.
5503 if (!ForceVectorization && P->hasScalarTail() && ExactTC.isFixed() &&
5504 ExactTC.getFixedValue() > 0 &&
5505 ExactTC.getFixedValue() <= TTI.getMinTripCountTailFoldingThreshold()) {
5506 VFs = VFs.take_back(1);
5507 }
5508
5510 bool ConsiderRegPressure = any_of(VFs, [this](ElementCount VF) {
5511 return Config.shouldConsiderRegPressureForVF(VF);
5512 });
5513 if (ConsiderRegPressure)
5514 RUs = calculateRegisterUsageForPlan(*P, VFs, TTI);
5515
5516 for (unsigned I = 0; I < VFs.size(); I++) {
5517 ElementCount VF = VFs[I];
5518 if (VF.isScalar())
5519 continue;
5520 if (!ForceVectorization && !willGenerateVectors(*P, VF, TTI)) {
5521 LLVM_DEBUG(
5522 dbgs()
5523 << "LV: Not considering vector loop of width " << VF
5524 << " because it will not generate any vector instructions.\n");
5525 continue;
5526 }
5527 if (Config.OptForSize && !ForceVectorization && hasReplicatorRegion(*P)) {
5528 LLVM_DEBUG(
5529 dbgs()
5530 << "LV: Not considering vector loop of width " << VF
5531 << " because it would cause replicated blocks to be generated,"
5532 << " which isn't allowed when optimizing for size.\n");
5533 continue;
5534 }
5535
5537 cost(*P, VF, ConsiderRegPressure ? &RUs[I] : nullptr, *CM);
5538 VectorizationFactor CurrentFactor(VF, Cost, ScalarCost);
5539
5540 if (isMoreProfitable(CurrentFactor, BestFactor, P->hasScalarTail())) {
5541 BestFactor = CurrentFactor;
5542 PlanForBestVF = P.get();
5543 }
5544
5545 // If profitable add it to ProfitableVF list.
5546 if (isMoreProfitable(CurrentFactor, ScalarFactor, P->hasScalarTail()))
5547 ProfitableVFs.push_back(CurrentFactor);
5548 }
5549 }
5550
5551 VPlan &BestPlan = *PlanForBestVF;
5552
5553 assert((BestFactor.Width.isScalar() || BestFactor.ScalarCost > 0) &&
5554 "when vectorizing, the scalar cost must be computed.");
5555
5556 LLVM_DEBUG(dbgs() << "LV: Selecting VF: " << BestFactor.Width << ".\n");
5557 return {BestFactor, &BestPlan};
5558}
5559
5561 Loop *L, LoopInfo *LI, DominatorTree *DT, const TargetLibraryInfo *TLI,
5563 std::unique_ptr<LoopVectorizationCostModel> CM, VFSelectionContext &Config,
5565 std::function<const BranchProbabilityInfo &()> GetBPI)
5566 : Opts(Config.getOpts()), OrigLoop(L), LI(LI), DT(DT), TLI(TLI), TTI(TTI),
5567 Legal(Legal), CM(std::move(CM)), Config(Config), PSE(PSE), ORE(ORE),
5568 GetBPI(GetBPI) {}
5569
5571
5573
5575 ElementCount BestVF, unsigned BestUF, VPlan &BestVPlan,
5576 bool HasRuntimeChecks, EpilogueVectorizationKind EpilogueVecKind,
5577 MutableArrayRef<VPBasicBlock *> TrackedBlocks) {
5578 assert(BestVPlan.hasVF(BestVF) &&
5579 "Trying to execute plan with unsupported VF");
5580 assert(BestVPlan.hasUF(BestUF) &&
5581 "Trying to execute plan with unsupported UF");
5582 if (BestVPlan.hasEarlyExit())
5583 ++LoopsEarlyExitVectorized;
5584
5586 *PSE.getSE(), TTI, Config.CostKind, BestVF, BestUF);
5587 if (TTI.hasMultiVectorLoadStore(
5588 BestUF, BestVPlan.hasTailFolded()
5592 BestUF, TTI);
5593 // TODO: Move to VPlan transform stage once the transition to the VPlan-based
5594 // cost model is complete for better cost estimates.
5595 RUN_VPLAN_PASS(VPlanTransforms::unrollByUF, BestVPlan, BestUF);
5599 bool HasBranchWeights =
5600 hasBranchWeightMD(*OrigLoop->getLoopLatch()->getTerminator());
5601 if (HasBranchWeights) {
5602 std::optional<unsigned> VScale = Config.getVScaleForTuning();
5604 BestVPlan, BestVF, VScale);
5605 }
5606
5607 if (vputils::findIncomingAliasMask(BestVPlan)) {
5608 assert(BestVPlan.hasTailFolded() && "Expected tail folding to be enabled");
5610 *Legal->getRuntimePointerChecking()->getDiffChecks(),
5611 *PSE.getSE(), HasBranchWeights);
5612 ++LoopsPartialAliasVectorized;
5613 }
5614
5615 // Retrieving VectorPH now when it's easier while VPlan still has Regions.
5616 VPBasicBlock *VectorPH = cast<VPBasicBlock>(BestVPlan.getVectorPreheader());
5617
5619 BestVF, BestUF, PSE);
5620 RUN_VPLAN_PASS(VPlanTransforms::optimizeForVFAndUF, BestVPlan, BestVF, BestUF,
5621 PSE);
5623 // Check if scalar epilogue is required, before simplifying constant branches.
5624 const bool RequiresScalarEpilogue = BestVPlan.requiresScalarEpilogue();
5625 if (EpilogueVecKind == EpilogueVectorizationKind::None)
5627 /*OnlyLatches=*/false);
5629
5631 // Convert the exit condition to AVLNext == 0 for EVL tail folded loops.
5633 // Regions are dissolved after optimizing for VF and UF, which completely
5634 // removes unneeded loop regions first.
5635 const bool HasTailFolded = BestVPlan.hasTailFolded();
5637 // Expand BranchOnTwoConds after dissolution, when latch has direct access to
5638 // its successors.
5640 // Convert loops with variable-length stepping after regions are dissolved.
5642 // Remove dead back-edges for single-iteration loops with BranchOnCond(true).
5643 // Only process loop latches to avoid removing edges from the middle block,
5644 // which may be needed for epilogue vectorization.
5646 /*OnlyLatches=*/true);
5647 std::optional<uint64_t> MaxRuntimeStep = getMaxRuntimeElementCount(
5648 BestVF * BestUF, *OrigLoop->getHeader()->getParent());
5649
5650 assert((LI->getUniqueLatchExitBlock(*OrigLoop) || RequiresScalarEpilogue) &&
5651 "loops not exiting via the latch without required epilogue?");
5653 VectorPH, HasTailFolded, RequiresScalarEpilogue,
5654 &BestVPlan.getVFxUF(), MaxRuntimeStep);
5656 BestVF);
5657 // Limit expansions to VPInstruction to when not vectorizing the epilogue.
5658 // Currently this code path still relies on code re-using SCEVs expanded
5659 // directly to IR instructions.
5660 if (EpilogueVecKind == EpilogueVectorizationKind::None)
5662 *PSE.getSE());
5663 RUN_VPLAN_PASS(VPlanTransforms::cse, BestVPlan, VPDominatorTree(BestVPlan));
5665 // Removing branches and incoming values may expose additional simplification
5666 // opportunities.
5668 /*OnlyLatches=*/EpilogueVecKind !=
5671 RUN_VPLAN_PASS(VPlanTransforms::simplifyKnownEVL, BestVPlan, BestVF, PSE);
5672 if (BestVPlan.getEntry()->getSingleSuccessor() ==
5673 BestVPlan.getScalarPreheader()) {
5674 // TODO: The vector loop would be dead, should not even try to vectorize.
5675 ORE->emit([&]() {
5676 return OptimizationRemarkAnalysis(DEBUG_TYPE, "VectorizationDead",
5677 OrigLoop->getStartLoc(),
5678 OrigLoop->getHeader())
5679 << "Created vector loop never executes due to insufficient trip "
5680 "count.";
5681 });
5683 }
5684
5685 // 0. Generate SCEV-dependent code in the entry, including TripCount, before
5686 // making any changes to the CFG.
5687 DenseMap<const SCEV *, Value *> ExpandedSCEVs =
5688 RUN_VPLAN_PASS(VPlanTransforms::expandSCEVs, BestVPlan, *PSE.getSE());
5689
5690 // Perform the actual loop transformation.
5691 IRBuilder<> Builder(PSE.getSE()->getModule());
5692 VPTransformState State(&TTI, BestVF, LI, DT, Legal->getAssumptionCache(),
5693 Builder, &BestVPlan, OrigLoop->getParentLoop());
5694
5695#ifdef EXPENSIVE_CHECKS
5696 assert(DT->verify(DominatorTree::VerificationLevel::Fast));
5697#endif
5698
5699 // 1. Create the scalar preheader; all other blocks are created during VPlan
5700 // execution.
5701 State.CFG.PrevBB = OrigLoop->getLoopPreheader();
5702 assert(State.CFG.PrevBB && "Invalid loop structure");
5703 BasicBlock *ScalarPHBB = SplitBlock(
5704 State.CFG.PrevBB, State.CFG.PrevBB->getTerminator(), DT, LI, nullptr,
5705 EpilogueVecKind == EpilogueVectorizationKind::Epilogue
5706 ? "vec.epilog.scalar.ph"
5707 : "scalar.ph");
5708 if (VPBasicBlock *ScalarPH = BestVPlan.getScalarPreheader())
5709 replaceVPBBWithIRVPBB(ScalarPH, ScalarPHBB, &BestVPlan);
5711
5712 assert(verifyVPlanIsValid(BestVPlan) && "final VPlan is invalid");
5713
5714 // After vectorization, the exit blocks of the original loop will have
5715 // additional predecessors. Invalidate SCEVs for the exit phis in case SE
5716 // looked through single-entry phis.
5717 ScalarEvolution &SE = *PSE.getSE();
5718 for (VPIRBasicBlock *Exit : BestVPlan.getExitBlocks()) {
5719 if (!Exit->hasPredecessors())
5720 continue;
5721 for (VPRecipeBase &PhiR : Exit->phis())
5723 &cast<VPIRPhi>(PhiR).getIRPhi());
5724 }
5725
5726 // Query whether the target wants loops it vectorizes to remain eligible for
5727 // runtime unrolling. Do this here, on the original loop and before its SCEV
5728 // is forgotten below.
5730 TTI.getUnrollingPreferences(OrigLoop, SE, UP, ORE);
5731 bool UnrollVectorizedLoop = UP.UnrollVectorizedLoop;
5732
5733 // Forget the original loop and block dispositions.
5734 SE.forgetLoop(OrigLoop);
5736
5737 //===------------------------------------------------===//
5738 //
5739 // Notice: any optimization or new instruction that go
5740 // into the code below should also be implemented in
5741 // the cost-model.
5742 //
5743 //===------------------------------------------------===//
5744
5745 // Retrieve loop information before executing the plan, which may remove the
5746 // original loop, if it becomes unreachable.
5747 MDNode *LID = OrigLoop->getLoopID();
5748 unsigned OrigLoopInvocationWeight = 0;
5749 std::optional<unsigned> OrigAverageTripCount =
5750 getLoopEstimatedTripCount(OrigLoop, &OrigLoopInvocationWeight);
5751
5752 BestVPlan.execute(&State);
5753
5754 // 2.6. Maintain Loop Hints
5755 // Keep all loop hints from the original loop on the vector loop (we'll
5756 // replace the vectorizer-specific hints below).
5757 VPBasicBlock *HeaderVPBB = vputils::getFirstLoopHeader(BestVPlan, State.VPDT);
5758 // Add metadata to disable runtime unrolling a scalar loop when there
5759 // are no runtime checks about strides and memory. A scalar loop that is
5760 // rarely used is not worth unrolling.
5761 bool DisableRuntimeUnroll = !HasRuntimeChecks && !BestVF.isScalar();
5763 HeaderVPBB ? LI->getLoopFor(State.CFG.VPBB2IRBB.lookup(HeaderVPBB))
5764 : nullptr,
5765 HeaderVPBB, BestVPlan,
5766 EpilogueVecKind == EpilogueVectorizationKind::Epilogue, LID,
5767 OrigAverageTripCount, OrigLoopInvocationWeight,
5768 estimateElementCount(BestVF * BestUF, Config.getVScaleForTuning()),
5769 DisableRuntimeUnroll, UnrollVectorizedLoop);
5770
5771 // 3. Remove redundant induction instructions, if a vector loop remains.
5772 if (HeaderVPBB)
5773 legacyCSE(State.CFG.VPBB2IRBB.lookup(HeaderVPBB));
5774
5775 // Wrap the generated blocks in VPIRBasicBlocks, so they can be used in the
5776 // epilogue plan.
5777 if (EpilogueVecKind == EpilogueVectorizationKind::MainLoop)
5779 vp_depth_first_shallow(BestVPlan.getEntry()))))
5780 if (!isa<VPIRBasicBlock>(VPBB)) {
5782 VPBB, State.CFG.VPBB2IRBB.at(VPBB), &BestVPlan);
5783 replace(TrackedBlocks, VPBB, IRVPBB);
5784 }
5785
5786 return ExpandedSCEVs;
5787}
5788
5790 return CM.isPredicatedInst(I);
5791}
5792
5794 return CM.TTI.prefersVectorizedAddressing();
5795}
5796
5798 VFRange &Range) {
5799 assert((VPI->getOpcode() == Instruction::Load ||
5800 VPI->getOpcode() == Instruction::Store) &&
5801 "Must be called with either a load or store");
5803
5804 auto WillWiden = [&](ElementCount VF) -> bool {
5806 CM.getWideningDecision(I, VF);
5808 "CM decision should be taken at this point.");
5810 return true;
5811 if (CM.isScalarAfterVectorization(I, VF) ||
5812 CM.isProfitableToScalarize(I, VF))
5813 return false;
5815 };
5816
5818 return nullptr;
5819
5820 // If a mask is not required, drop it - use unmasked version for safe loads.
5821 // TODO: Determine if mask is needed in VPlan.
5822 VPValue *Mask = CM.isMaskRequired(I) ? VPI->getMask() : nullptr;
5823
5824 // Determine if the pointer operand of the access is either consecutive or
5825 // reverse consecutive.
5827 CM.getWideningDecision(I, Range.Start);
5829 bool Consecutive =
5831
5832 VPValue *Ptr = VPI->getOpcode() == Instruction::Load ? VPI->getOperand(0)
5833 : VPI->getOperand(1);
5834 Builder.setInsertPoint(VPI);
5835 if (Consecutive) {
5836 Ptr = Builder.createConsecutiveVectorPointer(Ptr, getLoadStoreType(I),
5837 Reverse, VPI->getDebugLoc());
5838 }
5839
5840 if (Reverse && Mask)
5841 Mask = Builder.createNaryOp(VPInstruction::Reverse, Mask, I->getDebugLoc());
5842
5843 if (VPI->getOpcode() == Instruction::Load) {
5844 auto *Load = cast<LoadInst>(I);
5845 auto *LoadR =
5846 Builder.createWidenLoad(*Load, Ptr, Mask, Consecutive, Load->getAlign(),
5847 *VPI, Load->getDebugLoc());
5848 if (Reverse)
5849 return Builder.createNaryOp(VPInstruction::Reverse, LoadR,
5850 LoadR->getDebugLoc());
5851 return LoadR;
5852 }
5853
5855 VPValue *StoredVal = VPI->getOperand(0);
5856 if (Reverse)
5857 StoredVal = Builder.createNaryOp(VPInstruction::Reverse, StoredVal,
5858 Store->getDebugLoc());
5859 return Builder.createWidenStore(*Store, Ptr, StoredVal, Mask, Consecutive,
5860 Store->getAlign(), *VPI,
5861 Store->getDebugLoc());
5862}
5863
5864bool VPRecipeBuilder::shouldWiden(Instruction *I, VFRange &Range) const {
5866 "Instruction should have been handled earlier");
5867 // Instruction should be widened, unless it is scalar after vectorization,
5868 // scalarization is profitable or it is predicated.
5869 auto WillScalarize = [this, I](ElementCount VF) -> bool {
5870 return CM.isScalarAfterVectorization(I, VF) ||
5871 CM.isProfitableToScalarize(I, VF) ||
5872 CM.isScalarWithPredication(I, VF);
5873 };
5875 Range);
5876}
5877
5878VPRecipeWithIRFlags *VPRecipeBuilder::tryToWiden(VPInstruction *VPI) {
5879 auto *I = VPI->getUnderlyingInstr();
5880 switch (VPI->getOpcode()) {
5881 default:
5882 return nullptr;
5883 case Instruction::SDiv:
5884 case Instruction::UDiv:
5885 case Instruction::SRem:
5886 case Instruction::URem:
5887 // If not provably safe, use a masked intrinsic.
5888 if (CM.isPredicatedInst(I))
5889 return new VPWidenIntrinsicRecipe(
5891 I->getType(), {}, {}, VPI->getDebugLoc());
5892 [[fallthrough]];
5893 case Instruction::Add:
5894 case Instruction::And:
5895 case Instruction::AShr:
5896 case Instruction::FAdd:
5897 case Instruction::FCmp:
5898 case Instruction::FDiv:
5899 case Instruction::FMul:
5900 case Instruction::FNeg:
5901 case Instruction::FRem:
5902 case Instruction::FSub:
5903 case Instruction::ICmp:
5904 case Instruction::LShr:
5905 case Instruction::Mul:
5906 case Instruction::Or:
5907 case Instruction::Select:
5908 case Instruction::Shl:
5909 case Instruction::Sub:
5910 case Instruction::Xor:
5911 case Instruction::Freeze:
5912 case Instruction::ExtractValue:
5913 return new VPWidenRecipe(*I, VPI->operandsWithoutMask(), *VPI, *VPI,
5914 VPI->getDebugLoc());
5915 };
5916}
5917
5919 if (VPI->getOpcode() != Instruction::Store)
5920 return nullptr;
5921
5922 const HistogramInfo *HistInfo =
5923 Legal->getHistogramInfo(cast<StoreInst>(VPI->getUnderlyingInstr()));
5924 if (!HistInfo)
5925 return nullptr;
5926
5928 // Bucket address.
5929 HGramOps.push_back(VPI->getOperand(1));
5930 // Increment value.
5931 HGramOps.push_back(Plan.getOrAddLiveIn(HistInfo->Update->getOperand(1)));
5932
5933 // In case of predicated execution (due to tail-folding, or conditional
5934 // execution, or both), pass the relevant mask.
5935 if (VPValue *Mask = VPI->getMask())
5936 HGramOps.push_back(Mask);
5937
5938 return new VPHistogramRecipe(HistInfo->UpdateKind, HGramOps,
5939 cast<VPIRMetadata>(*VPI), VPI->getDebugLoc());
5940}
5941
5942std::optional<CompressedPtrInfo>
5944 if (!is_contained({Instruction::Load, Instruction::Store}, VPI->getOpcode()))
5945 return std::nullopt;
5947 return Legal->getCompressedPtrInfo(getLoadStorePointerOperand(I));
5948}
5949
5952 assert(getCompressedPtrInfo(VPI) && "Expected a compressed load/store");
5953
5954 VPBuilder::InsertPointGuard Guard(Builder);
5955 Builder.setInsertPoint(VPI);
5956
5957 VPValue *Mask = VPI->getMask();
5958 Type *AccessTy = vputils::getLoadStoreValueType(VPI);
5960
5961 VPValue *Ptr = VPI->getOpcode() == Instruction::Load ? VPI->getOperand(0)
5962 : VPI->getOperand(1);
5963 Ptr = Builder.createConsecutiveVectorPointer(Ptr, AccessTy,
5964 /*Reverse=*/false,
5965 VPI->getDebugLoc());
5966
5967 // Note: For expandload we fill masked-off lanes with passthru poison.
5968 if (VPI->getOpcode() == Instruction::Load)
5969 return new VPWidenMemIntrinsicRecipe(
5970 Intrinsic::masked_expandload, {Ptr, Mask, Plan.getPoison(AccessTy)},
5971 AccessTy, Alignment, *VPI, VPI->getDebugLoc());
5972
5973 VPValue *StoredValue = VPI->getOperand(0);
5974 return new VPWidenMemIntrinsicRecipe(Intrinsic::masked_compressstore,
5975 {StoredValue, Ptr, Mask}, AccessTy,
5976 Alignment, *VPI, VPI->getDebugLoc());
5977}
5978
5980 VPInstruction *VPI, VPBuilder &FinalRedStoresBuilder) {
5981 StoreInst *SI;
5982 if ((SI = dyn_cast<StoreInst>(VPI->getUnderlyingInstr())) &&
5983 Legal->isInvariantAddressOfReduction(SI->getPointerOperand())) {
5984 // Only create recipe for the final invariant store of the reduction.
5985 if (Legal->isInvariantStoreOfReduction(SI)) {
5986 VPValue *Val = VPI->getOperand(0);
5987 VPValue *Addr = VPI->getOperand(1);
5988 // We need to store the exiting value of the reduction, so use the blend
5989 // if tail folded.
5991 Val = Blend;
5992 [[maybe_unused]] auto *Rdx =
5994 assert((isa<VPIRValue>(Val) || !Rdx || Rdx->getBackedgeValue() == Val) &&
5995 "Store of reduction thats not the backedge value?");
5996 auto *Recipe = new VPReplicateRecipe(
5997 SI, {Val, Addr}, true /* IsUniform */, nullptr /*Mask*/, *VPI, *VPI,
5998 VPI->getDebugLoc());
5999 FinalRedStoresBuilder.insert(Recipe);
6000 }
6001 VPI->eraseFromParent();
6002 return true;
6003 }
6004
6005 return false;
6006}
6007
6009 VFRange &Range) {
6010 auto *I = VPI->getUnderlyingInstr();
6012 [&](ElementCount VF) { return CM.isUniformAfterVectorization(I, VF); },
6013 Range);
6014
6015 bool IsPredicated = CM.isPredicatedInst(I);
6016
6017 // Even if the instruction is not marked as uniform, there are certain
6018 // intrinsic calls that can be effectively treated as such, so we check for
6019 // them here. Conservatively, we only do this for scalable vectors, since
6020 // for fixed-width VFs we can always fall back on full scalarization.
6021 if (!IsUniform && Range.Start.isScalable() && isa<IntrinsicInst>(I)) {
6022 switch (cast<IntrinsicInst>(I)->getIntrinsicID()) {
6023 case Intrinsic::assume:
6024 case Intrinsic::lifetime_start:
6025 case Intrinsic::lifetime_end:
6026 // For scalable vectors if one of the operands is variant then we still
6027 // want to mark as uniform, which will generate one instruction for just
6028 // the first lane of the vector. We can't scalarize the call in the same
6029 // way as for fixed-width vectors because we don't know how many lanes
6030 // there are.
6031 //
6032 // The reasons for doing it this way for scalable vectors are:
6033 // 1. For the assume intrinsic generating the instruction for the first
6034 // lane is still be better than not generating any at all. For
6035 // example, the input may be a splat across all lanes.
6036 // 2. For the lifetime start/end intrinsics the pointer operand only
6037 // does anything useful when the input comes from a stack object,
6038 // which suggests it should always be uniform. For non-stack objects
6039 // the effect is to poison the object, which still allows us to
6040 // remove the call.
6041 IsUniform = true;
6042 break;
6043 default:
6044 break;
6045 }
6046 }
6047 VPValue *BlockInMask = nullptr;
6048 if (!IsPredicated) {
6049 // Finalize the recipe for Instr, first if it is not predicated.
6050 LLVM_DEBUG(dbgs() << "LV: Scalarizing:" << *I << "\n");
6051 } else {
6052 LLVM_DEBUG(dbgs() << "LV: Scalarizing and predicating:" << *I << "\n");
6053 // Instructions marked for predication are replicated and a mask operand is
6054 // added initially. Masked replicate recipes will later be placed under an
6055 // if-then construct to prevent side-effects. Generate recipes to compute
6056 // the block mask for this region.
6057 BlockInMask = VPI->getMask();
6058 }
6059
6060 // Note that there is some custom logic to mark some intrinsics as uniform
6061 // manually above for scalable vectors, which this assert needs to account for
6062 // as well.
6063 assert((Range.Start.isScalar() || !IsUniform || !IsPredicated ||
6064 (Range.Start.isScalable() && isa<IntrinsicInst>(I))) &&
6065 "Should not predicate a uniform recipe");
6066 if (IsUniform) {
6068 VPI->getOpcode(), VPI->operandsWithoutMask(), BlockInMask, *VPI, *VPI,
6069 VPI->getDebugLoc(), VPI->getScalarType(), I);
6070 }
6071 auto *Recipe = new VPReplicateRecipe(I, VPI->operandsWithoutMask(),
6072 /*IsSingleScalar=*/false, BlockInMask,
6073 *VPI, *VPI, VPI->getDebugLoc());
6074 return Recipe;
6075}
6076
6079 VFRange &Range) {
6080 assert(!R->isPhi() && "phis must be handled earlier");
6081 auto *VPI = cast<VPInstruction>(R);
6082 assert(VPI->getOpcode() != Instruction::Call &&
6083 "Call should have been handled by makeCallWideningDecisions");
6084
6085 // All widen recipes below deal only with VF > 1.
6087 [&](ElementCount VF) { return VF.isScalar(); }, Range))
6088 return nullptr;
6089
6090 Instruction *Instr = R->getUnderlyingInstr();
6091 assert(!is_contained({Instruction::Load, Instruction::Store},
6092 VPI->getOpcode()) &&
6093 "Should have been handled prior to this!");
6094
6095 // An extractvalue takes the shape of its operand: we cannot extract a lane
6096 // from a widened struct, nor build a struct from replicated lanes.
6097 if (VPI->getOpcode() == Instruction::ExtractValue &&
6099 if (VPRecipeBase *OpR = VPI->getOperand(0)->getDefiningRecipe())
6101 return tryToWiden(VPI);
6102 if (VPI->getOpcode() == Instruction::ExtractValue)
6103 return new VPReplicateRecipe(Instr, VPI->operandsWithoutMask(),
6105 /*Mask=*/nullptr, *VPI, *VPI,
6106 VPI->getDebugLoc());
6107
6108 if (!shouldWiden(Instr, Range))
6109 return nullptr;
6110
6111 if (VPI->getOpcode() == Instruction::GetElementPtr) {
6112 auto *GEP = cast<GetElementPtrInst>(Instr);
6113 return new VPWidenGEPRecipe(GEP->getSourceElementType(),
6114 VPI->operandsWithoutMask(), *VPI,
6115 VPI->getDebugLoc(), GEP);
6116 }
6117
6118 if (Instruction::isCast(VPI->getOpcode())) {
6119 auto *CI = cast<CastInst>(Instr);
6120 return new VPWidenCastRecipe(CI->getOpcode(), VPI->getOperand(0),
6121 VPI->getScalarType(), CI, *VPI, *VPI,
6122 VPI->getDebugLoc());
6123 }
6124
6125 return tryToWiden(VPI);
6126}
6127
6128// To allow RUN_VPLAN_PASS to print the VPlan after VF/UF independent
6129// optimizations.
6131
6132#ifndef NDEBUG
6133/// Cross-check the execution frequencies recorded in \p Plan against
6134/// BlockFrequencyInfo for the blocks of \p OrigLoop.
6135/// FIXME: Temporary verification aid, to be removed.
6136static bool verifyExecutionFrequenciesMatchBFI(VPlan &Plan, Loop *OrigLoop,
6137 LoopInfo *LI,
6139 // Limited to loops with the latch as only exiting block
6140 if (OrigLoop->getExitingBlock() != OrigLoop->getLoopLatch())
6141 return true;
6142
6143 // Visit the loop body in the same order as recordExecutionFrequencies. Both
6144 // are reverse post-orders of the same CFG, so indices correspond.
6147 assert(Blocks.size() == OrigLoop->getNumBlocks() &&
6148 "loop body and original loop must have the same blocks");
6149
6150 LoopBlocksRPO OrigRPO(OrigLoop);
6151 OrigRPO.perform(LI);
6152
6153 // Only request the expensive BFI once the cheap bail-outs are past.
6154 BlockFrequencyInfo &BFI = CM.getBFI();
6155 uint64_t HeaderFreq = BFI.getBlockFreq(OrigLoop->getHeader()).getFrequency();
6156 if (HeaderFreq == 0)
6157 return true;
6158
6159 // BFI's fixed-point mass propagation loses up to 1 ULP per edge, so bound the
6160 // error by the number of edges in the region.
6161 uint64_t Edges = 0;
6162 for (const VPBasicBlock *VPBB : Blocks)
6163 Edges += VPBB->getNumSuccessors();
6164 uint64_t Tolerance = Edges + BranchProbability::getDenominator() / HeaderFreq;
6165
6166 for (const auto &[VPBB, BB] :
6167 zip_equal(drop_begin(Blocks), drop_begin(OrigRPO))) {
6168 // Nothing to check for blocks without a recorded frequency.
6169 std::optional<VPExecutionFrequency> Freq =
6171 if (!Freq)
6172 continue;
6174
6175 // Clamp to the header's frequency, which BFI's rounding may exceed.
6178 std::min(BBFreq, HeaderFreq), HeaderFreq);
6179 if (AbsoluteDifference(Computed.getNumerator(), Expected.getNumerator()) <=
6180 Tolerance)
6181 continue;
6182
6183 errs() << "Block frequency mismatch for " << VPBB->getName() << ": VPlan "
6184 << Computed << ", BlockFrequencyInfo " << Expected << "\n";
6185 return false;
6186 }
6187 return true;
6188}
6189#endif
6190
6192LoopVectorizationPlanner::tryToBuildVPlan1(LoopVectorizationCostModel &PlanCM) {
6193 bool IsInnerLoop = OrigLoop->isInnermost();
6194
6195 // Set up loop versioning for inner loops with memory runtime checks.
6196 // Outer loops don't have LoopAccessInfo since canVectorizeMemory() is not
6197 // called for them.
6198 std::optional<LoopVersioning> LVer;
6199 if (IsInnerLoop) {
6200 const LoopAccessInfo *LAI = Legal->getLAI();
6201 LVer.emplace(*LAI, LAI->getRuntimePointerChecking()->getChecks(), OrigLoop,
6202 LI, DT, PSE.getSE());
6203 if (!LAI->getRuntimePointerChecking()->getChecks().empty() &&
6205 // Only use noalias metadata when using memory checks guaranteeing no
6206 // overlap across all iterations.
6207 LVer->prepareNoAliasMetadata();
6208 }
6209 }
6210
6211 // Create initial base VPlan0, to serve as common starting point for all
6212 // candidates built later for specific VF ranges.
6213 auto VPlan0 = VPlanTransforms::buildVPlan0(
6214 OrigLoop, *LI, Legal->getWidestInductionType(), PSE,
6215 LVer ? &*LVer : nullptr, GetBPI);
6216
6217 VPDominatorTree VPDT(*VPlan0);
6218 if (const LoopAccessInfo *LAI = Legal->getLAI())
6220 LAI->getSymbolicStrides(), VPDT);
6223 if (IsInnerLoop) {
6225 assert(verifyExecutionFrequenciesMatchBFI(*VPlan0, OrigLoop, LI, PlanCM) &&
6226 "execution frequencies do not match the loop's block frequencies");
6227 }
6228
6229 // Create recipes for header phis. For outer loops, reductions, recurrences
6230 // and in-loop reductions are empty since legality doesn't detect them.
6231 if (!RUN_VPLAN_PASS(
6232 VPlanTransforms::createHeaderPhiRecipes, *VPlan0, PSE, *OrigLoop, ORE,
6233 VPDT, Legal->getInductionVars(), Legal->getReductionVars(),
6234 Legal->getConditionalInductions(), Legal->getFixedOrderRecurrences(),
6235 Config.getInLoopReductions(), Config.getHints().allowReordering())) {
6236 return nullptr;
6237 }
6238
6239 if (const LoopAccessInfo *LAI = Legal->getLAI())
6241 LAI->getSymbolicStrides(), VPDT);
6242
6243 // Without -vplan-outer-loop-legality-checks, trust the explicit vectorization
6244 // pragma that vectorizing the outer loop is safe.
6245 if (!IsInnerLoop && Opts.vplan_outer_loop_legality_checks &&
6246 !proveOuterLoopMemorySafety(*VPlan0, PSE, *Legal->getAA(), VPDT,
6247 OrigLoop)) {
6249 "Cannot prove outer loop memory accesses safe",
6250 "cannot prove memory accesses in outer loop are safe to vectorize",
6251 "CantProveOuterLoopMemSafety", ORE, OrigLoop);
6252 return nullptr;
6253 }
6254
6255 // Add surviving induction predicates to PSE and check constraints.
6256 bool ForceVectorization =
6257 Config.getHints().getForce() == LoopVectorizeHints::FK_Enabled;
6258 bool OptForSize = !ForceVectorization && PlanCM.EpilogueLoweringStatus ==
6260 unsigned SCEVCheckThreshold = ForceVectorization
6261 ? Opts.pragma_vectorize_scev_check_threshold
6262 : Opts.vectorize_scev_check_threshold;
6264 OptForSize, SCEVCheckThreshold, ORE, OrigLoop))
6265 return nullptr;
6266
6268
6269 // If we're vectorizing a loop with an uncountable exit, make sure that the
6270 // recipes are safe to handle.
6271 // TODO: Remove this once we can properly check the VPlan itself for the
6272 // presence of an uncountable exit.
6273 if (Legal->hasUncountableEarlyExit()) {
6275 OrigLoop))
6276 return nullptr;
6277
6278 // TODO: Check target preference for style.
6281 ORE, OrigLoop, PSE, *DT, Legal->getAssumptionCache(),
6282 EEStyle)) {
6283 return nullptr;
6284 }
6285 } else {
6287 }
6288
6290 getDebugLocFromInstOrOperands(Legal->getPrimaryInduction()));
6291 if (PlanCM.foldTailByMasking())
6293
6295
6296 return VPlan0;
6297}
6298
6299void LoopVectorizationPlanner::buildVPlans(VPlan &VPlan1, ElementCount MinVF,
6300 ElementCount MaxVF,
6302 if (ElementCount::isKnownGT(MinVF, MaxVF))
6303 return;
6304
6305 auto MaxVFTimes2 = MaxVF * 2;
6306 for (ElementCount VF = MinVF; ElementCount::isKnownLT(VF, MaxVFTimes2);) {
6307 VFRange SubRange = {VF, MaxVFTimes2};
6308 auto Plan = tryToBuildVPlan(std::unique_ptr<VPlan>(VPlan1.duplicate()),
6309 SubRange, PlanCM);
6310 VF = SubRange.End;
6311
6312 if (!Plan)
6313 continue;
6314
6315 // Now optimize the initial VPlan.
6319 Config.getMinimalBitwidths());
6321 // TODO: try to put addExplicitVectorLength close to addActiveLaneMask
6322 if (PlanCM.foldTailWithEVL()) {
6324 Config.getMaxSafeElements());
6326 VPCostContext CostCtx(*TLI, *Plan, *CM, Config);
6328 }
6329
6330 if (auto P =
6332 VPlans.push_back(std::move(P));
6333
6336 useActiveLaneMask(Style),
6338
6340 assert(verifyVPlanIsValid(*Plan) && "VPlan is invalid");
6341 VPlans.push_back(std::move(Plan));
6342 }
6343}
6344
6346LoopVectorizationPlanner::tryToBuildVPlan(VPlanPtr Plan, VFRange &Range,
6348
6349 // For outer loops, the plan only needs basic recipe conversion and induction
6350 // live-out optimization; the full inner-loop recipe building below does not
6351 // apply (no widening decisions, interleave groups, reductions, etc.).
6352 if (Plan->isOuterLoop()) {
6353 for (ElementCount VF : Range)
6354 Plan->addVF(VF);
6356 *Plan, *TLI, PSE, OrigLoop))
6357 return nullptr;
6359 OrigLoop);
6360 return Plan;
6361 }
6362
6363 using namespace llvm::VPlanPatternMatch;
6364 SmallPtrSet<const InterleaveGroup<Instruction> *, 1> InterleaveGroups;
6365
6366 // ---------------------------------------------------------------------------
6367 // Build initial VPlan: Scan the body of the loop in a topological order to
6368 // visit each basic block after having visited its predecessor basic blocks.
6369 // ---------------------------------------------------------------------------
6370
6371 bool RequiresScalarEpilogueCheck =
6373 [&PlanCM](ElementCount VF) {
6374 return !PlanCM.requiresScalarEpilogue(VF.isVector());
6375 },
6376 Range);
6377 // Update the branch in the middle block if a scalar epilogue is required.
6378 VPBasicBlock *MiddleVPBB = Plan->getMiddleBlock();
6379 if (!RequiresScalarEpilogueCheck && MiddleVPBB->getNumSuccessors() == 2) {
6380 auto *BranchOnCond = cast<VPInstruction>(MiddleVPBB->getTerminator());
6381 assert(MiddleVPBB->getSuccessors()[1] == Plan->getScalarPreheader() &&
6382 "second successor must be scalar preheader");
6383 BranchOnCond->setOperand(0, Plan->getFalse());
6384 }
6385
6386 // Don't use getDecisionAndClampRange here, because we don't know the UF
6387 // so this function is better to be conservative, rather than to split
6388 // it up into different VPlans.
6389 // TODO: Consider using getDecisionAndClampRange here to split up VPlans.
6390 bool IVUpdateMayOverflow = false;
6391 for (ElementCount VF : Range)
6392 IVUpdateMayOverflow |= !isIndvarOverflowCheckKnownFalse(Opts, &PlanCM, VF);
6393
6395 // Use NUW for the induction increment if we proved that it won't overflow in
6396 // the vector loop or when not folding the tail. In the later case, we know
6397 // that the canonical induction increment will not overflow as the vector trip
6398 // count is >= increment and a multiple of the increment.
6399 VPRegionBlock *LoopRegion = Plan->getVectorLoopRegion();
6400 bool HasNUW = !IVUpdateMayOverflow || Style == TailFoldingStyle::None;
6401 if (!HasNUW) {
6402 auto *IVInc =
6403 LoopRegion->getExitingBasicBlock()->getTerminator()->getOperand(0);
6404 assert(match(IVInc,
6405 m_VPInstruction<Instruction::Add>(
6406 m_Specific(LoopRegion->getCanonicalIV()), m_VPValue())) &&
6407 "Did not find the canonical IV increment");
6408 LoopRegion->clearCanonicalIVNUW(cast<VPInstruction>(IVInc));
6409 }
6410
6411 // ---------------------------------------------------------------------------
6412 // Pre-construction: record ingredients whose recipes we'll need to further
6413 // process after constructing the initial VPlan.
6414 // ---------------------------------------------------------------------------
6415
6416 // For each interleave group which is relevant for this (possibly trimmed)
6417 // Range, add it to the set of groups to be later applied to the VPlan and add
6418 // placeholders for its members' Recipes which we'll be replacing with a
6419 // single VPInterleaveRecipe.
6420 for (InterleaveGroup<Instruction> *IG :
6422 auto ApplyIG = [IG, &PlanCM](ElementCount VF) -> bool {
6423 bool Result = (VF.isVector() && // Query is illegal for VF == 1
6424 PlanCM.getWideningDecision(IG->getInsertPos(), VF) ==
6426 // For scalable vectors, the interleave factors must be <= 8 since we
6427 // require the (de)interleaveN intrinsics instead of shufflevectors.
6428 assert((!Result || !VF.isScalable() || IG->getFactor() <= 8) &&
6429 "Unsupported interleave factor for scalable vectors");
6430 return Result;
6431 };
6432 if (!getDecisionAndClampRange(ApplyIG, Range))
6433 continue;
6434 InterleaveGroups.insert(IG);
6435 }
6436
6437 // ---------------------------------------------------------------------------
6438 // Construct wide recipes and apply predication for original scalar
6439 // VPInstructions in the loop.
6440 // ---------------------------------------------------------------------------
6441 VPRecipeBuilder RecipeBuilder(*Plan, Legal, PlanCM, Builder);
6442
6444 RecipeBuilder, *PSE.getSE()))
6445 return nullptr;
6446
6448 Range.Start);
6449
6450 VPCostContext CostCtx(*TLI, *Plan, PlanCM, Config);
6451
6453 RecipeBuilder, CostCtx);
6454
6456
6457 // Widened calls may only use the first lane of some operands.
6459 RecipeBuilder, CostCtx))
6461
6463
6464 // Convert remaining VPInstructions to widen or replicate recipes.
6465 // TODO: This legacy code should eventually be migrated to VPlan.
6466 VPBasicBlock *HeaderVPBB = LoopRegion->getEntryBasicBlock();
6467 for (VPBasicBlock *VPBB : VPBlockUtils::blocksOnly<VPBasicBlock>(
6468 vp_depth_first_shallow(HeaderVPBB))) {
6469 // All types but VPInstructions are already widened and don't need extra
6470 // processing. We process VPInstructions below.
6471 assert(
6472 all_of(
6473 make_range(VPBB->getFirstNonPhi(), VPBB->end()),
6474 IsaPred<VPWidenCanonicalIVRecipe, VPBlendRecipe, VPReductionRecipe,
6475 VPReplicateRecipe, VPWidenLoadRecipe, VPWidenStoreRecipe,
6476 VPWidenCallRecipe, VPWidenIntrinsicRecipe,
6477 VPVectorPointerRecipe, VPVectorEndPointerRecipe,
6478 VPHistogramRecipe, VPInstruction>) &&
6479 "Unexpected recipe");
6480 for (VPInstruction &VPI :
6482 // We represent single-scalar casts directly as VPInstructions.
6483 if (Instruction::isCast(VPI.getOpcode()) &&
6485 continue;
6486
6487 // Only VPInstructions with an underlying value need to be processed.
6488 if (!VPI.getUnderlyingValue())
6489 continue;
6490
6491 Builder.setInsertPoint(&VPI);
6492
6493 VPRecipeBase *Recipe =
6494 RecipeBuilder.tryToCreateWidenNonPhiRecipe(&VPI, Range);
6495 if (!Recipe)
6496 Recipe = RecipeBuilder.handleReplication(&VPI, Range);
6497 Builder.insert(Recipe);
6498
6499 if (Recipe->getNumDefinedValues() == 1) {
6500 VPI.replaceAllUsesWith(Recipe->getVPSingleValue());
6501 } else {
6502 assert(Recipe->getNumDefinedValues() == 0 &&
6503 "Unexpected multidef recipe");
6504 }
6505 VPI.eraseFromParent();
6506 }
6507 }
6508
6509 assert(isa<VPRegionBlock>(LoopRegion) &&
6510 !LoopRegion->getEntryBasicBlock()->empty() &&
6511 "entry block must be set to a VPRegionBlock having a non-empty entry "
6512 "VPBasicBlock");
6513
6515 Range);
6516
6517 // ---------------------------------------------------------------------------
6518 // Transform initial VPlan: Apply previously taken decisions, in order, to
6519 // bring the VPlan to its final state.
6520 // ---------------------------------------------------------------------------
6521
6522 addReductionResultComputation(Plan, Range.Start, PlanCM);
6523
6524 // Optimize FindIV reductions to use sentinel-based approach when possible.
6526 *OrigLoop);
6528 OrigLoop);
6529
6530 // Apply mandatory transformation to handle reductions with multiple in-loop
6531 // uses if possible, bail out otherwise.
6533 OrigLoop))
6534 return nullptr;
6535 // Apply mandatory transformation to handle FP maxnum/minnum reduction with
6536 // NaNs if possible, bail out otherwise.
6538 return nullptr;
6539
6540 // Create whole-vector selects for find-last recurrences.
6542 return nullptr;
6543
6544 // Interleave memory: for each Interleave Group we marked earlier as relevant
6545 // for this VPlan, replace the Recipes widening its memory instructions with a
6546 // single VPInterleaveRecipe at its insertion point.
6548 InterleaveGroups, PlanCM.isEpilogueAllowed());
6549
6551
6552 // Create partial reduction recipes for scaled reductions and transform
6553 // recipes to abstract recipes if it is legal and beneficial and clamp the
6554 // range for better cost estimation.
6556 Range);
6558 Range);
6559
6560 // Convert memory recipes to strided access recipes if the strided access is
6561 // legal and profitable.
6563 *OrigLoop, CostCtx, Range);
6564
6565 if (Legal->hasUncountableExitWithSideEffects())
6567 Range);
6568
6569 // Ensure scalar VF plans only contain VF=1, as required by hasScalarVFOnly.
6570 if (Range.Start.isScalar())
6571 Range.End = Range.Start * 2;
6572
6573 for (ElementCount VF : Range)
6574 Plan->addVF(VF);
6575 Plan->setName("Initial VPlan");
6576
6578
6579 if (PlanCM.maskPartialAliasing())
6581
6582 assert(verifyVPlanIsValid(*Plan) && "VPlan is invalid");
6583 return Plan;
6584}
6585
6586void LoopVectorizationPlanner::addReductionResultComputation(
6587 VPlanPtr &Plan, ElementCount MinVF, LoopVectorizationCostModel &PlanCM) {
6588 using namespace VPlanPatternMatch;
6589 VPRegionBlock *VectorLoopRegion = Plan->getVectorLoopRegion();
6590 VPBasicBlock *MiddleVPBB = Plan->getMiddleBlock();
6591 VPBasicBlock *LatchVPBB = VectorLoopRegion->getExitingBasicBlock();
6592 Builder.setInsertPoint(&*std::prev(std::prev(LatchVPBB->end())));
6593 VPBasicBlock::iterator IP = MiddleVPBB->getFirstNonPhi();
6594 VPValue *HeaderMask = Plan->getVectorLoopRegion()->getHeaderMask();
6595 for (VPRecipeBase &R : make_early_inc_range(
6596 Plan->getVectorLoopRegion()->getEntryBasicBlock()->phis())) {
6597 VPReductionPHIRecipe *PhiR = dyn_cast<VPReductionPHIRecipe>(&R);
6598 if (!PhiR)
6599 continue;
6600
6601 // Clean up reductions that have become invariant.
6602 if (PhiR->getBackedgeValue() == PhiR) {
6603 PhiR->replaceAllUsesWith(PhiR->getStartValue());
6604 PhiR->eraseFromParent();
6605 continue;
6606 }
6607
6608 RecurKind RecurrenceKind = PhiR->getRecurrenceKind();
6609 const RecurrenceDescriptor &RdxDesc = Legal->getRecurrenceDescriptor(
6611 Type *PhiTy = PhiR->getScalarType();
6612
6613 // Convert a VPBlendRecipe backedge to a select.
6614 if (auto *Blend = dyn_cast<VPBlendRecipe>(PhiR->getBackedgeValue())) {
6615 if (Blend->getNumIncomingValues() == 2 &&
6616 Blend->getMask(0) == HeaderMask) {
6617 auto *Sel = VPBuilder(Blend).createSelect(
6618 Blend->getMask(0), Blend->getIncomingValue(0),
6619 Blend->getIncomingValue(1), {}, "", *Blend);
6620 Blend->replaceAllUsesWith(Sel);
6621 Blend->eraseFromParent();
6622 }
6623 }
6624
6625 auto *OrigExitingVPV = PhiR->getBackedgeValue();
6626 auto *NewExitingVPV = OrigExitingVPV;
6627
6628 // Remove the predicated select if the target doesn't want it.
6629 VPValue *V;
6630 if (!PlanCM.usePredicatedReductionSelect(
6631 RecurrenceKind, PhiR->hasUsesOutsideReductionChain()) &&
6632 match(PhiR->getBackedgeValue(),
6633 m_Select(m_Specific(HeaderMask), m_VPValue(V), m_Specific(PhiR))))
6634 PhiR->setBackedgeValue(V);
6635
6636 // We want code in the middle block to appear to execute on the location of
6637 // the scalar loop's latch terminator because: (a) it is all compiler
6638 // generated, (b) these instructions are always executed after evaluating
6639 // the latch conditional branch, and (c) other passes may add new
6640 // predecessors which terminate on this line. This is the easiest way to
6641 // ensure we don't accidentally cause an extra step back into the loop while
6642 // debugging.
6643 DebugLoc ExitDL = OrigLoop->getLoopLatch()->getTerminator()->getDebugLoc();
6644
6645 // TODO: At the moment ComputeReductionResult also drives creation of the
6646 // bc.merge.rdx phi nodes, hence it needs to be created unconditionally here
6647 // even for in-loop reductions, until the reduction resume value handling is
6648 // also modeled in VPlan.
6649 VPInstruction *FinalReductionResult;
6650 VPBuilder::InsertPointGuard Guard(Builder);
6651 Builder.setInsertPoint(IP);
6652 // For AnyOf reductions, find the select among PhiR's users and convert
6653 // the reduction phi to operate on bools before creating the final
6654 // reduction result.
6655 if (RecurrenceDescriptor::isAnyOfRecurrenceKind(RecurrenceKind)) {
6656 auto *AnyOfSelect = findSingleUser<VPSingleDefRecipe>(
6657 PhiR,
6658 m_Select(m_Unless(m_Specific(HeaderMask)), m_VPValue(), m_VPValue()));
6659 VPValue *Start = PhiR->getStartValue();
6660 bool TrueValIsPhi = AnyOfSelect->getOperand(1) == PhiR;
6661 // NewVal is the non-phi operand of the select.
6662 VPValue *NewVal = TrueValIsPhi ? AnyOfSelect->getOperand(2)
6663 : AnyOfSelect->getOperand(1);
6664
6665 // Adjust AnyOf reductions; replace the reduction phi for the selected
6666 // value with a boolean reduction phi node to check if the condition is
6667 // true in any iteration. The final value is selected by the final
6668 // ComputeReductionResult.
6669 VPValue *Cmp = AnyOfSelect->getOperand(0);
6670 // If the compare is checking the reduction PHI node, adjust it to check
6671 // the start value.
6672 if (VPRecipeBase *CmpR = Cmp->getDefiningRecipe())
6673 CmpR->replaceUsesOfWith(PhiR, PhiR->getStartValue());
6674 Builder.setInsertPoint(AnyOfSelect);
6675
6676 // If the true value of the select is the reduction phi, the new value
6677 // is selected if the negated condition is true in any iteration.
6678 if (TrueValIsPhi)
6679 Cmp = Builder.createNot(Cmp);
6680
6681 // Build a fresh i1 chain (phi, or, and i1 versions of any blend/select
6682 // the exiting value flows through).
6683 auto *NewPhiR =
6684 PhiR->cloneWithOperands(Plan->getFalse(), Plan->getFalse());
6685 NewPhiR->insertBefore(PhiR);
6686 VPValue *NewExiting = Builder.createOr(NewPhiR, Cmp);
6687
6688 // The exiting value may flow through a chain of VPBlendRecipes and
6689 // select recipes (VPInstruction, VPWidenRecipe or VPReplicateRecipe with
6690 // Select opcode) before reaching OrigExitingVPV. Clone each chain link
6691 // in topological order so each clone refers to the already-rewritten i1
6692 // operands via Substitutions.
6693 DenseMap<VPValue *, VPValue *> Substitutions = {{AnyOfSelect, NewExiting},
6694 {PhiR, NewPhiR}};
6695 std::function<void(VPSingleDefRecipe *)> CloneChain =
6696 [&](VPSingleDefRecipe *Old) {
6697 if (Substitutions.contains(Old))
6698 return;
6700 for (VPValue *Op : Old->operands()) {
6701 if (isa<VPBlendRecipe>(Op) ||
6703 CloneChain(cast<VPSingleDefRecipe>(Op));
6704 NewOps.push_back(Substitutions.lookup_or(Op, Op));
6705 }
6706 VPSingleDefRecipe *New;
6707 if (auto *B = dyn_cast<VPBlendRecipe>(Old))
6708 New = B->cloneWithOperands(NewOps);
6709 else if (auto *W = dyn_cast<VPWidenRecipe>(Old))
6710 New = W->cloneWithOperands(NewOps);
6711 else if (auto *Rep = dyn_cast<VPReplicateRecipe>(Old))
6712 New = Rep->cloneWithOperands(NewOps);
6713 else
6714 New = cast<VPInstruction>(Old)->cloneWithOperands(NewOps);
6715 New->insertBefore(Old);
6716 Substitutions[Old] = New;
6717 };
6718
6719 if (OrigExitingVPV != AnyOfSelect) {
6720 CloneChain(cast<VPSingleDefRecipe>(OrigExitingVPV));
6721 NewExiting = Substitutions.lookup(OrigExitingVPV);
6722 }
6723 NewPhiR->setOperand(1, NewExiting);
6724 PhiR->replaceAllUsesWith(Plan->getPoison(PhiR->getScalarType()));
6725
6726 Builder.setInsertPoint(IP);
6727 FinalReductionResult =
6728 Builder.createAnyOfReduction(NewExiting, NewVal, Start, ExitDL);
6729 } else {
6730 // If the vector reduction can be performed in a smaller type, we
6731 // truncate then extend the loop exit value to enable InstCombine to
6732 // evaluate the entire expression in the smaller type.
6733 VPValue *ReductionOp = NewExitingVPV;
6734 Instruction::CastOps ExtendOpc = Instruction::CastOpsEnd;
6735 if (MinVF.isVector() && PhiTy != RdxDesc.getRecurrenceType()) {
6736 assert(!PhiR->isInLoop() && "Unexpected truncated inloop reduction!");
6738 "Unexpected truncated min-max recurrence!");
6739 Type *RdxTy = RdxDesc.getRecurrenceType();
6740 ExtendOpc = RdxDesc.isSigned() ? Instruction::SExt : Instruction::ZExt;
6741 {
6742 VPBuilder::InsertPointGuard Guard(Builder);
6743 Builder.setInsertPoint(
6744 std::next(NewExitingVPV->getDefiningRecipe()->getIterator()));
6745 ReductionOp =
6746 Builder.createWidenCast(Instruction::Trunc, NewExitingVPV, RdxTy);
6747 VPWidenCastRecipe *Extnd =
6748 Builder.createWidenCast(ExtendOpc, ReductionOp, PhiTy);
6749 if (PhiR->getOperand(1) == NewExitingVPV)
6750 PhiR->setOperand(1, Extnd);
6751 }
6752 }
6753
6754 VPIRFlags Flags(RecurrenceKind, PhiR->isOrdered(), PhiR->isInLoop(),
6755 PhiR->getFastMathFlagsOrNone());
6756 auto CreateResult = [&](VPValue *V) {
6757 VPInstruction *Res = Builder.createNaryOp(
6759 if (ExtendOpc != Instruction::CastOpsEnd)
6760 Res = Builder.createScalarCast(ExtendOpc, Res, PhiTy, {});
6761 return Res;
6762 };
6763 FinalReductionResult = CreateResult(ReductionOp);
6764
6765 // On early exits, lanes up to and including the exiting lane use the
6766 // updated accumulators, the other lanes the phi.
6767 for (VPUser *U : to_vector(OrigExitingVPV->users())) {
6768 VPValue *Lane;
6769 if (!match(U, m_ExtractLane(
6771 m_Specific(OrigExitingVPV))))
6772 continue;
6773 auto *ExtractR = cast<VPInstruction>(U);
6774 Builder.setInsertPoint(ExtractR);
6775 Type *LaneTy = Lane->getScalarType();
6776 VPValue *One = Plan->getConstantInt(LaneTy, 1);
6777 VPValue *Mask = Builder.createNaryOp(
6779 {Plan->getZero(LaneTy), Builder.createAdd(Lane, One), One});
6780 Mask = Builder.createNaryOp(VPInstruction::ExtractVectorForPart,
6781 {Mask, Plan->getConstantInt(64, 0)});
6782 VPValue *Blend = Builder.createSelect(Mask, OrigExitingVPV, PhiR);
6783 if (ExtendOpc != Instruction::CastOpsEnd)
6784 Blend = Builder.createWidenCast(Instruction::Trunc, Blend,
6785 RdxDesc.getRecurrenceType());
6786 ExtractR->replaceAllUsesWith(CreateResult(Blend));
6787 ExtractR->eraseFromParent();
6788 }
6789 }
6790
6791 // Update all users in the middle block, which computes the final result.
6792 // Also replace redundant extracts.
6793 for (auto *U : to_vector(OrigExitingVPV->users())) {
6794 auto *Parent = cast<VPRecipeBase>(U)->getParent();
6795 if (FinalReductionResult == U || Parent->getParent())
6796 continue;
6797 if (Parent != MiddleVPBB) {
6798 assert(match(U, m_Select(m_VPValue(), m_Specific(OrigExitingVPV),
6799 m_Specific(PhiR))) &&
6800 "only users outside middle block must be blends created above");
6801 continue;
6802 }
6803 // Skip ComputeReductionResult and FindIV reductions when they are not the
6804 // final result.
6805 if (match(U, m_VPInstruction<VPInstruction::ComputeReductionResult>()) ||
6807 match(U, m_VPInstruction<Instruction::ICmp>())))
6808 continue;
6809 U->replaceUsesOfWith(OrigExitingVPV, FinalReductionResult);
6810
6811 // Look through ExtractLastPart.
6813 U = cast<VPInstruction>(U)->getSingleUser();
6814
6817 cast<VPInstruction>(U)->replaceAllUsesWith(FinalReductionResult);
6818 }
6819
6820 RecurKind RK = PhiR->getRecurrenceKind();
6825 VPBuilder PHBuilder(Plan->getVectorPreheader());
6826 VPValue *Iden = Plan->getOrAddLiveIn(
6827 getRecurrenceIdentity(RK, PhiTy, PhiR->getFastMathFlagsOrNone()));
6828 auto *ScaleFactorVPV = Plan->getConstantInt(32, 1);
6829 VPValue *StartV = PHBuilder.createNaryOp(
6831 {PhiR->getStartValue(), Iden, ScaleFactorVPV}, *PhiR);
6832 PhiR->setOperand(0, StartV);
6833 }
6834 }
6835
6837}
6838
6840 VPlan &Plan, GeneratedRTChecks &RTChecks, ElementCount VF, unsigned UF,
6841 bool HasBranchWeights) const {
6842 const auto &[SCEVCheckCond, SCEVCheckBlock] = RTChecks.getSCEVChecks();
6843 if (SCEVCheckBlock && SCEVCheckBlock->hasNPredecessors(0)) {
6844 assert((!Config.OptForSize ||
6845 Config.getHints().getForce() == LoopVectorizeHints::FK_Enabled) &&
6846 "Cannot SCEV check stride or overflow when optimizing for size");
6848 SCEVCheckBlock, HasBranchWeights);
6849 }
6850 const auto &[MemCheckCond, MemCheckBlock] = RTChecks.getMemRuntimeChecks();
6851 if (MemCheckBlock && MemCheckBlock->hasNPredecessors(0)) {
6852 // VPlan-native path does not do any analysis for memory runtime checks
6853 // currently.
6854 assert((!Opts.enable_vplan_native_path || !Plan.isOuterLoop()) &&
6855 "Memory runtime checks are not supported for outer loops yet");
6856
6857 if (Config.OptForSize) {
6858 assert(
6859 Config.getHints().getForce() == LoopVectorizeHints::FK_Enabled &&
6860 "Cannot emit memory checks when optimizing for size, unless forced "
6861 "to vectorize.");
6862 ORE->emit([&]() {
6863 return OptimizationRemarkAnalysis(DEBUG_TYPE, "VectorizationCodeSize",
6864 OrigLoop->getStartLoc(),
6865 OrigLoop->getHeader())
6866 << "Code-size may be reduced by not forcing "
6867 "vectorization, or by source-code modifications "
6868 "eliminating the need for runtime checks "
6869 "(e.g., adding 'restrict').";
6870 });
6871 }
6872 const auto &RtPtrChecking = *Legal->getRuntimePointerChecking();
6873 // Erase the temporary IR before recipe expansion can reuse its values.
6874 RTChecks.eraseMemCheckBlock();
6876 OrigLoop, *PSE.getSE(), VF, UF, HasBranchWeights);
6877 }
6878}
6879
6881 VPlan &Plan, ElementCount VF, unsigned UF,
6882 ElementCount MinProfitableTripCount, bool TailFoldedEpilogue) const {
6883 const uint32_t *BranchWeights =
6884 hasBranchWeightMD(*OrigLoop->getLoopLatch()->getTerminator())
6886 : nullptr;
6887 // If either the main vector loop or the epilogue vector loop is tail-folded,
6888 // it can handle any trip count, so the min iter check never needs
6889 // to branch to the scalar loop.
6891 MinProfitableTripCount, Plan.requiresScalarEpilogue(),
6892 Plan.hasTailFolded() || TailFoldedEpilogue, OrigLoop,
6893 BranchWeights,
6894 OrigLoop->getLoopPredecessor()->getTerminator()->getDebugLoc(),
6895 PSE, Plan.getEntry());
6896}
6897
6898// Determine how to lower the epilogue, which depends on 1) optimising
6899// for minimum code-size, 2) tail-folding compiler options, 3) loop
6900// hints forcing tail-folding, and 4) a TTI hook that analyses whether the loop
6901// is suitable for tail-folding.
6902// This function determines epilogue lowering for the main vector loop while
6903// epilogue lowering for the tail-folded epilogue path will be handled
6904// separately in getEpilogueTailLowering.
6905static EpilogueLowering
6906getEpilogueLowering(const VectorizeOptions &Opts, LoopVectorizeHints &Hints,
6907 bool OptForSize, TargetTransformInfo *TTI,
6909 InterleavedAccessInfo *IAI) {
6910 // 1) OptSize takes precedence over all other options, i.e. if this is set,
6911 // don't look at hints or options, and don't request an epilogue.
6912 if (OptForSize)
6914
6915 // 2) If set, obey the directives
6916 if (Opts.tail_folding_policy) {
6917 switch (*Opts.tail_folding_policy) {
6919 return CM_EpilogueAllowed;
6924 };
6925 }
6926
6927 // 3) If set, obey the hints
6928 switch (Hints.getPredicate()) {
6932 return CM_EpilogueAllowed;
6933 };
6934
6935 // 4) if the TTI hook indicates this is profitable, request tail-folding.
6936 TailFoldingInfo TFI(TLI, &LVL, IAI);
6937 if (TTI->preferTailFoldingOverEpilogue(&TFI))
6939
6940 return CM_EpilogueAllowed;
6941}
6942
6943// Emit a remark if there are stores to floats that required a floating point
6944// extension. If the vectorized loop was generated with floating point there
6945// will be a performance penalty from the conversion overhead and the change in
6946// the vector width.
6949 for (BasicBlock *BB : L->getBlocks()) {
6950 for (Instruction &Inst : *BB) {
6951 if (auto *S = dyn_cast<StoreInst>(&Inst)) {
6952 if (S->getValueOperand()->getType()->isFloatTy())
6953 Worklist.push_back(S);
6954 }
6955 }
6956 }
6957
6958 // Traverse the floating point stores upwards searching, for floating point
6959 // conversions.
6962 while (!Worklist.empty()) {
6963 auto *I = Worklist.pop_back_val();
6964 if (!L->contains(I))
6965 continue;
6966 if (!Visited.insert(I).second)
6967 continue;
6968
6969 // Emit a remark if the floating point store required a floating
6970 // point conversion.
6971 // TODO: More work could be done to identify the root cause such as a
6972 // constant or a function return type and point the user to it.
6973 if (isa<FPExtInst>(I) && EmittedRemark.insert(I).second)
6974 ORE->emit([&]() {
6975 return OptimizationRemarkAnalysis(LV_NAME, "VectorMixedPrecision",
6976 I->getDebugLoc(), L->getHeader())
6977 << "floating point conversion changes vector width. "
6978 << "Mixed floating point precision requires an up/down "
6979 << "cast that will negatively impact performance.";
6980 });
6981
6982 for (Use &Op : I->operands())
6983 if (auto *OpI = dyn_cast<Instruction>(Op))
6984 Worklist.push_back(OpI);
6985 }
6986}
6987
6988/// For loops with uncountable early exits, find the cost of doing work when
6989/// exiting the loop early, such as calculating the final exit values of
6990/// variables used outside the loop. The loop leaves through at most one of the
6991/// vector.early.exit blocks, so return the maximum of their costs.
6992/// TODO: This is currently overly pessimistic because the loop may not take
6993/// the early exit, but better to keep this conservative for now. In future,
6994/// it might be possible to relax this by using branch probabilities.
6996 VPlan &Plan, ElementCount VF) {
6997 InstructionCost Cost = 0;
6998 for (auto *ExitVPBB : Plan.getExitBlocks()) {
6999 for (auto *PredVPBB : ExitVPBB->getPredecessors()) {
7000 // If the predecessor is not the middle.block, then it must be the
7001 // vector.early.exit block, which may contain work to calculate the exit
7002 // values of variables used outside the loop.
7003 if (PredVPBB != Plan.getMiddleBlock()) {
7004 LLVM_DEBUG(dbgs() << "Calculating cost of work in exit block "
7005 << PredVPBB->getName() << ":\n");
7006 Cost = std::max(Cost, PredVPBB->cost(VF, CostCtx));
7007 }
7008 }
7009 }
7010 return Cost;
7011}
7012
7013/// This function determines whether or not it's still profitable to vectorize
7014/// the loop given the extra work we have to do outside of the loop:
7015/// 1. Perform the runtime checks before entering the loop to ensure it's safe
7016/// to vectorize.
7017/// 2. In the case of loops with uncountable early exits, we may have to do
7018/// extra work when exiting the loop early, such as calculating the final
7019/// exit values of variables used outside the loop.
7020/// 3. The middle block.
7021static bool isOutsideLoopWorkProfitable(GeneratedRTChecks &Checks,
7022 VectorizationFactor &VF, Loop *L,
7024 VPCostContext &CostCtx, VPlan &Plan,
7025 EpilogueLowering SEL,
7026 std::optional<unsigned> VScale) {
7027 InstructionCost RtC = Checks.getCost();
7028 if (!RtC.isValid())
7029 return false;
7030
7031 // When interleaving only scalar and vector cost will be equal, which in turn
7032 // would lead to a divide by 0. Fall back to hard threshold.
7033 if (VF.Width.isScalar()) {
7034 // TODO: Should we rename VectorizeMemoryCheckThreshold?
7036 LLVM_DEBUG(
7037 dbgs()
7038 << "LV: Interleaving only is not profitable due to runtime checks\n");
7039 return false;
7040 }
7041 return true;
7042 }
7043
7044 // The scalar cost should only be 0 when vectorizing with a user specified
7045 // VF/IC. In those cases, runtime checks should always be generated.
7046 uint64_t ScalarC = VF.ScalarCost.getValue();
7047 if (ScalarC == 0)
7048 return true;
7049
7050 // The vector loop is left through either a vector.early.exit block or the
7051 // middle block, so add the cost of the more expensive of the two.
7052 InstructionCost EarlyExitCost =
7053 calculateEarlyExitCost(CostCtx, Plan, VF.Width);
7054 InstructionCost MiddleCost = Plan.getMiddleBlock()->cost(VF.Width, CostCtx);
7055 InstructionCost TotalCost = RtC + std::max(EarlyExitCost, MiddleCost);
7056
7057 // First, compute the minimum iteration count required so that the vector
7058 // loop outperforms the scalar loop.
7059 // The total cost of the scalar loop is
7060 // ScalarC * TC
7061 // where
7062 // * TC is the actual trip count of the loop.
7063 // * ScalarC is the cost of a single scalar iteration.
7064 //
7065 // The total cost of the vector loop is
7066 // TotalCost + VecC * (TC / VF) + EpiC
7067 // where
7068 // * TotalCost is the sum of the costs of
7069 // - the generated runtime checks, i.e. RtC
7070 // - the most expensive way of leaving the vector loop, i.e. the maximum
7071 // of the costs of the middle block and, for loops with uncountable
7072 // early exits, the vector.early.exit blocks.
7073 // * VecC is the cost of a single vector iteration.
7074 // * TC is the actual trip count of the loop
7075 // * VF is the vectorization factor
7076 // * EpiCost is the cost of the generated epilogue, including the cost
7077 // of the remaining scalar operations.
7078 //
7079 // Vectorization is profitable once the total vector cost is less than the
7080 // total scalar cost:
7081 // TotalCost + VecC * (TC / VF) + EpiC < ScalarC * TC
7082 //
7083 // Now we can compute the minimum required trip count TC as
7084 // VF * (TotalCost + EpiC) / (ScalarC * VF - VecC) < TC
7085 //
7086 // For now we assume the epilogue cost EpiC = 0 for simplicity. Note that
7087 // the computations are performed on doubles, not integers and the result
7088 // is rounded up, hence we get an upper estimate of the TC.
7089 unsigned IntVF = estimateElementCount(VF.Width, VScale);
7090 uint64_t Div = ScalarC * IntVF - VF.Cost.getValue();
7091 uint64_t MinTC1 =
7092 Div == 0 ? 0 : divideCeil(TotalCost.getValue() * IntVF, Div);
7093
7094 // Second, compute a minimum iteration count so that the cost of the
7095 // runtime checks is only a fraction of the total scalar loop cost. This
7096 // adds a loop-dependent bound on the overhead incurred if the runtime
7097 // checks fail. In case the runtime checks fail, the cost is RtC + ScalarC
7098 // * TC. To bound the runtime check to be a fraction 1/X of the scalar
7099 // cost, compute
7100 // RtC < ScalarC * TC * (1 / X) ==> RtC * X / ScalarC < TC
7101 uint64_t MinTC2 = divideCeil(RtC.getValue() * 10, ScalarC);
7102
7103 // Now pick the larger minimum. If it is not a multiple of VF and an epilogue
7104 // is allowed, choose the next closest multiple of VF. This should partly
7105 // compensate for ignoring the epilogue cost.
7106 uint64_t MinTC = std::max(MinTC1, MinTC2);
7107 if (SEL == CM_EpilogueAllowed)
7108 MinTC = alignTo(MinTC, IntVF);
7110
7111 LLVM_DEBUG(
7112 dbgs() << "LV: Minimum required TC for runtime checks to be profitable:"
7113 << VF.MinProfitableTripCount << "\n");
7114
7115 // Skip vectorization if the expected trip count is less than the minimum
7116 // required trip count.
7117 if (auto ExpectedTC = getSmallBestKnownTC(CostCtx.Opts, PSE, L)) {
7118 if (ElementCount::isKnownLT(*ExpectedTC, VF.MinProfitableTripCount)) {
7119 LLVM_DEBUG(dbgs() << "LV: Vectorization is not beneficial: expected "
7120 "trip count < minimum profitable VF ("
7121 << *ExpectedTC << " < " << VF.MinProfitableTripCount
7122 << ")\n");
7123
7124 return false;
7125 }
7126 }
7127 return true;
7128}
7129
7131 : InterleaveOnlyWhenForced(Opts.InterleaveOnlyWhenForced),
7132 VectorizeOnlyWhenForced(Opts.VectorizeOnlyWhenForced) {}
7133
7134/// ResumeForEpilogue markers in the main plan, used by the epilogue plan.
7139
7140/// Prepare \p MainPlan for vectorizing the main vector loop during epilogue
7141/// vectorization.
7143 using namespace VPlanPatternMatch;
7144 // When vectorizing the epilogue, FindFirstIV & FindLastIV reductions can
7145 // introduce multiple uses of undef/poison. If the reduction start value may
7146 // be undef or poison it needs to be frozen and the frozen start has to be
7147 // used when computing the reduction result. We also need to use the frozen
7148 // value in the resume phi generated by the main vector loop, as this is also
7149 // used to compute the reduction result after the epilogue vector loop. The
7150 // epilogue plan re-uses the frozen values.
7151 VPBuilder Builder(MainPlan.getEntry());
7152 for (VPInstruction &VPI :
7154 VPValue *OrigStart;
7155 if (!matchFindIVResult(&VPI, m_VPValue(), m_VPValue(OrigStart)))
7156 continue;
7158 continue;
7159 VPInstruction *Freeze = Builder.createFreeze(OrigStart, {}, "fr");
7160 VPI.setOperand(2, Freeze);
7161 OrigStart->replaceUsesWithIf(Freeze, IsaPred<VPPhi>);
7162 }
7163
7164 VPValue *VectorTC = nullptr;
7165 auto *Term =
7167 [[maybe_unused]] bool MatchedTC =
7168 match(Term, m_BranchOnCount(m_VPValue(), m_VPValue(VectorTC)));
7169 assert(MatchedTC && "must match vector trip count");
7170
7171 VPBasicBlock *MiddleVPBB = MainPlan.getMiddleBlock();
7172 VPBuilder MiddleBuilder(MiddleVPBB->getFirstNonPhi());
7173 VPInstruction *VectorTCMarker = MiddleBuilder.createNaryOp(
7175 {VectorTC, MainPlan.getZero(VectorTC->getScalarType())});
7176
7177 // Replace the resume phis of the VPIRPhis in the scalar header of the main
7178 // plan by ResumeForEpilogue instructions for their incoming values and return
7179 // them so they can be used as resume values when vectorizing the epilogue.
7180 // The epilogue plan creates the resume phis after the main plan executed.
7181 VPRecipeBase *MiddleTerm = MiddleVPBB->getTerminator();
7182 MiddleBuilder.setInsertPoint(MiddleTerm ? MiddleTerm->getIterator()
7183 : MiddleVPBB->end());
7184 auto ResumeValues = to_vector(
7185 map_range(MainPlan.getScalarHeader()->phis(), [&](VPRecipeBase &R) {
7186 auto *ResumePhi = cast<VPPhi>(R.getOperand(0));
7187 assert(ResumePhi->getNumIncoming() == 2 &&
7188 ResumePhi->getIncomingBlock(0) == MiddleVPBB &&
7189 "expected resume phi merging middle block and bypass value");
7190 return MiddleBuilder.createNaryOp(VPInstruction::ResumeForEpilogue,
7191 ResumePhi->operands());
7192 }));
7193 for (VPPhi &ResumePhi : make_early_inc_range(
7195 ResumePhi.replaceAllUsesWith(ResumePhi.getOperand(1));
7196 ResumePhi.eraseFromParent();
7197 }
7198 return {VectorTCMarker, std::move(ResumeValues)};
7199}
7200
7201/// Prepare \p Plan for vectorizing the epilogue loop. That is, re-use expanded
7202/// SCEVs from \p ExpandedSCEVs and set resume values for header recipes.
7204 VPlan &MainPlan, VPlan &Plan, const SCEV2ValueTy &ExpandedSCEVs,
7205 ElementCount MainLoopVF, unsigned MainLoopUF, ElementCount EpilogueVF,
7207 const MainPlanResumeMarkers &Markers, VPBasicBlock *MainCheck) {
7208 // Build a map from the scalar-header PHI to the ResumeForEpilogue markers
7209 // from the main plan.
7210 // TODO: Replace the IR PHI key.
7211 DenseMap<PHINode *, VPInstruction *> IRPhiToResumeForEpi;
7212 for (auto [HeaderPhi, ResumeForEpi] :
7213 zip_equal(MainPlan.getScalarHeader()->phis(), Markers.ResumeValues))
7214 IRPhiToResumeForEpi[&cast<VPIRPhi>(HeaderPhi).getIRPhi()] = ResumeForEpi;
7215 VPIRBasicBlock *EpilogueCheck = RUN_VPLAN_PASS(
7216 VPlanTransforms::modelGeneratedMainLoopBlocks, Plan, MainPlan, MainCheck);
7217 VPRegionBlock *VectorLoop = Plan.getVectorLoopRegion();
7218 VPBasicBlock *Header = VectorLoop->getEntryBasicBlock();
7219 Header->setName("vec.epilog.vector.body");
7220
7221 // When skipping the epilogue vector loop, the scalar loop resumes at the
7222 // values computed by the main vector loop.
7223 for (auto [R, ResumeForEpi] :
7224 zip_equal(Plan.getScalarHeader()->phis(), Markers.ResumeValues)) {
7225 // A tail-folded epilogue's middle block never branches to the scalar
7226 // preheader, so it has no resume phis and the scalar loop starts at the
7227 // original start values. The epilogue check never skips a tail-folded
7228 // epilogue either, so there is no resume value to set.
7229 auto *ResumePhi = dyn_cast<VPPhi>(R.getOperand(0));
7230 if (!ResumePhi) {
7231 assert(Plan.hasTailFolded() &&
7232 "expected resume phis unless the epilogue is tail-folded");
7233 continue;
7234 }
7235 ResumePhi->setIncomingValueForBlock(
7236 EpilogueCheck, Plan.getOrAddLiveIn(ResumeForEpi->getUnderlyingValue()));
7237 }
7238
7239 VPBasicBlock *VectorPH = Plan.getVectorPreheader();
7240 assert(VectorPH->getNumPredecessors() == 2 &&
7241 VectorPH->getPredecessors()[0] == EpilogueCheck &&
7242 "vector preheader must be entered from the epilogue check first");
7243 // Returns the value to resume at for \p ResumeForEpi: a phi in the vector
7244 // preheader merging the value computed by the main vector loop with the
7245 // value used when the main vector loop has been bypassed, or the former if
7246 // both are equal.
7247 auto GetResumeValue = [&](VPInstruction *ResumeForEpi,
7248 const Twine &Name) -> VPValue * {
7249 VPValue *MainV = Plan.getOrAddLiveIn(ResumeForEpi->getUnderlyingValue());
7250 VPValue *BypassV =
7251 Plan.getOrAddLiveIn(ResumeForEpi->getOperand(1)->getUnderlyingValue());
7252 if (MainV == BypassV)
7253 return MainV;
7254 return VPBuilder(VectorPH->getFirstNonPhi())
7255 .createScalarPhi({MainV, BypassV}, {}, Name);
7256 };
7257
7258 VPValue *IV = VectorLoop->getCanonicalIV();
7259 // When vectorizing the epilogue loop, the canonical induction needs to start
7260 // at the resume value from the main vector loop. Find the resume value
7261 // created during execution of the main VPlan. Add this resume value as an
7262 // offset to the canonical IV of the epilogue loop.
7263 VPValue *VPV = GetResumeValue(Markers.VectorTC, "vec.epilog.resume.val");
7264 assert(all_of(IV->users(),
7265 [](const VPUser *U) {
7266 if (isa<VPScalarIVStepsRecipe, VPDerivedIVRecipe>(U))
7267 return true;
7268 auto *VPI = dyn_cast<VPInstruction>(U);
7269 if (!VPI)
7270 return false;
7271 // Only users linear in the canonical IV (e.g. scaling it by
7272 // a stride) stay correct when offsetting it below; others,
7273 // like header masks, may need an epilogue-relative IV.
7274 // The active-lane-masks of a tail-folded epilogue compare
7275 // against the full trip count, so they expect the offset
7276 // IV, like the active-lane-mask phi's entry value.
7277 unsigned Opc = VPI->getOpcode();
7278 return Instruction::isCast(Opc) ||
7279 is_contained({Instruction::Add, Instruction::Mul,
7280 Instruction::Shl},
7281 Opc) ||
7283 }) &&
7284 "the canonical IV should only be used by its increment, casts, "
7285 "stride scaling, ScalarIVSteps or DerivedIV when resetting the start "
7286 "value");
7287 VPBuilder Builder(Header->getFirstNonPhi());
7288 VPInstruction *Add = Builder.createAdd(IV, VPV);
7289 // Replace all users of the canonical IV and its increment with the offset
7290 // version, except for the Add itself and the canonical IV increment.
7292 assert(Increment && "Must have a canonical IV increment at this point");
7293 IV->replaceUsesWithIf(
7294 Add, [Add, Increment](VPUser *U) { return U != Add && U != Increment; });
7295 VPInstruction *OffsetIVInc =
7297 Increment->replaceAllUsesWith(OffsetIVInc);
7298 OffsetIVInc->setOperand(0, Increment);
7299
7300 // Resume values must be created in the vector preheader.
7301 VPBuilder PHBuilder(VectorPH->getFirstNonPhi());
7302
7303 // Ensure that the start values for all header phi recipes are updated before
7304 // vectorizing the epilogue loop.
7305 for (VPRecipeBase &R : Header->phis()) {
7306 VPValue *ResumeVPV = nullptr;
7307 // TODO: Move setting of resume values to prepareToExecute.
7308 if (auto *ReductionPhi = dyn_cast<VPReductionPHIRecipe>(&R)) {
7309 // Find the reduction result by searching users of the phi or its backedge
7310 // value.
7311 auto IsReductionResult = [](VPRecipeBase *R) {
7312 auto *VPI = dyn_cast<VPInstruction>(R);
7313 return VPI && VPI->getOpcode() == VPInstruction::ComputeReductionResult;
7314 };
7315 auto *RdxResult = cast<VPInstruction>(
7316 vputils::findRecipe(ReductionPhi->getBackedgeValue(), IsReductionResult));
7317 assert(RdxResult && "expected to find reduction result");
7318
7319 VPInstruction *ResumeForEpi = IRPhiToResumeForEpi.at(
7320 cast<PHINode>(ReductionPhi->getUnderlyingInstr()));
7321
7322 // Check for FindIV pattern by looking for icmp user of RdxResult.
7323 // The pattern is: select(icmp ne RdxResult, Sentinel), RdxResult, Start
7324 using namespace VPlanPatternMatch;
7325 VPValue *SentinelVPV = nullptr;
7326 bool IsFindIV = any_of(RdxResult->users(), [&](VPUser *U) {
7327 return match(U, VPlanPatternMatch::m_SpecificICmp(
7328 ICmpInst::ICMP_NE, m_Specific(RdxResult),
7329 m_VPValue(SentinelVPV)));
7330 });
7331
7332 RecurKind RK = ReductionPhi->getRecurrenceKind();
7333 ResumeVPV = GetResumeValue(ResumeForEpi, "bc.merge.rdx");
7334 if (RecurrenceDescriptor::isAnyOfRecurrenceKind(RK) || IsFindIV) {
7335 VPValue *BypassOp = ResumeForEpi->getOperand(1);
7336 assert((isa<VPIRValue>(BypassOp) ||
7338 BypassOp,
7339 m_VPInstruction<Instruction::Freeze>(m_VPValue()))) &&
7340 "expected live-in or Freeze");
7341 VPValue *StartV = Plan.getOrAddLiveIn(BypassOp->getUnderlyingValue());
7343 // VPReductionPHIRecipes for AnyOf reductions expect a boolean as
7344 // start value; compare the final value from the main vector loop
7345 // to the start value.
7346 ResumeVPV = PHBuilder.createICmp(CmpInst::ICMP_NE, ResumeVPV, StartV);
7347 } else {
7348 assert(isa<VPIRValue>(SentinelVPV) &&
7349 "sentinel must be a live-in to be used in the preheader");
7350 // Use the start value frozen for the main plan, if any, when
7351 // computing the reduction result.
7352 if (match(BypassOp, m_Freeze(m_VPValue())))
7353 for (VPUser *U : RdxResult->users()) {
7354 auto *VPI = dyn_cast<VPInstruction>(U);
7355 if (VPI && matchFindIVResult(VPI, m_VPValue(), m_VPValue()))
7356 VPI->setOperand(2, StartV);
7357 }
7358
7359 // Adjust resume: select(icmp eq ResumeVPV, StartV), Sentinel,
7360 // ResumeVPV
7361 VPValue *Cmp =
7362 PHBuilder.createICmp(CmpInst::ICMP_EQ, ResumeVPV, StartV);
7363 ResumeVPV = PHBuilder.createSelect(Cmp, SentinelVPV, ResumeVPV);
7364 }
7365 // TODO: materializeBroadcasts does not cover values in the vector
7366 // preheader.
7367 ReductionPhi->setStartValue(
7368 PHBuilder.createNaryOp(VPInstruction::Broadcast, ResumeVPV));
7369 continue;
7370 }
7371 if (auto *VPI = dyn_cast<VPInstruction>(ReductionPhi->getStartValue())) {
7373 "unexpected start value");
7374 // Partial sub-reductions always start at 0 and account for the
7375 // reduction start value in a final subtraction. Update it to use the
7376 // resume value from the main vector loop.
7377 if (ReductionPhi->getVFScaleFactor() > 1 &&
7379 auto *Sub = cast<VPInstruction>(RdxResult->getSingleUser());
7380 assert((Sub->getOpcode() == Instruction::Sub ||
7381 Sub->getOpcode() == Instruction::FSub) &&
7382 "Unexpected opcode");
7383 assert(isa<VPIRValue>(Sub->getOperand(0)) &&
7384 "Expected operand to match the original start value of the "
7385 "reduction");
7386 // For integer sub-reductions, verify start value is zero.
7387 // For FP sub-reductions, verify start value is negative zero.
7388 [[maybe_unused]] auto StartValueIsIdentity = [&] {
7389 Value *IdentityValue =
7390 getRecurrenceIdentity(RK, ResumeVPV->getScalarType(),
7391 ReductionPhi->getFastMathFlagsOrNone());
7392 auto *StartValue = dyn_cast<VPIRValue>(VPI->getOperand(0));
7393 return StartValue && StartValue->getValue() == IdentityValue;
7394 };
7395 assert(StartValueIsIdentity() &&
7396 "Expected start value for partial sub-reduction to be zero "
7397 "(or negative zero)");
7398
7399 Sub->setOperand(0, ResumeVPV);
7400 } else {
7401 // The start vector may be shared by multiple reductions, so create
7402 // a new one using the resume.
7403 auto *NewStart = cast<VPInstruction>(VPI->clone());
7404 NewStart->setOperand(0, ResumeVPV);
7405 NewStart->insertBefore(VPI);
7406 ReductionPhi->setStartValue(NewStart);
7407 }
7408 continue;
7409 }
7410 } else if (isa<VPActiveLaneMaskPHIRecipe>(&R)) {
7411 // The active-lane-mask phi's entry value was computed assuming the
7412 // epilogue vector loop starts at 0. Rebuild it using the resume value
7413 // instead, so the mask reflects how many elements the main vector loop
7414 // already processed.
7415 VPBuilder EntryBuilder(Plan.getVectorPreheader());
7416 auto *EntryALM = EntryBuilder.createNaryOp(
7417 VPInstruction::ActiveLaneMask, {VPV, Plan.getTripCount()},
7418 R.getDebugLoc(), "active.lane.mask.entry");
7419 cast<VPHeaderPHIRecipe>(&R)->setStartValue(EntryALM);
7420 continue;
7421 } else {
7422 // Retrieve the induction resume value via ResumeForEpilogue.
7423 PHINode *IndPhi =
7425 ? cast<VPWidenInductionRecipe>(&R)->getPHINode()
7426 : cast<VPConditionalInductionPHIRecipe>(&R)->getPHINode();
7427 ResumeVPV =
7428 GetResumeValue(IRPhiToResumeForEpi.at(IndPhi), "bc.resume.val");
7429 auto *IntOrFpIV = dyn_cast<VPWidenIntOrFpInductionRecipe>(&R);
7430 if (IntOrFpIV && IntOrFpIV->isTruncated()) {
7431 // The resume value is for the original induction. Preserve any offset
7432 // folded into the truncated induction's start.
7433 // TODO: This is a short-term solution, as it relies on the induction
7434 // descriptor's IR start value. Compute the resume value with
7435 // createDerivedIV from the recipe's start and step instead.
7436 VPValue *OrigStart = Plan.getOrAddLiveIn(
7437 IntOrFpIV->getInductionDescriptor().getStartValue());
7438 VPValue *NarrowStart = IntOrFpIV->getStartValue();
7439 if (NarrowStart != OrigStart) {
7440 VPBuilder OffsetBuilder(VectorPH);
7441 VPValue *Offset = OffsetBuilder.createSub(NarrowStart, OrigStart);
7442 ResumeVPV = OffsetBuilder.createAdd(ResumeVPV, Offset);
7443 }
7444 }
7445 }
7446 assert(ResumeVPV && "Must have a resume value");
7447 cast<VPHeaderPHIRecipe>(&R)->setStartValue(ResumeVPV);
7448 }
7449
7450 // Re-use the SCEVs expanded for the main loop instead of expanding them
7451 // again, which also lets simplifyLiveInsWithSCEV fold their users.
7452 // Others are expanded with the epilogue plan.
7453 // TODO: Remove once the epilogue plan uses the main plan's VPValues directly.
7455 make_isa_range<VPExpandSCEVRecipe>(*Plan.getEntry()))) {
7456 Value *V = ExpandedSCEVs.lookup(ExpandR.getSCEV());
7457 if (!V)
7458 continue;
7459 VPValue *ExpandedVal = Plan.getOrAddLiveIn(V);
7460 ExpandR.replaceAllUsesWith(ExpandedVal);
7461 if (Plan.getTripCount() == &ExpandR)
7462 Plan.resetTripCount(ExpandedVal);
7463 ExpandR.eraseFromParent();
7464 }
7465
7466 auto VScale = Config.getVScaleForTuning();
7467 unsigned MainLoopStep = estimateElementCount(MainLoopVF * MainLoopUF, VScale);
7468 unsigned EpilogueLoopStep = estimateElementCount(EpilogueVF, VScale);
7470 Plan.getOrAddLiveIn(Markers.VectorTC->getUnderlyingValue()),
7471 Plan.requiresScalarEpilogue(), EpilogueVF, MainLoopStep,
7472 EpilogueLoopStep, SE);
7473}
7474
7476 const VectorizeOptions &Opts = getVectorizeOptions(*L);
7477 assert((Opts.enable_vplan_native_path || L->isInnermost()) &&
7478 "VPlan-native path is not enabled. Only process inner loops.");
7479
7480 LLVM_DEBUG(dbgs() << "\nLV: Checking a loop in '"
7481 << L->getHeader()->getParent()->getName() << "' from "
7482 << L->getLocStr() << "\n");
7483
7484 LoopVectorizeHints Hints(
7485 Opts, L, InterleaveOnlyWhenForced || !Opts.interleave_loops, *ORE, TTI);
7486
7487 LLVM_DEBUG(
7488 dbgs() << "LV: Loop hints:"
7489 << " force="
7491 ? "disabled"
7493 ? "enabled"
7494 : "?"))
7495 << " width=" << Hints.getWidth()
7496 << " interleave=" << Hints.getInterleave() << "\n");
7497
7498 // Function containing loop
7499 Function *F = L->getHeader()->getParent();
7500
7501 // Looking at the diagnostic output is the only way to determine if a loop
7502 // was vectorized (other than looking at the IR or machine code), so it
7503 // is important to generate an optimization remark for each loop. Most of
7504 // these messages are generated as OptimizationRemarkAnalysis. Remarks
7505 // generated as OptimizationRemark and OptimizationRemarkMissed are
7506 // less verbose reporting vectorized loops and unvectorized loops that may
7507 // benefit from vectorization, respectively.
7508
7509 if (!Hints.allowVectorization(L, VectorizeOnlyWhenForced ||
7510 !Opts.vectorize_loops)) {
7511 LLVM_DEBUG(dbgs() << "LV: Loop hints prevent vectorization.\n");
7512 return false;
7513 }
7514
7515 PredicatedScalarEvolution PSE(*SE, *L);
7516
7517 // Query this against the original loop and save it here because the profile
7518 // of the original loop header may change as the transformation happens.
7519 bool OptForSize = llvm::shouldOptimizeForSize(
7520 L->getHeader(), PSI,
7521 PSI && PSI->hasProfileSummary() ? &GetBFI() : nullptr,
7524
7525 // Check if it is legal to vectorize the loop.
7526 LoopVectorizationRequirements Requirements;
7527 LoopVectorizationLegality LVL(Opts, L, PSE, DT, TTI, TLI, F, *LAIs, LI, ORE,
7528 &Requirements, &Hints, DB, AC,
7529 /*AllowRuntimeSCEVChecks=*/!OptForSize, AA);
7530 if (!LVL.canVectorize(Opts.enable_vplan_native_path)) {
7531 LLVM_DEBUG(dbgs() << "LV: Not vectorizing: Cannot prove legality.\n");
7532 Hints.emitRemarkWithHints();
7533 return false;
7534 }
7535
7536 bool IsInnerLoop = L->isInnermost();
7537
7538 // Outer loops require a computable trip count.
7539 if (!IsInnerLoop && isa<SCEVCouldNotCompute>(PSE.getBackedgeTakenCount())) {
7540 LLVM_DEBUG(dbgs() << "LV: cannot compute the outer-loop trip count\n");
7541 return false;
7542 }
7543
7544 if (LVL.hasUncountableEarlyExit()) {
7545 if (!Opts.enable_early_exit_vectorization) {
7546 reportVectorizationFailure("Auto-vectorization of loops with uncountable "
7547 "early exit is not enabled",
7548 "UncountableEarlyExitLoopsDisabled", ORE, L);
7549 return false;
7550 }
7552 !Opts.enable_early_exit_vectorization_with_side_effects) {
7553 reportVectorizationFailure("Auto-vectorization of loops with uncountable "
7554 "early exit and side effects is not enabled",
7555 "UncountableEarlyExitSideEffectLoopsDisabled",
7556 ORE, L);
7557 return false;
7558 }
7559 }
7560
7561 InterleavedAccessInfo IAI(PSE, L, DT, LI, LVL.getLAI(), OptForSize);
7562 // If an override option has been passed in for interleaved accesses, use it.
7563 bool UseInterleaved =
7564 IsInnerLoop && valueOr(Opts.enable_interleaved_mem_accesses,
7565 TTI->enableInterleavedAccessVectorization());
7566
7567 // Analyze interleaved memory accesses.
7568 if (UseInterleaved) {
7570 // If the loop exits from a block other than the latch, the scalar
7571 // iteration reserved for the exit may leave the loop before reaching the
7572 // grouped accesses.
7573 if (L->getExitingBlock() != L->getLoopLatch() &&
7576 }
7577
7578 if (LVL.hasUncountableEarlyExit()) {
7579 BasicBlock *LoopLatch = L->getLoopLatch();
7580 if (IAI.requiresScalarEpilogue() ||
7581 any_of(LVL.getCountableExitingBlocks(), not_equal_to(LoopLatch))) {
7582 reportVectorizationFailure("Auto-vectorization of early exit loops "
7583 "requiring a scalar epilogue is unsupported",
7584 "UncountableEarlyExitUnsupported", ORE, L);
7585 return false;
7586 }
7587 }
7588
7589 EpilogueLowering SEL =
7590 getEpilogueLowering(Opts, Hints, OptForSize, TTI, TLI, LVL, &IAI);
7591
7592 // Check the loop for a trip count threshold: vectorize loops with a tiny trip
7593 // count by optimizing for size, to minimize overheads.
7594 auto ExpectedTC = getSmallBestKnownTC(Opts, PSE, L);
7595 if (ExpectedTC && ExpectedTC->isFixed() &&
7596 ExpectedTC->getFixedValue() < Opts.vectorizer_min_trip_count) {
7597 LLVM_DEBUG(dbgs() << "LV: Found a loop with a very small trip count. "
7598 << "This loop is worth vectorizing only if no scalar "
7599 << "epilogue is required.");
7601 LLVM_DEBUG(dbgs() << " But vectorizing was explicitly forced.\n");
7602 else {
7603 LLVM_DEBUG(dbgs() << "\n");
7604 // For loops with very small trip counts, require that no scalar epilogue
7605 // is needed. Tail-folded loops are still allowed since they avoid
7606 // epilogues, unless the trip count is below the target's minimum for
7607 // tail-folding. In that case the tail cannot be folded, so the loop
7608 // should be treated like any other low trip count loop.
7609 // TODO: Remove the check for CM_EpilogueNotAllowedOptSize here. The
7610 // EpilogueLowering enum currently conflates several pieces of
7611 // information:
7612 // * Whether a scalar epilogue is permitted
7613 // * Whether tail folding is preferred or required
7614 // * Whether optimizing for code size
7615 // Overwriting it here can drop OptForSize, breaking the
7616 // runtimeChecksRequired() bail-out in computeMaxVF. Split
7617 // EpilogueLowering into separate fields instead.
7618 if (SEL != CM_EpilogueNotAllowedOptSize &&
7620 ExpectedTC->getFixedValue() <=
7621 TTI->getMinTripCountTailFoldingThreshold()))
7623 }
7624 }
7625
7626 // Check the function attributes to see if implicit floats or vectors are
7627 // allowed.
7628 if (F->hasFnAttribute(Attribute::NoImplicitFloat)) {
7630 "Can't vectorize when the NoImplicitFloat attribute is used",
7631 "loop not vectorized due to NoImplicitFloat attribute",
7632 "NoImplicitFloat", ORE, L);
7633 Hints.emitRemarkWithHints();
7634 return false;
7635 }
7636
7637 // Check if the target supports potentially unsafe FP vectorization.
7638 // FIXME: Add a check for the type of safety issue (denormal, signaling)
7639 // for the target we're vectorizing for, to make sure none of the
7640 // additional fp-math flags can help.
7641 if (Hints.isPotentiallyUnsafe() &&
7642 TTI->isFPVectorizationPotentiallyUnsafe()) {
7644 "Potentially unsafe FP op prevents vectorization",
7645 "loop not vectorized due to unsafe FP support.", "UnsafeFP", ORE, L);
7646 Hints.emitRemarkWithHints();
7647 return false;
7648 }
7649
7650 // If the flag is set, use that instead and override the TTI behaviour.
7651 bool AllowOrderedReductions =
7652 valueOr(Opts.force_ordered_reductions, TTI->enableOrderedReductions());
7653 if (!LVL.canVectorizeFPMath(AllowOrderedReductions)) {
7654 ORE->emit([&]() {
7655 auto *ExactFPMathInst = Requirements.getExactFPInst();
7656 return OptimizationRemarkAnalysisFPCommute(DEBUG_TYPE, "CantReorderFPOps",
7657 ExactFPMathInst->getDebugLoc(),
7658 ExactFPMathInst->getParent())
7659 << "loop not vectorized: cannot prove it is safe to reorder "
7660 "floating-point operations";
7661 });
7662 LLVM_DEBUG(dbgs() << "LV: loop not vectorized: cannot prove it is safe to "
7663 "reorder floating-point operations\n");
7664 Hints.emitRemarkWithHints();
7665 return false;
7666 }
7667
7668 // Use the cost model.
7669 VFSelectionContext Config(Opts, *TTI, &LVL, L, *F, PSE, DB, ORE, &Hints,
7670 OptForSize);
7671 // Use the planner for vectorization.
7673 L, LI, DT, TLI, *TTI, &LVL,
7674 std::make_unique<LoopVectorizationCostModel>(
7675 SEL, L, PSE, LI, &LVL, *TTI, TLI, AC, ORE, GetBFI, F, IAI, Config),
7676 Config, PSE, ORE, GetBPI);
7677
7678 // Get user vectorization factor and interleave count.
7679 ElementCount UserVF = Hints.getWidth();
7680 unsigned UserIC = Hints.getInterleave();
7681 // Outer loops don't have LoopAccessInfo, so skip the safety check and reset
7682 // UserIC (interleaving is not supported for outer loops).
7683 if (!IsInnerLoop)
7684 UserIC = 0;
7685 else if (UserIC > 1 && !LVL.isSafeForAnyVectorWidth())
7686 UserIC = 1;
7687
7688 // Plan how to best vectorize.
7689 LVP.plan(UserVF, UserIC);
7690 auto [VF, BestPlanPtr] = LVP.computeBestVF();
7691 unsigned IC = 1;
7692
7693 // For VPlan build stress testing of outer loops, bail after plan
7694 // construction.
7695 if (!IsInnerLoop && Opts.vplan_build_outerloop_stress_test)
7696 return false;
7697
7698 if (IsInnerLoop && ORE->allowExtraAnalysis(LV_NAME))
7700
7701 assert((IsInnerLoop || !LVP.getCostModel().maskPartialAliasing()) &&
7702 "Did not expect to alias-mask outer loop");
7703
7704 GeneratedRTChecks Checks(Opts, PSE, DT, LI, TTI, Config.CostKind,
7706 if (LVP.hasPlanWithVF(VF.Width)) {
7707 // Select the interleave count. Outer loops are not interleaved.
7708 if (IsInnerLoop)
7709 IC = LVP.selectInterleaveCount(*BestPlanPtr, VF.Width, VF.Cost);
7710
7711 unsigned SelectedIC = UserIC > 0 ? UserIC : IC;
7712 // Optimistically generate runtime checks if they are needed. Drop them if
7713 // they turn out to not be profitable.
7714 if (VF.Width.isVector() || SelectedIC > 1) {
7715 Checks.create(L, LVL.getLAI(), PSE.getPredicate(), VF.Width, SelectedIC,
7716 *ORE);
7717
7718 // Bail out early if either the SCEV or memory runtime checks are known to
7719 // fail. In that case, the vector loop would never execute.
7720 using namespace llvm::PatternMatch;
7721 if ((Checks.getSCEVChecks().first &&
7722 match(Checks.getSCEVChecks().first, m_One())) ||
7723 (Checks.getMemRuntimeChecks().first &&
7724 match(Checks.getMemRuntimeChecks().first, m_One()))) {
7726 "runtime checks are known to fail, so we will never enter the "
7727 "vector loop",
7728 "RuntimeChecksNeverEnterVectorLoop", ORE, L);
7729 return false;
7730 }
7731 }
7732
7733 // Check if it is profitable to vectorize with runtime checks.
7734 bool ForceVectorization =
7736 assert((IsInnerLoop || ForceVectorization) &&
7737 "Outer loops must be forced to vectorize");
7738 VPCostContext CostCtx(*TLI, *BestPlanPtr, LVP.getCostModel(), Config,
7739 /*ReusePrintingSlotTracker=*/true);
7740 if (!ForceVectorization &&
7741 !isOutsideLoopWorkProfitable(Checks, VF, L, PSE, CostCtx, *BestPlanPtr,
7742 SEL, Config.getVScaleForTuning())) {
7743 ORE->emit([&]() {
7745 DEBUG_TYPE, "CantReorderMemOps", L->getStartLoc(),
7746 L->getHeader())
7747 << "loop not vectorized: cannot prove it is safe to reorder "
7748 "memory operations";
7749 });
7750 LLVM_DEBUG(dbgs() << "LV: Too many memory checks needed.\n");
7751 Hints.emitRemarkWithHints();
7752 return false;
7753 }
7754 }
7755
7756 // Identify the diagnostic messages that should be produced.
7757 std::pair<StringRef, std::string> VecDiagMsg, IntDiagMsg;
7758 bool VectorizeLoop = true, InterleaveLoop = true;
7759 if (VF.Width.isScalar()) {
7760 if (LVP.hasVectorPlan()) {
7761 LLVM_DEBUG(
7762 dbgs() << "LV: Vectorization is possible but not beneficial.\n");
7763 VecDiagMsg = {
7764 "VectorizationNotBeneficial",
7765 "the cost-model indicates that vectorization is not beneficial"};
7766 } else {
7767 LLVM_DEBUG(dbgs() << "LV: Vectorization is not possible. Failed to "
7768 "create any vector VPlans.\n");
7769 VecDiagMsg = {"VectorizationNotPossible",
7770 "vectorization is not possible"};
7771 }
7772 VectorizeLoop = false;
7773 }
7774
7775 if (UserIC == 1 && Hints.getInterleave() > 1) {
7777 "UserIC should only be ignored due to unsafe dependencies");
7778 LLVM_DEBUG(dbgs() << "LV: Ignoring user-specified interleave count.\n");
7779 IntDiagMsg = {"InterleavingUnsafe",
7780 "Ignoring user-specified interleave count due to possibly "
7781 "unsafe dependencies in the loop."};
7782 InterleaveLoop = false;
7783 } else if (!LVP.hasPlanWithVF(VF.Width) && UserIC > 1) {
7784 // Tell the user interleaving was avoided up-front, despite being explicitly
7785 // requested.
7786 LLVM_DEBUG(dbgs() << "LV: Ignoring UserIC, because vectorization and "
7787 "interleaving should be avoided up front\n");
7788 IntDiagMsg = {"InterleavingAvoided",
7789 "Ignoring UserIC, because interleaving was avoided up front"};
7790 InterleaveLoop = false;
7791 } else if (IC == 1 && UserIC <= 1) {
7792 // Tell the user interleaving is not beneficial.
7793 if (LVP.hasAPlan()) {
7794 LLVM_DEBUG(dbgs() << "LV: Interleaving is not beneficial.\n");
7795 IntDiagMsg = {
7796 "InterleavingNotBeneficial",
7797 "the cost-model indicates that interleaving is not beneficial"};
7798 if (UserIC == 1) {
7799 IntDiagMsg.first = "InterleavingNotBeneficialAndDisabled";
7800 IntDiagMsg.second +=
7801 " and is explicitly disabled or interleave count is set to 1";
7802 }
7803 } else {
7804 LLVM_DEBUG(dbgs() << "LV: Interleaving is not possible. Failed to create"
7805 << " any vplans\n");
7806 IntDiagMsg = {"InterleavingNotPossible", "interleaving is not possible"};
7807 }
7808 InterleaveLoop = false;
7809 } else if (IC > 1 && UserIC == 1) {
7810 // Tell the user interleaving is beneficial, but it explicitly disabled.
7811 LLVM_DEBUG(dbgs() << "LV: Interleaving is beneficial but is explicitly "
7812 "disabled.\n");
7813 IntDiagMsg = {"InterleavingBeneficialButDisabled",
7814 "the cost-model indicates that interleaving is beneficial "
7815 "but is explicitly disabled or interleave count is set to 1"};
7816 InterleaveLoop = false;
7817 }
7818
7819 // If there is a histogram in the loop, do not just interleave without
7820 // vectorizing. The order of operations will be incorrect without the
7821 // histogram intrinsics, which are only used for recipes with VF > 1.
7822 if (!VectorizeLoop && InterleaveLoop && LVL.hasHistograms()) {
7823 LLVM_DEBUG(dbgs() << "LV: Not interleaving without vectorization due "
7824 << "to histogram operations.\n");
7825 IntDiagMsg = {
7826 "HistogramPreventsScalarInterleaving",
7827 "Unable to interleave without vectorization due to constraints on "
7828 "the order of histogram operations"};
7829 InterleaveLoop = false;
7830 }
7831
7832 // Override IC if user provided an interleave count.
7833 IC = UserIC > 0 ? UserIC : IC;
7834
7835 if (LVP.getCostModel().maskPartialAliasing()) {
7836 LLVM_DEBUG(
7837 dbgs()
7838 << "LV: Not interleaving due to partial aliasing vectorization.\n");
7839 IntDiagMsg = {
7840 "PartialAliasingVectorization",
7841 "Unable to interleave due to partial aliasing vectorization."};
7842 InterleaveLoop = false;
7843 IC = 1;
7844 }
7845
7846 // FIXME: Enable interleaving for EE-with-side-effects.
7847 if (InterleaveLoop && LVL.hasUncountableExitWithSideEffects()) {
7848 LLVM_DEBUG(dbgs() << "LV: Not interleaving due to EE with side effects.\n");
7849 IntDiagMsg = {"EEWithSideEffectsPreventsInterleaving",
7850 "Unable to interleave due to early exit with side effects."};
7851 InterleaveLoop = false;
7852 IC = 1;
7853 }
7854
7855 if (InterleaveLoop && LVL.hasConditionalInductions()) {
7856 LLVM_DEBUG(
7857 dbgs() << "LV: Not interleaving due to conditional inductions.\n");
7858 IntDiagMsg = {"ConditionalInductionsPreventInterleaving",
7859 "Unable to interleave due to conditional inductions."};
7860 InterleaveLoop = false;
7861 IC = 1;
7862 }
7863
7864 // Emit diagnostic messages, if any.
7865 if (!VectorizeLoop && !InterleaveLoop) {
7866 // Do not vectorize or interleaving the loop.
7867 ORE->emit([&]() {
7868 return OptimizationRemarkMissed(LV_NAME, VecDiagMsg.first,
7869 L->getStartLoc(), L->getHeader())
7870 << VecDiagMsg.second;
7871 });
7872 ORE->emit([&]() {
7873 return OptimizationRemarkMissed(LV_NAME, IntDiagMsg.first,
7874 L->getStartLoc(), L->getHeader())
7875 << IntDiagMsg.second;
7876 });
7877 return false;
7878 }
7879
7880 if (!VectorizeLoop && InterleaveLoop) {
7881 LLVM_DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n');
7882 ORE->emit([&]() {
7883 return OptimizationRemarkAnalysis(LV_NAME, VecDiagMsg.first,
7884 L->getStartLoc(), L->getHeader())
7885 << VecDiagMsg.second;
7886 });
7887 } else if (VectorizeLoop && !InterleaveLoop) {
7888 LLVM_DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width
7889 << ") in " << L->getLocStr() << '\n');
7890 ORE->emit([&]() {
7891 return OptimizationRemarkAnalysis(LV_NAME, IntDiagMsg.first,
7892 L->getStartLoc(), L->getHeader())
7893 << IntDiagMsg.second;
7894 });
7895 } else if (VectorizeLoop && InterleaveLoop) {
7896 LLVM_DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width
7897 << ") in " << L->getLocStr() << '\n');
7898 LLVM_DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n');
7899 }
7900
7901 // Report the vectorization decision.
7902 if (VF.Width.isScalar()) {
7903 using namespace ore;
7904 assert(IC > 1);
7905 ORE->emit([&]() {
7906 return OptimizationRemark(LV_NAME, "Interleaved", L->getStartLoc(),
7907 L->getHeader())
7908 << "interleaved loop (interleaved count: "
7909 << NV("InterleaveCount", IC) << ")";
7910 });
7911 } else {
7912 // Report the vectorization decision.
7913 reportVectorization(ORE, L, VF.Width, IC);
7914 }
7915 if (ORE->allowExtraAnalysis(LV_NAME))
7917
7918 // If we decided that it is *legal* to interleave or vectorize the loop, then
7919 // do it.
7920
7921 // Whether a scalar epilogue may be created is decided by the epilogue
7922 // lowering policy.
7923 // TODO: Also move check to be based on VPlan.
7924 bool ScalarEpilogueAllowed = LVP.getCostModel().isEpilogueAllowed();
7925
7926 // Destroy the cost model before executing any plan, so that code generation
7927 // cannot rely on cost-modeling decisions.
7928 LVP.clearCostModel();
7929
7930 VPlan &BestPlan = *BestPlanPtr;
7931 // Consider vectorizing the epilogue too if it's profitable.
7932 std::unique_ptr<VPlan> EpiPlan =
7933 LVP.selectBestEpiloguePlan(BestPlan, VF.Width, IC, ScalarEpilogueAllowed);
7934 bool HasBranchWeights =
7935 hasBranchWeightMD(*L->getLoopLatch()->getTerminator());
7936 if (EpiPlan) {
7937 VPlan &BestEpiPlan = *EpiPlan;
7938 VPlan &BestMainPlan = BestPlan;
7939 ElementCount EpilogueVF = BestEpiPlan.getSingleVF();
7940
7941 // The first pass vectorizes the main loop and creates a scalar epilogue
7942 // to be vectorized by executing the plan (potentially with a different
7943 // factor) again shortly afterwards.
7944 BestEpiPlan.getMiddleBlock()->setName("vec.epilog.middle.block");
7945 BestEpiPlan.getVectorPreheader()->setName("vec.epilog.ph");
7947
7948 // Add minimum iteration check for the epilogue plan, followed by runtime
7949 // checks for the main plan.
7950 LVP.addMinimumIterationCheck(BestMainPlan, EpilogueVF, /*UF=*/1,
7952 BestEpiPlan.hasTailFolded());
7953 LVP.attachRuntimeChecks(BestMainPlan, Checks, VF.Width, IC,
7954 HasBranchWeights);
7956 VF.Width, IC, BestMainPlan.requiresScalarEpilogue(), L,
7957 HasBranchWeights ? MinItersBypassWeights : nullptr,
7958 L->getLoopPredecessor()->getTerminator()->getDebugLoc(),
7959 PSE);
7960
7961 LLVM_DEBUG({
7962 dbgs() << "Create Skeleton for epilogue vectorized loop (first pass)\n"
7963 << "Main Loop VF:" << VF.Width << ", Main Loop UF:" << IC
7964 << ", Epilogue Loop VF:" << EpilogueVF << ", Epilogue Loop UF:1\n";
7965 });
7966 // Keep track of the iteration count check of the main vector loop.
7967 VPBasicBlock *MainBlocks[] = {cast<VPBasicBlock>(
7968 BestMainPlan.getVectorPreheader()->getSinglePredecessor())};
7969 auto ExpandedSCEVs = LVP.executePlan(
7970 VF.Width, IC, BestMainPlan, Checks.hasChecks(),
7972 MainBlocks);
7973 VPBasicBlock *MainCheck = MainBlocks[0];
7974 ++LoopsVectorized;
7976 dbgs() << "intermediate fn:\n" << *L->getHeader()->getParent() << "\n";
7977 });
7978
7979 BasicBlock *EntryBB =
7980 cast<VPIRBasicBlock>(BestMainPlan.getEntry())->getIRBasicBlock();
7981 EntryBB->setName("iter.check");
7983 ->getIRBasicBlock()
7984 ->setName("vec.epilog.iter.check");
7985
7986 // Second pass vectorizes the epilogue and adjusts the control flow
7987 // edges from the first pass.
7988 preparePlanForEpilogueVectorLoop(BestMainPlan, BestEpiPlan, ExpandedSCEVs,
7989 VF.Width, IC, EpilogueVF, Config,
7990 *PSE.getSE(), Markers, MainCheck);
7992 LLVM_DEBUG({
7993 dbgs() << "Create Skeleton for epilogue vectorized loop (second pass)\n"
7994 << "Epilogue Loop VF:" << EpilogueVF << ", Epilogue Loop UF:1\n";
7995 });
7996 LVP.executePlan(
7997 EpilogueVF, /*BestUF=*/1, BestEpiPlan, Checks.hasChecks(),
8000 dbgs() << "final fn:\n" << *L->getHeader()->getParent() << "\n";
8001 });
8002 ++LoopsEpilogueVectorized;
8003 } else {
8004 LVP.addMinimumIterationCheck(BestPlan, VF.Width, IC,
8005 VF.MinProfitableTripCount,
8006 /*TailFoldedEpilogue=*/false);
8007 LVP.attachRuntimeChecks(BestPlan, Checks, VF.Width, IC, HasBranchWeights);
8008
8009 if (!IsInnerLoop)
8010 LLVM_DEBUG(dbgs() << "Vectorizing outer loop in \"" << F->getName()
8011 << "\"\n");
8012 LVP.executePlan(VF.Width, IC, BestPlan, Checks.hasChecks());
8013 ++LoopsVectorized;
8014 }
8015
8016#ifdef EXPENSIVE_CHECKS
8017 assert(DT->verify(DominatorTree::VerificationLevel::Fast) &&
8018 "DT not preserved correctly");
8019#endif
8020
8021 return true;
8022}
8023
8025 CFGChanged = false;
8026
8027 // Don't attempt if
8028 // 1. the target claims to have no vector registers, and
8029 // 2. interleaving won't help ILP.
8030 //
8031 // The second condition is necessary because, even if the target has no
8032 // vector registers, loop vectorization may still enable scalar
8033 // interleaving.
8034 if (!TTI->getNumberOfRegisters(TTI->getRegisterClassForType(true)) &&
8035 (TTI->getMaxInterleaveFactor(ElementCount::getFixed(1), false) < 2 ||
8036 TTI->getMaxInterleaveFactor(ElementCount::getFixed(1), true) < 2))
8037 return LoopVectorizeResult(false, false);
8038
8039 bool Changed = false;
8040
8041 // The vectorizer requires loops to be in simplified form.
8042 // Since simplification may add new inner loops, it has to run before the
8043 // legality and profitability checks. This means running the loop vectorizer
8044 // will simplify all loops, regardless of whether anything end up being
8045 // vectorized.
8046 for (const auto &L : *LI)
8047 Changed |= CFGChanged |= simplifyLoop(L, DT, LI, SE, AC, nullptr,
8048 false /* PreserveLCSSA */, TTI);
8049
8050 // Build up a worklist of inner-loops to vectorize. This is necessary as
8051 // the act of vectorizing or partially unrolling a loop creates new loops
8052 // and can invalidate iterators across the loops.
8053 SmallVector<Loop *, 8> Worklist;
8054
8055 const VectorizeOptions &Opts = getVectorizeOptions(F);
8056 for (Loop *L : *LI)
8057 collectSupportedLoops(Opts, *L, LI, ORE, Worklist);
8058
8059 LoopsAnalyzed += Worklist.size();
8060
8061 // Now walk the identified inner loops.
8062 while (!Worklist.empty()) {
8063 Loop *L = Worklist.pop_back_val();
8064
8065 // For the inner loops we actually process, form LCSSA to simplify the
8066 // transform.
8067 Changed |= formLCSSARecursively(*L, *DT, LI, SE);
8068
8070
8071 if (Changed) {
8072 LAIs->clear();
8073
8074#ifndef NDEBUG
8075 if (VerifySCEV)
8076 SE->verify();
8077#endif
8078 }
8079 }
8080
8081 // Verify once per function rather than once per processed loop, which would
8082 // make the pass quadratic in the number of loops.
8083 assert((!Changed || DT->verify(DominatorTree::VerificationLevel::Fast)) &&
8084 "DT not preserved correctly");
8085 assert((!Changed || !verifyFunction(F, &dbgs())) &&
8086 "Invalid IR produced by LoopVectorize");
8087
8088 // Process each loop nest in the function.
8090}
8091
8094 LI = &AM.getResult<LoopAnalysis>(F);
8095 // There are no loops in the function. Return before computing other
8096 // expensive analyses.
8097 if (LI->empty())
8098 return PreservedAnalyses::all();
8107 AA = &AM.getResult<AAManager>(F);
8108
8109 auto &MAMProxy = AM.getResult<ModuleAnalysisManagerFunctionProxy>(F);
8110 PSI = MAMProxy.getCachedResult<ProfileSummaryAnalysis>(*F.getParent());
8111 // CycleInfo cached by an earlier pass is invalidated when the CFG changes.
8112 // Both BlockFrequencyAnalysis and BranchProbabilityAnalysis depend on it, so
8113 // drop the stale result before either is (re-)computed.
8114 auto ClearStaleCycleInfo = [this, &AM, &F] {
8117 };
8118 GetBFI = [&AM, &F, ClearStaleCycleInfo]() -> BlockFrequencyInfo & {
8119 ClearStaleCycleInfo();
8121 };
8122 GetBPI = [&AM, &F, ClearStaleCycleInfo]() -> const BranchProbabilityInfo & {
8123 ClearStaleCycleInfo();
8125 };
8126 LoopVectorizeResult Result = runImpl(F);
8127 if (!Result.MadeAnyChange)
8128 return PreservedAnalyses::all();
8130
8131 if (isAssignmentTrackingEnabled(*F.getParent())) {
8132 for (auto &BB : F)
8134 }
8135
8136 PA.preserve<LoopAnalysis>();
8140
8141 if (Result.MadeCFGChange) {
8142 // Making CFG changes likely means a loop got vectorized. Indicate that
8143 // extra simplification passes should be run.
8144 // TODO: MadeCFGChanges is not a prefect proxy. Extra passes should only
8145 // be run if runtime checks have been added.
8148 } else {
8150 }
8151 return PA;
8152}
8153
8155 raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
8156 static_cast<PassInfoMixin<LoopVectorizePass> *>(this)->printPipeline(
8157 OS, MapClassName2PassName);
8158
8159 OS << '<';
8160 OS << (InterleaveOnlyWhenForced ? "" : "no-") << "interleave-forced-only;";
8161 OS << (VectorizeOnlyWhenForced ? "" : "no-") << "vectorize-forced-only;";
8162 OS << '>';
8163}
static unsigned getIntrinsicID(const SDNode *N)
const TargetLowering & TLI
SDValue Pred
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
AMDGPU Lower Kernel Arguments
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
This file contains the simple types necessary to represent the attributes associated with functions a...
static const Function * getParent(const Value *V)
This is the interface for LLVM's primary stateless and local alias analysis.
static bool IsEmptyBlock(MachineBasicBlock *MBB)
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
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")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static InstructionCost getCost(const AnalysisOptions &Opts, Instruction &Inst, TTI::TargetCostKind CostKind, TargetTransformInfo &TTI)
Definition CostModel.cpp:33
This file declares an analysis pass that computes CycleInfo for LLVM IR, specialized from GenericCycl...
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< ElementCount, 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.
This file provides a LoopVectorizationPlanner class.
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 void legacyCSE(BasicBlock *BB)
FIXME: This legacy common-subexpression-elimination routine is scheduled for removal,...
static VPIRBasicBlock * replaceVPBBWithIRVPBB(VPBasicBlock *VPBB, BasicBlock *IRBB, VPlan *Plan=nullptr)
Replace VPBB with a VPIRBasicBlock wrapping IRBB.
static Intrinsic::ID getMaskedDivRemIntrinsic(unsigned Opcode)
static DebugLoc getDebugLocFromInstOrOperands(Instruction *I)
Look for a meaningful debug location on the instruction or its operands.
static EpilogueLowering getEpilogueTailLowering(const VectorizeOptions &Opts, const LoopVectorizationCostModel &MainCM, const Loop *L, OptimizationRemarkEmitter *ORE, LoopVectorizationLegality &LVL, const LoopVectorizeHints &Hints, const TargetTransformInfo *TTI)
Determine how to lower the epilogue for the vector epilogue loop.
static bool useActiveLaneMaskForControlFlow(TailFoldingStyle Style)
static std::optional< VPExecutionFrequency > getRecordedExecutionFrequency(const VPBasicBlock *VPBB)
Returns the frequency with which VPBB executes, as recorded on its recipes.
static void collectSupportedLoops(const VectorizeOptions &Opts, Loop &L, LoopInfo *LI, OptimizationRemarkEmitter *ORE, SmallVectorImpl< Loop * > &V)
static unsigned estimateElementCount(ElementCount VF, std::optional< unsigned > VScale)
This function attempts to return a value that represents the ElementCount at runtime.
static bool hasVectorLibraryVariantFor(const CallInst &CI, ElementCount VF, bool MaskRequired, const TargetLibraryInfo *TLI)
Returns true iff CI has a library vector variant usable at VF.
static constexpr uint32_t MinItersBypassWeights[]
static Function * getVectorLibraryVariantFor(const CallInst &CI, ElementCount VF, bool MaskRequired, const TargetLibraryInfo *TLI)
Returns the vector library variant function of CI usable at VF, respecting MaskRequired,...
static bool isExplicitVecOuterLoop(const VectorizeOptions &Opts, Loop *OuterLp, OptimizationRemarkEmitter *ORE)
static void preparePlanForEpilogueVectorLoop(VPlan &MainPlan, VPlan &Plan, const SCEV2ValueTy &ExpandedSCEVs, ElementCount MainLoopVF, unsigned MainLoopUF, ElementCount EpilogueVF, VFSelectionContext &Config, ScalarEvolution &SE, const MainPlanResumeMarkers &Markers, VPBasicBlock *MainCheck)
Prepare Plan for vectorizing the epilogue loop.
static bool hasForcedEpilogueVF()
static bool hasConditionalInductionPhi(VPlan &Plan)
Returns true if the VPlan contains a VPConditionalInductionPHIRecipe.
static void printOptimizedVPlan(VPlan &)
static bool isIndvarOverflowCheckKnownFalse(const VectorizeOptions &Opts, 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 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 std::optional< ElementCount > getSmallBestKnownTC(const VectorizeOptions &Opts, PredicatedScalarEvolution &PSE, Loop *L, bool CanUseConstantMax=true, bool CanExcludeZeroTrips=false, bool ComputeUpperBoundOnly=false)
Returns "best known" trip count, which is either a valid positive trip count or std::nullopt when an ...
static bool useMaskedInterleavedAccesses(const VectorizeOptions &Opts, const TargetTransformInfo &TTI)
static bool useActiveLaneMask(TailFoldingStyle Style)
static bool hasReplicatorRegion(VPlan &Plan)
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 EpilogueLowering getEpilogueLowering(const VectorizeOptions &Opts, LoopVectorizeHints &Hints, bool OptForSize, TargetTransformInfo *TTI, TargetLibraryInfo *TLI, LoopVectorizationLegality &LVL, InterleavedAccessInfo *IAI)
static bool verifyExecutionFrequenciesMatchBFI(VPlan &Plan, Loop *OrigLoop, LoopInfo *LI, LoopVectorizationCostModel &CM)
Cross-check the execution frequencies recorded in Plan against BlockFrequencyInfo for the blocks of O...
static bool isOutsideLoopWorkProfitable(GeneratedRTChecks &Checks, VectorizationFactor &VF, Loop *L, PredicatedScalarEvolution &PSE, VPCostContext &CostCtx, VPlan &Plan, EpilogueLowering SEL, std::optional< unsigned > VScale)
This function determines whether or not it's still profitable to vectorize the loop given the extra w...
static InstructionCost calculateEarlyExitCost(VPCostContext &CostCtx, VPlan &Plan, ElementCount VF)
For loops with uncountable early exits, find the cost of doing work when exiting the loop early,...
static void checkMixedPrecision(Loop *L, OptimizationRemarkEmitter *ORE)
static cl::opt< ElementCount > EpilogueVectorizationForceVF("epilogue-vectorization-force-VF", cl::init(ElementCount::getFixed(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. Note: This allows all scalable VFs >= vscale x 1."))
static bool willGenerateVectors(VPlan &Plan, ElementCount VF, const TargetTransformInfo &TTI)
Check if any recipe of Plan will generate a vector value, which will be assigned a vector register.
static MainPlanResumeMarkers preparePlanForMainVectorLoop(VPlan &MainPlan)
Prepare MainPlan for vectorizing the main vector loop during epilogue vectorization.
#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.
R600 Emit Clause Markers
SmallVector< MachineOperand, 4 > Cond
static bool isValid(const char C)
Returns true if C is a valid mangled character: <0-9a-zA-Z_>.
SI Fold Operands
Func getContext().diagnose(DiagnosticInfoUnsupported(Func
This file contains some templates that are useful if you are working with the STL at all.
#define OP(OPC)
Definition Instruction.h:46
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
#define DEBUG_WITH_TYPE(TYPE,...)
DEBUG_WITH_TYPE macro - This macro should be used by passes to emit debug information.
Definition Debug.h:72
static const CodeGenOptions & getOpts(const TargetMachine &TM)
This pass exposes codegen information to IR-level passes.
LocallyHashedType DenseMapInfo< LocallyHashedType >::Empty
This file implements the TypeSwitch template, which mimics a switch() statement whose cases are type ...
This file contains the declarations of different VPlan-related auxiliary helpers.
This file provides utility VPlan to VPlan transformations.
#define RUN_VPLAN_PASS(PASS,...)
#define RUN_VPLAN_PASS_NO_VERIFY(PASS,...)
This file declares the class VPlanVerifier, which contains utility functions to check the consistency...
This file contains the declarations of the Vectorization Plan base classes:
Value * RHS
Value * LHS
static const uint32_t IV[8]
Definition blake3_impl.h:83
A manager for alias analyses.
static constexpr roundingMode rmTowardZero
Definition APFloat.h:384
static constexpr const fltSemantics & IEEEdouble()
Definition APFloat.h:306
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:230
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1560
unsigned getActiveBits() const
Compute the number of active bits in the value.
Definition APInt.h:1532
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:376
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Definition APInt.h:1115
void clearAnalysis(IRUnitT &IR)
Directly clear a cached analysis for an IR unit.
PassT::Result * getCachedResult(IRUnitT &IR) const
Get the cached result of an analysis pass for a given IR unit.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
ArrayRef< T > take_back(size_t N=1) const
Return a copy of *this with only the last N elements.
Definition ArrayRef.h:225
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:509
LLVM_ABI const BasicBlock * getSingleSuccessor() const
Return the successor of this block if it has a single successor.
LLVM_ABI LLVMContext & getContext() const
Get the context in which this basic block lives.
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
Analysis pass which computes BlockFrequencyInfo.
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
LLVM_ABI BlockFrequency getBlockFreq(const BasicBlock *BB) const
getblockFreq - Return block frequency.
uint64_t getFrequency() const
Returns the frequency as a fixpoint number scaled by the entry frequency.
Analysis pass which computes BranchProbabilityInfo.
Analysis providing branch probability information.
static LLVM_ABI BranchProbability getBranchProbability(uint64_t Numerator, uint64_t Denominator)
static uint32_t getDenominator()
uint32_t getNumerator() const
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
bool isNoBuiltin() const
Return true if the call should not be treated as a call to a builtin.
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
iterator_range< User::op_iterator > args()
Iteration adapter for range-for loops.
This class represents a function call, abstracting a target machine's calling convention.
static Type * makeCmpResultType(Type *opnd_type)
Create a result type for fcmp/icmp.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:763
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
@ ICMP_NE
not equal
Definition InstrTypes.h:762
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.
Analysis pass which computes a CycleInfo.
A debug info location.
Definition DebugLoc.h:127
static DebugLoc getTemporary()
Definition DebugLoc.h:153
static DebugLoc getUnknown()
Definition DebugLoc.h:154
An analysis that produces DemandedBits for a function.
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
Definition DenseMap.h:757
void insert_range(Range &&R)
Inserts a range of 'std::pair<KeyT, ValueT>' values into the map.
Definition DenseMap.h:894
ValueT lookup_or(const_arg_type_t< KeyT > Val, U &&Default) const
Definition DenseMap.h:803
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
Definition DenseMap.h:793
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:856
Implements a dense probed hash-table based set.
Definition DenseSet.h:283
Analysis pass which computes a DominatorTree.
Definition Dominators.h:241
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:122
constexpr bool isVector() const
One or more elements.
Definition TypeSize.h:321
static constexpr ElementCount getScalable(ScalarTy MinVal)
Definition TypeSize.h:309
static constexpr ElementCount getFixed(ScalarTy MinVal)
Definition TypeSize.h:306
static constexpr ElementCount get(ScalarTy MinVal, bool Scalable)
Definition TypeSize.h:312
constexpr bool isScalar() const
Exactly one element.
Definition TypeSize.h:317
constexpr bool isPowerOf2() const
Definition TypeSize.h:324
Tagged union holding either a T or a Error.
Definition Error.h:485
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:212
Common base class shared among various IRBuilders.
Definition IRBuilder.h:111
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2990
A struct for saving information about induction variables.
@ IK_PtrInduction
Pointer induction var. Step = C.
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.
iterator_range< user_iterator > users()
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:333
LLVM_ABI APInt getMask() const
For example, this is 0xFF for an 8 bit integer, 0xFFFF for i16, etc.
Definition Type.cpp:357
The group of interleaved loads/stores sharing the same stride and close to each other.
auto members() const
Return an iterator range over the non-null members of this group, in index order.
InstTy * getInsertPos() const
uint32_t getNumMembers() const
Drive the analysis of interleaved memory accesses in the loop.
bool requiresScalarEpilogue() const
Returns true if an interleaved group that may access memory out-of-bounds requires a scalar epilogue ...
bool hasGroups() const
Returns true if we have any interleave groups.
iterator_range< SmallPtrSetIterator< llvm::InterleaveGroup< Instruction > * > > getInterleaveGroups()
LLVM_ABI void analyzeInterleaving(bool EnableMaskedInterleavedGroup)
Analyze the interleaved accesses and collect them in interleave groups.
LLVM_ABI void invalidateGroupsRequiringScalarEpilogue()
Invalidate groups that require a scalar epilogue (due to gaps).
An instruction for reading from memory.
Type * getPointerOperandType() const
This analysis provides dependence information for the memory accesses of a loop.
const RuntimePointerChecking * getRuntimePointerChecking() const
unsigned getNumRuntimePointerChecks() const
Number of memchecks required to prove independence of otherwise may-alias pointers.
const SymbolicStrideMap & getSymbolicStrides() const
If an access has a symbolic strides, this maps the pointer value to the stride symbol.
Analysis pass that exposes the LoopInfo for a function.
Definition LoopInfo.h:598
bool contains(const LoopT *L) const
Return true if the specified loop is contained within 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.
unsigned getNumBlocks() const
Get the number of blocks in this loop in constant time.
BlockT * getHeader() const
BlockT * getExitingBlock() const
If getExitingBlocks would return exactly one block, return that block.
Store the result of a depth first search within basic blocks contained by a single loop.
RPOIterator beginRPO() const
Reverse iterate over the cached postorder blocks.
LLVM_ABI void perform(const LoopInfo *LI)
Traverse the loop blocks and store the DFS result.
RPOIterator endRPO() const
Wrapper class to LoopBlocksDFS that provides a standard begin()/end() interface for the DFS reverse p...
void perform(const LoopInfo *LI)
Traverse the loop blocks and store the DFS result.
void removeBlock(BlockT *BB)
This method completely removes BB from all data structures, including all of the Loop objects it is n...
LoopVectorizationCostModel - estimates the expected speedups due to vectorization.
bool isPredicatedInst(Instruction *I) const
Returns true if I is an instruction that needs to be predicated at runtime.
void collectValuesToIgnore()
Collect values we want to ignore in the cost model.
BlockFrequencyInfo * BFI
The BlockFrequencyInfo returned from GetBFI.
BlockFrequencyInfo & getBFI()
Returns the BlockFrequencyInfo for the function if cached, otherwise fetches it via GetBFI.
bool isForcedScalar(Instruction *I, ElementCount VF) const
Returns true if I has been forced to be scalarized at VF.
bool isUniformAfterVectorization(Instruction *I, ElementCount VF) const
Returns true if I is known to be uniform after vectorization.
void collectNonVectorizedAndSetWideningDecisions(ElementCount VF)
Collect values that will not be widened, including Uniforms, Scalars, and Instructions to Scalarize f...
static constexpr StringLiteral getInstWideningStr(InstWidening W)
bool isMaskRequired(Instruction *I) const
Wrapper function for LoopVectorizationLegality::isMaskRequired, that passes the Instruction I and if ...
PredicatedScalarEvolution & PSE
Predicated scalar evolution analysis.
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< InstWidening > memoryInstructionCanBeWidened(Instruction *I, ElementCount VF)
If I is a memory instruction with a consecutive pointer that can be widened, returns the widening kin...
InstructionCost getInstructionCost(Instruction *I, ElementCount VF)
Returns the execution time cost of an instruction for a given vector width.
bool interleavedAccessCanBeWidened(Instruction *I, ElementCount VF) const
Returns true if I is a memory instruction in an interleaved-group of memory accesses that can be vect...
const TargetLibraryInfo * TLI
Target Library Info.
const InterleaveGroup< Instruction > * getInterleavedAccessGroup(Instruction *Instr) const
Get the interleaved access group that Instr belongs to.
InstructionCost getVectorIntrinsicCost(CallInst *CI, ElementCount VF) const
Estimate cost of an intrinsic call instruction CI if it were vectorized with factor VF.
bool maskPartialAliasing() const
Returns true if all loop blocks should have partial aliases masked.
bool isScalarAfterVectorization(Instruction *I, ElementCount VF) const
Returns true if I is known to be scalar after vectorization.
bool isOptimizableIVTruncate(Instruction *I, ElementCount VF)
Return True if instruction I is an optimizable truncate whose operand is an induction variable.
bool isLegalGatherOrScatter(Instruction *I, ElementCount VF) const
Returns true if the target machine supports gather or scatter for I's data type and alignment.
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.
LoopVectorizationCostModel(EpilogueLowering SEL, Loop *L, PredicatedScalarEvolution &PSE, LoopInfo *LI, LoopVectorizationLegality *Legal, const TargetTransformInfo &TTI, const TargetLibraryInfo *TLI, AssumptionCache *AC, OptimizationRemarkEmitter *ORE, std::function< BlockFrequencyInfo &()> GetBFI, const Function *F, InterleavedAccessInfo &IAI, VFSelectionContext &Config)
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 usePredicatedReductionSelect(RecurKind RecurrenceKind, bool HasUsesOutsideReductionChain) const
Returns true if the predicated reduction select should be used to set the incoming value for the redu...
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 useEmulatedMaskMemRefHack(Instruction *I, ElementCount VF) const
Returns true if an artificially high cost for emulated masked memrefs should be used.
bool isLegalMaskedLoadOrStore(Instruction *I, ElementCount VF) const
Returns true if the target machine supports masked loads or stores for I's data type and alignment.
bool isProfitableToScalarize(Instruction *I, ElementCount VF) const
void setWideningDecision(const InterleaveGroup< Instruction > *Grp, ElementCount VF, InstWidening W, InstructionCost Cost)
Save vectorization decision W and Cost taken by the cost model for interleaving group Grp and vector ...
bool isEpilogueAllowed() const
Returns true if an epilogue is allowed (e.g., not prevented by optsize or a loop hint annotation).
bool canTruncateToMinimalBitwidth(Instruction *I, ElementCount VF) const
bool shouldConsiderInvariant(Value *Op)
Returns true if Op should be considered invariant and if it is trivially hoistable.
bool foldTailByMasking() const
Returns true if all loop blocks should be masked to fold tail loop.
bool foldTailWithEVL() const
Returns true if VP intrinsics with explicit vector length support should be generated in the tail fol...
bool blockNeedsPredicationForAnyReason(BasicBlock *BB) const
Returns true if the instructions in this block requires predication for any reason,...
AssumptionCache * AC
Assumption cache.
void setWideningDecision(Instruction *I, ElementCount VF, InstWidening W, InstructionCost Cost)
Save vectorization decision W and Cost taken by the cost model for instruction I and vector width VF.
InstWidening
Decision that was taken during cost calculation for memory instruction.
@ CM_InvalidatedDecision
A widening decision that has been invalidated after replacing the corresponding recipe during VPlan t...
std::pair< InstructionCost, InstructionCost > getDivRemSpeculationCost(Instruction *I, ElementCount VF)
Return the costs for our two available strategies for lowering a div/rem operation which requires spe...
InstructionCost getVectorCallCost(CallInst *CI, ElementCount VF) const
Estimate cost of a call instruction CI if it were vectorized with factor VF.
bool isScalarWithPredication(Instruction *I, ElementCount VF)
Returns true if I is an instruction which requires predication and for which our chosen predication s...
std::function< BlockFrequencyInfo &()> GetBFI
A function to lazily fetch BlockFrequencyInfo.
InstructionCost expectedCost(ElementCount VF)
Returns the expected execution cost.
void setCostBasedWideningDecision(ElementCount VF)
Memory access instruction may be vectorized in more than one way.
bool isDivRemScalarWithPredication(InstructionCost ScalarCost, InstructionCost MaskedCost) const
Given costs for both strategies, return true if the scalar predication lowering should be used for di...
InstWidening getWideningDecision(Instruction *I, ElementCount VF) const
Return the cost model decision for the given instruction I and vector width VF.
InstructionCost getWideningCost(Instruction *I, ElementCount VF)
Return the vectorization cost for the given instruction I and vector width VF.
TailFoldingStyle getTailFoldingStyle() const
Returns the TailFoldingStyle that is best for the current loop.
void collectInstsToScalarize(ElementCount VF)
Collects the instructions to scalarize for each predicated instruction in the loop.
LoopVectorizationLegality checks if it is legal to vectorize a loop, and to what vectorization factor...
MapVector< PHINode *, InductionDescriptor > InductionList
InductionList saves induction variables and maps them to the induction descriptor.
RecurrenceSet & getFixedOrderRecurrences()
Return the fixed-order recurrences found in the loop.
LLVM_ABI bool canVectorize(bool UseVPlanNativePath)
Returns true if it is legal to vectorize this loop.
bool hasUncountableExitWithSideEffects() const
Returns true if this is an early exit loop with state-changing or potentially-faulting operations and...
LLVM_ABI bool canVectorizeFPMath(bool EnableStrictReductions)
Returns true if it is legal to vectorize the FP math operations in this loop.
LLVM_ABI bool isFixedOrderRecurrence(const PHINode *Phi) const
Returns True if Phi is a fixed-order recurrence in this loop.
const SmallVector< BasicBlock *, 4 > & getCountableExitingBlocks() const
Returns all exiting blocks with a countable exit, i.e.
const HistogramInfo * getHistogramInfo(Instruction *I) const
Returns a HistogramInfo* for the given instruction if it was determined to be part of a load -> updat...
const ReductionList & getReductionVars() const
Returns the reduction variables found in the loop.
bool hasUncountableEarlyExit() const
Returns true if the loop has uncountable early exits, i.e.
LLVM_ABI bool isUniformMemOp(Instruction &I, std::optional< ElementCount > VF) const
A uniform memory op is a load or store which accesses the same memory location on all VF lanes,...
bool hasHistograms() const
Returns a list of all known histogram operations in the loop.
const LoopAccessInfo * getLAI() const
LLVM_ABI bool isUniform(Value *V, std::optional< ElementCount > VF) const
Returns true if value V is uniform across VF lanes, when VF is provided, and otherwise if V is invari...
Planner drives the vectorization process after having passed Legality checks.
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.
void addMinimumIterationCheck(VPlan &Plan, ElementCount VF, unsigned UF, ElementCount MinProfitableTripCount, bool TailFoldedEpilogue) const
Create a check to Plan to see if the vector loop should be executed based on its trip count.
void clearCostModel()
Destroy the cost model.
VPlan & getPlanFor(ElementCount VF) const
Return the VPlan for VF.
Definition VPlan.cpp:1655
void updateLoopMetadataAndProfileInfo(Loop *VectorLoop, VPBasicBlock *HeaderVPBB, const VPlan &Plan, bool VectorizingEpilogue, MDNode *OrigLoopID, std::optional< unsigned > OrigAverageTripCount, unsigned OrigLoopInvocationWeight, unsigned EstimatedVFxUF, bool DisableRuntimeUnroll, bool UnrollVectorizedLoop)
Update loop metadata and profile info for both the scalar remainder loop and VectorLoop,...
Definition VPlan.cpp:1706
bool hasAPlan() const
Returns true if there is at least one VPlan.
LoopVectorizationCostModel & getCostModel()
Return the cost model. Must not be called after clearCostModel().
LoopVectorizationPlanner(Loop *L, LoopInfo *LI, DominatorTree *DT, const TargetLibraryInfo *TLI, const TargetTransformInfo &TTI, LoopVectorizationLegality *Legal, std::unique_ptr< LoopVectorizationCostModel > CM, VFSelectionContext &Config, PredicatedScalarEvolution &PSE, OptimizationRemarkEmitter *ORE, std::function< const BranchProbabilityInfo &()> GetBPI)
unsigned selectInterleaveCount(VPlan &Plan, ElementCount VF, InstructionCost LoopCost)
void attachRuntimeChecks(VPlan &Plan, GeneratedRTChecks &RTChecks, ElementCount VF, unsigned UF, bool HasBranchWeights) const
Attach the runtime checks of RTChecks to Plan.
bool hasVectorPlan() const
Return true if there is at least one VPlan for a vector VF.
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:1641
DenseMap< const SCEV *, Value * > executePlan(ElementCount VF, unsigned UF, VPlan &BestPlan, bool HasRuntimeChecks, EpilogueVectorizationKind EpilogueVecKind=EpilogueVectorizationKind::None, MutableArrayRef< VPBasicBlock * > TrackedBlocks={})
void printPlans(raw_ostream &O)
Definition VPlan.cpp:1810
std::unique_ptr< VPlan > selectBestEpiloguePlan(VPlan &MainPlan, ElementCount MainLoopVF, unsigned IC, bool ScalarEpilogueAllowed)
void plan(ElementCount UserVF, unsigned UserIC)
Build VPlans for the specified UserVF and UserIC if they are non-zero or all applicable candidate VFs...
bool hasPlanWithVF(ElementCount VF) const
Look through the existing plans and return true if we have one with vectorization factor VF.
std::pair< VectorizationFactor, VPlan * > computeBestVF()
Compute and return the most profitable vectorization factor and the corresponding best VPlan.
This holds vectorization requirements that must be verified late in the process.
Utility class for getting and setting loop vectorizer hints in the form of loop metadata.
LLVM_ABI void emitRemarkWithHints() const
Dumps all the hint information.
LLVM_ABI bool allowVectorization(Loop *L, bool VectorizeOnlyWhenForced) const
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
Metadata node.
Definition Metadata.h:1087
bool empty() const
Definition MapVector.h:80
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition MapVector.h:127
Function * getFunction(StringRef Name) const
Look up the specified function in the module symbol table.
Definition Module.cpp:254
Represent a mutable reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:294
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.
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:152
PreservedAnalyses & preserve()
Mark an analysis as preserved.
Definition Analysis.h:133
An analysis pass based on the new PM to deliver ProfileSummaryInfo.
The RecurrenceDescriptor is used to identify recurrences variables in a loop.
Type * getRecurrenceType() const
Returns the type of the recurrence.
static bool isFindLastRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is of the form select(cmp(),x,y) where one of (x,...
static bool isAnyOfRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is of the form select(cmp(),x,y) where one of (x,...
static LLVM_ABI bool isSubRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is for a sub operation.
bool isSigned() const
Returns true if all source operands of the recurrence are SExtInsts.
static bool isFindIVRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is of the form select(cmp(),x,y) where one of (x,...
static bool isMinMaxRecurrenceKind(RecurKind Kind)
Returns true if the recurrence kind is any min/max kind.
Holds information about the memory runtime legality checks to verify that a group of pointers do not ...
bool Need
This flag indicates if we need to add the runtime check.
std::optional< ArrayRef< PointerDiffInfo > > getDiffChecks() const
const SmallVectorImpl< RuntimePointerCheck > & getChecks() const
Returns the checks that generateChecks created.
This class uses information about analyze scalars to rewrite expressions in canonical form.
ScalarEvolution * getSE()
bool isInsertedInstruction(Instruction *I) const
Return true if the specified instruction was inserted by the code rewriter.
LLVM_ABI Value * expandCodeForPredicate(const SCEVPredicate *Pred, Instruction *Loc)
Generates a code sequence that evaluates this predicate.
LLVM_ABI void eraseDeadInstructions(Value *Root)
Remove inserted instructions that are dead, e.g.
virtual bool isAlwaysTrue() const =0
Returns true if the predicate is always true.
This class represents an analyzed expression in the program.
LLVM_ABI bool isZero() const
Return true if the expression is a constant zero.
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 * getElementCount(Type *Ty, ElementCount EC, SCEVFlags Flags=SCEV::FlagNone)
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 SCEVUse getAddExpr(SmallVectorImpl< SCEVUse > &Ops, SCEVFlagsPair Flags={}, unsigned Depth=0)
Get a canonical add expression, or something simpler if possible.
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 SCEVUse getMulExpr(SmallVectorImpl< SCEVUse > &Ops, SCEVFlagsPair Flags={}, 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 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:182
size_type count(const_arg_type key) const
Count the number of elements of a given key in the SetVector.
Definition SetVector.h:268
bool contains(const_arg_type key) const
Check if the SetVector contains the given key.
Definition SetVector.h:258
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:157
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:346
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.
A wrapper around a string literal that serves as a proxy for constructing global tables of StringRefs...
Definition StringRef.h:880
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
Analysis pass providing the TargetTransformInfo.
Analysis pass providing the TargetLibraryInfo.
Provides information about what library functions are available for the current target.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
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.
@ ActiveLaneMask
The operation is masked with a contiguous active lane mask.
llvm::VectorInstrContext VectorInstrContext
@ 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
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:283
static LLVM_ABI Type * getVoidTy(LLVMContext &C)
Definition Type.cpp:267
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.h:354
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
static LLVM_ABI IntegerType * getInt1Ty(LLVMContext &C)
Definition Type.cpp:291
bool isVoidTy() const
Return true if this is 'void'.
Definition Type.h:141
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
iterator_range< op_iterator > op_range
Definition User.h:256
Value * getOperand(unsigned i) const
Definition User.h:207
static SmallVector< VFInfo, 8 > getMappings(const CallInst &CI)
Retrieve all the VFInfo instances associated to the CallInst CI.
Definition VectorUtils.h:76
Holds state needed to make cost decisions before computing costs per-VF, including the maximum VFs.
const TTI::TargetCostKind CostKind
The kind of cost that we are calculating.
const LoopVectorizeHints & getHints() const
bool isEpilogueVectorizationProfitable(ElementCount VF, unsigned IC) const
Returns true if epilogue vectorization is considered profitable for a main loop with vectorization fa...
std::optional< unsigned > getVScaleForTuning() const
VPBasicBlock serves as the leaf of the Hierarchical Control-Flow Graph.
Definition VPlan.h:4546
RecipeListTy::iterator iterator
Instruction iterators...
Definition VPlan.h:4577
iterator end()
Definition VPlan.h:4587
iterator begin()
Recipe iterator methods.
Definition VPlan.h:4585
iterator_range< iterator > phis()
Returns an iterator range over the PHI-like recipes in the block.
Definition VPlan.h:4640
InstructionCost cost(ElementCount VF, VPCostContext &Ctx) override
Return the cost of this VPBasicBlock.
Definition VPlan.cpp:734
iterator getFirstNonPhi()
Return the position of the first non-phi node recipe in the block.
Definition VPlan.cpp:224
const VPRecipeBase & front() const
Definition VPlan.h:4597
VPRecipeBase * getTerminator()
If the block has multiple successors, return the branch recipe terminating the block.
Definition VPlan.cpp:604
bool empty() const
Definition VPlan.h:4596
const VPBasicBlock * getExitingBasicBlock() const
Definition VPlan.cpp:194
void setName(const Twine &newName)
Definition VPlan.h:186
size_t getNumPredecessors() const
Definition VPlan.h:244
const VPBlocksTy & getPredecessors() const
Definition VPlan.h:228
VPlan * getPlan()
Definition VPlan.h:197
VPBlockBase * getSinglePredecessor() const
Definition VPlan.h:239
const VPBasicBlock * getEntryBasicBlock() const
Definition VPlan.cpp:179
VPBlockBase * getSingleSuccessor() const
Definition VPlan.h:233
static auto blocksAs(T &&Range)
Return an iterator range over Range with each block cast to BlockTy.
Definition VPlanUtils.h:465
static void reassociateBlocks(VPBlockBase *Old, VPBlockBase *New)
Reassociate all the blocks connected to Old so that they now point to New.
Definition VPlanUtils.h:428
static auto blocksOnly(T &&Range)
Return an iterator range over Range which only includes BlockTy blocks.
Definition VPlanUtils.h:458
static std::pair< VPBasicBlock *, VPBasicBlock * > getPlainCFGHeaderAndLatch(const VPlan &Plan)
Returns the header and latch of the outermost loop of Plan in plain CFG form (before regions are form...
A recipe for generating conditional branches on the bits of a mask.
Definition VPlan.h:3601
static VPBuilderBase getToInsertAfter(VPRecipeBase *R)
VPPhi * createScalarPhi(ArrayRef< VPValue * > IncomingValues, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="", std::optional< VPIRFlags > Flags=std::nullopt, Type *ResultTy=nullptr)
Create a phi with IncomingValues, using the default flags for the result type, unless Flags is set.
T * insert(T *R)
Insert R at the current insertion point. Returns R unchanged.
VPInstruction * createAdd(VPValue *LHS, VPValue *RHS, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="", VPRecipeWithIRFlags::WrapFlagsTy WrapFlags={false, false})
VPInstruction * createSelect(VPValue *Cond, VPValue *TrueVal, VPValue *FalseVal, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="", std::optional< VPIRFlags > Flags=std::nullopt)
Create a select of TrueVal and FalseVal based on Cond, using the default flags for the result type,...
static VPSingleDefRecipe * createSingleScalarOp(unsigned Opcode, ArrayRef< VPValue * > Operands, VPValue *Mask, const VPIRFlags &Flags, const VPIRMetadata &Metadata, DebugLoc DL, Type *ResultTy, Instruction *UV)
void setInsertPoint(const VPInsertPoint &IP)
Set the current insert point.
VPInstruction * createNaryOp(unsigned Opcode, ArrayRef< VPValue * > Operands, Instruction *Inst=nullptr, const VPIRFlags &Flags={}, const VPIRMetadata &MD={}, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="", Type *ResultTy=nullptr, const VPIRAttributes &Attrs={})
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:572
VPValue * getVPSingleValue()
Returns the only VPValue defined by the VPDef.
Definition VPlanValue.h:545
Template specialization of the standard LLVM dominator tree utility for VPBlockBases.
Recipe to expand a SCEV expression.
Definition VPlan.h:4140
A pure virtual base class for all recipes modeling header phis, including phis for first order recurr...
Definition VPlan.h:2486
virtual VPValue * getBackedgeValue()
Returns the incoming value from the loop backedge.
Definition VPlan.h:2529
void setBackedgeValue(VPValue *V)
Update the incoming value from the loop backedge.
Definition VPlan.h:2532
VPValue * getStartValue()
Returns the start value of the phi, if one is set.
Definition VPlan.h:2518
A recipe representing a sequence of load -> update -> store as part of a histogram operation.
Definition VPlan.h:2201
A special type of VPBasicBlock that wraps an existing IR basic block.
Definition VPlan.h:4705
LLVM_ABI_FOR_TEST FastMathFlags getFastMathFlagsOrNone() const
This is a concrete Recipe that models a single VPlan-level instruction.
Definition VPlan.h:1322
iterator_range< operand_iterator > operandsWithoutMask()
Returns an iterator range over the operands excluding the mask operand if present.
Definition VPlan.h:1582
VPInstruction * clone() override
Clone the current recipe.
Definition VPlan.h:1517
@ ResumeForEpilogue
Explicit user for values in the main VPlan, used by the epilogue vector loop.
Definition VPlan.h:1431
@ ReductionStartVector
Start vector for reductions with 3 operands: the original start value, the identity value for the red...
Definition VPlan.h:1423
@ ComputeReductionResult
Reduce the operands to the final reduction result using the operation specified via the operation's V...
Definition VPlan.h:1381
unsigned getOpcode() const
Definition VPlan.h:1531
VPValue * getMask() const
Returns the mask for the VPInstruction.
Definition VPlan.h:1578
VPInterleaveRecipe is a recipe for transforming an interleave group of load or stores into one wide l...
Definition VPlan.h:3234
VPRecipeBase is a base class modeling a sequence of one or more output IR instructions.
Definition VPlan.h:402
RecipeListTy::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
DebugLoc getDebugLoc() const
Returns the debug location of the recipe.
Definition VPlan.h:547
void insertBefore(VPRecipeBase *InsertPos)
Insert an unlinked recipe into a basic block immediately before the specified recipe.
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...
std::optional< CompressedPtrInfo > getCompressedPtrInfo(VPInstruction *VPI)
Returns the CompressedPtrInfo for VPI if it is a compressed load or store (as determined by LoopVecto...
bool prefersVectorizedAddressing() const
Returns true if the target prefers vectorized addressing.
VPRecipeBase * tryToWidenMemory(VPInstruction *VPI, VFRange &Range)
Check if the load or store instruction VPI should widened for Range.Start and potentially masked.
bool replaceWithFinalIfReductionStore(VPInstruction *VPI, VPBuilder &FinalRedStoresBuilder)
If VPI is a store of a reduction into an invariant address, delete it.
VPSingleDefRecipe * handleReplication(VPInstruction *VPI, VFRange &Range)
Build a replicating or single-scalar recipe for VPI.
VPWidenMemIntrinsicRecipe * widenCompressedLoadOrStore(VPInstruction *VPI)
Build a llvm.masked.expandload or llvm.masked.compressstore intrinsic for VPI.
bool isPredicatedInst(Instruction *I) const
Returns true if I needs to be predicated (i.e.
Type * getScalarType() const
Returns the scalar type of this VPRecipeValue.
Definition VPlanValue.h:349
A recipe for handling reduction phis.
Definition VPlan.h:2889
bool isOrdered() const
Returns true, if the phi is part of an ordered reduction.
Definition VPlan.h:2961
bool hasUsesOutsideReductionChain() const
Returns true, if the phi is part of a multi-use reduction.
Definition VPlan.h:2970
bool isInLoop() const
Returns true if the phi is part of an in-loop reduction.
Definition VPlan.h:2964
VPReductionPHIRecipe * cloneWithOperands(VPValue *Start, VPValue *BackedgeValue)
Definition VPlan.h:2925
RecurKind getRecurrenceKind() const
Returns the recurrence kind of the reduction.
Definition VPlan.h:2958
A recipe to represent inloop, ordered or partial reduction operations.
Definition VPlan.h:3327
VPRegionBlock represents a collection of VPBasicBlocks and VPRegionBlocks which form a Single-Entry-S...
Definition VPlan.h:4777
const VPBlockBase * getEntry() const
Definition VPlan.h:4821
void clearCanonicalIVNUW(VPInstruction *Increment)
Unsets NUW for the canonical IV increment Increment, for loop regions.
Definition VPlan.h:4944
VPRegionValue * getCanonicalIV()
Return the canonical induction variable of the region, null for replicating regions.
Definition VPlan.h:4897
VPReplicateRecipe replicates a given instruction producing multiple scalar copies of the original sca...
Definition VPlan.h:3494
VPSingleDefRecipe is a base class for recipes that model a sequence of one or more output IR that def...
Definition VPlan.h:605
Instruction * getUnderlyingInstr()
Returns the underlying instruction.
Definition VPlan.h:668
This class augments VPValue with operands which provide the inverse def-use edges from VPValue's user...
Definition VPlanValue.h:396
operand_range operands()
Definition VPlanValue.h:472
void setOperand(unsigned I, VPValue *New)
Definition VPlanValue.h:445
VPValue * getOperand(unsigned N) const
Definition VPlanValue.h:437
This is the base class of the VPlan Def/Use graph, used for modeling the data flow into,...
Definition VPlanValue.h:50
Type * getScalarType() const
Returns the scalar type of this VPValue, dispatching based on the concrete subclass.
Definition VPlan.cpp:138
Value * getLiveInIRValue() const
Return the underlying IR value for a VPIRValue.
Definition VPlan.cpp:132
VPRecipeBase * getDefiningRecipe()
Returns the recipe defining this VPValue or nullptr if it is not defined by a recipe,...
Definition VPlan.cpp:119
Value * getUnderlyingValue() const
Return the underlying Value attached to this VPValue.
Definition VPlanValue.h:75
void replaceUsesWithIf(VPValue *New, llvm::function_ref< bool(VPUser *U)> ShouldReplace)
Go through the uses list for this VPValue and make each use point to New if the callback ShouldReplac...
Definition VPlan.cpp:1476
void replaceAllUsesWith(VPValue *New)
Definition VPlan.cpp:1470
VPWidenCastRecipe is a recipe to create vector cast instructions.
Definition VPlan.h:1902
A recipe for handling GEP instructions.
Definition VPlan.h:2260
A recipe for widening vector memory intrinsics.
Definition VPlan.h:2079
VPWidenRecipe is a recipe for producing a widened instruction using the opcode and operands of the re...
Definition VPlan.h:1835
VPlan models a candidate for vectorization, encoding various decisions take to produce efficient outp...
Definition VPlan.h:4964
bool hasVF(ElementCount VF) const
Definition VPlan.h:5187
ElementCount getSingleVF() const
Returns the single VF of the plan, asserting that the plan has exactly one VF.
Definition VPlan.h:5200
VPBasicBlock * getEntry()
Definition VPlan.h:5056
VPValue * getTripCount() const
The trip count of the original loop.
Definition VPlan.h:5128
VPSymbolicValue & getVFxUF()
Returns VF * UF of the vector loop region.
Definition VPlan.h:5159
bool hasUF(unsigned UF) const
Definition VPlan.h:5212
ArrayRef< VPIRBasicBlock * > getExitBlocks() const
Return an ArrayRef containing VPIRBasicBlocks wrapping the exit blocks of the original scalar loop.
Definition VPlan.h:5122
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:5237
VPIRValue * getZero(Type *Ty)
Return a VPIRValue wrapping the null value of type Ty.
Definition VPlan.h:5263
LLVM_ABI_FOR_TEST VPRegionBlock * getVectorLoopRegion()
Returns the VPRegionBlock of the vector loop.
Definition VPlan.cpp:1060
bool hasEarlyExit() const
Returns true if the VPlan is based on a loop with an early exit.
Definition VPlan.h:5371
InstructionCost cost(ElementCount VF, VPCostContext &Ctx)
Return the cost of this plan.
Definition VPlan.cpp:1042
LLVM_ABI_FOR_TEST bool isOuterLoop() const
Returns true if this VPlan is for an outer loop, i.e., its vector loop region contains a nested loop ...
Definition VPlan.cpp:1085
VPBasicBlock * getMiddleBlock()
Returns the 'middle' block of the plan, that is the block that selects whether to execute the scalar ...
Definition VPlan.h:5098
VPBasicBlock * getVectorPreheader() const
Returns the preheader of the vector loop region, if one exists, or null otherwise.
Definition VPlan.h:5061
bool requiresScalarEpilogue() const
Returns true if the plan requires a scalar epilogue after the vector loop.
Definition VPlan.h:5084
VPSymbolicValue & getUF()
Returns the UF of the vector loop region.
Definition VPlan.h:5156
bool hasScalarVFOnly() const
Definition VPlan.h:5205
VPBasicBlock * getScalarPreheader() const
Return the VPBasicBlock for the preheader of the scalar loop.
Definition VPlan.h:5112
void execute(VPTransformState *State)
Generate the IR code for this VPlan.
Definition VPlan.cpp:937
bool hasTailFolded() const
Returns true if the vector loop region is tail-folded.
Definition VPlan.h:5077
VPIRBasicBlock * getScalarHeader() const
Return the VPIRBasicBlock wrapping the header of the scalar loop.
Definition VPlan.h:5118
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:1220
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:389
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:548
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:314
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:210
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
Definition DenseSet.h:183
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:201
static constexpr bool isKnownLE(const FixedOrScalableQuantity &LHS, const FixedOrScalableQuantity &RHS)
Definition TypeSize.h:231
constexpr bool isNonZero() const
Definition TypeSize.h:156
static constexpr bool isKnownLT(const FixedOrScalableQuantity &LHS, const FixedOrScalableQuantity &RHS)
Definition TypeSize.h:217
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:169
constexpr bool isFixed() const
Returns true if the quantity is not scaled by vscale.
Definition TypeSize.h:172
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:166
constexpr bool isZero() const
Definition TypeSize.h:154
static constexpr bool isKnownGT(const FixedOrScalableQuantity &LHS, const FixedOrScalableQuantity &RHS)
Definition TypeSize.h:224
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:253
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
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
A raw_ostream that writes to an std::string.
CallInst * Call
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.
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
void reportVectorizationFailure(const StringRef DebugMsg, const StringRef OREMsg, const StringRef ORETag, OptimizationRemarkEmitter *ORE, const Loop *TheLoop, Instruction *I=nullptr)
Reports a vectorization failure: print DebugMsg for debugging purposes along with the corresponding o...
void reportVectorizationInfo(const StringRef Msg, const StringRef ORETag, OptimizationRemarkEmitter *ORE, const Loop *TheLoop, Instruction *I=nullptr, DebugLoc DL={})
Reports an informative message: print Msg for debugging purposes as well as an optimization remark.
void reportVectorization(OptimizationRemarkEmitter *ORE, Loop *TheLoop, ElementCount VFWidth, unsigned IC)
Report successful vectorization of the loop.
SpecificConstantMatch m_ZeroInt()
Convenience matchers for specific integer values.
match_unless< Pattern > m_Unless(const Pattern &P)
Match if the inner matcher does NOT match.
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)
OneOps_match< OpTy, Instruction::Freeze > m_Freeze(const OpTy &Op)
Matches FreezeInst.
bool match(Val *V, const Pattern &P)
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
cst_pred_ty< is_one > m_One()
Match an integer 1 or a vector with all elements equal to 1.
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
auto m_Value()
Match an arbitrary value and ignore it.
auto m_LogicalOr()
Matches L || R where L and R are arbitrary values.
auto m_LogicalAnd()
Matches L && R where L and R are arbitrary values.
bind_cst_ty m_scev_APInt(const APInt *&C)
Match an SCEV constant and bind it to an APInt.
match_bind< const SCEVMulExpr > m_scev_Mul(const SCEVMulExpr *&V)
bool match(const SCEV *S, const Pattern &P)
SCEVBinaryExpr_match< SCEVMulExpr, Op0_t, Op1_t, SCEV::FlagNone, true > m_scev_c_Mul(const Op0_t &Op0, const Op1_t &Op1)
RecipeTy * findSingleUser(VPValue *V, const MatchT &P)
Return the sole user of V matching pattern P, casting it to RecipeTy, or nullptr.
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::FirstActiveLane, Op0_t > m_FirstActiveLane(const Op0_t &Op0)
VPInstruction_match< VPInstruction::ExtractLane, Op0_t, Op1_t > m_ExtractLane(const Op0_t &Op0, const Op1_t &Op1)
initializer< Ty > init(const Ty &Val)
Add a small namespace to avoid name clashes with the classes used in the streaming interface.
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
BranchProbability getExecutionProbability(BlockFrequency Freq)
Returns Freq as a BranchProbability, relative to the full mass.
bool isSingleScalar(const VPValue *VPV)
Returns true if VPV is a single scalar, either because it produces the same value for all lanes or on...
VPBasicBlock * getFirstLoopHeader(VPlan &Plan, VPDominatorTree &VPDT)
Returns the header block of the first, top-level loop, or null if none exist.
bool isAddressSCEVForCost(const SCEV *Addr, ScalarEvolution &SE, const Loop *L)
Returns true if Addr is an address SCEV that can be passed to TTI::getAddressComputationCost,...
VPInstruction * findCanonicalIVIncrement(VPlan &Plan)
Find the canonical IV increment of Plan's vector loop region.
bool onlyFirstLaneUsed(const VPValue *Def)
Returns true if only the first lane of Def is used by all users.
VPValue * findIncomingAliasMask(const VPlan &Plan)
Finds the incoming alias-mask within the vector preheader.
Type * getLoadStoreValueType(VPSingleDefRecipe *R)
Get the value type of a VPInstruction or VPReplicateRecipe load or store.
Definition VPlanUtils.h:252
bool doesGeneratePerAllLanes(const VPRecipeBase *R)
Returns true if R produces scalar values for all VF lanes.
VPRecipeBase * findRecipe(VPValue *Start, PredT Pred)
Search Start's users for a recipe satisfying Pred, looking through recipes with definitions.
Definition VPlanUtils.h:154
LLVM_ABI_FOR_TEST 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.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
SmallVector< VPBasicBlock * > vp_rpo_plain_cfg_loop_body(VPBasicBlock *Header)
Returns the VPBasicBlocks forming the loop body of a plain (pre-region) VPlan in reverse post-order s...
Definition VPlanCFG.h:262
@ Offset
Definition DWP.cpp:577
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:2196
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.
LLVM_ABI bool RemoveRedundantDbgInstrs(BasicBlock *BB)
Try to remove redundant dbg.value instructions from given basic block.
LLVM_ABI std::optional< unsigned > getLoopEstimatedTripCount(Loop *L, unsigned *EstimatedLoopInvocationWeight=nullptr)
Return either:
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
unsigned getLoadStoreAddressSpace(const Value *I)
A helper function that returns the address space of the pointer operand of load or store instruction.
bool isEqual(const GCNRPTracker::LiveRegSet &S1, const GCNRPTracker::LiveRegSet &S2)
LLVM_ABI Intrinsic::ID getVectorIntrinsicIDForCall(const CallInst *CI, const TargetLibraryInfo *TLI)
Returns intrinsic ID for call.
detail::zippy< detail::zip_first, T, U, Args... > zip_equal(T &&t, U &&u, Args &&...args)
zip iterator that assumes that all iteratees have the same length.
Definition STLExtras.h:856
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.
@ Load
The value being inserted comes from a load (InsertElement only).
@ Store
The extracted value is stored (ExtractElement only).
VPBuilderBase<> VPBuilder
Definition VPlan.h:66
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:469
auto dyn_cast_if_present(const Y &Val)
dyn_cast_if_present<X> - Functionally identical to dyn_cast, except that a null (or none in the case ...
Definition Casting.h:732
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:2229
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:649
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
Definition MathExtras.h:285
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:250
LLVM_ABI bool VerifySCEV
LLVM_ABI bool isSafeToSpeculativelyExecute(const Instruction *I, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr, bool UseVariableInfo=true, bool IgnoreUBImplyingAttrs=true)
Return true if the instruction does not have any effects besides calculating the result and does not ...
bool isa_and_nonnull(const Y &Val)
Definition Casting.h:676
iterator_range< df_iterator< VPBlockDeepTraversalWrapper< VPBlockBase * > > > vp_depth_first_deep(VPBlockBase *G)
Returns an iterator range to traverse the graph starting at G in depth-first order while traversing t...
Definition VPlanCFG.h:286
auto map_range(ContainerTy &&C, FuncTy F)
Return a range that applies F to the elements of C.
Definition STLExtras.h:366
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
auto make_isa_range(RangeT &&Range)
Return a range over Range containing only elements for which isa<T> holds, casting each of them to T.
Definition STLExtras.h:567
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
LLVM_ABI bool simplifyLoop(Loop *L, DominatorTree *DT, LoopInfo *LI, ScalarEvolution *SE, AssumptionCache *AC, MemorySSAUpdater *MSSAU, bool PreserveLCSSA, const TargetTransformInfo *TTI=nullptr)
Simplify each loop in a loop nest recursively.
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:1762
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
std::optional< uint64_t > getMaxRuntimeElementCount(ElementCount EC, const Function &F)
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
bool hasIrregularType(Type *Ty, const DataLayout &DL)
A helper function that returns true if the given type is irregular.
UncountableExitStyle
Different methods of handling early exits.
Definition VPlan.h:81
@ ReadOnly
No side effects to worry about, so we can process any uncountable exits in the loop and branch either...
Definition VPlan.h:85
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1769
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:149
SmallVector< VPRegisterUsage, 8 > calculateRegisterUsageForPlan(VPlan &Plan, ArrayRef< ElementCount > VFs, const TargetTransformInfo &TTI)
Estimate the register usage for Plan and vectorization factors in VFs by calculating the highest numb...
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:415
SmallVector< ValueTypeFromRangeType< R >, Size > to_vector(R &&Range)
Given a range of type R, iterate the entire range and return a SmallVector with elements of the vecto...
Type * toVectorizedTy(Type *Ty, ElementCount EC)
A helper for converting to vectorized types.
T * find_singleton(R &&Range, Predicate P, bool AllowRepeats=false)
Return the single value in Range that satisfies P(<member of Range> *, AllowRepeats)->T * returning n...
Definition STLExtras.h:1853
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
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
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
constexpr T divideCeil(U Numerator, V Denominator)
Returns the integer ceil(Numerator / Denominator).
Definition MathExtras.h:389
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.
void replace(R &&Range, const T &OldValue, const T &NewValue)
Provide wrappers to std::replace which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1926
RecurKind
These are the kinds of recurrences that we support.
@ 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.
constexpr T AbsoluteDifference(U X, V Y)
Subtract two unsigned integers, X and Y, of type T and return the absolute value of the result.
Definition MathExtras.h:600
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 >
bool proveOuterLoopMemorySafety(VPlan &Plan, PredicatedScalarEvolution &PSE, AAResults &AA, const VPDominatorTree &VPDT, const Loop *OuterLoop)
Returns true if the memory accesses in outer loop plain CFG Plan can be vectorized.
auto sum_of(R &&Range, E Init=E{0})
Returns the sum of all values in Range with Init initial value.
Definition STLExtras.h:1733
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1933
const VectorizeOptions & getVectorizeOptions(const LLVMContext &C)
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
auto predecessors(const MachineBasicBlock *BB)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
Type * getLoadStoreType(const Value *I)
A helper function that returns the type of a load or store instruction.
constexpr bool valueOr(BoolOrDefault X, bool Default)
ArrayRef< Type * > getContainedTypes(Type *const &Ty)
Returns the types contained in Ty.
bool pred_empty(const BasicBlock *BB)
Definition CFG.h:107
@ None
Don't use tail folding.
@ DataWithEVL
Use predicated EVL instructions for tail-folding.
@ DataAndControlFlow
Use predicate to control both data and control flow.
@ DataWithoutLaneMask
Same as Data, but avoids using the get.active.lane.mask intrinsic to calculate the mask and instead i...
@ Data
Use predicate only to mask operations on data in the loop.
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
LLVM_ABI bool hasBranchWeightMD(const Instruction &I)
Checks if an instructions has Branch Weight Metadata.
hash_code hash_combine(const Ts &...args)
Combine values into a single hash_code.
Definition Hashing.h:307
LLVM_ABI std::optional< int64_t > getStrideFromAddRec(const SCEVAddRecExpr *AR, const Loop *Lp, Type *AccessTy, Value *Ptr, PredicatedScalarEvolution &PSE)
If AR is an affine AddRec for Lp with a constant step, return the step in units of AccessTy's allocat...
@ Increment
Incrementally increasing token ID.
Definition AllocToken.h:26
@ Enabled
Convert any .debug_str_offsets tables to DWARF64 if needed.
Definition DWP.h:31
@ Disabled
Don't do any conversion of .debug_str_offsets tables.
Definition DWP.h:30
T bit_floor(T Value)
Returns the largest integral power of two no greater than Value if Value is nonzero.
Definition bit.h:347
Type * toVectorTy(Type *Scalar, ElementCount EC)
A helper function for converting Scalar types to vector types.
constexpr detail::CastFunc< To > CastTo
Definition Casting.h:884
std::unique_ptr< VPlan > VPlanPtr
Definition VPlan.h:76
LLVM_ABI Value * addDiffRuntimeChecks(Instruction *Loc, ArrayRef< PointerDiffInfo > Checks, SCEVExpander &Expander, ElementCount VF, unsigned IC)
constexpr detail::IsaCheckPredicate< Types... > IsaPred
Function object wrapper for the llvm::isa type check.
Definition Casting.h:866
LLVM_ABI_FOR_TEST bool verifyVPlanIsValid(const VPlan &Plan)
Verify invariants for general VPlans.
hash_code hash_combine_range(InputIteratorT first, InputIteratorT last)
Compute a hash_code for a sequence of values.
Definition Hashing.h:287
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:879
ResumeForEpilogue markers in the main plan, used by the epilogue plan.
SmallVector< VPInstruction * > ResumeValues
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).
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...
HistogramUpdateKind UpdateKind
The update operation applied to the histogram buckets.
TargetLibraryInfo * TLI
LLVM_ABI LoopVectorizeResult runImpl(Function &F)
LLVM_ABI bool processLoop(Loop *L)
ProfileSummaryInfo * PSI
LoopAccessInfoManager * LAIs
std::function< const BranchProbabilityInfo &()> GetBPI
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 marker analysis to determine if extra passes should be run after loop vectorization.
static LLVM_ABI AnalysisKey Key
Parameters that control the generic loop unrolling transformation.
bool UnrollVectorizedLoop
Disable runtime unrolling by default for vectorized loops.
Holds the VFShape for a specific scalar to vector function mapping.
A range of powers-of-2 vectorization factors with fixed start and adjustable end.
ElementCount End
Struct to hold various analysis needed for cost computations.
LLVMContext & LLVMCtx
const VFSelectionContext & Config
LoopVectorizationCostModel & CM
VPCostContext(const TargetLibraryInfo &TLI, const VPlan &Plan, LoopVectorizationCostModel &CM, VFSelectionContext &Config, bool ReusePrintingSlotTracker=false)
bool skipCostComputation(Instruction *UI, bool IsVector) const
Return true if the cost for UI shouldn't be computed, e.g.
InstructionCost getLegacyCost(Instruction *UI, ElementCount VF) const
Return the cost for UI with VF using the legacy cost model as fallback until computing the cost of al...
bool isMaskRequired(Instruction *I) const
Forwards to LoopVectorizationCostModel::isMaskRequired.
void invalidateWideningDecision(Instruction *I, ElementCount VF)
Mark the widening decision for I at VF as invalidated since a VPlan transform replaced the original r...
PredicatedScalarEvolution & PSE
bool willBeScalarized(Instruction *I, ElementCount VF) const
Returns true if I is known to be scalarized at VF.
static bool executesAtMostOnce(const VPlan &Plan, ElementCount VF)
Returns true if the vector loop body of Plan is known to execute at most once at VF,...
TargetTransformInfo::TargetCostKind CostKind
const TargetLibraryInfo & TLI
const TargetTransformInfo & TTI
SmallPtrSet< Instruction *, 8 > SkipCostComputation
const VectorizeOptions & Opts
A pure-virtual common base class for recipes defining a single VPValue and using IR flags.
Definition VPlan.h:1089
A struct that represents some properties of the register usage of a loop.
InstructionCost spillCost(const TargetTransformInfo &TTI, TargetTransformInfo::TargetCostKind CostKind, unsigned OverrideMaxNumRegs=0) const
Calculate the estimated cost of any spills due to using more registers than the number available for ...
VPTransformState holds information passed down when "executing" a VPlan, needed for generating the ou...
A recipe for widening load operations with vector-predication intrinsics, using the address to load f...
Definition VPlan.h:3978
A recipe for widening load operations, using the address to load from and an optional mask.
Definition VPlan.h:3923
A recipe for widening store operations with vector-predication intrinsics, using the value to store,...
Definition VPlan.h:4085
A recipe for widening store operations, using the stored value, the address to store to and an option...
Definition VPlan.h:4031
static void simplifyLiveInsWithSCEV(VPlan &Plan, PredicatedScalarEvolution &PSE)
Check Plan's live-ins and replace them with constants, if they can be simplified via SCEV.
static void addMinimumVectorEpilogueIterationCheck(VPlan &Plan, VPValue *MainVectorTripCount, bool RequiresScalarEpilogue, ElementCount EpilogueVF, unsigned MainLoopStep, unsigned EpilogueLoopStep, ScalarEvolution &SE)
Add a check to Plan to see if the epilogue vector loop should be executed.
static bool makeCallWideningDecisions(VPlan &Plan, VFRange &Range, VPRecipeBuilder &RecipeBuilder, VPCostContext &CostCtx)
Convert call VPInstructions in Plan into widened call, vector intrinsic or replicate recipes based on...
static void expandSCEVsToVPInstructions(VPlan &Plan, ScalarEvolution &SE)
Expand VPExpandSCEVRecipes in Plan's entry block to VPInstructions.
static void materializeBroadcasts(VPlan &Plan)
Add explicit broadcasts for live-ins and VPValues defined in Plan's entry block if they are used as v...
static void createInterleaveGroups(VPlan &Plan, const SmallPtrSetImpl< const InterleaveGroup< Instruction > * > &InterleaveGroups, const bool &EpilogueAllowed)
static LLVM_ABI_FOR_TEST bool handleUncountableEarlyExits(VPlan &Plan, OptimizationRemarkEmitter *ORE, Loop *TheLoop, PredicatedScalarEvolution &PSE, DominatorTree &DT, AssumptionCache *AC, UncountableExitStyle Style)
Update Plan to account for uncountable early exits by introducing appropriate branching logic in the ...
static bool simplifyKnownEVL(VPlan &Plan, ElementCount VF, PredicatedScalarEvolution &PSE)
Try to simplify VPInstruction::ExplicitVectorLength recipes when the AVL is known to be <= VF,...
static void introduceMasksAndLinearize(VPlan &Plan)
Predicate and linearize the control-flow in the only loop region of Plan.
static void materializeFactors(VPlan &Plan, VPBasicBlock *VectorPH, ElementCount VF)
Materialize UF, VF and VFxUF to be computed explicitly using VPInstructions.
static void foldTailByMasking(VPlan &Plan)
Adapts the vector loop region for tail folding by introducing a header mask and conditionally executi...
static LLVM_ABI_FOR_TEST bool tryToConvertVPInstructionsToVPRecipes(VPlan &Plan, const TargetLibraryInfo &TLI, PredicatedScalarEvolution &PSE, Loop *OuterLoop)
Replaces the VPInstructions in Plan with corresponding widen recipes.
static bool handleMultiUseReductions(VPlan &Plan, OptimizationRemarkEmitter *ORE, Loop *TheLoop)
Try to legalize reductions with multiple in-loop uses.
static void convertToVariableLengthStep(VPlan &Plan)
Transform loops with variable-length stepping after region dissolution.
static void materializeHeaderMask(VPlan &Plan, bool UseActiveLaneMask, bool UseActiveLaneMaskForControlFlow)
Materialize the abstract header mask of the loop region into concrete recipes: an active-lane-mask if...
static void recordExecutionFrequencies(VPlan &Plan)
Add execution frequencies to each recipe in the loop body of Plan.
static void addBranchWeightToMiddleTerminator(VPlan &Plan, ElementCount VF, std::optional< unsigned > VScaleForTuning)
Add branch weight metadata, if the Plan's middle block is terminated by a BranchOnCond recipe.
static std::unique_ptr< VPlan > narrowInterleaveGroups(VPlan &Plan, const TargetTransformInfo &TTI)
Try to find a single VF among Plan's VFs for which all interleave groups (with known minimum VF eleme...
static bool handleFindLastReductions(VPlan &Plan)
Check if Plan contains any FindLast reductions.
static void createInLoopReductionRecipes(VPlan &Plan, ElementCount MinVF)
Create VPReductionRecipes for in-loop reductions.
static void materializeAliasMaskCheckBlock(VPlan &Plan, ArrayRef< PointerDiffInfo > DiffChecks, ScalarEvolution &SE, bool HasBranchWeights)
Materializes the alias mask within a check block before the loop.
static LLVM_ABI_FOR_TEST bool createHeaderPhiRecipes(VPlan &Plan, PredicatedScalarEvolution &PSE, Loop &OrigLoop, OptimizationRemarkEmitter *ORE, const VPDominatorTree &VPDT, const MapVector< PHINode *, InductionDescriptor > &Inductions, const MapVector< PHINode *, RecurrenceDescriptor > &Reductions, const MapVector< PHINode *, ConditionalInductionDescriptor > &ConditionalInductions, 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 unrollByUF(VPlan &Plan, unsigned UF)
Explicitly unroll Plan by UF.
static DenseMap< const SCEV *, Value * > expandSCEVs(VPlan &Plan, ScalarEvolution &SE)
Expand remaining VPExpandSCEVRecipes in Plan's entry block using SCEVExpander.
static void convertToConcreteRecipes(VPlan &Plan)
Lower abstract recipes to concrete ones, that can be codegen'd.
static LLVM_ABI_FOR_TEST void createLoopRegions(VPlan &Plan, DebugLoc DL)
Replace loops in Plan's flat CFG with VPRegionBlocks, turning Plan's flat CFG into a hierarchical CFG...
static void makeMemOpWideningDecisions(VPlan &Plan, VFRange &Range, VPRecipeBuilder &RecipeBuilder, VPCostContext &CostCtx)
Convert load/store VPInstructions in Plan into widened or replicate recipes.
static VPIRBasicBlock * modelGeneratedMainLoopBlocks(VPlan &EpiPlan, VPlan &MainPlan, VPBasicBlock *MainCheck)
Model the blocks the executed MainPlan generated for the main vector loop in EpiPlan during epilogue ...
static LLVM_ABI_FOR_TEST void addMiddleCheck(VPlan &Plan)
If a check is needed to guard executing the scalar epilogue loop, it will be added to the middle bloc...
static 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 expandMaskBeforeFirst(VPlan &Plan, VPCostContext &Ctx, VFRange &Range)
Expand mask.beforefirst into an active-lane-mask of its first active lane for the VFs in Range where ...
static void attachAliasMaskToHeaderMask(VPlan &Plan)
Attaches the alias-mask to the existing header-mask.
static void optimizeFindIVReductions(VPlan &Plan, PredicatedScalarEvolution &PSE, Loop &L)
Optimize FindLast reductions selecting IVs (or expressions of IVs) by converting them to FindIV reduc...
static void convertToAbstractRecipes(VPlan &Plan, VPCostContext &Ctx, VFRange &Range)
This function converts initial recipes to the abstract recipes and clamps Range based on cost model f...
static void materializeConstantVectorTripCount(VPlan &Plan, ElementCount BestVF, unsigned BestUF, PredicatedScalarEvolution &PSE)
static void makeScalarizationDecisions(VPlan &Plan, VFRange &Range)
Make VPlan-based scalarization decision prior to delegating to the ones made by the legacy CM.
static void replaceWideCanonicalIVWithWideIV(VPlan &Plan, ScalarEvolution &SE, const TargetTransformInfo &TTI, TargetTransformInfo::TargetCostKind CostKind, ElementCount VF, unsigned UF)
Replace a VPWidenCanonicalIVRecipe if it is present in Plan, with a VPWidenIntOrFpInductionRecipe,...
static LLVM_ABI_FOR_TEST std::unique_ptr< VPlan > buildVPlan0(Loop *TheLoop, LoopInfo &LI, Type *InductionTy, PredicatedScalarEvolution &PSE, LoopVersioning *LVer=nullptr, function_ref< const BranchProbabilityInfo &()> GetBPI=nullptr)
Create a base VPlan0, serving as the common starting point for all later candidates.
static void optimizeInductionLiveOutUsers(VPlan &Plan, PredicatedScalarEvolution &PSE, const Loop *L)
If there's a single exit block, optimize its phi recipes that use exiting IV values by feeding them p...
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 adjustFirstOrderRecurrenceMiddleUsers(VPlan &Plan, VFRange &Range)
Adjust first-order recurrence users in the middle block: create penultimate element extracts for LCSS...
static void optimizeEVLMasks(VPlan &Plan)
Optimize recipes which use an EVL-based header mask to VP intrinsics, for example:
static bool handleMaxMinNumReductions(VPlan &Plan)
Check if Plan contains any FMaxNum or FMinNum reductions.
static void foldPredicateMerge(VPlan &Plan, VPCostContext &CostCtx)
Wrap reduction operations and their vp.merge in expression recipes when the merge is expected to be f...
static void removeDeadRecipes(VPlan &Plan)
Remove dead recipes from Plan.
static void attachCheckBlock(VPlan &Plan, Value *Cond, BasicBlock *CheckBlock, bool AddBranchWeights)
static LLVM_ABI_FOR_TEST void handleCountableEarlyExits(VPlan &Plan)
Disconnect countable early exits from the loop.
static void sinkPredicatedStores(VPlan &Plan, PredicatedScalarEvolution &PSE, const Loop *L)
Sink predicated stores to the same address with complementary predicates (P and NOT P) to an uncondit...
static bool finalizeSCEVPredicates(VPlan &Plan, PredicatedScalarEvolution &PSE, bool OptForSize, unsigned SCEVCheckThreshold, OptimizationRemarkEmitter *ORE, Loop *TheLoop)
Finalize SCEV predicates by adding induction predicates from Plan to PSE and checking constraints.
static void replicateByVF(VPlan &Plan, ElementCount VF)
Replace replicating VPReplicateRecipe, VPScalarIVStepsRecipe and VPInstruction in Plan with VF single...
static bool removeBranchOnConst(VPlan &Plan, bool OnlyLatches=false)
Remove BranchOnCond recipes with true or false conditions together with removing dead edges to their ...
static void convertToStridedAccesses(VPlan &Plan, PredicatedScalarEvolution &PSE, Loop &L, VPCostContext &Ctx, VFRange &Range)
Transform widen memory recipes into strided access recipes when legal and profitable.
static void addIterationCountCheckBlock(VPlan &Plan, ElementCount VF, unsigned UF, bool RequiresScalarEpilogue, Loop *OrigLoop, const uint32_t *MinItersBypassWeights, DebugLoc DL, PredicatedScalarEvolution &PSE)
Add a new check block before the vector preheader to Plan to check if the main vector loop should be ...
static void clearReductionWrapFlags(VPlan &Plan)
Clear NSW/NUW flags from reduction instructions if necessary.
static void createPartialReductions(VPlan &Plan, VPCostContext &CostCtx, VFRange &Range)
Detect and create partial reduction recipes for scaled or unordered reductions in Plan.
static bool widenCompressingPatterns(VPlan &Plan, VPRecipeBuilder &RecipeBuilder, ScalarEvolution &SE)
Widens compressing memory loads/stores.
static void cse(VPlan &Plan, const VPDominatorTree &VPDT)
Perform common-subexpression-elimination on Plan.
static void attachMemoryChecks(VPlan &Plan, const RuntimePointerChecking &RtPtrChecking, const Loop *TheLoop, ScalarEvolution &SE, ElementCount VF, unsigned UF, bool AddBranchWeights)
Generate the memory runtime checks of RtPtrChecking for TheLoop as recipes and attach the check block...
static void materializeUnpacks(VPlan &Plan)
Add explicit Unpack recipes to extract scalars from vectors as needed.
static void addMinimumIterationCheck(VPlan &Plan, ElementCount VF, unsigned UF, ElementCount MinProfitableTripCount, bool RequiresScalarEpilogue, bool TailFolded, Loop *OrigLoop, const uint32_t *MinItersBypassWeights, DebugLoc DL, PredicatedScalarEvolution &PSE, VPBasicBlock *CheckBlock)
static void replaceSymbolicStrides(VPlan &Plan, PredicatedScalarEvolution &PSE, const SymbolicStrideMap &StridesMap, const VPDominatorTree &VPDT)
Replace symbolic strides from StridesMap in Plan with constants when possible.
static LLVM_ABI_FOR_TEST void optimize(VPlan &Plan)
Apply VPlan-to-VPlan optimizations to Plan, including induction recipe optimizations,...
static void dissolveLoopRegions(VPlan &Plan)
Replace loop regions with explicit CFG.
static void truncateToMinimalBitwidths(VPlan &Plan, const MapVector< Instruction *, uint64_t > &MinBWs)
Insert truncates and extends for any truncated recipe.
static void narrowInductionTruncates(VPlan &Plan, VFRange &Range, const TargetTransformInfo &TTI)
Replace truncates of a wide induction, or of that induction's increment, by a VPWidenIntOrFpInduction...
static void dropPoisonGeneratingRecipes(VPlan &Plan)
Drop poison flags from recipes that may generate a poison value that is used after vectorization,...
static void optimizeForVFAndUF(VPlan &Plan, ElementCount BestVF, unsigned BestUF, PredicatedScalarEvolution &PSE)
Optimize Plan based on BestVF and BestUF.
static void widenMemoryAccessesByUF(VPlan &Plan, ElementCount VF, unsigned UF, const TargetTransformInfo &TTI)
Widens memory operations by a factor of UF based on a target hook.
static void convertEVLExitCond(VPlan &Plan)
Replaces the exit condition from (branch-on-cond eq CanonicalIVInc, VectorTripCount) to (branch-on-co...
static bool splitCombinedExits(VPlan &Plan, PredicatedScalarEvolution &PSE, Loop *TheLoop)
If a single exit has multiple conditions combined together, split them and create new exiting blocks.
static void combineRecipes(VPlan &Plan)
Perform instcombine-like simplifications on recipes in Plan.
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 unsigned VectorizeMemoryCheckThreshold
The maximum allowed number of runtime memory checks.
static LLVM_ABI bool HoistRuntimeChecks