LazyCallGraph.h 50 KB

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