blob: 5d5f5066b30651b64f162c3deff0131c5c9cd742 [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 Trickcbf24b42012-06-20 03:42:09 +000021#include "llvm/Analysis/LoopInfoImpl.h"
Andrew Trick2d31ae32011-08-10 01:59:05 +000022#include "llvm/Analysis/LoopIterator.h"
Dan Gohmanf0426602011-12-14 23:49:11 +000023#include "llvm/Analysis/ValueTracking.h"
Chris Lattnera59cbb22002-07-27 01:12:17 +000024#include "llvm/Assembly/Writer.h"
Misha Brukman10d208d2004-01-30 17:26:24 +000025#include "llvm/Support/CFG.h"
Dan Gohman9450b0e2009-09-28 00:27:48 +000026#include "llvm/Support/CommandLine.h"
Dan Gohmandda30cd2010-01-05 21:08:02 +000027#include "llvm/Support/Debug.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000028#include "llvm/ADT/DepthFirstIterator.h"
Chris Lattnerb1f5d8b2007-03-04 04:06:39 +000029#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner0bbe58f2001-11-26 18:41:20 +000030#include <algorithm>
Chris Lattner46758a82004-04-12 20:26:17 +000031using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000032
Andrew Trickcbf24b42012-06-20 03:42:09 +000033// Explicitly instantiate methods in LoopInfoImpl.h for IR-level Loops.
34template class llvm::LoopBase<BasicBlock, Loop>;
35template class llvm::LoopInfoBase<BasicBlock, Loop>;
36
Dan Gohman9450b0e2009-09-28 00:27:48 +000037// Always verify loopinfo if expensive checking is enabled.
38#ifdef XDEBUG
Dan Gohmanb3579832010-04-15 17:08:50 +000039static bool VerifyLoopInfo = true;
Dan Gohman9450b0e2009-09-28 00:27:48 +000040#else
Dan Gohmanb3579832010-04-15 17:08:50 +000041static bool VerifyLoopInfo = false;
Dan Gohman9450b0e2009-09-28 00:27:48 +000042#endif
43static cl::opt<bool,true>
44VerifyLoopInfoX("verify-loop-info", cl::location(VerifyLoopInfo),
45 cl::desc("Verify loop info (time consuming)"));
46
Andrew Trick37aa33b2012-06-20 05:23:33 +000047static cl::opt<bool>
48StableLoopInfo("stable-loops", cl::Hidden, cl::init(false),
49 cl::desc("Compute a stable loop tree."));
50
Devang Patel19974732007-05-03 01:11:54 +000051char LoopInfo::ID = 0;
Owen Anderson2ab36d32010-10-12 19:48:12 +000052INITIALIZE_PASS_BEGIN(LoopInfo, "loops", "Natural Loop Information", true, true)
53INITIALIZE_PASS_DEPENDENCY(DominatorTree)
54INITIALIZE_PASS_END(LoopInfo, "loops", "Natural Loop Information", true, true)
Chris Lattner93193f82002-01-31 00:42:27 +000055
56//===----------------------------------------------------------------------===//
Chris Lattner1b7f7dc2002-04-28 16:21:30 +000057// Loop implementation
Chris Lattner93193f82002-01-31 00:42:27 +000058//
Misha Brukman6b290a52002-10-11 05:31:10 +000059
Dan Gohman16a2c922009-07-13 22:02:44 +000060/// isLoopInvariant - Return true if the specified value is loop invariant
61///
62bool Loop::isLoopInvariant(Value *V) const {
63 if (Instruction *I = dyn_cast<Instruction>(V))
Chris Lattneradc79912010-09-06 01:05:37 +000064 return !contains(I);
Dan Gohman16a2c922009-07-13 22:02:44 +000065 return true; // All non-instructions are loop invariant
66}
67
Chris Lattneradc79912010-09-06 01:05:37 +000068/// hasLoopInvariantOperands - Return true if all the operands of the
Andrew Trick882bcc62011-08-03 23:45:50 +000069/// specified instruction are loop invariant.
Chris Lattneradc79912010-09-06 01:05:37 +000070bool Loop::hasLoopInvariantOperands(Instruction *I) const {
71 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
72 if (!isLoopInvariant(I->getOperand(i)))
73 return false;
Andrew Trick882bcc62011-08-03 23:45:50 +000074
Chris Lattneradc79912010-09-06 01:05:37 +000075 return true;
Dan Gohmana3420262009-07-14 01:06:29 +000076}
77
78/// makeLoopInvariant - If the given value is an instruciton inside of the
79/// loop and it can be hoisted, do so to make it trivially loop-invariant.
80/// Return true if the value after any hoisting is loop invariant. This
81/// function can be used as a slightly more aggressive replacement for
82/// isLoopInvariant.
83///
84/// If InsertPt is specified, it is the point to hoist instructions to.
85/// If null, the terminator of the loop preheader is used.
86///
Dan Gohmanbdc017e2009-07-15 01:25:43 +000087bool Loop::makeLoopInvariant(Value *V, bool &Changed,
88 Instruction *InsertPt) const {
Dan Gohmana3420262009-07-14 01:06:29 +000089 if (Instruction *I = dyn_cast<Instruction>(V))
Dan Gohmanbdc017e2009-07-15 01:25:43 +000090 return makeLoopInvariant(I, Changed, InsertPt);
Dan Gohmana3420262009-07-14 01:06:29 +000091 return true; // All non-instructions are loop-invariant.
92}
93
94/// makeLoopInvariant - If the given instruction is inside of the
95/// loop and it can be hoisted, do so to make it trivially loop-invariant.
96/// Return true if the instruction after any hoisting is loop invariant. This
97/// function can be used as a slightly more aggressive replacement for
98/// isLoopInvariant.
99///
100/// If InsertPt is specified, it is the point to hoist instructions to.
101/// If null, the terminator of the loop preheader is used.
102///
Dan Gohmanbdc017e2009-07-15 01:25:43 +0000103bool Loop::makeLoopInvariant(Instruction *I, bool &Changed,
104 Instruction *InsertPt) const {
Dan Gohmana3420262009-07-14 01:06:29 +0000105 // Test if the value is already loop-invariant.
106 if (isLoopInvariant(I))
107 return true;
Dan Gohmanf0426602011-12-14 23:49:11 +0000108 if (!isSafeToSpeculativelyExecute(I))
Dan Gohmana3420262009-07-14 01:06:29 +0000109 return false;
Eli Friedman0b79a772009-07-17 04:28:42 +0000110 if (I->mayReadFromMemory())
Dan Gohmana3420262009-07-14 01:06:29 +0000111 return false;
Bill Wendlingc9b2a982011-08-17 20:36:44 +0000112 // The landingpad instruction is immobile.
113 if (isa<LandingPadInst>(I))
114 return false;
Dan Gohmana3420262009-07-14 01:06:29 +0000115 // Determine the insertion point, unless one was given.
116 if (!InsertPt) {
117 BasicBlock *Preheader = getLoopPreheader();
118 // Without a preheader, hoisting is not feasible.
119 if (!Preheader)
120 return false;
121 InsertPt = Preheader->getTerminator();
122 }
123 // Don't hoist instructions with loop-variant operands.
124 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
Dan Gohmanbdc017e2009-07-15 01:25:43 +0000125 if (!makeLoopInvariant(I->getOperand(i), Changed, InsertPt))
Dan Gohmana3420262009-07-14 01:06:29 +0000126 return false;
Andrew Trick882bcc62011-08-03 23:45:50 +0000127
Dan Gohmana3420262009-07-14 01:06:29 +0000128 // Hoist.
129 I->moveBefore(InsertPt);
Dan Gohmanbdc017e2009-07-15 01:25:43 +0000130 Changed = true;
Dan Gohmana3420262009-07-14 01:06:29 +0000131 return true;
132}
133
Dan Gohman16a2c922009-07-13 22:02:44 +0000134/// getCanonicalInductionVariable - Check to see if the loop has a canonical
135/// induction variable: an integer recurrence that starts at 0 and increments
136/// by one each time through the loop. If so, return the phi node that
137/// corresponds to it.
138///
139/// The IndVarSimplify pass transforms loops to have a canonical induction
140/// variable.
141///
142PHINode *Loop::getCanonicalInductionVariable() const {
143 BasicBlock *H = getHeader();
144
145 BasicBlock *Incoming = 0, *Backedge = 0;
Dan Gohman63137d52010-07-23 21:25:16 +0000146 pred_iterator PI = pred_begin(H);
147 assert(PI != pred_end(H) &&
Dan Gohman16a2c922009-07-13 22:02:44 +0000148 "Loop must have at least one backedge!");
149 Backedge = *PI++;
Dan Gohman63137d52010-07-23 21:25:16 +0000150 if (PI == pred_end(H)) return 0; // dead loop
Dan Gohman16a2c922009-07-13 22:02:44 +0000151 Incoming = *PI++;
Dan Gohman63137d52010-07-23 21:25:16 +0000152 if (PI != pred_end(H)) return 0; // multiple backedges?
Dan Gohman16a2c922009-07-13 22:02:44 +0000153
154 if (contains(Incoming)) {
155 if (contains(Backedge))
156 return 0;
157 std::swap(Incoming, Backedge);
158 } else if (!contains(Backedge))
159 return 0;
160
161 // Loop over all of the PHI nodes, looking for a canonical indvar.
162 for (BasicBlock::iterator I = H->begin(); isa<PHINode>(I); ++I) {
163 PHINode *PN = cast<PHINode>(I);
164 if (ConstantInt *CI =
165 dyn_cast<ConstantInt>(PN->getIncomingValueForBlock(Incoming)))
166 if (CI->isNullValue())
167 if (Instruction *Inc =
168 dyn_cast<Instruction>(PN->getIncomingValueForBlock(Backedge)))
169 if (Inc->getOpcode() == Instruction::Add &&
170 Inc->getOperand(0) == PN)
171 if (ConstantInt *CI = dyn_cast<ConstantInt>(Inc->getOperand(1)))
172 if (CI->equalsInt(1))
173 return PN;
174 }
175 return 0;
176}
177
Dan Gohman16a2c922009-07-13 22:02:44 +0000178/// isLCSSAForm - Return true if the Loop is in LCSSA form
Dan Gohmanbbf81d82010-03-10 19:38:49 +0000179bool Loop::isLCSSAForm(DominatorTree &DT) const {
Dan Gohman16a2c922009-07-13 22:02:44 +0000180 // Sort the blocks vector so that we can use binary search to do quick
181 // lookups.
Gabor Greif5891ac82010-07-09 14:28:41 +0000182 SmallPtrSet<BasicBlock*, 16> LoopBBs(block_begin(), block_end());
Dan Gohman16a2c922009-07-13 22:02:44 +0000183
184 for (block_iterator BI = block_begin(), E = block_end(); BI != E; ++BI) {
Dan Gohman81d893c2009-11-09 18:19:43 +0000185 BasicBlock *BB = *BI;
186 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;++I)
Dan Gohman16a2c922009-07-13 22:02:44 +0000187 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
188 ++UI) {
Gabor Greif5891ac82010-07-09 14:28:41 +0000189 User *U = *UI;
190 BasicBlock *UserBB = cast<Instruction>(U)->getParent();
191 if (PHINode *P = dyn_cast<PHINode>(U))
Dan Gohman16a2c922009-07-13 22:02:44 +0000192 UserBB = P->getIncomingBlock(UI);
Dan Gohman16a2c922009-07-13 22:02:44 +0000193
Dan Gohmancbac7f12010-03-09 01:53:33 +0000194 // Check the current block, as a fast-path, before checking whether
195 // the use is anywhere in the loop. Most values are used in the same
196 // block they are defined in. Also, blocks not reachable from the
197 // entry are special; uses in them don't need to go through PHIs.
198 if (UserBB != BB &&
199 !LoopBBs.count(UserBB) &&
Dan Gohmanbbf81d82010-03-10 19:38:49 +0000200 DT.isReachableFromEntry(UserBB))
Dan Gohman16a2c922009-07-13 22:02:44 +0000201 return false;
202 }
203 }
204
205 return true;
206}
Dan Gohman93773862009-07-16 16:16:23 +0000207
208/// isLoopSimplifyForm - Return true if the Loop is in the form that
209/// the LoopSimplify form transforms loops to, which is sometimes called
210/// normal form.
211bool Loop::isLoopSimplifyForm() const {
Dan Gohmanf17e9512009-11-05 19:21:41 +0000212 // Normal-form loops have a preheader, a single backedge, and all of their
213 // exits have all their predecessors inside the loop.
214 return getLoopPreheader() && getLoopLatch() && hasDedicatedExits();
215}
216
Andrew Trickd9fc1ce2012-04-10 05:14:42 +0000217/// isSafeToClone - Return true if the loop body is safe to clone in practice.
218/// Routines that reform the loop CFG and split edges often fail on indirectbr.
219bool Loop::isSafeToClone() const {
220 // Return false if any loop blocks contain indirectbrs.
221 for (Loop::block_iterator I = block_begin(), E = block_end(); I != E; ++I) {
222 if (isa<IndirectBrInst>((*I)->getTerminator()))
223 return false;
224 }
225 return true;
226}
227
Dan Gohmanf17e9512009-11-05 19:21:41 +0000228/// hasDedicatedExits - Return true if no exit block for the loop
229/// has a predecessor that is outside the loop.
230bool Loop::hasDedicatedExits() const {
Dan Gohmaneed9e5b2009-10-20 20:41:13 +0000231 // Sort the blocks vector so that we can use binary search to do quick
232 // lookups.
233 SmallPtrSet<BasicBlock *, 16> LoopBBs(block_begin(), block_end());
Dan Gohman93773862009-07-16 16:16:23 +0000234 // Each predecessor of each exit block of a normal loop is contained
235 // within the loop.
236 SmallVector<BasicBlock *, 4> ExitBlocks;
237 getExitBlocks(ExitBlocks);
238 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
239 for (pred_iterator PI = pred_begin(ExitBlocks[i]),
240 PE = pred_end(ExitBlocks[i]); PI != PE; ++PI)
Dan Gohmaneed9e5b2009-10-20 20:41:13 +0000241 if (!LoopBBs.count(*PI))
Dan Gohman93773862009-07-16 16:16:23 +0000242 return false;
243 // All the requirements are met.
244 return true;
245}
246
Dan Gohmanf0608d82009-09-03 16:10:48 +0000247/// getUniqueExitBlocks - Return all unique successor blocks of this loop.
248/// These are the blocks _outside of the current loop_ which are branched to.
Dan Gohman050959c2009-12-11 20:05:23 +0000249/// This assumes that loop exits are in canonical form.
Dan Gohmanf0608d82009-09-03 16:10:48 +0000250///
251void
252Loop::getUniqueExitBlocks(SmallVectorImpl<BasicBlock *> &ExitBlocks) const {
Dan Gohman050959c2009-12-11 20:05:23 +0000253 assert(hasDedicatedExits() &&
254 "getUniqueExitBlocks assumes the loop has canonical form exits!");
Dan Gohman5c89b522009-09-08 15:45:00 +0000255
Dan Gohmanf0608d82009-09-03 16:10:48 +0000256 // Sort the blocks vector so that we can use binary search to do quick
257 // lookups.
258 SmallVector<BasicBlock *, 128> LoopBBs(block_begin(), block_end());
259 std::sort(LoopBBs.begin(), LoopBBs.end());
260
Dan Gohman058db922009-09-03 20:36:13 +0000261 SmallVector<BasicBlock *, 32> switchExitBlocks;
Dan Gohmanf0608d82009-09-03 16:10:48 +0000262
263 for (block_iterator BI = block_begin(), BE = block_end(); BI != BE; ++BI) {
264
265 BasicBlock *current = *BI;
266 switchExitBlocks.clear();
267
Dan Gohman63137d52010-07-23 21:25:16 +0000268 for (succ_iterator I = succ_begin(*BI), E = succ_end(*BI); I != E; ++I) {
Dan Gohmanf0608d82009-09-03 16:10:48 +0000269 // If block is inside the loop then it is not a exit block.
270 if (std::binary_search(LoopBBs.begin(), LoopBBs.end(), *I))
271 continue;
272
Dan Gohman63137d52010-07-23 21:25:16 +0000273 pred_iterator PI = pred_begin(*I);
Dan Gohmanf0608d82009-09-03 16:10:48 +0000274 BasicBlock *firstPred = *PI;
275
276 // If current basic block is this exit block's first predecessor
277 // then only insert exit block in to the output ExitBlocks vector.
278 // This ensures that same exit block is not inserted twice into
279 // ExitBlocks vector.
280 if (current != firstPred)
281 continue;
282
283 // If a terminator has more then two successors, for example SwitchInst,
284 // then it is possible that there are multiple edges from current block
285 // to one exit block.
Dan Gohman63137d52010-07-23 21:25:16 +0000286 if (std::distance(succ_begin(current), succ_end(current)) <= 2) {
Dan Gohmanf0608d82009-09-03 16:10:48 +0000287 ExitBlocks.push_back(*I);
288 continue;
289 }
290
291 // In case of multiple edges from current block to exit block, collect
292 // only one edge in ExitBlocks. Use switchExitBlocks to keep track of
293 // duplicate edges.
294 if (std::find(switchExitBlocks.begin(), switchExitBlocks.end(), *I)
295 == switchExitBlocks.end()) {
296 switchExitBlocks.push_back(*I);
297 ExitBlocks.push_back(*I);
298 }
299 }
300 }
301}
302
303/// getUniqueExitBlock - If getUniqueExitBlocks would return exactly one
304/// block, return that block. Otherwise return null.
305BasicBlock *Loop::getUniqueExitBlock() const {
306 SmallVector<BasicBlock *, 8> UniqueExitBlocks;
307 getUniqueExitBlocks(UniqueExitBlocks);
308 if (UniqueExitBlocks.size() == 1)
309 return UniqueExitBlocks[0];
310 return 0;
311}
312
Dan Gohmandda30cd2010-01-05 21:08:02 +0000313void Loop::dump() const {
314 print(dbgs());
315}
316
Chris Lattnera59cbb22002-07-27 01:12:17 +0000317//===----------------------------------------------------------------------===//
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000318// UnloopUpdater implementation
319//
320
Benjamin Kramera67f14b2011-08-19 01:42:18 +0000321namespace {
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000322/// Find the new parent loop for all blocks within the "unloop" whose last
323/// backedges has just been removed.
324class UnloopUpdater {
325 Loop *Unloop;
326 LoopInfo *LI;
327
328 LoopBlocksDFS DFS;
329
330 // Map unloop's immediate subloops to their nearest reachable parents. Nested
331 // loops within these subloops will not change parents. However, an immediate
332 // subloop's new parent will be the nearest loop reachable from either its own
333 // exits *or* any of its nested loop's exits.
334 DenseMap<Loop*, Loop*> SubloopParents;
335
336 // Flag the presence of an irreducible backedge whose destination is a block
337 // directly contained by the original unloop.
338 bool FoundIB;
339
340public:
341 UnloopUpdater(Loop *UL, LoopInfo *LInfo) :
342 Unloop(UL), LI(LInfo), DFS(UL), FoundIB(false) {}
343
344 void updateBlockParents();
345
Andrew Trickc12d9b92011-08-11 20:27:32 +0000346 void removeBlocksFromAncestors();
347
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000348 void updateSubloopParents();
349
350protected:
351 Loop *getNearestLoop(BasicBlock *BB, Loop *BBLoop);
352};
Benjamin Kramera67f14b2011-08-19 01:42:18 +0000353} // end anonymous namespace
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000354
355/// updateBlockParents - Update the parent loop for all blocks that are directly
356/// contained within the original "unloop".
357void UnloopUpdater::updateBlockParents() {
358 if (Unloop->getNumBlocks()) {
359 // Perform a post order CFG traversal of all blocks within this loop,
360 // propagating the nearest loop from sucessors to predecessors.
361 LoopBlocksTraversal Traversal(DFS, LI);
362 for (LoopBlocksTraversal::POTIterator POI = Traversal.begin(),
363 POE = Traversal.end(); POI != POE; ++POI) {
364
365 Loop *L = LI->getLoopFor(*POI);
366 Loop *NL = getNearestLoop(*POI, L);
367
368 if (NL != L) {
369 // For reducible loops, NL is now an ancestor of Unloop.
370 assert((NL != Unloop && (!NL || NL->contains(Unloop))) &&
371 "uninitialized successor");
372 LI->changeLoopFor(*POI, NL);
373 }
374 else {
375 // Or the current block is part of a subloop, in which case its parent
376 // is unchanged.
377 assert((FoundIB || Unloop->contains(L)) && "uninitialized successor");
378 }
379 }
380 }
381 // Each irreducible loop within the unloop induces a round of iteration using
382 // the DFS result cached by Traversal.
383 bool Changed = FoundIB;
384 for (unsigned NIters = 0; Changed; ++NIters) {
385 assert(NIters < Unloop->getNumBlocks() && "runaway iterative algorithm");
386
387 // Iterate over the postorder list of blocks, propagating the nearest loop
388 // from successors to predecessors as before.
389 Changed = false;
390 for (LoopBlocksDFS::POIterator POI = DFS.beginPostorder(),
391 POE = DFS.endPostorder(); POI != POE; ++POI) {
392
393 Loop *L = LI->getLoopFor(*POI);
394 Loop *NL = getNearestLoop(*POI, L);
395 if (NL != L) {
396 assert(NL != Unloop && (!NL || NL->contains(Unloop)) &&
397 "uninitialized successor");
398 LI->changeLoopFor(*POI, NL);
399 Changed = true;
400 }
401 }
402 }
403}
404
Andrew Trickc12d9b92011-08-11 20:27:32 +0000405/// removeBlocksFromAncestors - Remove unloop's blocks from all ancestors below
406/// their new parents.
407void UnloopUpdater::removeBlocksFromAncestors() {
Andrew Trick5865a8d2011-11-18 03:42:41 +0000408 // Remove all unloop's blocks (including those in nested subloops) from
409 // ancestors below the new parent loop.
Andrew Trickc12d9b92011-08-11 20:27:32 +0000410 for (Loop::block_iterator BI = Unloop->block_begin(),
411 BE = Unloop->block_end(); BI != BE; ++BI) {
Andrew Trick5865a8d2011-11-18 03:42:41 +0000412 Loop *OuterParent = LI->getLoopFor(*BI);
413 if (Unloop->contains(OuterParent)) {
414 while (OuterParent->getParentLoop() != Unloop)
415 OuterParent = OuterParent->getParentLoop();
416 OuterParent = SubloopParents[OuterParent];
417 }
Andrew Trickc12d9b92011-08-11 20:27:32 +0000418 // Remove blocks from former Ancestors except Unloop itself which will be
419 // deleted.
Andrew Trick5865a8d2011-11-18 03:42:41 +0000420 for (Loop *OldParent = Unloop->getParentLoop(); OldParent != OuterParent;
Andrew Trickc12d9b92011-08-11 20:27:32 +0000421 OldParent = OldParent->getParentLoop()) {
422 assert(OldParent && "new loop is not an ancestor of the original");
423 OldParent->removeBlockFromLoop(*BI);
424 }
425 }
426}
427
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000428/// updateSubloopParents - Update the parent loop for all subloops directly
429/// nested within unloop.
430void UnloopUpdater::updateSubloopParents() {
431 while (!Unloop->empty()) {
Andrew Trick5c1ff1f2011-08-11 17:54:58 +0000432 Loop *Subloop = *llvm::prior(Unloop->end());
433 Unloop->removeChildLoop(llvm::prior(Unloop->end()));
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000434
435 assert(SubloopParents.count(Subloop) && "DFS failed to visit subloop");
436 if (SubloopParents[Subloop])
437 SubloopParents[Subloop]->addChildLoop(Subloop);
Andrew Trick5434c1e2011-08-26 03:06:34 +0000438 else
439 LI->addTopLevelLoop(Subloop);
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000440 }
441}
442
443/// getNearestLoop - Return the nearest parent loop among this block's
444/// successors. If a successor is a subloop header, consider its parent to be
445/// the nearest parent of the subloop's exits.
446///
447/// For subloop blocks, simply update SubloopParents and return NULL.
448Loop *UnloopUpdater::getNearestLoop(BasicBlock *BB, Loop *BBLoop) {
449
Andrew Trick5c1ff1f2011-08-11 17:54:58 +0000450 // Initially for blocks directly contained by Unloop, NearLoop == Unloop and
451 // is considered uninitialized.
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000452 Loop *NearLoop = BBLoop;
453
454 Loop *Subloop = 0;
455 if (NearLoop != Unloop && Unloop->contains(NearLoop)) {
456 Subloop = NearLoop;
457 // Find the subloop ancestor that is directly contained within Unloop.
458 while (Subloop->getParentLoop() != Unloop) {
459 Subloop = Subloop->getParentLoop();
460 assert(Subloop && "subloop is not an ancestor of the original loop");
461 }
462 // Get the current nearest parent of the Subloop exits, initially Unloop.
463 if (!SubloopParents.count(Subloop))
464 SubloopParents[Subloop] = Unloop;
465 NearLoop = SubloopParents[Subloop];
466 }
467
468 succ_iterator I = succ_begin(BB), E = succ_end(BB);
469 if (I == E) {
470 assert(!Subloop && "subloop blocks must have a successor");
471 NearLoop = 0; // unloop blocks may now exit the function.
472 }
473 for (; I != E; ++I) {
474 if (*I == BB)
475 continue; // self loops are uninteresting
476
477 Loop *L = LI->getLoopFor(*I);
478 if (L == Unloop) {
479 // This successor has not been processed. This path must lead to an
480 // irreducible backedge.
481 assert((FoundIB || !DFS.hasPostorder(*I)) && "should have seen IB");
482 FoundIB = true;
483 }
484 if (L != Unloop && Unloop->contains(L)) {
485 // Successor is in a subloop.
486 if (Subloop)
487 continue; // Branching within subloops. Ignore it.
488
489 // BB branches from the original into a subloop header.
490 assert(L->getParentLoop() == Unloop && "cannot skip into nested loops");
491
492 // Get the current nearest parent of the Subloop's exits.
493 L = SubloopParents[L];
494 // L could be Unloop if the only exit was an irreducible backedge.
495 }
496 if (L == Unloop) {
497 continue;
498 }
499 // Handle critical edges from Unloop into a sibling loop.
500 if (L && !L->contains(Unloop)) {
501 L = L->getParentLoop();
502 }
503 // Remember the nearest parent loop among successors or subloop exits.
504 if (NearLoop == Unloop || !NearLoop || NearLoop->contains(L))
505 NearLoop = L;
506 }
507 if (Subloop) {
508 SubloopParents[Subloop] = NearLoop;
509 return BBLoop;
510 }
511 return NearLoop;
512}
513
514//===----------------------------------------------------------------------===//
Chris Lattnera59cbb22002-07-27 01:12:17 +0000515// LoopInfo implementation
516//
Chris Lattnera59cbb22002-07-27 01:12:17 +0000517bool LoopInfo::runOnFunction(Function &) {
518 releaseMemory();
Andrew Trick37aa33b2012-06-20 05:23:33 +0000519 if (StableLoopInfo)
520 LI.Analyze(getAnalysis<DominatorTree>().getBase());
521 else
522 LI.Calculate(getAnalysis<DominatorTree>().getBase()); // Update
Chris Lattnera59cbb22002-07-27 01:12:17 +0000523 return false;
524}
525
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000526/// updateUnloop - The last backedge has been removed from a loop--now the
527/// "unloop". Find a new parent for the blocks contained within unloop and
Andrew Trick5c1ff1f2011-08-11 17:54:58 +0000528/// update the loop tree. We don't necessarily have valid dominators at this
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000529/// point, but LoopInfo is still valid except for the removal of this loop.
530///
531/// Note that Unloop may now be an empty loop. Calling Loop::getHeader without
532/// checking first is illegal.
533void LoopInfo::updateUnloop(Loop *Unloop) {
534
535 // First handle the special case of no parent loop to simplify the algorithm.
536 if (!Unloop->getParentLoop()) {
537 // Since BBLoop had no parent, Unloop blocks are no longer in a loop.
538 for (Loop::block_iterator I = Unloop->block_begin(),
539 E = Unloop->block_end(); I != E; ++I) {
540
541 // Don't reparent blocks in subloops.
542 if (getLoopFor(*I) != Unloop)
543 continue;
544
545 // Blocks no longer have a parent but are still referenced by Unloop until
546 // the Unloop object is deleted.
547 LI.changeLoopFor(*I, 0);
548 }
549
550 // Remove the loop from the top-level LoopInfo object.
Duncan Sands1f6a3292011-08-12 14:54:45 +0000551 for (LoopInfo::iterator I = LI.begin();; ++I) {
552 assert(I != LI.end() && "Couldn't find loop");
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000553 if (*I == Unloop) {
554 LI.removeLoop(I);
555 break;
556 }
557 }
558
559 // Move all of the subloops to the top-level.
560 while (!Unloop->empty())
Andrew Trick5c1ff1f2011-08-11 17:54:58 +0000561 LI.addTopLevelLoop(Unloop->removeChildLoop(llvm::prior(Unloop->end())));
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000562
563 return;
564 }
565
566 // Update the parent loop for all blocks within the loop. Blocks within
567 // subloops will not change parents.
568 UnloopUpdater Updater(Unloop, this);
569 Updater.updateBlockParents();
570
Andrew Trickc12d9b92011-08-11 20:27:32 +0000571 // Remove blocks from former ancestor loops.
572 Updater.removeBlocksFromAncestors();
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000573
574 // Add direct subloops as children in their new parent loop.
575 Updater.updateSubloopParents();
576
577 // Remove unloop from its parent loop.
578 Loop *ParentLoop = Unloop->getParentLoop();
Duncan Sands1f6a3292011-08-12 14:54:45 +0000579 for (Loop::iterator I = ParentLoop->begin();; ++I) {
580 assert(I != ParentLoop->end() && "Couldn't find loop");
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000581 if (*I == Unloop) {
582 ParentLoop->removeChildLoop(I);
583 break;
584 }
585 }
586}
587
Dan Gohman5c89b522009-09-08 15:45:00 +0000588void LoopInfo::verifyAnalysis() const {
Dan Gohman9450b0e2009-09-28 00:27:48 +0000589 // LoopInfo is a FunctionPass, but verifying every loop in the function
590 // each time verifyAnalysis is called is very expensive. The
591 // -verify-loop-info option can enable this. In order to perform some
592 // checking by default, LoopPass has been taught to call verifyLoop
593 // manually during loop pass sequences.
594
595 if (!VerifyLoopInfo) return;
596
Andrew Trick5434c1e2011-08-26 03:06:34 +0000597 DenseSet<const Loop*> Loops;
Dan Gohman5c89b522009-09-08 15:45:00 +0000598 for (iterator I = begin(), E = end(); I != E; ++I) {
599 assert(!(*I)->getParentLoop() && "Top-level loop has a parent!");
Andrew Trick5434c1e2011-08-26 03:06:34 +0000600 (*I)->verifyLoopNest(&Loops);
Dan Gohman5c89b522009-09-08 15:45:00 +0000601 }
Dan Gohman9450b0e2009-09-28 00:27:48 +0000602
Andrew Trick5434c1e2011-08-26 03:06:34 +0000603 // Verify that blocks are mapped to valid loops.
604 //
605 // FIXME: With an up-to-date DFS (see LoopIterator.h) and DominatorTree, we
606 // could also verify that the blocks are still in the correct loops.
607 for (DenseMap<BasicBlock*, Loop*>::const_iterator I = LI.BBMap.begin(),
608 E = LI.BBMap.end(); I != E; ++I) {
609 assert(Loops.count(I->second) && "orphaned loop");
610 assert(I->second->contains(I->first) && "orphaned block");
611 }
Dan Gohman5c89b522009-09-08 15:45:00 +0000612}
613
Chris Lattner1b7f7dc2002-04-28 16:21:30 +0000614void LoopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerf57b8452002-04-27 06:56:12 +0000615 AU.setPreservesAll();
Devang Patel53c279b2007-06-08 00:17:13 +0000616 AU.addRequired<DominatorTree>();
Chris Lattner93193f82002-01-31 00:42:27 +0000617}
Chris Lattner791102f2009-08-23 05:17:37 +0000618
Chris Lattner45cfe542009-08-23 06:03:38 +0000619void LoopInfo::print(raw_ostream &OS, const Module*) const {
620 LI.print(OS);
Chris Lattner791102f2009-08-23 05:17:37 +0000621}
622
Andrew Trick2d31ae32011-08-10 01:59:05 +0000623//===----------------------------------------------------------------------===//
624// LoopBlocksDFS implementation
625//
626
627/// Traverse the loop blocks and store the DFS result.
628/// Useful for clients that just want the final DFS result and don't need to
629/// visit blocks during the initial traversal.
630void LoopBlocksDFS::perform(LoopInfo *LI) {
631 LoopBlocksTraversal Traversal(*this, LI);
632 for (LoopBlocksTraversal::POTIterator POI = Traversal.begin(),
633 POE = Traversal.end(); POI != POE; ++POI) ;
634}