blob: 9ebbb6784971b7ac6a890eb3259a2889fae65256 [file] [log] [blame]
Nick Lewycky0b682452013-07-27 01:24:00 +00001//===-- CFG.cpp - BasicBlock analysis --------------------------------------==//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This family of functions performs analyses on basic blocks, and instructions
11// contained within basic blocks.
12//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/Analysis/CFG.h"
Nick Lewycky0b682452013-07-27 01:24:00 +000016#include "llvm/ADT/SmallSet.h"
Nick Lewycky0b682452013-07-27 01:24:00 +000017#include "llvm/Analysis/LoopInfo.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000018#include "llvm/IR/Dominators.h"
Nick Lewycky0b682452013-07-27 01:24:00 +000019
20using namespace llvm;
21
22/// FindFunctionBackedges - Analyze the specified function to find all of the
23/// loop backedges in the function and return them. This is a relatively cheap
24/// (compared to computing dominators and loop info) analysis.
25///
26/// The output is added to Result, as pairs of <from,to> edge info.
27void llvm::FindFunctionBackedges(const Function &F,
28 SmallVectorImpl<std::pair<const BasicBlock*,const BasicBlock*> > &Result) {
29 const BasicBlock *BB = &F.getEntryBlock();
30 if (succ_begin(BB) == succ_end(BB))
31 return;
32
33 SmallPtrSet<const BasicBlock*, 8> Visited;
34 SmallVector<std::pair<const BasicBlock*, succ_const_iterator>, 8> VisitStack;
35 SmallPtrSet<const BasicBlock*, 8> InStack;
36
37 Visited.insert(BB);
38 VisitStack.push_back(std::make_pair(BB, succ_begin(BB)));
39 InStack.insert(BB);
40 do {
41 std::pair<const BasicBlock*, succ_const_iterator> &Top = VisitStack.back();
42 const BasicBlock *ParentBB = Top.first;
43 succ_const_iterator &I = Top.second;
44
45 bool FoundNew = false;
46 while (I != succ_end(ParentBB)) {
47 BB = *I++;
48 if (Visited.insert(BB)) {
49 FoundNew = true;
50 break;
51 }
52 // Successor is in VisitStack, it's a back edge.
53 if (InStack.count(BB))
54 Result.push_back(std::make_pair(ParentBB, BB));
55 }
56
57 if (FoundNew) {
58 // Go down one level if there is a unvisited successor.
59 InStack.insert(BB);
60 VisitStack.push_back(std::make_pair(BB, succ_begin(BB)));
61 } else {
62 // Go up one level.
63 InStack.erase(VisitStack.pop_back_val().first);
64 }
65 } while (!VisitStack.empty());
66}
67
68/// GetSuccessorNumber - Search for the specified successor of basic block BB
69/// and return its position in the terminator instruction's list of
70/// successors. It is an error to call this with a block that is not a
71/// successor.
72unsigned llvm::GetSuccessorNumber(BasicBlock *BB, BasicBlock *Succ) {
73 TerminatorInst *Term = BB->getTerminator();
74#ifndef NDEBUG
75 unsigned e = Term->getNumSuccessors();
76#endif
77 for (unsigned i = 0; ; ++i) {
78 assert(i != e && "Didn't find edge?");
79 if (Term->getSuccessor(i) == Succ)
80 return i;
81 }
82}
83
84/// isCriticalEdge - Return true if the specified edge is a critical edge.
85/// Critical edges are edges from a block with multiple successors to a block
86/// with multiple predecessors.
87bool llvm::isCriticalEdge(const TerminatorInst *TI, unsigned SuccNum,
88 bool AllowIdenticalEdges) {
89 assert(SuccNum < TI->getNumSuccessors() && "Illegal edge specification!");
90 if (TI->getNumSuccessors() == 1) return false;
91
92 const BasicBlock *Dest = TI->getSuccessor(SuccNum);
93 const_pred_iterator I = pred_begin(Dest), E = pred_end(Dest);
94
95 // If there is more than one predecessor, this is a critical edge...
96 assert(I != E && "No preds, but we have an edge to the block?");
97 const BasicBlock *FirstPred = *I;
98 ++I; // Skip one edge due to the incoming arc from TI.
99 if (!AllowIdenticalEdges)
100 return I != E;
101
102 // If AllowIdenticalEdges is true, then we allow this edge to be considered
103 // non-critical iff all preds come from TI's block.
104 while (I != E) {
105 const BasicBlock *P = *I;
106 if (P != FirstPred)
107 return true;
108 // Note: leave this as is until no one ever compiles with either gcc 4.0.1
109 // or Xcode 2. This seems to work around the pred_iterator assert in PR 2207
110 E = pred_end(P);
111 ++I;
112 }
113 return false;
114}
115
116// LoopInfo contains a mapping from basic block to the innermost loop. Find
117// the outermost loop in the loop nest that contains BB.
Jakub Staszakd184e2d2013-08-20 23:04:15 +0000118static const Loop *getOutermostLoop(const LoopInfo *LI, const BasicBlock *BB) {
Nick Lewycky0b682452013-07-27 01:24:00 +0000119 const Loop *L = LI->getLoopFor(BB);
120 if (L) {
121 while (const Loop *Parent = L->getParentLoop())
122 L = Parent;
123 }
124 return L;
125}
126
127// True if there is a loop which contains both BB1 and BB2.
Jakub Staszakd184e2d2013-08-20 23:04:15 +0000128static bool loopContainsBoth(const LoopInfo *LI,
Nick Lewycky0b682452013-07-27 01:24:00 +0000129 const BasicBlock *BB1, const BasicBlock *BB2) {
130 const Loop *L1 = getOutermostLoop(LI, BB1);
131 const Loop *L2 = getOutermostLoop(LI, BB2);
132 return L1 != NULL && L1 == L2;
133}
134
Nick Lewycky8d2e86d2013-08-13 00:03:47 +0000135static bool isPotentiallyReachableInner(SmallVectorImpl<BasicBlock *> &Worklist,
136 BasicBlock *StopBB,
Jakub Staszakd184e2d2013-08-20 23:04:15 +0000137 const DominatorTree *DT,
138 const LoopInfo *LI) {
Nick Lewycky0b682452013-07-27 01:24:00 +0000139 // When the stop block is unreachable, it's dominated from everywhere,
140 // regardless of whether there's a path between the two blocks.
141 if (DT && !DT->isReachableFromEntry(StopBB))
142 DT = 0;
143
144 // Limit the number of blocks we visit. The goal is to avoid run-away compile
145 // times on large CFGs without hampering sensible code. Arbitrarily chosen.
146 unsigned Limit = 32;
Nick Lewycky0b682452013-07-27 01:24:00 +0000147 SmallSet<const BasicBlock*, 64> Visited;
Nick Lewycky0b682452013-07-27 01:24:00 +0000148 do {
149 BasicBlock *BB = Worklist.pop_back_val();
150 if (!Visited.insert(BB))
151 continue;
152 if (BB == StopBB)
153 return true;
154 if (DT && DT->dominates(BB, StopBB))
155 return true;
156 if (LI && loopContainsBoth(LI, BB, StopBB))
157 return true;
158
159 if (!--Limit) {
160 // We haven't been able to prove it one way or the other. Conservatively
161 // answer true -- that there is potentially a path.
162 return true;
163 }
164
165 if (const Loop *Outer = LI ? getOutermostLoop(LI, BB) : 0) {
166 // All blocks in a single loop are reachable from all other blocks. From
167 // any of these blocks, we can skip directly to the exits of the loop,
168 // ignoring any other blocks inside the loop body.
169 Outer->getExitBlocks(Worklist);
170 } else {
Benjamin Kramer3c29c072014-02-10 14:17:42 +0000171 Worklist.append(succ_begin(BB), succ_end(BB));
Nick Lewycky0b682452013-07-27 01:24:00 +0000172 }
173 } while (!Worklist.empty());
174
Nick Lewycky8d2e86d2013-08-13 00:03:47 +0000175 // We have exhausted all possible paths and are certain that 'To' can not be
176 // reached from 'From'.
Nick Lewycky0b682452013-07-27 01:24:00 +0000177 return false;
178}
Nick Lewycky8d2e86d2013-08-13 00:03:47 +0000179
180bool llvm::isPotentiallyReachable(const BasicBlock *A, const BasicBlock *B,
Jakub Staszakd184e2d2013-08-20 23:04:15 +0000181 const DominatorTree *DT, const LoopInfo *LI) {
Nick Lewycky8d2e86d2013-08-13 00:03:47 +0000182 assert(A->getParent() == B->getParent() &&
183 "This analysis is function-local!");
184
185 SmallVector<BasicBlock*, 32> Worklist;
186 Worklist.push_back(const_cast<BasicBlock*>(A));
187
188 return isPotentiallyReachableInner(Worklist, const_cast<BasicBlock*>(B),
189 DT, LI);
190}
191
192bool llvm::isPotentiallyReachable(const Instruction *A, const Instruction *B,
Jakub Staszakd184e2d2013-08-20 23:04:15 +0000193 const DominatorTree *DT, const LoopInfo *LI) {
Nick Lewycky8d2e86d2013-08-13 00:03:47 +0000194 assert(A->getParent()->getParent() == B->getParent()->getParent() &&
195 "This analysis is function-local!");
196
197 SmallVector<BasicBlock*, 32> Worklist;
198
199 if (A->getParent() == B->getParent()) {
200 // The same block case is special because it's the only time we're looking
201 // within a single block to see which instruction comes first. Once we
202 // start looking at multiple blocks, the first instruction of the block is
203 // reachable, so we only need to determine reachability between whole
204 // blocks.
205 BasicBlock *BB = const_cast<BasicBlock *>(A->getParent());
206
207 // If the block is in a loop then we can reach any instruction in the block
208 // from any other instruction in the block by going around a backedge.
209 if (LI && LI->getLoopFor(BB) != 0)
210 return true;
211
212 // Linear scan, start at 'A', see whether we hit 'B' or the end first.
213 for (BasicBlock::const_iterator I = A, E = BB->end(); I != E; ++I) {
214 if (&*I == B)
215 return true;
216 }
217
218 // Can't be in a loop if it's the entry block -- the entry block may not
219 // have predecessors.
220 if (BB == &BB->getParent()->getEntryBlock())
221 return false;
222
223 // Otherwise, continue doing the normal per-BB CFG walk.
Benjamin Kramer3c29c072014-02-10 14:17:42 +0000224 Worklist.append(succ_begin(BB), succ_end(BB));
Nick Lewycky8d2e86d2013-08-13 00:03:47 +0000225
226 if (Worklist.empty()) {
227 // We've proven that there's no path!
228 return false;
229 }
230 } else {
231 Worklist.push_back(const_cast<BasicBlock*>(A->getParent()));
232 }
233
234 if (A->getParent() == &A->getParent()->getParent()->getEntryBlock())
235 return true;
236 if (B->getParent() == &A->getParent()->getParent()->getEntryBlock())
237 return false;
238
239 return isPotentiallyReachableInner(Worklist,
240 const_cast<BasicBlock*>(B->getParent()),
241 DT, LI);
242}