blob: f7a60a1737d4b54474961207c3349c1c05236737 [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"
Dan Gohmanf0426602011-12-14 23:49:11 +000022#include "llvm/Analysis/ValueTracking.h"
Chris Lattnera59cbb22002-07-27 01:12:17 +000023#include "llvm/Assembly/Writer.h"
Misha Brukman10d208d2004-01-30 17:26:24 +000024#include "llvm/Support/CFG.h"
Dan Gohman9450b0e2009-09-28 00:27:48 +000025#include "llvm/Support/CommandLine.h"
Dan Gohmandda30cd2010-01-05 21:08:02 +000026#include "llvm/Support/Debug.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000027#include "llvm/ADT/DepthFirstIterator.h"
Chris Lattnerb1f5d8b2007-03-04 04:06:39 +000028#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner0bbe58f2001-11-26 18:41:20 +000029#include <algorithm>
Chris Lattner46758a82004-04-12 20:26:17 +000030using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000031
Dan Gohman9450b0e2009-09-28 00:27:48 +000032// Always verify loopinfo if expensive checking is enabled.
33#ifdef XDEBUG
Dan Gohmanb3579832010-04-15 17:08:50 +000034static bool VerifyLoopInfo = true;
Dan Gohman9450b0e2009-09-28 00:27:48 +000035#else
Dan Gohmanb3579832010-04-15 17:08:50 +000036static bool VerifyLoopInfo = false;
Dan Gohman9450b0e2009-09-28 00:27:48 +000037#endif
38static cl::opt<bool,true>
39VerifyLoopInfoX("verify-loop-info", cl::location(VerifyLoopInfo),
40 cl::desc("Verify loop info (time consuming)"));
41
Devang Patel19974732007-05-03 01:11:54 +000042char LoopInfo::ID = 0;
Owen Anderson2ab36d32010-10-12 19:48:12 +000043INITIALIZE_PASS_BEGIN(LoopInfo, "loops", "Natural Loop Information", true, true)
44INITIALIZE_PASS_DEPENDENCY(DominatorTree)
45INITIALIZE_PASS_END(LoopInfo, "loops", "Natural Loop Information", true, true)
Chris Lattner93193f82002-01-31 00:42:27 +000046
47//===----------------------------------------------------------------------===//
Chris Lattner1b7f7dc2002-04-28 16:21:30 +000048// Loop implementation
Chris Lattner93193f82002-01-31 00:42:27 +000049//
Misha Brukman6b290a52002-10-11 05:31:10 +000050
Dan Gohman16a2c922009-07-13 22:02:44 +000051/// isLoopInvariant - Return true if the specified value is loop invariant
52///
53bool Loop::isLoopInvariant(Value *V) const {
54 if (Instruction *I = dyn_cast<Instruction>(V))
Chris Lattneradc79912010-09-06 01:05:37 +000055 return !contains(I);
Dan Gohman16a2c922009-07-13 22:02:44 +000056 return true; // All non-instructions are loop invariant
57}
58
Chris Lattneradc79912010-09-06 01:05:37 +000059/// hasLoopInvariantOperands - Return true if all the operands of the
Andrew Trick882bcc62011-08-03 23:45:50 +000060/// specified instruction are loop invariant.
Chris Lattneradc79912010-09-06 01:05:37 +000061bool Loop::hasLoopInvariantOperands(Instruction *I) const {
62 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
63 if (!isLoopInvariant(I->getOperand(i)))
64 return false;
Andrew Trick882bcc62011-08-03 23:45:50 +000065
Chris Lattneradc79912010-09-06 01:05:37 +000066 return true;
Dan Gohmana3420262009-07-14 01:06:29 +000067}
68
69/// makeLoopInvariant - If the given value is an instruciton inside of the
70/// loop and it can be hoisted, do so to make it trivially loop-invariant.
71/// Return true if the value after any hoisting is loop invariant. This
72/// function can be used as a slightly more aggressive replacement for
73/// isLoopInvariant.
74///
75/// If InsertPt is specified, it is the point to hoist instructions to.
76/// If null, the terminator of the loop preheader is used.
77///
Dan Gohmanbdc017e2009-07-15 01:25:43 +000078bool Loop::makeLoopInvariant(Value *V, bool &Changed,
79 Instruction *InsertPt) const {
Dan Gohmana3420262009-07-14 01:06:29 +000080 if (Instruction *I = dyn_cast<Instruction>(V))
Dan Gohmanbdc017e2009-07-15 01:25:43 +000081 return makeLoopInvariant(I, Changed, InsertPt);
Dan Gohmana3420262009-07-14 01:06:29 +000082 return true; // All non-instructions are loop-invariant.
83}
84
85/// makeLoopInvariant - If the given instruction is inside of the
86/// loop and it can be hoisted, do so to make it trivially loop-invariant.
87/// Return true if the instruction after any hoisting is loop invariant. This
88/// function can be used as a slightly more aggressive replacement for
89/// 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///
Dan Gohmanbdc017e2009-07-15 01:25:43 +000094bool Loop::makeLoopInvariant(Instruction *I, bool &Changed,
95 Instruction *InsertPt) const {
Dan Gohmana3420262009-07-14 01:06:29 +000096 // Test if the value is already loop-invariant.
97 if (isLoopInvariant(I))
98 return true;
Dan Gohmanf0426602011-12-14 23:49:11 +000099 if (!isSafeToSpeculativelyExecute(I))
Dan Gohmana3420262009-07-14 01:06:29 +0000100 return false;
Eli Friedman0b79a772009-07-17 04:28:42 +0000101 if (I->mayReadFromMemory())
Dan Gohmana3420262009-07-14 01:06:29 +0000102 return false;
Bill Wendlingc9b2a982011-08-17 20:36:44 +0000103 // The landingpad instruction is immobile.
104 if (isa<LandingPadInst>(I))
105 return false;
Dan Gohmana3420262009-07-14 01:06:29 +0000106 // Determine the insertion point, unless one was given.
107 if (!InsertPt) {
108 BasicBlock *Preheader = getLoopPreheader();
109 // Without a preheader, hoisting is not feasible.
110 if (!Preheader)
111 return false;
112 InsertPt = Preheader->getTerminator();
113 }
114 // Don't hoist instructions with loop-variant operands.
115 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
Dan Gohmanbdc017e2009-07-15 01:25:43 +0000116 if (!makeLoopInvariant(I->getOperand(i), Changed, InsertPt))
Dan Gohmana3420262009-07-14 01:06:29 +0000117 return false;
Andrew Trick882bcc62011-08-03 23:45:50 +0000118
Dan Gohmana3420262009-07-14 01:06:29 +0000119 // Hoist.
120 I->moveBefore(InsertPt);
Dan Gohmanbdc017e2009-07-15 01:25:43 +0000121 Changed = true;
Dan Gohmana3420262009-07-14 01:06:29 +0000122 return true;
123}
124
Dan Gohman16a2c922009-07-13 22:02:44 +0000125/// getCanonicalInductionVariable - Check to see if the loop has a canonical
126/// induction variable: an integer recurrence that starts at 0 and increments
127/// by one each time through the loop. If so, return the phi node that
128/// corresponds to it.
129///
130/// The IndVarSimplify pass transforms loops to have a canonical induction
131/// variable.
132///
133PHINode *Loop::getCanonicalInductionVariable() const {
134 BasicBlock *H = getHeader();
135
136 BasicBlock *Incoming = 0, *Backedge = 0;
Dan Gohman63137d52010-07-23 21:25:16 +0000137 pred_iterator PI = pred_begin(H);
138 assert(PI != pred_end(H) &&
Dan Gohman16a2c922009-07-13 22:02:44 +0000139 "Loop must have at least one backedge!");
140 Backedge = *PI++;
Dan Gohman63137d52010-07-23 21:25:16 +0000141 if (PI == pred_end(H)) return 0; // dead loop
Dan Gohman16a2c922009-07-13 22:02:44 +0000142 Incoming = *PI++;
Dan Gohman63137d52010-07-23 21:25:16 +0000143 if (PI != pred_end(H)) return 0; // multiple backedges?
Dan Gohman16a2c922009-07-13 22:02:44 +0000144
145 if (contains(Incoming)) {
146 if (contains(Backedge))
147 return 0;
148 std::swap(Incoming, Backedge);
149 } else if (!contains(Backedge))
150 return 0;
151
152 // Loop over all of the PHI nodes, looking for a canonical indvar.
153 for (BasicBlock::iterator I = H->begin(); isa<PHINode>(I); ++I) {
154 PHINode *PN = cast<PHINode>(I);
155 if (ConstantInt *CI =
156 dyn_cast<ConstantInt>(PN->getIncomingValueForBlock(Incoming)))
157 if (CI->isNullValue())
158 if (Instruction *Inc =
159 dyn_cast<Instruction>(PN->getIncomingValueForBlock(Backedge)))
160 if (Inc->getOpcode() == Instruction::Add &&
161 Inc->getOperand(0) == PN)
162 if (ConstantInt *CI = dyn_cast<ConstantInt>(Inc->getOperand(1)))
163 if (CI->equalsInt(1))
164 return PN;
165 }
166 return 0;
167}
168
Dan Gohman16a2c922009-07-13 22:02:44 +0000169/// isLCSSAForm - Return true if the Loop is in LCSSA form
Dan Gohmanbbf81d82010-03-10 19:38:49 +0000170bool Loop::isLCSSAForm(DominatorTree &DT) const {
Dan Gohman16a2c922009-07-13 22:02:44 +0000171 // Sort the blocks vector so that we can use binary search to do quick
172 // lookups.
Gabor Greif5891ac82010-07-09 14:28:41 +0000173 SmallPtrSet<BasicBlock*, 16> LoopBBs(block_begin(), block_end());
Dan Gohman16a2c922009-07-13 22:02:44 +0000174
175 for (block_iterator BI = block_begin(), E = block_end(); BI != E; ++BI) {
Dan Gohman81d893c2009-11-09 18:19:43 +0000176 BasicBlock *BB = *BI;
177 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;++I)
Dan Gohman16a2c922009-07-13 22:02:44 +0000178 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
179 ++UI) {
Gabor Greif5891ac82010-07-09 14:28:41 +0000180 User *U = *UI;
181 BasicBlock *UserBB = cast<Instruction>(U)->getParent();
182 if (PHINode *P = dyn_cast<PHINode>(U))
Dan Gohman16a2c922009-07-13 22:02:44 +0000183 UserBB = P->getIncomingBlock(UI);
Dan Gohman16a2c922009-07-13 22:02:44 +0000184
Dan Gohmancbac7f12010-03-09 01:53:33 +0000185 // Check the current block, as a fast-path, before checking whether
186 // the use is anywhere in the loop. Most values are used in the same
187 // block they are defined in. Also, blocks not reachable from the
188 // entry are special; uses in them don't need to go through PHIs.
189 if (UserBB != BB &&
190 !LoopBBs.count(UserBB) &&
Dan Gohmanbbf81d82010-03-10 19:38:49 +0000191 DT.isReachableFromEntry(UserBB))
Dan Gohman16a2c922009-07-13 22:02:44 +0000192 return false;
193 }
194 }
195
196 return true;
197}
Dan Gohman93773862009-07-16 16:16:23 +0000198
199/// isLoopSimplifyForm - Return true if the Loop is in the form that
200/// the LoopSimplify form transforms loops to, which is sometimes called
201/// normal form.
202bool Loop::isLoopSimplifyForm() const {
Dan Gohmanf17e9512009-11-05 19:21:41 +0000203 // Normal-form loops have a preheader, a single backedge, and all of their
204 // exits have all their predecessors inside the loop.
205 return getLoopPreheader() && getLoopLatch() && hasDedicatedExits();
206}
207
Andrew Trickd9fc1ce2012-04-10 05:14:42 +0000208/// isSafeToClone - Return true if the loop body is safe to clone in practice.
209/// Routines that reform the loop CFG and split edges often fail on indirectbr.
210bool Loop::isSafeToClone() const {
211 // Return false if any loop blocks contain indirectbrs.
212 for (Loop::block_iterator I = block_begin(), E = block_end(); I != E; ++I) {
213 if (isa<IndirectBrInst>((*I)->getTerminator()))
214 return false;
215 }
216 return true;
217}
218
Dan Gohmanf17e9512009-11-05 19:21:41 +0000219/// hasDedicatedExits - Return true if no exit block for the loop
220/// has a predecessor that is outside the loop.
221bool Loop::hasDedicatedExits() const {
Dan Gohmaneed9e5b2009-10-20 20:41:13 +0000222 // Sort the blocks vector so that we can use binary search to do quick
223 // lookups.
224 SmallPtrSet<BasicBlock *, 16> LoopBBs(block_begin(), block_end());
Dan Gohman93773862009-07-16 16:16:23 +0000225 // Each predecessor of each exit block of a normal loop is contained
226 // within the loop.
227 SmallVector<BasicBlock *, 4> ExitBlocks;
228 getExitBlocks(ExitBlocks);
229 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
230 for (pred_iterator PI = pred_begin(ExitBlocks[i]),
231 PE = pred_end(ExitBlocks[i]); PI != PE; ++PI)
Dan Gohmaneed9e5b2009-10-20 20:41:13 +0000232 if (!LoopBBs.count(*PI))
Dan Gohman93773862009-07-16 16:16:23 +0000233 return false;
234 // All the requirements are met.
235 return true;
236}
237
Dan Gohmanf0608d82009-09-03 16:10:48 +0000238/// getUniqueExitBlocks - Return all unique successor blocks of this loop.
239/// These are the blocks _outside of the current loop_ which are branched to.
Dan Gohman050959c2009-12-11 20:05:23 +0000240/// This assumes that loop exits are in canonical form.
Dan Gohmanf0608d82009-09-03 16:10:48 +0000241///
242void
243Loop::getUniqueExitBlocks(SmallVectorImpl<BasicBlock *> &ExitBlocks) const {
Dan Gohman050959c2009-12-11 20:05:23 +0000244 assert(hasDedicatedExits() &&
245 "getUniqueExitBlocks assumes the loop has canonical form exits!");
Dan Gohman5c89b522009-09-08 15:45:00 +0000246
Dan Gohmanf0608d82009-09-03 16:10:48 +0000247 // Sort the blocks vector so that we can use binary search to do quick
248 // lookups.
249 SmallVector<BasicBlock *, 128> LoopBBs(block_begin(), block_end());
250 std::sort(LoopBBs.begin(), LoopBBs.end());
251
Dan Gohman058db922009-09-03 20:36:13 +0000252 SmallVector<BasicBlock *, 32> switchExitBlocks;
Dan Gohmanf0608d82009-09-03 16:10:48 +0000253
254 for (block_iterator BI = block_begin(), BE = block_end(); BI != BE; ++BI) {
255
256 BasicBlock *current = *BI;
257 switchExitBlocks.clear();
258
Dan Gohman63137d52010-07-23 21:25:16 +0000259 for (succ_iterator I = succ_begin(*BI), E = succ_end(*BI); I != E; ++I) {
Dan Gohmanf0608d82009-09-03 16:10:48 +0000260 // If block is inside the loop then it is not a exit block.
261 if (std::binary_search(LoopBBs.begin(), LoopBBs.end(), *I))
262 continue;
263
Dan Gohman63137d52010-07-23 21:25:16 +0000264 pred_iterator PI = pred_begin(*I);
Dan Gohmanf0608d82009-09-03 16:10:48 +0000265 BasicBlock *firstPred = *PI;
266
267 // If current basic block is this exit block's first predecessor
268 // then only insert exit block in to the output ExitBlocks vector.
269 // This ensures that same exit block is not inserted twice into
270 // ExitBlocks vector.
271 if (current != firstPred)
272 continue;
273
274 // If a terminator has more then two successors, for example SwitchInst,
275 // then it is possible that there are multiple edges from current block
276 // to one exit block.
Dan Gohman63137d52010-07-23 21:25:16 +0000277 if (std::distance(succ_begin(current), succ_end(current)) <= 2) {
Dan Gohmanf0608d82009-09-03 16:10:48 +0000278 ExitBlocks.push_back(*I);
279 continue;
280 }
281
282 // In case of multiple edges from current block to exit block, collect
283 // only one edge in ExitBlocks. Use switchExitBlocks to keep track of
284 // duplicate edges.
285 if (std::find(switchExitBlocks.begin(), switchExitBlocks.end(), *I)
286 == switchExitBlocks.end()) {
287 switchExitBlocks.push_back(*I);
288 ExitBlocks.push_back(*I);
289 }
290 }
291 }
292}
293
294/// getUniqueExitBlock - If getUniqueExitBlocks would return exactly one
295/// block, return that block. Otherwise return null.
296BasicBlock *Loop::getUniqueExitBlock() const {
297 SmallVector<BasicBlock *, 8> UniqueExitBlocks;
298 getUniqueExitBlocks(UniqueExitBlocks);
299 if (UniqueExitBlocks.size() == 1)
300 return UniqueExitBlocks[0];
301 return 0;
302}
303
Dan Gohmandda30cd2010-01-05 21:08:02 +0000304void Loop::dump() const {
305 print(dbgs());
306}
307
Chris Lattnera59cbb22002-07-27 01:12:17 +0000308//===----------------------------------------------------------------------===//
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000309// UnloopUpdater implementation
310//
311
Benjamin Kramera67f14b2011-08-19 01:42:18 +0000312namespace {
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000313/// Find the new parent loop for all blocks within the "unloop" whose last
314/// backedges has just been removed.
315class UnloopUpdater {
316 Loop *Unloop;
317 LoopInfo *LI;
318
319 LoopBlocksDFS DFS;
320
321 // Map unloop's immediate subloops to their nearest reachable parents. Nested
322 // loops within these subloops will not change parents. However, an immediate
323 // subloop's new parent will be the nearest loop reachable from either its own
324 // exits *or* any of its nested loop's exits.
325 DenseMap<Loop*, Loop*> SubloopParents;
326
327 // Flag the presence of an irreducible backedge whose destination is a block
328 // directly contained by the original unloop.
329 bool FoundIB;
330
331public:
332 UnloopUpdater(Loop *UL, LoopInfo *LInfo) :
333 Unloop(UL), LI(LInfo), DFS(UL), FoundIB(false) {}
334
335 void updateBlockParents();
336
Andrew Trickc12d9b92011-08-11 20:27:32 +0000337 void removeBlocksFromAncestors();
338
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000339 void updateSubloopParents();
340
341protected:
342 Loop *getNearestLoop(BasicBlock *BB, Loop *BBLoop);
343};
Benjamin Kramera67f14b2011-08-19 01:42:18 +0000344} // end anonymous namespace
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000345
346/// updateBlockParents - Update the parent loop for all blocks that are directly
347/// contained within the original "unloop".
348void UnloopUpdater::updateBlockParents() {
349 if (Unloop->getNumBlocks()) {
350 // Perform a post order CFG traversal of all blocks within this loop,
351 // propagating the nearest loop from sucessors to predecessors.
352 LoopBlocksTraversal Traversal(DFS, LI);
353 for (LoopBlocksTraversal::POTIterator POI = Traversal.begin(),
354 POE = Traversal.end(); POI != POE; ++POI) {
355
356 Loop *L = LI->getLoopFor(*POI);
357 Loop *NL = getNearestLoop(*POI, L);
358
359 if (NL != L) {
360 // For reducible loops, NL is now an ancestor of Unloop.
361 assert((NL != Unloop && (!NL || NL->contains(Unloop))) &&
362 "uninitialized successor");
363 LI->changeLoopFor(*POI, NL);
364 }
365 else {
366 // Or the current block is part of a subloop, in which case its parent
367 // is unchanged.
368 assert((FoundIB || Unloop->contains(L)) && "uninitialized successor");
369 }
370 }
371 }
372 // Each irreducible loop within the unloop induces a round of iteration using
373 // the DFS result cached by Traversal.
374 bool Changed = FoundIB;
375 for (unsigned NIters = 0; Changed; ++NIters) {
376 assert(NIters < Unloop->getNumBlocks() && "runaway iterative algorithm");
377
378 // Iterate over the postorder list of blocks, propagating the nearest loop
379 // from successors to predecessors as before.
380 Changed = false;
381 for (LoopBlocksDFS::POIterator POI = DFS.beginPostorder(),
382 POE = DFS.endPostorder(); POI != POE; ++POI) {
383
384 Loop *L = LI->getLoopFor(*POI);
385 Loop *NL = getNearestLoop(*POI, L);
386 if (NL != L) {
387 assert(NL != Unloop && (!NL || NL->contains(Unloop)) &&
388 "uninitialized successor");
389 LI->changeLoopFor(*POI, NL);
390 Changed = true;
391 }
392 }
393 }
394}
395
Andrew Trickc12d9b92011-08-11 20:27:32 +0000396/// removeBlocksFromAncestors - Remove unloop's blocks from all ancestors below
397/// their new parents.
398void UnloopUpdater::removeBlocksFromAncestors() {
Andrew Trick5865a8d2011-11-18 03:42:41 +0000399 // Remove all unloop's blocks (including those in nested subloops) from
400 // ancestors below the new parent loop.
Andrew Trickc12d9b92011-08-11 20:27:32 +0000401 for (Loop::block_iterator BI = Unloop->block_begin(),
402 BE = Unloop->block_end(); BI != BE; ++BI) {
Andrew Trick5865a8d2011-11-18 03:42:41 +0000403 Loop *OuterParent = LI->getLoopFor(*BI);
404 if (Unloop->contains(OuterParent)) {
405 while (OuterParent->getParentLoop() != Unloop)
406 OuterParent = OuterParent->getParentLoop();
407 OuterParent = SubloopParents[OuterParent];
408 }
Andrew Trickc12d9b92011-08-11 20:27:32 +0000409 // Remove blocks from former Ancestors except Unloop itself which will be
410 // deleted.
Andrew Trick5865a8d2011-11-18 03:42:41 +0000411 for (Loop *OldParent = Unloop->getParentLoop(); OldParent != OuterParent;
Andrew Trickc12d9b92011-08-11 20:27:32 +0000412 OldParent = OldParent->getParentLoop()) {
413 assert(OldParent && "new loop is not an ancestor of the original");
414 OldParent->removeBlockFromLoop(*BI);
415 }
416 }
417}
418
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000419/// updateSubloopParents - Update the parent loop for all subloops directly
420/// nested within unloop.
421void UnloopUpdater::updateSubloopParents() {
422 while (!Unloop->empty()) {
Andrew Trick5c1ff1f2011-08-11 17:54:58 +0000423 Loop *Subloop = *llvm::prior(Unloop->end());
424 Unloop->removeChildLoop(llvm::prior(Unloop->end()));
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000425
426 assert(SubloopParents.count(Subloop) && "DFS failed to visit subloop");
427 if (SubloopParents[Subloop])
428 SubloopParents[Subloop]->addChildLoop(Subloop);
Andrew Trick5434c1e2011-08-26 03:06:34 +0000429 else
430 LI->addTopLevelLoop(Subloop);
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000431 }
432}
433
434/// getNearestLoop - Return the nearest parent loop among this block's
435/// successors. If a successor is a subloop header, consider its parent to be
436/// the nearest parent of the subloop's exits.
437///
438/// For subloop blocks, simply update SubloopParents and return NULL.
439Loop *UnloopUpdater::getNearestLoop(BasicBlock *BB, Loop *BBLoop) {
440
Andrew Trick5c1ff1f2011-08-11 17:54:58 +0000441 // Initially for blocks directly contained by Unloop, NearLoop == Unloop and
442 // is considered uninitialized.
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000443 Loop *NearLoop = BBLoop;
444
445 Loop *Subloop = 0;
446 if (NearLoop != Unloop && Unloop->contains(NearLoop)) {
447 Subloop = NearLoop;
448 // Find the subloop ancestor that is directly contained within Unloop.
449 while (Subloop->getParentLoop() != Unloop) {
450 Subloop = Subloop->getParentLoop();
451 assert(Subloop && "subloop is not an ancestor of the original loop");
452 }
453 // Get the current nearest parent of the Subloop exits, initially Unloop.
454 if (!SubloopParents.count(Subloop))
455 SubloopParents[Subloop] = Unloop;
456 NearLoop = SubloopParents[Subloop];
457 }
458
459 succ_iterator I = succ_begin(BB), E = succ_end(BB);
460 if (I == E) {
461 assert(!Subloop && "subloop blocks must have a successor");
462 NearLoop = 0; // unloop blocks may now exit the function.
463 }
464 for (; I != E; ++I) {
465 if (*I == BB)
466 continue; // self loops are uninteresting
467
468 Loop *L = LI->getLoopFor(*I);
469 if (L == Unloop) {
470 // This successor has not been processed. This path must lead to an
471 // irreducible backedge.
472 assert((FoundIB || !DFS.hasPostorder(*I)) && "should have seen IB");
473 FoundIB = true;
474 }
475 if (L != Unloop && Unloop->contains(L)) {
476 // Successor is in a subloop.
477 if (Subloop)
478 continue; // Branching within subloops. Ignore it.
479
480 // BB branches from the original into a subloop header.
481 assert(L->getParentLoop() == Unloop && "cannot skip into nested loops");
482
483 // Get the current nearest parent of the Subloop's exits.
484 L = SubloopParents[L];
485 // L could be Unloop if the only exit was an irreducible backedge.
486 }
487 if (L == Unloop) {
488 continue;
489 }
490 // Handle critical edges from Unloop into a sibling loop.
491 if (L && !L->contains(Unloop)) {
492 L = L->getParentLoop();
493 }
494 // Remember the nearest parent loop among successors or subloop exits.
495 if (NearLoop == Unloop || !NearLoop || NearLoop->contains(L))
496 NearLoop = L;
497 }
498 if (Subloop) {
499 SubloopParents[Subloop] = NearLoop;
500 return BBLoop;
501 }
502 return NearLoop;
503}
504
505//===----------------------------------------------------------------------===//
Chris Lattnera59cbb22002-07-27 01:12:17 +0000506// LoopInfo implementation
507//
Chris Lattnera59cbb22002-07-27 01:12:17 +0000508bool LoopInfo::runOnFunction(Function &) {
509 releaseMemory();
Dan Gohman9d59d9f2009-06-27 21:22:48 +0000510 LI.Calculate(getAnalysis<DominatorTree>().getBase()); // Update
Chris Lattnera59cbb22002-07-27 01:12:17 +0000511 return false;
512}
513
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000514/// updateUnloop - The last backedge has been removed from a loop--now the
515/// "unloop". Find a new parent for the blocks contained within unloop and
Andrew Trick5c1ff1f2011-08-11 17:54:58 +0000516/// update the loop tree. We don't necessarily have valid dominators at this
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000517/// point, but LoopInfo is still valid except for the removal of this loop.
518///
519/// Note that Unloop may now be an empty loop. Calling Loop::getHeader without
520/// checking first is illegal.
521void LoopInfo::updateUnloop(Loop *Unloop) {
522
523 // First handle the special case of no parent loop to simplify the algorithm.
524 if (!Unloop->getParentLoop()) {
525 // Since BBLoop had no parent, Unloop blocks are no longer in a loop.
526 for (Loop::block_iterator I = Unloop->block_begin(),
527 E = Unloop->block_end(); I != E; ++I) {
528
529 // Don't reparent blocks in subloops.
530 if (getLoopFor(*I) != Unloop)
531 continue;
532
533 // Blocks no longer have a parent but are still referenced by Unloop until
534 // the Unloop object is deleted.
535 LI.changeLoopFor(*I, 0);
536 }
537
538 // Remove the loop from the top-level LoopInfo object.
Duncan Sands1f6a3292011-08-12 14:54:45 +0000539 for (LoopInfo::iterator I = LI.begin();; ++I) {
540 assert(I != LI.end() && "Couldn't find loop");
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000541 if (*I == Unloop) {
542 LI.removeLoop(I);
543 break;
544 }
545 }
546
547 // Move all of the subloops to the top-level.
548 while (!Unloop->empty())
Andrew Trick5c1ff1f2011-08-11 17:54:58 +0000549 LI.addTopLevelLoop(Unloop->removeChildLoop(llvm::prior(Unloop->end())));
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000550
551 return;
552 }
553
554 // Update the parent loop for all blocks within the loop. Blocks within
555 // subloops will not change parents.
556 UnloopUpdater Updater(Unloop, this);
557 Updater.updateBlockParents();
558
Andrew Trickc12d9b92011-08-11 20:27:32 +0000559 // Remove blocks from former ancestor loops.
560 Updater.removeBlocksFromAncestors();
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000561
562 // Add direct subloops as children in their new parent loop.
563 Updater.updateSubloopParents();
564
565 // Remove unloop from its parent loop.
566 Loop *ParentLoop = Unloop->getParentLoop();
Duncan Sands1f6a3292011-08-12 14:54:45 +0000567 for (Loop::iterator I = ParentLoop->begin();; ++I) {
568 assert(I != ParentLoop->end() && "Couldn't find loop");
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000569 if (*I == Unloop) {
570 ParentLoop->removeChildLoop(I);
571 break;
572 }
573 }
574}
575
Dan Gohman5c89b522009-09-08 15:45:00 +0000576void LoopInfo::verifyAnalysis() const {
Dan Gohman9450b0e2009-09-28 00:27:48 +0000577 // LoopInfo is a FunctionPass, but verifying every loop in the function
578 // each time verifyAnalysis is called is very expensive. The
579 // -verify-loop-info option can enable this. In order to perform some
580 // checking by default, LoopPass has been taught to call verifyLoop
581 // manually during loop pass sequences.
582
583 if (!VerifyLoopInfo) return;
584
Andrew Trick5434c1e2011-08-26 03:06:34 +0000585 DenseSet<const Loop*> Loops;
Dan Gohman5c89b522009-09-08 15:45:00 +0000586 for (iterator I = begin(), E = end(); I != E; ++I) {
587 assert(!(*I)->getParentLoop() && "Top-level loop has a parent!");
Andrew Trick5434c1e2011-08-26 03:06:34 +0000588 (*I)->verifyLoopNest(&Loops);
Dan Gohman5c89b522009-09-08 15:45:00 +0000589 }
Dan Gohman9450b0e2009-09-28 00:27:48 +0000590
Andrew Trick5434c1e2011-08-26 03:06:34 +0000591 // Verify that blocks are mapped to valid loops.
592 //
593 // FIXME: With an up-to-date DFS (see LoopIterator.h) and DominatorTree, we
594 // could also verify that the blocks are still in the correct loops.
595 for (DenseMap<BasicBlock*, Loop*>::const_iterator I = LI.BBMap.begin(),
596 E = LI.BBMap.end(); I != E; ++I) {
597 assert(Loops.count(I->second) && "orphaned loop");
598 assert(I->second->contains(I->first) && "orphaned block");
599 }
Dan Gohman5c89b522009-09-08 15:45:00 +0000600}
601
Chris Lattner1b7f7dc2002-04-28 16:21:30 +0000602void LoopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerf57b8452002-04-27 06:56:12 +0000603 AU.setPreservesAll();
Devang Patel53c279b2007-06-08 00:17:13 +0000604 AU.addRequired<DominatorTree>();
Chris Lattner93193f82002-01-31 00:42:27 +0000605}
Chris Lattner791102f2009-08-23 05:17:37 +0000606
Chris Lattner45cfe542009-08-23 06:03:38 +0000607void LoopInfo::print(raw_ostream &OS, const Module*) const {
608 LI.print(OS);
Chris Lattner791102f2009-08-23 05:17:37 +0000609}
610
Andrew Trick2d31ae32011-08-10 01:59:05 +0000611//===----------------------------------------------------------------------===//
612// LoopBlocksDFS implementation
613//
614
615/// Traverse the loop blocks and store the DFS result.
616/// Useful for clients that just want the final DFS result and don't need to
617/// visit blocks during the initial traversal.
618void LoopBlocksDFS::perform(LoopInfo *LI) {
619 LoopBlocksTraversal Traversal(*this, LI);
620 for (LoopBlocksTraversal::POTIterator POI = Traversal.begin(),
621 POE = Traversal.end(); POI != POE; ++POI) ;
622}