CFG.cpp 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. //===-- CFG.cpp - BasicBlock analysis --------------------------------------==//
  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 family of functions performs analyses on basic blocks, and instructions
  10. // contained within basic blocks.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/Analysis/CFG.h"
  14. #include "llvm/Analysis/LoopInfo.h"
  15. #include "llvm/IR/Dominators.h"
  16. #include "llvm/Support/CommandLine.h"
  17. using namespace llvm;
  18. // The max number of basic blocks explored during reachability analysis between
  19. // two basic blocks. This is kept reasonably small to limit compile time when
  20. // repeatedly used by clients of this analysis (such as captureTracking).
  21. static cl::opt<unsigned> DefaultMaxBBsToExplore(
  22. "dom-tree-reachability-max-bbs-to-explore", cl::Hidden,
  23. cl::desc("Max number of BBs to explore for reachability analysis"),
  24. cl::init(32));
  25. /// FindFunctionBackedges - Analyze the specified function to find all of the
  26. /// loop backedges in the function and return them. This is a relatively cheap
  27. /// (compared to computing dominators and loop info) analysis.
  28. ///
  29. /// The output is added to Result, as pairs of <from,to> edge info.
  30. void llvm::FindFunctionBackedges(const Function &F,
  31. SmallVectorImpl<std::pair<const BasicBlock*,const BasicBlock*> > &Result) {
  32. const BasicBlock *BB = &F.getEntryBlock();
  33. if (succ_empty(BB))
  34. return;
  35. SmallPtrSet<const BasicBlock*, 8> Visited;
  36. SmallVector<std::pair<const BasicBlock *, const_succ_iterator>, 8> VisitStack;
  37. SmallPtrSet<const BasicBlock*, 8> InStack;
  38. Visited.insert(BB);
  39. VisitStack.push_back(std::make_pair(BB, succ_begin(BB)));
  40. InStack.insert(BB);
  41. do {
  42. std::pair<const BasicBlock *, const_succ_iterator> &Top = VisitStack.back();
  43. const BasicBlock *ParentBB = Top.first;
  44. const_succ_iterator &I = Top.second;
  45. bool FoundNew = false;
  46. while (I != succ_end(ParentBB)) {
  47. BB = *I++;
  48. if (Visited.insert(BB).second) {
  49. FoundNew = true;
  50. break;
  51. }
  52. // Successor is in VisitStack, it's a back edge.
  53. if (InStack.count(BB))
  54. Result.push_back(std::make_pair(ParentBB, BB));
  55. }
  56. if (FoundNew) {
  57. // Go down one level if there is a unvisited successor.
  58. InStack.insert(BB);
  59. VisitStack.push_back(std::make_pair(BB, succ_begin(BB)));
  60. } else {
  61. // Go up one level.
  62. InStack.erase(VisitStack.pop_back_val().first);
  63. }
  64. } while (!VisitStack.empty());
  65. }
  66. /// GetSuccessorNumber - Search for the specified successor of basic block BB
  67. /// and return its position in the terminator instruction's list of
  68. /// successors. It is an error to call this with a block that is not a
  69. /// successor.
  70. unsigned llvm::GetSuccessorNumber(const BasicBlock *BB,
  71. const BasicBlock *Succ) {
  72. const Instruction *Term = BB->getTerminator();
  73. #ifndef NDEBUG
  74. unsigned e = Term->getNumSuccessors();
  75. #endif
  76. for (unsigned i = 0; ; ++i) {
  77. assert(i != e && "Didn't find edge?");
  78. if (Term->getSuccessor(i) == Succ)
  79. return i;
  80. }
  81. }
  82. /// isCriticalEdge - Return true if the specified edge is a critical edge.
  83. /// Critical edges are edges from a block with multiple successors to a block
  84. /// with multiple predecessors.
  85. bool llvm::isCriticalEdge(const Instruction *TI, unsigned SuccNum,
  86. bool AllowIdenticalEdges) {
  87. assert(SuccNum < TI->getNumSuccessors() && "Illegal edge specification!");
  88. return isCriticalEdge(TI, TI->getSuccessor(SuccNum), AllowIdenticalEdges);
  89. }
  90. bool llvm::isCriticalEdge(const Instruction *TI, const BasicBlock *Dest,
  91. bool AllowIdenticalEdges) {
  92. assert(TI->isTerminator() && "Must be a terminator to have successors!");
  93. if (TI->getNumSuccessors() == 1) return false;
  94. assert(is_contained(predecessors(Dest), TI->getParent()) &&
  95. "No edge between TI's block and Dest.");
  96. const_pred_iterator I = pred_begin(Dest), E = pred_end(Dest);
  97. // If there is more than one predecessor, this is a critical edge...
  98. assert(I != E && "No preds, but we have an edge to the block?");
  99. const BasicBlock *FirstPred = *I;
  100. ++I; // Skip one edge due to the incoming arc from TI.
  101. if (!AllowIdenticalEdges)
  102. return I != E;
  103. // If AllowIdenticalEdges is true, then we allow this edge to be considered
  104. // non-critical iff all preds come from TI's block.
  105. for (; I != E; ++I)
  106. if (*I != FirstPred)
  107. return true;
  108. return false;
  109. }
  110. // LoopInfo contains a mapping from basic block to the innermost loop. Find
  111. // the outermost loop in the loop nest that contains BB.
  112. static const Loop *getOutermostLoop(const LoopInfo *LI, const BasicBlock *BB) {
  113. const Loop *L = LI->getLoopFor(BB);
  114. return L ? L->getOutermostLoop() : nullptr;
  115. }
  116. bool llvm::isPotentiallyReachableFromMany(
  117. SmallVectorImpl<BasicBlock *> &Worklist, const BasicBlock *StopBB,
  118. const SmallPtrSetImpl<BasicBlock *> *ExclusionSet, const DominatorTree *DT,
  119. const LoopInfo *LI) {
  120. // When the stop block is unreachable, it's dominated from everywhere,
  121. // regardless of whether there's a path between the two blocks.
  122. if (DT && !DT->isReachableFromEntry(StopBB))
  123. DT = nullptr;
  124. // We can't skip directly from a block that dominates the stop block if the
  125. // exclusion block is potentially in between.
  126. if (ExclusionSet && !ExclusionSet->empty())
  127. DT = nullptr;
  128. // Normally any block in a loop is reachable from any other block in a loop,
  129. // however excluded blocks might partition the body of a loop to make that
  130. // untrue.
  131. SmallPtrSet<const Loop *, 8> LoopsWithHoles;
  132. if (LI && ExclusionSet) {
  133. for (auto *BB : *ExclusionSet) {
  134. if (const Loop *L = getOutermostLoop(LI, BB))
  135. LoopsWithHoles.insert(L);
  136. }
  137. }
  138. const Loop *StopLoop = LI ? getOutermostLoop(LI, StopBB) : nullptr;
  139. unsigned Limit = DefaultMaxBBsToExplore;
  140. SmallPtrSet<const BasicBlock*, 32> Visited;
  141. do {
  142. BasicBlock *BB = Worklist.pop_back_val();
  143. if (!Visited.insert(BB).second)
  144. continue;
  145. if (BB == StopBB)
  146. return true;
  147. if (ExclusionSet && ExclusionSet->count(BB))
  148. continue;
  149. if (DT && DT->dominates(BB, StopBB))
  150. return true;
  151. const Loop *Outer = nullptr;
  152. if (LI) {
  153. Outer = getOutermostLoop(LI, BB);
  154. // If we're in a loop with a hole, not all blocks in the loop are
  155. // reachable from all other blocks. That implies we can't simply jump to
  156. // the loop's exit blocks, as that exit might need to pass through an
  157. // excluded block. Clear Outer so we process BB's successors.
  158. if (LoopsWithHoles.count(Outer))
  159. Outer = nullptr;
  160. if (StopLoop && Outer == StopLoop)
  161. return true;
  162. }
  163. if (!--Limit) {
  164. // We haven't been able to prove it one way or the other. Conservatively
  165. // answer true -- that there is potentially a path.
  166. return true;
  167. }
  168. if (Outer) {
  169. // All blocks in a single loop are reachable from all other blocks. From
  170. // any of these blocks, we can skip directly to the exits of the loop,
  171. // ignoring any other blocks inside the loop body.
  172. Outer->getExitBlocks(Worklist);
  173. } else {
  174. Worklist.append(succ_begin(BB), succ_end(BB));
  175. }
  176. } while (!Worklist.empty());
  177. // We have exhausted all possible paths and are certain that 'To' can not be
  178. // reached from 'From'.
  179. return false;
  180. }
  181. bool llvm::isPotentiallyReachable(
  182. const BasicBlock *A, const BasicBlock *B,
  183. const SmallPtrSetImpl<BasicBlock *> *ExclusionSet, const DominatorTree *DT,
  184. const LoopInfo *LI) {
  185. assert(A->getParent() == B->getParent() &&
  186. "This analysis is function-local!");
  187. if (DT) {
  188. if (DT->isReachableFromEntry(A) && !DT->isReachableFromEntry(B))
  189. return false;
  190. if (!ExclusionSet || ExclusionSet->empty()) {
  191. if (A->isEntryBlock() && DT->isReachableFromEntry(B))
  192. return true;
  193. if (B->isEntryBlock() && DT->isReachableFromEntry(A))
  194. return false;
  195. }
  196. }
  197. SmallVector<BasicBlock*, 32> Worklist;
  198. Worklist.push_back(const_cast<BasicBlock*>(A));
  199. return isPotentiallyReachableFromMany(Worklist, B, ExclusionSet, DT, LI);
  200. }
  201. bool llvm::isPotentiallyReachable(
  202. const Instruction *A, const Instruction *B,
  203. const SmallPtrSetImpl<BasicBlock *> *ExclusionSet, const DominatorTree *DT,
  204. const LoopInfo *LI) {
  205. assert(A->getParent()->getParent() == B->getParent()->getParent() &&
  206. "This analysis is function-local!");
  207. if (A->getParent() == B->getParent()) {
  208. // The same block case is special because it's the only time we're looking
  209. // within a single block to see which instruction comes first. Once we
  210. // start looking at multiple blocks, the first instruction of the block is
  211. // reachable, so we only need to determine reachability between whole
  212. // blocks.
  213. BasicBlock *BB = const_cast<BasicBlock *>(A->getParent());
  214. // If the block is in a loop then we can reach any instruction in the block
  215. // from any other instruction in the block by going around a backedge.
  216. if (LI && LI->getLoopFor(BB) != nullptr)
  217. return true;
  218. // If A comes before B, then B is definitively reachable from A.
  219. if (A == B || A->comesBefore(B))
  220. return true;
  221. // Can't be in a loop if it's the entry block -- the entry block may not
  222. // have predecessors.
  223. if (BB->isEntryBlock())
  224. return false;
  225. // Otherwise, continue doing the normal per-BB CFG walk.
  226. SmallVector<BasicBlock*, 32> Worklist;
  227. Worklist.append(succ_begin(BB), succ_end(BB));
  228. if (Worklist.empty()) {
  229. // We've proven that there's no path!
  230. return false;
  231. }
  232. return isPotentiallyReachableFromMany(Worklist, B->getParent(),
  233. ExclusionSet, DT, LI);
  234. }
  235. return isPotentiallyReachable(
  236. A->getParent(), B->getParent(), ExclusionSet, DT, LI);
  237. }