blob: d4e7b54f224a7b09925c63700f1c7ad5cd1fa9ca [file] [log] [blame]
Chris Lattner44d2c352003-10-13 03:32:08 +00001//===- LoopInfo.cpp - Natural Loop Calculator -----------------------------===//
Misha Brukman01808ca2005-04-21 21:13:18 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-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 Brukman01808ca2005-04-21 21:13:18 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner6de99422001-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 Brukman81804b42004-01-30 17:26:24 +000017#include "llvm/Analysis/LoopInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000018#include "llvm/ADT/DepthFirstIterator.h"
19#include "llvm/ADT/SmallPtrSet.h"
Andrew Trickcda51d42012-06-20 03:42:09 +000020#include "llvm/Analysis/LoopInfoImpl.h"
Andrew Trick78b40c32011-08-10 01:59:05 +000021#include "llvm/Analysis/LoopIterator.h"
Dan Gohman75d7d5e2011-12-14 23:49:11 +000022#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000023#include "llvm/IR/CFG.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000024#include "llvm/IR/Constants.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000025#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000026#include "llvm/IR/Instructions.h"
Pekka Jaaskelainen0d237252013-02-13 18:08:57 +000027#include "llvm/IR/Metadata.h"
Dan Gohman4dbb3012009-09-28 00:27:48 +000028#include "llvm/Support/CommandLine.h"
Dan Gohmanc3f21372010-01-05 21:08:02 +000029#include "llvm/Support/Debug.h"
Chris Lattner6de99422001-11-26 18:41:20 +000030#include <algorithm>
Chris Lattner55b7ef52004-04-12 20:26:17 +000031using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000032
Andrew Trickcda51d42012-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 Gohman4dbb3012009-09-28 00:27:48 +000037// Always verify loopinfo if expensive checking is enabled.
38#ifdef XDEBUG
Dan Gohmanb29cda92010-04-15 17:08:50 +000039static bool VerifyLoopInfo = true;
Dan Gohman4dbb3012009-09-28 00:27:48 +000040#else
Dan Gohmanb29cda92010-04-15 17:08:50 +000041static bool VerifyLoopInfo = false;
Dan Gohman4dbb3012009-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
Devang Patel8c78a0b2007-05-03 01:11:54 +000047char LoopInfo::ID = 0;
Owen Anderson8ac477f2010-10-12 19:48:12 +000048INITIALIZE_PASS_BEGIN(LoopInfo, "loops", "Natural Loop Information", true, true)
Chandler Carruth73523022014-01-13 13:07:17 +000049INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Owen Anderson8ac477f2010-10-12 19:48:12 +000050INITIALIZE_PASS_END(LoopInfo, "loops", "Natural Loop Information", true, true)
Chris Lattnerccf571a2002-01-31 00:42:27 +000051
Paul Redmond5fdf8362013-05-28 20:00:34 +000052// Loop identifier metadata name.
Craig Topperd3a34f82013-07-16 01:17:10 +000053static const char *const LoopMDName = "llvm.loop";
Paul Redmond5fdf8362013-05-28 20:00:34 +000054
Chris Lattnerccf571a2002-01-31 00:42:27 +000055//===----------------------------------------------------------------------===//
Chris Lattner78dd56f2002-04-28 16:21:30 +000056// Loop implementation
Chris Lattnerccf571a2002-01-31 00:42:27 +000057//
Misha Brukman3845be22002-10-11 05:31:10 +000058
Dan Gohman80a99422009-07-13 22:02:44 +000059/// isLoopInvariant - Return true if the specified value is loop invariant
60///
61bool Loop::isLoopInvariant(Value *V) const {
62 if (Instruction *I = dyn_cast<Instruction>(V))
Chris Lattnerda24b9a2010-09-06 01:05:37 +000063 return !contains(I);
Dan Gohman80a99422009-07-13 22:02:44 +000064 return true; // All non-instructions are loop invariant
65}
66
Chris Lattnerda24b9a2010-09-06 01:05:37 +000067/// hasLoopInvariantOperands - Return true if all the operands of the
Andrew Trickf898cbd2011-08-03 23:45:50 +000068/// specified instruction are loop invariant.
Chris Lattnerda24b9a2010-09-06 01:05:37 +000069bool Loop::hasLoopInvariantOperands(Instruction *I) const {
70 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
71 if (!isLoopInvariant(I->getOperand(i)))
72 return false;
Andrew Trickf898cbd2011-08-03 23:45:50 +000073
Chris Lattnerda24b9a2010-09-06 01:05:37 +000074 return true;
Dan Gohman6f6d8642009-07-14 01:06:29 +000075}
76
77/// makeLoopInvariant - If the given value is an instruciton inside of the
78/// loop and it can be hoisted, do so to make it trivially loop-invariant.
79/// Return true if the value after any hoisting is loop invariant. This
80/// function can be used as a slightly more aggressive replacement for
81/// isLoopInvariant.
82///
83/// If InsertPt is specified, it is the point to hoist instructions to.
84/// If null, the terminator of the loop preheader is used.
85///
Dan Gohmanc43e4792009-07-15 01:25:43 +000086bool Loop::makeLoopInvariant(Value *V, bool &Changed,
87 Instruction *InsertPt) const {
Dan Gohman6f6d8642009-07-14 01:06:29 +000088 if (Instruction *I = dyn_cast<Instruction>(V))
Dan Gohmanc43e4792009-07-15 01:25:43 +000089 return makeLoopInvariant(I, Changed, InsertPt);
Dan Gohman6f6d8642009-07-14 01:06:29 +000090 return true; // All non-instructions are loop-invariant.
91}
92
93/// makeLoopInvariant - If the given instruction is inside of the
94/// loop and it can be hoisted, do so to make it trivially loop-invariant.
95/// Return true if the instruction after any hoisting is loop invariant. This
96/// function can be used as a slightly more aggressive replacement for
97/// isLoopInvariant.
98///
99/// If InsertPt is specified, it is the point to hoist instructions to.
100/// If null, the terminator of the loop preheader is used.
101///
Dan Gohmanc43e4792009-07-15 01:25:43 +0000102bool Loop::makeLoopInvariant(Instruction *I, bool &Changed,
103 Instruction *InsertPt) const {
Dan Gohman6f6d8642009-07-14 01:06:29 +0000104 // Test if the value is already loop-invariant.
105 if (isLoopInvariant(I))
106 return true;
Dan Gohman75d7d5e2011-12-14 23:49:11 +0000107 if (!isSafeToSpeculativelyExecute(I))
Dan Gohman6f6d8642009-07-14 01:06:29 +0000108 return false;
Eli Friedmanb8f6a4f2009-07-17 04:28:42 +0000109 if (I->mayReadFromMemory())
Dan Gohman6f6d8642009-07-14 01:06:29 +0000110 return false;
Bill Wendlinga9ee09f2011-08-17 20:36:44 +0000111 // The landingpad instruction is immobile.
112 if (isa<LandingPadInst>(I))
113 return false;
Dan Gohman6f6d8642009-07-14 01:06:29 +0000114 // Determine the insertion point, unless one was given.
115 if (!InsertPt) {
116 BasicBlock *Preheader = getLoopPreheader();
117 // Without a preheader, hoisting is not feasible.
118 if (!Preheader)
119 return false;
120 InsertPt = Preheader->getTerminator();
121 }
122 // Don't hoist instructions with loop-variant operands.
123 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
Dan Gohmanc43e4792009-07-15 01:25:43 +0000124 if (!makeLoopInvariant(I->getOperand(i), Changed, InsertPt))
Dan Gohman6f6d8642009-07-14 01:06:29 +0000125 return false;
Andrew Trickf898cbd2011-08-03 23:45:50 +0000126
Dan Gohman6f6d8642009-07-14 01:06:29 +0000127 // Hoist.
128 I->moveBefore(InsertPt);
Dan Gohmanc43e4792009-07-15 01:25:43 +0000129 Changed = true;
Dan Gohman6f6d8642009-07-14 01:06:29 +0000130 return true;
131}
132
Dan Gohman80a99422009-07-13 22:02:44 +0000133/// getCanonicalInductionVariable - Check to see if the loop has a canonical
134/// induction variable: an integer recurrence that starts at 0 and increments
135/// by one each time through the loop. If so, return the phi node that
136/// corresponds to it.
137///
138/// The IndVarSimplify pass transforms loops to have a canonical induction
139/// variable.
140///
141PHINode *Loop::getCanonicalInductionVariable() const {
142 BasicBlock *H = getHeader();
143
144 BasicBlock *Incoming = 0, *Backedge = 0;
Dan Gohmanacafc612010-07-23 21:25:16 +0000145 pred_iterator PI = pred_begin(H);
146 assert(PI != pred_end(H) &&
Dan Gohman80a99422009-07-13 22:02:44 +0000147 "Loop must have at least one backedge!");
148 Backedge = *PI++;
Dan Gohmanacafc612010-07-23 21:25:16 +0000149 if (PI == pred_end(H)) return 0; // dead loop
Dan Gohman80a99422009-07-13 22:02:44 +0000150 Incoming = *PI++;
Dan Gohmanacafc612010-07-23 21:25:16 +0000151 if (PI != pred_end(H)) return 0; // multiple backedges?
Dan Gohman80a99422009-07-13 22:02:44 +0000152
153 if (contains(Incoming)) {
154 if (contains(Backedge))
155 return 0;
156 std::swap(Incoming, Backedge);
157 } else if (!contains(Backedge))
158 return 0;
159
160 // Loop over all of the PHI nodes, looking for a canonical indvar.
161 for (BasicBlock::iterator I = H->begin(); isa<PHINode>(I); ++I) {
162 PHINode *PN = cast<PHINode>(I);
163 if (ConstantInt *CI =
164 dyn_cast<ConstantInt>(PN->getIncomingValueForBlock(Incoming)))
165 if (CI->isNullValue())
166 if (Instruction *Inc =
167 dyn_cast<Instruction>(PN->getIncomingValueForBlock(Backedge)))
168 if (Inc->getOpcode() == Instruction::Add &&
169 Inc->getOperand(0) == PN)
170 if (ConstantInt *CI = dyn_cast<ConstantInt>(Inc->getOperand(1)))
171 if (CI->equalsInt(1))
172 return PN;
173 }
174 return 0;
175}
176
Dan Gohman80a99422009-07-13 22:02:44 +0000177/// isLCSSAForm - Return true if the Loop is in LCSSA form
Dan Gohman2734ebd2010-03-10 19:38:49 +0000178bool Loop::isLCSSAForm(DominatorTree &DT) const {
Dan Gohman80a99422009-07-13 22:02:44 +0000179 for (block_iterator BI = block_begin(), E = block_end(); BI != E; ++BI) {
Dan Gohman5196e412009-11-09 18:19:43 +0000180 BasicBlock *BB = *BI;
181 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;++I)
Chandler Carruthcdf47882014-03-09 03:16:01 +0000182 for (Use &U : I->uses()) {
183 Instruction *UI = cast<Instruction>(U.getUser());
184 BasicBlock *UserBB = UI->getParent();
185 if (PHINode *P = dyn_cast<PHINode>(UI))
186 UserBB = P->getIncomingBlock(U);
Dan Gohman80a99422009-07-13 22:02:44 +0000187
Dan Gohman93452ce2010-03-09 01:53:33 +0000188 // Check the current block, as a fast-path, before checking whether
189 // the use is anywhere in the loop. Most values are used in the same
190 // block they are defined in. Also, blocks not reachable from the
191 // entry are special; uses in them don't need to go through PHIs.
192 if (UserBB != BB &&
Wan Xiaofeibe640b22013-10-26 03:08:02 +0000193 !contains(UserBB) &&
Dan Gohman2734ebd2010-03-10 19:38:49 +0000194 DT.isReachableFromEntry(UserBB))
Dan Gohman80a99422009-07-13 22:02:44 +0000195 return false;
196 }
197 }
198
199 return true;
200}
Dan Gohman1511f702009-07-16 16:16:23 +0000201
202/// isLoopSimplifyForm - Return true if the Loop is in the form that
203/// the LoopSimplify form transforms loops to, which is sometimes called
204/// normal form.
205bool Loop::isLoopSimplifyForm() const {
Dan Gohmane3a17062009-11-05 19:21:41 +0000206 // Normal-form loops have a preheader, a single backedge, and all of their
207 // exits have all their predecessors inside the loop.
208 return getLoopPreheader() && getLoopLatch() && hasDedicatedExits();
209}
210
Andrew Trick4442bfe2012-04-10 05:14:42 +0000211/// isSafeToClone - Return true if the loop body is safe to clone in practice.
212/// Routines that reform the loop CFG and split edges often fail on indirectbr.
213bool Loop::isSafeToClone() const {
James Molloy4f6fb952012-12-20 16:04:27 +0000214 // Return false if any loop blocks contain indirectbrs, or there are any calls
215 // to noduplicate functions.
Andrew Trick4442bfe2012-04-10 05:14:42 +0000216 for (Loop::block_iterator I = block_begin(), E = block_end(); I != E; ++I) {
Jakub Staszak9dca4b32013-11-13 20:18:38 +0000217 if (isa<IndirectBrInst>((*I)->getTerminator()))
Andrew Trick4442bfe2012-04-10 05:14:42 +0000218 return false;
Jakub Staszak9dca4b32013-11-13 20:18:38 +0000219
220 if (const InvokeInst *II = dyn_cast<InvokeInst>((*I)->getTerminator()))
James Molloy4f6fb952012-12-20 16:04:27 +0000221 if (II->hasFnAttr(Attribute::NoDuplicate))
222 return false;
James Molloy4f6fb952012-12-20 16:04:27 +0000223
224 for (BasicBlock::iterator BI = (*I)->begin(), BE = (*I)->end(); BI != BE; ++BI) {
225 if (const CallInst *CI = dyn_cast<CallInst>(BI)) {
226 if (CI->hasFnAttr(Attribute::NoDuplicate))
227 return false;
228 }
229 }
Andrew Trick4442bfe2012-04-10 05:14:42 +0000230 }
231 return true;
232}
233
Paul Redmond5fdf8362013-05-28 20:00:34 +0000234MDNode *Loop::getLoopID() const {
235 MDNode *LoopID = 0;
236 if (isLoopSimplifyForm()) {
237 LoopID = getLoopLatch()->getTerminator()->getMetadata(LoopMDName);
238 } else {
239 // Go through each predecessor of the loop header and check the
240 // terminator for the metadata.
241 BasicBlock *H = getHeader();
242 for (block_iterator I = block_begin(), IE = block_end(); I != IE; ++I) {
243 TerminatorInst *TI = (*I)->getTerminator();
244 MDNode *MD = 0;
245
246 // Check if this terminator branches to the loop header.
247 for (unsigned i = 0, ie = TI->getNumSuccessors(); i != ie; ++i) {
248 if (TI->getSuccessor(i) == H) {
249 MD = TI->getMetadata(LoopMDName);
250 break;
251 }
252 }
253 if (!MD)
254 return 0;
255
256 if (!LoopID)
257 LoopID = MD;
258 else if (MD != LoopID)
259 return 0;
260 }
261 }
262 if (!LoopID || LoopID->getNumOperands() == 0 ||
263 LoopID->getOperand(0) != LoopID)
264 return 0;
265 return LoopID;
266}
267
268void Loop::setLoopID(MDNode *LoopID) const {
269 assert(LoopID && "Loop ID should not be null");
270 assert(LoopID->getNumOperands() > 0 && "Loop ID needs at least one operand");
271 assert(LoopID->getOperand(0) == LoopID && "Loop ID should refer to itself");
272
273 if (isLoopSimplifyForm()) {
274 getLoopLatch()->getTerminator()->setMetadata(LoopMDName, LoopID);
275 return;
276 }
277
278 BasicBlock *H = getHeader();
279 for (block_iterator I = block_begin(), IE = block_end(); I != IE; ++I) {
280 TerminatorInst *TI = (*I)->getTerminator();
281 for (unsigned i = 0, ie = TI->getNumSuccessors(); i != ie; ++i) {
282 if (TI->getSuccessor(i) == H)
283 TI->setMetadata(LoopMDName, LoopID);
284 }
285 }
286}
287
Pekka Jaaskelainen0d237252013-02-13 18:08:57 +0000288bool Loop::isAnnotatedParallel() const {
Paul Redmond5fdf8362013-05-28 20:00:34 +0000289 MDNode *desiredLoopIdMetadata = getLoopID();
Pekka Jaaskelainen0d237252013-02-13 18:08:57 +0000290
291 if (!desiredLoopIdMetadata)
292 return false;
293
294 // The loop branch contains the parallel loop metadata. In order to ensure
295 // that any parallel-loop-unaware optimization pass hasn't added loop-carried
296 // dependencies (thus converted the loop back to a sequential loop), check
297 // that all the memory instructions in the loop contain parallelism metadata
298 // that point to the same unique "loop id metadata" the loop branch does.
299 for (block_iterator BB = block_begin(), BE = block_end(); BB != BE; ++BB) {
300 for (BasicBlock::iterator II = (*BB)->begin(), EE = (*BB)->end();
301 II != EE; II++) {
302
303 if (!II->mayReadOrWriteMemory())
304 continue;
305
Pekka Jaaskelainen0d237252013-02-13 18:08:57 +0000306 // The memory instruction can refer to the loop identifier metadata
307 // directly or indirectly through another list metadata (in case of
308 // nested parallel loops). The loop identifier metadata refers to
309 // itself so we can check both cases with the same routine.
Jakub Staszak9dca4b32013-11-13 20:18:38 +0000310 MDNode *loopIdMD = II->getMetadata("llvm.mem.parallel_loop_access");
311
312 if (!loopIdMD)
313 return false;
314
Pekka Jaaskelainen0d237252013-02-13 18:08:57 +0000315 bool loopIdMDFound = false;
316 for (unsigned i = 0, e = loopIdMD->getNumOperands(); i < e; ++i) {
317 if (loopIdMD->getOperand(i) == desiredLoopIdMetadata) {
318 loopIdMDFound = true;
319 break;
320 }
321 }
322
323 if (!loopIdMDFound)
324 return false;
325 }
326 }
327 return true;
328}
329
330
Dan Gohmane3a17062009-11-05 19:21:41 +0000331/// hasDedicatedExits - Return true if no exit block for the loop
332/// has a predecessor that is outside the loop.
333bool Loop::hasDedicatedExits() const {
Dan Gohman1511f702009-07-16 16:16:23 +0000334 // Each predecessor of each exit block of a normal loop is contained
335 // within the loop.
336 SmallVector<BasicBlock *, 4> ExitBlocks;
337 getExitBlocks(ExitBlocks);
338 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
339 for (pred_iterator PI = pred_begin(ExitBlocks[i]),
340 PE = pred_end(ExitBlocks[i]); PI != PE; ++PI)
Wan Xiaofeibe640b22013-10-26 03:08:02 +0000341 if (!contains(*PI))
Dan Gohman1511f702009-07-16 16:16:23 +0000342 return false;
343 // All the requirements are met.
344 return true;
345}
346
Dan Gohman3a0ce3e2009-09-03 16:10:48 +0000347/// getUniqueExitBlocks - Return all unique successor blocks of this loop.
348/// These are the blocks _outside of the current loop_ which are branched to.
Dan Gohman84ba0392009-12-11 20:05:23 +0000349/// This assumes that loop exits are in canonical form.
Dan Gohman3a0ce3e2009-09-03 16:10:48 +0000350///
351void
352Loop::getUniqueExitBlocks(SmallVectorImpl<BasicBlock *> &ExitBlocks) const {
Dan Gohman84ba0392009-12-11 20:05:23 +0000353 assert(hasDedicatedExits() &&
354 "getUniqueExitBlocks assumes the loop has canonical form exits!");
Dan Gohman3ddbc242009-09-08 15:45:00 +0000355
Dan Gohmaned8f3202009-09-03 20:36:13 +0000356 SmallVector<BasicBlock *, 32> switchExitBlocks;
Dan Gohman3a0ce3e2009-09-03 16:10:48 +0000357
358 for (block_iterator BI = block_begin(), BE = block_end(); BI != BE; ++BI) {
359
360 BasicBlock *current = *BI;
361 switchExitBlocks.clear();
362
Dan Gohmanacafc612010-07-23 21:25:16 +0000363 for (succ_iterator I = succ_begin(*BI), E = succ_end(*BI); I != E; ++I) {
Dan Gohman3a0ce3e2009-09-03 16:10:48 +0000364 // If block is inside the loop then it is not a exit block.
Wan Xiaofeibe640b22013-10-26 03:08:02 +0000365 if (contains(*I))
Dan Gohman3a0ce3e2009-09-03 16:10:48 +0000366 continue;
367
Dan Gohmanacafc612010-07-23 21:25:16 +0000368 pred_iterator PI = pred_begin(*I);
Dan Gohman3a0ce3e2009-09-03 16:10:48 +0000369 BasicBlock *firstPred = *PI;
370
371 // If current basic block is this exit block's first predecessor
372 // then only insert exit block in to the output ExitBlocks vector.
373 // This ensures that same exit block is not inserted twice into
374 // ExitBlocks vector.
375 if (current != firstPred)
376 continue;
377
378 // If a terminator has more then two successors, for example SwitchInst,
379 // then it is possible that there are multiple edges from current block
380 // to one exit block.
Dan Gohmanacafc612010-07-23 21:25:16 +0000381 if (std::distance(succ_begin(current), succ_end(current)) <= 2) {
Dan Gohman3a0ce3e2009-09-03 16:10:48 +0000382 ExitBlocks.push_back(*I);
383 continue;
384 }
385
386 // In case of multiple edges from current block to exit block, collect
387 // only one edge in ExitBlocks. Use switchExitBlocks to keep track of
388 // duplicate edges.
389 if (std::find(switchExitBlocks.begin(), switchExitBlocks.end(), *I)
390 == switchExitBlocks.end()) {
391 switchExitBlocks.push_back(*I);
392 ExitBlocks.push_back(*I);
393 }
394 }
395 }
396}
397
398/// getUniqueExitBlock - If getUniqueExitBlocks would return exactly one
399/// block, return that block. Otherwise return null.
400BasicBlock *Loop::getUniqueExitBlock() const {
401 SmallVector<BasicBlock *, 8> UniqueExitBlocks;
402 getUniqueExitBlocks(UniqueExitBlocks);
403 if (UniqueExitBlocks.size() == 1)
404 return UniqueExitBlocks[0];
405 return 0;
406}
407
Manman Ren49d684e2012-09-12 05:06:18 +0000408#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Dan Gohmanc3f21372010-01-05 21:08:02 +0000409void Loop::dump() const {
410 print(dbgs());
411}
Manman Renc3366cc2012-09-06 19:55:56 +0000412#endif
Dan Gohmanc3f21372010-01-05 21:08:02 +0000413
Chris Lattner26750072002-07-27 01:12:17 +0000414//===----------------------------------------------------------------------===//
Andrew Trickd3530b92011-08-10 23:22:57 +0000415// UnloopUpdater implementation
416//
417
Benjamin Kramer4938edb2011-08-19 01:42:18 +0000418namespace {
Andrew Trickd3530b92011-08-10 23:22:57 +0000419/// Find the new parent loop for all blocks within the "unloop" whose last
420/// backedges has just been removed.
421class UnloopUpdater {
422 Loop *Unloop;
423 LoopInfo *LI;
424
425 LoopBlocksDFS DFS;
426
427 // Map unloop's immediate subloops to their nearest reachable parents. Nested
428 // loops within these subloops will not change parents. However, an immediate
429 // subloop's new parent will be the nearest loop reachable from either its own
430 // exits *or* any of its nested loop's exits.
431 DenseMap<Loop*, Loop*> SubloopParents;
432
433 // Flag the presence of an irreducible backedge whose destination is a block
434 // directly contained by the original unloop.
435 bool FoundIB;
436
437public:
438 UnloopUpdater(Loop *UL, LoopInfo *LInfo) :
439 Unloop(UL), LI(LInfo), DFS(UL), FoundIB(false) {}
440
441 void updateBlockParents();
442
Andrew Trickc12c30a2011-08-11 20:27:32 +0000443 void removeBlocksFromAncestors();
444
Andrew Trickd3530b92011-08-10 23:22:57 +0000445 void updateSubloopParents();
446
447protected:
448 Loop *getNearestLoop(BasicBlock *BB, Loop *BBLoop);
449};
Benjamin Kramer4938edb2011-08-19 01:42:18 +0000450} // end anonymous namespace
Andrew Trickd3530b92011-08-10 23:22:57 +0000451
452/// updateBlockParents - Update the parent loop for all blocks that are directly
453/// contained within the original "unloop".
454void UnloopUpdater::updateBlockParents() {
455 if (Unloop->getNumBlocks()) {
456 // Perform a post order CFG traversal of all blocks within this loop,
457 // propagating the nearest loop from sucessors to predecessors.
458 LoopBlocksTraversal Traversal(DFS, LI);
459 for (LoopBlocksTraversal::POTIterator POI = Traversal.begin(),
460 POE = Traversal.end(); POI != POE; ++POI) {
461
462 Loop *L = LI->getLoopFor(*POI);
463 Loop *NL = getNearestLoop(*POI, L);
464
465 if (NL != L) {
466 // For reducible loops, NL is now an ancestor of Unloop.
467 assert((NL != Unloop && (!NL || NL->contains(Unloop))) &&
468 "uninitialized successor");
469 LI->changeLoopFor(*POI, NL);
470 }
471 else {
472 // Or the current block is part of a subloop, in which case its parent
473 // is unchanged.
474 assert((FoundIB || Unloop->contains(L)) && "uninitialized successor");
475 }
476 }
477 }
478 // Each irreducible loop within the unloop induces a round of iteration using
479 // the DFS result cached by Traversal.
480 bool Changed = FoundIB;
481 for (unsigned NIters = 0; Changed; ++NIters) {
482 assert(NIters < Unloop->getNumBlocks() && "runaway iterative algorithm");
483
484 // Iterate over the postorder list of blocks, propagating the nearest loop
485 // from successors to predecessors as before.
486 Changed = false;
487 for (LoopBlocksDFS::POIterator POI = DFS.beginPostorder(),
488 POE = DFS.endPostorder(); POI != POE; ++POI) {
489
490 Loop *L = LI->getLoopFor(*POI);
491 Loop *NL = getNearestLoop(*POI, L);
492 if (NL != L) {
493 assert(NL != Unloop && (!NL || NL->contains(Unloop)) &&
494 "uninitialized successor");
495 LI->changeLoopFor(*POI, NL);
496 Changed = true;
497 }
498 }
499 }
500}
501
Andrew Trickc12c30a2011-08-11 20:27:32 +0000502/// removeBlocksFromAncestors - Remove unloop's blocks from all ancestors below
503/// their new parents.
504void UnloopUpdater::removeBlocksFromAncestors() {
Andrew Trick6b4d5782011-11-18 03:42:41 +0000505 // Remove all unloop's blocks (including those in nested subloops) from
506 // ancestors below the new parent loop.
Andrew Trickc12c30a2011-08-11 20:27:32 +0000507 for (Loop::block_iterator BI = Unloop->block_begin(),
508 BE = Unloop->block_end(); BI != BE; ++BI) {
Andrew Trick6b4d5782011-11-18 03:42:41 +0000509 Loop *OuterParent = LI->getLoopFor(*BI);
510 if (Unloop->contains(OuterParent)) {
511 while (OuterParent->getParentLoop() != Unloop)
512 OuterParent = OuterParent->getParentLoop();
513 OuterParent = SubloopParents[OuterParent];
514 }
Andrew Trickc12c30a2011-08-11 20:27:32 +0000515 // Remove blocks from former Ancestors except Unloop itself which will be
516 // deleted.
Andrew Trick6b4d5782011-11-18 03:42:41 +0000517 for (Loop *OldParent = Unloop->getParentLoop(); OldParent != OuterParent;
Andrew Trickc12c30a2011-08-11 20:27:32 +0000518 OldParent = OldParent->getParentLoop()) {
519 assert(OldParent && "new loop is not an ancestor of the original");
520 OldParent->removeBlockFromLoop(*BI);
521 }
522 }
523}
524
Andrew Trickd3530b92011-08-10 23:22:57 +0000525/// updateSubloopParents - Update the parent loop for all subloops directly
526/// nested within unloop.
527void UnloopUpdater::updateSubloopParents() {
528 while (!Unloop->empty()) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000529 Loop *Subloop = *std::prev(Unloop->end());
530 Unloop->removeChildLoop(std::prev(Unloop->end()));
Andrew Trickd3530b92011-08-10 23:22:57 +0000531
532 assert(SubloopParents.count(Subloop) && "DFS failed to visit subloop");
Benjamin Kramerf29db272012-08-22 15:37:57 +0000533 if (Loop *Parent = SubloopParents[Subloop])
534 Parent->addChildLoop(Subloop);
Andrew Trick147d9cd2011-08-26 03:06:34 +0000535 else
536 LI->addTopLevelLoop(Subloop);
Andrew Trickd3530b92011-08-10 23:22:57 +0000537 }
538}
539
540/// getNearestLoop - Return the nearest parent loop among this block's
541/// successors. If a successor is a subloop header, consider its parent to be
542/// the nearest parent of the subloop's exits.
543///
544/// For subloop blocks, simply update SubloopParents and return NULL.
545Loop *UnloopUpdater::getNearestLoop(BasicBlock *BB, Loop *BBLoop) {
546
Andrew Trick266ab102011-08-11 17:54:58 +0000547 // Initially for blocks directly contained by Unloop, NearLoop == Unloop and
548 // is considered uninitialized.
Andrew Trickd3530b92011-08-10 23:22:57 +0000549 Loop *NearLoop = BBLoop;
550
551 Loop *Subloop = 0;
552 if (NearLoop != Unloop && Unloop->contains(NearLoop)) {
553 Subloop = NearLoop;
554 // Find the subloop ancestor that is directly contained within Unloop.
555 while (Subloop->getParentLoop() != Unloop) {
556 Subloop = Subloop->getParentLoop();
557 assert(Subloop && "subloop is not an ancestor of the original loop");
558 }
559 // Get the current nearest parent of the Subloop exits, initially Unloop.
Benjamin Kramerf29db272012-08-22 15:37:57 +0000560 NearLoop =
561 SubloopParents.insert(std::make_pair(Subloop, Unloop)).first->second;
Andrew Trickd3530b92011-08-10 23:22:57 +0000562 }
563
564 succ_iterator I = succ_begin(BB), E = succ_end(BB);
565 if (I == E) {
566 assert(!Subloop && "subloop blocks must have a successor");
567 NearLoop = 0; // unloop blocks may now exit the function.
568 }
569 for (; I != E; ++I) {
570 if (*I == BB)
571 continue; // self loops are uninteresting
572
573 Loop *L = LI->getLoopFor(*I);
574 if (L == Unloop) {
575 // This successor has not been processed. This path must lead to an
576 // irreducible backedge.
577 assert((FoundIB || !DFS.hasPostorder(*I)) && "should have seen IB");
578 FoundIB = true;
579 }
580 if (L != Unloop && Unloop->contains(L)) {
581 // Successor is in a subloop.
582 if (Subloop)
583 continue; // Branching within subloops. Ignore it.
584
585 // BB branches from the original into a subloop header.
586 assert(L->getParentLoop() == Unloop && "cannot skip into nested loops");
587
588 // Get the current nearest parent of the Subloop's exits.
589 L = SubloopParents[L];
590 // L could be Unloop if the only exit was an irreducible backedge.
591 }
592 if (L == Unloop) {
593 continue;
594 }
595 // Handle critical edges from Unloop into a sibling loop.
596 if (L && !L->contains(Unloop)) {
597 L = L->getParentLoop();
598 }
599 // Remember the nearest parent loop among successors or subloop exits.
600 if (NearLoop == Unloop || !NearLoop || NearLoop->contains(L))
601 NearLoop = L;
602 }
603 if (Subloop) {
604 SubloopParents[Subloop] = NearLoop;
605 return BBLoop;
606 }
607 return NearLoop;
608}
609
610//===----------------------------------------------------------------------===//
Chris Lattner26750072002-07-27 01:12:17 +0000611// LoopInfo implementation
612//
Chris Lattner26750072002-07-27 01:12:17 +0000613bool LoopInfo::runOnFunction(Function &) {
614 releaseMemory();
Chandler Carruth73523022014-01-13 13:07:17 +0000615 LI.Analyze(getAnalysis<DominatorTreeWrapperPass>().getDomTree());
Chris Lattner26750072002-07-27 01:12:17 +0000616 return false;
617}
618
Andrew Trickd3530b92011-08-10 23:22:57 +0000619/// updateUnloop - The last backedge has been removed from a loop--now the
620/// "unloop". Find a new parent for the blocks contained within unloop and
Andrew Trick266ab102011-08-11 17:54:58 +0000621/// update the loop tree. We don't necessarily have valid dominators at this
Andrew Trickd3530b92011-08-10 23:22:57 +0000622/// point, but LoopInfo is still valid except for the removal of this loop.
623///
624/// Note that Unloop may now be an empty loop. Calling Loop::getHeader without
625/// checking first is illegal.
626void LoopInfo::updateUnloop(Loop *Unloop) {
627
628 // First handle the special case of no parent loop to simplify the algorithm.
629 if (!Unloop->getParentLoop()) {
630 // Since BBLoop had no parent, Unloop blocks are no longer in a loop.
631 for (Loop::block_iterator I = Unloop->block_begin(),
632 E = Unloop->block_end(); I != E; ++I) {
633
634 // Don't reparent blocks in subloops.
635 if (getLoopFor(*I) != Unloop)
636 continue;
637
638 // Blocks no longer have a parent but are still referenced by Unloop until
639 // the Unloop object is deleted.
640 LI.changeLoopFor(*I, 0);
641 }
642
643 // Remove the loop from the top-level LoopInfo object.
Duncan Sandsa41634e2011-08-12 14:54:45 +0000644 for (LoopInfo::iterator I = LI.begin();; ++I) {
645 assert(I != LI.end() && "Couldn't find loop");
Andrew Trickd3530b92011-08-10 23:22:57 +0000646 if (*I == Unloop) {
647 LI.removeLoop(I);
648 break;
649 }
650 }
651
652 // Move all of the subloops to the top-level.
653 while (!Unloop->empty())
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000654 LI.addTopLevelLoop(Unloop->removeChildLoop(std::prev(Unloop->end())));
Andrew Trickd3530b92011-08-10 23:22:57 +0000655
656 return;
657 }
658
659 // Update the parent loop for all blocks within the loop. Blocks within
660 // subloops will not change parents.
661 UnloopUpdater Updater(Unloop, this);
662 Updater.updateBlockParents();
663
Andrew Trickc12c30a2011-08-11 20:27:32 +0000664 // Remove blocks from former ancestor loops.
665 Updater.removeBlocksFromAncestors();
Andrew Trickd3530b92011-08-10 23:22:57 +0000666
667 // Add direct subloops as children in their new parent loop.
668 Updater.updateSubloopParents();
669
670 // Remove unloop from its parent loop.
671 Loop *ParentLoop = Unloop->getParentLoop();
Duncan Sandsa41634e2011-08-12 14:54:45 +0000672 for (Loop::iterator I = ParentLoop->begin();; ++I) {
673 assert(I != ParentLoop->end() && "Couldn't find loop");
Andrew Trickd3530b92011-08-10 23:22:57 +0000674 if (*I == Unloop) {
675 ParentLoop->removeChildLoop(I);
676 break;
677 }
678 }
679}
680
Dan Gohman3ddbc242009-09-08 15:45:00 +0000681void LoopInfo::verifyAnalysis() const {
Dan Gohman4dbb3012009-09-28 00:27:48 +0000682 // LoopInfo is a FunctionPass, but verifying every loop in the function
683 // each time verifyAnalysis is called is very expensive. The
684 // -verify-loop-info option can enable this. In order to perform some
685 // checking by default, LoopPass has been taught to call verifyLoop
686 // manually during loop pass sequences.
687
688 if (!VerifyLoopInfo) return;
689
Andrew Trick147d9cd2011-08-26 03:06:34 +0000690 DenseSet<const Loop*> Loops;
Dan Gohman3ddbc242009-09-08 15:45:00 +0000691 for (iterator I = begin(), E = end(); I != E; ++I) {
692 assert(!(*I)->getParentLoop() && "Top-level loop has a parent!");
Andrew Trick147d9cd2011-08-26 03:06:34 +0000693 (*I)->verifyLoopNest(&Loops);
Dan Gohman3ddbc242009-09-08 15:45:00 +0000694 }
Dan Gohman4dbb3012009-09-28 00:27:48 +0000695
Andrew Trick147d9cd2011-08-26 03:06:34 +0000696 // Verify that blocks are mapped to valid loops.
Andrew Trick147d9cd2011-08-26 03:06:34 +0000697 for (DenseMap<BasicBlock*, Loop*>::const_iterator I = LI.BBMap.begin(),
698 E = LI.BBMap.end(); I != E; ++I) {
699 assert(Loops.count(I->second) && "orphaned loop");
700 assert(I->second->contains(I->first) && "orphaned block");
701 }
Dan Gohman3ddbc242009-09-08 15:45:00 +0000702}
703
Chris Lattner78dd56f2002-04-28 16:21:30 +0000704void LoopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerc8e66542002-04-27 06:56:12 +0000705 AU.setPreservesAll();
Chandler Carruth73523022014-01-13 13:07:17 +0000706 AU.addRequired<DominatorTreeWrapperPass>();
Chris Lattnerccf571a2002-01-31 00:42:27 +0000707}
Chris Lattnerb1d782b2009-08-23 05:17:37 +0000708
Chris Lattner13626022009-08-23 06:03:38 +0000709void LoopInfo::print(raw_ostream &OS, const Module*) const {
710 LI.print(OS);
Chris Lattnerb1d782b2009-08-23 05:17:37 +0000711}
712
Andrew Trick78b40c32011-08-10 01:59:05 +0000713//===----------------------------------------------------------------------===//
714// LoopBlocksDFS implementation
715//
716
717/// Traverse the loop blocks and store the DFS result.
718/// Useful for clients that just want the final DFS result and don't need to
719/// visit blocks during the initial traversal.
720void LoopBlocksDFS::perform(LoopInfo *LI) {
721 LoopBlocksTraversal Traversal(*this, LI);
722 for (LoopBlocksTraversal::POTIterator POI = Traversal.begin(),
723 POE = Traversal.end(); POI != POE; ++POI) ;
724}