Dominators.h 12 KB

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