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