LLVM API Documentation

Dominators.cpp
Go to the documentation of this file.
00001 //===- Dominators.cpp - Dominator Calculation -----------------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements simple dominator construction algorithms for finding
00011 // forward dominators.  Postdominators are available in libanalysis, but are not
00012 // included in libvmcore, because it's not needed.  Forward dominators are
00013 // needed to support the Verifier pass.
00014 //
00015 //===----------------------------------------------------------------------===//
00016 
00017 #include "llvm/IR/Dominators.h"
00018 #include "llvm/ADT/DepthFirstIterator.h"
00019 #include "llvm/ADT/SmallPtrSet.h"
00020 #include "llvm/ADT/SmallVector.h"
00021 #include "llvm/IR/CFG.h"
00022 #include "llvm/IR/Instructions.h"
00023 #include "llvm/Support/CommandLine.h"
00024 #include "llvm/Support/Compiler.h"
00025 #include "llvm/Support/Debug.h"
00026 #include "llvm/Support/GenericDomTreeConstruction.h"
00027 #include "llvm/Support/raw_ostream.h"
00028 #include <algorithm>
00029 using namespace llvm;
00030 
00031 // Always verify dominfo if expensive checking is enabled.
00032 #ifdef XDEBUG
00033 static bool VerifyDomInfo = true;
00034 #else
00035 static bool VerifyDomInfo = false;
00036 #endif
00037 static cl::opt<bool,true>
00038 VerifyDomInfoX("verify-dom-info", cl::location(VerifyDomInfo),
00039                cl::desc("Verify dominator info (time consuming)"));
00040 
00041 bool BasicBlockEdge::isSingleEdge() const {
00042   const TerminatorInst *TI = Start->getTerminator();
00043   unsigned NumEdgesToEnd = 0;
00044   for (unsigned int i = 0, n = TI->getNumSuccessors(); i < n; ++i) {
00045     if (TI->getSuccessor(i) == End)
00046       ++NumEdgesToEnd;
00047     if (NumEdgesToEnd >= 2)
00048       return false;
00049   }
00050   assert(NumEdgesToEnd == 1);
00051   return true;
00052 }
00053 
00054 //===----------------------------------------------------------------------===//
00055 //  DominatorTree Implementation
00056 //===----------------------------------------------------------------------===//
00057 //
00058 // Provide public access to DominatorTree information.  Implementation details
00059 // can be found in Dominators.h, GenericDomTree.h, and
00060 // GenericDomTreeConstruction.h.
00061 //
00062 //===----------------------------------------------------------------------===//
00063 
00064 TEMPLATE_INSTANTIATION(class llvm::DomTreeNodeBase<BasicBlock>);
00065 TEMPLATE_INSTANTIATION(class llvm::DominatorTreeBase<BasicBlock>);
00066 
00067 #define LLVM_COMMA ,
00068 TEMPLATE_INSTANTIATION(void llvm::Calculate<Function LLVM_COMMA BasicBlock *>(
00069     DominatorTreeBase<GraphTraits<BasicBlock *>::NodeType> &DT LLVM_COMMA
00070         Function &F));
00071 TEMPLATE_INSTANTIATION(
00072     void llvm::Calculate<Function LLVM_COMMA Inverse<BasicBlock *> >(
00073         DominatorTreeBase<GraphTraits<Inverse<BasicBlock *> >::NodeType> &DT
00074             LLVM_COMMA Function &F));
00075 #undef LLVM_COMMA
00076 
00077 // dominates - Return true if Def dominates a use in User. This performs
00078 // the special checks necessary if Def and User are in the same basic block.
00079 // Note that Def doesn't dominate a use in Def itself!
00080 bool DominatorTree::dominates(const Instruction *Def,
00081                               const Instruction *User) const {
00082   const BasicBlock *UseBB = User->getParent();
00083   const BasicBlock *DefBB = Def->getParent();
00084 
00085   // Any unreachable use is dominated, even if Def == User.
00086   if (!isReachableFromEntry(UseBB))
00087     return true;
00088 
00089   // Unreachable definitions don't dominate anything.
00090   if (!isReachableFromEntry(DefBB))
00091     return false;
00092 
00093   // An instruction doesn't dominate a use in itself.
00094   if (Def == User)
00095     return false;
00096 
00097   // The value defined by an invoke dominates an instruction only if
00098   // it dominates every instruction in UseBB.
00099   // A PHI is dominated only if the instruction dominates every possible use
00100   // in the UseBB.
00101   if (isa<InvokeInst>(Def) || isa<PHINode>(User))
00102     return dominates(Def, UseBB);
00103 
00104   if (DefBB != UseBB)
00105     return dominates(DefBB, UseBB);
00106 
00107   // Loop through the basic block until we find Def or User.
00108   BasicBlock::const_iterator I = DefBB->begin();
00109   for (; &*I != Def && &*I != User; ++I)
00110     /*empty*/;
00111 
00112   return &*I == Def;
00113 }
00114 
00115 // true if Def would dominate a use in any instruction in UseBB.
00116 // note that dominates(Def, Def->getParent()) is false.
00117 bool DominatorTree::dominates(const Instruction *Def,
00118                               const BasicBlock *UseBB) const {
00119   const BasicBlock *DefBB = Def->getParent();
00120 
00121   // Any unreachable use is dominated, even if DefBB == UseBB.
00122   if (!isReachableFromEntry(UseBB))
00123     return true;
00124 
00125   // Unreachable definitions don't dominate anything.
00126   if (!isReachableFromEntry(DefBB))
00127     return false;
00128 
00129   if (DefBB == UseBB)
00130     return false;
00131 
00132   const InvokeInst *II = dyn_cast<InvokeInst>(Def);
00133   if (!II)
00134     return dominates(DefBB, UseBB);
00135 
00136   // Invoke results are only usable in the normal destination, not in the
00137   // exceptional destination.
00138   BasicBlock *NormalDest = II->getNormalDest();
00139   BasicBlockEdge E(DefBB, NormalDest);
00140   return dominates(E, UseBB);
00141 }
00142 
00143 bool DominatorTree::dominates(const BasicBlockEdge &BBE,
00144                               const BasicBlock *UseBB) const {
00145   // Assert that we have a single edge. We could handle them by simply
00146   // returning false, but since isSingleEdge is linear on the number of
00147   // edges, the callers can normally handle them more efficiently.
00148   assert(BBE.isSingleEdge());
00149 
00150   // If the BB the edge ends in doesn't dominate the use BB, then the
00151   // edge also doesn't.
00152   const BasicBlock *Start = BBE.getStart();
00153   const BasicBlock *End = BBE.getEnd();
00154   if (!dominates(End, UseBB))
00155     return false;
00156 
00157   // Simple case: if the end BB has a single predecessor, the fact that it
00158   // dominates the use block implies that the edge also does.
00159   if (End->getSinglePredecessor())
00160     return true;
00161 
00162   // The normal edge from the invoke is critical. Conceptually, what we would
00163   // like to do is split it and check if the new block dominates the use.
00164   // With X being the new block, the graph would look like:
00165   //
00166   //        DefBB
00167   //          /\      .  .
00168   //         /  \     .  .
00169   //        /    \    .  .
00170   //       /      \   |  |
00171   //      A        X  B  C
00172   //      |         \ | /
00173   //      .          \|/
00174   //      .      NormalDest
00175   //      .
00176   //
00177   // Given the definition of dominance, NormalDest is dominated by X iff X
00178   // dominates all of NormalDest's predecessors (X, B, C in the example). X
00179   // trivially dominates itself, so we only have to find if it dominates the
00180   // other predecessors. Since the only way out of X is via NormalDest, X can
00181   // only properly dominate a node if NormalDest dominates that node too.
00182   for (const_pred_iterator PI = pred_begin(End), E = pred_end(End);
00183        PI != E; ++PI) {
00184     const BasicBlock *BB = *PI;
00185     if (BB == Start)
00186       continue;
00187 
00188     if (!dominates(End, BB))
00189       return false;
00190   }
00191   return true;
00192 }
00193 
00194 bool DominatorTree::dominates(const BasicBlockEdge &BBE, const Use &U) const {
00195   // Assert that we have a single edge. We could handle them by simply
00196   // returning false, but since isSingleEdge is linear on the number of
00197   // edges, the callers can normally handle them more efficiently.
00198   assert(BBE.isSingleEdge());
00199 
00200   Instruction *UserInst = cast<Instruction>(U.getUser());
00201   // A PHI in the end of the edge is dominated by it.
00202   PHINode *PN = dyn_cast<PHINode>(UserInst);
00203   if (PN && PN->getParent() == BBE.getEnd() &&
00204       PN->getIncomingBlock(U) == BBE.getStart())
00205     return true;
00206 
00207   // Otherwise use the edge-dominates-block query, which
00208   // handles the crazy critical edge cases properly.
00209   const BasicBlock *UseBB;
00210   if (PN)
00211     UseBB = PN->getIncomingBlock(U);
00212   else
00213     UseBB = UserInst->getParent();
00214   return dominates(BBE, UseBB);
00215 }
00216 
00217 bool DominatorTree::dominates(const Instruction *Def, const Use &U) const {
00218   Instruction *UserInst = cast<Instruction>(U.getUser());
00219   const BasicBlock *DefBB = Def->getParent();
00220 
00221   // Determine the block in which the use happens. PHI nodes use
00222   // their operands on edges; simulate this by thinking of the use
00223   // happening at the end of the predecessor block.
00224   const BasicBlock *UseBB;
00225   if (PHINode *PN = dyn_cast<PHINode>(UserInst))
00226     UseBB = PN->getIncomingBlock(U);
00227   else
00228     UseBB = UserInst->getParent();
00229 
00230   // Any unreachable use is dominated, even if Def == User.
00231   if (!isReachableFromEntry(UseBB))
00232     return true;
00233 
00234   // Unreachable definitions don't dominate anything.
00235   if (!isReachableFromEntry(DefBB))
00236     return false;
00237 
00238   // Invoke instructions define their return values on the edges
00239   // to their normal successors, so we have to handle them specially.
00240   // Among other things, this means they don't dominate anything in
00241   // their own block, except possibly a phi, so we don't need to
00242   // walk the block in any case.
00243   if (const InvokeInst *II = dyn_cast<InvokeInst>(Def)) {
00244     BasicBlock *NormalDest = II->getNormalDest();
00245     BasicBlockEdge E(DefBB, NormalDest);
00246     return dominates(E, U);
00247   }
00248 
00249   // If the def and use are in different blocks, do a simple CFG dominator
00250   // tree query.
00251   if (DefBB != UseBB)
00252     return dominates(DefBB, UseBB);
00253 
00254   // Ok, def and use are in the same block. If the def is an invoke, it
00255   // doesn't dominate anything in the block. If it's a PHI, it dominates
00256   // everything in the block.
00257   if (isa<PHINode>(UserInst))
00258     return true;
00259 
00260   // Otherwise, just loop through the basic block until we find Def or User.
00261   BasicBlock::const_iterator I = DefBB->begin();
00262   for (; &*I != Def && &*I != UserInst; ++I)
00263     /*empty*/;
00264 
00265   return &*I != UserInst;
00266 }
00267 
00268 bool DominatorTree::isReachableFromEntry(const Use &U) const {
00269   Instruction *I = dyn_cast<Instruction>(U.getUser());
00270 
00271   // ConstantExprs aren't really reachable from the entry block, but they
00272   // don't need to be treated like unreachable code either.
00273   if (!I) return true;
00274 
00275   // PHI nodes use their operands on their incoming edges.
00276   if (PHINode *PN = dyn_cast<PHINode>(I))
00277     return isReachableFromEntry(PN->getIncomingBlock(U));
00278 
00279   // Everything else uses their operands in their own block.
00280   return isReachableFromEntry(I->getParent());
00281 }
00282 
00283 void DominatorTree::verifyDomTree() const {
00284   if (!VerifyDomInfo)
00285     return;
00286 
00287   Function &F = *getRoot()->getParent();
00288 
00289   DominatorTree OtherDT;
00290   OtherDT.recalculate(F);
00291   if (compare(OtherDT)) {
00292     errs() << "DominatorTree is not up to date!\nComputed:\n";
00293     print(errs());
00294     errs() << "\nActual:\n";
00295     OtherDT.print(errs());
00296     abort();
00297   }
00298 }
00299 
00300 //===----------------------------------------------------------------------===//
00301 //  DominatorTreeWrapperPass Implementation
00302 //===----------------------------------------------------------------------===//
00303 //
00304 // The implementation details of the wrapper pass that holds a DominatorTree.
00305 //
00306 //===----------------------------------------------------------------------===//
00307 
00308 char DominatorTreeWrapperPass::ID = 0;
00309 INITIALIZE_PASS(DominatorTreeWrapperPass, "domtree",
00310                 "Dominator Tree Construction", true, true)
00311 
00312 bool DominatorTreeWrapperPass::runOnFunction(Function &F) {
00313   DT.recalculate(F);
00314   return false;
00315 }
00316 
00317 void DominatorTreeWrapperPass::verifyAnalysis() const { DT.verifyDomTree(); }
00318 
00319 void DominatorTreeWrapperPass::print(raw_ostream &OS, const Module *) const {
00320   DT.print(OS);
00321 }
00322