Home | History | Annotate | Line # | Download | only in IR
      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 the (end of the) basic block BB dominates the use U.
    169   bool dominates(const BasicBlock *BB, const Use &U) const;
    170 
    171   /// Return true if value Def dominates use U, in the sense that Def is
    172   /// available at U, and could be substituted as the used value without
    173   /// violating the SSA dominance requirement.
    174   ///
    175   /// In particular, it is worth noting that:
    176   ///  * Non-instruction Defs dominate everything.
    177   ///  * Def does not dominate a use in Def itself (outside of degenerate cases
    178   ///    like unreachable code or trivial phi cycles).
    179   ///  * Invoke/callbr Defs only dominate uses in their default destination.
    180   bool dominates(const Value *Def, const Use &U) const;
    181   /// Return true if value Def dominates all possible uses inside instruction
    182   /// User. Same comments as for the Use-based API apply.
    183   bool dominates(const Value *Def, const Instruction *User) const;
    184   // Does not accept Value to avoid ambiguity with dominance checks between
    185   // two basic blocks.
    186   bool dominates(const Instruction *Def, const BasicBlock *BB) const;
    187 
    188   /// Return true if an edge dominates a use.
    189   ///
    190   /// If BBE is not a unique edge between start and end of the edge, it can
    191   /// never dominate the use.
    192   bool dominates(const BasicBlockEdge &BBE, const Use &U) const;
    193   bool dominates(const BasicBlockEdge &BBE, const BasicBlock *BB) const;
    194   /// Returns true if edge \p BBE1 dominates edge \p BBE2.
    195   bool dominates(const BasicBlockEdge &BBE1, const BasicBlockEdge &BBE2) const;
    196 
    197   // Ensure base class overloads are visible.
    198   using Base::isReachableFromEntry;
    199 
    200   /// Provide an overload for a Use.
    201   bool isReachableFromEntry(const Use &U) const;
    202 
    203   // Pop up a GraphViz/gv window with the Dominator Tree rendered using `dot`.
    204   void viewGraph(const Twine &Name, const Twine &Title);
    205   void viewGraph();
    206 };
    207 
    208 //===-------------------------------------
    209 // DominatorTree GraphTraits specializations so the DominatorTree can be
    210 // iterable by generic graph iterators.
    211 
    212 template <class Node, class ChildIterator> struct DomTreeGraphTraitsBase {
    213   using NodeRef = Node *;
    214   using ChildIteratorType = ChildIterator;
    215   using nodes_iterator = df_iterator<Node *, df_iterator_default_set<Node*>>;
    216 
    217   static NodeRef getEntryNode(NodeRef N) { return N; }
    218   static ChildIteratorType child_begin(NodeRef N) { return N->begin(); }
    219   static ChildIteratorType child_end(NodeRef N) { return N->end(); }
    220 
    221   static nodes_iterator nodes_begin(NodeRef N) {
    222     return df_begin(getEntryNode(N));
    223   }
    224 
    225   static nodes_iterator nodes_end(NodeRef N) { return df_end(getEntryNode(N)); }
    226 };
    227 
    228 template <>
    229 struct GraphTraits<DomTreeNode *>
    230     : public DomTreeGraphTraitsBase<DomTreeNode, DomTreeNode::const_iterator> {
    231 };
    232 
    233 template <>
    234 struct GraphTraits<const DomTreeNode *>
    235     : public DomTreeGraphTraitsBase<const DomTreeNode,
    236                                     DomTreeNode::const_iterator> {};
    237 
    238 template <> struct GraphTraits<DominatorTree*>
    239   : public GraphTraits<DomTreeNode*> {
    240   static NodeRef getEntryNode(DominatorTree *DT) { return DT->getRootNode(); }
    241 
    242   static nodes_iterator nodes_begin(DominatorTree *N) {
    243     return df_begin(getEntryNode(N));
    244   }
    245 
    246   static nodes_iterator nodes_end(DominatorTree *N) {
    247     return df_end(getEntryNode(N));
    248   }
    249 };
    250 
    251 /// Analysis pass which computes a \c DominatorTree.
    252 class DominatorTreeAnalysis : public AnalysisInfoMixin<DominatorTreeAnalysis> {
    253   friend AnalysisInfoMixin<DominatorTreeAnalysis>;
    254   static AnalysisKey Key;
    255 
    256 public:
    257   /// Provide the result typedef for this analysis pass.
    258   using Result = DominatorTree;
    259 
    260   /// Run the analysis pass over a function and produce a dominator tree.
    261   DominatorTree run(Function &F, FunctionAnalysisManager &);
    262 };
    263 
    264 /// Printer pass for the \c DominatorTree.
    265 class DominatorTreePrinterPass
    266     : public PassInfoMixin<DominatorTreePrinterPass> {
    267   raw_ostream &OS;
    268 
    269 public:
    270   explicit DominatorTreePrinterPass(raw_ostream &OS);
    271 
    272   PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM);
    273 };
    274 
    275 /// Verifier pass for the \c DominatorTree.
    276 struct DominatorTreeVerifierPass : PassInfoMixin<DominatorTreeVerifierPass> {
    277   PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM);
    278 };
    279 
    280 /// Legacy analysis pass which computes a \c DominatorTree.
    281 class DominatorTreeWrapperPass : public FunctionPass {
    282   DominatorTree DT;
    283 
    284 public:
    285   static char ID;
    286 
    287   DominatorTreeWrapperPass();
    288 
    289   DominatorTree &getDomTree() { return DT; }
    290   const DominatorTree &getDomTree() const { return DT; }
    291 
    292   bool runOnFunction(Function &F) override;
    293 
    294   void verifyAnalysis() const override;
    295 
    296   void getAnalysisUsage(AnalysisUsage &AU) const override {
    297     AU.setPreservesAll();
    298   }
    299 
    300   void releaseMemory() override { DT.reset(); }
    301 
    302   void print(raw_ostream &OS, const Module *M = nullptr) const override;
    303 };
    304 } // end namespace llvm
    305 
    306 #endif // LLVM_IR_DOMINATORS_H
    307