* Define some operators on PointerVal and PVS's
[oota-llvm.git] / include / llvm / Analysis / DataStructure / DataStructure.h
1 //===- DataStructure.h - Build a Module's call graph -------------*- C++ -*--=//
2 //
3 // Implement the LLVM data structure analysis library.
4 //
5 //===----------------------------------------------------------------------===//
6
7 #ifndef LLVM_ANALYSIS_DATA_STRUCTURE_H
8 #define LLVM_ANALYSIS_DATA_STRUCTURE_H
9
10 #include "llvm/Pass.h"
11 #include <string>
12
13 class Type;
14 class CallInst;
15 class AllocationInst;
16 class FunctionArgument;
17 class DSNode;
18 class FunctionRepBuilder;
19 class GlobalValue;
20 class FunctionDSGraph;
21 class DataStructure;
22
23 // FIXME: move this somewhere private
24 unsigned countPointerFields(const Type *Ty);
25
26 // PointerVal - Represent a pointer to a datastructure.  The pointer points to
27 // a node, and can index into it.  This is used for getelementptr instructions,
28 // which do not affect which node a pointer points to, but does change the field
29 // index
30 //
31 struct PointerVal {
32   DSNode *Node;
33   unsigned Index;  // Index into Node->FieldLinks[]
34 public:
35   PointerVal(DSNode *N, unsigned Idx = 0) : Node(N), Index(Idx) {}
36
37   DSNode *getNode() const { return Node; }
38   unsigned getIndex() const { return Index; }
39
40   inline bool operator==(DSNode *N) const { return Node == N; }
41   inline bool operator!=(DSNode *N) const { return Node != N; }
42
43   // operator< - Allow insertion into a map...
44   bool operator<(const PointerVal &PV) const {
45     return Node < PV.Node || (Node == PV.Node && Index < PV.Index);
46   }
47
48   inline bool operator==(const PointerVal &PV) const {
49     return Node == PV.Node && Index == PV.Index;
50   }
51   inline bool operator!=(const PointerVal &PV) const { return !operator==(PV); }
52
53   void print(std::ostream &O) const;
54 };
55
56
57 // PointerValSet - This class represents a list of pointer values.  The add
58 // method is used to add values to the set, and ensures that duplicates cannot
59 // happen.
60 //
61 class PointerValSet {
62   std::vector<PointerVal> Vals;
63   void dropRefs();
64   void addRefs();
65 public:
66   PointerValSet() {}
67   PointerValSet(const PointerValSet &PVS) : Vals(PVS.Vals) { addRefs(); }
68   ~PointerValSet() { dropRefs(); }
69   const PointerValSet &operator=(const PointerValSet &PVS);
70
71   // operator< - Allow insertion into a map...
72   bool operator<(const PointerValSet &PVS) const;
73   bool operator==(const PointerValSet &PVS) const;
74
75   const PointerVal &operator[](unsigned i) const { return Vals[i]; }
76
77   unsigned size() const { return Vals.size(); }
78   bool empty() const { return Vals.empty(); }
79   void clear() { dropRefs(); Vals.clear(); }
80
81   // add - Add the specified pointer, or contents of the specified PVS to this
82   // pointer set.  If a 'Pointer' value is provided, notify the underlying data
83   // structure node that the pointer is pointing to it, so that it can be
84   // invalidated if neccesary later.  True is returned if the value is new to
85   // this pointer.
86   //
87   bool add(const PointerVal &PV, Value *Pointer = 0);
88   bool add(const PointerValSet &PVS, Value *Pointer = 0) {
89     bool Changed = false;
90     for (unsigned i = 0, e = PVS.size(); i != e; ++i)
91       Changed |= add(PVS[i], Pointer);
92     return Changed;
93   }
94
95   // removePointerTo - Remove a single pointer val that points to the specified
96   // node...
97   void removePointerTo(DSNode *Node);
98
99   void print(std::ostream &O) const;
100 };
101
102
103 //===----------------------------------------------------------------------===//
104 // DSNode - Base class for all data structure nodes...
105 //
106 // This class keeps track of its type, the pointer fields in the data structure,
107 // and a list of LLVM values that are pointing to this node.
108 //
109 class DSNode {
110   friend class FunctionDSGraph;
111   const Type *Ty;
112   std::vector<PointerValSet> FieldLinks;
113   std::vector<Value*> Pointers;   // Values pointing to me...
114   std::vector<PointerValSet*> Referrers;
115   
116   DSNode(const DSNode &);         // DO NOT IMPLEMENT
117   void operator=(const DSNode &); // DO NOT IMPLEMENT
118 public:
119   enum NodeTy {
120     NewNode, CallNode, ShadowNode, ArgNode, GlobalNode
121   } NodeType;
122
123   DSNode(enum NodeTy NT, const Type *T);
124   virtual ~DSNode() {
125     dropAllReferences();
126     assert(Referrers.empty() && "Referrers to dead node exist!");
127   }
128
129   unsigned getNumLinks() const { return FieldLinks.size(); }
130   PointerValSet &getLink(unsigned i) {
131     assert(i < getNumLinks() && "Field links access out of range...");
132     return FieldLinks[i];
133   }
134
135   // addReferrer - Keep the referrer set up to date...
136   void addReferrer(PointerValSet *PVS) { Referrers.push_back(PVS); }
137   void removeReferrer(PointerValSet *PVS);
138   const std::vector<PointerValSet*> &getReferrers() const { return Referrers; }
139
140   // removeAllIncomingEdges - Erase all edges in the graph that point to
141   // this node
142   void removeAllIncomingEdges();
143
144   void addPointer(Value *V) { Pointers.push_back(V); }
145   const std::vector<Value*> &getPointers() const { return Pointers; }
146
147   const Type *getType() const { return Ty; }
148
149   void print(std::ostream &O) const;
150
151   virtual std::string getCaption() const = 0;
152   virtual const std::vector<PointerValSet> *getAuxLinks() const {
153     return 0;  // Default to nothing...
154   }
155
156   // isEquivalentTo - Return true if the nodes should be merged...
157   virtual bool isEquivalentTo(DSNode *Node) const = 0;
158
159   DSNode *clone() const {
160     DSNode *New = cloneImpl();
161     // Add all of the pointers to the new node...
162     for (unsigned pn = 0, pe = Pointers.size(); pn != pe; ++pn)
163       New->addPointer(Pointers[pn]);
164     return New;
165   }
166
167
168   virtual void dropAllReferences() {
169     FieldLinks.clear();
170   }
171
172   static bool classof(const DSNode *N) { return true; }
173 protected:
174   virtual DSNode *cloneImpl() const = 0;
175   virtual void mapNode(std::map<const DSNode*, DSNode*> &NodeMap,
176                        const DSNode *Old);
177 };
178
179
180 // AllocDSNode - Represent all allocation (malloc or alloca) in the program.
181 //
182 class AllocDSNode : public DSNode {
183   AllocationInst *Allocation;
184 public:
185   AllocDSNode(AllocationInst *V);
186
187   virtual std::string getCaption() const;
188
189   bool isAllocaNode() const;
190   bool isMallocNode() const { return !isAllocaNode(); }
191
192   // isEquivalentTo - Return true if the nodes should be merged...
193   virtual bool isEquivalentTo(DSNode *Node) const;
194
195   // Support type inquiry through isa, cast, and dyn_cast...
196   static bool classof(const AllocDSNode *) { return true; }
197   static bool classof(const DSNode *N) { return N->NodeType == NewNode; }
198 protected:
199   virtual AllocDSNode *cloneImpl() const { return new AllocDSNode(Allocation); }
200 };
201
202
203 // GlobalDSNode - Represent the memory location that a global variable occupies
204 //
205 class GlobalDSNode : public DSNode {
206   GlobalValue *Val;
207 public:
208   GlobalDSNode(GlobalValue *V);
209
210   GlobalValue *getGlobal() const { return Val; }
211   
212   virtual std::string getCaption() const;
213
214   // isEquivalentTo - Return true if the nodes should be merged...
215   virtual bool isEquivalentTo(DSNode *Node) const;
216
217   // Support type inquiry through isa, cast, and dyn_cast...
218   static bool classof(const GlobalDSNode *) { return true; }
219   static bool classof(const DSNode *N) { return N->NodeType == GlobalNode; }
220 private:
221   virtual GlobalDSNode *cloneImpl() const { return new GlobalDSNode(Val); }
222 };
223
224
225 // CallDSNode - Represent a call instruction in the program...
226 //
227 class CallDSNode : public DSNode {
228   friend class FunctionDSGraph;
229   CallInst *CI;
230   std::vector<PointerValSet> ArgLinks;
231 public:
232   CallDSNode(CallInst *CI);
233
234   CallInst *getCall() const { return CI; }
235
236   const std::vector<PointerValSet> *getAuxLinks() const { return &ArgLinks; }
237   virtual std::string getCaption() const;
238
239   bool addArgValue(unsigned ArgNo, const PointerValSet &PVS) {
240     return ArgLinks[ArgNo].add(PVS);
241   }
242
243   unsigned getNumArgs() const { return ArgLinks.size(); }
244   const PointerValSet &getArgValues(unsigned ArgNo) const {
245     assert(ArgNo < ArgLinks.size() && "Arg # out of range!");
246     return ArgLinks[ArgNo];
247   }
248   const std::vector<PointerValSet> &getArgs() const { return ArgLinks; }
249
250   virtual void dropAllReferences() {
251     DSNode::dropAllReferences();
252     ArgLinks.clear();
253   }
254
255   // isEquivalentTo - Return true if the nodes should be merged...
256   virtual bool isEquivalentTo(DSNode *Node) const;
257
258   // Support type inquiry through isa, cast, and dyn_cast...
259   static bool classof(const CallDSNode *) { return true; }
260   static bool classof(const DSNode *N) { return N->NodeType == CallNode; }
261 private:
262   virtual CallDSNode *cloneImpl() const { return new CallDSNode(CI); }
263   virtual void mapNode(std::map<const DSNode*, DSNode*> &NodeMap,
264                        const DSNode *Old);
265 }; 
266
267
268 // ArgDSNode - Represent an incoming argument to the current function...
269 //
270 class ArgDSNode : public DSNode {
271   FunctionArgument *FuncArg;
272 public:
273   ArgDSNode(FunctionArgument *MA);
274   virtual std::string getCaption() const;
275
276   // isEquivalentTo - Return true if the nodes should be merged...
277   virtual bool isEquivalentTo(DSNode *Node) const;
278
279   // Support type inquiry through isa, cast, and dyn_cast...
280   static bool classof(const ArgDSNode *) { return true; }
281   static bool classof(const DSNode *N) { return N->NodeType == ArgNode; }
282 private:
283   virtual ArgDSNode *cloneImpl() const { return new ArgDSNode(FuncArg); }
284 };
285
286
287 // ShadowDSNode - Represent a chunk of memory that we need to be able to
288 // address.  These are generated due to (for example) pointer type method
289 // arguments... if the pointer is dereferenced, we need to have a node to point
290 // to.  When functions are integrated into each other, shadow nodes are
291 // resolved.
292 //
293 // Shadow nodes may be marked as "critical" nodes when they are created.  This
294 // mark indicates that the node is the result of a function call, the value
295 // pointed to by an incoming argument, or the value pointed to by a global
296 // variable [fixme todo].  Since it is not possible to know what these nodes
297 // point to, given just the current context, they are marked "Critical" to avoid
298 // having the shadow node merger eliminate them.
299 //
300 class ShadowDSNode : public DSNode {
301   friend class FunctionDSGraph;
302   DSNode *Parent;
303   Module *Mod;
304   ShadowDSNode *ShadowParent;   // Nonnull if this is a synthesized node...
305   std::vector<std::pair<const Type *, ShadowDSNode *> > SynthNodes;
306   bool CriticalNode;
307 public:
308   ShadowDSNode(DSNode *Parent, Module *M, bool Critical = false);
309   virtual std::string getCaption() const;
310
311   // synthesizeNode - Create a new shadow node that is to be linked into this
312   // chain..
313   //
314   ShadowDSNode *synthesizeNode(const Type *Ty, FunctionRepBuilder *Rep);
315
316   bool isCriticalNode() const { return CriticalNode; }
317   void resetCriticalMark() { CriticalNode = false; }
318
319   // isEquivalentTo - Return true if the nodes should be merged...
320   virtual bool isEquivalentTo(DSNode *Node) const;
321
322   // Support type inquiry through isa, cast, and dyn_cast...
323   static bool classof(const ShadowDSNode *) { return true; }
324   static bool classof(const DSNode *N) { return N->NodeType == ShadowNode; }
325
326 private:
327   ShadowDSNode(const Type *Ty, Module *M, ShadowDSNode *ShadParent);
328 protected:
329   virtual void mapNode(std::map<const DSNode*, DSNode*> &NodeMap,
330                        const DSNode *Old);
331   virtual ShadowDSNode *cloneImpl() const {
332     if (ShadowParent)
333       return new ShadowDSNode(getType(), Mod, ShadowParent);
334     else
335       return new ShadowDSNode(Parent, Mod, CriticalNode);
336   }
337 };
338
339
340 // FunctionDSGraph - The graph that represents a method.
341 //
342 class FunctionDSGraph {
343   Function *Func;
344   std::vector<ArgDSNode*>    ArgNodes;
345   std::vector<AllocDSNode*>  AllocNodes;
346   std::vector<ShadowDSNode*> ShadowNodes;
347   std::vector<GlobalDSNode*> GlobalNodes;
348   std::vector<CallDSNode*>   CallNodes;
349   PointerValSet RetNode;             // Node that gets returned...
350   std::map<Value*, PointerValSet> ValueMap;
351
352   // cloneFunctionIntoSelf - Clone the specified method graph into the current
353   // method graph, returning the Return's set of the graph.  If ValueMap is set
354   // to true, the ValueMap of the function is cloned into this function as well
355   // as the data structure graph itself.
356   //
357   PointerValSet cloneFunctionIntoSelf(const FunctionDSGraph &G, bool ValueMap);
358   bool RemoveUnreachableShadowNodes();
359   bool UnlinkUndistinguishableShadowNodes();
360 public:
361   FunctionDSGraph(Function *F);
362   FunctionDSGraph(const FunctionDSGraph &DSG);
363   ~FunctionDSGraph();
364
365   void computeClosure(const DataStructure &DS);
366
367   Function *getFunction() const { return Func; }
368
369   void printFunction(std::ostream &O, const char *Label) const;
370 };
371
372
373 // FIXME: This should be a FunctionPass.  When the pass framework sees a 'Pass'
374 // that uses the output of a FunctionPass, it should automatically build a map
375 // of output from the method pass that the pass can use.
376 //
377 class DataStructure : public Pass {
378   // DSInfo, one intraprocedural and one closed graph for each method...
379   typedef std::map<Function*, std::pair<FunctionDSGraph*,
380                                         FunctionDSGraph*> > InfoMap;
381   mutable InfoMap DSInfo;
382 public:
383   static AnalysisID ID;            // DataStructure Analysis ID 
384
385   DataStructure(AnalysisID id) { assert(id == ID); }
386   ~DataStructure() { releaseMemory(); }
387
388   // run - Do nothing, because methods are analyzed lazily
389   virtual bool run(Module *TheModule) { return false; }
390
391   // getDSGraph - Return the data structure graph for the specified method.
392   // Since method graphs are lazily computed, we may have to create one on the
393   // fly here.
394   //
395   FunctionDSGraph &getDSGraph(Function *F) const {
396     std::pair<FunctionDSGraph*, FunctionDSGraph*> &N = DSInfo[F];
397     if (N.first) return *N.first;
398     return *(N.first = new FunctionDSGraph(F));
399   }
400
401   // getClosedDSGraph - Return the data structure graph for the specified
402   // method. Since method graphs are lazily computed, we may have to create one
403   // on the fly here. This is different than the normal DSGraph for the method
404   // because any function calls that are resolvable will have the data structure
405   // graphs of the called function incorporated into this function as well.
406   //
407   FunctionDSGraph &getClosedDSGraph(Function *F) const {
408     std::pair<FunctionDSGraph*, FunctionDSGraph*> &N = DSInfo[F];
409     if (N.second) return *N.second;
410     N.second = new FunctionDSGraph(getDSGraph(F));
411     N.second->computeClosure(*this);
412     return *N.second;
413   }
414
415   // print - Print out the analysis results...
416   void print(std::ostream &O, Module *M) const;
417
418   // If the pass pipeline is done with this pass, we can release our memory...
419   virtual void releaseMemory();
420
421   // getAnalysisUsageInfo - This obviously provides a call graph
422   virtual void getAnalysisUsageInfo(AnalysisSet &Required,
423                                     AnalysisSet &Destroyed,
424                                     AnalysisSet &Provided) {
425     Provided.push_back(ID);
426   }
427 };
428
429 #endif