blob: fec808d5d312d15c6ed446b60293c19cf0953cd6 [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"
Nico Weber432a3882018-04-30 14:59:11 +000024#include "llvm/Config/llvm-config.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000025#include "llvm/IR/CFG.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000026#include "llvm/IR/Constants.h"
Hal Finkel2f688682016-05-25 21:42:37 +000027#include "llvm/IR/DebugLoc.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000028#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000029#include "llvm/IR/Instructions.h"
Philip Reames5a3f5f72014-10-21 00:13:20 +000030#include "llvm/IR/LLVMContext.h"
Pekka Jaaskelainen0d237252013-02-13 18:08:57 +000031#include "llvm/IR/Metadata.h"
Chandler Carruthaaf0b4c2015-01-20 10:58:50 +000032#include "llvm/IR/PassManager.h"
Dan Gohman4dbb3012009-09-28 00:27:48 +000033#include "llvm/Support/CommandLine.h"
Dan Gohmanc3f21372010-01-05 21:08:02 +000034#include "llvm/Support/Debug.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000035#include "llvm/Support/raw_ostream.h"
Chris Lattner6de99422001-11-26 18:41:20 +000036#include <algorithm>
Chris Lattner55b7ef52004-04-12 20:26:17 +000037using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000038
Andrew Trickcda51d42012-06-20 03:42:09 +000039// Explicitly instantiate methods in LoopInfoImpl.h for IR-level Loops.
40template class llvm::LoopBase<BasicBlock, Loop>;
41template class llvm::LoopInfoBase<BasicBlock, Loop>;
42
Dan Gohman4dbb3012009-09-28 00:27:48 +000043// Always verify loopinfo if expensive checking is enabled.
Filipe Cabecinhas0da99372016-04-29 15:22:48 +000044#ifdef EXPENSIVE_CHECKS
Serge Pavlov69b3ff92017-01-24 05:52:07 +000045bool llvm::VerifyLoopInfo = true;
Dan Gohman4dbb3012009-09-28 00:27:48 +000046#else
Serge Pavlov69b3ff92017-01-24 05:52:07 +000047bool llvm::VerifyLoopInfo = false;
Dan Gohman4dbb3012009-09-28 00:27:48 +000048#endif
Sanjoy Das66a004a2017-09-20 01:12:09 +000049static cl::opt<bool, true>
50 VerifyLoopInfoX("verify-loop-info", cl::location(VerifyLoopInfo),
Zachary Turner8065f0b2017-12-01 00:53:10 +000051 cl::Hidden, cl::desc("Verify loop info (time consuming)"));
Dan Gohman4dbb3012009-09-28 00:27:48 +000052
Chris Lattnerccf571a2002-01-31 00:42:27 +000053//===----------------------------------------------------------------------===//
Chris Lattner78dd56f2002-04-28 16:21:30 +000054// Loop implementation
Chris Lattnerccf571a2002-01-31 00:42:27 +000055//
Misha Brukman3845be22002-10-11 05:31:10 +000056
Pete Cooper016daa62015-05-13 01:12:06 +000057bool Loop::isLoopInvariant(const Value *V) const {
58 if (const Instruction *I = dyn_cast<Instruction>(V))
Chris Lattnerda24b9a2010-09-06 01:05:37 +000059 return !contains(I);
Sanjoy Das66a004a2017-09-20 01:12:09 +000060 return true; // All non-instructions are loop invariant
Dan Gohman80a99422009-07-13 22:02:44 +000061}
62
Pete Cooper016daa62015-05-13 01:12:06 +000063bool Loop::hasLoopInvariantOperands(const Instruction *I) const {
Pete Coopera264dc02015-05-13 22:19:13 +000064 return all_of(I->operands(), [this](Value *V) { return isLoopInvariant(V); });
Dan Gohman6f6d8642009-07-14 01:06:29 +000065}
66
Dan Gohmanc43e4792009-07-15 01:25:43 +000067bool Loop::makeLoopInvariant(Value *V, bool &Changed,
68 Instruction *InsertPt) const {
Dan Gohman6f6d8642009-07-14 01:06:29 +000069 if (Instruction *I = dyn_cast<Instruction>(V))
Dan Gohmanc43e4792009-07-15 01:25:43 +000070 return makeLoopInvariant(I, Changed, InsertPt);
Sanjoy Das66a004a2017-09-20 01:12:09 +000071 return true; // All non-instructions are loop-invariant.
Dan Gohman6f6d8642009-07-14 01:06:29 +000072}
73
Dan Gohmanc43e4792009-07-15 01:25:43 +000074bool Loop::makeLoopInvariant(Instruction *I, bool &Changed,
75 Instruction *InsertPt) const {
Dan Gohman6f6d8642009-07-14 01:06:29 +000076 // Test if the value is already loop-invariant.
77 if (isLoopInvariant(I))
78 return true;
Dan Gohman75d7d5e2011-12-14 23:49:11 +000079 if (!isSafeToSpeculativelyExecute(I))
Dan Gohman6f6d8642009-07-14 01:06:29 +000080 return false;
Eli Friedmanb8f6a4f2009-07-17 04:28:42 +000081 if (I->mayReadFromMemory())
Dan Gohman6f6d8642009-07-14 01:06:29 +000082 return false;
David Majnemer654e1302015-07-31 17:58:14 +000083 // EH block instructions are immobile.
84 if (I->isEHPad())
Bill Wendlinga9ee09f2011-08-17 20:36:44 +000085 return false;
Dan Gohman6f6d8642009-07-14 01:06:29 +000086 // Determine the insertion point, unless one was given.
87 if (!InsertPt) {
88 BasicBlock *Preheader = getLoopPreheader();
89 // Without a preheader, hoisting is not feasible.
90 if (!Preheader)
91 return false;
92 InsertPt = Preheader->getTerminator();
93 }
94 // Don't hoist instructions with loop-variant operands.
Sanjay Patel960e5342016-01-15 00:08:10 +000095 for (Value *Operand : I->operands())
96 if (!makeLoopInvariant(Operand, Changed, InsertPt))
Dan Gohman6f6d8642009-07-14 01:06:29 +000097 return false;
Andrew Trickf898cbd2011-08-03 23:45:50 +000098
Dan Gohman6f6d8642009-07-14 01:06:29 +000099 // Hoist.
100 I->moveBefore(InsertPt);
Igor Laevsky7310c682015-11-18 14:50:18 +0000101
102 // There is possibility of hoisting this instruction above some arbitrary
103 // condition. Any metadata defined on it can be control dependent on this
104 // condition. Conservatively strip it here so that we don't give any wrong
105 // information to the optimizer.
106 I->dropUnknownNonDebugMetadata();
107
Dan Gohmanc43e4792009-07-15 01:25:43 +0000108 Changed = true;
Dan Gohman6f6d8642009-07-14 01:06:29 +0000109 return true;
110}
111
Dan Gohman80a99422009-07-13 22:02:44 +0000112PHINode *Loop::getCanonicalInductionVariable() const {
113 BasicBlock *H = getHeader();
114
Craig Topper9f008862014-04-15 04:59:12 +0000115 BasicBlock *Incoming = nullptr, *Backedge = nullptr;
Dan Gohmanacafc612010-07-23 21:25:16 +0000116 pred_iterator PI = pred_begin(H);
Sanjoy Das66a004a2017-09-20 01:12:09 +0000117 assert(PI != pred_end(H) && "Loop must have at least one backedge!");
Dan Gohman80a99422009-07-13 22:02:44 +0000118 Backedge = *PI++;
Sanjoy Das66a004a2017-09-20 01:12:09 +0000119 if (PI == pred_end(H))
120 return nullptr; // dead loop
Dan Gohman80a99422009-07-13 22:02:44 +0000121 Incoming = *PI++;
Sanjoy Das66a004a2017-09-20 01:12:09 +0000122 if (PI != pred_end(H))
123 return nullptr; // multiple backedges?
Dan Gohman80a99422009-07-13 22:02:44 +0000124
125 if (contains(Incoming)) {
126 if (contains(Backedge))
Craig Topper9f008862014-04-15 04:59:12 +0000127 return nullptr;
Dan Gohman80a99422009-07-13 22:02:44 +0000128 std::swap(Incoming, Backedge);
129 } else if (!contains(Backedge))
Craig Topper9f008862014-04-15 04:59:12 +0000130 return nullptr;
Dan Gohman80a99422009-07-13 22:02:44 +0000131
132 // Loop over all of the PHI nodes, looking for a canonical indvar.
133 for (BasicBlock::iterator I = H->begin(); isa<PHINode>(I); ++I) {
134 PHINode *PN = cast<PHINode>(I);
135 if (ConstantInt *CI =
Sanjoy Das66a004a2017-09-20 01:12:09 +0000136 dyn_cast<ConstantInt>(PN->getIncomingValueForBlock(Incoming)))
Craig Topper79ab6432017-07-06 18:39:47 +0000137 if (CI->isZero())
Dan Gohman80a99422009-07-13 22:02:44 +0000138 if (Instruction *Inc =
Sanjoy Das66a004a2017-09-20 01:12:09 +0000139 dyn_cast<Instruction>(PN->getIncomingValueForBlock(Backedge)))
140 if (Inc->getOpcode() == Instruction::Add && Inc->getOperand(0) == PN)
Dan Gohman80a99422009-07-13 22:02:44 +0000141 if (ConstantInt *CI = dyn_cast<ConstantInt>(Inc->getOperand(1)))
Craig Topperca2c8762017-07-06 18:39:49 +0000142 if (CI->isOne())
Dan Gohman80a99422009-07-13 22:02:44 +0000143 return PN;
144 }
Craig Topper9f008862014-04-15 04:59:12 +0000145 return nullptr;
Dan Gohman80a99422009-07-13 22:02:44 +0000146}
147
Igor Laevsky04423cf2016-10-11 13:37:22 +0000148// Check that 'BB' doesn't have any uses outside of the 'L'
149static bool isBlockInLCSSAForm(const Loop &L, const BasicBlock &BB,
150 DominatorTree &DT) {
151 for (const Instruction &I : BB) {
152 // Tokens can't be used in PHI nodes and live-out tokens prevent loop
153 // optimizations, so for the purposes of considered LCSSA form, we
154 // can ignore them.
155 if (I.getType()->isTokenTy())
156 continue;
Andrew Kaylor123048d2015-12-18 18:12:35 +0000157
Igor Laevsky04423cf2016-10-11 13:37:22 +0000158 for (const Use &U : I.uses()) {
159 const Instruction *UI = cast<Instruction>(U.getUser());
160 const BasicBlock *UserBB = UI->getParent();
161 if (const PHINode *P = dyn_cast<PHINode>(UI))
162 UserBB = P->getIncomingBlock(U);
Dan Gohman80a99422009-07-13 22:02:44 +0000163
Igor Laevsky04423cf2016-10-11 13:37:22 +0000164 // Check the current block, as a fast-path, before checking whether
165 // the use is anywhere in the loop. Most values are used in the same
166 // block they are defined in. Also, blocks not reachable from the
167 // entry are special; uses in them don't need to go through PHIs.
168 if (UserBB != &BB && !L.contains(UserBB) &&
169 DT.isReachableFromEntry(UserBB))
170 return false;
Andrew Kaylor123048d2015-12-18 18:12:35 +0000171 }
Dan Gohman80a99422009-07-13 22:02:44 +0000172 }
Dan Gohman80a99422009-07-13 22:02:44 +0000173 return true;
174}
Dan Gohman1511f702009-07-16 16:16:23 +0000175
Igor Laevsky04423cf2016-10-11 13:37:22 +0000176bool Loop::isLCSSAForm(DominatorTree &DT) const {
177 // For each block we check that it doesn't have any uses outside of this loop.
178 return all_of(this->blocks(), [&](const BasicBlock *BB) {
179 return isBlockInLCSSAForm(*this, *BB, DT);
180 });
181}
Sanjoy Das683bf072015-12-08 00:13:21 +0000182
Igor Laevsky04423cf2016-10-11 13:37:22 +0000183bool Loop::isRecursivelyLCSSAForm(DominatorTree &DT, const LoopInfo &LI) const {
Davide Italiano362cc7b2017-01-08 22:22:09 +0000184 // For each block we check that it doesn't have any uses outside of its
185 // innermost loop. This process will transitively guarantee that the current
186 // loop and all of the nested loops are in LCSSA form.
Igor Laevsky04423cf2016-10-11 13:37:22 +0000187 return all_of(this->blocks(), [&](const BasicBlock *BB) {
188 return isBlockInLCSSAForm(*LI.getLoopFor(BB), *BB, DT);
189 });
Sanjoy Das683bf072015-12-08 00:13:21 +0000190}
191
Dan Gohman1511f702009-07-16 16:16:23 +0000192bool Loop::isLoopSimplifyForm() const {
Dan Gohmane3a17062009-11-05 19:21:41 +0000193 // Normal-form loops have a preheader, a single backedge, and all of their
194 // exits have all their predecessors inside the loop.
195 return getLoopPreheader() && getLoopLatch() && hasDedicatedExits();
196}
197
Sanjay Patel784b5e32016-01-14 23:23:04 +0000198// Routines that reform the loop CFG and split edges often fail on indirectbr.
Andrew Trick4442bfe2012-04-10 05:14:42 +0000199bool Loop::isSafeToClone() const {
James Molloy4f6fb952012-12-20 16:04:27 +0000200 // Return false if any loop blocks contain indirectbrs, or there are any calls
201 // to noduplicate functions.
Sanjay Patel960e5342016-01-15 00:08:10 +0000202 for (BasicBlock *BB : this->blocks()) {
203 if (isa<IndirectBrInst>(BB->getTerminator()))
Andrew Trick4442bfe2012-04-10 05:14:42 +0000204 return false;
Jakub Staszak9dca4b32013-11-13 20:18:38 +0000205
David Majnemer3d90bb72016-05-03 03:57:40 +0000206 for (Instruction &I : *BB)
207 if (auto CS = CallSite(&I))
208 if (CS.cannotDuplicate())
James Molloy4f6fb952012-12-20 16:04:27 +0000209 return false;
Andrew Trick4442bfe2012-04-10 05:14:42 +0000210 }
211 return true;
212}
213
Paul Redmond5fdf8362013-05-28 20:00:34 +0000214MDNode *Loop::getLoopID() const {
Craig Topper9f008862014-04-15 04:59:12 +0000215 MDNode *LoopID = nullptr;
Xin Tongca023602017-01-15 21:17:52 +0000216 if (BasicBlock *Latch = getLoopLatch()) {
217 LoopID = Latch->getTerminator()->getMetadata(LLVMContext::MD_loop);
Paul Redmond5fdf8362013-05-28 20:00:34 +0000218 } else {
Xin Tongca023602017-01-15 21:17:52 +0000219 assert(!getLoopLatch() &&
220 "The loop should have no single latch at this point");
Paul Redmond5fdf8362013-05-28 20:00:34 +0000221 // Go through each predecessor of the loop header and check the
222 // terminator for the metadata.
223 BasicBlock *H = getHeader();
Sanjay Patel960e5342016-01-15 00:08:10 +0000224 for (BasicBlock *BB : this->blocks()) {
225 TerminatorInst *TI = BB->getTerminator();
Craig Topper9f008862014-04-15 04:59:12 +0000226 MDNode *MD = nullptr;
Paul Redmond5fdf8362013-05-28 20:00:34 +0000227
228 // Check if this terminator branches to the loop header.
Sanjay Patel960e5342016-01-15 00:08:10 +0000229 for (BasicBlock *Successor : TI->successors()) {
230 if (Successor == H) {
Duncan P. N. Exon Smith1d15a9f2016-03-25 00:35:38 +0000231 MD = TI->getMetadata(LLVMContext::MD_loop);
Paul Redmond5fdf8362013-05-28 20:00:34 +0000232 break;
233 }
234 }
235 if (!MD)
Craig Topper9f008862014-04-15 04:59:12 +0000236 return nullptr;
Paul Redmond5fdf8362013-05-28 20:00:34 +0000237
238 if (!LoopID)
239 LoopID = MD;
240 else if (MD != LoopID)
Craig Topper9f008862014-04-15 04:59:12 +0000241 return nullptr;
Paul Redmond5fdf8362013-05-28 20:00:34 +0000242 }
243 }
244 if (!LoopID || LoopID->getNumOperands() == 0 ||
245 LoopID->getOperand(0) != LoopID)
Craig Topper9f008862014-04-15 04:59:12 +0000246 return nullptr;
Paul Redmond5fdf8362013-05-28 20:00:34 +0000247 return LoopID;
248}
249
250void Loop::setLoopID(MDNode *LoopID) const {
251 assert(LoopID && "Loop ID should not be null");
252 assert(LoopID->getNumOperands() > 0 && "Loop ID needs at least one operand");
253 assert(LoopID->getOperand(0) == LoopID && "Loop ID should refer to itself");
254
Xin Tongca023602017-01-15 21:17:52 +0000255 if (BasicBlock *Latch = getLoopLatch()) {
256 Latch->getTerminator()->setMetadata(LLVMContext::MD_loop, LoopID);
Paul Redmond5fdf8362013-05-28 20:00:34 +0000257 return;
258 }
259
Sanjoy Das66a004a2017-09-20 01:12:09 +0000260 assert(!getLoopLatch() &&
261 "The loop should have no single latch at this point");
Paul Redmond5fdf8362013-05-28 20:00:34 +0000262 BasicBlock *H = getHeader();
Sanjay Patel960e5342016-01-15 00:08:10 +0000263 for (BasicBlock *BB : this->blocks()) {
264 TerminatorInst *TI = BB->getTerminator();
265 for (BasicBlock *Successor : TI->successors()) {
266 if (Successor == H)
Duncan P. N. Exon Smith1d15a9f2016-03-25 00:35:38 +0000267 TI->setMetadata(LLVMContext::MD_loop, LoopID);
Paul Redmond5fdf8362013-05-28 20:00:34 +0000268 }
269 }
270}
271
Hongbin Zheng73f65042017-10-15 07:31:02 +0000272void Loop::setLoopAlreadyUnrolled() {
273 MDNode *LoopID = getLoopID();
274 // First remove any existing loop unrolling metadata.
275 SmallVector<Metadata *, 4> MDs;
276 // Reserve first location for self reference to the LoopID metadata node.
277 MDs.push_back(nullptr);
278
279 if (LoopID) {
280 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
281 bool IsUnrollMetadata = false;
282 MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
283 if (MD) {
284 const MDString *S = dyn_cast<MDString>(MD->getOperand(0));
285 IsUnrollMetadata = S && S->getString().startswith("llvm.loop.unroll.");
286 }
287 if (!IsUnrollMetadata)
288 MDs.push_back(LoopID->getOperand(i));
289 }
290 }
291
292 // Add unroll(disable) metadata to disable future unrolling.
293 LLVMContext &Context = getHeader()->getContext();
294 SmallVector<Metadata *, 1> DisableOperands;
295 DisableOperands.push_back(MDString::get(Context, "llvm.loop.unroll.disable"));
296 MDNode *DisableNode = MDNode::get(Context, DisableOperands);
297 MDs.push_back(DisableNode);
298
299 MDNode *NewLoopID = MDNode::get(Context, MDs);
300 // Set operand 0 to refer to the loop id itself.
301 NewLoopID->replaceOperandWith(0, NewLoopID);
302 setLoopID(NewLoopID);
303}
304
Pekka Jaaskelainen0d237252013-02-13 18:08:57 +0000305bool Loop::isAnnotatedParallel() const {
Sanjay Patel6435c6e2016-01-17 23:18:05 +0000306 MDNode *DesiredLoopIdMetadata = getLoopID();
Pekka Jaaskelainen0d237252013-02-13 18:08:57 +0000307
Sanjay Patel6435c6e2016-01-17 23:18:05 +0000308 if (!DesiredLoopIdMetadata)
Sanjoy Das66a004a2017-09-20 01:12:09 +0000309 return false;
Pekka Jaaskelainen0d237252013-02-13 18:08:57 +0000310
311 // The loop branch contains the parallel loop metadata. In order to ensure
312 // that any parallel-loop-unaware optimization pass hasn't added loop-carried
313 // dependencies (thus converted the loop back to a sequential loop), check
314 // that all the memory instructions in the loop contain parallelism metadata
315 // that point to the same unique "loop id metadata" the loop branch does.
Sanjay Patel960e5342016-01-15 00:08:10 +0000316 for (BasicBlock *BB : this->blocks()) {
317 for (Instruction &I : *BB) {
318 if (!I.mayReadOrWriteMemory())
Pekka Jaaskelainen0d237252013-02-13 18:08:57 +0000319 continue;
320
Pekka Jaaskelainen0d237252013-02-13 18:08:57 +0000321 // The memory instruction can refer to the loop identifier metadata
322 // directly or indirectly through another list metadata (in case of
323 // nested parallel loops). The loop identifier metadata refers to
324 // itself so we can check both cases with the same routine.
Sanjay Patel6435c6e2016-01-17 23:18:05 +0000325 MDNode *LoopIdMD =
Sanjay Patel960e5342016-01-15 00:08:10 +0000326 I.getMetadata(LLVMContext::MD_mem_parallel_loop_access);
Jakub Staszak9dca4b32013-11-13 20:18:38 +0000327
Sanjay Patel6435c6e2016-01-17 23:18:05 +0000328 if (!LoopIdMD)
Jakub Staszak9dca4b32013-11-13 20:18:38 +0000329 return false;
330
Sanjay Patel6435c6e2016-01-17 23:18:05 +0000331 bool LoopIdMDFound = false;
332 for (const MDOperand &MDOp : LoopIdMD->operands()) {
333 if (MDOp == DesiredLoopIdMetadata) {
334 LoopIdMDFound = true;
Pekka Jaaskelainen0d237252013-02-13 18:08:57 +0000335 break;
336 }
337 }
338
Sanjay Patel6435c6e2016-01-17 23:18:05 +0000339 if (!LoopIdMDFound)
Pekka Jaaskelainen0d237252013-02-13 18:08:57 +0000340 return false;
341 }
342 }
343 return true;
344}
345
Sanjoy Das66a004a2017-09-20 01:12:09 +0000346DebugLoc Loop::getStartLoc() const { return getLocRange().getStart(); }
Amara Emerson0b402012016-11-08 11:18:59 +0000347
348Loop::LocRange Loop::getLocRange() const {
Hal Finkel2f688682016-05-25 21:42:37 +0000349 // If we have a debug location in the loop ID, then use it.
Amara Emerson0b402012016-11-08 11:18:59 +0000350 if (MDNode *LoopID = getLoopID()) {
351 DebugLoc Start;
352 // We use the first DebugLoc in the header as the start location of the loop
353 // and if there is a second DebugLoc in the header we use it as end location
354 // of the loop.
355 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
356 if (DILocation *L = dyn_cast<DILocation>(LoopID->getOperand(i))) {
357 if (!Start)
358 Start = DebugLoc(L);
359 else
360 return LocRange(Start, DebugLoc(L));
361 }
362 }
363
364 if (Start)
365 return LocRange(Start);
366 }
Hal Finkel2f688682016-05-25 21:42:37 +0000367
368 // Try the pre-header first.
369 if (BasicBlock *PHeadBB = getLoopPreheader())
370 if (DebugLoc DL = PHeadBB->getTerminator()->getDebugLoc())
Amara Emerson0b402012016-11-08 11:18:59 +0000371 return LocRange(DL);
Hal Finkel2f688682016-05-25 21:42:37 +0000372
373 // If we have no pre-header or there are no instructions with debug
374 // info in it, try the header.
375 if (BasicBlock *HeadBB = getHeader())
Amara Emerson0b402012016-11-08 11:18:59 +0000376 return LocRange(HeadBB->getTerminator()->getDebugLoc());
Hal Finkel2f688682016-05-25 21:42:37 +0000377
Amara Emerson0b402012016-11-08 11:18:59 +0000378 return LocRange();
Hal Finkel2f688682016-05-25 21:42:37 +0000379}
380
Dan Gohmane3a17062009-11-05 19:21:41 +0000381bool Loop::hasDedicatedExits() const {
Dan Gohman1511f702009-07-16 16:16:23 +0000382 // Each predecessor of each exit block of a normal loop is contained
383 // within the loop.
384 SmallVector<BasicBlock *, 4> ExitBlocks;
385 getExitBlocks(ExitBlocks);
Sanjay Patel960e5342016-01-15 00:08:10 +0000386 for (BasicBlock *BB : ExitBlocks)
387 for (BasicBlock *Predecessor : predecessors(BB))
388 if (!contains(Predecessor))
Dan Gohman1511f702009-07-16 16:16:23 +0000389 return false;
390 // All the requirements are met.
391 return true;
392}
393
Sanjoy Das66a004a2017-09-20 01:12:09 +0000394void Loop::getUniqueExitBlocks(
395 SmallVectorImpl<BasicBlock *> &ExitBlocks) const {
Dan Gohman84ba0392009-12-11 20:05:23 +0000396 assert(hasDedicatedExits() &&
397 "getUniqueExitBlocks assumes the loop has canonical form exits!");
Dan Gohman3ddbc242009-09-08 15:45:00 +0000398
Sanjay Patel6435c6e2016-01-17 23:18:05 +0000399 SmallVector<BasicBlock *, 32> SwitchExitBlocks;
Sanjay Patel960e5342016-01-15 00:08:10 +0000400 for (BasicBlock *BB : this->blocks()) {
Sanjay Patel6435c6e2016-01-17 23:18:05 +0000401 SwitchExitBlocks.clear();
Sanjay Patel960e5342016-01-15 00:08:10 +0000402 for (BasicBlock *Successor : successors(BB)) {
403 // If block is inside the loop then it is not an exit block.
404 if (contains(Successor))
Dan Gohman3a0ce3e2009-09-03 16:10:48 +0000405 continue;
406
Sanjay Patel960e5342016-01-15 00:08:10 +0000407 pred_iterator PI = pred_begin(Successor);
Sanjay Patel6435c6e2016-01-17 23:18:05 +0000408 BasicBlock *FirstPred = *PI;
Dan Gohman3a0ce3e2009-09-03 16:10:48 +0000409
410 // If current basic block is this exit block's first predecessor
411 // then only insert exit block in to the output ExitBlocks vector.
412 // This ensures that same exit block is not inserted twice into
413 // ExitBlocks vector.
Sanjay Patel6435c6e2016-01-17 23:18:05 +0000414 if (BB != FirstPred)
Dan Gohman3a0ce3e2009-09-03 16:10:48 +0000415 continue;
416
417 // If a terminator has more then two successors, for example SwitchInst,
418 // then it is possible that there are multiple edges from current block
419 // to one exit block.
Vedant Kumare0b5f862018-05-10 23:01:54 +0000420 if (succ_size(BB) <= 2) {
Sanjay Patel960e5342016-01-15 00:08:10 +0000421 ExitBlocks.push_back(Successor);
Dan Gohman3a0ce3e2009-09-03 16:10:48 +0000422 continue;
423 }
424
425 // In case of multiple edges from current block to exit block, collect
426 // only one edge in ExitBlocks. Use switchExitBlocks to keep track of
427 // duplicate edges.
David Majnemer0a16c222016-08-11 21:15:00 +0000428 if (!is_contained(SwitchExitBlocks, Successor)) {
Sanjay Patel6435c6e2016-01-17 23:18:05 +0000429 SwitchExitBlocks.push_back(Successor);
Sanjay Patel960e5342016-01-15 00:08:10 +0000430 ExitBlocks.push_back(Successor);
Dan Gohman3a0ce3e2009-09-03 16:10:48 +0000431 }
432 }
433 }
434}
435
Dan Gohman3a0ce3e2009-09-03 16:10:48 +0000436BasicBlock *Loop::getUniqueExitBlock() const {
437 SmallVector<BasicBlock *, 8> UniqueExitBlocks;
438 getUniqueExitBlocks(UniqueExitBlocks);
439 if (UniqueExitBlocks.size() == 1)
440 return UniqueExitBlocks[0];
Craig Topper9f008862014-04-15 04:59:12 +0000441 return nullptr;
Dan Gohman3a0ce3e2009-09-03 16:10:48 +0000442}
443
Aaron Ballman615eb472017-10-15 14:32:27 +0000444#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Sanjoy Das66a004a2017-09-20 01:12:09 +0000445LLVM_DUMP_METHOD void Loop::dump() const { print(dbgs()); }
Sebastian Pop18c964d2016-07-27 05:02:17 +0000446
447LLVM_DUMP_METHOD void Loop::dumpVerbose() const {
Sanjoy Das66a004a2017-09-20 01:12:09 +0000448 print(dbgs(), /*Depth=*/0, /*Verbose=*/true);
Sebastian Pop18c964d2016-07-27 05:02:17 +0000449}
Manman Renc3366cc2012-09-06 19:55:56 +0000450#endif
Dan Gohmanc3f21372010-01-05 21:08:02 +0000451
Chris Lattner26750072002-07-27 01:12:17 +0000452//===----------------------------------------------------------------------===//
Andrew Trickd3530b92011-08-10 23:22:57 +0000453// UnloopUpdater implementation
454//
455
Benjamin Kramer4938edb2011-08-19 01:42:18 +0000456namespace {
Andrew Trickd3530b92011-08-10 23:22:57 +0000457/// Find the new parent loop for all blocks within the "unloop" whose last
458/// backedges has just been removed.
459class UnloopUpdater {
Silviu Baranga24dbd2e2016-05-13 14:54:50 +0000460 Loop &Unloop;
Andrew Trickd3530b92011-08-10 23:22:57 +0000461 LoopInfo *LI;
462
463 LoopBlocksDFS DFS;
464
465 // Map unloop's immediate subloops to their nearest reachable parents. Nested
466 // loops within these subloops will not change parents. However, an immediate
467 // subloop's new parent will be the nearest loop reachable from either its own
468 // exits *or* any of its nested loop's exits.
Sanjoy Das66a004a2017-09-20 01:12:09 +0000469 DenseMap<Loop *, Loop *> SubloopParents;
Andrew Trickd3530b92011-08-10 23:22:57 +0000470
471 // Flag the presence of an irreducible backedge whose destination is a block
472 // directly contained by the original unloop.
473 bool FoundIB;
474
475public:
Sanjoy Das66a004a2017-09-20 01:12:09 +0000476 UnloopUpdater(Loop *UL, LoopInfo *LInfo)
477 : Unloop(*UL), LI(LInfo), DFS(UL), FoundIB(false) {}
Andrew Trickd3530b92011-08-10 23:22:57 +0000478
479 void updateBlockParents();
480
Andrew Trickc12c30a2011-08-11 20:27:32 +0000481 void removeBlocksFromAncestors();
482
Andrew Trickd3530b92011-08-10 23:22:57 +0000483 void updateSubloopParents();
484
485protected:
486 Loop *getNearestLoop(BasicBlock *BB, Loop *BBLoop);
487};
Benjamin Kramer4938edb2011-08-19 01:42:18 +0000488} // end anonymous namespace
Andrew Trickd3530b92011-08-10 23:22:57 +0000489
Sanjay Patel784b5e32016-01-14 23:23:04 +0000490/// Update the parent loop for all blocks that are directly contained within the
491/// original "unloop".
Andrew Trickd3530b92011-08-10 23:22:57 +0000492void UnloopUpdater::updateBlockParents() {
Silviu Baranga24dbd2e2016-05-13 14:54:50 +0000493 if (Unloop.getNumBlocks()) {
Andrew Trickd3530b92011-08-10 23:22:57 +0000494 // Perform a post order CFG traversal of all blocks within this loop,
Hiroshi Inoue713b5ba2017-07-09 05:54:44 +0000495 // propagating the nearest loop from successors to predecessors.
Andrew Trickd3530b92011-08-10 23:22:57 +0000496 LoopBlocksTraversal Traversal(DFS, LI);
Benjamin Krameraa209152016-06-26 17:27:42 +0000497 for (BasicBlock *POI : Traversal) {
Andrew Trickd3530b92011-08-10 23:22:57 +0000498
Benjamin Krameraa209152016-06-26 17:27:42 +0000499 Loop *L = LI->getLoopFor(POI);
500 Loop *NL = getNearestLoop(POI, L);
Andrew Trickd3530b92011-08-10 23:22:57 +0000501
502 if (NL != L) {
503 // For reducible loops, NL is now an ancestor of Unloop.
Silviu Baranga24dbd2e2016-05-13 14:54:50 +0000504 assert((NL != &Unloop && (!NL || NL->contains(&Unloop))) &&
Andrew Trickd3530b92011-08-10 23:22:57 +0000505 "uninitialized successor");
Benjamin Krameraa209152016-06-26 17:27:42 +0000506 LI->changeLoopFor(POI, NL);
Sanjoy Das66a004a2017-09-20 01:12:09 +0000507 } else {
Andrew Trickd3530b92011-08-10 23:22:57 +0000508 // Or the current block is part of a subloop, in which case its parent
509 // is unchanged.
Silviu Baranga24dbd2e2016-05-13 14:54:50 +0000510 assert((FoundIB || Unloop.contains(L)) && "uninitialized successor");
Andrew Trickd3530b92011-08-10 23:22:57 +0000511 }
512 }
513 }
514 // Each irreducible loop within the unloop induces a round of iteration using
515 // the DFS result cached by Traversal.
516 bool Changed = FoundIB;
517 for (unsigned NIters = 0; Changed; ++NIters) {
Silviu Baranga24dbd2e2016-05-13 14:54:50 +0000518 assert(NIters < Unloop.getNumBlocks() && "runaway iterative algorithm");
Andrew Trickd3530b92011-08-10 23:22:57 +0000519
520 // Iterate over the postorder list of blocks, propagating the nearest loop
521 // from successors to predecessors as before.
522 Changed = false;
523 for (LoopBlocksDFS::POIterator POI = DFS.beginPostorder(),
Sanjoy Das66a004a2017-09-20 01:12:09 +0000524 POE = DFS.endPostorder();
525 POI != POE; ++POI) {
Andrew Trickd3530b92011-08-10 23:22:57 +0000526
527 Loop *L = LI->getLoopFor(*POI);
528 Loop *NL = getNearestLoop(*POI, L);
529 if (NL != L) {
Silviu Baranga24dbd2e2016-05-13 14:54:50 +0000530 assert(NL != &Unloop && (!NL || NL->contains(&Unloop)) &&
Andrew Trickd3530b92011-08-10 23:22:57 +0000531 "uninitialized successor");
532 LI->changeLoopFor(*POI, NL);
533 Changed = true;
534 }
535 }
536 }
537}
538
Sanjay Patel784b5e32016-01-14 23:23:04 +0000539/// Remove unloop's blocks from all ancestors below their new parents.
Andrew Trickc12c30a2011-08-11 20:27:32 +0000540void UnloopUpdater::removeBlocksFromAncestors() {
Andrew Trick6b4d5782011-11-18 03:42:41 +0000541 // Remove all unloop's blocks (including those in nested subloops) from
542 // ancestors below the new parent loop.
Sanjoy Das66a004a2017-09-20 01:12:09 +0000543 for (Loop::block_iterator BI = Unloop.block_begin(), BE = Unloop.block_end();
544 BI != BE; ++BI) {
Andrew Trick6b4d5782011-11-18 03:42:41 +0000545 Loop *OuterParent = LI->getLoopFor(*BI);
Silviu Baranga24dbd2e2016-05-13 14:54:50 +0000546 if (Unloop.contains(OuterParent)) {
547 while (OuterParent->getParentLoop() != &Unloop)
Andrew Trick6b4d5782011-11-18 03:42:41 +0000548 OuterParent = OuterParent->getParentLoop();
549 OuterParent = SubloopParents[OuterParent];
550 }
Andrew Trickc12c30a2011-08-11 20:27:32 +0000551 // Remove blocks from former Ancestors except Unloop itself which will be
552 // deleted.
Silviu Baranga24dbd2e2016-05-13 14:54:50 +0000553 for (Loop *OldParent = Unloop.getParentLoop(); OldParent != OuterParent;
Andrew Trickc12c30a2011-08-11 20:27:32 +0000554 OldParent = OldParent->getParentLoop()) {
555 assert(OldParent && "new loop is not an ancestor of the original");
556 OldParent->removeBlockFromLoop(*BI);
557 }
558 }
559}
560
Sanjay Patel784b5e32016-01-14 23:23:04 +0000561/// Update the parent loop for all subloops directly nested within unloop.
Andrew Trickd3530b92011-08-10 23:22:57 +0000562void UnloopUpdater::updateSubloopParents() {
Silviu Baranga24dbd2e2016-05-13 14:54:50 +0000563 while (!Unloop.empty()) {
564 Loop *Subloop = *std::prev(Unloop.end());
565 Unloop.removeChildLoop(std::prev(Unloop.end()));
Andrew Trickd3530b92011-08-10 23:22:57 +0000566
567 assert(SubloopParents.count(Subloop) && "DFS failed to visit subloop");
Benjamin Kramerf29db272012-08-22 15:37:57 +0000568 if (Loop *Parent = SubloopParents[Subloop])
569 Parent->addChildLoop(Subloop);
Andrew Trick147d9cd2011-08-26 03:06:34 +0000570 else
571 LI->addTopLevelLoop(Subloop);
Andrew Trickd3530b92011-08-10 23:22:57 +0000572 }
573}
574
Sanjay Patel784b5e32016-01-14 23:23:04 +0000575/// Return the nearest parent loop among this block's successors. If a successor
576/// is a subloop header, consider its parent to be the nearest parent of the
577/// subloop's exits.
Andrew Trickd3530b92011-08-10 23:22:57 +0000578///
579/// For subloop blocks, simply update SubloopParents and return NULL.
580Loop *UnloopUpdater::getNearestLoop(BasicBlock *BB, Loop *BBLoop) {
581
Andrew Trick266ab102011-08-11 17:54:58 +0000582 // Initially for blocks directly contained by Unloop, NearLoop == Unloop and
583 // is considered uninitialized.
Andrew Trickd3530b92011-08-10 23:22:57 +0000584 Loop *NearLoop = BBLoop;
585
Craig Topper9f008862014-04-15 04:59:12 +0000586 Loop *Subloop = nullptr;
Silviu Baranga24dbd2e2016-05-13 14:54:50 +0000587 if (NearLoop != &Unloop && Unloop.contains(NearLoop)) {
Andrew Trickd3530b92011-08-10 23:22:57 +0000588 Subloop = NearLoop;
589 // Find the subloop ancestor that is directly contained within Unloop.
Silviu Baranga24dbd2e2016-05-13 14:54:50 +0000590 while (Subloop->getParentLoop() != &Unloop) {
Andrew Trickd3530b92011-08-10 23:22:57 +0000591 Subloop = Subloop->getParentLoop();
592 assert(Subloop && "subloop is not an ancestor of the original loop");
593 }
594 // Get the current nearest parent of the Subloop exits, initially Unloop.
David Majnemer0a16c222016-08-11 21:15:00 +0000595 NearLoop = SubloopParents.insert({Subloop, &Unloop}).first->second;
Andrew Trickd3530b92011-08-10 23:22:57 +0000596 }
597
598 succ_iterator I = succ_begin(BB), E = succ_end(BB);
599 if (I == E) {
600 assert(!Subloop && "subloop blocks must have a successor");
Craig Topper9f008862014-04-15 04:59:12 +0000601 NearLoop = nullptr; // unloop blocks may now exit the function.
Andrew Trickd3530b92011-08-10 23:22:57 +0000602 }
603 for (; I != E; ++I) {
604 if (*I == BB)
605 continue; // self loops are uninteresting
606
607 Loop *L = LI->getLoopFor(*I);
Silviu Baranga24dbd2e2016-05-13 14:54:50 +0000608 if (L == &Unloop) {
Andrew Trickd3530b92011-08-10 23:22:57 +0000609 // This successor has not been processed. This path must lead to an
610 // irreducible backedge.
611 assert((FoundIB || !DFS.hasPostorder(*I)) && "should have seen IB");
612 FoundIB = true;
613 }
Silviu Baranga24dbd2e2016-05-13 14:54:50 +0000614 if (L != &Unloop && Unloop.contains(L)) {
Andrew Trickd3530b92011-08-10 23:22:57 +0000615 // Successor is in a subloop.
616 if (Subloop)
617 continue; // Branching within subloops. Ignore it.
618
619 // BB branches from the original into a subloop header.
Silviu Baranga24dbd2e2016-05-13 14:54:50 +0000620 assert(L->getParentLoop() == &Unloop && "cannot skip into nested loops");
Andrew Trickd3530b92011-08-10 23:22:57 +0000621
622 // Get the current nearest parent of the Subloop's exits.
623 L = SubloopParents[L];
624 // L could be Unloop if the only exit was an irreducible backedge.
625 }
Silviu Baranga24dbd2e2016-05-13 14:54:50 +0000626 if (L == &Unloop) {
Andrew Trickd3530b92011-08-10 23:22:57 +0000627 continue;
628 }
629 // Handle critical edges from Unloop into a sibling loop.
Silviu Baranga24dbd2e2016-05-13 14:54:50 +0000630 if (L && !L->contains(&Unloop)) {
Andrew Trickd3530b92011-08-10 23:22:57 +0000631 L = L->getParentLoop();
632 }
633 // Remember the nearest parent loop among successors or subloop exits.
Silviu Baranga24dbd2e2016-05-13 14:54:50 +0000634 if (NearLoop == &Unloop || !NearLoop || NearLoop->contains(L))
Andrew Trickd3530b92011-08-10 23:22:57 +0000635 NearLoop = L;
636 }
637 if (Subloop) {
638 SubloopParents[Subloop] = NearLoop;
639 return BBLoop;
640 }
641 return NearLoop;
642}
643
Sanjoy Das66a004a2017-09-20 01:12:09 +0000644LoopInfo::LoopInfo(const DomTreeBase<BasicBlock> &DomTree) { analyze(DomTree); }
Cong Hou9b4f6b22015-07-16 23:23:35 +0000645
Chandler Carruthca68a3e2017-01-15 06:32:49 +0000646bool LoopInfo::invalidate(Function &F, const PreservedAnalyses &PA,
647 FunctionAnalysisManager::Invalidator &) {
648 // Check whether the analysis, all analyses on functions, or the function's
649 // CFG have been preserved.
650 auto PAC = PA.getChecker<LoopAnalysis>();
651 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>() ||
652 PAC.preservedSet<CFGAnalyses>());
653}
654
Sanjoy Das388b0122017-09-22 01:47:41 +0000655void LoopInfo::erase(Loop *Unloop) {
Sanjoy Das76ab2322017-09-19 23:19:00 +0000656 assert(!Unloop->isInvalid() && "Loop has already been erased!");
Andrew Trickd3530b92011-08-10 23:22:57 +0000657
Sanjoy Dasdef17292017-09-28 02:45:42 +0000658 auto InvalidateOnExit = make_scope_exit([&]() { destroy(Unloop); });
Sanjoy Das09613b12017-09-20 02:31:57 +0000659
Andrew Trickd3530b92011-08-10 23:22:57 +0000660 // First handle the special case of no parent loop to simplify the algorithm.
661 if (!Unloop->getParentLoop()) {
662 // Since BBLoop had no parent, Unloop blocks are no longer in a loop.
663 for (Loop::block_iterator I = Unloop->block_begin(),
Chandler Carruth691addc2015-01-18 01:25:51 +0000664 E = Unloop->block_end();
665 I != E; ++I) {
Andrew Trickd3530b92011-08-10 23:22:57 +0000666
667 // Don't reparent blocks in subloops.
668 if (getLoopFor(*I) != Unloop)
669 continue;
670
671 // Blocks no longer have a parent but are still referenced by Unloop until
672 // the Unloop object is deleted.
Chandler Carruth691addc2015-01-18 01:25:51 +0000673 changeLoopFor(*I, nullptr);
Andrew Trickd3530b92011-08-10 23:22:57 +0000674 }
675
676 // Remove the loop from the top-level LoopInfo object.
Chandler Carruth691addc2015-01-18 01:25:51 +0000677 for (iterator I = begin();; ++I) {
678 assert(I != end() && "Couldn't find loop");
Andrew Trickd3530b92011-08-10 23:22:57 +0000679 if (*I == Unloop) {
Chandler Carruth691addc2015-01-18 01:25:51 +0000680 removeLoop(I);
Andrew Trickd3530b92011-08-10 23:22:57 +0000681 break;
682 }
683 }
684
685 // Move all of the subloops to the top-level.
686 while (!Unloop->empty())
Chandler Carruth691addc2015-01-18 01:25:51 +0000687 addTopLevelLoop(Unloop->removeChildLoop(std::prev(Unloop->end())));
Andrew Trickd3530b92011-08-10 23:22:57 +0000688
689 return;
690 }
691
692 // Update the parent loop for all blocks within the loop. Blocks within
693 // subloops will not change parents.
694 UnloopUpdater Updater(Unloop, this);
695 Updater.updateBlockParents();
696
Andrew Trickc12c30a2011-08-11 20:27:32 +0000697 // Remove blocks from former ancestor loops.
698 Updater.removeBlocksFromAncestors();
Andrew Trickd3530b92011-08-10 23:22:57 +0000699
700 // Add direct subloops as children in their new parent loop.
701 Updater.updateSubloopParents();
702
703 // Remove unloop from its parent loop.
704 Loop *ParentLoop = Unloop->getParentLoop();
Duncan Sandsa41634e2011-08-12 14:54:45 +0000705 for (Loop::iterator I = ParentLoop->begin();; ++I) {
706 assert(I != ParentLoop->end() && "Couldn't find loop");
Andrew Trickd3530b92011-08-10 23:22:57 +0000707 if (*I == Unloop) {
708 ParentLoop->removeChildLoop(I);
709 break;
710 }
711 }
712}
713
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000714AnalysisKey LoopAnalysis::Key;
NAKAMURA Takumidf0cd722016-02-28 17:17:00 +0000715
Sean Silva36e0d012016-08-09 00:28:15 +0000716LoopInfo LoopAnalysis::run(Function &F, FunctionAnalysisManager &AM) {
Chandler Carruthaaf0b4c2015-01-20 10:58:50 +0000717 // FIXME: Currently we create a LoopInfo from scratch for every function.
718 // This may prove to be too wasteful due to deallocating and re-allocating
719 // memory each time for the underlying map and vector datastructures. At some
720 // point it may prove worthwhile to use a freelist and recycle LoopInfo
721 // objects. I don't want to add that kind of complexity until the scope of
722 // the problem is better understood.
723 LoopInfo LI;
Chandler Carruthb47f8012016-03-11 11:05:24 +0000724 LI.analyze(AM.getResult<DominatorTreeAnalysis>(F));
Richard Trieu6ae37962015-04-30 23:07:00 +0000725 return LI;
Chandler Carruthaaf0b4c2015-01-20 10:58:50 +0000726}
727
728PreservedAnalyses LoopPrinterPass::run(Function &F,
Sean Silva36e0d012016-08-09 00:28:15 +0000729 FunctionAnalysisManager &AM) {
Chandler Carruthb47f8012016-03-11 11:05:24 +0000730 AM.getResult<LoopAnalysis>(F).print(OS);
Chandler Carruthaaf0b4c2015-01-20 10:58:50 +0000731 return PreservedAnalyses::all();
732}
733
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000734void llvm::printLoop(Loop &L, raw_ostream &OS, const std::string &Banner) {
Fedor Sergeev3b459c32017-12-01 18:33:58 +0000735
736 if (forcePrintModuleIR()) {
737 // handling -print-module-scope
738 OS << Banner << " (loop: ";
739 L.getHeader()->printAsOperand(OS, false);
740 OS << ")\n";
741
742 // printing whole module
743 OS << *L.getHeader()->getModule();
744 return;
745 }
746
Justin Bognerc2b98f02015-11-04 22:24:08 +0000747 OS << Banner;
Fedor Sergeev61975b42017-11-22 20:59:53 +0000748
749 auto *PreHeader = L.getLoopPreheader();
750 if (PreHeader) {
751 OS << "\n; Preheader:";
752 PreHeader->print(OS);
753 OS << "\n; Loop:";
754 }
755
Justin Bognerc2b98f02015-11-04 22:24:08 +0000756 for (auto *Block : L.blocks())
757 if (Block)
758 Block->print(OS);
759 else
760 OS << "Printing <null> block";
Fedor Sergeev61975b42017-11-22 20:59:53 +0000761
762 SmallVector<BasicBlock *, 8> ExitBlocks;
763 L.getExitBlocks(ExitBlocks);
764 if (!ExitBlocks.empty()) {
765 OS << "\n; Exit blocks";
766 for (auto *Block : ExitBlocks)
767 if (Block)
768 Block->print(OS);
769 else
770 OS << "Printing <null> block";
771 }
Justin Bognerc2b98f02015-11-04 22:24:08 +0000772}
773
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000774//===----------------------------------------------------------------------===//
775// LoopInfo implementation
776//
777
778char LoopInfoWrapperPass::ID = 0;
779INITIALIZE_PASS_BEGIN(LoopInfoWrapperPass, "loops", "Natural Loop Information",
780 true, true)
781INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
782INITIALIZE_PASS_END(LoopInfoWrapperPass, "loops", "Natural Loop Information",
783 true, true)
784
785bool LoopInfoWrapperPass::runOnFunction(Function &) {
786 releaseMemory();
Cong Houd2c1d912015-07-16 18:23:57 +0000787 LI.analyze(getAnalysis<DominatorTreeWrapperPass>().getDomTree());
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000788 return false;
789}
790
791void LoopInfoWrapperPass::verifyAnalysis() const {
792 // LoopInfoWrapperPass is a FunctionPass, but verifying every loop in the
793 // function each time verifyAnalysis is called is very expensive. The
Dan Gohman4dbb3012009-09-28 00:27:48 +0000794 // -verify-loop-info option can enable this. In order to perform some
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000795 // checking by default, LoopPass has been taught to call verifyLoop manually
796 // during loop pass sequences.
Michael Zolotukhine0b2d972016-08-31 19:26:19 +0000797 if (VerifyLoopInfo) {
Serge Pavloved5eb932017-01-15 10:23:18 +0000798 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
799 LI.verify(DT);
Michael Zolotukhine0b2d972016-08-31 19:26:19 +0000800 }
Dan Gohman3ddbc242009-09-08 15:45:00 +0000801}
802
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000803void LoopInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerc8e66542002-04-27 06:56:12 +0000804 AU.setPreservesAll();
Chandler Carruth73523022014-01-13 13:07:17 +0000805 AU.addRequired<DominatorTreeWrapperPass>();
Chris Lattnerccf571a2002-01-31 00:42:27 +0000806}
Chris Lattnerb1d782b2009-08-23 05:17:37 +0000807
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000808void LoopInfoWrapperPass::print(raw_ostream &OS, const Module *) const {
Chandler Carruth691addc2015-01-18 01:25:51 +0000809 LI.print(OS);
Chris Lattnerb1d782b2009-08-23 05:17:37 +0000810}
811
Sean Silvae3c18a52016-07-19 23:54:23 +0000812PreservedAnalyses LoopVerifierPass::run(Function &F,
Sean Silva36e0d012016-08-09 00:28:15 +0000813 FunctionAnalysisManager &AM) {
Sean Silvae3c18a52016-07-19 23:54:23 +0000814 LoopInfo &LI = AM.getResult<LoopAnalysis>(F);
Michael Zolotukhine0b2d972016-08-31 19:26:19 +0000815 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
816 LI.verify(DT);
Sean Silvae3c18a52016-07-19 23:54:23 +0000817 return PreservedAnalyses::all();
818}
819
Andrew Trick78b40c32011-08-10 01:59:05 +0000820//===----------------------------------------------------------------------===//
821// LoopBlocksDFS implementation
822//
823
824/// Traverse the loop blocks and store the DFS result.
825/// Useful for clients that just want the final DFS result and don't need to
826/// visit blocks during the initial traversal.
827void LoopBlocksDFS::perform(LoopInfo *LI) {
828 LoopBlocksTraversal Traversal(*this, LI);
829 for (LoopBlocksTraversal::POTIterator POI = Traversal.begin(),
Sanjoy Das66a004a2017-09-20 01:12:09 +0000830 POE = Traversal.end();
831 POI != POE; ++POI)
832 ;
Andrew Trick78b40c32011-08-10 01:59:05 +0000833}