LLVM 22.0.0git
LoopUtils.h
Go to the documentation of this file.
1//===- llvm/Transforms/Utils/LoopUtils.h - Loop utilities -------*- 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// This file defines some loop transformation utilities.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_TRANSFORMS_UTILS_LOOPUTILS_H
14#define LLVM_TRANSFORMS_UTILS_LOOPUTILS_H
15
21
22namespace llvm {
23
24template <typename T> class DomTreeNodeBase;
26class AssumptionCache;
27class StringRef;
28class AnalysisUsage;
29class TargetTransformInfo;
30class AAResults;
31class BasicBlock;
32class ICFLoopSafetyInfo;
33class IRBuilderBase;
34class Loop;
35class LoopInfo;
36class MemoryAccess;
37class MemorySSA;
38class MemorySSAUpdater;
39class OptimizationRemarkEmitter;
40class PredIteratorCache;
41class ScalarEvolution;
42class SCEV;
43class SCEVExpander;
44class TargetLibraryInfo;
45class LPPassManager;
46class Instruction;
47struct RuntimeCheckingPtrGroup;
48typedef std::pair<const RuntimeCheckingPtrGroup *,
49 const RuntimeCheckingPtrGroup *>
51
52template <typename T, unsigned N> class SmallSetVector;
53template <typename T, unsigned N> class SmallPriorityWorklist;
54
55LLVM_ABI BasicBlock *InsertPreheaderForLoop(Loop *L, DominatorTree *DT,
56 LoopInfo *LI,
57 MemorySSAUpdater *MSSAU,
58 bool PreserveLCSSA);
59
60/// Ensure that all exit blocks of the loop are dedicated exits.
61///
62/// For any loop exit block with non-loop predecessors, we split the loop
63/// predecessors to use a dedicated loop exit block. We update the dominator
64/// tree and loop info if provided, and will preserve LCSSA if requested.
65LLVM_ABI bool formDedicatedExitBlocks(Loop *L, DominatorTree *DT, LoopInfo *LI,
66 MemorySSAUpdater *MSSAU,
67 bool PreserveLCSSA);
68
69/// Ensures LCSSA form for every instruction from the Worklist in the scope of
70/// innermost containing loop.
71///
72/// For the given instruction which have uses outside of the loop, an LCSSA PHI
73/// node is inserted and the uses outside the loop are rewritten to use this
74/// node.
75///
76/// LoopInfo and DominatorTree are required and, since the routine makes no
77/// changes to CFG, preserved.
78///
79/// Returns true if any modifications are made.
80///
81/// This function may introduce unused PHI nodes. If \p PHIsToRemove is not
82/// nullptr, those are added to it (before removing, the caller has to check if
83/// they still do not have any uses). Otherwise the PHIs are directly removed.
84///
85/// If \p InsertedPHIs is not nullptr, inserted phis will be added to this
86/// vector.
87LLVM_ABI bool
88formLCSSAForInstructions(SmallVectorImpl<Instruction *> &Worklist,
89 const DominatorTree &DT, const LoopInfo &LI,
90 ScalarEvolution *SE,
91 SmallVectorImpl<PHINode *> *PHIsToRemove = nullptr,
92 SmallVectorImpl<PHINode *> *InsertedPHIs = nullptr);
93
94/// Put loop into LCSSA form.
95///
96/// Looks at all instructions in the loop which have uses outside of the
97/// current loop. For each, an LCSSA PHI node is inserted and the uses outside
98/// the loop are rewritten to use this node. Sub-loops must be in LCSSA form
99/// already.
100///
101/// LoopInfo and DominatorTree are required and preserved.
102///
103/// If ScalarEvolution is passed in, it will be preserved.
104///
105/// Returns true if any modifications are made to the loop.
106LLVM_ABI bool formLCSSA(Loop &L, const DominatorTree &DT, const LoopInfo *LI,
107 ScalarEvolution *SE);
108
109/// Put a loop nest into LCSSA form.
110///
111/// This recursively forms LCSSA for a loop nest.
112///
113/// LoopInfo and DominatorTree are required and preserved.
114///
115/// If ScalarEvolution is passed in, it will be preserved.
116///
117/// Returns true if any modifications are made to the loop.
118LLVM_ABI bool formLCSSARecursively(Loop &L, const DominatorTree &DT,
119 const LoopInfo *LI, ScalarEvolution *SE);
120
121/// Flags controlling how much is checked when sinking or hoisting
122/// instructions. The number of memory access in the loop (and whether there
123/// are too many) is determined in the constructors when using MemorySSA.
125public:
126 // Explicitly set limits.
129 bool IsSink, Loop &L, MemorySSA &MSSA);
130 // Use default limits.
132
133 void setIsSink(bool B) { IsSink = B; }
134 bool getIsSink() { return IsSink; }
138
139protected:
140 bool NoOfMemAccTooLarge = false;
141 unsigned LicmMssaOptCounter = 0;
144 bool IsSink;
145};
146
147/// Walk the specified region of the CFG (defined by all blocks
148/// dominated by the specified block, and that are in the current loop) in
149/// reverse depth first order w.r.t the DominatorTree. This allows us to visit
150/// uses before definitions, allowing us to sink a loop body in one pass without
151/// iteration. Takes DomTreeNode, AAResults, LoopInfo, DominatorTree,
152/// TargetLibraryInfo, Loop, AliasSet information for all
153/// instructions of the loop and loop safety information as
154/// arguments. Diagnostics is emitted via \p ORE. It returns changed status.
155/// \p CurLoop is a loop to do sinking on. \p OutermostLoop is used only when
156/// this function is called by \p sinkRegionForLoopNest.
159 TargetTransformInfo *, Loop *CurLoop,
162 Loop *OutermostLoop = nullptr);
163
164/// Call sinkRegion on loops contained within the specified loop
165/// in order from innermost to outermost.
172
173/// Walk the specified region of the CFG (defined by all blocks
174/// dominated by the specified block, and that are in the current loop) in depth
175/// first order w.r.t the DominatorTree. This allows us to visit definitions
176/// before uses, allowing us to hoist a loop body in one pass without iteration.
177/// Takes DomTreeNode, AAResults, LoopInfo, DominatorTree,
178/// TargetLibraryInfo, Loop, AliasSet information for all
179/// instructions of the loop and loop safety information as arguments.
180/// Diagnostics is emitted via \p ORE. It returns changed status.
181/// \p AllowSpeculation is whether values should be hoisted even if they are not
182/// guaranteed to execute in the loop, but are safe to speculatively execute.
188 bool, bool AllowSpeculation,
189 bool HasCoroSuspendInst = false);
190
191/// Return true if the induction variable \p IV in a Loop whose latch is
192/// \p LatchBlock would become dead if the exit test \p Cond were removed.
193/// Conservatively returns false if analysis is insufficient.
195
196/// This function deletes dead loops. The caller of this function needs to
197/// guarantee that the loop is infact dead.
198/// The function requires a bunch or prerequisites to be present:
199/// - The loop needs to be in LCSSA form
200/// - The loop needs to have a Preheader
201/// - A unique dedicated exit block must exist
202///
203/// This also updates the relevant analysis information in \p DT, \p SE, \p LI
204/// and \p MSSA if pointers to those are provided.
205/// It also updates the loop PM if an updater struct is provided.
206
208 LoopInfo *LI, MemorySSA *MSSA = nullptr);
209
210/// Remove the backedge of the specified loop. Handles loop nests and general
211/// loop structures subject to the precondition that the loop has no parent
212/// loop and has a single latch block. Preserves all listed analyses.
214 LoopInfo &LI, MemorySSA *MSSA);
215
216/// Try to promote memory values to scalars by sinking stores out of
217/// the loop and moving loads to before the loop. We do this by looping over
218/// the stores in the loop, looking for stores to Must pointers which are
219/// loop invariant. It takes a set of must-alias values, Loop exit blocks
220/// vector, loop exit blocks insertion point vector, PredIteratorCache,
221/// LoopInfo, DominatorTree, Loop, AliasSet information for all instructions
222/// of the loop and loop safety information as arguments.
223/// Diagnostics is emitted via \p ORE. It returns changed status.
224/// \p AllowSpeculation is whether values should be hoisted even if they are not
225/// guaranteed to execute in the loop, but are safe to speculatively execute.
232 bool AllowSpeculation, bool HasReadsOutsideSet);
233
234/// Does a BFS from a given node to all of its children inside a given loop.
235/// The returned vector of basic blocks includes the starting point.
238
239/// Returns the instructions that use values defined in the loop.
241
242/// Find a combination of metadata ("llvm.loop.vectorize.width" and
243/// "llvm.loop.vectorize.scalable.enable") for a loop and use it to construct a
244/// ElementCount. If the metadata "llvm.loop.vectorize.width" cannot be found
245/// then std::nullopt is returned.
246LLVM_ABI std::optional<ElementCount>
248
249/// Create a new loop identifier for a loop created from a loop transformation.
250///
251/// @param OrigLoopID The loop ID of the loop before the transformation.
252/// @param FollowupAttrs List of attribute names that contain attributes to be
253/// added to the new loop ID.
254/// @param InheritOptionsAttrsPrefix Selects which attributes should be inherited
255/// from the original loop. The following values
256/// are considered:
257/// nullptr : Inherit all attributes from @p OrigLoopID.
258/// "" : Do not inherit any attribute from @p OrigLoopID; only use
259/// those specified by a followup attribute.
260/// "<prefix>": Inherit all attributes except those which start with
261/// <prefix>; commonly used to remove metadata for the
262/// applied transformation.
263/// @param AlwaysNew If true, do not try to reuse OrigLoopID and never return
264/// std::nullopt.
265///
266/// @return The loop ID for the after-transformation loop. The following values
267/// can be returned:
268/// std::nullopt : No followup attribute was found; it is up to the
269/// transformation to choose attributes that make sense.
270/// @p OrigLoopID: The original identifier can be reused.
271/// nullptr : The new loop has no attributes.
272/// MDNode* : A new unique loop identifier.
273LLVM_ABI std::optional<MDNode *>
274makeFollowupLoopID(MDNode *OrigLoopID, ArrayRef<StringRef> FollowupAttrs,
275 const char *InheritOptionsAttrsPrefix = "",
276 bool AlwaysNew = false);
277
278/// Look for the loop attribute that disables all transformation heuristic.
280
281/// Look for the loop attribute that disables the LICM transformation heuristics.
283
284/// The mode sets how eager a transformation should be applied.
286 /// The pass can use heuristics to determine whether a transformation should
287 /// be applied.
289
290 /// The transformation should be applied without considering a cost model.
292
293 /// The transformation should not be applied.
295
296 /// Force is a flag and should not be used alone.
297 TM_Force = 0x04,
298
299 /// The transformation was directed by the user, e.g. by a #pragma in
300 /// the source code. If the transformation could not be applied, a
301 /// warning should be emitted.
303
304 /// The transformation must not be applied. For instance, `#pragma clang loop
305 /// unroll(disable)` explicitly forbids any unrolling to take place. Unlike
306 /// general loop metadata, it must not be dropped. Most passes should not
307 /// behave differently under TM_Disable and TM_SuppressedByUser.
310
311/// @{
312/// Get the mode for LLVM's supported loop transformations.
318/// @}
319
320/// Set input string into loop metadata by keeping other values intact.
321/// If the string is already in loop metadata update value if it is
322/// different.
323LLVM_ABI void addStringMetadataToLoop(Loop *TheLoop, const char *MDString,
324 unsigned V = 0);
325
326/// Returns a loop's estimated trip count based on branch weight metadata.
327/// In addition if \p EstimatedLoopInvocationWeight is not null it is
328/// initialized with weight of loop's latch leading to the exit.
329/// Returns a valid positive trip count, saturated at UINT_MAX, or std::nullopt
330/// when a meaningful estimate cannot be made.
331LLVM_ABI std::optional<unsigned>
333 unsigned *EstimatedLoopInvocationWeight = nullptr);
334
335/// Set a loop's branch weight metadata to reflect that loop has \p
336/// EstimatedTripCount iterations and \p EstimatedLoopInvocationWeight exits
337/// through latch. Returns true if metadata is successfully updated, false
338/// otherwise. Note that loop must have a latch block which controls loop exit
339/// in order to succeed.
340LLVM_ABI bool setLoopEstimatedTripCount(Loop *L, unsigned EstimatedTripCount,
341 unsigned EstimatedLoopInvocationWeight);
342
343/// Check inner loop (L) backedge count is known to be invariant on all
344/// iterations of its outer loop. If the loop has no parent, this is trivially
345/// true.
346LLVM_ABI bool hasIterationCountInvariantInParent(Loop *L, ScalarEvolution &SE);
347
348/// Helper to consistently add the set of standard passes to a loop pass's \c
349/// AnalysisUsage.
350///
351/// All loop passes should call this as part of implementing their \c
352/// getAnalysisUsage.
353LLVM_ABI void getLoopAnalysisUsage(AnalysisUsage &AU);
354
355/// Returns true if is legal to hoist or sink this instruction disregarding the
356/// possible introduction of faults. Reasoning about potential faulting
357/// instructions is the responsibility of the caller since it is challenging to
358/// do efficiently from within this routine.
359/// \p TargetExecutesOncePerLoop is true only when it is guaranteed that the
360/// target executes at most once per execution of the loop body. This is used
361/// to assess the legality of duplicating atomic loads. Generally, this is
362/// true when moving out of loop and not true when moving into loops.
363/// If \p ORE is set use it to emit optimization remarks.
364LLVM_ABI bool canSinkOrHoistInst(Instruction &I, AAResults *AA,
365 DominatorTree *DT, Loop *CurLoop,
366 MemorySSAUpdater &MSSAU,
367 bool TargetExecutesOncePerLoop,
368 SinkAndHoistLICMFlags &LICMFlags,
369 OptimizationRemarkEmitter *ORE = nullptr);
370
371/// Returns the llvm.vector.reduce intrinsic that corresponds to the recurrence
372/// kind.
374/// Returns the llvm.vector.reduce min/max intrinsic that corresponds to the
375/// intrinsic op.
377
378/// Returns the arithmetic instruction opcode used when expanding a reduction.
380/// Returns the reduction intrinsic id corresponding to the binary operation.
382
383/// Returns the min/max intrinsic used when expanding a min/max reduction.
385
386/// Returns the min/max intrinsic used when expanding a min/max reduction.
388
389/// Returns the recurence kind used when expanding a min/max reduction.
391
392/// Returns the comparison predicate used when expanding a min/max reduction.
394
395/// Given information about an @llvm.vector.reduce.* intrinsic, return
396/// the identity value for the reduction.
397LLVM_ABI Value *getReductionIdentity(Intrinsic::ID RdxID, Type *Ty,
398 FastMathFlags FMF);
399
400/// Given information about an recurrence kind, return the identity
401/// for the @llvm.vector.reduce.* used to generate it.
402LLVM_ABI Value *getRecurrenceIdentity(RecurKind K, Type *Tp, FastMathFlags FMF);
403
404/// Returns a Min/Max operation corresponding to MinMaxRecurrenceKind.
405/// The Builder's fast-math-flags must be set to propagate the expected values.
406LLVM_ABI Value *createMinMaxOp(IRBuilderBase &Builder, RecurKind RK,
407 Value *Left, Value *Right);
408
409/// Generates an ordered vector reduction using extracts to reduce the value.
410LLVM_ABI Value *getOrderedReduction(IRBuilderBase &Builder, Value *Acc,
411 Value *Src, unsigned Op,
412 RecurKind MinMaxKind = RecurKind::None);
413
414/// Generates a vector reduction using shufflevectors to reduce the value.
415/// Fast-math-flags are propagated using the IRBuilder's setting.
416LLVM_ABI Value *getShuffleReduction(IRBuilderBase &Builder, Value *Src,
417 unsigned Op,
419 RecurKind MinMaxKind = RecurKind::None);
420
421/// Create a reduction of the given vector. The reduction operation
422/// is described by the \p Opcode parameter. min/max reductions require
423/// additional information supplied in \p RdxKind.
424/// Fast-math-flags are propagated using the IRBuilder's setting.
425LLVM_ABI Value *createSimpleReduction(IRBuilderBase &B, Value *Src,
426 RecurKind RdxKind);
427/// Overloaded function to generate vector-predication intrinsics for
428/// reduction.
429LLVM_ABI Value *createSimpleReduction(IRBuilderBase &B, Value *Src,
430 RecurKind RdxKind, Value *Mask,
431 Value *EVL);
432
433/// Create a reduction of the given vector \p Src for a reduction of kind
434/// RecurKind::AnyOf. The start value of the reduction is \p InitVal.
435LLVM_ABI Value *createAnyOfReduction(IRBuilderBase &B, Value *Src,
436 Value *InitVal, PHINode *OrigPhi);
437
438/// Create a reduction of the given vector \p Src for a reduction of the
439/// kind RecurKind::FindLastIV.
440LLVM_ABI Value *createFindLastIVReduction(IRBuilderBase &B, Value *Src,
441 RecurKind RdxKind, Value *Start,
442 Value *Sentinel);
443
444/// Create an ordered reduction intrinsic using the given recurrence
445/// kind \p RdxKind.
446LLVM_ABI Value *createOrderedReduction(IRBuilderBase &B, RecurKind RdxKind,
447 Value *Src, Value *Start);
448/// Overloaded function to generate vector-predication intrinsics for ordered
449/// reduction.
450LLVM_ABI Value *createOrderedReduction(IRBuilderBase &B, RecurKind RdxKind,
451 Value *Src, Value *Start, Value *Mask,
452 Value *EVL);
453
454/// Get the intersection (logical and) of all of the potential IR flags
455/// of each scalar operation (VL) that will be converted into a vector (I).
456/// If OpValue is non-null, we only consider operations similar to OpValue
457/// when intersecting.
458/// Flag set: NSW, NUW (if IncludeWrapFlags is true), exact, and all of
459/// fast-math.
460LLVM_ABI void propagateIRFlags(Value *I, ArrayRef<Value *> VL,
461 Value *OpValue = nullptr,
462 bool IncludeWrapFlags = true);
463
464/// Returns true if we can prove that \p S is defined and always negative in
465/// loop \p L.
466LLVM_ABI bool isKnownNegativeInLoop(const SCEV *S, const Loop *L,
467 ScalarEvolution &SE);
468
469/// Returns true if we can prove that \p S is defined and always non-negative in
470/// loop \p L.
471LLVM_ABI bool isKnownNonNegativeInLoop(const SCEV *S, const Loop *L,
472 ScalarEvolution &SE);
473/// Returns true if we can prove that \p S is defined and always positive in
474/// loop \p L.
475LLVM_ABI bool isKnownPositiveInLoop(const SCEV *S, const Loop *L,
476 ScalarEvolution &SE);
477
478/// Returns true if we can prove that \p S is defined and always non-positive in
479/// loop \p L.
480LLVM_ABI bool isKnownNonPositiveInLoop(const SCEV *S, const Loop *L,
481 ScalarEvolution &SE);
482
483/// Returns true if \p S is defined and never is equal to signed/unsigned max.
484LLVM_ABI bool cannotBeMaxInLoop(const SCEV *S, const Loop *L,
485 ScalarEvolution &SE, bool Signed);
486
487/// Returns true if \p S is defined and never is equal to signed/unsigned min.
488LLVM_ABI bool cannotBeMinInLoop(const SCEV *S, const Loop *L,
489 ScalarEvolution &SE, bool Signed);
490
498
499/// If the final value of any expressions that are recurrent in the loop can
500/// be computed, substitute the exit values from the loop into any instructions
501/// outside of the loop that use the final values of the current expressions.
502/// Return the number of loop exit values that have been replaced, and the
503/// corresponding phi node will be added to DeadInsts.
504LLVM_ABI int rewriteLoopExitValues(Loop *L, LoopInfo *LI,
505 TargetLibraryInfo *TLI, ScalarEvolution *SE,
506 const TargetTransformInfo *TTI,
507 SCEVExpander &Rewriter, DominatorTree *DT,
509 SmallVector<WeakTrackingVH, 16> &DeadInsts);
510
511/// Set weights for \p UnrolledLoop and \p RemainderLoop based on weights for
512/// \p OrigLoop and the following distribution of \p OrigLoop iteration among \p
513/// UnrolledLoop and \p RemainderLoop. \p UnrolledLoop receives weights that
514/// reflect TC/UF iterations, and \p RemainderLoop receives weights that reflect
515/// the remaining TC%UF iterations.
516///
517/// Note that \p OrigLoop may be equal to either \p UnrolledLoop or \p
518/// RemainderLoop in which case weights for \p OrigLoop are updated accordingly.
519/// Note also behavior is undefined if \p UnrolledLoop and \p RemainderLoop are
520/// equal. \p UF must be greater than zero.
521/// If \p OrigLoop has no profile info associated nothing happens.
522///
523/// This utility may be useful for such optimizations as unroller and
524/// vectorizer as it's typical transformation for them.
525LLVM_ABI void setProfileInfoAfterUnrolling(Loop *OrigLoop, Loop *UnrolledLoop,
526 Loop *RemainderLoop, uint64_t UF);
527
528/// Utility that implements appending of loops onto a worklist given a range.
529/// We want to process loops in postorder, but the worklist is a LIFO data
530/// structure, so we append to it in *reverse* postorder.
531/// For trees, a preorder traversal is a viable reverse postorder, so we
532/// actually append using a preorder walk algorithm.
533template <typename RangeT>
536/// Utility that implements appending of loops onto a worklist given a range.
537/// It has the same behavior as appendLoopsToWorklist, but assumes the range of
538/// loops has already been reversed, so it processes loops in the given order.
539template <typename RangeT>
540void appendReversedLoopsToWorklist(RangeT &&,
542
543extern template LLVM_TEMPLATE_ABI void
544appendLoopsToWorklist<ArrayRef<Loop *> &>(
546
547extern template LLVM_TEMPLATE_ABI void
550
551/// Utility that implements appending of loops onto a worklist given LoopInfo.
552/// Calls the templated utility taking a Range of loops, handing it the Loops
553/// in LoopInfo, iterated in reverse. This is because the loops are stored in
554/// RPO w.r.t. the control flow graph in LoopInfo. For the purpose of unrolling,
555/// loop deletion, and LICM, we largely want to work forward across the CFG so
556/// that we visit defs before uses and can propagate simplifications from one
557/// loop nest into the next. Calls appendReversedLoopsToWorklist with the
558/// already reversed loops in LI.
559/// FIXME: Consider changing the order in LoopInfo.
562
563/// Recursively clone the specified loop and all of its children,
564/// mapping the blocks with the specified map.
566 LPPassManager *LPM);
567
568/// Add code that checks at runtime if the accessed arrays in \p PointerChecks
569/// overlap. Returns the final comparator value or NULL if no check is needed.
571addRuntimeChecks(Instruction *Loc, Loop *TheLoop,
572 const SmallVectorImpl<RuntimePointerCheck> &PointerChecks,
573 SCEVExpander &Expander, bool HoistRuntimeChecks = false);
574
576 Instruction *Loc, ArrayRef<PointerDiffInfo> Checks, SCEVExpander &Expander,
577 function_ref<Value *(IRBuilderBase &, unsigned)> GetVF, unsigned IC);
578
579/// Struct to hold information about a partially invariant condition.
581 /// Instructions that need to be duplicated and checked for the unswitching
582 /// condition.
584
585 /// Constant to indicate for which value the condition is invariant.
586 Constant *KnownValue = nullptr;
587
588 /// True if the partially invariant path is no-op (=does not have any
589 /// side-effects and no loop value is used outside the loop).
590 bool PathIsNoop = true;
591
592 /// If the partially invariant path reaches a single exit block, ExitForPath
593 /// is set to that block. Otherwise it is nullptr.
594 BasicBlock *ExitForPath = nullptr;
595};
596
597/// Check if the loop header has a conditional branch that is not
598/// loop-invariant, because it involves load instructions. If all paths from
599/// either the true or false successor to the header or loop exists do not
600/// modify the memory feeding the condition, perform 'partial unswitching'. That
601/// is, duplicate the instructions feeding the condition in the pre-header. Then
602/// unswitch on the duplicated condition. The condition is now known in the
603/// unswitched version for the 'invariant' path through the original loop.
604///
605/// If the branch condition of the header is partially invariant, return a pair
606/// containing the instructions to duplicate and a boolean Constant to update
607/// the condition in the loops created for the true or false successors.
608LLVM_ABI std::optional<IVConditionInfo>
609hasPartialIVCondition(const Loop &L, unsigned MSSAThreshold,
610 const MemorySSA &MSSA, AAResults &AA);
611
612} // end namespace llvm
613
614#endif // LLVM_TRANSFORMS_UTILS_LOOPUTILS_H
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_ABI
Definition: Compiler.h:213
#define LLVM_TEMPLATE_ABI
Definition: Compiler.h:214
early cse Early CSE w MemorySSA
Definition: EarlyCSE.cpp:1962
Hexagon Hardware Loops
static cl::opt< ReplaceExitVal > ReplaceExitValue("replexitval", cl::Hidden, cl::init(OnlyCheapRepl), cl::desc("Choose the strategy to replace exit value in IndVarSimplify"), cl::values(clEnumValN(NeverRepl, "never", "never replace exit value"), clEnumValN(OnlyCheapRepl, "cheap", "only replace exit value when the cost is cheap"), clEnumValN(UnusedIndVarInLoop, "unusedindvarinloop", "only replace exit value when it is an unused " "induction variable in the loop and has cheap replacement cost"), clEnumValN(NoHardUse, "noharduse", "only replace exit values when loop def likely dead"), clEnumValN(AlwaysRepl, "always", "always replace exit value whenever possible")))
static cl::opt< bool, true > HoistRuntimeChecks("hoist-runtime-checks", cl::Hidden, cl::desc("Hoist inner loop runtime memory checks to outer loop if possible"), cl::location(VectorizerParams::HoistRuntimeChecks), cl::init(true))
#define I(x, y, z)
Definition: MD5.cpp:58
const SmallVectorImpl< MachineOperand > & Cond
static cl::opt< unsigned > MSSAThreshold("simple-loop-unswitch-memoryssa-threshold", cl::desc("Max number of memory uses to explore during " "partial unswitching analysis"), cl::init(100), cl::Hidden)
This pass exposes codegen information to IR-level passes.
static const uint32_t IV[8]
Definition: blake3_impl.h:83
A private abstract base class describing the concept of an individual alias analysis implementation.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
A cache of @llvm.assume calls within a function.
LLVM Basic Block Representation.
Definition: BasicBlock.h:62
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition: InstrTypes.h:678
This is an important base class in LLVM.
Definition: Constant.h:43
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition: Dominators.h:165
This implementation of LoopSafetyInfo use ImplicitControlFlowTracking to give precise answers on "may...
Definition: MustExecute.h:133
Common base class shared among various IRBuilders.
Definition: IRBuilder.h:114
Represents a single loop in the control flow graph.
Definition: LoopInfo.h:40
Metadata node.
Definition: Metadata.h:1077
Encapsulates MemorySSA, including all data associated with memory accesses.
Definition: MemorySSA.h:702
The optimization diagnostic interface.
PredIteratorCache - This class is an extremely trivial cache for predecessor iterator queries.
This class uses information about analyze scalars to rewrite expressions in canonical form.
The main scalar evolution driver.
Flags controlling how much is checked when sinking or hoisting instructions.
Definition: LoopUtils.h:124
unsigned LicmMssaNoAccForPromotionCap
Definition: LoopUtils.h:143
A version of PriorityWorklist that selects small size optimized data structures for the vector and ma...
A SetVector that performs no allocations if smaller than a certain size.
Definition: SetVector.h:356
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:574
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1197
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.
LLVM Value Representation.
Definition: Value.h:75
An efficient, type-erasing, non-owning reference to a callable.
@ BasicBlock
Various leaf nodes.
Definition: ISDOpcodes.h:81
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
LLVM_ABI Value * createSimpleReduction(IRBuilderBase &B, Value *Src, RecurKind RdxKind)
Create a reduction of the given vector.
Definition: LoopUtils.cpp:1313
LLVM_ABI std::optional< ElementCount > getOptionalElementCountLoopAttribute(const Loop *TheLoop)
Find a combination of metadata ("llvm.loop.vectorize.width" and "llvm.loop.vectorize....
Definition: LoopUtils.cpp:251
LLVM_ABI Value * addRuntimeChecks(Instruction *Loc, Loop *TheLoop, const SmallVectorImpl< RuntimePointerCheck > &PointerChecks, SCEVExpander &Expander, bool HoistRuntimeChecks=false)
Add code that checks at runtime if the accessed arrays in PointerChecks overlap.
Definition: LoopUtils.cpp:1980
LLVM_ABI Value * createFindLastIVReduction(IRBuilderBase &B, Value *Src, RecurKind RdxKind, Value *Start, Value *Sentinel)
Create a reduction of the given vector Src for a reduction of the kind RecurKind::FindLastIV.
Definition: LoopUtils.cpp:1247
LLVM_ABI std::optional< unsigned > getLoopEstimatedTripCount(Loop *L, unsigned *EstimatedLoopInvocationWeight=nullptr)
Returns a loop's estimated trip count based on branch weight metadata.
Definition: LoopUtils.cpp:841
LLVM_ABI BasicBlock * InsertPreheaderForLoop(Loop *L, DominatorTree *DT, LoopInfo *LI, MemorySSAUpdater *MSSAU, bool PreserveLCSSA)
InsertPreheaderForLoop - Once we discover that a loop doesn't have a preheader, this method is called...
LLVM_ABI Intrinsic::ID getMinMaxReductionIntrinsicOp(Intrinsic::ID RdxID)
Returns the min/max intrinsic used when expanding a min/max reduction.
Definition: LoopUtils.cpp:1023
std::pair< const RuntimeCheckingPtrGroup *, const RuntimeCheckingPtrGroup * > RuntimePointerCheck
A memcheck which made up of a pair of grouped pointers.
LLVM_ABI bool canSinkOrHoistInst(Instruction &I, AAResults *AA, DominatorTree *DT, Loop *CurLoop, MemorySSAUpdater &MSSAU, bool TargetExecutesOncePerLoop, SinkAndHoistLICMFlags &LICMFlags, OptimizationRemarkEmitter *ORE=nullptr)
Returns true if is legal to hoist or sink this instruction disregarding the possible introduction of ...
Definition: LICM.cpp:1167
LLVM_ABI bool isKnownNonPositiveInLoop(const SCEV *S, const Loop *L, ScalarEvolution &SE)
Returns true if we can prove that S is defined and always non-positive in loop L.
Definition: LoopUtils.cpp:1434
void appendReversedLoopsToWorklist(RangeT &&, SmallPriorityWorklist< Loop *, 4 > &)
Utility that implements appending of loops onto a worklist given a range.
Definition: LoopUtils.cpp:1814
LLVM_ABI bool formLCSSARecursively(Loop &L, const DominatorTree &DT, const LoopInfo *LI, ScalarEvolution *SE)
Put a loop nest into LCSSA form.
Definition: LCSSA.cpp:449
LLVM_ABI Value * getReductionIdentity(Intrinsic::ID RdxID, Type *Ty, FastMathFlags FMF)
Given information about an @llvm.vector.reduce.
Definition: LoopUtils.cpp:1263
LLVM_ABI std::optional< MDNode * > makeFollowupLoopID(MDNode *OrigLoopID, ArrayRef< StringRef > FollowupAttrs, const char *InheritOptionsAttrsPrefix="", bool AlwaysNew=false)
Create a new loop identifier for a loop created from a loop transformation.
Definition: LoopUtils.cpp:264
LLVM_ABI unsigned getArithmeticReductionInstruction(Intrinsic::ID RdxID)
Returns the arithmetic instruction opcode used when expanding a reduction.
Definition: LoopUtils.cpp:975
template class LLVM_TEMPLATE_ABI DomTreeNodeBase< BasicBlock >
LLVM_ABI bool hoistRegion(DomTreeNode *, AAResults *, LoopInfo *, DominatorTree *, AssumptionCache *, TargetLibraryInfo *, Loop *, MemorySSAUpdater &, ScalarEvolution *, ICFLoopSafetyInfo *, SinkAndHoistLICMFlags &, OptimizationRemarkEmitter *, bool, bool AllowSpeculation, bool HasCoroSuspendInst=false)
Walk the specified region of the CFG (defined by all blocks dominated by the specified block,...
Definition: LICM.cpp:888
LLVM_ABI Value * createMinMaxOp(IRBuilderBase &Builder, RecurKind RK, Value *Left, Value *Right)
Returns a Min/Max operation corresponding to MinMaxRecurrenceKind.
Definition: LoopUtils.cpp:1116
LLVM_ABI SmallVector< BasicBlock *, 16 > collectChildrenInLoop(DominatorTree *DT, DomTreeNode *N, const Loop *CurLoop)
Does a BFS from a given node to all of its children inside a given loop.
Definition: LoopUtils.cpp:450
LLVM_ABI void addStringMetadataToLoop(Loop *TheLoop, const char *MDString, unsigned V=0)
Set input string into loop metadata by keeping other values intact.
Definition: LoopUtils.cpp:215
LLVM_ABI bool cannotBeMaxInLoop(const SCEV *S, const Loop *L, ScalarEvolution &SE, bool Signed)
Returns true if S is defined and never is equal to signed/unsigned max.
Definition: LoopUtils.cpp:1452
LLVM_ABI TransformationMode hasVectorizeTransformation(const Loop *L)
Definition: LoopUtils.cpp:392
LLVM_ABI SmallVector< Instruction *, 8 > findDefsUsedOutsideOfLoop(Loop *L)
Returns the instructions that use values defined in the loop.
Definition: LoopUtils.cpp:124
LLVM_ABI constexpr Intrinsic::ID getReductionIntrinsicID(RecurKind RK)
Returns the llvm.vector.reduce intrinsic that corresponds to the recurrence kind.
Definition: LoopUtils.cpp:913
LLVM_ABI TransformationMode hasUnrollAndJamTransformation(const Loop *L)
Definition: LoopUtils.cpp:374
LLVM_ABI void deleteDeadLoop(Loop *L, DominatorTree *DT, ScalarEvolution *SE, LoopInfo *LI, MemorySSA *MSSA=nullptr)
This function deletes dead loops.
Definition: LoopUtils.cpp:485
LLVM_ABI bool hasDisableAllTransformsHint(const Loop *L)
Look for the loop attribute that disables all transformation heuristic.
Definition: LoopUtils.cpp:345
LLVM_TEMPLATE_ABI void appendLoopsToWorklist(RangeT &&, SmallPriorityWorklist< Loop *, 4 > &)
Utility that implements appending of loops onto a worklist given a range.
LLVM_ABI Value * getShuffleReduction(IRBuilderBase &Builder, Value *Src, unsigned Op, TargetTransformInfo::ReductionShuffle RS, RecurKind MinMaxKind=RecurKind::None)
Generates a vector reduction using shufflevectors to reduce the value.
Definition: LoopUtils.cpp:1159
LLVM_ABI TransformationMode hasUnrollTransformation(const Loop *L)
Definition: LoopUtils.cpp:353
DomTreeNodeBase< BasicBlock > DomTreeNode
Definition: Dominators.h:95
LLVM_ABI TransformationMode hasDistributeTransformation(const Loop *L)
Definition: LoopUtils.cpp:428
LLVM_ABI void breakLoopBackedge(Loop *L, DominatorTree &DT, ScalarEvolution &SE, LoopInfo &LI, MemorySSA *MSSA)
Remove the backedge of the specified loop.
Definition: LoopUtils.cpp:711
LLVM_ABI void getLoopAnalysisUsage(AnalysisUsage &AU)
Helper to consistently add the set of standard passes to a loop pass's AnalysisUsage.
Definition: LoopUtils.cpp:142
LLVM_ABI void propagateIRFlags(Value *I, ArrayRef< Value * > VL, Value *OpValue=nullptr, bool IncludeWrapFlags=true)
Get the intersection (logical and) of all of the potential IR flags of each scalar operation (VL) tha...
Definition: LoopUtils.cpp:1393
LLVM_ABI bool isKnownPositiveInLoop(const SCEV *S, const Loop *L, ScalarEvolution &SE)
Returns true if we can prove that S is defined and always positive in loop L.
Definition: LoopUtils.cpp:1427
TargetTransformInfo TTI
LLVM_ABI CmpInst::Predicate getMinMaxReductionPredicate(RecurKind RK)
Returns the comparison predicate used when expanding a min/max reduction.
Definition: LoopUtils.cpp:1094
LLVM_ABI TransformationMode hasLICMVersioningTransformation(const Loop *L)
Definition: LoopUtils.cpp:438
TransformationMode
The mode sets how eager a transformation should be applied.
Definition: LoopUtils.h:285
@ TM_Unspecified
The pass can use heuristics to determine whether a transformation should be applied.
Definition: LoopUtils.h:288
@ TM_SuppressedByUser
The transformation must not be applied.
Definition: LoopUtils.h:308
@ TM_ForcedByUser
The transformation was directed by the user, e.g.
Definition: LoopUtils.h:302
@ TM_Disable
The transformation should not be applied.
Definition: LoopUtils.h:294
@ TM_Force
Force is a flag and should not be used alone.
Definition: LoopUtils.h:297
@ TM_Enable
The transformation should be applied without considering a cost model.
Definition: LoopUtils.h:291
LLVM_ABI bool hasDisableLICMTransformsHint(const Loop *L)
Look for the loop attribute that disables the LICM transformation heuristics.
Definition: LoopUtils.cpp:349
template LLVM_TEMPLATE_ABI void appendLoopsToWorklist< Loop & >(Loop &L, SmallPriorityWorklist< Loop *, 4 > &Worklist)
LLVM_ABI Intrinsic::ID getReductionForBinop(Instruction::BinaryOps Opc)
Returns the reduction intrinsic id corresponding to the binary operation.
Definition: LoopUtils.cpp:1005
RecurKind
These are the kinds of recurrences that we support.
Definition: IVDescriptors.h:34
@ None
Not a recurrence.
LLVM_ABI bool setLoopEstimatedTripCount(Loop *L, unsigned EstimatedTripCount, unsigned EstimatedLoopInvocationWeight)
Set a loop's branch weight metadata to reflect that loop has EstimatedTripCount iterations and Estima...
Definition: LoopUtils.cpp:859
LLVM_ABI Value * getRecurrenceIdentity(RecurKind K, Type *Tp, FastMathFlags FMF)
Given information about an recurrence kind, return the identity for the @llvm.vector....
Definition: LoopUtils.cpp:1305
LLVM_ABI void setProfileInfoAfterUnrolling(Loop *OrigLoop, Loop *UnrolledLoop, Loop *RemainderLoop, uint64_t UF)
Set weights for UnrolledLoop and RemainderLoop based on weights for OrigLoop and the following distri...
Definition: LoopUtils.cpp:1786
LLVM_ABI bool formDedicatedExitBlocks(Loop *L, DominatorTree *DT, LoopInfo *LI, MemorySSAUpdater *MSSAU, bool PreserveLCSSA)
Ensure that all exit blocks of the loop are dedicated exits.
Definition: LoopUtils.cpp:58
DWARFExpression::Operation Op
LLVM_ABI bool isKnownNegativeInLoop(const SCEV *S, const Loop *L, ScalarEvolution &SE)
Returns true if we can prove that S is defined and always negative in loop L.
Definition: LoopUtils.cpp:1413
LLVM_ABI bool formLCSSAForInstructions(SmallVectorImpl< Instruction * > &Worklist, const DominatorTree &DT, const LoopInfo &LI, ScalarEvolution *SE, SmallVectorImpl< PHINode * > *PHIsToRemove=nullptr, SmallVectorImpl< PHINode * > *InsertedPHIs=nullptr)
Ensures LCSSA form for every instruction from the Worklist in the scope of innermost containing loop.
Definition: LCSSA.cpp:308
LLVM_ABI bool hasIterationCountInvariantInParent(Loop *L, ScalarEvolution &SE)
Check inner loop (L) backedge count is known to be invariant on all iterations of its outer loop.
Definition: LoopUtils.cpp:891
LLVM_ABI bool isAlmostDeadIV(PHINode *IV, BasicBlock *LatchBlock, Value *Cond)
Return true if the induction variable IV in a Loop whose latch is LatchBlock would become dead if the...
Definition: LoopUtils.cpp:471
LLVM_ABI int rewriteLoopExitValues(Loop *L, LoopInfo *LI, TargetLibraryInfo *TLI, ScalarEvolution *SE, const TargetTransformInfo *TTI, SCEVExpander &Rewriter, DominatorTree *DT, ReplaceExitVal ReplaceExitValue, SmallVector< WeakTrackingVH, 16 > &DeadInsts)
If the final value of any expressions that are recurrent in the loop can be computed,...
Definition: LoopUtils.cpp:1574
LLVM_ABI Value * createOrderedReduction(IRBuilderBase &B, RecurKind RdxKind, Value *Src, Value *Start)
Create an ordered reduction intrinsic using the given recurrence kind RdxKind.
Definition: LoopUtils.cpp:1366
LLVM_ABI bool sinkRegion(DomTreeNode *, AAResults *, LoopInfo *, DominatorTree *, TargetLibraryInfo *, TargetTransformInfo *, Loop *CurLoop, MemorySSAUpdater &, ICFLoopSafetyInfo *, SinkAndHoistLICMFlags &, OptimizationRemarkEmitter *, Loop *OutermostLoop=nullptr)
Walk the specified region of the CFG (defined by all blocks dominated by the specified block,...
Definition: LICM.cpp:558
LLVM_ABI Value * addDiffRuntimeChecks(Instruction *Loc, ArrayRef< PointerDiffInfo > Checks, SCEVExpander &Expander, function_ref< Value *(IRBuilderBase &, unsigned)> GetVF, unsigned IC)
Definition: LoopUtils.cpp:2038
LLVM_ABI RecurKind getMinMaxReductionRecurKind(Intrinsic::ID RdxID)
Returns the recurence kind used when expanding a min/max reduction.
Definition: LoopUtils.cpp:1075
ReplaceExitVal
Definition: LoopUtils.h:491
@ UnusedIndVarInLoop
Definition: LoopUtils.h:495
@ OnlyCheapRepl
Definition: LoopUtils.h:493
@ NeverRepl
Definition: LoopUtils.h:492
@ NoHardUse
Definition: LoopUtils.h:494
@ AlwaysRepl
Definition: LoopUtils.h:496
LLVM_ABI std::optional< IVConditionInfo > hasPartialIVCondition(const Loop &L, unsigned MSSAThreshold, const MemorySSA &MSSA, AAResults &AA)
Check if the loop header has a conditional branch that is not loop-invariant, because it involves loa...
Definition: LoopUtils.cpp:2084
LLVM_ABI bool formLCSSA(Loop &L, const DominatorTree &DT, const LoopInfo *LI, ScalarEvolution *SE)
Put loop into LCSSA form.
Definition: LCSSA.cpp:427
LLVM_ABI bool promoteLoopAccessesToScalars(const SmallSetVector< Value *, 8 > &, SmallVectorImpl< BasicBlock * > &, SmallVectorImpl< BasicBlock::iterator > &, SmallVectorImpl< MemoryAccess * > &, PredIteratorCache &, LoopInfo *, DominatorTree *, AssumptionCache *AC, const TargetLibraryInfo *, TargetTransformInfo *, Loop *, MemorySSAUpdater &, ICFLoopSafetyInfo *, OptimizationRemarkEmitter *, bool AllowSpeculation, bool HasReadsOutsideSet)
Try to promote memory values to scalars by sinking stores out of the loop and moving loads to before ...
Definition: LICM.cpp:1916
LLVM_ABI Value * createAnyOfReduction(IRBuilderBase &B, Value *Src, Value *InitVal, PHINode *OrigPhi)
Create a reduction of the given vector Src for a reduction of kind RecurKind::AnyOf.
Definition: LoopUtils.cpp:1217
LLVM_ABI bool cannotBeMinInLoop(const SCEV *S, const Loop *L, ScalarEvolution &SE, bool Signed)
Returns true if S is defined and never is equal to signed/unsigned min.
Definition: LoopUtils.cpp:1441
LLVM_ABI bool isKnownNonNegativeInLoop(const SCEV *S, const Loop *L, ScalarEvolution &SE)
Returns true if we can prove that S is defined and always non-negative in loop L.
Definition: LoopUtils.cpp:1420
LLVM_ABI bool sinkRegionForLoopNest(DomTreeNode *, AAResults *, LoopInfo *, DominatorTree *, TargetLibraryInfo *, TargetTransformInfo *, Loop *, MemorySSAUpdater &, ICFLoopSafetyInfo *, SinkAndHoistLICMFlags &, OptimizationRemarkEmitter *)
Call sinkRegion on loops contained within the specified loop in order from innermost to outermost.
Definition: LICM.cpp:625
LLVM_ABI Value * getOrderedReduction(IRBuilderBase &Builder, Value *Acc, Value *Src, unsigned Op, RecurKind MinMaxKind=RecurKind::None)
Generates an ordered vector reduction using extracts to reduce the value.
Definition: LoopUtils.cpp:1134
LLVM_ABI Intrinsic::ID getMinMaxReductionIntrinsicID(Intrinsic::ID IID)
Returns the llvm.vector.reduce min/max intrinsic that corresponds to the intrinsic op.
Definition: LoopUtils.cpp:959
LLVM_ABI Loop * cloneLoop(Loop *L, Loop *PL, ValueToValueMapTy &VM, LoopInfo *LI, LPPassManager *LPM)
Recursively clone the specified loop and all of its children, mapping the blocks with the specified m...
Definition: LoopUtils.cpp:1857
#define N
Struct to hold information about a partially invariant condition.
Definition: LoopUtils.h:580
SmallVector< Instruction * > InstToDuplicate
Instructions that need to be duplicated and checked for the unswitching condition.
Definition: LoopUtils.h:583