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 /// replaceScalar - When an instruction needs to be modified, this method can
58 /// be used to update the scalar map to remove the old and insert the new.
59 void replaceScalar(Value *Old, Value *New) {
60 iterator I = find(Old);
61 assert(I != end() && "Old value is not in the map!");
62 ValueMap.insert(std::make_pair(New, I->second));
66 DSNodeHandle &operator[](Value *V) {
67 std::pair<iterator,bool> IP =
68 ValueMap.insert(std::make_pair(V, DSNodeHandle()));
69 if (IP.second) { // Inserted the new entry into the map.
70 if (GlobalValue *GV = dyn_cast<GlobalValue>(V))
73 return IP.first->second;
76 void erase(iterator I) {
77 assert(I != ValueMap.end() && "Cannot erase end!");
78 if (GlobalValue *GV = dyn_cast<GlobalValue>(I->first))
88 // Access to the global set: the set of all globals currently in the
90 typedef GlobalSetTy::const_iterator global_iterator;
91 global_iterator global_begin() const { return GlobalSet.begin(); }
92 global_iterator global_end() const { return GlobalSet.end(); }
96 //===----------------------------------------------------------------------===//
97 /// DSGraph - The graph that represents a function.
100 // Public data-type declarations...
101 typedef DSScalarMap ScalarMapTy;
102 typedef hash_map<Function*, DSNodeHandle> ReturnNodesTy;
103 typedef hash_set<GlobalValue*> GlobalSetTy;
104 typedef ilist<DSNode> NodeListTy;
106 /// NodeMapTy - This data type is used when cloning one graph into another to
107 /// keep track of the correspondence between the nodes in the old and new
109 typedef hash_map<const DSNode*, DSNodeHandle> NodeMapTy;
111 DSGraph *GlobalsGraph; // Pointer to the common graph of global objects
112 bool PrintAuxCalls; // Should this graph print the Aux calls vector?
115 ScalarMapTy ScalarMap;
117 // ReturnNodes - A return value for every function merged into this graph.
118 // Each DSGraph may have multiple functions merged into it at any time, which
119 // is used for representing SCCs.
121 ReturnNodesTy ReturnNodes;
123 // FunctionCalls - This vector maintains a single entry for each call
124 // instruction in the current graph. The first entry in the vector is the
125 // scalar that holds the return value for the call, the second is the function
126 // scalar being invoked, and the rest are pointer arguments to the function.
127 // This vector is built by the Local graph and is never modified after that.
129 std::vector<DSCallSite> FunctionCalls;
131 // AuxFunctionCalls - This vector contains call sites that have been processed
132 // by some mechanism. In pratice, the BU Analysis uses this vector to hold
133 // the _unresolved_ call sites, because it cannot modify FunctionCalls.
135 std::vector<DSCallSite> AuxFunctionCalls;
137 // InlinedGlobals - This set records which globals have been inlined from
138 // other graphs (callers or callees, depending on the pass) into this one.
140 GlobalSetTy InlinedGlobals;
142 /// TD - This is the target data object for the machine this graph is
144 const TargetData &TD;
146 void operator=(const DSGraph &); // DO NOT IMPLEMENT
149 // Create a new, empty, DSGraph.
150 DSGraph(const TargetData &td)
151 : GlobalsGraph(0), PrintAuxCalls(false), TD(td) {}
153 // Compute the local DSGraph
154 DSGraph(const TargetData &td, Function &F, DSGraph *GlobalsGraph);
156 // Copy ctor - If you want to capture the node mapping between the source and
157 // destination graph, you may optionally do this by specifying a map to record
160 // Note that a copied graph does not retain the GlobalsGraph pointer of the
161 // source. You need to set a new GlobalsGraph with the setGlobalsGraph
164 DSGraph(const DSGraph &DSG);
165 DSGraph(const DSGraph &DSG, NodeMapTy &NodeMap);
168 DSGraph *getGlobalsGraph() const { return GlobalsGraph; }
169 void setGlobalsGraph(DSGraph *G) { GlobalsGraph = G; }
171 /// getTargetData - Return the TargetData object for the current target.
173 const TargetData &getTargetData() const { return TD; }
175 /// setPrintAuxCalls - If you call this method, the auxillary call vector will
176 /// be printed instead of the standard call vector to the dot file.
178 void setPrintAuxCalls() { PrintAuxCalls = true; }
179 bool shouldPrintAuxCalls() const { return PrintAuxCalls; }
181 /// node_iterator/begin/end - Iterate over all of the nodes in the graph. Be
182 /// extremely careful with these methods because any merging of nodes could
183 /// cause the node to be removed from this list. This means that if you are
184 /// iterating over nodes and doing something that could cause _any_ node to
185 /// merge, your node_iterators into this graph can be invalidated.
186 typedef NodeListTy::compat_iterator node_iterator;
187 node_iterator node_begin() const { return Nodes.compat_begin(); }
188 node_iterator node_end() const { return Nodes.compat_end(); }
190 /// getFunctionNames - Return a space separated list of the name of the
191 /// functions in this graph (if any)
192 std::string getFunctionNames() const;
194 /// addNode - Add a new node to the graph.
196 void addNode(DSNode *N) { Nodes.push_back(N); }
197 void unlinkNode(DSNode *N) { Nodes.remove(N); }
199 /// getScalarMap - Get a map that describes what the nodes the scalars in this
200 /// function point to...
202 ScalarMapTy &getScalarMap() { return ScalarMap; }
203 const ScalarMapTy &getScalarMap() const { return ScalarMap; }
205 /// getFunctionCalls - Return the list of call sites in the original local
208 const std::vector<DSCallSite> &getFunctionCalls() const {
209 return FunctionCalls;
212 /// getAuxFunctionCalls - Get the call sites as modified by whatever passes
215 std::vector<DSCallSite> &getAuxFunctionCalls() {
216 return AuxFunctionCalls;
218 const std::vector<DSCallSite> &getAuxFunctionCalls() const {
219 return AuxFunctionCalls;
222 /// getInlinedGlobals - Get the set of globals that are have been inlined
223 /// (from callees in BU or from callers in TD) into the current graph.
225 GlobalSetTy& getInlinedGlobals() {
226 return InlinedGlobals;
229 /// getNodeForValue - Given a value that is used or defined in the body of the
230 /// current function, return the DSNode that it points to.
232 DSNodeHandle &getNodeForValue(Value *V) { return ScalarMap[V]; }
234 const DSNodeHandle &getNodeForValue(Value *V) const {
235 ScalarMapTy::const_iterator I = ScalarMap.find(V);
236 assert(I != ScalarMap.end() &&
237 "Use non-const lookup function if node may not be in the map");
241 /// getReturnNodes - Return the mapping of functions to their return nodes for
243 const ReturnNodesTy &getReturnNodes() const { return ReturnNodes; }
244 ReturnNodesTy &getReturnNodes() { return ReturnNodes; }
246 /// getReturnNodeFor - Return the return node for the specified function.
248 DSNodeHandle &getReturnNodeFor(Function &F) {
249 ReturnNodesTy::iterator I = ReturnNodes.find(&F);
250 assert(I != ReturnNodes.end() && "F not in this DSGraph!");
254 const DSNodeHandle &getReturnNodeFor(Function &F) const {
255 ReturnNodesTy::const_iterator I = ReturnNodes.find(&F);
256 assert(I != ReturnNodes.end() && "F not in this DSGraph!");
260 /// getGraphSize - Return the number of nodes in this graph.
262 unsigned getGraphSize() const {
266 /// print - Print a dot graph to the specified ostream...
268 void print(std::ostream &O) const;
270 /// dump - call print(std::cerr), for use from the debugger...
274 /// viewGraph - Emit a dot graph, run 'dot', run gv on the postscript file,
275 /// then cleanup. For use from the debugger.
276 void viewGraph() const;
278 void writeGraphToFile(std::ostream &O, const std::string &GraphName) const;
280 /// maskNodeTypes - Apply a mask to all of the node types in the graph. This
281 /// is useful for clearing out markers like Incomplete.
283 void maskNodeTypes(unsigned Mask) {
284 for (node_iterator I = node_begin(), E = node_end(); I != E; ++I)
285 (*I)->maskNodeTypes(Mask);
287 void maskIncompleteMarkers() { maskNodeTypes(~DSNode::Incomplete); }
289 // markIncompleteNodes - Traverse the graph, identifying nodes that may be
290 // modified by other functions that have not been resolved yet. This marks
291 // nodes that are reachable through three sources of "unknownness":
292 // Global Variables, Function Calls, and Incoming Arguments
294 // For any node that may have unknown components (because something outside
295 // the scope of current analysis may have modified it), the 'Incomplete' flag
296 // is added to the NodeType.
298 enum MarkIncompleteFlags {
299 MarkFormalArgs = 1, IgnoreFormalArgs = 0,
300 IgnoreGlobals = 2, MarkGlobalsIncomplete = 0,
302 void markIncompleteNodes(unsigned Flags);
304 // removeDeadNodes - Use a reachability analysis to eliminate subgraphs that
305 // are unreachable. This often occurs because the data structure doesn't
306 // "escape" into it's caller, and thus should be eliminated from the caller's
307 // graph entirely. This is only appropriate to use when inlining graphs.
309 enum RemoveDeadNodesFlags {
310 RemoveUnreachableGlobals = 1, KeepUnreachableGlobals = 0,
312 void removeDeadNodes(unsigned Flags);
314 /// CloneFlags enum - Bits that may be passed into the cloneInto method to
315 /// specify how to clone the function graph.
317 StripAllocaBit = 1 << 0, KeepAllocaBit = 0,
318 DontCloneCallNodes = 1 << 1, CloneCallNodes = 0,
319 DontCloneAuxCallNodes = 1 << 2, CloneAuxCallNodes = 0,
320 StripModRefBits = 1 << 3, KeepModRefBits = 0,
321 StripIncompleteBit = 1 << 4, KeepIncompleteBit = 0,
322 UpdateInlinedGlobals = 1 << 5, DontUpdateInlinedGlobals = 0,
325 void updateFromGlobalGraph();
327 /// computeNodeMapping - Given roots in two different DSGraphs, traverse the
328 /// nodes reachable from the two graphs, computing the mapping of nodes from
329 /// the first to the second graph.
331 static void computeNodeMapping(const DSNodeHandle &NH1,
332 const DSNodeHandle &NH2, NodeMapTy &NodeMap,
333 bool StrictChecking = true);
336 /// cloneInto - Clone the specified DSGraph into the current graph. The
337 /// translated ScalarMap for the old function is filled into the OldValMap
338 /// member, and the translated ReturnNodes map is returned into ReturnNodes.
339 /// OldNodeMap contains a mapping from the original nodes to the newly cloned
342 /// The CloneFlags member controls various aspects of the cloning process.
344 void cloneInto(const DSGraph &G, ScalarMapTy &OldValMap,
345 ReturnNodesTy &OldReturnNodes, NodeMapTy &OldNodeMap,
346 unsigned CloneFlags = 0);
348 /// mergeInGraph - The method is used for merging graphs together. If the
349 /// argument graph is not *this, it makes a clone of the specified graph, then
350 /// merges the nodes specified in the call site with the formal arguments in
351 /// the graph. If the StripAlloca's argument is 'StripAllocaBit' then Alloca
352 /// markers are removed from nodes.
354 void mergeInGraph(const DSCallSite &CS, Function &F, const DSGraph &Graph,
355 unsigned CloneFlags);
358 /// getCallSiteForArguments - Get the arguments and return value bindings for
359 /// the specified function in the current graph.
361 DSCallSite getCallSiteForArguments(Function &F) const;
363 // Methods for checking to make sure graphs are well formed...
364 void AssertNodeInGraph(const DSNode *N) const {
365 assert((!N || N->getParentGraph() == this) &&
366 "AssertNodeInGraph: Node is not in graph!");
368 void AssertNodeContainsGlobal(const DSNode *N, GlobalValue *GV) const {
369 assert(std::find(N->getGlobals().begin(), N->getGlobals().end(), GV) !=
370 N->getGlobals().end() && "Global value not in node!");
373 void AssertCallSiteInGraph(const DSCallSite &CS) const {
374 if (CS.isIndirectCall())
375 AssertNodeInGraph(CS.getCalleeNode());
376 AssertNodeInGraph(CS.getRetVal().getNode());
377 for (unsigned j = 0, e = CS.getNumPtrArgs(); j != e; ++j)
378 AssertNodeInGraph(CS.getPtrArg(j).getNode());
381 void AssertCallNodesInGraph() const {
382 for (unsigned i = 0, e = FunctionCalls.size(); i != e; ++i)
383 AssertCallSiteInGraph(FunctionCalls[i]);
385 void AssertAuxCallNodesInGraph() const {
386 for (unsigned i = 0, e = AuxFunctionCalls.size(); i != e; ++i)
387 AssertCallSiteInGraph(AuxFunctionCalls[i]);
390 void AssertGraphOK() const;
392 /// removeTriviallyDeadNodes - After the graph has been constructed, this
393 /// method removes all unreachable nodes that are created because they got
394 /// merged with other nodes in the graph. This is used as the first step of
397 void removeTriviallyDeadNodes();
401 /// ReachabilityCloner - This class is used to incrementally clone and merge
402 /// nodes from a non-changing source graph into a potentially mutating
403 /// destination graph. Nodes are only cloned over on demand, either in
404 /// responds to a merge() or getClonedNH() call. When a node is cloned over,
405 /// all of the nodes reachable from it are automatically brought over as well.
406 class ReachabilityCloner {
410 /// BitsToKeep - These bits are retained from the source node when the
411 /// source nodes are merged into the destination graph.
415 // NodeMap - A mapping from nodes in the source graph to the nodes that
416 // represent them in the destination graph.
417 DSGraph::NodeMapTy NodeMap;
419 ReachabilityCloner(DSGraph &dest, const DSGraph &src, unsigned cloneFlags)
420 : Dest(dest), Src(src), CloneFlags(cloneFlags) {
421 assert(&Dest != &Src && "Cannot clone from graph to same graph!");
422 BitsToKeep = ~DSNode::DEAD;
423 if (CloneFlags & DSGraph::StripAllocaBit)
424 BitsToKeep &= ~DSNode::AllocaNode;
425 if (CloneFlags & DSGraph::StripModRefBits)
426 BitsToKeep &= ~(DSNode::Modified | DSNode::Read);
427 if (CloneFlags & DSGraph::StripIncompleteBit)
428 BitsToKeep &= ~DSNode::Incomplete;
431 DSNodeHandle getClonedNH(const DSNodeHandle &SrcNH);
433 void merge(const DSNodeHandle &NH, const DSNodeHandle &SrcNH);
435 /// mergeCallSite - Merge the nodes reachable from the specified src call
436 /// site into the nodes reachable from DestCS.
437 void mergeCallSite(const DSCallSite &DestCS, const DSCallSite &SrcCS);
439 bool clonedNode() const { return !NodeMap.empty(); }
441 void destroy() { NodeMap.clear(); }
443 } // End llvm namespace