1 //===- DataStructure.h - Build data structure graphs -------------*- C++ -*--=//
3 // Implement the LLVM data structure analysis library.
5 //===----------------------------------------------------------------------===//
7 #ifndef LLVM_ANALYSIS_DATA_STRUCTURE_H
8 #define LLVM_ANALYSIS_DATA_STRUCTURE_H
10 #include "llvm/Pass.h"
15 class DSNode; // Each node in the graph
16 class DSGraph; // A graph for a function
17 class DSNodeIterator; // Data structure graph traversal iterator
18 class LocalDataStructures; // A collection of local graphs for a program
19 class BUDataStructures; // A collection of bu graphs for a program
20 class TDDataStructures; // A collection of td graphs for a program
22 //===----------------------------------------------------------------------===//
23 // DSNodeHandle - Implement a "handle" to a data structure node that takes care
24 // of all of the add/un'refing of the node to prevent the backpointers in the
25 // graph from getting out of date.
30 // Allow construction, destruction, and assignment...
31 DSNodeHandle(DSNode *n = 0) : N(0) { operator=(n); }
32 DSNodeHandle(const DSNodeHandle &H) : N(0) { operator=(H.N); }
33 ~DSNodeHandle() { operator=(0); }
34 DSNodeHandle &operator=(const DSNodeHandle &H) {operator=(H.N); return *this;}
36 // Assignment of DSNode*, implement all of the add/un'refing (defined later)
37 inline DSNodeHandle &operator=(DSNode *n);
39 // Allow automatic, implicit, conversion to DSNode*
40 operator DSNode*() { return N; }
41 operator const DSNode*() const { return N; }
42 operator bool() const { return N != 0; }
43 operator bool() { return N != 0; }
45 bool operator<(const DSNodeHandle &H) const { // Allow sorting
48 bool operator==(const DSNodeHandle &H) const { return N == H.N; }
49 bool operator!=(const DSNodeHandle &H) const { return N != H.N; }
50 bool operator==(const DSNode *Node) const { return N == Node; }
51 bool operator!=(const DSNode *Node) const { return N != Node; }
53 // Avoid having comparisons to null cause errors...
54 bool operator==(int X) const { return operator==((DSNode*)X); }
56 // Allow explicit conversion to DSNode...
57 DSNode *get() { return N; }
58 const DSNode *get() const { return N; }
60 // Allow this to be treated like a pointer...
61 DSNode *operator->() { return N; }
62 const DSNode *operator->() const { return N; }
66 //===----------------------------------------------------------------------===//
67 // DSNode - Data structure node class
69 // This class keeps track of a node's type, and the fields in the data
75 std::vector<DSNodeHandle> Links;
76 std::vector<DSNodeHandle*> Referrers;
78 // Globals - The list of global values that are merged into this node.
79 std::vector<GlobalValue*> Globals;
81 void operator=(const DSNode &); // DO NOT IMPLEMENT
84 ShadowNode = 0 << 0, // Nothing is known about this node...
85 ScalarNode = 1 << 0, // Scalar of the current function contains this value
86 AllocaNode = 1 << 1, // This node was allocated with alloca
87 NewNode = 1 << 2, // This node was allocated with malloc
88 GlobalNode = 1 << 3, // This node was allocated by a global var decl
89 SubElement = 1 << 4, // This node is a part of some other node
90 CastNode = 1 << 5, // This node is accessed in unsafe ways
91 Incomplete = 1 << 6, // This node may not be complete
94 // NodeType - A union of the above bits. "Shadow" nodes do not add any flags
95 // to the nodes in the data structure graph, so it is possible to have nodes
96 // with a value of 0 for their NodeType. Scalar and Alloca markers go away
97 // when function graphs are inlined.
99 unsigned char NodeType;
101 DSNode(enum NodeTy NT, const Type *T);
102 DSNode(const DSNode &);
106 dropAllReferences(); // Only needed to satisfy assertion checks...
108 assert(Referrers.empty() && "Referrers to dead node exist!");
111 // Iterator for graph interface...
112 typedef DSNodeIterator iterator;
113 inline iterator begin(); // Defined in DataStructureGraph.h
114 inline iterator end();
117 const Type *getType() const { return Ty; }
119 unsigned getNumLinks() const { return Links.size(); }
120 DSNode *getLink(unsigned i) {
121 assert(i < getNumLinks() && "Field links access out of range...");
124 const DSNode *getLink(unsigned i) const {
125 assert(i < getNumLinks() && "Field links access out of range...");
129 void setLink(unsigned i, DSNode *N) {
130 assert(i < getNumLinks() && "Field links access out of range...");
134 // addGlobal - Add an entry for a global value to the Globals list. This also
135 // marks the node with the 'G' flag if it does not already have it.
137 void addGlobal(GlobalValue *GV);
138 const std::vector<GlobalValue*> &getGlobals() const { return Globals; }
139 std::vector<GlobalValue*> &getGlobals() { return Globals; }
141 // addEdgeTo - Add an edge from the current node to the specified node. This
142 // can cause merging of nodes in the graph.
144 void addEdgeTo(unsigned LinkNo, DSNode *N);
145 void addEdgeTo(DSNode *N) {
146 assert(getNumLinks() == 1 && "Must specify a field number to add edge if "
147 " more than one field exists!");
151 // mergeWith - Merge this node into the specified node, moving all links to
152 // and from the argument node into the current node. The specified node may
153 // be a null pointer (in which case, nothing happens).
155 void mergeWith(DSNode *N);
157 // addReferrer - Keep the referrer set up to date...
158 void addReferrer(DSNodeHandle *H) { Referrers.push_back(H); }
159 void removeReferrer(DSNodeHandle *H);
160 const std::vector<DSNodeHandle*> &getReferrers() const { return Referrers; }
162 void print(std::ostream &O, const DSGraph *G) const;
165 std::string getCaption(const DSGraph *G) const;
167 void dropAllReferences() {
173 inline DSNodeHandle &DSNodeHandle::operator=(DSNode *n) {
174 if (N) N->removeReferrer(this);
176 if (N) N->addReferrer(this);
181 // DSGraph - The graph that represents a function.
185 std::vector<DSNode*> Nodes;
186 DSNodeHandle RetNode; // Node that gets returned...
187 std::map<Value*, DSNodeHandle> ValueMap;
189 // FunctionCalls - This vector maintains a single entry for each call
190 // instruction in the current graph. Each call entry contains DSNodeHandles
191 // that refer to the arguments that are passed into the function call. The
192 // first entry in the vector is the scalar that holds the return value for the
193 // call, the second is the function scalar being invoked, and the rest are
194 // pointer arguments to the function.
196 std::vector<std::vector<DSNodeHandle> > FunctionCalls;
198 // OrigFunctionCalls - This vector retains a copy of the original function
199 // calls of the current graph. This is needed to support top-down inlining
200 // after bottom-up inlining is complete, since the latter deletes call nodes.
202 std::vector<std::vector<DSNodeHandle> > OrigFunctionCalls;
204 // PendingCallers - This vector records all unresolved callers of the
205 // current function, i.e., ones whose graphs have not been inlined into
206 // the current graph. As long as there are unresolved callers, the nodes
207 // for formal arguments in the current graph cannot be eliminated, and
208 // nodes in the graph reachable from the formal argument nodes or
209 // global variable nodes must be considered incomplete.
210 std::vector<Function*> PendingCallers;
213 // Define the interface only accessable to DataStructure
214 friend class LocalDataStructures;
215 friend class BUDataStructures;
216 friend class TDDataStructures;
217 DSGraph(Function &F); // Compute the local DSGraph
218 DSGraph(const DSGraph &DSG); // Copy ctor
221 // clone all the call nodes and save the copies in OrigFunctionCalls
222 void saveOrigFunctionCalls() {
223 assert(OrigFunctionCalls.size() == 0 && "Do this only once!");
224 OrigFunctionCalls = FunctionCalls;
227 // get the saved copies of the original function call nodes
228 std::vector<std::vector<DSNodeHandle> > &getOrigFunctionCalls() {
229 return OrigFunctionCalls;
232 void operator=(const DSGraph &); // DO NOT IMPLEMENT
235 Function &getFunction() const { return Func; }
237 // getValueMap - Get a map that describes what the nodes the scalars in this
238 // function point to...
240 std::map<Value*, DSNodeHandle> &getValueMap() { return ValueMap; }
241 const std::map<Value*, DSNodeHandle> &getValueMap() const { return ValueMap;}
243 std::vector<std::vector<DSNodeHandle> > &getFunctionCalls() {
244 return FunctionCalls;
247 const DSNode *getRetNode() const { return RetNode; }
249 unsigned getGraphSize() const {
253 void print(std::ostream &O) const;
256 // maskNodeTypes - Apply a mask to all of the node types in the graph. This
257 // is useful for clearing out markers like Scalar or Incomplete.
259 void maskNodeTypes(unsigned char Mask);
260 void maskIncompleteMarkers() { maskNodeTypes(~DSNode::Incomplete); }
262 // markIncompleteNodes - Traverse the graph, identifying nodes that may be
263 // modified by other functions that have not been resolved yet. This marks
264 // nodes that are reachable through three sources of "unknownness":
265 // Global Variables, Function Calls, and Incoming Arguments
267 // For any node that may have unknown components (because something outside
268 // the scope of current analysis may have modified it), the 'Incomplete' flag
269 // is added to the NodeType.
271 void markIncompleteNodes();
273 // removeTriviallyDeadNodes - After the graph has been constructed, this
274 // method removes all unreachable nodes that are created because they got
275 // merged with other nodes in the graph.
277 void removeTriviallyDeadNodes();
279 // removeDeadNodes - Use a more powerful reachability analysis to eliminate
280 // subgraphs that are unreachable. This often occurs because the data
281 // structure doesn't "escape" into it's caller, and thus should be eliminated
282 // from the caller's graph entirely. This is only appropriate to use when
285 void removeDeadNodes();
288 // AddCaller - add a known caller node into the graph and mark it pending.
289 // getCallers - get a vector of the functions that call this one
290 // getCallersPending - get a matching vector of bools indicating if each
291 // caller's DSGraph has been resolved into this one.
293 void addCaller(Function& caller) {
294 PendingCallers.push_back(&caller);
296 std::vector<Function*>& getPendingCallers() {
297 return PendingCallers;
300 // cloneInto - Clone the specified DSGraph into the current graph, returning
301 // the Return node of the graph. The translated ValueMap for the old function
302 // is filled into the OldValMap member. If StripLocals is set to true, Scalar
303 // and Alloca markers are removed from the graph, as the graph is being cloned
304 // into a calling function's graph.
306 DSNode *cloneInto(const DSGraph &G, std::map<Value*, DSNodeHandle> &OldValMap,
307 std::map<const DSNode*, DSNode*>& OldNodeMap,
308 bool StripLocals = true);
310 bool isNodeDead(DSNode *N);
315 // LocalDataStructures - The analysis that computes the local data structure
316 // graphs for all of the functions in the program.
318 // FIXME: This should be a Function pass that can be USED by a Pass, and would
319 // be automatically preserved. Until we can do that, this is a Pass.
321 class LocalDataStructures : public Pass {
322 // DSInfo, one graph for each function
323 std::map<Function*, DSGraph*> DSInfo;
325 static AnalysisID ID; // DataStructure Analysis ID
327 LocalDataStructures(AnalysisID id) { assert(id == ID); }
328 ~LocalDataStructures() { releaseMemory(); }
330 virtual const char *getPassName() const {
331 return "Local Data Structure Analysis";
334 virtual bool run(Module &M);
336 // getDSGraph - Return the data structure graph for the specified function.
337 DSGraph &getDSGraph(Function &F) const {
338 std::map<Function*, DSGraph*>::const_iterator I = DSInfo.find(&F);
339 assert(I != DSInfo.end() && "Function not in module!");
343 // print - Print out the analysis results...
344 void print(std::ostream &O, Module *M) const;
346 // If the pass pipeline is done with this pass, we can release our memory...
347 virtual void releaseMemory();
349 // getAnalysisUsage - This obviously provides a data structure graph.
350 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
351 AU.setPreservesAll();
357 // BUDataStructures - The analysis that computes the interprocedurally closed
358 // data structure graphs for all of the functions in the program. This pass
359 // only performs a "Bottom Up" propogation (hence the name).
361 class BUDataStructures : public Pass {
362 // DSInfo, one graph for each function
363 std::map<Function*, DSGraph*> DSInfo;
365 static AnalysisID ID; // BUDataStructure Analysis ID
367 BUDataStructures(AnalysisID id) { assert(id == ID); }
368 ~BUDataStructures() { releaseMemory(); }
370 virtual const char *getPassName() const {
371 return "Bottom-Up Data Structure Analysis Closure";
374 virtual bool run(Module &M);
376 // getDSGraph - Return the data structure graph for the specified function.
377 DSGraph &getDSGraph(Function &F) const {
378 std::map<Function*, DSGraph*>::const_iterator I = DSInfo.find(&F);
379 assert(I != DSInfo.end() && "Function not in module!");
383 // print - Print out the analysis results...
384 void print(std::ostream &O, Module *M) const;
386 // If the pass pipeline is done with this pass, we can release our memory...
387 virtual void releaseMemory();
389 // getAnalysisUsage - This obviously provides a data structure graph.
390 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
391 AU.setPreservesAll();
393 AU.addRequired(LocalDataStructures::ID);
396 DSGraph &calculateGraph(Function &F);
400 // TDDataStructures - Analysis that computes new data structure graphs
401 // for each function using the closed graphs for the callers computed
402 // by the bottom-up pass.
404 class TDDataStructures : public Pass {
405 // DSInfo, one graph for each function
406 std::map<Function*, DSGraph*> DSInfo;
408 static AnalysisID ID; // TDDataStructure Analysis ID
410 TDDataStructures(AnalysisID id) { assert(id == ID); }
411 ~TDDataStructures() { releaseMemory(); }
413 virtual const char *getPassName() const {
414 return "Top-down Data Structure Analysis Closure";
417 virtual bool run(Module &M);
419 // getDSGraph - Return the data structure graph for the specified function.
420 DSGraph &getDSGraph(Function &F) const {
421 std::map<Function*, DSGraph*>::const_iterator I = DSInfo.find(&F);
422 assert(I != DSInfo.end() && "Function not in module!");
426 // print - Print out the analysis results...
427 void print(std::ostream &O, Module *M) const;
429 // If the pass pipeline is done with this pass, we can release our memory...
430 virtual void releaseMemory();
432 // getAnalysisUsage - This obviously provides a data structure graph.
433 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
434 AU.setPreservesAll();
436 AU.addRequired(BUDataStructures::ID);
439 DSGraph &calculateGraph(Function &F);
440 void pushGraphIntoCallee(DSGraph &callerGraph, DSGraph &calleeGraph,
441 std::map<Value*, DSNodeHandle> &OldValMap,
442 std::map<const DSNode*, DSNode*> &OldNodeMap);