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"
20 #include "llvm/ADT/EquivalenceClasses.h"
27 //===----------------------------------------------------------------------===//
28 /// DSScalarMap - An instance of this class is used to keep track of all of
29 /// which DSNode each scalar in a function points to. This is specialized to
30 /// keep track of globals with nodes in the function, and to keep track of the
31 /// unique DSNodeHandle being used by the scalar map.
33 /// This class is crucial to the efficiency of DSA with some large SCC's. In
34 /// these cases, the cost of iterating over the scalar map dominates the cost
35 /// of DSA. In all of these cases, the DSA phase is really trying to identify
36 /// globals or unique node handles active in the function.
39 typedef hash_map<Value*, DSNodeHandle> ValueMapTy;
42 typedef hash_set<GlobalValue*> GlobalSetTy;
43 GlobalSetTy GlobalSet;
45 EquivalenceClasses<GlobalValue*> &GlobalECs;
47 DSScalarMap(EquivalenceClasses<GlobalValue*> &ECs) : GlobalECs(ECs) {}
49 EquivalenceClasses<GlobalValue*> &getGlobalECs() const { return GlobalECs; }
51 // Compatibility methods: provide an interface compatible with a map of
52 // Value* to DSNodeHandle's.
53 typedef ValueMapTy::const_iterator const_iterator;
54 typedef ValueMapTy::iterator iterator;
55 iterator begin() { return ValueMap.begin(); }
56 iterator end() { return ValueMap.end(); }
57 const_iterator begin() const { return ValueMap.begin(); }
58 const_iterator end() const { return ValueMap.end(); }
60 GlobalValue *getLeaderForGlobal(GlobalValue *GV) const {
61 EquivalenceClasses<GlobalValue*>::iterator ECI = GlobalECs.findValue(GV);
62 if (ECI == GlobalECs.end()) return GV;
63 return *GlobalECs.findLeader(ECI);
67 iterator find(Value *V) {
68 iterator I = ValueMap.find(V);
69 if (I != ValueMap.end()) return I;
71 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
72 // If this is a global, check to see if it is equivalenced to something
74 GlobalValue *Leader = getLeaderForGlobal(GV);
76 I = ValueMap.find((Value*)Leader);
80 const_iterator find(Value *V) const {
81 const_iterator I = ValueMap.find(V);
82 if (I != ValueMap.end()) return I;
84 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
85 // If this is a global, check to see if it is equivalenced to something
87 GlobalValue *Leader = getLeaderForGlobal(GV);
89 I = ValueMap.find((Value*)Leader);
94 unsigned count(Value *V) const { return ValueMap.find(V) != ValueMap.end(); }
96 void erase(Value *V) { erase(ValueMap.find(V)); }
98 void eraseIfExists(Value *V) {
100 if (I != end()) erase(I);
103 /// replaceScalar - When an instruction needs to be modified, this method can
104 /// be used to update the scalar map to remove the old and insert the new.
106 void replaceScalar(Value *Old, Value *New) {
107 iterator I = find(Old);
108 assert(I != end() && "Old value is not in the map!");
109 ValueMap.insert(std::make_pair(New, I->second));
113 /// copyScalarIfExists - If Old exists in the scalar map, make New point to
114 /// whatever Old did.
115 void copyScalarIfExists(Value *Old, Value *New) {
116 iterator I = find(Old);
118 ValueMap.insert(std::make_pair(New, I->second));
122 /// operator[] - Return the DSNodeHandle for the specified value, creating a
123 /// new null handle if there is no entry yet.
124 DSNodeHandle &operator[](Value *V) {
125 iterator I = ValueMap.find(V);
126 if (I != ValueMap.end())
127 return I->second; // Return value if already exists.
129 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
130 // If the node doesn't exist, check to see if it's a global that is
131 // equated to another global in the program.
132 EquivalenceClasses<GlobalValue*>::iterator ECI = GlobalECs.findValue(GV);
133 if (ECI != GlobalECs.end()) {
134 GlobalValue *Leader = *GlobalECs.findLeader(ECI);
136 return operator[]((Value*)Leader);
139 // Okay, this is either not an equivalenced global or it is the leader, it
140 // will be inserted into the scalar map now.
141 GlobalSet.insert(GV);
144 return ValueMap.insert(std::make_pair(V, DSNodeHandle())).first->second;
147 void erase(iterator I) {
148 assert(I != ValueMap.end() && "Cannot erase end!");
149 if (GlobalValue *GV = dyn_cast<GlobalValue>(I->first))
159 // Access to the global set: the set of all globals currently in the
161 typedef GlobalSetTy::const_iterator global_iterator;
162 global_iterator global_begin() const { return GlobalSet.begin(); }
163 global_iterator global_end() const { return GlobalSet.end(); }
164 unsigned global_size() const { return GlobalSet.size(); }
165 unsigned global_count(GlobalValue *GV) const { return GlobalSet.count(GV); }
169 //===----------------------------------------------------------------------===//
170 /// DSGraph - The graph that represents a function.
174 // Public data-type declarations...
175 typedef DSScalarMap ScalarMapTy;
176 typedef hash_map<Function*, DSNodeHandle> ReturnNodesTy;
177 typedef ilist<DSNode> NodeListTy;
179 /// NodeMapTy - This data type is used when cloning one graph into another to
180 /// keep track of the correspondence between the nodes in the old and new
182 typedef hash_map<const DSNode*, DSNodeHandle> NodeMapTy;
184 // InvNodeMapTy - This data type is used to represent the inverse of a node
186 typedef hash_multimap<DSNodeHandle, const DSNode*> InvNodeMapTy;
188 DSGraph *GlobalsGraph; // Pointer to the common graph of global objects
189 bool PrintAuxCalls; // Should this graph print the Aux calls vector?
192 ScalarMapTy ScalarMap;
194 // ReturnNodes - A return value for every function merged into this graph.
195 // Each DSGraph may have multiple functions merged into it at any time, which
196 // is used for representing SCCs.
198 ReturnNodesTy ReturnNodes;
200 // FunctionCalls - This list maintains a single entry for each call
201 // instruction in the current graph. The first entry in the vector is the
202 // scalar that holds the return value for the call, the second is the function
203 // scalar being invoked, and the rest are pointer arguments to the function.
204 // This vector is built by the Local graph and is never modified after that.
206 std::list<DSCallSite> FunctionCalls;
208 // AuxFunctionCalls - This vector contains call sites that have been processed
209 // by some mechanism. In pratice, the BU Analysis uses this vector to hold
210 // the _unresolved_ call sites, because it cannot modify FunctionCalls.
212 std::list<DSCallSite> AuxFunctionCalls;
214 /// TD - This is the target data object for the machine this graph is
216 const TargetData &TD;
218 void operator=(const DSGraph &); // DO NOT IMPLEMENT
219 DSGraph(const DSGraph&); // DO NOT IMPLEMENT
221 // Create a new, empty, DSGraph.
222 DSGraph(EquivalenceClasses<GlobalValue*> &ECs, const TargetData &td)
223 : GlobalsGraph(0), PrintAuxCalls(false), ScalarMap(ECs), TD(td) {}
225 // Compute the local DSGraph
226 DSGraph(EquivalenceClasses<GlobalValue*> &ECs, const TargetData &TD,
227 Function &F, DSGraph *GlobalsGraph);
229 // Copy ctor - If you want to capture the node mapping between the source and
230 // destination graph, you may optionally do this by specifying a map to record
233 // Note that a copied graph does not retain the GlobalsGraph pointer of the
234 // source. You need to set a new GlobalsGraph with the setGlobalsGraph
237 DSGraph(const DSGraph &DSG, EquivalenceClasses<GlobalValue*> &ECs);
238 DSGraph(const DSGraph &DSG, NodeMapTy &NodeMap,
239 EquivalenceClasses<GlobalValue*> &ECs);
242 DSGraph *getGlobalsGraph() const { return GlobalsGraph; }
243 void setGlobalsGraph(DSGraph *G) { GlobalsGraph = G; }
245 /// getGlobalECs - Return the set of equivalence classes that the global
246 /// variables in the program form.
247 EquivalenceClasses<GlobalValue*> &getGlobalECs() const {
248 return ScalarMap.getGlobalECs();
251 /// getTargetData - Return the TargetData object for the current target.
253 const TargetData &getTargetData() const { return TD; }
255 /// setPrintAuxCalls - If you call this method, the auxillary call vector will
256 /// be printed instead of the standard call vector to the dot file.
258 void setPrintAuxCalls() { PrintAuxCalls = true; }
259 bool shouldPrintAuxCalls() const { return PrintAuxCalls; }
261 /// node_iterator/begin/end - Iterate over all of the nodes in the graph. Be
262 /// extremely careful with these methods because any merging of nodes could
263 /// cause the node to be removed from this list. This means that if you are
264 /// iterating over nodes and doing something that could cause _any_ node to
265 /// merge, your node_iterators into this graph can be invalidated.
266 typedef NodeListTy::iterator node_iterator;
267 node_iterator node_begin() { return Nodes.begin(); }
268 node_iterator node_end() { return Nodes.end(); }
270 typedef NodeListTy::const_iterator node_const_iterator;
271 node_const_iterator node_begin() const { return Nodes.begin(); }
272 node_const_iterator node_end() const { return Nodes.end(); }
274 /// getFunctionNames - Return a space separated list of the name of the
275 /// functions in this graph (if any)
277 std::string getFunctionNames() const;
279 /// addNode - Add a new node to the graph.
281 void addNode(DSNode *N) { Nodes.push_back(N); }
282 void unlinkNode(DSNode *N) { Nodes.remove(N); }
284 /// getScalarMap - Get a map that describes what the nodes the scalars in this
285 /// function point to...
287 ScalarMapTy &getScalarMap() { return ScalarMap; }
288 const ScalarMapTy &getScalarMap() const { return ScalarMap; }
290 /// getFunctionCalls - Return the list of call sites in the original local
293 const std::list<DSCallSite> &getFunctionCalls() const { return FunctionCalls;}
294 std::list<DSCallSite> &getFunctionCalls() { return FunctionCalls;}
296 /// getAuxFunctionCalls - Get the call sites as modified by whatever passes
299 std::list<DSCallSite> &getAuxFunctionCalls() { return AuxFunctionCalls; }
300 const std::list<DSCallSite> &getAuxFunctionCalls() const {
301 return AuxFunctionCalls;
304 // Function Call iteration
305 typedef std::list<DSCallSite>::const_iterator fc_iterator;
306 fc_iterator fc_begin() const { return FunctionCalls.begin(); }
307 fc_iterator fc_end() const { return FunctionCalls.end(); }
310 // Aux Function Call iteration
311 typedef std::list<DSCallSite>::const_iterator afc_iterator;
312 afc_iterator afc_begin() const { return AuxFunctionCalls.begin(); }
313 afc_iterator afc_end() const { return AuxFunctionCalls.end(); }
315 /// getNodeForValue - Given a value that is used or defined in the body of the
316 /// current function, return the DSNode that it points to.
318 DSNodeHandle &getNodeForValue(Value *V) { return ScalarMap[V]; }
320 const DSNodeHandle &getNodeForValue(Value *V) const {
321 ScalarMapTy::const_iterator I = ScalarMap.find(V);
322 assert(I != ScalarMap.end() &&
323 "Use non-const lookup function if node may not be in the map");
327 /// retnodes_* iterator methods: expose iteration over return nodes in the
328 /// graph, which are also the set of functions incorporated in this graph.
329 typedef ReturnNodesTy::const_iterator retnodes_iterator;
330 retnodes_iterator retnodes_begin() const { return ReturnNodes.begin(); }
331 retnodes_iterator retnodes_end() const { return ReturnNodes.end(); }
334 /// getReturnNodes - Return the mapping of functions to their return nodes for
337 const ReturnNodesTy &getReturnNodes() const { return ReturnNodes; }
338 ReturnNodesTy &getReturnNodes() { return ReturnNodes; }
340 /// getReturnNodeFor - Return the return node for the specified function.
342 DSNodeHandle &getReturnNodeFor(Function &F) {
343 ReturnNodesTy::iterator I = ReturnNodes.find(&F);
344 assert(I != ReturnNodes.end() && "F not in this DSGraph!");
348 const DSNodeHandle &getReturnNodeFor(Function &F) const {
349 ReturnNodesTy::const_iterator I = ReturnNodes.find(&F);
350 assert(I != ReturnNodes.end() && "F not in this DSGraph!");
354 /// containsFunction - Return true if this DSGraph contains information for
355 /// the specified function.
356 bool containsFunction(Function *F) const {
357 return ReturnNodes.count(F);
360 /// getGraphSize - Return the number of nodes in this graph.
362 unsigned getGraphSize() const {
366 /// addObjectToGraph - This method can be used to add global, stack, and heap
367 /// objects to the graph. This can be used when updating DSGraphs due to the
368 /// introduction of new temporary objects. The new object is not pointed to
369 /// and does not point to any other objects in the graph. Note that this
370 /// method initializes the type of the DSNode to the declared type of the
371 /// object if UseDeclaredType is true, otherwise it leaves the node type as
373 DSNode *addObjectToGraph(Value *Ptr, bool UseDeclaredType = true);
376 /// print - Print a dot graph to the specified ostream...
378 void print(std::ostream &O) const;
380 /// dump - call print(std::cerr), for use from the debugger...
384 /// viewGraph - Emit a dot graph, run 'dot', run gv on the postscript file,
385 /// then cleanup. For use from the debugger.
387 void viewGraph() const;
389 void writeGraphToFile(std::ostream &O, const std::string &GraphName) const;
391 /// maskNodeTypes - Apply a mask to all of the node types in the graph. This
392 /// is useful for clearing out markers like Incomplete.
394 void maskNodeTypes(unsigned Mask) {
395 for (node_iterator I = node_begin(), E = node_end(); I != E; ++I)
396 I->maskNodeTypes(Mask);
398 void maskIncompleteMarkers() { maskNodeTypes(~DSNode::Incomplete); }
400 // markIncompleteNodes - Traverse the graph, identifying nodes that may be
401 // modified by other functions that have not been resolved yet. This marks
402 // nodes that are reachable through three sources of "unknownness":
403 // Global Variables, Function Calls, and Incoming Arguments
405 // For any node that may have unknown components (because something outside
406 // the scope of current analysis may have modified it), the 'Incomplete' flag
407 // is added to the NodeType.
409 enum MarkIncompleteFlags {
410 MarkFormalArgs = 1, IgnoreFormalArgs = 0,
411 IgnoreGlobals = 2, MarkGlobalsIncomplete = 0,
413 void markIncompleteNodes(unsigned Flags);
415 // removeDeadNodes - Use a reachability analysis to eliminate subgraphs that
416 // are unreachable. This often occurs because the data structure doesn't
417 // "escape" into it's caller, and thus should be eliminated from the caller's
418 // graph entirely. This is only appropriate to use when inlining graphs.
420 enum RemoveDeadNodesFlags {
421 RemoveUnreachableGlobals = 1, KeepUnreachableGlobals = 0,
423 void removeDeadNodes(unsigned Flags);
425 /// CloneFlags enum - Bits that may be passed into the cloneInto method to
426 /// specify how to clone the function graph.
428 StripAllocaBit = 1 << 0, KeepAllocaBit = 0,
429 DontCloneCallNodes = 1 << 1, CloneCallNodes = 0,
430 DontCloneAuxCallNodes = 1 << 2, CloneAuxCallNodes = 0,
431 StripModRefBits = 1 << 3, KeepModRefBits = 0,
432 StripIncompleteBit = 1 << 4, KeepIncompleteBit = 0,
435 void updateFromGlobalGraph();
437 /// computeNodeMapping - Given roots in two different DSGraphs, traverse the
438 /// nodes reachable from the two graphs, computing the mapping of nodes from
439 /// the first to the second graph.
441 static void computeNodeMapping(const DSNodeHandle &NH1,
442 const DSNodeHandle &NH2, NodeMapTy &NodeMap,
443 bool StrictChecking = true);
445 /// computeGToGGMapping - Compute the mapping of nodes in the graph to nodes
446 /// in the globals graph.
447 void computeGToGGMapping(NodeMapTy &NodeMap);
449 /// computeGGToGMapping - Compute the mapping of nodes in the global
450 /// graph to nodes in this graph.
451 void computeGGToGMapping(InvNodeMapTy &InvNodeMap);
453 /// computeCalleeCallerMapping - Given a call from a function in the current
454 /// graph to the 'Callee' function (which lives in 'CalleeGraph'), compute the
455 /// mapping of nodes from the callee to nodes in the caller.
456 void computeCalleeCallerMapping(DSCallSite CS, const Function &Callee,
457 DSGraph &CalleeGraph, NodeMapTy &NodeMap);
459 /// cloneInto - Clone the specified DSGraph into the current graph. The
460 /// translated ScalarMap for the old function is filled into the OldValMap
461 /// member, and the translated ReturnNodes map is returned into ReturnNodes.
462 /// OldNodeMap contains a mapping from the original nodes to the newly cloned
465 /// The CloneFlags member controls various aspects of the cloning process.
467 void cloneInto(const DSGraph &G, ScalarMapTy &OldValMap,
468 ReturnNodesTy &OldReturnNodes, NodeMapTy &OldNodeMap,
469 unsigned CloneFlags = 0);
471 /// getFunctionArgumentsForCall - Given a function that is currently in this
472 /// graph, return the DSNodeHandles that correspond to the pointer-compatible
473 /// function arguments. The vector is filled in with the return value (or
474 /// null if it is not pointer compatible), followed by all of the
475 /// pointer-compatible arguments.
476 void getFunctionArgumentsForCall(Function *F,
477 std::vector<DSNodeHandle> &Args) const;
479 /// mergeInGraph - This graph merges in the minimal number of
480 /// nodes from G2 into 'this' graph, merging the bindings specified by the
481 /// call site (in this graph) with the bindings specified by the vector in G2.
482 /// If the StripAlloca's argument is 'StripAllocaBit' then Alloca markers are
483 /// removed from nodes.
485 void mergeInGraph(const DSCallSite &CS, std::vector<DSNodeHandle> &Args,
486 const DSGraph &G2, unsigned CloneFlags);
488 /// mergeInGraph - This method is the same as the above method, but the
489 /// argument bindings are provided by using the formal arguments of F.
491 void mergeInGraph(const DSCallSite &CS, Function &F, const DSGraph &Graph,
492 unsigned CloneFlags);
494 /// getCallSiteForArguments - Get the arguments and return value bindings for
495 /// the specified function in the current graph.
497 DSCallSite getCallSiteForArguments(Function &F) const;
499 /// getDSCallSiteForCallSite - Given an LLVM CallSite object that is live in
500 /// the context of this graph, return the DSCallSite for it.
501 DSCallSite getDSCallSiteForCallSite(CallSite CS) const;
503 // Methods for checking to make sure graphs are well formed...
504 void AssertNodeInGraph(const DSNode *N) const {
505 assert((!N || N->getParentGraph() == this) &&
506 "AssertNodeInGraph: Node is not in graph!");
508 void AssertNodeContainsGlobal(const DSNode *N, GlobalValue *GV) const;
510 void AssertCallSiteInGraph(const DSCallSite &CS) const;
511 void AssertCallNodesInGraph() const;
512 void AssertAuxCallNodesInGraph() const;
514 void AssertGraphOK() const;
516 /// removeTriviallyDeadNodes - After the graph has been constructed, this
517 /// method removes all unreachable nodes that are created because they got
518 /// merged with other nodes in the graph. This is used as the first step of
521 void removeTriviallyDeadNodes();
525 /// ReachabilityCloner - This class is used to incrementally clone and merge
526 /// nodes from a non-changing source graph into a potentially mutating
527 /// destination graph. Nodes are only cloned over on demand, either in
528 /// responds to a merge() or getClonedNH() call. When a node is cloned over,
529 /// all of the nodes reachable from it are automatically brought over as well.
531 class ReachabilityCloner {
535 /// BitsToKeep - These bits are retained from the source node when the
536 /// source nodes are merged into the destination graph.
540 // NodeMap - A mapping from nodes in the source graph to the nodes that
541 // represent them in the destination graph.
542 DSGraph::NodeMapTy NodeMap;
544 ReachabilityCloner(DSGraph &dest, const DSGraph &src, unsigned cloneFlags)
545 : Dest(dest), Src(src), CloneFlags(cloneFlags) {
546 assert(&Dest != &Src && "Cannot clone from graph to same graph!");
547 BitsToKeep = ~DSNode::DEAD;
548 if (CloneFlags & DSGraph::StripAllocaBit)
549 BitsToKeep &= ~DSNode::AllocaNode;
550 if (CloneFlags & DSGraph::StripModRefBits)
551 BitsToKeep &= ~(DSNode::Modified | DSNode::Read);
552 if (CloneFlags & DSGraph::StripIncompleteBit)
553 BitsToKeep &= ~DSNode::Incomplete;
556 DSNodeHandle getClonedNH(const DSNodeHandle &SrcNH);
558 void merge(const DSNodeHandle &NH, const DSNodeHandle &SrcNH);
560 /// mergeCallSite - Merge the nodes reachable from the specified src call
561 /// site into the nodes reachable from DestCS.
563 void mergeCallSite(const DSCallSite &DestCS, const DSCallSite &SrcCS);
565 bool clonedAnyNodes() const { return !NodeMap.empty(); }
567 /// hasClonedNode - Return true if the specified node has been cloned from
568 /// the source graph into the destination graph.
569 bool hasClonedNode(const DSNode *N) {
570 return NodeMap.count(N);
573 void destroy() { NodeMap.clear(); }
576 } // End llvm namespace