10b68245eSNick Lewycky //===-- CFG.cpp - BasicBlock analysis --------------------------------------==//
20b68245eSNick Lewycky //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b68245eSNick Lewycky //
70b68245eSNick Lewycky //===----------------------------------------------------------------------===//
80b68245eSNick Lewycky //
90b68245eSNick Lewycky // This family of functions performs analyses on basic blocks, and instructions
100b68245eSNick Lewycky // contained within basic blocks.
110b68245eSNick Lewycky //
120b68245eSNick Lewycky //===----------------------------------------------------------------------===//
130b68245eSNick Lewycky
140b68245eSNick Lewycky #include "llvm/Analysis/CFG.h"
150b68245eSNick Lewycky #include "llvm/Analysis/LoopInfo.h"
165ad5f15cSChandler Carruth #include "llvm/IR/Dominators.h"
177aac3a90SAnna Thomas #include "llvm/Support/CommandLine.h"
180b68245eSNick Lewycky
190b68245eSNick Lewycky using namespace llvm;
200b68245eSNick Lewycky
217aac3a90SAnna Thomas // The max number of basic blocks explored during reachability analysis between
227aac3a90SAnna Thomas // two basic blocks. This is kept reasonably small to limit compile time when
237aac3a90SAnna Thomas // repeatedly used by clients of this analysis (such as captureTracking).
247aac3a90SAnna Thomas static cl::opt<unsigned> DefaultMaxBBsToExplore(
257aac3a90SAnna Thomas "dom-tree-reachability-max-bbs-to-explore", cl::Hidden,
267aac3a90SAnna Thomas cl::desc("Max number of BBs to explore for reachability analysis"),
277aac3a90SAnna Thomas cl::init(32));
287aac3a90SAnna Thomas
290b68245eSNick Lewycky /// FindFunctionBackedges - Analyze the specified function to find all of the
300b68245eSNick Lewycky /// loop backedges in the function and return them. This is a relatively cheap
310b68245eSNick Lewycky /// (compared to computing dominators and loop info) analysis.
320b68245eSNick Lewycky ///
330b68245eSNick Lewycky /// 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)340b68245eSNick Lewycky void llvm::FindFunctionBackedges(const Function &F,
350b68245eSNick Lewycky SmallVectorImpl<std::pair<const BasicBlock*,const BasicBlock*> > &Result) {
360b68245eSNick Lewycky const BasicBlock *BB = &F.getEntryBlock();
3740c3e03eSRamkumar Ramachandra if (succ_empty(BB))
380b68245eSNick Lewycky return;
390b68245eSNick Lewycky
400b68245eSNick Lewycky SmallPtrSet<const BasicBlock*, 8> Visited;
413abcbf99SAlina Sbirlea SmallVector<std::pair<const BasicBlock *, const_succ_iterator>, 8> VisitStack;
420b68245eSNick Lewycky SmallPtrSet<const BasicBlock*, 8> InStack;
430b68245eSNick Lewycky
440b68245eSNick Lewycky Visited.insert(BB);
450b68245eSNick Lewycky VisitStack.push_back(std::make_pair(BB, succ_begin(BB)));
460b68245eSNick Lewycky InStack.insert(BB);
470b68245eSNick Lewycky do {
483abcbf99SAlina Sbirlea std::pair<const BasicBlock *, const_succ_iterator> &Top = VisitStack.back();
490b68245eSNick Lewycky const BasicBlock *ParentBB = Top.first;
503abcbf99SAlina Sbirlea const_succ_iterator &I = Top.second;
510b68245eSNick Lewycky
520b68245eSNick Lewycky bool FoundNew = false;
530b68245eSNick Lewycky while (I != succ_end(ParentBB)) {
540b68245eSNick Lewycky BB = *I++;
5570573dcdSDavid Blaikie if (Visited.insert(BB).second) {
560b68245eSNick Lewycky FoundNew = true;
570b68245eSNick Lewycky break;
580b68245eSNick Lewycky }
590b68245eSNick Lewycky // Successor is in VisitStack, it's a back edge.
600b68245eSNick Lewycky if (InStack.count(BB))
610b68245eSNick Lewycky Result.push_back(std::make_pair(ParentBB, BB));
620b68245eSNick Lewycky }
630b68245eSNick Lewycky
640b68245eSNick Lewycky if (FoundNew) {
650b68245eSNick Lewycky // Go down one level if there is a unvisited successor.
660b68245eSNick Lewycky InStack.insert(BB);
670b68245eSNick Lewycky VisitStack.push_back(std::make_pair(BB, succ_begin(BB)));
680b68245eSNick Lewycky } else {
690b68245eSNick Lewycky // Go up one level.
700b68245eSNick Lewycky InStack.erase(VisitStack.pop_back_val().first);
710b68245eSNick Lewycky }
720b68245eSNick Lewycky } while (!VisitStack.empty());
730b68245eSNick Lewycky }
740b68245eSNick Lewycky
750b68245eSNick Lewycky /// GetSuccessorNumber - Search for the specified successor of basic block BB
760b68245eSNick Lewycky /// and return its position in the terminator instruction's list of
770b68245eSNick Lewycky /// successors. It is an error to call this with a block that is not a
780b68245eSNick Lewycky /// successor.
GetSuccessorNumber(const BasicBlock * BB,const BasicBlock * Succ)79a1f61fe8SRong Xu unsigned llvm::GetSuccessorNumber(const BasicBlock *BB,
80a1f61fe8SRong Xu const BasicBlock *Succ) {
81edb12a83SChandler Carruth const Instruction *Term = BB->getTerminator();
820b68245eSNick Lewycky #ifndef NDEBUG
830b68245eSNick Lewycky unsigned e = Term->getNumSuccessors();
840b68245eSNick Lewycky #endif
850b68245eSNick Lewycky for (unsigned i = 0; ; ++i) {
860b68245eSNick Lewycky assert(i != e && "Didn't find edge?");
870b68245eSNick Lewycky if (Term->getSuccessor(i) == Succ)
880b68245eSNick Lewycky return i;
890b68245eSNick Lewycky }
900b68245eSNick Lewycky }
910b68245eSNick Lewycky
920b68245eSNick Lewycky /// isCriticalEdge - Return true if the specified edge is a critical edge.
930b68245eSNick Lewycky /// Critical edges are edges from a block with multiple successors to a block
940b68245eSNick Lewycky /// with multiple predecessors.
isCriticalEdge(const Instruction * TI,unsigned SuccNum,bool AllowIdenticalEdges)95b99a2468SChandler Carruth bool llvm::isCriticalEdge(const Instruction *TI, unsigned SuccNum,
960b68245eSNick Lewycky bool AllowIdenticalEdges) {
97d0b6f429SFlorian Hahn assert(SuccNum < TI->getNumSuccessors() && "Illegal edge specification!");
98189efe29SFlorian Hahn return isCriticalEdge(TI, TI->getSuccessor(SuccNum), AllowIdenticalEdges);
99189efe29SFlorian Hahn }
100189efe29SFlorian Hahn
isCriticalEdge(const Instruction * TI,const BasicBlock * Dest,bool AllowIdenticalEdges)101189efe29SFlorian Hahn bool llvm::isCriticalEdge(const Instruction *TI, const BasicBlock *Dest,
102189efe29SFlorian Hahn bool AllowIdenticalEdges) {
103189efe29SFlorian Hahn assert(TI->isTerminator() && "Must be a terminator to have successors!");
1040b68245eSNick Lewycky if (TI->getNumSuccessors() == 1) return false;
1050b68245eSNick Lewycky
106eb44682dSKazu Hirata assert(is_contained(predecessors(Dest), TI->getParent()) &&
107189efe29SFlorian Hahn "No edge between TI's block and Dest.");
108189efe29SFlorian Hahn
1090b68245eSNick Lewycky const_pred_iterator I = pred_begin(Dest), E = pred_end(Dest);
1100b68245eSNick Lewycky
1110b68245eSNick Lewycky // If there is more than one predecessor, this is a critical edge...
1120b68245eSNick Lewycky assert(I != E && "No preds, but we have an edge to the block?");
1130b68245eSNick Lewycky const BasicBlock *FirstPred = *I;
1140b68245eSNick Lewycky ++I; // Skip one edge due to the incoming arc from TI.
1150b68245eSNick Lewycky if (!AllowIdenticalEdges)
1160b68245eSNick Lewycky return I != E;
1170b68245eSNick Lewycky
1180b68245eSNick Lewycky // If AllowIdenticalEdges is true, then we allow this edge to be considered
1190b68245eSNick Lewycky // non-critical iff all preds come from TI's block.
120e706b883SErik Verbruggen for (; I != E; ++I)
121e706b883SErik Verbruggen if (*I != FirstPred)
1220b68245eSNick Lewycky return true;
1230b68245eSNick Lewycky return false;
1240b68245eSNick Lewycky }
1250b68245eSNick Lewycky
1260b68245eSNick Lewycky // LoopInfo contains a mapping from basic block to the innermost loop. Find
1270b68245eSNick Lewycky // the outermost loop in the loop nest that contains BB.
getOutermostLoop(const LoopInfo * LI,const BasicBlock * BB)128d184e2deSJakub Staszak static const Loop *getOutermostLoop(const LoopInfo *LI, const BasicBlock *BB) {
1290b68245eSNick Lewycky const Loop *L = LI->getLoopFor(BB);
130d77f9448SNikita Popov return L ? L->getOutermostLoop() : nullptr;
1310b68245eSNick Lewycky }
1320b68245eSNick Lewycky
isPotentiallyReachableFromMany(SmallVectorImpl<BasicBlock * > & Worklist,BasicBlock * StopBB,const SmallPtrSetImpl<BasicBlock * > * ExclusionSet,const DominatorTree * DT,const LoopInfo * LI)1337900ef89SBruno Cardoso Lopes bool llvm::isPotentiallyReachableFromMany(
1347900ef89SBruno Cardoso Lopes SmallVectorImpl<BasicBlock *> &Worklist, BasicBlock *StopBB,
135c0ebfbe3SNick Lewycky const SmallPtrSetImpl<BasicBlock *> *ExclusionSet, const DominatorTree *DT,
136c0ebfbe3SNick Lewycky const LoopInfo *LI) {
1370b68245eSNick Lewycky // When the stop block is unreachable, it's dominated from everywhere,
1380b68245eSNick Lewycky // regardless of whether there's a path between the two blocks.
1390b68245eSNick Lewycky if (DT && !DT->isReachableFromEntry(StopBB))
1409f008867SCraig Topper DT = nullptr;
1410b68245eSNick Lewycky
142c0ebfbe3SNick Lewycky // We can't skip directly from a block that dominates the stop block if the
143c0ebfbe3SNick Lewycky // exclusion block is potentially in between.
144c0ebfbe3SNick Lewycky if (ExclusionSet && !ExclusionSet->empty())
145c0ebfbe3SNick Lewycky DT = nullptr;
146c0ebfbe3SNick Lewycky
147c0ebfbe3SNick Lewycky // Normally any block in a loop is reachable from any other block in a loop,
148c0ebfbe3SNick Lewycky // however excluded blocks might partition the body of a loop to make that
149c0ebfbe3SNick Lewycky // untrue.
150c0ebfbe3SNick Lewycky SmallPtrSet<const Loop *, 8> LoopsWithHoles;
151c0ebfbe3SNick Lewycky if (LI && ExclusionSet) {
152*601b3a13SKazu Hirata for (auto *BB : *ExclusionSet) {
153c0ebfbe3SNick Lewycky if (const Loop *L = getOutermostLoop(LI, BB))
154c0ebfbe3SNick Lewycky LoopsWithHoles.insert(L);
155c0ebfbe3SNick Lewycky }
156c0ebfbe3SNick Lewycky }
157c0ebfbe3SNick Lewycky
158c0ebfbe3SNick Lewycky const Loop *StopLoop = LI ? getOutermostLoop(LI, StopBB) : nullptr;
159c0ebfbe3SNick Lewycky
1607aac3a90SAnna Thomas unsigned Limit = DefaultMaxBBsToExplore;
161b30f2f51SMatthias Braun SmallPtrSet<const BasicBlock*, 32> Visited;
1620b68245eSNick Lewycky do {
1630b68245eSNick Lewycky BasicBlock *BB = Worklist.pop_back_val();
16470573dcdSDavid Blaikie if (!Visited.insert(BB).second)
1650b68245eSNick Lewycky continue;
1660b68245eSNick Lewycky if (BB == StopBB)
1670b68245eSNick Lewycky return true;
168c0ebfbe3SNick Lewycky if (ExclusionSet && ExclusionSet->count(BB))
169c0ebfbe3SNick Lewycky continue;
1700b68245eSNick Lewycky if (DT && DT->dominates(BB, StopBB))
1710b68245eSNick Lewycky return true;
172c0ebfbe3SNick Lewycky
173c0ebfbe3SNick Lewycky const Loop *Outer = nullptr;
174c0ebfbe3SNick Lewycky if (LI) {
175c0ebfbe3SNick Lewycky Outer = getOutermostLoop(LI, BB);
176c0ebfbe3SNick Lewycky // If we're in a loop with a hole, not all blocks in the loop are
177c0ebfbe3SNick Lewycky // reachable from all other blocks. That implies we can't simply jump to
178c0ebfbe3SNick Lewycky // the loop's exit blocks, as that exit might need to pass through an
179c0ebfbe3SNick Lewycky // excluded block. Clear Outer so we process BB's successors.
180c0ebfbe3SNick Lewycky if (LoopsWithHoles.count(Outer))
181c0ebfbe3SNick Lewycky Outer = nullptr;
182c0ebfbe3SNick Lewycky if (StopLoop && Outer == StopLoop)
1830b68245eSNick Lewycky return true;
184c0ebfbe3SNick Lewycky }
1850b68245eSNick Lewycky
1860b68245eSNick Lewycky if (!--Limit) {
1870b68245eSNick Lewycky // We haven't been able to prove it one way or the other. Conservatively
1880b68245eSNick Lewycky // answer true -- that there is potentially a path.
1890b68245eSNick Lewycky return true;
1900b68245eSNick Lewycky }
1910b68245eSNick Lewycky
192c0ebfbe3SNick Lewycky if (Outer) {
1930b68245eSNick Lewycky // All blocks in a single loop are reachable from all other blocks. From
1940b68245eSNick Lewycky // any of these blocks, we can skip directly to the exits of the loop,
1950b68245eSNick Lewycky // ignoring any other blocks inside the loop body.
1960b68245eSNick Lewycky Outer->getExitBlocks(Worklist);
1970b68245eSNick Lewycky } else {
1983c29c070SBenjamin Kramer Worklist.append(succ_begin(BB), succ_end(BB));
1990b68245eSNick Lewycky }
2000b68245eSNick Lewycky } while (!Worklist.empty());
2010b68245eSNick Lewycky
2028d2e86dbSNick Lewycky // We have exhausted all possible paths and are certain that 'To' can not be
2038d2e86dbSNick Lewycky // reached from 'From'.
2040b68245eSNick Lewycky return false;
2050b68245eSNick Lewycky }
2068d2e86dbSNick Lewycky
isPotentiallyReachable(const BasicBlock * A,const BasicBlock * B,const SmallPtrSetImpl<BasicBlock * > * ExclusionSet,const DominatorTree * DT,const LoopInfo * LI)207f9e9b0cdSNikita Popov bool llvm::isPotentiallyReachable(
208f9e9b0cdSNikita Popov const BasicBlock *A, const BasicBlock *B,
209f9e9b0cdSNikita Popov const SmallPtrSetImpl<BasicBlock *> *ExclusionSet, const DominatorTree *DT,
210f9e9b0cdSNikita Popov const LoopInfo *LI) {
2118d2e86dbSNick Lewycky assert(A->getParent() == B->getParent() &&
2128d2e86dbSNick Lewycky "This analysis is function-local!");
2138d2e86dbSNick Lewycky
214f9e9b0cdSNikita Popov if (DT) {
215f9e9b0cdSNikita Popov if (DT->isReachableFromEntry(A) && !DT->isReachableFromEntry(B))
216f9e9b0cdSNikita Popov return false;
217f9e9b0cdSNikita Popov if (!ExclusionSet || ExclusionSet->empty()) {
218f9e9b0cdSNikita Popov if (A->isEntryBlock() && DT->isReachableFromEntry(B))
219f9e9b0cdSNikita Popov return true;
220f9e9b0cdSNikita Popov if (B->isEntryBlock() && DT->isReachableFromEntry(A))
221f9e9b0cdSNikita Popov return false;
222f9e9b0cdSNikita Popov }
223f9e9b0cdSNikita Popov }
224f9e9b0cdSNikita Popov
2258d2e86dbSNick Lewycky SmallVector<BasicBlock*, 32> Worklist;
2268d2e86dbSNick Lewycky Worklist.push_back(const_cast<BasicBlock*>(A));
2278d2e86dbSNick Lewycky
2287900ef89SBruno Cardoso Lopes return isPotentiallyReachableFromMany(Worklist, const_cast<BasicBlock *>(B),
229f9e9b0cdSNikita Popov ExclusionSet, DT, LI);
2308d2e86dbSNick Lewycky }
2318d2e86dbSNick Lewycky
isPotentiallyReachable(const Instruction * A,const Instruction * B,const SmallPtrSetImpl<BasicBlock * > * ExclusionSet,const DominatorTree * DT,const LoopInfo * LI)232c0ebfbe3SNick Lewycky bool llvm::isPotentiallyReachable(
233c0ebfbe3SNick Lewycky const Instruction *A, const Instruction *B,
234c0ebfbe3SNick Lewycky const SmallPtrSetImpl<BasicBlock *> *ExclusionSet, const DominatorTree *DT,
235c0ebfbe3SNick Lewycky const LoopInfo *LI) {
2368d2e86dbSNick Lewycky assert(A->getParent()->getParent() == B->getParent()->getParent() &&
2378d2e86dbSNick Lewycky "This analysis is function-local!");
2388d2e86dbSNick Lewycky
2398d2e86dbSNick Lewycky if (A->getParent() == B->getParent()) {
2408d2e86dbSNick Lewycky // The same block case is special because it's the only time we're looking
2418d2e86dbSNick Lewycky // within a single block to see which instruction comes first. Once we
2428d2e86dbSNick Lewycky // start looking at multiple blocks, the first instruction of the block is
2438d2e86dbSNick Lewycky // reachable, so we only need to determine reachability between whole
2448d2e86dbSNick Lewycky // blocks.
2458d2e86dbSNick Lewycky BasicBlock *BB = const_cast<BasicBlock *>(A->getParent());
2468d2e86dbSNick Lewycky
2478d2e86dbSNick Lewycky // If the block is in a loop then we can reach any instruction in the block
2488d2e86dbSNick Lewycky // from any other instruction in the block by going around a backedge.
2499f008867SCraig Topper if (LI && LI->getLoopFor(BB) != nullptr)
2508d2e86dbSNick Lewycky return true;
2518d2e86dbSNick Lewycky
2526418bab6SNikita Popov // If A comes before B, then B is definitively reachable from A.
2536418bab6SNikita Popov if (A == B || A->comesBefore(B))
2548d2e86dbSNick Lewycky return true;
2558d2e86dbSNick Lewycky
2568d2e86dbSNick Lewycky // Can't be in a loop if it's the entry block -- the entry block may not
2578d2e86dbSNick Lewycky // have predecessors.
258fb9ed197SNikita Popov if (BB->isEntryBlock())
2598d2e86dbSNick Lewycky return false;
2608d2e86dbSNick Lewycky
2618d2e86dbSNick Lewycky // Otherwise, continue doing the normal per-BB CFG walk.
262f9e9b0cdSNikita Popov SmallVector<BasicBlock*, 32> Worklist;
2633c29c070SBenjamin Kramer Worklist.append(succ_begin(BB), succ_end(BB));
2648d2e86dbSNick Lewycky if (Worklist.empty()) {
2658d2e86dbSNick Lewycky // We've proven that there's no path!
2668d2e86dbSNick Lewycky return false;
2678d2e86dbSNick Lewycky }
2688d2e86dbSNick Lewycky
2697900ef89SBruno Cardoso Lopes return isPotentiallyReachableFromMany(
270f9e9b0cdSNikita Popov Worklist, const_cast<BasicBlock *>(B->getParent()), ExclusionSet,
271f9e9b0cdSNikita Popov DT, LI);
272f9e9b0cdSNikita Popov }
273f9e9b0cdSNikita Popov
274f9e9b0cdSNikita Popov return isPotentiallyReachable(
275f9e9b0cdSNikita Popov A->getParent(), B->getParent(), ExclusionSet, DT, LI);
2768d2e86dbSNick Lewycky }
277