17330f729Sjoerg //===-- CFG.cpp - BasicBlock analysis --------------------------------------==//
27330f729Sjoerg //
37330f729Sjoerg // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
47330f729Sjoerg // See https://llvm.org/LICENSE.txt for license information.
57330f729Sjoerg // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
67330f729Sjoerg //
77330f729Sjoerg //===----------------------------------------------------------------------===//
87330f729Sjoerg //
97330f729Sjoerg // This family of functions performs analyses on basic blocks, and instructions
107330f729Sjoerg // contained within basic blocks.
117330f729Sjoerg //
127330f729Sjoerg //===----------------------------------------------------------------------===//
137330f729Sjoerg
147330f729Sjoerg #include "llvm/Analysis/CFG.h"
157330f729Sjoerg #include "llvm/Analysis/LoopInfo.h"
167330f729Sjoerg #include "llvm/IR/Dominators.h"
17*82d56013Sjoerg #include "llvm/Support/CommandLine.h"
187330f729Sjoerg
197330f729Sjoerg using namespace llvm;
207330f729Sjoerg
21*82d56013Sjoerg // The max number of basic blocks explored during reachability analysis between
22*82d56013Sjoerg // two basic blocks. This is kept reasonably small to limit compile time when
23*82d56013Sjoerg // repeatedly used by clients of this analysis (such as captureTracking).
24*82d56013Sjoerg static cl::opt<unsigned> DefaultMaxBBsToExplore(
25*82d56013Sjoerg "dom-tree-reachability-max-bbs-to-explore", cl::Hidden,
26*82d56013Sjoerg cl::desc("Max number of BBs to explore for reachability analysis"),
27*82d56013Sjoerg cl::init(32));
28*82d56013Sjoerg
297330f729Sjoerg /// FindFunctionBackedges - Analyze the specified function to find all of the
307330f729Sjoerg /// loop backedges in the function and return them. This is a relatively cheap
317330f729Sjoerg /// (compared to computing dominators and loop info) analysis.
327330f729Sjoerg ///
337330f729Sjoerg /// The output is added to Result, as pairs of <from,to> edge info.
FindFunctionBackedges(const Function & F,SmallVectorImpl<std::pair<const BasicBlock *,const BasicBlock * >> & Result)347330f729Sjoerg void llvm::FindFunctionBackedges(const Function &F,
357330f729Sjoerg SmallVectorImpl<std::pair<const BasicBlock*,const BasicBlock*> > &Result) {
367330f729Sjoerg const BasicBlock *BB = &F.getEntryBlock();
377330f729Sjoerg if (succ_empty(BB))
387330f729Sjoerg return;
397330f729Sjoerg
407330f729Sjoerg SmallPtrSet<const BasicBlock*, 8> Visited;
41*82d56013Sjoerg SmallVector<std::pair<const BasicBlock *, const_succ_iterator>, 8> VisitStack;
427330f729Sjoerg SmallPtrSet<const BasicBlock*, 8> InStack;
437330f729Sjoerg
447330f729Sjoerg Visited.insert(BB);
457330f729Sjoerg VisitStack.push_back(std::make_pair(BB, succ_begin(BB)));
467330f729Sjoerg InStack.insert(BB);
477330f729Sjoerg do {
48*82d56013Sjoerg std::pair<const BasicBlock *, const_succ_iterator> &Top = VisitStack.back();
497330f729Sjoerg const BasicBlock *ParentBB = Top.first;
50*82d56013Sjoerg const_succ_iterator &I = Top.second;
517330f729Sjoerg
527330f729Sjoerg bool FoundNew = false;
537330f729Sjoerg while (I != succ_end(ParentBB)) {
547330f729Sjoerg BB = *I++;
557330f729Sjoerg if (Visited.insert(BB).second) {
567330f729Sjoerg FoundNew = true;
577330f729Sjoerg break;
587330f729Sjoerg }
597330f729Sjoerg // Successor is in VisitStack, it's a back edge.
607330f729Sjoerg if (InStack.count(BB))
617330f729Sjoerg Result.push_back(std::make_pair(ParentBB, BB));
627330f729Sjoerg }
637330f729Sjoerg
647330f729Sjoerg if (FoundNew) {
657330f729Sjoerg // Go down one level if there is a unvisited successor.
667330f729Sjoerg InStack.insert(BB);
677330f729Sjoerg VisitStack.push_back(std::make_pair(BB, succ_begin(BB)));
687330f729Sjoerg } else {
697330f729Sjoerg // Go up one level.
707330f729Sjoerg InStack.erase(VisitStack.pop_back_val().first);
717330f729Sjoerg }
727330f729Sjoerg } while (!VisitStack.empty());
737330f729Sjoerg }
747330f729Sjoerg
757330f729Sjoerg /// GetSuccessorNumber - Search for the specified successor of basic block BB
767330f729Sjoerg /// and return its position in the terminator instruction's list of
777330f729Sjoerg /// successors. It is an error to call this with a block that is not a
787330f729Sjoerg /// successor.
GetSuccessorNumber(const BasicBlock * BB,const BasicBlock * Succ)797330f729Sjoerg unsigned llvm::GetSuccessorNumber(const BasicBlock *BB,
807330f729Sjoerg const BasicBlock *Succ) {
817330f729Sjoerg const Instruction *Term = BB->getTerminator();
827330f729Sjoerg #ifndef NDEBUG
837330f729Sjoerg unsigned e = Term->getNumSuccessors();
847330f729Sjoerg #endif
857330f729Sjoerg for (unsigned i = 0; ; ++i) {
867330f729Sjoerg assert(i != e && "Didn't find edge?");
877330f729Sjoerg if (Term->getSuccessor(i) == Succ)
887330f729Sjoerg return i;
897330f729Sjoerg }
907330f729Sjoerg }
917330f729Sjoerg
927330f729Sjoerg /// isCriticalEdge - Return true if the specified edge is a critical edge.
937330f729Sjoerg /// Critical edges are edges from a block with multiple successors to a block
947330f729Sjoerg /// with multiple predecessors.
isCriticalEdge(const Instruction * TI,unsigned SuccNum,bool AllowIdenticalEdges)957330f729Sjoerg bool llvm::isCriticalEdge(const Instruction *TI, unsigned SuccNum,
967330f729Sjoerg bool AllowIdenticalEdges) {
977330f729Sjoerg assert(SuccNum < TI->getNumSuccessors() && "Illegal edge specification!");
987330f729Sjoerg return isCriticalEdge(TI, TI->getSuccessor(SuccNum), AllowIdenticalEdges);
997330f729Sjoerg }
1007330f729Sjoerg
isCriticalEdge(const Instruction * TI,const BasicBlock * Dest,bool AllowIdenticalEdges)1017330f729Sjoerg bool llvm::isCriticalEdge(const Instruction *TI, const BasicBlock *Dest,
1027330f729Sjoerg bool AllowIdenticalEdges) {
1037330f729Sjoerg assert(TI->isTerminator() && "Must be a terminator to have successors!");
1047330f729Sjoerg if (TI->getNumSuccessors() == 1) return false;
1057330f729Sjoerg
106*82d56013Sjoerg assert(is_contained(predecessors(Dest), TI->getParent()) &&
1077330f729Sjoerg "No edge between TI's block and Dest.");
1087330f729Sjoerg
1097330f729Sjoerg const_pred_iterator I = pred_begin(Dest), E = pred_end(Dest);
1107330f729Sjoerg
1117330f729Sjoerg // If there is more than one predecessor, this is a critical edge...
1127330f729Sjoerg assert(I != E && "No preds, but we have an edge to the block?");
1137330f729Sjoerg const BasicBlock *FirstPred = *I;
1147330f729Sjoerg ++I; // Skip one edge due to the incoming arc from TI.
1157330f729Sjoerg if (!AllowIdenticalEdges)
1167330f729Sjoerg return I != E;
1177330f729Sjoerg
1187330f729Sjoerg // If AllowIdenticalEdges is true, then we allow this edge to be considered
1197330f729Sjoerg // non-critical iff all preds come from TI's block.
1207330f729Sjoerg for (; I != E; ++I)
1217330f729Sjoerg if (*I != FirstPred)
1227330f729Sjoerg return true;
1237330f729Sjoerg return false;
1247330f729Sjoerg }
1257330f729Sjoerg
1267330f729Sjoerg // LoopInfo contains a mapping from basic block to the innermost loop. Find
1277330f729Sjoerg // the outermost loop in the loop nest that contains BB.
getOutermostLoop(const LoopInfo * LI,const BasicBlock * BB)1287330f729Sjoerg static const Loop *getOutermostLoop(const LoopInfo *LI, const BasicBlock *BB) {
1297330f729Sjoerg const Loop *L = LI->getLoopFor(BB);
1307330f729Sjoerg if (L) {
1317330f729Sjoerg while (const Loop *Parent = L->getParentLoop())
1327330f729Sjoerg L = Parent;
1337330f729Sjoerg }
1347330f729Sjoerg return L;
1357330f729Sjoerg }
1367330f729Sjoerg
isPotentiallyReachableFromMany(SmallVectorImpl<BasicBlock * > & Worklist,BasicBlock * StopBB,const SmallPtrSetImpl<BasicBlock * > * ExclusionSet,const DominatorTree * DT,const LoopInfo * LI)1377330f729Sjoerg bool llvm::isPotentiallyReachableFromMany(
1387330f729Sjoerg SmallVectorImpl<BasicBlock *> &Worklist, BasicBlock *StopBB,
1397330f729Sjoerg const SmallPtrSetImpl<BasicBlock *> *ExclusionSet, const DominatorTree *DT,
1407330f729Sjoerg const LoopInfo *LI) {
1417330f729Sjoerg // When the stop block is unreachable, it's dominated from everywhere,
1427330f729Sjoerg // regardless of whether there's a path between the two blocks.
1437330f729Sjoerg if (DT && !DT->isReachableFromEntry(StopBB))
1447330f729Sjoerg DT = nullptr;
1457330f729Sjoerg
1467330f729Sjoerg // We can't skip directly from a block that dominates the stop block if the
1477330f729Sjoerg // exclusion block is potentially in between.
1487330f729Sjoerg if (ExclusionSet && !ExclusionSet->empty())
1497330f729Sjoerg DT = nullptr;
1507330f729Sjoerg
1517330f729Sjoerg // Normally any block in a loop is reachable from any other block in a loop,
1527330f729Sjoerg // however excluded blocks might partition the body of a loop to make that
1537330f729Sjoerg // untrue.
1547330f729Sjoerg SmallPtrSet<const Loop *, 8> LoopsWithHoles;
1557330f729Sjoerg if (LI && ExclusionSet) {
1567330f729Sjoerg for (auto BB : *ExclusionSet) {
1577330f729Sjoerg if (const Loop *L = getOutermostLoop(LI, BB))
1587330f729Sjoerg LoopsWithHoles.insert(L);
1597330f729Sjoerg }
1607330f729Sjoerg }
1617330f729Sjoerg
1627330f729Sjoerg const Loop *StopLoop = LI ? getOutermostLoop(LI, StopBB) : nullptr;
1637330f729Sjoerg
164*82d56013Sjoerg unsigned Limit = DefaultMaxBBsToExplore;
1657330f729Sjoerg SmallPtrSet<const BasicBlock*, 32> Visited;
1667330f729Sjoerg do {
1677330f729Sjoerg BasicBlock *BB = Worklist.pop_back_val();
1687330f729Sjoerg if (!Visited.insert(BB).second)
1697330f729Sjoerg continue;
1707330f729Sjoerg if (BB == StopBB)
1717330f729Sjoerg return true;
1727330f729Sjoerg if (ExclusionSet && ExclusionSet->count(BB))
1737330f729Sjoerg continue;
1747330f729Sjoerg if (DT && DT->dominates(BB, StopBB))
1757330f729Sjoerg return true;
1767330f729Sjoerg
1777330f729Sjoerg const Loop *Outer = nullptr;
1787330f729Sjoerg if (LI) {
1797330f729Sjoerg Outer = getOutermostLoop(LI, BB);
1807330f729Sjoerg // If we're in a loop with a hole, not all blocks in the loop are
1817330f729Sjoerg // reachable from all other blocks. That implies we can't simply jump to
1827330f729Sjoerg // the loop's exit blocks, as that exit might need to pass through an
1837330f729Sjoerg // excluded block. Clear Outer so we process BB's successors.
1847330f729Sjoerg if (LoopsWithHoles.count(Outer))
1857330f729Sjoerg Outer = nullptr;
1867330f729Sjoerg if (StopLoop && Outer == StopLoop)
1877330f729Sjoerg return true;
1887330f729Sjoerg }
1897330f729Sjoerg
1907330f729Sjoerg if (!--Limit) {
1917330f729Sjoerg // We haven't been able to prove it one way or the other. Conservatively
1927330f729Sjoerg // answer true -- that there is potentially a path.
1937330f729Sjoerg return true;
1947330f729Sjoerg }
1957330f729Sjoerg
1967330f729Sjoerg if (Outer) {
1977330f729Sjoerg // All blocks in a single loop are reachable from all other blocks. From
1987330f729Sjoerg // any of these blocks, we can skip directly to the exits of the loop,
1997330f729Sjoerg // ignoring any other blocks inside the loop body.
2007330f729Sjoerg Outer->getExitBlocks(Worklist);
2017330f729Sjoerg } else {
2027330f729Sjoerg Worklist.append(succ_begin(BB), succ_end(BB));
2037330f729Sjoerg }
2047330f729Sjoerg } while (!Worklist.empty());
2057330f729Sjoerg
2067330f729Sjoerg // We have exhausted all possible paths and are certain that 'To' can not be
2077330f729Sjoerg // reached from 'From'.
2087330f729Sjoerg return false;
2097330f729Sjoerg }
2107330f729Sjoerg
isPotentiallyReachable(const BasicBlock * A,const BasicBlock * B,const SmallPtrSetImpl<BasicBlock * > * ExclusionSet,const DominatorTree * DT,const LoopInfo * LI)211*82d56013Sjoerg bool llvm::isPotentiallyReachable(
212*82d56013Sjoerg const BasicBlock *A, const BasicBlock *B,
213*82d56013Sjoerg const SmallPtrSetImpl<BasicBlock *> *ExclusionSet, const DominatorTree *DT,
214*82d56013Sjoerg const LoopInfo *LI) {
2157330f729Sjoerg assert(A->getParent() == B->getParent() &&
2167330f729Sjoerg "This analysis is function-local!");
2177330f729Sjoerg
218*82d56013Sjoerg if (DT) {
219*82d56013Sjoerg if (DT->isReachableFromEntry(A) && !DT->isReachableFromEntry(B))
220*82d56013Sjoerg return false;
221*82d56013Sjoerg if (!ExclusionSet || ExclusionSet->empty()) {
222*82d56013Sjoerg if (A->isEntryBlock() && DT->isReachableFromEntry(B))
223*82d56013Sjoerg return true;
224*82d56013Sjoerg if (B->isEntryBlock() && DT->isReachableFromEntry(A))
225*82d56013Sjoerg return false;
226*82d56013Sjoerg }
227*82d56013Sjoerg }
228*82d56013Sjoerg
2297330f729Sjoerg SmallVector<BasicBlock*, 32> Worklist;
2307330f729Sjoerg Worklist.push_back(const_cast<BasicBlock*>(A));
2317330f729Sjoerg
2327330f729Sjoerg return isPotentiallyReachableFromMany(Worklist, const_cast<BasicBlock *>(B),
233*82d56013Sjoerg ExclusionSet, DT, LI);
2347330f729Sjoerg }
2357330f729Sjoerg
isPotentiallyReachable(const Instruction * A,const Instruction * B,const SmallPtrSetImpl<BasicBlock * > * ExclusionSet,const DominatorTree * DT,const LoopInfo * LI)2367330f729Sjoerg bool llvm::isPotentiallyReachable(
2377330f729Sjoerg const Instruction *A, const Instruction *B,
2387330f729Sjoerg const SmallPtrSetImpl<BasicBlock *> *ExclusionSet, const DominatorTree *DT,
2397330f729Sjoerg const LoopInfo *LI) {
2407330f729Sjoerg assert(A->getParent()->getParent() == B->getParent()->getParent() &&
2417330f729Sjoerg "This analysis is function-local!");
2427330f729Sjoerg
2437330f729Sjoerg if (A->getParent() == B->getParent()) {
2447330f729Sjoerg // The same block case is special because it's the only time we're looking
2457330f729Sjoerg // within a single block to see which instruction comes first. Once we
2467330f729Sjoerg // start looking at multiple blocks, the first instruction of the block is
2477330f729Sjoerg // reachable, so we only need to determine reachability between whole
2487330f729Sjoerg // blocks.
2497330f729Sjoerg BasicBlock *BB = const_cast<BasicBlock *>(A->getParent());
2507330f729Sjoerg
2517330f729Sjoerg // If the block is in a loop then we can reach any instruction in the block
2527330f729Sjoerg // from any other instruction in the block by going around a backedge.
2537330f729Sjoerg if (LI && LI->getLoopFor(BB) != nullptr)
2547330f729Sjoerg return true;
2557330f729Sjoerg
256*82d56013Sjoerg // If A comes before B, then B is definitively reachable from A.
257*82d56013Sjoerg if (A == B || A->comesBefore(B))
2587330f729Sjoerg return true;
2597330f729Sjoerg
2607330f729Sjoerg // Can't be in a loop if it's the entry block -- the entry block may not
2617330f729Sjoerg // have predecessors.
262*82d56013Sjoerg if (BB->isEntryBlock())
2637330f729Sjoerg return false;
2647330f729Sjoerg
2657330f729Sjoerg // Otherwise, continue doing the normal per-BB CFG walk.
266*82d56013Sjoerg SmallVector<BasicBlock*, 32> Worklist;
2677330f729Sjoerg Worklist.append(succ_begin(BB), succ_end(BB));
2687330f729Sjoerg if (Worklist.empty()) {
2697330f729Sjoerg // We've proven that there's no path!
2707330f729Sjoerg return false;
2717330f729Sjoerg }
2727330f729Sjoerg
2737330f729Sjoerg return isPotentiallyReachableFromMany(
274*82d56013Sjoerg Worklist, const_cast<BasicBlock *>(B->getParent()), ExclusionSet,
275*82d56013Sjoerg DT, LI);
276*82d56013Sjoerg }
277*82d56013Sjoerg
278*82d56013Sjoerg return isPotentiallyReachable(
279*82d56013Sjoerg A->getParent(), B->getParent(), ExclusionSet, DT, LI);
2807330f729Sjoerg }
281