blob: 95f6eb0af0f549b49c951b2e218da07871ff13f1 [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"
Philip Reames5a3f5f72014-10-21 00:13:20 +000027#include "llvm/IR/LLVMContext.h"
Pekka Jaaskelainen0d237252013-02-13 18:08:57 +000028#include "llvm/IR/Metadata.h"
Chandler Carruthaaf0b4c2015-01-20 10:58:50 +000029#include "llvm/IR/PassManager.h"
Dan Gohman4dbb3012009-09-28 00:27:48 +000030#include "llvm/Support/CommandLine.h"
Dan Gohmanc3f21372010-01-05 21:08:02 +000031#include "llvm/Support/Debug.h"
Chris Lattner6de99422001-11-26 18:41:20 +000032#include <algorithm>
Chris Lattner55b7ef52004-04-12 20:26:17 +000033using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000034
Andrew Trickcda51d42012-06-20 03:42:09 +000035// Explicitly instantiate methods in LoopInfoImpl.h for IR-level Loops.
36template class llvm::LoopBase<BasicBlock, Loop>;
37template class llvm::LoopInfoBase<BasicBlock, Loop>;
38
Dan Gohman4dbb3012009-09-28 00:27:48 +000039// Always verify loopinfo if expensive checking is enabled.
40#ifdef XDEBUG
Dan Gohmanb29cda92010-04-15 17:08:50 +000041static bool VerifyLoopInfo = true;
Dan Gohman4dbb3012009-09-28 00:27:48 +000042#else
Dan Gohmanb29cda92010-04-15 17:08:50 +000043static bool VerifyLoopInfo = false;
Dan Gohman4dbb3012009-09-28 00:27:48 +000044#endif
45static cl::opt<bool,true>
46VerifyLoopInfoX("verify-loop-info", cl::location(VerifyLoopInfo),
47 cl::desc("Verify loop info (time consuming)"));
48
Paul Redmond5fdf8362013-05-28 20:00:34 +000049// Loop identifier metadata name.
Craig Topperd3a34f82013-07-16 01:17:10 +000050static const char *const LoopMDName = "llvm.loop";
Paul Redmond5fdf8362013-05-28 20:00:34 +000051
Chris Lattnerccf571a2002-01-31 00:42:27 +000052//===----------------------------------------------------------------------===//
Chris Lattner78dd56f2002-04-28 16:21:30 +000053// Loop implementation
Chris Lattnerccf571a2002-01-31 00:42:27 +000054//
Misha Brukman3845be22002-10-11 05:31:10 +000055
Dan Gohman80a99422009-07-13 22:02:44 +000056/// isLoopInvariant - Return true if the specified value is loop invariant
57///
58bool Loop::isLoopInvariant(Value *V) const {
59 if (Instruction *I = dyn_cast<Instruction>(V))
Chris Lattnerda24b9a2010-09-06 01:05:37 +000060 return !contains(I);
Dan Gohman80a99422009-07-13 22:02:44 +000061 return true; // All non-instructions are loop invariant
62}
63
Chris Lattnerda24b9a2010-09-06 01:05:37 +000064/// hasLoopInvariantOperands - Return true if all the operands of the
Andrew Trickf898cbd2011-08-03 23:45:50 +000065/// specified instruction are loop invariant.
Chris Lattnerda24b9a2010-09-06 01:05:37 +000066bool Loop::hasLoopInvariantOperands(Instruction *I) const {
67 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
68 if (!isLoopInvariant(I->getOperand(i)))
69 return false;
Andrew Trickf898cbd2011-08-03 23:45:50 +000070
Chris Lattnerda24b9a2010-09-06 01:05:37 +000071 return true;
Dan Gohman6f6d8642009-07-14 01:06:29 +000072}
73
74/// makeLoopInvariant - If the given value is an instruciton inside of the
75/// loop and it can be hoisted, do so to make it trivially loop-invariant.
76/// Return true if the value after any hoisting is loop invariant. This
77/// function can be used as a slightly more aggressive replacement for
78/// isLoopInvariant.
79///
80/// If InsertPt is specified, it is the point to hoist instructions to.
81/// If null, the terminator of the loop preheader is used.
82///
Dan Gohmanc43e4792009-07-15 01:25:43 +000083bool Loop::makeLoopInvariant(Value *V, bool &Changed,
84 Instruction *InsertPt) const {
Dan Gohman6f6d8642009-07-14 01:06:29 +000085 if (Instruction *I = dyn_cast<Instruction>(V))
Dan Gohmanc43e4792009-07-15 01:25:43 +000086 return makeLoopInvariant(I, Changed, InsertPt);
Dan Gohman6f6d8642009-07-14 01:06:29 +000087 return true; // All non-instructions are loop-invariant.
88}
89
90/// makeLoopInvariant - If the given instruction is inside of the
91/// loop and it can be hoisted, do so to make it trivially loop-invariant.
92/// Return true if the instruction after any hoisting is loop invariant. This
93/// function can be used as a slightly more aggressive replacement for
94/// isLoopInvariant.
95///
96/// If InsertPt is specified, it is the point to hoist instructions to.
97/// If null, the terminator of the loop preheader is used.
98///
Dan Gohmanc43e4792009-07-15 01:25:43 +000099bool Loop::makeLoopInvariant(Instruction *I, bool &Changed,
100 Instruction *InsertPt) const {
Dan Gohman6f6d8642009-07-14 01:06:29 +0000101 // Test if the value is already loop-invariant.
102 if (isLoopInvariant(I))
103 return true;
Dan Gohman75d7d5e2011-12-14 23:49:11 +0000104 if (!isSafeToSpeculativelyExecute(I))
Dan Gohman6f6d8642009-07-14 01:06:29 +0000105 return false;
Eli Friedmanb8f6a4f2009-07-17 04:28:42 +0000106 if (I->mayReadFromMemory())
Dan Gohman6f6d8642009-07-14 01:06:29 +0000107 return false;
Bill Wendlinga9ee09f2011-08-17 20:36:44 +0000108 // The landingpad instruction is immobile.
109 if (isa<LandingPadInst>(I))
110 return false;
Dan Gohman6f6d8642009-07-14 01:06:29 +0000111 // Determine the insertion point, unless one was given.
112 if (!InsertPt) {
113 BasicBlock *Preheader = getLoopPreheader();
114 // Without a preheader, hoisting is not feasible.
115 if (!Preheader)
116 return false;
117 InsertPt = Preheader->getTerminator();
118 }
119 // Don't hoist instructions with loop-variant operands.
120 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
Dan Gohmanc43e4792009-07-15 01:25:43 +0000121 if (!makeLoopInvariant(I->getOperand(i), Changed, InsertPt))
Dan Gohman6f6d8642009-07-14 01:06:29 +0000122 return false;
Andrew Trickf898cbd2011-08-03 23:45:50 +0000123
Dan Gohman6f6d8642009-07-14 01:06:29 +0000124 // Hoist.
125 I->moveBefore(InsertPt);
Dan Gohmanc43e4792009-07-15 01:25:43 +0000126 Changed = true;
Dan Gohman6f6d8642009-07-14 01:06:29 +0000127 return true;
128}
129
Dan Gohman80a99422009-07-13 22:02:44 +0000130/// getCanonicalInductionVariable - Check to see if the loop has a canonical
131/// induction variable: an integer recurrence that starts at 0 and increments
132/// by one each time through the loop. If so, return the phi node that
133/// corresponds to it.
134///
135/// The IndVarSimplify pass transforms loops to have a canonical induction
136/// variable.
137///
138PHINode *Loop::getCanonicalInductionVariable() const {
139 BasicBlock *H = getHeader();
140
Craig Topper9f008862014-04-15 04:59:12 +0000141 BasicBlock *Incoming = nullptr, *Backedge = nullptr;
Dan Gohmanacafc612010-07-23 21:25:16 +0000142 pred_iterator PI = pred_begin(H);
143 assert(PI != pred_end(H) &&
Dan Gohman80a99422009-07-13 22:02:44 +0000144 "Loop must have at least one backedge!");
145 Backedge = *PI++;
Craig Topper9f008862014-04-15 04:59:12 +0000146 if (PI == pred_end(H)) return nullptr; // dead loop
Dan Gohman80a99422009-07-13 22:02:44 +0000147 Incoming = *PI++;
Craig Topper9f008862014-04-15 04:59:12 +0000148 if (PI != pred_end(H)) return nullptr; // multiple backedges?
Dan Gohman80a99422009-07-13 22:02:44 +0000149
150 if (contains(Incoming)) {
151 if (contains(Backedge))
Craig Topper9f008862014-04-15 04:59:12 +0000152 return nullptr;
Dan Gohman80a99422009-07-13 22:02:44 +0000153 std::swap(Incoming, Backedge);
154 } else if (!contains(Backedge))
Craig Topper9f008862014-04-15 04:59:12 +0000155 return nullptr;
Dan Gohman80a99422009-07-13 22:02:44 +0000156
157 // Loop over all of the PHI nodes, looking for a canonical indvar.
158 for (BasicBlock::iterator I = H->begin(); isa<PHINode>(I); ++I) {
159 PHINode *PN = cast<PHINode>(I);
160 if (ConstantInt *CI =
161 dyn_cast<ConstantInt>(PN->getIncomingValueForBlock(Incoming)))
162 if (CI->isNullValue())
163 if (Instruction *Inc =
164 dyn_cast<Instruction>(PN->getIncomingValueForBlock(Backedge)))
165 if (Inc->getOpcode() == Instruction::Add &&
166 Inc->getOperand(0) == PN)
167 if (ConstantInt *CI = dyn_cast<ConstantInt>(Inc->getOperand(1)))
168 if (CI->equalsInt(1))
169 return PN;
170 }
Craig Topper9f008862014-04-15 04:59:12 +0000171 return nullptr;
Dan Gohman80a99422009-07-13 22:02:44 +0000172}
173
Dan Gohman80a99422009-07-13 22:02:44 +0000174/// isLCSSAForm - Return true if the Loop is in LCSSA form
Dan Gohman2734ebd2010-03-10 19:38:49 +0000175bool Loop::isLCSSAForm(DominatorTree &DT) const {
Dan Gohman80a99422009-07-13 22:02:44 +0000176 for (block_iterator BI = block_begin(), E = block_end(); BI != E; ++BI) {
Dan Gohman5196e412009-11-09 18:19:43 +0000177 BasicBlock *BB = *BI;
178 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;++I)
Chandler Carruthcdf47882014-03-09 03:16:01 +0000179 for (Use &U : I->uses()) {
180 Instruction *UI = cast<Instruction>(U.getUser());
181 BasicBlock *UserBB = UI->getParent();
182 if (PHINode *P = dyn_cast<PHINode>(UI))
183 UserBB = P->getIncomingBlock(U);
Dan Gohman80a99422009-07-13 22:02:44 +0000184
Dan Gohman93452ce2010-03-09 01:53:33 +0000185 // Check the current block, as a fast-path, before checking whether
186 // the use is anywhere in the loop. Most values are used in the same
187 // block they are defined in. Also, blocks not reachable from the
188 // entry are special; uses in them don't need to go through PHIs.
189 if (UserBB != BB &&
Wan Xiaofeibe640b22013-10-26 03:08:02 +0000190 !contains(UserBB) &&
Dan Gohman2734ebd2010-03-10 19:38:49 +0000191 DT.isReachableFromEntry(UserBB))
Dan Gohman80a99422009-07-13 22:02:44 +0000192 return false;
193 }
194 }
195
196 return true;
197}
Dan Gohman1511f702009-07-16 16:16:23 +0000198
199/// isLoopSimplifyForm - Return true if the Loop is in the form that
200/// the LoopSimplify form transforms loops to, which is sometimes called
201/// normal form.
202bool Loop::isLoopSimplifyForm() const {
Dan Gohmane3a17062009-11-05 19:21:41 +0000203 // Normal-form loops have a preheader, a single backedge, and all of their
204 // exits have all their predecessors inside the loop.
205 return getLoopPreheader() && getLoopLatch() && hasDedicatedExits();
206}
207
Andrew Trick4442bfe2012-04-10 05:14:42 +0000208/// isSafeToClone - Return true if the loop body is safe to clone in practice.
209/// Routines that reform the loop CFG and split edges often fail on indirectbr.
210bool Loop::isSafeToClone() const {
James Molloy4f6fb952012-12-20 16:04:27 +0000211 // Return false if any loop blocks contain indirectbrs, or there are any calls
212 // to noduplicate functions.
Andrew Trick4442bfe2012-04-10 05:14:42 +0000213 for (Loop::block_iterator I = block_begin(), E = block_end(); I != E; ++I) {
Jakub Staszak9dca4b32013-11-13 20:18:38 +0000214 if (isa<IndirectBrInst>((*I)->getTerminator()))
Andrew Trick4442bfe2012-04-10 05:14:42 +0000215 return false;
Jakub Staszak9dca4b32013-11-13 20:18:38 +0000216
217 if (const InvokeInst *II = dyn_cast<InvokeInst>((*I)->getTerminator()))
Eli Bendersky576ef3c2014-03-17 16:19:07 +0000218 if (II->cannotDuplicate())
James Molloy4f6fb952012-12-20 16:04:27 +0000219 return false;
James Molloy4f6fb952012-12-20 16:04:27 +0000220
221 for (BasicBlock::iterator BI = (*I)->begin(), BE = (*I)->end(); BI != BE; ++BI) {
222 if (const CallInst *CI = dyn_cast<CallInst>(BI)) {
Eli Bendersky576ef3c2014-03-17 16:19:07 +0000223 if (CI->cannotDuplicate())
James Molloy4f6fb952012-12-20 16:04:27 +0000224 return false;
225 }
226 }
Andrew Trick4442bfe2012-04-10 05:14:42 +0000227 }
228 return true;
229}
230
Paul Redmond5fdf8362013-05-28 20:00:34 +0000231MDNode *Loop::getLoopID() const {
Craig Topper9f008862014-04-15 04:59:12 +0000232 MDNode *LoopID = nullptr;
Paul Redmond5fdf8362013-05-28 20:00:34 +0000233 if (isLoopSimplifyForm()) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000234 LoopID = getLoopLatch()->getTerminator()->getMetadata(LoopMDName);
Paul Redmond5fdf8362013-05-28 20:00:34 +0000235 } else {
236 // Go through each predecessor of the loop header and check the
237 // terminator for the metadata.
238 BasicBlock *H = getHeader();
239 for (block_iterator I = block_begin(), IE = block_end(); I != IE; ++I) {
240 TerminatorInst *TI = (*I)->getTerminator();
Craig Topper9f008862014-04-15 04:59:12 +0000241 MDNode *MD = nullptr;
Paul Redmond5fdf8362013-05-28 20:00:34 +0000242
243 // Check if this terminator branches to the loop header.
244 for (unsigned i = 0, ie = TI->getNumSuccessors(); i != ie; ++i) {
245 if (TI->getSuccessor(i) == H) {
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000246 MD = TI->getMetadata(LoopMDName);
Paul Redmond5fdf8362013-05-28 20:00:34 +0000247 break;
248 }
249 }
250 if (!MD)
Craig Topper9f008862014-04-15 04:59:12 +0000251 return nullptr;
Paul Redmond5fdf8362013-05-28 20:00:34 +0000252
253 if (!LoopID)
254 LoopID = MD;
255 else if (MD != LoopID)
Craig Topper9f008862014-04-15 04:59:12 +0000256 return nullptr;
Paul Redmond5fdf8362013-05-28 20:00:34 +0000257 }
258 }
259 if (!LoopID || LoopID->getNumOperands() == 0 ||
260 LoopID->getOperand(0) != LoopID)
Craig Topper9f008862014-04-15 04:59:12 +0000261 return nullptr;
Paul Redmond5fdf8362013-05-28 20:00:34 +0000262 return LoopID;
263}
264
265void Loop::setLoopID(MDNode *LoopID) const {
266 assert(LoopID && "Loop ID should not be null");
267 assert(LoopID->getNumOperands() > 0 && "Loop ID needs at least one operand");
268 assert(LoopID->getOperand(0) == LoopID && "Loop ID should refer to itself");
269
270 if (isLoopSimplifyForm()) {
271 getLoopLatch()->getTerminator()->setMetadata(LoopMDName, LoopID);
272 return;
273 }
274
275 BasicBlock *H = getHeader();
276 for (block_iterator I = block_begin(), IE = block_end(); I != IE; ++I) {
277 TerminatorInst *TI = (*I)->getTerminator();
278 for (unsigned i = 0, ie = TI->getNumSuccessors(); i != ie; ++i) {
279 if (TI->getSuccessor(i) == H)
280 TI->setMetadata(LoopMDName, LoopID);
281 }
282 }
283}
284
Pekka Jaaskelainen0d237252013-02-13 18:08:57 +0000285bool Loop::isAnnotatedParallel() const {
Paul Redmond5fdf8362013-05-28 20:00:34 +0000286 MDNode *desiredLoopIdMetadata = getLoopID();
Pekka Jaaskelainen0d237252013-02-13 18:08:57 +0000287
288 if (!desiredLoopIdMetadata)
289 return false;
290
291 // The loop branch contains the parallel loop metadata. In order to ensure
292 // that any parallel-loop-unaware optimization pass hasn't added loop-carried
293 // dependencies (thus converted the loop back to a sequential loop), check
294 // that all the memory instructions in the loop contain parallelism metadata
295 // that point to the same unique "loop id metadata" the loop branch does.
296 for (block_iterator BB = block_begin(), BE = block_end(); BB != BE; ++BB) {
297 for (BasicBlock::iterator II = (*BB)->begin(), EE = (*BB)->end();
298 II != EE; II++) {
299
300 if (!II->mayReadOrWriteMemory())
301 continue;
302
Pekka Jaaskelainen0d237252013-02-13 18:08:57 +0000303 // The memory instruction can refer to the loop identifier metadata
304 // directly or indirectly through another list metadata (in case of
305 // nested parallel loops). The loop identifier metadata refers to
306 // itself so we can check both cases with the same routine.
Philip Reames5a3f5f72014-10-21 00:13:20 +0000307 MDNode *loopIdMD =
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000308 II->getMetadata(LLVMContext::MD_mem_parallel_loop_access);
Jakub Staszak9dca4b32013-11-13 20:18:38 +0000309
310 if (!loopIdMD)
311 return false;
312
Pekka Jaaskelainen0d237252013-02-13 18:08:57 +0000313 bool loopIdMDFound = false;
314 for (unsigned i = 0, e = loopIdMD->getNumOperands(); i < e; ++i) {
315 if (loopIdMD->getOperand(i) == desiredLoopIdMetadata) {
316 loopIdMDFound = true;
317 break;
318 }
319 }
320
321 if (!loopIdMDFound)
322 return false;
323 }
324 }
325 return true;
326}
327
328
Dan Gohmane3a17062009-11-05 19:21:41 +0000329/// hasDedicatedExits - Return true if no exit block for the loop
330/// has a predecessor that is outside the loop.
331bool Loop::hasDedicatedExits() const {
Dan Gohman1511f702009-07-16 16:16:23 +0000332 // Each predecessor of each exit block of a normal loop is contained
333 // within the loop.
334 SmallVector<BasicBlock *, 4> ExitBlocks;
335 getExitBlocks(ExitBlocks);
336 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000337 for (pred_iterator PI = pred_begin(ExitBlocks[i]),
338 PE = pred_end(ExitBlocks[i]); PI != PE; ++PI)
339 if (!contains(*PI))
Dan Gohman1511f702009-07-16 16:16:23 +0000340 return false;
341 // All the requirements are met.
342 return true;
343}
344
Dan Gohman3a0ce3e2009-09-03 16:10:48 +0000345/// getUniqueExitBlocks - Return all unique successor blocks of this loop.
346/// These are the blocks _outside of the current loop_ which are branched to.
Dan Gohman84ba0392009-12-11 20:05:23 +0000347/// This assumes that loop exits are in canonical form.
Dan Gohman3a0ce3e2009-09-03 16:10:48 +0000348///
349void
350Loop::getUniqueExitBlocks(SmallVectorImpl<BasicBlock *> &ExitBlocks) const {
Dan Gohman84ba0392009-12-11 20:05:23 +0000351 assert(hasDedicatedExits() &&
352 "getUniqueExitBlocks assumes the loop has canonical form exits!");
Dan Gohman3ddbc242009-09-08 15:45:00 +0000353
Dan Gohmaned8f3202009-09-03 20:36:13 +0000354 SmallVector<BasicBlock *, 32> switchExitBlocks;
Dan Gohman3a0ce3e2009-09-03 16:10:48 +0000355
356 for (block_iterator BI = block_begin(), BE = block_end(); BI != BE; ++BI) {
357
358 BasicBlock *current = *BI;
359 switchExitBlocks.clear();
360
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000361 for (succ_iterator I = succ_begin(*BI), E = succ_end(*BI); I != E; ++I) {
Dan Gohman3a0ce3e2009-09-03 16:10:48 +0000362 // If block is inside the loop then it is not a exit block.
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000363 if (contains(*I))
Dan Gohman3a0ce3e2009-09-03 16:10:48 +0000364 continue;
365
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000366 pred_iterator PI = pred_begin(*I);
Dan Gohman3a0ce3e2009-09-03 16:10:48 +0000367 BasicBlock *firstPred = *PI;
368
369 // If current basic block is this exit block's first predecessor
370 // then only insert exit block in to the output ExitBlocks vector.
371 // This ensures that same exit block is not inserted twice into
372 // ExitBlocks vector.
373 if (current != firstPred)
374 continue;
375
376 // If a terminator has more then two successors, for example SwitchInst,
377 // then it is possible that there are multiple edges from current block
378 // to one exit block.
Dan Gohmanacafc612010-07-23 21:25:16 +0000379 if (std::distance(succ_begin(current), succ_end(current)) <= 2) {
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000380 ExitBlocks.push_back(*I);
Dan Gohman3a0ce3e2009-09-03 16:10:48 +0000381 continue;
382 }
383
384 // In case of multiple edges from current block to exit block, collect
385 // only one edge in ExitBlocks. Use switchExitBlocks to keep track of
386 // duplicate edges.
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000387 if (std::find(switchExitBlocks.begin(), switchExitBlocks.end(), *I)
Dan Gohman3a0ce3e2009-09-03 16:10:48 +0000388 == switchExitBlocks.end()) {
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000389 switchExitBlocks.push_back(*I);
390 ExitBlocks.push_back(*I);
Dan Gohman3a0ce3e2009-09-03 16:10:48 +0000391 }
392 }
393 }
394}
395
396/// getUniqueExitBlock - If getUniqueExitBlocks would return exactly one
397/// block, return that block. Otherwise return null.
398BasicBlock *Loop::getUniqueExitBlock() const {
399 SmallVector<BasicBlock *, 8> UniqueExitBlocks;
400 getUniqueExitBlocks(UniqueExitBlocks);
401 if (UniqueExitBlocks.size() == 1)
402 return UniqueExitBlocks[0];
Craig Topper9f008862014-04-15 04:59:12 +0000403 return nullptr;
Dan Gohman3a0ce3e2009-09-03 16:10:48 +0000404}
405
Manman Ren49d684e2012-09-12 05:06:18 +0000406#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Dan Gohmanc3f21372010-01-05 21:08:02 +0000407void Loop::dump() const {
408 print(dbgs());
409}
Manman Renc3366cc2012-09-06 19:55:56 +0000410#endif
Dan Gohmanc3f21372010-01-05 21:08:02 +0000411
Chris Lattner26750072002-07-27 01:12:17 +0000412//===----------------------------------------------------------------------===//
Andrew Trickd3530b92011-08-10 23:22:57 +0000413// UnloopUpdater implementation
414//
415
Benjamin Kramer4938edb2011-08-19 01:42:18 +0000416namespace {
Andrew Trickd3530b92011-08-10 23:22:57 +0000417/// Find the new parent loop for all blocks within the "unloop" whose last
418/// backedges has just been removed.
419class UnloopUpdater {
420 Loop *Unloop;
421 LoopInfo *LI;
422
423 LoopBlocksDFS DFS;
424
425 // Map unloop's immediate subloops to their nearest reachable parents. Nested
426 // loops within these subloops will not change parents. However, an immediate
427 // subloop's new parent will be the nearest loop reachable from either its own
428 // exits *or* any of its nested loop's exits.
429 DenseMap<Loop*, Loop*> SubloopParents;
430
431 // Flag the presence of an irreducible backedge whose destination is a block
432 // directly contained by the original unloop.
433 bool FoundIB;
434
435public:
436 UnloopUpdater(Loop *UL, LoopInfo *LInfo) :
437 Unloop(UL), LI(LInfo), DFS(UL), FoundIB(false) {}
438
439 void updateBlockParents();
440
Andrew Trickc12c30a2011-08-11 20:27:32 +0000441 void removeBlocksFromAncestors();
442
Andrew Trickd3530b92011-08-10 23:22:57 +0000443 void updateSubloopParents();
444
445protected:
446 Loop *getNearestLoop(BasicBlock *BB, Loop *BBLoop);
447};
Benjamin Kramer4938edb2011-08-19 01:42:18 +0000448} // end anonymous namespace
Andrew Trickd3530b92011-08-10 23:22:57 +0000449
450/// updateBlockParents - Update the parent loop for all blocks that are directly
451/// contained within the original "unloop".
452void UnloopUpdater::updateBlockParents() {
453 if (Unloop->getNumBlocks()) {
454 // Perform a post order CFG traversal of all blocks within this loop,
455 // propagating the nearest loop from sucessors to predecessors.
456 LoopBlocksTraversal Traversal(DFS, LI);
457 for (LoopBlocksTraversal::POTIterator POI = Traversal.begin(),
458 POE = Traversal.end(); POI != POE; ++POI) {
459
460 Loop *L = LI->getLoopFor(*POI);
461 Loop *NL = getNearestLoop(*POI, L);
462
463 if (NL != L) {
464 // For reducible loops, NL is now an ancestor of Unloop.
465 assert((NL != Unloop && (!NL || NL->contains(Unloop))) &&
466 "uninitialized successor");
467 LI->changeLoopFor(*POI, NL);
468 }
469 else {
470 // Or the current block is part of a subloop, in which case its parent
471 // is unchanged.
472 assert((FoundIB || Unloop->contains(L)) && "uninitialized successor");
473 }
474 }
475 }
476 // Each irreducible loop within the unloop induces a round of iteration using
477 // the DFS result cached by Traversal.
478 bool Changed = FoundIB;
479 for (unsigned NIters = 0; Changed; ++NIters) {
480 assert(NIters < Unloop->getNumBlocks() && "runaway iterative algorithm");
481
482 // Iterate over the postorder list of blocks, propagating the nearest loop
483 // from successors to predecessors as before.
484 Changed = false;
485 for (LoopBlocksDFS::POIterator POI = DFS.beginPostorder(),
486 POE = DFS.endPostorder(); POI != POE; ++POI) {
487
488 Loop *L = LI->getLoopFor(*POI);
489 Loop *NL = getNearestLoop(*POI, L);
490 if (NL != L) {
491 assert(NL != Unloop && (!NL || NL->contains(Unloop)) &&
492 "uninitialized successor");
493 LI->changeLoopFor(*POI, NL);
494 Changed = true;
495 }
496 }
497 }
498}
499
Andrew Trickc12c30a2011-08-11 20:27:32 +0000500/// removeBlocksFromAncestors - Remove unloop's blocks from all ancestors below
501/// their new parents.
502void UnloopUpdater::removeBlocksFromAncestors() {
Andrew Trick6b4d5782011-11-18 03:42:41 +0000503 // Remove all unloop's blocks (including those in nested subloops) from
504 // ancestors below the new parent loop.
Andrew Trickc12c30a2011-08-11 20:27:32 +0000505 for (Loop::block_iterator BI = Unloop->block_begin(),
506 BE = Unloop->block_end(); BI != BE; ++BI) {
Andrew Trick6b4d5782011-11-18 03:42:41 +0000507 Loop *OuterParent = LI->getLoopFor(*BI);
508 if (Unloop->contains(OuterParent)) {
509 while (OuterParent->getParentLoop() != Unloop)
510 OuterParent = OuterParent->getParentLoop();
511 OuterParent = SubloopParents[OuterParent];
512 }
Andrew Trickc12c30a2011-08-11 20:27:32 +0000513 // Remove blocks from former Ancestors except Unloop itself which will be
514 // deleted.
Andrew Trick6b4d5782011-11-18 03:42:41 +0000515 for (Loop *OldParent = Unloop->getParentLoop(); OldParent != OuterParent;
Andrew Trickc12c30a2011-08-11 20:27:32 +0000516 OldParent = OldParent->getParentLoop()) {
517 assert(OldParent && "new loop is not an ancestor of the original");
518 OldParent->removeBlockFromLoop(*BI);
519 }
520 }
521}
522
Andrew Trickd3530b92011-08-10 23:22:57 +0000523/// updateSubloopParents - Update the parent loop for all subloops directly
524/// nested within unloop.
525void UnloopUpdater::updateSubloopParents() {
526 while (!Unloop->empty()) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000527 Loop *Subloop = *std::prev(Unloop->end());
528 Unloop->removeChildLoop(std::prev(Unloop->end()));
Andrew Trickd3530b92011-08-10 23:22:57 +0000529
530 assert(SubloopParents.count(Subloop) && "DFS failed to visit subloop");
Benjamin Kramerf29db272012-08-22 15:37:57 +0000531 if (Loop *Parent = SubloopParents[Subloop])
532 Parent->addChildLoop(Subloop);
Andrew Trick147d9cd2011-08-26 03:06:34 +0000533 else
534 LI->addTopLevelLoop(Subloop);
Andrew Trickd3530b92011-08-10 23:22:57 +0000535 }
536}
537
538/// getNearestLoop - Return the nearest parent loop among this block's
539/// successors. If a successor is a subloop header, consider its parent to be
540/// the nearest parent of the subloop's exits.
541///
542/// For subloop blocks, simply update SubloopParents and return NULL.
543Loop *UnloopUpdater::getNearestLoop(BasicBlock *BB, Loop *BBLoop) {
544
Andrew Trick266ab102011-08-11 17:54:58 +0000545 // Initially for blocks directly contained by Unloop, NearLoop == Unloop and
546 // is considered uninitialized.
Andrew Trickd3530b92011-08-10 23:22:57 +0000547 Loop *NearLoop = BBLoop;
548
Craig Topper9f008862014-04-15 04:59:12 +0000549 Loop *Subloop = nullptr;
Andrew Trickd3530b92011-08-10 23:22:57 +0000550 if (NearLoop != Unloop && Unloop->contains(NearLoop)) {
551 Subloop = NearLoop;
552 // Find the subloop ancestor that is directly contained within Unloop.
553 while (Subloop->getParentLoop() != Unloop) {
554 Subloop = Subloop->getParentLoop();
555 assert(Subloop && "subloop is not an ancestor of the original loop");
556 }
557 // Get the current nearest parent of the Subloop exits, initially Unloop.
Benjamin Kramerf29db272012-08-22 15:37:57 +0000558 NearLoop =
559 SubloopParents.insert(std::make_pair(Subloop, Unloop)).first->second;
Andrew Trickd3530b92011-08-10 23:22:57 +0000560 }
561
562 succ_iterator I = succ_begin(BB), E = succ_end(BB);
563 if (I == E) {
564 assert(!Subloop && "subloop blocks must have a successor");
Craig Topper9f008862014-04-15 04:59:12 +0000565 NearLoop = nullptr; // unloop blocks may now exit the function.
Andrew Trickd3530b92011-08-10 23:22:57 +0000566 }
567 for (; I != E; ++I) {
568 if (*I == BB)
569 continue; // self loops are uninteresting
570
571 Loop *L = LI->getLoopFor(*I);
572 if (L == Unloop) {
573 // This successor has not been processed. This path must lead to an
574 // irreducible backedge.
575 assert((FoundIB || !DFS.hasPostorder(*I)) && "should have seen IB");
576 FoundIB = true;
577 }
578 if (L != Unloop && Unloop->contains(L)) {
579 // Successor is in a subloop.
580 if (Subloop)
581 continue; // Branching within subloops. Ignore it.
582
583 // BB branches from the original into a subloop header.
584 assert(L->getParentLoop() == Unloop && "cannot skip into nested loops");
585
586 // Get the current nearest parent of the Subloop's exits.
587 L = SubloopParents[L];
588 // L could be Unloop if the only exit was an irreducible backedge.
589 }
590 if (L == Unloop) {
591 continue;
592 }
593 // Handle critical edges from Unloop into a sibling loop.
594 if (L && !L->contains(Unloop)) {
595 L = L->getParentLoop();
596 }
597 // Remember the nearest parent loop among successors or subloop exits.
598 if (NearLoop == Unloop || !NearLoop || NearLoop->contains(L))
599 NearLoop = L;
600 }
601 if (Subloop) {
602 SubloopParents[Subloop] = NearLoop;
603 return BBLoop;
604 }
605 return NearLoop;
606}
607
Andrew Trickd3530b92011-08-10 23:22:57 +0000608/// updateUnloop - The last backedge has been removed from a loop--now the
609/// "unloop". Find a new parent for the blocks contained within unloop and
Andrew Trick266ab102011-08-11 17:54:58 +0000610/// update the loop tree. We don't necessarily have valid dominators at this
Andrew Trickd3530b92011-08-10 23:22:57 +0000611/// point, but LoopInfo is still valid except for the removal of this loop.
612///
613/// Note that Unloop may now be an empty loop. Calling Loop::getHeader without
614/// checking first is illegal.
615void LoopInfo::updateUnloop(Loop *Unloop) {
616
617 // First handle the special case of no parent loop to simplify the algorithm.
618 if (!Unloop->getParentLoop()) {
619 // Since BBLoop had no parent, Unloop blocks are no longer in a loop.
620 for (Loop::block_iterator I = Unloop->block_begin(),
Chandler Carruth691addc2015-01-18 01:25:51 +0000621 E = Unloop->block_end();
622 I != E; ++I) {
Andrew Trickd3530b92011-08-10 23:22:57 +0000623
624 // Don't reparent blocks in subloops.
625 if (getLoopFor(*I) != Unloop)
626 continue;
627
628 // Blocks no longer have a parent but are still referenced by Unloop until
629 // the Unloop object is deleted.
Chandler Carruth691addc2015-01-18 01:25:51 +0000630 changeLoopFor(*I, nullptr);
Andrew Trickd3530b92011-08-10 23:22:57 +0000631 }
632
633 // Remove the loop from the top-level LoopInfo object.
Chandler Carruth691addc2015-01-18 01:25:51 +0000634 for (iterator I = begin();; ++I) {
635 assert(I != end() && "Couldn't find loop");
Andrew Trickd3530b92011-08-10 23:22:57 +0000636 if (*I == Unloop) {
Chandler Carruth691addc2015-01-18 01:25:51 +0000637 removeLoop(I);
Andrew Trickd3530b92011-08-10 23:22:57 +0000638 break;
639 }
640 }
641
642 // Move all of the subloops to the top-level.
643 while (!Unloop->empty())
Chandler Carruth691addc2015-01-18 01:25:51 +0000644 addTopLevelLoop(Unloop->removeChildLoop(std::prev(Unloop->end())));
Andrew Trickd3530b92011-08-10 23:22:57 +0000645
646 return;
647 }
648
649 // Update the parent loop for all blocks within the loop. Blocks within
650 // subloops will not change parents.
651 UnloopUpdater Updater(Unloop, this);
652 Updater.updateBlockParents();
653
Andrew Trickc12c30a2011-08-11 20:27:32 +0000654 // Remove blocks from former ancestor loops.
655 Updater.removeBlocksFromAncestors();
Andrew Trickd3530b92011-08-10 23:22:57 +0000656
657 // Add direct subloops as children in their new parent loop.
658 Updater.updateSubloopParents();
659
660 // Remove unloop from its parent loop.
661 Loop *ParentLoop = Unloop->getParentLoop();
Duncan Sandsa41634e2011-08-12 14:54:45 +0000662 for (Loop::iterator I = ParentLoop->begin();; ++I) {
663 assert(I != ParentLoop->end() && "Couldn't find loop");
Andrew Trickd3530b92011-08-10 23:22:57 +0000664 if (*I == Unloop) {
665 ParentLoop->removeChildLoop(I);
666 break;
667 }
668 }
669}
670
Chandler Carruthaaf0b4c2015-01-20 10:58:50 +0000671char LoopAnalysis::PassID;
672
673LoopInfo LoopAnalysis::run(Function &F, AnalysisManager<Function> *AM) {
674 // FIXME: Currently we create a LoopInfo from scratch for every function.
675 // This may prove to be too wasteful due to deallocating and re-allocating
676 // memory each time for the underlying map and vector datastructures. At some
677 // point it may prove worthwhile to use a freelist and recycle LoopInfo
678 // objects. I don't want to add that kind of complexity until the scope of
679 // the problem is better understood.
680 LoopInfo LI;
681 LI.Analyze(AM->getResult<DominatorTreeAnalysis>(F));
682 return std::move(LI);
683}
684
685PreservedAnalyses LoopPrinterPass::run(Function &F,
686 AnalysisManager<Function> *AM) {
687 AM->getResult<LoopAnalysis>(F).print(OS);
688 return PreservedAnalyses::all();
689}
690
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000691//===----------------------------------------------------------------------===//
692// LoopInfo implementation
693//
694
695char LoopInfoWrapperPass::ID = 0;
696INITIALIZE_PASS_BEGIN(LoopInfoWrapperPass, "loops", "Natural Loop Information",
697 true, true)
698INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
699INITIALIZE_PASS_END(LoopInfoWrapperPass, "loops", "Natural Loop Information",
700 true, true)
701
702bool LoopInfoWrapperPass::runOnFunction(Function &) {
703 releaseMemory();
Chandler Carruth691addc2015-01-18 01:25:51 +0000704 LI.Analyze(getAnalysis<DominatorTreeWrapperPass>().getDomTree());
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000705 return false;
706}
707
708void LoopInfoWrapperPass::verifyAnalysis() const {
709 // LoopInfoWrapperPass is a FunctionPass, but verifying every loop in the
710 // function each time verifyAnalysis is called is very expensive. The
Dan Gohman4dbb3012009-09-28 00:27:48 +0000711 // -verify-loop-info option can enable this. In order to perform some
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000712 // checking by default, LoopPass has been taught to call verifyLoop manually
713 // during loop pass sequences.
Chandler Carruth691addc2015-01-18 01:25:51 +0000714 if (VerifyLoopInfo)
715 LI.verify();
Dan Gohman3ddbc242009-09-08 15:45:00 +0000716}
717
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000718void LoopInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerc8e66542002-04-27 06:56:12 +0000719 AU.setPreservesAll();
Chandler Carruth73523022014-01-13 13:07:17 +0000720 AU.addRequired<DominatorTreeWrapperPass>();
Chris Lattnerccf571a2002-01-31 00:42:27 +0000721}
Chris Lattnerb1d782b2009-08-23 05:17:37 +0000722
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000723void LoopInfoWrapperPass::print(raw_ostream &OS, const Module *) const {
Chandler Carruth691addc2015-01-18 01:25:51 +0000724 LI.print(OS);
Chris Lattnerb1d782b2009-08-23 05:17:37 +0000725}
726
Andrew Trick78b40c32011-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}