Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-05-10 08:43:14

0001 //===- llvm/Analysis/LoopInfo.h - Natural Loop Calculator -------*- C++ -*-===//
0002 //
0003 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
0004 // See https://llvm.org/LICENSE.txt for license information.
0005 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
0006 //
0007 //===----------------------------------------------------------------------===//
0008 //
0009 // This file declares a GenericLoopInfo instantiation for LLVM IR.
0010 //
0011 //===----------------------------------------------------------------------===//
0012 
0013 #ifndef LLVM_ANALYSIS_LOOPINFO_H
0014 #define LLVM_ANALYSIS_LOOPINFO_H
0015 
0016 #include "llvm/ADT/GraphTraits.h"
0017 #include "llvm/IR/Instructions.h"
0018 #include "llvm/IR/PassManager.h"
0019 #include "llvm/Pass.h"
0020 #include "llvm/Support/GenericLoopInfo.h"
0021 #include <optional>
0022 #include <utility>
0023 
0024 namespace llvm {
0025 
0026 class DominatorTree;
0027 class InductionDescriptor;
0028 class LoopInfo;
0029 class Loop;
0030 class MemorySSAUpdater;
0031 class ScalarEvolution;
0032 class raw_ostream;
0033 
0034 // Implementation in Support/GenericLoopInfoImpl.h
0035 extern template class LoopBase<BasicBlock, Loop>;
0036 
0037 /// Represents a single loop in the control flow graph.  Note that not all SCCs
0038 /// in the CFG are necessarily loops.
0039 class LLVM_ABI Loop : public LoopBase<BasicBlock, Loop> {
0040 public:
0041   /// A range representing the start and end location of a loop.
0042   class LocRange {
0043     DebugLoc Start;
0044     DebugLoc End;
0045 
0046   public:
0047     LocRange() = default;
0048     LocRange(DebugLoc Start) : Start(Start), End(Start) {}
0049     LocRange(DebugLoc Start, DebugLoc End)
0050         : Start(std::move(Start)), End(std::move(End)) {}
0051 
0052     const DebugLoc &getStart() const { return Start; }
0053     const DebugLoc &getEnd() const { return End; }
0054 
0055     /// Check for null.
0056     ///
0057     explicit operator bool() const { return Start && End; }
0058   };
0059 
0060   /// Return true if the specified value is loop invariant.
0061   bool isLoopInvariant(const Value *V) const;
0062 
0063   /// Return true if all the operands of the specified instruction are loop
0064   /// invariant.
0065   bool hasLoopInvariantOperands(const Instruction *I) const;
0066 
0067   /// If the given value is an instruction inside of the loop and it can be
0068   /// hoisted, do so to make it trivially loop-invariant.
0069   /// Return true if \c V is already loop-invariant, and false if \c V can't
0070   /// be made loop-invariant. If \c V is made loop-invariant, \c Changed is
0071   /// set to true. This function can be used as a slightly more aggressive
0072   /// replacement for isLoopInvariant.
0073   ///
0074   /// If InsertPt is specified, it is the point to hoist instructions to.
0075   /// If null, the terminator of the loop preheader is used.
0076   ///
0077   bool makeLoopInvariant(Value *V, bool &Changed,
0078                          Instruction *InsertPt = nullptr,
0079                          MemorySSAUpdater *MSSAU = nullptr,
0080                          ScalarEvolution *SE = nullptr) const;
0081 
0082   /// If the given instruction is inside of the loop and it can be hoisted, do
0083   /// so to make it trivially loop-invariant.
0084   /// Return true if \c I is already loop-invariant, and false if \c I can't
0085   /// be made loop-invariant. If \c I is made loop-invariant, \c Changed is
0086   /// set to true. This function can be used as a slightly more aggressive
0087   /// replacement for isLoopInvariant.
0088   ///
0089   /// If InsertPt is specified, it is the point to hoist instructions to.
0090   /// If null, the terminator of the loop preheader is used.
0091   ///
0092   bool makeLoopInvariant(Instruction *I, bool &Changed,
0093                          Instruction *InsertPt = nullptr,
0094                          MemorySSAUpdater *MSSAU = nullptr,
0095                          ScalarEvolution *SE = nullptr) const;
0096 
0097   /// Check to see if the loop has a canonical induction variable: an integer
0098   /// recurrence that starts at 0 and increments by one each time through the
0099   /// loop. If so, return the phi node that corresponds to it.
0100   ///
0101   /// The IndVarSimplify pass transforms loops to have a canonical induction
0102   /// variable.
0103   ///
0104   PHINode *getCanonicalInductionVariable() const;
0105 
0106   /// Get the latch condition instruction.
0107   ICmpInst *getLatchCmpInst() const;
0108 
0109   /// Obtain the unique incoming and back edge. Return false if they are
0110   /// non-unique or the loop is dead; otherwise, return true.
0111   bool getIncomingAndBackEdge(BasicBlock *&Incoming,
0112                               BasicBlock *&Backedge) const;
0113 
0114   /// Below are some utilities to get the loop guard, loop bounds and induction
0115   /// variable, and to check if a given phinode is an auxiliary induction
0116   /// variable, if the loop is guarded, and if the loop is canonical.
0117   ///
0118   /// Here is an example:
0119   /// \code
0120   /// for (int i = lb; i < ub; i+=step)
0121   ///   <loop body>
0122   /// --- pseudo LLVMIR ---
0123   /// beforeloop:
0124   ///   guardcmp = (lb < ub)
0125   ///   if (guardcmp) goto preheader; else goto afterloop
0126   /// preheader:
0127   /// loop:
0128   ///   i_1 = phi[{lb, preheader}, {i_2, latch}]
0129   ///   <loop body>
0130   ///   i_2 = i_1 + step
0131   /// latch:
0132   ///   cmp = (i_2 < ub)
0133   ///   if (cmp) goto loop
0134   /// exit:
0135   /// afterloop:
0136   /// \endcode
0137   ///
0138   /// - getBounds
0139   ///   - getInitialIVValue      --> lb
0140   ///   - getStepInst            --> i_2 = i_1 + step
0141   ///   - getStepValue           --> step
0142   ///   - getFinalIVValue        --> ub
0143   ///   - getCanonicalPredicate  --> '<'
0144   ///   - getDirection           --> Increasing
0145   ///
0146   /// - getInductionVariable            --> i_1
0147   /// - isAuxiliaryInductionVariable(x) --> true if x == i_1
0148   /// - getLoopGuardBranch()
0149   ///                 --> `if (guardcmp) goto preheader; else goto afterloop`
0150   /// - isGuarded()                     --> true
0151   /// - isCanonical                     --> false
0152   struct LoopBounds {
0153     /// Return the LoopBounds object if
0154     /// - the given \p IndVar is an induction variable
0155     /// - the initial value of the induction variable can be found
0156     /// - the step instruction of the induction variable can be found
0157     /// - the final value of the induction variable can be found
0158     ///
0159     /// Else std::nullopt.
0160     static std::optional<Loop::LoopBounds>
0161     getBounds(const Loop &L, PHINode &IndVar, ScalarEvolution &SE);
0162 
0163     /// Get the initial value of the loop induction variable.
0164     Value &getInitialIVValue() const { return InitialIVValue; }
0165 
0166     /// Get the instruction that updates the loop induction variable.
0167     Instruction &getStepInst() const { return StepInst; }
0168 
0169     /// Get the step that the loop induction variable gets updated by in each
0170     /// loop iteration. Return nullptr if not found.
0171     Value *getStepValue() const { return StepValue; }
0172 
0173     /// Get the final value of the loop induction variable.
0174     Value &getFinalIVValue() const { return FinalIVValue; }
0175 
0176     /// Return the canonical predicate for the latch compare instruction, if
0177     /// able to be calcuated. Else BAD_ICMP_PREDICATE.
0178     ///
0179     /// A predicate is considered as canonical if requirements below are all
0180     /// satisfied:
0181     /// 1. The first successor of the latch branch is the loop header
0182     ///    If not, inverse the predicate.
0183     /// 2. One of the operands of the latch comparison is StepInst
0184     ///    If not, and
0185     ///    - if the current calcuated predicate is not ne or eq, flip the
0186     ///      predicate.
0187     ///    - else if the loop is increasing, return slt
0188     ///      (notice that it is safe to change from ne or eq to sign compare)
0189     ///    - else if the loop is decreasing, return sgt
0190     ///      (notice that it is safe to change from ne or eq to sign compare)
0191     ///
0192     /// Here is an example when both (1) and (2) are not satisfied:
0193     /// \code
0194     /// loop.header:
0195     ///  %iv = phi [%initialiv, %loop.preheader], [%inc, %loop.header]
0196     ///  %inc = add %iv, %step
0197     ///  %cmp = slt %iv, %finaliv
0198     ///  br %cmp, %loop.exit, %loop.header
0199     /// loop.exit:
0200     /// \endcode
0201     /// - The second successor of the latch branch is the loop header instead
0202     ///   of the first successor (slt -> sge)
0203     /// - The first operand of the latch comparison (%cmp) is the IndVar (%iv)
0204     ///   instead of the StepInst (%inc) (sge -> sgt)
0205     ///
0206     /// The predicate would be sgt if both (1) and (2) are satisfied.
0207     /// getCanonicalPredicate() returns sgt for this example.
0208     /// Note: The IR is not changed.
0209     ICmpInst::Predicate getCanonicalPredicate() const;
0210 
0211     /// An enum for the direction of the loop
0212     /// - for (int i = 0; i < ub; ++i)  --> Increasing
0213     /// - for (int i = ub; i > 0; --i)  --> Descresing
0214     /// - for (int i = x; i != y; i+=z) --> Unknown
0215     enum class Direction { Increasing, Decreasing, Unknown };
0216 
0217     /// Get the direction of the loop.
0218     Direction getDirection() const;
0219 
0220   private:
0221     LoopBounds(const Loop &Loop, Value &I, Instruction &SI, Value *SV, Value &F,
0222                ScalarEvolution &SE)
0223         : L(Loop), InitialIVValue(I), StepInst(SI), StepValue(SV),
0224           FinalIVValue(F), SE(SE) {}
0225 
0226     const Loop &L;
0227 
0228     // The initial value of the loop induction variable
0229     Value &InitialIVValue;
0230 
0231     // The instruction that updates the loop induction variable
0232     Instruction &StepInst;
0233 
0234     // The value that the loop induction variable gets updated by in each loop
0235     // iteration
0236     Value *StepValue;
0237 
0238     // The final value of the loop induction variable
0239     Value &FinalIVValue;
0240 
0241     ScalarEvolution &SE;
0242   };
0243 
0244   /// Return the struct LoopBounds collected if all struct members are found,
0245   /// else std::nullopt.
0246   std::optional<LoopBounds> getBounds(ScalarEvolution &SE) const;
0247 
0248   /// Return the loop induction variable if found, else return nullptr.
0249   /// An instruction is considered as the loop induction variable if
0250   /// - it is an induction variable of the loop; and
0251   /// - it is used to determine the condition of the branch in the loop latch
0252   ///
0253   /// Note: the induction variable doesn't need to be canonical, i.e. starts at
0254   /// zero and increments by one each time through the loop (but it can be).
0255   PHINode *getInductionVariable(ScalarEvolution &SE) const;
0256 
0257   /// Get the loop induction descriptor for the loop induction variable. Return
0258   /// true if the loop induction variable is found.
0259   bool getInductionDescriptor(ScalarEvolution &SE,
0260                               InductionDescriptor &IndDesc) const;
0261 
0262   /// Return true if the given PHINode \p AuxIndVar is
0263   /// - in the loop header
0264   /// - not used outside of the loop
0265   /// - incremented by a loop invariant step for each loop iteration
0266   /// - step instruction opcode should be add or sub
0267   /// Note: auxiliary induction variable is not required to be used in the
0268   ///       conditional branch in the loop latch. (but it can be)
0269   bool isAuxiliaryInductionVariable(PHINode &AuxIndVar,
0270                                     ScalarEvolution &SE) const;
0271 
0272   /// Return the loop guard branch, if it exists.
0273   ///
0274   /// This currently only works on simplified loop, as it requires a preheader
0275   /// and a latch to identify the guard. It will work on loops of the form:
0276   /// \code
0277   /// GuardBB:
0278   ///   br cond1, Preheader, ExitSucc <== GuardBranch
0279   /// Preheader:
0280   ///   br Header
0281   /// Header:
0282   ///  ...
0283   ///   br Latch
0284   /// Latch:
0285   ///   br cond2, Header, ExitBlock
0286   /// ExitBlock:
0287   ///   br ExitSucc
0288   /// ExitSucc:
0289   /// \endcode
0290   BranchInst *getLoopGuardBranch() const;
0291 
0292   /// Return true iff the loop is
0293   /// - in simplify rotated form, and
0294   /// - guarded by a loop guard branch.
0295   bool isGuarded() const { return (getLoopGuardBranch() != nullptr); }
0296 
0297   /// Return true if the loop is in rotated form.
0298   ///
0299   /// This does not check if the loop was rotated by loop rotation, instead it
0300   /// only checks if the loop is in rotated form (has a valid latch that exists
0301   /// the loop).
0302   bool isRotatedForm() const {
0303     assert(!isInvalid() && "Loop not in a valid state!");
0304     BasicBlock *Latch = getLoopLatch();
0305     return Latch && isLoopExiting(Latch);
0306   }
0307 
0308   /// Return true if the loop induction variable starts at zero and increments
0309   /// by one each time through the loop.
0310   bool isCanonical(ScalarEvolution &SE) const;
0311 
0312   /// Return true if the Loop is in LCSSA form. If \p IgnoreTokens is set to
0313   /// true, token values defined inside loop are allowed to violate LCSSA form.
0314   bool isLCSSAForm(const DominatorTree &DT, bool IgnoreTokens = true) const;
0315 
0316   /// Return true if this Loop and all inner subloops are in LCSSA form. If \p
0317   /// IgnoreTokens is set to true, token values defined inside loop are allowed
0318   /// to violate LCSSA form.
0319   bool isRecursivelyLCSSAForm(const DominatorTree &DT, const LoopInfo &LI,
0320                               bool IgnoreTokens = true) const;
0321 
0322   /// Return true if the Loop is in the form that the LoopSimplify form
0323   /// transforms loops to, which is sometimes called normal form.
0324   bool isLoopSimplifyForm() const;
0325 
0326   /// Return true if the loop body is safe to clone in practice.
0327   bool isSafeToClone() const;
0328 
0329   /// Returns true if the loop is annotated parallel.
0330   ///
0331   /// A parallel loop can be assumed to not contain any dependencies between
0332   /// iterations by the compiler. That is, any loop-carried dependency checking
0333   /// can be skipped completely when parallelizing the loop on the target
0334   /// machine. Thus, if the parallel loop information originates from the
0335   /// programmer, e.g. via the OpenMP parallel for pragma, it is the
0336   /// programmer's responsibility to ensure there are no loop-carried
0337   /// dependencies. The final execution order of the instructions across
0338   /// iterations is not guaranteed, thus, the end result might or might not
0339   /// implement actual concurrent execution of instructions across multiple
0340   /// iterations.
0341   bool isAnnotatedParallel() const;
0342 
0343   /// Return the llvm.loop loop id metadata node for this loop if it is present.
0344   ///
0345   /// If this loop contains the same llvm.loop metadata on each branch to the
0346   /// header then the node is returned. If any latch instruction does not
0347   /// contain llvm.loop or if multiple latches contain different nodes then
0348   /// 0 is returned.
0349   MDNode *getLoopID() const;
0350   /// Set the llvm.loop loop id metadata for this loop.
0351   ///
0352   /// The LoopID metadata node will be added to each terminator instruction in
0353   /// the loop that branches to the loop header.
0354   ///
0355   /// The LoopID metadata node should have one or more operands and the first
0356   /// operand should be the node itself.
0357   void setLoopID(MDNode *LoopID) const;
0358 
0359   /// Add llvm.loop.unroll.disable to this loop's loop id metadata.
0360   ///
0361   /// Remove existing unroll metadata and add unroll disable metadata to
0362   /// indicate the loop has already been unrolled.  This prevents a loop
0363   /// from being unrolled more than is directed by a pragma if the loop
0364   /// unrolling pass is run more than once (which it generally is).
0365   void setLoopAlreadyUnrolled();
0366 
0367   /// Add llvm.loop.mustprogress to this loop's loop id metadata.
0368   void setLoopMustProgress();
0369 
0370   void dump() const;
0371   void dumpVerbose() const;
0372 
0373   /// Return the debug location of the start of this loop.
0374   /// This looks for a BB terminating instruction with a known debug
0375   /// location by looking at the preheader and header blocks. If it
0376   /// cannot find a terminating instruction with location information,
0377   /// it returns an unknown location.
0378   DebugLoc getStartLoc() const;
0379 
0380   /// Return the source code span of the loop.
0381   LocRange getLocRange() const;
0382 
0383   /// Return a string containing the debug location of the loop (file name +
0384   /// line number if present, otherwise module name). Meant to be used for debug
0385   /// printing within LLVM_DEBUG.
0386   std::string getLocStr() const;
0387 
0388   StringRef getName() const {
0389     if (BasicBlock *Header = getHeader())
0390       if (Header->hasName())
0391         return Header->getName();
0392     return "<unnamed loop>";
0393   }
0394 
0395 private:
0396   Loop() = default;
0397 
0398   friend class LoopInfoBase<BasicBlock, Loop>;
0399   friend class LoopBase<BasicBlock, Loop>;
0400   explicit Loop(BasicBlock *BB) : LoopBase<BasicBlock, Loop>(BB) {}
0401   ~Loop() = default;
0402 };
0403 
0404 // Implementation in Support/GenericLoopInfoImpl.h
0405 extern template class LoopInfoBase<BasicBlock, Loop>;
0406 
0407 class LoopInfo : public LoopInfoBase<BasicBlock, Loop> {
0408   typedef LoopInfoBase<BasicBlock, Loop> BaseT;
0409 
0410   friend class LoopBase<BasicBlock, Loop>;
0411 
0412   void operator=(const LoopInfo &) = delete;
0413   LoopInfo(const LoopInfo &) = delete;
0414 
0415 public:
0416   LoopInfo() = default;
0417   explicit LoopInfo(const DominatorTreeBase<BasicBlock, false> &DomTree);
0418 
0419   LoopInfo(LoopInfo &&Arg) : BaseT(std::move(static_cast<BaseT &>(Arg))) {}
0420   LoopInfo &operator=(LoopInfo &&RHS) {
0421     BaseT::operator=(std::move(static_cast<BaseT &>(RHS)));
0422     return *this;
0423   }
0424 
0425   /// Handle invalidation explicitly.
0426   bool invalidate(Function &F, const PreservedAnalyses &PA,
0427                   FunctionAnalysisManager::Invalidator &);
0428 
0429   // Most of the public interface is provided via LoopInfoBase.
0430 
0431   /// Update LoopInfo after removing the last backedge from a loop. This updates
0432   /// the loop forest and parent loops for each block so that \c L is no longer
0433   /// referenced, but does not actually delete \c L immediately. The pointer
0434   /// will remain valid until this LoopInfo's memory is released.
0435   void erase(Loop *L);
0436 
0437   /// Returns true if replacing From with To everywhere is guaranteed to
0438   /// preserve LCSSA form.
0439   bool replacementPreservesLCSSAForm(Instruction *From, Value *To) {
0440     // Preserving LCSSA form is only problematic if the replacing value is an
0441     // instruction.
0442     Instruction *I = dyn_cast<Instruction>(To);
0443     if (!I)
0444       return true;
0445     // If both instructions are defined in the same basic block then replacement
0446     // cannot break LCSSA form.
0447     if (I->getParent() == From->getParent())
0448       return true;
0449     // If the instruction is not defined in a loop then it can safely replace
0450     // anything.
0451     Loop *ToLoop = getLoopFor(I->getParent());
0452     if (!ToLoop)
0453       return true;
0454     // If the replacing instruction is defined in the same loop as the original
0455     // instruction, or in a loop that contains it as an inner loop, then using
0456     // it as a replacement will not break LCSSA form.
0457     return ToLoop->contains(getLoopFor(From->getParent()));
0458   }
0459 
0460   /// Checks if moving a specific instruction can break LCSSA in any loop.
0461   ///
0462   /// Return true if moving \p Inst to before \p NewLoc will break LCSSA,
0463   /// assuming that the function containing \p Inst and \p NewLoc is currently
0464   /// in LCSSA form.
0465   bool movementPreservesLCSSAForm(Instruction *Inst, Instruction *NewLoc) {
0466     assert(Inst->getFunction() == NewLoc->getFunction() &&
0467            "Can't reason about IPO!");
0468 
0469     auto *OldBB = Inst->getParent();
0470     auto *NewBB = NewLoc->getParent();
0471 
0472     // Movement within the same loop does not break LCSSA (the equality check is
0473     // to avoid doing a hashtable lookup in case of intra-block movement).
0474     if (OldBB == NewBB)
0475       return true;
0476 
0477     auto *OldLoop = getLoopFor(OldBB);
0478     auto *NewLoop = getLoopFor(NewBB);
0479 
0480     if (OldLoop == NewLoop)
0481       return true;
0482 
0483     // Check if Outer contains Inner; with the null loop counting as the
0484     // "outermost" loop.
0485     auto Contains = [](const Loop *Outer, const Loop *Inner) {
0486       return !Outer || Outer->contains(Inner);
0487     };
0488 
0489     // To check that the movement of Inst to before NewLoc does not break LCSSA,
0490     // we need to check two sets of uses for possible LCSSA violations at
0491     // NewLoc: the users of NewInst, and the operands of NewInst.
0492 
0493     // If we know we're hoisting Inst out of an inner loop to an outer loop,
0494     // then the uses *of* Inst don't need to be checked.
0495 
0496     if (!Contains(NewLoop, OldLoop)) {
0497       for (Use &U : Inst->uses()) {
0498         auto *UI = cast<Instruction>(U.getUser());
0499         auto *UBB = isa<PHINode>(UI) ? cast<PHINode>(UI)->getIncomingBlock(U)
0500                                      : UI->getParent();
0501         if (UBB != NewBB && getLoopFor(UBB) != NewLoop)
0502           return false;
0503       }
0504     }
0505 
0506     // If we know we're sinking Inst from an outer loop into an inner loop, then
0507     // the *operands* of Inst don't need to be checked.
0508 
0509     if (!Contains(OldLoop, NewLoop)) {
0510       // See below on why we can't handle phi nodes here.
0511       if (isa<PHINode>(Inst))
0512         return false;
0513 
0514       for (Use &U : Inst->operands()) {
0515         auto *DefI = dyn_cast<Instruction>(U.get());
0516         if (!DefI)
0517           return false;
0518 
0519         // This would need adjustment if we allow Inst to be a phi node -- the
0520         // new use block won't simply be NewBB.
0521 
0522         auto *DefBlock = DefI->getParent();
0523         if (DefBlock != NewBB && getLoopFor(DefBlock) != NewLoop)
0524           return false;
0525       }
0526     }
0527 
0528     return true;
0529   }
0530 
0531   // Return true if a new use of V added in ExitBB would require an LCSSA PHI
0532   // to be inserted at the begining of the block.  Note that V is assumed to
0533   // dominate ExitBB, and ExitBB must be the exit block of some loop.  The
0534   // IR is assumed to be in LCSSA form before the planned insertion.
0535   bool wouldBeOutOfLoopUseRequiringLCSSA(const Value *V,
0536                                          const BasicBlock *ExitBB) const;
0537 };
0538 
0539 /// Enable verification of loop info.
0540 ///
0541 /// The flag enables checks which are expensive and are disabled by default
0542 /// unless the `EXPENSIVE_CHECKS` macro is defined.  The `-verify-loop-info`
0543 /// flag allows the checks to be enabled selectively without re-compilation.
0544 extern bool VerifyLoopInfo;
0545 
0546 // Allow clients to walk the list of nested loops...
0547 template <> struct GraphTraits<const Loop *> {
0548   typedef const Loop *NodeRef;
0549   typedef LoopInfo::iterator ChildIteratorType;
0550 
0551   static NodeRef getEntryNode(const Loop *L) { return L; }
0552   static ChildIteratorType child_begin(NodeRef N) { return N->begin(); }
0553   static ChildIteratorType child_end(NodeRef N) { return N->end(); }
0554 };
0555 
0556 template <> struct GraphTraits<Loop *> {
0557   typedef Loop *NodeRef;
0558   typedef LoopInfo::iterator ChildIteratorType;
0559 
0560   static NodeRef getEntryNode(Loop *L) { return L; }
0561   static ChildIteratorType child_begin(NodeRef N) { return N->begin(); }
0562   static ChildIteratorType child_end(NodeRef N) { return N->end(); }
0563 };
0564 
0565 /// Analysis pass that exposes the \c LoopInfo for a function.
0566 class LoopAnalysis : public AnalysisInfoMixin<LoopAnalysis> {
0567   friend AnalysisInfoMixin<LoopAnalysis>;
0568   static AnalysisKey Key;
0569 
0570 public:
0571   typedef LoopInfo Result;
0572 
0573   LoopInfo run(Function &F, FunctionAnalysisManager &AM);
0574 };
0575 
0576 /// Printer pass for the \c LoopAnalysis results.
0577 class LoopPrinterPass : public PassInfoMixin<LoopPrinterPass> {
0578   raw_ostream &OS;
0579 
0580 public:
0581   explicit LoopPrinterPass(raw_ostream &OS) : OS(OS) {}
0582   PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM);
0583   static bool isRequired() { return true; }
0584 };
0585 
0586 /// Verifier pass for the \c LoopAnalysis results.
0587 struct LoopVerifierPass : public PassInfoMixin<LoopVerifierPass> {
0588   PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM);
0589   static bool isRequired() { return true; }
0590 };
0591 
0592 /// The legacy pass manager's analysis pass to compute loop information.
0593 class LoopInfoWrapperPass : public FunctionPass {
0594   LoopInfo LI;
0595 
0596 public:
0597   static char ID; // Pass identification, replacement for typeid
0598 
0599   LoopInfoWrapperPass();
0600 
0601   LoopInfo &getLoopInfo() { return LI; }
0602   const LoopInfo &getLoopInfo() const { return LI; }
0603 
0604   /// Calculate the natural loop information for a given function.
0605   bool runOnFunction(Function &F) override;
0606 
0607   void verifyAnalysis() const override;
0608 
0609   void releaseMemory() override { LI.releaseMemory(); }
0610 
0611   void print(raw_ostream &O, const Module *M = nullptr) const override;
0612 
0613   void getAnalysisUsage(AnalysisUsage &AU) const override;
0614 };
0615 
0616 /// Function to print a loop's contents as LLVM's text IR assembly.
0617 void printLoop(Loop &L, raw_ostream &OS, const std::string &Banner = "");
0618 
0619 /// Find and return the loop attribute node for the attribute @p Name in
0620 /// @p LoopID. Return nullptr if there is no such attribute.
0621 MDNode *findOptionMDForLoopID(MDNode *LoopID, StringRef Name);
0622 
0623 /// Find string metadata for a loop.
0624 ///
0625 /// Returns the MDNode where the first operand is the metadata's name. The
0626 /// following operands are the metadata's values. If no metadata with @p Name is
0627 /// found, return nullptr.
0628 MDNode *findOptionMDForLoop(const Loop *TheLoop, StringRef Name);
0629 
0630 std::optional<bool> getOptionalBoolLoopAttribute(const Loop *TheLoop,
0631                                                  StringRef Name);
0632 
0633 /// Returns true if Name is applied to TheLoop and enabled.
0634 bool getBooleanLoopAttribute(const Loop *TheLoop, StringRef Name);
0635 
0636 /// Find named metadata for a loop with an integer value.
0637 std::optional<int> getOptionalIntLoopAttribute(const Loop *TheLoop,
0638                                                StringRef Name);
0639 
0640 /// Find named metadata for a loop with an integer value. Return \p Default if
0641 /// not set.
0642 int getIntLoopAttribute(const Loop *TheLoop, StringRef Name, int Default = 0);
0643 
0644 /// Find string metadata for loop
0645 ///
0646 /// If it has a value (e.g. {"llvm.distribute", 1} return the value as an
0647 /// operand or null otherwise.  If the string metadata is not found return
0648 /// Optional's not-a-value.
0649 std::optional<const MDOperand *> findStringMetadataForLoop(const Loop *TheLoop,
0650                                                            StringRef Name);
0651 
0652 /// Find the convergence heart of the loop.
0653 CallBase *getLoopConvergenceHeart(const Loop *TheLoop);
0654 
0655 /// Look for the loop attribute that requires progress within the loop.
0656 /// Note: Most consumers probably want "isMustProgress" which checks
0657 /// the containing function attribute too.
0658 bool hasMustProgress(const Loop *L);
0659 
0660 /// Return true if this loop can be assumed to make progress.  (i.e. can't
0661 /// be infinite without side effects without also being undefined)
0662 bool isMustProgress(const Loop *L);
0663 
0664 /// Return true if this loop can be assumed to run for a finite number of
0665 /// iterations.
0666 bool isFinite(const Loop *L);
0667 
0668 /// Return whether an MDNode might represent an access group.
0669 ///
0670 /// Access group metadata nodes have to be distinct and empty. Being
0671 /// always-empty ensures that it never needs to be changed (which -- because
0672 /// MDNodes are designed immutable -- would require creating a new MDNode). Note
0673 /// that this is not a sufficient condition: not every distinct and empty NDNode
0674 /// is representing an access group.
0675 bool isValidAsAccessGroup(MDNode *AccGroup);
0676 
0677 /// Create a new LoopID after the loop has been transformed.
0678 ///
0679 /// This can be used when no follow-up loop attributes are defined
0680 /// (llvm::makeFollowupLoopID returning None) to stop transformations to be
0681 /// applied again.
0682 ///
0683 /// @param Context        The LLVMContext in which to create the new LoopID.
0684 /// @param OrigLoopID     The original LoopID; can be nullptr if the original
0685 ///                       loop has no LoopID.
0686 /// @param RemovePrefixes Remove all loop attributes that have these prefixes.
0687 ///                       Use to remove metadata of the transformation that has
0688 ///                       been applied.
0689 /// @param AddAttrs       Add these loop attributes to the new LoopID.
0690 ///
0691 /// @return A new LoopID that can be applied using Loop::setLoopID().
0692 llvm::MDNode *
0693 makePostTransformationMetadata(llvm::LLVMContext &Context, MDNode *OrigLoopID,
0694                                llvm::ArrayRef<llvm::StringRef> RemovePrefixes,
0695                                llvm::ArrayRef<llvm::MDNode *> AddAttrs);
0696 } // namespace llvm
0697 
0698 #endif