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