Dominators.cpp 14 KB

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