#include "llvm/Analysis/LazyCallGraph.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/Sequence.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/iterator_range.h"
#include "llvm/Analysis/TargetLibraryInfo.h"
#include "llvm/Config/llvm-config.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/GlobalVariable.h"
#include "llvm/IR/InstIterator.h"
#include "llvm/IR/Instruction.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/PassManager.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/GraphWriter.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
#include <cassert>
#include <iterator>
#include <string>
#include <tuple>
#include <utility>
#ifdef EXPENSIVE_CHECKS
#include "llvm/ADT/ScopeExit.h"
#endif
using namespace llvm;
#define DEBUG_TYPE "lcg"
void LazyCallGraph::EdgeSequence::insertEdgeInternal(Node &TargetN,
Edge::Kind EK) {
EdgeIndexMap.insert({&TargetN, Edges.size()});
Edges.emplace_back(TargetN, EK);
}
void LazyCallGraph::EdgeSequence::setEdgeKind(Node &TargetN, Edge::Kind EK) {
Edges[EdgeIndexMap.find(&TargetN)->second].setKind(EK);
}
bool LazyCallGraph::EdgeSequence::removeEdgeInternal(Node &TargetN) {
auto IndexMapI = EdgeIndexMap.find(&TargetN);
if (IndexMapI == EdgeIndexMap.end())
return false;
Edges[IndexMapI->second] = Edge();
EdgeIndexMap.erase(IndexMapI);
return true;
}
static void addEdge(SmallVectorImpl<LazyCallGraph::Edge> &Edges,
DenseMap<LazyCallGraph::Node *, int> &EdgeIndexMap,
LazyCallGraph::Node &N, LazyCallGraph::Edge::Kind EK) {
if (!EdgeIndexMap.insert({&N, Edges.size()}).second)
return;
LLVM_DEBUG(dbgs() << " Added callable function: " << N.getName() << "\n");
Edges.emplace_back(LazyCallGraph::Edge(N, EK));
}
LazyCallGraph::EdgeSequence &LazyCallGraph::Node::populateSlow() {
assert(!Edges && "Must not have already populated the edges for this node!");
LLVM_DEBUG(dbgs() << " Adding functions called by '" << getName()
<< "' to the graph.\n");
Edges = EdgeSequence();
SmallVector<Constant *, 16> Worklist;
SmallPtrSet<Function *, 4> Callees;
SmallPtrSet<Constant *, 16> Visited;
for (BasicBlock &BB : *F)
for (Instruction &I : BB) {
if (auto *CB = dyn_cast<CallBase>(&I))
if (Function *Callee = CB->getCalledFunction())
if (!Callee->isDeclaration())
if (Callees.insert(Callee).second) {
Visited.insert(Callee);
addEdge(Edges->Edges, Edges->EdgeIndexMap, G->get(*Callee),
LazyCallGraph::Edge::Call);
}
for (Value *Op : I.operand_values())
if (Constant *C = dyn_cast<Constant>(Op))
if (Visited.insert(C).second)
Worklist.push_back(C);
}
visitReferences(Worklist, Visited, [&](Function &F) {
addEdge(Edges->Edges, Edges->EdgeIndexMap, G->get(F),
LazyCallGraph::Edge::Ref);
});
for (auto *F : G->LibFunctions)
if (!Visited.count(F))
addEdge(Edges->Edges, Edges->EdgeIndexMap, G->get(*F),
LazyCallGraph::Edge::Ref);
return *Edges;
}
void LazyCallGraph::Node::replaceFunction(Function &NewF) {
assert(F != &NewF && "Must not replace a function with itself!");
F = &NewF;
}
#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
LLVM_DUMP_METHOD void LazyCallGraph::Node::dump() const {
dbgs() << *this << '\n';
}
#endif
static bool isKnownLibFunction(Function &F, TargetLibraryInfo &TLI) {
LibFunc LF;
return TLI.getLibFunc(F, LF) ||
TLI.isKnownVectorFunctionInLibrary(F.getName());
}
LazyCallGraph::LazyCallGraph(
Module &M, function_ref<TargetLibraryInfo &(Function &)> GetTLI) {
LLVM_DEBUG(dbgs() << "Building CG for module: " << M.getModuleIdentifier()
<< "\n");
for (Function &F : M) {
if (F.isDeclaration())
continue;
if (isKnownLibFunction(F, GetTLI(F)))
LibFunctions.insert(&F);
if (F.hasLocalLinkage())
continue;
LLVM_DEBUG(dbgs() << " Adding '" << F.getName()
<< "' to entry set of the graph.\n");
addEdge(EntryEdges.Edges, EntryEdges.EdgeIndexMap, get(F), Edge::Ref);
}
for (auto &A : M.aliases()) {
if (A.hasLocalLinkage())
continue;
if (Function* F = dyn_cast<Function>(A.getAliasee())) {
LLVM_DEBUG(dbgs() << " Adding '" << F->getName()
<< "' with alias '" << A.getName()
<< "' to entry set of the graph.\n");
addEdge(EntryEdges.Edges, EntryEdges.EdgeIndexMap, get(*F), Edge::Ref);
}
}
SmallVector<Constant *, 16> Worklist;
SmallPtrSet<Constant *, 16> Visited;
for (GlobalVariable &GV : M.globals())
if (GV.hasInitializer())
if (Visited.insert(GV.getInitializer()).second)
Worklist.push_back(GV.getInitializer());
LLVM_DEBUG(
dbgs() << " Adding functions referenced by global initializers to the "
"entry set.\n");
visitReferences(Worklist, Visited, [&](Function &F) {
addEdge(EntryEdges.Edges, EntryEdges.EdgeIndexMap, get(F),
LazyCallGraph::Edge::Ref);
});
}
LazyCallGraph::LazyCallGraph(LazyCallGraph &&G)
: BPA(std::move(G.BPA)), NodeMap(std::move(G.NodeMap)),
EntryEdges(std::move(G.EntryEdges)), SCCBPA(std::move(G.SCCBPA)),
SCCMap(std::move(G.SCCMap)),
LibFunctions(std::move(G.LibFunctions)) {
updateGraphPtrs();
}
bool LazyCallGraph::invalidate(Module &, const PreservedAnalyses &PA,
ModuleAnalysisManager::Invalidator &) {
auto PAC = PA.getChecker<llvm::LazyCallGraphAnalysis>();
return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Module>>());
}
LazyCallGraph &LazyCallGraph::operator=(LazyCallGraph &&G) {
BPA = std::move(G.BPA);
NodeMap = std::move(G.NodeMap);
EntryEdges = std::move(G.EntryEdges);
SCCBPA = std::move(G.SCCBPA);
SCCMap = std::move(G.SCCMap);
LibFunctions = std::move(G.LibFunctions);
updateGraphPtrs();
return *this;
}
#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
LLVM_DUMP_METHOD void LazyCallGraph::SCC::dump() const {
dbgs() << *this << '\n';
}
#endif
#if !defined(NDEBUG) || defined(EXPENSIVE_CHECKS)
void LazyCallGraph::SCC::verify() {
assert(OuterRefSCC && "Can't have a null RefSCC!");
assert(!Nodes.empty() && "Can't have an empty SCC!");
for (Node *N : Nodes) {
assert(N && "Can't have a null node!");
assert(OuterRefSCC->G->lookupSCC(*N) == this &&
"Node does not map to this SCC!");
assert(N->DFSNumber == -1 &&
"Must set DFS numbers to -1 when adding a node to an SCC!");
assert(N->LowLink == -1 &&
"Must set low link to -1 when adding a node to an SCC!");
for (Edge &E : **N)
assert(E.getNode().isPopulated() && "Can't have an unpopulated node!");
#ifdef EXPENSIVE_CHECKS
SmallVector<Node *, 4> Worklist;
SmallPtrSet<Node *, 4> Visited;
Worklist.push_back(N);
while (!Worklist.empty()) {
Node *VisitingNode = Worklist.pop_back_val();
if (!Visited.insert(VisitingNode).second)
continue;
for (Edge &E : (*VisitingNode)->calls())
Worklist.push_back(&E.getNode());
}
for (Node *NodeToVisit : Nodes) {
assert(Visited.contains(NodeToVisit) &&
"Cannot reach all nodes within SCC");
}
#endif
}
}
#endif
bool LazyCallGraph::SCC::isParentOf(const SCC &C) const {
if (this == &C)
return false;
for (Node &N : *this)
for (Edge &E : N->calls())
if (OuterRefSCC->G->lookupSCC(E.getNode()) == &C)
return true;
return false;
}
bool LazyCallGraph::SCC::isAncestorOf(const SCC &TargetC) const {
if (this == &TargetC)
return false;
LazyCallGraph &G = *OuterRefSCC->G;
SmallPtrSet<const SCC *, 16> Visited = {this};
SmallVector<const SCC *, 16> Worklist = {this};
do {
const SCC &C = *Worklist.pop_back_val();
for (Node &N : C)
for (Edge &E : N->calls()) {
SCC *CalleeC = G.lookupSCC(E.getNode());
if (!CalleeC)
continue;
if (CalleeC == &TargetC)
return true;
if (Visited.insert(CalleeC).second)
Worklist.push_back(CalleeC);
}
} while (!Worklist.empty());
return false;
}
LazyCallGraph::RefSCC::RefSCC(LazyCallGraph &G) : G(&G) {}
#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
LLVM_DUMP_METHOD void LazyCallGraph::RefSCC::dump() const {
dbgs() << *this << '\n';
}
#endif
#if !defined(NDEBUG) || defined(EXPENSIVE_CHECKS)
void LazyCallGraph::RefSCC::verify() {
assert(G && "Can't have a null graph!");
assert(!SCCs.empty() && "Can't have an empty SCC!");
SmallPtrSet<SCC *, 4> SCCSet;
for (SCC *C : SCCs) {
assert(C && "Can't have a null SCC!");
C->verify();
assert(&C->getOuterRefSCC() == this &&
"SCC doesn't think it is inside this RefSCC!");
bool Inserted = SCCSet.insert(C).second;
assert(Inserted && "Found a duplicate SCC!");
auto IndexIt = SCCIndices.find(C);
assert(IndexIt != SCCIndices.end() &&
"Found an SCC that doesn't have an index!");
}
for (auto &SCCIndexPair : SCCIndices) {
SCC *C = SCCIndexPair.first;
int i = SCCIndexPair.second;
assert(C && "Can't have a null SCC in the indices!");
assert(SCCSet.count(C) && "Found an index for an SCC not in the RefSCC!");
assert(SCCs[i] == C && "Index doesn't point to SCC!");
}
for (int i = 0, Size = SCCs.size(); i < Size; ++i) {
SCC &SourceSCC = *SCCs[i];
for (Node &N : SourceSCC)
for (Edge &E : *N) {
if (!E.isCall())
continue;
SCC &TargetSCC = *G->lookupSCC(E.getNode());
if (&TargetSCC.getOuterRefSCC() == this) {
assert(SCCIndices.find(&TargetSCC)->second <= i &&
"Edge between SCCs violates post-order relationship.");
continue;
}
}
}
#ifdef EXPENSIVE_CHECKS
SmallVector<Node *> Nodes;
for (SCC *C : SCCs) {
for (Node &N : *C)
Nodes.push_back(&N);
}
for (Node *N : Nodes) {
SmallVector<Node *, 4> Worklist;
SmallPtrSet<Node *, 4> Visited;
Worklist.push_back(N);
while (!Worklist.empty()) {
Node *VisitingNode = Worklist.pop_back_val();
if (!Visited.insert(VisitingNode).second)
continue;
for (Edge &E : **VisitingNode)
Worklist.push_back(&E.getNode());
}
for (Node *NodeToVisit : Nodes) {
assert(Visited.contains(NodeToVisit) &&
"Cannot reach all nodes within RefSCC");
}
}
#endif
}
#endif
bool LazyCallGraph::RefSCC::isParentOf(const RefSCC &RC) const {
if (&RC == this)
return false;
for (SCC &C : *this)
for (Node &N : C)
for (Edge &E : *N)
if (G->lookupRefSCC(E.getNode()) == &RC)
return true;
return false;
}
bool LazyCallGraph::RefSCC::isAncestorOf(const RefSCC &RC) const {
if (&RC == this)
return false;
SmallVector<const RefSCC *, 4> Worklist;
SmallPtrSet<const RefSCC *, 4> Visited;
Worklist.push_back(this);
Visited.insert(this);
do {
const RefSCC &DescendantRC = *Worklist.pop_back_val();
for (SCC &C : DescendantRC)
for (Node &N : C)
for (Edge &E : *N) {
auto *ChildRC = G->lookupRefSCC(E.getNode());
if (ChildRC == &RC)
return true;
if (!ChildRC || !Visited.insert(ChildRC).second)
continue;
Worklist.push_back(ChildRC);
}
} while (!Worklist.empty());
return false;
}
template <typename SCCT, typename PostorderSequenceT, typename SCCIndexMapT,
typename ComputeSourceConnectedSetCallableT,
typename ComputeTargetConnectedSetCallableT>
static iterator_range<typename PostorderSequenceT::iterator>
updatePostorderSequenceForEdgeInsertion(
SCCT &SourceSCC, SCCT &TargetSCC, PostorderSequenceT &SCCs,
SCCIndexMapT &SCCIndices,
ComputeSourceConnectedSetCallableT ComputeSourceConnectedSet,
ComputeTargetConnectedSetCallableT ComputeTargetConnectedSet) {
int SourceIdx = SCCIndices[&SourceSCC];
int TargetIdx = SCCIndices[&TargetSCC];
assert(SourceIdx < TargetIdx && "Cannot have equal indices here!");
SmallPtrSet<SCCT *, 4> ConnectedSet;
ComputeSourceConnectedSet(ConnectedSet);
auto SourceI = std::stable_partition(
SCCs.begin() + SourceIdx, SCCs.begin() + TargetIdx + 1,
[&ConnectedSet](SCCT *C) { return !ConnectedSet.count(C); });
for (int i = SourceIdx, e = TargetIdx + 1; i < e; ++i)
SCCIndices.find(SCCs[i])->second = i;
if (!ConnectedSet.count(&TargetSCC)) {
assert(SourceI > (SCCs.begin() + SourceIdx) &&
"Must have moved the source to fix the post-order.");
assert(*std::prev(SourceI) == &TargetSCC &&
"Last SCC to move should have bene the target.");
return make_range(std::prev(SourceI), std::prev(SourceI));
}
assert(SCCs[TargetIdx] == &TargetSCC &&
"Should not have moved target if connected!");
SourceIdx = SourceI - SCCs.begin();
assert(SCCs[SourceIdx] == &SourceSCC &&
"Bad updated index computation for the source SCC!");
if (SourceIdx + 1 < TargetIdx) {
ConnectedSet.clear();
ComputeTargetConnectedSet(ConnectedSet);
auto TargetI = std::stable_partition(
SCCs.begin() + SourceIdx + 1, SCCs.begin() + TargetIdx + 1,
[&ConnectedSet](SCCT *C) { return ConnectedSet.count(C); });
for (int i = SourceIdx + 1, e = TargetIdx + 1; i < e; ++i)
SCCIndices.find(SCCs[i])->second = i;
TargetIdx = std::prev(TargetI) - SCCs.begin();
assert(SCCs[TargetIdx] == &TargetSCC &&
"Should always end with the target!");
}
return make_range(SCCs.begin() + SourceIdx, SCCs.begin() + TargetIdx);
}
bool
LazyCallGraph::RefSCC::switchInternalEdgeToCall(
Node &SourceN, Node &TargetN,
function_ref<void(ArrayRef<SCC *> MergeSCCs)> MergeCB) {
assert(!(*SourceN)[TargetN].isCall() && "Must start with a ref edge!");
SmallVector<SCC *, 1> DeletedSCCs;
#ifdef EXPENSIVE_CHECKS
verify();
auto VerifyOnExit = make_scope_exit([&]() { verify(); });
#endif
SCC &SourceSCC = *G->lookupSCC(SourceN);
SCC &TargetSCC = *G->lookupSCC(TargetN);
if (&SourceSCC == &TargetSCC) {
SourceN->setEdgeKind(TargetN, Edge::Call);
return false; }
int SourceIdx = SCCIndices[&SourceSCC];
int TargetIdx = SCCIndices[&TargetSCC];
if (TargetIdx < SourceIdx) {
SourceN->setEdgeKind(TargetN, Edge::Call);
return false; }
auto ComputeSourceConnectedSet = [&](SmallPtrSetImpl<SCC *> &ConnectedSet) {
#ifdef EXPENSIVE_CHECKS
verify();
#endif
ConnectedSet.insert(&SourceSCC);
auto IsConnected = [&](SCC &C) {
for (Node &N : C)
for (Edge &E : N->calls())
if (ConnectedSet.count(G->lookupSCC(E.getNode())))
return true;
return false;
};
for (SCC *C :
make_range(SCCs.begin() + SourceIdx + 1, SCCs.begin() + TargetIdx + 1))
if (IsConnected(*C))
ConnectedSet.insert(C);
};
auto ComputeTargetConnectedSet = [&](SmallPtrSetImpl<SCC *> &ConnectedSet) {
#ifdef EXPENSIVE_CHECKS
verify();
#endif
ConnectedSet.insert(&TargetSCC);
SmallVector<SCC *, 4> Worklist;
Worklist.push_back(&TargetSCC);
do {
SCC &C = *Worklist.pop_back_val();
for (Node &N : C)
for (Edge &E : *N) {
if (!E.isCall())
continue;
SCC &EdgeC = *G->lookupSCC(E.getNode());
if (&EdgeC.getOuterRefSCC() != this)
continue;
if (SCCIndices.find(&EdgeC)->second <= SourceIdx)
continue;
if (ConnectedSet.insert(&EdgeC).second)
Worklist.push_back(&EdgeC);
}
} while (!Worklist.empty());
};
auto MergeRange = updatePostorderSequenceForEdgeInsertion(
SourceSCC, TargetSCC, SCCs, SCCIndices, ComputeSourceConnectedSet,
ComputeTargetConnectedSet);
if (MergeCB)
MergeCB(makeArrayRef(MergeRange.begin(), MergeRange.end()));
if (MergeRange.empty()) {
SourceN->setEdgeKind(TargetN, Edge::Call);
return false; }
#ifdef EXPENSIVE_CHECKS
verify();
#endif
for (SCC *C : MergeRange) {
assert(C != &TargetSCC &&
"We merge *into* the target and shouldn't process it here!");
SCCIndices.erase(C);
TargetSCC.Nodes.append(C->Nodes.begin(), C->Nodes.end());
for (Node *N : C->Nodes)
G->SCCMap[N] = &TargetSCC;
C->clear();
DeletedSCCs.push_back(C);
}
int IndexOffset = MergeRange.end() - MergeRange.begin();
auto EraseEnd = SCCs.erase(MergeRange.begin(), MergeRange.end());
for (SCC *C : make_range(EraseEnd, SCCs.end()))
SCCIndices[C] -= IndexOffset;
SourceN->setEdgeKind(TargetN, Edge::Call);
return true;
}
void LazyCallGraph::RefSCC::switchTrivialInternalEdgeToRef(Node &SourceN,
Node &TargetN) {
assert((*SourceN)[TargetN].isCall() && "Must start with a call edge!");
#ifdef EXPENSIVE_CHECKS
verify();
auto VerifyOnExit = make_scope_exit([&]() { verify(); });
#endif
assert(G->lookupRefSCC(SourceN) == this &&
"Source must be in this RefSCC.");
assert(G->lookupRefSCC(TargetN) == this &&
"Target must be in this RefSCC.");
assert(G->lookupSCC(SourceN) != G->lookupSCC(TargetN) &&
"Source and Target must be in separate SCCs for this to be trivial!");
SourceN->setEdgeKind(TargetN, Edge::Ref);
}
iterator_range<LazyCallGraph::RefSCC::iterator>
LazyCallGraph::RefSCC::switchInternalEdgeToRef(Node &SourceN, Node &TargetN) {
assert((*SourceN)[TargetN].isCall() && "Must start with a call edge!");
#ifdef EXPENSIVE_CHECKS
verify();
auto VerifyOnExit = make_scope_exit([&]() { verify(); });
#endif
assert(G->lookupRefSCC(SourceN) == this &&
"Source must be in this RefSCC.");
assert(G->lookupRefSCC(TargetN) == this &&
"Target must be in this RefSCC.");
SCC &TargetSCC = *G->lookupSCC(TargetN);
assert(G->lookupSCC(SourceN) == &TargetSCC && "Source and Target must be in "
"the same SCC to require the "
"full CG update.");
SourceN->setEdgeKind(TargetN, Edge::Ref);
SCC &OldSCC = TargetSCC;
SmallVector<std::pair<Node *, EdgeSequence::call_iterator>, 16> DFSStack;
SmallVector<Node *, 16> PendingSCCStack;
SmallVector<SCC *, 4> NewSCCs;
SmallVector<Node *, 16> Worklist;
Worklist.swap(OldSCC.Nodes);
for (Node *N : Worklist) {
N->DFSNumber = N->LowLink = 0;
G->SCCMap.erase(N);
}
TargetN.DFSNumber = TargetN.LowLink = -1;
OldSCC.Nodes.push_back(&TargetN);
G->SCCMap[&TargetN] = &OldSCC;
for (Node *RootN : Worklist) {
assert(DFSStack.empty() &&
"Cannot begin a new root with a non-empty DFS stack!");
assert(PendingSCCStack.empty() &&
"Cannot begin a new root with pending nodes for an SCC!");
if (RootN->DFSNumber != 0) {
assert(RootN->DFSNumber == -1 &&
"Shouldn't have any mid-DFS root nodes!");
continue;
}
RootN->DFSNumber = RootN->LowLink = 1;
int NextDFSNumber = 2;
DFSStack.push_back({RootN, (*RootN)->call_begin()});
do {
Node *N;
EdgeSequence::call_iterator I;
std::tie(N, I) = DFSStack.pop_back_val();
auto E = (*N)->call_end();
while (I != E) {
Node &ChildN = I->getNode();
if (ChildN.DFSNumber == 0) {
DFSStack.push_back({N, I});
assert(!G->SCCMap.count(&ChildN) &&
"Found a node with 0 DFS number but already in an SCC!");
ChildN.DFSNumber = ChildN.LowLink = NextDFSNumber++;
N = &ChildN;
I = (*N)->call_begin();
E = (*N)->call_end();
continue;
}
if (ChildN.DFSNumber == -1) {
if (G->lookupSCC(ChildN) == &OldSCC) {
int OldSize = OldSCC.size();
OldSCC.Nodes.push_back(N);
OldSCC.Nodes.append(PendingSCCStack.begin(), PendingSCCStack.end());
PendingSCCStack.clear();
while (!DFSStack.empty())
OldSCC.Nodes.push_back(DFSStack.pop_back_val().first);
for (Node &N : drop_begin(OldSCC, OldSize)) {
N.DFSNumber = N.LowLink = -1;
G->SCCMap[&N] = &OldSCC;
}
N = nullptr;
break;
}
++I;
continue;
}
assert(ChildN.LowLink > 0 && "Must have a positive low-link number!");
if (ChildN.LowLink < N->LowLink)
N->LowLink = ChildN.LowLink;
++I;
}
if (!N)
break;
PendingSCCStack.push_back(N);
if (N->LowLink != N->DFSNumber)
continue;
int RootDFSNumber = N->DFSNumber;
auto SCCNodes = make_range(
PendingSCCStack.rbegin(),
find_if(reverse(PendingSCCStack), [RootDFSNumber](const Node *N) {
return N->DFSNumber < RootDFSNumber;
}));
NewSCCs.push_back(G->createSCC(*this, SCCNodes));
for (Node &N : *NewSCCs.back()) {
N.DFSNumber = N.LowLink = -1;
G->SCCMap[&N] = NewSCCs.back();
}
PendingSCCStack.erase(SCCNodes.end().base(), PendingSCCStack.end());
} while (!DFSStack.empty());
}
int OldIdx = SCCIndices[&OldSCC];
SCCs.insert(SCCs.begin() + OldIdx, NewSCCs.begin(), NewSCCs.end());
for (int Idx = OldIdx, Size = SCCs.size(); Idx < Size; ++Idx)
SCCIndices[SCCs[Idx]] = Idx;
return make_range(SCCs.begin() + OldIdx,
SCCs.begin() + OldIdx + NewSCCs.size());
}
void LazyCallGraph::RefSCC::switchOutgoingEdgeToCall(Node &SourceN,
Node &TargetN) {
assert(!(*SourceN)[TargetN].isCall() && "Must start with a ref edge!");
assert(G->lookupRefSCC(SourceN) == this && "Source must be in this RefSCC.");
assert(G->lookupRefSCC(TargetN) != this &&
"Target must not be in this RefSCC.");
#ifdef EXPENSIVE_CHECKS
assert(G->lookupRefSCC(TargetN)->isDescendantOf(*this) &&
"Target must be a descendant of the Source.");
#endif
SourceN->setEdgeKind(TargetN, Edge::Call);
#ifdef EXPENSIVE_CHECKS
verify();
#endif
}
void LazyCallGraph::RefSCC::switchOutgoingEdgeToRef(Node &SourceN,
Node &TargetN) {
assert((*SourceN)[TargetN].isCall() && "Must start with a call edge!");
assert(G->lookupRefSCC(SourceN) == this && "Source must be in this RefSCC.");
assert(G->lookupRefSCC(TargetN) != this &&
"Target must not be in this RefSCC.");
#ifdef EXPENSIVE_CHECKS
assert(G->lookupRefSCC(TargetN)->isDescendantOf(*this) &&
"Target must be a descendant of the Source.");
#endif
SourceN->setEdgeKind(TargetN, Edge::Ref);
#ifdef EXPENSIVE_CHECKS
verify();
#endif
}
void LazyCallGraph::RefSCC::insertInternalRefEdge(Node &SourceN,
Node &TargetN) {
assert(G->lookupRefSCC(SourceN) == this && "Source must be in this RefSCC.");
assert(G->lookupRefSCC(TargetN) == this && "Target must be in this RefSCC.");
SourceN->insertEdgeInternal(TargetN, Edge::Ref);
#ifdef EXPENSIVE_CHECKS
verify();
#endif
}
void LazyCallGraph::RefSCC::insertOutgoingEdge(Node &SourceN, Node &TargetN,
Edge::Kind EK) {
SourceN->insertEdgeInternal(TargetN, EK);
assert(G->lookupRefSCC(SourceN) == this && "Source must be in this RefSCC.");
assert(G->lookupRefSCC(TargetN) != this &&
"Target must not be in this RefSCC.");
#ifdef EXPENSIVE_CHECKS
assert(G->lookupRefSCC(TargetN)->isDescendantOf(*this) &&
"Target must be a descendant of the Source.");
#endif
#ifdef EXPENSIVE_CHECKS
verify();
#endif
}
SmallVector<LazyCallGraph::RefSCC *, 1>
LazyCallGraph::RefSCC::insertIncomingRefEdge(Node &SourceN, Node &TargetN) {
assert(G->lookupRefSCC(TargetN) == this && "Target must be in this RefSCC.");
RefSCC &SourceC = *G->lookupRefSCC(SourceN);
assert(&SourceC != this && "Source must not be in this RefSCC.");
#ifdef EXPENSIVE_CHECKS
assert(SourceC.isDescendantOf(*this) &&
"Source must be a descendant of the Target.");
#endif
SmallVector<RefSCC *, 1> DeletedRefSCCs;
#ifdef EXPENSIVE_CHECKS
verify();
auto VerifyOnExit = make_scope_exit([&]() { verify(); });
#endif
int SourceIdx = G->RefSCCIndices[&SourceC];
int TargetIdx = G->RefSCCIndices[this];
assert(SourceIdx < TargetIdx &&
"Postorder list doesn't see edge as incoming!");
auto ComputeSourceConnectedSet = [&](SmallPtrSetImpl<RefSCC *> &Set) {
Set.insert(&SourceC);
auto IsConnected = [&](RefSCC &RC) {
for (SCC &C : RC)
for (Node &N : C)
for (Edge &E : *N)
if (Set.count(G->lookupRefSCC(E.getNode())))
return true;
return false;
};
for (RefSCC *C : make_range(G->PostOrderRefSCCs.begin() + SourceIdx + 1,
G->PostOrderRefSCCs.begin() + TargetIdx + 1))
if (IsConnected(*C))
Set.insert(C);
};
auto ComputeTargetConnectedSet = [&](SmallPtrSetImpl<RefSCC *> &Set) {
Set.insert(this);
SmallVector<RefSCC *, 4> Worklist;
Worklist.push_back(this);
do {
RefSCC &RC = *Worklist.pop_back_val();
for (SCC &C : RC)
for (Node &N : C)
for (Edge &E : *N) {
RefSCC &EdgeRC = *G->lookupRefSCC(E.getNode());
if (G->getRefSCCIndex(EdgeRC) <= SourceIdx)
continue;
if (Set.insert(&EdgeRC).second)
Worklist.push_back(&EdgeRC);
}
} while (!Worklist.empty());
};
iterator_range<SmallVectorImpl<RefSCC *>::iterator> MergeRange =
updatePostorderSequenceForEdgeInsertion(
SourceC, *this, G->PostOrderRefSCCs, G->RefSCCIndices,
ComputeSourceConnectedSet, ComputeTargetConnectedSet);
SmallPtrSet<RefSCC *, 16> MergeSet(MergeRange.begin(), MergeRange.end());
MergeSet.insert(this);
SmallVector<SCC *, 16> MergedSCCs;
int SCCIndex = 0;
for (RefSCC *RC : MergeRange) {
assert(RC != this && "We're merging into the target RefSCC, so it "
"shouldn't be in the range.");
for (SCC &InnerC : *RC) {
InnerC.OuterRefSCC = this;
SCCIndices[&InnerC] = SCCIndex++;
for (Node &N : InnerC)
G->SCCMap[&N] = &InnerC;
}
if (MergedSCCs.empty())
MergedSCCs = std::move(RC->SCCs);
else
MergedSCCs.append(RC->SCCs.begin(), RC->SCCs.end());
RC->SCCs.clear();
DeletedRefSCCs.push_back(RC);
}
for (SCC &InnerC : *this)
SCCIndices[&InnerC] = SCCIndex++;
MergedSCCs.append(SCCs.begin(), SCCs.end());
SCCs = std::move(MergedSCCs);
for (RefSCC *RC : MergeRange)
G->RefSCCIndices.erase(RC);
int IndexOffset = MergeRange.end() - MergeRange.begin();
auto EraseEnd =
G->PostOrderRefSCCs.erase(MergeRange.begin(), MergeRange.end());
for (RefSCC *RC : make_range(EraseEnd, G->PostOrderRefSCCs.end()))
G->RefSCCIndices[RC] -= IndexOffset;
SourceN->insertEdgeInternal(TargetN, Edge::Ref);
return DeletedRefSCCs;
}
void LazyCallGraph::RefSCC::removeOutgoingEdge(Node &SourceN, Node &TargetN) {
assert(G->lookupRefSCC(SourceN) == this &&
"The source must be a member of this RefSCC.");
assert(G->lookupRefSCC(TargetN) != this &&
"The target must not be a member of this RefSCC");
#ifdef EXPENSIVE_CHECKS
verify();
auto VerifyOnExit = make_scope_exit([&]() { verify(); });
#endif
bool Removed = SourceN->removeEdgeInternal(TargetN);
(void)Removed;
assert(Removed && "Target not in the edge set for this caller?");
}
SmallVector<LazyCallGraph::RefSCC *, 1>
LazyCallGraph::RefSCC::removeInternalRefEdge(Node &SourceN,
ArrayRef<Node *> TargetNs) {
SmallVector<RefSCC *, 1> Result;
#ifdef EXPENSIVE_CHECKS
verify();
auto VerifyOnExit = make_scope_exit([&]() {
if (G)
verify();
});
#endif
for (Node *TargetN : TargetNs) {
assert(!(*SourceN)[*TargetN].isCall() &&
"Cannot remove a call edge, it must first be made a ref edge");
bool Removed = SourceN->removeEdgeInternal(*TargetN);
(void)Removed;
assert(Removed && "Target not in the edge set for this caller?");
}
if (llvm::all_of(TargetNs,
[&](Node *TargetN) { return &SourceN == TargetN; }))
return Result;
SCC &SourceC = *G->lookupSCC(SourceN);
if (llvm::all_of(TargetNs, [&](Node *TargetN) {
return G->lookupSCC(*TargetN) == &SourceC;
}))
return Result;
int PostOrderNumber = 0;
SmallVector<Node *, 8> Worklist;
for (SCC *C : SCCs) {
for (Node &N : *C)
N.DFSNumber = N.LowLink = 0;
Worklist.append(C->Nodes.begin(), C->Nodes.end());
}
const int NumRefSCCNodes = Worklist.size();
SmallVector<std::pair<Node *, EdgeSequence::iterator>, 4> DFSStack;
SmallVector<Node *, 4> PendingRefSCCStack;
do {
assert(DFSStack.empty() &&
"Cannot begin a new root with a non-empty DFS stack!");
assert(PendingRefSCCStack.empty() &&
"Cannot begin a new root with pending nodes for an SCC!");
Node *RootN = Worklist.pop_back_val();
if (RootN->DFSNumber != 0) {
assert(RootN->DFSNumber == -1 &&
"Shouldn't have any mid-DFS root nodes!");
continue;
}
RootN->DFSNumber = RootN->LowLink = 1;
int NextDFSNumber = 2;
DFSStack.push_back({RootN, (*RootN)->begin()});
do {
Node *N;
EdgeSequence::iterator I;
std::tie(N, I) = DFSStack.pop_back_val();
auto E = (*N)->end();
assert(N->DFSNumber != 0 && "We should always assign a DFS number "
"before processing a node.");
while (I != E) {
Node &ChildN = I->getNode();
if (ChildN.DFSNumber == 0) {
DFSStack.push_back({N, I});
ChildN.LowLink = ChildN.DFSNumber = NextDFSNumber++;
N = &ChildN;
I = ChildN->begin();
E = ChildN->end();
continue;
}
if (ChildN.DFSNumber == -1) {
++I;
continue;
}
assert(ChildN.LowLink != 0 &&
"Low-link must not be zero with a non-zero DFS number.");
if (ChildN.LowLink >= 0 && ChildN.LowLink < N->LowLink)
N->LowLink = ChildN.LowLink;
++I;
}
PendingRefSCCStack.push_back(N);
if (N->LowLink != N->DFSNumber) {
assert(!DFSStack.empty() &&
"We never found a viable root for a RefSCC to pop off!");
continue;
}
int RefSCCNumber = PostOrderNumber++;
int RootDFSNumber = N->DFSNumber;
auto StackRI = find_if(reverse(PendingRefSCCStack), [&](Node *N) {
if (N->DFSNumber < RootDFSNumber)
return true;
N->DFSNumber = -1;
N->LowLink = RefSCCNumber;
return false;
});
auto RefSCCNodes = make_range(StackRI.base(), PendingRefSCCStack.end());
if (llvm::size(RefSCCNodes) == NumRefSCCNodes) {
for (Node *N : RefSCCNodes)
N->LowLink = -1;
return Result;
}
PendingRefSCCStack.erase(RefSCCNodes.begin(), PendingRefSCCStack.end());
} while (!DFSStack.empty());
assert(DFSStack.empty() && "Didn't flush the entire DFS stack!");
assert(PendingRefSCCStack.empty() && "Didn't flush all pending nodes!");
} while (!Worklist.empty());
assert(PostOrderNumber > 1 &&
"Should never finish the DFS when the existing RefSCC remains valid!");
for (int i = 0; i < PostOrderNumber; ++i)
Result.push_back(G->createRefSCC(*G));
int Idx = G->getRefSCCIndex(*this);
G->PostOrderRefSCCs.erase(G->PostOrderRefSCCs.begin() + Idx);
G->PostOrderRefSCCs.insert(G->PostOrderRefSCCs.begin() + Idx, Result.begin(),
Result.end());
for (int i : seq<int>(Idx, G->PostOrderRefSCCs.size()))
G->RefSCCIndices[G->PostOrderRefSCCs[i]] = i;
for (SCC *C : SCCs) {
int SCCNumber = C->begin()->LowLink;
for (Node &N : *C) {
assert(N.LowLink == SCCNumber &&
"Cannot have different numbers for nodes in the same SCC!");
N.LowLink = -1;
}
RefSCC &RC = *Result[SCCNumber];
int SCCIndex = RC.SCCs.size();
RC.SCCs.push_back(C);
RC.SCCIndices[C] = SCCIndex;
C->OuterRefSCC = &RC;
}
G = nullptr;
SCCs.clear();
SCCIndices.clear();
#ifdef EXPENSIVE_CHECKS
for (RefSCC *RC : Result)
RC->verify();
#endif
return Result;
}
void LazyCallGraph::RefSCC::insertTrivialCallEdge(Node &SourceN,
Node &TargetN) {
#ifdef EXPENSIVE_CHECKS
auto ExitVerifier = make_scope_exit([this] { verify(); });
SCC &SourceC = *G->lookupSCC(SourceN);
SCC &TargetC = *G->lookupSCC(TargetN);
if (&SourceC != &TargetC)
assert(SourceC.isAncestorOf(TargetC) &&
"Call edge is not trivial in the SCC graph!");
#endif
auto InsertResult =
SourceN->EdgeIndexMap.insert({&TargetN, SourceN->Edges.size()});
if (!InsertResult.second) {
Edge &E = SourceN->Edges[InsertResult.first->second];
if (E.isCall())
return; E.setKind(Edge::Call);
} else {
SourceN->Edges.emplace_back(TargetN, Edge::Call);
}
}
void LazyCallGraph::RefSCC::insertTrivialRefEdge(Node &SourceN, Node &TargetN) {
#ifdef EXPENSIVE_CHECKS
auto ExitVerifier = make_scope_exit([this] { verify(); });
RefSCC &SourceRC = *G->lookupRefSCC(SourceN);
RefSCC &TargetRC = *G->lookupRefSCC(TargetN);
if (&SourceRC != &TargetRC)
assert(SourceRC.isAncestorOf(TargetRC) &&
"Ref edge is not trivial in the RefSCC graph!");
#endif
auto InsertResult =
SourceN->EdgeIndexMap.insert({&TargetN, SourceN->Edges.size()});
if (!InsertResult.second)
return;
SourceN->Edges.emplace_back(TargetN, Edge::Ref);
}
void LazyCallGraph::RefSCC::replaceNodeFunction(Node &N, Function &NewF) {
Function &OldF = N.getFunction();
#ifdef EXPENSIVE_CHECKS
auto ExitVerifier = make_scope_exit([this] { verify(); });
assert(G->lookupRefSCC(N) == this &&
"Cannot replace the function of a node outside this RefSCC.");
assert(G->NodeMap.find(&NewF) == G->NodeMap.end() &&
"Must not have already walked the new function!'");
assert(&OldF != &NewF && "Cannot replace a function with itself!");
assert(OldF.use_empty() &&
"Must have moved all uses from the old function to the new!");
#endif
N.replaceFunction(NewF);
G->NodeMap.erase(&OldF);
G->NodeMap[&NewF] = &N;
}
void LazyCallGraph::insertEdge(Node &SourceN, Node &TargetN, Edge::Kind EK) {
assert(SCCMap.empty() &&
"This method cannot be called after SCCs have been formed!");
return SourceN->insertEdgeInternal(TargetN, EK);
}
void LazyCallGraph::removeEdge(Node &SourceN, Node &TargetN) {
assert(SCCMap.empty() &&
"This method cannot be called after SCCs have been formed!");
bool Removed = SourceN->removeEdgeInternal(TargetN);
(void)Removed;
assert(Removed && "Target not in the edge set for this caller?");
}
void LazyCallGraph::removeDeadFunction(Function &F) {
assert(F.hasZeroLiveUses() &&
"This routine should only be called on trivially dead functions!");
assert(!isLibFunction(F) &&
"Must not remove lib functions from the call graph!");
auto NI = NodeMap.find(&F);
if (NI == NodeMap.end())
return;
Node &N = *NI->second;
NodeMap.erase(NI);
EntryEdges.removeEdgeInternal(N);
auto CI = SCCMap.find(&N);
assert(CI != SCCMap.end() &&
"Tried to remove a node without an SCC after DFS walk started!");
SCC &C = *CI->second;
SCCMap.erase(CI);
RefSCC &RC = C.getOuterRefSCC();
assert(C.size() == 1 && "Dead functions must be in a singular SCC");
assert(RC.size() == 1 && "Dead functions must be in a singular RefSCC");
N.clear();
N.G = nullptr;
N.F = nullptr;
C.clear();
RC.clear();
RC.G = nullptr;
}
static LazyCallGraph::Edge::Kind getEdgeKind(Function &OriginalFunction,
Function &NewFunction) {
#ifndef NDEBUG
SmallVector<Constant *, 16> Worklist;
SmallPtrSet<Constant *, 16> Visited;
#endif
for (Instruction &I : instructions(OriginalFunction)) {
if (auto *CB = dyn_cast<CallBase>(&I)) {
if (Function *Callee = CB->getCalledFunction()) {
if (Callee == &NewFunction)
return LazyCallGraph::Edge::Kind::Call;
}
}
#ifndef NDEBUG
for (Value *Op : I.operand_values()) {
if (Constant *C = dyn_cast<Constant>(Op)) {
if (Visited.insert(C).second)
Worklist.push_back(C);
}
}
#endif
}
#ifndef NDEBUG
bool FoundNewFunction = false;
LazyCallGraph::visitReferences(Worklist, Visited, [&](Function &F) {
if (&F == &NewFunction)
FoundNewFunction = true;
});
assert(FoundNewFunction && "No edge from original function to new function");
#endif
return LazyCallGraph::Edge::Kind::Ref;
}
void LazyCallGraph::addSplitFunction(Function &OriginalFunction,
Function &NewFunction) {
assert(lookup(OriginalFunction) &&
"Original function's node should already exist");
Node &OriginalN = get(OriginalFunction);
SCC *OriginalC = lookupSCC(OriginalN);
RefSCC *OriginalRC = lookupRefSCC(OriginalN);
#ifdef EXPENSIVE_CHECKS
OriginalRC->verify();
auto VerifyOnExit = make_scope_exit([&]() { OriginalRC->verify(); });
#endif
assert(!lookup(NewFunction) &&
"New function's node should not already exist");
Node &NewN = initNode(NewFunction);
Edge::Kind EK = getEdgeKind(OriginalFunction, NewFunction);
SCC *NewC = nullptr;
for (Edge &E : *NewN) {
Node &EN = E.getNode();
if (EK == Edge::Kind::Call && E.isCall() && lookupSCC(EN) == OriginalC) {
NewC = OriginalC;
NewC->Nodes.push_back(&NewN);
break;
}
}
if (!NewC) {
for (Edge &E : *NewN) {
Node &EN = E.getNode();
if (lookupRefSCC(EN) == OriginalRC) {
RefSCC *NewRC = OriginalRC;
NewC = createSCC(*NewRC, SmallVector<Node *, 1>({&NewN}));
int InsertIndex = EK == Edge::Kind::Call ? NewRC->SCCIndices[OriginalC]
: NewRC->SCCIndices.size();
NewRC->SCCs.insert(NewRC->SCCs.begin() + InsertIndex, NewC);
for (int I = InsertIndex, Size = NewRC->SCCs.size(); I < Size; ++I)
NewRC->SCCIndices[NewRC->SCCs[I]] = I;
break;
}
}
}
if (!NewC) {
RefSCC *NewRC = createRefSCC(*this);
NewC = createSCC(*NewRC, SmallVector<Node *, 1>({&NewN}));
NewRC->SCCIndices[NewC] = 0;
NewRC->SCCs.push_back(NewC);
auto OriginalRCIndex = RefSCCIndices.find(OriginalRC)->second;
PostOrderRefSCCs.insert(PostOrderRefSCCs.begin() + OriginalRCIndex, NewRC);
for (int I = OriginalRCIndex, Size = PostOrderRefSCCs.size(); I < Size; ++I)
RefSCCIndices[PostOrderRefSCCs[I]] = I;
}
SCCMap[&NewN] = NewC;
OriginalN->insertEdgeInternal(NewN, EK);
}
void LazyCallGraph::addSplitRefRecursiveFunctions(
Function &OriginalFunction, ArrayRef<Function *> NewFunctions) {
assert(!NewFunctions.empty() && "Can't add zero functions");
assert(lookup(OriginalFunction) &&
"Original function's node should already exist");
Node &OriginalN = get(OriginalFunction);
RefSCC *OriginalRC = lookupRefSCC(OriginalN);
#ifdef EXPENSIVE_CHECKS
OriginalRC->verify();
auto VerifyOnExit = make_scope_exit([&]() {
OriginalRC->verify();
for (Function *NewFunction : NewFunctions)
lookupRefSCC(get(*NewFunction))->verify();
});
#endif
bool ExistsRefToOriginalRefSCC = false;
for (Function *NewFunction : NewFunctions) {
Node &NewN = initNode(*NewFunction);
OriginalN->insertEdgeInternal(NewN, Edge::Kind::Ref);
for (Edge &E : *NewN) {
if (lookupRefSCC(E.getNode()) == OriginalRC) {
ExistsRefToOriginalRefSCC = true;
break;
}
}
}
RefSCC *NewRC;
if (ExistsRefToOriginalRefSCC) {
NewRC = OriginalRC;
} else {
NewRC = createRefSCC(*this);
auto OriginalRCIndex = RefSCCIndices.find(OriginalRC)->second;
PostOrderRefSCCs.insert(PostOrderRefSCCs.begin() + OriginalRCIndex, NewRC);
for (int I = OriginalRCIndex, Size = PostOrderRefSCCs.size(); I < Size; ++I)
RefSCCIndices[PostOrderRefSCCs[I]] = I;
}
for (Function *NewFunction : NewFunctions) {
Node &NewN = get(*NewFunction);
SCC *NewC = createSCC(*NewRC, SmallVector<Node *, 1>({&NewN}));
auto Index = NewRC->SCCIndices.size();
NewRC->SCCIndices[NewC] = Index;
NewRC->SCCs.push_back(NewC);
SCCMap[&NewN] = NewC;
}
#ifndef NDEBUG
for (Function *F1 : NewFunctions) {
assert(getEdgeKind(OriginalFunction, *F1) == Edge::Kind::Ref &&
"Expected ref edges from original function to every new function");
Node &N1 = get(*F1);
for (Function *F2 : NewFunctions) {
if (F1 == F2)
continue;
Node &N2 = get(*F2);
assert(!N1->lookup(N2)->isCall() &&
"Edges between new functions must be ref edges");
}
}
#endif
}
LazyCallGraph::Node &LazyCallGraph::insertInto(Function &F, Node *&MappedN) {
return *new (MappedN = BPA.Allocate()) Node(*this, F);
}
void LazyCallGraph::updateGraphPtrs() {
for (auto &FunctionNodePair : NodeMap)
FunctionNodePair.second->G = this;
for (auto *RC : PostOrderRefSCCs)
RC->G = this;
}
LazyCallGraph::Node &LazyCallGraph::initNode(Function &F) {
Node &N = get(F);
N.DFSNumber = N.LowLink = -1;
N.populate();
NodeMap[&F] = &N;
return N;
}
template <typename RootsT, typename GetBeginT, typename GetEndT,
typename GetNodeT, typename FormSCCCallbackT>
void LazyCallGraph::buildGenericSCCs(RootsT &&Roots, GetBeginT &&GetBegin,
GetEndT &&GetEnd, GetNodeT &&GetNode,
FormSCCCallbackT &&FormSCC) {
using EdgeItT = decltype(GetBegin(std::declval<Node &>()));
SmallVector<std::pair<Node *, EdgeItT>, 16> DFSStack;
SmallVector<Node *, 16> PendingSCCStack;
for (Node *RootN : Roots) {
assert(DFSStack.empty() &&
"Cannot begin a new root with a non-empty DFS stack!");
assert(PendingSCCStack.empty() &&
"Cannot begin a new root with pending nodes for an SCC!");
if (RootN->DFSNumber != 0) {
assert(RootN->DFSNumber == -1 &&
"Shouldn't have any mid-DFS root nodes!");
continue;
}
RootN->DFSNumber = RootN->LowLink = 1;
int NextDFSNumber = 2;
DFSStack.push_back({RootN, GetBegin(*RootN)});
do {
Node *N;
EdgeItT I;
std::tie(N, I) = DFSStack.pop_back_val();
auto E = GetEnd(*N);
while (I != E) {
Node &ChildN = GetNode(I);
if (ChildN.DFSNumber == 0) {
DFSStack.push_back({N, I});
ChildN.DFSNumber = ChildN.LowLink = NextDFSNumber++;
N = &ChildN;
I = GetBegin(*N);
E = GetEnd(*N);
continue;
}
if (ChildN.DFSNumber == -1) {
++I;
continue;
}
assert(ChildN.LowLink > 0 && "Must have a positive low-link number!");
if (ChildN.LowLink < N->LowLink)
N->LowLink = ChildN.LowLink;
++I;
}
PendingSCCStack.push_back(N);
if (N->LowLink != N->DFSNumber)
continue;
int RootDFSNumber = N->DFSNumber;
auto SCCNodes = make_range(
PendingSCCStack.rbegin(),
find_if(reverse(PendingSCCStack), [RootDFSNumber](const Node *N) {
return N->DFSNumber < RootDFSNumber;
}));
FormSCC(SCCNodes);
PendingSCCStack.erase(SCCNodes.end().base(), PendingSCCStack.end());
} while (!DFSStack.empty());
}
}
void LazyCallGraph::buildSCCs(RefSCC &RC, node_stack_range Nodes) {
assert(RC.SCCs.empty() && "Already built SCCs!");
assert(RC.SCCIndices.empty() && "Already mapped SCC indices!");
for (Node *N : Nodes) {
assert(N->LowLink >= (*Nodes.begin())->LowLink &&
"We cannot have a low link in an SCC lower than its root on the "
"stack!");
N->DFSNumber = N->LowLink = 0;
}
buildGenericSCCs(
Nodes, [](Node &N) { return N->call_begin(); },
[](Node &N) { return N->call_end(); },
[](EdgeSequence::call_iterator I) -> Node & { return I->getNode(); },
[this, &RC](node_stack_range Nodes) {
RC.SCCs.push_back(createSCC(RC, Nodes));
for (Node &N : *RC.SCCs.back()) {
N.DFSNumber = N.LowLink = -1;
SCCMap[&N] = RC.SCCs.back();
}
});
for (int i = 0, Size = RC.SCCs.size(); i < Size; ++i)
RC.SCCIndices[RC.SCCs[i]] = i;
}
void LazyCallGraph::buildRefSCCs() {
if (EntryEdges.empty() || !PostOrderRefSCCs.empty())
return;
assert(RefSCCIndices.empty() && "Already mapped RefSCC indices!");
SmallVector<Node *, 16> Roots;
for (Edge &E : *this)
Roots.push_back(&E.getNode());
buildGenericSCCs(
Roots,
[](Node &N) {
N.populate();
return N->begin();
},
[](Node &N) { return N->end(); },
[](EdgeSequence::iterator I) -> Node & { return I->getNode(); },
[this](node_stack_range Nodes) {
RefSCC *NewRC = createRefSCC(*this);
buildSCCs(*NewRC, Nodes);
bool Inserted =
RefSCCIndices.insert({NewRC, PostOrderRefSCCs.size()}).second;
(void)Inserted;
assert(Inserted && "Cannot already have this RefSCC in the index map!");
PostOrderRefSCCs.push_back(NewRC);
#ifdef EXPENSIVE_CHECKS
NewRC->verify();
#endif
});
}
void LazyCallGraph::visitReferences(SmallVectorImpl<Constant *> &Worklist,
SmallPtrSetImpl<Constant *> &Visited,
function_ref<void(Function &)> Callback) {
while (!Worklist.empty()) {
Constant *C = Worklist.pop_back_val();
if (Function *F = dyn_cast<Function>(C)) {
if (!F->isDeclaration())
Callback(*F);
continue;
}
if (isa<BlockAddress>(C))
continue;
for (Value *Op : C->operand_values())
if (Visited.insert(cast<Constant>(Op)).second)
Worklist.push_back(cast<Constant>(Op));
}
}
AnalysisKey LazyCallGraphAnalysis::Key;
LazyCallGraphPrinterPass::LazyCallGraphPrinterPass(raw_ostream &OS) : OS(OS) {}
static void printNode(raw_ostream &OS, LazyCallGraph::Node &N) {
OS << " Edges in function: " << N.getFunction().getName() << "\n";
for (LazyCallGraph::Edge &E : N.populate())
OS << " " << (E.isCall() ? "call" : "ref ") << " -> "
<< E.getFunction().getName() << "\n";
OS << "\n";
}
static void printSCC(raw_ostream &OS, LazyCallGraph::SCC &C) {
OS << " SCC with " << C.size() << " functions:\n";
for (LazyCallGraph::Node &N : C)
OS << " " << N.getFunction().getName() << "\n";
}
static void printRefSCC(raw_ostream &OS, LazyCallGraph::RefSCC &C) {
OS << " RefSCC with " << C.size() << " call SCCs:\n";
for (LazyCallGraph::SCC &InnerC : C)
printSCC(OS, InnerC);
OS << "\n";
}
PreservedAnalyses LazyCallGraphPrinterPass::run(Module &M,
ModuleAnalysisManager &AM) {
LazyCallGraph &G = AM.getResult<LazyCallGraphAnalysis>(M);
OS << "Printing the call graph for module: " << M.getModuleIdentifier()
<< "\n\n";
for (Function &F : M)
printNode(OS, G.get(F));
G.buildRefSCCs();
for (LazyCallGraph::RefSCC &C : G.postorder_ref_sccs())
printRefSCC(OS, C);
return PreservedAnalyses::all();
}
LazyCallGraphDOTPrinterPass::LazyCallGraphDOTPrinterPass(raw_ostream &OS)
: OS(OS) {}
static void printNodeDOT(raw_ostream &OS, LazyCallGraph::Node &N) {
std::string Name =
"\"" + DOT::EscapeString(std::string(N.getFunction().getName())) + "\"";
for (LazyCallGraph::Edge &E : N.populate()) {
OS << " " << Name << " -> \""
<< DOT::EscapeString(std::string(E.getFunction().getName())) << "\"";
if (!E.isCall()) OS << " [style=dashed,label=\"ref\"]";
OS << ";\n";
}
OS << "\n";
}
PreservedAnalyses LazyCallGraphDOTPrinterPass::run(Module &M,
ModuleAnalysisManager &AM) {
LazyCallGraph &G = AM.getResult<LazyCallGraphAnalysis>(M);
OS << "digraph \"" << DOT::EscapeString(M.getModuleIdentifier()) << "\" {\n";
for (Function &F : M)
printNodeDOT(OS, G.get(F));
OS << "}\n";
return PreservedAnalyses::all();
}