blob: af35462544e7bf9848ff6c769226048181d2e687 [file] [log] [blame]
Chris Lattnercf3056d2003-10-13 03:32:08 +00001//===- LoopInfo.cpp - Natural Loop Calculator -----------------------------===//
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner0bbe58f2001-11-26 18:41:20 +00009//
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 the
12// loops identified may actually be several natural loops that share the same
13// header node... not just a single natural loop.
14//
15//===----------------------------------------------------------------------===//
16
Misha Brukman10d208d2004-01-30 17:26:24 +000017#include "llvm/Analysis/LoopInfo.h"
Chris Lattner92020fa2004-04-15 15:16:02 +000018#include "llvm/Constants.h"
19#include "llvm/Instructions.h"
20#include "llvm/Analysis/Dominators.h"
Andrew Trick2d31ae32011-08-10 01:59:05 +000021#include "llvm/Analysis/LoopIterator.h"
Chris Lattnera59cbb22002-07-27 01:12:17 +000022#include "llvm/Assembly/Writer.h"
Misha Brukman10d208d2004-01-30 17:26:24 +000023#include "llvm/Support/CFG.h"
Dan Gohman9450b0e2009-09-28 00:27:48 +000024#include "llvm/Support/CommandLine.h"
Dan Gohmandda30cd2010-01-05 21:08:02 +000025#include "llvm/Support/Debug.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000026#include "llvm/ADT/DepthFirstIterator.h"
Chris Lattnerb1f5d8b2007-03-04 04:06:39 +000027#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner0bbe58f2001-11-26 18:41:20 +000028#include <algorithm>
Chris Lattner46758a82004-04-12 20:26:17 +000029using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000030
Dan Gohman9450b0e2009-09-28 00:27:48 +000031// Always verify loopinfo if expensive checking is enabled.
32#ifdef XDEBUG
Dan Gohmanb3579832010-04-15 17:08:50 +000033static bool VerifyLoopInfo = true;
Dan Gohman9450b0e2009-09-28 00:27:48 +000034#else
Dan Gohmanb3579832010-04-15 17:08:50 +000035static bool VerifyLoopInfo = false;
Dan Gohman9450b0e2009-09-28 00:27:48 +000036#endif
37static cl::opt<bool,true>
38VerifyLoopInfoX("verify-loop-info", cl::location(VerifyLoopInfo),
39 cl::desc("Verify loop info (time consuming)"));
40
Devang Patel19974732007-05-03 01:11:54 +000041char LoopInfo::ID = 0;
Owen Anderson2ab36d32010-10-12 19:48:12 +000042INITIALIZE_PASS_BEGIN(LoopInfo, "loops", "Natural Loop Information", true, true)
43INITIALIZE_PASS_DEPENDENCY(DominatorTree)
44INITIALIZE_PASS_END(LoopInfo, "loops", "Natural Loop Information", true, true)
Chris Lattner93193f82002-01-31 00:42:27 +000045
46//===----------------------------------------------------------------------===//
Chris Lattner1b7f7dc2002-04-28 16:21:30 +000047// Loop implementation
Chris Lattner93193f82002-01-31 00:42:27 +000048//
Misha Brukman6b290a52002-10-11 05:31:10 +000049
Dan Gohman16a2c922009-07-13 22:02:44 +000050/// isLoopInvariant - Return true if the specified value is loop invariant
51///
52bool Loop::isLoopInvariant(Value *V) const {
53 if (Instruction *I = dyn_cast<Instruction>(V))
Chris Lattneradc79912010-09-06 01:05:37 +000054 return !contains(I);
Dan Gohman16a2c922009-07-13 22:02:44 +000055 return true; // All non-instructions are loop invariant
56}
57
Chris Lattneradc79912010-09-06 01:05:37 +000058/// hasLoopInvariantOperands - Return true if all the operands of the
Andrew Trick882bcc62011-08-03 23:45:50 +000059/// specified instruction are loop invariant.
Chris Lattneradc79912010-09-06 01:05:37 +000060bool Loop::hasLoopInvariantOperands(Instruction *I) const {
61 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
62 if (!isLoopInvariant(I->getOperand(i)))
63 return false;
Andrew Trick882bcc62011-08-03 23:45:50 +000064
Chris Lattneradc79912010-09-06 01:05:37 +000065 return true;
Dan Gohmana3420262009-07-14 01:06:29 +000066}
67
68/// makeLoopInvariant - If the given value is an instruciton inside of the
69/// loop and it can be hoisted, do so to make it trivially loop-invariant.
70/// Return true if the value after any hoisting is loop invariant. This
71/// function can be used as a slightly more aggressive replacement for
72/// isLoopInvariant.
73///
74/// If InsertPt is specified, it is the point to hoist instructions to.
75/// If null, the terminator of the loop preheader is used.
76///
Dan Gohmanbdc017e2009-07-15 01:25:43 +000077bool Loop::makeLoopInvariant(Value *V, bool &Changed,
78 Instruction *InsertPt) const {
Dan Gohmana3420262009-07-14 01:06:29 +000079 if (Instruction *I = dyn_cast<Instruction>(V))
Dan Gohmanbdc017e2009-07-15 01:25:43 +000080 return makeLoopInvariant(I, Changed, InsertPt);
Dan Gohmana3420262009-07-14 01:06:29 +000081 return true; // All non-instructions are loop-invariant.
82}
83
84/// makeLoopInvariant - If the given instruction is inside of the
85/// loop and it can be hoisted, do so to make it trivially loop-invariant.
86/// Return true if the instruction after any hoisting is loop invariant. This
87/// function can be used as a slightly more aggressive replacement for
88/// isLoopInvariant.
89///
90/// If InsertPt is specified, it is the point to hoist instructions to.
91/// If null, the terminator of the loop preheader is used.
92///
Dan Gohmanbdc017e2009-07-15 01:25:43 +000093bool Loop::makeLoopInvariant(Instruction *I, bool &Changed,
94 Instruction *InsertPt) const {
Dan Gohmana3420262009-07-14 01:06:29 +000095 // Test if the value is already loop-invariant.
96 if (isLoopInvariant(I))
97 return true;
Eli Friedman0b79a772009-07-17 04:28:42 +000098 if (!I->isSafeToSpeculativelyExecute())
Dan Gohmana3420262009-07-14 01:06:29 +000099 return false;
Eli Friedman0b79a772009-07-17 04:28:42 +0000100 if (I->mayReadFromMemory())
Dan Gohmana3420262009-07-14 01:06:29 +0000101 return false;
102 // Determine the insertion point, unless one was given.
103 if (!InsertPt) {
104 BasicBlock *Preheader = getLoopPreheader();
105 // Without a preheader, hoisting is not feasible.
106 if (!Preheader)
107 return false;
108 InsertPt = Preheader->getTerminator();
109 }
110 // Don't hoist instructions with loop-variant operands.
111 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
Dan Gohmanbdc017e2009-07-15 01:25:43 +0000112 if (!makeLoopInvariant(I->getOperand(i), Changed, InsertPt))
Dan Gohmana3420262009-07-14 01:06:29 +0000113 return false;
Andrew Trick882bcc62011-08-03 23:45:50 +0000114
Dan Gohmana3420262009-07-14 01:06:29 +0000115 // Hoist.
116 I->moveBefore(InsertPt);
Dan Gohmanbdc017e2009-07-15 01:25:43 +0000117 Changed = true;
Dan Gohmana3420262009-07-14 01:06:29 +0000118 return true;
119}
120
Dan Gohman16a2c922009-07-13 22:02:44 +0000121/// getCanonicalInductionVariable - Check to see if the loop has a canonical
122/// induction variable: an integer recurrence that starts at 0 and increments
123/// by one each time through the loop. If so, return the phi node that
124/// corresponds to it.
125///
126/// The IndVarSimplify pass transforms loops to have a canonical induction
127/// variable.
128///
129PHINode *Loop::getCanonicalInductionVariable() const {
130 BasicBlock *H = getHeader();
131
132 BasicBlock *Incoming = 0, *Backedge = 0;
Dan Gohman63137d52010-07-23 21:25:16 +0000133 pred_iterator PI = pred_begin(H);
134 assert(PI != pred_end(H) &&
Dan Gohman16a2c922009-07-13 22:02:44 +0000135 "Loop must have at least one backedge!");
136 Backedge = *PI++;
Dan Gohman63137d52010-07-23 21:25:16 +0000137 if (PI == pred_end(H)) return 0; // dead loop
Dan Gohman16a2c922009-07-13 22:02:44 +0000138 Incoming = *PI++;
Dan Gohman63137d52010-07-23 21:25:16 +0000139 if (PI != pred_end(H)) return 0; // multiple backedges?
Dan Gohman16a2c922009-07-13 22:02:44 +0000140
141 if (contains(Incoming)) {
142 if (contains(Backedge))
143 return 0;
144 std::swap(Incoming, Backedge);
145 } else if (!contains(Backedge))
146 return 0;
147
148 // Loop over all of the PHI nodes, looking for a canonical indvar.
149 for (BasicBlock::iterator I = H->begin(); isa<PHINode>(I); ++I) {
150 PHINode *PN = cast<PHINode>(I);
151 if (ConstantInt *CI =
152 dyn_cast<ConstantInt>(PN->getIncomingValueForBlock(Incoming)))
153 if (CI->isNullValue())
154 if (Instruction *Inc =
155 dyn_cast<Instruction>(PN->getIncomingValueForBlock(Backedge)))
156 if (Inc->getOpcode() == Instruction::Add &&
157 Inc->getOperand(0) == PN)
158 if (ConstantInt *CI = dyn_cast<ConstantInt>(Inc->getOperand(1)))
159 if (CI->equalsInt(1))
160 return PN;
161 }
162 return 0;
163}
164
Dan Gohman16a2c922009-07-13 22:02:44 +0000165/// getTripCount - Return a loop-invariant LLVM value indicating the number of
166/// times the loop will be executed. Note that this means that the backedge
167/// of the loop executes N-1 times. If the trip-count cannot be determined,
168/// this returns null.
169///
170/// The IndVarSimplify pass transforms loops to have a form that this
171/// function easily understands.
172///
173Value *Loop::getTripCount() const {
174 // Canonical loops will end with a 'cmp ne I, V', where I is the incremented
175 // canonical induction variable and V is the trip count of the loop.
Dan Gohmanf8336a72010-07-23 21:34:51 +0000176 PHINode *IV = getCanonicalInductionVariable();
177 if (IV == 0 || IV->getNumIncomingValues() != 2) return 0;
Dan Gohman16a2c922009-07-13 22:02:44 +0000178
Dan Gohmanf8336a72010-07-23 21:34:51 +0000179 bool P0InLoop = contains(IV->getIncomingBlock(0));
180 Value *Inc = IV->getIncomingValue(!P0InLoop);
181 BasicBlock *BackedgeBlock = IV->getIncomingBlock(!P0InLoop);
Dan Gohman16a2c922009-07-13 22:02:44 +0000182
183 if (BranchInst *BI = dyn_cast<BranchInst>(BackedgeBlock->getTerminator()))
184 if (BI->isConditional()) {
185 if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition())) {
186 if (ICI->getOperand(0) == Inc) {
187 if (BI->getSuccessor(0) == getHeader()) {
188 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
189 return ICI->getOperand(1);
190 } else if (ICI->getPredicate() == ICmpInst::ICMP_EQ) {
191 return ICI->getOperand(1);
192 }
193 }
194 }
195 }
196
197 return 0;
198}
199
200/// getSmallConstantTripCount - Returns the trip count of this loop as a
201/// normal unsigned value, if possible. Returns 0 if the trip count is unknown
Duncan Sands768b87c2010-11-13 12:16:27 +0000202/// or not constant. Will also return 0 if the trip count is very large
Dan Gohman16a2c922009-07-13 22:02:44 +0000203/// (>= 2^32)
204unsigned Loop::getSmallConstantTripCount() const {
205 Value* TripCount = this->getTripCount();
206 if (TripCount) {
207 if (ConstantInt *TripCountC = dyn_cast<ConstantInt>(TripCount)) {
208 // Guard against huge trip counts.
209 if (TripCountC->getValue().getActiveBits() <= 32) {
210 return (unsigned)TripCountC->getZExtValue();
211 }
212 }
213 }
214 return 0;
215}
216
217/// getSmallConstantTripMultiple - Returns the largest constant divisor of the
218/// trip count of this loop as a normal unsigned value, if possible. This
219/// means that the actual trip count is always a multiple of the returned
220/// value (don't forget the trip count could very well be zero as well!).
221///
222/// Returns 1 if the trip count is unknown or not guaranteed to be the
223/// multiple of a constant (which is also the case if the trip count is simply
224/// constant, use getSmallConstantTripCount for that case), Will also return 1
225/// if the trip count is very large (>= 2^32).
226unsigned Loop::getSmallConstantTripMultiple() const {
227 Value* TripCount = this->getTripCount();
228 // This will hold the ConstantInt result, if any
229 ConstantInt *Result = NULL;
230 if (TripCount) {
231 // See if the trip count is constant itself
232 Result = dyn_cast<ConstantInt>(TripCount);
233 // if not, see if it is a multiplication
234 if (!Result)
235 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TripCount)) {
236 switch (BO->getOpcode()) {
237 case BinaryOperator::Mul:
238 Result = dyn_cast<ConstantInt>(BO->getOperand(1));
239 break;
Dan Gohmanac146652009-11-20 01:09:34 +0000240 case BinaryOperator::Shl:
241 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1)))
242 if (CI->getValue().getActiveBits() <= 5)
243 return 1u << CI->getZExtValue();
244 break;
Dan Gohman16a2c922009-07-13 22:02:44 +0000245 default:
246 break;
247 }
248 }
249 }
250 // Guard against huge trip counts.
251 if (Result && Result->getValue().getActiveBits() <= 32) {
252 return (unsigned)Result->getZExtValue();
253 } else {
254 return 1;
255 }
256}
257
258/// isLCSSAForm - Return true if the Loop is in LCSSA form
Dan Gohmanbbf81d82010-03-10 19:38:49 +0000259bool Loop::isLCSSAForm(DominatorTree &DT) const {
Dan Gohman16a2c922009-07-13 22:02:44 +0000260 // Sort the blocks vector so that we can use binary search to do quick
261 // lookups.
Gabor Greif5891ac82010-07-09 14:28:41 +0000262 SmallPtrSet<BasicBlock*, 16> LoopBBs(block_begin(), block_end());
Dan Gohman16a2c922009-07-13 22:02:44 +0000263
264 for (block_iterator BI = block_begin(), E = block_end(); BI != E; ++BI) {
Dan Gohman81d893c2009-11-09 18:19:43 +0000265 BasicBlock *BB = *BI;
266 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;++I)
Dan Gohman16a2c922009-07-13 22:02:44 +0000267 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
268 ++UI) {
Gabor Greif5891ac82010-07-09 14:28:41 +0000269 User *U = *UI;
270 BasicBlock *UserBB = cast<Instruction>(U)->getParent();
271 if (PHINode *P = dyn_cast<PHINode>(U))
Dan Gohman16a2c922009-07-13 22:02:44 +0000272 UserBB = P->getIncomingBlock(UI);
Dan Gohman16a2c922009-07-13 22:02:44 +0000273
Dan Gohmancbac7f12010-03-09 01:53:33 +0000274 // Check the current block, as a fast-path, before checking whether
275 // the use is anywhere in the loop. Most values are used in the same
276 // block they are defined in. Also, blocks not reachable from the
277 // entry are special; uses in them don't need to go through PHIs.
278 if (UserBB != BB &&
279 !LoopBBs.count(UserBB) &&
Dan Gohmanbbf81d82010-03-10 19:38:49 +0000280 DT.isReachableFromEntry(UserBB))
Dan Gohman16a2c922009-07-13 22:02:44 +0000281 return false;
282 }
283 }
284
285 return true;
286}
Dan Gohman93773862009-07-16 16:16:23 +0000287
288/// isLoopSimplifyForm - Return true if the Loop is in the form that
289/// the LoopSimplify form transforms loops to, which is sometimes called
290/// normal form.
291bool Loop::isLoopSimplifyForm() const {
Dan Gohmanf17e9512009-11-05 19:21:41 +0000292 // Normal-form loops have a preheader, a single backedge, and all of their
293 // exits have all their predecessors inside the loop.
294 return getLoopPreheader() && getLoopLatch() && hasDedicatedExits();
295}
296
297/// hasDedicatedExits - Return true if no exit block for the loop
298/// has a predecessor that is outside the loop.
299bool Loop::hasDedicatedExits() const {
Dan Gohmaneed9e5b2009-10-20 20:41:13 +0000300 // Sort the blocks vector so that we can use binary search to do quick
301 // lookups.
302 SmallPtrSet<BasicBlock *, 16> LoopBBs(block_begin(), block_end());
Dan Gohman93773862009-07-16 16:16:23 +0000303 // Each predecessor of each exit block of a normal loop is contained
304 // within the loop.
305 SmallVector<BasicBlock *, 4> ExitBlocks;
306 getExitBlocks(ExitBlocks);
307 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
308 for (pred_iterator PI = pred_begin(ExitBlocks[i]),
309 PE = pred_end(ExitBlocks[i]); PI != PE; ++PI)
Dan Gohmaneed9e5b2009-10-20 20:41:13 +0000310 if (!LoopBBs.count(*PI))
Dan Gohman93773862009-07-16 16:16:23 +0000311 return false;
312 // All the requirements are met.
313 return true;
314}
315
Dan Gohmanf0608d82009-09-03 16:10:48 +0000316/// getUniqueExitBlocks - Return all unique successor blocks of this loop.
317/// These are the blocks _outside of the current loop_ which are branched to.
Dan Gohman050959c2009-12-11 20:05:23 +0000318/// This assumes that loop exits are in canonical form.
Dan Gohmanf0608d82009-09-03 16:10:48 +0000319///
320void
321Loop::getUniqueExitBlocks(SmallVectorImpl<BasicBlock *> &ExitBlocks) const {
Dan Gohman050959c2009-12-11 20:05:23 +0000322 assert(hasDedicatedExits() &&
323 "getUniqueExitBlocks assumes the loop has canonical form exits!");
Dan Gohman5c89b522009-09-08 15:45:00 +0000324
Dan Gohmanf0608d82009-09-03 16:10:48 +0000325 // Sort the blocks vector so that we can use binary search to do quick
326 // lookups.
327 SmallVector<BasicBlock *, 128> LoopBBs(block_begin(), block_end());
328 std::sort(LoopBBs.begin(), LoopBBs.end());
329
Dan Gohman058db922009-09-03 20:36:13 +0000330 SmallVector<BasicBlock *, 32> switchExitBlocks;
Dan Gohmanf0608d82009-09-03 16:10:48 +0000331
332 for (block_iterator BI = block_begin(), BE = block_end(); BI != BE; ++BI) {
333
334 BasicBlock *current = *BI;
335 switchExitBlocks.clear();
336
Dan Gohman63137d52010-07-23 21:25:16 +0000337 for (succ_iterator I = succ_begin(*BI), E = succ_end(*BI); I != E; ++I) {
Dan Gohmanf0608d82009-09-03 16:10:48 +0000338 // If block is inside the loop then it is not a exit block.
339 if (std::binary_search(LoopBBs.begin(), LoopBBs.end(), *I))
340 continue;
341
Dan Gohman63137d52010-07-23 21:25:16 +0000342 pred_iterator PI = pred_begin(*I);
Dan Gohmanf0608d82009-09-03 16:10:48 +0000343 BasicBlock *firstPred = *PI;
344
345 // If current basic block is this exit block's first predecessor
346 // then only insert exit block in to the output ExitBlocks vector.
347 // This ensures that same exit block is not inserted twice into
348 // ExitBlocks vector.
349 if (current != firstPred)
350 continue;
351
352 // If a terminator has more then two successors, for example SwitchInst,
353 // then it is possible that there are multiple edges from current block
354 // to one exit block.
Dan Gohman63137d52010-07-23 21:25:16 +0000355 if (std::distance(succ_begin(current), succ_end(current)) <= 2) {
Dan Gohmanf0608d82009-09-03 16:10:48 +0000356 ExitBlocks.push_back(*I);
357 continue;
358 }
359
360 // In case of multiple edges from current block to exit block, collect
361 // only one edge in ExitBlocks. Use switchExitBlocks to keep track of
362 // duplicate edges.
363 if (std::find(switchExitBlocks.begin(), switchExitBlocks.end(), *I)
364 == switchExitBlocks.end()) {
365 switchExitBlocks.push_back(*I);
366 ExitBlocks.push_back(*I);
367 }
368 }
369 }
370}
371
372/// getUniqueExitBlock - If getUniqueExitBlocks would return exactly one
373/// block, return that block. Otherwise return null.
374BasicBlock *Loop::getUniqueExitBlock() const {
375 SmallVector<BasicBlock *, 8> UniqueExitBlocks;
376 getUniqueExitBlocks(UniqueExitBlocks);
377 if (UniqueExitBlocks.size() == 1)
378 return UniqueExitBlocks[0];
379 return 0;
380}
381
Dan Gohmandda30cd2010-01-05 21:08:02 +0000382void Loop::dump() const {
383 print(dbgs());
384}
385
Chris Lattnera59cbb22002-07-27 01:12:17 +0000386//===----------------------------------------------------------------------===//
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000387// UnloopUpdater implementation
388//
389
390/// Find the new parent loop for all blocks within the "unloop" whose last
391/// backedges has just been removed.
392class UnloopUpdater {
393 Loop *Unloop;
394 LoopInfo *LI;
395
396 LoopBlocksDFS DFS;
397
398 // Map unloop's immediate subloops to their nearest reachable parents. Nested
399 // loops within these subloops will not change parents. However, an immediate
400 // subloop's new parent will be the nearest loop reachable from either its own
401 // exits *or* any of its nested loop's exits.
402 DenseMap<Loop*, Loop*> SubloopParents;
403
404 // Flag the presence of an irreducible backedge whose destination is a block
405 // directly contained by the original unloop.
406 bool FoundIB;
407
408public:
409 UnloopUpdater(Loop *UL, LoopInfo *LInfo) :
410 Unloop(UL), LI(LInfo), DFS(UL), FoundIB(false) {}
411
412 void updateBlockParents();
413
Andrew Trickc12d9b92011-08-11 20:27:32 +0000414 void removeBlocksFromAncestors();
415
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000416 void updateSubloopParents();
417
418protected:
419 Loop *getNearestLoop(BasicBlock *BB, Loop *BBLoop);
420};
421
422/// updateBlockParents - Update the parent loop for all blocks that are directly
423/// contained within the original "unloop".
424void UnloopUpdater::updateBlockParents() {
425 if (Unloop->getNumBlocks()) {
426 // Perform a post order CFG traversal of all blocks within this loop,
427 // propagating the nearest loop from sucessors to predecessors.
428 LoopBlocksTraversal Traversal(DFS, LI);
429 for (LoopBlocksTraversal::POTIterator POI = Traversal.begin(),
430 POE = Traversal.end(); POI != POE; ++POI) {
431
432 Loop *L = LI->getLoopFor(*POI);
433 Loop *NL = getNearestLoop(*POI, L);
434
435 if (NL != L) {
436 // For reducible loops, NL is now an ancestor of Unloop.
437 assert((NL != Unloop && (!NL || NL->contains(Unloop))) &&
438 "uninitialized successor");
439 LI->changeLoopFor(*POI, NL);
440 }
441 else {
442 // Or the current block is part of a subloop, in which case its parent
443 // is unchanged.
444 assert((FoundIB || Unloop->contains(L)) && "uninitialized successor");
445 }
446 }
447 }
448 // Each irreducible loop within the unloop induces a round of iteration using
449 // the DFS result cached by Traversal.
450 bool Changed = FoundIB;
451 for (unsigned NIters = 0; Changed; ++NIters) {
452 assert(NIters < Unloop->getNumBlocks() && "runaway iterative algorithm");
453
454 // Iterate over the postorder list of blocks, propagating the nearest loop
455 // from successors to predecessors as before.
456 Changed = false;
457 for (LoopBlocksDFS::POIterator POI = DFS.beginPostorder(),
458 POE = DFS.endPostorder(); POI != POE; ++POI) {
459
460 Loop *L = LI->getLoopFor(*POI);
461 Loop *NL = getNearestLoop(*POI, L);
462 if (NL != L) {
463 assert(NL != Unloop && (!NL || NL->contains(Unloop)) &&
464 "uninitialized successor");
465 LI->changeLoopFor(*POI, NL);
466 Changed = true;
467 }
468 }
469 }
470}
471
Andrew Trickc12d9b92011-08-11 20:27:32 +0000472/// removeBlocksFromAncestors - Remove unloop's blocks from all ancestors below
473/// their new parents.
474void UnloopUpdater::removeBlocksFromAncestors() {
475 // Remove unloop's blocks from all ancestors below their new parents.
476 for (Loop::block_iterator BI = Unloop->block_begin(),
477 BE = Unloop->block_end(); BI != BE; ++BI) {
478 Loop *NewParent = LI->getLoopFor(*BI);
479 // If this block is an immediate subloop, remove all blocks (including
480 // nested subloops) from ancestors below the new parent loop.
481 // Otherwise, if this block is in a nested subloop, skip it.
482 if (SubloopParents.count(NewParent))
483 NewParent = SubloopParents[NewParent];
484 else if (Unloop->contains(NewParent))
485 continue;
486
487 // Remove blocks from former Ancestors except Unloop itself which will be
488 // deleted.
489 for (Loop *OldParent = Unloop->getParentLoop(); OldParent != NewParent;
490 OldParent = OldParent->getParentLoop()) {
491 assert(OldParent && "new loop is not an ancestor of the original");
492 OldParent->removeBlockFromLoop(*BI);
493 }
494 }
495}
496
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000497/// updateSubloopParents - Update the parent loop for all subloops directly
498/// nested within unloop.
499void UnloopUpdater::updateSubloopParents() {
500 while (!Unloop->empty()) {
Andrew Trick5c1ff1f2011-08-11 17:54:58 +0000501 Loop *Subloop = *llvm::prior(Unloop->end());
502 Unloop->removeChildLoop(llvm::prior(Unloop->end()));
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000503
504 assert(SubloopParents.count(Subloop) && "DFS failed to visit subloop");
505 if (SubloopParents[Subloop])
506 SubloopParents[Subloop]->addChildLoop(Subloop);
507 }
508}
509
510/// getNearestLoop - Return the nearest parent loop among this block's
511/// successors. If a successor is a subloop header, consider its parent to be
512/// the nearest parent of the subloop's exits.
513///
514/// For subloop blocks, simply update SubloopParents and return NULL.
515Loop *UnloopUpdater::getNearestLoop(BasicBlock *BB, Loop *BBLoop) {
516
Andrew Trick5c1ff1f2011-08-11 17:54:58 +0000517 // Initially for blocks directly contained by Unloop, NearLoop == Unloop and
518 // is considered uninitialized.
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000519 Loop *NearLoop = BBLoop;
520
521 Loop *Subloop = 0;
522 if (NearLoop != Unloop && Unloop->contains(NearLoop)) {
523 Subloop = NearLoop;
524 // Find the subloop ancestor that is directly contained within Unloop.
525 while (Subloop->getParentLoop() != Unloop) {
526 Subloop = Subloop->getParentLoop();
527 assert(Subloop && "subloop is not an ancestor of the original loop");
528 }
529 // Get the current nearest parent of the Subloop exits, initially Unloop.
530 if (!SubloopParents.count(Subloop))
531 SubloopParents[Subloop] = Unloop;
532 NearLoop = SubloopParents[Subloop];
533 }
534
535 succ_iterator I = succ_begin(BB), E = succ_end(BB);
536 if (I == E) {
537 assert(!Subloop && "subloop blocks must have a successor");
538 NearLoop = 0; // unloop blocks may now exit the function.
539 }
540 for (; I != E; ++I) {
541 if (*I == BB)
542 continue; // self loops are uninteresting
543
544 Loop *L = LI->getLoopFor(*I);
545 if (L == Unloop) {
546 // This successor has not been processed. This path must lead to an
547 // irreducible backedge.
548 assert((FoundIB || !DFS.hasPostorder(*I)) && "should have seen IB");
549 FoundIB = true;
550 }
551 if (L != Unloop && Unloop->contains(L)) {
552 // Successor is in a subloop.
553 if (Subloop)
554 continue; // Branching within subloops. Ignore it.
555
556 // BB branches from the original into a subloop header.
557 assert(L->getParentLoop() == Unloop && "cannot skip into nested loops");
558
559 // Get the current nearest parent of the Subloop's exits.
560 L = SubloopParents[L];
561 // L could be Unloop if the only exit was an irreducible backedge.
562 }
563 if (L == Unloop) {
564 continue;
565 }
566 // Handle critical edges from Unloop into a sibling loop.
567 if (L && !L->contains(Unloop)) {
568 L = L->getParentLoop();
569 }
570 // Remember the nearest parent loop among successors or subloop exits.
571 if (NearLoop == Unloop || !NearLoop || NearLoop->contains(L))
572 NearLoop = L;
573 }
574 if (Subloop) {
575 SubloopParents[Subloop] = NearLoop;
576 return BBLoop;
577 }
578 return NearLoop;
579}
580
581//===----------------------------------------------------------------------===//
Chris Lattnera59cbb22002-07-27 01:12:17 +0000582// LoopInfo implementation
583//
Chris Lattnera59cbb22002-07-27 01:12:17 +0000584bool LoopInfo::runOnFunction(Function &) {
585 releaseMemory();
Dan Gohman9d59d9f2009-06-27 21:22:48 +0000586 LI.Calculate(getAnalysis<DominatorTree>().getBase()); // Update
Chris Lattnera59cbb22002-07-27 01:12:17 +0000587 return false;
588}
589
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000590/// updateUnloop - The last backedge has been removed from a loop--now the
591/// "unloop". Find a new parent for the blocks contained within unloop and
Andrew Trick5c1ff1f2011-08-11 17:54:58 +0000592/// update the loop tree. We don't necessarily have valid dominators at this
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000593/// point, but LoopInfo is still valid except for the removal of this loop.
594///
595/// Note that Unloop may now be an empty loop. Calling Loop::getHeader without
596/// checking first is illegal.
597void LoopInfo::updateUnloop(Loop *Unloop) {
598
599 // First handle the special case of no parent loop to simplify the algorithm.
600 if (!Unloop->getParentLoop()) {
601 // Since BBLoop had no parent, Unloop blocks are no longer in a loop.
602 for (Loop::block_iterator I = Unloop->block_begin(),
603 E = Unloop->block_end(); I != E; ++I) {
604
605 // Don't reparent blocks in subloops.
606 if (getLoopFor(*I) != Unloop)
607 continue;
608
609 // Blocks no longer have a parent but are still referenced by Unloop until
610 // the Unloop object is deleted.
611 LI.changeLoopFor(*I, 0);
612 }
613
614 // Remove the loop from the top-level LoopInfo object.
615 for (LoopInfo::iterator I = LI.begin(), E = LI.end();; ++I) {
616 assert(I != E && "Couldn't find loop");
617 if (*I == Unloop) {
618 LI.removeLoop(I);
619 break;
620 }
621 }
622
623 // Move all of the subloops to the top-level.
624 while (!Unloop->empty())
Andrew Trick5c1ff1f2011-08-11 17:54:58 +0000625 LI.addTopLevelLoop(Unloop->removeChildLoop(llvm::prior(Unloop->end())));
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000626
627 return;
628 }
629
630 // Update the parent loop for all blocks within the loop. Blocks within
631 // subloops will not change parents.
632 UnloopUpdater Updater(Unloop, this);
633 Updater.updateBlockParents();
634
Andrew Trickc12d9b92011-08-11 20:27:32 +0000635 // Remove blocks from former ancestor loops.
636 Updater.removeBlocksFromAncestors();
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000637
638 // Add direct subloops as children in their new parent loop.
639 Updater.updateSubloopParents();
640
641 // Remove unloop from its parent loop.
642 Loop *ParentLoop = Unloop->getParentLoop();
643 for (Loop::iterator I = ParentLoop->begin(), E = ParentLoop->end();; ++I) {
644 assert(I != E && "Couldn't find loop");
645 if (*I == Unloop) {
646 ParentLoop->removeChildLoop(I);
647 break;
648 }
649 }
650}
651
Dan Gohman5c89b522009-09-08 15:45:00 +0000652void LoopInfo::verifyAnalysis() const {
Dan Gohman9450b0e2009-09-28 00:27:48 +0000653 // LoopInfo is a FunctionPass, but verifying every loop in the function
654 // each time verifyAnalysis is called is very expensive. The
655 // -verify-loop-info option can enable this. In order to perform some
656 // checking by default, LoopPass has been taught to call verifyLoop
657 // manually during loop pass sequences.
658
659 if (!VerifyLoopInfo) return;
660
Dan Gohman5c89b522009-09-08 15:45:00 +0000661 for (iterator I = begin(), E = end(); I != E; ++I) {
662 assert(!(*I)->getParentLoop() && "Top-level loop has a parent!");
663 (*I)->verifyLoopNest();
664 }
Dan Gohman9450b0e2009-09-28 00:27:48 +0000665
666 // TODO: check BBMap consistency.
Dan Gohman5c89b522009-09-08 15:45:00 +0000667}
668
Chris Lattner1b7f7dc2002-04-28 16:21:30 +0000669void LoopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerf57b8452002-04-27 06:56:12 +0000670 AU.setPreservesAll();
Devang Patel53c279b2007-06-08 00:17:13 +0000671 AU.addRequired<DominatorTree>();
Chris Lattner93193f82002-01-31 00:42:27 +0000672}
Chris Lattner791102f2009-08-23 05:17:37 +0000673
Chris Lattner45cfe542009-08-23 06:03:38 +0000674void LoopInfo::print(raw_ostream &OS, const Module*) const {
675 LI.print(OS);
Chris Lattner791102f2009-08-23 05:17:37 +0000676}
677
Andrew Trick2d31ae32011-08-10 01:59:05 +0000678//===----------------------------------------------------------------------===//
679// LoopBlocksDFS implementation
680//
681
682/// Traverse the loop blocks and store the DFS result.
683/// Useful for clients that just want the final DFS result and don't need to
684/// visit blocks during the initial traversal.
685void LoopBlocksDFS::perform(LoopInfo *LI) {
686 LoopBlocksTraversal Traversal(*this, LI);
687 for (LoopBlocksTraversal::POTIterator POI = Traversal.begin(),
688 POE = Traversal.end(); POI != POE; ++POI) ;
689}