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