* Implement fully general merging of array subscripts on demand! This
[oota-llvm.git] / include / llvm / Analysis / DataStructure / DSGraph.h
1 //===- DSGraph.h - Represent a collection of data structures ----*- C++ -*-===//
2 //
3 // This header defines the primative classes that make up a data structure
4 // graph.
5 //
6 //===----------------------------------------------------------------------===//
7
8 #ifndef LLVM_ANALYSIS_DSGRAPH_H
9 #define LLVM_ANALYSIS_DSGRAPH_H
10
11 #include "llvm/Pass.h"
12
13 class GlobalValue;
14 class Type;
15
16 class DSNode;                  // Each node in the graph
17 class DSGraph;                 // A graph for a function
18 class DSNodeIterator;          // Data structure graph traversal iterator
19
20 //===----------------------------------------------------------------------===//
21 /// DSNodeHandle - Implement a "handle" to a data structure node that takes care
22 /// of all of the add/un'refing of the node to prevent the backpointers in the
23 /// graph from getting out of date.  This class represents a "pointer" in the
24 /// graph, whose destination is an indexed offset into a node.
25 ///
26 class DSNodeHandle {
27   DSNode *N;
28   unsigned Offset;
29 public:
30   // Allow construction, destruction, and assignment...
31   DSNodeHandle(DSNode *n = 0, unsigned offs = 0) : N(0), Offset(offs) {
32     setNode(n);
33   }
34   DSNodeHandle(const DSNodeHandle &H) : N(0), Offset(H.Offset) { setNode(H.N); }
35   ~DSNodeHandle() { setNode((DSNode*)0); }
36   DSNodeHandle &operator=(const DSNodeHandle &H) {
37     setNode(H.N); Offset = H.Offset;
38     return *this;
39   }
40
41   bool operator<(const DSNodeHandle &H) const {  // Allow sorting
42     return N < H.N || (N == H.N && Offset < H.Offset);
43   }
44   bool operator==(const DSNodeHandle &H) const { // Allow comparison
45     return N == H.N && Offset == H.Offset;
46   }
47   bool operator!=(const DSNodeHandle &H) const { return !operator==(H); }
48
49   // Allow explicit conversion to DSNode...
50   DSNode *getNode() const { return N; }
51   unsigned getOffset() const { return Offset; }
52
53   inline void setNode(DSNode *N);  // Defined inline later...
54   void setOffset(unsigned O) { Offset = O; }
55
56   void addEdgeTo(unsigned LinkNo, const DSNodeHandle &N);
57   void addEdgeTo(const DSNodeHandle &N) { addEdgeTo(0, N); }
58
59   /// mergeWith - Merge the logical node pointed to by 'this' with the node
60   /// pointed to by 'N'.
61   ///
62   void mergeWith(const DSNodeHandle &N);
63
64   // hasLink - Return true if there is a link at the specified offset...
65   inline bool hasLink(unsigned Num) const;
66
67   /// getLink - Treat this current node pointer as a pointer to a structure of
68   /// some sort.  This method will return the pointer a mem[this+Num]
69   ///
70   inline const DSNodeHandle *getLink(unsigned Num) const;
71   inline DSNodeHandle *getLink(unsigned Num);
72
73   inline void setLink(unsigned Num, const DSNodeHandle &NH);
74 };
75
76
77 //===----------------------------------------------------------------------===//
78 /// DSNode - Data structure node class
79 ///
80 /// This class represents an untyped memory object of Size bytes.  It keeps
81 /// track of any pointers that have been stored into the object as well as the
82 /// different types represented in this object.
83 ///
84 class DSNode {
85   /// Links - Contains one entry for every _distinct_ pointer field in the
86   /// memory block.  These are demand allocated and indexed by the MergeMap
87   /// vector.
88   ///
89   std::vector<DSNodeHandle> Links;
90
91   /// MergeMap - Maps from every byte in the object to a signed byte number.
92   /// This map is neccesary due to the merging that is possible as part of the
93   /// unification algorithm.  To merge two distinct bytes of the object together
94   /// into a single logical byte, the indexes for the two bytes are set to the
95   /// same value.  This fully general merging is capable of representing all
96   /// manners of array merging if neccesary.
97   ///
98   /// This map is also used to map outgoing pointers to various byte offsets in
99   /// this data structure node.  If this value is >= 0, then it indicates that
100   /// the numbered entry in the Links vector contains the outgoing edge for this
101   /// byte offset.  In this way, the Links vector can be demand allocated and
102   /// byte elements of the node may be merged without needing a Link allocated
103   /// for it.
104   ///
105   /// Initially, each each element of the MergeMap is assigned a unique negative
106   /// number, which are then merged as the unification occurs.
107   ///
108   std::vector<signed char> MergeMap;
109
110   /// Referrers - Keep track of all of the node handles that point to this
111   /// DSNode.  These pointers may need to be updated to point to a different
112   /// node if this node gets merged with it.
113   ///
114   std::vector<DSNodeHandle*> Referrers;
115
116   /// TypeEntries - As part of the merging process of this algorithm, nodes of
117   /// different types can be represented by this single DSNode.  This vector is
118   /// kept sorted.
119   ///
120   typedef std::pair<const Type *, unsigned> TypeRec;
121   std::vector<TypeRec> TypeEntries;
122
123   /// Globals - The list of global values that are merged into this node.
124   ///
125   std::vector<GlobalValue*> Globals;
126
127   void operator=(const DSNode &); // DO NOT IMPLEMENT
128 public:
129   enum NodeTy {
130     ShadowNode = 0,        // Nothing is known about this node...
131     ScalarNode = 1 << 0,   // Scalar of the current function contains this value
132     AllocaNode = 1 << 1,   // This node was allocated with alloca
133     NewNode    = 1 << 2,   // This node was allocated with malloc
134     GlobalNode = 1 << 3,   // This node was allocated by a global var decl
135     Incomplete = 1 << 4,   // This node may not be complete
136   };
137   
138   /// NodeType - A union of the above bits.  "Shadow" nodes do not add any flags
139   /// to the nodes in the data structure graph, so it is possible to have nodes
140   /// with a value of 0 for their NodeType.  Scalar and Alloca markers go away
141   /// when function graphs are inlined.
142   ///
143   unsigned char NodeType;
144
145   DSNode(enum NodeTy NT, const Type *T);
146   DSNode(const DSNode &);
147
148   ~DSNode() {
149 #ifndef NDEBUG
150     dropAllReferences();  // Only needed to satisfy assertion checks...
151     assert(Referrers.empty() && "Referrers to dead node exist!");
152 #endif
153   }
154
155   // Iterator for graph interface...
156   typedef DSNodeIterator iterator;
157   inline iterator begin();   // Defined in DataStructureGraph.h
158   inline iterator end();
159
160   //===--------------------------------------------------
161   // Accessors
162
163   // getSize - Return the maximum number of bytes occupied by this object...
164   unsigned getSize() const { return MergeMap.size(); }
165
166   // getTypeEntries - Return the possible types and their offsets in this object
167   const std::vector<TypeRec> &getTypeEntries() const { return TypeEntries; }
168
169   // getReferrers - Return a list of the pointers to this node...
170   const std::vector<DSNodeHandle*> &getReferrers() const { return Referrers; }
171
172
173   /// hasLink - Return true if this memory object has a link at the specified
174   /// location.
175   ///
176   bool hasLink(unsigned i) const {
177     assert(i < getSize() && "Field Link index is out of range!");
178     return MergeMap[i] >= 0;
179   }
180
181   DSNodeHandle *getLink(unsigned i) {
182     if (hasLink(i))
183       return &Links[MergeMap[i]];
184     return 0;
185   }
186   const DSNodeHandle *getLink(unsigned i) const {
187     if (hasLink(i))
188       return &Links[MergeMap[i]];
189     return 0;
190   }
191
192   /// setLink - Set the link at the specified offset to the specified
193   /// NodeHandle, replacing what was there.  It is uncommon to use this method,
194   /// instead one of the higher level methods should be used, below.
195   ///
196   void setLink(unsigned i, const DSNodeHandle &NH);
197
198   /// addEdgeTo - Add an edge from the current node to the specified node.  This
199   /// can cause merging of nodes in the graph.
200   ///
201   void addEdgeTo(unsigned Offset, const DSNodeHandle &NH);
202
203   /// mergeWith - Merge this node and the specified node, moving all links to
204   /// and from the argument node into the current node, deleting the node
205   /// argument.  Offset indicates what offset the specified node is to be merged
206   /// into the current node.
207   ///
208   /// The specified node may be a null pointer (in which case, nothing happens).
209   ///
210   void mergeWith(const DSNodeHandle &NH, unsigned Offset);
211
212   /// mergeIndexes - If we discover that two indexes are equivalent and must be
213   /// merged, this function is used to do the dirty work.
214   ///
215   void mergeIndexes(unsigned idx1, unsigned idx2) {
216     assert(idx1 < getSize() && idx2 < getSize() && "Indexes out of range!");
217     signed char MV1 = MergeMap[idx1];
218     signed char MV2 = MergeMap[idx2];
219     if (MV1 != MV2)
220       mergeMappedValues(MV1, MV2);
221   }
222
223
224   /// addGlobal - Add an entry for a global value to the Globals list.  This
225   /// also marks the node with the 'G' flag if it does not already have it.
226   ///
227   void addGlobal(GlobalValue *GV);
228   const std::vector<GlobalValue*> &getGlobals() const { return Globals; }
229   std::vector<GlobalValue*> &getGlobals() { return Globals; }
230
231   void print(std::ostream &O, const DSGraph *G) const;
232   void dump() const;
233
234   void dropAllReferences() {
235     Links.clear();
236   }
237
238   /// remapLinks - Change all of the Links in the current node according to the
239   /// specified mapping.
240   void remapLinks(std::map<const DSNode*, DSNode*> &OldNodeMap);
241
242 private:
243   friend class DSNodeHandle;
244   // addReferrer - Keep the referrer set up to date...
245   void addReferrer(DSNodeHandle *H) { Referrers.push_back(H); }
246   void removeReferrer(DSNodeHandle *H);
247
248   /// rewriteMergeMap - Loop over the mergemap, replacing any references to the
249   /// index From to be references to the index To.
250   ///
251   void rewriteMergeMap(signed char From, signed char To) {
252     assert(From != To && "Cannot change something into itself!");
253     for (unsigned i = 0, e = MergeMap.size(); i != e; ++i)
254       if (MergeMap[i] == From)
255         MergeMap[i] = To;
256   }
257
258   /// mergeMappedValues - This is the higher level form of rewriteMergeMap.  It
259   /// is fully capable of merging links together if neccesary as well as simply
260   /// rewriting the map entries.
261   ///
262   void mergeMappedValues(signed char V1, signed char V2);
263 };
264
265
266 //===----------------------------------------------------------------------===//
267 // Define inline DSNodeHandle functions that depend on the definition of DSNode
268 //
269
270 inline void DSNodeHandle::setNode(DSNode *n) {
271   if (N) N->removeReferrer(this);
272   N = n;
273   if (N) N->addReferrer(this);
274 }
275
276 inline bool DSNodeHandle::hasLink(unsigned Num) const {
277   assert(N && "DSNodeHandle does not point to a node yet!");
278   return N->hasLink(Num+Offset);
279 }
280
281
282 /// getLink - Treat this current node pointer as a pointer to a structure of
283 /// some sort.  This method will return the pointer a mem[this+Num]
284 ///
285 inline const DSNodeHandle *DSNodeHandle::getLink(unsigned Num) const {
286   assert(N && "DSNodeHandle does not point to a node yet!");
287   return N->getLink(Num+Offset);
288 }
289 inline DSNodeHandle *DSNodeHandle::getLink(unsigned Num) {
290   assert(N && "DSNodeHandle does not point to a node yet!");
291   return N->getLink(Num+Offset);
292 }
293
294 inline void DSNodeHandle::setLink(unsigned Num, const DSNodeHandle &NH) {
295   assert(N && "DSNodeHandle does not point to a node yet!");
296   N->setLink(Num+Offset, NH);
297 }
298
299 ///  addEdgeTo - Add an edge from the current node to the specified node.  This
300 /// can cause merging of nodes in the graph.
301 ///
302 inline void DSNodeHandle::addEdgeTo(unsigned LinkNo, const DSNodeHandle &Node) {
303   assert(N && "DSNodeHandle does not point to a node yet!");
304   N->addEdgeTo(LinkNo+Offset, Node);
305 }
306
307 /// mergeWith - Merge the logical node pointed to by 'this' with the node
308 /// pointed to by 'N'.
309 ///
310 inline void DSNodeHandle::mergeWith(const DSNodeHandle &Node) {
311   assert(N && "DSNodeHandle does not point to a node yet!");
312   N->mergeWith(Node, Offset);
313 }
314
315
316 //===----------------------------------------------------------------------===//
317 /// DSGraph - The graph that represents a function.
318 ///
319 class DSGraph {
320   Function *Func;
321   std::vector<DSNode*> Nodes;
322   DSNodeHandle RetNode;                          // Node that gets returned...
323   std::map<Value*, DSNodeHandle> ValueMap;
324
325 #if 0
326   // GlobalsGraph -- Reference to the common graph of globally visible objects.
327   // This includes GlobalValues, New nodes, Cast nodes, and Calls.
328   // 
329   GlobalDSGraph* GlobalsGraph;
330 #endif
331
332   // FunctionCalls - This vector maintains a single entry for each call
333   // instruction in the current graph.  Each call entry contains DSNodeHandles
334   // that refer to the arguments that are passed into the function call.  The
335   // first entry in the vector is the scalar that holds the return value for the
336   // call, the second is the function scalar being invoked, and the rest are
337   // pointer arguments to the function.
338   //
339   std::vector<std::vector<DSNodeHandle> > FunctionCalls;
340
341 #if 0
342   // OrigFunctionCalls - This vector retains a copy of the original function
343   // calls of the current graph.  This is needed to support top-down inlining
344   // after bottom-up inlining is complete, since the latter deletes call nodes.
345   // 
346   std::vector<std::vector<DSNodeHandle> > OrigFunctionCalls;
347
348   // PendingCallers - This vector records all unresolved callers of the
349   // current function, i.e., ones whose graphs have not been inlined into
350   // the current graph.  As long as there are unresolved callers, the nodes
351   // for formal arguments in the current graph cannot be eliminated, and
352   // nodes in the graph reachable from the formal argument nodes or
353   // global variable nodes must be considered incomplete. 
354   std::set<Function*> PendingCallers;
355 #endif
356   
357 protected:
358
359 #if 0
360   // clone all the call nodes and save the copies in OrigFunctionCalls
361   void saveOrigFunctionCalls() {
362     assert(OrigFunctionCalls.size() == 0 && "Do this only once!");
363     OrigFunctionCalls = FunctionCalls;
364   }
365
366   // get the saved copies of the original function call nodes
367   std::vector<std::vector<DSNodeHandle> > &getOrigFunctionCalls() {
368     return OrigFunctionCalls;
369   }
370 #endif
371
372   void operator=(const DSGraph &); // DO NOT IMPLEMENT
373 public:
374   DSGraph() : Func(0) {}           // Create a new, empty, DSGraph.
375   DSGraph(Function &F);            // Compute the local DSGraph
376   DSGraph(const DSGraph &DSG);     // Copy ctor
377   ~DSGraph();
378
379   bool hasFunction() const { return Func != 0; }
380   Function &getFunction() const { return *Func; }
381
382   /// getNodes - Get a vector of all the nodes in the graph
383   /// 
384   const std::vector<DSNode*> &getNodes() const { return Nodes; }
385         std::vector<DSNode*> &getNodes()       { return Nodes; }
386
387   /// addNode - Add a new node to the graph.
388   ///
389   void addNode(DSNode *N) { Nodes.push_back(N); }
390
391   /// getValueMap - Get a map that describes what the nodes the scalars in this
392   /// function point to...
393   ///
394   std::map<Value*, DSNodeHandle> &getValueMap() { return ValueMap; }
395   const std::map<Value*, DSNodeHandle> &getValueMap() const { return ValueMap;}
396
397   std::vector<std::vector<DSNodeHandle> > &getFunctionCalls() {
398     return FunctionCalls;
399   }
400   const std::vector<std::vector<DSNodeHandle> > &getFunctionCalls() const {
401     return FunctionCalls;
402   }
403
404   const DSNodeHandle &getRetNode() const { return RetNode; }
405         DSNodeHandle &getRetNode()       { return RetNode; }
406
407   unsigned getGraphSize() const {
408     return Nodes.size();
409   }
410
411   void print(std::ostream &O) const;
412   void dump() const;
413   void writeGraphToFile(std::ostream &O, const std::string &GraphName);
414
415   // maskNodeTypes - Apply a mask to all of the node types in the graph.  This
416   // is useful for clearing out markers like Scalar or Incomplete.
417   //
418   void maskNodeTypes(unsigned char Mask);
419   void maskIncompleteMarkers() { maskNodeTypes(~DSNode::Incomplete); }
420
421   // markIncompleteNodes - Traverse the graph, identifying nodes that may be
422   // modified by other functions that have not been resolved yet.  This marks
423   // nodes that are reachable through three sources of "unknownness":
424   //   Global Variables, Function Calls, and Incoming Arguments
425   //
426   // For any node that may have unknown components (because something outside
427   // the scope of current analysis may have modified it), the 'Incomplete' flag
428   // is added to the NodeType.
429   //
430   void markIncompleteNodes(bool markFormalArgs = true);
431
432   // removeTriviallyDeadNodes - After the graph has been constructed, this
433   // method removes all unreachable nodes that are created because they got
434   // merged with other nodes in the graph.
435   //
436   void removeTriviallyDeadNodes(bool KeepAllGlobals = false);
437
438   // removeDeadNodes - Use a more powerful reachability analysis to eliminate
439   // subgraphs that are unreachable.  This often occurs because the data
440   // structure doesn't "escape" into it's caller, and thus should be eliminated
441   // from the caller's graph entirely.  This is only appropriate to use when
442   // inlining graphs.
443   //
444   void removeDeadNodes(bool KeepAllGlobals = false, bool KeepCalls = true);
445
446 #if 0
447   // AddCaller - add a known caller node into the graph and mark it pending.
448   // getCallers - get a vector of the functions that call this one
449   // getCallersPending - get a matching vector of bools indicating if each
450   //                     caller's DSGraph has been resolved into this one.
451   // 
452   void addCaller(Function &caller) {
453     PendingCallers.insert(&caller);
454   }
455   std::set<Function*> &getPendingCallers() {
456     return PendingCallers;
457   }
458 #endif
459
460   // cloneInto - Clone the specified DSGraph into the current graph, returning
461   // the Return node of the graph.  The translated ValueMap for the old function
462   // is filled into the OldValMap member.
463   // If StripScalars (StripAllocas) is set to true, Scalar (Alloca) markers
464   // are removed from the graph as the graph is being cloned.
465   // If CopyCallers is set to true, the PendingCallers list is copied.
466   // If CopyOrigCalls is set to true, the OrigFunctionCalls list is copied.
467   //
468   DSNodeHandle cloneInto(const DSGraph &G,
469                          std::map<Value*, DSNodeHandle> &OldValMap,
470                          std::map<const DSNode*, DSNode*> &OldNodeMap,
471                          bool StripScalars = false, bool StripAllocas = false,
472                          bool CopyCallers = true, bool CopyOrigCalls = true);
473
474 #if 0
475   // cloneGlobalInto - Clone the given global node (or the node for the given
476   // GlobalValue) from the GlobalsGraph and all its target links (recursively).
477   // 
478   DSNode* cloneGlobalInto(const DSNode* GNode);
479   DSNode* cloneGlobalInto(GlobalValue* GV) {
480     assert(!GV || (((DSGraph*) GlobalsGraph)->ValueMap[GV] != 0));
481     return GV? cloneGlobalInto(((DSGraph*) GlobalsGraph)->ValueMap[GV]) : 0;
482   }
483 #endif
484
485 private:
486   bool isNodeDead(DSNode *N);
487 };
488
489 #endif