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/DataStructure/DSNode.h"
19 #include "llvm/ADT/hash_map"
25 //===----------------------------------------------------------------------===//
26 /// DSScalarMap - An instance of this class is used to keep track of all of
27 /// which DSNode each scalar in a function points to. This is specialized to
28 /// keep track of globals with nodes in the function, and to keep track of the
29 /// unique DSNodeHandle being used by the scalar map.
31 /// This class is crucial to the efficiency of DSA with some large SCC's. In
32 /// these cases, the cost of iterating over the scalar map dominates the cost
33 /// of DSA. In all of these cases, the DSA phase is really trying to identify
34 /// globals or unique node handles active in the function.
37 typedef hash_map<Value*, DSNodeHandle> ValueMapTy;
40 typedef hash_set<GlobalValue*> GlobalSetTy;
41 GlobalSetTy GlobalSet;
44 // Compatibility methods: provide an interface compatible with a map of
45 // Value* to DSNodeHandle's.
46 typedef ValueMapTy::const_iterator const_iterator;
47 typedef ValueMapTy::iterator iterator;
48 iterator begin() { return ValueMap.begin(); }
49 iterator end() { return ValueMap.end(); }
50 const_iterator begin() const { return ValueMap.begin(); }
51 const_iterator end() const { return ValueMap.end(); }
52 iterator find(Value *V) { return ValueMap.find(V); }
53 const_iterator find(Value *V) const { return ValueMap.find(V); }
54 unsigned count(Value *V) const { return ValueMap.count(V); }
56 void erase(Value *V) { erase(find(V)); }
58 /// replaceScalar - When an instruction needs to be modified, this method can
59 /// be used to update the scalar map to remove the old and insert the new.
61 void replaceScalar(Value *Old, Value *New) {
62 iterator I = find(Old);
63 assert(I != end() && "Old value is not in the map!");
64 ValueMap.insert(std::make_pair(New, I->second));
68 DSNodeHandle &operator[](Value *V) {
69 std::pair<iterator,bool> IP =
70 ValueMap.insert(std::make_pair(V, DSNodeHandle()));
71 if (IP.second) { // Inserted the new entry into the map.
72 if (GlobalValue *GV = dyn_cast<GlobalValue>(V))
75 return IP.first->second;
78 void erase(iterator I) {
79 assert(I != ValueMap.end() && "Cannot erase end!");
80 if (GlobalValue *GV = dyn_cast<GlobalValue>(I->first))
90 // Access to the global set: the set of all globals currently in the
92 typedef GlobalSetTy::const_iterator global_iterator;
93 global_iterator global_begin() const { return GlobalSet.begin(); }
94 global_iterator global_end() const { return GlobalSet.end(); }
98 //===----------------------------------------------------------------------===//
99 /// DSGraph - The graph that represents a function.
103 // Public data-type declarations...
104 typedef DSScalarMap ScalarMapTy;
105 typedef hash_map<Function*, DSNodeHandle> ReturnNodesTy;
106 typedef hash_set<GlobalValue*> GlobalSetTy;
107 typedef ilist<DSNode> NodeListTy;
109 /// NodeMapTy - This data type is used when cloning one graph into another to
110 /// keep track of the correspondence between the nodes in the old and new
112 typedef hash_map<const DSNode*, DSNodeHandle> NodeMapTy;
114 DSGraph *GlobalsGraph; // Pointer to the common graph of global objects
115 bool PrintAuxCalls; // Should this graph print the Aux calls vector?
118 ScalarMapTy ScalarMap;
120 // ReturnNodes - A return value for every function merged into this graph.
121 // Each DSGraph may have multiple functions merged into it at any time, which
122 // is used for representing SCCs.
124 ReturnNodesTy ReturnNodes;
126 // FunctionCalls - This vector maintains a single entry for each call
127 // instruction in the current graph. The first entry in the vector is the
128 // scalar that holds the return value for the call, the second is the function
129 // scalar being invoked, and the rest are pointer arguments to the function.
130 // This vector is built by the Local graph and is never modified after that.
132 std::vector<DSCallSite> FunctionCalls;
134 // AuxFunctionCalls - This vector contains call sites that have been processed
135 // by some mechanism. In pratice, the BU Analysis uses this vector to hold
136 // the _unresolved_ call sites, because it cannot modify FunctionCalls.
138 std::vector<DSCallSite> AuxFunctionCalls;
140 // InlinedGlobals - This set records which globals have been inlined from
141 // other graphs (callers or callees, depending on the pass) into this one.
143 GlobalSetTy InlinedGlobals;
145 /// TD - This is the target data object for the machine this graph is
147 const TargetData &TD;
149 void operator=(const DSGraph &); // DO NOT IMPLEMENT
152 // Create a new, empty, DSGraph.
153 DSGraph(const TargetData &td)
154 : GlobalsGraph(0), PrintAuxCalls(false), TD(td) {}
156 // Compute the local DSGraph
157 DSGraph(const TargetData &td, Function &F, DSGraph *GlobalsGraph);
159 // Copy ctor - If you want to capture the node mapping between the source and
160 // destination graph, you may optionally do this by specifying a map to record
163 // Note that a copied graph does not retain the GlobalsGraph pointer of the
164 // source. You need to set a new GlobalsGraph with the setGlobalsGraph
167 DSGraph(const DSGraph &DSG);
168 DSGraph(const DSGraph &DSG, NodeMapTy &NodeMap);
171 DSGraph *getGlobalsGraph() const { return GlobalsGraph; }
172 void setGlobalsGraph(DSGraph *G) { GlobalsGraph = G; }
174 /// getTargetData - Return the TargetData object for the current target.
176 const TargetData &getTargetData() const { return TD; }
178 /// setPrintAuxCalls - If you call this method, the auxillary call vector will
179 /// be printed instead of the standard call vector to the dot file.
181 void setPrintAuxCalls() { PrintAuxCalls = true; }
182 bool shouldPrintAuxCalls() const { return PrintAuxCalls; }
184 /// node_iterator/begin/end - Iterate over all of the nodes in the graph. Be
185 /// extremely careful with these methods because any merging of nodes could
186 /// cause the node to be removed from this list. This means that if you are
187 /// iterating over nodes and doing something that could cause _any_ node to
188 /// merge, your node_iterators into this graph can be invalidated.
189 typedef NodeListTy::compat_iterator node_iterator;
190 node_iterator node_begin() const { return Nodes.compat_begin(); }
191 node_iterator node_end() const { return Nodes.compat_end(); }
193 /// getFunctionNames - Return a space separated list of the name of the
194 /// functions in this graph (if any)
196 std::string getFunctionNames() const;
198 /// addNode - Add a new node to the graph.
200 void addNode(DSNode *N) { Nodes.push_back(N); }
201 void unlinkNode(DSNode *N) { Nodes.remove(N); }
203 /// getScalarMap - Get a map that describes what the nodes the scalars in this
204 /// function point to...
206 ScalarMapTy &getScalarMap() { return ScalarMap; }
207 const ScalarMapTy &getScalarMap() const { return ScalarMap; }
209 /// getFunctionCalls - Return the list of call sites in the original local
212 const std::vector<DSCallSite> &getFunctionCalls() const {
213 return FunctionCalls;
216 /// getAuxFunctionCalls - Get the call sites as modified by whatever passes
219 std::vector<DSCallSite> &getAuxFunctionCalls() {
220 return AuxFunctionCalls;
222 const std::vector<DSCallSite> &getAuxFunctionCalls() const {
223 return AuxFunctionCalls;
226 /// getInlinedGlobals - Get the set of globals that are have been inlined
227 /// (from callees in BU or from callers in TD) into the current graph.
229 GlobalSetTy& getInlinedGlobals() {
230 return InlinedGlobals;
233 /// getNodeForValue - Given a value that is used or defined in the body of the
234 /// current function, return the DSNode that it points to.
236 DSNodeHandle &getNodeForValue(Value *V) { return ScalarMap[V]; }
238 const DSNodeHandle &getNodeForValue(Value *V) const {
239 ScalarMapTy::const_iterator I = ScalarMap.find(V);
240 assert(I != ScalarMap.end() &&
241 "Use non-const lookup function if node may not be in the map");
245 /// getReturnNodes - Return the mapping of functions to their return nodes for
248 const ReturnNodesTy &getReturnNodes() const { return ReturnNodes; }
249 ReturnNodesTy &getReturnNodes() { return ReturnNodes; }
251 /// getReturnNodeFor - Return the return node for the specified function.
253 DSNodeHandle &getReturnNodeFor(Function &F) {
254 ReturnNodesTy::iterator I = ReturnNodes.find(&F);
255 assert(I != ReturnNodes.end() && "F not in this DSGraph!");
259 const DSNodeHandle &getReturnNodeFor(Function &F) const {
260 ReturnNodesTy::const_iterator I = ReturnNodes.find(&F);
261 assert(I != ReturnNodes.end() && "F not in this DSGraph!");
265 /// getGraphSize - Return the number of nodes in this graph.
267 unsigned getGraphSize() const {
271 /// print - Print a dot graph to the specified ostream...
273 void print(std::ostream &O) const;
275 /// dump - call print(std::cerr), for use from the debugger...
279 /// viewGraph - Emit a dot graph, run 'dot', run gv on the postscript file,
280 /// then cleanup. For use from the debugger.
282 void viewGraph() const;
284 void writeGraphToFile(std::ostream &O, const std::string &GraphName) const;
286 /// maskNodeTypes - Apply a mask to all of the node types in the graph. This
287 /// is useful for clearing out markers like Incomplete.
289 void maskNodeTypes(unsigned Mask) {
290 for (node_iterator I = node_begin(), E = node_end(); I != E; ++I)
291 (*I)->maskNodeTypes(Mask);
293 void maskIncompleteMarkers() { maskNodeTypes(~DSNode::Incomplete); }
295 // markIncompleteNodes - Traverse the graph, identifying nodes that may be
296 // modified by other functions that have not been resolved yet. This marks
297 // nodes that are reachable through three sources of "unknownness":
298 // Global Variables, Function Calls, and Incoming Arguments
300 // For any node that may have unknown components (because something outside
301 // the scope of current analysis may have modified it), the 'Incomplete' flag
302 // is added to the NodeType.
304 enum MarkIncompleteFlags {
305 MarkFormalArgs = 1, IgnoreFormalArgs = 0,
306 IgnoreGlobals = 2, MarkGlobalsIncomplete = 0,
308 void markIncompleteNodes(unsigned Flags);
310 // removeDeadNodes - Use a reachability analysis to eliminate subgraphs that
311 // are unreachable. This often occurs because the data structure doesn't
312 // "escape" into it's caller, and thus should be eliminated from the caller's
313 // graph entirely. This is only appropriate to use when inlining graphs.
315 enum RemoveDeadNodesFlags {
316 RemoveUnreachableGlobals = 1, KeepUnreachableGlobals = 0,
318 void removeDeadNodes(unsigned Flags);
320 /// CloneFlags enum - Bits that may be passed into the cloneInto method to
321 /// specify how to clone the function graph.
323 StripAllocaBit = 1 << 0, KeepAllocaBit = 0,
324 DontCloneCallNodes = 1 << 1, CloneCallNodes = 0,
325 DontCloneAuxCallNodes = 1 << 2, CloneAuxCallNodes = 0,
326 StripModRefBits = 1 << 3, KeepModRefBits = 0,
327 StripIncompleteBit = 1 << 4, KeepIncompleteBit = 0,
328 UpdateInlinedGlobals = 1 << 5, DontUpdateInlinedGlobals = 0,
331 void updateFromGlobalGraph();
333 /// computeNodeMapping - Given roots in two different DSGraphs, traverse the
334 /// nodes reachable from the two graphs, computing the mapping of nodes from
335 /// the first to the second graph.
337 static void computeNodeMapping(const DSNodeHandle &NH1,
338 const DSNodeHandle &NH2, NodeMapTy &NodeMap,
339 bool StrictChecking = true);
342 /// cloneInto - Clone the specified DSGraph into the current graph. The
343 /// translated ScalarMap for the old function is filled into the OldValMap
344 /// member, and the translated ReturnNodes map is returned into ReturnNodes.
345 /// OldNodeMap contains a mapping from the original nodes to the newly cloned
348 /// The CloneFlags member controls various aspects of the cloning process.
350 void cloneInto(const DSGraph &G, ScalarMapTy &OldValMap,
351 ReturnNodesTy &OldReturnNodes, NodeMapTy &OldNodeMap,
352 unsigned CloneFlags = 0);
354 /// mergeInGraph - The method is used for merging graphs together. If the
355 /// argument graph is not *this, it makes a clone of the specified graph, then
356 /// merges the nodes specified in the call site with the formal arguments in
357 /// the graph. If the StripAlloca's argument is 'StripAllocaBit' then Alloca
358 /// markers are removed from nodes.
360 void mergeInGraph(const DSCallSite &CS, Function &F, const DSGraph &Graph,
361 unsigned CloneFlags);
363 /// getCallSiteForArguments - Get the arguments and return value bindings for
364 /// the specified function in the current graph.
366 DSCallSite getCallSiteForArguments(Function &F) const;
368 /// getDSCallSiteForCallSite - Given an LLVM CallSite object that is live in
369 /// the context of this graph, return the DSCallSite for it.
370 DSCallSite getDSCallSiteForCallSite(CallSite CS) const;
372 // Methods for checking to make sure graphs are well formed...
373 void AssertNodeInGraph(const DSNode *N) const {
374 assert((!N || N->getParentGraph() == this) &&
375 "AssertNodeInGraph: Node is not in graph!");
377 void AssertNodeContainsGlobal(const DSNode *N, GlobalValue *GV) const;
379 void AssertCallSiteInGraph(const DSCallSite &CS) const;
380 void AssertCallNodesInGraph() const;
381 void AssertAuxCallNodesInGraph() const;
383 void AssertGraphOK() const;
385 /// removeTriviallyDeadNodes - After the graph has been constructed, this
386 /// method removes all unreachable nodes that are created because they got
387 /// merged with other nodes in the graph. This is used as the first step of
390 void removeTriviallyDeadNodes();
394 /// ReachabilityCloner - This class is used to incrementally clone and merge
395 /// nodes from a non-changing source graph into a potentially mutating
396 /// destination graph. Nodes are only cloned over on demand, either in
397 /// responds to a merge() or getClonedNH() call. When a node is cloned over,
398 /// all of the nodes reachable from it are automatically brought over as well.
400 class ReachabilityCloner {
404 /// BitsToKeep - These bits are retained from the source node when the
405 /// source nodes are merged into the destination graph.
409 // NodeMap - A mapping from nodes in the source graph to the nodes that
410 // represent them in the destination graph.
411 DSGraph::NodeMapTy NodeMap;
413 ReachabilityCloner(DSGraph &dest, const DSGraph &src, unsigned cloneFlags)
414 : Dest(dest), Src(src), CloneFlags(cloneFlags) {
415 assert(&Dest != &Src && "Cannot clone from graph to same graph!");
416 BitsToKeep = ~DSNode::DEAD;
417 if (CloneFlags & DSGraph::StripAllocaBit)
418 BitsToKeep &= ~DSNode::AllocaNode;
419 if (CloneFlags & DSGraph::StripModRefBits)
420 BitsToKeep &= ~(DSNode::Modified | DSNode::Read);
421 if (CloneFlags & DSGraph::StripIncompleteBit)
422 BitsToKeep &= ~DSNode::Incomplete;
425 DSNodeHandle getClonedNH(const DSNodeHandle &SrcNH);
427 void merge(const DSNodeHandle &NH, const DSNodeHandle &SrcNH);
429 /// mergeCallSite - Merge the nodes reachable from the specified src call
430 /// site into the nodes reachable from DestCS.
432 void mergeCallSite(const DSCallSite &DestCS, const DSCallSite &SrcCS);
434 bool clonedAnyNodes() const { return !NodeMap.empty(); }
436 /// hasClonedNode - Return true if the specified node has been cloned from
437 /// the source graph into the destination graph.
438 bool hasClonedNode(const DSNode *N) {
439 return NodeMap.count(N);
442 void destroy() { NodeMap.clear(); }
445 } // End llvm namespace