LLVM  7.0.0svn
Dominators.h
Go to the documentation of this file.
1 //===- Dominators.h - Dominator Info Calculation ----------------*- C++ -*-===//
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 file defines the DominatorTree class, which provides fast and efficient
11 // dominance queries.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #ifndef LLVM_IR_DOMINATORS_H
16 #define LLVM_IR_DOMINATORS_H
17 
18 #include "llvm/ADT/DenseMapInfo.h"
20 #include "llvm/ADT/GraphTraits.h"
21 #include "llvm/ADT/Hashing.h"
22 #include "llvm/IR/BasicBlock.h"
23 #include "llvm/IR/CFG.h"
24 #include "llvm/IR/PassManager.h"
25 #include "llvm/Pass.h"
27 #include <utility>
28 
29 namespace llvm {
30 
31 class Function;
32 class Instruction;
33 class Module;
34 class raw_ostream;
35 
36 extern template class DomTreeNodeBase<BasicBlock>;
37 extern template class DominatorTreeBase<BasicBlock, false>; // DomTree
38 extern template class DominatorTreeBase<BasicBlock, true>; // PostDomTree
39 
40 namespace DomTreeBuilder {
43 
44 extern template struct Update<BasicBlock *>;
45 
47 
48 extern template void Calculate<BBDomTree>(BBDomTree &DT);
49 extern template void Calculate<BBPostDomTree>(BBPostDomTree &DT);
50 
51 extern template void InsertEdge<BBDomTree>(BBDomTree &DT, BasicBlock *From,
52  BasicBlock *To);
53 extern template void InsertEdge<BBPostDomTree>(BBPostDomTree &DT,
54  BasicBlock *From,
55  BasicBlock *To);
56 
57 extern template void DeleteEdge<BBDomTree>(BBDomTree &DT, BasicBlock *From,
58  BasicBlock *To);
59 extern template void DeleteEdge<BBPostDomTree>(BBPostDomTree &DT,
60  BasicBlock *From,
61  BasicBlock *To);
62 
63 extern template void ApplyUpdates<BBDomTree>(BBDomTree &DT, BBUpdates);
64 extern template void ApplyUpdates<BBPostDomTree>(BBPostDomTree &DT, BBUpdates);
65 
66 extern template bool Verify<BBDomTree>(const BBDomTree &DT);
67 extern template bool Verify<BBPostDomTree>(const BBPostDomTree &DT);
68 } // namespace DomTreeBuilder
69 
71 
73  const BasicBlock *Start;
74  const BasicBlock *End;
75 
76 public:
77  BasicBlockEdge(const BasicBlock *Start_, const BasicBlock *End_) :
78  Start(Start_), End(End_) {}
79 
80  BasicBlockEdge(const std::pair<BasicBlock *, BasicBlock *> &Pair)
81  : Start(Pair.first), End(Pair.second) {}
82 
83  BasicBlockEdge(const std::pair<const BasicBlock *, const BasicBlock *> &Pair)
84  : Start(Pair.first), End(Pair.second) {}
85 
86  const BasicBlock *getStart() const {
87  return Start;
88  }
89 
90  const BasicBlock *getEnd() const {
91  return End;
92  }
93 
94  /// Check if this is the only edge between Start and End.
95  bool isSingleEdge() const;
96 };
97 
98 template <> struct DenseMapInfo<BasicBlockEdge> {
100 
101  static unsigned getHashValue(const BasicBlockEdge *V);
102 
103  static inline BasicBlockEdge getEmptyKey() {
104  return BasicBlockEdge(BBInfo::getEmptyKey(), BBInfo::getEmptyKey());
105  }
106 
107  static inline BasicBlockEdge getTombstoneKey() {
108  return BasicBlockEdge(BBInfo::getTombstoneKey(), BBInfo::getTombstoneKey());
109  }
110 
111  static unsigned getHashValue(const BasicBlockEdge &Edge) {
112  return hash_combine(BBInfo::getHashValue(Edge.getStart()),
113  BBInfo::getHashValue(Edge.getEnd()));
114  }
115 
116  static bool isEqual(const BasicBlockEdge &LHS, const BasicBlockEdge &RHS) {
117  return BBInfo::isEqual(LHS.getStart(), RHS.getStart()) &&
118  BBInfo::isEqual(LHS.getEnd(), RHS.getEnd());
119  }
120 };
121 
122 /// \brief Concrete subclass of DominatorTreeBase that is used to compute a
123 /// normal dominator tree.
124 ///
125 /// Definition: A block is said to be forward statically reachable if there is
126 /// a path from the entry of the function to the block. A statically reachable
127 /// block may become statically unreachable during optimization.
128 ///
129 /// A forward unreachable block may appear in the dominator tree, or it may
130 /// not. If it does, dominance queries will return results as if all reachable
131 /// blocks dominate it. When asking for a Node corresponding to a potentially
132 /// unreachable block, calling code must handle the case where the block was
133 /// unreachable and the result of getNode() is nullptr.
134 ///
135 /// Generally, a block known to be unreachable when the dominator tree is
136 /// constructed will not be in the tree. One which becomes unreachable after
137 /// the dominator tree is initially constructed may still exist in the tree,
138 /// even if the tree is properly updated. Calling code should not rely on the
139 /// preceding statements; this is stated only to assist human understanding.
141  public:
143 
144  DominatorTree() = default;
145  explicit DominatorTree(Function &F) { recalculate(F); }
146 
147  /// Handle invalidation explicitly.
148  bool invalidate(Function &F, const PreservedAnalyses &PA,
150 
151  /// \brief Returns *false* if the other dominator tree matches this dominator
152  /// tree.
153  inline bool compare(const DominatorTree &Other) const {
154  const DomTreeNode *R = getRootNode();
155  const DomTreeNode *OtherR = Other.getRootNode();
156  return !R || !OtherR || R->getBlock() != OtherR->getBlock() ||
157  Base::compare(Other);
158  }
159 
160  // Ensure base-class overloads are visible.
161  using Base::dominates;
162 
163  /// \brief Return true if Def dominates a use in User.
164  ///
165  /// This performs the special checks necessary if Def and User are in the same
166  /// basic block. Note that Def doesn't dominate a use in Def itself!
167  bool dominates(const Instruction *Def, const Use &U) const;
168  bool dominates(const Instruction *Def, const Instruction *User) const;
169  bool dominates(const Instruction *Def, const BasicBlock *BB) const;
170 
171  /// Return true if an edge dominates a use.
172  ///
173  /// If BBE is not a unique edge between start and end of the edge, it can
174  /// never dominate the use.
175  bool dominates(const BasicBlockEdge &BBE, const Use &U) const;
176  bool dominates(const BasicBlockEdge &BBE, const BasicBlock *BB) const;
177 
178  // Ensure base class overloads are visible.
179  using Base::isReachableFromEntry;
180 
181  /// \brief Provide an overload for a Use.
182  bool isReachableFromEntry(const Use &U) const;
183 
184  /// \brief Verify the correctness of the domtree by re-computing it.
185  ///
186  /// This should only be used for debugging as it aborts the program if the
187  /// verification fails.
188  void verifyDomTree() const;
189 
190  // Pop up a GraphViz/gv window with the Dominator Tree rendered using `dot`.
191  void viewGraph(const Twine &Name, const Twine &Title);
192  void viewGraph();
193 };
194 
195 //===-------------------------------------
196 // DominatorTree GraphTraits specializations so the DominatorTree can be
197 // iterable by generic graph iterators.
198 
199 template <class Node, class ChildIterator> struct DomTreeGraphTraitsBase {
200  using NodeRef = Node *;
201  using ChildIteratorType = ChildIterator;
203 
204  static NodeRef getEntryNode(NodeRef N) { return N; }
205  static ChildIteratorType child_begin(NodeRef N) { return N->begin(); }
206  static ChildIteratorType child_end(NodeRef N) { return N->end(); }
207 
209  return df_begin(getEntryNode(N));
210  }
211 
212  static nodes_iterator nodes_end(NodeRef N) { return df_end(getEntryNode(N)); }
213 };
214 
215 template <>
218 
219 template <>
221  : public DomTreeGraphTraitsBase<const DomTreeNode,
223 
224 template <> struct GraphTraits<DominatorTree*>
225  : public GraphTraits<DomTreeNode*> {
226  static NodeRef getEntryNode(DominatorTree *DT) { return DT->getRootNode(); }
227 
228  static nodes_iterator nodes_begin(DominatorTree *N) {
229  return df_begin(getEntryNode(N));
230  }
231 
232  static nodes_iterator nodes_end(DominatorTree *N) {
233  return df_end(getEntryNode(N));
234  }
235 };
236 
237 /// \brief Analysis pass which computes a \c DominatorTree.
238 class DominatorTreeAnalysis : public AnalysisInfoMixin<DominatorTreeAnalysis> {
240  static AnalysisKey Key;
241 
242 public:
243  /// \brief Provide the result typedef for this analysis pass.
245 
246  /// \brief Run the analysis pass over a function and produce a dominator tree.
248 };
249 
250 /// \brief Printer pass for the \c DominatorTree.
252  : public PassInfoMixin<DominatorTreePrinterPass> {
253  raw_ostream &OS;
254 
255 public:
257 
259 };
260 
261 /// \brief Verifier pass for the \c DominatorTree.
262 struct DominatorTreeVerifierPass : PassInfoMixin<DominatorTreeVerifierPass> {
264 };
265 
266 /// \brief Legacy analysis pass which computes a \c DominatorTree.
268  DominatorTree DT;
269 
270 public:
271  static char ID;
272 
275  }
276 
277  DominatorTree &getDomTree() { return DT; }
278  const DominatorTree &getDomTree() const { return DT; }
279 
280  bool runOnFunction(Function &F) override;
281 
282  void verifyAnalysis() const override;
283 
284  void getAnalysisUsage(AnalysisUsage &AU) const override {
285  AU.setPreservesAll();
286  }
287 
288  void releaseMemory() override { DT.releaseMemory(); }
289 
290  void print(raw_ostream &OS, const Module *M = nullptr) const override;
291 };
292 
293 //===-------------------------------------
294 /// \brief Class to defer updates to a DominatorTree.
295 ///
296 /// Definition: Applying updates to every edge insertion and deletion is
297 /// expensive and not necessary. When one needs the DominatorTree for analysis
298 /// they can request a flush() to perform a larger batch update. This has the
299 /// advantage of the DominatorTree inspecting the set of updates to find
300 /// duplicates or unnecessary subtree updates.
301 ///
302 /// The scope of DeferredDominance operates at a Function level.
303 ///
304 /// It is not necessary for the user to scrub the updates for duplicates or
305 /// updates that point to the same block (Delete, BB_A, BB_A). Performance
306 /// can be gained if the caller attempts to batch updates before submitting
307 /// to applyUpdates(ArrayRef) in cases where duplicate edge requests will
308 /// occur.
309 ///
310 /// It is required for the state of the LLVM IR to be applied *before*
311 /// submitting updates. The update routines must analyze the current state
312 /// between a pair of (From, To) basic blocks to determine if the update
313 /// needs to be queued.
314 /// Example (good):
315 /// TerminatorInstructionBB->removeFromParent();
316 /// DDT->deleteEdge(BB, Successor);
317 /// Example (bad):
318 /// DDT->deleteEdge(BB, Successor);
319 /// TerminatorInstructionBB->removeFromParent();
321 public:
322  DeferredDominance(DominatorTree &DT_) : DT(DT_) {}
323 
324  /// \brief Queues multiple updates and discards duplicates.
325  void applyUpdates(ArrayRef<DominatorTree::UpdateType> Updates);
326 
327  /// \brief Helper method for a single edge insertion. It's almost always
328  /// better to batch updates and call applyUpdates to quickly remove duplicate
329  /// edges. This is best used when there is only a single insertion needed to
330  /// update Dominators.
331  void insertEdge(BasicBlock *From, BasicBlock *To);
332 
333  /// \brief Helper method for a single edge deletion. It's almost always better
334  /// to batch updates and call applyUpdates to quickly remove duplicate edges.
335  /// This is best used when there is only a single deletion needed to update
336  /// Dominators.
337  void deleteEdge(BasicBlock *From, BasicBlock *To);
338 
339  /// \brief Delays the deletion of a basic block until a flush() event.
340  void deleteBB(BasicBlock *DelBB);
341 
342  /// \brief Returns true if DelBB is awaiting deletion at a flush() event.
343  bool pendingDeletedBB(BasicBlock *DelBB);
344 
345  /// \brief Flushes all pending updates and block deletions. Returns a
346  /// correct DominatorTree reference to be used by the caller for analysis.
347  DominatorTree &flush();
348 
349  /// \brief Drops all internal state and forces a (slow) recalculation of the
350  /// DominatorTree based on the current state of the LLVM IR in F. This should
351  /// only be used in corner cases such as the Entry block of F being deleted.
352  void recalculate(Function &F);
353 
354  /// \brief Debug method to help view the state of pending updates.
355  LLVM_DUMP_METHOD void dump() const;
356 
357 private:
358  DominatorTree &DT;
360  SmallPtrSet<BasicBlock *, 8> DeletedBBs;
361 
362  /// Apply an update (Kind, From, To) to the internal queued updates. The
363  /// update is only added when determined to be necessary. Checks for
364  /// self-domination, unnecessary updates, duplicate requests, and balanced
365  /// pairs of requests are all performed. Returns true if the update is
366  /// queued and false if it is discarded.
367  bool applyUpdate(DominatorTree::UpdateKind Kind, BasicBlock *From,
368  BasicBlock *To);
369 
370  /// Performs all pending basic block deletions. We have to defer the deletion
371  /// of these blocks until after the DominatorTree updates are applied. The
372  /// internal workings of the DominatorTree code expect every update's From
373  /// and To blocks to exist and to be a member of the same Function.
374  bool flushDelBB();
375 };
376 
377 } // end namespace llvm
378 
379 #endif // LLVM_IR_DOMINATORS_H
typename std::vector< DomTreeNodeBase *>::const_iterator const_iterator
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
Compute iterated dominance frontiers using a linear time algorithm.
Definition: AllocatorList.h:24
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds...
Definition: Compiler.h:449
DominatorTree(Function &F)
Definition: Dominators.h:145
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:63
static bool isEqual(const BasicBlockEdge &LHS, const BasicBlockEdge &RHS)
Definition: Dominators.h:116
template void DeleteEdge< BBPostDomTree >(BBPostDomTree &DT, BasicBlock *From, BasicBlock *To)
static NodeRef getEntryNode(NodeRef N)
Definition: Dominators.h:204
template void ApplyUpdates< BBDomTree >(BBDomTree &DT, BBUpdates)
template bool Verify< BBDomTree >(const BBDomTree &DT)
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
Definition: Dominators.h:284
unsigned second
Analysis pass which computes a DominatorTree.
Definition: Dominators.h:238
F(f)
const BasicBlock * getEnd() const
Definition: Dominators.h:90
static nodes_iterator nodes_begin(NodeRef N)
Definition: Dominators.h:208
static nodes_iterator nodes_begin(DominatorTree *N)
Definition: Dominators.h:228
void initializeDominatorTreeWrapperPassPass(PassRegistry &)
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
BasicBlockEdge(const std::pair< BasicBlock *, BasicBlock *> &Pair)
Definition: Dominators.h:80
static BasicBlockEdge getEmptyKey()
Definition: Dominators.h:103
A Use represents the edge between a Value definition and its users.
Definition: Use.h:56
DominatorTree & getDomTree()
Definition: Dominators.h:277
ELFYAML::ELF_STO Other
Definition: ELFYAML.cpp:736
template void ApplyUpdates< BBPostDomTree >(BBPostDomTree &DT, BBUpdates)
static bool isEqual(const Function &Caller, const Function &Callee)
static nodes_iterator nodes_end(DominatorTree *N)
Definition: Dominators.h:232
A CRTP mix-in to automatically provide informational APIs needed for passes.
Definition: PassManager.h:365
DeferredDominance(DominatorTree &DT_)
Definition: Dominators.h:322
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: APInt.h:33
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
Definition: Dominators.h:140
void releaseMemory() override
releaseMemory() - This member can be implemented by a pass if it wants to be able to release its memo...
Definition: Dominators.h:288
static nodes_iterator nodes_end(NodeRef N)
Definition: Dominators.h:212
Core dominator tree base class.
Definition: LoopInfo.h:61
NodeT * getBlock() const
static bool runOnFunction(Function &F, bool PostInlining)
typename DomTreeNode *::UnknownGraphTypeError NodeRef
Definition: GraphTraits.h:59
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:153
LLVM Basic Block Representation.
Definition: BasicBlock.h:59
DominatorTree run(Function &F, FunctionAnalysisManager &)
Run the analysis pass over a function and produce a dominator tree.
Definition: Dominators.cpp:340
df_iterator< T > df_end(const T &G)
A CRTP mix-in that provides informational APIs needed for analysis passes.
Definition: PassManager.h:382
Represent the analysis usage information of a pass.
static const unsigned End
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:285
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
Printer pass for the DominatorTree.
Definition: Dominators.h:251
template void Calculate< BBDomTree >(BBDomTree &DT)
DomTreeNodeBase< NodeT > * getRootNode()
getRootNode - This returns the entry node for the CFG of the function.
ArrayRef< Update< BasicBlock * > > BBUpdates
Definition: Dominators.h:46
Verifier pass for the DominatorTree.
Definition: Dominators.h:262
unsigned first
static ChildIteratorType child_begin(NodeRef N)
Definition: Dominators.h:205
static ChildIteratorType child_end(NodeRef N)
Definition: Dominators.h:206
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
Definition: SmallPtrSet.h:418
template void InsertEdge< BBPostDomTree >(BBPostDomTree &DT, BasicBlock *From, BasicBlock *To)
const DominatorTree & getDomTree() const
Definition: Dominators.h:278
df_iterator< T > df_begin(const T &G)
hash_code hash_combine(const Ts &...args)
Combine values into a single hash_code.
Definition: Hashing.h:602
Class to defer updates to a DominatorTree.
Definition: Dominators.h:320
void setPreservesAll()
Set by analyses that do not transform their input at all.
template void DeleteEdge< BBDomTree >(BBDomTree &DT, BasicBlock *From, BasicBlock *To)
bool compare(const DominatorTree &Other) const
Returns false if the other dominator tree matches this dominator tree.
Definition: Dominators.h:153
#define N
static unsigned getHashValue(const BasicBlockEdge &Edge)
Definition: Dominators.h:111
static NodeRef getEntryNode(DominatorTree *DT)
Definition: Dominators.h:226
API to communicate dependencies between analyses during invalidation.
Definition: PassManager.h:559
int compare(DigitsT LDigits, int16_t LScale, DigitsT RDigits, int16_t RScale)
Compare two scaled numbers.
Definition: ScaledNumber.h:252
const unsigned Kind
BasicBlockEdge(const BasicBlock *Start_, const BasicBlock *End_)
Definition: Dominators.h:77
const BasicBlock * getStart() const
Definition: Dominators.h:86
aarch64 promote const
DomTreeNodeBase< BasicBlock > DomTreeNode
Definition: Dominators.h:70
template void Calculate< BBPostDomTree >(BBPostDomTree &DT)
template bool Verify< BBPostDomTree >(const BBPostDomTree &DT)
This class implements an extremely fast bulk output stream that can only output to a stream...
Definition: raw_ostream.h:44
This file defines a set of templates that efficiently compute a dominator tree over a generic graph...
A container for analyses that lazily runs them and caches their results.
Legacy analysis pass which computes a DominatorTree.
Definition: Dominators.h:267
This header defines various interfaces for pass management in LLVM.
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition: PassManager.h:70
BasicBlockEdge(const std::pair< const BasicBlock *, const BasicBlock *> &Pair)
Definition: Dominators.h:83
template void InsertEdge< BBDomTree >(BBDomTree &DT, BasicBlock *From, BasicBlock *To)
static BasicBlockEdge getTombstoneKey()
Definition: Dominators.h:107