Dominators.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  1. //===- Dominators.cpp - Dominator Calculation -----------------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements simple dominator construction algorithms for finding
  11. // forward dominators. Postdominators are available in libanalysis, but are not
  12. // included in libvmcore, because it's not needed. Forward dominators are
  13. // needed to support the Verifier pass.
  14. //
  15. //===----------------------------------------------------------------------===//
  16. #include "llvm/IR/Dominators.h"
  17. #include "llvm/ADT/DepthFirstIterator.h"
  18. #include "llvm/ADT/SmallPtrSet.h"
  19. #include "llvm/ADT/SmallVector.h"
  20. #include "llvm/IR/CFG.h"
  21. #include "llvm/IR/Instructions.h"
  22. #include "llvm/IR/PassManager.h"
  23. #include "llvm/Support/CommandLine.h"
  24. #include "llvm/Support/Compiler.h"
  25. #include "llvm/Support/Debug.h"
  26. #include "llvm/Support/GenericDomTreeConstruction.h"
  27. #include "llvm/Support/raw_ostream.h"
  28. #include <algorithm>
  29. using namespace llvm;
  30. // Always verify dominfo if expensive checking is enabled.
  31. #ifdef XDEBUG
  32. static bool VerifyDomInfo = true;
  33. #else
  34. static bool VerifyDomInfo = false;
  35. #endif
  36. #if 0 // HLSL Change Starts - option pending
  37. static cl::opt<bool,true>
  38. VerifyDomInfoX("verify-dom-info", cl::location(VerifyDomInfo),
  39. cl::desc("Verify dominator info (time consuming)"));
  40. #endif // HLSL Change Ends
  41. bool BasicBlockEdge::isSingleEdge() const {
  42. const TerminatorInst *TI = Start->getTerminator();
  43. unsigned NumEdgesToEnd = 0;
  44. for (unsigned int i = 0, n = TI->getNumSuccessors(); i < n; ++i) {
  45. if (TI->getSuccessor(i) == End)
  46. ++NumEdgesToEnd;
  47. if (NumEdgesToEnd >= 2)
  48. return false;
  49. }
  50. assert(NumEdgesToEnd == 1);
  51. return true;
  52. }
  53. //===----------------------------------------------------------------------===//
  54. // DominatorTree Implementation
  55. //===----------------------------------------------------------------------===//
  56. //
  57. // Provide public access to DominatorTree information. Implementation details
  58. // can be found in Dominators.h, GenericDomTree.h, and
  59. // GenericDomTreeConstruction.h.
  60. //
  61. //===----------------------------------------------------------------------===//
  62. template class llvm::DomTreeNodeBase<BasicBlock>;
  63. template class llvm::DominatorTreeBase<BasicBlock>;
  64. template void llvm::Calculate<Function, BasicBlock *>(
  65. DominatorTreeBase<GraphTraits<BasicBlock *>::NodeType> &DT, Function &F);
  66. template void llvm::Calculate<Function, Inverse<BasicBlock *>>(
  67. DominatorTreeBase<GraphTraits<Inverse<BasicBlock *>>::NodeType> &DT,
  68. Function &F);
  69. // dominates - Return true if Def dominates a use in User. This performs
  70. // the special checks necessary if Def and User are in the same basic block.
  71. // Note that Def doesn't dominate a use in Def itself!
  72. bool DominatorTree::dominates(const Instruction *Def,
  73. const Instruction *User) const {
  74. const BasicBlock *UseBB = User->getParent();
  75. const BasicBlock *DefBB = Def->getParent();
  76. // Any unreachable use is dominated, even if Def == User.
  77. if (!isReachableFromEntry(UseBB))
  78. return true;
  79. // Unreachable definitions don't dominate anything.
  80. if (!isReachableFromEntry(DefBB))
  81. return false;
  82. // An instruction doesn't dominate a use in itself.
  83. if (Def == User)
  84. return false;
  85. // The value defined by an invoke dominates an instruction only if
  86. // it dominates every instruction in UseBB.
  87. // A PHI is dominated only if the instruction dominates every possible use
  88. // in the UseBB.
  89. if (isa<InvokeInst>(Def) || isa<PHINode>(User))
  90. return dominates(Def, UseBB);
  91. if (DefBB != UseBB)
  92. return dominates(DefBB, UseBB);
  93. // Loop through the basic block until we find Def or User.
  94. BasicBlock::const_iterator I = DefBB->begin();
  95. for (; &*I != Def && &*I != User; ++I)
  96. /*empty*/;
  97. return &*I == Def;
  98. }
  99. // true if Def would dominate a use in any instruction in UseBB.
  100. // note that dominates(Def, Def->getParent()) is false.
  101. bool DominatorTree::dominates(const Instruction *Def,
  102. const BasicBlock *UseBB) const {
  103. const BasicBlock *DefBB = Def->getParent();
  104. // Any unreachable use is dominated, even if DefBB == UseBB.
  105. if (!isReachableFromEntry(UseBB))
  106. return true;
  107. // Unreachable definitions don't dominate anything.
  108. if (!isReachableFromEntry(DefBB))
  109. return false;
  110. if (DefBB == UseBB)
  111. return false;
  112. const InvokeInst *II = dyn_cast<InvokeInst>(Def);
  113. if (!II)
  114. return dominates(DefBB, UseBB);
  115. // Invoke results are only usable in the normal destination, not in the
  116. // exceptional destination.
  117. BasicBlock *NormalDest = II->getNormalDest();
  118. BasicBlockEdge E(DefBB, NormalDest);
  119. return dominates(E, UseBB);
  120. }
  121. bool DominatorTree::dominates(const BasicBlockEdge &BBE,
  122. const BasicBlock *UseBB) const {
  123. // Assert that we have a single edge. We could handle them by simply
  124. // returning false, but since isSingleEdge is linear on the number of
  125. // edges, the callers can normally handle them more efficiently.
  126. assert(BBE.isSingleEdge());
  127. // If the BB the edge ends in doesn't dominate the use BB, then the
  128. // edge also doesn't.
  129. const BasicBlock *Start = BBE.getStart();
  130. const BasicBlock *End = BBE.getEnd();
  131. if (!dominates(End, UseBB))
  132. return false;
  133. // Simple case: if the end BB has a single predecessor, the fact that it
  134. // dominates the use block implies that the edge also does.
  135. if (End->getSinglePredecessor())
  136. return true;
  137. // The normal edge from the invoke is critical. Conceptually, what we would
  138. // like to do is split it and check if the new block dominates the use.
  139. // With X being the new block, the graph would look like:
  140. //
  141. // DefBB
  142. // /\ . .
  143. // / \ . .
  144. // / \ . .
  145. // / \ | |
  146. // A X B C
  147. // | \ | /
  148. // . \|/
  149. // . NormalDest
  150. // .
  151. //
  152. // Given the definition of dominance, NormalDest is dominated by X iff X
  153. // dominates all of NormalDest's predecessors (X, B, C in the example). X
  154. // trivially dominates itself, so we only have to find if it dominates the
  155. // other predecessors. Since the only way out of X is via NormalDest, X can
  156. // only properly dominate a node if NormalDest dominates that node too.
  157. for (const_pred_iterator PI = pred_begin(End), E = pred_end(End);
  158. PI != E; ++PI) {
  159. const BasicBlock *BB = *PI;
  160. if (BB == Start)
  161. continue;
  162. if (!dominates(End, BB))
  163. return false;
  164. }
  165. return true;
  166. }
  167. bool DominatorTree::dominates(const BasicBlockEdge &BBE, const Use &U) const {
  168. // Assert that we have a single edge. We could handle them by simply
  169. // returning false, but since isSingleEdge is linear on the number of
  170. // edges, the callers can normally handle them more efficiently.
  171. assert(BBE.isSingleEdge());
  172. Instruction *UserInst = cast<Instruction>(U.getUser());
  173. // A PHI in the end of the edge is dominated by it.
  174. PHINode *PN = dyn_cast<PHINode>(UserInst);
  175. if (PN && PN->getParent() == BBE.getEnd() &&
  176. PN->getIncomingBlock(U) == BBE.getStart())
  177. return true;
  178. // Otherwise use the edge-dominates-block query, which
  179. // handles the crazy critical edge cases properly.
  180. const BasicBlock *UseBB;
  181. if (PN)
  182. UseBB = PN->getIncomingBlock(U);
  183. else
  184. UseBB = UserInst->getParent();
  185. return dominates(BBE, UseBB);
  186. }
  187. bool DominatorTree::dominates(const Instruction *Def, const Use &U) const {
  188. Instruction *UserInst = cast<Instruction>(U.getUser());
  189. const BasicBlock *DefBB = Def->getParent();
  190. // Determine the block in which the use happens. PHI nodes use
  191. // their operands on edges; simulate this by thinking of the use
  192. // happening at the end of the predecessor block.
  193. const BasicBlock *UseBB;
  194. if (PHINode *PN = dyn_cast<PHINode>(UserInst))
  195. UseBB = PN->getIncomingBlock(U);
  196. else
  197. UseBB = UserInst->getParent();
  198. // Any unreachable use is dominated, even if Def == User.
  199. if (!isReachableFromEntry(UseBB))
  200. return true;
  201. // Unreachable definitions don't dominate anything.
  202. if (!isReachableFromEntry(DefBB))
  203. return false;
  204. // Invoke instructions define their return values on the edges
  205. // to their normal successors, so we have to handle them specially.
  206. // Among other things, this means they don't dominate anything in
  207. // their own block, except possibly a phi, so we don't need to
  208. // walk the block in any case.
  209. if (const InvokeInst *II = dyn_cast<InvokeInst>(Def)) {
  210. BasicBlock *NormalDest = II->getNormalDest();
  211. BasicBlockEdge E(DefBB, NormalDest);
  212. return dominates(E, U);
  213. }
  214. // If the def and use are in different blocks, do a simple CFG dominator
  215. // tree query.
  216. if (DefBB != UseBB)
  217. return dominates(DefBB, UseBB);
  218. // Ok, def and use are in the same block. If the def is an invoke, it
  219. // doesn't dominate anything in the block. If it's a PHI, it dominates
  220. // everything in the block.
  221. if (isa<PHINode>(UserInst))
  222. return true;
  223. // Otherwise, just loop through the basic block until we find Def or User.
  224. BasicBlock::const_iterator I = DefBB->begin();
  225. for (; &*I != Def && &*I != UserInst; ++I)
  226. /*empty*/;
  227. return &*I != UserInst;
  228. }
  229. bool DominatorTree::isReachableFromEntry(const Use &U) const {
  230. Instruction *I = dyn_cast<Instruction>(U.getUser());
  231. // ConstantExprs aren't really reachable from the entry block, but they
  232. // don't need to be treated like unreachable code either.
  233. if (!I) return true;
  234. // PHI nodes use their operands on their incoming edges.
  235. if (PHINode *PN = dyn_cast<PHINode>(I))
  236. return isReachableFromEntry(PN->getIncomingBlock(U));
  237. // Everything else uses their operands in their own block.
  238. return isReachableFromEntry(I->getParent());
  239. }
  240. void DominatorTree::verifyDomTree() const {
  241. Function &F = *getRoot()->getParent();
  242. DominatorTree OtherDT;
  243. OtherDT.recalculate(F);
  244. if (compare(OtherDT)) {
  245. errs() << "DominatorTree is not up to date!\nComputed:\n";
  246. print(errs());
  247. errs() << "\nActual:\n";
  248. OtherDT.print(errs());
  249. abort();
  250. }
  251. }
  252. //===----------------------------------------------------------------------===//
  253. // DominatorTreeAnalysis and related pass implementations
  254. //===----------------------------------------------------------------------===//
  255. //
  256. // This implements the DominatorTreeAnalysis which is used with the new pass
  257. // manager. It also implements some methods from utility passes.
  258. //
  259. //===----------------------------------------------------------------------===//
  260. DominatorTree DominatorTreeAnalysis::run(Function &F) {
  261. DominatorTree DT;
  262. DT.recalculate(F);
  263. return DT;
  264. }
  265. char DominatorTreeAnalysis::PassID;
  266. DominatorTreePrinterPass::DominatorTreePrinterPass(raw_ostream &OS) : OS(OS) {}
  267. PreservedAnalyses DominatorTreePrinterPass::run(Function &F,
  268. FunctionAnalysisManager *AM) {
  269. OS << "DominatorTree for function: " << F.getName() << "\n";
  270. AM->getResult<DominatorTreeAnalysis>(F).print(OS);
  271. return PreservedAnalyses::all();
  272. }
  273. PreservedAnalyses DominatorTreeVerifierPass::run(Function &F,
  274. FunctionAnalysisManager *AM) {
  275. AM->getResult<DominatorTreeAnalysis>(F).verifyDomTree();
  276. return PreservedAnalyses::all();
  277. }
  278. //===----------------------------------------------------------------------===//
  279. // DominatorTreeWrapperPass Implementation
  280. //===----------------------------------------------------------------------===//
  281. //
  282. // The implementation details of the wrapper pass that holds a DominatorTree
  283. // suitable for use with the legacy pass manager.
  284. //
  285. //===----------------------------------------------------------------------===//
  286. char DominatorTreeWrapperPass::ID = 0;
  287. INITIALIZE_PASS(DominatorTreeWrapperPass, "domtree",
  288. "Dominator Tree Construction", true, true)
  289. bool DominatorTreeWrapperPass::runOnFunction(Function &F) {
  290. DT.recalculate(F);
  291. return false;
  292. }
  293. void DominatorTreeWrapperPass::verifyAnalysis() const {
  294. if (VerifyDomInfo)
  295. DT.verifyDomTree();
  296. }
  297. void DominatorTreeWrapperPass::print(raw_ostream &OS, const Module *) const {
  298. DT.print(OS);
  299. }