LLVM 20.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;
25using DomTreeNode = DomTreeNodeBase<BasicBlock>;
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
55BasicBlock *InsertPreheaderForLoop(Loop *L, DominatorTree *DT, LoopInfo *LI,
56 MemorySSAUpdater *MSSAU, bool PreserveLCSSA);
57
58/// Ensure that all exit blocks of the loop are dedicated exits.
59///
60/// For any loop exit block with non-loop predecessors, we split the loop
61/// predecessors to use a dedicated loop exit block. We update the dominator
62/// tree and loop info if provided, and will preserve LCSSA if requested.
63bool formDedicatedExitBlocks(Loop *L, DominatorTree *DT, LoopInfo *LI,
64 MemorySSAUpdater *MSSAU, bool PreserveLCSSA);
65
66/// Ensures LCSSA form for every instruction from the Worklist in the scope of
67/// innermost containing loop.
68///
69/// For the given instruction which have uses outside of the loop, an LCSSA PHI
70/// node is inserted and the uses outside the loop are rewritten to use this
71/// node.
72///
73/// LoopInfo and DominatorTree are required and, since the routine makes no
74/// changes to CFG, preserved.
75///
76/// Returns true if any modifications are made.
77///
78/// This function may introduce unused PHI nodes. If \p PHIsToRemove is not
79/// nullptr, those are added to it (before removing, the caller has to check if
80/// they still do not have any uses). Otherwise the PHIs are directly removed.
81///
82/// If \p InsertedPHIs is not nullptr, inserted phis will be added to this
83/// vector.
85 SmallVectorImpl<Instruction *> &Worklist, const DominatorTree &DT,
86 const LoopInfo &LI, ScalarEvolution *SE,
87 SmallVectorImpl<PHINode *> *PHIsToRemove = nullptr,
88 SmallVectorImpl<PHINode *> *InsertedPHIs = nullptr);
89
90/// Put loop into LCSSA form.
91///
92/// Looks at all instructions in the loop which have uses outside of the
93/// current loop. For each, an LCSSA PHI node is inserted and the uses outside
94/// the loop are rewritten to use this node. Sub-loops must be in LCSSA form
95/// already.
96///
97/// LoopInfo and DominatorTree are required and preserved.
98///
99/// If ScalarEvolution is passed in, it will be preserved.
100///
101/// Returns true if any modifications are made to the loop.
102bool formLCSSA(Loop &L, const DominatorTree &DT, const LoopInfo *LI,
103 ScalarEvolution *SE);
104
105/// Put a loop nest into LCSSA form.
106///
107/// This recursively forms LCSSA for a loop nest.
108///
109/// LoopInfo and DominatorTree are required and preserved.
110///
111/// If ScalarEvolution is passed in, it will be preserved.
112///
113/// Returns true if any modifications are made to the loop.
114bool formLCSSARecursively(Loop &L, const DominatorTree &DT, const LoopInfo *LI,
115 ScalarEvolution *SE);
116
117/// Flags controlling how much is checked when sinking or hoisting
118/// instructions. The number of memory access in the loop (and whether there
119/// are too many) is determined in the constructors when using MemorySSA.
121public:
122 // Explicitly set limits.
125 Loop &L, MemorySSA &MSSA);
126 // Use default limits.
128
129 void setIsSink(bool B) { IsSink = B; }
130 bool getIsSink() { return IsSink; }
134
135protected:
136 bool NoOfMemAccTooLarge = false;
137 unsigned LicmMssaOptCounter = 0;
140 bool IsSink;
141};
142
143/// Walk the specified region of the CFG (defined by all blocks
144/// dominated by the specified block, and that are in the current loop) in
145/// reverse depth first order w.r.t the DominatorTree. This allows us to visit
146/// uses before definitions, allowing us to sink a loop body in one pass without
147/// iteration. Takes DomTreeNode, AAResults, LoopInfo, DominatorTree,
148/// TargetLibraryInfo, Loop, AliasSet information for all
149/// instructions of the loop and loop safety information as
150/// arguments. Diagnostics is emitted via \p ORE. It returns changed status.
151/// \p CurLoop is a loop to do sinking on. \p OutermostLoop is used only when
152/// this function is called by \p sinkRegionForLoopNest.
157 Loop *OutermostLoop = nullptr);
158
159/// Call sinkRegion on loops contained within the specified loop
160/// in order from innermost to outermost.
166
167/// Walk the specified region of the CFG (defined by all blocks
168/// dominated by the specified block, and that are in the current loop) in depth
169/// first order w.r.t the DominatorTree. This allows us to visit definitions
170/// before uses, allowing us to hoist a loop body in one pass without iteration.
171/// Takes DomTreeNode, AAResults, LoopInfo, DominatorTree,
172/// TargetLibraryInfo, Loop, AliasSet information for all
173/// instructions of the loop and loop safety information as arguments.
174/// Diagnostics is emitted via \p ORE. It returns changed status.
175/// \p AllowSpeculation is whether values should be hoisted even if they are not
176/// guaranteed to execute in the loop, but are safe to speculatively execute.
181 bool AllowSpeculation);
182
183/// Return true if the induction variable \p IV in a Loop whose latch is
184/// \p LatchBlock would become dead if the exit test \p Cond were removed.
185/// Conservatively returns false if analysis is insufficient.
186bool isAlmostDeadIV(PHINode *IV, BasicBlock *LatchBlock, Value *Cond);
187
188/// This function deletes dead loops. The caller of this function needs to
189/// guarantee that the loop is infact dead.
190/// The function requires a bunch or prerequisites to be present:
191/// - The loop needs to be in LCSSA form
192/// - The loop needs to have a Preheader
193/// - A unique dedicated exit block must exist
194///
195/// This also updates the relevant analysis information in \p DT, \p SE, \p LI
196/// and \p MSSA if pointers to those are provided.
197/// It also updates the loop PM if an updater struct is provided.
198
200 LoopInfo *LI, MemorySSA *MSSA = nullptr);
201
202/// Remove the backedge of the specified loop. Handles loop nests and general
203/// loop structures subject to the precondition that the loop has no parent
204/// loop and has a single latch block. Preserves all listed analyses.
206 LoopInfo &LI, MemorySSA *MSSA);
207
208/// Try to promote memory values to scalars by sinking stores out of
209/// the loop and moving loads to before the loop. We do this by looping over
210/// the stores in the loop, looking for stores to Must pointers which are
211/// loop invariant. It takes a set of must-alias values, Loop exit blocks
212/// vector, loop exit blocks insertion point vector, PredIteratorCache,
213/// LoopInfo, DominatorTree, Loop, AliasSet information for all instructions
214/// of the loop and loop safety information as arguments.
215/// Diagnostics is emitted via \p ORE. It returns changed status.
216/// \p AllowSpeculation is whether values should be hoisted even if they are not
217/// guaranteed to execute in the loop, but are safe to speculatively execute.
224 bool AllowSpeculation, bool HasReadsOutsideSet);
225
226/// Does a BFS from a given node to all of its children inside a given loop.
227/// The returned vector of basic blocks includes the starting point.
230
231/// Returns the instructions that use values defined in the loop.
233
234/// Find a combination of metadata ("llvm.loop.vectorize.width" and
235/// "llvm.loop.vectorize.scalable.enable") for a loop and use it to construct a
236/// ElementCount. If the metadata "llvm.loop.vectorize.width" cannot be found
237/// then std::nullopt is returned.
238std::optional<ElementCount>
240
241/// Create a new loop identifier for a loop created from a loop transformation.
242///
243/// @param OrigLoopID The loop ID of the loop before the transformation.
244/// @param FollowupAttrs List of attribute names that contain attributes to be
245/// added to the new loop ID.
246/// @param InheritOptionsAttrsPrefix Selects which attributes should be inherited
247/// from the original loop. The following values
248/// are considered:
249/// nullptr : Inherit all attributes from @p OrigLoopID.
250/// "" : Do not inherit any attribute from @p OrigLoopID; only use
251/// those specified by a followup attribute.
252/// "<prefix>": Inherit all attributes except those which start with
253/// <prefix>; commonly used to remove metadata for the
254/// applied transformation.
255/// @param AlwaysNew If true, do not try to reuse OrigLoopID and never return
256/// std::nullopt.
257///
258/// @return The loop ID for the after-transformation loop. The following values
259/// can be returned:
260/// std::nullopt : No followup attribute was found; it is up to the
261/// transformation to choose attributes that make sense.
262/// @p OrigLoopID: The original identifier can be reused.
263/// nullptr : The new loop has no attributes.
264/// MDNode* : A new unique loop identifier.
265std::optional<MDNode *>
266makeFollowupLoopID(MDNode *OrigLoopID, ArrayRef<StringRef> FollowupAttrs,
267 const char *InheritOptionsAttrsPrefix = "",
268 bool AlwaysNew = false);
269
270/// Look for the loop attribute that disables all transformation heuristic.
271bool hasDisableAllTransformsHint(const Loop *L);
272
273/// Look for the loop attribute that disables the LICM transformation heuristics.
275
276/// The mode sets how eager a transformation should be applied.
278 /// The pass can use heuristics to determine whether a transformation should
279 /// be applied.
281
282 /// The transformation should be applied without considering a cost model.
284
285 /// The transformation should not be applied.
287
288 /// Force is a flag and should not be used alone.
289 TM_Force = 0x04,
290
291 /// The transformation was directed by the user, e.g. by a #pragma in
292 /// the source code. If the transformation could not be applied, a
293 /// warning should be emitted.
295
296 /// The transformation must not be applied. For instance, `#pragma clang loop
297 /// unroll(disable)` explicitly forbids any unrolling to take place. Unlike
298 /// general loop metadata, it must not be dropped. Most passes should not
299 /// behave differently under TM_Disable and TM_SuppressedByUser.
302
303/// @{
304/// Get the mode for LLVM's supported loop transformations.
310/// @}
311
312/// Set input string into loop metadata by keeping other values intact.
313/// If the string is already in loop metadata update value if it is
314/// different.
315void addStringMetadataToLoop(Loop *TheLoop, const char *MDString,
316 unsigned V = 0);
317
318/// Returns a loop's estimated trip count based on branch weight metadata.
319/// In addition if \p EstimatedLoopInvocationWeight is not null it is
320/// initialized with weight of loop's latch leading to the exit.
321/// Returns 0 when the count is estimated to be 0, or std::nullopt when a
322/// meaningful estimate can not be made.
323std::optional<unsigned>
325 unsigned *EstimatedLoopInvocationWeight = nullptr);
326
327/// Set a loop's branch weight metadata to reflect that loop has \p
328/// EstimatedTripCount iterations and \p EstimatedLoopInvocationWeight exits
329/// through latch. Returns true if metadata is successfully updated, false
330/// otherwise. Note that loop must have a latch block which controls loop exit
331/// in order to succeed.
332bool setLoopEstimatedTripCount(Loop *L, unsigned EstimatedTripCount,
333 unsigned EstimatedLoopInvocationWeight);
334
335/// Check inner loop (L) backedge count is known to be invariant on all
336/// iterations of its outer loop. If the loop has no parent, this is trivially
337/// true.
338bool hasIterationCountInvariantInParent(Loop *L, ScalarEvolution &SE);
339
340/// Helper to consistently add the set of standard passes to a loop pass's \c
341/// AnalysisUsage.
342///
343/// All loop passes should call this as part of implementing their \c
344/// getAnalysisUsage.
345void getLoopAnalysisUsage(AnalysisUsage &AU);
346
347/// Returns true if is legal to hoist or sink this instruction disregarding the
348/// possible introduction of faults. Reasoning about potential faulting
349/// instructions is the responsibility of the caller since it is challenging to
350/// do efficiently from within this routine.
351/// \p TargetExecutesOncePerLoop is true only when it is guaranteed that the
352/// target executes at most once per execution of the loop body. This is used
353/// to assess the legality of duplicating atomic loads. Generally, this is
354/// true when moving out of loop and not true when moving into loops.
355/// If \p ORE is set use it to emit optimization remarks.
356bool canSinkOrHoistInst(Instruction &I, AAResults *AA, DominatorTree *DT,
357 Loop *CurLoop, MemorySSAUpdater &MSSAU,
358 bool TargetExecutesOncePerLoop,
359 SinkAndHoistLICMFlags &LICMFlags,
360 OptimizationRemarkEmitter *ORE = nullptr);
361
362/// Returns the llvm.vector.reduce intrinsic that corresponds to the recurrence
363/// kind.
365
366/// Returns the arithmetic instruction opcode used when expanding a reduction.
368
369/// Returns the min/max intrinsic used when expanding a min/max reduction.
371
372/// Returns the min/max intrinsic used when expanding a min/max reduction.
374
375/// Returns the recurence kind used when expanding a min/max reduction.
377
378/// Returns the comparison predicate used when expanding a min/max reduction.
380
381/// Given information about an @llvm.vector.reduce.* intrinsic, return
382/// the identity value for the reduction.
383Value *getReductionIdentity(Intrinsic::ID RdxID, Type *Ty, FastMathFlags FMF);
384
385/// Given information about an recurrence kind, return the identity
386/// for the @llvm.vector.reduce.* used to generate it.
387Value *getRecurrenceIdentity(RecurKind K, Type *Tp, FastMathFlags FMF);
388
389/// Returns a Min/Max operation corresponding to MinMaxRecurrenceKind.
390/// The Builder's fast-math-flags must be set to propagate the expected values.
391Value *createMinMaxOp(IRBuilderBase &Builder, RecurKind RK, Value *Left,
392 Value *Right);
393
394/// Generates an ordered vector reduction using extracts to reduce the value.
395Value *getOrderedReduction(IRBuilderBase &Builder, Value *Acc, Value *Src,
396 unsigned Op, RecurKind MinMaxKind = RecurKind::None);
397
398/// Generates a vector reduction using shufflevectors to reduce the value.
399/// Fast-math-flags are propagated using the IRBuilder's setting.
400Value *getShuffleReduction(IRBuilderBase &Builder, Value *Src, unsigned Op,
402 RecurKind MinMaxKind = RecurKind::None);
403
404/// Create a reduction of the given vector. The reduction operation
405/// is described by the \p Opcode parameter. min/max reductions require
406/// additional information supplied in \p RdxKind.
407/// Fast-math-flags are propagated using the IRBuilder's setting.
408Value *createSimpleReduction(IRBuilderBase &B, Value *Src,
409 RecurKind RdxKind);
410/// Overloaded function to generate vector-predication intrinsics for
411/// reduction.
412Value *createSimpleReduction(VectorBuilder &VB, Value *Src,
413 const RecurrenceDescriptor &Desc);
414
415/// Create a reduction of the given vector \p Src for a reduction of the
416/// kind RecurKind::IAnyOf or RecurKind::FAnyOf. The reduction operation is
417/// described by \p Desc.
418Value *createAnyOfReduction(IRBuilderBase &B, Value *Src,
419 const RecurrenceDescriptor &Desc,
420 PHINode *OrigPhi);
421
422/// Create a reduction of the given vector \p Src for a reduction of the
423/// kind RecurKind::IFindLastIV or RecurKind::FFindLastIV. The reduction
424/// operation is described by \p Desc.
425Value *createFindLastIVReduction(IRBuilderBase &B, Value *Src,
426 const RecurrenceDescriptor &Desc);
427
428/// Create a generic reduction using a recurrence descriptor \p Desc
429/// Fast-math-flags are propagated using the RecurrenceDescriptor.
430Value *createReduction(IRBuilderBase &B, const RecurrenceDescriptor &Desc,
431 Value *Src, PHINode *OrigPhi = nullptr);
432
433/// Create an ordered reduction intrinsic using the given recurrence
434/// descriptor \p Desc.
435Value *createOrderedReduction(IRBuilderBase &B,
436 const RecurrenceDescriptor &Desc, Value *Src,
437 Value *Start);
438/// Overloaded function to generate vector-predication intrinsics for ordered
439/// reduction.
440Value *createOrderedReduction(VectorBuilder &VB,
441 const RecurrenceDescriptor &Desc, Value *Src,
442 Value *Start);
443
444/// Get the intersection (logical and) of all of the potential IR flags
445/// of each scalar operation (VL) that will be converted into a vector (I).
446/// If OpValue is non-null, we only consider operations similar to OpValue
447/// when intersecting.
448/// Flag set: NSW, NUW (if IncludeWrapFlags is true), exact, and all of
449/// fast-math.
450void propagateIRFlags(Value *I, ArrayRef<Value *> VL, Value *OpValue = nullptr,
451 bool IncludeWrapFlags = true);
452
453/// Returns true if we can prove that \p S is defined and always negative in
454/// loop \p L.
455bool isKnownNegativeInLoop(const SCEV *S, const Loop *L, ScalarEvolution &SE);
456
457/// Returns true if we can prove that \p S is defined and always non-negative in
458/// loop \p L.
459bool isKnownNonNegativeInLoop(const SCEV *S, const Loop *L,
460 ScalarEvolution &SE);
461/// Returns true if we can prove that \p S is defined and always positive in
462/// loop \p L.
463bool isKnownPositiveInLoop(const SCEV *S, const Loop *L, ScalarEvolution &SE);
464
465/// Returns true if we can prove that \p S is defined and always non-positive in
466/// loop \p L.
467bool isKnownNonPositiveInLoop(const SCEV *S, const Loop *L,
468 ScalarEvolution &SE);
469
470/// Returns true if \p S is defined and never is equal to signed/unsigned max.
471bool cannotBeMaxInLoop(const SCEV *S, const Loop *L, ScalarEvolution &SE,
472 bool Signed);
473
474/// Returns true if \p S is defined and never is equal to signed/unsigned min.
475bool cannotBeMinInLoop(const SCEV *S, const Loop *L, ScalarEvolution &SE,
476 bool Signed);
477
485
486/// If the final value of any expressions that are recurrent in the loop can
487/// be computed, substitute the exit values from the loop into any instructions
488/// outside of the loop that use the final values of the current expressions.
489/// Return the number of loop exit values that have been replaced, and the
490/// corresponding phi node will be added to DeadInsts.
491int rewriteLoopExitValues(Loop *L, LoopInfo *LI, TargetLibraryInfo *TLI,
492 ScalarEvolution *SE, const TargetTransformInfo *TTI,
493 SCEVExpander &Rewriter, DominatorTree *DT,
495 SmallVector<WeakTrackingVH, 16> &DeadInsts);
496
497/// Set weights for \p UnrolledLoop and \p RemainderLoop based on weights for
498/// \p OrigLoop and the following distribution of \p OrigLoop iteration among \p
499/// UnrolledLoop and \p RemainderLoop. \p UnrolledLoop receives weights that
500/// reflect TC/UF iterations, and \p RemainderLoop receives weights that reflect
501/// the remaining TC%UF iterations.
502///
503/// Note that \p OrigLoop may be equal to either \p UnrolledLoop or \p
504/// RemainderLoop in which case weights for \p OrigLoop are updated accordingly.
505/// Note also behavior is undefined if \p UnrolledLoop and \p RemainderLoop are
506/// equal. \p UF must be greater than zero.
507/// If \p OrigLoop has no profile info associated nothing happens.
508///
509/// This utility may be useful for such optimizations as unroller and
510/// vectorizer as it's typical transformation for them.
511void setProfileInfoAfterUnrolling(Loop *OrigLoop, Loop *UnrolledLoop,
512 Loop *RemainderLoop, uint64_t UF);
513
514/// Utility that implements appending of loops onto a worklist given a range.
515/// We want to process loops in postorder, but the worklist is a LIFO data
516/// structure, so we append to it in *reverse* postorder.
517/// For trees, a preorder traversal is a viable reverse postorder, so we
518/// actually append using a preorder walk algorithm.
519template <typename RangeT>
520void appendLoopsToWorklist(RangeT &&, SmallPriorityWorklist<Loop *, 4> &);
521/// Utility that implements appending of loops onto a worklist given a range.
522/// It has the same behavior as appendLoopsToWorklist, but assumes the range of
523/// loops has already been reversed, so it processes loops in the given order.
524template <typename RangeT>
525void appendReversedLoopsToWorklist(RangeT &&,
526 SmallPriorityWorklist<Loop *, 4> &);
527
528/// Utility that implements appending of loops onto a worklist given LoopInfo.
529/// Calls the templated utility taking a Range of loops, handing it the Loops
530/// in LoopInfo, iterated in reverse. This is because the loops are stored in
531/// RPO w.r.t. the control flow graph in LoopInfo. For the purpose of unrolling,
532/// loop deletion, and LICM, we largely want to work forward across the CFG so
533/// that we visit defs before uses and can propagate simplifications from one
534/// loop nest into the next. Calls appendReversedLoopsToWorklist with the
535/// already reversed loops in LI.
536/// FIXME: Consider changing the order in LoopInfo.
537void appendLoopsToWorklist(LoopInfo &, SmallPriorityWorklist<Loop *, 4> &);
538
539/// Recursively clone the specified loop and all of its children,
540/// mapping the blocks with the specified map.
541Loop *cloneLoop(Loop *L, Loop *PL, ValueToValueMapTy &VM,
542 LoopInfo *LI, LPPassManager *LPM);
543
544/// Add code that checks at runtime if the accessed arrays in \p PointerChecks
545/// overlap. Returns the final comparator value or NULL if no check is needed.
546Value *
547addRuntimeChecks(Instruction *Loc, Loop *TheLoop,
548 const SmallVectorImpl<RuntimePointerCheck> &PointerChecks,
549 SCEVExpander &Expander, bool HoistRuntimeChecks = false);
550
552 Instruction *Loc, ArrayRef<PointerDiffInfo> Checks, SCEVExpander &Expander,
553 function_ref<Value *(IRBuilderBase &, unsigned)> GetVF, unsigned IC);
554
555/// Struct to hold information about a partially invariant condition.
557 /// Instructions that need to be duplicated and checked for the unswitching
558 /// condition.
560
561 /// Constant to indicate for which value the condition is invariant.
563
564 /// True if the partially invariant path is no-op (=does not have any
565 /// side-effects and no loop value is used outside the loop).
566 bool PathIsNoop = true;
567
568 /// If the partially invariant path reaches a single exit block, ExitForPath
569 /// is set to that block. Otherwise it is nullptr.
571};
572
573/// Check if the loop header has a conditional branch that is not
574/// loop-invariant, because it involves load instructions. If all paths from
575/// either the true or false successor to the header or loop exists do not
576/// modify the memory feeding the condition, perform 'partial unswitching'. That
577/// is, duplicate the instructions feeding the condition in the pre-header. Then
578/// unswitch on the duplicated condition. The condition is now known in the
579/// unswitched version for the 'invariant' path through the original loop.
580///
581/// If the branch condition of the header is partially invariant, return a pair
582/// containing the instructions to duplicate and a boolean Constant to update
583/// the condition in the loops created for the true or false successors.
584std::optional<IVConditionInfo> hasPartialIVCondition(const Loop &L,
585 unsigned MSSAThreshold,
586 const MemorySSA &MSSA,
587 AAResults &AA);
588
589} // end namespace llvm
590
591#endif // LLVM_TRANSFORMS_UTILS_LOOPUTILS_H
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
early cse Early CSE w MemorySSA
Definition: EarlyCSE.cpp:1960
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:78
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:61
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition: InstrTypes.h:673
This is an important base class in LLVM.
Definition: Constant.h:42
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition: Dominators.h:162
This implementation of LoopSafetyInfo use ImplicitControlFlowTracking to give precise answers on "may...
Definition: MustExecute.h:131
Represents a single loop in the control flow graph.
Definition: LoopInfo.h:39
Metadata node.
Definition: Metadata.h:1069
Encapsulates MemorySSA, including all data associated with memory accesses.
Definition: MemorySSA.h:701
The optimization diagnostic interface.
PredIteratorCache - This class is an extremely trivial cache for predecessor iterator queries.
The main scalar evolution driver.
Flags controlling how much is checked when sinking or hoisting instructions.
Definition: LoopUtils.h:120
unsigned LicmMssaNoAccForPromotionCap
Definition: LoopUtils.h:139
A SetVector that performs no allocations if smaller than a certain size.
Definition: SetVector.h:370
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:573
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1196
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:74
@ BasicBlock
Various leaf nodes.
Definition: ISDOpcodes.h:71
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
Value * createSimpleReduction(IRBuilderBase &B, Value *Src, RecurKind RdxKind)
Create a reduction of the given vector.
Definition: LoopUtils.cpp:1278
std::optional< ElementCount > getOptionalElementCountLoopAttribute(const Loop *TheLoop)
Find a combination of metadata ("llvm.loop.vectorize.width" and "llvm.loop.vectorize....
Definition: LoopUtils.cpp:250
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:1954
std::optional< unsigned > getLoopEstimatedTripCount(Loop *L, unsigned *EstimatedLoopInvocationWeight=nullptr)
Returns a loop's estimated trip count based on branch weight metadata.
Definition: LoopUtils.cpp:850
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...
Intrinsic::ID getMinMaxReductionIntrinsicOp(Intrinsic::ID RdxID)
Returns the min/max intrinsic used when expanding a min/max reduction.
Definition: LoopUtils.cpp:989
std::pair< const RuntimeCheckingPtrGroup *, const RuntimeCheckingPtrGroup * > RuntimePointerCheck
A memcheck which made up of a pair of grouped pointers.
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:1161
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:1409
void appendReversedLoopsToWorklist(RangeT &&, SmallPriorityWorklist< Loop *, 4 > &)
Utility that implements appending of loops onto a worklist given a range.
Definition: LoopUtils.cpp:1789
bool formLCSSARecursively(Loop &L, const DominatorTree &DT, const LoopInfo *LI, ScalarEvolution *SE)
Put a loop nest into LCSSA form.
Definition: LCSSA.cpp:465
Value * getReductionIdentity(Intrinsic::ID RdxID, Type *Ty, FastMathFlags FMF)
Given information about an @llvm.vector.reduce.
Definition: LoopUtils.cpp:1228
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:263
unsigned getArithmeticReductionInstruction(Intrinsic::ID RdxID)
Returns the arithmetic instruction opcode used when expanding a reduction.
Definition: LoopUtils.cpp:960
Op::Description Desc
Value * createMinMaxOp(IRBuilderBase &Builder, RecurKind RK, Value *Left, Value *Right)
Returns a Min/Max operation corresponding to MinMaxRecurrenceKind.
Definition: LoopUtils.cpp:1076
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:449
void addStringMetadataToLoop(Loop *TheLoop, const char *MDString, unsigned V=0)
Set input string into loop metadata by keeping other values intact.
Definition: LoopUtils.cpp:214
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:1427
Value * createAnyOfReduction(IRBuilderBase &B, Value *Src, const RecurrenceDescriptor &Desc, PHINode *OrigPhi)
Create a reduction of the given vector Src for a reduction of the kind RecurKind::IAnyOf or RecurKind...
Definition: LoopUtils.cpp:1176
TransformationMode hasVectorizeTransformation(const Loop *L)
Definition: LoopUtils.cpp:391
bool hoistRegion(DomTreeNode *, AAResults *, LoopInfo *, DominatorTree *, AssumptionCache *, TargetLibraryInfo *, Loop *, MemorySSAUpdater &, ScalarEvolution *, ICFLoopSafetyInfo *, SinkAndHoistLICMFlags &, OptimizationRemarkEmitter *, bool, bool AllowSpeculation)
Walk the specified region of the CFG (defined by all blocks dominated by the specified block,...
Definition: LICM.cpp:875
SmallVector< Instruction *, 8 > findDefsUsedOutsideOfLoop(Loop *L)
Returns the instructions that use values defined in the loop.
Definition: LoopUtils.cpp:123
constexpr Intrinsic::ID getReductionIntrinsicID(RecurKind RK)
Returns the llvm.vector.reduce intrinsic that corresponds to the recurrence kind.
Definition: LoopUtils.cpp:922
TransformationMode hasUnrollAndJamTransformation(const Loop *L)
Definition: LoopUtils.cpp:373
void deleteDeadLoop(Loop *L, DominatorTree *DT, ScalarEvolution *SE, LoopInfo *LI, MemorySSA *MSSA=nullptr)
This function deletes dead loops.
Definition: LoopUtils.cpp:484
bool hasDisableAllTransformsHint(const Loop *L)
Look for the loop attribute that disables all transformation heuristic.
Definition: LoopUtils.cpp:344
Value * createOrderedReduction(IRBuilderBase &B, const RecurrenceDescriptor &Desc, Value *Src, Value *Start)
Create an ordered reduction intrinsic using the given recurrence descriptor Desc.
Definition: LoopUtils.cpp:1341
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:1118
Value * createReduction(IRBuilderBase &B, const RecurrenceDescriptor &Desc, Value *Src, PHINode *OrigPhi=nullptr)
Create a generic reduction using a recurrence descriptor Desc Fast-math-flags are propagated using th...
Definition: LoopUtils.cpp:1323
TransformationMode hasUnrollTransformation(const Loop *L)
Definition: LoopUtils.cpp:352
DomTreeNodeBase< BasicBlock > DomTreeNode
Definition: Dominators.h:92
TransformationMode hasDistributeTransformation(const Loop *L)
Definition: LoopUtils.cpp:427
void breakLoopBackedge(Loop *L, DominatorTree &DT, ScalarEvolution &SE, LoopInfo &LI, MemorySSA *MSSA)
Remove the backedge of the specified loop.
Definition: LoopUtils.cpp:725
void getLoopAnalysisUsage(AnalysisUsage &AU)
Helper to consistently add the set of standard passes to a loop pass's AnalysisUsage.
Definition: LoopUtils.cpp:141
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:1368
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:1402
TargetTransformInfo TTI
CmpInst::Predicate getMinMaxReductionPredicate(RecurKind RK)
Returns the comparison predicate used when expanding a min/max reduction.
Definition: LoopUtils.cpp:1054
TransformationMode hasLICMVersioningTransformation(const Loop *L)
Definition: LoopUtils.cpp:437
Value * createFindLastIVReduction(IRBuilderBase &B, Value *Src, const RecurrenceDescriptor &Desc)
Create a reduction of the given vector Src for a reduction of the kind RecurKind::IFindLastIV or Recu...
Definition: LoopUtils.cpp:1211
TransformationMode
The mode sets how eager a transformation should be applied.
Definition: LoopUtils.h:277
@ TM_Unspecified
The pass can use heuristics to determine whether a transformation should be applied.
Definition: LoopUtils.h:280
@ TM_SuppressedByUser
The transformation must not be applied.
Definition: LoopUtils.h:300
@ TM_ForcedByUser
The transformation was directed by the user, e.g.
Definition: LoopUtils.h:294
@ TM_Disable
The transformation should not be applied.
Definition: LoopUtils.h:286
@ TM_Force
Force is a flag and should not be used alone.
Definition: LoopUtils.h:289
@ TM_Enable
The transformation should be applied without considering a cost model.
Definition: LoopUtils.h:283
bool hasDisableLICMTransformsHint(const Loop *L)
Look for the loop attribute that disables the LICM transformation heuristics.
Definition: LoopUtils.cpp:348
RecurKind
These are the kinds of recurrences that we support.
Definition: IVDescriptors.h:33
@ None
Not a recurrence.
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:868
Value * getRecurrenceIdentity(RecurKind K, Type *Tp, FastMathFlags FMF)
Given information about an recurrence kind, return the identity for the @llvm.vector....
Definition: LoopUtils.cpp:1270
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:1761
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:57
DWARFExpression::Operation Op
void appendLoopsToWorklist(RangeT &&, SmallPriorityWorklist< Loop *, 4 > &)
Utility that implements appending of loops onto a worklist given a range.
Definition: LoopUtils.cpp:1814
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:1388
ValueMap< const Value *, WeakTrackingVH > ValueToValueMapTy
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:325
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:900
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:470
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:1549
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:555
Value * addDiffRuntimeChecks(Instruction *Loc, ArrayRef< PointerDiffInfo > Checks, SCEVExpander &Expander, function_ref< Value *(IRBuilderBase &, unsigned)> GetVF, unsigned IC)
Definition: LoopUtils.cpp:2012
RecurKind getMinMaxReductionRecurKind(Intrinsic::ID RdxID)
Returns the recurence kind used when expanding a min/max reduction.
Definition: LoopUtils.cpp:1035
ReplaceExitVal
Definition: LoopUtils.h:478
@ UnusedIndVarInLoop
Definition: LoopUtils.h:482
@ OnlyCheapRepl
Definition: LoopUtils.h:480
@ NeverRepl
Definition: LoopUtils.h:479
@ NoHardUse
Definition: LoopUtils.h:481
@ AlwaysRepl
Definition: LoopUtils.h:483
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:2058
bool formLCSSA(Loop &L, const DominatorTree &DT, const LoopInfo *LI, ScalarEvolution *SE)
Put loop into LCSSA form.
Definition: LCSSA.cpp:443
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:1969
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:1416
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:1395
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:622
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:1093
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:1831
#define N
Struct to hold information about a partially invariant condition.
Definition: LoopUtils.h:556
BasicBlock * ExitForPath
If the partially invariant path reaches a single exit block, ExitForPath is set to that block.
Definition: LoopUtils.h:570
SmallVector< Instruction * > InstToDuplicate
Instructions that need to be duplicated and checked for the unswitching condition.
Definition: LoopUtils.h:559
Constant * KnownValue
Constant to indicate for which value the condition is invariant.
Definition: LoopUtils.h:562
bool PathIsNoop
True if the partially invariant path is no-op (=does not have any side-effects and no loop value is u...
Definition: LoopUtils.h:566