LLVM 24.0.0git
LoopVectorizationPlanner.h
Go to the documentation of this file.
1//===- LoopVectorizationPlanner.h - Planner for LoopVectorization ---------===//
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/// \file
10/// This file provides a LoopVectorizationPlanner class.
11/// InnerLoopVectorizer vectorizes loops which contain only one basic
12/// LoopVectorizationPlanner - drives the vectorization process after having
13/// passed Legality checks.
14/// The planner builds and optimizes the Vectorization Plans which record the
15/// decisions how to vectorize the given loop. In particular, represent the
16/// control-flow of the vectorized version, the replication of instructions that
17/// are to be scalarized, and interleave access groups.
18///
19/// Also provides a VPlan-based builder utility analogous to IRBuilder.
20/// It provides an instruction-level API for generating VPInstructions while
21/// abstracting away the Recipe manipulation details.
22//===----------------------------------------------------------------------===//
23
24#ifndef LLVM_TRANSFORMS_VECTORIZE_LOOPVECTORIZATIONPLANNER_H
25#define LLVM_TRANSFORMS_VECTORIZE_LOOPVECTORIZATIONPLANNER_H
26
27#include "VPlan.h"
28#include "llvm/ADT/SmallSet.h"
31#include <optional>
32
33namespace {
34class GeneratedRTChecks;
35}
36
37namespace llvm {
38
40class LoopInfo;
41class DominatorTree;
47class LoopVersioning;
50class VPRecipeBuilder;
51struct VPRegisterUsage;
52struct VFRange;
53
54/// \return An upper bound for vscale based on TTI or the vscale_range
55/// attribute.
56std::optional<unsigned> getMaxVScale(const Function &F);
57
58/// \return The upper bound for the runtime value of \p EC, or std::nullopt
59/// if the upper bound is unknown.
60std::optional<uint64_t>
62
63// Utility functions that are used by different vectorization classes
65
66/// Reports a vectorization failure: print \p DebugMsg for debugging
67/// purposes along with the corresponding optimization remark \p RemarkName.
68/// If \p I is passed, it is an instruction that prevents vectorization.
69/// Otherwise, the loop \p TheLoop is used for the location of the remark.
70void reportVectorizationFailure(const StringRef DebugMsg,
71 const StringRef OREMsg, const StringRef ORETag,
73 const Loop *TheLoop, Instruction *I = nullptr);
74
75/// Same as above, but the debug message and optimization remark are identical
76inline void reportVectorizationFailure(const StringRef DebugMsg,
77 const StringRef ORETag,
79 const Loop *TheLoop,
80 Instruction *I = nullptr) {
81 reportVectorizationFailure(DebugMsg, DebugMsg, ORETag, ORE, TheLoop, I);
82}
83
84/// Reports an informative message: print \p Msg for debugging purposes as well
85/// as an optimization remark. Uses either \p I as location of the remark, or
86/// otherwise \p TheLoop. If \p DL is passed, use it as debug location for the
87/// remark.
88void reportVectorizationInfo(const StringRef Msg, const StringRef ORETag,
90 const Loop *TheLoop, Instruction *I = nullptr,
91 DebugLoc DL = {});
92
93/// Report successful vectorization of the loop. In case an outer loop is
94/// vectorized, prepend "outer" to the vectorization remark.
95void reportVectorization(OptimizationRemarkEmitter *ORE, Loop *TheLoop,
96 ElementCount VFWidth, unsigned IC);
97
98} // namespace LoopVectorizationUtils
99
100/// VPlan-based builder utility analogous to IRBuilder.
102private:
103 class VPInsertPoint {
104 VPBasicBlock *Block = nullptr;
105 VPBasicBlock::iterator Iterator;
106
107 public:
108 /// Creates a new insertion point which doesn't point to anything.
109 VPInsertPoint() = default;
110
111 /// Creates a new insertion point to insert at \p Iterator in \p Block.
112 VPInsertPoint(VPBasicBlock *Block, VPBasicBlock::iterator Iterator)
113 : Block(Block), Iterator(Iterator) {}
114
115 /// Creates a new insertion point to insert before \p R.
116 VPInsertPoint(VPRecipeBase *R)
117 : Block(R->getParent()), Iterator(R->getIterator()) {}
118
119 /// Creates a new insertion point to insert at the end of \p Block.
120 VPInsertPoint(VPBasicBlock *Block) : Block(Block), Iterator(Block->end()) {}
121
122 /// Returns true if this insert point is set.
123 operator bool() const { return Block; }
124
125 VPBasicBlock *getBlock() const { return Block; }
126 VPBasicBlock::iterator getIterator() const { return Iterator; }
127
128 operator VPRecipeBase *() const {
129 return Iterator == Block->end() ? nullptr : &*Iterator;
130 }
131 };
132
133 VPInsertPoint InsertPt;
134
135 /// Insert \p VPI in BB at InsertPt if BB is set.
136 template <typename T> T *tryInsertInstruction(T *R) {
137 if (InsertPt)
138 InsertPt.getBlock()->insert(R, InsertPt.getIterator());
139 return R;
140 }
141
142 VPInstruction *createInstruction(unsigned Opcode,
144 const VPIRMetadata &MD, DebugLoc DL,
145 const Twine &Name = "") {
146 return tryInsertInstruction(
147 new VPInstruction(Opcode, Operands, {}, MD, DL, Name));
148 }
149
150public:
151 VPlan &getPlan() const {
152 assert(InsertPt && "Insert block must be set");
153 return *InsertPt.getBlock()->getPlan();
154 }
155
156 VPBuilder() = default;
157 VPBuilder(const VPInsertPoint &IP) : InsertPt(IP) {}
159 : InsertPt(TheBB, IP) {}
160
161 /// Get the recipe at the current insert point or nullptr if the insert point
162 /// is the end of the block.
163 VPRecipeBase *getRecipeAtInsertPoint() const { return InsertPt; }
164
165 /// Create a VPBuilder to insert after \p R.
167 return {R->getParent(), std::next(R->getIterator())};
168 }
169
170 /// Sets the current insert point to a previously-saved location.
171 void restoreIP(VPInsertPoint IP) { InsertPt = IP; }
172
173 /// Set the current insert point.
174 void setInsertPoint(const VPInsertPoint &IP) {
175 assert(IP && "Attempting to set a null insert point");
176 InsertPt = IP;
177 }
179 assert(TheBB && "Attempting to set a null insert point");
180 InsertPt = VPInsertPoint(TheBB, IP);
181 }
182
183 /// Insert \p R at the current insertion point. Returns \p R unchanged.
184 template <typename T> [[maybe_unused]] T *insert(T *R) {
185 InsertPt.getBlock()->insert(R, InsertPt.getIterator());
186 return R;
187 }
188
189 /// Create an N-ary operation with \p Opcode, \p Operands and set \p Inst as
190 /// its underlying Instruction.
192 Instruction *Inst = nullptr,
193 const VPIRFlags &Flags = {},
194 const VPIRMetadata &MD = {},
196 const Twine &Name = "",
197 Type *ResultTy = nullptr) {
198 VPInstruction *NewVPInst = tryInsertInstruction(
199 new VPInstruction(Opcode, Operands, Flags, MD, DL, Name, ResultTy));
200 NewVPInst->setUnderlyingValue(Inst);
201 return NewVPInst;
202 }
204 DebugLoc DL, const Twine &Name = "") {
205 return createInstruction(Opcode, Operands, {}, DL, Name);
206 }
208 const VPIRFlags &Flags,
210 const Twine &Name = "") {
211 return tryInsertInstruction(
212 new VPInstruction(Opcode, Operands, Flags, {}, DL, Name));
213 }
214
216 Type *ResultTy, const VPIRFlags &Flags = {},
218 const Twine &Name = "") {
219 return tryInsertInstruction(
220 new VPInstruction(Opcode, Operands, Flags, {}, DL, Name, ResultTy));
221 }
222
225 const Twine &Name = "") {
226 // Assume that the maximum possible number of elements in a vector fits
227 // within the index type for the default address space.
228 VPlan &Plan = getPlan();
229 Type *IndexTy = Plan.getDataLayout().getIndexType(Plan.getContext(), 0);
230 return tryInsertInstruction(new VPInstruction(
231 VPInstruction::FirstActiveLane, Masks, {}, {}, DL, Name, IndexTy));
232 }
233
236 const Twine &Name = "") {
237 // Assume that the maximum possible number of elements in a vector fits
238 // within the index type for the default address space.
239 VPlan &Plan = getPlan();
240 Type *IndexTy = Plan.getDataLayout().getIndexType(Plan.getContext(), 0);
241 return tryInsertInstruction(new VPInstruction(
242 VPInstruction::LastActiveLane, Masks, {}, {}, DL, Name, IndexTy));
243 }
244
246 unsigned Opcode, ArrayRef<VPValue *> Operands,
247 VPRecipeWithIRFlags::WrapFlagsTy WrapFlags = {false, false},
248 DebugLoc DL = DebugLoc::getUnknown(), const Twine &Name = "") {
249 return tryInsertInstruction(
250 new VPInstruction(Opcode, Operands, WrapFlags, {}, DL, Name));
251 }
252
255 const Twine &Name = "") {
256 return createInstruction(VPInstruction::Not, {Operand}, {}, DL, Name);
257 }
258
261 const Twine &Name = "") {
262 return createInstruction(Instruction::BinaryOps::And, {LHS, RHS}, {}, DL,
263 Name);
264 }
265
268 const Twine &Name = "") {
269
270 return tryInsertInstruction(new VPInstruction(
271 Instruction::BinaryOps::Or, {LHS, RHS},
272 VPRecipeWithIRFlags::DisjointFlagsTy(false), {}, DL, Name));
273 }
274
277 const Twine &Name = "",
278 VPRecipeWithIRFlags::WrapFlagsTy WrapFlags = {false, false}) {
279 return createOverflowingOp(Instruction::Add, {LHS, RHS}, WrapFlags, DL,
280 Name);
281 }
282
283 VPInstruction *
285 const Twine &Name = "",
286 VPRecipeWithIRFlags::WrapFlagsTy WrapFlags = {false, false}) {
287 return createOverflowingOp(Instruction::Sub, {LHS, RHS}, WrapFlags, DL,
288 Name);
289 }
290
296
302
303 /// Create a select of \p TrueVal and \p FalseVal based on \p Cond, using the
304 /// default flags for the result type, unless \p Flags is set.
306 VPValue *FalseVal,
308 const Twine &Name = "",
309 std::optional<VPIRFlags> Flags = std::nullopt) {
310 return tryInsertInstruction(
311 new VPInstruction(Instruction::Select, {Cond, TrueVal, FalseVal},
312 Flags.value_or(VPIRFlags::getDefaultFlags(
313 Instruction::Select, TrueVal->getScalarType())),
314 {}, DL, Name));
315 }
316
317 /// Create a new ICmp VPInstruction with predicate \p Pred and operands \p A
318 /// and \p B.
321 const Twine &Name = "") {
323 Pred <= CmpInst::LAST_ICMP_PREDICATE && "invalid predicate");
324 return tryInsertInstruction(
325 new VPInstruction(Instruction::ICmp, {A, B}, Pred, {}, DL, Name));
326 }
327
328 /// Create a new FCmp VPInstruction with predicate \p Pred and operands \p A
329 /// and \p B.
332 const Twine &Name = "") {
334 Pred <= CmpInst::LAST_FCMP_PREDICATE && "invalid predicate");
335 return tryInsertInstruction(
336 new VPInstruction(Instruction::FCmp, {A, B},
337 VPIRFlags(Pred, FastMathFlags()), {}, DL, Name));
338 }
339
340 /// Create an AnyOf reduction pattern: or-reduce \p ChainOp, freeze the
341 /// result, then select between \p TrueVal and \p FalseVal.
343 VPValue *FalseVal,
345
348 const Twine &Name = "") {
349 return createNoWrapPtrAdd(Ptr, Offset, GEPNoWrapFlags::none(), DL, Name);
350 }
351
353 GEPNoWrapFlags GEPFlags,
355 const Twine &Name = "") {
356 return tryInsertInstruction(new VPInstruction(
357 VPInstruction::PtrAdd, {Ptr, Offset}, GEPFlags, {}, DL, Name));
358 }
359
362 const Twine &Name = "") {
363 return tryInsertInstruction(
365 GEPNoWrapFlags::none(), {}, DL, Name));
366 }
367
368 /// Create a phi with \p IncomingValues, using the default flags for the
369 /// result type, unless \p Flags is set.
372 const Twine &Name = "",
373 std::optional<VPIRFlags> Flags = std::nullopt,
374 Type *ResultTy = nullptr) {
375 Type *ScalarTy = ResultTy ? ResultTy : IncomingValues[0]->getScalarType();
376 return tryInsertInstruction(new VPPhi(
377 IncomingValues,
378 Flags.value_or(VPIRFlags::getDefaultFlags(Instruction::PHI, ScalarTy)),
379 DL, Name, ResultTy));
380 }
381
384 const Twine &Name = "") {
385 return tryInsertInstruction(new VPWidenPHIRecipe(IncomingValues, DL, Name));
386 }
387
389 VPlan &Plan = getPlan();
390 unsigned MinEC = EC.getKnownMinValue();
391 if (EC.isScalable()) {
392 VPValue *VScale = createVScale(Ty);
393 if (MinEC == 1)
394 return VScale;
395 // TODO: Move this optimization into createOverflowingOp directly.
396 if (isPowerOf2_32(MinEC)) {
397 VPValue *ShtAmt = Plan.getConstantInt(Ty, Log2_32(MinEC));
398 return createOverflowingOp(Instruction::Shl, {VScale, ShtAmt},
399 {true, false});
400 }
401 VPValue *MulAmt = Plan.getConstantInt(Ty, MinEC);
402 return createOverflowingOp(Instruction::Mul, {VScale, MulAmt},
403 {true, false});
404 }
405 return Plan.getConstantInt(Ty, MinEC);
406 }
407
408 /// Convert \p Current to \p Start + \p Current * \p Step.
410 FPMathOperator *FPBinOp, VPValue *Start,
411 VPValue *Current, VPValue *Step,
412 const VPIRFlags::WrapFlagsTy &Flags = {}) {
413 return tryInsertInstruction(
414 new VPDerivedIVRecipe(Kind, FPBinOp, Start, Current, Step, Flags));
415 }
416
418 Type *ResultTy, DebugLoc DL,
419 std::optional<VPIRFlags> Flags = std::nullopt,
420 const VPIRMetadata &Metadata = {}) {
421 return tryInsertInstruction(new VPInstruction(
422 Opcode, Op, Flags.value_or(VPIRFlags::getDefaultFlags(Opcode)),
423 Metadata, DL, "", ResultTy));
424 }
425
426 /// Create a scalar call to the intrinsic \p IntrinsicID with \p Operands, and
427 /// result type \p ResultTy
430 Type *ResultTy, DebugLoc DL) {
431 VPlan &Plan = getPlan();
433 Ops.push_back(Plan.getConstantInt(8 * sizeof(IntrinsicID), IntrinsicID));
434 return tryInsertInstruction(new VPInstruction(VPInstruction::Intrinsic, Ops,
435 {}, {}, DL, "", ResultTy));
436 }
437
438 /// Create a scalar llvm.vscale call.
441 return createScalarIntrinsic(Intrinsic::vscale, {}, ResultTy, DL);
442 }
443
445 Type *SrcTy = Op->getScalarType();
446 if (ResultTy == SrcTy)
447 return Op;
448 Instruction::CastOps CastOp =
449 ResultTy->getScalarSizeInBits() < SrcTy->getScalarSizeInBits()
450 ? Instruction::Trunc
451 : Instruction::ZExt;
452 return createScalarCast(CastOp, Op, ResultTy, DL);
453 }
454
456 Type *SrcTy = Op->getScalarType();
457 if (ResultTy == SrcTy)
458 return Op;
459 Instruction::CastOps CastOp =
460 ResultTy->getScalarSizeInBits() < SrcTy->getScalarSizeInBits()
461 ? Instruction::Trunc
462 : Instruction::SExt;
463 return createScalarCast(CastOp, Op, ResultTy, DL);
464 }
465
467 const Twine &Name = "") {
468 return createNaryOp(Instruction::Freeze, Op, DL, Name);
469 }
470
472 Type *ResultTy) {
473 assert(Op->getScalarType() != ResultTy &&
474 "must not create a no-op cast recipe");
475 return tryInsertInstruction(new VPWidenCastRecipe(
476 Opcode, Op, ResultTy, nullptr, VPIRFlags::getDefaultFlags(Opcode)));
477 }
478
479 /// Create a single-scalar recipe with \p Opcode and \p Operands without
480 /// inserting it.
483 VPValue *Mask,
484 const VPIRFlags &Flags,
485 const VPIRMetadata &Metadata,
486 DebugLoc DL, Instruction *UV) {
487 if (Instruction::isCast(Opcode)) {
488 assert(!Mask && "Cast cannot be predicated");
489 auto *VPI = new VPInstruction(Opcode, Operands, Flags, Metadata, DL,
490 UV->getName(), UV->getType());
491 VPI->setUnderlyingValue(UV);
492 return VPI;
493 }
494 return new VPReplicateRecipe(UV, Operands, /*IsSingleScalar=*/true, Mask,
495 Flags, Metadata, DL);
496 }
497
500 FPMathOperator *FPBinOp, VPValue *IV, VPValue *Step,
501 VPValue *VF, DebugLoc DL) {
502 return tryInsertInstruction(new VPScalarIVStepsRecipe(
503 IV, Step, VF, InductionOpcode,
504 FPBinOp ? FPBinOp->getFastMathFlags() : FastMathFlags(), DL));
505 }
506
508 return tryInsertInstruction(new VPExpandSCEVRecipe(Expr));
509 }
510
512 createVectorPointer(VPValue *Ptr, Type *SourceElementTy, VPValue *Stride,
513 GEPNoWrapFlags GEPFlags, DebugLoc DL) {
514 return tryInsertInstruction(
515 new VPVectorPointerRecipe(Ptr, SourceElementTy, Stride, GEPFlags, DL));
516 }
517
518 /// Create a vector pointer recipe for a consecutive memory access to \p Ptr
519 /// with element type \p SourceElementTy.
521 Type *SourceElementTy,
522 bool Reverse, DebugLoc DL);
523
525 Intrinsic::ID VectorIntrinsicID, ArrayRef<VPValue *> CallArguments,
526 Type *Ty, Align Alignment, const VPIRMetadata &MD, DebugLoc DL) {
527 return tryInsertInstruction(new VPWidenMemIntrinsicRecipe(
528 VectorIntrinsicID, CallArguments, Ty, Alignment, MD, DL));
529 }
530
531 /// Create a recipe widening \p Load, loading from \p Addr with \p Mask (may
532 /// be null).
534 VPValue *Mask, bool Consecutive,
535 const VPIRMetadata &Metadata,
536 DebugLoc DL) {
537 return tryInsertInstruction(
538 new VPWidenLoadRecipe(Load, Addr, Mask, Consecutive, Metadata, DL));
539 }
540
541 /// Create a recipe widening \p Store, storing \p StoredVal to \p Addr with
542 /// \p Mask (may be null).
544 VPValue *StoredVal, VPValue *Mask,
545 bool Consecutive,
546 const VPIRMetadata &Metadata,
547 DebugLoc DL) {
548 return tryInsertInstruction(new VPWidenStoreRecipe(
549 Store, Addr, StoredVal, Mask, Consecutive, Metadata, DL));
550 }
551
552 //===--------------------------------------------------------------------===//
553 // RAII helpers.
554 //===--------------------------------------------------------------------===//
555
556 /// RAII object that stores the current insertion point and restores it when
557 /// the object is destroyed.
559 VPBuilder &Builder;
560 VPInsertPoint InsertPt;
561
562 public:
563 InsertPointGuard(VPBuilder &B) : Builder(B), InsertPt(B.InsertPt) {}
564
567
568 ~InsertPointGuard() { Builder.restoreIP(InsertPt); }
569 };
570};
571
572/// TODO: The following VectorizationFactor was pulled out of
573/// LoopVectorizationCostModel class. LV also deals with
574/// VectorizerParams::VectorizationFactor.
575/// We need to streamline them.
576
577/// Information about vectorization costs.
579 /// Vector width with best cost.
581
582 /// Cost of the loop with that width.
584
585 /// Cost of the scalar loop.
587
588 /// The minimum trip count required to make vectorization profitable, e.g. due
589 /// to runtime checks.
591
595
596 /// Width 1 means no vectorization, cost 0 means uncomputed cost.
598 return {ElementCount::getFixed(1), 0, 0};
599 }
600
601 bool operator==(const VectorizationFactor &rhs) const {
602 return Width == rhs.Width && Cost == rhs.Cost;
603 }
604
605 bool operator!=(const VectorizationFactor &rhs) const {
606 return !(*this == rhs);
607 }
608};
609
610/// A class that represents two vectorization factors (initialized with 0 by
611/// default). One for fixed-width vectorization and one for scalable
612/// vectorization. This can be used by the vectorizer to choose from a range of
613/// fixed and/or scalable VFs in order to find the most cost-effective VF to
614/// vectorize with.
618
620 : FixedVF(ElementCount::getFixed(0)),
621 ScalableVF(ElementCount::getScalable(0)) {}
623 *(Max.isScalable() ? &ScalableVF : &FixedVF) = Max;
624 }
628 assert(!FixedVF.isScalable() && ScalableVF.isScalable() &&
629 "Invalid scalable properties");
630 }
631
633
634 /// \return true if either fixed- or scalable VF is non-zero.
635 explicit operator bool() const { return FixedVF || ScalableVF; }
636};
637
638/// Holds state needed to make cost decisions before computing costs per-VF,
639/// including the maximum VFs.
641 /// \return True if maximizing vector bandwidth is enabled by the target or
642 /// user options, for the given register kind (scalable or fixed-width).
643 bool useMaxBandwidth(bool IsScalable) const;
644
645 /// \return the maximized element count based on the targets vector
646 /// registers and the loop trip-count, but limited to a maximum safe VF.
647 /// This is a helper function of computeFeasibleMaxVF.
648 ElementCount getMaximizedVFForTarget(unsigned MaxTripCount,
649 unsigned SmallestType,
650 unsigned WidestType,
651 ElementCount MaxSafeVF, unsigned UserIC,
652 bool FoldTailByMasking,
653 bool RequiresScalarEpilogue);
654
655 /// If \p VF * \p UserIC > MaxTripcount, clamps VF to the next lower VF
656 /// that results in VF * UserIC <= MaxTripCount.
657 ElementCount clampVFByMaxTripCount(ElementCount VF, unsigned MaxTripCount,
658 unsigned UserIC, bool FoldTailByMasking,
659 bool RequiresScalarEpilogue) const;
660
661 /// Checks if scalable vectorization is supported and enabled. Caches the
662 /// result to avoid repeated debug dumps for repeated queries.
663 bool isScalableVectorizationAllowed();
664
665 /// \return the maximum legal scalable VF, based on the safe max number
666 /// of elements.
667 ElementCount getMaxLegalScalableVF(unsigned MaxSafeElements);
668
669 /// Initializes the value of vscale used for tuning the cost model. If
670 /// vscale_range.min == vscale_range.max then return vscale_range.max, else
671 /// return the value returned by the corresponding TTI method.
672 void initializeVScaleForTuning();
673
674 const TargetTransformInfo &TTI;
675 const LoopVectorizationLegality *Legal;
676 const Loop *TheLoop;
677 const Function &F;
679 DemandedBits *DB;
681 const LoopVectorizeHints *Hints;
682
683 /// Cached result of isScalableVectorizationAllowed.
684 std::optional<bool> IsScalableVectorizationAllowed;
685
686 /// Used to store the value of vscale used for tuning the cost model. It is
687 /// initialized during object construction.
688 std::optional<unsigned> VScaleForTuning;
689
690 /// The highest VF possible for this loop, without using MaxBandwidth.
691 FixedScalableVFPair MaxPermissibleVFWithoutMaxBW;
692
693 /// All element types found in the loop.
694 SmallPtrSet<Type *, 16> ElementTypesInLoop;
695
696 /// PHINodes of the reductions that should be expanded in-loop. Set by
697 /// collectInLoopReductions.
698 SmallPtrSet<PHINode *, 4> InLoopReductions;
699
700 /// Maximum safe number of elements to be processed per vector iteration,
701 /// which do not prevent store-load forwarding and are safe with regard to the
702 /// memory dependencies. Required for EVL-based vectorization, where this
703 /// value is used as the upper bound of the safe AVL. Set by
704 /// computeFeasibleMaxVF.
705 std::optional<unsigned> MaxSafeElements;
706
707 /// Map of scalar integer values to the smallest bitwidth they can be legally
708 /// represented as. The vector equivalents of these values should be truncated
709 /// to this type.
711
712public:
713 /// The kind of cost that we are calculating.
715
716 /// Whether this loop should be optimized for size based on function attribute
717 /// or profile information.
718 const bool OptForSize;
719
721 const LoopVectorizationLegality *Legal,
722 const Loop *TheLoop, const Function &F,
725 const LoopVectorizeHints *Hints, bool OptForSize)
726 : TTI(TTI), Legal(Legal), TheLoop(TheLoop), F(F), PSE(PSE), DB(DB),
727 ORE(ORE), Hints(Hints),
728 CostKind(F.hasMinSize() ? TTI::TCK_CodeSize : TTI::TCK_RecipThroughput),
730 initializeVScaleForTuning();
731 }
732
733 /// \return The vscale value used for tuning the cost model.
734 std::optional<unsigned> getVScaleForTuning() const { return VScaleForTuning; }
735
736 const TargetTransformInfo &getTTI() const { return TTI; }
737
738 PredicatedScalarEvolution &getPSE() const { return PSE; }
739
740 /// \return The loop being analyzed.
741 const Loop *getLoop() const { return TheLoop; }
742
743 /// \return The vectorization hints for the loop being analyzed.
744 const LoopVectorizeHints &getHints() const { return *Hints; }
745
746 /// Returns true if epilogue vectorization is considered profitable for a
747 /// main loop with vectorization factor \p VF and interleave count \p IC.
748 bool isEpilogueVectorizationProfitable(ElementCount VF, unsigned IC) const;
749
750 /// \return True if register pressure should be considered for the given VF.
752
753 /// \return True if scalable vectors are supported by the target or forced.
754 bool supportsScalableVectors() const;
755
756 /// Collect element types in the loop that need widening.
758 const SmallPtrSetImpl<const Value *> *ValuesToIgnore = nullptr);
759
760 /// \return The size (in bits) of the smallest and widest types in the code
761 /// that need to be vectorized. We ignore values that remain scalar such as
762 /// 64 bit loop indices.
763 std::pair<unsigned, unsigned> getSmallestAndWidestTypes() const;
764
765 /// \return An upper bound for the vectorization factors for both
766 /// fixed and scalable vectorization, where the minimum-known number of
767 /// elements is a power-of-2 larger than zero. If scalable vectorization is
768 /// disabled or unsupported, then the scalable part will be equal to
769 /// ElementCount::getScalable(0). Also sets MaxSafeElements.
770 FixedScalableVFPair computeFeasibleMaxVF(unsigned MaxTripCount,
771 ElementCount UserVF, unsigned UserIC,
772 bool FoldTailByMasking,
773 bool RequiresScalarEpilogue);
774
775 /// Return maximum safe number of elements to be processed per vector
776 /// iteration, which do not prevent store-load forwarding and are safe with
777 /// regard to the memory dependencies. Required for EVL-based VPlans to
778 /// correctly calculate AVL (application vector length) as min(remaining AVL,
779 /// MaxSafeElements). Set by computeFeasibleMaxVF.
780 /// TODO: need to consider adjusting cost model to use this value as a
781 /// vectorization factor for EVL-based vectorization.
782 std::optional<unsigned> getMaxSafeElements() const { return MaxSafeElements; }
783
784 /// Returns true if we should use strict in-order reductions for the given
785 /// RdxDesc. This is true if the -enable-strict-reductions flag is passed,
786 /// the IsOrdered flag of RdxDesc is set and we do not allow reordering
787 /// of FP operations.
788 bool useOrderedReductions(const RecurrenceDescriptor &RdxDesc) const;
789
790 /// Returns true if the target machine supports a masked load (if \p IsLoad)
791 /// or masked store of scalar type \p ScalarTy with \p Alignment in address
792 /// space \p AddressSpace. The caller must ensure the access is consecutive or
793 /// part of an interleave group.
794 bool isLegalMaskedLoadOrStore(bool IsLoad, Type *ScalarTy, Align Alignment,
795 unsigned AddressSpace) const;
796
797 /// Returns true if the target machine supports a gather (if \p IsLoad)
798 /// or scatter of scalar type \p ScalarTy with \p Alignment for vectorization
799 /// factor \p VF.
800 bool isLegalGatherOrScatter(bool IsLoad, Type *ScalarTy, Align Alignment,
801 ElementCount VF) const;
802
803 /// Split reductions into those that happen in the loop, and those that
804 /// happen outside. In-loop reductions are collected into InLoopReductions.
806
807 /// Returns true if the Phi is part of an inloop reduction.
808 bool isInLoopReduction(PHINode *Phi) const {
809 return InLoopReductions.contains(Phi);
810 }
811
812 /// Returns the set of in-loop reduction PHIs.
814 return InLoopReductions;
815 }
816
817 /// Check whether vectorization would require runtime checks. When optimizing
818 /// for size, returning true here aborts vectorization.
820
821 /// Returns a scalable VF to use for outer-loop vectorization if the target
822 /// supports it and a fixed VF otherwise.
824
825 /// Compute smallest bitwidth each instruction can be represented with.
826 /// The vector equivalents of these instructions should be truncated to this
827 /// type.
829
830 /// \returns The smallest bitwidth each instruction can be represented with.
832 return MinBWs;
833 }
834};
835
836/// Planner drives the vectorization process after having passed
837/// Legality checks.
839 /// The loop that we evaluate.
840 Loop *OrigLoop;
841
842 /// Loop Info analysis.
843 LoopInfo *LI;
844
845 /// The dominator tree.
846 DominatorTree *DT;
847
848 /// Target Library Info.
849 const TargetLibraryInfo *TLI;
850
851 /// Target Transform Info.
852 const TargetTransformInfo &TTI;
853
854 /// The legality analysis.
856
857 /// The profitability analysis. Cleared after making cost based decisions.
858 std::unique_ptr<LoopVectorizationCostModel> CM;
859
860 /// VF selection state independent of cost-modeling decisions.
861 VFSelectionContext &Config;
862
863 /// The interleaved access analysis.
865
867
869
870 /// Lazily fetch BranchProbabilityInfo, independent of BlockFrequencyInfo.
871 std::function<const BranchProbabilityInfo &()> GetBPI;
872
874
875 /// Profitable vector factors.
877
878 /// A builder used to construct the current plan.
879 VPBuilder Builder;
880
881 /// Computes the cost of \p Plan for vectorization factor \p VF.
882 ///
883 /// The current implementation requires access to the
884 /// LoopVectorizationLegality to handle inductions and reductions, which is
885 /// why it is kept separate from the VPlan-only cost infrastructure.
886 ///
887 /// TODO: Move to VPlan::cost once the use of LoopVectorizationLegality has
888 /// been retired.
889 InstructionCost cost(VPlan &Plan, ElementCount VF, VPRegisterUsage *RU) const;
890
891 /// Precompute costs for certain instructions using the legacy cost model. The
892 /// function is used to bring up the VPlan-based cost model to initially avoid
893 /// taking different decisions due to inaccuracies in the legacy cost model.
894 InstructionCost precomputeCosts(VPlan &Plan, ElementCount VF,
895 VPCostContext &CostCtx) const;
896
897public:
899 Loop *L, LoopInfo *LI, DominatorTree *DT, const TargetLibraryInfo *TLI,
901 std::unique_ptr<LoopVectorizationCostModel> CM,
904 std::function<const BranchProbabilityInfo &()> GetBPI);
905
907
908 /// Return the cost model. Must not be called after clearCostModel().
910 assert(CM && "Cost model has already been cleared");
911 return *CM;
912 }
913
914 /// Destroy the cost model.
915 void clearCostModel();
916
917 /// Build VPlans for the specified \p UserVF and \p UserIC if they are
918 /// non-zero or all applicable candidate VFs otherwise. If vectorization and
919 /// interleaving should be avoided up-front, no plans are generated.
920 void plan(ElementCount UserVF, unsigned UserIC);
921
922 /// Return the VPlan for \p VF. At the moment, there is always a single VPlan
923 /// for each VF.
924 VPlan &getPlanFor(ElementCount VF) const;
925
926 /// Compute and return the most profitable vectorization factor and the
927 /// corresponding best VPlan. Also collect all profitable VFs in
928 /// ProfitableVFs.
929 std::pair<VectorizationFactor, VPlan *> computeBestVF();
930
931 /// \return The desired interleave count.
932 /// If interleave count has been specified by metadata it will be returned.
933 /// Otherwise, the interleave count is computed and returned. VF and LoopCost
934 /// are the selected vectorization factor and the cost of the selected VF.
935 unsigned selectInterleaveCount(VPlan &Plan, ElementCount VF,
936 InstructionCost LoopCost);
937
938 /// Generate the IR code for the vectorized loop captured in VPlan \p BestPlan
939 /// according to the best selected \p VF and \p UF.
940 ///
941 /// TODO: \p EpilogueVecKind should be removed once the re-use issue has been
942 /// fixed.
943 ///
944 /// Returns a mapping of SCEVs to their expanded IR values.
945 /// Note that this is a temporary workaround needed due to the current
946 /// epilogue handling.
948 None, ///< Not part of epilogue vectorization.
949 MainLoop, ///< Vectorizing the main loop of epilogue vectorization.
950 Epilogue ///< Vectorizing the epilogue loop.
951 };
953 executePlan(ElementCount VF, unsigned UF, VPlan &BestPlan,
955 EpilogueVectorizationKind EpilogueVecKind =
957
958#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
959 void printPlans(raw_ostream &O);
960#endif
961
962 /// Look through the existing plans and return true if we have one with
963 /// vectorization factor \p VF.
965 return any_of(VPlans,
966 [&](const VPlanPtr &Plan) { return Plan->hasVF(VF); });
967 }
968
969 /// Test a \p Predicate on a \p Range of VF's. Return the value of applying
970 /// \p Predicate on Range.Start, possibly decreasing Range.End such that the
971 /// returned value holds for the entire \p Range.
972 static bool
973 getDecisionAndClampRange(const std::function<bool(ElementCount)> &Predicate,
974 VFRange &Range);
975
976 /// \return A VPlan for the most profitable epilogue vectorization, with its
977 /// VF narrowed to the chosen factor. The returned plan is a duplicate.
978 /// Returns nullptr if epilogue vectorization is not supported or not
979 /// profitable for the loop. \p ScalarEpilogueAllowed indicates whether the
980 /// epilogue lowering policy permits creating a scalar epilogue at all.
981 std::unique_ptr<VPlan> selectBestEpiloguePlan(VPlan &MainPlan,
982 ElementCount MainLoopVF,
983 unsigned IC,
984 bool ScalarEpilogueAllowed);
985
986 /// Emit remarks for recipes with invalid costs in the available VPlans.
988
989 /// Create a check to \p Plan to see if the vector loop should be executed
990 /// based on its trip count.
991 void addMinimumIterationCheck(VPlan &Plan, ElementCount VF, unsigned UF,
992 ElementCount MinProfitableTripCount) const;
993
994 /// Attach the runtime checks of \p RTChecks to \p Plan.
995 void attachRuntimeChecks(VPlan &Plan, GeneratedRTChecks &RTChecks,
996 bool HasBranchWeights) const;
997
998 /// Update loop metadata and profile info for both the scalar remainder loop
999 /// and \p VectorLoop, if it exists. Keeps all loop hints from the original
1000 /// loop on the vector loop and replaces vectorizer-specific metadata. The
1001 /// loop ID of the original loop \p OrigLoopID must be passed, together with
1002 /// the average trip count and invocation weight of the original loop (\p
1003 /// OrigAverageTripCount and \p OrigLoopInvocationWeight respectively). They
1004 /// cannot be retrieved after the plan has been executed, as the original loop
1005 /// may have been removed. \p UnrollVectorizedLoop indicates whether the
1006 /// target wants the vector loop left eligible for runtime unrolling.
1008 Loop *VectorLoop, VPBasicBlock *HeaderVPBB, const VPlan &Plan,
1009 bool VectorizingEpilogue, MDNode *OrigLoopID,
1010 std::optional<unsigned> OrigAverageTripCount,
1011 unsigned OrigLoopInvocationWeight, unsigned EstimatedVFxUF,
1012 bool DisableRuntimeUnroll, bool UnrollVectorizedLoop);
1013
1014private:
1015 /// Build an initial VPlan, with HCFG wrapping the original scalar loop and
1016 /// scalar transformations applied. Returns null if an initial VPlan cannot
1017 /// be built.
1018 VPlanPtr tryToBuildVPlan1();
1019
1020 /// Build a VPlan using VPRecipes according to the information gathered by
1021 /// Legal and VPlan-based analysis. For outer loops, performs basic recipe
1022 /// conversion only. For inner loops, \p Range's largest included VF is
1023 /// restricted to the maximum VF the returned VPlan is valid for. If no VPlan
1024 /// can be built for the input range, set the largest included VF to the
1025 /// maximum VF for which no plan could be built. Each VPlan is built starting
1026 /// from a copy of \p InitialPlan, which is a plain CFG VPlan wrapping the
1027 /// original scalar loop.
1028 VPlanPtr tryToBuildVPlan(VPlanPtr InitialPlan, VFRange &Range);
1029
1030 /// Build VPlans for power-of-2 VF's between \p MinVF and \p MaxVF inclusive,
1031 /// based on \p VPlan1 and according to the information gathered by Legal
1032 /// when it checked if it is legal to vectorize the loop.
1033 void buildVPlans(VPlan &VPlan1, ElementCount MinVF, ElementCount MaxVF);
1034
1035 /// Add ComputeReductionResult recipes to the middle block to compute the
1036 /// final reduction results. Add Select recipes to the latch block when
1037 /// folding tail, to feed ComputeReductionResult with the last or penultimate
1038 /// iteration values according to the header mask.
1039 void addReductionResultComputation(VPlanPtr &Plan, ElementCount MinVF);
1040
1041 /// Returns true if the per-lane cost of VectorizationFactor A is lower than
1042 /// that of B.
1043 bool isMoreProfitable(const VectorizationFactor &A,
1044 const VectorizationFactor &B, bool HasTail,
1045 bool IsEpilogue = false) const;
1046
1047 /// Returns true if the per-lane cost of VectorizationFactor A is lower than
1048 /// that of B in the context of vectorizing a loop with known \p MaxTripCount.
1049 bool isMoreProfitable(const VectorizationFactor &A,
1050 const VectorizationFactor &B,
1051 const unsigned MaxTripCount, bool HasTail,
1052 bool IsEpilogue = false) const;
1053
1054 /// Determines if we have the infrastructure to vectorize the loop and its
1055 /// epilogue, assuming the main loop is vectorized by \p MainPlan.
1056 bool isCandidateForEpilogueVectorization(VPlan &MainPlan) const;
1057};
1058
1059/// A helper function that returns true if the given type is irregular. The
1060/// type is irregular if its allocated size doesn't equal the store size of an
1061/// element of the corresponding vector type.
1062inline bool hasIrregularType(Type *Ty, const DataLayout &DL) {
1063 // Determine if an array of N elements of type Ty is "bitcast compatible"
1064 // with a <N x Ty> vector.
1065 // This is only true if there is no padding between the array elements.
1066 return DL.getTypeAllocSizeInBits(Ty) != DL.getTypeSizeInBits(Ty);
1067}
1068
1069} // namespace llvm
1070
1071#endif // LLVM_TRANSFORMS_VECTORIZE_LOOPVECTORIZATIONPLANNER_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file defines an InstructionCost class that is used when calculating the cost of an instruction,...
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define T
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
const SmallVectorImpl< MachineOperand > & Cond
SI Fold Operands
const char * Msg
This file defines the SmallSet class.
This pass exposes codegen information to IR-level passes.
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
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
Analysis providing branch probability information.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
LLVM_ABI IntegerType * getIndexType(LLVMContext &C, unsigned AddressSpace) const
Returns the type of a GEP index in AddressSpace.
A debug info location.
Definition DebugLoc.h:126
static DebugLoc getUnknown()
Definition DebugLoc.h:153
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
static constexpr ElementCount getFixed(ScalarTy MinVal)
Definition TypeSize.h:305
Utility class for floating point operations which can have information about relaxed accuracy require...
Definition Operator.h:202
FastMathFlags getFastMathFlags() const
Convenience function for getting all the fast-math flags.
Definition Operator.h:291
Convenience struct for specifying and reasoning about fast-math flags.
Definition FMF.h:23
Represents flags for the getelementptr instruction/expression.
static GEPNoWrapFlags none()
InductionKind
This enum represents the kinds of inductions that we support.
InnerLoopVectorizer vectorizes loops which contain only one basic block to a specified vectorization ...
bool isCast() const
Drive the analysis of interleaved memory accesses in the loop.
An instruction for reading from memory.
LoopVectorizationCostModel - estimates the expected speedups due to vectorization.
LoopVectorizationLegality checks if it is legal to vectorize a loop, and to what vectorization factor...
DenseMap< const SCEV *, Value * > executePlan(ElementCount VF, unsigned UF, VPlan &BestPlan, InnerLoopVectorizer &LB, DominatorTree *DT, EpilogueVectorizationKind EpilogueVecKind=EpilogueVectorizationKind::None)
EpilogueVectorizationKind
Generate the IR code for the vectorized loop captured in VPlan BestPlan according to the best selecte...
@ MainLoop
Vectorizing the main loop of epilogue vectorization.
void clearCostModel()
Destroy the cost model.
VPlan & getPlanFor(ElementCount VF) const
Return the VPlan for VF.
Definition VPlan.cpp:1682
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:1733
LoopVectorizationCostModel & getCostModel()
Return the cost model. Must not be called after clearCostModel().
void attachRuntimeChecks(VPlan &Plan, GeneratedRTChecks &RTChecks, bool HasBranchWeights) const
Attach the runtime checks of RTChecks to Plan.
unsigned selectInterleaveCount(VPlan &Plan, ElementCount VF, InstructionCost LoopCost)
void emitInvalidCostRemarks(OptimizationRemarkEmitter *ORE)
Emit remarks for recipes with invalid costs in the available VPlans.
LoopVectorizationPlanner(Loop *L, LoopInfo *LI, DominatorTree *DT, const TargetLibraryInfo *TLI, const TargetTransformInfo &TTI, LoopVectorizationLegality *Legal, std::unique_ptr< LoopVectorizationCostModel > CM, VFSelectionContext &Config, InterleavedAccessInfo &IAI, PredicatedScalarEvolution &PSE, OptimizationRemarkEmitter *ORE, std::function< const BranchProbabilityInfo &()> GetBPI)
static bool getDecisionAndClampRange(const std::function< bool(ElementCount)> &Predicate, VFRange &Range)
Test a Predicate on a Range of VF's.
Definition VPlan.cpp:1647
void printPlans(raw_ostream &O)
Definition VPlan.cpp:1837
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.
Utility class for getting and setting loop vectorizer hints in the form of loop metadata.
This class emits a version of the loop where run-time checks ensure that may-alias pointers can't ove...
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
Metadata node.
Definition Metadata.h:1081
This class implements a map that also provides access to all stored values in a deterministic order.
Definition MapVector.h:38
Root of the metadata hierarchy.
Definition Metadata.h:64
The optimization diagnostic interface.
An interface layer with SCEV used to manage how we see SCEV expressions for values in the context of ...
The RecurrenceDescriptor is used to identify recurrences variables in a loop.
This class represents an analyzed expression in the program.
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
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.
TargetCostKind
The kind of cost model.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
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
Holds state needed to make cost decisions before computing costs per-VF, including the maximum VFs.
PredicatedScalarEvolution & getPSE() const
const bool OptForSize
Whether this loop should be optimized for size based on function attribute or profile information.
FixedScalableVFPair computeVPlanOuterloopVF(ElementCount UserVF)
Returns a scalable VF to use for outer-loop vectorization if the target supports it and a fixed VF ot...
bool isInLoopReduction(PHINode *Phi) const
Returns true if the Phi is part of an inloop reduction.
std::pair< unsigned, unsigned > getSmallestAndWidestTypes() const
const TTI::TargetCostKind CostKind
The kind of cost that we are calculating.
bool runtimeChecksRequired()
Check whether vectorization would require runtime checks.
bool isLegalGatherOrScatter(bool IsLoad, Type *ScalarTy, Align Alignment, ElementCount VF) const
Returns true if the target machine supports a gather (if IsLoad) or scatter of scalar type ScalarTy w...
bool isLegalMaskedLoadOrStore(bool IsLoad, Type *ScalarTy, Align Alignment, unsigned AddressSpace) const
Returns true if the target machine supports a masked load (if IsLoad) or masked store of scalar type ...
void collectInLoopReductions()
Split reductions into those that happen in the loop, and those that happen outside.
const TargetTransformInfo & getTTI() const
const SmallPtrSetImpl< PHINode * > & getInLoopReductions() const
Returns the set of in-loop reduction PHIs.
std::optional< unsigned > getMaxSafeElements() const
Return maximum safe number of elements to be processed per vector iteration, which do not prevent sto...
FixedScalableVFPair computeFeasibleMaxVF(unsigned MaxTripCount, ElementCount UserVF, unsigned UserIC, bool FoldTailByMasking, bool RequiresScalarEpilogue)
const MapVector< Instruction *, uint64_t > & getMinimalBitwidths() const
const LoopVectorizeHints & getHints() const
VFSelectionContext(const TargetTransformInfo &TTI, const LoopVectorizationLegality *Legal, const Loop *TheLoop, const Function &F, PredicatedScalarEvolution &PSE, DemandedBits *DB, OptimizationRemarkEmitter *ORE, const LoopVectorizeHints *Hints, bool OptForSize)
bool isEpilogueVectorizationProfitable(ElementCount VF, unsigned IC) const
Returns true if epilogue vectorization is considered profitable for a main loop with vectorization fa...
bool useOrderedReductions(const RecurrenceDescriptor &RdxDesc) const
Returns true if we should use strict in-order reductions for the given RdxDesc.
bool shouldConsiderRegPressureForVF(ElementCount VF) const
void collectElementTypesForWidening(const SmallPtrSetImpl< const Value * > *ValuesToIgnore=nullptr)
Collect element types in the loop that need widening.
std::optional< unsigned > getVScaleForTuning() const
void computeMinimalBitwidths()
Compute smallest bitwidth each instruction can be represented with.
VPBasicBlock serves as the leaf of the Hierarchical Control-Flow Graph.
Definition VPlan.h:4427
RecipeListTy::iterator iterator
Instruction iterators...
Definition VPlan.h:4454
InsertPointGuard(const InsertPointGuard &)=delete
InsertPointGuard & operator=(const InsertPointGuard &)=delete
VPlan-based builder utility analogous to IRBuilder.
VPInstruction * createFirstActiveLane(ArrayRef< VPValue * > Masks, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="")
VPWidenStoreRecipe * createWidenStore(StoreInst &Store, VPValue *Addr, VPValue *StoredVal, VPValue *Mask, bool Consecutive, const VPIRMetadata &Metadata, DebugLoc DL)
Create a recipe widening Store, storing StoredVal to Addr with Mask (may be null).
VPInstruction * createAdd(VPValue *LHS, VPValue *RHS, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="", VPRecipeWithIRFlags::WrapFlagsTy WrapFlags={false, false})
VPInstruction * createOr(VPValue *LHS, VPValue *RHS, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="")
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.
VPInstruction * createSub(VPValue *LHS, VPValue *RHS, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="", VPRecipeWithIRFlags::WrapFlagsTy WrapFlags={false, false})
void setInsertPoint(VPBasicBlock *TheBB, VPBasicBlock::iterator IP)
VPValue * createElementCount(Type *Ty, ElementCount EC)
T * insert(T *R)
Insert R at the current insertion point. Returns R unchanged.
VPInstruction * createLogicalOr(VPValue *LHS, VPValue *RHS, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="")
VPInstruction * createVScale(Type *ResultTy, DebugLoc DL=DebugLoc::getUnknown())
Create a scalar llvm.vscale call.
VPSingleDefRecipe * createConsecutiveVectorPointer(VPValue *Ptr, Type *SourceElementTy, bool Reverse, DebugLoc DL)
Create a vector pointer recipe for a consecutive memory access to Ptr with element type SourceElement...
Definition VPlan.cpp:1662
VPWidenLoadRecipe * createWidenLoad(LoadInst &Load, VPValue *Addr, VPValue *Mask, bool Consecutive, const VPIRMetadata &Metadata, DebugLoc DL)
Create a recipe widening Load, loading from Addr with Mask (may be null).
void restoreIP(VPInsertPoint IP)
Sets the current insert point to a previously-saved location.
VPVectorPointerRecipe * createVectorPointer(VPValue *Ptr, Type *SourceElementTy, VPValue *Stride, GEPNoWrapFlags GEPFlags, DebugLoc DL)
VPInstruction * createNot(VPValue *Operand, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="")
VPInstruction * createAnyOfReduction(VPValue *ChainOp, VPValue *TrueVal, VPValue *FalseVal, DebugLoc DL=DebugLoc::getUnknown())
Create an AnyOf reduction pattern: or-reduce ChainOp, freeze the result, then select between TrueVal ...
Definition VPlan.cpp:1634
void setInsertPoint(const VPInsertPoint &IP)
Set the current insert point.
VPInstruction * createLogicalAnd(VPValue *LHS, VPValue *RHS, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="")
VPInstruction * createScalarCast(Instruction::CastOps Opcode, VPValue *Op, Type *ResultTy, DebugLoc DL, std::optional< VPIRFlags > Flags=std::nullopt, const VPIRMetadata &Metadata={})
VPScalarIVStepsRecipe * createScalarIVSteps(Instruction::BinaryOps InductionOpcode, FPMathOperator *FPBinOp, VPValue *IV, VPValue *Step, VPValue *VF, DebugLoc DL)
VPInstruction * createNoWrapPtrAdd(VPValue *Ptr, VPValue *Offset, GEPNoWrapFlags GEPFlags, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="")
VPInstruction * createFCmp(CmpInst::Predicate Pred, VPValue *A, VPValue *B, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="")
Create a new FCmp VPInstruction with predicate Pred and operands A and B.
VPInstruction * createPtrAdd(VPValue *Ptr, VPValue *Offset, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="")
VPWidenPHIRecipe * createWidenPhi(ArrayRef< VPValue * > IncomingValues, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="")
VPRecipeBase * getRecipeAtInsertPoint() const
Get the recipe at the current insert point or nullptr if the insert point is the end of the block.
VPInstruction * createFreeze(VPValue *Op, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="")
VPValue * createScalarZExtOrTrunc(VPValue *Op, Type *ResultTy, DebugLoc DL)
static VPBuilder getToInsertAfter(VPRecipeBase *R)
Create a VPBuilder to insert after R.
VPInstruction * createNaryOp(unsigned Opcode, ArrayRef< VPValue * > Operands, DebugLoc DL, const Twine &Name="")
VPInstruction * createOverflowingOp(unsigned Opcode, ArrayRef< VPValue * > Operands, VPRecipeWithIRFlags::WrapFlagsTy WrapFlags={false, false}, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="")
VPInstruction * createLastActiveLane(ArrayRef< VPValue * > Masks, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="")
VPDerivedIVRecipe * createDerivedIV(InductionDescriptor::InductionKind Kind, FPMathOperator *FPBinOp, VPValue *Start, VPValue *Current, VPValue *Step, const VPIRFlags::WrapFlagsTy &Flags={})
Convert Current to Start + Current * Step.
VPWidenMemIntrinsicRecipe * createWidenMemIntrinsic(Intrinsic::ID VectorIntrinsicID, ArrayRef< VPValue * > CallArguments, Type *Ty, Align Alignment, const VPIRMetadata &MD, DebugLoc DL)
VPWidenCastRecipe * createWidenCast(Instruction::CastOps Opcode, VPValue *Op, Type *ResultTy)
VPInstruction * createICmp(CmpInst::Predicate Pred, VPValue *A, VPValue *B, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="")
Create a new ICmp VPInstruction with predicate Pred and operands A and B.
VPInstruction * createAnd(VPValue *LHS, VPValue *RHS, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="")
VPInstruction * createScalarIntrinsic(Intrinsic::ID IntrinsicID, ArrayRef< VPValue * > Operands, Type *ResultTy, DebugLoc DL)
Create a scalar call to the intrinsic IntrinsicID with Operands, and result type ResultTy.
VPInstruction * createNaryOp(unsigned Opcode, ArrayRef< VPValue * > Operands, Type *ResultTy, const VPIRFlags &Flags={}, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="")
VPBuilder()=default
VPInstruction * createNaryOp(unsigned Opcode, ArrayRef< VPValue * > Operands, const VPIRFlags &Flags, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="")
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,...
VPExpandSCEVRecipe * createExpandSCEV(const SCEV *Expr)
VPBuilder(VPBasicBlock *TheBB, VPBasicBlock::iterator IP)
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)
Create an N-ary operation with Opcode, Operands and set Inst as its underlying Instruction.
static VPSingleDefRecipe * createSingleScalarOp(unsigned Opcode, ArrayRef< VPValue * > Operands, VPValue *Mask, const VPIRFlags &Flags, const VPIRMetadata &Metadata, DebugLoc DL, Instruction *UV)
Create a single-scalar recipe with Opcode and Operands without inserting it.
VPValue * createScalarSExtOrTrunc(VPValue *Op, Type *ResultTy, DebugLoc DL)
VPInstruction * createWidePtrAdd(VPValue *Ptr, VPValue *Offset, DebugLoc DL=DebugLoc::getUnknown(), const Twine &Name="")
VPBuilder(const VPInsertPoint &IP)
A recipe for converting Current into Start + Current * Step.
Definition VPlan.h:4208
Recipe to expand a SCEV expression.
Definition VPlan.h:4040
Class to record and manage LLVM IR flags.
Definition VPlan.h:704
static LLVM_ABI_FOR_TEST VPIRFlags getDefaultFlags(unsigned Opcode, Type *ResultTy=nullptr)
Returns default flags for Opcode and scalar ResultTy for opcodes that support it, asserts otherwise.
Helper to manage IR metadata for recipes.
Definition VPlan.h:1193
This is a concrete Recipe that models a single VPlan-level instruction.
Definition VPlan.h:1306
@ Intrinsic
Calls a scalar intrinsic. The intrinsic ID is the last operand.
Definition VPlan.h:1427
VPRecipeBase is a base class modeling a sequence of one or more output IR instructions.
Definition VPlan.h:411
Helper class to create VPRecipies from IR instructions.
VPReplicateRecipe replicates a given instruction producing multiple scalar copies of the original sca...
Definition VPlan.h:3410
A recipe for handling phi nodes of integer and floating-point inductions, producing their scalar valu...
Definition VPlan.h:4269
VPSingleDefRecipe is a base class for recipes that model a sequence of one or more output IR that def...
Definition VPlan.h:619
This is the base class of the VPlan Def/Use graph, used for modeling the data flow into,...
Definition VPlanValue.h:50
A recipe to compute the pointers for widened memory accesses of SourceElementTy, with the Stride expr...
Definition VPlan.h:2367
VPWidenCastRecipe is a recipe to create vector cast instructions.
Definition VPlan.h:1890
A recipe for widening vector memory intrinsics.
Definition VPlan.h:2066
A recipe for widened phis.
Definition VPlan.h:2760
VPlan models a candidate for vectorization, encoding various decisions take to produce efficient outp...
Definition VPlan.h:4839
const DataLayout & getDataLayout() const
Definition VPlan.h:5053
LLVMContext & getContext() const
Definition VPlan.h:5049
VPIRValue * getConstantInt(Type *Ty, uint64_t Val, bool IsSigned=false)
Return a VPIRValue wrapping a ConstantInt with the given type and value.
Definition VPlan.h:5155
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:319
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
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.
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
@ Load
The value being inserted comes from a load (InsertElement only).
@ Store
The extracted value is stored (ExtractElement only).
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
unsigned Log2_32(uint32_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition MathExtras.h:326
std::optional< uint64_t > getMaxRuntimeElementCount(ElementCount EC, const Function &F)
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:280
bool hasIrregularType(Type *Ty, const DataLayout &DL)
A helper function that returns true if the given type is irregular.
DWARFExpression::Operation Op
std::optional< unsigned > getMaxVScale(const Function &F)
std::unique_ptr< VPlan > VPlanPtr
Definition VPlan.h:76
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
A class that represents two vectorization factors (initialized with 0 by default).
FixedScalableVFPair(const ElementCount &FixedVF, const ElementCount &ScalableVF)
FixedScalableVFPair(const ElementCount &Max)
static FixedScalableVFPair getNone()
A range of powers-of-2 vectorization factors with fixed start and adjustable end.
Struct to hold various analysis needed for cost computations.
A struct that represents some properties of the register usage of a loop.
A recipe for widening load operations, using the address to load from and an optional mask.
Definition VPlan.h:3827
A recipe for widening store operations, using the stored value, the address to store to and an option...
Definition VPlan.h:3932
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.
bool operator==(const VectorizationFactor &rhs) const
ElementCount Width
Vector width with best cost.
InstructionCost ScalarCost
Cost of the scalar loop.
bool operator!=(const VectorizationFactor &rhs) const
static VectorizationFactor Disabled()
Width 1 means no vectorization, cost 0 means uncomputed cost.
VectorizationFactor(ElementCount Width, InstructionCost Cost, InstructionCost ScalarCost)