LLVM 22.0.0git
LoopInfo.h
Go to the documentation of this file.
1//===- llvm/Analysis/LoopInfo.h - Natural Loop Calculator -------*- 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 declares a GenericLoopInfo instantiation for LLVM IR.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_ANALYSIS_LOOPINFO_H
14#define LLVM_ANALYSIS_LOOPINFO_H
15
18#include "llvm/IR/PassManager.h"
19#include "llvm/Pass.h"
22#include <optional>
23#include <utility>
24
25namespace llvm {
26
27class DominatorTree;
28class InductionDescriptor;
29class LoopInfo;
30class Loop;
31class MemorySSAUpdater;
32class ScalarEvolution;
33class raw_ostream;
34
35// Implementation in Support/GenericLoopInfoImpl.h
37
38/// Represents a single loop in the control flow graph. Note that not all SCCs
39/// in the CFG are necessarily loops.
41public:
42 /// A range representing the start and end location of a loop.
43 class LocRange {
44 DebugLoc Start;
46
47 public:
48 LocRange() = default;
49 LocRange(DebugLoc Start) : Start(Start), End(Start) {}
51 : Start(std::move(Start)), End(std::move(End)) {}
52
53 const DebugLoc &getStart() const { return Start; }
54 const DebugLoc &getEnd() const { return End; }
55
56 /// Check for null.
57 ///
58 explicit operator bool() const { return Start && End; }
59 };
60
61 /// Return true if the specified value is loop invariant.
62 bool isLoopInvariant(const Value *V, bool HasCoroSuspendInst = false) const;
63
64 /// Return true if all the operands of the specified instruction are loop
65 /// invariant.
66 bool hasLoopInvariantOperands(const Instruction *I,
67 bool HasCoroSuspendInst = false) const;
68
69 /// If the given value is an instruction inside of the loop and it can be
70 /// hoisted, do so to make it trivially loop-invariant.
71 /// Return true if \c V is already loop-invariant, and false if \c V can't
72 /// be made loop-invariant. If \c V is made loop-invariant, \c Changed is
73 /// set to true. This function can be used as a slightly more aggressive
74 /// replacement for isLoopInvariant.
75 ///
76 /// If InsertPt is specified, it is the point to hoist instructions to.
77 /// If null, the terminator of the loop preheader is used.
78 ///
79 bool makeLoopInvariant(Value *V, bool &Changed,
80 Instruction *InsertPt = nullptr,
81 MemorySSAUpdater *MSSAU = nullptr,
82 ScalarEvolution *SE = nullptr) const;
83
84 /// If the given instruction is inside of the loop and it can be hoisted, do
85 /// so to make it trivially loop-invariant.
86 /// Return true if \c I is already loop-invariant, and false if \c I can't
87 /// be made loop-invariant. If \c I is made loop-invariant, \c Changed is
88 /// set to true. This function can be used as a slightly more aggressive
89 /// replacement for isLoopInvariant.
90 ///
91 /// If InsertPt is specified, it is the point to hoist instructions to.
92 /// If null, the terminator of the loop preheader is used.
93 ///
94 bool makeLoopInvariant(Instruction *I, bool &Changed,
95 Instruction *InsertPt = nullptr,
96 MemorySSAUpdater *MSSAU = nullptr,
97 ScalarEvolution *SE = nullptr) const;
98
99 /// Check to see if the loop has a canonical induction variable: an integer
100 /// recurrence that starts at 0 and increments by one each time through the
101 /// loop. If so, return the phi node that corresponds to it.
102 ///
103 /// The IndVarSimplify pass transforms loops to have a canonical induction
104 /// variable.
105 ///
106 PHINode *getCanonicalInductionVariable() const;
107
108 /// Get the latch condition instruction.
109 ICmpInst *getLatchCmpInst() const;
110
111 /// Obtain the unique incoming and back edge. Return false if they are
112 /// non-unique or the loop is dead; otherwise, return true.
113 bool getIncomingAndBackEdge(BasicBlock *&Incoming,
114 BasicBlock *&Backedge) const;
115
116 /// Below are some utilities to get the loop guard, loop bounds and induction
117 /// variable, and to check if a given phinode is an auxiliary induction
118 /// variable, if the loop is guarded, and if the loop is canonical.
119 ///
120 /// Here is an example:
121 /// \code
122 /// for (int i = lb; i < ub; i+=step)
123 /// <loop body>
124 /// --- pseudo LLVMIR ---
125 /// beforeloop:
126 /// guardcmp = (lb < ub)
127 /// if (guardcmp) goto preheader; else goto afterloop
128 /// preheader:
129 /// loop:
130 /// i_1 = phi[{lb, preheader}, {i_2, latch}]
131 /// <loop body>
132 /// i_2 = i_1 + step
133 /// latch:
134 /// cmp = (i_2 < ub)
135 /// if (cmp) goto loop
136 /// exit:
137 /// afterloop:
138 /// \endcode
139 ///
140 /// - getBounds
141 /// - getInitialIVValue --> lb
142 /// - getStepInst --> i_2 = i_1 + step
143 /// - getStepValue --> step
144 /// - getFinalIVValue --> ub
145 /// - getCanonicalPredicate --> '<'
146 /// - getDirection --> Increasing
147 ///
148 /// - getInductionVariable --> i_1
149 /// - isAuxiliaryInductionVariable(x) --> true if x == i_1
150 /// - getLoopGuardBranch()
151 /// --> `if (guardcmp) goto preheader; else goto afterloop`
152 /// - isGuarded() --> true
153 /// - isCanonical --> false
154 struct LoopBounds {
155 /// Return the LoopBounds object if
156 /// - the given \p IndVar is an induction variable
157 /// - the initial value of the induction variable can be found
158 /// - the step instruction of the induction variable can be found
159 /// - the final value of the induction variable can be found
160 ///
161 /// Else std::nullopt.
162 LLVM_ABI static std::optional<Loop::LoopBounds>
163 getBounds(const Loop &L, PHINode &IndVar, ScalarEvolution &SE);
164
165 /// Get the initial value of the loop induction variable.
166 Value &getInitialIVValue() const { return InitialIVValue; }
167
168 /// Get the instruction that updates the loop induction variable.
169 Instruction &getStepInst() const { return StepInst; }
170
171 /// Get the step that the loop induction variable gets updated by in each
172 /// loop iteration. Return nullptr if not found.
173 Value *getStepValue() const { return StepValue; }
174
175 /// Get the final value of the loop induction variable.
176 Value &getFinalIVValue() const { return FinalIVValue; }
177
178 /// Return the canonical predicate for the latch compare instruction, if
179 /// able to be calcuated. Else BAD_ICMP_PREDICATE.
180 ///
181 /// A predicate is considered as canonical if requirements below are all
182 /// satisfied:
183 /// 1. The first successor of the latch branch is the loop header
184 /// If not, inverse the predicate.
185 /// 2. One of the operands of the latch comparison is StepInst
186 /// If not, and
187 /// - if the current calcuated predicate is not ne or eq, flip the
188 /// predicate.
189 /// - else if the loop is increasing, return slt
190 /// (notice that it is safe to change from ne or eq to sign compare)
191 /// - else if the loop is decreasing, return sgt
192 /// (notice that it is safe to change from ne or eq to sign compare)
193 ///
194 /// Here is an example when both (1) and (2) are not satisfied:
195 /// \code
196 /// loop.header:
197 /// %iv = phi [%initialiv, %loop.preheader], [%inc, %loop.header]
198 /// %inc = add %iv, %step
199 /// %cmp = slt %iv, %finaliv
200 /// br %cmp, %loop.exit, %loop.header
201 /// loop.exit:
202 /// \endcode
203 /// - The second successor of the latch branch is the loop header instead
204 /// of the first successor (slt -> sge)
205 /// - The first operand of the latch comparison (%cmp) is the IndVar (%iv)
206 /// instead of the StepInst (%inc) (sge -> sgt)
207 ///
208 /// The predicate would be sgt if both (1) and (2) are satisfied.
209 /// getCanonicalPredicate() returns sgt for this example.
210 /// Note: The IR is not changed.
211 LLVM_ABI ICmpInst::Predicate getCanonicalPredicate() const;
212
213 /// An enum for the direction of the loop
214 /// - for (int i = 0; i < ub; ++i) --> Increasing
215 /// - for (int i = ub; i > 0; --i) --> Descresing
216 /// - for (int i = x; i != y; i+=z) --> Unknown
217 enum class Direction { Increasing, Decreasing, Unknown };
218
219 /// Get the direction of the loop.
220 LLVM_ABI Direction getDirection() const;
221
222 private:
223 LoopBounds(const Loop &Loop, Value &I, Instruction &SI, Value *SV, Value &F,
224 ScalarEvolution &SE)
225 : L(Loop), InitialIVValue(I), StepInst(SI), StepValue(SV),
226 FinalIVValue(F), SE(SE) {}
227
228 const Loop &L;
229
230 // The initial value of the loop induction variable
231 Value &InitialIVValue;
232
233 // The instruction that updates the loop induction variable
234 Instruction &StepInst;
235
236 // The value that the loop induction variable gets updated by in each loop
237 // iteration
238 Value *StepValue;
239
240 // The final value of the loop induction variable
241 Value &FinalIVValue;
242
243 ScalarEvolution &SE;
244 };
245
246 /// Return the struct LoopBounds collected if all struct members are found,
247 /// else std::nullopt.
248 std::optional<LoopBounds> getBounds(ScalarEvolution &SE) const;
249
250 /// Return the loop induction variable if found, else return nullptr.
251 /// An instruction is considered as the loop induction variable if
252 /// - it is an induction variable of the loop; and
253 /// - it is used to determine the condition of the branch in the loop latch
254 ///
255 /// Note: the induction variable doesn't need to be canonical, i.e. starts at
256 /// zero and increments by one each time through the loop (but it can be).
257 PHINode *getInductionVariable(ScalarEvolution &SE) const;
258
259 /// Get the loop induction descriptor for the loop induction variable. Return
260 /// true if the loop induction variable is found.
261 bool getInductionDescriptor(ScalarEvolution &SE,
262 InductionDescriptor &IndDesc) const;
263
264 /// Return true if the given PHINode \p AuxIndVar is
265 /// - in the loop header
266 /// - not used outside of the loop
267 /// - incremented by a loop invariant step for each loop iteration
268 /// - step instruction opcode should be add or sub
269 /// Note: auxiliary induction variable is not required to be used in the
270 /// conditional branch in the loop latch. (but it can be)
271 bool isAuxiliaryInductionVariable(PHINode &AuxIndVar,
272 ScalarEvolution &SE) const;
273
274 /// Return the loop guard branch, if it exists.
275 ///
276 /// This currently only works on simplified loop, as it requires a preheader
277 /// and a latch to identify the guard. It will work on loops of the form:
278 /// \code
279 /// GuardBB:
280 /// br cond1, Preheader, ExitSucc <== GuardBranch
281 /// Preheader:
282 /// br Header
283 /// Header:
284 /// ...
285 /// br Latch
286 /// Latch:
287 /// br cond2, Header, ExitBlock
288 /// ExitBlock:
289 /// br ExitSucc
290 /// ExitSucc:
291 /// \endcode
292 BranchInst *getLoopGuardBranch() const;
293
294 /// Return true iff the loop is
295 /// - in simplify rotated form, and
296 /// - guarded by a loop guard branch.
297 bool isGuarded() const { return (getLoopGuardBranch() != nullptr); }
298
299 /// Return true if the loop is in rotated form.
300 ///
301 /// This does not check if the loop was rotated by loop rotation, instead it
302 /// only checks if the loop is in rotated form (has a valid latch that exists
303 /// the loop).
304 bool isRotatedForm() const {
305 assert(!isInvalid() && "Loop not in a valid state!");
306 BasicBlock *Latch = getLoopLatch();
307 return Latch && isLoopExiting(Latch);
308 }
309
310 /// Return true if the loop induction variable starts at zero and increments
311 /// by one each time through the loop.
312 bool isCanonical(ScalarEvolution &SE) const;
313
314 /// Return true if the Loop is in LCSSA form. If \p IgnoreTokens is set to
315 /// true, token values defined inside loop are allowed to violate LCSSA form.
316 bool isLCSSAForm(const DominatorTree &DT, bool IgnoreTokens = true) const;
317
318 /// Return true if this Loop and all inner subloops are in LCSSA form. If \p
319 /// IgnoreTokens is set to true, token values defined inside loop are allowed
320 /// to violate LCSSA form.
321 bool isRecursivelyLCSSAForm(const DominatorTree &DT, const LoopInfo &LI,
322 bool IgnoreTokens = true) const;
323
324 /// Return true if the Loop is in the form that the LoopSimplify form
325 /// transforms loops to, which is sometimes called normal form.
326 bool isLoopSimplifyForm() const;
327
328 /// Return true if the loop body is safe to clone in practice.
329 bool isSafeToClone() const;
330
331 /// Returns true if the loop is annotated parallel.
332 ///
333 /// A parallel loop can be assumed to not contain any dependencies between
334 /// iterations by the compiler. That is, any loop-carried dependency checking
335 /// can be skipped completely when parallelizing the loop on the target
336 /// machine. Thus, if the parallel loop information originates from the
337 /// programmer, e.g. via the OpenMP parallel for pragma, it is the
338 /// programmer's responsibility to ensure there are no loop-carried
339 /// dependencies. The final execution order of the instructions across
340 /// iterations is not guaranteed, thus, the end result might or might not
341 /// implement actual concurrent execution of instructions across multiple
342 /// iterations.
343 bool isAnnotatedParallel() const;
344
345 /// Return the llvm.loop loop id metadata node for this loop if it is present.
346 ///
347 /// If this loop contains the same llvm.loop metadata on each branch to the
348 /// header then the node is returned. If any latch instruction does not
349 /// contain llvm.loop or if multiple latches contain different nodes then
350 /// 0 is returned.
351 MDNode *getLoopID() const;
352 /// Set the llvm.loop loop id metadata for this loop.
353 ///
354 /// The LoopID metadata node will be added to each terminator instruction in
355 /// the loop that branches to the loop header.
356 ///
357 /// The LoopID metadata node should have one or more operands and the first
358 /// operand should be the node itself.
359 void setLoopID(MDNode *LoopID) const;
360
361 /// Add llvm.loop.unroll.disable to this loop's loop id metadata.
362 ///
363 /// Remove existing unroll metadata and add unroll disable metadata to
364 /// indicate the loop has already been unrolled. This prevents a loop
365 /// from being unrolled more than is directed by a pragma if the loop
366 /// unrolling pass is run more than once (which it generally is).
367 void setLoopAlreadyUnrolled();
368
369 /// Add llvm.loop.mustprogress to this loop's loop id metadata.
370 void setLoopMustProgress();
371
372 void dump() const;
373 void dumpVerbose() const;
374
375 /// Return the debug location of the start of this loop.
376 /// This looks for a BB terminating instruction with a known debug
377 /// location by looking at the preheader and header blocks. If it
378 /// cannot find a terminating instruction with location information,
379 /// it returns an unknown location.
380 DebugLoc getStartLoc() const;
381
382 /// Return the source code span of the loop.
383 LocRange getLocRange() const;
384
385 /// Return a string containing the debug location of the loop (file name +
386 /// line number if present, otherwise module name). Meant to be used for debug
387 /// printing within LLVM_DEBUG.
388 std::string getLocStr() const;
389
391 if (BasicBlock *Header = getHeader())
392 if (Header->hasName())
393 return Header->getName();
394 return "<unnamed loop>";
395 }
396
397private:
398 Loop() = default;
399
401 friend class LoopBase<BasicBlock, Loop>;
402 explicit Loop(BasicBlock *BB) : LoopBase<BasicBlock, Loop>(BB) {}
403 ~Loop() = default;
404};
405
406// Implementation in Support/GenericLoopInfoImpl.h
408
411
412 friend class LoopBase<BasicBlock, Loop>;
413
414 void operator=(const LoopInfo &) = delete;
415 LoopInfo(const LoopInfo &) = delete;
416
417public:
418 LoopInfo() = default;
421
422 LoopInfo(LoopInfo &&Arg) : BaseT(std::move(static_cast<BaseT &>(Arg))) {}
424 BaseT::operator=(std::move(static_cast<BaseT &>(RHS)));
425 return *this;
426 }
427
428 /// Handle invalidation explicitly.
429 LLVM_ABI bool invalidate(Function &F, const PreservedAnalyses &PA,
431
432 // Most of the public interface is provided via LoopInfoBase.
433
434 /// Update LoopInfo after removing the last backedge from a loop. This updates
435 /// the loop forest and parent loops for each block so that \c L is no longer
436 /// referenced, but does not actually delete \c L immediately. The pointer
437 /// will remain valid until this LoopInfo's memory is released.
438 LLVM_ABI void erase(Loop *L);
439
440 /// Returns true if replacing From with To everywhere is guaranteed to
441 /// preserve LCSSA form.
443 // Preserving LCSSA form is only problematic if the replacing value is an
444 // instruction.
445 Instruction *I = dyn_cast<Instruction>(To);
446 if (!I)
447 return true;
448 // If both instructions are defined in the same basic block then replacement
449 // cannot break LCSSA form.
450 if (I->getParent() == From->getParent())
451 return true;
452 // If the instruction is not defined in a loop then it can safely replace
453 // anything.
454 Loop *ToLoop = getLoopFor(I->getParent());
455 if (!ToLoop)
456 return true;
457 // If the replacing instruction is defined in the same loop as the original
458 // instruction, or in a loop that contains it as an inner loop, then using
459 // it as a replacement will not break LCSSA form.
460 return ToLoop->contains(getLoopFor(From->getParent()));
461 }
462
463 /// Checks if moving a specific instruction can break LCSSA in any loop.
464 ///
465 /// Return true if moving \p Inst to before \p NewLoc will break LCSSA,
466 /// assuming that the function containing \p Inst and \p NewLoc is currently
467 /// in LCSSA form.
469 assert(Inst->getFunction() == NewLoc->getFunction() &&
470 "Can't reason about IPO!");
471
472 auto *OldBB = Inst->getParent();
473 auto *NewBB = NewLoc->getParent();
474
475 // Movement within the same loop does not break LCSSA (the equality check is
476 // to avoid doing a hashtable lookup in case of intra-block movement).
477 if (OldBB == NewBB)
478 return true;
479
480 auto *OldLoop = getLoopFor(OldBB);
481 auto *NewLoop = getLoopFor(NewBB);
482
483 if (OldLoop == NewLoop)
484 return true;
485
486 // Check if Outer contains Inner; with the null loop counting as the
487 // "outermost" loop.
488 auto Contains = [](const Loop *Outer, const Loop *Inner) {
489 return !Outer || Outer->contains(Inner);
490 };
491
492 // To check that the movement of Inst to before NewLoc does not break LCSSA,
493 // we need to check two sets of uses for possible LCSSA violations at
494 // NewLoc: the users of NewInst, and the operands of NewInst.
495
496 // If we know we're hoisting Inst out of an inner loop to an outer loop,
497 // then the uses *of* Inst don't need to be checked.
498
499 if (!Contains(NewLoop, OldLoop)) {
500 for (Use &U : Inst->uses()) {
501 auto *UI = cast<Instruction>(U.getUser());
502 auto *UBB = isa<PHINode>(UI) ? cast<PHINode>(UI)->getIncomingBlock(U)
503 : UI->getParent();
504 if (UBB != NewBB && getLoopFor(UBB) != NewLoop)
505 return false;
506 }
507 }
508
509 // If we know we're sinking Inst from an outer loop into an inner loop, then
510 // the *operands* of Inst don't need to be checked.
511
512 if (!Contains(OldLoop, NewLoop)) {
513 // See below on why we can't handle phi nodes here.
514 if (isa<PHINode>(Inst))
515 return false;
516
517 for (Use &U : Inst->operands()) {
518 auto *DefI = dyn_cast<Instruction>(U.get());
519 if (!DefI)
520 return false;
521
522 // This would need adjustment if we allow Inst to be a phi node -- the
523 // new use block won't simply be NewBB.
524
525 auto *DefBlock = DefI->getParent();
526 if (DefBlock != NewBB && getLoopFor(DefBlock) != NewLoop)
527 return false;
528 }
529 }
530
531 return true;
532 }
533
534 // Return true if a new use of V added in ExitBB would require an LCSSA PHI
535 // to be inserted at the beginning of the block. Note that V is assumed to
536 // dominate ExitBB, and ExitBB must be the exit block of some loop. The
537 // IR is assumed to be in LCSSA form before the planned insertion.
538 LLVM_ABI bool
539 wouldBeOutOfLoopUseRequiringLCSSA(const Value *V,
540 const BasicBlock *ExitBB) const;
541};
542
543/// Enable verification of loop info.
544///
545/// The flag enables checks which are expensive and are disabled by default
546/// unless the `EXPENSIVE_CHECKS` macro is defined. The `-verify-loop-info`
547/// flag allows the checks to be enabled selectively without re-compilation.
548LLVM_ABI extern bool VerifyLoopInfo;
549
550// Allow clients to walk the list of nested loops...
551template <> struct GraphTraits<const Loop *> {
552 typedef const Loop *NodeRef;
554
555 static NodeRef getEntryNode(const Loop *L) { return L; }
556 static ChildIteratorType child_begin(NodeRef N) { return N->begin(); }
557 static ChildIteratorType child_end(NodeRef N) { return N->end(); }
558};
559
560template <> struct GraphTraits<Loop *> {
561 typedef Loop *NodeRef;
563
564 static NodeRef getEntryNode(Loop *L) { return L; }
565 static ChildIteratorType child_begin(NodeRef N) { return N->begin(); }
566 static ChildIteratorType child_end(NodeRef N) { return N->end(); }
567};
568
569/// Analysis pass that exposes the \c LoopInfo for a function.
572 LLVM_ABI static AnalysisKey Key;
573
574public:
576
578};
579
580/// Printer pass for the \c LoopAnalysis results.
583
584public:
587 static bool isRequired() { return true; }
588};
589
590/// Verifier pass for the \c LoopAnalysis results.
593 static bool isRequired() { return true; }
594};
595
596/// The legacy pass manager's analysis pass to compute loop information.
598 LoopInfo LI;
599
600public:
601 static char ID; // Pass identification, replacement for typeid
602
604
605 LoopInfo &getLoopInfo() { return LI; }
606 const LoopInfo &getLoopInfo() const { return LI; }
607
608 /// Calculate the natural loop information for a given function.
609 bool runOnFunction(Function &F) override;
610
611 void verifyAnalysis() const override;
612
613 void releaseMemory() override { LI.releaseMemory(); }
614
615 void print(raw_ostream &O, const Module *M = nullptr) const override;
616
617 void getAnalysisUsage(AnalysisUsage &AU) const override;
618};
619
620/// Function to print a loop's contents as LLVM's text IR assembly.
621LLVM_ABI void printLoop(Loop &L, raw_ostream &OS,
622 const std::string &Banner = "");
623
624/// Find and return the loop attribute node for the attribute @p Name in
625/// @p LoopID. Return nullptr if there is no such attribute.
626LLVM_ABI MDNode *findOptionMDForLoopID(MDNode *LoopID, StringRef Name);
627
628/// Find string metadata for a loop.
629///
630/// Returns the MDNode where the first operand is the metadata's name. The
631/// following operands are the metadata's values. If no metadata with @p Name is
632/// found, return nullptr.
633LLVM_ABI MDNode *findOptionMDForLoop(const Loop *TheLoop, StringRef Name);
634
635LLVM_ABI std::optional<bool> getOptionalBoolLoopAttribute(const Loop *TheLoop,
636 StringRef Name);
637
638/// Returns true if Name is applied to TheLoop and enabled.
639LLVM_ABI bool getBooleanLoopAttribute(const Loop *TheLoop, StringRef Name);
640
641/// Find named metadata for a loop with an integer value.
642LLVM_ABI std::optional<int> getOptionalIntLoopAttribute(const Loop *TheLoop,
643 StringRef Name);
644
645/// Find named metadata for a loop with an integer value. Return \p Default if
646/// not set.
647LLVM_ABI int getIntLoopAttribute(const Loop *TheLoop, StringRef Name,
648 int Default = 0);
649
650/// Find string metadata for loop
651///
652/// If it has a value (e.g. {"llvm.distribute", 1} return the value as an
653/// operand or null otherwise. If the string metadata is not found return
654/// Optional's not-a-value.
655LLVM_ABI std::optional<const MDOperand *>
656findStringMetadataForLoop(const Loop *TheLoop, StringRef Name);
657
658/// Find the convergence heart of the loop.
659LLVM_ABI CallBase *getLoopConvergenceHeart(const Loop *TheLoop);
660
661/// Look for the loop attribute that requires progress within the loop.
662/// Note: Most consumers probably want "isMustProgress" which checks
663/// the containing function attribute too.
664LLVM_ABI bool hasMustProgress(const Loop *L);
665
666/// Return true if this loop can be assumed to make progress. (i.e. can't
667/// be infinite without side effects without also being undefined)
668LLVM_ABI bool isMustProgress(const Loop *L);
669
670/// Return true if this loop can be assumed to run for a finite number of
671/// iterations.
672LLVM_ABI bool isFinite(const Loop *L);
673
674/// Return whether an MDNode might represent an access group.
675///
676/// Access group metadata nodes have to be distinct and empty. Being
677/// always-empty ensures that it never needs to be changed (which -- because
678/// MDNodes are designed immutable -- would require creating a new MDNode). Note
679/// that this is not a sufficient condition: not every distinct and empty NDNode
680/// is representing an access group.
681LLVM_ABI bool isValidAsAccessGroup(MDNode *AccGroup);
682
683/// Create a new LoopID after the loop has been transformed.
684///
685/// This can be used when no follow-up loop attributes are defined
686/// (llvm::makeFollowupLoopID returning None) to stop transformations to be
687/// applied again.
688///
689/// @param Context The LLVMContext in which to create the new LoopID.
690/// @param OrigLoopID The original LoopID; can be nullptr if the original
691/// loop has no LoopID.
692/// @param RemovePrefixes Remove all loop attributes that have these prefixes.
693/// Use to remove metadata of the transformation that has
694/// been applied.
695/// @param AddAttrs Add these loop attributes to the new LoopID.
696///
697/// @return A new LoopID that can be applied using Loop::setLoopID().
699makePostTransformationMetadata(llvm::LLVMContext &Context, MDNode *OrigLoopID,
700 llvm::ArrayRef<llvm::StringRef> RemovePrefixes,
702} // namespace llvm
703
704#endif
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
BlockVerifier::State From
#define LLVM_ABI
Definition: Compiler.h:213
#define LLVM_TEMPLATE_ABI
Definition: Compiler.h:214
static bool isCanonical(const MDString *S)
std::string Name
bool End
Definition: ELF_riscv.cpp:480
static bool runOnFunction(Function &F, bool PostInlining)
This file defines the little GraphTraits<X> template class that should be specialized by classes that...
This header defines various interfaces for pass management in LLVM.
Loop::LoopBounds::Direction Direction
Definition: LoopInfo.cpp:243
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
StandardInstrumentations SI(Mod->getContext(), Debug, VerifyEach)
raw_pwrite_stream & OS
static bool Contains(directive::VersionRange V, int P)
Definition: Spelling.cpp:18
Value * RHS
API to communicate dependencies between analyses during invalidation.
Definition: PassManager.h:294
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:255
Represent the analysis usage information of a pass.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
LLVM Basic Block Representation.
Definition: BasicBlock.h:62
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition: InstrTypes.h:678
A debug info location.
Definition: DebugLoc.h:124
Core dominator tree base class.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition: Dominators.h:165
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:314
This instruction compares its operands according to the predicate given to the constructor.
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
Definition: Instruction.cpp:82
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:68
Analysis pass that exposes the LoopInfo for a function.
Definition: LoopInfo.h:570
LoopInfo Result
Definition: LoopInfo.h:575
Instances of this class are used to represent loops that are detected in the flow graph.
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
This class builds and contains all of the top-level loop structures in the specified function.
std::vector< Loop * >::const_iterator iterator
iterator/begin/end - The interface to the top-level loops in the current function.
The legacy pass manager's analysis pass to compute loop information.
Definition: LoopInfo.h:597
const LoopInfo & getLoopInfo() const
Definition: LoopInfo.h:606
LoopInfo & getLoopInfo()
Definition: LoopInfo.h:605
void releaseMemory() override
releaseMemory() - This member can be implemented by a pass if it wants to be able to release its memo...
Definition: LoopInfo.h:613
LoopInfo()=default
LoopInfo & operator=(LoopInfo &&RHS)
Definition: LoopInfo.h:423
LoopInfo(LoopInfo &&Arg)
Definition: LoopInfo.h:422
bool replacementPreservesLCSSAForm(Instruction *From, Value *To)
Returns true if replacing From with To everywhere is guaranteed to preserve LCSSA form.
Definition: LoopInfo.h:442
LLVM_ABI LoopInfo(const DominatorTreeBase< BasicBlock, false > &DomTree)
bool movementPreservesLCSSAForm(Instruction *Inst, Instruction *NewLoc)
Checks if moving a specific instruction can break LCSSA in any loop.
Definition: LoopInfo.h:468
Printer pass for the LoopAnalysis results.
Definition: LoopInfo.h:581
static bool isRequired()
Definition: LoopInfo.h:587
LoopPrinterPass(raw_ostream &OS)
Definition: LoopInfo.h:585
A range representing the start and end location of a loop.
Definition: LoopInfo.h:43
LocRange(DebugLoc Start, DebugLoc End)
Definition: LoopInfo.h:50
const DebugLoc & getStart() const
Definition: LoopInfo.h:53
LocRange(DebugLoc Start)
Definition: LoopInfo.h:49
const DebugLoc & getEnd() const
Definition: LoopInfo.h:54
Represents a single loop in the control flow graph.
Definition: LoopInfo.h:40
bool isGuarded() const
Return true iff the loop is.
Definition: LoopInfo.h:297
StringRef getName() const
Definition: LoopInfo.h:390
bool isRotatedForm() const
Return true if the loop is in rotated form.
Definition: LoopInfo.h:304
Metadata node.
Definition: Metadata.h:1077
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:67
A set of analyses that are preserved following a run of a transformation pass.
Definition: Analysis.h:112
The main scalar evolution driver.
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:55
A Use represents the edge between a Value definition and its users.
Definition: Use.h:35
op_range operands()
Definition: User.h:292
LLVM Value Representation.
Definition: Value.h:75
iterator_range< use_iterator > uses()
Definition: Value.h:380
const ParentTy * getParent() const
Definition: ilist_node.h:34
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:53
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
LLVM_ABI bool getBooleanLoopAttribute(const Loop *TheLoop, StringRef Name)
Returns true if Name is applied to TheLoop and enabled.
Definition: LoopInfo.cpp:1121
Printable print(const GCNRegPressure &RP, const GCNSubtarget *ST=nullptr, unsigned DynamicVGPRBlockSize=0)
LLVM_ABI std::optional< bool > getOptionalBoolLoopAttribute(const Loop *TheLoop, StringRef Name)
Definition: LoopInfo.cpp:1103
LLVM_ABI int getIntLoopAttribute(const Loop *TheLoop, StringRef Name, int Default=0)
Find named metadata for a loop with an integer value.
Definition: LoopInfo.cpp:1139
LLVM_ABI std::optional< const MDOperand * > findStringMetadataForLoop(const Loop *TheLoop, StringRef Name)
Find string metadata for loop.
Definition: LoopInfo.cpp:1089
template class LLVM_TEMPLATE_ABI LoopInfoBase< BasicBlock, Loop >
Definition: LoopInfo.h:400
LLVM_ABI MDNode * findOptionMDForLoop(const Loop *TheLoop, StringRef Name)
Find string metadata for a loop.
Definition: LoopInfo.cpp:1079
LLVM_ABI bool hasMustProgress(const Loop *L)
Look for the loop attribute that requires progress within the loop.
Definition: LoopInfo.cpp:1170
template class LLVM_TEMPLATE_ABI LoopBase< BasicBlock, Loop >
Definition: LoopInfo.h:401
void erase(Container &C, ValueType V)
Wrapper function to remove a value from a container:
Definition: STLExtras.h:2147
LLVM_ABI bool isMustProgress(const Loop *L)
Return true if this loop can be assumed to make progress.
Definition: LoopInfo.cpp:1174
LLVM_ABI CallBase * getLoopConvergenceHeart(const Loop *TheLoop)
Find the convergence heart of the loop.
Definition: LoopInfo.cpp:1144
LLVM_ABI bool isFinite(const Loop *L)
Return true if this loop can be assumed to run for a finite number of iterations.
Definition: LoopInfo.cpp:1164
LLVM_ABI bool VerifyLoopInfo
Enable verification of loop info.
Definition: LoopInfo.cpp:51
LLVM_ABI std::optional< int > getOptionalIntLoopAttribute(const Loop *TheLoop, StringRef Name)
Find named metadata for a loop with an integer value.
Definition: LoopInfo.cpp:1125
LLVM_ABI bool isValidAsAccessGroup(MDNode *AccGroup)
Return whether an MDNode might represent an access group.
Definition: LoopInfo.cpp:1178
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1886
LLVM_ABI llvm::MDNode * makePostTransformationMetadata(llvm::LLVMContext &Context, MDNode *OrigLoopID, llvm::ArrayRef< llvm::StringRef > RemovePrefixes, llvm::ArrayRef< llvm::MDNode * > AddAttrs)
Create a new LoopID after the loop has been transformed.
Definition: LoopInfo.cpp:1182
@ Default
The result values are uniform if and only if all operands are uniform.
LLVM_ABI void printLoop(Loop &L, raw_ostream &OS, const std::string &Banner="")
Function to print a loop's contents as LLVM's text IR assembly.
Definition: LoopInfo.cpp:1001
LLVM_ABI MDNode * findOptionMDForLoopID(MDNode *LoopID, StringRef Name)
Find and return the loop attribute node for the attribute Name in LoopID.
Definition: LoopInfo.cpp:1053
Implement std::hash so that hash_code can be used in STL containers.
Definition: BitVector.h:856
#define N
A CRTP mix-in that provides informational APIs needed for analysis passes.
Definition: PassManager.h:93
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition: Analysis.h:29
static NodeRef getEntryNode(Loop *L)
Definition: LoopInfo.h:564
LoopInfo::iterator ChildIteratorType
Definition: LoopInfo.h:562
static ChildIteratorType child_begin(NodeRef N)
Definition: LoopInfo.h:565
static ChildIteratorType child_end(NodeRef N)
Definition: LoopInfo.h:566
static ChildIteratorType child_begin(NodeRef N)
Definition: LoopInfo.h:556
static ChildIteratorType child_end(NodeRef N)
Definition: LoopInfo.h:557
static NodeRef getEntryNode(const Loop *L)
Definition: LoopInfo.h:555
LoopInfo::iterator ChildIteratorType
Definition: LoopInfo.h:553
Incoming for lane maks phi as machine instruction, incoming register Reg and incoming block Block are...
Verifier pass for the LoopAnalysis results.
Definition: LoopInfo.h:591
static bool isRequired()
Definition: LoopInfo.h:593
Below are some utilities to get the loop guard, loop bounds and induction variable,...
Definition: LoopInfo.h:154
Direction
An enum for the direction of the loop.
Definition: LoopInfo.h:217
Value & getFinalIVValue() const
Get the final value of the loop induction variable.
Definition: LoopInfo.h:176
Value * getStepValue() const
Get the step that the loop induction variable gets updated by in each loop iteration.
Definition: LoopInfo.h:173
Instruction & getStepInst() const
Get the instruction that updates the loop induction variable.
Definition: LoopInfo.h:169
Value & getInitialIVValue() const
Get the initial value of the loop induction variable.
Definition: LoopInfo.h:166
A CRTP mix-in to automatically provide informational APIs needed for passes.
Definition: PassManager.h:70