LLVM  3.7.0
CFG.cpp
Go to the documentation of this file.
1 //===-- 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"
16 #include "llvm/ADT/SmallSet.h"
17 #include "llvm/Analysis/LoopInfo.h"
18 #include "llvm/IR/Dominators.h"
19 
20 using 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.
28  SmallVectorImpl<std::pair<const BasicBlock*,const BasicBlock*> > &Result) {
29  const BasicBlock *BB = &F.getEntryBlock();
30  if (succ_empty(BB))
31  return;
32 
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).second) {
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.
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.
87 bool 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  for (; I != E; ++I)
105  if (*I != FirstPred)
106  return true;
107  return false;
108 }
109 
110 // LoopInfo contains a mapping from basic block to the innermost loop. Find
111 // the outermost loop in the loop nest that contains BB.
112 static const Loop *getOutermostLoop(const LoopInfo *LI, const BasicBlock *BB) {
113  const Loop *L = LI->getLoopFor(BB);
114  if (L) {
115  while (const Loop *Parent = L->getParentLoop())
116  L = Parent;
117  }
118  return L;
119 }
120 
121 // True if there is a loop which contains both BB1 and BB2.
122 static bool loopContainsBoth(const LoopInfo *LI,
123  const BasicBlock *BB1, const BasicBlock *BB2) {
124  const Loop *L1 = getOutermostLoop(LI, BB1);
125  const Loop *L2 = getOutermostLoop(LI, BB2);
126  return L1 != nullptr && L1 == L2;
127 }
128 
130  SmallVectorImpl<BasicBlock *> &Worklist, BasicBlock *StopBB,
131  const DominatorTree *DT, const LoopInfo *LI) {
132  // When the stop block is unreachable, it's dominated from everywhere,
133  // regardless of whether there's a path between the two blocks.
134  if (DT && !DT->isReachableFromEntry(StopBB))
135  DT = nullptr;
136 
137  // Limit the number of blocks we visit. The goal is to avoid run-away compile
138  // times on large CFGs without hampering sensible code. Arbitrarily chosen.
139  unsigned Limit = 32;
141  do {
142  BasicBlock *BB = Worklist.pop_back_val();
143  if (!Visited.insert(BB).second)
144  continue;
145  if (BB == StopBB)
146  return true;
147  if (DT && DT->dominates(BB, StopBB))
148  return true;
149  if (LI && loopContainsBoth(LI, BB, StopBB))
150  return true;
151 
152  if (!--Limit) {
153  // We haven't been able to prove it one way or the other. Conservatively
154  // answer true -- that there is potentially a path.
155  return true;
156  }
157 
158  if (const Loop *Outer = LI ? getOutermostLoop(LI, BB) : nullptr) {
159  // All blocks in a single loop are reachable from all other blocks. From
160  // any of these blocks, we can skip directly to the exits of the loop,
161  // ignoring any other blocks inside the loop body.
162  Outer->getExitBlocks(Worklist);
163  } else {
164  Worklist.append(succ_begin(BB), succ_end(BB));
165  }
166  } while (!Worklist.empty());
167 
168  // We have exhausted all possible paths and are certain that 'To' can not be
169  // reached from 'From'.
170  return false;
171 }
172 
174  const DominatorTree *DT, const LoopInfo *LI) {
175  assert(A->getParent() == B->getParent() &&
176  "This analysis is function-local!");
177 
179  Worklist.push_back(const_cast<BasicBlock*>(A));
180 
181  return isPotentiallyReachableFromMany(Worklist, const_cast<BasicBlock *>(B),
182  DT, LI);
183 }
184 
186  const DominatorTree *DT, const LoopInfo *LI) {
187  assert(A->getParent()->getParent() == B->getParent()->getParent() &&
188  "This analysis is function-local!");
189 
191 
192  if (A->getParent() == B->getParent()) {
193  // The same block case is special because it's the only time we're looking
194  // within a single block to see which instruction comes first. Once we
195  // start looking at multiple blocks, the first instruction of the block is
196  // reachable, so we only need to determine reachability between whole
197  // blocks.
198  BasicBlock *BB = const_cast<BasicBlock *>(A->getParent());
199 
200  // If the block is in a loop then we can reach any instruction in the block
201  // from any other instruction in the block by going around a backedge.
202  if (LI && LI->getLoopFor(BB) != nullptr)
203  return true;
204 
205  // Linear scan, start at 'A', see whether we hit 'B' or the end first.
206  for (BasicBlock::const_iterator I = A, E = BB->end(); I != E; ++I) {
207  if (&*I == B)
208  return true;
209  }
210 
211  // Can't be in a loop if it's the entry block -- the entry block may not
212  // have predecessors.
213  if (BB == &BB->getParent()->getEntryBlock())
214  return false;
215 
216  // Otherwise, continue doing the normal per-BB CFG walk.
217  Worklist.append(succ_begin(BB), succ_end(BB));
218 
219  if (Worklist.empty()) {
220  // We've proven that there's no path!
221  return false;
222  }
223  } else {
224  Worklist.push_back(const_cast<BasicBlock*>(A->getParent()));
225  }
226 
227  if (A->getParent() == &A->getParent()->getParent()->getEntryBlock())
228  return true;
229  if (B->getParent() == &A->getParent()->getParent()->getEntryBlock())
230  return false;
231 
233  Worklist, const_cast<BasicBlock *>(B->getParent()), DT, LI);
234 }
size_type count(PtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
Definition: SmallPtrSet.h:276
LoopT * getParentLoop() const
Definition: LoopInfo.h:97
const Function * getParent() const
Return the enclosing method, or null if none.
Definition: BasicBlock.h:111
F(f)
unsigned GetSuccessorNumber(BasicBlock *BB, BasicBlock *Succ)
Search for the specified successor of basic block BB and return its position in the terminator instru...
Definition: CFG.cpp:72
LoopT * getLoopFor(const BlockT *BB) const
getLoopFor - Return the inner most loop that BB lives in.
Definition: LoopInfo.h:540
T LLVM_ATTRIBUTE_UNUSED_RESULT pop_back_val()
Definition: SmallVector.h:406
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: APInt.h:33
Interval::succ_iterator succ_begin(Interval *I)
succ_begin/succ_end - define methods so that Intervals may be used just like BasicBlocks can with the...
Definition: Interval.h:104
bool LLVM_ATTRIBUTE_UNUSED_RESULT empty() const
Definition: SmallVector.h:57
bool isReachableFromEntry(const Use &U) const
Provide an overload for a Use.
Definition: Dominators.cpp:265
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
Definition: Dominators.h:67
Interval::succ_iterator succ_end(Interval *I)
Definition: Interval.h:107
unsigned getNumSuccessors() const
Return the number of successors that this terminator has.
Definition: InstrTypes.h:57
static const Loop * getOutermostLoop(const LoopInfo *LI, const BasicBlock *BB)
Definition: CFG.cpp:112
static bool loopContainsBoth(const LoopInfo *LI, const BasicBlock *BB1, const BasicBlock *BB2)
Definition: CFG.cpp:122
Subclasses of this class are all able to terminate a basic block.
Definition: InstrTypes.h:35
LLVM Basic Block Representation.
Definition: BasicBlock.h:65
BasicBlock * getSuccessor(unsigned idx) const
Return the specified successor.
Definition: InstrTypes.h:62
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition: SmallSet.h:32
bool succ_empty(const BasicBlock *BB)
Definition: IR/CFG.h:268
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:264
Interval::pred_iterator pred_begin(Interval *I)
pred_begin/pred_end - define methods so that Intervals may be used just like BasicBlocks can with the...
Definition: Interval.h:114
Interval::pred_iterator pred_end(Interval *I)
Definition: Interval.h:117
bool isPotentiallyReachable(const Instruction *From, const Instruction *To, const DominatorTree *DT=nullptr, const LoopInfo *LI=nullptr)
Determine whether instruction 'To' is reachable from 'From', returning true if uncertain.
Definition: CFG.cpp:185
std::pair< NoneType, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Definition: SmallSet.h:69
void append(in_iter in_start, in_iter in_end)
Add the specified range to the end of the SmallVector.
Definition: SmallVector.h:416
bool dominates(const Instruction *Def, const Use &U) const
Return true if Def dominates a use in User.
Definition: Dominators.cpp:214
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
Definition: SmallPtrSet.h:299
void FindFunctionBackedges(const Function &F, SmallVectorImpl< std::pair< const BasicBlock *, const BasicBlock * > > &Result)
Analyze the specified function to find all of the loop backedges in the function and return them...
Definition: CFG.cpp:27
bool erase(PtrType Ptr)
erase - If the set contains the specified pointer, remove it and return true, otherwise return false...
Definition: SmallPtrSet.h:271
iterator end()
Definition: BasicBlock.h:233
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:861
const BasicBlock & getEntryBlock() const
Definition: Function.h:442
#define I(x, y, z)
Definition: MD5.cpp:54
TerminatorInst * getTerminator()
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition: BasicBlock.cpp:124
bool isPotentiallyReachableFromMany(SmallVectorImpl< BasicBlock * > &Worklist, BasicBlock *StopBB, const DominatorTree *DT=nullptr, const LoopInfo *LI=nullptr)
Determine whether there is at least one path from a block in 'Worklist' to 'StopBB', returning true if uncertain.
Definition: CFG.cpp:129
const BasicBlock * getParent() const
Definition: Instruction.h:72
bool isCriticalEdge(const TerminatorInst *TI, unsigned SuccNum, bool AllowIdenticalEdges=false)
Return true if the specified edge is a critical edge.
Definition: CFG.cpp:87