LLVM 23.0.0git
LazyCallGraph.h
Go to the documentation of this file.
1//===- LazyCallGraph.h - Analysis of a Module's call graph ------*- C++ -*-===//
2//
3// 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
6//
7//===----------------------------------------------------------------------===//
8/// \file
9///
10/// Implements a lazy call graph analysis and related passes for the new pass
11/// manager.
12///
13/// NB: This is *not* a traditional call graph! It is a graph which models both
14/// the current calls and potential calls. As a consequence there are many
15/// edges in this call graph that do not correspond to a 'call' or 'invoke'
16/// instruction.
17///
18/// The primary use cases of this graph analysis is to facilitate iterating
19/// across the functions of a module in ways that ensure all callees are
20/// visited prior to a caller (given any SCC constraints), or vice versa. As
21/// such is it particularly well suited to organizing CGSCC optimizations such
22/// as inlining, outlining, argument promotion, etc. That is its primary use
23/// case and motivates the design. It may not be appropriate for other
24/// purposes. The use graph of functions or some other conservative analysis of
25/// call instructions may be interesting for optimizations and subsequent
26/// analyses which don't work in the context of an overly specified
27/// potential-call-edge graph.
28///
29/// To understand the specific rules and nature of this call graph analysis,
30/// see the documentation of the \c LazyCallGraph below.
31///
32//===----------------------------------------------------------------------===//
33
34#ifndef LLVM_ANALYSIS_LAZYCALLGRAPH_H
35#define LLVM_ANALYSIS_LAZYCALLGRAPH_H
36
37#include "llvm/ADT/Any.h"
38#include "llvm/ADT/ArrayRef.h"
39#include "llvm/ADT/DenseMap.h"
41#include "llvm/ADT/SetVector.h"
43#include "llvm/ADT/StringRef.h"
44#include "llvm/ADT/iterator.h"
47#include "llvm/IR/PassManager.h"
51#include <cassert>
52#include <iterator>
53#include <optional>
54#include <string>
55#include <utility>
56
57namespace llvm {
58
59class Constant;
60template <class GraphType> struct GraphTraits;
61class Module;
62
63/// A lazily constructed view of the call graph of a module.
64///
65/// With the edges of this graph, the motivating constraint that we are
66/// attempting to maintain is that function-local optimization, CGSCC-local
67/// optimizations, and optimizations transforming a pair of functions connected
68/// by an edge in the graph, do not invalidate a bottom-up traversal of the SCC
69/// DAG. That is, no optimizations will delete, remove, or add an edge such
70/// that functions already visited in a bottom-up order of the SCC DAG are no
71/// longer valid to have visited, or such that functions not yet visited in
72/// a bottom-up order of the SCC DAG are not required to have already been
73/// visited.
74///
75/// Within this constraint, the desire is to minimize the merge points of the
76/// SCC DAG. The greater the fanout of the SCC DAG and the fewer merge points
77/// in the SCC DAG, the more independence there is in optimizing within it.
78/// There is a strong desire to enable parallelization of optimizations over
79/// the call graph, and both limited fanout and merge points will (artificially
80/// in some cases) limit the scaling of such an effort.
81///
82/// To this end, graph represents both direct and any potential resolution to
83/// an indirect call edge. Another way to think about it is that it represents
84/// both the direct call edges and any direct call edges that might be formed
85/// through static optimizations. Specifically, it considers taking the address
86/// of a function to be an edge in the call graph because this might be
87/// forwarded to become a direct call by some subsequent function-local
88/// optimization. The result is that the graph closely follows the use-def
89/// edges for functions. Walking "up" the graph can be done by looking at all
90/// of the uses of a function.
91///
92/// The roots of the call graph are the external functions and functions
93/// escaped into global variables. Those functions can be called from outside
94/// of the module or via unknowable means in the IR -- we may not be able to
95/// form even a potential call edge from a function body which may dynamically
96/// load the function and call it.
97///
98/// This analysis still requires updates to remain valid after optimizations
99/// which could potentially change the set of potential callees. The
100/// constraints it operates under only make the traversal order remain valid.
101///
102/// The entire analysis must be re-computed if full interprocedural
103/// optimizations run at any point. For example, globalopt completely
104/// invalidates the information in this analysis.
105///
106/// FIXME: This class is named LazyCallGraph in a lame attempt to distinguish
107/// it from the existing CallGraph. At some point, it is expected that this
108/// will be the only call graph and it will be renamed accordingly.
110public:
111 class Node;
112 class EdgeSequence;
113 class RefSCC;
114
115 /// A class used to represent edges in the call graph.
116 ///
117 /// The lazy call graph models both *call* edges and *reference* edges. Call
118 /// edges are much what you would expect, and exist when there is a 'call' or
119 /// 'invoke' instruction of some function. Reference edges are also tracked
120 /// along side these, and exist whenever any instruction (transitively
121 /// through its operands) references a function. All call edges are
122 /// inherently reference edges, and so the reference graph forms a superset
123 /// of the formal call graph.
124 ///
125 /// All of these forms of edges are fundamentally represented as outgoing
126 /// edges. The edges are stored in the source node and point at the target
127 /// node. This allows the edge structure itself to be a very compact data
128 /// structure: essentially a tagged pointer.
129 class Edge {
130 public:
131 /// The kind of edge in the graph.
132 enum Kind : bool { Ref = false, Call = true };
133
135 explicit Edge(Node &N, Kind K);
136
137 /// Test whether the edge is null.
138 ///
139 /// This happens when an edge has been deleted. We leave the edge objects
140 /// around but clear them.
141 explicit operator bool() const;
142
143 /// Returns the \c Kind of the edge.
144 Kind getKind() const;
145
146 /// Test whether the edge represents a direct call to a function.
147 ///
148 /// This requires that the edge is not null.
149 bool isCall() const;
150
151 /// Get the call graph node referenced by this edge.
152 ///
153 /// This requires that the edge is not null.
154 Node &getNode() const;
155
156 /// Get the function referenced by this edge.
157 ///
158 /// This requires that the edge is not null.
159 Function &getFunction() const;
160
161 private:
164
166
167 void setKind(Kind K) { Value.setInt(K); }
168 };
169
170 /// The edge sequence object.
171 ///
172 /// This typically exists entirely within the node but is exposed as
173 /// a separate type because a node doesn't initially have edges. An explicit
174 /// population step is required to produce this sequence at first and it is
175 /// then cached in the node. It is also used to represent edges entering the
176 /// graph from outside the module to model the graph's roots.
177 ///
178 /// The sequence itself both iterable and indexable. The indexes remain
179 /// stable even as the sequence mutates (including removal).
180 class EdgeSequence {
181 friend class LazyCallGraph;
184
185 using VectorT = SmallVector<Edge, 4>;
186 using VectorImplT = SmallVectorImpl<Edge>;
187
188 public:
189 /// An iterator used for the edges to both entry nodes and child nodes.
190 class iterator
191 : public iterator_adaptor_base<iterator, VectorImplT::iterator,
192 std::forward_iterator_tag> {
193 friend class LazyCallGraph;
195
197
198 // Build the iterator for a specific position in the edge list.
200 : iterator_adaptor_base(BaseI), E(E) {
201 while (I != E && !*I)
202 ++I;
203 }
204
205 public:
206 iterator() = default;
207
208 using iterator_adaptor_base::operator++;
209 iterator &operator++() {
210 do {
211 ++I;
212 } while (I != E && !*I);
213 return *this;
214 }
215 };
216
217 /// An iterator over specifically call edges.
218 ///
219 /// This has the same iteration properties as the \c iterator, but
220 /// restricts itself to edges which represent actual calls.
221 class call_iterator
222 : public iterator_adaptor_base<call_iterator, VectorImplT::iterator,
223 std::forward_iterator_tag> {
224 friend class LazyCallGraph;
226
228
229 /// Advance the iterator to the next valid, call edge.
230 void advanceToNextEdge() {
231 while (I != E && (!*I || !I->isCall()))
232 ++I;
233 }
234
235 // Build the iterator for a specific position in the edge list.
237 : iterator_adaptor_base(BaseI), E(E) {
238 advanceToNextEdge();
239 }
240
241 public:
242 call_iterator() = default;
243
244 using iterator_adaptor_base::operator++;
245 call_iterator &operator++() {
246 ++I;
247 advanceToNextEdge();
248 return *this;
249 }
250 };
251
252 iterator begin() { return iterator(Edges.begin(), Edges.end()); }
253 iterator end() { return iterator(Edges.end(), Edges.end()); }
254
256 assert(EdgeIndexMap.contains(&N) && "No such edge!");
257 auto &E = Edges[EdgeIndexMap.find(&N)->second];
258 assert(E && "Dead or null edge!");
259 return E;
260 }
261
263 auto EI = EdgeIndexMap.find(&N);
264 if (EI == EdgeIndexMap.end())
265 return nullptr;
266 auto &E = Edges[EI->second];
267 return E ? &E : nullptr;
268 }
269
271 return call_iterator(Edges.begin(), Edges.end());
272 }
273 call_iterator call_end() { return call_iterator(Edges.end(), Edges.end()); }
274
278
279 bool empty() {
280 for (auto &E : Edges)
281 if (E)
282 return false;
283
284 return true;
285 }
286
287 private:
288 VectorT Edges;
289 DenseMap<Node *, int> EdgeIndexMap;
290
291 EdgeSequence() = default;
292
293 /// Internal helper to insert an edge to a node.
294 void insertEdgeInternal(Node &ChildN, Edge::Kind EK);
295
296 /// Internal helper to change an edge kind.
297 void setEdgeKind(Node &ChildN, Edge::Kind EK);
298
299 /// Internal helper to remove the edge to the given function.
300 bool removeEdgeInternal(Node &ChildN);
301 };
302
303 /// A node in the call graph.
304 ///
305 /// This represents a single node. Its primary roles are to cache the list of
306 /// callees, de-duplicate and provide fast testing of whether a function is a
307 /// callee, and facilitate iteration of child nodes in the graph.
308 ///
309 /// The node works much like an optional in order to lazily populate the
310 /// edges of each node. Until populated, there are no edges. Once populated,
311 /// you can access the edges by dereferencing the node or using the `->`
312 /// operator as if the node was an `std::optional<EdgeSequence>`.
313 class Node {
314 friend class LazyCallGraph;
316
317 public:
318 LazyCallGraph &getGraph() const { return *G; }
319
320 Function &getFunction() const { return *F; }
321
322 StringRef getName() const { return F->getName(); }
323
324 /// Equality is defined as address equality.
325 bool operator==(const Node &N) const { return this == &N; }
326 bool operator!=(const Node &N) const { return !operator==(N); }
327
328 /// Tests whether the node has been populated with edges.
329 bool isPopulated() const { return Edges.has_value(); }
330
331 /// Tests whether this is actually a dead node and no longer valid.
332 ///
333 /// Users rarely interact with nodes in this state and other methods are
334 /// invalid. This is used to model a node in an edge list where the
335 /// function has been completely removed.
336 bool isDead() const {
337 assert(!G == !F &&
338 "Both graph and function pointers should be null or non-null.");
339 return !G;
340 }
341
342 // We allow accessing the edges by dereferencing or using the arrow
343 // operator, essentially wrapping the internal optional.
345 // Rip const off because the node itself isn't changing here.
346 return const_cast<EdgeSequence &>(*Edges);
347 }
348 EdgeSequence *operator->() const { return &**this; }
349
350 /// Populate the edges of this node if necessary.
351 ///
352 /// The first time this is called it will populate the edges for this node
353 /// in the graph. It does this by scanning the underlying function, so once
354 /// this is done, any changes to that function must be explicitly reflected
355 /// in updates to the graph.
356 ///
357 /// \returns the populated \c EdgeSequence to simplify walking it.
358 ///
359 /// This will not update or re-scan anything if called repeatedly. Instead,
360 /// the edge sequence is cached and returned immediately on subsequent
361 /// calls.
363 if (Edges)
364 return *Edges;
365
366 return populateSlow();
367 }
368
369 private:
371 Function *F;
372
373 // We provide for the DFS numbering and Tarjan walk lowlink numbers to be
374 // stored directly within the node. These are both '-1' when nodes are part
375 // of an SCC (or RefSCC), or '0' when not yet reached in a DFS walk.
376 int DFSNumber = 0;
377 int LowLink = 0;
378
379 std::optional<EdgeSequence> Edges;
380
381 /// Basic constructor implements the scanning of F into Edges and
382 /// EdgeIndexMap.
383 Node(LazyCallGraph &G, Function &F) : G(&G), F(&F) {}
384
385 /// Implementation of the scan when populating.
386 LLVM_ABI EdgeSequence &populateSlow();
387
388 /// Internal helper to directly replace the function with a new one.
389 ///
390 /// This is used to facilitate transformations which need to replace the
391 /// formal Function object but directly move the body and users from one to
392 /// the other.
393 void replaceFunction(Function &NewF);
394
395 void clear() { Edges.reset(); }
396
397 /// Print the name of this node's function.
398 friend raw_ostream &operator<<(raw_ostream &OS, const Node &N) {
399 return OS << N.F->getName();
400 }
401
402 /// Dump the name of this node's function to stderr.
403 void dump() const;
404 };
405
406 /// An SCC of the call graph.
407 ///
408 /// This represents a Strongly Connected Component of the direct call graph
409 /// -- ignoring indirect calls and function references. It stores this as
410 /// a collection of call graph nodes. While the order of nodes in the SCC is
411 /// stable, it is not any particular order.
412 ///
413 /// The SCCs are nested within a \c RefSCC, see below for details about that
414 /// outer structure. SCCs do not support mutation of the call graph, that
415 /// must be done through the containing \c RefSCC in order to fully reason
416 /// about the ordering and connections of the graph.
417 class LLVM_ABI SCC {
418 friend class LazyCallGraph;
420
421 RefSCC *OuterRefSCC;
423
424 template <typename NodeRangeT>
425 SCC(RefSCC &OuterRefSCC, NodeRangeT &&Nodes)
426 : OuterRefSCC(&OuterRefSCC), Nodes(std::forward<NodeRangeT>(Nodes)) {}
427
428 void clear() {
429 OuterRefSCC = nullptr;
430 Nodes.clear();
431 }
432
433 /// Print a short description useful for debugging or logging.
434 ///
435 /// We print the function names in the SCC wrapped in '()'s and skipping
436 /// the middle functions if there are a large number.
437 //
438 // Note: this is defined inline to dodge issues with GCC's interpretation
439 // of enclosing namespaces for friend function declarations.
440 friend raw_ostream &operator<<(raw_ostream &OS, const SCC &C) {
441 OS << '(';
442 int I = 0;
443 for (LazyCallGraph::Node &N : C) {
444 if (I > 0)
445 OS << ", ";
446 // Elide the inner elements if there are too many.
447 if (I > 8) {
448 OS << "..., " << *C.Nodes.back();
449 break;
450 }
451 OS << N;
452 ++I;
453 }
454 OS << ')';
455 return OS;
456 }
457
458 /// Dump a short description of this SCC to stderr.
459 void dump() const;
460
461#if !defined(NDEBUG) || defined(EXPENSIVE_CHECKS)
462 /// Verify invariants about the SCC.
463 ///
464 /// This will attempt to validate all of the basic invariants within an
465 /// SCC, but not that it is a strongly connected component per se.
466 /// Primarily useful while building and updating the graph to check that
467 /// basic properties are in place rather than having inexplicable crashes
468 /// later.
469 void verify();
470#endif
471
472 public:
474
475 iterator begin() const { return Nodes.begin(); }
476 iterator end() const { return Nodes.end(); }
477
478 int size() const { return Nodes.size(); }
479
480 RefSCC &getOuterRefSCC() const { return *OuterRefSCC; }
481
482 /// Test if this SCC is a parent of \a C.
483 ///
484 /// Note that this is linear in the number of edges departing the current
485 /// SCC.
486 bool isParentOf(const SCC &C) const;
487
488 /// Test if this SCC is an ancestor of \a C.
489 ///
490 /// Note that in the worst case this is linear in the number of edges
491 /// departing the current SCC and every SCC in the entire graph reachable
492 /// from this SCC. Thus this very well may walk every edge in the entire
493 /// call graph! Do not call this in a tight loop!
494 bool isAncestorOf(const SCC &C) const;
495
496 /// Test if this SCC is a child of \a C.
497 ///
498 /// See the comments for \c isParentOf for detailed notes about the
499 /// complexity of this routine.
500 bool isChildOf(const SCC &C) const { return C.isParentOf(*this); }
501
502 /// Test if this SCC is a descendant of \a C.
503 ///
504 /// See the comments for \c isParentOf for detailed notes about the
505 /// complexity of this routine.
506 bool isDescendantOf(const SCC &C) const { return C.isAncestorOf(*this); }
507
508 /// Provide a short name by printing this SCC to a std::string.
509 ///
510 /// This copes with the fact that we don't have a name per se for an SCC
511 /// while still making the use of this in debugging and logging useful.
512 std::string getName() const {
513 std::string Name;
514 raw_string_ostream(Name) << *this;
515 return Name;
516 }
517 };
518
519 /// A RefSCC of the call graph.
520 ///
521 /// This models a Strongly Connected Component of function reference edges in
522 /// the call graph. As opposed to actual SCCs, these can be used to scope
523 /// subgraphs of the module which are independent from other subgraphs of the
524 /// module because they do not reference it in any way. This is also the unit
525 /// where we do mutation of the graph in order to restrict mutations to those
526 /// which don't violate this independence.
527 ///
528 /// A RefSCC contains a DAG of actual SCCs. All the nodes within the RefSCC
529 /// are necessarily within some actual SCC that nests within it. Since
530 /// a direct call *is* a reference, there will always be at least one RefSCC
531 /// around any SCC.
532 ///
533 /// Spurious ref edges, meaning ref edges that still exist in the call graph
534 /// even though the corresponding IR reference no longer exists, are allowed.
535 /// This is mostly to support argument promotion, which can modify a caller to
536 /// no longer pass a function. The only place that needs to specially handle
537 /// this is deleting a dead function/node, otherwise the dead ref edges are
538 /// automatically removed when visiting the function/node no longer containing
539 /// the ref edge.
540 class RefSCC {
541 friend class LazyCallGraph;
543
544 LazyCallGraph *G;
545
546 /// A postorder list of the inner SCCs.
548
549 /// A map from SCC to index in the postorder list.
551
552 /// Fast-path constructor. RefSCCs should instead be constructed by calling
553 /// formRefSCCFast on the graph itself.
554 RefSCC(LazyCallGraph &G);
555
556 void clear() {
557 SCCs.clear();
558 SCCIndices.clear();
559 }
560
561 /// Print a short description useful for debugging or logging.
562 ///
563 /// We print the SCCs wrapped in '[]'s and skipping the middle SCCs if
564 /// there are a large number.
565 //
566 // Note: this is defined inline to dodge issues with GCC's interpretation
567 // of enclosing namespaces for friend function declarations.
568 friend raw_ostream &operator<<(raw_ostream &OS, const RefSCC &RC) {
569 OS << '[';
570 int I = 0;
571 for (LazyCallGraph::SCC &C : RC) {
572 if (I > 0)
573 OS << ", ";
574 // Elide the inner elements if there are too many.
575 if (I > 4) {
576 OS << "..., " << *RC.SCCs.back();
577 break;
578 }
579 OS << C;
580 ++I;
581 }
582 OS << ']';
583 return OS;
584 }
585
586 /// Dump a short description of this RefSCC to stderr.
587 void dump() const;
588
589#if !defined(NDEBUG) || defined(EXPENSIVE_CHECKS)
590 /// Verify invariants about the RefSCC and all its SCCs.
591 ///
592 /// This will attempt to validate all of the invariants *within* the
593 /// RefSCC, but not that it is a strongly connected component of the larger
594 /// graph. This makes it useful even when partially through an update.
595 ///
596 /// Invariants checked:
597 /// - SCCs and their indices match.
598 /// - The SCCs list is in fact in post-order.
599 void verify();
600#endif
601
602 public:
607
608 iterator begin() const { return SCCs.begin(); }
609 iterator end() const { return SCCs.end(); }
610
611 ssize_t size() const { return SCCs.size(); }
612
613 SCC &operator[](int Idx) { return *SCCs[Idx]; }
614
615 iterator find(SCC &C) const {
616 return SCCs.begin() + SCCIndices.find(&C)->second;
617 }
618
619 /// Test if this RefSCC is a parent of \a RC.
620 ///
621 /// CAUTION: This method walks every edge in the \c RefSCC, it can be very
622 /// expensive.
623 LLVM_ABI bool isParentOf(const RefSCC &RC) const;
624
625 /// Test if this RefSCC is an ancestor of \a RC.
626 ///
627 /// CAUTION: This method walks the directed graph of edges as far as
628 /// necessary to find a possible path to the argument. In the worst case
629 /// this may walk the entire graph and can be extremely expensive.
630 LLVM_ABI bool isAncestorOf(const RefSCC &RC) const;
631
632 /// Test if this RefSCC is a child of \a RC.
633 ///
634 /// CAUTION: This method walks every edge in the argument \c RefSCC, it can
635 /// be very expensive.
636 bool isChildOf(const RefSCC &RC) const { return RC.isParentOf(*this); }
637
638 /// Test if this RefSCC is a descendant of \a RC.
639 ///
640 /// CAUTION: This method walks the directed graph of edges as far as
641 /// necessary to find a possible path from the argument. In the worst case
642 /// this may walk the entire graph and can be extremely expensive.
643 bool isDescendantOf(const RefSCC &RC) const {
644 return RC.isAncestorOf(*this);
645 }
646
647 /// Provide a short name by printing this RefSCC to a std::string.
648 ///
649 /// This copes with the fact that we don't have a name per se for an RefSCC
650 /// while still making the use of this in debugging and logging useful.
651 std::string getName() const {
652 std::string Name;
653 raw_string_ostream(Name) << *this;
654 return Name;
655 }
656
657 ///@{
658 /// \name Mutation API
659 ///
660 /// These methods provide the core API for updating the call graph in the
661 /// presence of (potentially still in-flight) DFS-found RefSCCs and SCCs.
662 ///
663 /// Note that these methods sometimes have complex runtimes, so be careful
664 /// how you call them.
665
666 /// Make an existing internal ref edge into a call edge.
667 ///
668 /// This may form a larger cycle and thus collapse SCCs into TargetN's SCC.
669 /// If that happens, the optional callback \p MergedCB will be invoked (if
670 /// provided) on the SCCs being merged away prior to actually performing
671 /// the merge. Note that this will never include the target SCC as that
672 /// will be the SCC functions are merged into to resolve the cycle. Once
673 /// this function returns, these merged SCCs are not in a valid state but
674 /// the pointers will remain valid until destruction of the parent graph
675 /// instance for the purpose of clearing cached information. This function
676 /// also returns 'true' if a cycle was formed and some SCCs merged away as
677 /// a convenience.
678 ///
679 /// After this operation, both SourceN's SCC and TargetN's SCC may move
680 /// position within this RefSCC's postorder list. Any SCCs merged are
681 /// merged into the TargetN's SCC in order to preserve reachability analyses
682 /// which took place on that SCC.
684 Node &SourceN, Node &TargetN,
685 function_ref<void(ArrayRef<SCC *> MergedSCCs)> MergeCB = {});
686
687 /// Make an existing internal call edge between separate SCCs into a ref
688 /// edge.
689 ///
690 /// If SourceN and TargetN in separate SCCs within this RefSCC, changing
691 /// the call edge between them to a ref edge is a trivial operation that
692 /// does not require any structural changes to the call graph.
693 LLVM_ABI void switchTrivialInternalEdgeToRef(Node &SourceN, Node &TargetN);
694
695 /// Make an existing internal call edge within a single SCC into a ref
696 /// edge.
697 ///
698 /// Since SourceN and TargetN are part of a single SCC, this SCC may be
699 /// split up due to breaking a cycle in the call edges that formed it. If
700 /// that happens, then this routine will insert new SCCs into the postorder
701 /// list *before* the SCC of TargetN (previously the SCC of both). This
702 /// preserves postorder as the TargetN can reach all of the other nodes by
703 /// definition of previously being in a single SCC formed by the cycle from
704 /// SourceN to TargetN.
705 ///
706 /// The newly added SCCs are added *immediately* and contiguously
707 /// prior to the TargetN SCC and return the range covering the new SCCs in
708 /// the RefSCC's postorder sequence. You can directly iterate the returned
709 /// range to observe all of the new SCCs in postorder.
710 ///
711 /// Note that if SourceN and TargetN are in separate SCCs, the simpler
712 /// routine `switchTrivialInternalEdgeToRef` should be used instead.
714 Node &TargetN);
715
716 /// Make an existing outgoing ref edge into a call edge.
717 ///
718 /// Note that this is trivial as there are no cyclic impacts and there
719 /// remains a reference edge.
720 LLVM_ABI void switchOutgoingEdgeToCall(Node &SourceN, Node &TargetN);
721
722 /// Make an existing outgoing call edge into a ref edge.
723 ///
724 /// This is trivial as there are no cyclic impacts and there remains
725 /// a reference edge.
726 LLVM_ABI void switchOutgoingEdgeToRef(Node &SourceN, Node &TargetN);
727
728 /// Insert a ref edge from one node in this RefSCC to another in this
729 /// RefSCC.
730 ///
731 /// This is always a trivial operation as it doesn't change any part of the
732 /// graph structure besides connecting the two nodes.
733 ///
734 /// Note that we don't support directly inserting internal *call* edges
735 /// because that could change the graph structure and requires returning
736 /// information about what became invalid. As a consequence, the pattern
737 /// should be to first insert the necessary ref edge, and then to switch it
738 /// to a call edge if needed and handle any invalidation that results. See
739 /// the \c switchInternalEdgeToCall routine for details.
740 LLVM_ABI void insertInternalRefEdge(Node &SourceN, Node &TargetN);
741
742 /// Insert an edge whose parent is in this RefSCC and child is in some
743 /// child RefSCC.
744 ///
745 /// There must be an existing path from the \p SourceN to the \p TargetN.
746 /// This operation is inexpensive and does not change the set of SCCs and
747 /// RefSCCs in the graph.
748 LLVM_ABI void insertOutgoingEdge(Node &SourceN, Node &TargetN,
749 Edge::Kind EK);
750
751 /// Insert an edge whose source is in a descendant RefSCC and target is in
752 /// this RefSCC.
753 ///
754 /// There must be an existing path from the target to the source in this
755 /// case.
756 ///
757 /// NB! This is has the potential to be a very expensive function. It
758 /// inherently forms a cycle in the prior RefSCC DAG and we have to merge
759 /// RefSCCs to resolve that cycle. But finding all of the RefSCCs which
760 /// participate in the cycle can in the worst case require traversing every
761 /// RefSCC in the graph. Every attempt is made to avoid that, but passes
762 /// must still exercise caution calling this routine repeatedly.
763 ///
764 /// Also note that this can only insert ref edges. In order to insert
765 /// a call edge, first insert a ref edge and then switch it to a call edge.
766 /// These are intentionally kept as separate interfaces because each step
767 /// of the operation invalidates a different set of data structures.
768 ///
769 /// This returns all the RefSCCs which were merged into the this RefSCC
770 /// (the target's). This allows callers to invalidate any cached
771 /// information.
772 ///
773 /// FIXME: We could possibly optimize this quite a bit for cases where the
774 /// caller and callee are very nearby in the graph. See comments in the
775 /// implementation for details, but that use case might impact users.
777 Node &TargetN);
778
779 /// Remove an edge whose source is in this RefSCC and target is *not*.
780 ///
781 /// This removes an inter-RefSCC edge. All inter-RefSCC edges originating
782 /// from this SCC have been fully explored by any in-flight DFS graph
783 /// formation, so this is always safe to call once you have the source
784 /// RefSCC.
785 ///
786 /// This operation does not change the cyclic structure of the graph and so
787 /// is very inexpensive. It may change the connectivity graph of the SCCs
788 /// though, so be careful calling this while iterating over them.
789 LLVM_ABI void removeOutgoingEdge(Node &SourceN, Node &TargetN);
790
791 /// Remove a list of ref edges which are entirely within this RefSCC.
792 ///
793 /// Both the \a SourceN and all of the \a TargetNs must be within this
794 /// RefSCC. Removing these edges may break cycles that form this RefSCC and
795 /// thus this operation may change the RefSCC graph significantly. In
796 /// particular, this operation will re-form new RefSCCs based on the
797 /// remaining connectivity of the graph. The following invariants are
798 /// guaranteed to hold after calling this method:
799 ///
800 /// 1) If a ref-cycle remains after removal, it leaves this RefSCC intact
801 /// and in the graph. No new RefSCCs are built.
802 /// 2) Otherwise, this RefSCC will be dead after this call and no longer in
803 /// the graph or the postorder traversal of the call graph. Any iterator
804 /// pointing at this RefSCC will become invalid.
805 /// 3) All newly formed RefSCCs will be returned and the order of the
806 /// RefSCCs returned will be a valid postorder traversal of the new
807 /// RefSCCs.
808 /// 4) No RefSCC other than this RefSCC has its member set changed (this is
809 /// inherent in the definition of removing such an edge).
810 ///
811 /// These invariants are very important to ensure that we can build
812 /// optimization pipelines on top of the CGSCC pass manager which
813 /// intelligently update the RefSCC graph without invalidating other parts
814 /// of the RefSCC graph.
815 ///
816 /// Note that we provide no routine to remove a *call* edge. Instead, you
817 /// must first switch it to a ref edge using \c switchInternalEdgeToRef.
818 /// This split API is intentional as each of these two steps can invalidate
819 /// a different aspect of the graph structure and needs to have the
820 /// invalidation handled independently.
821 ///
822 /// The runtime complexity of this method is, in the worst case, O(V+E)
823 /// where V is the number of nodes in this RefSCC and E is the number of
824 /// edges leaving the nodes in this RefSCC. Note that E includes both edges
825 /// within this RefSCC and edges from this RefSCC to child RefSCCs. Some
826 /// effort has been made to minimize the overhead of common cases such as
827 /// self-edges and edge removals which result in a spanning tree with no
828 /// more cycles.
830 removeInternalRefEdges(ArrayRef<std::pair<Node *, Node *>> Edges);
831
832 /// A convenience wrapper around the above to handle trivial cases of
833 /// inserting a new call edge.
834 ///
835 /// This is trivial whenever the target is in the same SCC as the source or
836 /// the edge is an outgoing edge to some descendant SCC. In these cases
837 /// there is no change to the cyclic structure of SCCs or RefSCCs.
838 ///
839 /// To further make calling this convenient, it also handles inserting
840 /// already existing edges.
841 LLVM_ABI void insertTrivialCallEdge(Node &SourceN, Node &TargetN);
842
843 /// A convenience wrapper around the above to handle trivial cases of
844 /// inserting a new ref edge.
845 ///
846 /// This is trivial whenever the target is in the same RefSCC as the source
847 /// or the edge is an outgoing edge to some descendant RefSCC. In these
848 /// cases there is no change to the cyclic structure of the RefSCCs.
849 ///
850 /// To further make calling this convenient, it also handles inserting
851 /// already existing edges.
852 LLVM_ABI void insertTrivialRefEdge(Node &SourceN, Node &TargetN);
853
854 /// Directly replace a node's function with a new function.
855 ///
856 /// This should be used when moving the body and users of a function to
857 /// a new formal function object but not otherwise changing the call graph
858 /// structure in any way.
859 ///
860 /// It requires that the old function in the provided node have zero uses
861 /// and the new function must have calls and references to it establishing
862 /// an equivalent graph.
864
865 ///@}
866 };
867
868 /// A post-order depth-first RefSCC iterator over the call graph.
869 ///
870 /// This iterator walks the cached post-order sequence of RefSCCs. However,
871 /// it trades stability for flexibility. It is restricted to a forward
872 /// iterator but will survive mutations which insert new RefSCCs and continue
873 /// to point to the same RefSCC even if it moves in the post-order sequence.
874 class postorder_ref_scc_iterator
875 : public iterator_facade_base<postorder_ref_scc_iterator,
876 std::forward_iterator_tag, RefSCC> {
877 friend class LazyCallGraph;
879
880 /// Nonce type to select the constructor for the end iterator.
881 struct IsAtEndT {};
882
884 RefSCC *RC = nullptr;
885
886 /// Build the begin iterator for a node.
887 postorder_ref_scc_iterator(LazyCallGraph &G) : G(&G), RC(getRC(G, 0)) {
888 incrementUntilNonEmptyRefSCC();
889 }
890
891 /// Build the end iterator for a node. This is selected purely by overload.
892 postorder_ref_scc_iterator(LazyCallGraph &G, IsAtEndT /*Nonce*/) : G(&G) {}
893
894 /// Get the post-order RefSCC at the given index of the postorder walk,
895 /// populating it if necessary.
896 static RefSCC *getRC(LazyCallGraph &G, int Index) {
897 if (Index == (int)G.PostOrderRefSCCs.size())
898 // We're at the end.
899 return nullptr;
900
901 return G.PostOrderRefSCCs[Index];
902 }
903
904 // Keep incrementing until RC is non-empty (or null).
905 void incrementUntilNonEmptyRefSCC() {
906 while (RC && RC->size() == 0)
907 increment();
908 }
909
910 void increment() {
911 assert(RC && "Cannot increment the end iterator!");
912 RC = getRC(*G, G->RefSCCIndices.find(RC)->second + 1);
913 }
914
915 public:
916 bool operator==(const postorder_ref_scc_iterator &Arg) const {
917 return G == Arg.G && RC == Arg.RC;
918 }
919
920 reference operator*() const { return *RC; }
921
922 using iterator_facade_base::operator++;
923 postorder_ref_scc_iterator &operator++() {
924 increment();
925 incrementUntilNonEmptyRefSCC();
926 return *this;
927 }
928 };
929
930 /// Construct a graph for the given module.
931 ///
932 /// This sets up the graph and computes all of the entry points of the graph.
933 /// No function definitions are scanned until their nodes in the graph are
934 /// requested during traversal.
937
940
941#if !defined(NDEBUG) || defined(EXPENSIVE_CHECKS)
942 /// Verify that every RefSCC is valid.
943 void verify();
944#endif
945
947 ModuleAnalysisManager::Invalidator &);
948
949 EdgeSequence::iterator begin() { return EntryEdges.begin(); }
950 EdgeSequence::iterator end() { return EntryEdges.end(); }
951
952 LLVM_ABI void buildRefSCCs();
953
955 if (!EntryEdges.empty())
956 assert(!PostOrderRefSCCs.empty() &&
957 "Must form RefSCCs before iterating them!");
958 return postorder_ref_scc_iterator(*this);
959 }
961 if (!EntryEdges.empty())
962 assert(!PostOrderRefSCCs.empty() &&
963 "Must form RefSCCs before iterating them!");
964 return postorder_ref_scc_iterator(*this,
965 postorder_ref_scc_iterator::IsAtEndT());
966 }
967
971
972 /// Lookup a function in the graph which has already been scanned and added.
973 Node *lookup(const Function &F) const { return NodeMap.lookup(&F); }
974
975 /// Lookup a function's SCC in the graph.
976 ///
977 /// \returns null if the function hasn't been assigned an SCC via the RefSCC
978 /// iterator walk.
979 SCC *lookupSCC(Node &N) const { return SCCMap.lookup(&N); }
980
981 /// Lookup a function's RefSCC in the graph.
982 ///
983 /// \returns null if the function hasn't been assigned a RefSCC via the
984 /// RefSCC iterator walk.
986 if (SCC *C = lookupSCC(N))
987 return &C->getOuterRefSCC();
988
989 return nullptr;
990 }
991
992 /// Get a graph node for a given function, scanning it to populate the graph
993 /// data as necessary.
995 Node *&N = NodeMap[&F];
996 if (N)
997 return *N;
998
999 return insertInto(F, N);
1000 }
1001
1002 /// Get the sequence of known and defined library functions.
1003 ///
1004 /// These functions, because they are known to LLVM, can have calls
1005 /// introduced out of thin air from arbitrary IR.
1007 return LibFunctions.getArrayRef();
1008 }
1009
1010 /// Test whether a function is a known and defined library function tracked by
1011 /// the call graph.
1012 ///
1013 /// Because these functions are known to LLVM they are specially modeled in
1014 /// the call graph and even when all IR-level references have been removed
1015 /// remain active and reachable.
1016 bool isLibFunction(Function &F) const { return LibFunctions.count(&F); }
1017
1018 ///@{
1019 /// \name Pre-SCC Mutation API
1020 ///
1021 /// These methods are only valid to call prior to forming any SCCs for this
1022 /// call graph. They can be used to update the core node-graph during
1023 /// a node-based inorder traversal that precedes any SCC-based traversal.
1024 ///
1025 /// Once you begin manipulating a call graph's SCCs, most mutation of the
1026 /// graph must be performed via a RefSCC method. There are some exceptions
1027 /// below.
1028
1029 /// Update the call graph after inserting a new edge.
1030 LLVM_ABI void insertEdge(Node &SourceN, Node &TargetN, Edge::Kind EK);
1031
1032 /// Update the call graph after inserting a new edge.
1033 void insertEdge(Function &Source, Function &Target, Edge::Kind EK) {
1034 return insertEdge(get(Source), get(Target), EK);
1035 }
1036
1037 /// Update the call graph after deleting an edge.
1038 LLVM_ABI void removeEdge(Node &SourceN, Node &TargetN);
1039
1040 /// Update the call graph after deleting an edge.
1042 return removeEdge(get(Source), get(Target));
1043 }
1044
1045 ///@}
1046
1047 ///@{
1048 /// \name General Mutation API
1049 ///
1050 /// There are a very limited set of mutations allowed on the graph as a whole
1051 /// once SCCs have started to be formed. These routines have strict contracts
1052 /// but may be called at any point.
1053
1054 /// Remove dead functions from the call graph.
1055 ///
1056 /// These functions should have already been passed to markDeadFunction().
1057 /// This is done as a batch to prevent compile time blowup as a result of
1058 /// handling a single function at a time.
1060
1061 /// Mark a function as dead to be removed later by removeDeadFunctions().
1062 ///
1063 /// The function body should have no incoming or outgoing call or ref edges.
1064 /// For example, a function with a single "unreachable" instruction.
1066
1067 /// Add a new function split/outlined from an existing function.
1068 ///
1069 /// The new function may only reference other functions that the original
1070 /// function did.
1071 ///
1072 /// The original function must reference (either directly or indirectly) the
1073 /// new function.
1074 ///
1075 /// The new function may also reference the original function.
1076 /// It may end up in a parent SCC in the case that the original function's
1077 /// edge to the new function is a ref edge, and the edge back is a call edge.
1078 LLVM_ABI void addSplitFunction(Function &OriginalFunction,
1079 Function &NewFunction);
1080
1081 /// Add new ref-recursive functions split/outlined from an existing function.
1082 ///
1083 /// The new functions may only reference other functions that the original
1084 /// function did. The new functions may reference (not call) the original
1085 /// function.
1086 ///
1087 /// The original function must reference (not call) all new functions.
1088 /// All new functions must reference (not call) each other.
1089 LLVM_ABI void
1090 addSplitRefRecursiveFunctions(Function &OriginalFunction,
1091 ArrayRef<Function *> NewFunctions);
1092
1093 ///@}
1094
1095 ///@{
1096 /// \name Static helpers for code doing updates to the call graph.
1097 ///
1098 /// These helpers are used to implement parts of the call graph but are also
1099 /// useful to code doing updates or otherwise wanting to walk the IR in the
1100 /// same patterns as when we build the call graph.
1101
1102 /// Recursively visits the defined functions whose address is reachable from
1103 /// every constant in the \p Worklist.
1104 ///
1105 /// Doesn't recurse through any constants already in the \p Visited set, and
1106 /// updates that set with every constant visited.
1107 ///
1108 /// For each defined function, calls \p Callback with that function.
1111 function_ref<void(Function &)> Callback);
1112
1113 ///@}
1114
1115private:
1116 using node_stack_iterator = SmallVectorImpl<Node *>::reverse_iterator;
1117 using node_stack_range = iterator_range<node_stack_iterator>;
1118
1119 /// Allocator that holds all the call graph nodes.
1121
1122 /// Maps function->node for fast lookup.
1124
1125 /// The entry edges into the graph.
1126 ///
1127 /// These edges are from "external" sources. Put another way, they
1128 /// escape at the module scope.
1129 EdgeSequence EntryEdges;
1130
1131 /// Allocator that holds all the call graph SCCs.
1133
1134 /// Maps Function -> SCC for fast lookup.
1136
1137 /// Allocator that holds all the call graph RefSCCs.
1139
1140 /// The post-order sequence of RefSCCs.
1141 ///
1142 /// This list is lazily formed the first time we walk the graph.
1143 SmallVector<RefSCC *, 16> PostOrderRefSCCs;
1144
1145 /// A map from RefSCC to the index for it in the postorder sequence of
1146 /// RefSCCs.
1147 DenseMap<RefSCC *, int> RefSCCIndices;
1148
1149 /// Defined functions that are also known library functions which the
1150 /// optimizer can reason about and therefore might introduce calls to out of
1151 /// thin air.
1152 SmallSetVector<Function *, 4> LibFunctions;
1153
1154 /// Helper to insert a new function, with an already looked-up entry in
1155 /// the NodeMap.
1156 LLVM_ABI Node &insertInto(Function &F, Node *&MappedN);
1157
1158 /// Helper to initialize a new node created outside of creating SCCs and add
1159 /// it to the NodeMap if necessary. For example, useful when a function is
1160 /// split.
1161 Node &initNode(Function &F);
1162
1163 /// Helper to update pointers back to the graph object during moves.
1164 void updateGraphPtrs();
1165
1166 /// Allocates an SCC and constructs it using the graph allocator.
1167 ///
1168 /// The arguments are forwarded to the constructor.
1169 template <typename... Ts> SCC *createSCC(Ts &&...Args) {
1170 return new (SCCBPA.Allocate()) SCC(std::forward<Ts>(Args)...);
1171 }
1172
1173 /// Allocates a RefSCC and constructs it using the graph allocator.
1174 ///
1175 /// The arguments are forwarded to the constructor.
1176 template <typename... Ts> RefSCC *createRefSCC(Ts &&...Args) {
1177 return new (RefSCCBPA.Allocate()) RefSCC(std::forward<Ts>(Args)...);
1178 }
1179
1180 /// Common logic for building SCCs from a sequence of roots.
1181 ///
1182 /// This is a very generic implementation of the depth-first walk and SCC
1183 /// formation algorithm. It uses a generic sequence of roots and generic
1184 /// callbacks for each step. This is designed to be used to implement both
1185 /// the RefSCC formation and SCC formation with shared logic.
1186 ///
1187 /// Currently this is a relatively naive implementation of Tarjan's DFS
1188 /// algorithm to form the SCCs.
1189 ///
1190 /// FIXME: We should consider newer variants such as Nuutila.
1191 template <typename RootsT, typename GetBeginT, typename GetEndT,
1192 typename GetNodeT, typename FormSCCCallbackT>
1193 static void buildGenericSCCs(RootsT &&Roots, GetBeginT &&GetBegin,
1194 GetEndT &&GetEnd, GetNodeT &&GetNode,
1195 FormSCCCallbackT &&FormSCC);
1196
1197 /// Build the SCCs for a RefSCC out of a list of nodes.
1198 void buildSCCs(RefSCC &RC, node_stack_range Nodes);
1199
1200 /// Get the index of a RefSCC within the postorder traversal.
1201 ///
1202 /// Requires that this RefSCC is a valid one in the (perhaps partial)
1203 /// postorder traversed part of the graph.
1204 int getRefSCCIndex(RefSCC &RC) {
1205 auto IndexIt = RefSCCIndices.find(&RC);
1206 assert(IndexIt != RefSCCIndices.end() && "RefSCC doesn't have an index!");
1207 assert(PostOrderRefSCCs[IndexIt->second] == &RC &&
1208 "Index does not point back at RC!");
1209 return IndexIt->second;
1210 }
1211};
1212
1213inline LazyCallGraph::Edge::Edge() = default;
1214inline LazyCallGraph::Edge::Edge(Node &N, Kind K) : Value(&N, K) {}
1215
1216inline LazyCallGraph::Edge::operator bool() const {
1217 return Value.getPointer() && !Value.getPointer()->isDead();
1218}
1219
1220inline LazyCallGraph::Edge::Kind LazyCallGraph::Edge::getKind() const {
1221 assert(*this && "Queried a null edge!");
1222 return Value.getInt();
1223}
1224
1225inline bool LazyCallGraph::Edge::isCall() const {
1226 assert(*this && "Queried a null edge!");
1227 return getKind() == Call;
1228}
1229
1230inline LazyCallGraph::Node &LazyCallGraph::Edge::getNode() const {
1231 assert(*this && "Queried a null edge!");
1232 return *Value.getPointer();
1233}
1234
1235inline Function &LazyCallGraph::Edge::getFunction() const {
1236 assert(*this && "Queried a null edge!");
1237 return getNode().getFunction();
1238}
1239
1240// Provide GraphTraits specializations for call graphs.
1241template <> struct GraphTraits<LazyCallGraph::Node *> {
1244
1245 static NodeRef getEntryNode(NodeRef N) { return N; }
1246 static ChildIteratorType child_begin(NodeRef N) { return (*N)->begin(); }
1247 static ChildIteratorType child_end(NodeRef N) { return (*N)->end(); }
1248};
1249template <> struct GraphTraits<LazyCallGraph *> {
1252
1253 static NodeRef getEntryNode(NodeRef N) { return N; }
1254 static ChildIteratorType child_begin(NodeRef N) { return (*N)->begin(); }
1255 static ChildIteratorType child_end(NodeRef N) { return (*N)->end(); }
1256};
1257
1258/// An analysis pass which computes the call graph for a module.
1259class LazyCallGraphAnalysis : public AnalysisInfoMixin<LazyCallGraphAnalysis> {
1261
1262 LLVM_ABI static AnalysisKey Key;
1263
1264public:
1265 /// Inform generic clients of the result type.
1267
1268 /// Compute the \c LazyCallGraph for the module \c M.
1269 ///
1270 /// This just builds the set of entry points to the call graph. The rest is
1271 /// built lazily as it is walked.
1275 auto GetTLI = [&FAM](Function &F) -> TargetLibraryInfo & {
1276 return FAM.getResult<TargetLibraryAnalysis>(F);
1277 };
1278 return LazyCallGraph(M, GetTLI);
1279 }
1280};
1281
1282/// A pass which prints the call graph to a \c raw_ostream.
1283///
1284/// This is primarily useful for testing the analysis.
1286 : public PassInfoMixin<LazyCallGraphPrinterPass> {
1287 raw_ostream &OS;
1288
1289public:
1291
1293
1294 static bool isRequired() { return true; }
1295};
1296
1297/// A pass which prints the call graph as a DOT file to a \c raw_ostream.
1298///
1299/// This is primarily useful for visualization purposes.
1301 : public PassInfoMixin<LazyCallGraphDOTPrinterPass> {
1302 raw_ostream &OS;
1303
1304public:
1306
1308
1309 static bool isRequired() { return true; }
1310};
1311
1312extern template struct LLVM_TEMPLATE_ABI
1313 Any::TypeId<const LazyCallGraph::SCC *>;
1314} // end namespace llvm
1315
1316#endif // LLVM_ANALYSIS_LAZYCALLGRAPH_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static msgpack::DocNode getNode(msgpack::DocNode DN, msgpack::Type Type, MCValue Val)
This file defines the BumpPtrAllocator interface.
This file provides Any, a non-template class modeled in the spirit of std::any.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define LLVM_ABI
Definition Compiler.h:213
#define LLVM_TEMPLATE_ABI
Definition Compiler.h:214
This file defines the DenseMap class.
This header defines various interfaces for pass management in LLVM.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define G(x, y, z)
Definition MD5.cpp:55
ppc ctr loops verify
FunctionAnalysisManager FAM
This file defines the PointerIntPair class.
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallVector class.
Value * RHS
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
This is an important base class in LLVM.
Definition Constant.h:43
An analysis pass which computes the call graph for a module.
LazyCallGraph run(Module &M, ModuleAnalysisManager &AM)
Compute the LazyCallGraph for the module M.
LazyCallGraph Result
Inform generic clients of the result type.
LLVM_ABI LazyCallGraphDOTPrinterPass(raw_ostream &OS)
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
LLVM_ABI LazyCallGraphPrinterPass(raw_ostream &OS)
An iterator over specifically call edges.
An iterator used for the edges to both entry nodes and child nodes.
The edge sequence object.
friend class LazyCallGraph::Node
iterator_range< call_iterator > calls()
A class used to represent edges in the call graph.
Function & getFunction() const
Get the function referenced by this edge.
bool isCall() const
Test whether the edge represents a direct call to a function.
Kind
The kind of edge in the graph.
Kind getKind() const
Returns the Kind of the edge.
Node & getNode() const
Get the call graph node referenced by this edge.
A node in the call graph.
LazyCallGraph & getGraph() const
EdgeSequence & populate()
Populate the edges of this node if necessary.
bool isDead() const
Tests whether this is actually a dead node and no longer valid.
bool operator!=(const Node &N) const
bool isPopulated() const
Tests whether the node has been populated with edges.
bool operator==(const Node &N) const
Equality is defined as address equality.
friend raw_ostream & operator<<(raw_ostream &OS, const Node &N)
Print the name of this node's function.
EdgeSequence * operator->() const
StringRef getName() const
EdgeSequence & operator*() const
Function & getFunction() const
A RefSCC of the call graph.
LLVM_ABI SmallVector< RefSCC *, 1 > insertIncomingRefEdge(Node &SourceN, Node &TargetN)
Insert an edge whose source is in a descendant RefSCC and target is in this RefSCC.
LLVM_ABI bool switchInternalEdgeToCall(Node &SourceN, Node &TargetN, function_ref< void(ArrayRef< SCC * > MergedSCCs)> MergeCB={})
Make an existing internal ref edge into a call edge.
LLVM_ABI bool isAncestorOf(const RefSCC &RC) const
Test if this RefSCC is an ancestor of RC.
LLVM_ABI void insertTrivialRefEdge(Node &SourceN, Node &TargetN)
A convenience wrapper around the above to handle trivial cases of inserting a new ref edge.
iterator find(SCC &C) const
bool isDescendantOf(const RefSCC &RC) const
Test if this RefSCC is a descendant of RC.
bool isChildOf(const RefSCC &RC) const
Test if this RefSCC is a child of RC.
LLVM_ABI void switchOutgoingEdgeToCall(Node &SourceN, Node &TargetN)
Make an existing outgoing ref edge into a call edge.
iterator_range< iterator > range
LLVM_ABI void replaceNodeFunction(Node &N, Function &NewF)
Directly replace a node's function with a new function.
LLVM_ABI void insertOutgoingEdge(Node &SourceN, Node &TargetN, Edge::Kind EK)
Insert an edge whose parent is in this RefSCC and child is in some child RefSCC.
LLVM_ABI SmallVector< RefSCC *, 1 > removeInternalRefEdges(ArrayRef< std::pair< Node *, Node * > > Edges)
Remove a list of ref edges which are entirely within this RefSCC.
LLVM_ABI iterator_range< iterator > switchInternalEdgeToRef(Node &SourceN, Node &TargetN)
Make an existing internal call edge within a single SCC into a ref edge.
LLVM_ABI void insertInternalRefEdge(Node &SourceN, Node &TargetN)
Insert a ref edge from one node in this RefSCC to another in this RefSCC.
LLVM_ABI void insertTrivialCallEdge(Node &SourceN, Node &TargetN)
A convenience wrapper around the above to handle trivial cases of inserting a new call edge.
LLVM_ABI void removeOutgoingEdge(Node &SourceN, Node &TargetN)
Remove an edge whose source is in this RefSCC and target is not.
std::string getName() const
Provide a short name by printing this RefSCC to a std::string.
pointee_iterator< SmallVectorImpl< SCC * >::const_iterator > iterator
pointee_iterator< SmallPtrSetImpl< RefSCC * >::const_iterator > parent_iterator
LLVM_ABI void switchOutgoingEdgeToRef(Node &SourceN, Node &TargetN)
Make an existing outgoing call edge into a ref edge.
friend raw_ostream & operator<<(raw_ostream &OS, const RefSCC &RC)
Print a short description useful for debugging or logging.
LLVM_ABI void switchTrivialInternalEdgeToRef(Node &SourceN, Node &TargetN)
Make an existing internal call edge between separate SCCs into a ref edge.
LLVM_ABI bool isParentOf(const RefSCC &RC) const
Test if this RefSCC is a parent of RC.
An SCC of the call graph.
pointee_iterator< SmallVectorImpl< Node * >::const_iterator > iterator
bool isChildOf(const SCC &C) const
Test if this SCC is a child of C.
friend raw_ostream & operator<<(raw_ostream &OS, const SCC &C)
Print a short description useful for debugging or logging.
bool isDescendantOf(const SCC &C) const
Test if this SCC is a descendant of C.
std::string getName() const
Provide a short name by printing this SCC to a std::string.
RefSCC & getOuterRefSCC() const
A post-order depth-first RefSCC iterator over the call graph.
postorder_ref_scc_iterator & operator++()
bool operator==(const postorder_ref_scc_iterator &Arg) const
A lazily constructed view of the call graph of a module.
bool isLibFunction(Function &F) const
Test whether a function is a known and defined library function tracked by the call graph.
EdgeSequence::iterator begin()
RefSCC * lookupRefSCC(Node &N) const
Lookup a function's RefSCC in the graph.
LLVM_ABI void insertEdge(Node &SourceN, Node &TargetN, Edge::Kind EK)
Update the call graph after inserting a new edge.
LLVM_ABI LazyCallGraph(Module &M, function_ref< TargetLibraryInfo &(Function &)> GetTLI)
Construct a graph for the given module.
LLVM_ABI void buildRefSCCs()
static LLVM_ABI void visitReferences(SmallVectorImpl< Constant * > &Worklist, SmallPtrSetImpl< Constant * > &Visited, function_ref< void(Function &)> Callback)
Recursively visits the defined functions whose address is reachable from every constant in the Workli...
LLVM_ABI void markDeadFunction(Function &F)
Mark a function as dead to be removed later by removeDeadFunctions().
LLVM_ABI void addSplitFunction(Function &OriginalFunction, Function &NewFunction)
Add a new function split/outlined from an existing function.
LLVM_ABI void addSplitRefRecursiveFunctions(Function &OriginalFunction, ArrayRef< Function * > NewFunctions)
Add new ref-recursive functions split/outlined from an existing function.
LLVM_ABI void removeDeadFunctions(ArrayRef< Function * > DeadFs)
Remove dead functions from the call graph.
postorder_ref_scc_iterator postorder_ref_scc_begin()
ArrayRef< Function * > getLibFunctions() const
Get the sequence of known and defined library functions.
postorder_ref_scc_iterator postorder_ref_scc_end()
LLVM_ABI void removeEdge(Node &SourceN, Node &TargetN)
Update the call graph after deleting an edge.
void removeEdge(Function &Source, Function &Target)
Update the call graph after deleting an edge.
void insertEdge(Function &Source, Function &Target, Edge::Kind EK)
Update the call graph after inserting a new edge.
Node & get(Function &F)
Get a graph node for a given function, scanning it to populate the graph data as necessary.
SCC * lookupSCC(Node &N) const
Lookup a function's SCC in the graph.
iterator_range< postorder_ref_scc_iterator > postorder_ref_sccs()
LLVM_ABI LazyCallGraph & operator=(LazyCallGraph &&RHS)
LLVM_ABI bool invalidate(Module &, const PreservedAnalyses &PA, ModuleAnalysisManager::Invalidator &)
void verify()
Verify that every RefSCC is valid.
EdgeSequence::iterator end()
Node * lookup(const Function &F) const
Lookup a function in the graph which has already been scanned and added.
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
PointerIntPair - This class implements a pair of a pointer and small integer.
void setInt(IntType IntVal) &
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
A SetVector that performs no allocations if smaller than a certain size.
Definition SetVector.h:339
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
typename SuperClass::iterator iterator
std::reverse_iterator< iterator > reverse_iterator
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
A BumpPtrAllocator that allows only elements of a specific type to be allocated.
Definition Allocator.h:390
T * Allocate(size_t num=1)
Allocate space for an array of objects without constructing them.
Definition Allocator.h:440
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
Analysis pass providing the TargetLibraryInfo.
Provides information about what library functions are available for the current target.
Target - Wrapper for Target specific information.
An efficient, type-erasing, non-owning reference to a callable.
CRTP base class for adapting an iterator to a different type.
Definition iterator.h:240
CRTP base class which implements the entire standard iterator facade in terms of a minimal subset of ...
Definition iterator.h:80
A range adaptor for a pair of iterators.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
A raw_ostream that writes to an std::string.
This provides a very simple, boring adaptor for a begin and end iterator into a range type.
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
This is an optimization pass for GlobalISel generic memory operations.
Definition Types.h:26
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
InnerAnalysisManagerProxy< FunctionAnalysisManager, Module > FunctionAnalysisManagerModuleProxy
Provide the FunctionAnalysisManager to Module proxy.
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:870
#define N
A CRTP mix-in that provides informational APIs needed for analysis passes.
Definition PassManager.h:93
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition Analysis.h:29
static ChildIteratorType child_begin(NodeRef N)
LazyCallGraph::EdgeSequence::iterator ChildIteratorType
static ChildIteratorType child_end(NodeRef N)
static NodeRef getEntryNode(NodeRef N)
static ChildIteratorType child_end(NodeRef N)
LazyCallGraph::EdgeSequence::iterator ChildIteratorType
static ChildIteratorType child_begin(NodeRef N)
A CRTP mix-in to automatically provide informational APIs needed for passes.
Definition PassManager.h:70
An iterator type that allows iterating over the pointees via some other iterator.
Definition iterator.h:329