blob: 9e54d60779a0081cee64a50a607c0642634b2803 [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"
Sanjoy Das09613b12017-09-20 02:31:57 +000019#include "llvm/ADT/ScopeExit.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000020#include "llvm/ADT/SmallPtrSet.h"
Andrew Trickcda51d42012-06-20 03:42:09 +000021#include "llvm/Analysis/LoopInfoImpl.h"
Andrew Trick78b40c32011-08-10 01:59:05 +000022#include "llvm/Analysis/LoopIterator.h"
Dan Gohman75d7d5e2011-12-14 23:49:11 +000023#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000024#include "llvm/IR/CFG.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000025#include "llvm/IR/Constants.h"
Hal Finkel2f688682016-05-25 21:42:37 +000026#include "llvm/IR/DebugLoc.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000027#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000028#include "llvm/IR/Instructions.h"
Philip Reames5a3f5f72014-10-21 00:13:20 +000029#include "llvm/IR/LLVMContext.h"
Pekka Jaaskelainen0d237252013-02-13 18:08:57 +000030#include "llvm/IR/Metadata.h"
Chandler Carruthaaf0b4c2015-01-20 10:58:50 +000031#include "llvm/IR/PassManager.h"
Dan Gohman4dbb3012009-09-28 00:27:48 +000032#include "llvm/Support/CommandLine.h"
Dan Gohmanc3f21372010-01-05 21:08:02 +000033#include "llvm/Support/Debug.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000034#include "llvm/Support/raw_ostream.h"
Chris Lattner6de99422001-11-26 18:41:20 +000035#include <algorithm>
Chris Lattner55b7ef52004-04-12 20:26:17 +000036using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000037
Andrew Trickcda51d42012-06-20 03:42:09 +000038// Explicitly instantiate methods in LoopInfoImpl.h for IR-level Loops.
39template class llvm::LoopBase<BasicBlock, Loop>;
40template class llvm::LoopInfoBase<BasicBlock, Loop>;
41
Dan Gohman4dbb3012009-09-28 00:27:48 +000042// Always verify loopinfo if expensive checking is enabled.
Filipe Cabecinhas0da99372016-04-29 15:22:48 +000043#ifdef EXPENSIVE_CHECKS
Serge Pavlov69b3ff92017-01-24 05:52:07 +000044bool llvm::VerifyLoopInfo = true;
Dan Gohman4dbb3012009-09-28 00:27:48 +000045#else
Serge Pavlov69b3ff92017-01-24 05:52:07 +000046bool llvm::VerifyLoopInfo = false;
Dan Gohman4dbb3012009-09-28 00:27:48 +000047#endif
Sanjoy Das66a004a2017-09-20 01:12:09 +000048static cl::opt<bool, true>
49 VerifyLoopInfoX("verify-loop-info", cl::location(VerifyLoopInfo),
Zachary Turner8065f0b2017-12-01 00:53:10 +000050 cl::Hidden, cl::desc("Verify loop info (time consuming)"));
Dan Gohman4dbb3012009-09-28 00:27:48 +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
Pete Cooper016daa62015-05-13 01:12:06 +000056bool Loop::isLoopInvariant(const Value *V) const {
57 if (const Instruction *I = dyn_cast<Instruction>(V))
Chris Lattnerda24b9a2010-09-06 01:05:37 +000058 return !contains(I);
Sanjoy Das66a004a2017-09-20 01:12:09 +000059 return true; // All non-instructions are loop invariant
Dan Gohman80a99422009-07-13 22:02:44 +000060}
61
Pete Cooper016daa62015-05-13 01:12:06 +000062bool Loop::hasLoopInvariantOperands(const Instruction *I) const {
Pete Coopera264dc02015-05-13 22:19:13 +000063 return all_of(I->operands(), [this](Value *V) { return isLoopInvariant(V); });
Dan Gohman6f6d8642009-07-14 01:06:29 +000064}
65
Dan Gohmanc43e4792009-07-15 01:25:43 +000066bool Loop::makeLoopInvariant(Value *V, bool &Changed,
67 Instruction *InsertPt) const {
Dan Gohman6f6d8642009-07-14 01:06:29 +000068 if (Instruction *I = dyn_cast<Instruction>(V))
Dan Gohmanc43e4792009-07-15 01:25:43 +000069 return makeLoopInvariant(I, Changed, InsertPt);
Sanjoy Das66a004a2017-09-20 01:12:09 +000070 return true; // All non-instructions are loop-invariant.
Dan Gohman6f6d8642009-07-14 01:06:29 +000071}
72
Dan Gohmanc43e4792009-07-15 01:25:43 +000073bool Loop::makeLoopInvariant(Instruction *I, bool &Changed,
74 Instruction *InsertPt) const {
Dan Gohman6f6d8642009-07-14 01:06:29 +000075 // Test if the value is already loop-invariant.
76 if (isLoopInvariant(I))
77 return true;
Dan Gohman75d7d5e2011-12-14 23:49:11 +000078 if (!isSafeToSpeculativelyExecute(I))
Dan Gohman6f6d8642009-07-14 01:06:29 +000079 return false;
Eli Friedmanb8f6a4f2009-07-17 04:28:42 +000080 if (I->mayReadFromMemory())
Dan Gohman6f6d8642009-07-14 01:06:29 +000081 return false;
David Majnemer654e1302015-07-31 17:58:14 +000082 // EH block instructions are immobile.
83 if (I->isEHPad())
Bill Wendlinga9ee09f2011-08-17 20:36:44 +000084 return false;
Dan Gohman6f6d8642009-07-14 01:06:29 +000085 // Determine the insertion point, unless one was given.
86 if (!InsertPt) {
87 BasicBlock *Preheader = getLoopPreheader();
88 // Without a preheader, hoisting is not feasible.
89 if (!Preheader)
90 return false;
91 InsertPt = Preheader->getTerminator();
92 }
93 // Don't hoist instructions with loop-variant operands.
Sanjay Patel960e5342016-01-15 00:08:10 +000094 for (Value *Operand : I->operands())
95 if (!makeLoopInvariant(Operand, Changed, InsertPt))
Dan Gohman6f6d8642009-07-14 01:06:29 +000096 return false;
Andrew Trickf898cbd2011-08-03 23:45:50 +000097
Dan Gohman6f6d8642009-07-14 01:06:29 +000098 // Hoist.
99 I->moveBefore(InsertPt);
Igor Laevsky7310c682015-11-18 14:50:18 +0000100
101 // There is possibility of hoisting this instruction above some arbitrary
102 // condition. Any metadata defined on it can be control dependent on this
103 // condition. Conservatively strip it here so that we don't give any wrong
104 // information to the optimizer.
105 I->dropUnknownNonDebugMetadata();
106
Dan Gohmanc43e4792009-07-15 01:25:43 +0000107 Changed = true;
Dan Gohman6f6d8642009-07-14 01:06:29 +0000108 return true;
109}
110
Dan Gohman80a99422009-07-13 22:02:44 +0000111PHINode *Loop::getCanonicalInductionVariable() const {
112 BasicBlock *H = getHeader();
113
Craig Topper9f008862014-04-15 04:59:12 +0000114 BasicBlock *Incoming = nullptr, *Backedge = nullptr;
Dan Gohmanacafc612010-07-23 21:25:16 +0000115 pred_iterator PI = pred_begin(H);
Sanjoy Das66a004a2017-09-20 01:12:09 +0000116 assert(PI != pred_end(H) && "Loop must have at least one backedge!");
Dan Gohman80a99422009-07-13 22:02:44 +0000117 Backedge = *PI++;
Sanjoy Das66a004a2017-09-20 01:12:09 +0000118 if (PI == pred_end(H))
119 return nullptr; // dead loop
Dan Gohman80a99422009-07-13 22:02:44 +0000120 Incoming = *PI++;
Sanjoy Das66a004a2017-09-20 01:12:09 +0000121 if (PI != pred_end(H))
122 return nullptr; // multiple backedges?
Dan Gohman80a99422009-07-13 22:02:44 +0000123
124 if (contains(Incoming)) {
125 if (contains(Backedge))
Craig Topper9f008862014-04-15 04:59:12 +0000126 return nullptr;
Dan Gohman80a99422009-07-13 22:02:44 +0000127 std::swap(Incoming, Backedge);
128 } else if (!contains(Backedge))
Craig Topper9f008862014-04-15 04:59:12 +0000129 return nullptr;
Dan Gohman80a99422009-07-13 22:02:44 +0000130
131 // Loop over all of the PHI nodes, looking for a canonical indvar.
132 for (BasicBlock::iterator I = H->begin(); isa<PHINode>(I); ++I) {
133 PHINode *PN = cast<PHINode>(I);
134 if (ConstantInt *CI =
Sanjoy Das66a004a2017-09-20 01:12:09 +0000135 dyn_cast<ConstantInt>(PN->getIncomingValueForBlock(Incoming)))
Craig Topper79ab6432017-07-06 18:39:47 +0000136 if (CI->isZero())
Dan Gohman80a99422009-07-13 22:02:44 +0000137 if (Instruction *Inc =
Sanjoy Das66a004a2017-09-20 01:12:09 +0000138 dyn_cast<Instruction>(PN->getIncomingValueForBlock(Backedge)))
139 if (Inc->getOpcode() == Instruction::Add && Inc->getOperand(0) == PN)
Dan Gohman80a99422009-07-13 22:02:44 +0000140 if (ConstantInt *CI = dyn_cast<ConstantInt>(Inc->getOperand(1)))
Craig Topperca2c8762017-07-06 18:39:49 +0000141 if (CI->isOne())
Dan Gohman80a99422009-07-13 22:02:44 +0000142 return PN;
143 }
Craig Topper9f008862014-04-15 04:59:12 +0000144 return nullptr;
Dan Gohman80a99422009-07-13 22:02:44 +0000145}
146
Igor Laevsky04423cf2016-10-11 13:37:22 +0000147// Check that 'BB' doesn't have any uses outside of the 'L'
148static bool isBlockInLCSSAForm(const Loop &L, const BasicBlock &BB,
149 DominatorTree &DT) {
150 for (const Instruction &I : BB) {
151 // Tokens can't be used in PHI nodes and live-out tokens prevent loop
152 // optimizations, so for the purposes of considered LCSSA form, we
153 // can ignore them.
154 if (I.getType()->isTokenTy())
155 continue;
Andrew Kaylor123048d2015-12-18 18:12:35 +0000156
Igor Laevsky04423cf2016-10-11 13:37:22 +0000157 for (const Use &U : I.uses()) {
158 const Instruction *UI = cast<Instruction>(U.getUser());
159 const BasicBlock *UserBB = UI->getParent();
160 if (const PHINode *P = dyn_cast<PHINode>(UI))
161 UserBB = P->getIncomingBlock(U);
Dan Gohman80a99422009-07-13 22:02:44 +0000162
Igor Laevsky04423cf2016-10-11 13:37:22 +0000163 // Check the current block, as a fast-path, before checking whether
164 // the use is anywhere in the loop. Most values are used in the same
165 // block they are defined in. Also, blocks not reachable from the
166 // entry are special; uses in them don't need to go through PHIs.
167 if (UserBB != &BB && !L.contains(UserBB) &&
168 DT.isReachableFromEntry(UserBB))
169 return false;
Andrew Kaylor123048d2015-12-18 18:12:35 +0000170 }
Dan Gohman80a99422009-07-13 22:02:44 +0000171 }
Dan Gohman80a99422009-07-13 22:02:44 +0000172 return true;
173}
Dan Gohman1511f702009-07-16 16:16:23 +0000174
Igor Laevsky04423cf2016-10-11 13:37:22 +0000175bool Loop::isLCSSAForm(DominatorTree &DT) const {
176 // For each block we check that it doesn't have any uses outside of this loop.
177 return all_of(this->blocks(), [&](const BasicBlock *BB) {
178 return isBlockInLCSSAForm(*this, *BB, DT);
179 });
180}
Sanjoy Das683bf072015-12-08 00:13:21 +0000181
Igor Laevsky04423cf2016-10-11 13:37:22 +0000182bool Loop::isRecursivelyLCSSAForm(DominatorTree &DT, const LoopInfo &LI) const {
Davide Italiano362cc7b2017-01-08 22:22:09 +0000183 // For each block we check that it doesn't have any uses outside of its
184 // innermost loop. This process will transitively guarantee that the current
185 // loop and all of the nested loops are in LCSSA form.
Igor Laevsky04423cf2016-10-11 13:37:22 +0000186 return all_of(this->blocks(), [&](const BasicBlock *BB) {
187 return isBlockInLCSSAForm(*LI.getLoopFor(BB), *BB, DT);
188 });
Sanjoy Das683bf072015-12-08 00:13:21 +0000189}
190
Dan Gohman1511f702009-07-16 16:16:23 +0000191bool Loop::isLoopSimplifyForm() const {
Dan Gohmane3a17062009-11-05 19:21:41 +0000192 // Normal-form loops have a preheader, a single backedge, and all of their
193 // exits have all their predecessors inside the loop.
194 return getLoopPreheader() && getLoopLatch() && hasDedicatedExits();
195}
196
Sanjay Patel784b5e32016-01-14 23:23:04 +0000197// Routines that reform the loop CFG and split edges often fail on indirectbr.
Andrew Trick4442bfe2012-04-10 05:14:42 +0000198bool Loop::isSafeToClone() const {
James Molloy4f6fb952012-12-20 16:04:27 +0000199 // Return false if any loop blocks contain indirectbrs, or there are any calls
200 // to noduplicate functions.
Sanjay Patel960e5342016-01-15 00:08:10 +0000201 for (BasicBlock *BB : this->blocks()) {
202 if (isa<IndirectBrInst>(BB->getTerminator()))
Andrew Trick4442bfe2012-04-10 05:14:42 +0000203 return false;
Jakub Staszak9dca4b32013-11-13 20:18:38 +0000204
David Majnemer3d90bb72016-05-03 03:57:40 +0000205 for (Instruction &I : *BB)
206 if (auto CS = CallSite(&I))
207 if (CS.cannotDuplicate())
James Molloy4f6fb952012-12-20 16:04:27 +0000208 return false;
Andrew Trick4442bfe2012-04-10 05:14:42 +0000209 }
210 return true;
211}
212
Paul Redmond5fdf8362013-05-28 20:00:34 +0000213MDNode *Loop::getLoopID() const {
Craig Topper9f008862014-04-15 04:59:12 +0000214 MDNode *LoopID = nullptr;
Xin Tongca023602017-01-15 21:17:52 +0000215 if (BasicBlock *Latch = getLoopLatch()) {
216 LoopID = Latch->getTerminator()->getMetadata(LLVMContext::MD_loop);
Paul Redmond5fdf8362013-05-28 20:00:34 +0000217 } else {
Xin Tongca023602017-01-15 21:17:52 +0000218 assert(!getLoopLatch() &&
219 "The loop should have no single latch at this point");
Paul Redmond5fdf8362013-05-28 20:00:34 +0000220 // Go through each predecessor of the loop header and check the
221 // terminator for the metadata.
222 BasicBlock *H = getHeader();
Sanjay Patel960e5342016-01-15 00:08:10 +0000223 for (BasicBlock *BB : this->blocks()) {
224 TerminatorInst *TI = BB->getTerminator();
Craig Topper9f008862014-04-15 04:59:12 +0000225 MDNode *MD = nullptr;
Paul Redmond5fdf8362013-05-28 20:00:34 +0000226
227 // Check if this terminator branches to the loop header.
Sanjay Patel960e5342016-01-15 00:08:10 +0000228 for (BasicBlock *Successor : TI->successors()) {
229 if (Successor == H) {
Duncan P. N. Exon Smith1d15a9f2016-03-25 00:35:38 +0000230 MD = TI->getMetadata(LLVMContext::MD_loop);
Paul Redmond5fdf8362013-05-28 20:00:34 +0000231 break;
232 }
233 }
234 if (!MD)
Craig Topper9f008862014-04-15 04:59:12 +0000235 return nullptr;
Paul Redmond5fdf8362013-05-28 20:00:34 +0000236
237 if (!LoopID)
238 LoopID = MD;
239 else if (MD != LoopID)
Craig Topper9f008862014-04-15 04:59:12 +0000240 return nullptr;
Paul Redmond5fdf8362013-05-28 20:00:34 +0000241 }
242 }
243 if (!LoopID || LoopID->getNumOperands() == 0 ||
244 LoopID->getOperand(0) != LoopID)
Craig Topper9f008862014-04-15 04:59:12 +0000245 return nullptr;
Paul Redmond5fdf8362013-05-28 20:00:34 +0000246 return LoopID;
247}
248
249void Loop::setLoopID(MDNode *LoopID) const {
250 assert(LoopID && "Loop ID should not be null");
251 assert(LoopID->getNumOperands() > 0 && "Loop ID needs at least one operand");
252 assert(LoopID->getOperand(0) == LoopID && "Loop ID should refer to itself");
253
Xin Tongca023602017-01-15 21:17:52 +0000254 if (BasicBlock *Latch = getLoopLatch()) {
255 Latch->getTerminator()->setMetadata(LLVMContext::MD_loop, LoopID);
Paul Redmond5fdf8362013-05-28 20:00:34 +0000256 return;
257 }
258
Sanjoy Das66a004a2017-09-20 01:12:09 +0000259 assert(!getLoopLatch() &&
260 "The loop should have no single latch at this point");
Paul Redmond5fdf8362013-05-28 20:00:34 +0000261 BasicBlock *H = getHeader();
Sanjay Patel960e5342016-01-15 00:08:10 +0000262 for (BasicBlock *BB : this->blocks()) {
263 TerminatorInst *TI = BB->getTerminator();
264 for (BasicBlock *Successor : TI->successors()) {
265 if (Successor == H)
Duncan P. N. Exon Smith1d15a9f2016-03-25 00:35:38 +0000266 TI->setMetadata(LLVMContext::MD_loop, LoopID);
Paul Redmond5fdf8362013-05-28 20:00:34 +0000267 }
268 }
269}
270
Hongbin Zheng73f65042017-10-15 07:31:02 +0000271void Loop::setLoopAlreadyUnrolled() {
272 MDNode *LoopID = getLoopID();
273 // First remove any existing loop unrolling metadata.
274 SmallVector<Metadata *, 4> MDs;
275 // Reserve first location for self reference to the LoopID metadata node.
276 MDs.push_back(nullptr);
277
278 if (LoopID) {
279 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
280 bool IsUnrollMetadata = false;
281 MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
282 if (MD) {
283 const MDString *S = dyn_cast<MDString>(MD->getOperand(0));
284 IsUnrollMetadata = S && S->getString().startswith("llvm.loop.unroll.");
285 }
286 if (!IsUnrollMetadata)
287 MDs.push_back(LoopID->getOperand(i));
288 }
289 }
290
291 // Add unroll(disable) metadata to disable future unrolling.
292 LLVMContext &Context = getHeader()->getContext();
293 SmallVector<Metadata *, 1> DisableOperands;
294 DisableOperands.push_back(MDString::get(Context, "llvm.loop.unroll.disable"));
295 MDNode *DisableNode = MDNode::get(Context, DisableOperands);
296 MDs.push_back(DisableNode);
297
298 MDNode *NewLoopID = MDNode::get(Context, MDs);
299 // Set operand 0 to refer to the loop id itself.
300 NewLoopID->replaceOperandWith(0, NewLoopID);
301 setLoopID(NewLoopID);
302}
303
Pekka Jaaskelainen0d237252013-02-13 18:08:57 +0000304bool Loop::isAnnotatedParallel() const {
Sanjay Patel6435c6e2016-01-17 23:18:05 +0000305 MDNode *DesiredLoopIdMetadata = getLoopID();
Pekka Jaaskelainen0d237252013-02-13 18:08:57 +0000306
Sanjay Patel6435c6e2016-01-17 23:18:05 +0000307 if (!DesiredLoopIdMetadata)
Sanjoy Das66a004a2017-09-20 01:12:09 +0000308 return false;
Pekka Jaaskelainen0d237252013-02-13 18:08:57 +0000309
310 // The loop branch contains the parallel loop metadata. In order to ensure
311 // that any parallel-loop-unaware optimization pass hasn't added loop-carried
312 // dependencies (thus converted the loop back to a sequential loop), check
313 // that all the memory instructions in the loop contain parallelism metadata
314 // that point to the same unique "loop id metadata" the loop branch does.
Sanjay Patel960e5342016-01-15 00:08:10 +0000315 for (BasicBlock *BB : this->blocks()) {
316 for (Instruction &I : *BB) {
317 if (!I.mayReadOrWriteMemory())
Pekka Jaaskelainen0d237252013-02-13 18:08:57 +0000318 continue;
319
Pekka Jaaskelainen0d237252013-02-13 18:08:57 +0000320 // The memory instruction can refer to the loop identifier metadata
321 // directly or indirectly through another list metadata (in case of
322 // nested parallel loops). The loop identifier metadata refers to
323 // itself so we can check both cases with the same routine.
Sanjay Patel6435c6e2016-01-17 23:18:05 +0000324 MDNode *LoopIdMD =
Sanjay Patel960e5342016-01-15 00:08:10 +0000325 I.getMetadata(LLVMContext::MD_mem_parallel_loop_access);
Jakub Staszak9dca4b32013-11-13 20:18:38 +0000326
Sanjay Patel6435c6e2016-01-17 23:18:05 +0000327 if (!LoopIdMD)
Jakub Staszak9dca4b32013-11-13 20:18:38 +0000328 return false;
329
Sanjay Patel6435c6e2016-01-17 23:18:05 +0000330 bool LoopIdMDFound = false;
331 for (const MDOperand &MDOp : LoopIdMD->operands()) {
332 if (MDOp == DesiredLoopIdMetadata) {
333 LoopIdMDFound = true;
Pekka Jaaskelainen0d237252013-02-13 18:08:57 +0000334 break;
335 }
336 }
337
Sanjay Patel6435c6e2016-01-17 23:18:05 +0000338 if (!LoopIdMDFound)
Pekka Jaaskelainen0d237252013-02-13 18:08:57 +0000339 return false;
340 }
341 }
342 return true;
343}
344
Sanjoy Das66a004a2017-09-20 01:12:09 +0000345DebugLoc Loop::getStartLoc() const { return getLocRange().getStart(); }
Amara Emerson0b402012016-11-08 11:18:59 +0000346
347Loop::LocRange Loop::getLocRange() const {
Hal Finkel2f688682016-05-25 21:42:37 +0000348 // If we have a debug location in the loop ID, then use it.
Amara Emerson0b402012016-11-08 11:18:59 +0000349 if (MDNode *LoopID = getLoopID()) {
350 DebugLoc Start;
351 // We use the first DebugLoc in the header as the start location of the loop
352 // and if there is a second DebugLoc in the header we use it as end location
353 // of the loop.
354 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
355 if (DILocation *L = dyn_cast<DILocation>(LoopID->getOperand(i))) {
356 if (!Start)
357 Start = DebugLoc(L);
358 else
359 return LocRange(Start, DebugLoc(L));
360 }
361 }
362
363 if (Start)
364 return LocRange(Start);
365 }
Hal Finkel2f688682016-05-25 21:42:37 +0000366
367 // Try the pre-header first.
368 if (BasicBlock *PHeadBB = getLoopPreheader())
369 if (DebugLoc DL = PHeadBB->getTerminator()->getDebugLoc())
Amara Emerson0b402012016-11-08 11:18:59 +0000370 return LocRange(DL);
Hal Finkel2f688682016-05-25 21:42:37 +0000371
372 // If we have no pre-header or there are no instructions with debug
373 // info in it, try the header.
374 if (BasicBlock *HeadBB = getHeader())
Amara Emerson0b402012016-11-08 11:18:59 +0000375 return LocRange(HeadBB->getTerminator()->getDebugLoc());
Hal Finkel2f688682016-05-25 21:42:37 +0000376
Amara Emerson0b402012016-11-08 11:18:59 +0000377 return LocRange();
Hal Finkel2f688682016-05-25 21:42:37 +0000378}
379
Dan Gohmane3a17062009-11-05 19:21:41 +0000380bool Loop::hasDedicatedExits() const {
Dan Gohman1511f702009-07-16 16:16:23 +0000381 // Each predecessor of each exit block of a normal loop is contained
382 // within the loop.
383 SmallVector<BasicBlock *, 4> ExitBlocks;
384 getExitBlocks(ExitBlocks);
Sanjay Patel960e5342016-01-15 00:08:10 +0000385 for (BasicBlock *BB : ExitBlocks)
386 for (BasicBlock *Predecessor : predecessors(BB))
387 if (!contains(Predecessor))
Dan Gohman1511f702009-07-16 16:16:23 +0000388 return false;
389 // All the requirements are met.
390 return true;
391}
392
Sanjoy Das66a004a2017-09-20 01:12:09 +0000393void Loop::getUniqueExitBlocks(
394 SmallVectorImpl<BasicBlock *> &ExitBlocks) const {
Dan Gohman84ba0392009-12-11 20:05:23 +0000395 assert(hasDedicatedExits() &&
396 "getUniqueExitBlocks assumes the loop has canonical form exits!");
Dan Gohman3ddbc242009-09-08 15:45:00 +0000397
Sanjay Patel6435c6e2016-01-17 23:18:05 +0000398 SmallVector<BasicBlock *, 32> SwitchExitBlocks;
Sanjay Patel960e5342016-01-15 00:08:10 +0000399 for (BasicBlock *BB : this->blocks()) {
Sanjay Patel6435c6e2016-01-17 23:18:05 +0000400 SwitchExitBlocks.clear();
Sanjay Patel960e5342016-01-15 00:08:10 +0000401 for (BasicBlock *Successor : successors(BB)) {
402 // If block is inside the loop then it is not an exit block.
403 if (contains(Successor))
Dan Gohman3a0ce3e2009-09-03 16:10:48 +0000404 continue;
405
Sanjay Patel960e5342016-01-15 00:08:10 +0000406 pred_iterator PI = pred_begin(Successor);
Sanjay Patel6435c6e2016-01-17 23:18:05 +0000407 BasicBlock *FirstPred = *PI;
Dan Gohman3a0ce3e2009-09-03 16:10:48 +0000408
409 // If current basic block is this exit block's first predecessor
410 // then only insert exit block in to the output ExitBlocks vector.
411 // This ensures that same exit block is not inserted twice into
412 // ExitBlocks vector.
Sanjay Patel6435c6e2016-01-17 23:18:05 +0000413 if (BB != FirstPred)
Dan Gohman3a0ce3e2009-09-03 16:10:48 +0000414 continue;
415
416 // If a terminator has more then two successors, for example SwitchInst,
417 // then it is possible that there are multiple edges from current block
418 // to one exit block.
Sanjay Patel960e5342016-01-15 00:08:10 +0000419 if (std::distance(succ_begin(BB), succ_end(BB)) <= 2) {
420 ExitBlocks.push_back(Successor);
Dan Gohman3a0ce3e2009-09-03 16:10:48 +0000421 continue;
422 }
423
424 // In case of multiple edges from current block to exit block, collect
425 // only one edge in ExitBlocks. Use switchExitBlocks to keep track of
426 // duplicate edges.
David Majnemer0a16c222016-08-11 21:15:00 +0000427 if (!is_contained(SwitchExitBlocks, Successor)) {
Sanjay Patel6435c6e2016-01-17 23:18:05 +0000428 SwitchExitBlocks.push_back(Successor);
Sanjay Patel960e5342016-01-15 00:08:10 +0000429 ExitBlocks.push_back(Successor);
Dan Gohman3a0ce3e2009-09-03 16:10:48 +0000430 }
431 }
432 }
433}
434
Dan Gohman3a0ce3e2009-09-03 16:10:48 +0000435BasicBlock *Loop::getUniqueExitBlock() const {
436 SmallVector<BasicBlock *, 8> UniqueExitBlocks;
437 getUniqueExitBlocks(UniqueExitBlocks);
438 if (UniqueExitBlocks.size() == 1)
439 return UniqueExitBlocks[0];
Craig Topper9f008862014-04-15 04:59:12 +0000440 return nullptr;
Dan Gohman3a0ce3e2009-09-03 16:10:48 +0000441}
442
Aaron Ballman615eb472017-10-15 14:32:27 +0000443#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Sanjoy Das66a004a2017-09-20 01:12:09 +0000444LLVM_DUMP_METHOD void Loop::dump() const { print(dbgs()); }
Sebastian Pop18c964d2016-07-27 05:02:17 +0000445
446LLVM_DUMP_METHOD void Loop::dumpVerbose() const {
Sanjoy Das66a004a2017-09-20 01:12:09 +0000447 print(dbgs(), /*Depth=*/0, /*Verbose=*/true);
Sebastian Pop18c964d2016-07-27 05:02:17 +0000448}
Manman Renc3366cc2012-09-06 19:55:56 +0000449#endif
Dan Gohmanc3f21372010-01-05 21:08:02 +0000450
Chris Lattner26750072002-07-27 01:12:17 +0000451//===----------------------------------------------------------------------===//
Andrew Trickd3530b92011-08-10 23:22:57 +0000452// UnloopUpdater implementation
453//
454
Benjamin Kramer4938edb2011-08-19 01:42:18 +0000455namespace {
Andrew Trickd3530b92011-08-10 23:22:57 +0000456/// Find the new parent loop for all blocks within the "unloop" whose last
457/// backedges has just been removed.
458class UnloopUpdater {
Silviu Baranga24dbd2e2016-05-13 14:54:50 +0000459 Loop &Unloop;
Andrew Trickd3530b92011-08-10 23:22:57 +0000460 LoopInfo *LI;
461
462 LoopBlocksDFS DFS;
463
464 // Map unloop's immediate subloops to their nearest reachable parents. Nested
465 // loops within these subloops will not change parents. However, an immediate
466 // subloop's new parent will be the nearest loop reachable from either its own
467 // exits *or* any of its nested loop's exits.
Sanjoy Das66a004a2017-09-20 01:12:09 +0000468 DenseMap<Loop *, Loop *> SubloopParents;
Andrew Trickd3530b92011-08-10 23:22:57 +0000469
470 // Flag the presence of an irreducible backedge whose destination is a block
471 // directly contained by the original unloop.
472 bool FoundIB;
473
474public:
Sanjoy Das66a004a2017-09-20 01:12:09 +0000475 UnloopUpdater(Loop *UL, LoopInfo *LInfo)
476 : Unloop(*UL), LI(LInfo), DFS(UL), FoundIB(false) {}
Andrew Trickd3530b92011-08-10 23:22:57 +0000477
478 void updateBlockParents();
479
Andrew Trickc12c30a2011-08-11 20:27:32 +0000480 void removeBlocksFromAncestors();
481
Andrew Trickd3530b92011-08-10 23:22:57 +0000482 void updateSubloopParents();
483
484protected:
485 Loop *getNearestLoop(BasicBlock *BB, Loop *BBLoop);
486};
Benjamin Kramer4938edb2011-08-19 01:42:18 +0000487} // end anonymous namespace
Andrew Trickd3530b92011-08-10 23:22:57 +0000488
Sanjay Patel784b5e32016-01-14 23:23:04 +0000489/// Update the parent loop for all blocks that are directly contained within the
490/// original "unloop".
Andrew Trickd3530b92011-08-10 23:22:57 +0000491void UnloopUpdater::updateBlockParents() {
Silviu Baranga24dbd2e2016-05-13 14:54:50 +0000492 if (Unloop.getNumBlocks()) {
Andrew Trickd3530b92011-08-10 23:22:57 +0000493 // Perform a post order CFG traversal of all blocks within this loop,
Hiroshi Inoue713b5ba2017-07-09 05:54:44 +0000494 // propagating the nearest loop from successors to predecessors.
Andrew Trickd3530b92011-08-10 23:22:57 +0000495 LoopBlocksTraversal Traversal(DFS, LI);
Benjamin Krameraa209152016-06-26 17:27:42 +0000496 for (BasicBlock *POI : Traversal) {
Andrew Trickd3530b92011-08-10 23:22:57 +0000497
Benjamin Krameraa209152016-06-26 17:27:42 +0000498 Loop *L = LI->getLoopFor(POI);
499 Loop *NL = getNearestLoop(POI, L);
Andrew Trickd3530b92011-08-10 23:22:57 +0000500
501 if (NL != L) {
502 // For reducible loops, NL is now an ancestor of Unloop.
Silviu Baranga24dbd2e2016-05-13 14:54:50 +0000503 assert((NL != &Unloop && (!NL || NL->contains(&Unloop))) &&
Andrew Trickd3530b92011-08-10 23:22:57 +0000504 "uninitialized successor");
Benjamin Krameraa209152016-06-26 17:27:42 +0000505 LI->changeLoopFor(POI, NL);
Sanjoy Das66a004a2017-09-20 01:12:09 +0000506 } else {
Andrew Trickd3530b92011-08-10 23:22:57 +0000507 // Or the current block is part of a subloop, in which case its parent
508 // is unchanged.
Silviu Baranga24dbd2e2016-05-13 14:54:50 +0000509 assert((FoundIB || Unloop.contains(L)) && "uninitialized successor");
Andrew Trickd3530b92011-08-10 23:22:57 +0000510 }
511 }
512 }
513 // Each irreducible loop within the unloop induces a round of iteration using
514 // the DFS result cached by Traversal.
515 bool Changed = FoundIB;
516 for (unsigned NIters = 0; Changed; ++NIters) {
Silviu Baranga24dbd2e2016-05-13 14:54:50 +0000517 assert(NIters < Unloop.getNumBlocks() && "runaway iterative algorithm");
Andrew Trickd3530b92011-08-10 23:22:57 +0000518
519 // Iterate over the postorder list of blocks, propagating the nearest loop
520 // from successors to predecessors as before.
521 Changed = false;
522 for (LoopBlocksDFS::POIterator POI = DFS.beginPostorder(),
Sanjoy Das66a004a2017-09-20 01:12:09 +0000523 POE = DFS.endPostorder();
524 POI != POE; ++POI) {
Andrew Trickd3530b92011-08-10 23:22:57 +0000525
526 Loop *L = LI->getLoopFor(*POI);
527 Loop *NL = getNearestLoop(*POI, L);
528 if (NL != L) {
Silviu Baranga24dbd2e2016-05-13 14:54:50 +0000529 assert(NL != &Unloop && (!NL || NL->contains(&Unloop)) &&
Andrew Trickd3530b92011-08-10 23:22:57 +0000530 "uninitialized successor");
531 LI->changeLoopFor(*POI, NL);
532 Changed = true;
533 }
534 }
535 }
536}
537
Sanjay Patel784b5e32016-01-14 23:23:04 +0000538/// Remove unloop's blocks from all ancestors below their new parents.
Andrew Trickc12c30a2011-08-11 20:27:32 +0000539void UnloopUpdater::removeBlocksFromAncestors() {
Andrew Trick6b4d5782011-11-18 03:42:41 +0000540 // Remove all unloop's blocks (including those in nested subloops) from
541 // ancestors below the new parent loop.
Sanjoy Das66a004a2017-09-20 01:12:09 +0000542 for (Loop::block_iterator BI = Unloop.block_begin(), BE = Unloop.block_end();
543 BI != BE; ++BI) {
Andrew Trick6b4d5782011-11-18 03:42:41 +0000544 Loop *OuterParent = LI->getLoopFor(*BI);
Silviu Baranga24dbd2e2016-05-13 14:54:50 +0000545 if (Unloop.contains(OuterParent)) {
546 while (OuterParent->getParentLoop() != &Unloop)
Andrew Trick6b4d5782011-11-18 03:42:41 +0000547 OuterParent = OuterParent->getParentLoop();
548 OuterParent = SubloopParents[OuterParent];
549 }
Andrew Trickc12c30a2011-08-11 20:27:32 +0000550 // Remove blocks from former Ancestors except Unloop itself which will be
551 // deleted.
Silviu Baranga24dbd2e2016-05-13 14:54:50 +0000552 for (Loop *OldParent = Unloop.getParentLoop(); OldParent != OuterParent;
Andrew Trickc12c30a2011-08-11 20:27:32 +0000553 OldParent = OldParent->getParentLoop()) {
554 assert(OldParent && "new loop is not an ancestor of the original");
555 OldParent->removeBlockFromLoop(*BI);
556 }
557 }
558}
559
Sanjay Patel784b5e32016-01-14 23:23:04 +0000560/// Update the parent loop for all subloops directly nested within unloop.
Andrew Trickd3530b92011-08-10 23:22:57 +0000561void UnloopUpdater::updateSubloopParents() {
Silviu Baranga24dbd2e2016-05-13 14:54:50 +0000562 while (!Unloop.empty()) {
563 Loop *Subloop = *std::prev(Unloop.end());
564 Unloop.removeChildLoop(std::prev(Unloop.end()));
Andrew Trickd3530b92011-08-10 23:22:57 +0000565
566 assert(SubloopParents.count(Subloop) && "DFS failed to visit subloop");
Benjamin Kramerf29db272012-08-22 15:37:57 +0000567 if (Loop *Parent = SubloopParents[Subloop])
568 Parent->addChildLoop(Subloop);
Andrew Trick147d9cd2011-08-26 03:06:34 +0000569 else
570 LI->addTopLevelLoop(Subloop);
Andrew Trickd3530b92011-08-10 23:22:57 +0000571 }
572}
573
Sanjay Patel784b5e32016-01-14 23:23:04 +0000574/// Return the nearest parent loop among this block's successors. If a successor
575/// is a subloop header, consider its parent to be the nearest parent of the
576/// subloop's exits.
Andrew Trickd3530b92011-08-10 23:22:57 +0000577///
578/// For subloop blocks, simply update SubloopParents and return NULL.
579Loop *UnloopUpdater::getNearestLoop(BasicBlock *BB, Loop *BBLoop) {
580
Andrew Trick266ab102011-08-11 17:54:58 +0000581 // Initially for blocks directly contained by Unloop, NearLoop == Unloop and
582 // is considered uninitialized.
Andrew Trickd3530b92011-08-10 23:22:57 +0000583 Loop *NearLoop = BBLoop;
584
Craig Topper9f008862014-04-15 04:59:12 +0000585 Loop *Subloop = nullptr;
Silviu Baranga24dbd2e2016-05-13 14:54:50 +0000586 if (NearLoop != &Unloop && Unloop.contains(NearLoop)) {
Andrew Trickd3530b92011-08-10 23:22:57 +0000587 Subloop = NearLoop;
588 // Find the subloop ancestor that is directly contained within Unloop.
Silviu Baranga24dbd2e2016-05-13 14:54:50 +0000589 while (Subloop->getParentLoop() != &Unloop) {
Andrew Trickd3530b92011-08-10 23:22:57 +0000590 Subloop = Subloop->getParentLoop();
591 assert(Subloop && "subloop is not an ancestor of the original loop");
592 }
593 // Get the current nearest parent of the Subloop exits, initially Unloop.
David Majnemer0a16c222016-08-11 21:15:00 +0000594 NearLoop = SubloopParents.insert({Subloop, &Unloop}).first->second;
Andrew Trickd3530b92011-08-10 23:22:57 +0000595 }
596
597 succ_iterator I = succ_begin(BB), E = succ_end(BB);
598 if (I == E) {
599 assert(!Subloop && "subloop blocks must have a successor");
Craig Topper9f008862014-04-15 04:59:12 +0000600 NearLoop = nullptr; // unloop blocks may now exit the function.
Andrew Trickd3530b92011-08-10 23:22:57 +0000601 }
602 for (; I != E; ++I) {
603 if (*I == BB)
604 continue; // self loops are uninteresting
605
606 Loop *L = LI->getLoopFor(*I);
Silviu Baranga24dbd2e2016-05-13 14:54:50 +0000607 if (L == &Unloop) {
Andrew Trickd3530b92011-08-10 23:22:57 +0000608 // This successor has not been processed. This path must lead to an
609 // irreducible backedge.
610 assert((FoundIB || !DFS.hasPostorder(*I)) && "should have seen IB");
611 FoundIB = true;
612 }
Silviu Baranga24dbd2e2016-05-13 14:54:50 +0000613 if (L != &Unloop && Unloop.contains(L)) {
Andrew Trickd3530b92011-08-10 23:22:57 +0000614 // Successor is in a subloop.
615 if (Subloop)
616 continue; // Branching within subloops. Ignore it.
617
618 // BB branches from the original into a subloop header.
Silviu Baranga24dbd2e2016-05-13 14:54:50 +0000619 assert(L->getParentLoop() == &Unloop && "cannot skip into nested loops");
Andrew Trickd3530b92011-08-10 23:22:57 +0000620
621 // Get the current nearest parent of the Subloop's exits.
622 L = SubloopParents[L];
623 // L could be Unloop if the only exit was an irreducible backedge.
624 }
Silviu Baranga24dbd2e2016-05-13 14:54:50 +0000625 if (L == &Unloop) {
Andrew Trickd3530b92011-08-10 23:22:57 +0000626 continue;
627 }
628 // Handle critical edges from Unloop into a sibling loop.
Silviu Baranga24dbd2e2016-05-13 14:54:50 +0000629 if (L && !L->contains(&Unloop)) {
Andrew Trickd3530b92011-08-10 23:22:57 +0000630 L = L->getParentLoop();
631 }
632 // Remember the nearest parent loop among successors or subloop exits.
Silviu Baranga24dbd2e2016-05-13 14:54:50 +0000633 if (NearLoop == &Unloop || !NearLoop || NearLoop->contains(L))
Andrew Trickd3530b92011-08-10 23:22:57 +0000634 NearLoop = L;
635 }
636 if (Subloop) {
637 SubloopParents[Subloop] = NearLoop;
638 return BBLoop;
639 }
640 return NearLoop;
641}
642
Sanjoy Das66a004a2017-09-20 01:12:09 +0000643LoopInfo::LoopInfo(const DomTreeBase<BasicBlock> &DomTree) { analyze(DomTree); }
Cong Hou9b4f6b22015-07-16 23:23:35 +0000644
Chandler Carruthca68a3e2017-01-15 06:32:49 +0000645bool LoopInfo::invalidate(Function &F, const PreservedAnalyses &PA,
646 FunctionAnalysisManager::Invalidator &) {
647 // Check whether the analysis, all analyses on functions, or the function's
648 // CFG have been preserved.
649 auto PAC = PA.getChecker<LoopAnalysis>();
650 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>() ||
651 PAC.preservedSet<CFGAnalyses>());
652}
653
Sanjoy Das388b0122017-09-22 01:47:41 +0000654void LoopInfo::erase(Loop *Unloop) {
Sanjoy Das76ab2322017-09-19 23:19:00 +0000655 assert(!Unloop->isInvalid() && "Loop has already been erased!");
Andrew Trickd3530b92011-08-10 23:22:57 +0000656
Sanjoy Dasdef17292017-09-28 02:45:42 +0000657 auto InvalidateOnExit = make_scope_exit([&]() { destroy(Unloop); });
Sanjoy Das09613b12017-09-20 02:31:57 +0000658
Andrew Trickd3530b92011-08-10 23:22:57 +0000659 // First handle the special case of no parent loop to simplify the algorithm.
660 if (!Unloop->getParentLoop()) {
661 // Since BBLoop had no parent, Unloop blocks are no longer in a loop.
662 for (Loop::block_iterator I = Unloop->block_begin(),
Chandler Carruth691addc2015-01-18 01:25:51 +0000663 E = Unloop->block_end();
664 I != E; ++I) {
Andrew Trickd3530b92011-08-10 23:22:57 +0000665
666 // Don't reparent blocks in subloops.
667 if (getLoopFor(*I) != Unloop)
668 continue;
669
670 // Blocks no longer have a parent but are still referenced by Unloop until
671 // the Unloop object is deleted.
Chandler Carruth691addc2015-01-18 01:25:51 +0000672 changeLoopFor(*I, nullptr);
Andrew Trickd3530b92011-08-10 23:22:57 +0000673 }
674
675 // Remove the loop from the top-level LoopInfo object.
Chandler Carruth691addc2015-01-18 01:25:51 +0000676 for (iterator I = begin();; ++I) {
677 assert(I != end() && "Couldn't find loop");
Andrew Trickd3530b92011-08-10 23:22:57 +0000678 if (*I == Unloop) {
Chandler Carruth691addc2015-01-18 01:25:51 +0000679 removeLoop(I);
Andrew Trickd3530b92011-08-10 23:22:57 +0000680 break;
681 }
682 }
683
684 // Move all of the subloops to the top-level.
685 while (!Unloop->empty())
Chandler Carruth691addc2015-01-18 01:25:51 +0000686 addTopLevelLoop(Unloop->removeChildLoop(std::prev(Unloop->end())));
Andrew Trickd3530b92011-08-10 23:22:57 +0000687
688 return;
689 }
690
691 // Update the parent loop for all blocks within the loop. Blocks within
692 // subloops will not change parents.
693 UnloopUpdater Updater(Unloop, this);
694 Updater.updateBlockParents();
695
Andrew Trickc12c30a2011-08-11 20:27:32 +0000696 // Remove blocks from former ancestor loops.
697 Updater.removeBlocksFromAncestors();
Andrew Trickd3530b92011-08-10 23:22:57 +0000698
699 // Add direct subloops as children in their new parent loop.
700 Updater.updateSubloopParents();
701
702 // Remove unloop from its parent loop.
703 Loop *ParentLoop = Unloop->getParentLoop();
Duncan Sandsa41634e2011-08-12 14:54:45 +0000704 for (Loop::iterator I = ParentLoop->begin();; ++I) {
705 assert(I != ParentLoop->end() && "Couldn't find loop");
Andrew Trickd3530b92011-08-10 23:22:57 +0000706 if (*I == Unloop) {
707 ParentLoop->removeChildLoop(I);
708 break;
709 }
710 }
711}
712
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000713AnalysisKey LoopAnalysis::Key;
NAKAMURA Takumidf0cd722016-02-28 17:17:00 +0000714
Sean Silva36e0d012016-08-09 00:28:15 +0000715LoopInfo LoopAnalysis::run(Function &F, FunctionAnalysisManager &AM) {
Chandler Carruthaaf0b4c2015-01-20 10:58:50 +0000716 // FIXME: Currently we create a LoopInfo from scratch for every function.
717 // This may prove to be too wasteful due to deallocating and re-allocating
718 // memory each time for the underlying map and vector datastructures. At some
719 // point it may prove worthwhile to use a freelist and recycle LoopInfo
720 // objects. I don't want to add that kind of complexity until the scope of
721 // the problem is better understood.
722 LoopInfo LI;
Chandler Carruthb47f8012016-03-11 11:05:24 +0000723 LI.analyze(AM.getResult<DominatorTreeAnalysis>(F));
Richard Trieu6ae37962015-04-30 23:07:00 +0000724 return LI;
Chandler Carruthaaf0b4c2015-01-20 10:58:50 +0000725}
726
727PreservedAnalyses LoopPrinterPass::run(Function &F,
Sean Silva36e0d012016-08-09 00:28:15 +0000728 FunctionAnalysisManager &AM) {
Chandler Carruthb47f8012016-03-11 11:05:24 +0000729 AM.getResult<LoopAnalysis>(F).print(OS);
Chandler Carruthaaf0b4c2015-01-20 10:58:50 +0000730 return PreservedAnalyses::all();
731}
732
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000733void llvm::printLoop(Loop &L, raw_ostream &OS, const std::string &Banner) {
Fedor Sergeev3b459c32017-12-01 18:33:58 +0000734
735 if (forcePrintModuleIR()) {
736 // handling -print-module-scope
737 OS << Banner << " (loop: ";
738 L.getHeader()->printAsOperand(OS, false);
739 OS << ")\n";
740
741 // printing whole module
742 OS << *L.getHeader()->getModule();
743 return;
744 }
745
Justin Bognerc2b98f02015-11-04 22:24:08 +0000746 OS << Banner;
Fedor Sergeev61975b42017-11-22 20:59:53 +0000747
748 auto *PreHeader = L.getLoopPreheader();
749 if (PreHeader) {
750 OS << "\n; Preheader:";
751 PreHeader->print(OS);
752 OS << "\n; Loop:";
753 }
754
Justin Bognerc2b98f02015-11-04 22:24:08 +0000755 for (auto *Block : L.blocks())
756 if (Block)
757 Block->print(OS);
758 else
759 OS << "Printing <null> block";
Fedor Sergeev61975b42017-11-22 20:59:53 +0000760
761 SmallVector<BasicBlock *, 8> ExitBlocks;
762 L.getExitBlocks(ExitBlocks);
763 if (!ExitBlocks.empty()) {
764 OS << "\n; Exit blocks";
765 for (auto *Block : ExitBlocks)
766 if (Block)
767 Block->print(OS);
768 else
769 OS << "Printing <null> block";
770 }
Justin Bognerc2b98f02015-11-04 22:24:08 +0000771}
772
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000773//===----------------------------------------------------------------------===//
774// LoopInfo implementation
775//
776
777char LoopInfoWrapperPass::ID = 0;
778INITIALIZE_PASS_BEGIN(LoopInfoWrapperPass, "loops", "Natural Loop Information",
779 true, true)
780INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
781INITIALIZE_PASS_END(LoopInfoWrapperPass, "loops", "Natural Loop Information",
782 true, true)
783
784bool LoopInfoWrapperPass::runOnFunction(Function &) {
785 releaseMemory();
Cong Houd2c1d912015-07-16 18:23:57 +0000786 LI.analyze(getAnalysis<DominatorTreeWrapperPass>().getDomTree());
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000787 return false;
788}
789
790void LoopInfoWrapperPass::verifyAnalysis() const {
791 // LoopInfoWrapperPass is a FunctionPass, but verifying every loop in the
792 // function each time verifyAnalysis is called is very expensive. The
Dan Gohman4dbb3012009-09-28 00:27:48 +0000793 // -verify-loop-info option can enable this. In order to perform some
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000794 // checking by default, LoopPass has been taught to call verifyLoop manually
795 // during loop pass sequences.
Michael Zolotukhine0b2d972016-08-31 19:26:19 +0000796 if (VerifyLoopInfo) {
Serge Pavloved5eb932017-01-15 10:23:18 +0000797 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
798 LI.verify(DT);
Michael Zolotukhine0b2d972016-08-31 19:26:19 +0000799 }
Dan Gohman3ddbc242009-09-08 15:45:00 +0000800}
801
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000802void LoopInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerc8e66542002-04-27 06:56:12 +0000803 AU.setPreservesAll();
Chandler Carruth73523022014-01-13 13:07:17 +0000804 AU.addRequired<DominatorTreeWrapperPass>();
Chris Lattnerccf571a2002-01-31 00:42:27 +0000805}
Chris Lattnerb1d782b2009-08-23 05:17:37 +0000806
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000807void LoopInfoWrapperPass::print(raw_ostream &OS, const Module *) const {
Chandler Carruth691addc2015-01-18 01:25:51 +0000808 LI.print(OS);
Chris Lattnerb1d782b2009-08-23 05:17:37 +0000809}
810
Sean Silvae3c18a52016-07-19 23:54:23 +0000811PreservedAnalyses LoopVerifierPass::run(Function &F,
Sean Silva36e0d012016-08-09 00:28:15 +0000812 FunctionAnalysisManager &AM) {
Sean Silvae3c18a52016-07-19 23:54:23 +0000813 LoopInfo &LI = AM.getResult<LoopAnalysis>(F);
Michael Zolotukhine0b2d972016-08-31 19:26:19 +0000814 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
815 LI.verify(DT);
Sean Silvae3c18a52016-07-19 23:54:23 +0000816 return PreservedAnalyses::all();
817}
818
Andrew Trick78b40c32011-08-10 01:59:05 +0000819//===----------------------------------------------------------------------===//
820// LoopBlocksDFS implementation
821//
822
823/// Traverse the loop blocks and store the DFS result.
824/// Useful for clients that just want the final DFS result and don't need to
825/// visit blocks during the initial traversal.
826void LoopBlocksDFS::perform(LoopInfo *LI) {
827 LoopBlocksTraversal Traversal(*this, LI);
828 for (LoopBlocksTraversal::POTIterator POI = Traversal.begin(),
Sanjoy Das66a004a2017-09-20 01:12:09 +0000829 POE = Traversal.end();
830 POI != POE; ++POI)
831 ;
Andrew Trick78b40c32011-08-10 01:59:05 +0000832}