Added LLVM copyright header (for lack of a better term).
[oota-llvm.git] / include / llvm / Analysis / DataStructure / DSGraph.h
1 //===- DSGraph.h - Represent a collection of data structures ----*- C++ -*-===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 // 
8 //===----------------------------------------------------------------------===//
9 //
10 // This header defines the data structure graph.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #ifndef LLVM_ANALYSIS_DSGRAPH_H
15 #define LLVM_ANALYSIS_DSGRAPH_H
16
17 #include "llvm/Analysis/DSNode.h"
18 class GlobalValue;
19
20 //===----------------------------------------------------------------------===//
21 /// DSGraph - The graph that represents a function.
22 ///
23 struct DSGraph {
24   // Public data-type declarations...
25   typedef hash_map<Value*, DSNodeHandle> ScalarMapTy;
26   typedef hash_map<Function*, DSNodeHandle> ReturnNodesTy;
27   typedef hash_set<const GlobalValue*> GlobalSetTy;
28
29   /// NodeMapTy - This data type is used when cloning one graph into another to
30   /// keep track of the correspondence between the nodes in the old and new
31   /// graphs.
32   typedef hash_map<const DSNode*, DSNodeHandle> NodeMapTy;
33 private:
34   DSGraph *GlobalsGraph;   // Pointer to the common graph of global objects
35   bool PrintAuxCalls;      // Should this graph print the Aux calls vector?
36
37   std::vector<DSNode*> Nodes;
38   ScalarMapTy ScalarMap;
39
40   // ReturnNodes - A return value for every function merged into this graph.
41   // Each DSGraph may have multiple functions merged into it at any time, which
42   // is used for representing SCCs.
43   //
44   ReturnNodesTy ReturnNodes;
45
46   // FunctionCalls - This vector maintains a single entry for each call
47   // instruction in the current graph.  The first entry in the vector is the
48   // scalar that holds the return value for the call, the second is the function
49   // scalar being invoked, and the rest are pointer arguments to the function.
50   // This vector is built by the Local graph and is never modified after that.
51   //
52   std::vector<DSCallSite> FunctionCalls;
53
54   // AuxFunctionCalls - This vector contains call sites that have been processed
55   // by some mechanism.  In pratice, the BU Analysis uses this vector to hold
56   // the _unresolved_ call sites, because it cannot modify FunctionCalls.
57   //
58   std::vector<DSCallSite> AuxFunctionCalls;
59
60   // InlinedGlobals - This set records which globals have been inlined from
61   // other graphs (callers or callees, depending on the pass) into this one.
62   // 
63   GlobalSetTy InlinedGlobals;
64
65   void operator=(const DSGraph &); // DO NOT IMPLEMENT
66
67 public:
68   // Create a new, empty, DSGraph.
69   DSGraph() : GlobalsGraph(0), PrintAuxCalls(false) {}
70   DSGraph(Function &F, DSGraph *GlobalsGraph); // Compute the local DSGraph
71
72   // Copy ctor - If you want to capture the node mapping between the source and
73   // destination graph, you may optionally do this by specifying a map to record
74   // this into.
75   //
76   // Note that a copied graph does not retain the GlobalsGraph pointer of the
77   // source.  You need to set a new GlobalsGraph with the setGlobalsGraph
78   // method.
79   //
80   DSGraph(const DSGraph &DSG);
81   DSGraph(const DSGraph &DSG, NodeMapTy &NodeMap);
82   ~DSGraph();
83
84   DSGraph *getGlobalsGraph() const { return GlobalsGraph; }
85   void setGlobalsGraph(DSGraph *G) { GlobalsGraph = G; }
86
87   // setPrintAuxCalls - If you call this method, the auxillary call vector will
88   // be printed instead of the standard call vector to the dot file.
89   //
90   void setPrintAuxCalls() { PrintAuxCalls = true; }
91   bool shouldPrintAuxCalls() const { return PrintAuxCalls; }
92
93   /// getNodes - Get a vector of all the nodes in the graph
94   /// 
95   const std::vector<DSNode*> &getNodes() const { return Nodes; }
96         std::vector<DSNode*> &getNodes()       { return Nodes; }
97
98   /// getFunctionNames - Return a space separated list of the name of the
99   /// functions in this graph (if any)
100   std::string getFunctionNames() const;
101
102   /// addNode - Add a new node to the graph.
103   ///
104   void addNode(DSNode *N) { Nodes.push_back(N); }
105
106   /// getScalarMap - Get a map that describes what the nodes the scalars in this
107   /// function point to...
108   ///
109   ScalarMapTy &getScalarMap() { return ScalarMap; }
110   const ScalarMapTy &getScalarMap() const { return ScalarMap; }
111
112   /// getFunctionCalls - Return the list of call sites in the original local
113   /// graph...
114   ///
115   const std::vector<DSCallSite> &getFunctionCalls() const {
116     return FunctionCalls;
117   }
118
119   /// getAuxFunctionCalls - Get the call sites as modified by whatever passes
120   /// have been run.
121   ///
122   std::vector<DSCallSite> &getAuxFunctionCalls() {
123     return AuxFunctionCalls;
124   }
125   const std::vector<DSCallSite> &getAuxFunctionCalls() const {
126     return AuxFunctionCalls;
127   }
128
129   /// getInlinedGlobals - Get the set of globals that are have been inlined
130   /// (from callees in BU or from callers in TD) into the current graph.
131   ///
132   GlobalSetTy& getInlinedGlobals() {
133     return InlinedGlobals;
134   }
135
136   /// getNodeForValue - Given a value that is used or defined in the body of the
137   /// current function, return the DSNode that it points to.
138   ///
139   DSNodeHandle &getNodeForValue(Value *V) { return ScalarMap[V]; }
140
141   const DSNodeHandle &getNodeForValue(Value *V) const {
142     ScalarMapTy::const_iterator I = ScalarMap.find(V);
143     assert(I != ScalarMap.end() &&
144            "Use non-const lookup function if node may not be in the map");
145     return I->second;
146   }
147
148   /// getReturnNodes - Return the mapping of functions to their return nodes for
149   /// this graph.
150   const ReturnNodesTy &getReturnNodes() const { return ReturnNodes; }
151         ReturnNodesTy &getReturnNodes()       { return ReturnNodes; }
152
153   /// getReturnNodeFor - Return the return node for the specified function.
154   ///
155   DSNodeHandle &getReturnNodeFor(Function &F) {
156     ReturnNodesTy::iterator I = ReturnNodes.find(&F);
157     assert(I != ReturnNodes.end() && "F not in this DSGraph!");
158     return I->second;
159   }
160
161   const DSNodeHandle &getReturnNodeFor(Function &F) const {
162     ReturnNodesTy::const_iterator I = ReturnNodes.find(&F);
163     assert(I != ReturnNodes.end() && "F not in this DSGraph!");
164     return I->second;
165   }
166
167   /// getGraphSize - Return the number of nodes in this graph.
168   ///
169   unsigned getGraphSize() const {
170     return Nodes.size();
171   }
172
173   /// print - Print a dot graph to the specified ostream...
174   ///
175   void print(std::ostream &O) const;
176
177   /// dump - call print(std::cerr), for use from the debugger...
178   ///
179   void dump() const;
180
181   /// viewGraph - Emit a dot graph, run 'dot', run gv on the postscript file,
182   /// then cleanup.  For use from the debugger.
183   void viewGraph() const;
184
185   void writeGraphToFile(std::ostream &O, const std::string &GraphName) const;
186
187   /// maskNodeTypes - Apply a mask to all of the node types in the graph.  This
188   /// is useful for clearing out markers like Incomplete.
189   ///
190   void maskNodeTypes(unsigned Mask) {
191     for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
192       Nodes[i]->maskNodeTypes(Mask);
193   }
194   void maskIncompleteMarkers() { maskNodeTypes(~DSNode::Incomplete); }
195
196   // markIncompleteNodes - Traverse the graph, identifying nodes that may be
197   // modified by other functions that have not been resolved yet.  This marks
198   // nodes that are reachable through three sources of "unknownness":
199   //   Global Variables, Function Calls, and Incoming Arguments
200   //
201   // For any node that may have unknown components (because something outside
202   // the scope of current analysis may have modified it), the 'Incomplete' flag
203   // is added to the NodeType.
204   //
205   enum MarkIncompleteFlags {
206     MarkFormalArgs = 1, IgnoreFormalArgs = 0,
207     IgnoreGlobals = 2, MarkGlobalsIncomplete = 0,
208   };
209   void markIncompleteNodes(unsigned Flags);
210
211   // removeDeadNodes - Use a reachability analysis to eliminate subgraphs that
212   // are unreachable.  This often occurs because the data structure doesn't
213   // "escape" into it's caller, and thus should be eliminated from the caller's
214   // graph entirely.  This is only appropriate to use when inlining graphs.
215   //
216   enum RemoveDeadNodesFlags {
217     RemoveUnreachableGlobals = 1, KeepUnreachableGlobals = 0,
218   };
219   void removeDeadNodes(unsigned Flags);
220
221   /// CloneFlags enum - Bits that may be passed into the cloneInto method to
222   /// specify how to clone the function graph.
223   enum CloneFlags {
224     StripAllocaBit        = 1 << 0, KeepAllocaBit     = 0,
225     DontCloneCallNodes    = 1 << 1, CloneCallNodes    = 0,
226     DontCloneAuxCallNodes = 1 << 2, CloneAuxCallNodes = 0,
227     StripModRefBits       = 1 << 3, KeepModRefBits    = 0,
228     StripIncompleteBit    = 1 << 4, KeepIncompleteBit = 0,
229   };
230
231 private:
232   void cloneReachableNodes(const DSNode*  Node,
233                            unsigned BitsToClear,
234                            NodeMapTy& OldNodeMap,
235                            NodeMapTy& CompletedNodeMap);
236
237 public:
238   void updateFromGlobalGraph();
239
240   void cloneReachableSubgraph(const DSGraph& G,
241                               const hash_set<const DSNode*>& RootNodes,
242                               NodeMapTy& OldNodeMap,
243                               NodeMapTy& CompletedNodeMap,
244                               unsigned CloneFlags = 0);
245
246   /// cloneInto - Clone the specified DSGraph into the current graph.  The
247   /// translated ScalarMap for the old function is filled into the OldValMap
248   /// member, and the translated ReturnNodes map is returned into ReturnNodes.
249   ///
250   /// The CloneFlags member controls various aspects of the cloning process.
251   ///
252   void cloneInto(const DSGraph &G, ScalarMapTy &OldValMap,
253                  ReturnNodesTy &OldReturnNodes, NodeMapTy &OldNodeMap,
254                  unsigned CloneFlags = 0);
255
256   /// mergeInGraph - The method is used for merging graphs together.  If the
257   /// argument graph is not *this, it makes a clone of the specified graph, then
258   /// merges the nodes specified in the call site with the formal arguments in
259   /// the graph.  If the StripAlloca's argument is 'StripAllocaBit' then Alloca
260   /// markers are removed from nodes.
261   ///
262   void mergeInGraph(const DSCallSite &CS, Function &F, const DSGraph &Graph,
263                     unsigned CloneFlags);
264
265
266   /// getCallSiteForArguments - Get the arguments and return value bindings for
267   /// the specified function in the current graph.
268   ///
269   DSCallSite getCallSiteForArguments(Function &F) const;
270
271   // Methods for checking to make sure graphs are well formed...
272   void AssertNodeInGraph(const DSNode *N) const {
273     assert((!N || find(Nodes.begin(), Nodes.end(), N) != Nodes.end()) &&
274            "AssertNodeInGraph: Node is not in graph!");
275   }
276   void AssertNodeContainsGlobal(const DSNode *N, GlobalValue *GV) const {
277     assert(std::find(N->getGlobals().begin(), N->getGlobals().end(), GV) !=
278            N->getGlobals().end() && "Global value not in node!");
279   }
280
281   void AssertCallSiteInGraph(const DSCallSite &CS) const {
282     if (CS.isIndirectCall())
283       AssertNodeInGraph(CS.getCalleeNode());
284     AssertNodeInGraph(CS.getRetVal().getNode());
285     for (unsigned j = 0, e = CS.getNumPtrArgs(); j != e; ++j)
286       AssertNodeInGraph(CS.getPtrArg(j).getNode());
287   }
288
289   void AssertCallNodesInGraph() const {
290     for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
291       AssertCallSiteInGraph(FunctionCalls[i]);
292   }
293   void AssertAuxCallNodesInGraph() const {
294     for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
295       AssertCallSiteInGraph(AuxFunctionCalls[i]);
296   }
297
298   void AssertGraphOK() const;
299
300   /// mergeInGlobalsGraph - This method is useful for clients to incorporate the
301   /// globals graph into the DS, BU or TD graph for a function.  This code
302   /// retains all globals, i.e., does not delete unreachable globals after they
303   /// are inlined.
304   ///
305   void mergeInGlobalsGraph();
306
307   /// removeTriviallyDeadNodes - After the graph has been constructed, this
308   /// method removes all unreachable nodes that are created because they got
309   /// merged with other nodes in the graph.  This is used as the first step of
310   /// removeDeadNodes.
311   ///
312   void removeTriviallyDeadNodes();
313 };
314
315 #endif