blob: 55869a10ff3561fd7ded1a95cd4a700df4d7fa6e [file] [log] [blame]
Chandler Carruthbf71a342014-02-06 04:37:03 +00001//===- LazyCallGraph.cpp - Analysis of a Module's call graph --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "llvm/Analysis/LazyCallGraph.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"
Chandler Carruth219b89b2014-03-04 11:01:28 +000014#include "llvm/IR/CallSite.h"
Chandler Carruth7da14f12014-03-06 03:23:41 +000015#include "llvm/IR/InstVisitor.h"
Chandler Carruthbf71a342014-02-06 04:37:03 +000016#include "llvm/IR/Instructions.h"
17#include "llvm/IR/PassManager.h"
Chandler Carruth99b756d2014-04-21 05:04:24 +000018#include "llvm/Support/Debug.h"
Sean Silva7cb30662016-06-18 09:17:32 +000019#include "llvm/Support/GraphWriter.h"
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +000020#include <utility>
Chandler Carruthbf71a342014-02-06 04:37:03 +000021
22using namespace llvm;
23
Chandler Carruthf1221bd2014-04-22 02:48:03 +000024#define DEBUG_TYPE "lcg"
25
Chandler Carruthaaad9f82017-02-09 23:24:13 +000026void LazyCallGraph::EdgeSequence::insertEdgeInternal(Node &TargetN,
27 Edge::Kind EK) {
28 EdgeIndexMap.insert({&TargetN, Edges.size()});
29 Edges.emplace_back(TargetN, EK);
Chandler Carrutha4499e92016-02-02 03:57:13 +000030}
31
Chandler Carruthaaad9f82017-02-09 23:24:13 +000032void LazyCallGraph::EdgeSequence::setEdgeKind(Node &TargetN, Edge::Kind EK) {
33 Edges[EdgeIndexMap.find(&TargetN)->second].setKind(EK);
34}
35
36bool LazyCallGraph::EdgeSequence::removeEdgeInternal(Node &TargetN) {
37 auto IndexMapI = EdgeIndexMap.find(&TargetN);
38 if (IndexMapI == EdgeIndexMap.end())
39 return false;
40
41 Edges[IndexMapI->second] = Edge();
42 EdgeIndexMap.erase(IndexMapI);
43 return true;
44}
45
46static void addEdge(SmallVectorImpl<LazyCallGraph::Edge> &Edges,
47 DenseMap<LazyCallGraph::Node *, int> &EdgeIndexMap,
48 LazyCallGraph::Node &N, LazyCallGraph::Edge::Kind EK) {
49 if (!EdgeIndexMap.insert({&N, Edges.size()}).second)
50 return;
51
52 DEBUG(dbgs() << " Added callable function: " << N.getName() << "\n");
53 Edges.emplace_back(LazyCallGraph::Edge(N, EK));
54}
55
56LazyCallGraph::EdgeSequence &LazyCallGraph::Node::populateSlow() {
57 assert(!Edges && "Must not have already populated the edges for this node!");
58
59 DEBUG(dbgs() << " Adding functions called by '" << getName()
Chandler Carruth99b756d2014-04-21 05:04:24 +000060 << "' to the graph.\n");
61
Chandler Carruthaaad9f82017-02-09 23:24:13 +000062 Edges = EdgeSequence();
63
Chandler Carruthbf71a342014-02-06 04:37:03 +000064 SmallVector<Constant *, 16> Worklist;
Chandler Carrutha4499e92016-02-02 03:57:13 +000065 SmallPtrSet<Function *, 4> Callees;
Chandler Carruthbf71a342014-02-06 04:37:03 +000066 SmallPtrSet<Constant *, 16> Visited;
Chandler Carrutha4499e92016-02-02 03:57:13 +000067
68 // Find all the potential call graph edges in this function. We track both
69 // actual call edges and indirect references to functions. The direct calls
70 // are trivially added, but to accumulate the latter we walk the instructions
71 // and add every operand which is a constant to the worklist to process
72 // afterward.
Chandler Carruth86f0bdf2016-12-09 00:46:44 +000073 //
74 // Note that we consider *any* function with a definition to be a viable
75 // edge. Even if the function's definition is subject to replacement by
76 // some other module (say, a weak definition) there may still be
77 // optimizations which essentially speculate based on the definition and
78 // a way to check that the specific definition is in fact the one being
79 // used. For example, this could be done by moving the weak definition to
80 // a strong (internal) definition and making the weak definition be an
81 // alias. Then a test of the address of the weak function against the new
82 // strong definition's address would be an effective way to determine the
83 // safety of optimizing a direct call edge.
Chandler Carruthaaad9f82017-02-09 23:24:13 +000084 for (BasicBlock &BB : *F)
Chandler Carrutha4499e92016-02-02 03:57:13 +000085 for (Instruction &I : BB) {
86 if (auto CS = CallSite(&I))
87 if (Function *Callee = CS.getCalledFunction())
Chandler Carruth86f0bdf2016-12-09 00:46:44 +000088 if (!Callee->isDeclaration())
89 if (Callees.insert(Callee).second) {
90 Visited.insert(Callee);
Chandler Carruthaaad9f82017-02-09 23:24:13 +000091 addEdge(Edges->Edges, Edges->EdgeIndexMap, G->get(*Callee),
92 LazyCallGraph::Edge::Call);
Chandler Carruth86f0bdf2016-12-09 00:46:44 +000093 }
Chandler Carrutha4499e92016-02-02 03:57:13 +000094
Chandler Carruthb9e2f8c2014-03-09 12:20:34 +000095 for (Value *Op : I.operand_values())
Chandler Carruth1583e992014-03-03 10:42:58 +000096 if (Constant *C = dyn_cast<Constant>(Op))
David Blaikie70573dc2014-11-19 07:49:26 +000097 if (Visited.insert(C).second)
Chandler Carruthbf71a342014-02-06 04:37:03 +000098 Worklist.push_back(C);
Chandler Carrutha4499e92016-02-02 03:57:13 +000099 }
Chandler Carruthbf71a342014-02-06 04:37:03 +0000100
101 // We've collected all the constant (and thus potentially function or
102 // function containing) operands to all of the instructions in the function.
103 // Process them (recursively) collecting every function found.
Chandler Carruth88823462016-08-24 09:37:14 +0000104 visitReferences(Worklist, Visited, [&](Function &F) {
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000105 addEdge(Edges->Edges, Edges->EdgeIndexMap, G->get(F),
106 LazyCallGraph::Edge::Ref);
Chandler Carruth88823462016-08-24 09:37:14 +0000107 });
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000108
Chandler Carruthf59a8382017-07-15 08:08:19 +0000109 // Add implicit reference edges to any defined libcall functions (if we
110 // haven't found an explicit edge).
111 for (auto *F : G->LibFunctions)
112 if (!Visited.count(F))
113 addEdge(Edges->Edges, Edges->EdgeIndexMap, G->get(*F),
114 LazyCallGraph::Edge::Ref);
115
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000116 return *Edges;
Chandler Carruthbf71a342014-02-06 04:37:03 +0000117}
118
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000119void LazyCallGraph::Node::replaceFunction(Function &NewF) {
120 assert(F != &NewF && "Must not replace a function with itself!");
121 F = &NewF;
Chandler Carruthaa839b22014-04-27 01:59:50 +0000122}
123
Matthias Braun8c209aa2017-01-28 02:02:38 +0000124#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
125LLVM_DUMP_METHOD void LazyCallGraph::Node::dump() const {
Chandler Carruthdca83402016-06-27 23:26:08 +0000126 dbgs() << *this << '\n';
127}
Matthias Braun8c209aa2017-01-28 02:02:38 +0000128#endif
Chandler Carruthdca83402016-06-27 23:26:08 +0000129
Chandler Carruthf59a8382017-07-15 08:08:19 +0000130static bool isKnownLibFunction(Function &F, TargetLibraryInfo &TLI) {
131 LibFunc LF;
132
133 // Either this is a normal library function or a "vectorizable" function.
134 return TLI.getLibFunc(F, LF) || TLI.isFunctionVectorizable(F.getName());
135}
136
137LazyCallGraph::LazyCallGraph(Module &M, TargetLibraryInfo &TLI) {
Chandler Carruth99b756d2014-04-21 05:04:24 +0000138 DEBUG(dbgs() << "Building CG for module: " << M.getModuleIdentifier()
139 << "\n");
Chandler Carruthf59a8382017-07-15 08:08:19 +0000140 for (Function &F : M) {
141 if (F.isDeclaration())
142 continue;
143 // If this function is a known lib function to LLVM then we want to
144 // synthesize reference edges to it to model the fact that LLVM can turn
145 // arbitrary code into a library function call.
146 if (isKnownLibFunction(F, TLI))
Chandler Carruth06a86302017-07-19 04:12:25 +0000147 LibFunctions.insert(&F);
Chandler Carruthf59a8382017-07-15 08:08:19 +0000148
149 if (F.hasLocalLinkage())
150 continue;
151
152 // External linkage defined functions have edges to them from other
153 // modules.
154 DEBUG(dbgs() << " Adding '" << F.getName()
155 << "' to entry set of the graph.\n");
156 addEdge(EntryEdges.Edges, EntryEdges.EdgeIndexMap, get(F), Edge::Ref);
157 }
Chandler Carruthbf71a342014-02-06 04:37:03 +0000158
159 // Now add entry nodes for functions reachable via initializers to globals.
160 SmallVector<Constant *, 16> Worklist;
161 SmallPtrSet<Constant *, 16> Visited;
Chandler Carruthb9e2f8c2014-03-09 12:20:34 +0000162 for (GlobalVariable &GV : M.globals())
163 if (GV.hasInitializer())
David Blaikie70573dc2014-11-19 07:49:26 +0000164 if (Visited.insert(GV.getInitializer()).second)
Chandler Carruthb9e2f8c2014-03-09 12:20:34 +0000165 Worklist.push_back(GV.getInitializer());
Chandler Carruthbf71a342014-02-06 04:37:03 +0000166
Chandler Carruth99b756d2014-04-21 05:04:24 +0000167 DEBUG(dbgs() << " Adding functions referenced by global initializers to the "
168 "entry set.\n");
Chandler Carruth88823462016-08-24 09:37:14 +0000169 visitReferences(Worklist, Visited, [&](Function &F) {
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000170 addEdge(EntryEdges.Edges, EntryEdges.EdgeIndexMap, get(F),
171 LazyCallGraph::Edge::Ref);
Chandler Carruth88823462016-08-24 09:37:14 +0000172 });
Chandler Carruthbf71a342014-02-06 04:37:03 +0000173}
174
Chandler Carruthbf71a342014-02-06 04:37:03 +0000175LazyCallGraph::LazyCallGraph(LazyCallGraph &&G)
Chandler Carruth2174f442014-04-18 20:44:16 +0000176 : BPA(std::move(G.BPA)), NodeMap(std::move(G.NodeMap)),
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000177 EntryEdges(std::move(G.EntryEdges)), SCCBPA(std::move(G.SCCBPA)),
Chandler Carruthadbf14a2017-08-05 07:37:00 +0000178 SCCMap(std::move(G.SCCMap)),
Chandler Carruthf59a8382017-07-15 08:08:19 +0000179 LibFunctions(std::move(G.LibFunctions)) {
Chandler Carruthd8d865e2014-04-18 11:02:33 +0000180 updateGraphPtrs();
181}
182
183LazyCallGraph &LazyCallGraph::operator=(LazyCallGraph &&G) {
184 BPA = std::move(G.BPA);
Chandler Carruth2174f442014-04-18 20:44:16 +0000185 NodeMap = std::move(G.NodeMap);
Chandler Carrutha4499e92016-02-02 03:57:13 +0000186 EntryEdges = std::move(G.EntryEdges);
Chandler Carruthd8d865e2014-04-18 11:02:33 +0000187 SCCBPA = std::move(G.SCCBPA);
188 SCCMap = std::move(G.SCCMap);
Chandler Carruthf59a8382017-07-15 08:08:19 +0000189 LibFunctions = std::move(G.LibFunctions);
Chandler Carruthd8d865e2014-04-18 11:02:33 +0000190 updateGraphPtrs();
191 return *this;
192}
193
Matthias Braun8c209aa2017-01-28 02:02:38 +0000194#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
195LLVM_DUMP_METHOD void LazyCallGraph::SCC::dump() const {
Chandler Carruthdca83402016-06-27 23:26:08 +0000196 dbgs() << *this << '\n';
197}
Matthias Braun8c209aa2017-01-28 02:02:38 +0000198#endif
Chandler Carruthdca83402016-06-27 23:26:08 +0000199
Chandler Carruthe5944d92016-02-17 00:18:16 +0000200#ifndef NDEBUG
201void LazyCallGraph::SCC::verify() {
202 assert(OuterRefSCC && "Can't have a null RefSCC!");
203 assert(!Nodes.empty() && "Can't have an empty SCC!");
Chandler Carruth8f92d6d2014-04-26 01:03:46 +0000204
Chandler Carruthe5944d92016-02-17 00:18:16 +0000205 for (Node *N : Nodes) {
206 assert(N && "Can't have a null node!");
207 assert(OuterRefSCC->G->lookupSCC(*N) == this &&
208 "Node does not map to this SCC!");
209 assert(N->DFSNumber == -1 &&
210 "Must set DFS numbers to -1 when adding a node to an SCC!");
211 assert(N->LowLink == -1 &&
212 "Must set low link to -1 when adding a node to an SCC!");
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000213 for (Edge &E : **N)
Chandler Carruth39df40d2017-08-05 04:04:06 +0000214 assert(E.getNode().isPopulated() && "Can't have an unpopulated node!");
Chandler Carruthe5944d92016-02-17 00:18:16 +0000215 }
216}
217#endif
218
Chandler Carruthbae595b2016-11-22 19:23:31 +0000219bool LazyCallGraph::SCC::isParentOf(const SCC &C) const {
220 if (this == &C)
221 return false;
222
223 for (Node &N : *this)
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000224 for (Edge &E : N->calls())
225 if (OuterRefSCC->G->lookupSCC(E.getNode()) == &C)
226 return true;
Chandler Carruthbae595b2016-11-22 19:23:31 +0000227
228 // No edges found.
229 return false;
230}
231
232bool LazyCallGraph::SCC::isAncestorOf(const SCC &TargetC) const {
233 if (this == &TargetC)
234 return false;
235
236 LazyCallGraph &G = *OuterRefSCC->G;
237
238 // Start with this SCC.
239 SmallPtrSet<const SCC *, 16> Visited = {this};
240 SmallVector<const SCC *, 16> Worklist = {this};
241
242 // Walk down the graph until we run out of edges or find a path to TargetC.
243 do {
244 const SCC &C = *Worklist.pop_back_val();
245 for (Node &N : C)
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000246 for (Edge &E : N->calls()) {
247 SCC *CalleeC = G.lookupSCC(E.getNode());
Chandler Carruthbae595b2016-11-22 19:23:31 +0000248 if (!CalleeC)
249 continue;
250
251 // If the callee's SCC is the TargetC, we're done.
252 if (CalleeC == &TargetC)
253 return true;
254
255 // If this is the first time we've reached this SCC, put it on the
256 // worklist to recurse through.
257 if (Visited.insert(CalleeC).second)
258 Worklist.push_back(CalleeC);
259 }
260 } while (!Worklist.empty());
261
262 // No paths found.
263 return false;
264}
265
Chandler Carruthe5944d92016-02-17 00:18:16 +0000266LazyCallGraph::RefSCC::RefSCC(LazyCallGraph &G) : G(&G) {}
267
Matthias Braun8c209aa2017-01-28 02:02:38 +0000268#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
269LLVM_DUMP_METHOD void LazyCallGraph::RefSCC::dump() const {
Chandler Carruthdca83402016-06-27 23:26:08 +0000270 dbgs() << *this << '\n';
271}
Matthias Braun8c209aa2017-01-28 02:02:38 +0000272#endif
Chandler Carruthdca83402016-06-27 23:26:08 +0000273
Chandler Carruthe5944d92016-02-17 00:18:16 +0000274#ifndef NDEBUG
275void LazyCallGraph::RefSCC::verify() {
276 assert(G && "Can't have a null graph!");
277 assert(!SCCs.empty() && "Can't have an empty SCC!");
278
279 // Verify basic properties of the SCCs.
Chandler Carruth88823462016-08-24 09:37:14 +0000280 SmallPtrSet<SCC *, 4> SCCSet;
Chandler Carruthe5944d92016-02-17 00:18:16 +0000281 for (SCC *C : SCCs) {
282 assert(C && "Can't have a null SCC!");
283 C->verify();
284 assert(&C->getOuterRefSCC() == this &&
285 "SCC doesn't think it is inside this RefSCC!");
Chandler Carruth88823462016-08-24 09:37:14 +0000286 bool Inserted = SCCSet.insert(C).second;
287 assert(Inserted && "Found a duplicate SCC!");
Chandler Carruth23a6c3f2016-12-06 10:29:23 +0000288 auto IndexIt = SCCIndices.find(C);
289 assert(IndexIt != SCCIndices.end() &&
290 "Found an SCC that doesn't have an index!");
Chandler Carruthe5944d92016-02-17 00:18:16 +0000291 }
292
293 // Check that our indices map correctly.
294 for (auto &SCCIndexPair : SCCIndices) {
295 SCC *C = SCCIndexPair.first;
296 int i = SCCIndexPair.second;
297 assert(C && "Can't have a null SCC in the indices!");
Chandler Carruth88823462016-08-24 09:37:14 +0000298 assert(SCCSet.count(C) && "Found an index for an SCC not in the RefSCC!");
Chandler Carruthe5944d92016-02-17 00:18:16 +0000299 assert(SCCs[i] == C && "Index doesn't point to SCC!");
300 }
301
302 // Check that the SCCs are in fact in post-order.
303 for (int i = 0, Size = SCCs.size(); i < Size; ++i) {
304 SCC &SourceSCC = *SCCs[i];
305 for (Node &N : SourceSCC)
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000306 for (Edge &E : *N) {
Chandler Carruthe5944d92016-02-17 00:18:16 +0000307 if (!E.isCall())
308 continue;
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000309 SCC &TargetSCC = *G->lookupSCC(E.getNode());
Chandler Carruthe5944d92016-02-17 00:18:16 +0000310 if (&TargetSCC.getOuterRefSCC() == this) {
311 assert(SCCIndices.find(&TargetSCC)->second <= i &&
312 "Edge between SCCs violates post-order relationship.");
313 continue;
314 }
Chandler Carruthe5944d92016-02-17 00:18:16 +0000315 }
316 }
317}
318#endif
319
Chandler Carruth38bd6b52017-08-05 06:24:09 +0000320bool LazyCallGraph::RefSCC::isParentOf(const RefSCC &RC) const {
321 if (&RC == this)
322 return false;
323
324 // Search all edges to see if this is a parent.
325 for (SCC &C : *this)
326 for (Node &N : C)
327 for (Edge &E : *N)
328 if (G->lookupRefSCC(E.getNode()) == &RC)
329 return true;
330
331 return false;
332}
333
334bool LazyCallGraph::RefSCC::isAncestorOf(const RefSCC &RC) const {
335 if (&RC == this)
336 return false;
337
338 // For each descendant of this RefSCC, see if one of its children is the
339 // argument. If not, add that descendant to the worklist and continue
340 // searching.
341 SmallVector<const RefSCC *, 4> Worklist;
342 SmallPtrSet<const RefSCC *, 4> Visited;
343 Worklist.push_back(this);
344 Visited.insert(this);
Chandler Carruth4b096742014-05-01 12:12:42 +0000345 do {
Chandler Carruth38bd6b52017-08-05 06:24:09 +0000346 const RefSCC &DescendantRC = *Worklist.pop_back_val();
347 for (SCC &C : DescendantRC)
348 for (Node &N : C)
349 for (Edge &E : *N) {
350 auto *ChildRC = G->lookupRefSCC(E.getNode());
351 if (ChildRC == &RC)
352 return true;
353 if (!ChildRC || !Visited.insert(ChildRC).second)
354 continue;
355 Worklist.push_back(ChildRC);
356 }
357 } while (!Worklist.empty());
Chandler Carruth4b096742014-05-01 12:12:42 +0000358
359 return false;
360}
361
Chandler Carruth1f621f02016-09-04 08:34:24 +0000362/// Generic helper that updates a postorder sequence of SCCs for a potentially
363/// cycle-introducing edge insertion.
364///
365/// A postorder sequence of SCCs of a directed graph has one fundamental
366/// property: all deges in the DAG of SCCs point "up" the sequence. That is,
367/// all edges in the SCC DAG point to prior SCCs in the sequence.
368///
369/// This routine both updates a postorder sequence and uses that sequence to
370/// compute the set of SCCs connected into a cycle. It should only be called to
371/// insert a "downward" edge which will require changing the sequence to
372/// restore it to a postorder.
373///
374/// When inserting an edge from an earlier SCC to a later SCC in some postorder
375/// sequence, all of the SCCs which may be impacted are in the closed range of
376/// those two within the postorder sequence. The algorithm used here to restore
377/// the state is as follows:
378///
379/// 1) Starting from the source SCC, construct a set of SCCs which reach the
380/// source SCC consisting of just the source SCC. Then scan toward the
381/// target SCC in postorder and for each SCC, if it has an edge to an SCC
382/// in the set, add it to the set. Otherwise, the source SCC is not
383/// a successor, move it in the postorder sequence to immediately before
384/// the source SCC, shifting the source SCC and all SCCs in the set one
385/// position toward the target SCC. Stop scanning after processing the
386/// target SCC.
387/// 2) If the source SCC is now past the target SCC in the postorder sequence,
388/// and thus the new edge will flow toward the start, we are done.
389/// 3) Otherwise, starting from the target SCC, walk all edges which reach an
390/// SCC between the source and the target, and add them to the set of
391/// connected SCCs, then recurse through them. Once a complete set of the
392/// SCCs the target connects to is known, hoist the remaining SCCs between
393/// the source and the target to be above the target. Note that there is no
394/// need to process the source SCC, it is already known to connect.
395/// 4) At this point, all of the SCCs in the closed range between the source
396/// SCC and the target SCC in the postorder sequence are connected,
397/// including the target SCC and the source SCC. Inserting the edge from
398/// the source SCC to the target SCC will form a cycle out of precisely
399/// these SCCs. Thus we can merge all of the SCCs in this closed range into
400/// a single SCC.
401///
402/// This process has various important properties:
403/// - Only mutates the SCCs when adding the edge actually changes the SCC
404/// structure.
405/// - Never mutates SCCs which are unaffected by the change.
406/// - Updates the postorder sequence to correctly satisfy the postorder
407/// constraint after the edge is inserted.
408/// - Only reorders SCCs in the closed postorder sequence from the source to
409/// the target, so easy to bound how much has changed even in the ordering.
410/// - Big-O is the number of edges in the closed postorder range of SCCs from
411/// source to target.
412///
413/// This helper routine, in addition to updating the postorder sequence itself
414/// will also update a map from SCCs to indices within that sequecne.
415///
416/// The sequence and the map must operate on pointers to the SCC type.
417///
418/// Two callbacks must be provided. The first computes the subset of SCCs in
419/// the postorder closed range from the source to the target which connect to
420/// the source SCC via some (transitive) set of edges. The second computes the
421/// subset of the same range which the target SCC connects to via some
422/// (transitive) set of edges. Both callbacks should populate the set argument
423/// provided.
424template <typename SCCT, typename PostorderSequenceT, typename SCCIndexMapT,
425 typename ComputeSourceConnectedSetCallableT,
426 typename ComputeTargetConnectedSetCallableT>
427static iterator_range<typename PostorderSequenceT::iterator>
428updatePostorderSequenceForEdgeInsertion(
429 SCCT &SourceSCC, SCCT &TargetSCC, PostorderSequenceT &SCCs,
430 SCCIndexMapT &SCCIndices,
431 ComputeSourceConnectedSetCallableT ComputeSourceConnectedSet,
432 ComputeTargetConnectedSetCallableT ComputeTargetConnectedSet) {
433 int SourceIdx = SCCIndices[&SourceSCC];
434 int TargetIdx = SCCIndices[&TargetSCC];
435 assert(SourceIdx < TargetIdx && "Cannot have equal indices here!");
436
437 SmallPtrSet<SCCT *, 4> ConnectedSet;
438
439 // Compute the SCCs which (transitively) reach the source.
440 ComputeSourceConnectedSet(ConnectedSet);
441
442 // Partition the SCCs in this part of the port-order sequence so only SCCs
443 // connecting to the source remain between it and the target. This is
444 // a benign partition as it preserves postorder.
445 auto SourceI = std::stable_partition(
446 SCCs.begin() + SourceIdx, SCCs.begin() + TargetIdx + 1,
447 [&ConnectedSet](SCCT *C) { return !ConnectedSet.count(C); });
448 for (int i = SourceIdx, e = TargetIdx + 1; i < e; ++i)
449 SCCIndices.find(SCCs[i])->second = i;
450
451 // If the target doesn't connect to the source, then we've corrected the
452 // post-order and there are no cycles formed.
453 if (!ConnectedSet.count(&TargetSCC)) {
454 assert(SourceI > (SCCs.begin() + SourceIdx) &&
455 "Must have moved the source to fix the post-order.");
456 assert(*std::prev(SourceI) == &TargetSCC &&
457 "Last SCC to move should have bene the target.");
458
459 // Return an empty range at the target SCC indicating there is nothing to
460 // merge.
461 return make_range(std::prev(SourceI), std::prev(SourceI));
462 }
463
464 assert(SCCs[TargetIdx] == &TargetSCC &&
465 "Should not have moved target if connected!");
466 SourceIdx = SourceI - SCCs.begin();
467 assert(SCCs[SourceIdx] == &SourceSCC &&
468 "Bad updated index computation for the source SCC!");
469
470
471 // See whether there are any remaining intervening SCCs between the source
472 // and target. If so we need to make sure they all are reachable form the
473 // target.
474 if (SourceIdx + 1 < TargetIdx) {
475 ConnectedSet.clear();
476 ComputeTargetConnectedSet(ConnectedSet);
477
478 // Partition SCCs so that only SCCs reached from the target remain between
479 // the source and the target. This preserves postorder.
480 auto TargetI = std::stable_partition(
481 SCCs.begin() + SourceIdx + 1, SCCs.begin() + TargetIdx + 1,
482 [&ConnectedSet](SCCT *C) { return ConnectedSet.count(C); });
483 for (int i = SourceIdx + 1, e = TargetIdx + 1; i < e; ++i)
484 SCCIndices.find(SCCs[i])->second = i;
485 TargetIdx = std::prev(TargetI) - SCCs.begin();
486 assert(SCCs[TargetIdx] == &TargetSCC &&
487 "Should always end with the target!");
488 }
489
490 // At this point, we know that connecting source to target forms a cycle
491 // because target connects back to source, and we know that all of the SCCs
492 // between the source and target in the postorder sequence participate in that
493 // cycle.
494 return make_range(SCCs.begin() + SourceIdx, SCCs.begin() + TargetIdx);
495}
496
Chandler Carruthc213c672017-07-09 13:45:11 +0000497bool
498LazyCallGraph::RefSCC::switchInternalEdgeToCall(
499 Node &SourceN, Node &TargetN,
500 function_ref<void(ArrayRef<SCC *> MergeSCCs)> MergeCB) {
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000501 assert(!(*SourceN)[TargetN].isCall() && "Must start with a ref edge!");
Chandler Carruthe5944d92016-02-17 00:18:16 +0000502 SmallVector<SCC *, 1> DeletedSCCs;
Chandler Carruth5217c942014-04-30 10:48:36 +0000503
Chandler Carruth11b3f602016-09-04 08:34:31 +0000504#ifndef NDEBUG
505 // In a debug build, verify the RefSCC is valid to start with and when this
506 // routine finishes.
507 verify();
508 auto VerifyOnExit = make_scope_exit([&]() { verify(); });
509#endif
510
Chandler Carruthe5944d92016-02-17 00:18:16 +0000511 SCC &SourceSCC = *G->lookupSCC(SourceN);
512 SCC &TargetSCC = *G->lookupSCC(TargetN);
513
514 // If the two nodes are already part of the same SCC, we're also done as
515 // we've just added more connectivity.
516 if (&SourceSCC == &TargetSCC) {
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000517 SourceN->setEdgeKind(TargetN, Edge::Call);
Chandler Carruthc213c672017-07-09 13:45:11 +0000518 return false; // No new cycle.
Chandler Carruthe5944d92016-02-17 00:18:16 +0000519 }
520
521 // At this point we leverage the postorder list of SCCs to detect when the
522 // insertion of an edge changes the SCC structure in any way.
523 //
524 // First and foremost, we can eliminate the need for any changes when the
525 // edge is toward the beginning of the postorder sequence because all edges
526 // flow in that direction already. Thus adding a new one cannot form a cycle.
527 int SourceIdx = SCCIndices[&SourceSCC];
528 int TargetIdx = SCCIndices[&TargetSCC];
529 if (TargetIdx < SourceIdx) {
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000530 SourceN->setEdgeKind(TargetN, Edge::Call);
Chandler Carruthc213c672017-07-09 13:45:11 +0000531 return false; // No new cycle.
Chandler Carruthe5944d92016-02-17 00:18:16 +0000532 }
533
Chandler Carruthe5944d92016-02-17 00:18:16 +0000534 // Compute the SCCs which (transitively) reach the source.
Chandler Carruth1f621f02016-09-04 08:34:24 +0000535 auto ComputeSourceConnectedSet = [&](SmallPtrSetImpl<SCC *> &ConnectedSet) {
Chandler Carruthe5944d92016-02-17 00:18:16 +0000536#ifndef NDEBUG
Chandler Carruth1f621f02016-09-04 08:34:24 +0000537 // Check that the RefSCC is still valid before computing this as the
538 // results will be nonsensical of we've broken its invariants.
Chandler Carruthe5944d92016-02-17 00:18:16 +0000539 verify();
540#endif
Chandler Carruth1f621f02016-09-04 08:34:24 +0000541 ConnectedSet.insert(&SourceSCC);
542 auto IsConnected = [&](SCC &C) {
543 for (Node &N : C)
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000544 for (Edge &E : N->calls())
545 if (ConnectedSet.count(G->lookupSCC(E.getNode())))
Chandler Carruth1f621f02016-09-04 08:34:24 +0000546 return true;
Chandler Carruthe5944d92016-02-17 00:18:16 +0000547
Chandler Carruth1f621f02016-09-04 08:34:24 +0000548 return false;
549 };
Chandler Carruthe5944d92016-02-17 00:18:16 +0000550
Chandler Carruth1f621f02016-09-04 08:34:24 +0000551 for (SCC *C :
552 make_range(SCCs.begin() + SourceIdx + 1, SCCs.begin() + TargetIdx + 1))
553 if (IsConnected(*C))
554 ConnectedSet.insert(C);
555 };
556
557 // Use a normal worklist to find which SCCs the target connects to. We still
558 // bound the search based on the range in the postorder list we care about,
559 // but because this is forward connectivity we just "recurse" through the
560 // edges.
561 auto ComputeTargetConnectedSet = [&](SmallPtrSetImpl<SCC *> &ConnectedSet) {
Chandler Carruthe5944d92016-02-17 00:18:16 +0000562#ifndef NDEBUG
Chandler Carruth1f621f02016-09-04 08:34:24 +0000563 // Check that the RefSCC is still valid before computing this as the
564 // results will be nonsensical of we've broken its invariants.
565 verify();
Chandler Carruthe5944d92016-02-17 00:18:16 +0000566#endif
Chandler Carruthe5944d92016-02-17 00:18:16 +0000567 ConnectedSet.insert(&TargetSCC);
568 SmallVector<SCC *, 4> Worklist;
569 Worklist.push_back(&TargetSCC);
570 do {
571 SCC &C = *Worklist.pop_back_val();
572 for (Node &N : C)
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000573 for (Edge &E : *N) {
Chandler Carruthe5944d92016-02-17 00:18:16 +0000574 if (!E.isCall())
575 continue;
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000576 SCC &EdgeC = *G->lookupSCC(E.getNode());
Chandler Carruthe5944d92016-02-17 00:18:16 +0000577 if (&EdgeC.getOuterRefSCC() != this)
578 // Not in this RefSCC...
579 continue;
580 if (SCCIndices.find(&EdgeC)->second <= SourceIdx)
581 // Not in the postorder sequence between source and target.
582 continue;
583
584 if (ConnectedSet.insert(&EdgeC).second)
585 Worklist.push_back(&EdgeC);
586 }
587 } while (!Worklist.empty());
Chandler Carruth1f621f02016-09-04 08:34:24 +0000588 };
Chandler Carruthe5944d92016-02-17 00:18:16 +0000589
Chandler Carruth1f621f02016-09-04 08:34:24 +0000590 // Use a generic helper to update the postorder sequence of SCCs and return
591 // a range of any SCCs connected into a cycle by inserting this edge. This
592 // routine will also take care of updating the indices into the postorder
593 // sequence.
594 auto MergeRange = updatePostorderSequenceForEdgeInsertion(
595 SourceSCC, TargetSCC, SCCs, SCCIndices, ComputeSourceConnectedSet,
596 ComputeTargetConnectedSet);
Chandler Carruthe5944d92016-02-17 00:18:16 +0000597
Chandler Carruthc213c672017-07-09 13:45:11 +0000598 // Run the user's callback on the merged SCCs before we actually merge them.
599 if (MergeCB)
600 MergeCB(makeArrayRef(MergeRange.begin(), MergeRange.end()));
601
Chandler Carruth1f621f02016-09-04 08:34:24 +0000602 // If the merge range is empty, then adding the edge didn't actually form any
603 // new cycles. We're done.
604 if (MergeRange.begin() == MergeRange.end()) {
605 // Now that the SCC structure is finalized, flip the kind to call.
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000606 SourceN->setEdgeKind(TargetN, Edge::Call);
Chandler Carruthc213c672017-07-09 13:45:11 +0000607 return false; // No new cycle.
Chandler Carruthe5944d92016-02-17 00:18:16 +0000608 }
609
Chandler Carruth1f621f02016-09-04 08:34:24 +0000610#ifndef NDEBUG
611 // Before merging, check that the RefSCC remains valid after all the
612 // postorder updates.
613 verify();
614#endif
615
616 // Otherwise we need to merge all of the SCCs in the cycle into a single
Chandler Carruthe5944d92016-02-17 00:18:16 +0000617 // result SCC.
618 //
619 // NB: We merge into the target because all of these functions were already
620 // reachable from the target, meaning any SCC-wide properties deduced about it
621 // other than the set of functions within it will not have changed.
Chandler Carruthe5944d92016-02-17 00:18:16 +0000622 for (SCC *C : MergeRange) {
623 assert(C != &TargetSCC &&
624 "We merge *into* the target and shouldn't process it here!");
625 SCCIndices.erase(C);
626 TargetSCC.Nodes.append(C->Nodes.begin(), C->Nodes.end());
627 for (Node *N : C->Nodes)
628 G->SCCMap[N] = &TargetSCC;
629 C->clear();
630 DeletedSCCs.push_back(C);
631 }
632
633 // Erase the merged SCCs from the list and update the indices of the
634 // remaining SCCs.
635 int IndexOffset = MergeRange.end() - MergeRange.begin();
636 auto EraseEnd = SCCs.erase(MergeRange.begin(), MergeRange.end());
637 for (SCC *C : make_range(EraseEnd, SCCs.end()))
638 SCCIndices[C] -= IndexOffset;
639
640 // Now that the SCC structure is finalized, flip the kind to call.
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000641 SourceN->setEdgeKind(TargetN, Edge::Call);
Chandler Carruthe5944d92016-02-17 00:18:16 +0000642
Chandler Carruthc213c672017-07-09 13:45:11 +0000643 // And we're done, but we did form a new cycle.
644 return true;
Chandler Carruth5217c942014-04-30 10:48:36 +0000645}
646
Chandler Carruth443e57e2016-12-28 10:34:50 +0000647void LazyCallGraph::RefSCC::switchTrivialInternalEdgeToRef(Node &SourceN,
648 Node &TargetN) {
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000649 assert((*SourceN)[TargetN].isCall() && "Must start with a call edge!");
Chandler Carruth443e57e2016-12-28 10:34:50 +0000650
651#ifndef NDEBUG
652 // In a debug build, verify the RefSCC is valid to start with and when this
653 // routine finishes.
654 verify();
655 auto VerifyOnExit = make_scope_exit([&]() { verify(); });
656#endif
657
658 assert(G->lookupRefSCC(SourceN) == this &&
659 "Source must be in this RefSCC.");
660 assert(G->lookupRefSCC(TargetN) == this &&
661 "Target must be in this RefSCC.");
662 assert(G->lookupSCC(SourceN) != G->lookupSCC(TargetN) &&
663 "Source and Target must be in separate SCCs for this to be trivial!");
664
665 // Set the edge kind.
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000666 SourceN->setEdgeKind(TargetN, Edge::Ref);
Chandler Carruth443e57e2016-12-28 10:34:50 +0000667}
668
Chandler Carruth88823462016-08-24 09:37:14 +0000669iterator_range<LazyCallGraph::RefSCC::iterator>
670LazyCallGraph::RefSCC::switchInternalEdgeToRef(Node &SourceN, Node &TargetN) {
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000671 assert((*SourceN)[TargetN].isCall() && "Must start with a call edge!");
Chandler Carruthe5944d92016-02-17 00:18:16 +0000672
Chandler Carruth11b3f602016-09-04 08:34:31 +0000673#ifndef NDEBUG
674 // In a debug build, verify the RefSCC is valid to start with and when this
675 // routine finishes.
676 verify();
677 auto VerifyOnExit = make_scope_exit([&]() { verify(); });
678#endif
679
Chandler Carruth443e57e2016-12-28 10:34:50 +0000680 assert(G->lookupRefSCC(SourceN) == this &&
Chandler Carruthe5944d92016-02-17 00:18:16 +0000681 "Source must be in this RefSCC.");
Chandler Carruth443e57e2016-12-28 10:34:50 +0000682 assert(G->lookupRefSCC(TargetN) == this &&
Chandler Carruthe5944d92016-02-17 00:18:16 +0000683 "Target must be in this RefSCC.");
684
Chandler Carruth443e57e2016-12-28 10:34:50 +0000685 SCC &TargetSCC = *G->lookupSCC(TargetN);
686 assert(G->lookupSCC(SourceN) == &TargetSCC && "Source and Target must be in "
687 "the same SCC to require the "
688 "full CG update.");
689
Chandler Carruthe5944d92016-02-17 00:18:16 +0000690 // Set the edge kind.
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000691 SourceN->setEdgeKind(TargetN, Edge::Ref);
Chandler Carruthe5944d92016-02-17 00:18:16 +0000692
Chandler Carruthe5944d92016-02-17 00:18:16 +0000693 // Otherwise we are removing a call edge from a single SCC. This may break
694 // the cycle. In order to compute the new set of SCCs, we need to do a small
695 // DFS over the nodes within the SCC to form any sub-cycles that remain as
696 // distinct SCCs and compute a postorder over the resulting SCCs.
697 //
698 // However, we specially handle the target node. The target node is known to
699 // reach all other nodes in the original SCC by definition. This means that
700 // we want the old SCC to be replaced with an SCC contaning that node as it
701 // will be the root of whatever SCC DAG results from the DFS. Assumptions
702 // about an SCC such as the set of functions called will continue to hold,
703 // etc.
704
705 SCC &OldSCC = TargetSCC;
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000706 SmallVector<std::pair<Node *, EdgeSequence::call_iterator>, 16> DFSStack;
Chandler Carruthe5944d92016-02-17 00:18:16 +0000707 SmallVector<Node *, 16> PendingSCCStack;
708 SmallVector<SCC *, 4> NewSCCs;
709
710 // Prepare the nodes for a fresh DFS.
711 SmallVector<Node *, 16> Worklist;
712 Worklist.swap(OldSCC.Nodes);
713 for (Node *N : Worklist) {
714 N->DFSNumber = N->LowLink = 0;
715 G->SCCMap.erase(N);
716 }
717
718 // Force the target node to be in the old SCC. This also enables us to take
719 // a very significant short-cut in the standard Tarjan walk to re-form SCCs
720 // below: whenever we build an edge that reaches the target node, we know
721 // that the target node eventually connects back to all other nodes in our
722 // walk. As a consequence, we can detect and handle participants in that
723 // cycle without walking all the edges that form this connection, and instead
724 // by relying on the fundamental guarantee coming into this operation (all
725 // nodes are reachable from the target due to previously forming an SCC).
726 TargetN.DFSNumber = TargetN.LowLink = -1;
727 OldSCC.Nodes.push_back(&TargetN);
728 G->SCCMap[&TargetN] = &OldSCC;
729
730 // Scan down the stack and DFS across the call edges.
731 for (Node *RootN : Worklist) {
732 assert(DFSStack.empty() &&
733 "Cannot begin a new root with a non-empty DFS stack!");
734 assert(PendingSCCStack.empty() &&
735 "Cannot begin a new root with pending nodes for an SCC!");
736
737 // Skip any nodes we've already reached in the DFS.
738 if (RootN->DFSNumber != 0) {
739 assert(RootN->DFSNumber == -1 &&
740 "Shouldn't have any mid-DFS root nodes!");
741 continue;
742 }
743
744 RootN->DFSNumber = RootN->LowLink = 1;
745 int NextDFSNumber = 2;
746
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000747 DFSStack.push_back({RootN, (*RootN)->call_begin()});
Chandler Carruthe5944d92016-02-17 00:18:16 +0000748 do {
749 Node *N;
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000750 EdgeSequence::call_iterator I;
Chandler Carruthe5944d92016-02-17 00:18:16 +0000751 std::tie(N, I) = DFSStack.pop_back_val();
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000752 auto E = (*N)->call_end();
Chandler Carruthe5944d92016-02-17 00:18:16 +0000753 while (I != E) {
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000754 Node &ChildN = I->getNode();
Chandler Carruthe5944d92016-02-17 00:18:16 +0000755 if (ChildN.DFSNumber == 0) {
756 // We haven't yet visited this child, so descend, pushing the current
757 // node onto the stack.
758 DFSStack.push_back({N, I});
759
760 assert(!G->SCCMap.count(&ChildN) &&
761 "Found a node with 0 DFS number but already in an SCC!");
762 ChildN.DFSNumber = ChildN.LowLink = NextDFSNumber++;
763 N = &ChildN;
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000764 I = (*N)->call_begin();
765 E = (*N)->call_end();
Chandler Carruthe5944d92016-02-17 00:18:16 +0000766 continue;
767 }
768
769 // Check for the child already being part of some component.
770 if (ChildN.DFSNumber == -1) {
771 if (G->lookupSCC(ChildN) == &OldSCC) {
772 // If the child is part of the old SCC, we know that it can reach
773 // every other node, so we have formed a cycle. Pull the entire DFS
774 // and pending stacks into it. See the comment above about setting
775 // up the old SCC for why we do this.
776 int OldSize = OldSCC.size();
777 OldSCC.Nodes.push_back(N);
778 OldSCC.Nodes.append(PendingSCCStack.begin(), PendingSCCStack.end());
779 PendingSCCStack.clear();
780 while (!DFSStack.empty())
781 OldSCC.Nodes.push_back(DFSStack.pop_back_val().first);
782 for (Node &N : make_range(OldSCC.begin() + OldSize, OldSCC.end())) {
783 N.DFSNumber = N.LowLink = -1;
784 G->SCCMap[&N] = &OldSCC;
785 }
786 N = nullptr;
787 break;
788 }
789
790 // If the child has already been added to some child component, it
791 // couldn't impact the low-link of this parent because it isn't
792 // connected, and thus its low-link isn't relevant so skip it.
793 ++I;
794 continue;
795 }
796
797 // Track the lowest linked child as the lowest link for this node.
798 assert(ChildN.LowLink > 0 && "Must have a positive low-link number!");
799 if (ChildN.LowLink < N->LowLink)
800 N->LowLink = ChildN.LowLink;
801
802 // Move to the next edge.
803 ++I;
804 }
805 if (!N)
806 // Cleared the DFS early, start another round.
807 break;
808
809 // We've finished processing N and its descendents, put it on our pending
810 // SCC stack to eventually get merged into an SCC of nodes.
811 PendingSCCStack.push_back(N);
812
813 // If this node is linked to some lower entry, continue walking up the
814 // stack.
815 if (N->LowLink != N->DFSNumber)
816 continue;
817
818 // Otherwise, we've completed an SCC. Append it to our post order list of
819 // SCCs.
820 int RootDFSNumber = N->DFSNumber;
821 // Find the range of the node stack by walking down until we pass the
822 // root DFS number.
823 auto SCCNodes = make_range(
824 PendingSCCStack.rbegin(),
David Majnemer42531262016-08-12 03:55:06 +0000825 find_if(reverse(PendingSCCStack), [RootDFSNumber](const Node *N) {
826 return N->DFSNumber < RootDFSNumber;
827 }));
Chandler Carruthe5944d92016-02-17 00:18:16 +0000828
829 // Form a new SCC out of these nodes and then clear them off our pending
830 // stack.
831 NewSCCs.push_back(G->createSCC(*this, SCCNodes));
832 for (Node &N : *NewSCCs.back()) {
833 N.DFSNumber = N.LowLink = -1;
834 G->SCCMap[&N] = NewSCCs.back();
835 }
836 PendingSCCStack.erase(SCCNodes.end().base(), PendingSCCStack.end());
837 } while (!DFSStack.empty());
838 }
839
840 // Insert the remaining SCCs before the old one. The old SCC can reach all
841 // other SCCs we form because it contains the target node of the removed edge
842 // of the old SCC. This means that we will have edges into all of the new
843 // SCCs, which means the old one must come last for postorder.
844 int OldIdx = SCCIndices[&OldSCC];
845 SCCs.insert(SCCs.begin() + OldIdx, NewSCCs.begin(), NewSCCs.end());
846
847 // Update the mapping from SCC* to index to use the new SCC*s, and remove the
848 // old SCC from the mapping.
849 for (int Idx = OldIdx, Size = SCCs.size(); Idx < Size; ++Idx)
850 SCCIndices[SCCs[Idx]] = Idx;
851
Chandler Carruth88823462016-08-24 09:37:14 +0000852 return make_range(SCCs.begin() + OldIdx,
853 SCCs.begin() + OldIdx + NewSCCs.size());
Chandler Carruthe5944d92016-02-17 00:18:16 +0000854}
855
856void LazyCallGraph::RefSCC::switchOutgoingEdgeToCall(Node &SourceN,
857 Node &TargetN) {
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000858 assert(!(*SourceN)[TargetN].isCall() && "Must start with a ref edge!");
Chandler Carruthe5944d92016-02-17 00:18:16 +0000859
860 assert(G->lookupRefSCC(SourceN) == this && "Source must be in this RefSCC.");
861 assert(G->lookupRefSCC(TargetN) != this &&
862 "Target must not be in this RefSCC.");
Francis Visoiu Mistrih262ad162017-02-28 18:34:55 +0000863#ifdef EXPENSIVE_CHECKS
Chandler Carruthe5944d92016-02-17 00:18:16 +0000864 assert(G->lookupRefSCC(TargetN)->isDescendantOf(*this) &&
865 "Target must be a descendant of the Source.");
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +0000866#endif
Chandler Carruthe5944d92016-02-17 00:18:16 +0000867
868 // Edges between RefSCCs are the same regardless of call or ref, so we can
869 // just flip the edge here.
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000870 SourceN->setEdgeKind(TargetN, Edge::Call);
Chandler Carruthe5944d92016-02-17 00:18:16 +0000871
872#ifndef NDEBUG
873 // Check that the RefSCC is still valid.
874 verify();
875#endif
876}
877
878void LazyCallGraph::RefSCC::switchOutgoingEdgeToRef(Node &SourceN,
879 Node &TargetN) {
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000880 assert((*SourceN)[TargetN].isCall() && "Must start with a call edge!");
Chandler Carruthe5944d92016-02-17 00:18:16 +0000881
882 assert(G->lookupRefSCC(SourceN) == this && "Source must be in this RefSCC.");
883 assert(G->lookupRefSCC(TargetN) != this &&
884 "Target must not be in this RefSCC.");
Francis Visoiu Mistrih262ad162017-02-28 18:34:55 +0000885#ifdef EXPENSIVE_CHECKS
Chandler Carruthe5944d92016-02-17 00:18:16 +0000886 assert(G->lookupRefSCC(TargetN)->isDescendantOf(*this) &&
887 "Target must be a descendant of the Source.");
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +0000888#endif
Chandler Carruthe5944d92016-02-17 00:18:16 +0000889
890 // Edges between RefSCCs are the same regardless of call or ref, so we can
891 // just flip the edge here.
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000892 SourceN->setEdgeKind(TargetN, Edge::Ref);
Chandler Carruthe5944d92016-02-17 00:18:16 +0000893
894#ifndef NDEBUG
895 // Check that the RefSCC is still valid.
896 verify();
897#endif
898}
899
900void LazyCallGraph::RefSCC::insertInternalRefEdge(Node &SourceN,
901 Node &TargetN) {
902 assert(G->lookupRefSCC(SourceN) == this && "Source must be in this RefSCC.");
903 assert(G->lookupRefSCC(TargetN) == this && "Target must be in this RefSCC.");
904
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000905 SourceN->insertEdgeInternal(TargetN, Edge::Ref);
Chandler Carruthe5944d92016-02-17 00:18:16 +0000906
907#ifndef NDEBUG
908 // Check that the RefSCC is still valid.
909 verify();
910#endif
911}
912
913void LazyCallGraph::RefSCC::insertOutgoingEdge(Node &SourceN, Node &TargetN,
914 Edge::Kind EK) {
Chandler Carruth7cc4ed82014-05-01 12:18:20 +0000915 // First insert it into the caller.
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000916 SourceN->insertEdgeInternal(TargetN, EK);
Chandler Carruth7cc4ed82014-05-01 12:18:20 +0000917
Chandler Carruthe5944d92016-02-17 00:18:16 +0000918 assert(G->lookupRefSCC(SourceN) == this && "Source must be in this RefSCC.");
Chandler Carruth7cc4ed82014-05-01 12:18:20 +0000919
Chandler Carruthe5944d92016-02-17 00:18:16 +0000920 RefSCC &TargetC = *G->lookupRefSCC(TargetN);
921 assert(&TargetC != this && "Target must not be in this RefSCC.");
Francis Visoiu Mistrih262ad162017-02-28 18:34:55 +0000922#ifdef EXPENSIVE_CHECKS
Chandler Carruthe5944d92016-02-17 00:18:16 +0000923 assert(TargetC.isDescendantOf(*this) &&
924 "Target must be a descendant of the Source.");
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +0000925#endif
Chandler Carruth7cc4ed82014-05-01 12:18:20 +0000926
Chandler Carruthe5944d92016-02-17 00:18:16 +0000927#ifndef NDEBUG
928 // Check that the RefSCC is still valid.
929 verify();
930#endif
Chandler Carruth7cc4ed82014-05-01 12:18:20 +0000931}
932
Chandler Carruthe5944d92016-02-17 00:18:16 +0000933SmallVector<LazyCallGraph::RefSCC *, 1>
934LazyCallGraph::RefSCC::insertIncomingRefEdge(Node &SourceN, Node &TargetN) {
Chandler Carruth49d728a2016-09-16 10:20:17 +0000935 assert(G->lookupRefSCC(TargetN) == this && "Target must be in this RefSCC.");
936 RefSCC &SourceC = *G->lookupRefSCC(SourceN);
937 assert(&SourceC != this && "Source must not be in this RefSCC.");
Francis Visoiu Mistrih262ad162017-02-28 18:34:55 +0000938#ifdef EXPENSIVE_CHECKS
Chandler Carruth49d728a2016-09-16 10:20:17 +0000939 assert(SourceC.isDescendantOf(*this) &&
940 "Source must be a descendant of the Target.");
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +0000941#endif
Chandler Carruth49d728a2016-09-16 10:20:17 +0000942
943 SmallVector<RefSCC *, 1> DeletedRefSCCs;
Chandler Carruth312dddf2014-05-04 09:38:32 +0000944
Chandler Carruth11b3f602016-09-04 08:34:31 +0000945#ifndef NDEBUG
946 // In a debug build, verify the RefSCC is valid to start with and when this
947 // routine finishes.
948 verify();
949 auto VerifyOnExit = make_scope_exit([&]() { verify(); });
950#endif
951
Chandler Carruth49d728a2016-09-16 10:20:17 +0000952 int SourceIdx = G->RefSCCIndices[&SourceC];
953 int TargetIdx = G->RefSCCIndices[this];
954 assert(SourceIdx < TargetIdx &&
955 "Postorder list doesn't see edge as incoming!");
Chandler Carruth312dddf2014-05-04 09:38:32 +0000956
Chandler Carruth49d728a2016-09-16 10:20:17 +0000957 // Compute the RefSCCs which (transitively) reach the source. We do this by
958 // working backwards from the source using the parent set in each RefSCC,
959 // skipping any RefSCCs that don't fall in the postorder range. This has the
960 // advantage of walking the sparser parent edge (in high fan-out graphs) but
961 // more importantly this removes examining all forward edges in all RefSCCs
962 // within the postorder range which aren't in fact connected. Only connected
963 // RefSCCs (and their edges) are visited here.
964 auto ComputeSourceConnectedSet = [&](SmallPtrSetImpl<RefSCC *> &Set) {
965 Set.insert(&SourceC);
Chandler Carruth13ffd112017-08-05 03:37:37 +0000966 auto IsConnected = [&](RefSCC &RC) {
967 for (SCC &C : RC)
968 for (Node &N : C)
969 for (Edge &E : *N)
970 if (Set.count(G->lookupRefSCC(E.getNode())))
971 return true;
972
973 return false;
974 };
975
976 for (RefSCC *C : make_range(G->PostOrderRefSCCs.begin() + SourceIdx + 1,
977 G->PostOrderRefSCCs.begin() + TargetIdx + 1))
978 if (IsConnected(*C))
979 Set.insert(C);
Chandler Carruth49d728a2016-09-16 10:20:17 +0000980 };
Chandler Carruth312dddf2014-05-04 09:38:32 +0000981
Chandler Carruth49d728a2016-09-16 10:20:17 +0000982 // Use a normal worklist to find which SCCs the target connects to. We still
983 // bound the search based on the range in the postorder list we care about,
984 // but because this is forward connectivity we just "recurse" through the
985 // edges.
986 auto ComputeTargetConnectedSet = [&](SmallPtrSetImpl<RefSCC *> &Set) {
987 Set.insert(this);
988 SmallVector<RefSCC *, 4> Worklist;
989 Worklist.push_back(this);
990 do {
991 RefSCC &RC = *Worklist.pop_back_val();
992 for (SCC &C : RC)
993 for (Node &N : C)
Chandler Carruthaaad9f82017-02-09 23:24:13 +0000994 for (Edge &E : *N) {
995 RefSCC &EdgeRC = *G->lookupRefSCC(E.getNode());
Chandler Carruth49d728a2016-09-16 10:20:17 +0000996 if (G->getRefSCCIndex(EdgeRC) <= SourceIdx)
997 // Not in the postorder sequence between source and target.
998 continue;
Chandler Carruth312dddf2014-05-04 09:38:32 +0000999
Chandler Carruth49d728a2016-09-16 10:20:17 +00001000 if (Set.insert(&EdgeRC).second)
1001 Worklist.push_back(&EdgeRC);
1002 }
1003 } while (!Worklist.empty());
1004 };
1005
1006 // Use a generic helper to update the postorder sequence of RefSCCs and return
1007 // a range of any RefSCCs connected into a cycle by inserting this edge. This
1008 // routine will also take care of updating the indices into the postorder
1009 // sequence.
1010 iterator_range<SmallVectorImpl<RefSCC *>::iterator> MergeRange =
1011 updatePostorderSequenceForEdgeInsertion(
1012 SourceC, *this, G->PostOrderRefSCCs, G->RefSCCIndices,
1013 ComputeSourceConnectedSet, ComputeTargetConnectedSet);
1014
Chandler Carruth5205c352016-12-07 01:42:40 +00001015 // Build a set so we can do fast tests for whether a RefSCC will end up as
1016 // part of the merged RefSCC.
Chandler Carruth49d728a2016-09-16 10:20:17 +00001017 SmallPtrSet<RefSCC *, 16> MergeSet(MergeRange.begin(), MergeRange.end());
Chandler Carruth312dddf2014-05-04 09:38:32 +00001018
Chandler Carruth5205c352016-12-07 01:42:40 +00001019 // This RefSCC will always be part of that set, so just insert it here.
1020 MergeSet.insert(this);
1021
Chandler Carruth312dddf2014-05-04 09:38:32 +00001022 // Now that we have identified all of the SCCs which need to be merged into
1023 // a connected set with the inserted edge, merge all of them into this SCC.
Chandler Carruthe5944d92016-02-17 00:18:16 +00001024 SmallVector<SCC *, 16> MergedSCCs;
1025 int SCCIndex = 0;
Chandler Carruth49d728a2016-09-16 10:20:17 +00001026 for (RefSCC *RC : MergeRange) {
1027 assert(RC != this && "We're merging into the target RefSCC, so it "
1028 "shouldn't be in the range.");
Chandler Carruth312dddf2014-05-04 09:38:32 +00001029
Chandler Carruthe5944d92016-02-17 00:18:16 +00001030 // Walk the inner SCCs to update their up-pointer and walk all the edges to
1031 // update any parent sets.
1032 // FIXME: We should try to find a way to avoid this (rather expensive) edge
1033 // walk by updating the parent sets in some other manner.
Chandler Carruth49d728a2016-09-16 10:20:17 +00001034 for (SCC &InnerC : *RC) {
Chandler Carruthe5944d92016-02-17 00:18:16 +00001035 InnerC.OuterRefSCC = this;
1036 SCCIndices[&InnerC] = SCCIndex++;
Chandler Carruthadbf14a2017-08-05 07:37:00 +00001037 for (Node &N : InnerC)
Chandler Carruthe5944d92016-02-17 00:18:16 +00001038 G->SCCMap[&N] = &InnerC;
Chandler Carruth312dddf2014-05-04 09:38:32 +00001039 }
Chandler Carruthe5944d92016-02-17 00:18:16 +00001040
1041 // Now merge in the SCCs. We can actually move here so try to reuse storage
1042 // the first time through.
1043 if (MergedSCCs.empty())
Chandler Carruth49d728a2016-09-16 10:20:17 +00001044 MergedSCCs = std::move(RC->SCCs);
Chandler Carruthe5944d92016-02-17 00:18:16 +00001045 else
Chandler Carruth49d728a2016-09-16 10:20:17 +00001046 MergedSCCs.append(RC->SCCs.begin(), RC->SCCs.end());
1047 RC->SCCs.clear();
1048 DeletedRefSCCs.push_back(RC);
Chandler Carruth312dddf2014-05-04 09:38:32 +00001049 }
Chandler Carruthe5944d92016-02-17 00:18:16 +00001050
Chandler Carruth49d728a2016-09-16 10:20:17 +00001051 // Append our original SCCs to the merged list and move it into place.
Chandler Carruthe5944d92016-02-17 00:18:16 +00001052 for (SCC &InnerC : *this)
1053 SCCIndices[&InnerC] = SCCIndex++;
1054 MergedSCCs.append(SCCs.begin(), SCCs.end());
1055 SCCs = std::move(MergedSCCs);
1056
Chandler Carruth49d728a2016-09-16 10:20:17 +00001057 // Remove the merged away RefSCCs from the post order sequence.
1058 for (RefSCC *RC : MergeRange)
1059 G->RefSCCIndices.erase(RC);
1060 int IndexOffset = MergeRange.end() - MergeRange.begin();
1061 auto EraseEnd =
1062 G->PostOrderRefSCCs.erase(MergeRange.begin(), MergeRange.end());
1063 for (RefSCC *RC : make_range(EraseEnd, G->PostOrderRefSCCs.end()))
1064 G->RefSCCIndices[RC] -= IndexOffset;
1065
Chandler Carruthe5944d92016-02-17 00:18:16 +00001066 // At this point we have a merged RefSCC with a post-order SCCs list, just
1067 // connect the nodes to form the new edge.
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001068 SourceN->insertEdgeInternal(TargetN, Edge::Ref);
Chandler Carruthe5944d92016-02-17 00:18:16 +00001069
Chandler Carruth312dddf2014-05-04 09:38:32 +00001070 // We return the list of SCCs which were merged so that callers can
1071 // invalidate any data they have associated with those SCCs. Note that these
1072 // SCCs are no longer in an interesting state (they are totally empty) but
1073 // the pointers will remain stable for the life of the graph itself.
Chandler Carruth49d728a2016-09-16 10:20:17 +00001074 return DeletedRefSCCs;
Chandler Carruth312dddf2014-05-04 09:38:32 +00001075}
1076
Chandler Carruthe5944d92016-02-17 00:18:16 +00001077void LazyCallGraph::RefSCC::removeOutgoingEdge(Node &SourceN, Node &TargetN) {
1078 assert(G->lookupRefSCC(SourceN) == this &&
1079 "The source must be a member of this RefSCC.");
1080
1081 RefSCC &TargetRC = *G->lookupRefSCC(TargetN);
1082 assert(&TargetRC != this && "The target must not be a member of this RefSCC");
1083
Chandler Carruth11b3f602016-09-04 08:34:31 +00001084#ifndef NDEBUG
1085 // In a debug build, verify the RefSCC is valid to start with and when this
1086 // routine finishes.
1087 verify();
1088 auto VerifyOnExit = make_scope_exit([&]() { verify(); });
1089#endif
1090
Chandler Carruthaa839b22014-04-27 01:59:50 +00001091 // First remove it from the node.
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001092 bool Removed = SourceN->removeEdgeInternal(TargetN);
1093 (void)Removed;
1094 assert(Removed && "Target not in the edge set for this caller?");
Chandler Carruthaca48d02014-04-26 09:06:53 +00001095}
1096
Chandler Carruthe5944d92016-02-17 00:18:16 +00001097SmallVector<LazyCallGraph::RefSCC *, 1>
1098LazyCallGraph::RefSCC::removeInternalRefEdge(Node &SourceN, Node &TargetN) {
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001099 assert(!(*SourceN)[TargetN].isCall() &&
Chandler Carruthe5944d92016-02-17 00:18:16 +00001100 "Cannot remove a call edge, it must first be made a ref edge");
Chandler Carruthaa839b22014-04-27 01:59:50 +00001101
Chandler Carruth11b3f602016-09-04 08:34:31 +00001102#ifndef NDEBUG
1103 // In a debug build, verify the RefSCC is valid to start with and when this
1104 // routine finishes.
1105 verify();
1106 auto VerifyOnExit = make_scope_exit([&]() { verify(); });
1107#endif
1108
Chandler Carruthe5944d92016-02-17 00:18:16 +00001109 // First remove the actual edge.
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001110 bool Removed = SourceN->removeEdgeInternal(TargetN);
1111 (void)Removed;
1112 assert(Removed && "Target not in the edge set for this caller?");
Chandler Carruthe5944d92016-02-17 00:18:16 +00001113
1114 // We return a list of the resulting *new* RefSCCs in post-order.
1115 SmallVector<RefSCC *, 1> Result;
Chandler Carruth9302fbf2014-04-23 11:03:03 +00001116
Chandler Carrutha7205b62014-04-26 03:36:37 +00001117 // Direct recursion doesn't impact the SCC graph at all.
Chandler Carruthe5944d92016-02-17 00:18:16 +00001118 if (&SourceN == &TargetN)
1119 return Result;
Chandler Carrutha7205b62014-04-26 03:36:37 +00001120
Chandler Carruthc6334572016-12-28 02:24:58 +00001121 // If this ref edge is within an SCC then there are sufficient other edges to
1122 // form a cycle without this edge so removing it is a no-op.
1123 SCC &SourceC = *G->lookupSCC(SourceN);
1124 SCC &TargetC = *G->lookupSCC(TargetN);
1125 if (&SourceC == &TargetC)
1126 return Result;
1127
Chandler Carruthe5944d92016-02-17 00:18:16 +00001128 // We build somewhat synthetic new RefSCCs by providing a postorder mapping
1129 // for each inner SCC. We also store these associated with *nodes* rather
1130 // than SCCs because this saves a round-trip through the node->SCC map and in
1131 // the common case, SCCs are small. We will verify that we always give the
1132 // same number to every node in the SCC such that these are equivalent.
1133 const int RootPostOrderNumber = 0;
1134 int PostOrderNumber = RootPostOrderNumber + 1;
1135 SmallDenseMap<Node *, int> PostOrderMapping;
1136
1137 // Every node in the target SCC can already reach every node in this RefSCC
1138 // (by definition). It is the only node we know will stay inside this RefSCC.
1139 // Everything which transitively reaches Target will also remain in the
1140 // RefSCC. We handle this by pre-marking that the nodes in the target SCC map
1141 // back to the root post order number.
1142 //
1143 // This also enables us to take a very significant short-cut in the standard
1144 // Tarjan walk to re-form RefSCCs below: whenever we build an edge that
1145 // references the target node, we know that the target node eventually
1146 // references all other nodes in our walk. As a consequence, we can detect
1147 // and handle participants in that cycle without walking all the edges that
1148 // form the connections, and instead by relying on the fundamental guarantee
1149 // coming into this operation.
Chandler Carruthe5944d92016-02-17 00:18:16 +00001150 for (Node &N : TargetC)
1151 PostOrderMapping[&N] = RootPostOrderNumber;
1152
1153 // Reset all the other nodes to prepare for a DFS over them, and add them to
1154 // our worklist.
1155 SmallVector<Node *, 8> Worklist;
1156 for (SCC *C : SCCs) {
1157 if (C == &TargetC)
1158 continue;
1159
1160 for (Node &N : *C)
1161 N.DFSNumber = N.LowLink = 0;
1162
1163 Worklist.append(C->Nodes.begin(), C->Nodes.end());
Chandler Carruth9302fbf2014-04-23 11:03:03 +00001164 }
1165
Chandler Carruthe5944d92016-02-17 00:18:16 +00001166 auto MarkNodeForSCCNumber = [&PostOrderMapping](Node &N, int Number) {
1167 N.DFSNumber = N.LowLink = -1;
1168 PostOrderMapping[&N] = Number;
1169 };
Chandler Carruth9302fbf2014-04-23 11:03:03 +00001170
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001171 SmallVector<std::pair<Node *, EdgeSequence::iterator>, 4> DFSStack;
Chandler Carruthe5944d92016-02-17 00:18:16 +00001172 SmallVector<Node *, 4> PendingRefSCCStack;
Chandler Carruthaca48d02014-04-26 09:06:53 +00001173 do {
Chandler Carruthe5944d92016-02-17 00:18:16 +00001174 assert(DFSStack.empty() &&
1175 "Cannot begin a new root with a non-empty DFS stack!");
1176 assert(PendingRefSCCStack.empty() &&
1177 "Cannot begin a new root with pending nodes for an SCC!");
1178
1179 Node *RootN = Worklist.pop_back_val();
1180 // Skip any nodes we've already reached in the DFS.
1181 if (RootN->DFSNumber != 0) {
1182 assert(RootN->DFSNumber == -1 &&
1183 "Shouldn't have any mid-DFS root nodes!");
1184 continue;
1185 }
1186
1187 RootN->DFSNumber = RootN->LowLink = 1;
1188 int NextDFSNumber = 2;
1189
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001190 DFSStack.push_back({RootN, (*RootN)->begin()});
Chandler Carruthe5944d92016-02-17 00:18:16 +00001191 do {
1192 Node *N;
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001193 EdgeSequence::iterator I;
Chandler Carruthe5944d92016-02-17 00:18:16 +00001194 std::tie(N, I) = DFSStack.pop_back_val();
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001195 auto E = (*N)->end();
Chandler Carruthe5944d92016-02-17 00:18:16 +00001196
1197 assert(N->DFSNumber != 0 && "We should always assign a DFS number "
1198 "before processing a node.");
1199
1200 while (I != E) {
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001201 Node &ChildN = I->getNode();
Chandler Carruthe5944d92016-02-17 00:18:16 +00001202 if (ChildN.DFSNumber == 0) {
1203 // Mark that we should start at this child when next this node is the
1204 // top of the stack. We don't start at the next child to ensure this
1205 // child's lowlink is reflected.
1206 DFSStack.push_back({N, I});
1207
1208 // Continue, resetting to the child node.
1209 ChildN.LowLink = ChildN.DFSNumber = NextDFSNumber++;
1210 N = &ChildN;
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001211 I = ChildN->begin();
1212 E = ChildN->end();
Chandler Carruthe5944d92016-02-17 00:18:16 +00001213 continue;
1214 }
1215 if (ChildN.DFSNumber == -1) {
1216 // Check if this edge's target node connects to the deleted edge's
1217 // target node. If so, we know that every node connected will end up
1218 // in this RefSCC, so collapse the entire current stack into the root
1219 // slot in our SCC numbering. See above for the motivation of
1220 // optimizing the target connected nodes in this way.
1221 auto PostOrderI = PostOrderMapping.find(&ChildN);
1222 if (PostOrderI != PostOrderMapping.end() &&
1223 PostOrderI->second == RootPostOrderNumber) {
1224 MarkNodeForSCCNumber(*N, RootPostOrderNumber);
1225 while (!PendingRefSCCStack.empty())
1226 MarkNodeForSCCNumber(*PendingRefSCCStack.pop_back_val(),
1227 RootPostOrderNumber);
1228 while (!DFSStack.empty())
1229 MarkNodeForSCCNumber(*DFSStack.pop_back_val().first,
1230 RootPostOrderNumber);
1231 // Ensure we break all the way out of the enclosing loop.
1232 N = nullptr;
1233 break;
1234 }
1235
1236 // 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 }
1250 if (!N)
1251 // We short-circuited this node.
1252 break;
1253
1254 // We've finished processing N and its descendents, put it on our pending
1255 // stack to eventually get merged into a RefSCC.
1256 PendingRefSCCStack.push_back(N);
1257
1258 // If this node is linked to some lower entry, continue walking up the
1259 // stack.
1260 if (N->LowLink != N->DFSNumber) {
1261 assert(!DFSStack.empty() &&
1262 "We never found a viable root for a RefSCC to pop off!");
1263 continue;
1264 }
1265
1266 // Otherwise, form a new RefSCC from the top of the pending node stack.
1267 int RootDFSNumber = N->DFSNumber;
1268 // Find the range of the node stack by walking down until we pass the
1269 // root DFS number.
1270 auto RefSCCNodes = make_range(
1271 PendingRefSCCStack.rbegin(),
David Majnemer42531262016-08-12 03:55:06 +00001272 find_if(reverse(PendingRefSCCStack), [RootDFSNumber](const Node *N) {
1273 return N->DFSNumber < RootDFSNumber;
1274 }));
Chandler Carruthe5944d92016-02-17 00:18:16 +00001275
1276 // Mark the postorder number for these nodes and clear them off the
1277 // stack. We'll use the postorder number to pull them into RefSCCs at the
1278 // end. FIXME: Fuse with the loop above.
1279 int RefSCCNumber = PostOrderNumber++;
1280 for (Node *N : RefSCCNodes)
1281 MarkNodeForSCCNumber(*N, RefSCCNumber);
1282
1283 PendingRefSCCStack.erase(RefSCCNodes.end().base(),
1284 PendingRefSCCStack.end());
1285 } while (!DFSStack.empty());
Chandler Carruth9302fbf2014-04-23 11:03:03 +00001286
Chandler Carruthaca48d02014-04-26 09:06:53 +00001287 assert(DFSStack.empty() && "Didn't flush the entire DFS stack!");
Chandler Carruthe5944d92016-02-17 00:18:16 +00001288 assert(PendingRefSCCStack.empty() && "Didn't flush all pending nodes!");
Chandler Carruthaca48d02014-04-26 09:06:53 +00001289 } while (!Worklist.empty());
Chandler Carruth9302fbf2014-04-23 11:03:03 +00001290
Chandler Carruthe5944d92016-02-17 00:18:16 +00001291 // We now have a post-order numbering for RefSCCs and a mapping from each
1292 // node in this RefSCC to its final RefSCC. We create each new RefSCC node
1293 // (re-using this RefSCC node for the root) and build a radix-sort style map
1294 // from postorder number to the RefSCC. We then append SCCs to each of these
1295 // RefSCCs in the order they occured in the original SCCs container.
1296 for (int i = 1; i < PostOrderNumber; ++i)
1297 Result.push_back(G->createRefSCC(*G));
1298
Chandler Carruth49d728a2016-09-16 10:20:17 +00001299 // Insert the resulting postorder sequence into the global graph postorder
1300 // sequence before the current RefSCC in that sequence. The idea being that
1301 // this RefSCC is the target of the reference edge removed, and thus has
1302 // a direct or indirect edge to every other RefSCC formed and so must be at
1303 // the end of any postorder traversal.
1304 //
1305 // FIXME: It'd be nice to change the APIs so that we returned an iterator
1306 // range over the global postorder sequence and generally use that sequence
1307 // rather than building a separate result vector here.
1308 if (!Result.empty()) {
1309 int Idx = G->getRefSCCIndex(*this);
1310 G->PostOrderRefSCCs.insert(G->PostOrderRefSCCs.begin() + Idx,
1311 Result.begin(), Result.end());
1312 for (int i : seq<int>(Idx, G->PostOrderRefSCCs.size()))
1313 G->RefSCCIndices[G->PostOrderRefSCCs[i]] = i;
1314 assert(G->PostOrderRefSCCs[G->getRefSCCIndex(*this)] == this &&
1315 "Failed to update this RefSCC's index after insertion!");
1316 }
1317
Chandler Carruthe5944d92016-02-17 00:18:16 +00001318 for (SCC *C : SCCs) {
1319 auto PostOrderI = PostOrderMapping.find(&*C->begin());
1320 assert(PostOrderI != PostOrderMapping.end() &&
1321 "Cannot have missing mappings for nodes!");
1322 int SCCNumber = PostOrderI->second;
Chandler Carruth9302fbf2014-04-23 11:03:03 +00001323#ifndef NDEBUG
Chandler Carruthe5944d92016-02-17 00:18:16 +00001324 for (Node &N : *C)
1325 assert(PostOrderMapping.find(&N)->second == SCCNumber &&
1326 "Cannot have different numbers for nodes in the same SCC!");
1327#endif
1328 if (SCCNumber == 0)
1329 // The root node is handled separately by removing the SCCs.
1330 continue;
1331
1332 RefSCC &RC = *Result[SCCNumber - 1];
1333 int SCCIndex = RC.SCCs.size();
1334 RC.SCCs.push_back(C);
Chandler Carruth23a6c3f2016-12-06 10:29:23 +00001335 RC.SCCIndices[C] = SCCIndex;
Chandler Carruthe5944d92016-02-17 00:18:16 +00001336 C->OuterRefSCC = &RC;
1337 }
1338
Chandler Carruthe5944d92016-02-17 00:18:16 +00001339 // Now erase all but the root's SCCs.
David Majnemer42531262016-08-12 03:55:06 +00001340 SCCs.erase(remove_if(SCCs,
1341 [&](SCC *C) {
1342 return PostOrderMapping.lookup(&*C->begin()) !=
1343 RootPostOrderNumber;
1344 }),
Chandler Carruthe5944d92016-02-17 00:18:16 +00001345 SCCs.end());
Chandler Carruth88823462016-08-24 09:37:14 +00001346 SCCIndices.clear();
1347 for (int i = 0, Size = SCCs.size(); i < Size; ++i)
1348 SCCIndices[SCCs[i]] = i;
Chandler Carruthe5944d92016-02-17 00:18:16 +00001349
1350#ifndef NDEBUG
Chandler Carruth23a6c3f2016-12-06 10:29:23 +00001351 // Verify all of the new RefSCCs.
1352 for (RefSCC *RC : Result)
1353 RC->verify();
1354#endif
1355
Chandler Carruth9302fbf2014-04-23 11:03:03 +00001356 // Return the new list of SCCs.
Chandler Carruthe5944d92016-02-17 00:18:16 +00001357 return Result;
Chandler Carruth9302fbf2014-04-23 11:03:03 +00001358}
1359
Chandler Carruth5dbc1642016-10-12 07:59:56 +00001360void LazyCallGraph::RefSCC::handleTrivialEdgeInsertion(Node &SourceN,
1361 Node &TargetN) {
1362 // The only trivial case that requires any graph updates is when we add new
1363 // ref edge and may connect different RefSCCs along that path. This is only
1364 // because of the parents set. Every other part of the graph remains constant
1365 // after this edge insertion.
1366 assert(G->lookupRefSCC(SourceN) == this && "Source must be in this RefSCC.");
1367 RefSCC &TargetRC = *G->lookupRefSCC(TargetN);
1368 if (&TargetRC == this) {
1369
1370 return;
1371 }
1372
Francis Visoiu Mistrih262ad162017-02-28 18:34:55 +00001373#ifdef EXPENSIVE_CHECKS
Chandler Carruth5dbc1642016-10-12 07:59:56 +00001374 assert(TargetRC.isDescendantOf(*this) &&
1375 "Target must be a descendant of the Source.");
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001376#endif
Chandler Carruth5dbc1642016-10-12 07:59:56 +00001377}
1378
1379void LazyCallGraph::RefSCC::insertTrivialCallEdge(Node &SourceN,
1380 Node &TargetN) {
1381#ifndef NDEBUG
1382 // Check that the RefSCC is still valid when we finish.
1383 auto ExitVerifier = make_scope_exit([this] { verify(); });
Chandler Carruthbae595b2016-11-22 19:23:31 +00001384
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001385#ifdef EXPENSIVE_CHECKS
1386 // Check that we aren't breaking some invariants of the SCC graph. Note that
1387 // this is quadratic in the number of edges in the call graph!
Chandler Carruthbae595b2016-11-22 19:23:31 +00001388 SCC &SourceC = *G->lookupSCC(SourceN);
1389 SCC &TargetC = *G->lookupSCC(TargetN);
1390 if (&SourceC != &TargetC)
1391 assert(SourceC.isAncestorOf(TargetC) &&
1392 "Call edge is not trivial in the SCC graph!");
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001393#endif // EXPENSIVE_CHECKS
1394#endif // NDEBUG
1395
Chandler Carruth5dbc1642016-10-12 07:59:56 +00001396 // First insert it into the source or find the existing edge.
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001397 auto InsertResult =
1398 SourceN->EdgeIndexMap.insert({&TargetN, SourceN->Edges.size()});
Chandler Carruth5dbc1642016-10-12 07:59:56 +00001399 if (!InsertResult.second) {
1400 // Already an edge, just update it.
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001401 Edge &E = SourceN->Edges[InsertResult.first->second];
Chandler Carruth5dbc1642016-10-12 07:59:56 +00001402 if (E.isCall())
1403 return; // Nothing to do!
1404 E.setKind(Edge::Call);
1405 } else {
1406 // Create the new edge.
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001407 SourceN->Edges.emplace_back(TargetN, Edge::Call);
Chandler Carruth5dbc1642016-10-12 07:59:56 +00001408 }
1409
1410 // Now that we have the edge, handle the graph fallout.
1411 handleTrivialEdgeInsertion(SourceN, TargetN);
1412}
1413
1414void LazyCallGraph::RefSCC::insertTrivialRefEdge(Node &SourceN, Node &TargetN) {
1415#ifndef NDEBUG
1416 // Check that the RefSCC is still valid when we finish.
1417 auto ExitVerifier = make_scope_exit([this] { verify(); });
Chandler Carruth9eb857c2016-11-22 21:40:10 +00001418
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001419#ifdef EXPENSIVE_CHECKS
Chandler Carruth9eb857c2016-11-22 21:40:10 +00001420 // Check that we aren't breaking some invariants of the RefSCC graph.
1421 RefSCC &SourceRC = *G->lookupRefSCC(SourceN);
1422 RefSCC &TargetRC = *G->lookupRefSCC(TargetN);
1423 if (&SourceRC != &TargetRC)
1424 assert(SourceRC.isAncestorOf(TargetRC) &&
1425 "Ref edge is not trivial in the RefSCC graph!");
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001426#endif // EXPENSIVE_CHECKS
1427#endif // NDEBUG
1428
Chandler Carruth5dbc1642016-10-12 07:59:56 +00001429 // First insert it into the source or find the existing edge.
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001430 auto InsertResult =
1431 SourceN->EdgeIndexMap.insert({&TargetN, SourceN->Edges.size()});
Chandler Carruth5dbc1642016-10-12 07:59:56 +00001432 if (!InsertResult.second)
1433 // Already an edge, we're done.
1434 return;
1435
1436 // Create the new edge.
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001437 SourceN->Edges.emplace_back(TargetN, Edge::Ref);
Chandler Carruth5dbc1642016-10-12 07:59:56 +00001438
1439 // Now that we have the edge, handle the graph fallout.
1440 handleTrivialEdgeInsertion(SourceN, TargetN);
1441}
1442
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001443void LazyCallGraph::RefSCC::replaceNodeFunction(Node &N, Function &NewF) {
1444 Function &OldF = N.getFunction();
Chandler Carruthc00a7ff2014-04-28 11:10:23 +00001445
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001446#ifndef NDEBUG
1447 // Check that the RefSCC is still valid when we finish.
1448 auto ExitVerifier = make_scope_exit([this] { verify(); });
1449
1450 assert(G->lookupRefSCC(N) == this &&
1451 "Cannot replace the function of a node outside this RefSCC.");
1452
1453 assert(G->NodeMap.find(&NewF) == G->NodeMap.end() &&
1454 "Must not have already walked the new function!'");
1455
1456 // It is important that this replacement not introduce graph changes so we
1457 // insist that the caller has already removed every use of the original
1458 // function and that all uses of the new function correspond to existing
1459 // edges in the graph. The common and expected way to use this is when
1460 // replacing the function itself in the IR without changing the call graph
1461 // shape and just updating the analysis based on that.
1462 assert(&OldF != &NewF && "Cannot replace a function with itself!");
1463 assert(OldF.use_empty() &&
1464 "Must have moved all uses from the old function to the new!");
1465#endif
1466
1467 N.replaceFunction(NewF);
1468
1469 // Update various call graph maps.
1470 G->NodeMap.erase(&OldF);
1471 G->NodeMap[&NewF] = &N;
Chandler Carruthc00a7ff2014-04-28 11:10:23 +00001472}
1473
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001474void LazyCallGraph::insertEdge(Node &SourceN, Node &TargetN, Edge::Kind EK) {
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001475 assert(SCCMap.empty() &&
Chandler Carruthaa839b22014-04-27 01:59:50 +00001476 "This method cannot be called after SCCs have been formed!");
Chandler Carruth9302fbf2014-04-23 11:03:03 +00001477
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001478 return SourceN->insertEdgeInternal(TargetN, EK);
1479}
1480
1481void LazyCallGraph::removeEdge(Node &SourceN, Node &TargetN) {
1482 assert(SCCMap.empty() &&
1483 "This method cannot be called after SCCs have been formed!");
1484
1485 bool Removed = SourceN->removeEdgeInternal(TargetN);
1486 (void)Removed;
1487 assert(Removed && "Target not in the edge set for this caller?");
Chandler Carruth9302fbf2014-04-23 11:03:03 +00001488}
1489
Chandler Carruth5dbc1642016-10-12 07:59:56 +00001490void LazyCallGraph::removeDeadFunction(Function &F) {
1491 // FIXME: This is unnecessarily restrictive. We should be able to remove
1492 // functions which recursively call themselves.
1493 assert(F.use_empty() &&
1494 "This routine should only be called on trivially dead functions!");
1495
Chandler Carruth06a86302017-07-19 04:12:25 +00001496 // We shouldn't remove library functions as they are never really dead while
1497 // the call graph is in use -- every function definition refers to them.
1498 assert(!isLibFunction(F) &&
1499 "Must not remove lib functions from the call graph!");
1500
Chandler Carruth5dbc1642016-10-12 07:59:56 +00001501 auto NI = NodeMap.find(&F);
1502 if (NI == NodeMap.end())
1503 // Not in the graph at all!
1504 return;
1505
1506 Node &N = *NI->second;
1507 NodeMap.erase(NI);
1508
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001509 // Remove this from the entry edges if present.
1510 EntryEdges.removeEdgeInternal(N);
1511
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001512 if (SCCMap.empty()) {
1513 // No SCCs have been formed, so removing this is fine and there is nothing
Chandler Carruth5dbc1642016-10-12 07:59:56 +00001514 // else necessary at this point but clearing out the node.
1515 N.clear();
1516 return;
1517 }
1518
Chandler Carruth5dbc1642016-10-12 07:59:56 +00001519 // Cannot remove a function which has yet to be visited in the DFS walk, so
1520 // if we have a node at all then we must have an SCC and RefSCC.
1521 auto CI = SCCMap.find(&N);
1522 assert(CI != SCCMap.end() &&
1523 "Tried to remove a node without an SCC after DFS walk started!");
1524 SCC &C = *CI->second;
1525 SCCMap.erase(CI);
1526 RefSCC &RC = C.getOuterRefSCC();
1527
1528 // This node must be the only member of its SCC as it has no callers, and
1529 // that SCC must be the only member of a RefSCC as it has no references.
1530 // Validate these properties first.
1531 assert(C.size() == 1 && "Dead functions must be in a singular SCC");
1532 assert(RC.size() == 1 && "Dead functions must be in a singular RefSCC");
Chandler Carruth1f8fcfe2017-02-09 23:30:14 +00001533
Chandler Carruth5dbc1642016-10-12 07:59:56 +00001534 auto RCIndexI = RefSCCIndices.find(&RC);
1535 int RCIndex = RCIndexI->second;
1536 PostOrderRefSCCs.erase(PostOrderRefSCCs.begin() + RCIndex);
1537 RefSCCIndices.erase(RCIndexI);
1538 for (int i = RCIndex, Size = PostOrderRefSCCs.size(); i < Size; ++i)
1539 RefSCCIndices[PostOrderRefSCCs[i]] = i;
1540
1541 // Finally clear out all the data structures from the node down through the
1542 // components.
1543 N.clear();
Chandler Carruth403d3c42017-08-05 03:37:39 +00001544 N.G = nullptr;
Chandler Carruthc718b8e2017-08-05 05:47:37 +00001545 N.F = nullptr;
Chandler Carruth5dbc1642016-10-12 07:59:56 +00001546 C.clear();
1547 RC.clear();
Chandler Carruth403d3c42017-08-05 03:37:39 +00001548 RC.G = nullptr;
Chandler Carruth5dbc1642016-10-12 07:59:56 +00001549
1550 // Nothing to delete as all the objects are allocated in stable bump pointer
1551 // allocators.
1552}
1553
Chandler Carruth2a898e02014-04-23 23:20:36 +00001554LazyCallGraph::Node &LazyCallGraph::insertInto(Function &F, Node *&MappedN) {
1555 return *new (MappedN = BPA.Allocate()) Node(*this, F);
Chandler Carruthd8d865e2014-04-18 11:02:33 +00001556}
1557
1558void LazyCallGraph::updateGraphPtrs() {
Chandler Carruth7cb23e72017-08-05 03:37:39 +00001559 // Walk the node map to update their graph pointers. While this iterates in
1560 // an unstable order, the order has no effect so it remains correct.
1561 for (auto &FunctionNodePair : NodeMap)
1562 FunctionNodePair.second->G = this;
Chandler Carruthaa839b22014-04-27 01:59:50 +00001563
Chandler Carruth2c58e1a2017-08-05 03:37:38 +00001564 for (auto *RC : PostOrderRefSCCs)
1565 RC->G = this;
Chandler Carruthbf71a342014-02-06 04:37:03 +00001566}
Chandler Carruthbf71a342014-02-06 04:37:03 +00001567
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001568template <typename RootsT, typename GetBeginT, typename GetEndT,
1569 typename GetNodeT, typename FormSCCCallbackT>
1570void LazyCallGraph::buildGenericSCCs(RootsT &&Roots, GetBeginT &&GetBegin,
1571 GetEndT &&GetEnd, GetNodeT &&GetNode,
1572 FormSCCCallbackT &&FormSCC) {
1573 typedef decltype(GetBegin(std::declval<Node &>())) EdgeItT;
Chandler Carruth3f9869a2014-04-23 06:09:03 +00001574
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001575 SmallVector<std::pair<Node *, EdgeItT>, 16> DFSStack;
Chandler Carruthe5944d92016-02-17 00:18:16 +00001576 SmallVector<Node *, 16> PendingSCCStack;
1577
1578 // Scan down the stack and DFS across the call edges.
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001579 for (Node *RootN : Roots) {
Chandler Carruthe5944d92016-02-17 00:18:16 +00001580 assert(DFSStack.empty() &&
1581 "Cannot begin a new root with a non-empty DFS stack!");
1582 assert(PendingSCCStack.empty() &&
1583 "Cannot begin a new root with pending nodes for an SCC!");
1584
1585 // Skip any nodes we've already reached in the DFS.
1586 if (RootN->DFSNumber != 0) {
1587 assert(RootN->DFSNumber == -1 &&
1588 "Shouldn't have any mid-DFS root nodes!");
1589 continue;
Chandler Carruth3f9869a2014-04-23 06:09:03 +00001590 }
1591
Chandler Carruthe5944d92016-02-17 00:18:16 +00001592 RootN->DFSNumber = RootN->LowLink = 1;
1593 int NextDFSNumber = 2;
Chandler Carruth3f9869a2014-04-23 06:09:03 +00001594
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001595 DFSStack.push_back({RootN, GetBegin(*RootN)});
Chandler Carruthe5944d92016-02-17 00:18:16 +00001596 do {
1597 Node *N;
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001598 EdgeItT I;
Chandler Carruthe5944d92016-02-17 00:18:16 +00001599 std::tie(N, I) = DFSStack.pop_back_val();
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001600 auto E = GetEnd(*N);
Chandler Carruthe5944d92016-02-17 00:18:16 +00001601 while (I != E) {
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001602 Node &ChildN = GetNode(I);
Chandler Carruthe5944d92016-02-17 00:18:16 +00001603 if (ChildN.DFSNumber == 0) {
1604 // We haven't yet visited this child, so descend, pushing the current
1605 // node onto the stack.
1606 DFSStack.push_back({N, I});
1607
Chandler Carruthe5944d92016-02-17 00:18:16 +00001608 ChildN.DFSNumber = ChildN.LowLink = NextDFSNumber++;
1609 N = &ChildN;
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001610 I = GetBegin(*N);
1611 E = GetEnd(*N);
Chandler Carruthe5944d92016-02-17 00:18:16 +00001612 continue;
1613 }
1614
1615 // If the child has already been added to some child component, it
1616 // couldn't impact the low-link of this parent because it isn't
1617 // connected, and thus its low-link isn't relevant so skip it.
1618 if (ChildN.DFSNumber == -1) {
1619 ++I;
1620 continue;
1621 }
1622
1623 // Track the lowest linked child as the lowest link for this node.
1624 assert(ChildN.LowLink > 0 && "Must have a positive low-link number!");
1625 if (ChildN.LowLink < N->LowLink)
1626 N->LowLink = ChildN.LowLink;
1627
1628 // Move to the next edge.
1629 ++I;
1630 }
1631
1632 // We've finished processing N and its descendents, put it on our pending
1633 // SCC stack to eventually get merged into an SCC of nodes.
1634 PendingSCCStack.push_back(N);
1635
1636 // If this node is linked to some lower entry, continue walking up the
1637 // stack.
1638 if (N->LowLink != N->DFSNumber)
1639 continue;
1640
1641 // Otherwise, we've completed an SCC. Append it to our post order list of
1642 // SCCs.
1643 int RootDFSNumber = N->DFSNumber;
1644 // Find the range of the node stack by walking down until we pass the
1645 // root DFS number.
1646 auto SCCNodes = make_range(
1647 PendingSCCStack.rbegin(),
David Majnemer42531262016-08-12 03:55:06 +00001648 find_if(reverse(PendingSCCStack), [RootDFSNumber](const Node *N) {
1649 return N->DFSNumber < RootDFSNumber;
1650 }));
Chandler Carruthe5944d92016-02-17 00:18:16 +00001651 // Form a new SCC out of these nodes and then clear them off our pending
1652 // stack.
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001653 FormSCC(SCCNodes);
Chandler Carruthe5944d92016-02-17 00:18:16 +00001654 PendingSCCStack.erase(SCCNodes.end().base(), PendingSCCStack.end());
1655 } while (!DFSStack.empty());
1656 }
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001657}
1658
1659/// Build the internal SCCs for a RefSCC from a sequence of nodes.
1660///
1661/// Appends the SCCs to the provided vector and updates the map with their
1662/// indices. Both the vector and map must be empty when passed into this
1663/// routine.
1664void LazyCallGraph::buildSCCs(RefSCC &RC, node_stack_range Nodes) {
1665 assert(RC.SCCs.empty() && "Already built SCCs!");
1666 assert(RC.SCCIndices.empty() && "Already mapped SCC indices!");
1667
1668 for (Node *N : Nodes) {
1669 assert(N->LowLink >= (*Nodes.begin())->LowLink &&
1670 "We cannot have a low link in an SCC lower than its root on the "
1671 "stack!");
1672
1673 // This node will go into the next RefSCC, clear out its DFS and low link
1674 // as we scan.
1675 N->DFSNumber = N->LowLink = 0;
1676 }
1677
1678 // Each RefSCC contains a DAG of the call SCCs. To build these, we do
1679 // a direct walk of the call edges using Tarjan's algorithm. We reuse the
1680 // internal storage as we won't need it for the outer graph's DFS any longer.
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001681 buildGenericSCCs(
1682 Nodes, [](Node &N) { return N->call_begin(); },
1683 [](Node &N) { return N->call_end(); },
1684 [](EdgeSequence::call_iterator I) -> Node & { return I->getNode(); },
1685 [this, &RC](node_stack_range Nodes) {
1686 RC.SCCs.push_back(createSCC(RC, Nodes));
1687 for (Node &N : *RC.SCCs.back()) {
1688 N.DFSNumber = N.LowLink = -1;
1689 SCCMap[&N] = RC.SCCs.back();
1690 }
1691 });
Chandler Carruthe5944d92016-02-17 00:18:16 +00001692
1693 // Wire up the SCC indices.
1694 for (int i = 0, Size = RC.SCCs.size(); i < Size; ++i)
1695 RC.SCCIndices[RC.SCCs[i]] = i;
Chandler Carruth3f9869a2014-04-23 06:09:03 +00001696}
1697
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001698void LazyCallGraph::buildRefSCCs() {
1699 if (EntryEdges.empty() || !PostOrderRefSCCs.empty())
1700 // RefSCCs are either non-existent or already built!
1701 return;
1702
1703 assert(RefSCCIndices.empty() && "Already mapped RefSCC indices!");
1704
1705 SmallVector<Node *, 16> Roots;
1706 for (Edge &E : *this)
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001707 Roots.push_back(&E.getNode());
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001708
1709 // The roots will be popped of a stack, so use reverse to get a less
1710 // surprising order. This doesn't change any of the semantics anywhere.
1711 std::reverse(Roots.begin(), Roots.end());
1712
1713 buildGenericSCCs(
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001714 Roots,
1715 [](Node &N) {
1716 // We need to populate each node as we begin to walk its edges.
1717 N.populate();
1718 return N->begin();
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001719 },
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001720 [](Node &N) { return N->end(); },
1721 [](EdgeSequence::iterator I) -> Node & { return I->getNode(); },
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001722 [this](node_stack_range Nodes) {
1723 RefSCC *NewRC = createRefSCC(*this);
1724 buildSCCs(*NewRC, Nodes);
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001725
1726 // Push the new node into the postorder list and remember its position
1727 // in the index map.
1728 bool Inserted =
1729 RefSCCIndices.insert({NewRC, PostOrderRefSCCs.size()}).second;
1730 (void)Inserted;
1731 assert(Inserted && "Cannot already have this RefSCC in the index map!");
1732 PostOrderRefSCCs.push_back(NewRC);
Chandler Carrutha80cfb32017-02-06 20:59:07 +00001733#ifndef NDEBUG
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001734 NewRC->verify();
Chandler Carrutha80cfb32017-02-06 20:59:07 +00001735#endif
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001736 });
1737}
1738
Chandler Carruthdab4eae2016-11-23 17:53:26 +00001739AnalysisKey LazyCallGraphAnalysis::Key;
NAKAMURA Takumidf0cd722016-02-28 17:17:00 +00001740
Chandler Carruthbf71a342014-02-06 04:37:03 +00001741LazyCallGraphPrinterPass::LazyCallGraphPrinterPass(raw_ostream &OS) : OS(OS) {}
1742
Chandler Carruthe5944d92016-02-17 00:18:16 +00001743static void printNode(raw_ostream &OS, LazyCallGraph::Node &N) {
Chandler Carrutha4499e92016-02-02 03:57:13 +00001744 OS << " Edges in function: " << N.getFunction().getName() << "\n";
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001745 for (LazyCallGraph::Edge &E : N.populate())
Chandler Carrutha4499e92016-02-02 03:57:13 +00001746 OS << " " << (E.isCall() ? "call" : "ref ") << " -> "
1747 << E.getFunction().getName() << "\n";
Chandler Carruth11f50322015-01-14 00:27:45 +00001748
1749 OS << "\n";
1750}
1751
Chandler Carruthe5944d92016-02-17 00:18:16 +00001752static void printSCC(raw_ostream &OS, LazyCallGraph::SCC &C) {
1753 ptrdiff_t Size = std::distance(C.begin(), C.end());
1754 OS << " SCC with " << 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) {
1761 ptrdiff_t Size = std::distance(C.begin(), C.end());
1762 OS << " RefSCC with " << Size << " call SCCs:\n";
1763
1764 for (LazyCallGraph::SCC &InnerC : C)
1765 printSCC(OS, InnerC);
Chandler Carruth11f50322015-01-14 00:27:45 +00001766
1767 OS << "\n";
1768}
1769
Chandler Carruthd174ce42015-01-05 02:47:05 +00001770PreservedAnalyses LazyCallGraphPrinterPass::run(Module &M,
Chandler Carruthb47f8012016-03-11 11:05:24 +00001771 ModuleAnalysisManager &AM) {
1772 LazyCallGraph &G = AM.getResult<LazyCallGraphAnalysis>(M);
Chandler Carruth11f50322015-01-14 00:27:45 +00001773
1774 OS << "Printing the call graph for module: " << M.getModuleIdentifier()
1775 << "\n\n";
1776
Chandler Carruthe5944d92016-02-17 00:18:16 +00001777 for (Function &F : M)
1778 printNode(OS, G.get(F));
Chandler Carruth11f50322015-01-14 00:27:45 +00001779
Chandler Carruth2e0fe3e2017-02-06 19:38:06 +00001780 G.buildRefSCCs();
Chandler Carruthe5944d92016-02-17 00:18:16 +00001781 for (LazyCallGraph::RefSCC &C : G.postorder_ref_sccs())
1782 printRefSCC(OS, C);
Chandler Carruth18eadd922014-04-18 10:50:32 +00001783
Chandler Carruthbf71a342014-02-06 04:37:03 +00001784 return PreservedAnalyses::all();
Chandler Carruthbf71a342014-02-06 04:37:03 +00001785}
Sean Silva7cb30662016-06-18 09:17:32 +00001786
1787LazyCallGraphDOTPrinterPass::LazyCallGraphDOTPrinterPass(raw_ostream &OS)
1788 : OS(OS) {}
1789
1790static void printNodeDOT(raw_ostream &OS, LazyCallGraph::Node &N) {
1791 std::string Name = "\"" + DOT::EscapeString(N.getFunction().getName()) + "\"";
1792
Chandler Carruthaaad9f82017-02-09 23:24:13 +00001793 for (LazyCallGraph::Edge &E : N.populate()) {
Sean Silva7cb30662016-06-18 09:17:32 +00001794 OS << " " << Name << " -> \""
1795 << DOT::EscapeString(E.getFunction().getName()) << "\"";
1796 if (!E.isCall()) // It is a ref edge.
1797 OS << " [style=dashed,label=\"ref\"]";
1798 OS << ";\n";
1799 }
1800
1801 OS << "\n";
1802}
1803
1804PreservedAnalyses LazyCallGraphDOTPrinterPass::run(Module &M,
1805 ModuleAnalysisManager &AM) {
1806 LazyCallGraph &G = AM.getResult<LazyCallGraphAnalysis>(M);
1807
1808 OS << "digraph \"" << DOT::EscapeString(M.getModuleIdentifier()) << "\" {\n";
1809
1810 for (Function &F : M)
1811 printNodeDOT(OS, G.get(F));
1812
1813 OS << "}\n";
1814
1815 return PreservedAnalyses::all();
1816}