Remove static global GCNames from Function.cpp and move it to the Context
[oota-llvm.git] / include / llvm / Analysis / LazyCallGraph.h
1 //===- LazyCallGraph.h - Analysis of a Module's call graph ------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 /// \file
10 ///
11 /// Implements a lazy call graph analysis and related passes for the new pass
12 /// manager.
13 ///
14 /// NB: This is *not* a traditional call graph! It is a graph which models both
15 /// the current calls and potential calls. As a consequence there are many
16 /// edges in this call graph that do not correspond to a 'call' or 'invoke'
17 /// instruction.
18 ///
19 /// The primary use cases of this graph analysis is to facilitate iterating
20 /// across the functions of a module in ways that ensure all callees are
21 /// visited prior to a caller (given any SCC constraints), or vice versa. As
22 /// such is it particularly well suited to organizing CGSCC optimizations such
23 /// as inlining, outlining, argument promotion, etc. That is its primary use
24 /// case and motivates the design. It may not be appropriate for other
25 /// purposes. The use graph of functions or some other conservative analysis of
26 /// call instructions may be interesting for optimizations and subsequent
27 /// analyses which don't work in the context of an overly specified
28 /// potential-call-edge graph.
29 ///
30 /// To understand the specific rules and nature of this call graph analysis,
31 /// see the documentation of the \c LazyCallGraph below.
32 ///
33 //===----------------------------------------------------------------------===//
34
35 #ifndef LLVM_ANALYSIS_LAZYCALLGRAPH_H
36 #define LLVM_ANALYSIS_LAZYCALLGRAPH_H
37
38 #include "llvm/ADT/DenseMap.h"
39 #include "llvm/ADT/PointerUnion.h"
40 #include "llvm/ADT/STLExtras.h"
41 #include "llvm/ADT/SetVector.h"
42 #include "llvm/ADT/SmallPtrSet.h"
43 #include "llvm/ADT/SmallVector.h"
44 #include "llvm/ADT/iterator.h"
45 #include "llvm/ADT/iterator_range.h"
46 #include "llvm/IR/BasicBlock.h"
47 #include "llvm/IR/Function.h"
48 #include "llvm/IR/Module.h"
49 #include "llvm/IR/PassManager.h"
50 #include "llvm/Support/Allocator.h"
51 #include <iterator>
52
53 namespace llvm {
54 class PreservedAnalyses;
55 class raw_ostream;
56
57 /// A lazily constructed view of the call graph of a module.
58 ///
59 /// With the edges of this graph, the motivating constraint that we are
60 /// attempting to maintain is that function-local optimization, CGSCC-local
61 /// optimizations, and optimizations transforming a pair of functions connected
62 /// by an edge in the graph, do not invalidate a bottom-up traversal of the SCC
63 /// DAG. That is, no optimizations will delete, remove, or add an edge such
64 /// that functions already visited in a bottom-up order of the SCC DAG are no
65 /// longer valid to have visited, or such that functions not yet visited in
66 /// a bottom-up order of the SCC DAG are not required to have already been
67 /// visited.
68 ///
69 /// Within this constraint, the desire is to minimize the merge points of the
70 /// SCC DAG. The greater the fanout of the SCC DAG and the fewer merge points
71 /// in the SCC DAG, the more independence there is in optimizing within it.
72 /// There is a strong desire to enable parallelization of optimizations over
73 /// the call graph, and both limited fanout and merge points will (artificially
74 /// in some cases) limit the scaling of such an effort.
75 ///
76 /// To this end, graph represents both direct and any potential resolution to
77 /// an indirect call edge. Another way to think about it is that it represents
78 /// both the direct call edges and any direct call edges that might be formed
79 /// through static optimizations. Specifically, it considers taking the address
80 /// of a function to be an edge in the call graph because this might be
81 /// forwarded to become a direct call by some subsequent function-local
82 /// optimization. The result is that the graph closely follows the use-def
83 /// edges for functions. Walking "up" the graph can be done by looking at all
84 /// of the uses of a function.
85 ///
86 /// The roots of the call graph are the external functions and functions
87 /// escaped into global variables. Those functions can be called from outside
88 /// of the module or via unknowable means in the IR -- we may not be able to
89 /// form even a potential call edge from a function body which may dynamically
90 /// load the function and call it.
91 ///
92 /// This analysis still requires updates to remain valid after optimizations
93 /// which could potentially change the set of potential callees. The
94 /// constraints it operates under only make the traversal order remain valid.
95 ///
96 /// The entire analysis must be re-computed if full interprocedural
97 /// optimizations run at any point. For example, globalopt completely
98 /// invalidates the information in this analysis.
99 ///
100 /// FIXME: This class is named LazyCallGraph in a lame attempt to distinguish
101 /// it from the existing CallGraph. At some point, it is expected that this
102 /// will be the only call graph and it will be renamed accordingly.
103 class LazyCallGraph {
104 public:
105   class Node;
106   class SCC;
107   typedef SmallVector<PointerUnion<Function *, Node *>, 4> NodeVectorT;
108   typedef SmallVectorImpl<PointerUnion<Function *, Node *>> NodeVectorImplT;
109
110   /// A lazy iterator used for both the entry nodes and child nodes.
111   ///
112   /// When this iterator is dereferenced, if not yet available, a function will
113   /// be scanned for "calls" or uses of functions and its child information
114   /// will be constructed. All of these results are accumulated and cached in
115   /// the graph.
116   class iterator
117       : public iterator_adaptor_base<iterator, NodeVectorImplT::iterator,
118                                      std::forward_iterator_tag, Node> {
119     friend class LazyCallGraph;
120     friend class LazyCallGraph::Node;
121
122     LazyCallGraph *G;
123     NodeVectorImplT::iterator E;
124
125     // Build the iterator for a specific position in a node list.
126     iterator(LazyCallGraph &G, NodeVectorImplT::iterator NI,
127              NodeVectorImplT::iterator E)
128         : iterator_adaptor_base(NI), G(&G), E(E) {
129       while (I != E && I->isNull())
130         ++I;
131     }
132
133   public:
134     iterator() {}
135
136     using iterator_adaptor_base::operator++;
137     iterator &operator++() {
138       do {
139         ++I;
140       } while (I != E && I->isNull());
141       return *this;
142     }
143
144     reference operator*() const {
145       if (I->is<Node *>())
146         return *I->get<Node *>();
147
148       Function *F = I->get<Function *>();
149       Node &ChildN = G->get(*F);
150       *I = &ChildN;
151       return ChildN;
152     }
153   };
154
155   /// A node in the call graph.
156   ///
157   /// This represents a single node. It's primary roles are to cache the list of
158   /// callees, de-duplicate and provide fast testing of whether a function is
159   /// a callee, and facilitate iteration of child nodes in the graph.
160   class Node {
161     friend class LazyCallGraph;
162     friend class LazyCallGraph::SCC;
163
164     LazyCallGraph *G;
165     Function &F;
166
167     // We provide for the DFS numbering and Tarjan walk lowlink numbers to be
168     // stored directly within the node.
169     int DFSNumber;
170     int LowLink;
171
172     mutable NodeVectorT Callees;
173     DenseMap<Function *, size_t> CalleeIndexMap;
174
175     /// Basic constructor implements the scanning of F into Callees and
176     /// CalleeIndexMap.
177     Node(LazyCallGraph &G, Function &F);
178
179     /// Internal helper to insert a callee.
180     void insertEdgeInternal(Function &Callee);
181
182     /// Internal helper to insert a callee.
183     void insertEdgeInternal(Node &CalleeN);
184
185     /// Internal helper to remove a callee from this node.
186     void removeEdgeInternal(Function &Callee);
187
188   public:
189     typedef LazyCallGraph::iterator iterator;
190
191     Function &getFunction() const { return F; }
192
193     iterator begin() const {
194       return iterator(*G, Callees.begin(), Callees.end());
195     }
196     iterator end() const { return iterator(*G, Callees.end(), Callees.end()); }
197
198     /// Equality is defined as address equality.
199     bool operator==(const Node &N) const { return this == &N; }
200     bool operator!=(const Node &N) const { return !operator==(N); }
201   };
202
203   /// An SCC of the call graph.
204   ///
205   /// This represents a Strongly Connected Component of the call graph as
206   /// a collection of call graph nodes. While the order of nodes in the SCC is
207   /// stable, it is not any particular order.
208   class SCC {
209     friend class LazyCallGraph;
210     friend class LazyCallGraph::Node;
211
212     LazyCallGraph *G;
213     SmallPtrSet<SCC *, 1> ParentSCCs;
214     SmallVector<Node *, 1> Nodes;
215
216     SCC(LazyCallGraph &G) : G(&G) {}
217
218     void insert(Node &N);
219
220     void
221     internalDFS(SmallVectorImpl<std::pair<Node *, Node::iterator>> &DFSStack,
222                 SmallVectorImpl<Node *> &PendingSCCStack, Node *N,
223                 SmallVectorImpl<SCC *> &ResultSCCs);
224
225   public:
226     typedef SmallVectorImpl<Node *>::const_iterator iterator;
227     typedef pointee_iterator<SmallPtrSet<SCC *, 1>::const_iterator>
228         parent_iterator;
229
230     iterator begin() const { return Nodes.begin(); }
231     iterator end() const { return Nodes.end(); }
232
233     parent_iterator parent_begin() const { return ParentSCCs.begin(); }
234     parent_iterator parent_end() const { return ParentSCCs.end(); }
235
236     iterator_range<parent_iterator> parents() const {
237       return make_range(parent_begin(), parent_end());
238     }
239
240     /// Test if this SCC is a parent of \a C.
241     bool isParentOf(const SCC &C) const { return C.isChildOf(*this); }
242
243     /// Test if this SCC is an ancestor of \a C.
244     bool isAncestorOf(const SCC &C) const { return C.isDescendantOf(*this); }
245
246     /// Test if this SCC is a child of \a C.
247     bool isChildOf(const SCC &C) const {
248       return ParentSCCs.count(const_cast<SCC *>(&C));
249     }
250
251     /// Test if this SCC is a descendant of \a C.
252     bool isDescendantOf(const SCC &C) const;
253
254     /// Short name useful for debugging or logging.
255     ///
256     /// We use the name of the first function in the SCC to name the SCC for
257     /// the purposes of debugging and logging.
258     StringRef getName() const { return (*begin())->getFunction().getName(); }
259
260     ///@{
261     /// \name Mutation API
262     ///
263     /// These methods provide the core API for updating the call graph in the
264     /// presence of a (potentially still in-flight) DFS-found SCCs.
265     ///
266     /// Note that these methods sometimes have complex runtimes, so be careful
267     /// how you call them.
268
269     /// Insert an edge from one node in this SCC to another in this SCC.
270     ///
271     /// By the definition of an SCC, this does not change the nature or make-up
272     /// of any SCCs.
273     void insertIntraSCCEdge(Node &CallerN, Node &CalleeN);
274
275     /// Insert an edge whose tail is in this SCC and head is in some child SCC.
276     ///
277     /// There must be an existing path from the caller to the callee. This
278     /// operation is inexpensive and does not change the set of SCCs in the
279     /// graph.
280     void insertOutgoingEdge(Node &CallerN, Node &CalleeN);
281
282     /// Insert an edge whose tail is in a descendant SCC and head is in this
283     /// SCC.
284     ///
285     /// There must be an existing path from the callee to the caller in this
286     /// case. NB! This is has the potential to be a very expensive function. It
287     /// inherently forms a cycle in the prior SCC DAG and we have to merge SCCs
288     /// to resolve that cycle. But finding all of the SCCs which participate in
289     /// the cycle can in the worst case require traversing every SCC in the
290     /// graph. Every attempt is made to avoid that, but passes must still
291     /// exercise caution calling this routine repeatedly.
292     ///
293     /// FIXME: We could possibly optimize this quite a bit for cases where the
294     /// caller and callee are very nearby in the graph. See comments in the
295     /// implementation for details, but that use case might impact users.
296     SmallVector<SCC *, 1> insertIncomingEdge(Node &CallerN, Node &CalleeN);
297
298     /// Remove an edge whose source is in this SCC and target is *not*.
299     ///
300     /// This removes an inter-SCC edge. All inter-SCC edges originating from
301     /// this SCC have been fully explored by any in-flight DFS SCC formation,
302     /// so this is always safe to call once you have the source SCC.
303     ///
304     /// This operation does not change the set of SCCs or the members of the
305     /// SCCs and so is very inexpensive. It may change the connectivity graph
306     /// of the SCCs though, so be careful calling this while iterating over
307     /// them.
308     void removeInterSCCEdge(Node &CallerN, Node &CalleeN);
309
310     /// Remove an edge which is entirely within this SCC.
311     ///
312     /// Both the \a Caller and the \a Callee must be within this SCC. Removing
313     /// such an edge make break cycles that form this SCC and thus this
314     /// operation may change the SCC graph significantly. In particular, this
315     /// operation will re-form new SCCs based on the remaining connectivity of
316     /// the graph. The following invariants are guaranteed to hold after
317     /// calling this method:
318     ///
319     /// 1) This SCC is still an SCC in the graph.
320     /// 2) This SCC will be the parent of any new SCCs. Thus, this SCC is
321     ///    preserved as the root of any new SCC directed graph formed.
322     /// 3) No SCC other than this SCC has its member set changed (this is
323     ///    inherent in the definition of removing such an edge).
324     /// 4) All of the parent links of the SCC graph will be updated to reflect
325     ///    the new SCC structure.
326     /// 5) All SCCs formed out of this SCC, excluding this SCC, will be
327     ///    returned in a vector.
328     /// 6) The order of the SCCs in the vector will be a valid postorder
329     ///    traversal of the new SCCs.
330     ///
331     /// These invariants are very important to ensure that we can build
332     /// optimization pipeliens on top of the CGSCC pass manager which
333     /// intelligently update the SCC graph without invalidating other parts of
334     /// the SCC graph.
335     ///
336     /// The runtime complexity of this method is, in the worst case, O(V+E)
337     /// where V is the number of nodes in this SCC and E is the number of edges
338     /// leaving the nodes in this SCC. Note that E includes both edges within
339     /// this SCC and edges from this SCC to child SCCs. Some effort has been
340     /// made to minimize the overhead of common cases such as self-edges and
341     /// edge removals which result in a spanning tree with no more cycles.
342     SmallVector<SCC *, 1> removeIntraSCCEdge(Node &CallerN, Node &CalleeN);
343
344     ///@}
345   };
346
347   /// A post-order depth-first SCC iterator over the call graph.
348   ///
349   /// This iterator triggers the Tarjan DFS-based formation of the SCC DAG for
350   /// the call graph, walking it lazily in depth-first post-order. That is, it
351   /// always visits SCCs for a callee prior to visiting the SCC for a caller
352   /// (when they are in different SCCs).
353   class postorder_scc_iterator
354       : public iterator_facade_base<postorder_scc_iterator,
355                                     std::forward_iterator_tag, SCC> {
356     friend class LazyCallGraph;
357     friend class LazyCallGraph::Node;
358
359     /// Nonce type to select the constructor for the end iterator.
360     struct IsAtEndT {};
361
362     LazyCallGraph *G;
363     SCC *C;
364
365     // Build the begin iterator for a node.
366     postorder_scc_iterator(LazyCallGraph &G) : G(&G) {
367       C = G.getNextSCCInPostOrder();
368     }
369
370     // Build the end iterator for a node. This is selected purely by overload.
371     postorder_scc_iterator(LazyCallGraph &G, IsAtEndT /*Nonce*/)
372         : G(&G), C(nullptr) {}
373
374   public:
375     bool operator==(const postorder_scc_iterator &Arg) const {
376       return G == Arg.G && C == Arg.C;
377     }
378
379     reference operator*() const { return *C; }
380
381     using iterator_facade_base::operator++;
382     postorder_scc_iterator &operator++() {
383       C = G->getNextSCCInPostOrder();
384       return *this;
385     }
386   };
387
388   /// Construct a graph for the given module.
389   ///
390   /// This sets up the graph and computes all of the entry points of the graph.
391   /// No function definitions are scanned until their nodes in the graph are
392   /// requested during traversal.
393   LazyCallGraph(Module &M);
394
395   LazyCallGraph(LazyCallGraph &&G);
396   LazyCallGraph &operator=(LazyCallGraph &&RHS);
397
398   iterator begin() {
399     return iterator(*this, EntryNodes.begin(), EntryNodes.end());
400   }
401   iterator end() { return iterator(*this, EntryNodes.end(), EntryNodes.end()); }
402
403   postorder_scc_iterator postorder_scc_begin() {
404     return postorder_scc_iterator(*this);
405   }
406   postorder_scc_iterator postorder_scc_end() {
407     return postorder_scc_iterator(*this, postorder_scc_iterator::IsAtEndT());
408   }
409
410   iterator_range<postorder_scc_iterator> postorder_sccs() {
411     return make_range(postorder_scc_begin(), postorder_scc_end());
412   }
413
414   /// Lookup a function in the graph which has already been scanned and added.
415   Node *lookup(const Function &F) const { return NodeMap.lookup(&F); }
416
417   /// Lookup a function's SCC in the graph.
418   ///
419   /// \returns null if the function hasn't been assigned an SCC via the SCC
420   /// iterator walk.
421   SCC *lookupSCC(Node &N) const { return SCCMap.lookup(&N); }
422
423   /// Get a graph node for a given function, scanning it to populate the graph
424   /// data as necessary.
425   Node &get(Function &F) {
426     Node *&N = NodeMap[&F];
427     if (N)
428       return *N;
429
430     return insertInto(F, N);
431   }
432
433   ///@{
434   /// \name Pre-SCC Mutation API
435   ///
436   /// These methods are only valid to call prior to forming any SCCs for this
437   /// call graph. They can be used to update the core node-graph during
438   /// a node-based inorder traversal that precedes any SCC-based traversal.
439   ///
440   /// Once you begin manipulating a call graph's SCCs, you must perform all
441   /// mutation of the graph via the SCC methods.
442
443   /// Update the call graph after inserting a new edge.
444   void insertEdge(Node &Caller, Function &Callee);
445
446   /// Update the call graph after inserting a new edge.
447   void insertEdge(Function &Caller, Function &Callee) {
448     return insertEdge(get(Caller), Callee);
449   }
450
451   /// Update the call graph after deleting an edge.
452   void removeEdge(Node &Caller, Function &Callee);
453
454   /// Update the call graph after deleting an edge.
455   void removeEdge(Function &Caller, Function &Callee) {
456     return removeEdge(get(Caller), Callee);
457   }
458
459   ///@}
460
461 private:
462   /// Allocator that holds all the call graph nodes.
463   SpecificBumpPtrAllocator<Node> BPA;
464
465   /// Maps function->node for fast lookup.
466   DenseMap<const Function *, Node *> NodeMap;
467
468   /// The entry nodes to the graph.
469   ///
470   /// These nodes are reachable through "external" means. Put another way, they
471   /// escape at the module scope.
472   NodeVectorT EntryNodes;
473
474   /// Map of the entry nodes in the graph to their indices in \c EntryNodes.
475   DenseMap<Function *, size_t> EntryIndexMap;
476
477   /// Allocator that holds all the call graph SCCs.
478   SpecificBumpPtrAllocator<SCC> SCCBPA;
479
480   /// Maps Function -> SCC for fast lookup.
481   DenseMap<Node *, SCC *> SCCMap;
482
483   /// The leaf SCCs of the graph.
484   ///
485   /// These are all of the SCCs which have no children.
486   SmallVector<SCC *, 4> LeafSCCs;
487
488   /// Stack of nodes in the DFS walk.
489   SmallVector<std::pair<Node *, iterator>, 4> DFSStack;
490
491   /// Set of entry nodes not-yet-processed into SCCs.
492   SmallVector<Function *, 4> SCCEntryNodes;
493
494   /// Stack of nodes the DFS has walked but not yet put into a SCC.
495   SmallVector<Node *, 4> PendingSCCStack;
496
497   /// Counter for the next DFS number to assign.
498   int NextDFSNumber;
499
500   /// Helper to insert a new function, with an already looked-up entry in
501   /// the NodeMap.
502   Node &insertInto(Function &F, Node *&MappedN);
503
504   /// Helper to update pointers back to the graph object during moves.
505   void updateGraphPtrs();
506
507   /// Helper to form a new SCC out of the top of a DFSStack-like
508   /// structure.
509   SCC *formSCC(Node *RootN, SmallVectorImpl<Node *> &NodeStack);
510
511   /// Retrieve the next node in the post-order SCC walk of the call graph.
512   SCC *getNextSCCInPostOrder();
513 };
514
515 // Provide GraphTraits specializations for call graphs.
516 template <> struct GraphTraits<LazyCallGraph::Node *> {
517   typedef LazyCallGraph::Node NodeType;
518   typedef LazyCallGraph::iterator ChildIteratorType;
519
520   static NodeType *getEntryNode(NodeType *N) { return N; }
521   static ChildIteratorType child_begin(NodeType *N) { return N->begin(); }
522   static ChildIteratorType child_end(NodeType *N) { return N->end(); }
523 };
524 template <> struct GraphTraits<LazyCallGraph *> {
525   typedef LazyCallGraph::Node NodeType;
526   typedef LazyCallGraph::iterator ChildIteratorType;
527
528   static NodeType *getEntryNode(NodeType *N) { return N; }
529   static ChildIteratorType child_begin(NodeType *N) { return N->begin(); }
530   static ChildIteratorType child_end(NodeType *N) { return N->end(); }
531 };
532
533 /// An analysis pass which computes the call graph for a module.
534 class LazyCallGraphAnalysis {
535 public:
536   /// Inform generic clients of the result type.
537   typedef LazyCallGraph Result;
538
539   static void *ID() { return (void *)&PassID; }
540
541   static StringRef name() { return "Lazy CallGraph Analysis"; }
542
543   /// Compute the \c LazyCallGraph for the module \c M.
544   ///
545   /// This just builds the set of entry points to the call graph. The rest is
546   /// built lazily as it is walked.
547   LazyCallGraph run(Module &M) { return LazyCallGraph(M); }
548
549 private:
550   static char PassID;
551 };
552
553 /// A pass which prints the call graph to a \c raw_ostream.
554 ///
555 /// This is primarily useful for testing the analysis.
556 class LazyCallGraphPrinterPass {
557   raw_ostream &OS;
558
559 public:
560   explicit LazyCallGraphPrinterPass(raw_ostream &OS);
561
562   PreservedAnalyses run(Module &M, ModuleAnalysisManager *AM);
563
564   static StringRef name() { return "LazyCallGraphPrinterPass"; }
565 };
566
567 }
568
569 #endif