1 //===- DSGraph.h - Represent a collection of data structures ----*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
10 // This header defines the data structure graph (DSGraph) and the
11 // ReachabilityCloner class.
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_ANALYSIS_DSGRAPH_H
16 #define LLVM_ANALYSIS_DSGRAPH_H
18 #include "llvm/Analysis/DSNode.h"
24 //===----------------------------------------------------------------------===//
25 /// DSScalarMap - An instance of this class is used to keep track of all of
26 /// which DSNode each scalar in a function points to. This is specialized to
27 /// keep track of globals with nodes in the function, and to keep track of the
28 /// unique DSNodeHandle being used by the scalar map.
30 /// This class is crucial to the efficiency of DSA with some large SCC's. In
31 /// these cases, the cost of iterating over the scalar map dominates the cost
32 /// of DSA. In all of these cases, the DSA phase is really trying to identify
33 /// globals or unique node handles active in the function.
36 typedef hash_map<Value*, DSNodeHandle> ValueMapTy;
39 typedef hash_set<GlobalValue*> GlobalSetTy;
40 GlobalSetTy GlobalSet;
43 // Compatibility methods: provide an interface compatible with a map of
44 // Value* to DSNodeHandle's.
45 typedef ValueMapTy::const_iterator const_iterator;
46 typedef ValueMapTy::iterator iterator;
47 iterator begin() { return ValueMap.begin(); }
48 iterator end() { return ValueMap.end(); }
49 const_iterator begin() const { return ValueMap.begin(); }
50 const_iterator end() const { return ValueMap.end(); }
51 iterator find(Value *V) { return ValueMap.find(V); }
52 const_iterator find(Value *V) const { return ValueMap.find(V); }
53 unsigned count(Value *V) const { return ValueMap.count(V); }
55 void erase(Value *V) { erase(find(V)); }
57 DSNodeHandle &operator[](Value *V) {
58 std::pair<iterator,bool> IP =
59 ValueMap.insert(std::make_pair(V, DSNodeHandle()));
60 if (IP.second) { // Inserted the new entry into the map.
61 if (GlobalValue *GV = dyn_cast<GlobalValue>(V))
64 return IP.first->second;
67 void erase(iterator I) {
68 assert(I != ValueMap.end() && "Cannot erase end!");
69 if (GlobalValue *GV = dyn_cast<GlobalValue>(I->first))
79 // Access to the global set: the set of all globals currently in the
81 typedef GlobalSetTy::const_iterator global_iterator;
82 global_iterator global_begin() const { return GlobalSet.begin(); }
83 global_iterator global_end() const { return GlobalSet.end(); }
87 //===----------------------------------------------------------------------===//
88 /// DSGraph - The graph that represents a function.
91 // Public data-type declarations...
92 typedef DSScalarMap ScalarMapTy;
93 typedef hash_map<Function*, DSNodeHandle> ReturnNodesTy;
94 typedef hash_set<GlobalValue*> GlobalSetTy;
95 typedef ilist<DSNode> NodeListTy;
97 /// NodeMapTy - This data type is used when cloning one graph into another to
98 /// keep track of the correspondence between the nodes in the old and new
100 typedef hash_map<const DSNode*, DSNodeHandle> NodeMapTy;
102 DSGraph *GlobalsGraph; // Pointer to the common graph of global objects
103 bool PrintAuxCalls; // Should this graph print the Aux calls vector?
106 ScalarMapTy ScalarMap;
108 // ReturnNodes - A return value for every function merged into this graph.
109 // Each DSGraph may have multiple functions merged into it at any time, which
110 // is used for representing SCCs.
112 ReturnNodesTy ReturnNodes;
114 // FunctionCalls - This vector maintains a single entry for each call
115 // instruction in the current graph. The first entry in the vector is the
116 // scalar that holds the return value for the call, the second is the function
117 // scalar being invoked, and the rest are pointer arguments to the function.
118 // This vector is built by the Local graph and is never modified after that.
120 std::vector<DSCallSite> FunctionCalls;
122 // AuxFunctionCalls - This vector contains call sites that have been processed
123 // by some mechanism. In pratice, the BU Analysis uses this vector to hold
124 // the _unresolved_ call sites, because it cannot modify FunctionCalls.
126 std::vector<DSCallSite> AuxFunctionCalls;
128 // InlinedGlobals - This set records which globals have been inlined from
129 // other graphs (callers or callees, depending on the pass) into this one.
131 GlobalSetTy InlinedGlobals;
133 /// TD - This is the target data object for the machine this graph is
135 const TargetData &TD;
137 void operator=(const DSGraph &); // DO NOT IMPLEMENT
140 // Create a new, empty, DSGraph.
141 DSGraph(const TargetData &td)
142 : GlobalsGraph(0), PrintAuxCalls(false), TD(td) {}
144 // Compute the local DSGraph
145 DSGraph(const TargetData &td, Function &F, DSGraph *GlobalsGraph);
147 // Copy ctor - If you want to capture the node mapping between the source and
148 // destination graph, you may optionally do this by specifying a map to record
151 // Note that a copied graph does not retain the GlobalsGraph pointer of the
152 // source. You need to set a new GlobalsGraph with the setGlobalsGraph
155 DSGraph(const DSGraph &DSG);
156 DSGraph(const DSGraph &DSG, NodeMapTy &NodeMap);
159 DSGraph *getGlobalsGraph() const { return GlobalsGraph; }
160 void setGlobalsGraph(DSGraph *G) { GlobalsGraph = G; }
162 /// getTargetData - Return the TargetData object for the current target.
164 const TargetData &getTargetData() const { return TD; }
166 /// setPrintAuxCalls - If you call this method, the auxillary call vector will
167 /// be printed instead of the standard call vector to the dot file.
169 void setPrintAuxCalls() { PrintAuxCalls = true; }
170 bool shouldPrintAuxCalls() const { return PrintAuxCalls; }
172 /// getNodes - Get a vector of all the nodes in the graph
174 typedef NodeListTy::compat_iterator node_iterator;
175 node_iterator node_begin() const { return Nodes.compat_begin(); }
176 node_iterator node_end() const { return Nodes.compat_end(); }
178 /// getFunctionNames - Return a space separated list of the name of the
179 /// functions in this graph (if any)
180 std::string getFunctionNames() const;
182 /// addNode - Add a new node to the graph.
184 void addNode(DSNode *N) { Nodes.push_back(N); }
185 void unlinkNode(DSNode *N) { Nodes.remove(N); }
187 /// getScalarMap - Get a map that describes what the nodes the scalars in this
188 /// function point to...
190 ScalarMapTy &getScalarMap() { return ScalarMap; }
191 const ScalarMapTy &getScalarMap() const { return ScalarMap; }
193 /// getFunctionCalls - Return the list of call sites in the original local
196 const std::vector<DSCallSite> &getFunctionCalls() const {
197 return FunctionCalls;
200 /// getAuxFunctionCalls - Get the call sites as modified by whatever passes
203 std::vector<DSCallSite> &getAuxFunctionCalls() {
204 return AuxFunctionCalls;
206 const std::vector<DSCallSite> &getAuxFunctionCalls() const {
207 return AuxFunctionCalls;
210 /// getInlinedGlobals - Get the set of globals that are have been inlined
211 /// (from callees in BU or from callers in TD) into the current graph.
213 GlobalSetTy& getInlinedGlobals() {
214 return InlinedGlobals;
217 /// getNodeForValue - Given a value that is used or defined in the body of the
218 /// current function, return the DSNode that it points to.
220 DSNodeHandle &getNodeForValue(Value *V) { return ScalarMap[V]; }
222 const DSNodeHandle &getNodeForValue(Value *V) const {
223 ScalarMapTy::const_iterator I = ScalarMap.find(V);
224 assert(I != ScalarMap.end() &&
225 "Use non-const lookup function if node may not be in the map");
229 /// getReturnNodes - Return the mapping of functions to their return nodes for
231 const ReturnNodesTy &getReturnNodes() const { return ReturnNodes; }
232 ReturnNodesTy &getReturnNodes() { return ReturnNodes; }
234 /// getReturnNodeFor - Return the return node for the specified function.
236 DSNodeHandle &getReturnNodeFor(Function &F) {
237 ReturnNodesTy::iterator I = ReturnNodes.find(&F);
238 assert(I != ReturnNodes.end() && "F not in this DSGraph!");
242 const DSNodeHandle &getReturnNodeFor(Function &F) const {
243 ReturnNodesTy::const_iterator I = ReturnNodes.find(&F);
244 assert(I != ReturnNodes.end() && "F not in this DSGraph!");
248 /// getGraphSize - Return the number of nodes in this graph.
250 unsigned getGraphSize() const {
254 /// print - Print a dot graph to the specified ostream...
256 void print(std::ostream &O) const;
258 /// dump - call print(std::cerr), for use from the debugger...
262 /// viewGraph - Emit a dot graph, run 'dot', run gv on the postscript file,
263 /// then cleanup. For use from the debugger.
264 void viewGraph() const;
266 void writeGraphToFile(std::ostream &O, const std::string &GraphName) const;
268 /// maskNodeTypes - Apply a mask to all of the node types in the graph. This
269 /// is useful for clearing out markers like Incomplete.
271 void maskNodeTypes(unsigned Mask) {
272 for (node_iterator I = node_begin(), E = node_end(); I != E; ++I)
273 (*I)->maskNodeTypes(Mask);
275 void maskIncompleteMarkers() { maskNodeTypes(~DSNode::Incomplete); }
277 // markIncompleteNodes - Traverse the graph, identifying nodes that may be
278 // modified by other functions that have not been resolved yet. This marks
279 // nodes that are reachable through three sources of "unknownness":
280 // Global Variables, Function Calls, and Incoming Arguments
282 // For any node that may have unknown components (because something outside
283 // the scope of current analysis may have modified it), the 'Incomplete' flag
284 // is added to the NodeType.
286 enum MarkIncompleteFlags {
287 MarkFormalArgs = 1, IgnoreFormalArgs = 0,
288 IgnoreGlobals = 2, MarkGlobalsIncomplete = 0,
290 void markIncompleteNodes(unsigned Flags);
292 // removeDeadNodes - Use a reachability analysis to eliminate subgraphs that
293 // are unreachable. This often occurs because the data structure doesn't
294 // "escape" into it's caller, and thus should be eliminated from the caller's
295 // graph entirely. This is only appropriate to use when inlining graphs.
297 enum RemoveDeadNodesFlags {
298 RemoveUnreachableGlobals = 1, KeepUnreachableGlobals = 0,
300 void removeDeadNodes(unsigned Flags);
302 /// CloneFlags enum - Bits that may be passed into the cloneInto method to
303 /// specify how to clone the function graph.
305 StripAllocaBit = 1 << 0, KeepAllocaBit = 0,
306 DontCloneCallNodes = 1 << 1, CloneCallNodes = 0,
307 DontCloneAuxCallNodes = 1 << 2, CloneAuxCallNodes = 0,
308 StripModRefBits = 1 << 3, KeepModRefBits = 0,
309 StripIncompleteBit = 1 << 4, KeepIncompleteBit = 0,
310 UpdateInlinedGlobals = 1 << 5, DontUpdateInlinedGlobals = 0,
313 void updateFromGlobalGraph();
315 /// computeNodeMapping - Given roots in two different DSGraphs, traverse the
316 /// nodes reachable from the two graphs, computing the mapping of nodes from
317 /// the first to the second graph.
319 static void computeNodeMapping(const DSNodeHandle &NH1,
320 const DSNodeHandle &NH2, NodeMapTy &NodeMap,
321 bool StrictChecking = true);
324 /// cloneInto - Clone the specified DSGraph into the current graph. The
325 /// translated ScalarMap for the old function is filled into the OldValMap
326 /// member, and the translated ReturnNodes map is returned into ReturnNodes.
327 /// OldNodeMap contains a mapping from the original nodes to the newly cloned
330 /// The CloneFlags member controls various aspects of the cloning process.
332 void cloneInto(const DSGraph &G, ScalarMapTy &OldValMap,
333 ReturnNodesTy &OldReturnNodes, NodeMapTy &OldNodeMap,
334 unsigned CloneFlags = 0);
336 /// mergeInGraph - The method is used for merging graphs together. If the
337 /// argument graph is not *this, it makes a clone of the specified graph, then
338 /// merges the nodes specified in the call site with the formal arguments in
339 /// the graph. If the StripAlloca's argument is 'StripAllocaBit' then Alloca
340 /// markers are removed from nodes.
342 void mergeInGraph(const DSCallSite &CS, Function &F, const DSGraph &Graph,
343 unsigned CloneFlags);
346 /// getCallSiteForArguments - Get the arguments and return value bindings for
347 /// the specified function in the current graph.
349 DSCallSite getCallSiteForArguments(Function &F) const;
351 // Methods for checking to make sure graphs are well formed...
352 void AssertNodeInGraph(const DSNode *N) const {
353 assert((!N || N->getParentGraph() == this) &&
354 "AssertNodeInGraph: Node is not in graph!");
356 void AssertNodeContainsGlobal(const DSNode *N, GlobalValue *GV) const {
357 assert(std::find(N->getGlobals().begin(), N->getGlobals().end(), GV) !=
358 N->getGlobals().end() && "Global value not in node!");
361 void AssertCallSiteInGraph(const DSCallSite &CS) const {
362 if (CS.isIndirectCall())
363 AssertNodeInGraph(CS.getCalleeNode());
364 AssertNodeInGraph(CS.getRetVal().getNode());
365 for (unsigned j = 0, e = CS.getNumPtrArgs(); j != e; ++j)
366 AssertNodeInGraph(CS.getPtrArg(j).getNode());
369 void AssertCallNodesInGraph() const {
370 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
371 AssertCallSiteInGraph(FunctionCalls[i]);
373 void AssertAuxCallNodesInGraph() const {
374 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
375 AssertCallSiteInGraph(AuxFunctionCalls[i]);
378 void AssertGraphOK() const;
380 /// removeTriviallyDeadNodes - After the graph has been constructed, this
381 /// method removes all unreachable nodes that are created because they got
382 /// merged with other nodes in the graph. This is used as the first step of
385 void removeTriviallyDeadNodes();
389 /// ReachabilityCloner - This class is used to incrementally clone and merge
390 /// nodes from a non-changing source graph into a potentially mutating
391 /// destination graph. Nodes are only cloned over on demand, either in
392 /// responds to a merge() or getClonedNH() call. When a node is cloned over,
393 /// all of the nodes reachable from it are automatically brought over as well.
394 class ReachabilityCloner {
398 /// BitsToKeep - These bits are retained from the source node when the
399 /// source nodes are merged into the destination graph.
403 // NodeMap - A mapping from nodes in the source graph to the nodes that
404 // represent them in the destination graph.
405 DSGraph::NodeMapTy NodeMap;
407 ReachabilityCloner(DSGraph &dest, const DSGraph &src, unsigned cloneFlags)
408 : Dest(dest), Src(src), CloneFlags(cloneFlags) {
409 assert(&Dest != &Src && "Cannot clone from graph to same graph!");
410 BitsToKeep = ~DSNode::DEAD;
411 if (CloneFlags & DSGraph::StripAllocaBit)
412 BitsToKeep &= ~DSNode::AllocaNode;
413 if (CloneFlags & DSGraph::StripModRefBits)
414 BitsToKeep &= ~(DSNode::Modified | DSNode::Read);
415 if (CloneFlags & DSGraph::StripIncompleteBit)
416 BitsToKeep &= ~DSNode::Incomplete;
419 DSNodeHandle getClonedNH(const DSNodeHandle &SrcNH);
421 void merge(const DSNodeHandle &NH, const DSNodeHandle &SrcNH);
423 /// mergeCallSite - Merge the nodes reachable from the specified src call
424 /// site into the nodes reachable from DestCS.
425 void mergeCallSite(const DSCallSite &DestCS, const DSCallSite &SrcCS);
427 bool clonedNode() const { return !NodeMap.empty(); }
429 void destroy() { NodeMap.clear(); }
431 } // End llvm namespace