blob: 08d6e76ea0363649f108ade38684e0d8ddb8fe89 [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))
Benjamin Kramer31a47f92019-08-16 10:59:18 +0000103 if (Function *Callee = CS.getCalledFunction())
Chandler Carruth86f0bdf2016-12-09 00:46:44 +0000104 if (!Callee->isDeclaration())
105 if (Callees.insert(Callee).second) {
106 Visited.insert(Callee);
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000107 addEdge(Edges->Edges, Edges->EdgeIndexMap, G->get(*Callee),
Benjamin Kramer31a47f92019-08-16 10:59:18 +0000108 LazyCallGraph::Edge::Call);
Chandler Carruth86f0bdf2016-12-09 00:46:44 +0000109 }
Chandler Carrutha4499e92016-02-02 03:57:13 +0000110
Chandler Carruthb9e2f8c2014-03-09 12:20:34 +0000111 for (Value *Op : I.operand_values())
Chandler Carruth1583e992014-03-03 10:42:58 +0000112 if (Constant *C = dyn_cast<Constant>(Op))
David Blaikie70573dc2014-11-19 07:49:26 +0000113 if (Visited.insert(C).second)
Chandler Carruthbf71a342014-02-06 04:37:03 +0000114 Worklist.push_back(C);
Chandler Carrutha4499e92016-02-02 03:57:13 +0000115 }
Chandler Carruthbf71a342014-02-06 04:37:03 +0000116
117 // We've collected all the constant (and thus potentially function or
118 // function containing) operands to all of the instructions in the function.
119 // Process them (recursively) collecting every function found.
Chandler Carruth88823462016-08-24 09:37:14 +0000120 visitReferences(Worklist, Visited, [&](Function &F) {
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000121 addEdge(Edges->Edges, Edges->EdgeIndexMap, G->get(F),
122 LazyCallGraph::Edge::Ref);
Chandler Carruth88823462016-08-24 09:37:14 +0000123 });
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000124
Chandler Carruthf59a8382017-07-15 08:08:19 +0000125 // Add implicit reference edges to any defined libcall functions (if we
126 // haven't found an explicit edge).
127 for (auto *F : G->LibFunctions)
128 if (!Visited.count(F))
129 addEdge(Edges->Edges, Edges->EdgeIndexMap, G->get(*F),
130 LazyCallGraph::Edge::Ref);
131
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000132 return *Edges;
Chandler Carruthbf71a342014-02-06 04:37:03 +0000133}
134
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000135void LazyCallGraph::Node::replaceFunction(Function &NewF) {
136 assert(F != &NewF && "Must not replace a function with itself!");
137 F = &NewF;
Chandler Carruthaa839b22014-04-27 01:59:50 +0000138}
139
Aaron Ballman615eb472017-10-15 14:32:27 +0000140#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Matthias Braun8c209aa2017-01-28 02:02:38 +0000141LLVM_DUMP_METHOD void LazyCallGraph::Node::dump() const {
Chandler Carruthdca83402016-06-27 23:26:08 +0000142 dbgs() << *this << '\n';
143}
Matthias Braun8c209aa2017-01-28 02:02:38 +0000144#endif
Chandler Carruthdca83402016-06-27 23:26:08 +0000145
Chandler Carruthf59a8382017-07-15 08:08:19 +0000146static bool isKnownLibFunction(Function &F, TargetLibraryInfo &TLI) {
147 LibFunc LF;
148
149 // Either this is a normal library function or a "vectorizable" function.
150 return TLI.getLibFunc(F, LF) || TLI.isFunctionVectorizable(F.getName());
151}
152
153LazyCallGraph::LazyCallGraph(Module &M, TargetLibraryInfo &TLI) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000154 LLVM_DEBUG(dbgs() << "Building CG for module: " << M.getModuleIdentifier()
155 << "\n");
Chandler Carruthf59a8382017-07-15 08:08:19 +0000156 for (Function &F : M) {
157 if (F.isDeclaration())
158 continue;
159 // If this function is a known lib function to LLVM then we want to
160 // synthesize reference edges to it to model the fact that LLVM can turn
161 // arbitrary code into a library function call.
162 if (isKnownLibFunction(F, TLI))
Chandler Carruth06a86302017-07-19 04:12:25 +0000163 LibFunctions.insert(&F);
Chandler Carruthf59a8382017-07-15 08:08:19 +0000164
165 if (F.hasLocalLinkage())
166 continue;
167
168 // External linkage defined functions have edges to them from other
169 // modules.
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000170 LLVM_DEBUG(dbgs() << " Adding '" << F.getName()
171 << "' to entry set of the graph.\n");
Chandler Carruthf59a8382017-07-15 08:08:19 +0000172 addEdge(EntryEdges.Edges, EntryEdges.EdgeIndexMap, get(F), Edge::Ref);
173 }
Chandler Carruthbf71a342014-02-06 04:37:03 +0000174
Guozhi Wei36fc9c32019-04-05 18:51:08 +0000175 // Externally visible aliases of internal functions are also viable entry
176 // edges to the module.
177 for (auto &A : M.aliases()) {
178 if (A.hasLocalLinkage())
179 continue;
180 if (Function* F = dyn_cast<Function>(A.getAliasee())) {
181 LLVM_DEBUG(dbgs() << " Adding '" << F->getName()
182 << "' with alias '" << A.getName()
183 << "' to entry set of the graph.\n");
184 addEdge(EntryEdges.Edges, EntryEdges.EdgeIndexMap, get(*F), Edge::Ref);
185 }
186 }
187
Chandler Carruthbf71a342014-02-06 04:37:03 +0000188 // Now add entry nodes for functions reachable via initializers to globals.
189 SmallVector<Constant *, 16> Worklist;
190 SmallPtrSet<Constant *, 16> Visited;
Chandler Carruthb9e2f8c2014-03-09 12:20:34 +0000191 for (GlobalVariable &GV : M.globals())
192 if (GV.hasInitializer())
David Blaikie70573dc2014-11-19 07:49:26 +0000193 if (Visited.insert(GV.getInitializer()).second)
Chandler Carruthb9e2f8c2014-03-09 12:20:34 +0000194 Worklist.push_back(GV.getInitializer());
Chandler Carruthbf71a342014-02-06 04:37:03 +0000195
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000196 LLVM_DEBUG(
197 dbgs() << " Adding functions referenced by global initializers to the "
198 "entry set.\n");
Chandler Carruth88823462016-08-24 09:37:14 +0000199 visitReferences(Worklist, Visited, [&](Function &F) {
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000200 addEdge(EntryEdges.Edges, EntryEdges.EdgeIndexMap, get(F),
201 LazyCallGraph::Edge::Ref);
Chandler Carruth88823462016-08-24 09:37:14 +0000202 });
Chandler Carruthbf71a342014-02-06 04:37:03 +0000203}
204
Chandler Carruthbf71a342014-02-06 04:37:03 +0000205LazyCallGraph::LazyCallGraph(LazyCallGraph &&G)
Chandler Carruth2174f442014-04-18 20:44:16 +0000206 : BPA(std::move(G.BPA)), NodeMap(std::move(G.NodeMap)),
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000207 EntryEdges(std::move(G.EntryEdges)), SCCBPA(std::move(G.SCCBPA)),
Chandler Carruthadbf14a2017-08-05 07:37:00 +0000208 SCCMap(std::move(G.SCCMap)),
Chandler Carruthf59a8382017-07-15 08:08:19 +0000209 LibFunctions(std::move(G.LibFunctions)) {
Chandler Carruthd8d865e2014-04-18 11:02:33 +0000210 updateGraphPtrs();
211}
212
213LazyCallGraph &LazyCallGraph::operator=(LazyCallGraph &&G) {
214 BPA = std::move(G.BPA);
Chandler Carruth2174f442014-04-18 20:44:16 +0000215 NodeMap = std::move(G.NodeMap);
Chandler Carrutha4499e92016-02-02 03:57:13 +0000216 EntryEdges = std::move(G.EntryEdges);
Chandler Carruthd8d865e2014-04-18 11:02:33 +0000217 SCCBPA = std::move(G.SCCBPA);
218 SCCMap = std::move(G.SCCMap);
Chandler Carruthf59a8382017-07-15 08:08:19 +0000219 LibFunctions = std::move(G.LibFunctions);
Chandler Carruthd8d865e2014-04-18 11:02:33 +0000220 updateGraphPtrs();
221 return *this;
222}
223
Aaron Ballman615eb472017-10-15 14:32:27 +0000224#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Matthias Braun8c209aa2017-01-28 02:02:38 +0000225LLVM_DUMP_METHOD void LazyCallGraph::SCC::dump() const {
Chandler Carruthdca83402016-06-27 23:26:08 +0000226 dbgs() << *this << '\n';
227}
Matthias Braun8c209aa2017-01-28 02:02:38 +0000228#endif
Chandler Carruthdca83402016-06-27 23:26:08 +0000229
Chandler Carruthe5944d92016-02-17 00:18:16 +0000230#ifndef NDEBUG
231void LazyCallGraph::SCC::verify() {
232 assert(OuterRefSCC && "Can't have a null RefSCC!");
233 assert(!Nodes.empty() && "Can't have an empty SCC!");
Chandler Carruth8f92d6d2014-04-26 01:03:46 +0000234
Chandler Carruthe5944d92016-02-17 00:18:16 +0000235 for (Node *N : Nodes) {
236 assert(N && "Can't have a null node!");
237 assert(OuterRefSCC->G->lookupSCC(*N) == this &&
238 "Node does not map to this SCC!");
239 assert(N->DFSNumber == -1 &&
240 "Must set DFS numbers to -1 when adding a node to an SCC!");
241 assert(N->LowLink == -1 &&
242 "Must set low link to -1 when adding a node to an SCC!");
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000243 for (Edge &E : **N)
Chandler Carruth39df40d2017-08-05 04:04:06 +0000244 assert(E.getNode().isPopulated() && "Can't have an unpopulated node!");
Chandler Carruthe5944d92016-02-17 00:18:16 +0000245 }
246}
247#endif
248
Chandler Carruthbae595b2016-11-22 19:23:31 +0000249bool LazyCallGraph::SCC::isParentOf(const SCC &C) const {
250 if (this == &C)
251 return false;
252
253 for (Node &N : *this)
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000254 for (Edge &E : N->calls())
255 if (OuterRefSCC->G->lookupSCC(E.getNode()) == &C)
256 return true;
Chandler Carruthbae595b2016-11-22 19:23:31 +0000257
258 // No edges found.
259 return false;
260}
261
262bool LazyCallGraph::SCC::isAncestorOf(const SCC &TargetC) const {
263 if (this == &TargetC)
264 return false;
265
266 LazyCallGraph &G = *OuterRefSCC->G;
267
268 // Start with this SCC.
269 SmallPtrSet<const SCC *, 16> Visited = {this};
270 SmallVector<const SCC *, 16> Worklist = {this};
271
272 // Walk down the graph until we run out of edges or find a path to TargetC.
273 do {
274 const SCC &C = *Worklist.pop_back_val();
275 for (Node &N : C)
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000276 for (Edge &E : N->calls()) {
277 SCC *CalleeC = G.lookupSCC(E.getNode());
Chandler Carruthbae595b2016-11-22 19:23:31 +0000278 if (!CalleeC)
279 continue;
280
281 // If the callee's SCC is the TargetC, we're done.
282 if (CalleeC == &TargetC)
283 return true;
284
285 // If this is the first time we've reached this SCC, put it on the
286 // worklist to recurse through.
287 if (Visited.insert(CalleeC).second)
288 Worklist.push_back(CalleeC);
289 }
290 } while (!Worklist.empty());
291
292 // No paths found.
293 return false;
294}
295
Chandler Carruthe5944d92016-02-17 00:18:16 +0000296LazyCallGraph::RefSCC::RefSCC(LazyCallGraph &G) : G(&G) {}
297
Aaron Ballman615eb472017-10-15 14:32:27 +0000298#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Matthias Braun8c209aa2017-01-28 02:02:38 +0000299LLVM_DUMP_METHOD void LazyCallGraph::RefSCC::dump() const {
Chandler Carruthdca83402016-06-27 23:26:08 +0000300 dbgs() << *this << '\n';
301}
Matthias Braun8c209aa2017-01-28 02:02:38 +0000302#endif
Chandler Carruthdca83402016-06-27 23:26:08 +0000303
Chandler Carruthe5944d92016-02-17 00:18:16 +0000304#ifndef NDEBUG
305void LazyCallGraph::RefSCC::verify() {
306 assert(G && "Can't have a null graph!");
307 assert(!SCCs.empty() && "Can't have an empty SCC!");
308
309 // Verify basic properties of the SCCs.
Chandler Carruth88823462016-08-24 09:37:14 +0000310 SmallPtrSet<SCC *, 4> SCCSet;
Chandler Carruthe5944d92016-02-17 00:18:16 +0000311 for (SCC *C : SCCs) {
312 assert(C && "Can't have a null SCC!");
313 C->verify();
314 assert(&C->getOuterRefSCC() == this &&
315 "SCC doesn't think it is inside this RefSCC!");
Chandler Carruth88823462016-08-24 09:37:14 +0000316 bool Inserted = SCCSet.insert(C).second;
317 assert(Inserted && "Found a duplicate SCC!");
Chandler Carruth23a6c3f2016-12-06 10:29:23 +0000318 auto IndexIt = SCCIndices.find(C);
319 assert(IndexIt != SCCIndices.end() &&
320 "Found an SCC that doesn't have an index!");
Chandler Carruthe5944d92016-02-17 00:18:16 +0000321 }
322
323 // Check that our indices map correctly.
324 for (auto &SCCIndexPair : SCCIndices) {
325 SCC *C = SCCIndexPair.first;
326 int i = SCCIndexPair.second;
327 assert(C && "Can't have a null SCC in the indices!");
Chandler Carruth88823462016-08-24 09:37:14 +0000328 assert(SCCSet.count(C) && "Found an index for an SCC not in the RefSCC!");
Chandler Carruthe5944d92016-02-17 00:18:16 +0000329 assert(SCCs[i] == C && "Index doesn't point to SCC!");
330 }
331
332 // Check that the SCCs are in fact in post-order.
333 for (int i = 0, Size = SCCs.size(); i < Size; ++i) {
334 SCC &SourceSCC = *SCCs[i];
335 for (Node &N : SourceSCC)
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000336 for (Edge &E : *N) {
Chandler Carruthe5944d92016-02-17 00:18:16 +0000337 if (!E.isCall())
338 continue;
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000339 SCC &TargetSCC = *G->lookupSCC(E.getNode());
Chandler Carruthe5944d92016-02-17 00:18:16 +0000340 if (&TargetSCC.getOuterRefSCC() == this) {
341 assert(SCCIndices.find(&TargetSCC)->second <= i &&
342 "Edge between SCCs violates post-order relationship.");
343 continue;
344 }
Chandler Carruthe5944d92016-02-17 00:18:16 +0000345 }
346 }
347}
348#endif
349
Chandler Carruth38bd6b52017-08-05 06:24:09 +0000350bool LazyCallGraph::RefSCC::isParentOf(const RefSCC &RC) const {
351 if (&RC == this)
352 return false;
353
354 // Search all edges to see if this is a parent.
355 for (SCC &C : *this)
356 for (Node &N : C)
357 for (Edge &E : *N)
358 if (G->lookupRefSCC(E.getNode()) == &RC)
359 return true;
360
361 return false;
362}
363
364bool LazyCallGraph::RefSCC::isAncestorOf(const RefSCC &RC) const {
365 if (&RC == this)
366 return false;
367
368 // For each descendant of this RefSCC, see if one of its children is the
369 // argument. If not, add that descendant to the worklist and continue
370 // searching.
371 SmallVector<const RefSCC *, 4> Worklist;
372 SmallPtrSet<const RefSCC *, 4> Visited;
373 Worklist.push_back(this);
374 Visited.insert(this);
Chandler Carruth4b096742014-05-01 12:12:42 +0000375 do {
Chandler Carruth38bd6b52017-08-05 06:24:09 +0000376 const RefSCC &DescendantRC = *Worklist.pop_back_val();
377 for (SCC &C : DescendantRC)
378 for (Node &N : C)
379 for (Edge &E : *N) {
380 auto *ChildRC = G->lookupRefSCC(E.getNode());
381 if (ChildRC == &RC)
382 return true;
383 if (!ChildRC || !Visited.insert(ChildRC).second)
384 continue;
385 Worklist.push_back(ChildRC);
386 }
387 } while (!Worklist.empty());
Chandler Carruth4b096742014-05-01 12:12:42 +0000388
389 return false;
390}
391
Chandler Carruth1f621f02016-09-04 08:34:24 +0000392/// Generic helper that updates a postorder sequence of SCCs for a potentially
393/// cycle-introducing edge insertion.
394///
395/// A postorder sequence of SCCs of a directed graph has one fundamental
396/// property: all deges in the DAG of SCCs point "up" the sequence. That is,
397/// all edges in the SCC DAG point to prior SCCs in the sequence.
398///
399/// This routine both updates a postorder sequence and uses that sequence to
400/// compute the set of SCCs connected into a cycle. It should only be called to
401/// insert a "downward" edge which will require changing the sequence to
402/// restore it to a postorder.
403///
404/// When inserting an edge from an earlier SCC to a later SCC in some postorder
405/// sequence, all of the SCCs which may be impacted are in the closed range of
406/// those two within the postorder sequence. The algorithm used here to restore
407/// the state is as follows:
408///
409/// 1) Starting from the source SCC, construct a set of SCCs which reach the
410/// source SCC consisting of just the source SCC. Then scan toward the
411/// target SCC in postorder and for each SCC, if it has an edge to an SCC
412/// in the set, add it to the set. Otherwise, the source SCC is not
413/// a successor, move it in the postorder sequence to immediately before
414/// the source SCC, shifting the source SCC and all SCCs in the set one
415/// position toward the target SCC. Stop scanning after processing the
416/// target SCC.
417/// 2) If the source SCC is now past the target SCC in the postorder sequence,
418/// and thus the new edge will flow toward the start, we are done.
419/// 3) Otherwise, starting from the target SCC, walk all edges which reach an
420/// SCC between the source and the target, and add them to the set of
421/// connected SCCs, then recurse through them. Once a complete set of the
422/// SCCs the target connects to is known, hoist the remaining SCCs between
423/// the source and the target to be above the target. Note that there is no
424/// need to process the source SCC, it is already known to connect.
425/// 4) At this point, all of the SCCs in the closed range between the source
426/// SCC and the target SCC in the postorder sequence are connected,
427/// including the target SCC and the source SCC. Inserting the edge from
428/// the source SCC to the target SCC will form a cycle out of precisely
429/// these SCCs. Thus we can merge all of the SCCs in this closed range into
430/// a single SCC.
431///
432/// This process has various important properties:
433/// - Only mutates the SCCs when adding the edge actually changes the SCC
434/// structure.
435/// - Never mutates SCCs which are unaffected by the change.
436/// - Updates the postorder sequence to correctly satisfy the postorder
437/// constraint after the edge is inserted.
438/// - Only reorders SCCs in the closed postorder sequence from the source to
439/// the target, so easy to bound how much has changed even in the ordering.
440/// - Big-O is the number of edges in the closed postorder range of SCCs from
441/// source to target.
442///
443/// This helper routine, in addition to updating the postorder sequence itself
Vedant Kumar1a8456d2018-03-02 18:57:02 +0000444/// will also update a map from SCCs to indices within that sequence.
Chandler Carruth1f621f02016-09-04 08:34:24 +0000445///
446/// The sequence and the map must operate on pointers to the SCC type.
447///
448/// Two callbacks must be provided. The first computes the subset of SCCs in
449/// the postorder closed range from the source to the target which connect to
450/// the source SCC via some (transitive) set of edges. The second computes the
451/// subset of the same range which the target SCC connects to via some
452/// (transitive) set of edges. Both callbacks should populate the set argument
453/// provided.
454template <typename SCCT, typename PostorderSequenceT, typename SCCIndexMapT,
455 typename ComputeSourceConnectedSetCallableT,
456 typename ComputeTargetConnectedSetCallableT>
457static iterator_range<typename PostorderSequenceT::iterator>
458updatePostorderSequenceForEdgeInsertion(
459 SCCT &SourceSCC, SCCT &TargetSCC, PostorderSequenceT &SCCs,
460 SCCIndexMapT &SCCIndices,
461 ComputeSourceConnectedSetCallableT ComputeSourceConnectedSet,
462 ComputeTargetConnectedSetCallableT ComputeTargetConnectedSet) {
463 int SourceIdx = SCCIndices[&SourceSCC];
464 int TargetIdx = SCCIndices[&TargetSCC];
465 assert(SourceIdx < TargetIdx && "Cannot have equal indices here!");
466
467 SmallPtrSet<SCCT *, 4> ConnectedSet;
468
469 // Compute the SCCs which (transitively) reach the source.
470 ComputeSourceConnectedSet(ConnectedSet);
471
472 // Partition the SCCs in this part of the port-order sequence so only SCCs
473 // connecting to the source remain between it and the target. This is
474 // a benign partition as it preserves postorder.
475 auto SourceI = std::stable_partition(
476 SCCs.begin() + SourceIdx, SCCs.begin() + TargetIdx + 1,
477 [&ConnectedSet](SCCT *C) { return !ConnectedSet.count(C); });
478 for (int i = SourceIdx, e = TargetIdx + 1; i < e; ++i)
479 SCCIndices.find(SCCs[i])->second = i;
480
481 // If the target doesn't connect to the source, then we've corrected the
482 // post-order and there are no cycles formed.
483 if (!ConnectedSet.count(&TargetSCC)) {
484 assert(SourceI > (SCCs.begin() + SourceIdx) &&
485 "Must have moved the source to fix the post-order.");
486 assert(*std::prev(SourceI) == &TargetSCC &&
487 "Last SCC to move should have bene the target.");
488
489 // Return an empty range at the target SCC indicating there is nothing to
490 // merge.
491 return make_range(std::prev(SourceI), std::prev(SourceI));
492 }
493
494 assert(SCCs[TargetIdx] == &TargetSCC &&
495 "Should not have moved target if connected!");
496 SourceIdx = SourceI - SCCs.begin();
497 assert(SCCs[SourceIdx] == &SourceSCC &&
498 "Bad updated index computation for the source SCC!");
499
500
501 // See whether there are any remaining intervening SCCs between the source
502 // and target. If so we need to make sure they all are reachable form the
503 // target.
504 if (SourceIdx + 1 < TargetIdx) {
505 ConnectedSet.clear();
506 ComputeTargetConnectedSet(ConnectedSet);
507
508 // Partition SCCs so that only SCCs reached from the target remain between
509 // the source and the target. This preserves postorder.
510 auto TargetI = std::stable_partition(
511 SCCs.begin() + SourceIdx + 1, SCCs.begin() + TargetIdx + 1,
512 [&ConnectedSet](SCCT *C) { return ConnectedSet.count(C); });
513 for (int i = SourceIdx + 1, e = TargetIdx + 1; i < e; ++i)
514 SCCIndices.find(SCCs[i])->second = i;
515 TargetIdx = std::prev(TargetI) - SCCs.begin();
516 assert(SCCs[TargetIdx] == &TargetSCC &&
517 "Should always end with the target!");
518 }
519
520 // At this point, we know that connecting source to target forms a cycle
521 // because target connects back to source, and we know that all of the SCCs
522 // between the source and target in the postorder sequence participate in that
523 // cycle.
524 return make_range(SCCs.begin() + SourceIdx, SCCs.begin() + TargetIdx);
525}
526
Chandler Carruthc213c672017-07-09 13:45:11 +0000527bool
528LazyCallGraph::RefSCC::switchInternalEdgeToCall(
529 Node &SourceN, Node &TargetN,
530 function_ref<void(ArrayRef<SCC *> MergeSCCs)> MergeCB) {
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000531 assert(!(*SourceN)[TargetN].isCall() && "Must start with a ref edge!");
Chandler Carruthe5944d92016-02-17 00:18:16 +0000532 SmallVector<SCC *, 1> DeletedSCCs;
Chandler Carruth5217c942014-04-30 10:48:36 +0000533
Chandler Carruth11b3f602016-09-04 08:34:31 +0000534#ifndef NDEBUG
535 // In a debug build, verify the RefSCC is valid to start with and when this
536 // routine finishes.
537 verify();
538 auto VerifyOnExit = make_scope_exit([&]() { verify(); });
539#endif
540
Chandler Carruthe5944d92016-02-17 00:18:16 +0000541 SCC &SourceSCC = *G->lookupSCC(SourceN);
542 SCC &TargetSCC = *G->lookupSCC(TargetN);
543
544 // If the two nodes are already part of the same SCC, we're also done as
545 // we've just added more connectivity.
546 if (&SourceSCC == &TargetSCC) {
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000547 SourceN->setEdgeKind(TargetN, Edge::Call);
Chandler Carruthc213c672017-07-09 13:45:11 +0000548 return false; // No new cycle.
Chandler Carruthe5944d92016-02-17 00:18:16 +0000549 }
550
551 // At this point we leverage the postorder list of SCCs to detect when the
552 // insertion of an edge changes the SCC structure in any way.
553 //
554 // First and foremost, we can eliminate the need for any changes when the
555 // edge is toward the beginning of the postorder sequence because all edges
556 // flow in that direction already. Thus adding a new one cannot form a cycle.
557 int SourceIdx = SCCIndices[&SourceSCC];
558 int TargetIdx = SCCIndices[&TargetSCC];
559 if (TargetIdx < SourceIdx) {
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000560 SourceN->setEdgeKind(TargetN, Edge::Call);
Chandler Carruthc213c672017-07-09 13:45:11 +0000561 return false; // No new cycle.
Chandler Carruthe5944d92016-02-17 00:18:16 +0000562 }
563
Chandler Carruthe5944d92016-02-17 00:18:16 +0000564 // Compute the SCCs which (transitively) reach the source.
Chandler Carruth1f621f02016-09-04 08:34:24 +0000565 auto ComputeSourceConnectedSet = [&](SmallPtrSetImpl<SCC *> &ConnectedSet) {
Chandler Carruthe5944d92016-02-17 00:18:16 +0000566#ifndef NDEBUG
Chandler Carruth1f621f02016-09-04 08:34:24 +0000567 // Check that the RefSCC is still valid before computing this as the
568 // results will be nonsensical of we've broken its invariants.
Chandler Carruthe5944d92016-02-17 00:18:16 +0000569 verify();
570#endif
Chandler Carruth1f621f02016-09-04 08:34:24 +0000571 ConnectedSet.insert(&SourceSCC);
572 auto IsConnected = [&](SCC &C) {
573 for (Node &N : C)
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000574 for (Edge &E : N->calls())
575 if (ConnectedSet.count(G->lookupSCC(E.getNode())))
Chandler Carruth1f621f02016-09-04 08:34:24 +0000576 return true;
Chandler Carruthe5944d92016-02-17 00:18:16 +0000577
Chandler Carruth1f621f02016-09-04 08:34:24 +0000578 return false;
579 };
Chandler Carruthe5944d92016-02-17 00:18:16 +0000580
Chandler Carruth1f621f02016-09-04 08:34:24 +0000581 for (SCC *C :
582 make_range(SCCs.begin() + SourceIdx + 1, SCCs.begin() + TargetIdx + 1))
583 if (IsConnected(*C))
584 ConnectedSet.insert(C);
585 };
586
587 // Use a normal worklist to find which SCCs the target connects to. We still
588 // bound the search based on the range in the postorder list we care about,
589 // but because this is forward connectivity we just "recurse" through the
590 // edges.
591 auto ComputeTargetConnectedSet = [&](SmallPtrSetImpl<SCC *> &ConnectedSet) {
Chandler Carruthe5944d92016-02-17 00:18:16 +0000592#ifndef NDEBUG
Chandler Carruth1f621f02016-09-04 08:34:24 +0000593 // Check that the RefSCC is still valid before computing this as the
594 // results will be nonsensical of we've broken its invariants.
595 verify();
Chandler Carruthe5944d92016-02-17 00:18:16 +0000596#endif
Chandler Carruthe5944d92016-02-17 00:18:16 +0000597 ConnectedSet.insert(&TargetSCC);
598 SmallVector<SCC *, 4> Worklist;
599 Worklist.push_back(&TargetSCC);
600 do {
601 SCC &C = *Worklist.pop_back_val();
602 for (Node &N : C)
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000603 for (Edge &E : *N) {
Chandler Carruthe5944d92016-02-17 00:18:16 +0000604 if (!E.isCall())
605 continue;
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000606 SCC &EdgeC = *G->lookupSCC(E.getNode());
Chandler Carruthe5944d92016-02-17 00:18:16 +0000607 if (&EdgeC.getOuterRefSCC() != this)
608 // Not in this RefSCC...
609 continue;
610 if (SCCIndices.find(&EdgeC)->second <= SourceIdx)
611 // Not in the postorder sequence between source and target.
612 continue;
613
614 if (ConnectedSet.insert(&EdgeC).second)
615 Worklist.push_back(&EdgeC);
616 }
617 } while (!Worklist.empty());
Chandler Carruth1f621f02016-09-04 08:34:24 +0000618 };
Chandler Carruthe5944d92016-02-17 00:18:16 +0000619
Chandler Carruth1f621f02016-09-04 08:34:24 +0000620 // Use a generic helper to update the postorder sequence of SCCs and return
621 // a range of any SCCs connected into a cycle by inserting this edge. This
622 // routine will also take care of updating the indices into the postorder
623 // sequence.
624 auto MergeRange = updatePostorderSequenceForEdgeInsertion(
625 SourceSCC, TargetSCC, SCCs, SCCIndices, ComputeSourceConnectedSet,
626 ComputeTargetConnectedSet);
Chandler Carruthe5944d92016-02-17 00:18:16 +0000627
Chandler Carruthc213c672017-07-09 13:45:11 +0000628 // Run the user's callback on the merged SCCs before we actually merge them.
629 if (MergeCB)
630 MergeCB(makeArrayRef(MergeRange.begin(), MergeRange.end()));
631
Chandler Carruth1f621f02016-09-04 08:34:24 +0000632 // If the merge range is empty, then adding the edge didn't actually form any
633 // new cycles. We're done.
Matthias Braun9fd397b2018-10-31 00:23:23 +0000634 if (empty(MergeRange)) {
Chandler Carruth1f621f02016-09-04 08:34:24 +0000635 // Now that the SCC structure is finalized, flip the kind to call.
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000636 SourceN->setEdgeKind(TargetN, Edge::Call);
Chandler Carruthc213c672017-07-09 13:45:11 +0000637 return false; // No new cycle.
Chandler Carruthe5944d92016-02-17 00:18:16 +0000638 }
639
Chandler Carruth1f621f02016-09-04 08:34:24 +0000640#ifndef NDEBUG
641 // Before merging, check that the RefSCC remains valid after all the
642 // postorder updates.
643 verify();
644#endif
645
646 // Otherwise we need to merge all of the SCCs in the cycle into a single
Chandler Carruthe5944d92016-02-17 00:18:16 +0000647 // result SCC.
648 //
649 // NB: We merge into the target because all of these functions were already
650 // reachable from the target, meaning any SCC-wide properties deduced about it
651 // other than the set of functions within it will not have changed.
Chandler Carruthe5944d92016-02-17 00:18:16 +0000652 for (SCC *C : MergeRange) {
653 assert(C != &TargetSCC &&
654 "We merge *into* the target and shouldn't process it here!");
655 SCCIndices.erase(C);
656 TargetSCC.Nodes.append(C->Nodes.begin(), C->Nodes.end());
657 for (Node *N : C->Nodes)
658 G->SCCMap[N] = &TargetSCC;
659 C->clear();
660 DeletedSCCs.push_back(C);
661 }
662
663 // Erase the merged SCCs from the list and update the indices of the
664 // remaining SCCs.
665 int IndexOffset = MergeRange.end() - MergeRange.begin();
666 auto EraseEnd = SCCs.erase(MergeRange.begin(), MergeRange.end());
667 for (SCC *C : make_range(EraseEnd, SCCs.end()))
668 SCCIndices[C] -= IndexOffset;
669
670 // Now that the SCC structure is finalized, flip the kind to call.
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000671 SourceN->setEdgeKind(TargetN, Edge::Call);
Chandler Carruthe5944d92016-02-17 00:18:16 +0000672
Chandler Carruthc213c672017-07-09 13:45:11 +0000673 // And we're done, but we did form a new cycle.
674 return true;
Chandler Carruth5217c942014-04-30 10:48:36 +0000675}
676
Chandler Carruth443e57e2016-12-28 10:34:50 +0000677void LazyCallGraph::RefSCC::switchTrivialInternalEdgeToRef(Node &SourceN,
678 Node &TargetN) {
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000679 assert((*SourceN)[TargetN].isCall() && "Must start with a call edge!");
Chandler Carruth443e57e2016-12-28 10:34:50 +0000680
681#ifndef NDEBUG
682 // In a debug build, verify the RefSCC is valid to start with and when this
683 // routine finishes.
684 verify();
685 auto VerifyOnExit = make_scope_exit([&]() { verify(); });
686#endif
687
688 assert(G->lookupRefSCC(SourceN) == this &&
689 "Source must be in this RefSCC.");
690 assert(G->lookupRefSCC(TargetN) == this &&
691 "Target must be in this RefSCC.");
692 assert(G->lookupSCC(SourceN) != G->lookupSCC(TargetN) &&
693 "Source and Target must be in separate SCCs for this to be trivial!");
694
695 // Set the edge kind.
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000696 SourceN->setEdgeKind(TargetN, Edge::Ref);
Chandler Carruth443e57e2016-12-28 10:34:50 +0000697}
698
Chandler Carruth88823462016-08-24 09:37:14 +0000699iterator_range<LazyCallGraph::RefSCC::iterator>
700LazyCallGraph::RefSCC::switchInternalEdgeToRef(Node &SourceN, Node &TargetN) {
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000701 assert((*SourceN)[TargetN].isCall() && "Must start with a call edge!");
Chandler Carruthe5944d92016-02-17 00:18:16 +0000702
Chandler Carruth11b3f602016-09-04 08:34:31 +0000703#ifndef NDEBUG
704 // In a debug build, verify the RefSCC is valid to start with and when this
705 // routine finishes.
706 verify();
707 auto VerifyOnExit = make_scope_exit([&]() { verify(); });
708#endif
709
Chandler Carruth443e57e2016-12-28 10:34:50 +0000710 assert(G->lookupRefSCC(SourceN) == this &&
Chandler Carruthe5944d92016-02-17 00:18:16 +0000711 "Source must be in this RefSCC.");
Chandler Carruth443e57e2016-12-28 10:34:50 +0000712 assert(G->lookupRefSCC(TargetN) == this &&
Chandler Carruthe5944d92016-02-17 00:18:16 +0000713 "Target must be in this RefSCC.");
714
Chandler Carruth443e57e2016-12-28 10:34:50 +0000715 SCC &TargetSCC = *G->lookupSCC(TargetN);
716 assert(G->lookupSCC(SourceN) == &TargetSCC && "Source and Target must be in "
717 "the same SCC to require the "
718 "full CG update.");
719
Chandler Carruthe5944d92016-02-17 00:18:16 +0000720 // Set the edge kind.
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000721 SourceN->setEdgeKind(TargetN, Edge::Ref);
Chandler Carruthe5944d92016-02-17 00:18:16 +0000722
Chandler Carruthe5944d92016-02-17 00:18:16 +0000723 // Otherwise we are removing a call edge from a single SCC. This may break
724 // the cycle. In order to compute the new set of SCCs, we need to do a small
725 // DFS over the nodes within the SCC to form any sub-cycles that remain as
726 // distinct SCCs and compute a postorder over the resulting SCCs.
727 //
728 // However, we specially handle the target node. The target node is known to
729 // reach all other nodes in the original SCC by definition. This means that
Vedant Kumar1a8456d2018-03-02 18:57:02 +0000730 // we want the old SCC to be replaced with an SCC containing that node as it
Chandler Carruthe5944d92016-02-17 00:18:16 +0000731 // will be the root of whatever SCC DAG results from the DFS. Assumptions
732 // about an SCC such as the set of functions called will continue to hold,
733 // etc.
734
735 SCC &OldSCC = TargetSCC;
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000736 SmallVector<std::pair<Node *, EdgeSequence::call_iterator>, 16> DFSStack;
Chandler Carruthe5944d92016-02-17 00:18:16 +0000737 SmallVector<Node *, 16> PendingSCCStack;
738 SmallVector<SCC *, 4> NewSCCs;
739
740 // Prepare the nodes for a fresh DFS.
741 SmallVector<Node *, 16> Worklist;
742 Worklist.swap(OldSCC.Nodes);
743 for (Node *N : Worklist) {
744 N->DFSNumber = N->LowLink = 0;
745 G->SCCMap.erase(N);
746 }
747
748 // Force the target node to be in the old SCC. This also enables us to take
749 // a very significant short-cut in the standard Tarjan walk to re-form SCCs
750 // below: whenever we build an edge that reaches the target node, we know
751 // that the target node eventually connects back to all other nodes in our
752 // walk. As a consequence, we can detect and handle participants in that
753 // cycle without walking all the edges that form this connection, and instead
754 // by relying on the fundamental guarantee coming into this operation (all
755 // nodes are reachable from the target due to previously forming an SCC).
756 TargetN.DFSNumber = TargetN.LowLink = -1;
757 OldSCC.Nodes.push_back(&TargetN);
758 G->SCCMap[&TargetN] = &OldSCC;
759
760 // Scan down the stack and DFS across the call edges.
761 for (Node *RootN : Worklist) {
762 assert(DFSStack.empty() &&
763 "Cannot begin a new root with a non-empty DFS stack!");
764 assert(PendingSCCStack.empty() &&
765 "Cannot begin a new root with pending nodes for an SCC!");
766
767 // Skip any nodes we've already reached in the DFS.
768 if (RootN->DFSNumber != 0) {
769 assert(RootN->DFSNumber == -1 &&
770 "Shouldn't have any mid-DFS root nodes!");
771 continue;
772 }
773
774 RootN->DFSNumber = RootN->LowLink = 1;
775 int NextDFSNumber = 2;
776
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000777 DFSStack.push_back({RootN, (*RootN)->call_begin()});
Chandler Carruthe5944d92016-02-17 00:18:16 +0000778 do {
779 Node *N;
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000780 EdgeSequence::call_iterator I;
Chandler Carruthe5944d92016-02-17 00:18:16 +0000781 std::tie(N, I) = DFSStack.pop_back_val();
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000782 auto E = (*N)->call_end();
Chandler Carruthe5944d92016-02-17 00:18:16 +0000783 while (I != E) {
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000784 Node &ChildN = I->getNode();
Chandler Carruthe5944d92016-02-17 00:18:16 +0000785 if (ChildN.DFSNumber == 0) {
786 // We haven't yet visited this child, so descend, pushing the current
787 // node onto the stack.
788 DFSStack.push_back({N, I});
789
790 assert(!G->SCCMap.count(&ChildN) &&
791 "Found a node with 0 DFS number but already in an SCC!");
792 ChildN.DFSNumber = ChildN.LowLink = NextDFSNumber++;
793 N = &ChildN;
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000794 I = (*N)->call_begin();
795 E = (*N)->call_end();
Chandler Carruthe5944d92016-02-17 00:18:16 +0000796 continue;
797 }
798
799 // Check for the child already being part of some component.
800 if (ChildN.DFSNumber == -1) {
801 if (G->lookupSCC(ChildN) == &OldSCC) {
802 // If the child is part of the old SCC, we know that it can reach
803 // every other node, so we have formed a cycle. Pull the entire DFS
804 // and pending stacks into it. See the comment above about setting
805 // up the old SCC for why we do this.
806 int OldSize = OldSCC.size();
807 OldSCC.Nodes.push_back(N);
808 OldSCC.Nodes.append(PendingSCCStack.begin(), PendingSCCStack.end());
809 PendingSCCStack.clear();
810 while (!DFSStack.empty())
811 OldSCC.Nodes.push_back(DFSStack.pop_back_val().first);
812 for (Node &N : make_range(OldSCC.begin() + OldSize, OldSCC.end())) {
813 N.DFSNumber = N.LowLink = -1;
814 G->SCCMap[&N] = &OldSCC;
815 }
816 N = nullptr;
817 break;
818 }
819
820 // If the child has already been added to some child component, it
821 // couldn't impact the low-link of this parent because it isn't
822 // connected, and thus its low-link isn't relevant so skip it.
823 ++I;
824 continue;
825 }
826
827 // Track the lowest linked child as the lowest link for this node.
828 assert(ChildN.LowLink > 0 && "Must have a positive low-link number!");
829 if (ChildN.LowLink < N->LowLink)
830 N->LowLink = ChildN.LowLink;
831
832 // Move to the next edge.
833 ++I;
834 }
835 if (!N)
836 // Cleared the DFS early, start another round.
837 break;
838
Vedant Kumar1a8456d2018-03-02 18:57:02 +0000839 // We've finished processing N and its descendants, put it on our pending
Chandler Carruthe5944d92016-02-17 00:18:16 +0000840 // SCC stack to eventually get merged into an SCC of nodes.
841 PendingSCCStack.push_back(N);
842
843 // If this node is linked to some lower entry, continue walking up the
844 // stack.
845 if (N->LowLink != N->DFSNumber)
846 continue;
847
848 // Otherwise, we've completed an SCC. Append it to our post order list of
849 // SCCs.
850 int RootDFSNumber = N->DFSNumber;
851 // Find the range of the node stack by walking down until we pass the
852 // root DFS number.
853 auto SCCNodes = make_range(
854 PendingSCCStack.rbegin(),
David Majnemer42531262016-08-12 03:55:06 +0000855 find_if(reverse(PendingSCCStack), [RootDFSNumber](const Node *N) {
856 return N->DFSNumber < RootDFSNumber;
857 }));
Chandler Carruthe5944d92016-02-17 00:18:16 +0000858
859 // Form a new SCC out of these nodes and then clear them off our pending
860 // stack.
861 NewSCCs.push_back(G->createSCC(*this, SCCNodes));
862 for (Node &N : *NewSCCs.back()) {
863 N.DFSNumber = N.LowLink = -1;
864 G->SCCMap[&N] = NewSCCs.back();
865 }
866 PendingSCCStack.erase(SCCNodes.end().base(), PendingSCCStack.end());
867 } while (!DFSStack.empty());
868 }
869
870 // Insert the remaining SCCs before the old one. The old SCC can reach all
871 // other SCCs we form because it contains the target node of the removed edge
872 // of the old SCC. This means that we will have edges into all of the new
873 // SCCs, which means the old one must come last for postorder.
874 int OldIdx = SCCIndices[&OldSCC];
875 SCCs.insert(SCCs.begin() + OldIdx, NewSCCs.begin(), NewSCCs.end());
876
877 // Update the mapping from SCC* to index to use the new SCC*s, and remove the
878 // old SCC from the mapping.
879 for (int Idx = OldIdx, Size = SCCs.size(); Idx < Size; ++Idx)
880 SCCIndices[SCCs[Idx]] = Idx;
881
Chandler Carruth88823462016-08-24 09:37:14 +0000882 return make_range(SCCs.begin() + OldIdx,
883 SCCs.begin() + OldIdx + NewSCCs.size());
Chandler Carruthe5944d92016-02-17 00:18:16 +0000884}
885
886void LazyCallGraph::RefSCC::switchOutgoingEdgeToCall(Node &SourceN,
887 Node &TargetN) {
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000888 assert(!(*SourceN)[TargetN].isCall() && "Must start with a ref edge!");
Chandler Carruthe5944d92016-02-17 00:18:16 +0000889
890 assert(G->lookupRefSCC(SourceN) == this && "Source must be in this RefSCC.");
891 assert(G->lookupRefSCC(TargetN) != this &&
892 "Target must not be in this RefSCC.");
Francis Visoiu Mistrih262ad162017-02-28 18:34:55 +0000893#ifdef EXPENSIVE_CHECKS
Chandler Carruthe5944d92016-02-17 00:18:16 +0000894 assert(G->lookupRefSCC(TargetN)->isDescendantOf(*this) &&
895 "Target must be a descendant of the Source.");
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +0000896#endif
Chandler Carruthe5944d92016-02-17 00:18:16 +0000897
898 // Edges between RefSCCs are the same regardless of call or ref, so we can
899 // just flip the edge here.
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000900 SourceN->setEdgeKind(TargetN, Edge::Call);
Chandler Carruthe5944d92016-02-17 00:18:16 +0000901
902#ifndef NDEBUG
903 // Check that the RefSCC is still valid.
904 verify();
905#endif
906}
907
908void LazyCallGraph::RefSCC::switchOutgoingEdgeToRef(Node &SourceN,
909 Node &TargetN) {
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000910 assert((*SourceN)[TargetN].isCall() && "Must start with a call edge!");
Chandler Carruthe5944d92016-02-17 00:18:16 +0000911
912 assert(G->lookupRefSCC(SourceN) == this && "Source must be in this RefSCC.");
913 assert(G->lookupRefSCC(TargetN) != this &&
914 "Target must not be in this RefSCC.");
Francis Visoiu Mistrih262ad162017-02-28 18:34:55 +0000915#ifdef EXPENSIVE_CHECKS
Chandler Carruthe5944d92016-02-17 00:18:16 +0000916 assert(G->lookupRefSCC(TargetN)->isDescendantOf(*this) &&
917 "Target must be a descendant of the Source.");
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +0000918#endif
Chandler Carruthe5944d92016-02-17 00:18:16 +0000919
920 // Edges between RefSCCs are the same regardless of call or ref, so we can
921 // just flip the edge here.
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000922 SourceN->setEdgeKind(TargetN, Edge::Ref);
Chandler Carruthe5944d92016-02-17 00:18:16 +0000923
924#ifndef NDEBUG
925 // Check that the RefSCC is still valid.
926 verify();
927#endif
928}
929
930void LazyCallGraph::RefSCC::insertInternalRefEdge(Node &SourceN,
931 Node &TargetN) {
932 assert(G->lookupRefSCC(SourceN) == this && "Source must be in this RefSCC.");
933 assert(G->lookupRefSCC(TargetN) == this && "Target must be in this RefSCC.");
934
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000935 SourceN->insertEdgeInternal(TargetN, Edge::Ref);
Chandler Carruthe5944d92016-02-17 00:18:16 +0000936
937#ifndef NDEBUG
938 // Check that the RefSCC is still valid.
939 verify();
940#endif
941}
942
943void LazyCallGraph::RefSCC::insertOutgoingEdge(Node &SourceN, Node &TargetN,
944 Edge::Kind EK) {
Chandler Carruth7cc4ed82014-05-01 12:18:20 +0000945 // First insert it into the caller.
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000946 SourceN->insertEdgeInternal(TargetN, EK);
Chandler Carruth7cc4ed82014-05-01 12:18:20 +0000947
Chandler Carruthe5944d92016-02-17 00:18:16 +0000948 assert(G->lookupRefSCC(SourceN) == this && "Source must be in this RefSCC.");
Chandler Carruth7cc4ed82014-05-01 12:18:20 +0000949
Chandler Carruth691d0242017-08-05 08:33:16 +0000950 assert(G->lookupRefSCC(TargetN) != this &&
951 "Target must not be in this RefSCC.");
Francis Visoiu Mistrih262ad162017-02-28 18:34:55 +0000952#ifdef EXPENSIVE_CHECKS
Chandler Carruth691d0242017-08-05 08:33:16 +0000953 assert(G->lookupRefSCC(TargetN)->isDescendantOf(*this) &&
Chandler Carruthe5944d92016-02-17 00:18:16 +0000954 "Target must be a descendant of the Source.");
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +0000955#endif
Chandler Carruth7cc4ed82014-05-01 12:18:20 +0000956
Chandler Carruthe5944d92016-02-17 00:18:16 +0000957#ifndef NDEBUG
958 // Check that the RefSCC is still valid.
959 verify();
960#endif
Chandler Carruth7cc4ed82014-05-01 12:18:20 +0000961}
962
Chandler Carruthe5944d92016-02-17 00:18:16 +0000963SmallVector<LazyCallGraph::RefSCC *, 1>
964LazyCallGraph::RefSCC::insertIncomingRefEdge(Node &SourceN, Node &TargetN) {
Chandler Carruth49d728a2016-09-16 10:20:17 +0000965 assert(G->lookupRefSCC(TargetN) == this && "Target must be in this RefSCC.");
966 RefSCC &SourceC = *G->lookupRefSCC(SourceN);
967 assert(&SourceC != this && "Source must not be in this RefSCC.");
Francis Visoiu Mistrih262ad162017-02-28 18:34:55 +0000968#ifdef EXPENSIVE_CHECKS
Chandler Carruth49d728a2016-09-16 10:20:17 +0000969 assert(SourceC.isDescendantOf(*this) &&
970 "Source must be a descendant of the Target.");
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +0000971#endif
Chandler Carruth49d728a2016-09-16 10:20:17 +0000972
973 SmallVector<RefSCC *, 1> DeletedRefSCCs;
Chandler Carruth312dddf2014-05-04 09:38:32 +0000974
Chandler Carruth11b3f602016-09-04 08:34:31 +0000975#ifndef NDEBUG
976 // In a debug build, verify the RefSCC is valid to start with and when this
977 // routine finishes.
978 verify();
979 auto VerifyOnExit = make_scope_exit([&]() { verify(); });
980#endif
981
Chandler Carruth49d728a2016-09-16 10:20:17 +0000982 int SourceIdx = G->RefSCCIndices[&SourceC];
983 int TargetIdx = G->RefSCCIndices[this];
984 assert(SourceIdx < TargetIdx &&
985 "Postorder list doesn't see edge as incoming!");
Chandler Carruth312dddf2014-05-04 09:38:32 +0000986
Chandler Carruth49d728a2016-09-16 10:20:17 +0000987 // Compute the RefSCCs which (transitively) reach the source. We do this by
988 // working backwards from the source using the parent set in each RefSCC,
989 // skipping any RefSCCs that don't fall in the postorder range. This has the
990 // advantage of walking the sparser parent edge (in high fan-out graphs) but
991 // more importantly this removes examining all forward edges in all RefSCCs
992 // within the postorder range which aren't in fact connected. Only connected
993 // RefSCCs (and their edges) are visited here.
994 auto ComputeSourceConnectedSet = [&](SmallPtrSetImpl<RefSCC *> &Set) {
995 Set.insert(&SourceC);
Chandler Carruth13ffd112017-08-05 03:37:37 +0000996 auto IsConnected = [&](RefSCC &RC) {
997 for (SCC &C : RC)
998 for (Node &N : C)
999 for (Edge &E : *N)
1000 if (Set.count(G->lookupRefSCC(E.getNode())))
1001 return true;
1002
1003 return false;
1004 };
1005
1006 for (RefSCC *C : make_range(G->PostOrderRefSCCs.begin() + SourceIdx + 1,
1007 G->PostOrderRefSCCs.begin() + TargetIdx + 1))
1008 if (IsConnected(*C))
1009 Set.insert(C);
Chandler Carruth49d728a2016-09-16 10:20:17 +00001010 };
Chandler Carruth312dddf2014-05-04 09:38:32 +00001011
Chandler Carruth49d728a2016-09-16 10:20:17 +00001012 // Use a normal worklist to find which SCCs the target connects to. We still
1013 // bound the search based on the range in the postorder list we care about,
1014 // but because this is forward connectivity we just "recurse" through the
1015 // edges.
1016 auto ComputeTargetConnectedSet = [&](SmallPtrSetImpl<RefSCC *> &Set) {
1017 Set.insert(this);
1018 SmallVector<RefSCC *, 4> Worklist;
1019 Worklist.push_back(this);
1020 do {
1021 RefSCC &RC = *Worklist.pop_back_val();
1022 for (SCC &C : RC)
1023 for (Node &N : C)
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001024 for (Edge &E : *N) {
1025 RefSCC &EdgeRC = *G->lookupRefSCC(E.getNode());
Chandler Carruth49d728a2016-09-16 10:20:17 +00001026 if (G->getRefSCCIndex(EdgeRC) <= SourceIdx)
1027 // Not in the postorder sequence between source and target.
1028 continue;
Chandler Carruth312dddf2014-05-04 09:38:32 +00001029
Chandler Carruth49d728a2016-09-16 10:20:17 +00001030 if (Set.insert(&EdgeRC).second)
1031 Worklist.push_back(&EdgeRC);
1032 }
1033 } while (!Worklist.empty());
1034 };
1035
1036 // Use a generic helper to update the postorder sequence of RefSCCs and return
1037 // a range of any RefSCCs connected into a cycle by inserting this edge. This
1038 // routine will also take care of updating the indices into the postorder
1039 // sequence.
1040 iterator_range<SmallVectorImpl<RefSCC *>::iterator> MergeRange =
1041 updatePostorderSequenceForEdgeInsertion(
1042 SourceC, *this, G->PostOrderRefSCCs, G->RefSCCIndices,
1043 ComputeSourceConnectedSet, ComputeTargetConnectedSet);
1044
Chandler Carruth5205c352016-12-07 01:42:40 +00001045 // Build a set so we can do fast tests for whether a RefSCC will end up as
1046 // part of the merged RefSCC.
Chandler Carruth49d728a2016-09-16 10:20:17 +00001047 SmallPtrSet<RefSCC *, 16> MergeSet(MergeRange.begin(), MergeRange.end());
Chandler Carruth312dddf2014-05-04 09:38:32 +00001048
Chandler Carruth5205c352016-12-07 01:42:40 +00001049 // This RefSCC will always be part of that set, so just insert it here.
1050 MergeSet.insert(this);
1051
Chandler Carruth312dddf2014-05-04 09:38:32 +00001052 // Now that we have identified all of the SCCs which need to be merged into
1053 // a connected set with the inserted edge, merge all of them into this SCC.
Chandler Carruthe5944d92016-02-17 00:18:16 +00001054 SmallVector<SCC *, 16> MergedSCCs;
1055 int SCCIndex = 0;
Chandler Carruth49d728a2016-09-16 10:20:17 +00001056 for (RefSCC *RC : MergeRange) {
1057 assert(RC != this && "We're merging into the target RefSCC, so it "
1058 "shouldn't be in the range.");
Chandler Carruth312dddf2014-05-04 09:38:32 +00001059
Chandler Carruthe5944d92016-02-17 00:18:16 +00001060 // Walk the inner SCCs to update their up-pointer and walk all the edges to
1061 // update any parent sets.
1062 // FIXME: We should try to find a way to avoid this (rather expensive) edge
1063 // walk by updating the parent sets in some other manner.
Chandler Carruth49d728a2016-09-16 10:20:17 +00001064 for (SCC &InnerC : *RC) {
Chandler Carruthe5944d92016-02-17 00:18:16 +00001065 InnerC.OuterRefSCC = this;
1066 SCCIndices[&InnerC] = SCCIndex++;
Chandler Carruthadbf14a2017-08-05 07:37:00 +00001067 for (Node &N : InnerC)
Chandler Carruthe5944d92016-02-17 00:18:16 +00001068 G->SCCMap[&N] = &InnerC;
Chandler Carruth312dddf2014-05-04 09:38:32 +00001069 }
Chandler Carruthe5944d92016-02-17 00:18:16 +00001070
1071 // Now merge in the SCCs. We can actually move here so try to reuse storage
1072 // the first time through.
1073 if (MergedSCCs.empty())
Chandler Carruth49d728a2016-09-16 10:20:17 +00001074 MergedSCCs = std::move(RC->SCCs);
Chandler Carruthe5944d92016-02-17 00:18:16 +00001075 else
Chandler Carruth49d728a2016-09-16 10:20:17 +00001076 MergedSCCs.append(RC->SCCs.begin(), RC->SCCs.end());
1077 RC->SCCs.clear();
1078 DeletedRefSCCs.push_back(RC);
Chandler Carruth312dddf2014-05-04 09:38:32 +00001079 }
Chandler Carruthe5944d92016-02-17 00:18:16 +00001080
Chandler Carruth49d728a2016-09-16 10:20:17 +00001081 // Append our original SCCs to the merged list and move it into place.
Chandler Carruthe5944d92016-02-17 00:18:16 +00001082 for (SCC &InnerC : *this)
1083 SCCIndices[&InnerC] = SCCIndex++;
1084 MergedSCCs.append(SCCs.begin(), SCCs.end());
1085 SCCs = std::move(MergedSCCs);
1086
Chandler Carruth49d728a2016-09-16 10:20:17 +00001087 // Remove the merged away RefSCCs from the post order sequence.
1088 for (RefSCC *RC : MergeRange)
1089 G->RefSCCIndices.erase(RC);
1090 int IndexOffset = MergeRange.end() - MergeRange.begin();
1091 auto EraseEnd =
1092 G->PostOrderRefSCCs.erase(MergeRange.begin(), MergeRange.end());
1093 for (RefSCC *RC : make_range(EraseEnd, G->PostOrderRefSCCs.end()))
1094 G->RefSCCIndices[RC] -= IndexOffset;
1095
Chandler Carruthe5944d92016-02-17 00:18:16 +00001096 // At this point we have a merged RefSCC with a post-order SCCs list, just
1097 // connect the nodes to form the new edge.
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001098 SourceN->insertEdgeInternal(TargetN, Edge::Ref);
Chandler Carruthe5944d92016-02-17 00:18:16 +00001099
Chandler Carruth312dddf2014-05-04 09:38:32 +00001100 // We return the list of SCCs which were merged so that callers can
1101 // invalidate any data they have associated with those SCCs. Note that these
1102 // SCCs are no longer in an interesting state (they are totally empty) but
1103 // the pointers will remain stable for the life of the graph itself.
Chandler Carruth49d728a2016-09-16 10:20:17 +00001104 return DeletedRefSCCs;
Chandler Carruth312dddf2014-05-04 09:38:32 +00001105}
1106
Chandler Carruthe5944d92016-02-17 00:18:16 +00001107void LazyCallGraph::RefSCC::removeOutgoingEdge(Node &SourceN, Node &TargetN) {
1108 assert(G->lookupRefSCC(SourceN) == this &&
1109 "The source must be a member of this RefSCC.");
Benjamin Krameref42fd42017-08-05 08:28:48 +00001110 assert(G->lookupRefSCC(TargetN) != this &&
1111 "The target must not be a member of this RefSCC");
Chandler Carruthe5944d92016-02-17 00:18:16 +00001112
Chandler Carruth11b3f602016-09-04 08:34:31 +00001113#ifndef NDEBUG
1114 // In a debug build, verify the RefSCC is valid to start with and when this
1115 // routine finishes.
1116 verify();
1117 auto VerifyOnExit = make_scope_exit([&]() { verify(); });
1118#endif
1119
Chandler Carruthaa839b22014-04-27 01:59:50 +00001120 // First remove it from the node.
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001121 bool Removed = SourceN->removeEdgeInternal(TargetN);
1122 (void)Removed;
1123 assert(Removed && "Target not in the edge set for this caller?");
Chandler Carruthaca48d02014-04-26 09:06:53 +00001124}
1125
Chandler Carruthe5944d92016-02-17 00:18:16 +00001126SmallVector<LazyCallGraph::RefSCC *, 1>
Chandler Carruth23c2f442017-08-09 09:05:27 +00001127LazyCallGraph::RefSCC::removeInternalRefEdge(Node &SourceN,
1128 ArrayRef<Node *> TargetNs) {
Chandler Carruthe5944d92016-02-17 00:18:16 +00001129 // We return a list of the resulting *new* RefSCCs in post-order.
1130 SmallVector<RefSCC *, 1> Result;
Chandler Carruth9302fbf2014-04-23 11:03:03 +00001131
Chandler Carruth23c2f442017-08-09 09:05:27 +00001132#ifndef NDEBUG
1133 // In a debug build, verify the RefSCC is valid to start with and that either
1134 // we return an empty list of result RefSCCs and this RefSCC remains valid,
1135 // or we return new RefSCCs and this RefSCC is dead.
1136 verify();
1137 auto VerifyOnExit = make_scope_exit([&]() {
Chandler Carruth9c161e82017-08-10 03:05:21 +00001138 // If we didn't replace our RefSCC with new ones, check that this one
1139 // remains valid.
1140 if (G)
Chandler Carruth23c2f442017-08-09 09:05:27 +00001141 verify();
Chandler Carruth23c2f442017-08-09 09:05:27 +00001142 });
1143#endif
1144
1145 // First remove the actual edges.
1146 for (Node *TargetN : TargetNs) {
1147 assert(!(*SourceN)[*TargetN].isCall() &&
1148 "Cannot remove a call edge, it must first be made a ref edge");
1149
1150 bool Removed = SourceN->removeEdgeInternal(*TargetN);
1151 (void)Removed;
1152 assert(Removed && "Target not in the edge set for this caller?");
1153 }
1154
1155 // Direct self references don't impact the ref graph at all.
1156 if (llvm::all_of(TargetNs,
1157 [&](Node *TargetN) { return &SourceN == TargetN; }))
Chandler Carruthe5944d92016-02-17 00:18:16 +00001158 return Result;
Chandler Carrutha7205b62014-04-26 03:36:37 +00001159
Chandler Carruth23c2f442017-08-09 09:05:27 +00001160 // If all targets are in the same SCC as the source, because no call edges
1161 // were removed there is no RefSCC structure change.
Chandler Carruthc6334572016-12-28 02:24:58 +00001162 SCC &SourceC = *G->lookupSCC(SourceN);
Chandler Carruth23c2f442017-08-09 09:05:27 +00001163 if (llvm::all_of(TargetNs, [&](Node *TargetN) {
1164 return G->lookupSCC(*TargetN) == &SourceC;
1165 }))
Chandler Carruthc6334572016-12-28 02:24:58 +00001166 return Result;
1167
Chandler Carruthe5944d92016-02-17 00:18:16 +00001168 // We build somewhat synthetic new RefSCCs by providing a postorder mapping
Chandler Carruth2cd28b22017-08-09 09:37:39 +00001169 // for each inner SCC. We store these inside the low-link field of the nodes
1170 // rather than associated with SCCs because this saves a round-trip through
1171 // the node->SCC map and in the common case, SCCs are small. We will verify
1172 // that we always give the same number to every node in the SCC such that
1173 // these are equivalent.
Chandler Carruth23c2f442017-08-09 09:05:27 +00001174 int PostOrderNumber = 0;
Chandler Carruthe5944d92016-02-17 00:18:16 +00001175
Chandler Carruthe5944d92016-02-17 00:18:16 +00001176 // Reset all the other nodes to prepare for a DFS over them, and add them to
1177 // our worklist.
1178 SmallVector<Node *, 8> Worklist;
1179 for (SCC *C : SCCs) {
Chandler Carruthe5944d92016-02-17 00:18:16 +00001180 for (Node &N : *C)
1181 N.DFSNumber = N.LowLink = 0;
1182
1183 Worklist.append(C->Nodes.begin(), C->Nodes.end());
Chandler Carruth9302fbf2014-04-23 11:03:03 +00001184 }
1185
Chandler Carruth9c3deaa2017-08-09 09:14:34 +00001186 // Track the number of nodes in this RefSCC so that we can quickly recognize
1187 // an important special case of the edge removal not breaking the cycle of
1188 // this RefSCC.
1189 const int NumRefSCCNodes = Worklist.size();
1190
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001191 SmallVector<std::pair<Node *, EdgeSequence::iterator>, 4> DFSStack;
Chandler Carruthe5944d92016-02-17 00:18:16 +00001192 SmallVector<Node *, 4> PendingRefSCCStack;
Chandler Carruthaca48d02014-04-26 09:06:53 +00001193 do {
Chandler Carruthe5944d92016-02-17 00:18:16 +00001194 assert(DFSStack.empty() &&
1195 "Cannot begin a new root with a non-empty DFS stack!");
1196 assert(PendingRefSCCStack.empty() &&
1197 "Cannot begin a new root with pending nodes for an SCC!");
1198
1199 Node *RootN = Worklist.pop_back_val();
1200 // Skip any nodes we've already reached in the DFS.
1201 if (RootN->DFSNumber != 0) {
1202 assert(RootN->DFSNumber == -1 &&
1203 "Shouldn't have any mid-DFS root nodes!");
1204 continue;
1205 }
1206
1207 RootN->DFSNumber = RootN->LowLink = 1;
1208 int NextDFSNumber = 2;
1209
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001210 DFSStack.push_back({RootN, (*RootN)->begin()});
Chandler Carruthe5944d92016-02-17 00:18:16 +00001211 do {
1212 Node *N;
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001213 EdgeSequence::iterator I;
Chandler Carruthe5944d92016-02-17 00:18:16 +00001214 std::tie(N, I) = DFSStack.pop_back_val();
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001215 auto E = (*N)->end();
Chandler Carruthe5944d92016-02-17 00:18:16 +00001216
1217 assert(N->DFSNumber != 0 && "We should always assign a DFS number "
1218 "before processing a node.");
1219
1220 while (I != E) {
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001221 Node &ChildN = I->getNode();
Chandler Carruthe5944d92016-02-17 00:18:16 +00001222 if (ChildN.DFSNumber == 0) {
1223 // Mark that we should start at this child when next this node is the
1224 // top of the stack. We don't start at the next child to ensure this
1225 // child's lowlink is reflected.
1226 DFSStack.push_back({N, I});
1227
1228 // Continue, resetting to the child node.
1229 ChildN.LowLink = ChildN.DFSNumber = NextDFSNumber++;
1230 N = &ChildN;
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001231 I = ChildN->begin();
1232 E = ChildN->end();
Chandler Carruthe5944d92016-02-17 00:18:16 +00001233 continue;
1234 }
1235 if (ChildN.DFSNumber == -1) {
Chandler Carruthe5944d92016-02-17 00:18:16 +00001236 // If this child isn't currently in this RefSCC, no need to process
Chandler Carruthadbf14a2017-08-05 07:37:00 +00001237 // it.
Chandler Carruthe5944d92016-02-17 00:18:16 +00001238 ++I;
1239 continue;
1240 }
1241
1242 // Track the lowest link of the children, if any are still in the stack.
1243 // Any child not on the stack will have a LowLink of -1.
1244 assert(ChildN.LowLink != 0 &&
1245 "Low-link must not be zero with a non-zero DFS number.");
1246 if (ChildN.LowLink >= 0 && ChildN.LowLink < N->LowLink)
1247 N->LowLink = ChildN.LowLink;
1248 ++I;
1249 }
Chandler Carruthe5944d92016-02-17 00:18:16 +00001250
Vedant Kumar1a8456d2018-03-02 18:57:02 +00001251 // We've finished processing N and its descendants, put it on our pending
Chandler Carruthe5944d92016-02-17 00:18:16 +00001252 // stack to eventually get merged into a RefSCC.
1253 PendingRefSCCStack.push_back(N);
1254
1255 // If this node is linked to some lower entry, continue walking up the
1256 // stack.
1257 if (N->LowLink != N->DFSNumber) {
1258 assert(!DFSStack.empty() &&
1259 "We never found a viable root for a RefSCC to pop off!");
1260 continue;
1261 }
1262
1263 // Otherwise, form a new RefSCC from the top of the pending node stack.
Chandler Carruth2cd28b22017-08-09 09:37:39 +00001264 int RefSCCNumber = PostOrderNumber++;
Chandler Carruthe5944d92016-02-17 00:18:16 +00001265 int RootDFSNumber = N->DFSNumber;
Chandler Carruth2cd28b22017-08-09 09:37:39 +00001266
Chandler Carruthe5944d92016-02-17 00:18:16 +00001267 // Find the range of the node stack by walking down until we pass the
Chandler Carruth2cd28b22017-08-09 09:37:39 +00001268 // root DFS number. Update the DFS numbers and low link numbers in the
1269 // process to avoid re-walking this list where possible.
1270 auto StackRI = find_if(reverse(PendingRefSCCStack), [&](Node *N) {
1271 if (N->DFSNumber < RootDFSNumber)
1272 // We've found the bottom.
1273 return true;
1274
1275 // Update this node and keep scanning.
1276 N->DFSNumber = -1;
1277 // Save the post-order number in the lowlink field so that we can use
1278 // it to map SCCs into new RefSCCs after we finish the DFS.
1279 N->LowLink = RefSCCNumber;
1280 return false;
1281 });
1282 auto RefSCCNodes = make_range(StackRI.base(), PendingRefSCCStack.end());
Chandler Carruth9c3deaa2017-08-09 09:14:34 +00001283
1284 // If we find a cycle containing all nodes originally in this RefSCC then
1285 // the removal hasn't changed the structure at all. This is an important
1286 // special case and we can directly exit the entire routine more
1287 // efficiently as soon as we discover it.
Vedant Kumar5a0872c2018-05-16 23:20:42 +00001288 if (llvm::size(RefSCCNodes) == NumRefSCCNodes) {
Chandler Carruth2cd28b22017-08-09 09:37:39 +00001289 // Clear out the low link field as we won't need it.
Chandler Carruth9c3deaa2017-08-09 09:14:34 +00001290 for (Node *N : RefSCCNodes)
Chandler Carruth2cd28b22017-08-09 09:37:39 +00001291 N->LowLink = -1;
Chandler Carruth9c3deaa2017-08-09 09:14:34 +00001292 // Return the empty result immediately.
1293 return Result;
1294 }
Chandler Carruthe5944d92016-02-17 00:18:16 +00001295
Chandler Carruth2cd28b22017-08-09 09:37:39 +00001296 // We've already marked the nodes internally with the RefSCC number so
1297 // just clear them off the stack and continue.
Chandler Carruth9c3deaa2017-08-09 09:14:34 +00001298 PendingRefSCCStack.erase(RefSCCNodes.begin(), PendingRefSCCStack.end());
Chandler Carruthe5944d92016-02-17 00:18:16 +00001299 } while (!DFSStack.empty());
Chandler Carruth9302fbf2014-04-23 11:03:03 +00001300
Chandler Carruthaca48d02014-04-26 09:06:53 +00001301 assert(DFSStack.empty() && "Didn't flush the entire DFS stack!");
Chandler Carruthe5944d92016-02-17 00:18:16 +00001302 assert(PendingRefSCCStack.empty() && "Didn't flush all pending nodes!");
Chandler Carruthaca48d02014-04-26 09:06:53 +00001303 } while (!Worklist.empty());
Chandler Carruth9302fbf2014-04-23 11:03:03 +00001304
Chandler Carruth9c3deaa2017-08-09 09:14:34 +00001305 assert(PostOrderNumber > 1 &&
1306 "Should never finish the DFS when the existing RefSCC remains valid!");
Chandler Carruth23c2f442017-08-09 09:05:27 +00001307
1308 // Otherwise we create a collection of new RefSCC nodes and build
1309 // a radix-sort style map from postorder number to these new RefSCCs. We then
Malcolm Parsons21e545d2018-01-24 10:33:39 +00001310 // append SCCs to each of these RefSCCs in the order they occurred in the
Chandler Carruth23c2f442017-08-09 09:05:27 +00001311 // original SCCs container.
1312 for (int i = 0; i < PostOrderNumber; ++i)
Chandler Carruthe5944d92016-02-17 00:18:16 +00001313 Result.push_back(G->createRefSCC(*G));
1314
Chandler Carruth49d728a2016-09-16 10:20:17 +00001315 // Insert the resulting postorder sequence into the global graph postorder
Chandler Carruth23c2f442017-08-09 09:05:27 +00001316 // sequence before the current RefSCC in that sequence, and then remove the
1317 // current one.
Chandler Carruth49d728a2016-09-16 10:20:17 +00001318 //
1319 // FIXME: It'd be nice to change the APIs so that we returned an iterator
1320 // range over the global postorder sequence and generally use that sequence
1321 // rather than building a separate result vector here.
Chandler Carruth23c2f442017-08-09 09:05:27 +00001322 int Idx = G->getRefSCCIndex(*this);
1323 G->PostOrderRefSCCs.erase(G->PostOrderRefSCCs.begin() + Idx);
1324 G->PostOrderRefSCCs.insert(G->PostOrderRefSCCs.begin() + Idx, Result.begin(),
1325 Result.end());
1326 for (int i : seq<int>(Idx, G->PostOrderRefSCCs.size()))
1327 G->RefSCCIndices[G->PostOrderRefSCCs[i]] = i;
Chandler Carruth49d728a2016-09-16 10:20:17 +00001328
Chandler Carruthe5944d92016-02-17 00:18:16 +00001329 for (SCC *C : SCCs) {
Chandler Carruth2cd28b22017-08-09 09:37:39 +00001330 // We store the SCC number in the node's low-link field above.
1331 int SCCNumber = C->begin()->LowLink;
1332 // Clear out all of the SCC's node's low-link fields now that we're done
1333 // using them as side-storage.
1334 for (Node &N : *C) {
1335 assert(N.LowLink == SCCNumber &&
Chandler Carruthe5944d92016-02-17 00:18:16 +00001336 "Cannot have different numbers for nodes in the same SCC!");
Chandler Carruth2cd28b22017-08-09 09:37:39 +00001337 N.LowLink = -1;
1338 }
Chandler Carruthe5944d92016-02-17 00:18:16 +00001339
Chandler Carruth23c2f442017-08-09 09:05:27 +00001340 RefSCC &RC = *Result[SCCNumber];
Chandler Carruthe5944d92016-02-17 00:18:16 +00001341 int SCCIndex = RC.SCCs.size();
1342 RC.SCCs.push_back(C);
Chandler Carruth23a6c3f2016-12-06 10:29:23 +00001343 RC.SCCIndices[C] = SCCIndex;
Chandler Carruthe5944d92016-02-17 00:18:16 +00001344 C->OuterRefSCC = &RC;
1345 }
1346
Chandler Carruth23c2f442017-08-09 09:05:27 +00001347 // Now that we've moved things into the new RefSCCs, clear out our current
1348 // one.
1349 G = nullptr;
1350 SCCs.clear();
Chandler Carruth88823462016-08-24 09:37:14 +00001351 SCCIndices.clear();
Chandler Carruth23a6c3f2016-12-06 10:29:23 +00001352
Chandler Carruth9c161e82017-08-10 03:05:21 +00001353#ifndef NDEBUG
1354 // Verify the new RefSCCs we've built.
1355 for (RefSCC *RC : Result)
1356 RC->verify();
1357#endif
1358
Chandler Carruth9302fbf2014-04-23 11:03:03 +00001359 // Return the new list of SCCs.
Chandler Carruthe5944d92016-02-17 00:18:16 +00001360 return Result;
Chandler Carruth9302fbf2014-04-23 11:03:03 +00001361}
1362
Chandler Carruth5dbc1642016-10-12 07:59:56 +00001363void LazyCallGraph::RefSCC::handleTrivialEdgeInsertion(Node &SourceN,
1364 Node &TargetN) {
1365 // The only trivial case that requires any graph updates is when we add new
1366 // ref edge and may connect different RefSCCs along that path. This is only
1367 // because of the parents set. Every other part of the graph remains constant
1368 // after this edge insertion.
1369 assert(G->lookupRefSCC(SourceN) == this && "Source must be in this RefSCC.");
1370 RefSCC &TargetRC = *G->lookupRefSCC(TargetN);
Eugene Zelenko530851c2017-08-11 21:30:02 +00001371 if (&TargetRC == this)
Chandler Carruth5dbc1642016-10-12 07:59:56 +00001372 return;
Chandler Carruth5dbc1642016-10-12 07:59:56 +00001373
Francis Visoiu Mistrih262ad162017-02-28 18:34:55 +00001374#ifdef EXPENSIVE_CHECKS
Chandler Carruth5dbc1642016-10-12 07:59:56 +00001375 assert(TargetRC.isDescendantOf(*this) &&
1376 "Target must be a descendant of the Source.");
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001377#endif
Chandler Carruth5dbc1642016-10-12 07:59:56 +00001378}
1379
1380void LazyCallGraph::RefSCC::insertTrivialCallEdge(Node &SourceN,
1381 Node &TargetN) {
1382#ifndef NDEBUG
1383 // Check that the RefSCC is still valid when we finish.
1384 auto ExitVerifier = make_scope_exit([this] { verify(); });
Chandler Carruthbae595b2016-11-22 19:23:31 +00001385
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001386#ifdef EXPENSIVE_CHECKS
1387 // Check that we aren't breaking some invariants of the SCC graph. Note that
1388 // this is quadratic in the number of edges in the call graph!
Chandler Carruthbae595b2016-11-22 19:23:31 +00001389 SCC &SourceC = *G->lookupSCC(SourceN);
1390 SCC &TargetC = *G->lookupSCC(TargetN);
1391 if (&SourceC != &TargetC)
1392 assert(SourceC.isAncestorOf(TargetC) &&
1393 "Call edge is not trivial in the SCC graph!");
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001394#endif // EXPENSIVE_CHECKS
1395#endif // NDEBUG
1396
Chandler Carruth5dbc1642016-10-12 07:59:56 +00001397 // First insert it into the source or find the existing edge.
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001398 auto InsertResult =
1399 SourceN->EdgeIndexMap.insert({&TargetN, SourceN->Edges.size()});
Chandler Carruth5dbc1642016-10-12 07:59:56 +00001400 if (!InsertResult.second) {
1401 // Already an edge, just update it.
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001402 Edge &E = SourceN->Edges[InsertResult.first->second];
Chandler Carruth5dbc1642016-10-12 07:59:56 +00001403 if (E.isCall())
1404 return; // Nothing to do!
1405 E.setKind(Edge::Call);
1406 } else {
1407 // Create the new edge.
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001408 SourceN->Edges.emplace_back(TargetN, Edge::Call);
Chandler Carruth5dbc1642016-10-12 07:59:56 +00001409 }
1410
1411 // Now that we have the edge, handle the graph fallout.
1412 handleTrivialEdgeInsertion(SourceN, TargetN);
1413}
1414
1415void LazyCallGraph::RefSCC::insertTrivialRefEdge(Node &SourceN, Node &TargetN) {
1416#ifndef NDEBUG
1417 // Check that the RefSCC is still valid when we finish.
1418 auto ExitVerifier = make_scope_exit([this] { verify(); });
Chandler Carruth9eb857c2016-11-22 21:40:10 +00001419
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001420#ifdef EXPENSIVE_CHECKS
Chandler Carruth9eb857c2016-11-22 21:40:10 +00001421 // Check that we aren't breaking some invariants of the RefSCC graph.
1422 RefSCC &SourceRC = *G->lookupRefSCC(SourceN);
1423 RefSCC &TargetRC = *G->lookupRefSCC(TargetN);
1424 if (&SourceRC != &TargetRC)
1425 assert(SourceRC.isAncestorOf(TargetRC) &&
1426 "Ref edge is not trivial in the RefSCC graph!");
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001427#endif // EXPENSIVE_CHECKS
1428#endif // NDEBUG
1429
Chandler Carruth5dbc1642016-10-12 07:59:56 +00001430 // First insert it into the source or find the existing edge.
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001431 auto InsertResult =
1432 SourceN->EdgeIndexMap.insert({&TargetN, SourceN->Edges.size()});
Chandler Carruth5dbc1642016-10-12 07:59:56 +00001433 if (!InsertResult.second)
1434 // Already an edge, we're done.
1435 return;
1436
1437 // Create the new edge.
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001438 SourceN->Edges.emplace_back(TargetN, Edge::Ref);
Chandler Carruth5dbc1642016-10-12 07:59:56 +00001439
1440 // Now that we have the edge, handle the graph fallout.
1441 handleTrivialEdgeInsertion(SourceN, TargetN);
1442}
1443
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001444void LazyCallGraph::RefSCC::replaceNodeFunction(Node &N, Function &NewF) {
1445 Function &OldF = N.getFunction();
Chandler Carruthc00a7ff2014-04-28 11:10:23 +00001446
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001447#ifndef NDEBUG
1448 // Check that the RefSCC is still valid when we finish.
1449 auto ExitVerifier = make_scope_exit([this] { verify(); });
1450
1451 assert(G->lookupRefSCC(N) == this &&
1452 "Cannot replace the function of a node outside this RefSCC.");
1453
1454 assert(G->NodeMap.find(&NewF) == G->NodeMap.end() &&
1455 "Must not have already walked the new function!'");
1456
1457 // It is important that this replacement not introduce graph changes so we
1458 // insist that the caller has already removed every use of the original
1459 // function and that all uses of the new function correspond to existing
1460 // edges in the graph. The common and expected way to use this is when
1461 // replacing the function itself in the IR without changing the call graph
1462 // shape and just updating the analysis based on that.
1463 assert(&OldF != &NewF && "Cannot replace a function with itself!");
1464 assert(OldF.use_empty() &&
1465 "Must have moved all uses from the old function to the new!");
1466#endif
1467
1468 N.replaceFunction(NewF);
1469
1470 // Update various call graph maps.
1471 G->NodeMap.erase(&OldF);
1472 G->NodeMap[&NewF] = &N;
Chandler Carruthc00a7ff2014-04-28 11:10:23 +00001473}
1474
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001475void LazyCallGraph::insertEdge(Node &SourceN, Node &TargetN, Edge::Kind EK) {
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001476 assert(SCCMap.empty() &&
Chandler Carruthaa839b22014-04-27 01:59:50 +00001477 "This method cannot be called after SCCs have been formed!");
Chandler Carruth9302fbf2014-04-23 11:03:03 +00001478
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001479 return SourceN->insertEdgeInternal(TargetN, EK);
1480}
1481
1482void LazyCallGraph::removeEdge(Node &SourceN, Node &TargetN) {
1483 assert(SCCMap.empty() &&
1484 "This method cannot be called after SCCs have been formed!");
1485
1486 bool Removed = SourceN->removeEdgeInternal(TargetN);
1487 (void)Removed;
1488 assert(Removed && "Target not in the edge set for this caller?");
Chandler Carruth9302fbf2014-04-23 11:03:03 +00001489}
1490
Chandler Carruth5dbc1642016-10-12 07:59:56 +00001491void LazyCallGraph::removeDeadFunction(Function &F) {
1492 // FIXME: This is unnecessarily restrictive. We should be able to remove
1493 // functions which recursively call themselves.
1494 assert(F.use_empty() &&
1495 "This routine should only be called on trivially dead functions!");
1496
Chandler Carruth06a86302017-07-19 04:12:25 +00001497 // We shouldn't remove library functions as they are never really dead while
1498 // the call graph is in use -- every function definition refers to them.
1499 assert(!isLibFunction(F) &&
1500 "Must not remove lib functions from the call graph!");
1501
Chandler Carruth5dbc1642016-10-12 07:59:56 +00001502 auto NI = NodeMap.find(&F);
1503 if (NI == NodeMap.end())
1504 // Not in the graph at all!
1505 return;
1506
1507 Node &N = *NI->second;
1508 NodeMap.erase(NI);
1509
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001510 // Remove this from the entry edges if present.
1511 EntryEdges.removeEdgeInternal(N);
1512
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001513 if (SCCMap.empty()) {
1514 // No SCCs have been formed, so removing this is fine and there is nothing
Chandler Carruth5dbc1642016-10-12 07:59:56 +00001515 // else necessary at this point but clearing out the node.
1516 N.clear();
1517 return;
1518 }
1519
Chandler Carruth5dbc1642016-10-12 07:59:56 +00001520 // Cannot remove a function which has yet to be visited in the DFS walk, so
1521 // if we have a node at all then we must have an SCC and RefSCC.
1522 auto CI = SCCMap.find(&N);
1523 assert(CI != SCCMap.end() &&
1524 "Tried to remove a node without an SCC after DFS walk started!");
1525 SCC &C = *CI->second;
1526 SCCMap.erase(CI);
1527 RefSCC &RC = C.getOuterRefSCC();
1528
1529 // This node must be the only member of its SCC as it has no callers, and
1530 // that SCC must be the only member of a RefSCC as it has no references.
1531 // Validate these properties first.
1532 assert(C.size() == 1 && "Dead functions must be in a singular SCC");
1533 assert(RC.size() == 1 && "Dead functions must be in a singular RefSCC");
Chandler Carruth1f8fcfe2017-02-09 23:30:14 +00001534
Chandler Carruth5dbc1642016-10-12 07:59:56 +00001535 auto RCIndexI = RefSCCIndices.find(&RC);
1536 int RCIndex = RCIndexI->second;
1537 PostOrderRefSCCs.erase(PostOrderRefSCCs.begin() + RCIndex);
1538 RefSCCIndices.erase(RCIndexI);
1539 for (int i = RCIndex, Size = PostOrderRefSCCs.size(); i < Size; ++i)
1540 RefSCCIndices[PostOrderRefSCCs[i]] = i;
1541
1542 // Finally clear out all the data structures from the node down through the
1543 // components.
1544 N.clear();
Chandler Carruth403d3c42017-08-05 03:37:39 +00001545 N.G = nullptr;
Chandler Carruthc718b8e2017-08-05 05:47:37 +00001546 N.F = nullptr;
Chandler Carruth5dbc1642016-10-12 07:59:56 +00001547 C.clear();
1548 RC.clear();
Chandler Carruth403d3c42017-08-05 03:37:39 +00001549 RC.G = nullptr;
Chandler Carruth5dbc1642016-10-12 07:59:56 +00001550
1551 // Nothing to delete as all the objects are allocated in stable bump pointer
1552 // allocators.
1553}
1554
Chandler Carruth2a898e02014-04-23 23:20:36 +00001555LazyCallGraph::Node &LazyCallGraph::insertInto(Function &F, Node *&MappedN) {
1556 return *new (MappedN = BPA.Allocate()) Node(*this, F);
Chandler Carruthd8d865e2014-04-18 11:02:33 +00001557}
1558
1559void LazyCallGraph::updateGraphPtrs() {
Chandler Carruth7cb23e72017-08-05 03:37:39 +00001560 // Walk the node map to update their graph pointers. While this iterates in
1561 // an unstable order, the order has no effect so it remains correct.
1562 for (auto &FunctionNodePair : NodeMap)
1563 FunctionNodePair.second->G = this;
Chandler Carruthaa839b22014-04-27 01:59:50 +00001564
Chandler Carruth2c58e1a2017-08-05 03:37:38 +00001565 for (auto *RC : PostOrderRefSCCs)
1566 RC->G = this;
Chandler Carruthbf71a342014-02-06 04:37:03 +00001567}
Chandler Carruthbf71a342014-02-06 04:37:03 +00001568
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001569template <typename RootsT, typename GetBeginT, typename GetEndT,
1570 typename GetNodeT, typename FormSCCCallbackT>
1571void LazyCallGraph::buildGenericSCCs(RootsT &&Roots, GetBeginT &&GetBegin,
1572 GetEndT &&GetEnd, GetNodeT &&GetNode,
1573 FormSCCCallbackT &&FormSCC) {
Eugene Zelenko530851c2017-08-11 21:30:02 +00001574 using EdgeItT = decltype(GetBegin(std::declval<Node &>()));
Chandler Carruth3f9869a2014-04-23 06:09:03 +00001575
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001576 SmallVector<std::pair<Node *, EdgeItT>, 16> DFSStack;
Chandler Carruthe5944d92016-02-17 00:18:16 +00001577 SmallVector<Node *, 16> PendingSCCStack;
1578
1579 // Scan down the stack and DFS across the call edges.
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001580 for (Node *RootN : Roots) {
Chandler Carruthe5944d92016-02-17 00:18:16 +00001581 assert(DFSStack.empty() &&
1582 "Cannot begin a new root with a non-empty DFS stack!");
1583 assert(PendingSCCStack.empty() &&
1584 "Cannot begin a new root with pending nodes for an SCC!");
1585
1586 // Skip any nodes we've already reached in the DFS.
1587 if (RootN->DFSNumber != 0) {
1588 assert(RootN->DFSNumber == -1 &&
1589 "Shouldn't have any mid-DFS root nodes!");
1590 continue;
Chandler Carruth3f9869a2014-04-23 06:09:03 +00001591 }
1592
Chandler Carruthe5944d92016-02-17 00:18:16 +00001593 RootN->DFSNumber = RootN->LowLink = 1;
1594 int NextDFSNumber = 2;
Chandler Carruth3f9869a2014-04-23 06:09:03 +00001595
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001596 DFSStack.push_back({RootN, GetBegin(*RootN)});
Chandler Carruthe5944d92016-02-17 00:18:16 +00001597 do {
1598 Node *N;
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001599 EdgeItT I;
Chandler Carruthe5944d92016-02-17 00:18:16 +00001600 std::tie(N, I) = DFSStack.pop_back_val();
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001601 auto E = GetEnd(*N);
Chandler Carruthe5944d92016-02-17 00:18:16 +00001602 while (I != E) {
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001603 Node &ChildN = GetNode(I);
Chandler Carruthe5944d92016-02-17 00:18:16 +00001604 if (ChildN.DFSNumber == 0) {
1605 // We haven't yet visited this child, so descend, pushing the current
1606 // node onto the stack.
1607 DFSStack.push_back({N, I});
1608
Chandler Carruthe5944d92016-02-17 00:18:16 +00001609 ChildN.DFSNumber = ChildN.LowLink = NextDFSNumber++;
1610 N = &ChildN;
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001611 I = GetBegin(*N);
1612 E = GetEnd(*N);
Chandler Carruthe5944d92016-02-17 00:18:16 +00001613 continue;
1614 }
1615
1616 // If the child has already been added to some child component, it
1617 // couldn't impact the low-link of this parent because it isn't
1618 // connected, and thus its low-link isn't relevant so skip it.
1619 if (ChildN.DFSNumber == -1) {
1620 ++I;
1621 continue;
1622 }
1623
1624 // Track the lowest linked child as the lowest link for this node.
1625 assert(ChildN.LowLink > 0 && "Must have a positive low-link number!");
1626 if (ChildN.LowLink < N->LowLink)
1627 N->LowLink = ChildN.LowLink;
1628
1629 // Move to the next edge.
1630 ++I;
1631 }
1632
Vedant Kumar1a8456d2018-03-02 18:57:02 +00001633 // We've finished processing N and its descendants, put it on our pending
Chandler Carruthe5944d92016-02-17 00:18:16 +00001634 // SCC stack to eventually get merged into an SCC of nodes.
1635 PendingSCCStack.push_back(N);
1636
1637 // If this node is linked to some lower entry, continue walking up the
1638 // stack.
1639 if (N->LowLink != N->DFSNumber)
1640 continue;
1641
1642 // Otherwise, we've completed an SCC. Append it to our post order list of
1643 // SCCs.
1644 int RootDFSNumber = N->DFSNumber;
1645 // Find the range of the node stack by walking down until we pass the
1646 // root DFS number.
1647 auto SCCNodes = make_range(
1648 PendingSCCStack.rbegin(),
David Majnemer42531262016-08-12 03:55:06 +00001649 find_if(reverse(PendingSCCStack), [RootDFSNumber](const Node *N) {
1650 return N->DFSNumber < RootDFSNumber;
1651 }));
Chandler Carruthe5944d92016-02-17 00:18:16 +00001652 // Form a new SCC out of these nodes and then clear them off our pending
1653 // stack.
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001654 FormSCC(SCCNodes);
Chandler Carruthe5944d92016-02-17 00:18:16 +00001655 PendingSCCStack.erase(SCCNodes.end().base(), PendingSCCStack.end());
1656 } while (!DFSStack.empty());
1657 }
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001658}
1659
1660/// Build the internal SCCs for a RefSCC from a sequence of nodes.
1661///
1662/// Appends the SCCs to the provided vector and updates the map with their
1663/// indices. Both the vector and map must be empty when passed into this
1664/// routine.
1665void LazyCallGraph::buildSCCs(RefSCC &RC, node_stack_range Nodes) {
1666 assert(RC.SCCs.empty() && "Already built SCCs!");
1667 assert(RC.SCCIndices.empty() && "Already mapped SCC indices!");
1668
1669 for (Node *N : Nodes) {
1670 assert(N->LowLink >= (*Nodes.begin())->LowLink &&
1671 "We cannot have a low link in an SCC lower than its root on the "
1672 "stack!");
1673
1674 // This node will go into the next RefSCC, clear out its DFS and low link
1675 // as we scan.
1676 N->DFSNumber = N->LowLink = 0;
1677 }
1678
1679 // Each RefSCC contains a DAG of the call SCCs. To build these, we do
1680 // a direct walk of the call edges using Tarjan's algorithm. We reuse the
1681 // internal storage as we won't need it for the outer graph's DFS any longer.
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001682 buildGenericSCCs(
1683 Nodes, [](Node &N) { return N->call_begin(); },
1684 [](Node &N) { return N->call_end(); },
1685 [](EdgeSequence::call_iterator I) -> Node & { return I->getNode(); },
1686 [this, &RC](node_stack_range Nodes) {
1687 RC.SCCs.push_back(createSCC(RC, Nodes));
1688 for (Node &N : *RC.SCCs.back()) {
1689 N.DFSNumber = N.LowLink = -1;
1690 SCCMap[&N] = RC.SCCs.back();
1691 }
1692 });
Chandler Carruthe5944d92016-02-17 00:18:16 +00001693
1694 // Wire up the SCC indices.
1695 for (int i = 0, Size = RC.SCCs.size(); i < Size; ++i)
1696 RC.SCCIndices[RC.SCCs[i]] = i;
Chandler Carruth3f9869a2014-04-23 06:09:03 +00001697}
1698
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001699void LazyCallGraph::buildRefSCCs() {
1700 if (EntryEdges.empty() || !PostOrderRefSCCs.empty())
1701 // RefSCCs are either non-existent or already built!
1702 return;
1703
1704 assert(RefSCCIndices.empty() && "Already mapped RefSCC indices!");
1705
1706 SmallVector<Node *, 16> Roots;
1707 for (Edge &E : *this)
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001708 Roots.push_back(&E.getNode());
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001709
1710 // The roots will be popped of a stack, so use reverse to get a less
1711 // surprising order. This doesn't change any of the semantics anywhere.
1712 std::reverse(Roots.begin(), Roots.end());
1713
1714 buildGenericSCCs(
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001715 Roots,
1716 [](Node &N) {
1717 // We need to populate each node as we begin to walk its edges.
1718 N.populate();
1719 return N->begin();
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001720 },
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001721 [](Node &N) { return N->end(); },
1722 [](EdgeSequence::iterator I) -> Node & { return I->getNode(); },
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001723 [this](node_stack_range Nodes) {
1724 RefSCC *NewRC = createRefSCC(*this);
1725 buildSCCs(*NewRC, Nodes);
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001726
1727 // Push the new node into the postorder list and remember its position
1728 // in the index map.
1729 bool Inserted =
1730 RefSCCIndices.insert({NewRC, PostOrderRefSCCs.size()}).second;
1731 (void)Inserted;
1732 assert(Inserted && "Cannot already have this RefSCC in the index map!");
1733 PostOrderRefSCCs.push_back(NewRC);
Chandler Carrutha80cfb32017-02-06 20:59:07 +00001734#ifndef NDEBUG
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001735 NewRC->verify();
Chandler Carrutha80cfb32017-02-06 20:59:07 +00001736#endif
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001737 });
1738}
1739
Chandler Carruthdab4eae2016-11-23 17:53:26 +00001740AnalysisKey LazyCallGraphAnalysis::Key;
NAKAMURA Takumidf0cd722016-02-28 17:17:00 +00001741
Chandler Carruthbf71a342014-02-06 04:37:03 +00001742LazyCallGraphPrinterPass::LazyCallGraphPrinterPass(raw_ostream &OS) : OS(OS) {}
1743
Chandler Carruthe5944d92016-02-17 00:18:16 +00001744static void printNode(raw_ostream &OS, LazyCallGraph::Node &N) {
Chandler Carrutha4499e92016-02-02 03:57:13 +00001745 OS << " Edges in function: " << N.getFunction().getName() << "\n";
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001746 for (LazyCallGraph::Edge &E : N.populate())
Chandler Carrutha4499e92016-02-02 03:57:13 +00001747 OS << " " << (E.isCall() ? "call" : "ref ") << " -> "
1748 << E.getFunction().getName() << "\n";
Chandler Carruth11f50322015-01-14 00:27:45 +00001749
1750 OS << "\n";
1751}
1752
Chandler Carruthe5944d92016-02-17 00:18:16 +00001753static void printSCC(raw_ostream &OS, LazyCallGraph::SCC &C) {
Fangrui Songcb4327d2019-08-06 10:24:36 +00001754 OS << " SCC with " << C.size() << " functions:\n";
Chandler Carruth11f50322015-01-14 00:27:45 +00001755
Chandler Carruthe5944d92016-02-17 00:18:16 +00001756 for (LazyCallGraph::Node &N : C)
1757 OS << " " << N.getFunction().getName() << "\n";
1758}
1759
1760static void printRefSCC(raw_ostream &OS, LazyCallGraph::RefSCC &C) {
Fangrui Songcb4327d2019-08-06 10:24:36 +00001761 OS << " RefSCC with " << C.size() << " call SCCs:\n";
Chandler Carruthe5944d92016-02-17 00:18:16 +00001762
1763 for (LazyCallGraph::SCC &InnerC : C)
1764 printSCC(OS, InnerC);
Chandler Carruth11f50322015-01-14 00:27:45 +00001765
1766 OS << "\n";
1767}
1768
Chandler Carruthd174ce42015-01-05 02:47:05 +00001769PreservedAnalyses LazyCallGraphPrinterPass::run(Module &M,
Chandler Carruthb47f8012016-03-11 11:05:24 +00001770 ModuleAnalysisManager &AM) {
1771 LazyCallGraph &G = AM.getResult<LazyCallGraphAnalysis>(M);
Chandler Carruth11f50322015-01-14 00:27:45 +00001772
1773 OS << "Printing the call graph for module: " << M.getModuleIdentifier()
1774 << "\n\n";
1775
Chandler Carruthe5944d92016-02-17 00:18:16 +00001776 for (Function &F : M)
1777 printNode(OS, G.get(F));
Chandler Carruth11f50322015-01-14 00:27:45 +00001778
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001779 G.buildRefSCCs();
Chandler Carruthe5944d92016-02-17 00:18:16 +00001780 for (LazyCallGraph::RefSCC &C : G.postorder_ref_sccs())
1781 printRefSCC(OS, C);
Chandler Carruth18eadd922014-04-18 10:50:32 +00001782
Chandler Carruthbf71a342014-02-06 04:37:03 +00001783 return PreservedAnalyses::all();
Chandler Carruthbf71a342014-02-06 04:37:03 +00001784}
Sean Silva7cb30662016-06-18 09:17:32 +00001785
1786LazyCallGraphDOTPrinterPass::LazyCallGraphDOTPrinterPass(raw_ostream &OS)
1787 : OS(OS) {}
1788
1789static void printNodeDOT(raw_ostream &OS, LazyCallGraph::Node &N) {
1790 std::string Name = "\"" + DOT::EscapeString(N.getFunction().getName()) + "\"";
1791
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001792 for (LazyCallGraph::Edge &E : N.populate()) {
Sean Silva7cb30662016-06-18 09:17:32 +00001793 OS << " " << Name << " -> \""
1794 << DOT::EscapeString(E.getFunction().getName()) << "\"";
1795 if (!E.isCall()) // It is a ref edge.
1796 OS << " [style=dashed,label=\"ref\"]";
1797 OS << ";\n";
1798 }
1799
1800 OS << "\n";
1801}
1802
1803PreservedAnalyses LazyCallGraphDOTPrinterPass::run(Module &M,
1804 ModuleAnalysisManager &AM) {
1805 LazyCallGraph &G = AM.getResult<LazyCallGraphAnalysis>(M);
1806
1807 OS << "digraph \"" << DOT::EscapeString(M.getModuleIdentifier()) << "\" {\n";
1808
1809 for (Function &F : M)
1810 printNodeDOT(OS, G.get(F));
1811
1812 OS << "}\n";
1813
1814 return PreservedAnalyses::all();
1815}