Dominators.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- Dominators.h - Dominator Info Calculation ----------------*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. //
  14. // This file defines the DominatorTree class, which provides fast and efficient
  15. // dominance queries.
  16. //
  17. //===----------------------------------------------------------------------===//
  18. #ifndef LLVM_IR_DOMINATORS_H
  19. #define LLVM_IR_DOMINATORS_H
  20. #include "llvm/ADT/DenseMapInfo.h"
  21. #include "llvm/ADT/DepthFirstIterator.h"
  22. #include "llvm/ADT/GraphTraits.h"
  23. #include "llvm/ADT/Hashing.h"
  24. #include "llvm/IR/BasicBlock.h"
  25. #include "llvm/IR/CFG.h"
  26. #include "llvm/IR/PassManager.h"
  27. #include "llvm/Pass.h"
  28. #include "llvm/Support/GenericDomTree.h"
  29. #include <utility>
  30. namespace llvm {
  31. class Function;
  32. class Instruction;
  33. class Module;
  34. class raw_ostream;
  35. extern template class DomTreeNodeBase<BasicBlock>;
  36. extern template class DominatorTreeBase<BasicBlock, false>; // DomTree
  37. extern template class DominatorTreeBase<BasicBlock, true>; // PostDomTree
  38. extern template class cfg::Update<BasicBlock *>;
  39. namespace DomTreeBuilder {
  40. using BBDomTree = DomTreeBase<BasicBlock>;
  41. using BBPostDomTree = PostDomTreeBase<BasicBlock>;
  42. using BBUpdates = ArrayRef<llvm::cfg::Update<BasicBlock *>>;
  43. using BBDomTreeGraphDiff = GraphDiff<BasicBlock *, false>;
  44. using BBPostDomTreeGraphDiff = GraphDiff<BasicBlock *, true>;
  45. extern template void Calculate<BBDomTree>(BBDomTree &DT);
  46. extern template void CalculateWithUpdates<BBDomTree>(BBDomTree &DT,
  47. BBUpdates U);
  48. extern template void Calculate<BBPostDomTree>(BBPostDomTree &DT);
  49. extern template void InsertEdge<BBDomTree>(BBDomTree &DT, BasicBlock *From,
  50. BasicBlock *To);
  51. extern template void InsertEdge<BBPostDomTree>(BBPostDomTree &DT,
  52. BasicBlock *From,
  53. BasicBlock *To);
  54. extern template void DeleteEdge<BBDomTree>(BBDomTree &DT, BasicBlock *From,
  55. BasicBlock *To);
  56. extern template void DeleteEdge<BBPostDomTree>(BBPostDomTree &DT,
  57. BasicBlock *From,
  58. BasicBlock *To);
  59. extern template void ApplyUpdates<BBDomTree>(BBDomTree &DT,
  60. BBDomTreeGraphDiff &,
  61. BBDomTreeGraphDiff *);
  62. extern template void ApplyUpdates<BBPostDomTree>(BBPostDomTree &DT,
  63. BBPostDomTreeGraphDiff &,
  64. BBPostDomTreeGraphDiff *);
  65. extern template bool Verify<BBDomTree>(const BBDomTree &DT,
  66. BBDomTree::VerificationLevel VL);
  67. extern template bool Verify<BBPostDomTree>(const BBPostDomTree &DT,
  68. BBPostDomTree::VerificationLevel VL);
  69. } // namespace DomTreeBuilder
  70. using DomTreeNode = DomTreeNodeBase<BasicBlock>;
  71. class BasicBlockEdge {
  72. const BasicBlock *Start;
  73. const BasicBlock *End;
  74. public:
  75. BasicBlockEdge(const BasicBlock *Start_, const BasicBlock *End_) :
  76. Start(Start_), End(End_) {}
  77. BasicBlockEdge(const std::pair<BasicBlock *, BasicBlock *> &Pair)
  78. : Start(Pair.first), End(Pair.second) {}
  79. BasicBlockEdge(const std::pair<const BasicBlock *, const BasicBlock *> &Pair)
  80. : Start(Pair.first), End(Pair.second) {}
  81. const BasicBlock *getStart() const {
  82. return Start;
  83. }
  84. const BasicBlock *getEnd() const {
  85. return End;
  86. }
  87. /// Check if this is the only edge between Start and End.
  88. bool isSingleEdge() const;
  89. };
  90. template <> struct DenseMapInfo<BasicBlockEdge> {
  91. using BBInfo = DenseMapInfo<const BasicBlock *>;
  92. static unsigned getHashValue(const BasicBlockEdge *V);
  93. static inline BasicBlockEdge getEmptyKey() {
  94. return BasicBlockEdge(BBInfo::getEmptyKey(), BBInfo::getEmptyKey());
  95. }
  96. static inline BasicBlockEdge getTombstoneKey() {
  97. return BasicBlockEdge(BBInfo::getTombstoneKey(), BBInfo::getTombstoneKey());
  98. }
  99. static unsigned getHashValue(const BasicBlockEdge &Edge) {
  100. return hash_combine(BBInfo::getHashValue(Edge.getStart()),
  101. BBInfo::getHashValue(Edge.getEnd()));
  102. }
  103. static bool isEqual(const BasicBlockEdge &LHS, const BasicBlockEdge &RHS) {
  104. return BBInfo::isEqual(LHS.getStart(), RHS.getStart()) &&
  105. BBInfo::isEqual(LHS.getEnd(), RHS.getEnd());
  106. }
  107. };
  108. /// Concrete subclass of DominatorTreeBase that is used to compute a
  109. /// normal dominator tree.
  110. ///
  111. /// Definition: A block is said to be forward statically reachable if there is
  112. /// a path from the entry of the function to the block. A statically reachable
  113. /// block may become statically unreachable during optimization.
  114. ///
  115. /// A forward unreachable block may appear in the dominator tree, or it may
  116. /// not. If it does, dominance queries will return results as if all reachable
  117. /// blocks dominate it. When asking for a Node corresponding to a potentially
  118. /// unreachable block, calling code must handle the case where the block was
  119. /// unreachable and the result of getNode() is nullptr.
  120. ///
  121. /// Generally, a block known to be unreachable when the dominator tree is
  122. /// constructed will not be in the tree. One which becomes unreachable after
  123. /// the dominator tree is initially constructed may still exist in the tree,
  124. /// even if the tree is properly updated. Calling code should not rely on the
  125. /// preceding statements; this is stated only to assist human understanding.
  126. class DominatorTree : public DominatorTreeBase<BasicBlock, false> {
  127. public:
  128. using Base = DominatorTreeBase<BasicBlock, false>;
  129. DominatorTree() = default;
  130. explicit DominatorTree(Function &F) { recalculate(F); }
  131. explicit DominatorTree(DominatorTree &DT, DomTreeBuilder::BBUpdates U) {
  132. recalculate(*DT.Parent, U);
  133. }
  134. /// Handle invalidation explicitly.
  135. bool invalidate(Function &F, const PreservedAnalyses &PA,
  136. FunctionAnalysisManager::Invalidator &);
  137. // Ensure base-class overloads are visible.
  138. using Base::dominates;
  139. /// Return true if value Def dominates use U, in the sense that Def is
  140. /// available at U, and could be substituted as the used value without
  141. /// violating the SSA dominance requirement.
  142. ///
  143. /// In particular, it is worth noting that:
  144. /// * Non-instruction Defs dominate everything.
  145. /// * Def does not dominate a use in Def itself (outside of degenerate cases
  146. /// like unreachable code or trivial phi cycles).
  147. /// * Invoke/callbr Defs only dominate uses in their default destination.
  148. bool dominates(const Value *Def, const Use &U) const;
  149. /// Return true if value Def dominates all possible uses inside instruction
  150. /// User. Same comments as for the Use-based API apply.
  151. bool dominates(const Value *Def, const Instruction *User) const;
  152. // Does not accept Value to avoid ambiguity with dominance checks between
  153. // two basic blocks.
  154. bool dominates(const Instruction *Def, const BasicBlock *BB) const;
  155. /// Return true if an edge dominates a use.
  156. ///
  157. /// If BBE is not a unique edge between start and end of the edge, it can
  158. /// never dominate the use.
  159. bool dominates(const BasicBlockEdge &BBE, const Use &U) const;
  160. bool dominates(const BasicBlockEdge &BBE, const BasicBlock *BB) const;
  161. /// Returns true if edge \p BBE1 dominates edge \p BBE2.
  162. bool dominates(const BasicBlockEdge &BBE1, const BasicBlockEdge &BBE2) const;
  163. // Ensure base class overloads are visible.
  164. using Base::isReachableFromEntry;
  165. /// Provide an overload for a Use.
  166. bool isReachableFromEntry(const Use &U) const;
  167. // Pop up a GraphViz/gv window with the Dominator Tree rendered using `dot`.
  168. void viewGraph(const Twine &Name, const Twine &Title);
  169. void viewGraph();
  170. };
  171. //===-------------------------------------
  172. // DominatorTree GraphTraits specializations so the DominatorTree can be
  173. // iterable by generic graph iterators.
  174. template <class Node, class ChildIterator> struct DomTreeGraphTraitsBase {
  175. using NodeRef = Node *;
  176. using ChildIteratorType = ChildIterator;
  177. using nodes_iterator = df_iterator<Node *, df_iterator_default_set<Node*>>;
  178. static NodeRef getEntryNode(NodeRef N) { return N; }
  179. static ChildIteratorType child_begin(NodeRef N) { return N->begin(); }
  180. static ChildIteratorType child_end(NodeRef N) { return N->end(); }
  181. static nodes_iterator nodes_begin(NodeRef N) {
  182. return df_begin(getEntryNode(N));
  183. }
  184. static nodes_iterator nodes_end(NodeRef N) { return df_end(getEntryNode(N)); }
  185. };
  186. template <>
  187. struct GraphTraits<DomTreeNode *>
  188. : public DomTreeGraphTraitsBase<DomTreeNode, DomTreeNode::const_iterator> {
  189. };
  190. template <>
  191. struct GraphTraits<const DomTreeNode *>
  192. : public DomTreeGraphTraitsBase<const DomTreeNode,
  193. DomTreeNode::const_iterator> {};
  194. template <> struct GraphTraits<DominatorTree*>
  195. : public GraphTraits<DomTreeNode*> {
  196. static NodeRef getEntryNode(DominatorTree *DT) { return DT->getRootNode(); }
  197. static nodes_iterator nodes_begin(DominatorTree *N) {
  198. return df_begin(getEntryNode(N));
  199. }
  200. static nodes_iterator nodes_end(DominatorTree *N) {
  201. return df_end(getEntryNode(N));
  202. }
  203. };
  204. /// Analysis pass which computes a \c DominatorTree.
  205. class DominatorTreeAnalysis : public AnalysisInfoMixin<DominatorTreeAnalysis> {
  206. friend AnalysisInfoMixin<DominatorTreeAnalysis>;
  207. static AnalysisKey Key;
  208. public:
  209. /// Provide the result typedef for this analysis pass.
  210. using Result = DominatorTree;
  211. /// Run the analysis pass over a function and produce a dominator tree.
  212. DominatorTree run(Function &F, FunctionAnalysisManager &);
  213. };
  214. /// Printer pass for the \c DominatorTree.
  215. class DominatorTreePrinterPass
  216. : public PassInfoMixin<DominatorTreePrinterPass> {
  217. raw_ostream &OS;
  218. public:
  219. explicit DominatorTreePrinterPass(raw_ostream &OS);
  220. PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM);
  221. };
  222. /// Verifier pass for the \c DominatorTree.
  223. struct DominatorTreeVerifierPass : PassInfoMixin<DominatorTreeVerifierPass> {
  224. PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM);
  225. };
  226. /// Legacy analysis pass which computes a \c DominatorTree.
  227. class DominatorTreeWrapperPass : public FunctionPass {
  228. DominatorTree DT;
  229. public:
  230. static char ID;
  231. DominatorTreeWrapperPass();
  232. DominatorTree &getDomTree() { return DT; }
  233. const DominatorTree &getDomTree() const { return DT; }
  234. bool runOnFunction(Function &F) override;
  235. void verifyAnalysis() const override;
  236. void getAnalysisUsage(AnalysisUsage &AU) const override {
  237. AU.setPreservesAll();
  238. }
  239. void releaseMemory() override { DT.reset(); }
  240. void print(raw_ostream &OS, const Module *M = nullptr) const override;
  241. };
  242. } // end namespace llvm
  243. #endif // LLVM_IR_DOMINATORS_H
  244. #ifdef __GNUC__
  245. #pragma GCC diagnostic pop
  246. #endif