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