LLVM 24.0.0git
LoopVectorizationLegality.h
Go to the documentation of this file.
1//===- llvm/Transforms/Vectorize/LoopVectorizationLegality.h ----*- C++ -*-===//
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 defines the LoopVectorizationLegality class. Original code
11/// in Loop Vectorizer has been moved out to its own file for modularity
12/// and reusability.
13///
14/// Currently, it works for innermost loop vectorization. Extending this to
15/// outer loop vectorization is a TODO item.
16///
17/// Also provides:
18/// 1) LoopVectorizeHints class which keeps a number of loop annotations
19/// locally for easy look up. It has the ability to write them back as
20/// loop metadata, upon request.
21/// 2) LoopVectorizationRequirements class for lazy bail out for the purpose
22/// of reporting useful failure to vectorize message.
23//
24//===----------------------------------------------------------------------===//
25
26#ifndef LLVM_TRANSFORMS_VECTORIZE_LOOPVECTORIZATIONLEGALITY_H
27#define LLVM_TRANSFORMS_VECTORIZE_LOOPVECTORIZATIONLEGALITY_H
28
29#include "llvm/ADT/MapVector.h"
33
34namespace llvm {
35class AssumptionCache;
36class BasicBlock;
38class DemandedBits;
39class DominatorTree;
40class Function;
41class Loop;
42class LoopInfo;
43class Metadata;
49class Type;
50
51/// Utility class for getting and setting loop vectorizer hints in the form
52/// of loop metadata.
53/// This class keeps a number of loop annotations locally (as member variables)
54/// and can, upon request, write them back as metadata on the loop. It will
55/// initially scan the loop for existing metadata, and will update the local
56/// values based on information in the loop.
57/// We cannot write all values to metadata, as the mere presence of some info,
58/// for example 'force', means a decision has been made. So, we need to be
59/// careful NOT to add them if the user hasn't specifically asked so.
61 enum HintKind { HK_WIDTH, HK_INTERLEAVE, HK_ISVECTORIZED, HK_SCALABLE };
62
63 /// Hint - associates name and validation with the hint value.
64 struct Hint {
65 const char *Name;
66 unsigned Value; // This may have to change for non-numeric values.
67 HintKind Kind;
68
69 Hint(const char *Name, unsigned Value, HintKind Kind)
70 : Name(Name), Value(Value), Kind(Kind) {}
71
72 LLVM_ABI bool validate(unsigned Val);
73 };
74
75 /// Vectorization width.
76 Hint Width;
77
78 /// Vectorization interleave factor.
79 Hint Interleave;
80
81 /// Vectorization forced; one of ForceKind. Carried as a plain value because
82 /// the enable/disable pair is a standalone tag with no operand to validate.
83 unsigned Force;
84
85 /// Already Vectorized
86 Hint IsVectorized;
87
88 /// Vector Predicate; one of ForceKind, carried as a plain value like Force.
89 unsigned Predicate;
90
91 /// Says whether we should use fixed width or scalable vectorization.
92 Hint Scalable;
93
94 /// Return the loop metadata prefix.
95 static StringRef Prefix() { return "llvm.loop."; }
96
97 /// True if there is any unsafe math in the loop.
98 bool PotentiallyUnsafe = false;
99
100public:
102 FK_Undefined = -1, ///< Not selected.
103 FK_Disabled = 0, ///< Forcing disabled.
104 FK_Enabled = 1, ///< Forcing enabled.
105 };
106
108 /// Not selected.
110 /// Disables vectorization with scalable vectors.
112 /// Vectorize loops using scalable vectors or fixed-width vectors, but favor
113 /// scalable vectors when the cost-model is inconclusive. This is the
114 /// default when the scalable.enable hint is enabled through a pragma.
116 /// Always vectorize loops using scalable vectors if feasible (i.e. the plan
117 /// has a valid cost and is not restricted by fixed-length dependence
118 /// distances).
120 };
121
122 LLVM_ABI LoopVectorizeHints(const Loop *L, bool InterleaveOnlyWhenForced,
124 const TargetTransformInfo *TTI = nullptr);
125
126 /// Mark the loop L as already vectorized by setting the width to 1.
128
130 bool VectorizeOnlyWhenForced) const;
131
132 /// Dumps all the hint information.
133 LLVM_ABI void emitRemarkWithHints() const;
134
136 return ElementCount::get(
137 Width.Value,
138 (ScalableForceKind)Scalable.Value == SK_PreferScalable ||
139 (ScalableForceKind)Scalable.Value == SK_AlwaysScalable);
140 }
141
142 unsigned getInterleave() const {
143 if (Interleave.Value)
144 return Interleave.Value;
145 // If interleaving is not explicitly set, assume that if we do not want
146 // unrolling, we also don't want any interleaving.
148 return 1;
149 return 0;
150 }
151 unsigned getIsVectorized() const { return IsVectorized.Value; }
152 unsigned getPredicate() const { return Predicate; }
153 enum ForceKind getForce() const {
154 if ((ForceKind)Force == FK_Undefined &&
156 return FK_Disabled;
157 return (ForceKind)Force;
158 }
159
160 /// \return true if scalable vectorization has been explicitly disabled.
162 return (ScalableForceKind)Scalable.Value == SK_FixedWidthOnly;
163 }
164
165 /// \return true if scalable vectorization is always preferred over
166 /// fixed-length when feasible, regardless of cost.
168 return (ScalableForceKind)Scalable.Value == SK_AlwaysScalable;
169 }
170
171 /// When enabling loop hints are provided we allow the vectorizer to change
172 /// the order of operations that is given by the scalar loop. This is not
173 /// enabled by default because can be unsafe or inefficient. For example,
174 /// reordering floating-point operations will change the way round-off
175 /// error accumulates in the loop.
176 LLVM_ABI bool allowReordering() const;
177
178 bool isPotentiallyUnsafe() const {
179 // Avoid FP vectorization if the target is unsure about proper support.
180 // This may be related to the SIMD unit in the target not handling
181 // IEEE 754 FP ops properly, or bad single-to-double promotions.
182 // Otherwise, a sequence of vectorized loops, even without reduction,
183 // could lead to different end results on the destination vectors.
184 return getForce() != LoopVectorizeHints::FK_Enabled && PotentiallyUnsafe;
185 }
186
187 void setPotentiallyUnsafe() { PotentiallyUnsafe = true; }
188
189private:
190 /// Find hints specified in the loop metadata and update local values.
191 void getHintsFromMetadata();
192
193 /// Checks string hint with one operand and set value if valid.
194 void setHint(StringRef Name, Metadata *Arg);
195
196 /// The loop these hints belong to.
197 const Loop *TheLoop;
198
199 /// Interface to emit optimization remarks.
201
202 /// Reports a condition where loop vectorization is disallowed: prints
203 /// \p DebugMsg for debugging purposes along with the corresponding
204 /// optimization remark \p RemarkName, with \p RemarkMsg as the user-facing
205 /// message. The loop \p L is used for the location of the remark.
206 void reportDisallowedVectorization(const StringRef DebugMsg,
207 const StringRef RemarkName,
208 const StringRef RemarkMsg,
209 const Loop *L) const;
210};
211
212/// This holds vectorization requirements that must be verified late in
213/// the process. The requirements are set by legalize and costmodel. Once
214/// vectorization has been determined to be possible and profitable the
215/// requirements can be verified by looking for metadata or compiler options.
216/// For example, some loops require FP commutativity which is only allowed if
217/// vectorization is explicitly specified or if the fast-math compiler option
218/// has been provided.
219/// Late evaluation of these requirements allows helpful diagnostics to be
220/// composed that tells the user what need to be done to vectorize the loop. For
221/// example, by specifying #pragma clang loop vectorize or -ffast-math. Late
222/// evaluation should be used only when diagnostics can generated that can be
223/// followed by a non-expert user.
225public:
226 /// Track the 1st floating-point instruction that can not be reassociated.
228 if (I && !ExactFPMathInst)
229 ExactFPMathInst = I;
230 }
231
232 Instruction *getExactFPInst() { return ExactFPMathInst; }
233
234private:
235 Instruction *ExactFPMathInst = nullptr;
236};
237
238/// This holds details about a histogram operation -- a load -> update -> store
239/// sequence where each lane in a vector might be updating the same element as
240/// another lane.
249
250/// Indicates the characteristics of a loop with an uncountable exit.
251/// * None -- No uncountable exit present.
252/// * ReadOnly -- At least one uncountable exit in a readonly loop.
253/// * ReadWrite -- At least one uncountable exit in a loop with side effects
254/// that may require masking.
256
257/// LoopVectorizationLegality checks if it is legal to vectorize a loop, and
258/// to what vectorization factor.
259/// This class does not look at the profitability of vectorization, only the
260/// legality. This class has two main kinds of checks:
261/// * Memory checks - The code in canVectorizeMemory checks if vectorization
262/// will change the order of memory accesses in a way that will change the
263/// correctness of the program.
264/// * Scalars checks - The code in canVectorizeInstrs and canVectorizeMemory
265/// checks for a number of different conditions, such as the availability of a
266/// single induction variable, that all types are supported and vectorize-able,
267/// etc. This code reflects the capabilities of InnerLoopVectorizer.
268/// This class is also used by InnerLoopVectorizer for identifying
269/// induction variable and the different reduction variables.
271public:
277 AssumptionCache *AC, bool AllowRuntimeSCEVChecks, AAResults *AA)
278 : TheLoop(L), LI(LI), PSE(PSE), TTI(TTI), TLI(TLI), DT(DT), LAIs(LAIs),
279 ORE(ORE), Requirements(R), Hints(H), DB(DB), AC(AC),
280 AllowRuntimeSCEVChecks(AllowRuntimeSCEVChecks), AA(AA) {}
281
282 /// ReductionList contains the reduction descriptors for all
283 /// of the reductions that were found in the loop.
285
286 /// InductionList saves induction variables and maps them to the
287 /// induction descriptor.
289
290 /// RecurrenceSet contains the phi nodes that are recurrences other than
291 /// inductions and reductions.
293
294 /// Returns true if it is legal to vectorize this loop.
295 /// This does not mean that it is profitable to vectorize this
296 /// loop, only that it is legal to do so.
297 /// Temporarily taking UseVPlanNativePath parameter. If true, take
298 /// the new code path being implemented for outer loop vectorization
299 /// (should be functional for inner loop vectorization) based on VPlan.
300 /// If false, good old LV code.
301 LLVM_ABI bool canVectorize(bool UseVPlanNativePath);
302
303 /// Returns true if it is legal to vectorize the FP math operations in this
304 /// loop. Vectorizing is legal if we allow reordering of FP operations, or if
305 /// we can use in-order reductions.
306 LLVM_ABI bool canVectorizeFPMath(bool EnableStrictReductions);
307
308 /// Return true if we can vectorize this loop while folding its tail by
309 /// masking.
310 LLVM_ABI bool canFoldTailByMasking() const;
311
312 /// Mark all respective loads/stores for masking. Must only be called when
313 /// tail-folding is possible.
315
316 /// Returns the primary induction variable.
317 PHINode *getPrimaryInduction() { return PrimaryInduction; }
318
319 /// Returns the reduction variables found in the loop.
320 const ReductionList &getReductionVars() const { return Reductions; }
321
322 /// Returns the recurrence descriptor associated with a given phi node \p PN,
323 /// expecting one to exist.
326 "only reductions have recurrence descriptors");
327 return Reductions.find(PN)->second;
328 }
329
330 /// Returns the induction variables found in the loop.
331 const InductionList &getInductionVars() const { return Inductions; }
332
333 /// Return the fixed-order recurrences found in the loop.
334 RecurrenceSet &getFixedOrderRecurrences() { return FixedOrderRecurrences; }
335
336 /// Returns the widest induction type.
337 IntegerType *getWidestInductionType() { return WidestIndTy; }
338
339 /// Returns True if given store is a final invariant store of one of the
340 /// reductions found in the loop.
342
343 /// Returns True if given address is invariant and is used to store recurrent
344 /// expression
346
347 /// Returns True if V is a Phi node of an induction variable in this loop.
348 LLVM_ABI bool isInductionPhi(const Value *V) const;
349
350 /// Returns True if V is a cast that is part of an induction def-use chain,
351 /// and had been proven to be redundant under a runtime guard (in other
352 /// words, the cast has the same SCEV expression as the induction phi).
353 LLVM_ABI bool isCastedInductionVariable(const Value *V) const;
354
355 /// Returns True if V can be considered as an induction variable in this
356 /// loop. V can be the induction phi, or some redundant cast in the def-use
357 /// chain of the inducion phi.
358 LLVM_ABI bool isInductionVariable(const Value *V) const;
359
360 /// Returns True if PN is a reduction variable in this loop.
361 bool isReductionVariable(PHINode *PN) const { return Reductions.count(PN); }
362
363 /// Returns True if Phi is a fixed-order recurrence in this loop.
364 LLVM_ABI bool isFixedOrderRecurrence(const PHINode *Phi) const;
365
366 /// Return true if the block BB needs to be predicated in order for the loop
367 /// to be vectorized.
368 LLVM_ABI bool blockNeedsPredication(const BasicBlock *BB) const;
369
370 /// Add unit stride predicates for memory accesses to PSE, if runtime checks
371 /// are allowed and an inner loop is vectorized.
373
374 /// Check if this pointer is consecutive when vectorizing. This happens
375 /// when the last index of the GEP is the induction variable, or that the
376 /// pointer itself is an induction variable.
377 /// This check allows us to vectorize A[idx] into a wide load/store.
378 /// Returns:
379 /// 0 - Stride is unknown or non-consecutive.
380 /// 1 - Address is consecutive.
381 /// -1 - Address is consecutive, and decreasing.
382 /// NOTE: This method must only be used before modifying the original scalar
383 /// loop. Do not use after invoking 'createVectorizedLoopSkeleton' (PR34965).
384 LLVM_ABI int isConsecutivePtr(Type *AccessTy, Value *Ptr) const;
385
386 /// Returns true if \p V is invariant across all loop iterations according to
387 /// SCEV.
388 LLVM_ABI bool isInvariant(Value *V) const;
389
390 /// Returns true if value V is uniform across \p VF lanes, when \p VF is
391 /// provided, and otherwise if \p V is invariant across all loop iterations.
392 LLVM_ABI bool isUniform(Value *V, std::optional<ElementCount> VF) const;
393
394 /// A uniform memory op is a load or store which accesses the same memory
395 /// location on all \p VF lanes, if \p VF is provided and otherwise if the
396 /// memory location is invariant.
398 std::optional<ElementCount> VF) const;
399
400 /// Returns the information that we collected about runtime memory check.
402 return LAI->getRuntimePointerChecking();
403 }
404
405 const LoopAccessInfo *getLAI() const { return LAI; }
406
408 return LAI->getDepChecker().isSafeForAnyVectorWidth() &&
409 LAI->getDepChecker().isSafeForAnyStoreLoadForwardDistances();
410 }
411
413 return LAI->getDepChecker().getMaxSafeVectorWidthInBits();
414 }
415
416 /// Returns information about whether this loop contains at least one
417 /// uncountable early exit, and if so, if it also contains instructions (such
418 /// as stores) that cause side-effects.
420 return UncountableExitType;
421 }
422
423 /// Returns true if the loop has uncountable early exits, i.e. uncountable
424 /// exits that aren't the latch block.
428
429 /// Returns true if this is an early exit loop with state-changing or
430 /// potentially-faulting operations and the condition for the uncountable
431 /// exit must be determined before any of the state changes or potentially
432 /// faulting operations take place.
436
437 /// Return true if there is store-load forwarding dependencies.
439 return LAI->getDepChecker().isSafeForAnyStoreLoadForwardDistances();
440 }
441
442 /// Return safe power-of-2 number of elements, which do not prevent store-load
443 /// forwarding and safe to operate simultaneously.
445 return LAI->getDepChecker().getStoreLoadForwardSafeDistanceInBits();
446 }
447
448 /// Returns true if instruction \p I requires a mask for vectorization.
449 /// This accounts for both control flow masking (conditionally executed
450 /// blocks) and tail-folding masking (predicated loop vectorization).
451 bool isMaskRequired(const Instruction *I, bool TailFolded) const {
452 if (TailFolded)
453 return TailFoldedMaskedOp.contains(I);
454 return ConditionallyExecutedOps.contains(I);
455 }
456
457 /// Returns true if there is at least one function call in the loop which
458 /// has a vectorized variant available.
459 bool hasVectorCallVariants() const { return VecCallVariantsFound; }
460
461 unsigned getNumStores() const { return LAI->getNumStores(); }
462 unsigned getNumLoads() const { return LAI->getNumLoads(); }
463
464 /// Returns a HistogramInfo* for the given instruction if it was determined
465 /// to be part of a load -> update -> store sequence where multiple lanes
466 /// may be working on the same memory address.
467 std::optional<const HistogramInfo *> getHistogramInfo(Instruction *I) const {
468 for (const HistogramInfo &HGram : Histograms)
469 if (HGram.Load == I || HGram.Update == I || HGram.Store == I)
470 return &HGram;
471
472 return std::nullopt;
473 }
474
475 /// Returns a list of all known histogram operations in the loop.
476 bool hasHistograms() const { return !Histograms.empty(); }
477
481
482 Loop *getLoop() const { return TheLoop; }
483
484 LoopInfo *getLoopInfo() const { return LI; }
485
486 AssumptionCache *getAssumptionCache() const { return AC; }
487
488 ScalarEvolution *getScalarEvolution() const { return PSE.getSE(); }
489
490 DominatorTree *getDominatorTree() const { return DT; }
491
492 /// Returns all exiting blocks with a countable exit, i.e. the
493 /// exit-not-taken count is known exactly at compile time.
495 return CountableExitingBlocks;
496 }
497
498private:
499 /// Return true if the pre-header, exiting and latch blocks of \p Lp and all
500 /// its nested loops are considered legal for vectorization. These legal
501 /// checks are common for inner and outer loop vectorization.
502 /// Temporarily taking UseVPlanNativePath parameter. If true, take
503 /// the new code path being implemented for outer loop vectorization
504 /// (should be functional for inner loop vectorization) based on VPlan.
505 /// If false, good old LV code.
506 bool canVectorizeLoopNestCFG(Loop *Lp, bool UseVPlanNativePath);
507
508 /// Set up outer loop inductions by checking Phis in outer loop header for
509 /// supported inductions (int inductions). Return false if any of these Phis
510 /// is not a supported induction or if we fail to find an induction.
511 bool setupOuterLoopInductions();
512
513 /// Return true if the pre-header, exiting and latch blocks of \p Lp
514 /// (non-recursive) are considered legal for vectorization.
515 /// Temporarily taking UseVPlanNativePath parameter. If true, take
516 /// the new code path being implemented for outer loop vectorization
517 /// (should be functional for inner loop vectorization) based on VPlan.
518 /// If false, good old LV code.
519 bool canVectorizeLoopCFG(Loop *Lp, bool UseVPlanNativePath) const;
520
521 /// Check if a single basic block loop is vectorizable.
522 /// At this point we know that this is a loop with a constant trip count
523 /// and we only need to check individual instructions.
524 bool canVectorizeInstrs();
525
526 /// Check if an individual instruction is vectorizable.
527 bool canVectorizeInstr(Instruction &I);
528
529 /// When we vectorize loops we may change the order in which
530 /// we read and write from memory. This method checks if it is
531 /// legal to vectorize the code, considering only memory constrains.
532 /// Returns true if the loop is vectorizable
533 bool canVectorizeMemory();
534
535 /// If LAA cannot determine whether all dependences are safe, we may be able
536 /// to further analyse some IndirectUnsafe dependences and if they match a
537 /// certain pattern (like a histogram) then we may still be able to vectorize.
538 bool canVectorizeIndirectUnsafeDependences();
539
540 /// Return true if we can vectorize this loop using the IF-conversion
541 /// transformation.
542 bool canVectorizeWithIfConvert();
543
544 /// Return true if we can vectorize this outer loop. The method performs
545 /// specific checks for outer loop vectorization.
546 bool canVectorizeOuterLoop();
547
548 /// Returns true if this is an early exit loop that can be vectorized.
549 /// Currently, a loop with an uncountable early exit is considered
550 /// vectorizable if:
551 /// 1. Writes to memory will access different underlying objects than
552 /// any load used as part of the uncountable exit condition.
553 /// 2. The loop has only one early uncountable exit
554 /// 3. The early exit block dominates the latch block.
555 /// 4. The latch block has an exact exit count.
556 /// 5. The loop does not contain reductions or recurrences.
557 /// 6. We can prove at compile-time that loops will not contain faulting
558 /// loads, or that any faulting loads would also occur in a purely
559 /// scalar loop.
560 /// 7. It is safe to speculatively execute instructions such as divide or
561 /// call instructions.
562 /// The list above is not based on theoretical limitations of vectorization,
563 /// but simply a statement that more work is needed to support these
564 /// additional cases safely.
565 bool isVectorizableEarlyExitLoop();
566
567 /// When vectorizing an early exit loop containing side effects, we need to
568 /// determine whether an uncounted exit will be taken before any operation
569 /// that has side effects.
570 ///
571 /// Consider a loop like the following:
572 /// for (int i = 0; i < N; ++i) {
573 /// a[i] = b[i];
574 /// if (c[i] == 0)
575 /// break;
576 /// }
577 ///
578 /// We have both a load and a store operation occurring before the condition
579 /// is checked for early termination. We could potentially restrict
580 /// vectorization to cases where we know all addresses are guaranteed to be
581 /// dereferenceable, which would allow the load before the condition check to
582 /// be vectorized.
583 ///
584 /// The store, however, should not execute across all lanes if early
585 /// termination occurs before the end of the vector. We must only store to the
586 /// locations that would have been stored to by a scalar loop. So we need to
587 /// know what the result of 'c[i] == 0' is before performing the vector store,
588 /// with or without masking.
589 ///
590 /// We can either do this by moving the condition load to the top of the
591 /// vector body and using the comparison to create masks for other operations
592 /// in the loop, or by looking ahead one vector iteration and bailing out to
593 /// the scalar loop if an exit would occur.
594 ///
595 /// Using the latter approach (applicable to more targets), we need to hoist
596 /// the first load (of c[0]) out of the loop then rotate the load within the
597 /// loop to the next iteration, remembering to adjust the vector trip count.
598 /// Something like the following:
599 ///
600 /// vec.ph:
601 /// %ci.0 = load <4 x i32>, ptr %c
602 /// %cmp.0 = icmp eq <4 x i32> %ci.0, zeroinitializer
603 /// %any.of.0 = call i1 @llvm.vector.reduce.or.v4i1(<4 x i1> %cmp.0)
604 /// br i1 %any.of.0, label %scalar.ph, label %vec.body
605 /// vec.body:
606 /// %iv = phi...
607 /// phi for c[i] if used elsewhere in the loop...
608 /// other operations in the loop...
609 /// %iv.next = add i64 %iv, 4
610 /// %addr.next = getelementptr i32, ptr %c, i64 %iv.next
611 /// %ci.next = load <4 x i32>, ptr %addr.next
612 /// %cmp.next = icmp eq <4 x i32> %ci.next, zeroinitializer
613 /// %any.of.next = call i1 @llvm.vector.reduce.or.v4i1(<4 x i1> %cmp.next)
614 /// iv.next compared with shortened vector tripcount...
615 /// uncountable condition combined with counted condition...
616 /// br...
617 ///
618 /// Doing this means the last few iterations will always be performed by a
619 /// scalar loop regardless of which exit is taken, and so vector iterations
620 /// will never execute a memory operation to a location that the scalar loop
621 /// would not have.
622 ///
623 /// This means we must ensure that it is safe to move the load for 'c[i]'
624 /// before other memory operations (or any other observable side effects) in
625 /// the loop.
626 ///
627 /// Currently, c[i] must have only one user (the comparison used for the
628 /// uncountable exit) since we would otherwise need to introduce a PHI node
629 /// for it.
630 bool canUncountableExitConditionLoadBeMoved(BasicBlock *ExitingBlock);
631
632 /// Return true if all of the instructions in the block can be speculatively
633 /// executed, and record the loads/stores that require masking.
634 /// \p SafePtrs is a list of addresses that are known to be legal and we know
635 /// that we can read from them without segfault.
636 /// \p MaskedOp is a list of instructions that have to be transformed into
637 /// calls to the appropriate masked intrinsic when the loop is vectorized
638 /// or dropped if the instruction is a conditional assume intrinsic.
639 bool
640 blockCanBePredicated(BasicBlock *BB, SmallPtrSetImpl<Value *> &SafePtrs,
642
643 /// Updates the vectorization state by adding \p Phi to the inductions list.
644 /// This can set \p Phi as the main induction of the loop if \p Phi is a
645 /// better choice for the main induction than the existing one.
646 void addInductionPhi(PHINode *Phi, const InductionDescriptor &ID);
647
648 /// The loop that we evaluate.
649 Loop *TheLoop;
650
651 /// Loop Info analysis.
652 LoopInfo *LI;
653
654 /// A wrapper around ScalarEvolution used to add runtime SCEV checks.
655 /// Applies dynamic knowledge to simplify SCEV expressions in the context
656 /// of existing SCEV assumptions. The analysis will also add a minimal set
657 /// of new predicates if this is required to enable vectorization and
658 /// unrolling.
660
661 /// Target Transform Info.
663
664 /// Target Library Info.
666
667 /// Dominator Tree.
668 DominatorTree *DT;
669
670 // LoopAccess analysis.
672
673 const LoopAccessInfo *LAI = nullptr;
674
675 /// Interface to emit optimization remarks.
677
678 // --- vectorization state --- //
679
680 /// Holds the primary induction variable. This is the counter of the
681 /// loop.
682 PHINode *PrimaryInduction = nullptr;
683
684 /// Holds the reduction variables.
686
687 /// Holds all of the induction variables that we found in the loop.
688 /// Notice that inductions don't need to start at zero and that induction
689 /// variables can be pointers.
690 InductionList Inductions;
691
692 /// Holds all the casts that participate in the update chain of the induction
693 /// variables, and that have been proven to be redundant (possibly under a
694 /// runtime guard). These casts can be ignored when creating the vectorized
695 /// loop body.
696 SmallPtrSet<Instruction *, 4> InductionCastsToIgnore;
697
698 /// Holds the phi nodes that are fixed-order recurrences.
699 RecurrenceSet FixedOrderRecurrences;
700
701 /// Holds the widest induction type encountered.
702 IntegerType *WidestIndTy = nullptr;
703
704 /// Vectorization requirements that will go through late-evaluation.
705 LoopVectorizationRequirements *Requirements;
706
707 /// Used to emit an analysis of any legality issues.
708 LoopVectorizeHints *Hints;
709
710 /// The demanded bits analysis is used to compute the minimum type size in
711 /// which a reduction can be computed.
712 DemandedBits *DB;
713
714 /// The assumption cache analysis is used to compute the minimum type size in
715 /// which a reduction can be computed.
716 AssumptionCache *AC;
717
718 /// Instructions that require masking because they are in source-level
719 /// conditionally executed blocks.
720 SmallPtrSet<const Instruction *, 8> ConditionallyExecutedOps;
721 /// Instructions that require masking only due to tail-folding predication.
722 SmallPtrSet<const Instruction *, 8> TailFoldedMaskedOp;
723
724 /// Contains all identified histogram operations, which are sequences of
725 /// load -> update -> store instructions where multiple lanes in a vector
726 /// may work on the same memory location.
728
729 /// Whether or not creating SCEV predicates is allowed.
730 bool AllowRuntimeSCEVChecks;
731
732 // Alias Analysis results used to check for possible aliasing with loads
733 // used in uncountable exit conditions.
734 AAResults *AA;
735
736 /// If we discover function calls within the loop which have a valid
737 /// vectorized variant, record that fact so that LoopVectorize can
738 /// (potentially) make a better decision on the maximum VF and enable
739 /// the use of those function variants.
740 bool VecCallVariantsFound = false;
741
742 /// Keep track of all the countable and uncountable exiting blocks if
743 /// the exact backedge taken count is not computable.
744 SmallVector<BasicBlock *, 4> CountableExitingBlocks;
745
746 /// Records whether we have an uncountable early exit in a loop that's
747 /// either read-only or read-write.
749};
750
751} // namespace llvm
752
753#endif // LLVM_TRANSFORMS_VECTORIZE_LOOPVECTORIZATIONLEGALITY_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
#define LLVM_ABI
Definition Compiler.h:215
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define H(x, y, z)
Definition MD5.cpp:56
This file implements a map that provides insertion order iteration.
A cache of @llvm.assume calls within a function.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
static constexpr ElementCount get(ScalarTy MinVal, bool Scalable)
Definition TypeSize.h:315
A struct for saving information about induction variables.
Class to represent integer types.
An instruction for reading from memory.
Drive the analysis of memory accesses in the loop.
MapVector< PHINode *, InductionDescriptor > InductionList
InductionList saves induction variables and maps them to the induction descriptor.
LLVM_ABI bool isInvariantStoreOfReduction(StoreInst *SI)
Returns True if given store is a final invariant store of one of the reductions found in the loop.
bool hasVectorCallVariants() const
Returns true if there is at least one function call in the loop which has a vectorized variant availa...
LLVM_ABI void collectUnitStridePredicates() const
Add unit stride predicates for memory accesses to PSE, if runtime checks are allowed and an inner loo...
const RecurrenceDescriptor & getRecurrenceDescriptor(PHINode *PN) const
Returns the recurrence descriptor associated with a given phi node PN, expecting one to exist.
RecurrenceSet & getFixedOrderRecurrences()
Return the fixed-order recurrences found in the loop.
uint64_t getMaxStoreLoadForwardSafeDistanceInBits() const
Return safe power-of-2 number of elements, which do not prevent store-load forwarding and safe to ope...
LLVM_ABI bool isInvariantAddressOfReduction(Value *V)
Returns True if given address is invariant and is used to store recurrent expression.
LLVM_ABI bool canVectorize(bool UseVPlanNativePath)
Returns true if it is legal to vectorize this loop.
PredicatedScalarEvolution * getPredicatedScalarEvolution() const
LLVM_ABI bool blockNeedsPredication(const BasicBlock *BB) const
Return true if the block BB needs to be predicated in order for the loop to be vectorized.
LLVM_ABI int isConsecutivePtr(Type *AccessTy, Value *Ptr) const
Check if this pointer is consecutive when vectorizing.
AssumptionCache * getAssumptionCache() const
std::optional< const HistogramInfo * > getHistogramInfo(Instruction *I) const
Returns a HistogramInfo* for the given instruction if it was determined to be part of a load -> updat...
SmallPtrSet< const PHINode *, 8 > RecurrenceSet
RecurrenceSet contains the phi nodes that are recurrences other than inductions and reductions.
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.
bool isReductionVariable(PHINode *PN) const
Returns True if PN is a reduction variable in this loop.
LLVM_ABI bool isFixedOrderRecurrence(const PHINode *Phi) const
Returns True if Phi is a fixed-order recurrence in this loop.
IntegerType * getWidestInductionType()
Returns the widest induction type.
LLVM_ABI bool isInductionPhi(const Value *V) const
Returns True if V is a Phi node of an induction variable in this loop.
PHINode * getPrimaryInduction()
Returns the primary induction variable.
UncountableExitTrait getUncountableExitTrait() const
Returns information about whether this loop contains at least one uncountable early exit,...
const SmallVector< BasicBlock *, 4 > & getCountableExitingBlocks() const
Returns all exiting blocks with a countable exit, i.e.
const InductionList & getInductionVars() const
Returns the induction variables found in the loop.
LLVM_ABI bool isInvariant(Value *V) const
Returns true if V is invariant across all loop iterations according to SCEV.
const ReductionList & getReductionVars() const
Returns the reduction variables found in the loop.
bool isSafeForAnyStoreLoadForwardDistances() const
Return true if there is store-load forwarding dependencies.
LLVM_ABI bool canFoldTailByMasking() const
Return true if we can vectorize this loop while folding its tail by masking.
LLVM_ABI void prepareToFoldTailByMasking()
Mark all respective loads/stores for masking.
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
MapVector< PHINode *, RecurrenceDescriptor > ReductionList
ReductionList contains the reduction descriptors for all of the reductions that were found in the loo...
ScalarEvolution * getScalarEvolution() const
bool isMaskRequired(const Instruction *I, bool TailFolded) const
Returns true if instruction I requires a mask for vectorization.
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...
LoopVectorizationLegality(Loop *L, PredicatedScalarEvolution &PSE, DominatorTree *DT, TargetTransformInfo *TTI, TargetLibraryInfo *TLI, Function *F, LoopAccessInfoManager &LAIs, LoopInfo *LI, OptimizationRemarkEmitter *ORE, LoopVectorizationRequirements *R, LoopVectorizeHints *H, DemandedBits *DB, AssumptionCache *AC, bool AllowRuntimeSCEVChecks, AAResults *AA)
const RuntimePointerChecking * getRuntimePointerChecking() const
Returns the information that we collected about runtime memory check.
LLVM_ABI bool isInductionVariable(const Value *V) const
Returns True if V can be considered as an induction variable in this loop.
LLVM_ABI bool isCastedInductionVariable(const Value *V) const
Returns True if V is a cast that is part of an induction def-use chain, and had been proven to be red...
This holds vectorization requirements that must be verified late in the process.
void addExactFPMathInst(Instruction *I)
Track the 1st floating-point instruction that can not be reassociated.
Utility class for getting and setting loop vectorizer hints in the form of loop metadata.
@ SK_PreferScalable
Vectorize loops using scalable vectors or fixed-width vectors, but favor scalable vectors when the co...
@ SK_AlwaysScalable
Always vectorize loops using scalable vectors if feasible (i.e.
@ SK_FixedWidthOnly
Disables vectorization with scalable vectors.
LLVM_ABI bool allowVectorization(Function *F, Loop *L, bool VectorizeOnlyWhenForced) const
LLVM_ABI bool allowReordering() const
When enabling loop hints are provided we allow the vectorizer to change the order of operations that ...
LLVM_ABI void emitRemarkWithHints() const
Dumps all the hint information.
LLVM_ABI void setAlreadyVectorized()
Mark the loop L as already vectorized by setting the width to 1.
LLVM_ABI LoopVectorizeHints(const Loop *L, bool InterleaveOnlyWhenForced, OptimizationRemarkEmitter &ORE, const TargetTransformInfo *TTI=nullptr)
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
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 ...
Analysis providing profile information.
The RecurrenceDescriptor is used to identify recurrences variables in a loop.
Holds information about the memory runtime legality checks to verify that a group of pointers do not ...
The main scalar evolution driver.
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.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
LLVM Value Representation.
Definition Value.h:75
Abstract Attribute helper functions.
Definition Attributor.h:165
This is an optimization pass for GlobalISel generic memory operations.
UncountableExitTrait
Indicates the characteristics of a loop with an uncountable exit.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
LLVM_ABI bool hasDisableAllTransformsHint(const Loop *L)
Look for the loop attribute that disables all transformation heuristic.
LLVM_ABI TransformationMode hasUnrollTransformation(const Loop *L)
TargetTransformInfo TTI
@ TM_Disable
The transformation should not be applied.
Definition LoopUtils.h:292
This holds details about a histogram operation – a load -> update -> store sequence where each lane i...
HistogramInfo(LoadInst *Load, Instruction *Update, StoreInst *Store)