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