blob: c832dc9487746388109ec06a61faaf8e4347037c [file] [log] [blame]
Chandler Carruthbf71a342014-02-06 04:37:03 +00001//===- LazyCallGraph.cpp - Analysis of a Module's call graph --------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Chandler Carruthbf71a342014-02-06 04:37:03 +00006//
7//===----------------------------------------------------------------------===//
8
9#include "llvm/Analysis/LazyCallGraph.h"
Eugene Zelenko530851c2017-08-11 21:30:02 +000010#include "llvm/ADT/ArrayRef.h"
Chandler Carruth18eadd922014-04-18 10:50:32 +000011#include "llvm/ADT/STLExtras.h"
Chandler Carruth86f0bdf2016-12-09 00:46:44 +000012#include "llvm/ADT/ScopeExit.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000013#include "llvm/ADT/Sequence.h"
Eugene Zelenko530851c2017-08-11 21:30:02 +000014#include "llvm/ADT/SmallPtrSet.h"
15#include "llvm/ADT/SmallVector.h"
16#include "llvm/ADT/iterator_range.h"
17#include "llvm/Analysis/TargetLibraryInfo.h"
Nico Weber432a3882018-04-30 14:59:11 +000018#include "llvm/Config/llvm-config.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000019#include "llvm/IR/CallSite.h"
Eugene Zelenko530851c2017-08-11 21:30:02 +000020#include "llvm/IR/Function.h"
21#include "llvm/IR/GlobalVariable.h"
22#include "llvm/IR/Instruction.h"
23#include "llvm/IR/Module.h"
Chandler Carruthbf71a342014-02-06 04:37:03 +000024#include "llvm/IR/PassManager.h"
Eugene Zelenko530851c2017-08-11 21:30:02 +000025#include "llvm/Support/Casting.h"
26#include "llvm/Support/Compiler.h"
Chandler Carruth99b756d2014-04-21 05:04:24 +000027#include "llvm/Support/Debug.h"
Sean Silva7cb30662016-06-18 09:17:32 +000028#include "llvm/Support/GraphWriter.h"
Eugene Zelenko530851c2017-08-11 21:30:02 +000029#include "llvm/Support/raw_ostream.h"
30#include <algorithm>
31#include <cassert>
32#include <cstddef>
33#include <iterator>
34#include <string>
35#include <tuple>
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +000036#include <utility>
Chandler Carruthbf71a342014-02-06 04:37:03 +000037
38using namespace llvm;
39
Chandler Carruthf1221bd2014-04-22 02:48:03 +000040#define DEBUG_TYPE "lcg"
41
Chandler Carruthaaad9f82017-02-09 23:24:13 +000042void LazyCallGraph::EdgeSequence::insertEdgeInternal(Node &TargetN,
43 Edge::Kind EK) {
44 EdgeIndexMap.insert({&TargetN, Edges.size()});
45 Edges.emplace_back(TargetN, EK);
Chandler Carrutha4499e92016-02-02 03:57:13 +000046}
47
Chandler Carruthaaad9f82017-02-09 23:24:13 +000048void LazyCallGraph::EdgeSequence::setEdgeKind(Node &TargetN, Edge::Kind EK) {
49 Edges[EdgeIndexMap.find(&TargetN)->second].setKind(EK);
50}
51
52bool LazyCallGraph::EdgeSequence::removeEdgeInternal(Node &TargetN) {
53 auto IndexMapI = EdgeIndexMap.find(&TargetN);
54 if (IndexMapI == EdgeIndexMap.end())
55 return false;
56
57 Edges[IndexMapI->second] = Edge();
58 EdgeIndexMap.erase(IndexMapI);
59 return true;
60}
61
62static void addEdge(SmallVectorImpl<LazyCallGraph::Edge> &Edges,
63 DenseMap<LazyCallGraph::Node *, int> &EdgeIndexMap,
64 LazyCallGraph::Node &N, LazyCallGraph::Edge::Kind EK) {
65 if (!EdgeIndexMap.insert({&N, Edges.size()}).second)
66 return;
67
Nicola Zaghend34e60c2018-05-14 12:53:11 +000068 LLVM_DEBUG(dbgs() << " Added callable function: " << N.getName() << "\n");
Chandler Carruthaaad9f82017-02-09 23:24:13 +000069 Edges.emplace_back(LazyCallGraph::Edge(N, EK));
70}
71
72LazyCallGraph::EdgeSequence &LazyCallGraph::Node::populateSlow() {
73 assert(!Edges && "Must not have already populated the edges for this node!");
74
Nicola Zaghend34e60c2018-05-14 12:53:11 +000075 LLVM_DEBUG(dbgs() << " Adding functions called by '" << getName()
76 << "' to the graph.\n");
Chandler Carruth99b756d2014-04-21 05:04:24 +000077
Chandler Carruthaaad9f82017-02-09 23:24:13 +000078 Edges = EdgeSequence();
79
Chandler Carruthbf71a342014-02-06 04:37:03 +000080 SmallVector<Constant *, 16> Worklist;
Chandler Carrutha4499e92016-02-02 03:57:13 +000081 SmallPtrSet<Function *, 4> Callees;
Chandler Carruthbf71a342014-02-06 04:37:03 +000082 SmallPtrSet<Constant *, 16> Visited;
Chandler Carrutha4499e92016-02-02 03:57:13 +000083
84 // Find all the potential call graph edges in this function. We track both
85 // actual call edges and indirect references to functions. The direct calls
86 // are trivially added, but to accumulate the latter we walk the instructions
87 // and add every operand which is a constant to the worklist to process
88 // afterward.
Chandler Carruth86f0bdf2016-12-09 00:46:44 +000089 //
90 // Note that we consider *any* function with a definition to be a viable
91 // edge. Even if the function's definition is subject to replacement by
92 // some other module (say, a weak definition) there may still be
93 // optimizations which essentially speculate based on the definition and
94 // a way to check that the specific definition is in fact the one being
95 // used. For example, this could be done by moving the weak definition to
96 // a strong (internal) definition and making the weak definition be an
97 // alias. Then a test of the address of the weak function against the new
98 // strong definition's address would be an effective way to determine the
99 // safety of optimizing a direct call edge.
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000100 for (BasicBlock &BB : *F)
Chandler Carrutha4499e92016-02-02 03:57:13 +0000101 for (Instruction &I : BB) {
102 if (auto CS = CallSite(&I))
Mark Lacey626ed222019-08-15 17:47:53 +0000103 for (Function *Callee : CS.getKnownCallees())
Chandler Carruth86f0bdf2016-12-09 00:46:44 +0000104 if (!Callee->isDeclaration())
105 if (Callees.insert(Callee).second) {
106 Visited.insert(Callee);
Mark Lacey626ed222019-08-15 17:47:53 +0000107 auto EdgeK = CS.getCalledFunction() ? LazyCallGraph::Edge::Call
108 : LazyCallGraph::Edge::Ref;
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000109 addEdge(Edges->Edges, Edges->EdgeIndexMap, G->get(*Callee),
Mark Lacey626ed222019-08-15 17:47:53 +0000110 EdgeK);
Chandler Carruth86f0bdf2016-12-09 00:46:44 +0000111 }
Chandler Carrutha4499e92016-02-02 03:57:13 +0000112
Chandler Carruthb9e2f8c2014-03-09 12:20:34 +0000113 for (Value *Op : I.operand_values())
Chandler Carruth1583e992014-03-03 10:42:58 +0000114 if (Constant *C = dyn_cast<Constant>(Op))
David Blaikie70573dc2014-11-19 07:49:26 +0000115 if (Visited.insert(C).second)
Chandler Carruthbf71a342014-02-06 04:37:03 +0000116 Worklist.push_back(C);
Chandler Carrutha4499e92016-02-02 03:57:13 +0000117 }
Chandler Carruthbf71a342014-02-06 04:37:03 +0000118
119 // We've collected all the constant (and thus potentially function or
120 // function containing) operands to all of the instructions in the function.
121 // Process them (recursively) collecting every function found.
Chandler Carruth88823462016-08-24 09:37:14 +0000122 visitReferences(Worklist, Visited, [&](Function &F) {
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000123 addEdge(Edges->Edges, Edges->EdgeIndexMap, G->get(F),
124 LazyCallGraph::Edge::Ref);
Chandler Carruth88823462016-08-24 09:37:14 +0000125 });
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000126
Chandler Carruthf59a8382017-07-15 08:08:19 +0000127 // Add implicit reference edges to any defined libcall functions (if we
128 // haven't found an explicit edge).
129 for (auto *F : G->LibFunctions)
130 if (!Visited.count(F))
131 addEdge(Edges->Edges, Edges->EdgeIndexMap, G->get(*F),
132 LazyCallGraph::Edge::Ref);
133
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000134 return *Edges;
Chandler Carruthbf71a342014-02-06 04:37:03 +0000135}
136
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000137void LazyCallGraph::Node::replaceFunction(Function &NewF) {
138 assert(F != &NewF && "Must not replace a function with itself!");
139 F = &NewF;
Chandler Carruthaa839b22014-04-27 01:59:50 +0000140}
141
Aaron Ballman615eb472017-10-15 14:32:27 +0000142#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Matthias Braun8c209aa2017-01-28 02:02:38 +0000143LLVM_DUMP_METHOD void LazyCallGraph::Node::dump() const {
Chandler Carruthdca83402016-06-27 23:26:08 +0000144 dbgs() << *this << '\n';
145}
Matthias Braun8c209aa2017-01-28 02:02:38 +0000146#endif
Chandler Carruthdca83402016-06-27 23:26:08 +0000147
Chandler Carruthf59a8382017-07-15 08:08:19 +0000148static bool isKnownLibFunction(Function &F, TargetLibraryInfo &TLI) {
149 LibFunc LF;
150
151 // Either this is a normal library function or a "vectorizable" function.
152 return TLI.getLibFunc(F, LF) || TLI.isFunctionVectorizable(F.getName());
153}
154
155LazyCallGraph::LazyCallGraph(Module &M, TargetLibraryInfo &TLI) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000156 LLVM_DEBUG(dbgs() << "Building CG for module: " << M.getModuleIdentifier()
157 << "\n");
Chandler Carruthf59a8382017-07-15 08:08:19 +0000158 for (Function &F : M) {
159 if (F.isDeclaration())
160 continue;
161 // If this function is a known lib function to LLVM then we want to
162 // synthesize reference edges to it to model the fact that LLVM can turn
163 // arbitrary code into a library function call.
164 if (isKnownLibFunction(F, TLI))
Chandler Carruth06a86302017-07-19 04:12:25 +0000165 LibFunctions.insert(&F);
Chandler Carruthf59a8382017-07-15 08:08:19 +0000166
167 if (F.hasLocalLinkage())
168 continue;
169
170 // External linkage defined functions have edges to them from other
171 // modules.
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000172 LLVM_DEBUG(dbgs() << " Adding '" << F.getName()
173 << "' to entry set of the graph.\n");
Chandler Carruthf59a8382017-07-15 08:08:19 +0000174 addEdge(EntryEdges.Edges, EntryEdges.EdgeIndexMap, get(F), Edge::Ref);
175 }
Chandler Carruthbf71a342014-02-06 04:37:03 +0000176
Guozhi Wei36fc9c32019-04-05 18:51:08 +0000177 // Externally visible aliases of internal functions are also viable entry
178 // edges to the module.
179 for (auto &A : M.aliases()) {
180 if (A.hasLocalLinkage())
181 continue;
182 if (Function* F = dyn_cast<Function>(A.getAliasee())) {
183 LLVM_DEBUG(dbgs() << " Adding '" << F->getName()
184 << "' with alias '" << A.getName()
185 << "' to entry set of the graph.\n");
186 addEdge(EntryEdges.Edges, EntryEdges.EdgeIndexMap, get(*F), Edge::Ref);
187 }
188 }
189
Chandler Carruthbf71a342014-02-06 04:37:03 +0000190 // Now add entry nodes for functions reachable via initializers to globals.
191 SmallVector<Constant *, 16> Worklist;
192 SmallPtrSet<Constant *, 16> Visited;
Chandler Carruthb9e2f8c2014-03-09 12:20:34 +0000193 for (GlobalVariable &GV : M.globals())
194 if (GV.hasInitializer())
David Blaikie70573dc2014-11-19 07:49:26 +0000195 if (Visited.insert(GV.getInitializer()).second)
Chandler Carruthb9e2f8c2014-03-09 12:20:34 +0000196 Worklist.push_back(GV.getInitializer());
Chandler Carruthbf71a342014-02-06 04:37:03 +0000197
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000198 LLVM_DEBUG(
199 dbgs() << " Adding functions referenced by global initializers to the "
200 "entry set.\n");
Chandler Carruth88823462016-08-24 09:37:14 +0000201 visitReferences(Worklist, Visited, [&](Function &F) {
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000202 addEdge(EntryEdges.Edges, EntryEdges.EdgeIndexMap, get(F),
203 LazyCallGraph::Edge::Ref);
Chandler Carruth88823462016-08-24 09:37:14 +0000204 });
Chandler Carruthbf71a342014-02-06 04:37:03 +0000205}
206
Chandler Carruthbf71a342014-02-06 04:37:03 +0000207LazyCallGraph::LazyCallGraph(LazyCallGraph &&G)
Chandler Carruth2174f442014-04-18 20:44:16 +0000208 : BPA(std::move(G.BPA)), NodeMap(std::move(G.NodeMap)),
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000209 EntryEdges(std::move(G.EntryEdges)), SCCBPA(std::move(G.SCCBPA)),
Chandler Carruthadbf14a2017-08-05 07:37:00 +0000210 SCCMap(std::move(G.SCCMap)),
Chandler Carruthf59a8382017-07-15 08:08:19 +0000211 LibFunctions(std::move(G.LibFunctions)) {
Chandler Carruthd8d865e2014-04-18 11:02:33 +0000212 updateGraphPtrs();
213}
214
215LazyCallGraph &LazyCallGraph::operator=(LazyCallGraph &&G) {
216 BPA = std::move(G.BPA);
Chandler Carruth2174f442014-04-18 20:44:16 +0000217 NodeMap = std::move(G.NodeMap);
Chandler Carrutha4499e92016-02-02 03:57:13 +0000218 EntryEdges = std::move(G.EntryEdges);
Chandler Carruthd8d865e2014-04-18 11:02:33 +0000219 SCCBPA = std::move(G.SCCBPA);
220 SCCMap = std::move(G.SCCMap);
Chandler Carruthf59a8382017-07-15 08:08:19 +0000221 LibFunctions = std::move(G.LibFunctions);
Chandler Carruthd8d865e2014-04-18 11:02:33 +0000222 updateGraphPtrs();
223 return *this;
224}
225
Aaron Ballman615eb472017-10-15 14:32:27 +0000226#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Matthias Braun8c209aa2017-01-28 02:02:38 +0000227LLVM_DUMP_METHOD void LazyCallGraph::SCC::dump() const {
Chandler Carruthdca83402016-06-27 23:26:08 +0000228 dbgs() << *this << '\n';
229}
Matthias Braun8c209aa2017-01-28 02:02:38 +0000230#endif
Chandler Carruthdca83402016-06-27 23:26:08 +0000231
Chandler Carruthe5944d92016-02-17 00:18:16 +0000232#ifndef NDEBUG
233void LazyCallGraph::SCC::verify() {
234 assert(OuterRefSCC && "Can't have a null RefSCC!");
235 assert(!Nodes.empty() && "Can't have an empty SCC!");
Chandler Carruth8f92d6d2014-04-26 01:03:46 +0000236
Chandler Carruthe5944d92016-02-17 00:18:16 +0000237 for (Node *N : Nodes) {
238 assert(N && "Can't have a null node!");
239 assert(OuterRefSCC->G->lookupSCC(*N) == this &&
240 "Node does not map to this SCC!");
241 assert(N->DFSNumber == -1 &&
242 "Must set DFS numbers to -1 when adding a node to an SCC!");
243 assert(N->LowLink == -1 &&
244 "Must set low link to -1 when adding a node to an SCC!");
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000245 for (Edge &E : **N)
Chandler Carruth39df40d2017-08-05 04:04:06 +0000246 assert(E.getNode().isPopulated() && "Can't have an unpopulated node!");
Chandler Carruthe5944d92016-02-17 00:18:16 +0000247 }
248}
249#endif
250
Chandler Carruthbae595b2016-11-22 19:23:31 +0000251bool LazyCallGraph::SCC::isParentOf(const SCC &C) const {
252 if (this == &C)
253 return false;
254
255 for (Node &N : *this)
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000256 for (Edge &E : N->calls())
257 if (OuterRefSCC->G->lookupSCC(E.getNode()) == &C)
258 return true;
Chandler Carruthbae595b2016-11-22 19:23:31 +0000259
260 // No edges found.
261 return false;
262}
263
264bool LazyCallGraph::SCC::isAncestorOf(const SCC &TargetC) const {
265 if (this == &TargetC)
266 return false;
267
268 LazyCallGraph &G = *OuterRefSCC->G;
269
270 // Start with this SCC.
271 SmallPtrSet<const SCC *, 16> Visited = {this};
272 SmallVector<const SCC *, 16> Worklist = {this};
273
274 // Walk down the graph until we run out of edges or find a path to TargetC.
275 do {
276 const SCC &C = *Worklist.pop_back_val();
277 for (Node &N : C)
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000278 for (Edge &E : N->calls()) {
279 SCC *CalleeC = G.lookupSCC(E.getNode());
Chandler Carruthbae595b2016-11-22 19:23:31 +0000280 if (!CalleeC)
281 continue;
282
283 // If the callee's SCC is the TargetC, we're done.
284 if (CalleeC == &TargetC)
285 return true;
286
287 // If this is the first time we've reached this SCC, put it on the
288 // worklist to recurse through.
289 if (Visited.insert(CalleeC).second)
290 Worklist.push_back(CalleeC);
291 }
292 } while (!Worklist.empty());
293
294 // No paths found.
295 return false;
296}
297
Chandler Carruthe5944d92016-02-17 00:18:16 +0000298LazyCallGraph::RefSCC::RefSCC(LazyCallGraph &G) : G(&G) {}
299
Aaron Ballman615eb472017-10-15 14:32:27 +0000300#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Matthias Braun8c209aa2017-01-28 02:02:38 +0000301LLVM_DUMP_METHOD void LazyCallGraph::RefSCC::dump() const {
Chandler Carruthdca83402016-06-27 23:26:08 +0000302 dbgs() << *this << '\n';
303}
Matthias Braun8c209aa2017-01-28 02:02:38 +0000304#endif
Chandler Carruthdca83402016-06-27 23:26:08 +0000305
Chandler Carruthe5944d92016-02-17 00:18:16 +0000306#ifndef NDEBUG
307void LazyCallGraph::RefSCC::verify() {
308 assert(G && "Can't have a null graph!");
309 assert(!SCCs.empty() && "Can't have an empty SCC!");
310
311 // Verify basic properties of the SCCs.
Chandler Carruth88823462016-08-24 09:37:14 +0000312 SmallPtrSet<SCC *, 4> SCCSet;
Chandler Carruthe5944d92016-02-17 00:18:16 +0000313 for (SCC *C : SCCs) {
314 assert(C && "Can't have a null SCC!");
315 C->verify();
316 assert(&C->getOuterRefSCC() == this &&
317 "SCC doesn't think it is inside this RefSCC!");
Chandler Carruth88823462016-08-24 09:37:14 +0000318 bool Inserted = SCCSet.insert(C).second;
319 assert(Inserted && "Found a duplicate SCC!");
Chandler Carruth23a6c3f2016-12-06 10:29:23 +0000320 auto IndexIt = SCCIndices.find(C);
321 assert(IndexIt != SCCIndices.end() &&
322 "Found an SCC that doesn't have an index!");
Chandler Carruthe5944d92016-02-17 00:18:16 +0000323 }
324
325 // Check that our indices map correctly.
326 for (auto &SCCIndexPair : SCCIndices) {
327 SCC *C = SCCIndexPair.first;
328 int i = SCCIndexPair.second;
329 assert(C && "Can't have a null SCC in the indices!");
Chandler Carruth88823462016-08-24 09:37:14 +0000330 assert(SCCSet.count(C) && "Found an index for an SCC not in the RefSCC!");
Chandler Carruthe5944d92016-02-17 00:18:16 +0000331 assert(SCCs[i] == C && "Index doesn't point to SCC!");
332 }
333
334 // Check that the SCCs are in fact in post-order.
335 for (int i = 0, Size = SCCs.size(); i < Size; ++i) {
336 SCC &SourceSCC = *SCCs[i];
337 for (Node &N : SourceSCC)
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000338 for (Edge &E : *N) {
Chandler Carruthe5944d92016-02-17 00:18:16 +0000339 if (!E.isCall())
340 continue;
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000341 SCC &TargetSCC = *G->lookupSCC(E.getNode());
Chandler Carruthe5944d92016-02-17 00:18:16 +0000342 if (&TargetSCC.getOuterRefSCC() == this) {
343 assert(SCCIndices.find(&TargetSCC)->second <= i &&
344 "Edge between SCCs violates post-order relationship.");
345 continue;
346 }
Chandler Carruthe5944d92016-02-17 00:18:16 +0000347 }
348 }
349}
350#endif
351
Chandler Carruth38bd6b52017-08-05 06:24:09 +0000352bool LazyCallGraph::RefSCC::isParentOf(const RefSCC &RC) const {
353 if (&RC == this)
354 return false;
355
356 // Search all edges to see if this is a parent.
357 for (SCC &C : *this)
358 for (Node &N : C)
359 for (Edge &E : *N)
360 if (G->lookupRefSCC(E.getNode()) == &RC)
361 return true;
362
363 return false;
364}
365
366bool LazyCallGraph::RefSCC::isAncestorOf(const RefSCC &RC) const {
367 if (&RC == this)
368 return false;
369
370 // For each descendant of this RefSCC, see if one of its children is the
371 // argument. If not, add that descendant to the worklist and continue
372 // searching.
373 SmallVector<const RefSCC *, 4> Worklist;
374 SmallPtrSet<const RefSCC *, 4> Visited;
375 Worklist.push_back(this);
376 Visited.insert(this);
Chandler Carruth4b096742014-05-01 12:12:42 +0000377 do {
Chandler Carruth38bd6b52017-08-05 06:24:09 +0000378 const RefSCC &DescendantRC = *Worklist.pop_back_val();
379 for (SCC &C : DescendantRC)
380 for (Node &N : C)
381 for (Edge &E : *N) {
382 auto *ChildRC = G->lookupRefSCC(E.getNode());
383 if (ChildRC == &RC)
384 return true;
385 if (!ChildRC || !Visited.insert(ChildRC).second)
386 continue;
387 Worklist.push_back(ChildRC);
388 }
389 } while (!Worklist.empty());
Chandler Carruth4b096742014-05-01 12:12:42 +0000390
391 return false;
392}
393
Chandler Carruth1f621f02016-09-04 08:34:24 +0000394/// Generic helper that updates a postorder sequence of SCCs for a potentially
395/// cycle-introducing edge insertion.
396///
397/// A postorder sequence of SCCs of a directed graph has one fundamental
398/// property: all deges in the DAG of SCCs point "up" the sequence. That is,
399/// all edges in the SCC DAG point to prior SCCs in the sequence.
400///
401/// This routine both updates a postorder sequence and uses that sequence to
402/// compute the set of SCCs connected into a cycle. It should only be called to
403/// insert a "downward" edge which will require changing the sequence to
404/// restore it to a postorder.
405///
406/// When inserting an edge from an earlier SCC to a later SCC in some postorder
407/// sequence, all of the SCCs which may be impacted are in the closed range of
408/// those two within the postorder sequence. The algorithm used here to restore
409/// the state is as follows:
410///
411/// 1) Starting from the source SCC, construct a set of SCCs which reach the
412/// source SCC consisting of just the source SCC. Then scan toward the
413/// target SCC in postorder and for each SCC, if it has an edge to an SCC
414/// in the set, add it to the set. Otherwise, the source SCC is not
415/// a successor, move it in the postorder sequence to immediately before
416/// the source SCC, shifting the source SCC and all SCCs in the set one
417/// position toward the target SCC. Stop scanning after processing the
418/// target SCC.
419/// 2) If the source SCC is now past the target SCC in the postorder sequence,
420/// and thus the new edge will flow toward the start, we are done.
421/// 3) Otherwise, starting from the target SCC, walk all edges which reach an
422/// SCC between the source and the target, and add them to the set of
423/// connected SCCs, then recurse through them. Once a complete set of the
424/// SCCs the target connects to is known, hoist the remaining SCCs between
425/// the source and the target to be above the target. Note that there is no
426/// need to process the source SCC, it is already known to connect.
427/// 4) At this point, all of the SCCs in the closed range between the source
428/// SCC and the target SCC in the postorder sequence are connected,
429/// including the target SCC and the source SCC. Inserting the edge from
430/// the source SCC to the target SCC will form a cycle out of precisely
431/// these SCCs. Thus we can merge all of the SCCs in this closed range into
432/// a single SCC.
433///
434/// This process has various important properties:
435/// - Only mutates the SCCs when adding the edge actually changes the SCC
436/// structure.
437/// - Never mutates SCCs which are unaffected by the change.
438/// - Updates the postorder sequence to correctly satisfy the postorder
439/// constraint after the edge is inserted.
440/// - Only reorders SCCs in the closed postorder sequence from the source to
441/// the target, so easy to bound how much has changed even in the ordering.
442/// - Big-O is the number of edges in the closed postorder range of SCCs from
443/// source to target.
444///
445/// This helper routine, in addition to updating the postorder sequence itself
Vedant Kumar1a8456d2018-03-02 18:57:02 +0000446/// will also update a map from SCCs to indices within that sequence.
Chandler Carruth1f621f02016-09-04 08:34:24 +0000447///
448/// The sequence and the map must operate on pointers to the SCC type.
449///
450/// Two callbacks must be provided. The first computes the subset of SCCs in
451/// the postorder closed range from the source to the target which connect to
452/// the source SCC via some (transitive) set of edges. The second computes the
453/// subset of the same range which the target SCC connects to via some
454/// (transitive) set of edges. Both callbacks should populate the set argument
455/// provided.
456template <typename SCCT, typename PostorderSequenceT, typename SCCIndexMapT,
457 typename ComputeSourceConnectedSetCallableT,
458 typename ComputeTargetConnectedSetCallableT>
459static iterator_range<typename PostorderSequenceT::iterator>
460updatePostorderSequenceForEdgeInsertion(
461 SCCT &SourceSCC, SCCT &TargetSCC, PostorderSequenceT &SCCs,
462 SCCIndexMapT &SCCIndices,
463 ComputeSourceConnectedSetCallableT ComputeSourceConnectedSet,
464 ComputeTargetConnectedSetCallableT ComputeTargetConnectedSet) {
465 int SourceIdx = SCCIndices[&SourceSCC];
466 int TargetIdx = SCCIndices[&TargetSCC];
467 assert(SourceIdx < TargetIdx && "Cannot have equal indices here!");
468
469 SmallPtrSet<SCCT *, 4> ConnectedSet;
470
471 // Compute the SCCs which (transitively) reach the source.
472 ComputeSourceConnectedSet(ConnectedSet);
473
474 // Partition the SCCs in this part of the port-order sequence so only SCCs
475 // connecting to the source remain between it and the target. This is
476 // a benign partition as it preserves postorder.
477 auto SourceI = std::stable_partition(
478 SCCs.begin() + SourceIdx, SCCs.begin() + TargetIdx + 1,
479 [&ConnectedSet](SCCT *C) { return !ConnectedSet.count(C); });
480 for (int i = SourceIdx, e = TargetIdx + 1; i < e; ++i)
481 SCCIndices.find(SCCs[i])->second = i;
482
483 // If the target doesn't connect to the source, then we've corrected the
484 // post-order and there are no cycles formed.
485 if (!ConnectedSet.count(&TargetSCC)) {
486 assert(SourceI > (SCCs.begin() + SourceIdx) &&
487 "Must have moved the source to fix the post-order.");
488 assert(*std::prev(SourceI) == &TargetSCC &&
489 "Last SCC to move should have bene the target.");
490
491 // Return an empty range at the target SCC indicating there is nothing to
492 // merge.
493 return make_range(std::prev(SourceI), std::prev(SourceI));
494 }
495
496 assert(SCCs[TargetIdx] == &TargetSCC &&
497 "Should not have moved target if connected!");
498 SourceIdx = SourceI - SCCs.begin();
499 assert(SCCs[SourceIdx] == &SourceSCC &&
500 "Bad updated index computation for the source SCC!");
501
502
503 // See whether there are any remaining intervening SCCs between the source
504 // and target. If so we need to make sure they all are reachable form the
505 // target.
506 if (SourceIdx + 1 < TargetIdx) {
507 ConnectedSet.clear();
508 ComputeTargetConnectedSet(ConnectedSet);
509
510 // Partition SCCs so that only SCCs reached from the target remain between
511 // the source and the target. This preserves postorder.
512 auto TargetI = std::stable_partition(
513 SCCs.begin() + SourceIdx + 1, SCCs.begin() + TargetIdx + 1,
514 [&ConnectedSet](SCCT *C) { return ConnectedSet.count(C); });
515 for (int i = SourceIdx + 1, e = TargetIdx + 1; i < e; ++i)
516 SCCIndices.find(SCCs[i])->second = i;
517 TargetIdx = std::prev(TargetI) - SCCs.begin();
518 assert(SCCs[TargetIdx] == &TargetSCC &&
519 "Should always end with the target!");
520 }
521
522 // At this point, we know that connecting source to target forms a cycle
523 // because target connects back to source, and we know that all of the SCCs
524 // between the source and target in the postorder sequence participate in that
525 // cycle.
526 return make_range(SCCs.begin() + SourceIdx, SCCs.begin() + TargetIdx);
527}
528
Chandler Carruthc213c672017-07-09 13:45:11 +0000529bool
530LazyCallGraph::RefSCC::switchInternalEdgeToCall(
531 Node &SourceN, Node &TargetN,
532 function_ref<void(ArrayRef<SCC *> MergeSCCs)> MergeCB) {
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000533 assert(!(*SourceN)[TargetN].isCall() && "Must start with a ref edge!");
Chandler Carruthe5944d92016-02-17 00:18:16 +0000534 SmallVector<SCC *, 1> DeletedSCCs;
Chandler Carruth5217c942014-04-30 10:48:36 +0000535
Chandler Carruth11b3f602016-09-04 08:34:31 +0000536#ifndef NDEBUG
537 // In a debug build, verify the RefSCC is valid to start with and when this
538 // routine finishes.
539 verify();
540 auto VerifyOnExit = make_scope_exit([&]() { verify(); });
541#endif
542
Chandler Carruthe5944d92016-02-17 00:18:16 +0000543 SCC &SourceSCC = *G->lookupSCC(SourceN);
544 SCC &TargetSCC = *G->lookupSCC(TargetN);
545
546 // If the two nodes are already part of the same SCC, we're also done as
547 // we've just added more connectivity.
548 if (&SourceSCC == &TargetSCC) {
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000549 SourceN->setEdgeKind(TargetN, Edge::Call);
Chandler Carruthc213c672017-07-09 13:45:11 +0000550 return false; // No new cycle.
Chandler Carruthe5944d92016-02-17 00:18:16 +0000551 }
552
553 // At this point we leverage the postorder list of SCCs to detect when the
554 // insertion of an edge changes the SCC structure in any way.
555 //
556 // First and foremost, we can eliminate the need for any changes when the
557 // edge is toward the beginning of the postorder sequence because all edges
558 // flow in that direction already. Thus adding a new one cannot form a cycle.
559 int SourceIdx = SCCIndices[&SourceSCC];
560 int TargetIdx = SCCIndices[&TargetSCC];
561 if (TargetIdx < SourceIdx) {
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000562 SourceN->setEdgeKind(TargetN, Edge::Call);
Chandler Carruthc213c672017-07-09 13:45:11 +0000563 return false; // No new cycle.
Chandler Carruthe5944d92016-02-17 00:18:16 +0000564 }
565
Chandler Carruthe5944d92016-02-17 00:18:16 +0000566 // Compute the SCCs which (transitively) reach the source.
Chandler Carruth1f621f02016-09-04 08:34:24 +0000567 auto ComputeSourceConnectedSet = [&](SmallPtrSetImpl<SCC *> &ConnectedSet) {
Chandler Carruthe5944d92016-02-17 00:18:16 +0000568#ifndef NDEBUG
Chandler Carruth1f621f02016-09-04 08:34:24 +0000569 // Check that the RefSCC is still valid before computing this as the
570 // results will be nonsensical of we've broken its invariants.
Chandler Carruthe5944d92016-02-17 00:18:16 +0000571 verify();
572#endif
Chandler Carruth1f621f02016-09-04 08:34:24 +0000573 ConnectedSet.insert(&SourceSCC);
574 auto IsConnected = [&](SCC &C) {
575 for (Node &N : C)
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000576 for (Edge &E : N->calls())
577 if (ConnectedSet.count(G->lookupSCC(E.getNode())))
Chandler Carruth1f621f02016-09-04 08:34:24 +0000578 return true;
Chandler Carruthe5944d92016-02-17 00:18:16 +0000579
Chandler Carruth1f621f02016-09-04 08:34:24 +0000580 return false;
581 };
Chandler Carruthe5944d92016-02-17 00:18:16 +0000582
Chandler Carruth1f621f02016-09-04 08:34:24 +0000583 for (SCC *C :
584 make_range(SCCs.begin() + SourceIdx + 1, SCCs.begin() + TargetIdx + 1))
585 if (IsConnected(*C))
586 ConnectedSet.insert(C);
587 };
588
589 // Use a normal worklist to find which SCCs the target connects to. We still
590 // bound the search based on the range in the postorder list we care about,
591 // but because this is forward connectivity we just "recurse" through the
592 // edges.
593 auto ComputeTargetConnectedSet = [&](SmallPtrSetImpl<SCC *> &ConnectedSet) {
Chandler Carruthe5944d92016-02-17 00:18:16 +0000594#ifndef NDEBUG
Chandler Carruth1f621f02016-09-04 08:34:24 +0000595 // Check that the RefSCC is still valid before computing this as the
596 // results will be nonsensical of we've broken its invariants.
597 verify();
Chandler Carruthe5944d92016-02-17 00:18:16 +0000598#endif
Chandler Carruthe5944d92016-02-17 00:18:16 +0000599 ConnectedSet.insert(&TargetSCC);
600 SmallVector<SCC *, 4> Worklist;
601 Worklist.push_back(&TargetSCC);
602 do {
603 SCC &C = *Worklist.pop_back_val();
604 for (Node &N : C)
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000605 for (Edge &E : *N) {
Chandler Carruthe5944d92016-02-17 00:18:16 +0000606 if (!E.isCall())
607 continue;
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000608 SCC &EdgeC = *G->lookupSCC(E.getNode());
Chandler Carruthe5944d92016-02-17 00:18:16 +0000609 if (&EdgeC.getOuterRefSCC() != this)
610 // Not in this RefSCC...
611 continue;
612 if (SCCIndices.find(&EdgeC)->second <= SourceIdx)
613 // Not in the postorder sequence between source and target.
614 continue;
615
616 if (ConnectedSet.insert(&EdgeC).second)
617 Worklist.push_back(&EdgeC);
618 }
619 } while (!Worklist.empty());
Chandler Carruth1f621f02016-09-04 08:34:24 +0000620 };
Chandler Carruthe5944d92016-02-17 00:18:16 +0000621
Chandler Carruth1f621f02016-09-04 08:34:24 +0000622 // Use a generic helper to update the postorder sequence of SCCs and return
623 // a range of any SCCs connected into a cycle by inserting this edge. This
624 // routine will also take care of updating the indices into the postorder
625 // sequence.
626 auto MergeRange = updatePostorderSequenceForEdgeInsertion(
627 SourceSCC, TargetSCC, SCCs, SCCIndices, ComputeSourceConnectedSet,
628 ComputeTargetConnectedSet);
Chandler Carruthe5944d92016-02-17 00:18:16 +0000629
Chandler Carruthc213c672017-07-09 13:45:11 +0000630 // Run the user's callback on the merged SCCs before we actually merge them.
631 if (MergeCB)
632 MergeCB(makeArrayRef(MergeRange.begin(), MergeRange.end()));
633
Chandler Carruth1f621f02016-09-04 08:34:24 +0000634 // If the merge range is empty, then adding the edge didn't actually form any
635 // new cycles. We're done.
Matthias Braun9fd397b2018-10-31 00:23:23 +0000636 if (empty(MergeRange)) {
Chandler Carruth1f621f02016-09-04 08:34:24 +0000637 // Now that the SCC structure is finalized, flip the kind to call.
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000638 SourceN->setEdgeKind(TargetN, Edge::Call);
Chandler Carruthc213c672017-07-09 13:45:11 +0000639 return false; // No new cycle.
Chandler Carruthe5944d92016-02-17 00:18:16 +0000640 }
641
Chandler Carruth1f621f02016-09-04 08:34:24 +0000642#ifndef NDEBUG
643 // Before merging, check that the RefSCC remains valid after all the
644 // postorder updates.
645 verify();
646#endif
647
648 // Otherwise we need to merge all of the SCCs in the cycle into a single
Chandler Carruthe5944d92016-02-17 00:18:16 +0000649 // result SCC.
650 //
651 // NB: We merge into the target because all of these functions were already
652 // reachable from the target, meaning any SCC-wide properties deduced about it
653 // other than the set of functions within it will not have changed.
Chandler Carruthe5944d92016-02-17 00:18:16 +0000654 for (SCC *C : MergeRange) {
655 assert(C != &TargetSCC &&
656 "We merge *into* the target and shouldn't process it here!");
657 SCCIndices.erase(C);
658 TargetSCC.Nodes.append(C->Nodes.begin(), C->Nodes.end());
659 for (Node *N : C->Nodes)
660 G->SCCMap[N] = &TargetSCC;
661 C->clear();
662 DeletedSCCs.push_back(C);
663 }
664
665 // Erase the merged SCCs from the list and update the indices of the
666 // remaining SCCs.
667 int IndexOffset = MergeRange.end() - MergeRange.begin();
668 auto EraseEnd = SCCs.erase(MergeRange.begin(), MergeRange.end());
669 for (SCC *C : make_range(EraseEnd, SCCs.end()))
670 SCCIndices[C] -= IndexOffset;
671
672 // Now that the SCC structure is finalized, flip the kind to call.
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000673 SourceN->setEdgeKind(TargetN, Edge::Call);
Chandler Carruthe5944d92016-02-17 00:18:16 +0000674
Chandler Carruthc213c672017-07-09 13:45:11 +0000675 // And we're done, but we did form a new cycle.
676 return true;
Chandler Carruth5217c942014-04-30 10:48:36 +0000677}
678
Chandler Carruth443e57e2016-12-28 10:34:50 +0000679void LazyCallGraph::RefSCC::switchTrivialInternalEdgeToRef(Node &SourceN,
680 Node &TargetN) {
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000681 assert((*SourceN)[TargetN].isCall() && "Must start with a call edge!");
Chandler Carruth443e57e2016-12-28 10:34:50 +0000682
683#ifndef NDEBUG
684 // In a debug build, verify the RefSCC is valid to start with and when this
685 // routine finishes.
686 verify();
687 auto VerifyOnExit = make_scope_exit([&]() { verify(); });
688#endif
689
690 assert(G->lookupRefSCC(SourceN) == this &&
691 "Source must be in this RefSCC.");
692 assert(G->lookupRefSCC(TargetN) == this &&
693 "Target must be in this RefSCC.");
694 assert(G->lookupSCC(SourceN) != G->lookupSCC(TargetN) &&
695 "Source and Target must be in separate SCCs for this to be trivial!");
696
697 // Set the edge kind.
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000698 SourceN->setEdgeKind(TargetN, Edge::Ref);
Chandler Carruth443e57e2016-12-28 10:34:50 +0000699}
700
Chandler Carruth88823462016-08-24 09:37:14 +0000701iterator_range<LazyCallGraph::RefSCC::iterator>
702LazyCallGraph::RefSCC::switchInternalEdgeToRef(Node &SourceN, Node &TargetN) {
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000703 assert((*SourceN)[TargetN].isCall() && "Must start with a call edge!");
Chandler Carruthe5944d92016-02-17 00:18:16 +0000704
Chandler Carruth11b3f602016-09-04 08:34:31 +0000705#ifndef NDEBUG
706 // In a debug build, verify the RefSCC is valid to start with and when this
707 // routine finishes.
708 verify();
709 auto VerifyOnExit = make_scope_exit([&]() { verify(); });
710#endif
711
Chandler Carruth443e57e2016-12-28 10:34:50 +0000712 assert(G->lookupRefSCC(SourceN) == this &&
Chandler Carruthe5944d92016-02-17 00:18:16 +0000713 "Source must be in this RefSCC.");
Chandler Carruth443e57e2016-12-28 10:34:50 +0000714 assert(G->lookupRefSCC(TargetN) == this &&
Chandler Carruthe5944d92016-02-17 00:18:16 +0000715 "Target must be in this RefSCC.");
716
Chandler Carruth443e57e2016-12-28 10:34:50 +0000717 SCC &TargetSCC = *G->lookupSCC(TargetN);
718 assert(G->lookupSCC(SourceN) == &TargetSCC && "Source and Target must be in "
719 "the same SCC to require the "
720 "full CG update.");
721
Chandler Carruthe5944d92016-02-17 00:18:16 +0000722 // Set the edge kind.
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000723 SourceN->setEdgeKind(TargetN, Edge::Ref);
Chandler Carruthe5944d92016-02-17 00:18:16 +0000724
Chandler Carruthe5944d92016-02-17 00:18:16 +0000725 // Otherwise we are removing a call edge from a single SCC. This may break
726 // the cycle. In order to compute the new set of SCCs, we need to do a small
727 // DFS over the nodes within the SCC to form any sub-cycles that remain as
728 // distinct SCCs and compute a postorder over the resulting SCCs.
729 //
730 // However, we specially handle the target node. The target node is known to
731 // reach all other nodes in the original SCC by definition. This means that
Vedant Kumar1a8456d2018-03-02 18:57:02 +0000732 // we want the old SCC to be replaced with an SCC containing that node as it
Chandler Carruthe5944d92016-02-17 00:18:16 +0000733 // will be the root of whatever SCC DAG results from the DFS. Assumptions
734 // about an SCC such as the set of functions called will continue to hold,
735 // etc.
736
737 SCC &OldSCC = TargetSCC;
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000738 SmallVector<std::pair<Node *, EdgeSequence::call_iterator>, 16> DFSStack;
Chandler Carruthe5944d92016-02-17 00:18:16 +0000739 SmallVector<Node *, 16> PendingSCCStack;
740 SmallVector<SCC *, 4> NewSCCs;
741
742 // Prepare the nodes for a fresh DFS.
743 SmallVector<Node *, 16> Worklist;
744 Worklist.swap(OldSCC.Nodes);
745 for (Node *N : Worklist) {
746 N->DFSNumber = N->LowLink = 0;
747 G->SCCMap.erase(N);
748 }
749
750 // Force the target node to be in the old SCC. This also enables us to take
751 // a very significant short-cut in the standard Tarjan walk to re-form SCCs
752 // below: whenever we build an edge that reaches the target node, we know
753 // that the target node eventually connects back to all other nodes in our
754 // walk. As a consequence, we can detect and handle participants in that
755 // cycle without walking all the edges that form this connection, and instead
756 // by relying on the fundamental guarantee coming into this operation (all
757 // nodes are reachable from the target due to previously forming an SCC).
758 TargetN.DFSNumber = TargetN.LowLink = -1;
759 OldSCC.Nodes.push_back(&TargetN);
760 G->SCCMap[&TargetN] = &OldSCC;
761
762 // Scan down the stack and DFS across the call edges.
763 for (Node *RootN : Worklist) {
764 assert(DFSStack.empty() &&
765 "Cannot begin a new root with a non-empty DFS stack!");
766 assert(PendingSCCStack.empty() &&
767 "Cannot begin a new root with pending nodes for an SCC!");
768
769 // Skip any nodes we've already reached in the DFS.
770 if (RootN->DFSNumber != 0) {
771 assert(RootN->DFSNumber == -1 &&
772 "Shouldn't have any mid-DFS root nodes!");
773 continue;
774 }
775
776 RootN->DFSNumber = RootN->LowLink = 1;
777 int NextDFSNumber = 2;
778
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000779 DFSStack.push_back({RootN, (*RootN)->call_begin()});
Chandler Carruthe5944d92016-02-17 00:18:16 +0000780 do {
781 Node *N;
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000782 EdgeSequence::call_iterator I;
Chandler Carruthe5944d92016-02-17 00:18:16 +0000783 std::tie(N, I) = DFSStack.pop_back_val();
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000784 auto E = (*N)->call_end();
Chandler Carruthe5944d92016-02-17 00:18:16 +0000785 while (I != E) {
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000786 Node &ChildN = I->getNode();
Chandler Carruthe5944d92016-02-17 00:18:16 +0000787 if (ChildN.DFSNumber == 0) {
788 // We haven't yet visited this child, so descend, pushing the current
789 // node onto the stack.
790 DFSStack.push_back({N, I});
791
792 assert(!G->SCCMap.count(&ChildN) &&
793 "Found a node with 0 DFS number but already in an SCC!");
794 ChildN.DFSNumber = ChildN.LowLink = NextDFSNumber++;
795 N = &ChildN;
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000796 I = (*N)->call_begin();
797 E = (*N)->call_end();
Chandler Carruthe5944d92016-02-17 00:18:16 +0000798 continue;
799 }
800
801 // Check for the child already being part of some component.
802 if (ChildN.DFSNumber == -1) {
803 if (G->lookupSCC(ChildN) == &OldSCC) {
804 // If the child is part of the old SCC, we know that it can reach
805 // every other node, so we have formed a cycle. Pull the entire DFS
806 // and pending stacks into it. See the comment above about setting
807 // up the old SCC for why we do this.
808 int OldSize = OldSCC.size();
809 OldSCC.Nodes.push_back(N);
810 OldSCC.Nodes.append(PendingSCCStack.begin(), PendingSCCStack.end());
811 PendingSCCStack.clear();
812 while (!DFSStack.empty())
813 OldSCC.Nodes.push_back(DFSStack.pop_back_val().first);
814 for (Node &N : make_range(OldSCC.begin() + OldSize, OldSCC.end())) {
815 N.DFSNumber = N.LowLink = -1;
816 G->SCCMap[&N] = &OldSCC;
817 }
818 N = nullptr;
819 break;
820 }
821
822 // If the child has already been added to some child component, it
823 // couldn't impact the low-link of this parent because it isn't
824 // connected, and thus its low-link isn't relevant so skip it.
825 ++I;
826 continue;
827 }
828
829 // Track the lowest linked child as the lowest link for this node.
830 assert(ChildN.LowLink > 0 && "Must have a positive low-link number!");
831 if (ChildN.LowLink < N->LowLink)
832 N->LowLink = ChildN.LowLink;
833
834 // Move to the next edge.
835 ++I;
836 }
837 if (!N)
838 // Cleared the DFS early, start another round.
839 break;
840
Vedant Kumar1a8456d2018-03-02 18:57:02 +0000841 // We've finished processing N and its descendants, put it on our pending
Chandler Carruthe5944d92016-02-17 00:18:16 +0000842 // SCC stack to eventually get merged into an SCC of nodes.
843 PendingSCCStack.push_back(N);
844
845 // If this node is linked to some lower entry, continue walking up the
846 // stack.
847 if (N->LowLink != N->DFSNumber)
848 continue;
849
850 // Otherwise, we've completed an SCC. Append it to our post order list of
851 // SCCs.
852 int RootDFSNumber = N->DFSNumber;
853 // Find the range of the node stack by walking down until we pass the
854 // root DFS number.
855 auto SCCNodes = make_range(
856 PendingSCCStack.rbegin(),
David Majnemer42531262016-08-12 03:55:06 +0000857 find_if(reverse(PendingSCCStack), [RootDFSNumber](const Node *N) {
858 return N->DFSNumber < RootDFSNumber;
859 }));
Chandler Carruthe5944d92016-02-17 00:18:16 +0000860
861 // Form a new SCC out of these nodes and then clear them off our pending
862 // stack.
863 NewSCCs.push_back(G->createSCC(*this, SCCNodes));
864 for (Node &N : *NewSCCs.back()) {
865 N.DFSNumber = N.LowLink = -1;
866 G->SCCMap[&N] = NewSCCs.back();
867 }
868 PendingSCCStack.erase(SCCNodes.end().base(), PendingSCCStack.end());
869 } while (!DFSStack.empty());
870 }
871
872 // Insert the remaining SCCs before the old one. The old SCC can reach all
873 // other SCCs we form because it contains the target node of the removed edge
874 // of the old SCC. This means that we will have edges into all of the new
875 // SCCs, which means the old one must come last for postorder.
876 int OldIdx = SCCIndices[&OldSCC];
877 SCCs.insert(SCCs.begin() + OldIdx, NewSCCs.begin(), NewSCCs.end());
878
879 // Update the mapping from SCC* to index to use the new SCC*s, and remove the
880 // old SCC from the mapping.
881 for (int Idx = OldIdx, Size = SCCs.size(); Idx < Size; ++Idx)
882 SCCIndices[SCCs[Idx]] = Idx;
883
Chandler Carruth88823462016-08-24 09:37:14 +0000884 return make_range(SCCs.begin() + OldIdx,
885 SCCs.begin() + OldIdx + NewSCCs.size());
Chandler Carruthe5944d92016-02-17 00:18:16 +0000886}
887
888void LazyCallGraph::RefSCC::switchOutgoingEdgeToCall(Node &SourceN,
889 Node &TargetN) {
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000890 assert(!(*SourceN)[TargetN].isCall() && "Must start with a ref edge!");
Chandler Carruthe5944d92016-02-17 00:18:16 +0000891
892 assert(G->lookupRefSCC(SourceN) == this && "Source must be in this RefSCC.");
893 assert(G->lookupRefSCC(TargetN) != this &&
894 "Target must not be in this RefSCC.");
Francis Visoiu Mistrih262ad162017-02-28 18:34:55 +0000895#ifdef EXPENSIVE_CHECKS
Chandler Carruthe5944d92016-02-17 00:18:16 +0000896 assert(G->lookupRefSCC(TargetN)->isDescendantOf(*this) &&
897 "Target must be a descendant of the Source.");
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +0000898#endif
Chandler Carruthe5944d92016-02-17 00:18:16 +0000899
900 // Edges between RefSCCs are the same regardless of call or ref, so we can
901 // just flip the edge here.
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000902 SourceN->setEdgeKind(TargetN, Edge::Call);
Chandler Carruthe5944d92016-02-17 00:18:16 +0000903
904#ifndef NDEBUG
905 // Check that the RefSCC is still valid.
906 verify();
907#endif
908}
909
910void LazyCallGraph::RefSCC::switchOutgoingEdgeToRef(Node &SourceN,
911 Node &TargetN) {
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000912 assert((*SourceN)[TargetN].isCall() && "Must start with a call edge!");
Chandler Carruthe5944d92016-02-17 00:18:16 +0000913
914 assert(G->lookupRefSCC(SourceN) == this && "Source must be in this RefSCC.");
915 assert(G->lookupRefSCC(TargetN) != this &&
916 "Target must not be in this RefSCC.");
Francis Visoiu Mistrih262ad162017-02-28 18:34:55 +0000917#ifdef EXPENSIVE_CHECKS
Chandler Carruthe5944d92016-02-17 00:18:16 +0000918 assert(G->lookupRefSCC(TargetN)->isDescendantOf(*this) &&
919 "Target must be a descendant of the Source.");
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +0000920#endif
Chandler Carruthe5944d92016-02-17 00:18:16 +0000921
922 // Edges between RefSCCs are the same regardless of call or ref, so we can
923 // just flip the edge here.
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000924 SourceN->setEdgeKind(TargetN, Edge::Ref);
Chandler Carruthe5944d92016-02-17 00:18:16 +0000925
926#ifndef NDEBUG
927 // Check that the RefSCC is still valid.
928 verify();
929#endif
930}
931
932void LazyCallGraph::RefSCC::insertInternalRefEdge(Node &SourceN,
933 Node &TargetN) {
934 assert(G->lookupRefSCC(SourceN) == this && "Source must be in this RefSCC.");
935 assert(G->lookupRefSCC(TargetN) == this && "Target must be in this RefSCC.");
936
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000937 SourceN->insertEdgeInternal(TargetN, Edge::Ref);
Chandler Carruthe5944d92016-02-17 00:18:16 +0000938
939#ifndef NDEBUG
940 // Check that the RefSCC is still valid.
941 verify();
942#endif
943}
944
945void LazyCallGraph::RefSCC::insertOutgoingEdge(Node &SourceN, Node &TargetN,
946 Edge::Kind EK) {
Chandler Carruth7cc4ed82014-05-01 12:18:20 +0000947 // First insert it into the caller.
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000948 SourceN->insertEdgeInternal(TargetN, EK);
Chandler Carruth7cc4ed82014-05-01 12:18:20 +0000949
Chandler Carruthe5944d92016-02-17 00:18:16 +0000950 assert(G->lookupRefSCC(SourceN) == this && "Source must be in this RefSCC.");
Chandler Carruth7cc4ed82014-05-01 12:18:20 +0000951
Chandler Carruth691d0242017-08-05 08:33:16 +0000952 assert(G->lookupRefSCC(TargetN) != this &&
953 "Target must not be in this RefSCC.");
Francis Visoiu Mistrih262ad162017-02-28 18:34:55 +0000954#ifdef EXPENSIVE_CHECKS
Chandler Carruth691d0242017-08-05 08:33:16 +0000955 assert(G->lookupRefSCC(TargetN)->isDescendantOf(*this) &&
Chandler Carruthe5944d92016-02-17 00:18:16 +0000956 "Target must be a descendant of the Source.");
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +0000957#endif
Chandler Carruth7cc4ed82014-05-01 12:18:20 +0000958
Chandler Carruthe5944d92016-02-17 00:18:16 +0000959#ifndef NDEBUG
960 // Check that the RefSCC is still valid.
961 verify();
962#endif
Chandler Carruth7cc4ed82014-05-01 12:18:20 +0000963}
964
Chandler Carruthe5944d92016-02-17 00:18:16 +0000965SmallVector<LazyCallGraph::RefSCC *, 1>
966LazyCallGraph::RefSCC::insertIncomingRefEdge(Node &SourceN, Node &TargetN) {
Chandler Carruth49d728a2016-09-16 10:20:17 +0000967 assert(G->lookupRefSCC(TargetN) == this && "Target must be in this RefSCC.");
968 RefSCC &SourceC = *G->lookupRefSCC(SourceN);
969 assert(&SourceC != this && "Source must not be in this RefSCC.");
Francis Visoiu Mistrih262ad162017-02-28 18:34:55 +0000970#ifdef EXPENSIVE_CHECKS
Chandler Carruth49d728a2016-09-16 10:20:17 +0000971 assert(SourceC.isDescendantOf(*this) &&
972 "Source must be a descendant of the Target.");
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +0000973#endif
Chandler Carruth49d728a2016-09-16 10:20:17 +0000974
975 SmallVector<RefSCC *, 1> DeletedRefSCCs;
Chandler Carruth312dddf2014-05-04 09:38:32 +0000976
Chandler Carruth11b3f602016-09-04 08:34:31 +0000977#ifndef NDEBUG
978 // In a debug build, verify the RefSCC is valid to start with and when this
979 // routine finishes.
980 verify();
981 auto VerifyOnExit = make_scope_exit([&]() { verify(); });
982#endif
983
Chandler Carruth49d728a2016-09-16 10:20:17 +0000984 int SourceIdx = G->RefSCCIndices[&SourceC];
985 int TargetIdx = G->RefSCCIndices[this];
986 assert(SourceIdx < TargetIdx &&
987 "Postorder list doesn't see edge as incoming!");
Chandler Carruth312dddf2014-05-04 09:38:32 +0000988
Chandler Carruth49d728a2016-09-16 10:20:17 +0000989 // Compute the RefSCCs which (transitively) reach the source. We do this by
990 // working backwards from the source using the parent set in each RefSCC,
991 // skipping any RefSCCs that don't fall in the postorder range. This has the
992 // advantage of walking the sparser parent edge (in high fan-out graphs) but
993 // more importantly this removes examining all forward edges in all RefSCCs
994 // within the postorder range which aren't in fact connected. Only connected
995 // RefSCCs (and their edges) are visited here.
996 auto ComputeSourceConnectedSet = [&](SmallPtrSetImpl<RefSCC *> &Set) {
997 Set.insert(&SourceC);
Chandler Carruth13ffd112017-08-05 03:37:37 +0000998 auto IsConnected = [&](RefSCC &RC) {
999 for (SCC &C : RC)
1000 for (Node &N : C)
1001 for (Edge &E : *N)
1002 if (Set.count(G->lookupRefSCC(E.getNode())))
1003 return true;
1004
1005 return false;
1006 };
1007
1008 for (RefSCC *C : make_range(G->PostOrderRefSCCs.begin() + SourceIdx + 1,
1009 G->PostOrderRefSCCs.begin() + TargetIdx + 1))
1010 if (IsConnected(*C))
1011 Set.insert(C);
Chandler Carruth49d728a2016-09-16 10:20:17 +00001012 };
Chandler Carruth312dddf2014-05-04 09:38:32 +00001013
Chandler Carruth49d728a2016-09-16 10:20:17 +00001014 // Use a normal worklist to find which SCCs the target connects to. We still
1015 // bound the search based on the range in the postorder list we care about,
1016 // but because this is forward connectivity we just "recurse" through the
1017 // edges.
1018 auto ComputeTargetConnectedSet = [&](SmallPtrSetImpl<RefSCC *> &Set) {
1019 Set.insert(this);
1020 SmallVector<RefSCC *, 4> Worklist;
1021 Worklist.push_back(this);
1022 do {
1023 RefSCC &RC = *Worklist.pop_back_val();
1024 for (SCC &C : RC)
1025 for (Node &N : C)
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001026 for (Edge &E : *N) {
1027 RefSCC &EdgeRC = *G->lookupRefSCC(E.getNode());
Chandler Carruth49d728a2016-09-16 10:20:17 +00001028 if (G->getRefSCCIndex(EdgeRC) <= SourceIdx)
1029 // Not in the postorder sequence between source and target.
1030 continue;
Chandler Carruth312dddf2014-05-04 09:38:32 +00001031
Chandler Carruth49d728a2016-09-16 10:20:17 +00001032 if (Set.insert(&EdgeRC).second)
1033 Worklist.push_back(&EdgeRC);
1034 }
1035 } while (!Worklist.empty());
1036 };
1037
1038 // Use a generic helper to update the postorder sequence of RefSCCs and return
1039 // a range of any RefSCCs connected into a cycle by inserting this edge. This
1040 // routine will also take care of updating the indices into the postorder
1041 // sequence.
1042 iterator_range<SmallVectorImpl<RefSCC *>::iterator> MergeRange =
1043 updatePostorderSequenceForEdgeInsertion(
1044 SourceC, *this, G->PostOrderRefSCCs, G->RefSCCIndices,
1045 ComputeSourceConnectedSet, ComputeTargetConnectedSet);
1046
Chandler Carruth5205c352016-12-07 01:42:40 +00001047 // Build a set so we can do fast tests for whether a RefSCC will end up as
1048 // part of the merged RefSCC.
Chandler Carruth49d728a2016-09-16 10:20:17 +00001049 SmallPtrSet<RefSCC *, 16> MergeSet(MergeRange.begin(), MergeRange.end());
Chandler Carruth312dddf2014-05-04 09:38:32 +00001050
Chandler Carruth5205c352016-12-07 01:42:40 +00001051 // This RefSCC will always be part of that set, so just insert it here.
1052 MergeSet.insert(this);
1053
Chandler Carruth312dddf2014-05-04 09:38:32 +00001054 // Now that we have identified all of the SCCs which need to be merged into
1055 // a connected set with the inserted edge, merge all of them into this SCC.
Chandler Carruthe5944d92016-02-17 00:18:16 +00001056 SmallVector<SCC *, 16> MergedSCCs;
1057 int SCCIndex = 0;
Chandler Carruth49d728a2016-09-16 10:20:17 +00001058 for (RefSCC *RC : MergeRange) {
1059 assert(RC != this && "We're merging into the target RefSCC, so it "
1060 "shouldn't be in the range.");
Chandler Carruth312dddf2014-05-04 09:38:32 +00001061
Chandler Carruthe5944d92016-02-17 00:18:16 +00001062 // Walk the inner SCCs to update their up-pointer and walk all the edges to
1063 // update any parent sets.
1064 // FIXME: We should try to find a way to avoid this (rather expensive) edge
1065 // walk by updating the parent sets in some other manner.
Chandler Carruth49d728a2016-09-16 10:20:17 +00001066 for (SCC &InnerC : *RC) {
Chandler Carruthe5944d92016-02-17 00:18:16 +00001067 InnerC.OuterRefSCC = this;
1068 SCCIndices[&InnerC] = SCCIndex++;
Chandler Carruthadbf14a2017-08-05 07:37:00 +00001069 for (Node &N : InnerC)
Chandler Carruthe5944d92016-02-17 00:18:16 +00001070 G->SCCMap[&N] = &InnerC;
Chandler Carruth312dddf2014-05-04 09:38:32 +00001071 }
Chandler Carruthe5944d92016-02-17 00:18:16 +00001072
1073 // Now merge in the SCCs. We can actually move here so try to reuse storage
1074 // the first time through.
1075 if (MergedSCCs.empty())
Chandler Carruth49d728a2016-09-16 10:20:17 +00001076 MergedSCCs = std::move(RC->SCCs);
Chandler Carruthe5944d92016-02-17 00:18:16 +00001077 else
Chandler Carruth49d728a2016-09-16 10:20:17 +00001078 MergedSCCs.append(RC->SCCs.begin(), RC->SCCs.end());
1079 RC->SCCs.clear();
1080 DeletedRefSCCs.push_back(RC);
Chandler Carruth312dddf2014-05-04 09:38:32 +00001081 }
Chandler Carruthe5944d92016-02-17 00:18:16 +00001082
Chandler Carruth49d728a2016-09-16 10:20:17 +00001083 // Append our original SCCs to the merged list and move it into place.
Chandler Carruthe5944d92016-02-17 00:18:16 +00001084 for (SCC &InnerC : *this)
1085 SCCIndices[&InnerC] = SCCIndex++;
1086 MergedSCCs.append(SCCs.begin(), SCCs.end());
1087 SCCs = std::move(MergedSCCs);
1088
Chandler Carruth49d728a2016-09-16 10:20:17 +00001089 // Remove the merged away RefSCCs from the post order sequence.
1090 for (RefSCC *RC : MergeRange)
1091 G->RefSCCIndices.erase(RC);
1092 int IndexOffset = MergeRange.end() - MergeRange.begin();
1093 auto EraseEnd =
1094 G->PostOrderRefSCCs.erase(MergeRange.begin(), MergeRange.end());
1095 for (RefSCC *RC : make_range(EraseEnd, G->PostOrderRefSCCs.end()))
1096 G->RefSCCIndices[RC] -= IndexOffset;
1097
Chandler Carruthe5944d92016-02-17 00:18:16 +00001098 // At this point we have a merged RefSCC with a post-order SCCs list, just
1099 // connect the nodes to form the new edge.
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001100 SourceN->insertEdgeInternal(TargetN, Edge::Ref);
Chandler Carruthe5944d92016-02-17 00:18:16 +00001101
Chandler Carruth312dddf2014-05-04 09:38:32 +00001102 // We return the list of SCCs which were merged so that callers can
1103 // invalidate any data they have associated with those SCCs. Note that these
1104 // SCCs are no longer in an interesting state (they are totally empty) but
1105 // the pointers will remain stable for the life of the graph itself.
Chandler Carruth49d728a2016-09-16 10:20:17 +00001106 return DeletedRefSCCs;
Chandler Carruth312dddf2014-05-04 09:38:32 +00001107}
1108
Chandler Carruthe5944d92016-02-17 00:18:16 +00001109void LazyCallGraph::RefSCC::removeOutgoingEdge(Node &SourceN, Node &TargetN) {
1110 assert(G->lookupRefSCC(SourceN) == this &&
1111 "The source must be a member of this RefSCC.");
Benjamin Krameref42fd42017-08-05 08:28:48 +00001112 assert(G->lookupRefSCC(TargetN) != this &&
1113 "The target must not be a member of this RefSCC");
Chandler Carruthe5944d92016-02-17 00:18:16 +00001114
Chandler Carruth11b3f602016-09-04 08:34:31 +00001115#ifndef NDEBUG
1116 // In a debug build, verify the RefSCC is valid to start with and when this
1117 // routine finishes.
1118 verify();
1119 auto VerifyOnExit = make_scope_exit([&]() { verify(); });
1120#endif
1121
Chandler Carruthaa839b22014-04-27 01:59:50 +00001122 // First remove it from the node.
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001123 bool Removed = SourceN->removeEdgeInternal(TargetN);
1124 (void)Removed;
1125 assert(Removed && "Target not in the edge set for this caller?");
Chandler Carruthaca48d02014-04-26 09:06:53 +00001126}
1127
Chandler Carruthe5944d92016-02-17 00:18:16 +00001128SmallVector<LazyCallGraph::RefSCC *, 1>
Chandler Carruth23c2f442017-08-09 09:05:27 +00001129LazyCallGraph::RefSCC::removeInternalRefEdge(Node &SourceN,
1130 ArrayRef<Node *> TargetNs) {
Chandler Carruthe5944d92016-02-17 00:18:16 +00001131 // We return a list of the resulting *new* RefSCCs in post-order.
1132 SmallVector<RefSCC *, 1> Result;
Chandler Carruth9302fbf2014-04-23 11:03:03 +00001133
Chandler Carruth23c2f442017-08-09 09:05:27 +00001134#ifndef NDEBUG
1135 // In a debug build, verify the RefSCC is valid to start with and that either
1136 // we return an empty list of result RefSCCs and this RefSCC remains valid,
1137 // or we return new RefSCCs and this RefSCC is dead.
1138 verify();
1139 auto VerifyOnExit = make_scope_exit([&]() {
Chandler Carruth9c161e82017-08-10 03:05:21 +00001140 // If we didn't replace our RefSCC with new ones, check that this one
1141 // remains valid.
1142 if (G)
Chandler Carruth23c2f442017-08-09 09:05:27 +00001143 verify();
Chandler Carruth23c2f442017-08-09 09:05:27 +00001144 });
1145#endif
1146
1147 // First remove the actual edges.
1148 for (Node *TargetN : TargetNs) {
1149 assert(!(*SourceN)[*TargetN].isCall() &&
1150 "Cannot remove a call edge, it must first be made a ref edge");
1151
1152 bool Removed = SourceN->removeEdgeInternal(*TargetN);
1153 (void)Removed;
1154 assert(Removed && "Target not in the edge set for this caller?");
1155 }
1156
1157 // Direct self references don't impact the ref graph at all.
1158 if (llvm::all_of(TargetNs,
1159 [&](Node *TargetN) { return &SourceN == TargetN; }))
Chandler Carruthe5944d92016-02-17 00:18:16 +00001160 return Result;
Chandler Carrutha7205b62014-04-26 03:36:37 +00001161
Chandler Carruth23c2f442017-08-09 09:05:27 +00001162 // If all targets are in the same SCC as the source, because no call edges
1163 // were removed there is no RefSCC structure change.
Chandler Carruthc6334572016-12-28 02:24:58 +00001164 SCC &SourceC = *G->lookupSCC(SourceN);
Chandler Carruth23c2f442017-08-09 09:05:27 +00001165 if (llvm::all_of(TargetNs, [&](Node *TargetN) {
1166 return G->lookupSCC(*TargetN) == &SourceC;
1167 }))
Chandler Carruthc6334572016-12-28 02:24:58 +00001168 return Result;
1169
Chandler Carruthe5944d92016-02-17 00:18:16 +00001170 // We build somewhat synthetic new RefSCCs by providing a postorder mapping
Chandler Carruth2cd28b22017-08-09 09:37:39 +00001171 // for each inner SCC. We store these inside the low-link field of the nodes
1172 // rather than associated with SCCs because this saves a round-trip through
1173 // the node->SCC map and in the common case, SCCs are small. We will verify
1174 // that we always give the same number to every node in the SCC such that
1175 // these are equivalent.
Chandler Carruth23c2f442017-08-09 09:05:27 +00001176 int PostOrderNumber = 0;
Chandler Carruthe5944d92016-02-17 00:18:16 +00001177
Chandler Carruthe5944d92016-02-17 00:18:16 +00001178 // Reset all the other nodes to prepare for a DFS over them, and add them to
1179 // our worklist.
1180 SmallVector<Node *, 8> Worklist;
1181 for (SCC *C : SCCs) {
Chandler Carruthe5944d92016-02-17 00:18:16 +00001182 for (Node &N : *C)
1183 N.DFSNumber = N.LowLink = 0;
1184
1185 Worklist.append(C->Nodes.begin(), C->Nodes.end());
Chandler Carruth9302fbf2014-04-23 11:03:03 +00001186 }
1187
Chandler Carruth9c3deaa2017-08-09 09:14:34 +00001188 // Track the number of nodes in this RefSCC so that we can quickly recognize
1189 // an important special case of the edge removal not breaking the cycle of
1190 // this RefSCC.
1191 const int NumRefSCCNodes = Worklist.size();
1192
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001193 SmallVector<std::pair<Node *, EdgeSequence::iterator>, 4> DFSStack;
Chandler Carruthe5944d92016-02-17 00:18:16 +00001194 SmallVector<Node *, 4> PendingRefSCCStack;
Chandler Carruthaca48d02014-04-26 09:06:53 +00001195 do {
Chandler Carruthe5944d92016-02-17 00:18:16 +00001196 assert(DFSStack.empty() &&
1197 "Cannot begin a new root with a non-empty DFS stack!");
1198 assert(PendingRefSCCStack.empty() &&
1199 "Cannot begin a new root with pending nodes for an SCC!");
1200
1201 Node *RootN = Worklist.pop_back_val();
1202 // Skip any nodes we've already reached in the DFS.
1203 if (RootN->DFSNumber != 0) {
1204 assert(RootN->DFSNumber == -1 &&
1205 "Shouldn't have any mid-DFS root nodes!");
1206 continue;
1207 }
1208
1209 RootN->DFSNumber = RootN->LowLink = 1;
1210 int NextDFSNumber = 2;
1211
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001212 DFSStack.push_back({RootN, (*RootN)->begin()});
Chandler Carruthe5944d92016-02-17 00:18:16 +00001213 do {
1214 Node *N;
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001215 EdgeSequence::iterator I;
Chandler Carruthe5944d92016-02-17 00:18:16 +00001216 std::tie(N, I) = DFSStack.pop_back_val();
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001217 auto E = (*N)->end();
Chandler Carruthe5944d92016-02-17 00:18:16 +00001218
1219 assert(N->DFSNumber != 0 && "We should always assign a DFS number "
1220 "before processing a node.");
1221
1222 while (I != E) {
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001223 Node &ChildN = I->getNode();
Chandler Carruthe5944d92016-02-17 00:18:16 +00001224 if (ChildN.DFSNumber == 0) {
1225 // Mark that we should start at this child when next this node is the
1226 // top of the stack. We don't start at the next child to ensure this
1227 // child's lowlink is reflected.
1228 DFSStack.push_back({N, I});
1229
1230 // Continue, resetting to the child node.
1231 ChildN.LowLink = ChildN.DFSNumber = NextDFSNumber++;
1232 N = &ChildN;
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001233 I = ChildN->begin();
1234 E = ChildN->end();
Chandler Carruthe5944d92016-02-17 00:18:16 +00001235 continue;
1236 }
1237 if (ChildN.DFSNumber == -1) {
Chandler Carruthe5944d92016-02-17 00:18:16 +00001238 // If this child isn't currently in this RefSCC, no need to process
Chandler Carruthadbf14a2017-08-05 07:37:00 +00001239 // it.
Chandler Carruthe5944d92016-02-17 00:18:16 +00001240 ++I;
1241 continue;
1242 }
1243
1244 // Track the lowest link of the children, if any are still in the stack.
1245 // Any child not on the stack will have a LowLink of -1.
1246 assert(ChildN.LowLink != 0 &&
1247 "Low-link must not be zero with a non-zero DFS number.");
1248 if (ChildN.LowLink >= 0 && ChildN.LowLink < N->LowLink)
1249 N->LowLink = ChildN.LowLink;
1250 ++I;
1251 }
Chandler Carruthe5944d92016-02-17 00:18:16 +00001252
Vedant Kumar1a8456d2018-03-02 18:57:02 +00001253 // We've finished processing N and its descendants, put it on our pending
Chandler Carruthe5944d92016-02-17 00:18:16 +00001254 // stack to eventually get merged into a RefSCC.
1255 PendingRefSCCStack.push_back(N);
1256
1257 // If this node is linked to some lower entry, continue walking up the
1258 // stack.
1259 if (N->LowLink != N->DFSNumber) {
1260 assert(!DFSStack.empty() &&
1261 "We never found a viable root for a RefSCC to pop off!");
1262 continue;
1263 }
1264
1265 // Otherwise, form a new RefSCC from the top of the pending node stack.
Chandler Carruth2cd28b22017-08-09 09:37:39 +00001266 int RefSCCNumber = PostOrderNumber++;
Chandler Carruthe5944d92016-02-17 00:18:16 +00001267 int RootDFSNumber = N->DFSNumber;
Chandler Carruth2cd28b22017-08-09 09:37:39 +00001268
Chandler Carruthe5944d92016-02-17 00:18:16 +00001269 // Find the range of the node stack by walking down until we pass the
Chandler Carruth2cd28b22017-08-09 09:37:39 +00001270 // root DFS number. Update the DFS numbers and low link numbers in the
1271 // process to avoid re-walking this list where possible.
1272 auto StackRI = find_if(reverse(PendingRefSCCStack), [&](Node *N) {
1273 if (N->DFSNumber < RootDFSNumber)
1274 // We've found the bottom.
1275 return true;
1276
1277 // Update this node and keep scanning.
1278 N->DFSNumber = -1;
1279 // Save the post-order number in the lowlink field so that we can use
1280 // it to map SCCs into new RefSCCs after we finish the DFS.
1281 N->LowLink = RefSCCNumber;
1282 return false;
1283 });
1284 auto RefSCCNodes = make_range(StackRI.base(), PendingRefSCCStack.end());
Chandler Carruth9c3deaa2017-08-09 09:14:34 +00001285
1286 // If we find a cycle containing all nodes originally in this RefSCC then
1287 // the removal hasn't changed the structure at all. This is an important
1288 // special case and we can directly exit the entire routine more
1289 // efficiently as soon as we discover it.
Vedant Kumar5a0872c2018-05-16 23:20:42 +00001290 if (llvm::size(RefSCCNodes) == NumRefSCCNodes) {
Chandler Carruth2cd28b22017-08-09 09:37:39 +00001291 // Clear out the low link field as we won't need it.
Chandler Carruth9c3deaa2017-08-09 09:14:34 +00001292 for (Node *N : RefSCCNodes)
Chandler Carruth2cd28b22017-08-09 09:37:39 +00001293 N->LowLink = -1;
Chandler Carruth9c3deaa2017-08-09 09:14:34 +00001294 // Return the empty result immediately.
1295 return Result;
1296 }
Chandler Carruthe5944d92016-02-17 00:18:16 +00001297
Chandler Carruth2cd28b22017-08-09 09:37:39 +00001298 // We've already marked the nodes internally with the RefSCC number so
1299 // just clear them off the stack and continue.
Chandler Carruth9c3deaa2017-08-09 09:14:34 +00001300 PendingRefSCCStack.erase(RefSCCNodes.begin(), PendingRefSCCStack.end());
Chandler Carruthe5944d92016-02-17 00:18:16 +00001301 } while (!DFSStack.empty());
Chandler Carruth9302fbf2014-04-23 11:03:03 +00001302
Chandler Carruthaca48d02014-04-26 09:06:53 +00001303 assert(DFSStack.empty() && "Didn't flush the entire DFS stack!");
Chandler Carruthe5944d92016-02-17 00:18:16 +00001304 assert(PendingRefSCCStack.empty() && "Didn't flush all pending nodes!");
Chandler Carruthaca48d02014-04-26 09:06:53 +00001305 } while (!Worklist.empty());
Chandler Carruth9302fbf2014-04-23 11:03:03 +00001306
Chandler Carruth9c3deaa2017-08-09 09:14:34 +00001307 assert(PostOrderNumber > 1 &&
1308 "Should never finish the DFS when the existing RefSCC remains valid!");
Chandler Carruth23c2f442017-08-09 09:05:27 +00001309
1310 // Otherwise we create a collection of new RefSCC nodes and build
1311 // a radix-sort style map from postorder number to these new RefSCCs. We then
Malcolm Parsons21e545d2018-01-24 10:33:39 +00001312 // append SCCs to each of these RefSCCs in the order they occurred in the
Chandler Carruth23c2f442017-08-09 09:05:27 +00001313 // original SCCs container.
1314 for (int i = 0; i < PostOrderNumber; ++i)
Chandler Carruthe5944d92016-02-17 00:18:16 +00001315 Result.push_back(G->createRefSCC(*G));
1316
Chandler Carruth49d728a2016-09-16 10:20:17 +00001317 // Insert the resulting postorder sequence into the global graph postorder
Chandler Carruth23c2f442017-08-09 09:05:27 +00001318 // sequence before the current RefSCC in that sequence, and then remove the
1319 // current one.
Chandler Carruth49d728a2016-09-16 10:20:17 +00001320 //
1321 // FIXME: It'd be nice to change the APIs so that we returned an iterator
1322 // range over the global postorder sequence and generally use that sequence
1323 // rather than building a separate result vector here.
Chandler Carruth23c2f442017-08-09 09:05:27 +00001324 int Idx = G->getRefSCCIndex(*this);
1325 G->PostOrderRefSCCs.erase(G->PostOrderRefSCCs.begin() + Idx);
1326 G->PostOrderRefSCCs.insert(G->PostOrderRefSCCs.begin() + Idx, Result.begin(),
1327 Result.end());
1328 for (int i : seq<int>(Idx, G->PostOrderRefSCCs.size()))
1329 G->RefSCCIndices[G->PostOrderRefSCCs[i]] = i;
Chandler Carruth49d728a2016-09-16 10:20:17 +00001330
Chandler Carruthe5944d92016-02-17 00:18:16 +00001331 for (SCC *C : SCCs) {
Chandler Carruth2cd28b22017-08-09 09:37:39 +00001332 // We store the SCC number in the node's low-link field above.
1333 int SCCNumber = C->begin()->LowLink;
1334 // Clear out all of the SCC's node's low-link fields now that we're done
1335 // using them as side-storage.
1336 for (Node &N : *C) {
1337 assert(N.LowLink == SCCNumber &&
Chandler Carruthe5944d92016-02-17 00:18:16 +00001338 "Cannot have different numbers for nodes in the same SCC!");
Chandler Carruth2cd28b22017-08-09 09:37:39 +00001339 N.LowLink = -1;
1340 }
Chandler Carruthe5944d92016-02-17 00:18:16 +00001341
Chandler Carruth23c2f442017-08-09 09:05:27 +00001342 RefSCC &RC = *Result[SCCNumber];
Chandler Carruthe5944d92016-02-17 00:18:16 +00001343 int SCCIndex = RC.SCCs.size();
1344 RC.SCCs.push_back(C);
Chandler Carruth23a6c3f2016-12-06 10:29:23 +00001345 RC.SCCIndices[C] = SCCIndex;
Chandler Carruthe5944d92016-02-17 00:18:16 +00001346 C->OuterRefSCC = &RC;
1347 }
1348
Chandler Carruth23c2f442017-08-09 09:05:27 +00001349 // Now that we've moved things into the new RefSCCs, clear out our current
1350 // one.
1351 G = nullptr;
1352 SCCs.clear();
Chandler Carruth88823462016-08-24 09:37:14 +00001353 SCCIndices.clear();
Chandler Carruth23a6c3f2016-12-06 10:29:23 +00001354
Chandler Carruth9c161e82017-08-10 03:05:21 +00001355#ifndef NDEBUG
1356 // Verify the new RefSCCs we've built.
1357 for (RefSCC *RC : Result)
1358 RC->verify();
1359#endif
1360
Chandler Carruth9302fbf2014-04-23 11:03:03 +00001361 // Return the new list of SCCs.
Chandler Carruthe5944d92016-02-17 00:18:16 +00001362 return Result;
Chandler Carruth9302fbf2014-04-23 11:03:03 +00001363}
1364
Chandler Carruth5dbc1642016-10-12 07:59:56 +00001365void LazyCallGraph::RefSCC::handleTrivialEdgeInsertion(Node &SourceN,
1366 Node &TargetN) {
1367 // The only trivial case that requires any graph updates is when we add new
1368 // ref edge and may connect different RefSCCs along that path. This is only
1369 // because of the parents set. Every other part of the graph remains constant
1370 // after this edge insertion.
1371 assert(G->lookupRefSCC(SourceN) == this && "Source must be in this RefSCC.");
1372 RefSCC &TargetRC = *G->lookupRefSCC(TargetN);
Eugene Zelenko530851c2017-08-11 21:30:02 +00001373 if (&TargetRC == this)
Chandler Carruth5dbc1642016-10-12 07:59:56 +00001374 return;
Chandler Carruth5dbc1642016-10-12 07:59:56 +00001375
Francis Visoiu Mistrih262ad162017-02-28 18:34:55 +00001376#ifdef EXPENSIVE_CHECKS
Chandler Carruth5dbc1642016-10-12 07:59:56 +00001377 assert(TargetRC.isDescendantOf(*this) &&
1378 "Target must be a descendant of the Source.");
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001379#endif
Chandler Carruth5dbc1642016-10-12 07:59:56 +00001380}
1381
1382void LazyCallGraph::RefSCC::insertTrivialCallEdge(Node &SourceN,
1383 Node &TargetN) {
1384#ifndef NDEBUG
1385 // Check that the RefSCC is still valid when we finish.
1386 auto ExitVerifier = make_scope_exit([this] { verify(); });
Chandler Carruthbae595b2016-11-22 19:23:31 +00001387
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001388#ifdef EXPENSIVE_CHECKS
1389 // Check that we aren't breaking some invariants of the SCC graph. Note that
1390 // this is quadratic in the number of edges in the call graph!
Chandler Carruthbae595b2016-11-22 19:23:31 +00001391 SCC &SourceC = *G->lookupSCC(SourceN);
1392 SCC &TargetC = *G->lookupSCC(TargetN);
1393 if (&SourceC != &TargetC)
1394 assert(SourceC.isAncestorOf(TargetC) &&
1395 "Call edge is not trivial in the SCC graph!");
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001396#endif // EXPENSIVE_CHECKS
1397#endif // NDEBUG
1398
Chandler Carruth5dbc1642016-10-12 07:59:56 +00001399 // First insert it into the source or find the existing edge.
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001400 auto InsertResult =
1401 SourceN->EdgeIndexMap.insert({&TargetN, SourceN->Edges.size()});
Chandler Carruth5dbc1642016-10-12 07:59:56 +00001402 if (!InsertResult.second) {
1403 // Already an edge, just update it.
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001404 Edge &E = SourceN->Edges[InsertResult.first->second];
Chandler Carruth5dbc1642016-10-12 07:59:56 +00001405 if (E.isCall())
1406 return; // Nothing to do!
1407 E.setKind(Edge::Call);
1408 } else {
1409 // Create the new edge.
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001410 SourceN->Edges.emplace_back(TargetN, Edge::Call);
Chandler Carruth5dbc1642016-10-12 07:59:56 +00001411 }
1412
1413 // Now that we have the edge, handle the graph fallout.
1414 handleTrivialEdgeInsertion(SourceN, TargetN);
1415}
1416
1417void LazyCallGraph::RefSCC::insertTrivialRefEdge(Node &SourceN, Node &TargetN) {
1418#ifndef NDEBUG
1419 // Check that the RefSCC is still valid when we finish.
1420 auto ExitVerifier = make_scope_exit([this] { verify(); });
Chandler Carruth9eb857c2016-11-22 21:40:10 +00001421
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001422#ifdef EXPENSIVE_CHECKS
Chandler Carruth9eb857c2016-11-22 21:40:10 +00001423 // Check that we aren't breaking some invariants of the RefSCC graph.
1424 RefSCC &SourceRC = *G->lookupRefSCC(SourceN);
1425 RefSCC &TargetRC = *G->lookupRefSCC(TargetN);
1426 if (&SourceRC != &TargetRC)
1427 assert(SourceRC.isAncestorOf(TargetRC) &&
1428 "Ref edge is not trivial in the RefSCC graph!");
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001429#endif // EXPENSIVE_CHECKS
1430#endif // NDEBUG
1431
Chandler Carruth5dbc1642016-10-12 07:59:56 +00001432 // First insert it into the source or find the existing edge.
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001433 auto InsertResult =
1434 SourceN->EdgeIndexMap.insert({&TargetN, SourceN->Edges.size()});
Chandler Carruth5dbc1642016-10-12 07:59:56 +00001435 if (!InsertResult.second)
1436 // Already an edge, we're done.
1437 return;
1438
1439 // Create the new edge.
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001440 SourceN->Edges.emplace_back(TargetN, Edge::Ref);
Chandler Carruth5dbc1642016-10-12 07:59:56 +00001441
1442 // Now that we have the edge, handle the graph fallout.
1443 handleTrivialEdgeInsertion(SourceN, TargetN);
1444}
1445
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001446void LazyCallGraph::RefSCC::replaceNodeFunction(Node &N, Function &NewF) {
1447 Function &OldF = N.getFunction();
Chandler Carruthc00a7ff2014-04-28 11:10:23 +00001448
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001449#ifndef NDEBUG
1450 // Check that the RefSCC is still valid when we finish.
1451 auto ExitVerifier = make_scope_exit([this] { verify(); });
1452
1453 assert(G->lookupRefSCC(N) == this &&
1454 "Cannot replace the function of a node outside this RefSCC.");
1455
1456 assert(G->NodeMap.find(&NewF) == G->NodeMap.end() &&
1457 "Must not have already walked the new function!'");
1458
1459 // It is important that this replacement not introduce graph changes so we
1460 // insist that the caller has already removed every use of the original
1461 // function and that all uses of the new function correspond to existing
1462 // edges in the graph. The common and expected way to use this is when
1463 // replacing the function itself in the IR without changing the call graph
1464 // shape and just updating the analysis based on that.
1465 assert(&OldF != &NewF && "Cannot replace a function with itself!");
1466 assert(OldF.use_empty() &&
1467 "Must have moved all uses from the old function to the new!");
1468#endif
1469
1470 N.replaceFunction(NewF);
1471
1472 // Update various call graph maps.
1473 G->NodeMap.erase(&OldF);
1474 G->NodeMap[&NewF] = &N;
Chandler Carruthc00a7ff2014-04-28 11:10:23 +00001475}
1476
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001477void LazyCallGraph::insertEdge(Node &SourceN, Node &TargetN, Edge::Kind EK) {
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001478 assert(SCCMap.empty() &&
Chandler Carruthaa839b22014-04-27 01:59:50 +00001479 "This method cannot be called after SCCs have been formed!");
Chandler Carruth9302fbf2014-04-23 11:03:03 +00001480
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001481 return SourceN->insertEdgeInternal(TargetN, EK);
1482}
1483
1484void LazyCallGraph::removeEdge(Node &SourceN, Node &TargetN) {
1485 assert(SCCMap.empty() &&
1486 "This method cannot be called after SCCs have been formed!");
1487
1488 bool Removed = SourceN->removeEdgeInternal(TargetN);
1489 (void)Removed;
1490 assert(Removed && "Target not in the edge set for this caller?");
Chandler Carruth9302fbf2014-04-23 11:03:03 +00001491}
1492
Chandler Carruth5dbc1642016-10-12 07:59:56 +00001493void LazyCallGraph::removeDeadFunction(Function &F) {
1494 // FIXME: This is unnecessarily restrictive. We should be able to remove
1495 // functions which recursively call themselves.
1496 assert(F.use_empty() &&
1497 "This routine should only be called on trivially dead functions!");
1498
Chandler Carruth06a86302017-07-19 04:12:25 +00001499 // We shouldn't remove library functions as they are never really dead while
1500 // the call graph is in use -- every function definition refers to them.
1501 assert(!isLibFunction(F) &&
1502 "Must not remove lib functions from the call graph!");
1503
Chandler Carruth5dbc1642016-10-12 07:59:56 +00001504 auto NI = NodeMap.find(&F);
1505 if (NI == NodeMap.end())
1506 // Not in the graph at all!
1507 return;
1508
1509 Node &N = *NI->second;
1510 NodeMap.erase(NI);
1511
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001512 // Remove this from the entry edges if present.
1513 EntryEdges.removeEdgeInternal(N);
1514
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001515 if (SCCMap.empty()) {
1516 // No SCCs have been formed, so removing this is fine and there is nothing
Chandler Carruth5dbc1642016-10-12 07:59:56 +00001517 // else necessary at this point but clearing out the node.
1518 N.clear();
1519 return;
1520 }
1521
Chandler Carruth5dbc1642016-10-12 07:59:56 +00001522 // Cannot remove a function which has yet to be visited in the DFS walk, so
1523 // if we have a node at all then we must have an SCC and RefSCC.
1524 auto CI = SCCMap.find(&N);
1525 assert(CI != SCCMap.end() &&
1526 "Tried to remove a node without an SCC after DFS walk started!");
1527 SCC &C = *CI->second;
1528 SCCMap.erase(CI);
1529 RefSCC &RC = C.getOuterRefSCC();
1530
1531 // This node must be the only member of its SCC as it has no callers, and
1532 // that SCC must be the only member of a RefSCC as it has no references.
1533 // Validate these properties first.
1534 assert(C.size() == 1 && "Dead functions must be in a singular SCC");
1535 assert(RC.size() == 1 && "Dead functions must be in a singular RefSCC");
Chandler Carruth1f8fcfe2017-02-09 23:30:14 +00001536
Chandler Carruth5dbc1642016-10-12 07:59:56 +00001537 auto RCIndexI = RefSCCIndices.find(&RC);
1538 int RCIndex = RCIndexI->second;
1539 PostOrderRefSCCs.erase(PostOrderRefSCCs.begin() + RCIndex);
1540 RefSCCIndices.erase(RCIndexI);
1541 for (int i = RCIndex, Size = PostOrderRefSCCs.size(); i < Size; ++i)
1542 RefSCCIndices[PostOrderRefSCCs[i]] = i;
1543
1544 // Finally clear out all the data structures from the node down through the
1545 // components.
1546 N.clear();
Chandler Carruth403d3c42017-08-05 03:37:39 +00001547 N.G = nullptr;
Chandler Carruthc718b8e2017-08-05 05:47:37 +00001548 N.F = nullptr;
Chandler Carruth5dbc1642016-10-12 07:59:56 +00001549 C.clear();
1550 RC.clear();
Chandler Carruth403d3c42017-08-05 03:37:39 +00001551 RC.G = nullptr;
Chandler Carruth5dbc1642016-10-12 07:59:56 +00001552
1553 // Nothing to delete as all the objects are allocated in stable bump pointer
1554 // allocators.
1555}
1556
Chandler Carruth2a898e02014-04-23 23:20:36 +00001557LazyCallGraph::Node &LazyCallGraph::insertInto(Function &F, Node *&MappedN) {
1558 return *new (MappedN = BPA.Allocate()) Node(*this, F);
Chandler Carruthd8d865e2014-04-18 11:02:33 +00001559}
1560
1561void LazyCallGraph::updateGraphPtrs() {
Chandler Carruth7cb23e72017-08-05 03:37:39 +00001562 // Walk the node map to update their graph pointers. While this iterates in
1563 // an unstable order, the order has no effect so it remains correct.
1564 for (auto &FunctionNodePair : NodeMap)
1565 FunctionNodePair.second->G = this;
Chandler Carruthaa839b22014-04-27 01:59:50 +00001566
Chandler Carruth2c58e1a2017-08-05 03:37:38 +00001567 for (auto *RC : PostOrderRefSCCs)
1568 RC->G = this;
Chandler Carruthbf71a342014-02-06 04:37:03 +00001569}
Chandler Carruthbf71a342014-02-06 04:37:03 +00001570
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001571template <typename RootsT, typename GetBeginT, typename GetEndT,
1572 typename GetNodeT, typename FormSCCCallbackT>
1573void LazyCallGraph::buildGenericSCCs(RootsT &&Roots, GetBeginT &&GetBegin,
1574 GetEndT &&GetEnd, GetNodeT &&GetNode,
1575 FormSCCCallbackT &&FormSCC) {
Eugene Zelenko530851c2017-08-11 21:30:02 +00001576 using EdgeItT = decltype(GetBegin(std::declval<Node &>()));
Chandler Carruth3f9869a2014-04-23 06:09:03 +00001577
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001578 SmallVector<std::pair<Node *, EdgeItT>, 16> DFSStack;
Chandler Carruthe5944d92016-02-17 00:18:16 +00001579 SmallVector<Node *, 16> PendingSCCStack;
1580
1581 // Scan down the stack and DFS across the call edges.
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001582 for (Node *RootN : Roots) {
Chandler Carruthe5944d92016-02-17 00:18:16 +00001583 assert(DFSStack.empty() &&
1584 "Cannot begin a new root with a non-empty DFS stack!");
1585 assert(PendingSCCStack.empty() &&
1586 "Cannot begin a new root with pending nodes for an SCC!");
1587
1588 // Skip any nodes we've already reached in the DFS.
1589 if (RootN->DFSNumber != 0) {
1590 assert(RootN->DFSNumber == -1 &&
1591 "Shouldn't have any mid-DFS root nodes!");
1592 continue;
Chandler Carruth3f9869a2014-04-23 06:09:03 +00001593 }
1594
Chandler Carruthe5944d92016-02-17 00:18:16 +00001595 RootN->DFSNumber = RootN->LowLink = 1;
1596 int NextDFSNumber = 2;
Chandler Carruth3f9869a2014-04-23 06:09:03 +00001597
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001598 DFSStack.push_back({RootN, GetBegin(*RootN)});
Chandler Carruthe5944d92016-02-17 00:18:16 +00001599 do {
1600 Node *N;
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001601 EdgeItT I;
Chandler Carruthe5944d92016-02-17 00:18:16 +00001602 std::tie(N, I) = DFSStack.pop_back_val();
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001603 auto E = GetEnd(*N);
Chandler Carruthe5944d92016-02-17 00:18:16 +00001604 while (I != E) {
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001605 Node &ChildN = GetNode(I);
Chandler Carruthe5944d92016-02-17 00:18:16 +00001606 if (ChildN.DFSNumber == 0) {
1607 // We haven't yet visited this child, so descend, pushing the current
1608 // node onto the stack.
1609 DFSStack.push_back({N, I});
1610
Chandler Carruthe5944d92016-02-17 00:18:16 +00001611 ChildN.DFSNumber = ChildN.LowLink = NextDFSNumber++;
1612 N = &ChildN;
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001613 I = GetBegin(*N);
1614 E = GetEnd(*N);
Chandler Carruthe5944d92016-02-17 00:18:16 +00001615 continue;
1616 }
1617
1618 // If the child has already been added to some child component, it
1619 // couldn't impact the low-link of this parent because it isn't
1620 // connected, and thus its low-link isn't relevant so skip it.
1621 if (ChildN.DFSNumber == -1) {
1622 ++I;
1623 continue;
1624 }
1625
1626 // Track the lowest linked child as the lowest link for this node.
1627 assert(ChildN.LowLink > 0 && "Must have a positive low-link number!");
1628 if (ChildN.LowLink < N->LowLink)
1629 N->LowLink = ChildN.LowLink;
1630
1631 // Move to the next edge.
1632 ++I;
1633 }
1634
Vedant Kumar1a8456d2018-03-02 18:57:02 +00001635 // We've finished processing N and its descendants, put it on our pending
Chandler Carruthe5944d92016-02-17 00:18:16 +00001636 // SCC stack to eventually get merged into an SCC of nodes.
1637 PendingSCCStack.push_back(N);
1638
1639 // If this node is linked to some lower entry, continue walking up the
1640 // stack.
1641 if (N->LowLink != N->DFSNumber)
1642 continue;
1643
1644 // Otherwise, we've completed an SCC. Append it to our post order list of
1645 // SCCs.
1646 int RootDFSNumber = N->DFSNumber;
1647 // Find the range of the node stack by walking down until we pass the
1648 // root DFS number.
1649 auto SCCNodes = make_range(
1650 PendingSCCStack.rbegin(),
David Majnemer42531262016-08-12 03:55:06 +00001651 find_if(reverse(PendingSCCStack), [RootDFSNumber](const Node *N) {
1652 return N->DFSNumber < RootDFSNumber;
1653 }));
Chandler Carruthe5944d92016-02-17 00:18:16 +00001654 // Form a new SCC out of these nodes and then clear them off our pending
1655 // stack.
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001656 FormSCC(SCCNodes);
Chandler Carruthe5944d92016-02-17 00:18:16 +00001657 PendingSCCStack.erase(SCCNodes.end().base(), PendingSCCStack.end());
1658 } while (!DFSStack.empty());
1659 }
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001660}
1661
1662/// Build the internal SCCs for a RefSCC from a sequence of nodes.
1663///
1664/// Appends the SCCs to the provided vector and updates the map with their
1665/// indices. Both the vector and map must be empty when passed into this
1666/// routine.
1667void LazyCallGraph::buildSCCs(RefSCC &RC, node_stack_range Nodes) {
1668 assert(RC.SCCs.empty() && "Already built SCCs!");
1669 assert(RC.SCCIndices.empty() && "Already mapped SCC indices!");
1670
1671 for (Node *N : Nodes) {
1672 assert(N->LowLink >= (*Nodes.begin())->LowLink &&
1673 "We cannot have a low link in an SCC lower than its root on the "
1674 "stack!");
1675
1676 // This node will go into the next RefSCC, clear out its DFS and low link
1677 // as we scan.
1678 N->DFSNumber = N->LowLink = 0;
1679 }
1680
1681 // Each RefSCC contains a DAG of the call SCCs. To build these, we do
1682 // a direct walk of the call edges using Tarjan's algorithm. We reuse the
1683 // internal storage as we won't need it for the outer graph's DFS any longer.
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001684 buildGenericSCCs(
1685 Nodes, [](Node &N) { return N->call_begin(); },
1686 [](Node &N) { return N->call_end(); },
1687 [](EdgeSequence::call_iterator I) -> Node & { return I->getNode(); },
1688 [this, &RC](node_stack_range Nodes) {
1689 RC.SCCs.push_back(createSCC(RC, Nodes));
1690 for (Node &N : *RC.SCCs.back()) {
1691 N.DFSNumber = N.LowLink = -1;
1692 SCCMap[&N] = RC.SCCs.back();
1693 }
1694 });
Chandler Carruthe5944d92016-02-17 00:18:16 +00001695
1696 // Wire up the SCC indices.
1697 for (int i = 0, Size = RC.SCCs.size(); i < Size; ++i)
1698 RC.SCCIndices[RC.SCCs[i]] = i;
Chandler Carruth3f9869a2014-04-23 06:09:03 +00001699}
1700
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001701void LazyCallGraph::buildRefSCCs() {
1702 if (EntryEdges.empty() || !PostOrderRefSCCs.empty())
1703 // RefSCCs are either non-existent or already built!
1704 return;
1705
1706 assert(RefSCCIndices.empty() && "Already mapped RefSCC indices!");
1707
1708 SmallVector<Node *, 16> Roots;
1709 for (Edge &E : *this)
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001710 Roots.push_back(&E.getNode());
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001711
1712 // The roots will be popped of a stack, so use reverse to get a less
1713 // surprising order. This doesn't change any of the semantics anywhere.
1714 std::reverse(Roots.begin(), Roots.end());
1715
1716 buildGenericSCCs(
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001717 Roots,
1718 [](Node &N) {
1719 // We need to populate each node as we begin to walk its edges.
1720 N.populate();
1721 return N->begin();
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001722 },
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001723 [](Node &N) { return N->end(); },
1724 [](EdgeSequence::iterator I) -> Node & { return I->getNode(); },
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001725 [this](node_stack_range Nodes) {
1726 RefSCC *NewRC = createRefSCC(*this);
1727 buildSCCs(*NewRC, Nodes);
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001728
1729 // Push the new node into the postorder list and remember its position
1730 // in the index map.
1731 bool Inserted =
1732 RefSCCIndices.insert({NewRC, PostOrderRefSCCs.size()}).second;
1733 (void)Inserted;
1734 assert(Inserted && "Cannot already have this RefSCC in the index map!");
1735 PostOrderRefSCCs.push_back(NewRC);
Chandler Carrutha80cfb32017-02-06 20:59:07 +00001736#ifndef NDEBUG
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001737 NewRC->verify();
Chandler Carrutha80cfb32017-02-06 20:59:07 +00001738#endif
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001739 });
1740}
1741
Chandler Carruthdab4eae2016-11-23 17:53:26 +00001742AnalysisKey LazyCallGraphAnalysis::Key;
NAKAMURA Takumidf0cd722016-02-28 17:17:00 +00001743
Chandler Carruthbf71a342014-02-06 04:37:03 +00001744LazyCallGraphPrinterPass::LazyCallGraphPrinterPass(raw_ostream &OS) : OS(OS) {}
1745
Chandler Carruthe5944d92016-02-17 00:18:16 +00001746static void printNode(raw_ostream &OS, LazyCallGraph::Node &N) {
Chandler Carrutha4499e92016-02-02 03:57:13 +00001747 OS << " Edges in function: " << N.getFunction().getName() << "\n";
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001748 for (LazyCallGraph::Edge &E : N.populate())
Chandler Carrutha4499e92016-02-02 03:57:13 +00001749 OS << " " << (E.isCall() ? "call" : "ref ") << " -> "
1750 << E.getFunction().getName() << "\n";
Chandler Carruth11f50322015-01-14 00:27:45 +00001751
1752 OS << "\n";
1753}
1754
Chandler Carruthe5944d92016-02-17 00:18:16 +00001755static void printSCC(raw_ostream &OS, LazyCallGraph::SCC &C) {
Fangrui Songcb4327d2019-08-06 10:24:36 +00001756 OS << " SCC with " << C.size() << " functions:\n";
Chandler Carruth11f50322015-01-14 00:27:45 +00001757
Chandler Carruthe5944d92016-02-17 00:18:16 +00001758 for (LazyCallGraph::Node &N : C)
1759 OS << " " << N.getFunction().getName() << "\n";
1760}
1761
1762static void printRefSCC(raw_ostream &OS, LazyCallGraph::RefSCC &C) {
Fangrui Songcb4327d2019-08-06 10:24:36 +00001763 OS << " RefSCC with " << C.size() << " call SCCs:\n";
Chandler Carruthe5944d92016-02-17 00:18:16 +00001764
1765 for (LazyCallGraph::SCC &InnerC : C)
1766 printSCC(OS, InnerC);
Chandler Carruth11f50322015-01-14 00:27:45 +00001767
1768 OS << "\n";
1769}
1770
Chandler Carruthd174ce42015-01-05 02:47:05 +00001771PreservedAnalyses LazyCallGraphPrinterPass::run(Module &M,
Chandler Carruthb47f8012016-03-11 11:05:24 +00001772 ModuleAnalysisManager &AM) {
1773 LazyCallGraph &G = AM.getResult<LazyCallGraphAnalysis>(M);
Chandler Carruth11f50322015-01-14 00:27:45 +00001774
1775 OS << "Printing the call graph for module: " << M.getModuleIdentifier()
1776 << "\n\n";
1777
Chandler Carruthe5944d92016-02-17 00:18:16 +00001778 for (Function &F : M)
1779 printNode(OS, G.get(F));
Chandler Carruth11f50322015-01-14 00:27:45 +00001780
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001781 G.buildRefSCCs();
Chandler Carruthe5944d92016-02-17 00:18:16 +00001782 for (LazyCallGraph::RefSCC &C : G.postorder_ref_sccs())
1783 printRefSCC(OS, C);
Chandler Carruth18eadd922014-04-18 10:50:32 +00001784
Chandler Carruthbf71a342014-02-06 04:37:03 +00001785 return PreservedAnalyses::all();
Chandler Carruthbf71a342014-02-06 04:37:03 +00001786}
Sean Silva7cb30662016-06-18 09:17:32 +00001787
1788LazyCallGraphDOTPrinterPass::LazyCallGraphDOTPrinterPass(raw_ostream &OS)
1789 : OS(OS) {}
1790
1791static void printNodeDOT(raw_ostream &OS, LazyCallGraph::Node &N) {
1792 std::string Name = "\"" + DOT::EscapeString(N.getFunction().getName()) + "\"";
1793
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001794 for (LazyCallGraph::Edge &E : N.populate()) {
Sean Silva7cb30662016-06-18 09:17:32 +00001795 OS << " " << Name << " -> \""
1796 << DOT::EscapeString(E.getFunction().getName()) << "\"";
1797 if (!E.isCall()) // It is a ref edge.
1798 OS << " [style=dashed,label=\"ref\"]";
1799 OS << ";\n";
1800 }
1801
1802 OS << "\n";
1803}
1804
1805PreservedAnalyses LazyCallGraphDOTPrinterPass::run(Module &M,
1806 ModuleAnalysisManager &AM) {
1807 LazyCallGraph &G = AM.getResult<LazyCallGraphAnalysis>(M);
1808
1809 OS << "digraph \"" << DOT::EscapeString(M.getModuleIdentifier()) << "\" {\n";
1810
1811 for (Function &F : M)
1812 printNodeDOT(OS, G.get(F));
1813
1814 OS << "}\n";
1815
1816 return PreservedAnalyses::all();
1817}