blob: 2ac1ae2e5cf6e3683bb1c0af425e9905770cab0d [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"
Benjamin Kramer799003b2015-03-23 19:32:43 +000032#include "llvm/Support/raw_ostream.h"
Chris Lattner6de99422001-11-26 18:41:20 +000033#include <algorithm>
Chris Lattner55b7ef52004-04-12 20:26:17 +000034using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000035
Andrew Trickcda51d42012-06-20 03:42:09 +000036// Explicitly instantiate methods in LoopInfoImpl.h for IR-level Loops.
37template class llvm::LoopBase<BasicBlock, Loop>;
38template class llvm::LoopInfoBase<BasicBlock, Loop>;
39
Dan Gohman4dbb3012009-09-28 00:27:48 +000040// Always verify loopinfo if expensive checking is enabled.
Filipe Cabecinhas0da99372016-04-29 15:22:48 +000041#ifdef EXPENSIVE_CHECKS
Dan Gohmanb29cda92010-04-15 17:08:50 +000042static bool VerifyLoopInfo = true;
Dan Gohman4dbb3012009-09-28 00:27:48 +000043#else
Dan Gohmanb29cda92010-04-15 17:08:50 +000044static bool VerifyLoopInfo = false;
Dan Gohman4dbb3012009-09-28 00:27:48 +000045#endif
46static cl::opt<bool,true>
47VerifyLoopInfoX("verify-loop-info", cl::location(VerifyLoopInfo),
48 cl::desc("Verify loop info (time consuming)"));
49
Chris Lattnerccf571a2002-01-31 00:42:27 +000050//===----------------------------------------------------------------------===//
Chris Lattner78dd56f2002-04-28 16:21:30 +000051// Loop implementation
Chris Lattnerccf571a2002-01-31 00:42:27 +000052//
Misha Brukman3845be22002-10-11 05:31:10 +000053
Pete Cooper016daa62015-05-13 01:12:06 +000054bool Loop::isLoopInvariant(const Value *V) const {
55 if (const Instruction *I = dyn_cast<Instruction>(V))
Chris Lattnerda24b9a2010-09-06 01:05:37 +000056 return !contains(I);
Dan Gohman80a99422009-07-13 22:02:44 +000057 return true; // All non-instructions are loop invariant
58}
59
Pete Cooper016daa62015-05-13 01:12:06 +000060bool Loop::hasLoopInvariantOperands(const Instruction *I) const {
Pete Coopera264dc02015-05-13 22:19:13 +000061 return all_of(I->operands(), [this](Value *V) { return isLoopInvariant(V); });
Dan Gohman6f6d8642009-07-14 01:06:29 +000062}
63
Dan Gohmanc43e4792009-07-15 01:25:43 +000064bool Loop::makeLoopInvariant(Value *V, bool &Changed,
65 Instruction *InsertPt) const {
Dan Gohman6f6d8642009-07-14 01:06:29 +000066 if (Instruction *I = dyn_cast<Instruction>(V))
Dan Gohmanc43e4792009-07-15 01:25:43 +000067 return makeLoopInvariant(I, Changed, InsertPt);
Dan Gohman6f6d8642009-07-14 01:06:29 +000068 return true; // All non-instructions are loop-invariant.
69}
70
Dan Gohmanc43e4792009-07-15 01:25:43 +000071bool Loop::makeLoopInvariant(Instruction *I, bool &Changed,
72 Instruction *InsertPt) const {
Dan Gohman6f6d8642009-07-14 01:06:29 +000073 // Test if the value is already loop-invariant.
74 if (isLoopInvariant(I))
75 return true;
Dan Gohman75d7d5e2011-12-14 23:49:11 +000076 if (!isSafeToSpeculativelyExecute(I))
Dan Gohman6f6d8642009-07-14 01:06:29 +000077 return false;
Eli Friedmanb8f6a4f2009-07-17 04:28:42 +000078 if (I->mayReadFromMemory())
Dan Gohman6f6d8642009-07-14 01:06:29 +000079 return false;
David Majnemer654e1302015-07-31 17:58:14 +000080 // EH block instructions are immobile.
81 if (I->isEHPad())
Bill Wendlinga9ee09f2011-08-17 20:36:44 +000082 return false;
Dan Gohman6f6d8642009-07-14 01:06:29 +000083 // Determine the insertion point, unless one was given.
84 if (!InsertPt) {
85 BasicBlock *Preheader = getLoopPreheader();
86 // Without a preheader, hoisting is not feasible.
87 if (!Preheader)
88 return false;
89 InsertPt = Preheader->getTerminator();
90 }
91 // Don't hoist instructions with loop-variant operands.
Sanjay Patel960e5342016-01-15 00:08:10 +000092 for (Value *Operand : I->operands())
93 if (!makeLoopInvariant(Operand, Changed, InsertPt))
Dan Gohman6f6d8642009-07-14 01:06:29 +000094 return false;
Andrew Trickf898cbd2011-08-03 23:45:50 +000095
Dan Gohman6f6d8642009-07-14 01:06:29 +000096 // Hoist.
97 I->moveBefore(InsertPt);
Igor Laevsky7310c682015-11-18 14:50:18 +000098
99 // There is possibility of hoisting this instruction above some arbitrary
100 // condition. Any metadata defined on it can be control dependent on this
101 // condition. Conservatively strip it here so that we don't give any wrong
102 // information to the optimizer.
103 I->dropUnknownNonDebugMetadata();
104
Dan Gohmanc43e4792009-07-15 01:25:43 +0000105 Changed = true;
Dan Gohman6f6d8642009-07-14 01:06:29 +0000106 return true;
107}
108
Dan Gohman80a99422009-07-13 22:02:44 +0000109PHINode *Loop::getCanonicalInductionVariable() const {
110 BasicBlock *H = getHeader();
111
Craig Topper9f008862014-04-15 04:59:12 +0000112 BasicBlock *Incoming = nullptr, *Backedge = nullptr;
Dan Gohmanacafc612010-07-23 21:25:16 +0000113 pred_iterator PI = pred_begin(H);
114 assert(PI != pred_end(H) &&
Dan Gohman80a99422009-07-13 22:02:44 +0000115 "Loop must have at least one backedge!");
116 Backedge = *PI++;
Craig Topper9f008862014-04-15 04:59:12 +0000117 if (PI == pred_end(H)) return nullptr; // dead loop
Dan Gohman80a99422009-07-13 22:02:44 +0000118 Incoming = *PI++;
Craig Topper9f008862014-04-15 04:59:12 +0000119 if (PI != pred_end(H)) return nullptr; // multiple backedges?
Dan Gohman80a99422009-07-13 22:02:44 +0000120
121 if (contains(Incoming)) {
122 if (contains(Backedge))
Craig Topper9f008862014-04-15 04:59:12 +0000123 return nullptr;
Dan Gohman80a99422009-07-13 22:02:44 +0000124 std::swap(Incoming, Backedge);
125 } else if (!contains(Backedge))
Craig Topper9f008862014-04-15 04:59:12 +0000126 return nullptr;
Dan Gohman80a99422009-07-13 22:02:44 +0000127
128 // Loop over all of the PHI nodes, looking for a canonical indvar.
129 for (BasicBlock::iterator I = H->begin(); isa<PHINode>(I); ++I) {
130 PHINode *PN = cast<PHINode>(I);
131 if (ConstantInt *CI =
132 dyn_cast<ConstantInt>(PN->getIncomingValueForBlock(Incoming)))
133 if (CI->isNullValue())
134 if (Instruction *Inc =
135 dyn_cast<Instruction>(PN->getIncomingValueForBlock(Backedge)))
136 if (Inc->getOpcode() == Instruction::Add &&
137 Inc->getOperand(0) == PN)
138 if (ConstantInt *CI = dyn_cast<ConstantInt>(Inc->getOperand(1)))
139 if (CI->equalsInt(1))
140 return PN;
141 }
Craig Topper9f008862014-04-15 04:59:12 +0000142 return nullptr;
Dan Gohman80a99422009-07-13 22:02:44 +0000143}
144
Dan Gohman2734ebd2010-03-10 19:38:49 +0000145bool Loop::isLCSSAForm(DominatorTree &DT) const {
Sanjay Patel960e5342016-01-15 00:08:10 +0000146 for (BasicBlock *BB : this->blocks()) {
147 for (Instruction &I : *BB) {
Andrew Kaylor123048d2015-12-18 18:12:35 +0000148 // Tokens can't be used in PHI nodes and live-out tokens prevent loop
149 // optimizations, so for the purposes of considered LCSSA form, we
150 // can ignore them.
Sanjay Patel960e5342016-01-15 00:08:10 +0000151 if (I.getType()->isTokenTy())
Andrew Kaylor123048d2015-12-18 18:12:35 +0000152 continue;
153
Sanjay Patel960e5342016-01-15 00:08:10 +0000154 for (Use &U : I.uses()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000155 Instruction *UI = cast<Instruction>(U.getUser());
156 BasicBlock *UserBB = UI->getParent();
157 if (PHINode *P = dyn_cast<PHINode>(UI))
158 UserBB = P->getIncomingBlock(U);
Dan Gohman80a99422009-07-13 22:02:44 +0000159
Dan Gohman93452ce2010-03-09 01:53:33 +0000160 // Check the current block, as a fast-path, before checking whether
161 // the use is anywhere in the loop. Most values are used in the same
162 // block they are defined in. Also, blocks not reachable from the
163 // entry are special; uses in them don't need to go through PHIs.
164 if (UserBB != BB &&
Wan Xiaofeibe640b22013-10-26 03:08:02 +0000165 !contains(UserBB) &&
Dan Gohman2734ebd2010-03-10 19:38:49 +0000166 DT.isReachableFromEntry(UserBB))
Dan Gohman80a99422009-07-13 22:02:44 +0000167 return false;
168 }
Andrew Kaylor123048d2015-12-18 18:12:35 +0000169 }
Dan Gohman80a99422009-07-13 22:02:44 +0000170 }
171
172 return true;
173}
Dan Gohman1511f702009-07-16 16:16:23 +0000174
Sanjoy Das683bf072015-12-08 00:13:21 +0000175bool Loop::isRecursivelyLCSSAForm(DominatorTree &DT) const {
176 if (!isLCSSAForm(DT))
177 return false;
178
179 return std::all_of(begin(), end(), [&](const Loop *L) {
180 return L->isRecursivelyLCSSAForm(DT);
181 });
182}
183
Dan Gohman1511f702009-07-16 16:16:23 +0000184bool Loop::isLoopSimplifyForm() const {
Dan Gohmane3a17062009-11-05 19:21:41 +0000185 // Normal-form loops have a preheader, a single backedge, and all of their
186 // exits have all their predecessors inside the loop.
187 return getLoopPreheader() && getLoopLatch() && hasDedicatedExits();
188}
189
Sanjay Patel784b5e32016-01-14 23:23:04 +0000190// Routines that reform the loop CFG and split edges often fail on indirectbr.
Andrew Trick4442bfe2012-04-10 05:14:42 +0000191bool Loop::isSafeToClone() const {
James Molloy4f6fb952012-12-20 16:04:27 +0000192 // Return false if any loop blocks contain indirectbrs, or there are any calls
193 // to noduplicate functions.
Sanjay Patel960e5342016-01-15 00:08:10 +0000194 for (BasicBlock *BB : this->blocks()) {
195 if (isa<IndirectBrInst>(BB->getTerminator()))
Andrew Trick4442bfe2012-04-10 05:14:42 +0000196 return false;
Jakub Staszak9dca4b32013-11-13 20:18:38 +0000197
David Majnemer3d90bb72016-05-03 03:57:40 +0000198 for (Instruction &I : *BB)
199 if (auto CS = CallSite(&I))
200 if (CS.cannotDuplicate())
James Molloy4f6fb952012-12-20 16:04:27 +0000201 return false;
Andrew Trick4442bfe2012-04-10 05:14:42 +0000202 }
203 return true;
204}
205
Paul Redmond5fdf8362013-05-28 20:00:34 +0000206MDNode *Loop::getLoopID() const {
Craig Topper9f008862014-04-15 04:59:12 +0000207 MDNode *LoopID = nullptr;
Paul Redmond5fdf8362013-05-28 20:00:34 +0000208 if (isLoopSimplifyForm()) {
Duncan P. N. Exon Smith1d15a9f2016-03-25 00:35:38 +0000209 LoopID = getLoopLatch()->getTerminator()->getMetadata(LLVMContext::MD_loop);
Paul Redmond5fdf8362013-05-28 20:00:34 +0000210 } else {
211 // Go through each predecessor of the loop header and check the
212 // terminator for the metadata.
213 BasicBlock *H = getHeader();
Sanjay Patel960e5342016-01-15 00:08:10 +0000214 for (BasicBlock *BB : this->blocks()) {
215 TerminatorInst *TI = BB->getTerminator();
Craig Topper9f008862014-04-15 04:59:12 +0000216 MDNode *MD = nullptr;
Paul Redmond5fdf8362013-05-28 20:00:34 +0000217
218 // Check if this terminator branches to the loop header.
Sanjay Patel960e5342016-01-15 00:08:10 +0000219 for (BasicBlock *Successor : TI->successors()) {
220 if (Successor == H) {
Duncan P. N. Exon Smith1d15a9f2016-03-25 00:35:38 +0000221 MD = TI->getMetadata(LLVMContext::MD_loop);
Paul Redmond5fdf8362013-05-28 20:00:34 +0000222 break;
223 }
224 }
225 if (!MD)
Craig Topper9f008862014-04-15 04:59:12 +0000226 return nullptr;
Paul Redmond5fdf8362013-05-28 20:00:34 +0000227
228 if (!LoopID)
229 LoopID = MD;
230 else if (MD != LoopID)
Craig Topper9f008862014-04-15 04:59:12 +0000231 return nullptr;
Paul Redmond5fdf8362013-05-28 20:00:34 +0000232 }
233 }
234 if (!LoopID || LoopID->getNumOperands() == 0 ||
235 LoopID->getOperand(0) != LoopID)
Craig Topper9f008862014-04-15 04:59:12 +0000236 return nullptr;
Paul Redmond5fdf8362013-05-28 20:00:34 +0000237 return LoopID;
238}
239
240void Loop::setLoopID(MDNode *LoopID) const {
241 assert(LoopID && "Loop ID should not be null");
242 assert(LoopID->getNumOperands() > 0 && "Loop ID needs at least one operand");
243 assert(LoopID->getOperand(0) == LoopID && "Loop ID should refer to itself");
244
245 if (isLoopSimplifyForm()) {
Duncan P. N. Exon Smith1d15a9f2016-03-25 00:35:38 +0000246 getLoopLatch()->getTerminator()->setMetadata(LLVMContext::MD_loop, LoopID);
Paul Redmond5fdf8362013-05-28 20:00:34 +0000247 return;
248 }
249
250 BasicBlock *H = getHeader();
Sanjay Patel960e5342016-01-15 00:08:10 +0000251 for (BasicBlock *BB : this->blocks()) {
252 TerminatorInst *TI = BB->getTerminator();
253 for (BasicBlock *Successor : TI->successors()) {
254 if (Successor == H)
Duncan P. N. Exon Smith1d15a9f2016-03-25 00:35:38 +0000255 TI->setMetadata(LLVMContext::MD_loop, LoopID);
Paul Redmond5fdf8362013-05-28 20:00:34 +0000256 }
257 }
258}
259
Pekka Jaaskelainen0d237252013-02-13 18:08:57 +0000260bool Loop::isAnnotatedParallel() const {
Sanjay Patel6435c6e2016-01-17 23:18:05 +0000261 MDNode *DesiredLoopIdMetadata = getLoopID();
Pekka Jaaskelainen0d237252013-02-13 18:08:57 +0000262
Sanjay Patel6435c6e2016-01-17 23:18:05 +0000263 if (!DesiredLoopIdMetadata)
Pekka Jaaskelainen0d237252013-02-13 18:08:57 +0000264 return false;
265
266 // The loop branch contains the parallel loop metadata. In order to ensure
267 // that any parallel-loop-unaware optimization pass hasn't added loop-carried
268 // dependencies (thus converted the loop back to a sequential loop), check
269 // that all the memory instructions in the loop contain parallelism metadata
270 // that point to the same unique "loop id metadata" the loop branch does.
Sanjay Patel960e5342016-01-15 00:08:10 +0000271 for (BasicBlock *BB : this->blocks()) {
272 for (Instruction &I : *BB) {
273 if (!I.mayReadOrWriteMemory())
Pekka Jaaskelainen0d237252013-02-13 18:08:57 +0000274 continue;
275
Pekka Jaaskelainen0d237252013-02-13 18:08:57 +0000276 // The memory instruction can refer to the loop identifier metadata
277 // directly or indirectly through another list metadata (in case of
278 // nested parallel loops). The loop identifier metadata refers to
279 // itself so we can check both cases with the same routine.
Sanjay Patel6435c6e2016-01-17 23:18:05 +0000280 MDNode *LoopIdMD =
Sanjay Patel960e5342016-01-15 00:08:10 +0000281 I.getMetadata(LLVMContext::MD_mem_parallel_loop_access);
Jakub Staszak9dca4b32013-11-13 20:18:38 +0000282
Sanjay Patel6435c6e2016-01-17 23:18:05 +0000283 if (!LoopIdMD)
Jakub Staszak9dca4b32013-11-13 20:18:38 +0000284 return false;
285
Sanjay Patel6435c6e2016-01-17 23:18:05 +0000286 bool LoopIdMDFound = false;
287 for (const MDOperand &MDOp : LoopIdMD->operands()) {
288 if (MDOp == DesiredLoopIdMetadata) {
289 LoopIdMDFound = true;
Pekka Jaaskelainen0d237252013-02-13 18:08:57 +0000290 break;
291 }
292 }
293
Sanjay Patel6435c6e2016-01-17 23:18:05 +0000294 if (!LoopIdMDFound)
Pekka Jaaskelainen0d237252013-02-13 18:08:57 +0000295 return false;
296 }
297 }
298 return true;
299}
300
Dan Gohmane3a17062009-11-05 19:21:41 +0000301bool Loop::hasDedicatedExits() const {
Dan Gohman1511f702009-07-16 16:16:23 +0000302 // Each predecessor of each exit block of a normal loop is contained
303 // within the loop.
304 SmallVector<BasicBlock *, 4> ExitBlocks;
305 getExitBlocks(ExitBlocks);
Sanjay Patel960e5342016-01-15 00:08:10 +0000306 for (BasicBlock *BB : ExitBlocks)
307 for (BasicBlock *Predecessor : predecessors(BB))
308 if (!contains(Predecessor))
Dan Gohman1511f702009-07-16 16:16:23 +0000309 return false;
310 // All the requirements are met.
311 return true;
312}
313
Dan Gohman3a0ce3e2009-09-03 16:10:48 +0000314void
315Loop::getUniqueExitBlocks(SmallVectorImpl<BasicBlock *> &ExitBlocks) const {
Dan Gohman84ba0392009-12-11 20:05:23 +0000316 assert(hasDedicatedExits() &&
317 "getUniqueExitBlocks assumes the loop has canonical form exits!");
Dan Gohman3ddbc242009-09-08 15:45:00 +0000318
Sanjay Patel6435c6e2016-01-17 23:18:05 +0000319 SmallVector<BasicBlock *, 32> SwitchExitBlocks;
Sanjay Patel960e5342016-01-15 00:08:10 +0000320 for (BasicBlock *BB : this->blocks()) {
Sanjay Patel6435c6e2016-01-17 23:18:05 +0000321 SwitchExitBlocks.clear();
Sanjay Patel960e5342016-01-15 00:08:10 +0000322 for (BasicBlock *Successor : successors(BB)) {
323 // If block is inside the loop then it is not an exit block.
324 if (contains(Successor))
Dan Gohman3a0ce3e2009-09-03 16:10:48 +0000325 continue;
326
Sanjay Patel960e5342016-01-15 00:08:10 +0000327 pred_iterator PI = pred_begin(Successor);
Sanjay Patel6435c6e2016-01-17 23:18:05 +0000328 BasicBlock *FirstPred = *PI;
Dan Gohman3a0ce3e2009-09-03 16:10:48 +0000329
330 // If current basic block is this exit block's first predecessor
331 // then only insert exit block in to the output ExitBlocks vector.
332 // This ensures that same exit block is not inserted twice into
333 // ExitBlocks vector.
Sanjay Patel6435c6e2016-01-17 23:18:05 +0000334 if (BB != FirstPred)
Dan Gohman3a0ce3e2009-09-03 16:10:48 +0000335 continue;
336
337 // If a terminator has more then two successors, for example SwitchInst,
338 // then it is possible that there are multiple edges from current block
339 // to one exit block.
Sanjay Patel960e5342016-01-15 00:08:10 +0000340 if (std::distance(succ_begin(BB), succ_end(BB)) <= 2) {
341 ExitBlocks.push_back(Successor);
Dan Gohman3a0ce3e2009-09-03 16:10:48 +0000342 continue;
343 }
344
345 // In case of multiple edges from current block to exit block, collect
346 // only one edge in ExitBlocks. Use switchExitBlocks to keep track of
347 // duplicate edges.
Sanjay Patel6435c6e2016-01-17 23:18:05 +0000348 if (std::find(SwitchExitBlocks.begin(), SwitchExitBlocks.end(), Successor)
349 == SwitchExitBlocks.end()) {
350 SwitchExitBlocks.push_back(Successor);
Sanjay Patel960e5342016-01-15 00:08:10 +0000351 ExitBlocks.push_back(Successor);
Dan Gohman3a0ce3e2009-09-03 16:10:48 +0000352 }
353 }
354 }
355}
356
Dan Gohman3a0ce3e2009-09-03 16:10:48 +0000357BasicBlock *Loop::getUniqueExitBlock() const {
358 SmallVector<BasicBlock *, 8> UniqueExitBlocks;
359 getUniqueExitBlocks(UniqueExitBlocks);
360 if (UniqueExitBlocks.size() == 1)
361 return UniqueExitBlocks[0];
Craig Topper9f008862014-04-15 04:59:12 +0000362 return nullptr;
Dan Gohman3a0ce3e2009-09-03 16:10:48 +0000363}
364
Manman Ren49d684e2012-09-12 05:06:18 +0000365#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Yaron Kereneb2a2542016-01-29 20:50:44 +0000366LLVM_DUMP_METHOD void Loop::dump() const {
Dan Gohmanc3f21372010-01-05 21:08:02 +0000367 print(dbgs());
368}
Manman Renc3366cc2012-09-06 19:55:56 +0000369#endif
Dan Gohmanc3f21372010-01-05 21:08:02 +0000370
Chris Lattner26750072002-07-27 01:12:17 +0000371//===----------------------------------------------------------------------===//
Andrew Trickd3530b92011-08-10 23:22:57 +0000372// UnloopUpdater implementation
373//
374
Benjamin Kramer4938edb2011-08-19 01:42:18 +0000375namespace {
Andrew Trickd3530b92011-08-10 23:22:57 +0000376/// Find the new parent loop for all blocks within the "unloop" whose last
377/// backedges has just been removed.
378class UnloopUpdater {
379 Loop *Unloop;
380 LoopInfo *LI;
381
382 LoopBlocksDFS DFS;
383
384 // Map unloop's immediate subloops to their nearest reachable parents. Nested
385 // loops within these subloops will not change parents. However, an immediate
386 // subloop's new parent will be the nearest loop reachable from either its own
387 // exits *or* any of its nested loop's exits.
388 DenseMap<Loop*, Loop*> SubloopParents;
389
390 // Flag the presence of an irreducible backedge whose destination is a block
391 // directly contained by the original unloop.
392 bool FoundIB;
393
394public:
395 UnloopUpdater(Loop *UL, LoopInfo *LInfo) :
396 Unloop(UL), LI(LInfo), DFS(UL), FoundIB(false) {}
397
398 void updateBlockParents();
399
Andrew Trickc12c30a2011-08-11 20:27:32 +0000400 void removeBlocksFromAncestors();
401
Andrew Trickd3530b92011-08-10 23:22:57 +0000402 void updateSubloopParents();
403
404protected:
405 Loop *getNearestLoop(BasicBlock *BB, Loop *BBLoop);
406};
Benjamin Kramer4938edb2011-08-19 01:42:18 +0000407} // end anonymous namespace
Andrew Trickd3530b92011-08-10 23:22:57 +0000408
Sanjay Patel784b5e32016-01-14 23:23:04 +0000409/// Update the parent loop for all blocks that are directly contained within the
410/// original "unloop".
Andrew Trickd3530b92011-08-10 23:22:57 +0000411void UnloopUpdater::updateBlockParents() {
412 if (Unloop->getNumBlocks()) {
413 // Perform a post order CFG traversal of all blocks within this loop,
414 // propagating the nearest loop from sucessors to predecessors.
415 LoopBlocksTraversal Traversal(DFS, LI);
416 for (LoopBlocksTraversal::POTIterator POI = Traversal.begin(),
417 POE = Traversal.end(); POI != POE; ++POI) {
418
419 Loop *L = LI->getLoopFor(*POI);
420 Loop *NL = getNearestLoop(*POI, L);
421
422 if (NL != L) {
423 // For reducible loops, NL is now an ancestor of Unloop.
424 assert((NL != Unloop && (!NL || NL->contains(Unloop))) &&
425 "uninitialized successor");
426 LI->changeLoopFor(*POI, NL);
427 }
428 else {
429 // Or the current block is part of a subloop, in which case its parent
430 // is unchanged.
431 assert((FoundIB || Unloop->contains(L)) && "uninitialized successor");
432 }
433 }
434 }
435 // Each irreducible loop within the unloop induces a round of iteration using
436 // the DFS result cached by Traversal.
437 bool Changed = FoundIB;
438 for (unsigned NIters = 0; Changed; ++NIters) {
439 assert(NIters < Unloop->getNumBlocks() && "runaway iterative algorithm");
440
441 // Iterate over the postorder list of blocks, propagating the nearest loop
442 // from successors to predecessors as before.
443 Changed = false;
444 for (LoopBlocksDFS::POIterator POI = DFS.beginPostorder(),
445 POE = DFS.endPostorder(); POI != POE; ++POI) {
446
447 Loop *L = LI->getLoopFor(*POI);
448 Loop *NL = getNearestLoop(*POI, L);
449 if (NL != L) {
450 assert(NL != Unloop && (!NL || NL->contains(Unloop)) &&
451 "uninitialized successor");
452 LI->changeLoopFor(*POI, NL);
453 Changed = true;
454 }
455 }
456 }
457}
458
Sanjay Patel784b5e32016-01-14 23:23:04 +0000459/// Remove unloop's blocks from all ancestors below their new parents.
Andrew Trickc12c30a2011-08-11 20:27:32 +0000460void UnloopUpdater::removeBlocksFromAncestors() {
Andrew Trick6b4d5782011-11-18 03:42:41 +0000461 // Remove all unloop's blocks (including those in nested subloops) from
462 // ancestors below the new parent loop.
Andrew Trickc12c30a2011-08-11 20:27:32 +0000463 for (Loop::block_iterator BI = Unloop->block_begin(),
464 BE = Unloop->block_end(); BI != BE; ++BI) {
Andrew Trick6b4d5782011-11-18 03:42:41 +0000465 Loop *OuterParent = LI->getLoopFor(*BI);
466 if (Unloop->contains(OuterParent)) {
467 while (OuterParent->getParentLoop() != Unloop)
468 OuterParent = OuterParent->getParentLoop();
469 OuterParent = SubloopParents[OuterParent];
470 }
Andrew Trickc12c30a2011-08-11 20:27:32 +0000471 // Remove blocks from former Ancestors except Unloop itself which will be
472 // deleted.
Andrew Trick6b4d5782011-11-18 03:42:41 +0000473 for (Loop *OldParent = Unloop->getParentLoop(); OldParent != OuterParent;
Andrew Trickc12c30a2011-08-11 20:27:32 +0000474 OldParent = OldParent->getParentLoop()) {
475 assert(OldParent && "new loop is not an ancestor of the original");
476 OldParent->removeBlockFromLoop(*BI);
477 }
478 }
479}
480
Sanjay Patel784b5e32016-01-14 23:23:04 +0000481/// Update the parent loop for all subloops directly nested within unloop.
Andrew Trickd3530b92011-08-10 23:22:57 +0000482void UnloopUpdater::updateSubloopParents() {
483 while (!Unloop->empty()) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000484 Loop *Subloop = *std::prev(Unloop->end());
485 Unloop->removeChildLoop(std::prev(Unloop->end()));
Andrew Trickd3530b92011-08-10 23:22:57 +0000486
487 assert(SubloopParents.count(Subloop) && "DFS failed to visit subloop");
Benjamin Kramerf29db272012-08-22 15:37:57 +0000488 if (Loop *Parent = SubloopParents[Subloop])
489 Parent->addChildLoop(Subloop);
Andrew Trick147d9cd2011-08-26 03:06:34 +0000490 else
491 LI->addTopLevelLoop(Subloop);
Andrew Trickd3530b92011-08-10 23:22:57 +0000492 }
493}
494
Sanjay Patel784b5e32016-01-14 23:23:04 +0000495/// Return the nearest parent loop among this block's successors. If a successor
496/// is a subloop header, consider its parent to be the nearest parent of the
497/// subloop's exits.
Andrew Trickd3530b92011-08-10 23:22:57 +0000498///
499/// For subloop blocks, simply update SubloopParents and return NULL.
500Loop *UnloopUpdater::getNearestLoop(BasicBlock *BB, Loop *BBLoop) {
501
Andrew Trick266ab102011-08-11 17:54:58 +0000502 // Initially for blocks directly contained by Unloop, NearLoop == Unloop and
503 // is considered uninitialized.
Andrew Trickd3530b92011-08-10 23:22:57 +0000504 Loop *NearLoop = BBLoop;
505
Craig Topper9f008862014-04-15 04:59:12 +0000506 Loop *Subloop = nullptr;
Andrew Trickd3530b92011-08-10 23:22:57 +0000507 if (NearLoop != Unloop && Unloop->contains(NearLoop)) {
508 Subloop = NearLoop;
509 // Find the subloop ancestor that is directly contained within Unloop.
510 while (Subloop->getParentLoop() != Unloop) {
511 Subloop = Subloop->getParentLoop();
512 assert(Subloop && "subloop is not an ancestor of the original loop");
513 }
514 // Get the current nearest parent of the Subloop exits, initially Unloop.
Benjamin Kramerf29db272012-08-22 15:37:57 +0000515 NearLoop =
516 SubloopParents.insert(std::make_pair(Subloop, Unloop)).first->second;
Andrew Trickd3530b92011-08-10 23:22:57 +0000517 }
518
519 succ_iterator I = succ_begin(BB), E = succ_end(BB);
520 if (I == E) {
521 assert(!Subloop && "subloop blocks must have a successor");
Craig Topper9f008862014-04-15 04:59:12 +0000522 NearLoop = nullptr; // unloop blocks may now exit the function.
Andrew Trickd3530b92011-08-10 23:22:57 +0000523 }
524 for (; I != E; ++I) {
525 if (*I == BB)
526 continue; // self loops are uninteresting
527
528 Loop *L = LI->getLoopFor(*I);
529 if (L == Unloop) {
530 // This successor has not been processed. This path must lead to an
531 // irreducible backedge.
532 assert((FoundIB || !DFS.hasPostorder(*I)) && "should have seen IB");
533 FoundIB = true;
534 }
535 if (L != Unloop && Unloop->contains(L)) {
536 // Successor is in a subloop.
537 if (Subloop)
538 continue; // Branching within subloops. Ignore it.
539
540 // BB branches from the original into a subloop header.
541 assert(L->getParentLoop() == Unloop && "cannot skip into nested loops");
542
543 // Get the current nearest parent of the Subloop's exits.
544 L = SubloopParents[L];
545 // L could be Unloop if the only exit was an irreducible backedge.
546 }
547 if (L == Unloop) {
548 continue;
549 }
550 // Handle critical edges from Unloop into a sibling loop.
551 if (L && !L->contains(Unloop)) {
552 L = L->getParentLoop();
553 }
554 // Remember the nearest parent loop among successors or subloop exits.
555 if (NearLoop == Unloop || !NearLoop || NearLoop->contains(L))
556 NearLoop = L;
557 }
558 if (Subloop) {
559 SubloopParents[Subloop] = NearLoop;
560 return BBLoop;
561 }
562 return NearLoop;
563}
564
Cong Hou9b4f6b22015-07-16 23:23:35 +0000565LoopInfo::LoopInfo(const DominatorTreeBase<BasicBlock> &DomTree) {
566 analyze(DomTree);
567}
568
Justin Bognere9fb228d2016-01-08 19:08:53 +0000569void LoopInfo::markAsRemoved(Loop *Unloop) {
570 assert(!Unloop->isInvalid() && "Loop has already been removed");
571 Unloop->invalidate();
572 RemovedLoops.push_back(Unloop);
Andrew Trickd3530b92011-08-10 23:22:57 +0000573
574 // First handle the special case of no parent loop to simplify the algorithm.
575 if (!Unloop->getParentLoop()) {
576 // Since BBLoop had no parent, Unloop blocks are no longer in a loop.
577 for (Loop::block_iterator I = Unloop->block_begin(),
Chandler Carruth691addc2015-01-18 01:25:51 +0000578 E = Unloop->block_end();
579 I != E; ++I) {
Andrew Trickd3530b92011-08-10 23:22:57 +0000580
581 // Don't reparent blocks in subloops.
582 if (getLoopFor(*I) != Unloop)
583 continue;
584
585 // Blocks no longer have a parent but are still referenced by Unloop until
586 // the Unloop object is deleted.
Chandler Carruth691addc2015-01-18 01:25:51 +0000587 changeLoopFor(*I, nullptr);
Andrew Trickd3530b92011-08-10 23:22:57 +0000588 }
589
590 // Remove the loop from the top-level LoopInfo object.
Chandler Carruth691addc2015-01-18 01:25:51 +0000591 for (iterator I = begin();; ++I) {
592 assert(I != end() && "Couldn't find loop");
Andrew Trickd3530b92011-08-10 23:22:57 +0000593 if (*I == Unloop) {
Chandler Carruth691addc2015-01-18 01:25:51 +0000594 removeLoop(I);
Andrew Trickd3530b92011-08-10 23:22:57 +0000595 break;
596 }
597 }
598
599 // Move all of the subloops to the top-level.
600 while (!Unloop->empty())
Chandler Carruth691addc2015-01-18 01:25:51 +0000601 addTopLevelLoop(Unloop->removeChildLoop(std::prev(Unloop->end())));
Andrew Trickd3530b92011-08-10 23:22:57 +0000602
603 return;
604 }
605
606 // Update the parent loop for all blocks within the loop. Blocks within
607 // subloops will not change parents.
608 UnloopUpdater Updater(Unloop, this);
609 Updater.updateBlockParents();
610
Andrew Trickc12c30a2011-08-11 20:27:32 +0000611 // Remove blocks from former ancestor loops.
612 Updater.removeBlocksFromAncestors();
Andrew Trickd3530b92011-08-10 23:22:57 +0000613
614 // Add direct subloops as children in their new parent loop.
615 Updater.updateSubloopParents();
616
617 // Remove unloop from its parent loop.
618 Loop *ParentLoop = Unloop->getParentLoop();
Duncan Sandsa41634e2011-08-12 14:54:45 +0000619 for (Loop::iterator I = ParentLoop->begin();; ++I) {
620 assert(I != ParentLoop->end() && "Couldn't find loop");
Andrew Trickd3530b92011-08-10 23:22:57 +0000621 if (*I == Unloop) {
622 ParentLoop->removeChildLoop(I);
623 break;
624 }
625 }
626}
627
Chandler Carruthb4faf132016-03-11 10:22:49 +0000628char LoopAnalysis::PassID;
NAKAMURA Takumidf0cd722016-02-28 17:17:00 +0000629
Chandler Carruthb47f8012016-03-11 11:05:24 +0000630LoopInfo LoopAnalysis::run(Function &F, AnalysisManager<Function> &AM) {
Chandler Carruthaaf0b4c2015-01-20 10:58:50 +0000631 // FIXME: Currently we create a LoopInfo from scratch for every function.
632 // This may prove to be too wasteful due to deallocating and re-allocating
633 // memory each time for the underlying map and vector datastructures. At some
634 // point it may prove worthwhile to use a freelist and recycle LoopInfo
635 // objects. I don't want to add that kind of complexity until the scope of
636 // the problem is better understood.
637 LoopInfo LI;
Chandler Carruthb47f8012016-03-11 11:05:24 +0000638 LI.analyze(AM.getResult<DominatorTreeAnalysis>(F));
Richard Trieu6ae37962015-04-30 23:07:00 +0000639 return LI;
Chandler Carruthaaf0b4c2015-01-20 10:58:50 +0000640}
641
642PreservedAnalyses LoopPrinterPass::run(Function &F,
Chandler Carruthb47f8012016-03-11 11:05:24 +0000643 AnalysisManager<Function> &AM) {
644 AM.getResult<LoopAnalysis>(F).print(OS);
Chandler Carruthaaf0b4c2015-01-20 10:58:50 +0000645 return PreservedAnalyses::all();
646}
647
Justin Bognerc2b98f02015-11-04 22:24:08 +0000648PrintLoopPass::PrintLoopPass() : OS(dbgs()) {}
649PrintLoopPass::PrintLoopPass(raw_ostream &OS, const std::string &Banner)
650 : OS(OS), Banner(Banner) {}
651
652PreservedAnalyses PrintLoopPass::run(Loop &L) {
653 OS << Banner;
654 for (auto *Block : L.blocks())
655 if (Block)
656 Block->print(OS);
657 else
658 OS << "Printing <null> block";
659 return PreservedAnalyses::all();
660}
661
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000662//===----------------------------------------------------------------------===//
663// LoopInfo implementation
664//
665
666char LoopInfoWrapperPass::ID = 0;
667INITIALIZE_PASS_BEGIN(LoopInfoWrapperPass, "loops", "Natural Loop Information",
668 true, true)
669INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
670INITIALIZE_PASS_END(LoopInfoWrapperPass, "loops", "Natural Loop Information",
671 true, true)
672
673bool LoopInfoWrapperPass::runOnFunction(Function &) {
674 releaseMemory();
Cong Houd2c1d912015-07-16 18:23:57 +0000675 LI.analyze(getAnalysis<DominatorTreeWrapperPass>().getDomTree());
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000676 return false;
677}
678
679void LoopInfoWrapperPass::verifyAnalysis() const {
680 // LoopInfoWrapperPass is a FunctionPass, but verifying every loop in the
681 // function each time verifyAnalysis is called is very expensive. The
Dan Gohman4dbb3012009-09-28 00:27:48 +0000682 // -verify-loop-info option can enable this. In order to perform some
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000683 // checking by default, LoopPass has been taught to call verifyLoop manually
684 // during loop pass sequences.
Chandler Carruth691addc2015-01-18 01:25:51 +0000685 if (VerifyLoopInfo)
686 LI.verify();
Dan Gohman3ddbc242009-09-08 15:45:00 +0000687}
688
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000689void LoopInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerc8e66542002-04-27 06:56:12 +0000690 AU.setPreservesAll();
Chandler Carruth73523022014-01-13 13:07:17 +0000691 AU.addRequired<DominatorTreeWrapperPass>();
Chris Lattnerccf571a2002-01-31 00:42:27 +0000692}
Chris Lattnerb1d782b2009-08-23 05:17:37 +0000693
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000694void LoopInfoWrapperPass::print(raw_ostream &OS, const Module *) const {
Chandler Carruth691addc2015-01-18 01:25:51 +0000695 LI.print(OS);
Chris Lattnerb1d782b2009-08-23 05:17:37 +0000696}
697
Andrew Trick78b40c32011-08-10 01:59:05 +0000698//===----------------------------------------------------------------------===//
699// LoopBlocksDFS implementation
700//
701
702/// Traverse the loop blocks and store the DFS result.
703/// Useful for clients that just want the final DFS result and don't need to
704/// visit blocks during the initial traversal.
705void LoopBlocksDFS::perform(LoopInfo *LI) {
706 LoopBlocksTraversal Traversal(*this, LI);
707 for (LoopBlocksTraversal::POTIterator POI = Traversal.begin(),
708 POE = Traversal.end(); POI != POE; ++POI) ;
709}