18 #include "llvm/Config/llvm-config.h" 40 #define DEBUG_TYPE "lcg" 42 void LazyCallGraph::EdgeSequence::insertEdgeInternal(Node &TargetN,
44 EdgeIndexMap.insert({&TargetN, Edges.
size()});
48 void LazyCallGraph::EdgeSequence::setEdgeKind(Node &TargetN,
Edge::Kind EK) {
49 Edges[EdgeIndexMap.find(&TargetN)->second].setKind(EK);
52 bool LazyCallGraph::EdgeSequence::removeEdgeInternal(Node &TargetN) {
53 auto IndexMapI = EdgeIndexMap.find(&TargetN);
54 if (IndexMapI == EdgeIndexMap.end())
57 Edges[IndexMapI->second] = Edge();
58 EdgeIndexMap.erase(IndexMapI);
65 if (!EdgeIndexMap.
insert({&N, Edges.size()}).second)
73 assert(!Edges &&
"Must not have already populated the edges for this node!");
76 <<
"' to the graph.\n");
78 Edges = EdgeSequence();
104 if (!
Callee->isDeclaration())
111 for (
Value *
Op :
I.operand_values())
121 addEdge(Edges->Edges, Edges->EdgeIndexMap,
G->get(F),
127 for (
auto *F :
G->LibFunctions)
128 if (!Visited.
count(F))
129 addEdge(Edges->Edges, Edges->EdgeIndexMap,
G->get(*F),
135 void LazyCallGraph::Node::replaceFunction(
Function &NewF) {
136 assert(
F != &NewF &&
"Must not replace a function with itself!");
140 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 142 dbgs() << *
this <<
'\n';
158 if (
F.isDeclaration())
164 LibFunctions.insert(&
F);
166 if (
F.hasLocalLinkage())
172 <<
"' to entry set of the graph.\n");
178 for (
auto &A : M.aliases()) {
179 if (A.hasLocalLinkage())
181 if (
Function*
F = dyn_cast<Function>(A.getAliasee())) {
183 <<
"' with alias '" << A.getName()
184 <<
"' to entry set of the graph.\n");
193 if (GV.hasInitializer())
198 dbgs() <<
" Adding functions referenced by global initializers to the " 201 addEdge(EntryEdges.Edges, EntryEdges.EdgeIndexMap,
get(F),
207 : BPA(
std::move(
G.BPA)), NodeMap(
std::move(
G.NodeMap)),
208 EntryEdges(
std::move(
G.EntryEdges)), SCCBPA(
std::move(
G.SCCBPA)),
209 SCCMap(
std::move(
G.SCCMap)),
210 LibFunctions(
std::move(
G.LibFunctions)) {
215 BPA = std::move(
G.BPA);
216 NodeMap = std::move(
G.NodeMap);
217 EntryEdges = std::move(
G.EntryEdges);
218 SCCBPA = std::move(
G.SCCBPA);
219 SCCMap = std::move(
G.SCCMap);
220 LibFunctions = std::move(
G.LibFunctions);
225 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 227 dbgs() << *
this <<
'\n';
232 void LazyCallGraph::SCC::verify() {
233 assert(OuterRefSCC &&
"Can't have a null RefSCC!");
234 assert(!Nodes.empty() &&
"Can't have an empty SCC!");
236 for (
Node *
N : Nodes) {
237 assert(
N &&
"Can't have a null node!");
238 assert(OuterRefSCC->G->lookupSCC(*
N) ==
this &&
239 "Node does not map to this SCC!");
241 "Must set DFS numbers to -1 when adding a node to an SCC!");
243 "Must set low link to -1 when adding a node to an SCC!");
245 assert(
E.getNode().isPopulated() &&
"Can't have an unpopulated node!");
254 for (
Node &
N : *
this)
256 if (OuterRefSCC->G->lookupSCC(
E.getNode()) == &C)
264 if (
this == &TargetC)
277 for (
Edge &
E :
N->calls()) {
283 if (CalleeC == &TargetC)
288 if (Visited.
insert(CalleeC).second)
291 }
while (!Worklist.
empty());
299 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 301 dbgs() << *
this <<
'\n';
306 void LazyCallGraph::RefSCC::verify() {
307 assert(G &&
"Can't have a null graph!");
308 assert(!SCCs.empty() &&
"Can't have an empty SCC!");
312 for (
SCC *
C : SCCs) {
313 assert(
C &&
"Can't have a null SCC!");
315 assert(&
C->getOuterRefSCC() ==
this &&
316 "SCC doesn't think it is inside this RefSCC!");
317 bool Inserted = SCCSet.insert(
C).second;
318 assert(Inserted &&
"Found a duplicate SCC!");
319 auto IndexIt = SCCIndices.find(
C);
320 assert(IndexIt != SCCIndices.end() &&
321 "Found an SCC that doesn't have an index!");
325 for (
auto &SCCIndexPair : SCCIndices) {
326 SCC *
C = SCCIndexPair.first;
327 int i = SCCIndexPair.second;
328 assert(C &&
"Can't have a null SCC in the indices!");
329 assert(SCCSet.count(C) &&
"Found an index for an SCC not in the RefSCC!");
330 assert(SCCs[i] == C &&
"Index doesn't point to SCC!");
334 for (
int i = 0,
Size = SCCs.size(); i <
Size; ++i) {
335 SCC &SourceSCC = *SCCs[i];
336 for (
Node &
N : SourceSCC)
342 assert(SCCIndices.find(&TargetSCC)->second <= i &&
343 "Edge between SCCs violates post-order relationship.");
378 for (
SCC &
C : DescendantRC)
384 if (!ChildRC || !Visited.
insert(ChildRC).second)
388 }
while (!Worklist.
empty());
455 template <
typename SCCT,
typename PostorderSequenceT,
typename SCCIndexMapT,
456 typename ComputeSourceConnectedSetCallableT,
457 typename ComputeTargetConnectedSetCallableT>
460 SCCT &SourceSCC, SCCT &TargetSCC, PostorderSequenceT &SCCs,
461 SCCIndexMapT &SCCIndices,
462 ComputeSourceConnectedSetCallableT ComputeSourceConnectedSet,
463 ComputeTargetConnectedSetCallableT ComputeTargetConnectedSet) {
464 int SourceIdx = SCCIndices[&SourceSCC];
465 int TargetIdx = SCCIndices[&TargetSCC];
466 assert(SourceIdx < TargetIdx &&
"Cannot have equal indices here!");
471 ComputeSourceConnectedSet(ConnectedSet);
476 auto SourceI = std::stable_partition(
477 SCCs.begin() + SourceIdx, SCCs.begin() + TargetIdx + 1,
478 [&ConnectedSet](SCCT *
C) {
return !ConnectedSet.
count(
C); });
479 for (
int i = SourceIdx,
e = TargetIdx + 1; i <
e; ++i)
480 SCCIndices.find(SCCs[i])->second = i;
484 if (!ConnectedSet.
count(&TargetSCC)) {
485 assert(SourceI > (SCCs.begin() + SourceIdx) &&
486 "Must have moved the source to fix the post-order.");
487 assert(*std::prev(SourceI) == &TargetSCC &&
488 "Last SCC to move should have bene the target.");
492 return make_range(std::prev(SourceI), std::prev(SourceI));
495 assert(SCCs[TargetIdx] == &TargetSCC &&
496 "Should not have moved target if connected!");
497 SourceIdx = SourceI - SCCs.begin();
498 assert(SCCs[SourceIdx] == &SourceSCC &&
499 "Bad updated index computation for the source SCC!");
505 if (SourceIdx + 1 < TargetIdx) {
506 ConnectedSet.
clear();
507 ComputeTargetConnectedSet(ConnectedSet);
511 auto TargetI = std::stable_partition(
512 SCCs.begin() + SourceIdx + 1, SCCs.begin() + TargetIdx + 1,
513 [&ConnectedSet](SCCT *
C) {
return ConnectedSet.
count(
C); });
514 for (
int i = SourceIdx + 1, e = TargetIdx + 1; i <
e; ++i)
515 SCCIndices.find(SCCs[i])->second = i;
516 TargetIdx = std::prev(TargetI) - SCCs.begin();
517 assert(SCCs[TargetIdx] == &TargetSCC &&
518 "Should always end with the target!");
525 return make_range(SCCs.begin() + SourceIdx, SCCs.begin() + TargetIdx);
532 assert(!(*SourceN)[TargetN].isCall() &&
"Must start with a ref edge!");
547 if (&SourceSCC == &TargetSCC) {
558 int SourceIdx = SCCIndices[&SourceSCC];
559 int TargetIdx = SCCIndices[&TargetSCC];
560 if (TargetIdx < SourceIdx) {
572 ConnectedSet.insert(&SourceSCC);
573 auto IsConnected = [&](
SCC &
C) {
575 for (
Edge &
E :
N->calls())
576 if (ConnectedSet.count(G->
lookupSCC(
E.getNode())))
583 make_range(SCCs.begin() + SourceIdx + 1, SCCs.begin() + TargetIdx + 1))
585 ConnectedSet.insert(
C);
598 ConnectedSet.insert(&TargetSCC);
611 if (SCCIndices.find(&EdgeC)->second <= SourceIdx)
615 if (ConnectedSet.insert(&EdgeC).second)
618 }
while (!Worklist.
empty());
626 SourceSCC, TargetSCC, SCCs, SCCIndices, ComputeSourceConnectedSet,
627 ComputeTargetConnectedSet);
631 MergeCB(
makeArrayRef(MergeRange.begin(), MergeRange.end()));
635 if (MergeRange.empty()) {
653 for (
SCC *
C : MergeRange) {
655 "We merge *into* the target and shouldn't process it here!");
657 TargetSCC.Nodes.append(
C->Nodes.begin(),
C->Nodes.end());
659 G->SCCMap[
N] = &TargetSCC;
666 int IndexOffset = MergeRange.end() - MergeRange.begin();
667 auto EraseEnd = SCCs.erase(MergeRange.begin(), MergeRange.end());
669 SCCIndices[
C] -= IndexOffset;
680 assert((*SourceN)[TargetN].isCall() &&
"Must start with a call edge!");
690 "Source must be in this RefSCC.");
692 "Target must be in this RefSCC.");
694 "Source and Target must be in separate SCCs for this to be trivial!");
697 SourceN->setEdgeKind(TargetN,
Edge::Ref);
702 assert((*SourceN)[TargetN].isCall() &&
"Must start with a call edge!");
712 "Source must be in this RefSCC.");
714 "Target must be in this RefSCC.");
717 assert(G->
lookupSCC(SourceN) == &TargetSCC &&
"Source and Target must be in " 718 "the same SCC to require the " 722 SourceN->setEdgeKind(TargetN,
Edge::Ref);
736 SCC &OldSCC = TargetSCC;
743 Worklist.
swap(OldSCC.Nodes);
744 for (
Node *
N : Worklist) {
745 N->DFSNumber =
N->LowLink = 0;
757 TargetN.DFSNumber = TargetN.LowLink = -1;
758 OldSCC.Nodes.push_back(&TargetN);
759 G->SCCMap[&TargetN] = &OldSCC;
762 for (
Node *RootN : Worklist) {
764 "Cannot begin a new root with a non-empty DFS stack!");
766 "Cannot begin a new root with pending nodes for an SCC!");
769 if (RootN->DFSNumber != 0) {
770 assert(RootN->DFSNumber == -1 &&
771 "Shouldn't have any mid-DFS root nodes!");
775 RootN->DFSNumber = RootN->LowLink = 1;
776 int NextDFSNumber = 2;
778 DFSStack.
push_back({RootN, (*RootN)->call_begin()});
783 auto E = (*N)->call_end();
785 Node &ChildN = I->getNode();
786 if (ChildN.DFSNumber == 0) {
791 assert(!G->SCCMap.count(&ChildN) &&
792 "Found a node with 0 DFS number but already in an SCC!");
793 ChildN.DFSNumber = ChildN.LowLink = NextDFSNumber++;
795 I = (*N)->call_begin();
796 E = (*N)->call_end();
801 if (ChildN.DFSNumber == -1) {
807 int OldSize = OldSCC.
size();
808 OldSCC.Nodes.push_back(N);
809 OldSCC.Nodes.append(PendingSCCStack.
begin(), PendingSCCStack.
end());
810 PendingSCCStack.
clear();
811 while (!DFSStack.
empty())
814 N.DFSNumber = N.LowLink = -1;
815 G->SCCMap[&
N] = &OldSCC;
829 assert(ChildN.LowLink > 0 &&
"Must have a positive low-link number!");
830 if (ChildN.LowLink < N->LowLink)
831 N->LowLink = ChildN.LowLink;
846 if (N->LowLink != N->DFSNumber)
851 int RootDFSNumber = N->DFSNumber;
857 return N->DFSNumber < RootDFSNumber;
862 NewSCCs.
push_back(G->createSCC(*
this, SCCNodes));
864 N.DFSNumber = N.LowLink = -1;
865 G->SCCMap[&
N] = NewSCCs.
back();
867 PendingSCCStack.
erase(SCCNodes.end().base(), PendingSCCStack.
end());
868 }
while (!DFSStack.
empty());
875 int OldIdx = SCCIndices[&OldSCC];
876 SCCs.insert(SCCs.begin() + OldIdx, NewSCCs.
begin(), NewSCCs.
end());
880 for (
int Idx = OldIdx,
Size = SCCs.size(); Idx <
Size; ++Idx)
881 SCCIndices[SCCs[Idx]] = Idx;
884 SCCs.begin() + OldIdx + NewSCCs.
size());
889 assert(!(*SourceN)[TargetN].isCall() &&
"Must start with a ref edge!");
893 "Target must not be in this RefSCC.");
894 #ifdef EXPENSIVE_CHECKS 896 "Target must be a descendant of the Source.");
911 assert((*SourceN)[TargetN].isCall() &&
"Must start with a call edge!");
915 "Target must not be in this RefSCC.");
916 #ifdef EXPENSIVE_CHECKS 918 "Target must be a descendant of the Source.");
923 SourceN->setEdgeKind(TargetN,
Edge::Ref);
936 SourceN->insertEdgeInternal(TargetN,
Edge::Ref);
947 SourceN->insertEdgeInternal(TargetN, EK);
952 "Target must not be in this RefSCC.");
953 #ifdef EXPENSIVE_CHECKS 955 "Target must be a descendant of the Source.");
968 assert(&SourceC !=
this &&
"Source must not be in this RefSCC.");
969 #ifdef EXPENSIVE_CHECKS 970 assert(SourceC.isDescendantOf(*
this) &&
971 "Source must be a descendant of the Target.");
983 int SourceIdx = G->RefSCCIndices[&SourceC];
984 int TargetIdx = G->RefSCCIndices[
this];
985 assert(SourceIdx < TargetIdx &&
986 "Postorder list doesn't see edge as incoming!");
996 Set.insert(&SourceC);
997 auto IsConnected = [&](
RefSCC &RC) {
1008 G->PostOrderRefSCCs.begin() + TargetIdx + 1))
1009 if (IsConnected(*
C))
1027 if (G->getRefSCCIndex(EdgeRC) <= SourceIdx)
1031 if (Set.insert(&EdgeRC).second)
1034 }
while (!Worklist.
empty());
1043 SourceC, *
this, G->PostOrderRefSCCs, G->RefSCCIndices,
1044 ComputeSourceConnectedSet, ComputeTargetConnectedSet);
1057 for (
RefSCC *RC : MergeRange) {
1058 assert(RC !=
this &&
"We're merging into the target RefSCC, so it " 1059 "shouldn't be in the range.");
1065 for (
SCC &InnerC : *RC) {
1066 InnerC.OuterRefSCC =
this;
1067 SCCIndices[&InnerC] = SCCIndex++;
1068 for (
Node &
N : InnerC)
1069 G->SCCMap[&
N] = &InnerC;
1074 if (MergedSCCs.
empty())
1075 MergedSCCs = std::move(RC->SCCs);
1077 MergedSCCs.
append(RC->SCCs.begin(), RC->SCCs.end());
1079 DeletedRefSCCs.push_back(RC);
1083 for (
SCC &InnerC : *
this)
1084 SCCIndices[&InnerC] = SCCIndex++;
1085 MergedSCCs.
append(SCCs.begin(), SCCs.end());
1086 SCCs = std::move(MergedSCCs);
1089 for (
RefSCC *RC : MergeRange)
1090 G->RefSCCIndices.erase(RC);
1091 int IndexOffset = MergeRange.end() - MergeRange.begin();
1093 G->PostOrderRefSCCs.erase(MergeRange.begin(), MergeRange.end());
1095 G->RefSCCIndices[RC] -= IndexOffset;
1099 SourceN->insertEdgeInternal(TargetN,
Edge::Ref);
1105 return DeletedRefSCCs;
1110 "The source must be a member of this RefSCC.");
1112 "The target must not be a member of this RefSCC");
1122 bool Removed = SourceN->removeEdgeInternal(TargetN);
1124 assert(Removed &&
"Target not in the edge set for this caller?");
1147 for (
Node *TargetN : TargetNs) {
1148 assert(!(*SourceN)[*TargetN].isCall() &&
1149 "Cannot remove a call edge, it must first be made a ref edge");
1151 bool Removed = SourceN->removeEdgeInternal(*TargetN);
1153 assert(Removed &&
"Target not in the edge set for this caller?");
1158 [&](
Node *TargetN) {
return &SourceN == TargetN; }))
1165 return G->
lookupSCC(*TargetN) == &SourceC;
1175 int PostOrderNumber = 0;
1180 for (
SCC *
C : SCCs) {
1182 N.DFSNumber =
N.LowLink = 0;
1184 Worklist.
append(C->Nodes.begin(), C->Nodes.end());
1190 const int NumRefSCCNodes = Worklist.
size();
1196 "Cannot begin a new root with a non-empty DFS stack!");
1198 "Cannot begin a new root with pending nodes for an SCC!");
1202 if (RootN->DFSNumber != 0) {
1203 assert(RootN->DFSNumber == -1 &&
1204 "Shouldn't have any mid-DFS root nodes!");
1208 RootN->DFSNumber = RootN->LowLink = 1;
1209 int NextDFSNumber = 2;
1211 DFSStack.
push_back({RootN, (*RootN)->begin()});
1216 auto E = (*N)->end();
1218 assert(N->DFSNumber != 0 &&
"We should always assign a DFS number " 1219 "before processing a node.");
1222 Node &ChildN = I->getNode();
1223 if (ChildN.DFSNumber == 0) {
1230 ChildN.LowLink = ChildN.DFSNumber = NextDFSNumber++;
1232 I = ChildN->
begin();
1236 if (ChildN.DFSNumber == -1) {
1245 assert(ChildN.LowLink != 0 &&
1246 "Low-link must not be zero with a non-zero DFS number.");
1247 if (ChildN.LowLink >= 0 && ChildN.LowLink < N->LowLink)
1248 N->LowLink = ChildN.LowLink;
1258 if (N->LowLink != N->DFSNumber) {
1260 "We never found a viable root for a RefSCC to pop off!");
1265 int RefSCCNumber = PostOrderNumber++;
1266 int RootDFSNumber = N->DFSNumber;
1272 if (N->DFSNumber < RootDFSNumber)
1280 N->LowLink = RefSCCNumber;
1283 auto RefSCCNodes =
make_range(StackRI.base(), PendingRefSCCStack.
end());
1289 if (
llvm::size(RefSCCNodes) == NumRefSCCNodes) {
1291 for (
Node *N : RefSCCNodes)
1299 PendingRefSCCStack.
erase(RefSCCNodes.begin(), PendingRefSCCStack.
end());
1300 }
while (!DFSStack.
empty());
1302 assert(DFSStack.
empty() &&
"Didn't flush the entire DFS stack!");
1303 assert(PendingRefSCCStack.
empty() &&
"Didn't flush all pending nodes!");
1304 }
while (!Worklist.
empty());
1306 assert(PostOrderNumber > 1 &&
1307 "Should never finish the DFS when the existing RefSCC remains valid!");
1313 for (
int i = 0; i < PostOrderNumber; ++i)
1323 int Idx = G->getRefSCCIndex(*
this);
1324 G->PostOrderRefSCCs.erase(G->PostOrderRefSCCs.begin() + Idx);
1325 G->PostOrderRefSCCs.insert(G->PostOrderRefSCCs.begin() + Idx, Result.
begin(),
1327 for (
int i : seq<int>(Idx, G->PostOrderRefSCCs.size()))
1328 G->RefSCCIndices[G->PostOrderRefSCCs[i]] = i;
1330 for (
SCC *
C : SCCs) {
1332 int SCCNumber =
C->begin()->LowLink;
1336 assert(
N.LowLink == SCCNumber &&
1337 "Cannot have different numbers for nodes in the same SCC!");
1341 RefSCC &RC = *Result[SCCNumber];
1342 int SCCIndex = RC.SCCs.size();
1343 RC.SCCs.push_back(C);
1344 RC.SCCIndices[
C] = SCCIndex;
1345 C->OuterRefSCC = &RC;
1356 for (
RefSCC *RC : Result)
1364 void LazyCallGraph::RefSCC::handleTrivialEdgeInsertion(
Node &SourceN,
1372 if (&TargetRC ==
this)
1375 #ifdef EXPENSIVE_CHECKS 1376 assert(TargetRC.isDescendantOf(*
this) &&
1377 "Target must be a descendant of the Source.");
1387 #ifdef EXPENSIVE_CHECKS 1392 if (&SourceC != &TargetC)
1393 assert(SourceC.isAncestorOf(TargetC) &&
1394 "Call edge is not trivial in the SCC graph!");
1395 #endif // EXPENSIVE_CHECKS 1400 SourceN->EdgeIndexMap.insert({&TargetN, SourceN->Edges.
size()});
1401 if (!InsertResult.second) {
1403 Edge &
E = SourceN->Edges[InsertResult.first->second];
1413 handleTrivialEdgeInsertion(SourceN, TargetN);
1421 #ifdef EXPENSIVE_CHECKS 1425 if (&SourceRC != &TargetRC)
1426 assert(SourceRC.isAncestorOf(TargetRC) &&
1427 "Ref edge is not trivial in the RefSCC graph!");
1428 #endif // EXPENSIVE_CHECKS 1433 SourceN->EdgeIndexMap.insert({&TargetN, SourceN->Edges.
size()});
1434 if (!InsertResult.second)
1442 handleTrivialEdgeInsertion(SourceN, TargetN);
1453 "Cannot replace the function of a node outside this RefSCC.");
1455 assert(G->NodeMap.find(&NewF) == G->NodeMap.end() &&
1456 "Must not have already walked the new function!'");
1464 assert(&OldF != &NewF &&
"Cannot replace a function with itself!");
1466 "Must have moved all uses from the old function to the new!");
1469 N.replaceFunction(NewF);
1472 G->NodeMap.erase(&OldF);
1473 G->NodeMap[&NewF] = &
N;
1478 "This method cannot be called after SCCs have been formed!");
1480 return SourceN->insertEdgeInternal(TargetN, EK);
1485 "This method cannot be called after SCCs have been formed!");
1487 bool Removed = SourceN->removeEdgeInternal(TargetN);
1489 assert(Removed &&
"Target not in the edge set for this caller?");
1496 "This routine should only be called on trivially dead functions!");
1501 "Must not remove lib functions from the call graph!");
1503 auto NI = NodeMap.find(&F);
1504 if (NI == NodeMap.end())
1508 Node &
N = *NI->second;
1512 EntryEdges.removeEdgeInternal(N);
1514 if (SCCMap.empty()) {
1523 auto CI = SCCMap.find(&N);
1524 assert(CI != SCCMap.end() &&
1525 "Tried to remove a node without an SCC after DFS walk started!");
1526 SCC &
C = *CI->second;
1528 RefSCC &RC = C.getOuterRefSCC();
1533 assert(C.size() == 1 &&
"Dead functions must be in a singular SCC");
1534 assert(RC.
size() == 1 &&
"Dead functions must be in a singular RefSCC");
1536 auto RCIndexI = RefSCCIndices.find(&RC);
1537 int RCIndex = RCIndexI->second;
1538 PostOrderRefSCCs.erase(PostOrderRefSCCs.begin() + RCIndex);
1539 RefSCCIndices.erase(RCIndexI);
1540 for (
int i = RCIndex,
Size = PostOrderRefSCCs.size(); i <
Size; ++i)
1541 RefSCCIndices[PostOrderRefSCCs[i]] = i;
1557 return *
new (MappedN = BPA.Allocate())
Node(*
this, F);
1560 void LazyCallGraph::updateGraphPtrs() {
1563 for (
auto &FunctionNodePair : NodeMap)
1564 FunctionNodePair.second->G =
this;
1566 for (
auto *RC : PostOrderRefSCCs)
1570 template <
typename RootsT,
typename GetBeginT,
typename GetEndT,
1571 typename GetNodeT,
typename FormSCCCallbackT>
1572 void LazyCallGraph::buildGenericSCCs(RootsT &&Roots, GetBeginT &&GetBegin,
1573 GetEndT &&GetEnd, GetNodeT &&GetNode,
1574 FormSCCCallbackT &&FormSCC) {
1575 using EdgeItT = decltype(GetBegin(std::declval<Node &>()));
1581 for (
Node *RootN : Roots) {
1583 "Cannot begin a new root with a non-empty DFS stack!");
1585 "Cannot begin a new root with pending nodes for an SCC!");
1588 if (RootN->DFSNumber != 0) {
1589 assert(RootN->DFSNumber == -1 &&
1590 "Shouldn't have any mid-DFS root nodes!");
1594 RootN->DFSNumber = RootN->LowLink = 1;
1595 int NextDFSNumber = 2;
1597 DFSStack.
push_back({RootN, GetBegin(*RootN)});
1602 auto E = GetEnd(*N);
1604 Node &ChildN = GetNode(I);
1605 if (ChildN.DFSNumber == 0) {
1610 ChildN.DFSNumber = ChildN.LowLink = NextDFSNumber++;
1620 if (ChildN.DFSNumber == -1) {
1626 assert(ChildN.LowLink > 0 &&
"Must have a positive low-link number!");
1627 if (ChildN.LowLink < N->LowLink)
1628 N->LowLink = ChildN.LowLink;
1640 if (N->LowLink != N->DFSNumber)
1645 int RootDFSNumber = N->DFSNumber;
1649 PendingSCCStack.
rbegin(),
1651 return N->DFSNumber < RootDFSNumber;
1656 PendingSCCStack.
erase(SCCNodes.end().base(), PendingSCCStack.
end());
1657 }
while (!DFSStack.
empty());
1667 assert(RC.SCCs.empty() &&
"Already built SCCs!");
1668 assert(RC.SCCIndices.empty() &&
"Already mapped SCC indices!");
1670 for (
Node *
N : Nodes) {
1671 assert(
N->LowLink >= (*Nodes.begin())->LowLink &&
1672 "We cannot have a low link in an SCC lower than its root on the " 1677 N->DFSNumber =
N->LowLink = 0;
1688 RC.SCCs.push_back(createSCC(RC, Nodes));
1689 for (
Node &N : *RC.SCCs.back()) {
1690 N.DFSNumber = N.LowLink = -1;
1691 SCCMap[&
N] = RC.SCCs.back();
1696 for (
int i = 0,
Size = RC.SCCs.size(); i <
Size; ++i)
1697 RC.SCCIndices[RC.SCCs[i]] = i;
1701 if (EntryEdges.
empty() || !PostOrderRefSCCs.empty())
1705 assert(RefSCCIndices.empty() &&
"Already mapped RefSCC indices!");
1708 for (
Edge &
E : *
this)
1725 RefSCC *NewRC = createRefSCC(*
this);
1726 buildSCCs(*NewRC, Nodes);
1731 RefSCCIndices.insert({NewRC, PostOrderRefSCCs.size()}).
second;
1733 assert(Inserted &&
"Cannot already have this RefSCC in the index map!");
1734 PostOrderRefSCCs.push_back(NewRC);
1748 OS <<
" " << (
E.isCall() ?
"call" :
"ref ") <<
" -> " 1749 <<
E.getFunction().getName() <<
"\n";
1755 OS <<
" SCC with " << C.
size() <<
" functions:\n";
1758 OS <<
" " <<
N.getFunction().getName() <<
"\n";
1762 OS <<
" RefSCC with " << C.
size() <<
" call SCCs:\n";
1794 OS <<
" " << Name <<
" -> \"" 1797 OS <<
" [style=dashed,label=\"ref\"]";
This routine provides some synthesis utilities to produce sequences of values.
reference emplace_back(ArgTypes &&... Args)
void insertEdge(Node &SourceN, Node &TargetN, Edge::Kind EK)
Update the call graph after inserting a new edge.
iterator_range< call_iterator > calls()
void removeOutgoingEdge(Node &SourceN, Node &TargetN)
Remove an edge whose source is in this RefSCC and target is not.
void removeEdge(Node &SourceN, Node &TargetN)
Update the call graph after deleting an edge.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
This class represents lattice values for constants.
EdgeSequence & populate()
Populate the edges of this node if necessary.
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds...
A Module instance is used to store all the information related to an LLVM module. ...
amdgpu Simplify well known AMD library false FunctionCallee Value const Twine & Name
Kind
The kind of edge in the graph.
void push_back(const T &Elt)
The edge sequence object.
This provides a very simple, boring adaptor for a begin and end iterator into a range type...
SCC * lookupSCC(Node &N) const
Lookup a function's SCC in the graph.
Implements a lazy call graph analysis and related passes for the new pass manager.
Function & getFunction() const
An efficient, type-erasing, non-owning reference to a callable.
LLVM_NODISCARD detail::scope_exit< typename std::decay< Callable >::type > make_scope_exit(Callable &&F)
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly...
Node & get(Function &F)
Get a graph node for a given function, scanning it to populate the graph data as necessary.
static void printNode(raw_ostream &OS, LazyCallGraph::Node &N)
RefSCC * lookupRefSCC(Node &N) const
Lookup a function's RefSCC in the graph.
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
RefSCC & getOuterRefSCC() const
bool isAncestorOf(const SCC &C) const
Test if this SCC is an ancestor of C.
StringRef getName() const
ArrayRef< T > makeArrayRef(const T &OneElt)
Construct an ArrayRef from a single element.
bool switchInternalEdgeToCall(Node &SourceN, Node &TargetN, function_ref< void(ArrayRef< SCC *> MergedSCCs)> MergeCB={})
Make an existing internal ref edge into a call edge.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
call_iterator call_begin()
bool isLibFunction(Function &F) const
Test whether a function is a known and defined library function tracked by the call graph...
static StringRef getName(Value *V)
auto reverse(ContainerTy &&C, typename std::enable_if< has_rbegin< ContainerTy >::value >::type *=nullptr) -> decltype(make_range(C.rbegin(), C.rend()))
A RefSCC of the call graph.
void insertTrivialCallEdge(Node &SourceN, Node &TargetN)
A convenience wrapper around the above to handle trivial cases of inserting a new call edge...
A lazily constructed view of the call graph of a module.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
LazyCallGraph & operator=(LazyCallGraph &&RHS)
void replaceNodeFunction(Node &N, Function &NewF)
Directly replace a node's function with a new function.
static void addEdge(SmallVectorImpl< LazyCallGraph::Edge > &Edges, DenseMap< LazyCallGraph::Node *, int > &EdgeIndexMap, LazyCallGraph::Node &N, LazyCallGraph::Edge::Kind EK)
void switchOutgoingEdgeToCall(Node &SourceN, Node &TargetN)
Make an existing outgoing ref edge into a call edge.
static bool isKnownLibFunction(Function &F, TargetLibraryInfo &TLI)
A set of analyses that are preserved following a run of a transformation pass.
LLVM Basic Block Representation.
An iterator used for the edges to both entry nodes and child nodes.
LazyCallGraphDOTPrinterPass(raw_ostream &OS)
std::string EscapeString(const std::string &Label)
void swap(SmallVectorImpl &RHS)
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This is an important base class in LLVM.
Node & getNode() const
Get the call graph node referenced by this edge.
void switchOutgoingEdgeToRef(Node &SourceN, Node &TargetN)
Make an existing outgoing call edge into a ref edge.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
void insertInternalRefEdge(Node &SourceN, Node &TargetN)
Insert a ref edge from one node in this RefSCC to another in this RefSCC.
static void printNodeDOT(raw_ostream &OS, LazyCallGraph::Node &N)
SmallVector< RefSCC *, 1 > insertIncomingRefEdge(Node &SourceN, Node &TargetN)
Insert an edge whose source is in a descendant RefSCC and target is in this RefSCC.
A node in the call graph.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
A class used to represent edges in the call graph.
auto find_if(R &&Range, UnaryPredicate P) -> decltype(adl_begin(Range))
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly...
iterator erase(const_iterator CI)
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
bool isParentOf(const RefSCC &RC) const
Test if this RefSCC is a parent of RC.
const std::string & getModuleIdentifier() const
Get the module identifier which is, essentially, the name of the module.
bool verify(const TargetRegisterInfo &TRI) const
Check that information hold by this instance make sense for the given TRI.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
void removeDeadFunction(Function &F)
Remove a dead function from the call graph (typically to delete it).
auto size(R &&Range, typename std::enable_if< std::is_same< typename std::iterator_traits< decltype(Range.begin())>::iterator_category, std::random_access_iterator_tag >::value, void >::type *=nullptr) -> decltype(std::distance(Range.begin(), Range.end()))
Get the size of a range.
bool isParentOf(const SCC &C) const
Test if this SCC is a parent of C.
bool isFunctionVectorizable(StringRef F, unsigned VF) const
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Module.h This file contains the declarations for the Module class.
Provides information about what library functions are available for the current target.
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
LLVM_NODISCARD T pop_back_val()
SmallVector< RefSCC *, 1 > removeInternalRefEdge(Node &SourceN, ArrayRef< Node *> TargetNs)
Remove a list of ref edges which are entirely within this RefSCC.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
A range adaptor for a pair of iterators.
amdgpu Simplify well known AMD library false FunctionCallee Callee
An iterator over specifically call edges.
void insertOutgoingEdge(Node &SourceN, Node &TargetN, Edge::Kind EK)
Insert an edge whose parent is in this RefSCC and child is in some child RefSCC.
bool getLibFunc(StringRef funcName, LibFunc &F) const
Searches for a particular function name.
void append(in_iter in_start, in_iter in_end)
Add the specified range to the end of the SmallVector.
void switchTrivialInternalEdgeToRef(Node &SourceN, Node &TargetN)
Make an existing internal call edge between separate SCCs into a ref edge.
iterator_range< iterator > switchInternalEdgeToRef(Node &SourceN, Node &TargetN)
Make an existing internal call edge within a single SCC into a ref edge.
LazyCallGraph(Module &M, function_ref< TargetLibraryInfo &(Function &)> GetTLI)
Construct a graph for the given module.
LazyCallGraphPrinterPass(raw_ostream &OS)
bool isAncestorOf(const RefSCC &RC) const
Test if this RefSCC is an ancestor of RC.
LLVM_NODISCARD bool empty() const
StringRef getName() const
Return a constant reference to the value's name.
static void printRefSCC(raw_ostream &OS, LazyCallGraph::RefSCC &C)
static void printSCC(raw_ostream &OS, LazyCallGraph::SCC &C)
An analysis pass which computes the call graph for a module.
void insertTrivialRefEdge(Node &SourceN, Node &TargetN)
A convenience wrapper around the above to handle trivial cases of inserting a new ref edge...
reverse_iterator rbegin()
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static iterator_range< typename PostorderSequenceT::iterator > updatePostorderSequenceForEdgeInsertion(SCCT &SourceSCC, SCCT &TargetSCC, PostorderSequenceT &SCCs, SCCIndexMapT &SCCIndices, ComputeSourceConnectedSetCallableT ComputeSourceConnectedSet, ComputeTargetConnectedSetCallableT ComputeTargetConnectedSet)
Generic helper that updates a postorder sequence of SCCs for a potentially cycle-introducing edge ins...
LLVM Value Representation.
An SCC of the call graph.
This class implements an extremely fast bulk output stream that can only output to a stream...
A container for analyses that lazily runs them and caches their results.
This header defines various interfaces for pass management in LLVM.
static void visitReferences(SmallVectorImpl< Constant *> &Worklist, SmallPtrSetImpl< Constant *> &Visited, CallbackT Callback)
Recursively visits the defined functions whose address is reachable from every constant in the Workli...
bool isDescendantOf(const RefSCC &RC) const
Test if this RefSCC is a descendant of RC.
iterator_range< postorder_ref_scc_iterator > postorder_ref_sccs()
A special type used by analysis passes to provide an address that identifies that particular analysis...
bool isCall() const
Test whether the edge represents a direct call to a function.