blob: 30f7ef3924223d706d055b7c310627b1c4e0d6a9 [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"
Hal Finkel2f688682016-05-25 21:42:37 +000025#include "llvm/IR/DebugLoc.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000026#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000027#include "llvm/IR/Instructions.h"
Philip Reames5a3f5f72014-10-21 00:13:20 +000028#include "llvm/IR/LLVMContext.h"
Pekka Jaaskelainen0d237252013-02-13 18:08:57 +000029#include "llvm/IR/Metadata.h"
Chandler Carruthaaf0b4c2015-01-20 10:58:50 +000030#include "llvm/IR/PassManager.h"
Dan Gohman4dbb3012009-09-28 00:27:48 +000031#include "llvm/Support/CommandLine.h"
Dan Gohmanc3f21372010-01-05 21:08:02 +000032#include "llvm/Support/Debug.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000033#include "llvm/Support/raw_ostream.h"
Chris Lattner6de99422001-11-26 18:41:20 +000034#include <algorithm>
Chris Lattner55b7ef52004-04-12 20:26:17 +000035using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000036
Andrew Trickcda51d42012-06-20 03:42:09 +000037// Explicitly instantiate methods in LoopInfoImpl.h for IR-level Loops.
38template class llvm::LoopBase<BasicBlock, Loop>;
39template class llvm::LoopInfoBase<BasicBlock, Loop>;
40
Dan Gohman4dbb3012009-09-28 00:27:48 +000041// Always verify loopinfo if expensive checking is enabled.
Filipe Cabecinhas0da99372016-04-29 15:22:48 +000042#ifdef EXPENSIVE_CHECKS
Dan Gohmanb29cda92010-04-15 17:08:50 +000043static bool VerifyLoopInfo = true;
Dan Gohman4dbb3012009-09-28 00:27:48 +000044#else
Dan Gohmanb29cda92010-04-15 17:08:50 +000045static bool VerifyLoopInfo = false;
Dan Gohman4dbb3012009-09-28 00:27:48 +000046#endif
47static cl::opt<bool,true>
48VerifyLoopInfoX("verify-loop-info", cl::location(VerifyLoopInfo),
49 cl::desc("Verify loop info (time consuming)"));
50
Chris Lattnerccf571a2002-01-31 00:42:27 +000051//===----------------------------------------------------------------------===//
Chris Lattner78dd56f2002-04-28 16:21:30 +000052// Loop implementation
Chris Lattnerccf571a2002-01-31 00:42:27 +000053//
Misha Brukman3845be22002-10-11 05:31:10 +000054
Pete Cooper016daa62015-05-13 01:12:06 +000055bool Loop::isLoopInvariant(const Value *V) const {
56 if (const Instruction *I = dyn_cast<Instruction>(V))
Chris Lattnerda24b9a2010-09-06 01:05:37 +000057 return !contains(I);
Dan Gohman80a99422009-07-13 22:02:44 +000058 return true; // All non-instructions are loop invariant
59}
60
Pete Cooper016daa62015-05-13 01:12:06 +000061bool Loop::hasLoopInvariantOperands(const Instruction *I) const {
Pete Coopera264dc02015-05-13 22:19:13 +000062 return all_of(I->operands(), [this](Value *V) { return isLoopInvariant(V); });
Dan Gohman6f6d8642009-07-14 01:06:29 +000063}
64
Dan Gohmanc43e4792009-07-15 01:25:43 +000065bool Loop::makeLoopInvariant(Value *V, bool &Changed,
66 Instruction *InsertPt) const {
Dan Gohman6f6d8642009-07-14 01:06:29 +000067 if (Instruction *I = dyn_cast<Instruction>(V))
Dan Gohmanc43e4792009-07-15 01:25:43 +000068 return makeLoopInvariant(I, Changed, InsertPt);
Dan Gohman6f6d8642009-07-14 01:06:29 +000069 return true; // All non-instructions are loop-invariant.
70}
71
Dan Gohmanc43e4792009-07-15 01:25:43 +000072bool Loop::makeLoopInvariant(Instruction *I, bool &Changed,
73 Instruction *InsertPt) const {
Dan Gohman6f6d8642009-07-14 01:06:29 +000074 // Test if the value is already loop-invariant.
75 if (isLoopInvariant(I))
76 return true;
Dan Gohman75d7d5e2011-12-14 23:49:11 +000077 if (!isSafeToSpeculativelyExecute(I))
Dan Gohman6f6d8642009-07-14 01:06:29 +000078 return false;
Eli Friedmanb8f6a4f2009-07-17 04:28:42 +000079 if (I->mayReadFromMemory())
Dan Gohman6f6d8642009-07-14 01:06:29 +000080 return false;
David Majnemer654e1302015-07-31 17:58:14 +000081 // EH block instructions are immobile.
82 if (I->isEHPad())
Bill Wendlinga9ee09f2011-08-17 20:36:44 +000083 return false;
Dan Gohman6f6d8642009-07-14 01:06:29 +000084 // Determine the insertion point, unless one was given.
85 if (!InsertPt) {
86 BasicBlock *Preheader = getLoopPreheader();
87 // Without a preheader, hoisting is not feasible.
88 if (!Preheader)
89 return false;
90 InsertPt = Preheader->getTerminator();
91 }
92 // Don't hoist instructions with loop-variant operands.
Sanjay Patel960e5342016-01-15 00:08:10 +000093 for (Value *Operand : I->operands())
94 if (!makeLoopInvariant(Operand, Changed, InsertPt))
Dan Gohman6f6d8642009-07-14 01:06:29 +000095 return false;
Andrew Trickf898cbd2011-08-03 23:45:50 +000096
Dan Gohman6f6d8642009-07-14 01:06:29 +000097 // Hoist.
98 I->moveBefore(InsertPt);
Igor Laevsky7310c682015-11-18 14:50:18 +000099
100 // There is possibility of hoisting this instruction above some arbitrary
101 // condition. Any metadata defined on it can be control dependent on this
102 // condition. Conservatively strip it here so that we don't give any wrong
103 // information to the optimizer.
104 I->dropUnknownNonDebugMetadata();
105
Dan Gohmanc43e4792009-07-15 01:25:43 +0000106 Changed = true;
Dan Gohman6f6d8642009-07-14 01:06:29 +0000107 return true;
108}
109
Dan Gohman80a99422009-07-13 22:02:44 +0000110PHINode *Loop::getCanonicalInductionVariable() const {
111 BasicBlock *H = getHeader();
112
Craig Topper9f008862014-04-15 04:59:12 +0000113 BasicBlock *Incoming = nullptr, *Backedge = nullptr;
Dan Gohmanacafc612010-07-23 21:25:16 +0000114 pred_iterator PI = pred_begin(H);
115 assert(PI != pred_end(H) &&
Dan Gohman80a99422009-07-13 22:02:44 +0000116 "Loop must have at least one backedge!");
117 Backedge = *PI++;
Craig Topper9f008862014-04-15 04:59:12 +0000118 if (PI == pred_end(H)) return nullptr; // dead loop
Dan Gohman80a99422009-07-13 22:02:44 +0000119 Incoming = *PI++;
Craig Topper9f008862014-04-15 04:59:12 +0000120 if (PI != pred_end(H)) return nullptr; // multiple backedges?
Dan Gohman80a99422009-07-13 22:02:44 +0000121
122 if (contains(Incoming)) {
123 if (contains(Backedge))
Craig Topper9f008862014-04-15 04:59:12 +0000124 return nullptr;
Dan Gohman80a99422009-07-13 22:02:44 +0000125 std::swap(Incoming, Backedge);
126 } else if (!contains(Backedge))
Craig Topper9f008862014-04-15 04:59:12 +0000127 return nullptr;
Dan Gohman80a99422009-07-13 22:02:44 +0000128
129 // Loop over all of the PHI nodes, looking for a canonical indvar.
130 for (BasicBlock::iterator I = H->begin(); isa<PHINode>(I); ++I) {
131 PHINode *PN = cast<PHINode>(I);
132 if (ConstantInt *CI =
133 dyn_cast<ConstantInt>(PN->getIncomingValueForBlock(Incoming)))
134 if (CI->isNullValue())
135 if (Instruction *Inc =
136 dyn_cast<Instruction>(PN->getIncomingValueForBlock(Backedge)))
137 if (Inc->getOpcode() == Instruction::Add &&
138 Inc->getOperand(0) == PN)
139 if (ConstantInt *CI = dyn_cast<ConstantInt>(Inc->getOperand(1)))
140 if (CI->equalsInt(1))
141 return PN;
142 }
Craig Topper9f008862014-04-15 04:59:12 +0000143 return nullptr;
Dan Gohman80a99422009-07-13 22:02:44 +0000144}
145
Dan Gohman2734ebd2010-03-10 19:38:49 +0000146bool Loop::isLCSSAForm(DominatorTree &DT) const {
Sanjay Patel960e5342016-01-15 00:08:10 +0000147 for (BasicBlock *BB : this->blocks()) {
148 for (Instruction &I : *BB) {
Andrew Kaylor123048d2015-12-18 18:12:35 +0000149 // Tokens can't be used in PHI nodes and live-out tokens prevent loop
150 // optimizations, so for the purposes of considered LCSSA form, we
151 // can ignore them.
Sanjay Patel960e5342016-01-15 00:08:10 +0000152 if (I.getType()->isTokenTy())
Andrew Kaylor123048d2015-12-18 18:12:35 +0000153 continue;
154
Sanjay Patel960e5342016-01-15 00:08:10 +0000155 for (Use &U : I.uses()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000156 Instruction *UI = cast<Instruction>(U.getUser());
157 BasicBlock *UserBB = UI->getParent();
158 if (PHINode *P = dyn_cast<PHINode>(UI))
159 UserBB = P->getIncomingBlock(U);
Dan Gohman80a99422009-07-13 22:02:44 +0000160
Dan Gohman93452ce2010-03-09 01:53:33 +0000161 // Check the current block, as a fast-path, before checking whether
162 // the use is anywhere in the loop. Most values are used in the same
163 // block they are defined in. Also, blocks not reachable from the
164 // entry are special; uses in them don't need to go through PHIs.
165 if (UserBB != BB &&
Wan Xiaofeibe640b22013-10-26 03:08:02 +0000166 !contains(UserBB) &&
Dan Gohman2734ebd2010-03-10 19:38:49 +0000167 DT.isReachableFromEntry(UserBB))
Dan Gohman80a99422009-07-13 22:02:44 +0000168 return false;
169 }
Andrew Kaylor123048d2015-12-18 18:12:35 +0000170 }
Dan Gohman80a99422009-07-13 22:02:44 +0000171 }
172
173 return true;
174}
Dan Gohman1511f702009-07-16 16:16:23 +0000175
Sanjoy Das683bf072015-12-08 00:13:21 +0000176bool Loop::isRecursivelyLCSSAForm(DominatorTree &DT) const {
177 if (!isLCSSAForm(DT))
178 return false;
179
180 return std::all_of(begin(), end(), [&](const Loop *L) {
181 return L->isRecursivelyLCSSAForm(DT);
182 });
183}
184
Dan Gohman1511f702009-07-16 16:16:23 +0000185bool Loop::isLoopSimplifyForm() const {
Dan Gohmane3a17062009-11-05 19:21:41 +0000186 // Normal-form loops have a preheader, a single backedge, and all of their
187 // exits have all their predecessors inside the loop.
188 return getLoopPreheader() && getLoopLatch() && hasDedicatedExits();
189}
190
Sanjay Patel784b5e32016-01-14 23:23:04 +0000191// Routines that reform the loop CFG and split edges often fail on indirectbr.
Andrew Trick4442bfe2012-04-10 05:14:42 +0000192bool Loop::isSafeToClone() const {
James Molloy4f6fb952012-12-20 16:04:27 +0000193 // Return false if any loop blocks contain indirectbrs, or there are any calls
194 // to noduplicate functions.
Sanjay Patel960e5342016-01-15 00:08:10 +0000195 for (BasicBlock *BB : this->blocks()) {
196 if (isa<IndirectBrInst>(BB->getTerminator()))
Andrew Trick4442bfe2012-04-10 05:14:42 +0000197 return false;
Jakub Staszak9dca4b32013-11-13 20:18:38 +0000198
David Majnemer3d90bb72016-05-03 03:57:40 +0000199 for (Instruction &I : *BB)
200 if (auto CS = CallSite(&I))
201 if (CS.cannotDuplicate())
James Molloy4f6fb952012-12-20 16:04:27 +0000202 return false;
Andrew Trick4442bfe2012-04-10 05:14:42 +0000203 }
204 return true;
205}
206
Paul Redmond5fdf8362013-05-28 20:00:34 +0000207MDNode *Loop::getLoopID() const {
Craig Topper9f008862014-04-15 04:59:12 +0000208 MDNode *LoopID = nullptr;
Paul Redmond5fdf8362013-05-28 20:00:34 +0000209 if (isLoopSimplifyForm()) {
Duncan P. N. Exon Smith1d15a9f2016-03-25 00:35:38 +0000210 LoopID = getLoopLatch()->getTerminator()->getMetadata(LLVMContext::MD_loop);
Paul Redmond5fdf8362013-05-28 20:00:34 +0000211 } else {
212 // Go through each predecessor of the loop header and check the
213 // terminator for the metadata.
214 BasicBlock *H = getHeader();
Sanjay Patel960e5342016-01-15 00:08:10 +0000215 for (BasicBlock *BB : this->blocks()) {
216 TerminatorInst *TI = BB->getTerminator();
Craig Topper9f008862014-04-15 04:59:12 +0000217 MDNode *MD = nullptr;
Paul Redmond5fdf8362013-05-28 20:00:34 +0000218
219 // Check if this terminator branches to the loop header.
Sanjay Patel960e5342016-01-15 00:08:10 +0000220 for (BasicBlock *Successor : TI->successors()) {
221 if (Successor == H) {
Duncan P. N. Exon Smith1d15a9f2016-03-25 00:35:38 +0000222 MD = TI->getMetadata(LLVMContext::MD_loop);
Paul Redmond5fdf8362013-05-28 20:00:34 +0000223 break;
224 }
225 }
226 if (!MD)
Craig Topper9f008862014-04-15 04:59:12 +0000227 return nullptr;
Paul Redmond5fdf8362013-05-28 20:00:34 +0000228
229 if (!LoopID)
230 LoopID = MD;
231 else if (MD != LoopID)
Craig Topper9f008862014-04-15 04:59:12 +0000232 return nullptr;
Paul Redmond5fdf8362013-05-28 20:00:34 +0000233 }
234 }
235 if (!LoopID || LoopID->getNumOperands() == 0 ||
236 LoopID->getOperand(0) != LoopID)
Craig Topper9f008862014-04-15 04:59:12 +0000237 return nullptr;
Paul Redmond5fdf8362013-05-28 20:00:34 +0000238 return LoopID;
239}
240
241void Loop::setLoopID(MDNode *LoopID) const {
242 assert(LoopID && "Loop ID should not be null");
243 assert(LoopID->getNumOperands() > 0 && "Loop ID needs at least one operand");
244 assert(LoopID->getOperand(0) == LoopID && "Loop ID should refer to itself");
245
246 if (isLoopSimplifyForm()) {
Duncan P. N. Exon Smith1d15a9f2016-03-25 00:35:38 +0000247 getLoopLatch()->getTerminator()->setMetadata(LLVMContext::MD_loop, LoopID);
Paul Redmond5fdf8362013-05-28 20:00:34 +0000248 return;
249 }
250
251 BasicBlock *H = getHeader();
Sanjay Patel960e5342016-01-15 00:08:10 +0000252 for (BasicBlock *BB : this->blocks()) {
253 TerminatorInst *TI = BB->getTerminator();
254 for (BasicBlock *Successor : TI->successors()) {
255 if (Successor == H)
Duncan P. N. Exon Smith1d15a9f2016-03-25 00:35:38 +0000256 TI->setMetadata(LLVMContext::MD_loop, LoopID);
Paul Redmond5fdf8362013-05-28 20:00:34 +0000257 }
258 }
259}
260
Pekka Jaaskelainen0d237252013-02-13 18:08:57 +0000261bool Loop::isAnnotatedParallel() const {
Sanjay Patel6435c6e2016-01-17 23:18:05 +0000262 MDNode *DesiredLoopIdMetadata = getLoopID();
Pekka Jaaskelainen0d237252013-02-13 18:08:57 +0000263
Sanjay Patel6435c6e2016-01-17 23:18:05 +0000264 if (!DesiredLoopIdMetadata)
Pekka Jaaskelainen0d237252013-02-13 18:08:57 +0000265 return false;
266
267 // The loop branch contains the parallel loop metadata. In order to ensure
268 // that any parallel-loop-unaware optimization pass hasn't added loop-carried
269 // dependencies (thus converted the loop back to a sequential loop), check
270 // that all the memory instructions in the loop contain parallelism metadata
271 // that point to the same unique "loop id metadata" the loop branch does.
Sanjay Patel960e5342016-01-15 00:08:10 +0000272 for (BasicBlock *BB : this->blocks()) {
273 for (Instruction &I : *BB) {
274 if (!I.mayReadOrWriteMemory())
Pekka Jaaskelainen0d237252013-02-13 18:08:57 +0000275 continue;
276
Pekka Jaaskelainen0d237252013-02-13 18:08:57 +0000277 // The memory instruction can refer to the loop identifier metadata
278 // directly or indirectly through another list metadata (in case of
279 // nested parallel loops). The loop identifier metadata refers to
280 // itself so we can check both cases with the same routine.
Sanjay Patel6435c6e2016-01-17 23:18:05 +0000281 MDNode *LoopIdMD =
Sanjay Patel960e5342016-01-15 00:08:10 +0000282 I.getMetadata(LLVMContext::MD_mem_parallel_loop_access);
Jakub Staszak9dca4b32013-11-13 20:18:38 +0000283
Sanjay Patel6435c6e2016-01-17 23:18:05 +0000284 if (!LoopIdMD)
Jakub Staszak9dca4b32013-11-13 20:18:38 +0000285 return false;
286
Sanjay Patel6435c6e2016-01-17 23:18:05 +0000287 bool LoopIdMDFound = false;
288 for (const MDOperand &MDOp : LoopIdMD->operands()) {
289 if (MDOp == DesiredLoopIdMetadata) {
290 LoopIdMDFound = true;
Pekka Jaaskelainen0d237252013-02-13 18:08:57 +0000291 break;
292 }
293 }
294
Sanjay Patel6435c6e2016-01-17 23:18:05 +0000295 if (!LoopIdMDFound)
Pekka Jaaskelainen0d237252013-02-13 18:08:57 +0000296 return false;
297 }
298 }
299 return true;
300}
301
Hal Finkel2f688682016-05-25 21:42:37 +0000302DebugLoc Loop::getStartLoc() const {
303 // If we have a debug location in the loop ID, then use it.
304 if (MDNode *LoopID = getLoopID())
305 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i)
306 if (DILocation *L = dyn_cast<DILocation>(LoopID->getOperand(i)))
307 return DebugLoc(L);
308
309 // Try the pre-header first.
310 if (BasicBlock *PHeadBB = getLoopPreheader())
311 if (DebugLoc DL = PHeadBB->getTerminator()->getDebugLoc())
312 return DL;
313
314 // If we have no pre-header or there are no instructions with debug
315 // info in it, try the header.
316 if (BasicBlock *HeadBB = getHeader())
317 return HeadBB->getTerminator()->getDebugLoc();
318
319 return DebugLoc();
320}
321
Dan Gohmane3a17062009-11-05 19:21:41 +0000322bool Loop::hasDedicatedExits() const {
Dan Gohman1511f702009-07-16 16:16:23 +0000323 // Each predecessor of each exit block of a normal loop is contained
324 // within the loop.
325 SmallVector<BasicBlock *, 4> ExitBlocks;
326 getExitBlocks(ExitBlocks);
Sanjay Patel960e5342016-01-15 00:08:10 +0000327 for (BasicBlock *BB : ExitBlocks)
328 for (BasicBlock *Predecessor : predecessors(BB))
329 if (!contains(Predecessor))
Dan Gohman1511f702009-07-16 16:16:23 +0000330 return false;
331 // All the requirements are met.
332 return true;
333}
334
Dan Gohman3a0ce3e2009-09-03 16:10:48 +0000335void
336Loop::getUniqueExitBlocks(SmallVectorImpl<BasicBlock *> &ExitBlocks) const {
Dan Gohman84ba0392009-12-11 20:05:23 +0000337 assert(hasDedicatedExits() &&
338 "getUniqueExitBlocks assumes the loop has canonical form exits!");
Dan Gohman3ddbc242009-09-08 15:45:00 +0000339
Sanjay Patel6435c6e2016-01-17 23:18:05 +0000340 SmallVector<BasicBlock *, 32> SwitchExitBlocks;
Sanjay Patel960e5342016-01-15 00:08:10 +0000341 for (BasicBlock *BB : this->blocks()) {
Sanjay Patel6435c6e2016-01-17 23:18:05 +0000342 SwitchExitBlocks.clear();
Sanjay Patel960e5342016-01-15 00:08:10 +0000343 for (BasicBlock *Successor : successors(BB)) {
344 // If block is inside the loop then it is not an exit block.
345 if (contains(Successor))
Dan Gohman3a0ce3e2009-09-03 16:10:48 +0000346 continue;
347
Sanjay Patel960e5342016-01-15 00:08:10 +0000348 pred_iterator PI = pred_begin(Successor);
Sanjay Patel6435c6e2016-01-17 23:18:05 +0000349 BasicBlock *FirstPred = *PI;
Dan Gohman3a0ce3e2009-09-03 16:10:48 +0000350
351 // If current basic block is this exit block's first predecessor
352 // then only insert exit block in to the output ExitBlocks vector.
353 // This ensures that same exit block is not inserted twice into
354 // ExitBlocks vector.
Sanjay Patel6435c6e2016-01-17 23:18:05 +0000355 if (BB != FirstPred)
Dan Gohman3a0ce3e2009-09-03 16:10:48 +0000356 continue;
357
358 // If a terminator has more then two successors, for example SwitchInst,
359 // then it is possible that there are multiple edges from current block
360 // to one exit block.
Sanjay Patel960e5342016-01-15 00:08:10 +0000361 if (std::distance(succ_begin(BB), succ_end(BB)) <= 2) {
362 ExitBlocks.push_back(Successor);
Dan Gohman3a0ce3e2009-09-03 16:10:48 +0000363 continue;
364 }
365
366 // In case of multiple edges from current block to exit block, collect
367 // only one edge in ExitBlocks. Use switchExitBlocks to keep track of
368 // duplicate edges.
Sanjay Patel6435c6e2016-01-17 23:18:05 +0000369 if (std::find(SwitchExitBlocks.begin(), SwitchExitBlocks.end(), Successor)
370 == SwitchExitBlocks.end()) {
371 SwitchExitBlocks.push_back(Successor);
Sanjay Patel960e5342016-01-15 00:08:10 +0000372 ExitBlocks.push_back(Successor);
Dan Gohman3a0ce3e2009-09-03 16:10:48 +0000373 }
374 }
375 }
376}
377
Dan Gohman3a0ce3e2009-09-03 16:10:48 +0000378BasicBlock *Loop::getUniqueExitBlock() const {
379 SmallVector<BasicBlock *, 8> UniqueExitBlocks;
380 getUniqueExitBlocks(UniqueExitBlocks);
381 if (UniqueExitBlocks.size() == 1)
382 return UniqueExitBlocks[0];
Craig Topper9f008862014-04-15 04:59:12 +0000383 return nullptr;
Dan Gohman3a0ce3e2009-09-03 16:10:48 +0000384}
385
Manman Ren49d684e2012-09-12 05:06:18 +0000386#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Yaron Kereneb2a2542016-01-29 20:50:44 +0000387LLVM_DUMP_METHOD void Loop::dump() const {
Dan Gohmanc3f21372010-01-05 21:08:02 +0000388 print(dbgs());
389}
Manman Renc3366cc2012-09-06 19:55:56 +0000390#endif
Dan Gohmanc3f21372010-01-05 21:08:02 +0000391
Chris Lattner26750072002-07-27 01:12:17 +0000392//===----------------------------------------------------------------------===//
Andrew Trickd3530b92011-08-10 23:22:57 +0000393// UnloopUpdater implementation
394//
395
Benjamin Kramer4938edb2011-08-19 01:42:18 +0000396namespace {
Andrew Trickd3530b92011-08-10 23:22:57 +0000397/// Find the new parent loop for all blocks within the "unloop" whose last
398/// backedges has just been removed.
399class UnloopUpdater {
Silviu Baranga24dbd2e2016-05-13 14:54:50 +0000400 Loop &Unloop;
Andrew Trickd3530b92011-08-10 23:22:57 +0000401 LoopInfo *LI;
402
403 LoopBlocksDFS DFS;
404
405 // Map unloop's immediate subloops to their nearest reachable parents. Nested
406 // loops within these subloops will not change parents. However, an immediate
407 // subloop's new parent will be the nearest loop reachable from either its own
408 // exits *or* any of its nested loop's exits.
409 DenseMap<Loop*, Loop*> SubloopParents;
410
411 // Flag the presence of an irreducible backedge whose destination is a block
412 // directly contained by the original unloop.
413 bool FoundIB;
414
415public:
416 UnloopUpdater(Loop *UL, LoopInfo *LInfo) :
Silviu Baranga24dbd2e2016-05-13 14:54:50 +0000417 Unloop(*UL), LI(LInfo), DFS(UL), FoundIB(false) {}
Andrew Trickd3530b92011-08-10 23:22:57 +0000418
419 void updateBlockParents();
420
Andrew Trickc12c30a2011-08-11 20:27:32 +0000421 void removeBlocksFromAncestors();
422
Andrew Trickd3530b92011-08-10 23:22:57 +0000423 void updateSubloopParents();
424
425protected:
426 Loop *getNearestLoop(BasicBlock *BB, Loop *BBLoop);
427};
Benjamin Kramer4938edb2011-08-19 01:42:18 +0000428} // end anonymous namespace
Andrew Trickd3530b92011-08-10 23:22:57 +0000429
Sanjay Patel784b5e32016-01-14 23:23:04 +0000430/// Update the parent loop for all blocks that are directly contained within the
431/// original "unloop".
Andrew Trickd3530b92011-08-10 23:22:57 +0000432void UnloopUpdater::updateBlockParents() {
Silviu Baranga24dbd2e2016-05-13 14:54:50 +0000433 if (Unloop.getNumBlocks()) {
Andrew Trickd3530b92011-08-10 23:22:57 +0000434 // Perform a post order CFG traversal of all blocks within this loop,
435 // propagating the nearest loop from sucessors to predecessors.
436 LoopBlocksTraversal Traversal(DFS, LI);
Benjamin Krameraa209152016-06-26 17:27:42 +0000437 for (BasicBlock *POI : Traversal) {
Andrew Trickd3530b92011-08-10 23:22:57 +0000438
Benjamin Krameraa209152016-06-26 17:27:42 +0000439 Loop *L = LI->getLoopFor(POI);
440 Loop *NL = getNearestLoop(POI, L);
Andrew Trickd3530b92011-08-10 23:22:57 +0000441
442 if (NL != L) {
443 // For reducible loops, NL is now an ancestor of Unloop.
Silviu Baranga24dbd2e2016-05-13 14:54:50 +0000444 assert((NL != &Unloop && (!NL || NL->contains(&Unloop))) &&
Andrew Trickd3530b92011-08-10 23:22:57 +0000445 "uninitialized successor");
Benjamin Krameraa209152016-06-26 17:27:42 +0000446 LI->changeLoopFor(POI, NL);
Andrew Trickd3530b92011-08-10 23:22:57 +0000447 }
448 else {
449 // Or the current block is part of a subloop, in which case its parent
450 // is unchanged.
Silviu Baranga24dbd2e2016-05-13 14:54:50 +0000451 assert((FoundIB || Unloop.contains(L)) && "uninitialized successor");
Andrew Trickd3530b92011-08-10 23:22:57 +0000452 }
453 }
454 }
455 // Each irreducible loop within the unloop induces a round of iteration using
456 // the DFS result cached by Traversal.
457 bool Changed = FoundIB;
458 for (unsigned NIters = 0; Changed; ++NIters) {
Silviu Baranga24dbd2e2016-05-13 14:54:50 +0000459 assert(NIters < Unloop.getNumBlocks() && "runaway iterative algorithm");
Andrew Trickd3530b92011-08-10 23:22:57 +0000460
461 // Iterate over the postorder list of blocks, propagating the nearest loop
462 // from successors to predecessors as before.
463 Changed = false;
464 for (LoopBlocksDFS::POIterator POI = DFS.beginPostorder(),
465 POE = DFS.endPostorder(); POI != POE; ++POI) {
466
467 Loop *L = LI->getLoopFor(*POI);
468 Loop *NL = getNearestLoop(*POI, L);
469 if (NL != L) {
Silviu Baranga24dbd2e2016-05-13 14:54:50 +0000470 assert(NL != &Unloop && (!NL || NL->contains(&Unloop)) &&
Andrew Trickd3530b92011-08-10 23:22:57 +0000471 "uninitialized successor");
472 LI->changeLoopFor(*POI, NL);
473 Changed = true;
474 }
475 }
476 }
477}
478
Sanjay Patel784b5e32016-01-14 23:23:04 +0000479/// Remove unloop's blocks from all ancestors below their new parents.
Andrew Trickc12c30a2011-08-11 20:27:32 +0000480void UnloopUpdater::removeBlocksFromAncestors() {
Andrew Trick6b4d5782011-11-18 03:42:41 +0000481 // Remove all unloop's blocks (including those in nested subloops) from
482 // ancestors below the new parent loop.
Silviu Baranga24dbd2e2016-05-13 14:54:50 +0000483 for (Loop::block_iterator BI = Unloop.block_begin(),
484 BE = Unloop.block_end(); BI != BE; ++BI) {
Andrew Trick6b4d5782011-11-18 03:42:41 +0000485 Loop *OuterParent = LI->getLoopFor(*BI);
Silviu Baranga24dbd2e2016-05-13 14:54:50 +0000486 if (Unloop.contains(OuterParent)) {
487 while (OuterParent->getParentLoop() != &Unloop)
Andrew Trick6b4d5782011-11-18 03:42:41 +0000488 OuterParent = OuterParent->getParentLoop();
489 OuterParent = SubloopParents[OuterParent];
490 }
Andrew Trickc12c30a2011-08-11 20:27:32 +0000491 // Remove blocks from former Ancestors except Unloop itself which will be
492 // deleted.
Silviu Baranga24dbd2e2016-05-13 14:54:50 +0000493 for (Loop *OldParent = Unloop.getParentLoop(); OldParent != OuterParent;
Andrew Trickc12c30a2011-08-11 20:27:32 +0000494 OldParent = OldParent->getParentLoop()) {
495 assert(OldParent && "new loop is not an ancestor of the original");
496 OldParent->removeBlockFromLoop(*BI);
497 }
498 }
499}
500
Sanjay Patel784b5e32016-01-14 23:23:04 +0000501/// Update the parent loop for all subloops directly nested within unloop.
Andrew Trickd3530b92011-08-10 23:22:57 +0000502void UnloopUpdater::updateSubloopParents() {
Silviu Baranga24dbd2e2016-05-13 14:54:50 +0000503 while (!Unloop.empty()) {
504 Loop *Subloop = *std::prev(Unloop.end());
505 Unloop.removeChildLoop(std::prev(Unloop.end()));
Andrew Trickd3530b92011-08-10 23:22:57 +0000506
507 assert(SubloopParents.count(Subloop) && "DFS failed to visit subloop");
Benjamin Kramerf29db272012-08-22 15:37:57 +0000508 if (Loop *Parent = SubloopParents[Subloop])
509 Parent->addChildLoop(Subloop);
Andrew Trick147d9cd2011-08-26 03:06:34 +0000510 else
511 LI->addTopLevelLoop(Subloop);
Andrew Trickd3530b92011-08-10 23:22:57 +0000512 }
513}
514
Sanjay Patel784b5e32016-01-14 23:23:04 +0000515/// Return the nearest parent loop among this block's successors. If a successor
516/// is a subloop header, consider its parent to be the nearest parent of the
517/// subloop's exits.
Andrew Trickd3530b92011-08-10 23:22:57 +0000518///
519/// For subloop blocks, simply update SubloopParents and return NULL.
520Loop *UnloopUpdater::getNearestLoop(BasicBlock *BB, Loop *BBLoop) {
521
Andrew Trick266ab102011-08-11 17:54:58 +0000522 // Initially for blocks directly contained by Unloop, NearLoop == Unloop and
523 // is considered uninitialized.
Andrew Trickd3530b92011-08-10 23:22:57 +0000524 Loop *NearLoop = BBLoop;
525
Craig Topper9f008862014-04-15 04:59:12 +0000526 Loop *Subloop = nullptr;
Silviu Baranga24dbd2e2016-05-13 14:54:50 +0000527 if (NearLoop != &Unloop && Unloop.contains(NearLoop)) {
Andrew Trickd3530b92011-08-10 23:22:57 +0000528 Subloop = NearLoop;
529 // Find the subloop ancestor that is directly contained within Unloop.
Silviu Baranga24dbd2e2016-05-13 14:54:50 +0000530 while (Subloop->getParentLoop() != &Unloop) {
Andrew Trickd3530b92011-08-10 23:22:57 +0000531 Subloop = Subloop->getParentLoop();
532 assert(Subloop && "subloop is not an ancestor of the original loop");
533 }
534 // Get the current nearest parent of the Subloop exits, initially Unloop.
Benjamin Kramerf29db272012-08-22 15:37:57 +0000535 NearLoop =
Silviu Baranga24dbd2e2016-05-13 14:54:50 +0000536 SubloopParents.insert(std::make_pair(Subloop, &Unloop)).first->second;
Andrew Trickd3530b92011-08-10 23:22:57 +0000537 }
538
539 succ_iterator I = succ_begin(BB), E = succ_end(BB);
540 if (I == E) {
541 assert(!Subloop && "subloop blocks must have a successor");
Craig Topper9f008862014-04-15 04:59:12 +0000542 NearLoop = nullptr; // unloop blocks may now exit the function.
Andrew Trickd3530b92011-08-10 23:22:57 +0000543 }
544 for (; I != E; ++I) {
545 if (*I == BB)
546 continue; // self loops are uninteresting
547
548 Loop *L = LI->getLoopFor(*I);
Silviu Baranga24dbd2e2016-05-13 14:54:50 +0000549 if (L == &Unloop) {
Andrew Trickd3530b92011-08-10 23:22:57 +0000550 // This successor has not been processed. This path must lead to an
551 // irreducible backedge.
552 assert((FoundIB || !DFS.hasPostorder(*I)) && "should have seen IB");
553 FoundIB = true;
554 }
Silviu Baranga24dbd2e2016-05-13 14:54:50 +0000555 if (L != &Unloop && Unloop.contains(L)) {
Andrew Trickd3530b92011-08-10 23:22:57 +0000556 // Successor is in a subloop.
557 if (Subloop)
558 continue; // Branching within subloops. Ignore it.
559
560 // BB branches from the original into a subloop header.
Silviu Baranga24dbd2e2016-05-13 14:54:50 +0000561 assert(L->getParentLoop() == &Unloop && "cannot skip into nested loops");
Andrew Trickd3530b92011-08-10 23:22:57 +0000562
563 // Get the current nearest parent of the Subloop's exits.
564 L = SubloopParents[L];
565 // L could be Unloop if the only exit was an irreducible backedge.
566 }
Silviu Baranga24dbd2e2016-05-13 14:54:50 +0000567 if (L == &Unloop) {
Andrew Trickd3530b92011-08-10 23:22:57 +0000568 continue;
569 }
570 // Handle critical edges from Unloop into a sibling loop.
Silviu Baranga24dbd2e2016-05-13 14:54:50 +0000571 if (L && !L->contains(&Unloop)) {
Andrew Trickd3530b92011-08-10 23:22:57 +0000572 L = L->getParentLoop();
573 }
574 // Remember the nearest parent loop among successors or subloop exits.
Silviu Baranga24dbd2e2016-05-13 14:54:50 +0000575 if (NearLoop == &Unloop || !NearLoop || NearLoop->contains(L))
Andrew Trickd3530b92011-08-10 23:22:57 +0000576 NearLoop = L;
577 }
578 if (Subloop) {
579 SubloopParents[Subloop] = NearLoop;
580 return BBLoop;
581 }
582 return NearLoop;
583}
584
Cong Hou9b4f6b22015-07-16 23:23:35 +0000585LoopInfo::LoopInfo(const DominatorTreeBase<BasicBlock> &DomTree) {
586 analyze(DomTree);
587}
588
Justin Bognere9fb228d2016-01-08 19:08:53 +0000589void LoopInfo::markAsRemoved(Loop *Unloop) {
590 assert(!Unloop->isInvalid() && "Loop has already been removed");
591 Unloop->invalidate();
592 RemovedLoops.push_back(Unloop);
Andrew Trickd3530b92011-08-10 23:22:57 +0000593
594 // First handle the special case of no parent loop to simplify the algorithm.
595 if (!Unloop->getParentLoop()) {
596 // Since BBLoop had no parent, Unloop blocks are no longer in a loop.
597 for (Loop::block_iterator I = Unloop->block_begin(),
Chandler Carruth691addc2015-01-18 01:25:51 +0000598 E = Unloop->block_end();
599 I != E; ++I) {
Andrew Trickd3530b92011-08-10 23:22:57 +0000600
601 // Don't reparent blocks in subloops.
602 if (getLoopFor(*I) != Unloop)
603 continue;
604
605 // Blocks no longer have a parent but are still referenced by Unloop until
606 // the Unloop object is deleted.
Chandler Carruth691addc2015-01-18 01:25:51 +0000607 changeLoopFor(*I, nullptr);
Andrew Trickd3530b92011-08-10 23:22:57 +0000608 }
609
610 // Remove the loop from the top-level LoopInfo object.
Chandler Carruth691addc2015-01-18 01:25:51 +0000611 for (iterator I = begin();; ++I) {
612 assert(I != end() && "Couldn't find loop");
Andrew Trickd3530b92011-08-10 23:22:57 +0000613 if (*I == Unloop) {
Chandler Carruth691addc2015-01-18 01:25:51 +0000614 removeLoop(I);
Andrew Trickd3530b92011-08-10 23:22:57 +0000615 break;
616 }
617 }
618
619 // Move all of the subloops to the top-level.
620 while (!Unloop->empty())
Chandler Carruth691addc2015-01-18 01:25:51 +0000621 addTopLevelLoop(Unloop->removeChildLoop(std::prev(Unloop->end())));
Andrew Trickd3530b92011-08-10 23:22:57 +0000622
623 return;
624 }
625
626 // Update the parent loop for all blocks within the loop. Blocks within
627 // subloops will not change parents.
628 UnloopUpdater Updater(Unloop, this);
629 Updater.updateBlockParents();
630
Andrew Trickc12c30a2011-08-11 20:27:32 +0000631 // Remove blocks from former ancestor loops.
632 Updater.removeBlocksFromAncestors();
Andrew Trickd3530b92011-08-10 23:22:57 +0000633
634 // Add direct subloops as children in their new parent loop.
635 Updater.updateSubloopParents();
636
637 // Remove unloop from its parent loop.
638 Loop *ParentLoop = Unloop->getParentLoop();
Duncan Sandsa41634e2011-08-12 14:54:45 +0000639 for (Loop::iterator I = ParentLoop->begin();; ++I) {
640 assert(I != ParentLoop->end() && "Couldn't find loop");
Andrew Trickd3530b92011-08-10 23:22:57 +0000641 if (*I == Unloop) {
642 ParentLoop->removeChildLoop(I);
643 break;
644 }
645 }
646}
647
Chandler Carruthb4faf132016-03-11 10:22:49 +0000648char LoopAnalysis::PassID;
NAKAMURA Takumidf0cd722016-02-28 17:17:00 +0000649
Chandler Carruthb47f8012016-03-11 11:05:24 +0000650LoopInfo LoopAnalysis::run(Function &F, AnalysisManager<Function> &AM) {
Chandler Carruthaaf0b4c2015-01-20 10:58:50 +0000651 // FIXME: Currently we create a LoopInfo from scratch for every function.
652 // This may prove to be too wasteful due to deallocating and re-allocating
653 // memory each time for the underlying map and vector datastructures. At some
654 // point it may prove worthwhile to use a freelist and recycle LoopInfo
655 // objects. I don't want to add that kind of complexity until the scope of
656 // the problem is better understood.
657 LoopInfo LI;
Chandler Carruthb47f8012016-03-11 11:05:24 +0000658 LI.analyze(AM.getResult<DominatorTreeAnalysis>(F));
Richard Trieu6ae37962015-04-30 23:07:00 +0000659 return LI;
Chandler Carruthaaf0b4c2015-01-20 10:58:50 +0000660}
661
662PreservedAnalyses LoopPrinterPass::run(Function &F,
Chandler Carruthb47f8012016-03-11 11:05:24 +0000663 AnalysisManager<Function> &AM) {
664 AM.getResult<LoopAnalysis>(F).print(OS);
Chandler Carruthaaf0b4c2015-01-20 10:58:50 +0000665 return PreservedAnalyses::all();
666}
667
Justin Bognerc2b98f02015-11-04 22:24:08 +0000668PrintLoopPass::PrintLoopPass() : OS(dbgs()) {}
669PrintLoopPass::PrintLoopPass(raw_ostream &OS, const std::string &Banner)
670 : OS(OS), Banner(Banner) {}
671
Chandler Carruth164a2aa62016-06-17 00:11:01 +0000672PreservedAnalyses PrintLoopPass::run(Loop &L, AnalysisManager<Loop> &) {
Justin Bognerc2b98f02015-11-04 22:24:08 +0000673 OS << Banner;
674 for (auto *Block : L.blocks())
675 if (Block)
676 Block->print(OS);
677 else
678 OS << "Printing <null> block";
679 return PreservedAnalyses::all();
680}
681
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000682//===----------------------------------------------------------------------===//
683// LoopInfo implementation
684//
685
686char LoopInfoWrapperPass::ID = 0;
687INITIALIZE_PASS_BEGIN(LoopInfoWrapperPass, "loops", "Natural Loop Information",
688 true, true)
689INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
690INITIALIZE_PASS_END(LoopInfoWrapperPass, "loops", "Natural Loop Information",
691 true, true)
692
693bool LoopInfoWrapperPass::runOnFunction(Function &) {
694 releaseMemory();
Cong Houd2c1d912015-07-16 18:23:57 +0000695 LI.analyze(getAnalysis<DominatorTreeWrapperPass>().getDomTree());
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000696 return false;
697}
698
699void LoopInfoWrapperPass::verifyAnalysis() const {
700 // LoopInfoWrapperPass is a FunctionPass, but verifying every loop in the
701 // function each time verifyAnalysis is called is very expensive. The
Dan Gohman4dbb3012009-09-28 00:27:48 +0000702 // -verify-loop-info option can enable this. In order to perform some
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000703 // checking by default, LoopPass has been taught to call verifyLoop manually
704 // during loop pass sequences.
Chandler Carruth691addc2015-01-18 01:25:51 +0000705 if (VerifyLoopInfo)
706 LI.verify();
Dan Gohman3ddbc242009-09-08 15:45:00 +0000707}
708
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000709void LoopInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerc8e66542002-04-27 06:56:12 +0000710 AU.setPreservesAll();
Chandler Carruth73523022014-01-13 13:07:17 +0000711 AU.addRequired<DominatorTreeWrapperPass>();
Chris Lattnerccf571a2002-01-31 00:42:27 +0000712}
Chris Lattnerb1d782b2009-08-23 05:17:37 +0000713
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000714void LoopInfoWrapperPass::print(raw_ostream &OS, const Module *) const {
Chandler Carruth691addc2015-01-18 01:25:51 +0000715 LI.print(OS);
Chris Lattnerb1d782b2009-08-23 05:17:37 +0000716}
717
Andrew Trick78b40c32011-08-10 01:59:05 +0000718//===----------------------------------------------------------------------===//
719// LoopBlocksDFS implementation
720//
721
722/// Traverse the loop blocks and store the DFS result.
723/// Useful for clients that just want the final DFS result and don't need to
724/// visit blocks during the initial traversal.
725void LoopBlocksDFS::perform(LoopInfo *LI) {
726 LoopBlocksTraversal Traversal(*this, LI);
727 for (LoopBlocksTraversal::POTIterator POI = Traversal.begin(),
728 POE = Traversal.end(); POI != POE; ++POI) ;
729}