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