1 //===- llvm/Analysis/LoopInfo.h - Natural Loop Calculator -------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the LoopInfo class that is used to identify natural loops
11 // and determine the loop depth of various nodes of the CFG. Note that natural
12 // loops may actually be several loops that share the same header node.
14 // This analysis calculates the nesting structure of loops in a function. For
15 // each natural loop identified, this analysis identifies natural loops
16 // contained entirely within the function, the basic blocks the make up the
17 // loop, the nesting depth of the loop, and the successor blocks of the loop.
19 // It can calculate on the fly a variety of different bits of information, such
20 // as whether there is a preheader for the loop, the number of back edges to the
21 // header, and whether or not a particular block branches out of the loop.
23 //===----------------------------------------------------------------------===//
25 #ifndef LLVM_ANALYSIS_LOOP_INFO_H
26 #define LLVM_ANALYSIS_LOOP_INFO_H
28 #include "llvm/Pass.h"
29 #include "Support/GraphTraits.h"
39 //===----------------------------------------------------------------------===//
40 /// Loop class - Instances of this class are used to represent loops that are
41 /// detected in the flow graph
45 std::vector<Loop*> SubLoops; // Loops contained entirely within this one
46 std::vector<BasicBlock*> Blocks; // First entry is the header node
47 unsigned LoopDepth; // Nesting depth of this loop
49 Loop(const Loop &); // DO NOT IMPLEMENT
50 const Loop &operator=(const Loop &); // DO NOT IMPLEMENT
52 /// Loop ctor - This creates an empty loop.
53 Loop() : ParentLoop(0), LoopDepth(0) {
56 for (unsigned i = 0, e = SubLoops.size(); i != e; ++i)
60 unsigned getLoopDepth() const { return LoopDepth; }
61 BasicBlock *getHeader() const { return Blocks.front(); }
62 Loop *getParentLoop() const { return ParentLoop; }
64 /// contains - Return true of the specified basic block is in this loop
66 bool contains(const BasicBlock *BB) const;
68 /// iterator/begin/end - Return the loops contained entirely within this loop.
70 typedef std::vector<Loop*>::const_iterator iterator;
71 iterator begin() const { return SubLoops.begin(); }
72 iterator end() const { return SubLoops.end(); }
74 /// getBlocks - Get a list of the basic blocks which make up this loop.
76 const std::vector<BasicBlock*> &getBlocks() const { return Blocks; }
78 /// isLoopExit - True if terminator in the block can branch to another block
79 /// that is outside of the current loop.
81 bool isLoopExit(const BasicBlock *BB) const;
83 /// getNumBackEdges - Calculate the number of back edges to the loop header
85 unsigned getNumBackEdges() const;
87 //===--------------------------------------------------------------------===//
88 // APIs for simple analysis of the loop.
90 // Note that all of these methods can fail on general loops (ie, there may not
91 // be a preheader, etc). For best success, the loop simplification and
92 // induction variable canonicalization pass should be used to normalize loops
93 // for easy analysis. These methods assume canonical loops.
95 /// getExitBlocks - Return all of the successor blocks of this loop. These
96 /// are the blocks _outside of the current loop_ which are branched to.
98 void getExitBlocks(std::vector<BasicBlock*> &Blocks) const;
100 /// getLoopPreheader - If there is a preheader for this loop, return it. A
101 /// loop has a preheader if there is only one edge to the header of the loop
102 /// from outside of the loop. If this is the case, the block branching to the
103 /// header of the loop is the preheader node.
105 /// This method returns null if there is no preheader for the loop.
107 BasicBlock *getLoopPreheader() const;
109 /// getCanonicalInductionVariable - Check to see if the loop has a canonical
110 /// induction variable: an integer recurrence that starts at 0 and increments
111 /// by one each time through the loop. If so, return the phi node that
112 /// corresponds to it.
114 PHINode *getCanonicalInductionVariable() const;
116 /// getCanonicalInductionVariableIncrement - Return the LLVM value that holds
117 /// the canonical induction variable value for the "next" iteration of the
118 /// loop. This always succeeds if getCanonicalInductionVariable succeeds.
120 Instruction *getCanonicalInductionVariableIncrement() const;
122 /// getTripCount - Return a loop-invariant LLVM value indicating the number of
123 /// times the loop will be executed. Note that this means that the backedge
124 /// of the loop executes N-1 times. If the trip-count cannot be determined,
125 /// this returns null.
127 Value *getTripCount() const;
129 //===--------------------------------------------------------------------===//
130 // APIs for updating loop information after changing the CFG
133 /// addBasicBlockToLoop - This method is used by other analyses to update loop
134 /// information. NewBB is set to be a new member of the current loop.
135 /// Because of this, it is added as a member of all parent loops, and is added
136 /// to the specified LoopInfo object as being in the current basic block. It
137 /// is not valid to replace the loop header with this method.
139 void addBasicBlockToLoop(BasicBlock *NewBB, LoopInfo &LI);
141 /// replaceChildLoopWith - This is used when splitting loops up. It replaces
142 /// the OldChild entry in our children list with NewChild, and updates the
143 /// parent pointer of OldChild to be null and the NewChild to be this loop.
144 /// This updates the loop depth of the new child.
145 void replaceChildLoopWith(Loop *OldChild, Loop *NewChild);
147 /// addChildLoop - Add the specified loop to be a child of this loop. This
148 /// updates the loop depth of the new child.
150 void addChildLoop(Loop *NewChild);
152 /// removeChildLoop - This removes the specified child from being a subloop of
153 /// this loop. The loop is not deleted, as it will presumably be inserted
154 /// into another loop.
155 Loop *removeChildLoop(iterator OldChild);
157 /// addBlockEntry - This adds a basic block directly to the basic block list.
158 /// This should only be used by transformations that create new loops. Other
159 /// transformations should use addBasicBlockToLoop.
160 void addBlockEntry(BasicBlock *BB) {
161 Blocks.push_back(BB);
164 /// removeBlockFromLoop - This removes the specified basic block from the
165 /// current loop, updating the Blocks as appropriate. This does not update
166 /// the mapping in the LoopInfo class.
167 void removeBlockFromLoop(BasicBlock *BB);
169 void print(std::ostream &O, unsigned Depth = 0) const;
172 friend class LoopInfo;
173 Loop(BasicBlock *BB) : ParentLoop(0) {
174 Blocks.push_back(BB); LoopDepth = 0;
176 void setLoopDepth(unsigned Level) {
178 for (unsigned i = 0, e = SubLoops.size(); i != e; ++i)
179 SubLoops[i]->setLoopDepth(Level+1);
185 //===----------------------------------------------------------------------===//
186 /// LoopInfo - This class builds and contains all of the top level loop
187 /// structures in the specified function.
189 class LoopInfo : public FunctionPass {
190 // BBMap - Mapping of basic blocks to the inner most loop they occur in
191 std::map<BasicBlock*, Loop*> BBMap;
192 std::vector<Loop*> TopLevelLoops;
195 ~LoopInfo() { releaseMemory(); }
197 /// iterator/begin/end - The interface to the top-level loops in the current
200 typedef std::vector<Loop*>::const_iterator iterator;
201 iterator begin() const { return TopLevelLoops.begin(); }
202 iterator end() const { return TopLevelLoops.end(); }
204 /// getLoopFor - Return the inner most loop that BB lives in. If a basic
205 /// block is in no loop (for example the entry node), null is returned.
207 const Loop *getLoopFor(const BasicBlock *BB) const {
208 std::map<BasicBlock *, Loop*>::const_iterator I=BBMap.find((BasicBlock*)BB);
209 return I != BBMap.end() ? I->second : 0;
212 /// operator[] - same as getLoopFor...
214 inline const Loop *operator[](const BasicBlock *BB) const {
215 return getLoopFor(BB);
218 /// getLoopDepth - Return the loop nesting level of the specified block...
220 unsigned getLoopDepth(const BasicBlock *BB) const {
221 const Loop *L = getLoopFor(BB);
222 return L ? L->getLoopDepth() : 0;
225 // isLoopHeader - True if the block is a loop header node
226 bool isLoopHeader(BasicBlock *BB) const {
227 return getLoopFor(BB)->getHeader() == BB;
230 /// runOnFunction - Calculate the natural loop information.
232 virtual bool runOnFunction(Function &F);
234 virtual void releaseMemory();
235 void print(std::ostream &O) const;
237 /// getAnalysisUsage - Requires dominator sets
239 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
241 /// removeLoop - This removes the specified top-level loop from this loop info
242 /// object. The loop is not deleted, as it will presumably be inserted into
244 Loop *removeLoop(iterator I);
246 /// changeLoopFor - Change the top-level loop that contains BB to the
247 /// specified loop. This should be used by transformations that restructure
248 /// the loop hierarchy tree.
249 void changeLoopFor(BasicBlock *BB, Loop *L);
251 /// changeTopLevelLoop - Replace the specified loop in the top-level loops
252 /// list with the indicated loop.
253 void changeTopLevelLoop(Loop *OldLoop, Loop *NewLoop);
255 /// removeBlock - This method completely removes BB from all data structures,
256 /// including all of the Loop objects it is nested in and our mapping from
257 /// BasicBlocks to loops.
258 void removeBlock(BasicBlock *BB);
260 static void stub(); // Noop
262 void Calculate(const DominatorSet &DS);
263 Loop *ConsiderForLoop(BasicBlock *BB, const DominatorSet &DS);
264 void MoveSiblingLoopInto(Loop *NewChild, Loop *NewParent);
265 void InsertLoopInto(Loop *L, Loop *Parent);
269 // Make sure that any clients of this file link in LoopInfo.cpp
271 LOOP_INFO_INCLUDE_FILE((void*)&LoopInfo::stub);
273 // Allow clients to walk the list of nested loops...
274 template <> struct GraphTraits<const Loop*> {
275 typedef const Loop NodeType;
276 typedef std::vector<Loop*>::const_iterator ChildIteratorType;
278 static NodeType *getEntryNode(const Loop *L) { return L; }
279 static inline ChildIteratorType child_begin(NodeType *N) {
282 static inline ChildIteratorType child_end(NodeType *N) {
287 template <> struct GraphTraits<Loop*> {
288 typedef Loop NodeType;
289 typedef std::vector<Loop*>::const_iterator ChildIteratorType;
291 static NodeType *getEntryNode(Loop *L) { return L; }
292 static inline ChildIteratorType child_begin(NodeType *N) {
295 static inline ChildIteratorType child_end(NodeType *N) {
300 } // End llvm namespace