blob: 142ebed4ed7cfcba8605c3d74a789d1d923d68b2 [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"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000018#include "llvm/ADT/DepthFirstIterator.h"
19#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner92020fa2004-04-15 15:16:02 +000020#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"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000025#include "llvm/IR/Constants.h"
26#include "llvm/IR/Instructions.h"
Pekka Jaaskelainen5d0ce792013-02-13 18:08:57 +000027#include "llvm/IR/Metadata.h"
Misha Brukman10d208d2004-01-30 17:26:24 +000028#include "llvm/Support/CFG.h"
Dan Gohman9450b0e2009-09-28 00:27:48 +000029#include "llvm/Support/CommandLine.h"
Dan Gohmandda30cd2010-01-05 21:08:02 +000030#include "llvm/Support/Debug.h"
Chris Lattner0bbe58f2001-11-26 18:41:20 +000031#include <algorithm>
Chris Lattner46758a82004-04-12 20:26:17 +000032using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000033
Andrew Trickcbf24b42012-06-20 03:42:09 +000034// Explicitly instantiate methods in LoopInfoImpl.h for IR-level Loops.
35template class llvm::LoopBase<BasicBlock, Loop>;
36template class llvm::LoopInfoBase<BasicBlock, Loop>;
37
Dan Gohman9450b0e2009-09-28 00:27:48 +000038// Always verify loopinfo if expensive checking is enabled.
39#ifdef XDEBUG
Dan Gohmanb3579832010-04-15 17:08:50 +000040static bool VerifyLoopInfo = true;
Dan Gohman9450b0e2009-09-28 00:27:48 +000041#else
Dan Gohmanb3579832010-04-15 17:08:50 +000042static bool VerifyLoopInfo = false;
Dan Gohman9450b0e2009-09-28 00:27:48 +000043#endif
44static cl::opt<bool,true>
45VerifyLoopInfoX("verify-loop-info", cl::location(VerifyLoopInfo),
46 cl::desc("Verify loop info (time consuming)"));
47
Devang Patel19974732007-05-03 01:11:54 +000048char LoopInfo::ID = 0;
Owen Anderson2ab36d32010-10-12 19:48:12 +000049INITIALIZE_PASS_BEGIN(LoopInfo, "loops", "Natural Loop Information", true, true)
50INITIALIZE_PASS_DEPENDENCY(DominatorTree)
51INITIALIZE_PASS_END(LoopInfo, "loops", "Natural Loop Information", true, true)
Chris Lattner93193f82002-01-31 00:42:27 +000052
Paul Redmondee21b6f2013-05-28 20:00:34 +000053// Loop identifier metadata name.
Craig Topper4172a8a2013-07-16 01:17:10 +000054static const char *const LoopMDName = "llvm.loop";
Paul Redmondee21b6f2013-05-28 20:00:34 +000055
Chris Lattner93193f82002-01-31 00:42:27 +000056//===----------------------------------------------------------------------===//
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 {
James Molloy67ae1352012-12-20 16:04:27 +0000220 // Return false if any loop blocks contain indirectbrs, or there are any calls
221 // to noduplicate functions.
Andrew Trickd9fc1ce2012-04-10 05:14:42 +0000222 for (Loop::block_iterator I = block_begin(), E = block_end(); I != E; ++I) {
James Molloy67ae1352012-12-20 16:04:27 +0000223 if (isa<IndirectBrInst>((*I)->getTerminator())) {
Andrew Trickd9fc1ce2012-04-10 05:14:42 +0000224 return false;
James Molloy67ae1352012-12-20 16:04:27 +0000225 } else if (const InvokeInst *II = dyn_cast<InvokeInst>((*I)->getTerminator())) {
226 if (II->hasFnAttr(Attribute::NoDuplicate))
227 return false;
228 }
229
230 for (BasicBlock::iterator BI = (*I)->begin(), BE = (*I)->end(); BI != BE; ++BI) {
231 if (const CallInst *CI = dyn_cast<CallInst>(BI)) {
232 if (CI->hasFnAttr(Attribute::NoDuplicate))
233 return false;
234 }
235 }
Andrew Trickd9fc1ce2012-04-10 05:14:42 +0000236 }
237 return true;
238}
239
Paul Redmondee21b6f2013-05-28 20:00:34 +0000240MDNode *Loop::getLoopID() const {
241 MDNode *LoopID = 0;
242 if (isLoopSimplifyForm()) {
243 LoopID = getLoopLatch()->getTerminator()->getMetadata(LoopMDName);
244 } else {
245 // Go through each predecessor of the loop header and check the
246 // terminator for the metadata.
247 BasicBlock *H = getHeader();
248 for (block_iterator I = block_begin(), IE = block_end(); I != IE; ++I) {
249 TerminatorInst *TI = (*I)->getTerminator();
250 MDNode *MD = 0;
251
252 // Check if this terminator branches to the loop header.
253 for (unsigned i = 0, ie = TI->getNumSuccessors(); i != ie; ++i) {
254 if (TI->getSuccessor(i) == H) {
255 MD = TI->getMetadata(LoopMDName);
256 break;
257 }
258 }
259 if (!MD)
260 return 0;
261
262 if (!LoopID)
263 LoopID = MD;
264 else if (MD != LoopID)
265 return 0;
266 }
267 }
268 if (!LoopID || LoopID->getNumOperands() == 0 ||
269 LoopID->getOperand(0) != LoopID)
270 return 0;
271 return LoopID;
272}
273
274void Loop::setLoopID(MDNode *LoopID) const {
275 assert(LoopID && "Loop ID should not be null");
276 assert(LoopID->getNumOperands() > 0 && "Loop ID needs at least one operand");
277 assert(LoopID->getOperand(0) == LoopID && "Loop ID should refer to itself");
278
279 if (isLoopSimplifyForm()) {
280 getLoopLatch()->getTerminator()->setMetadata(LoopMDName, LoopID);
281 return;
282 }
283
284 BasicBlock *H = getHeader();
285 for (block_iterator I = block_begin(), IE = block_end(); I != IE; ++I) {
286 TerminatorInst *TI = (*I)->getTerminator();
287 for (unsigned i = 0, ie = TI->getNumSuccessors(); i != ie; ++i) {
288 if (TI->getSuccessor(i) == H)
289 TI->setMetadata(LoopMDName, LoopID);
290 }
291 }
292}
293
Pekka Jaaskelainen5d0ce792013-02-13 18:08:57 +0000294bool Loop::isAnnotatedParallel() const {
Paul Redmondee21b6f2013-05-28 20:00:34 +0000295 MDNode *desiredLoopIdMetadata = getLoopID();
Pekka Jaaskelainen5d0ce792013-02-13 18:08:57 +0000296
297 if (!desiredLoopIdMetadata)
298 return false;
299
300 // The loop branch contains the parallel loop metadata. In order to ensure
301 // that any parallel-loop-unaware optimization pass hasn't added loop-carried
302 // dependencies (thus converted the loop back to a sequential loop), check
303 // that all the memory instructions in the loop contain parallelism metadata
304 // that point to the same unique "loop id metadata" the loop branch does.
305 for (block_iterator BB = block_begin(), BE = block_end(); BB != BE; ++BB) {
306 for (BasicBlock::iterator II = (*BB)->begin(), EE = (*BB)->end();
307 II != EE; II++) {
308
309 if (!II->mayReadOrWriteMemory())
310 continue;
311
312 if (!II->getMetadata("llvm.mem.parallel_loop_access"))
313 return false;
314
315 // The memory instruction can refer to the loop identifier metadata
316 // directly or indirectly through another list metadata (in case of
317 // nested parallel loops). The loop identifier metadata refers to
318 // itself so we can check both cases with the same routine.
319 MDNode *loopIdMD =
320 dyn_cast<MDNode>(II->getMetadata("llvm.mem.parallel_loop_access"));
321 bool loopIdMDFound = false;
322 for (unsigned i = 0, e = loopIdMD->getNumOperands(); i < e; ++i) {
323 if (loopIdMD->getOperand(i) == desiredLoopIdMetadata) {
324 loopIdMDFound = true;
325 break;
326 }
327 }
328
329 if (!loopIdMDFound)
330 return false;
331 }
332 }
333 return true;
334}
335
336
Dan Gohmanf17e9512009-11-05 19:21:41 +0000337/// hasDedicatedExits - Return true if no exit block for the loop
338/// has a predecessor that is outside the loop.
339bool Loop::hasDedicatedExits() const {
Dan Gohmaneed9e5b2009-10-20 20:41:13 +0000340 // Sort the blocks vector so that we can use binary search to do quick
341 // lookups.
342 SmallPtrSet<BasicBlock *, 16> LoopBBs(block_begin(), block_end());
Dan Gohman93773862009-07-16 16:16:23 +0000343 // Each predecessor of each exit block of a normal loop is contained
344 // within the loop.
345 SmallVector<BasicBlock *, 4> ExitBlocks;
346 getExitBlocks(ExitBlocks);
347 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
348 for (pred_iterator PI = pred_begin(ExitBlocks[i]),
349 PE = pred_end(ExitBlocks[i]); PI != PE; ++PI)
Dan Gohmaneed9e5b2009-10-20 20:41:13 +0000350 if (!LoopBBs.count(*PI))
Dan Gohman93773862009-07-16 16:16:23 +0000351 return false;
352 // All the requirements are met.
353 return true;
354}
355
Dan Gohmanf0608d82009-09-03 16:10:48 +0000356/// getUniqueExitBlocks - Return all unique successor blocks of this loop.
357/// These are the blocks _outside of the current loop_ which are branched to.
Dan Gohman050959c2009-12-11 20:05:23 +0000358/// This assumes that loop exits are in canonical form.
Dan Gohmanf0608d82009-09-03 16:10:48 +0000359///
360void
361Loop::getUniqueExitBlocks(SmallVectorImpl<BasicBlock *> &ExitBlocks) const {
Dan Gohman050959c2009-12-11 20:05:23 +0000362 assert(hasDedicatedExits() &&
363 "getUniqueExitBlocks assumes the loop has canonical form exits!");
Dan Gohman5c89b522009-09-08 15:45:00 +0000364
Dan Gohmanf0608d82009-09-03 16:10:48 +0000365 // Sort the blocks vector so that we can use binary search to do quick
366 // lookups.
367 SmallVector<BasicBlock *, 128> LoopBBs(block_begin(), block_end());
368 std::sort(LoopBBs.begin(), LoopBBs.end());
369
Dan Gohman058db922009-09-03 20:36:13 +0000370 SmallVector<BasicBlock *, 32> switchExitBlocks;
Dan Gohmanf0608d82009-09-03 16:10:48 +0000371
372 for (block_iterator BI = block_begin(), BE = block_end(); BI != BE; ++BI) {
373
374 BasicBlock *current = *BI;
375 switchExitBlocks.clear();
376
Dan Gohman63137d52010-07-23 21:25:16 +0000377 for (succ_iterator I = succ_begin(*BI), E = succ_end(*BI); I != E; ++I) {
Dan Gohmanf0608d82009-09-03 16:10:48 +0000378 // If block is inside the loop then it is not a exit block.
379 if (std::binary_search(LoopBBs.begin(), LoopBBs.end(), *I))
380 continue;
381
Dan Gohman63137d52010-07-23 21:25:16 +0000382 pred_iterator PI = pred_begin(*I);
Dan Gohmanf0608d82009-09-03 16:10:48 +0000383 BasicBlock *firstPred = *PI;
384
385 // If current basic block is this exit block's first predecessor
386 // then only insert exit block in to the output ExitBlocks vector.
387 // This ensures that same exit block is not inserted twice into
388 // ExitBlocks vector.
389 if (current != firstPred)
390 continue;
391
392 // If a terminator has more then two successors, for example SwitchInst,
393 // then it is possible that there are multiple edges from current block
394 // to one exit block.
Dan Gohman63137d52010-07-23 21:25:16 +0000395 if (std::distance(succ_begin(current), succ_end(current)) <= 2) {
Dan Gohmanf0608d82009-09-03 16:10:48 +0000396 ExitBlocks.push_back(*I);
397 continue;
398 }
399
400 // In case of multiple edges from current block to exit block, collect
401 // only one edge in ExitBlocks. Use switchExitBlocks to keep track of
402 // duplicate edges.
403 if (std::find(switchExitBlocks.begin(), switchExitBlocks.end(), *I)
404 == switchExitBlocks.end()) {
405 switchExitBlocks.push_back(*I);
406 ExitBlocks.push_back(*I);
407 }
408 }
409 }
410}
411
412/// getUniqueExitBlock - If getUniqueExitBlocks would return exactly one
413/// block, return that block. Otherwise return null.
414BasicBlock *Loop::getUniqueExitBlock() const {
415 SmallVector<BasicBlock *, 8> UniqueExitBlocks;
416 getUniqueExitBlocks(UniqueExitBlocks);
417 if (UniqueExitBlocks.size() == 1)
418 return UniqueExitBlocks[0];
419 return 0;
420}
421
Manman Ren286c4dc2012-09-12 05:06:18 +0000422#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Dan Gohmandda30cd2010-01-05 21:08:02 +0000423void Loop::dump() const {
424 print(dbgs());
425}
Manman Rencc77eec2012-09-06 19:55:56 +0000426#endif
Dan Gohmandda30cd2010-01-05 21:08:02 +0000427
Chris Lattnera59cbb22002-07-27 01:12:17 +0000428//===----------------------------------------------------------------------===//
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000429// UnloopUpdater implementation
430//
431
Benjamin Kramera67f14b2011-08-19 01:42:18 +0000432namespace {
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000433/// Find the new parent loop for all blocks within the "unloop" whose last
434/// backedges has just been removed.
435class UnloopUpdater {
436 Loop *Unloop;
437 LoopInfo *LI;
438
439 LoopBlocksDFS DFS;
440
441 // Map unloop's immediate subloops to their nearest reachable parents. Nested
442 // loops within these subloops will not change parents. However, an immediate
443 // subloop's new parent will be the nearest loop reachable from either its own
444 // exits *or* any of its nested loop's exits.
445 DenseMap<Loop*, Loop*> SubloopParents;
446
447 // Flag the presence of an irreducible backedge whose destination is a block
448 // directly contained by the original unloop.
449 bool FoundIB;
450
451public:
452 UnloopUpdater(Loop *UL, LoopInfo *LInfo) :
453 Unloop(UL), LI(LInfo), DFS(UL), FoundIB(false) {}
454
455 void updateBlockParents();
456
Andrew Trickc12d9b92011-08-11 20:27:32 +0000457 void removeBlocksFromAncestors();
458
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000459 void updateSubloopParents();
460
461protected:
462 Loop *getNearestLoop(BasicBlock *BB, Loop *BBLoop);
463};
Benjamin Kramera67f14b2011-08-19 01:42:18 +0000464} // end anonymous namespace
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000465
466/// updateBlockParents - Update the parent loop for all blocks that are directly
467/// contained within the original "unloop".
468void UnloopUpdater::updateBlockParents() {
469 if (Unloop->getNumBlocks()) {
470 // Perform a post order CFG traversal of all blocks within this loop,
471 // propagating the nearest loop from sucessors to predecessors.
472 LoopBlocksTraversal Traversal(DFS, LI);
473 for (LoopBlocksTraversal::POTIterator POI = Traversal.begin(),
474 POE = Traversal.end(); POI != POE; ++POI) {
475
476 Loop *L = LI->getLoopFor(*POI);
477 Loop *NL = getNearestLoop(*POI, L);
478
479 if (NL != L) {
480 // For reducible loops, NL is now an ancestor of Unloop.
481 assert((NL != Unloop && (!NL || NL->contains(Unloop))) &&
482 "uninitialized successor");
483 LI->changeLoopFor(*POI, NL);
484 }
485 else {
486 // Or the current block is part of a subloop, in which case its parent
487 // is unchanged.
488 assert((FoundIB || Unloop->contains(L)) && "uninitialized successor");
489 }
490 }
491 }
492 // Each irreducible loop within the unloop induces a round of iteration using
493 // the DFS result cached by Traversal.
494 bool Changed = FoundIB;
495 for (unsigned NIters = 0; Changed; ++NIters) {
496 assert(NIters < Unloop->getNumBlocks() && "runaway iterative algorithm");
497
498 // Iterate over the postorder list of blocks, propagating the nearest loop
499 // from successors to predecessors as before.
500 Changed = false;
501 for (LoopBlocksDFS::POIterator POI = DFS.beginPostorder(),
502 POE = DFS.endPostorder(); POI != POE; ++POI) {
503
504 Loop *L = LI->getLoopFor(*POI);
505 Loop *NL = getNearestLoop(*POI, L);
506 if (NL != L) {
507 assert(NL != Unloop && (!NL || NL->contains(Unloop)) &&
508 "uninitialized successor");
509 LI->changeLoopFor(*POI, NL);
510 Changed = true;
511 }
512 }
513 }
514}
515
Andrew Trickc12d9b92011-08-11 20:27:32 +0000516/// removeBlocksFromAncestors - Remove unloop's blocks from all ancestors below
517/// their new parents.
518void UnloopUpdater::removeBlocksFromAncestors() {
Andrew Trick5865a8d2011-11-18 03:42:41 +0000519 // Remove all unloop's blocks (including those in nested subloops) from
520 // ancestors below the new parent loop.
Andrew Trickc12d9b92011-08-11 20:27:32 +0000521 for (Loop::block_iterator BI = Unloop->block_begin(),
522 BE = Unloop->block_end(); BI != BE; ++BI) {
Andrew Trick5865a8d2011-11-18 03:42:41 +0000523 Loop *OuterParent = LI->getLoopFor(*BI);
524 if (Unloop->contains(OuterParent)) {
525 while (OuterParent->getParentLoop() != Unloop)
526 OuterParent = OuterParent->getParentLoop();
527 OuterParent = SubloopParents[OuterParent];
528 }
Andrew Trickc12d9b92011-08-11 20:27:32 +0000529 // Remove blocks from former Ancestors except Unloop itself which will be
530 // deleted.
Andrew Trick5865a8d2011-11-18 03:42:41 +0000531 for (Loop *OldParent = Unloop->getParentLoop(); OldParent != OuterParent;
Andrew Trickc12d9b92011-08-11 20:27:32 +0000532 OldParent = OldParent->getParentLoop()) {
533 assert(OldParent && "new loop is not an ancestor of the original");
534 OldParent->removeBlockFromLoop(*BI);
535 }
536 }
537}
538
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000539/// updateSubloopParents - Update the parent loop for all subloops directly
540/// nested within unloop.
541void UnloopUpdater::updateSubloopParents() {
542 while (!Unloop->empty()) {
Andrew Trick5c1ff1f2011-08-11 17:54:58 +0000543 Loop *Subloop = *llvm::prior(Unloop->end());
544 Unloop->removeChildLoop(llvm::prior(Unloop->end()));
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000545
546 assert(SubloopParents.count(Subloop) && "DFS failed to visit subloop");
Benjamin Kramer05d96f92012-08-22 15:37:57 +0000547 if (Loop *Parent = SubloopParents[Subloop])
548 Parent->addChildLoop(Subloop);
Andrew Trick5434c1e2011-08-26 03:06:34 +0000549 else
550 LI->addTopLevelLoop(Subloop);
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000551 }
552}
553
554/// getNearestLoop - Return the nearest parent loop among this block's
555/// successors. If a successor is a subloop header, consider its parent to be
556/// the nearest parent of the subloop's exits.
557///
558/// For subloop blocks, simply update SubloopParents and return NULL.
559Loop *UnloopUpdater::getNearestLoop(BasicBlock *BB, Loop *BBLoop) {
560
Andrew Trick5c1ff1f2011-08-11 17:54:58 +0000561 // Initially for blocks directly contained by Unloop, NearLoop == Unloop and
562 // is considered uninitialized.
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000563 Loop *NearLoop = BBLoop;
564
565 Loop *Subloop = 0;
566 if (NearLoop != Unloop && Unloop->contains(NearLoop)) {
567 Subloop = NearLoop;
568 // Find the subloop ancestor that is directly contained within Unloop.
569 while (Subloop->getParentLoop() != Unloop) {
570 Subloop = Subloop->getParentLoop();
571 assert(Subloop && "subloop is not an ancestor of the original loop");
572 }
573 // Get the current nearest parent of the Subloop exits, initially Unloop.
Benjamin Kramer05d96f92012-08-22 15:37:57 +0000574 NearLoop =
575 SubloopParents.insert(std::make_pair(Subloop, Unloop)).first->second;
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000576 }
577
578 succ_iterator I = succ_begin(BB), E = succ_end(BB);
579 if (I == E) {
580 assert(!Subloop && "subloop blocks must have a successor");
581 NearLoop = 0; // unloop blocks may now exit the function.
582 }
583 for (; I != E; ++I) {
584 if (*I == BB)
585 continue; // self loops are uninteresting
586
587 Loop *L = LI->getLoopFor(*I);
588 if (L == Unloop) {
589 // This successor has not been processed. This path must lead to an
590 // irreducible backedge.
591 assert((FoundIB || !DFS.hasPostorder(*I)) && "should have seen IB");
592 FoundIB = true;
593 }
594 if (L != Unloop && Unloop->contains(L)) {
595 // Successor is in a subloop.
596 if (Subloop)
597 continue; // Branching within subloops. Ignore it.
598
599 // BB branches from the original into a subloop header.
600 assert(L->getParentLoop() == Unloop && "cannot skip into nested loops");
601
602 // Get the current nearest parent of the Subloop's exits.
603 L = SubloopParents[L];
604 // L could be Unloop if the only exit was an irreducible backedge.
605 }
606 if (L == Unloop) {
607 continue;
608 }
609 // Handle critical edges from Unloop into a sibling loop.
610 if (L && !L->contains(Unloop)) {
611 L = L->getParentLoop();
612 }
613 // Remember the nearest parent loop among successors or subloop exits.
614 if (NearLoop == Unloop || !NearLoop || NearLoop->contains(L))
615 NearLoop = L;
616 }
617 if (Subloop) {
618 SubloopParents[Subloop] = NearLoop;
619 return BBLoop;
620 }
621 return NearLoop;
622}
623
624//===----------------------------------------------------------------------===//
Chris Lattnera59cbb22002-07-27 01:12:17 +0000625// LoopInfo implementation
626//
Chris Lattnera59cbb22002-07-27 01:12:17 +0000627bool LoopInfo::runOnFunction(Function &) {
628 releaseMemory();
Andrew Trickc9b1e252012-06-26 04:11:38 +0000629 LI.Analyze(getAnalysis<DominatorTree>().getBase());
Chris Lattnera59cbb22002-07-27 01:12:17 +0000630 return false;
631}
632
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000633/// updateUnloop - The last backedge has been removed from a loop--now the
634/// "unloop". Find a new parent for the blocks contained within unloop and
Andrew Trick5c1ff1f2011-08-11 17:54:58 +0000635/// update the loop tree. We don't necessarily have valid dominators at this
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000636/// point, but LoopInfo is still valid except for the removal of this loop.
637///
638/// Note that Unloop may now be an empty loop. Calling Loop::getHeader without
639/// checking first is illegal.
640void LoopInfo::updateUnloop(Loop *Unloop) {
641
642 // First handle the special case of no parent loop to simplify the algorithm.
643 if (!Unloop->getParentLoop()) {
644 // Since BBLoop had no parent, Unloop blocks are no longer in a loop.
645 for (Loop::block_iterator I = Unloop->block_begin(),
646 E = Unloop->block_end(); I != E; ++I) {
647
648 // Don't reparent blocks in subloops.
649 if (getLoopFor(*I) != Unloop)
650 continue;
651
652 // Blocks no longer have a parent but are still referenced by Unloop until
653 // the Unloop object is deleted.
654 LI.changeLoopFor(*I, 0);
655 }
656
657 // Remove the loop from the top-level LoopInfo object.
Duncan Sands1f6a3292011-08-12 14:54:45 +0000658 for (LoopInfo::iterator I = LI.begin();; ++I) {
659 assert(I != LI.end() && "Couldn't find loop");
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000660 if (*I == Unloop) {
661 LI.removeLoop(I);
662 break;
663 }
664 }
665
666 // Move all of the subloops to the top-level.
667 while (!Unloop->empty())
Andrew Trick5c1ff1f2011-08-11 17:54:58 +0000668 LI.addTopLevelLoop(Unloop->removeChildLoop(llvm::prior(Unloop->end())));
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000669
670 return;
671 }
672
673 // Update the parent loop for all blocks within the loop. Blocks within
674 // subloops will not change parents.
675 UnloopUpdater Updater(Unloop, this);
676 Updater.updateBlockParents();
677
Andrew Trickc12d9b92011-08-11 20:27:32 +0000678 // Remove blocks from former ancestor loops.
679 Updater.removeBlocksFromAncestors();
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000680
681 // Add direct subloops as children in their new parent loop.
682 Updater.updateSubloopParents();
683
684 // Remove unloop from its parent loop.
685 Loop *ParentLoop = Unloop->getParentLoop();
Duncan Sands1f6a3292011-08-12 14:54:45 +0000686 for (Loop::iterator I = ParentLoop->begin();; ++I) {
687 assert(I != ParentLoop->end() && "Couldn't find loop");
Andrew Trickfb62b8d2011-08-10 23:22:57 +0000688 if (*I == Unloop) {
689 ParentLoop->removeChildLoop(I);
690 break;
691 }
692 }
693}
694
Dan Gohman5c89b522009-09-08 15:45:00 +0000695void LoopInfo::verifyAnalysis() const {
Dan Gohman9450b0e2009-09-28 00:27:48 +0000696 // LoopInfo is a FunctionPass, but verifying every loop in the function
697 // each time verifyAnalysis is called is very expensive. The
698 // -verify-loop-info option can enable this. In order to perform some
699 // checking by default, LoopPass has been taught to call verifyLoop
700 // manually during loop pass sequences.
701
702 if (!VerifyLoopInfo) return;
703
Andrew Trick5434c1e2011-08-26 03:06:34 +0000704 DenseSet<const Loop*> Loops;
Dan Gohman5c89b522009-09-08 15:45:00 +0000705 for (iterator I = begin(), E = end(); I != E; ++I) {
706 assert(!(*I)->getParentLoop() && "Top-level loop has a parent!");
Andrew Trick5434c1e2011-08-26 03:06:34 +0000707 (*I)->verifyLoopNest(&Loops);
Dan Gohman5c89b522009-09-08 15:45:00 +0000708 }
Dan Gohman9450b0e2009-09-28 00:27:48 +0000709
Andrew Trick5434c1e2011-08-26 03:06:34 +0000710 // Verify that blocks are mapped to valid loops.
Andrew Trick5434c1e2011-08-26 03:06:34 +0000711 for (DenseMap<BasicBlock*, Loop*>::const_iterator I = LI.BBMap.begin(),
712 E = LI.BBMap.end(); I != E; ++I) {
713 assert(Loops.count(I->second) && "orphaned loop");
714 assert(I->second->contains(I->first) && "orphaned block");
715 }
Dan Gohman5c89b522009-09-08 15:45:00 +0000716}
717
Chris Lattner1b7f7dc2002-04-28 16:21:30 +0000718void LoopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerf57b8452002-04-27 06:56:12 +0000719 AU.setPreservesAll();
Devang Patel53c279b2007-06-08 00:17:13 +0000720 AU.addRequired<DominatorTree>();
Chris Lattner93193f82002-01-31 00:42:27 +0000721}
Chris Lattner791102f2009-08-23 05:17:37 +0000722
Chris Lattner45cfe542009-08-23 06:03:38 +0000723void LoopInfo::print(raw_ostream &OS, const Module*) const {
724 LI.print(OS);
Chris Lattner791102f2009-08-23 05:17:37 +0000725}
726
Andrew Trick2d31ae32011-08-10 01:59:05 +0000727//===----------------------------------------------------------------------===//
728// LoopBlocksDFS implementation
729//
730
731/// Traverse the loop blocks and store the DFS result.
732/// Useful for clients that just want the final DFS result and don't need to
733/// visit blocks during the initial traversal.
734void LoopBlocksDFS::perform(LoopInfo *LI) {
735 LoopBlocksTraversal Traversal(*this, LI);
736 for (LoopBlocksTraversal::POTIterator POI = Traversal.begin(),
737 POE = Traversal.end(); POI != POE; ++POI) ;
738}