Clean up the minor mess I caused with removing iterator.h. I shall take care of 80...
[oota-llvm.git] / include / llvm / Analysis / AliasSetTracker.h
1 //===- llvm/Analysis/AliasSetTracker.h - Build Alias Sets -------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines two classes: AliasSetTracker and AliasSet.  These interface
11 // are used to classify a collection of pointer references into a maximal number
12 // of disjoint sets.  Each AliasSet object constructed by the AliasSetTracker
13 // object refers to memory disjoint from the other sets.
14 //
15 //===----------------------------------------------------------------------===//
16
17 #ifndef LLVM_ANALYSIS_ALIASSETTRACKER_H
18 #define LLVM_ANALYSIS_ALIASSETTRACKER_H
19
20 #include "llvm/Support/CallSite.h"
21 #include "llvm/Support/ValueHandle.h"
22 #include "llvm/ADT/DenseMap.h"
23 #include "llvm/ADT/ilist.h"
24 #include "llvm/ADT/ilist_node.h"
25 #include <vector>
26
27 namespace llvm {
28
29 class AliasAnalysis;
30 class LoadInst;
31 class StoreInst;
32 class FreeInst;
33 class VAArgInst;
34 class AliasSetTracker;
35 class AliasSet;
36
37 class AliasSet : public ilist_node<AliasSet> {
38   friend class AliasSetTracker;
39
40   class PointerRec {
41     Value *Val;  // The pointer this record corresponds to.
42     PointerRec **PrevInList, *NextInList;
43     AliasSet *AS;
44     unsigned Size;
45   public:
46     PointerRec(Value *V)
47       : Val(V), PrevInList(0), NextInList(0), AS(0), Size(0) {}
48
49     Value *getValue() const { return Val; }
50     
51     PointerRec *getNext() const { return NextInList; }
52     bool hasAliasSet() const { return AS != 0; }
53
54     PointerRec** setPrevInList(PointerRec **PIL) {
55       PrevInList = PIL;
56       return &NextInList;
57     }
58
59     void updateSize(unsigned NewSize) {
60       if (NewSize > Size) Size = NewSize;
61     }
62
63     unsigned getSize() const { return Size; }
64
65     AliasSet *getAliasSet(AliasSetTracker &AST) {
66       assert(AS && "No AliasSet yet!");
67       if (AS->Forward) {
68         AliasSet *OldAS = AS;
69         AS = OldAS->getForwardedTarget(AST);
70         AS->addRef();
71         OldAS->dropRef(AST);
72       }
73       return AS;
74     }
75
76     void setAliasSet(AliasSet *as) {
77       assert(AS == 0 && "Already have an alias set!");
78       AS = as;
79     }
80
81     void eraseFromList() {
82       if (NextInList) NextInList->PrevInList = PrevInList;
83       *PrevInList = NextInList;
84       if (AS->PtrListEnd == &NextInList) {
85         AS->PtrListEnd = PrevInList;
86         assert(*AS->PtrListEnd == 0 && "List not terminated right!");
87       }
88       delete this;
89     }
90   };
91
92   PointerRec *PtrList, **PtrListEnd;  // Doubly linked list of nodes.
93   AliasSet *Forward;             // Forwarding pointer.
94   AliasSet *Next, *Prev;         // Doubly linked list of AliasSets.
95
96   std::vector<CallSite> CallSites; // All calls & invokes in this alias set.
97
98   // RefCount - Number of nodes pointing to this AliasSet plus the number of
99   // AliasSets forwarding to it.
100   unsigned RefCount : 28;
101
102   /// AccessType - Keep track of whether this alias set merely refers to the
103   /// locations of memory, whether it modifies the memory, or whether it does
104   /// both.  The lattice goes from "NoModRef" to either Refs or Mods, then to
105   /// ModRef as necessary.
106   ///
107   enum AccessType {
108     NoModRef = 0, Refs = 1,         // Ref = bit 1
109     Mods     = 2, ModRef = 3        // Mod = bit 2
110   };
111   unsigned AccessTy : 2;
112
113   /// AliasType - Keep track the relationships between the pointers in the set.
114   /// Lattice goes from MustAlias to MayAlias.
115   ///
116   enum AliasType {
117     MustAlias = 0, MayAlias = 1
118   };
119   unsigned AliasTy : 1;
120
121   // Volatile - True if this alias set contains volatile loads or stores.
122   bool Volatile : 1;
123
124   void addRef() { ++RefCount; }
125   void dropRef(AliasSetTracker &AST) {
126     assert(RefCount >= 1 && "Invalid reference count detected!");
127     if (--RefCount == 0)
128       removeFromTracker(AST);
129   }
130
131 public:
132   /// Accessors...
133   bool isRef() const { return AccessTy & Refs; }
134   bool isMod() const { return AccessTy & Mods; }
135   bool isMustAlias() const { return AliasTy == MustAlias; }
136   bool isMayAlias()  const { return AliasTy == MayAlias; }
137
138   // isVolatile - Return true if this alias set contains volatile loads or
139   // stores.
140   bool isVolatile() const { return Volatile; }
141
142   /// isForwardingAliasSet - Return true if this alias set should be ignored as
143   /// part of the AliasSetTracker object.
144   bool isForwardingAliasSet() const { return Forward; }
145
146   /// mergeSetIn - Merge the specified alias set into this alias set...
147   ///
148   void mergeSetIn(AliasSet &AS, AliasSetTracker &AST);
149
150   // Alias Set iteration - Allow access to all of the pointer which are part of
151   // this alias set...
152   class iterator;
153   iterator begin() const { return iterator(PtrList); }
154   iterator end()   const { return iterator(); }
155   bool empty() const { return PtrList == 0; }
156
157   void print(raw_ostream &OS) const;
158   void dump() const;
159
160   /// Define an iterator for alias sets... this is just a forward iterator.
161   class iterator : public std::iterator<std::forward_iterator_tag, PointerRec, ptrdiff_t> {
162     PointerRec *CurNode;
163   public:
164     explicit iterator(PointerRec *CN = 0) : CurNode(CN) {}
165
166     bool operator==(const iterator& x) const {
167       return CurNode == x.CurNode;
168     }
169     bool operator!=(const iterator& x) const { return !operator==(x); }
170
171     const iterator &operator=(const iterator &I) {
172       CurNode = I.CurNode;
173       return *this;
174     }
175
176     value_type &operator*() const {
177       assert(CurNode && "Dereferencing AliasSet.end()!");
178       return *CurNode;
179     }
180     value_type *operator->() const { return &operator*(); }
181
182     Value *getPointer() const { return CurNode->getValue(); }
183     unsigned getSize() const { return CurNode->getSize(); }
184
185     iterator& operator++() {                // Preincrement
186       assert(CurNode && "Advancing past AliasSet.end()!");
187       CurNode = CurNode->getNext();
188       return *this;
189     }
190     iterator operator++(int) { // Postincrement
191       iterator tmp = *this; ++*this; return tmp;
192     }
193   };
194
195 private:
196   // Can only be created by AliasSetTracker. Also, ilist creates one
197   // to serve as a sentinel.
198   friend struct ilist_sentinel_traits<AliasSet>;
199   AliasSet() : PtrList(0), PtrListEnd(&PtrList), Forward(0), RefCount(0),
200                AccessTy(NoModRef), AliasTy(MustAlias), Volatile(false) {
201   }
202
203   AliasSet(const AliasSet &AS);        // do not implement
204   void operator=(const AliasSet &AS);  // do not implement
205
206   PointerRec *getSomePointer() const {
207     return PtrList;
208   }
209
210   /// getForwardedTarget - Return the real alias set this represents.  If this
211   /// has been merged with another set and is forwarding, return the ultimate
212   /// destination set.  This also implements the union-find collapsing as well.
213   AliasSet *getForwardedTarget(AliasSetTracker &AST) {
214     if (!Forward) return this;
215
216     AliasSet *Dest = Forward->getForwardedTarget(AST);
217     if (Dest != Forward) {
218       Dest->addRef();
219       Forward->dropRef(AST);
220       Forward = Dest;
221     }
222     return Dest;
223   }
224
225   void removeFromTracker(AliasSetTracker &AST);
226
227   void addPointer(AliasSetTracker &AST, PointerRec &Entry, unsigned Size,
228                   bool KnownMustAlias = false);
229   void addCallSite(CallSite CS, AliasAnalysis &AA);
230   void removeCallSite(CallSite CS) {
231     for (size_t i = 0, e = CallSites.size(); i != e; ++i)
232       if (CallSites[i].getInstruction() == CS.getInstruction()) {
233         CallSites[i] = CallSites.back();
234         CallSites.pop_back();
235       }
236   }
237   void setVolatile() { Volatile = true; }
238
239   /// aliasesPointer - Return true if the specified pointer "may" (or must)
240   /// alias one of the members in the set.
241   ///
242   bool aliasesPointer(const Value *Ptr, unsigned Size, AliasAnalysis &AA) const;
243   bool aliasesCallSite(CallSite CS, AliasAnalysis &AA) const;
244 };
245
246 inline raw_ostream& operator<<(raw_ostream &OS, const AliasSet &AS) {
247   AS.print(OS);
248   return OS;
249 }
250
251
252 class AliasSetTracker {
253   /// CallbackVH - A CallbackVH to arrange for AliasSetTracker to be
254   /// notified whenever a Value is deleted.
255   class ASTCallbackVH : public CallbackVH {
256     AliasSetTracker *AST;
257     virtual void deleted();
258   public:
259     ASTCallbackVH(Value *V, AliasSetTracker *AST = 0);
260     ASTCallbackVH &operator=(Value *V);
261   };
262   /// ASTCallbackVHDenseMapInfo - Traits to tell DenseMap that ASTCallbackVH
263   /// is not a POD (it needs its destructor called).
264   struct ASTCallbackVHDenseMapInfo : public DenseMapInfo<Value *> {
265     static bool isPod() { return false; }
266   };
267
268   AliasAnalysis &AA;
269   ilist<AliasSet> AliasSets;
270
271   typedef DenseMap<ASTCallbackVH, AliasSet::PointerRec*,
272                    ASTCallbackVHDenseMapInfo>
273     PointerMapType;
274
275   // Map from pointers to their node
276   PointerMapType PointerMap;
277
278 public:
279   /// AliasSetTracker ctor - Create an empty collection of AliasSets, and use
280   /// the specified alias analysis object to disambiguate load and store
281   /// addresses.
282   explicit AliasSetTracker(AliasAnalysis &aa) : AA(aa) {}
283   ~AliasSetTracker() { clear(); }
284
285   /// add methods - These methods are used to add different types of
286   /// instructions to the alias sets.  Adding a new instruction can result in
287   /// one of three actions happening:
288   ///
289   ///   1. If the instruction doesn't alias any other sets, create a new set.
290   ///   2. If the instruction aliases exactly one set, add it to the set
291   ///   3. If the instruction aliases multiple sets, merge the sets, and add
292   ///      the instruction to the result.
293   ///
294   /// These methods return true if inserting the instruction resulted in the
295   /// addition of a new alias set (i.e., the pointer did not alias anything).
296   ///
297   bool add(Value *Ptr, unsigned Size);  // Add a location
298   bool add(LoadInst *LI);
299   bool add(StoreInst *SI);
300   bool add(FreeInst *FI);
301   bool add(VAArgInst *VAAI);
302   bool add(CallSite CS);          // Call/Invoke instructions
303   bool add(CallInst *CI)   { return add(CallSite(CI)); }
304   bool add(InvokeInst *II) { return add(CallSite(II)); }
305   bool add(Instruction *I);       // Dispatch to one of the other add methods...
306   void add(BasicBlock &BB);       // Add all instructions in basic block
307   void add(const AliasSetTracker &AST); // Add alias relations from another AST
308
309   /// remove methods - These methods are used to remove all entries that might
310   /// be aliased by the specified instruction.  These methods return true if any
311   /// alias sets were eliminated.
312   bool remove(Value *Ptr, unsigned Size);  // Remove a location
313   bool remove(LoadInst *LI);
314   bool remove(StoreInst *SI);
315   bool remove(FreeInst *FI);
316   bool remove(VAArgInst *VAAI);
317   bool remove(CallSite CS);
318   bool remove(CallInst *CI)   { return remove(CallSite(CI)); }
319   bool remove(InvokeInst *II) { return remove(CallSite(II)); }
320   bool remove(Instruction *I);
321   void remove(AliasSet &AS);
322   
323   void clear();
324
325   /// getAliasSets - Return the alias sets that are active.
326   ///
327   const ilist<AliasSet> &getAliasSets() const { return AliasSets; }
328
329   /// getAliasSetForPointer - Return the alias set that the specified pointer
330   /// lives in.  If the New argument is non-null, this method sets the value to
331   /// true if a new alias set is created to contain the pointer (because the
332   /// pointer didn't alias anything).
333   AliasSet &getAliasSetForPointer(Value *P, unsigned Size, bool *New = 0);
334
335   /// getAliasSetForPointerIfExists - Return the alias set containing the
336   /// location specified if one exists, otherwise return null.
337   AliasSet *getAliasSetForPointerIfExists(Value *P, unsigned Size) {
338     return findAliasSetForPointer(P, Size);
339   }
340
341   /// containsPointer - Return true if the specified location is represented by
342   /// this alias set, false otherwise.  This does not modify the AST object or
343   /// alias sets.
344   bool containsPointer(Value *P, unsigned Size) const;
345
346   /// getAliasAnalysis - Return the underlying alias analysis object used by
347   /// this tracker.
348   AliasAnalysis &getAliasAnalysis() const { return AA; }
349
350   /// deleteValue method - This method is used to remove a pointer value from
351   /// the AliasSetTracker entirely.  It should be used when an instruction is
352   /// deleted from the program to update the AST.  If you don't use this, you
353   /// would have dangling pointers to deleted instructions.
354   ///
355   void deleteValue(Value *PtrVal);
356
357   /// copyValue - This method should be used whenever a preexisting value in the
358   /// program is copied or cloned, introducing a new value.  Note that it is ok
359   /// for clients that use this method to introduce the same value multiple
360   /// times: if the tracker already knows about a value, it will ignore the
361   /// request.
362   ///
363   void copyValue(Value *From, Value *To);
364
365
366   typedef ilist<AliasSet>::iterator iterator;
367   typedef ilist<AliasSet>::const_iterator const_iterator;
368
369   const_iterator begin() const { return AliasSets.begin(); }
370   const_iterator end()   const { return AliasSets.end(); }
371
372   iterator begin() { return AliasSets.begin(); }
373   iterator end()   { return AliasSets.end(); }
374
375   void print(raw_ostream &OS) const;
376   void dump() const;
377
378 private:
379   friend class AliasSet;
380   void removeAliasSet(AliasSet *AS);
381
382   // getEntryFor - Just like operator[] on the map, except that it creates an
383   // entry for the pointer if it doesn't already exist.
384   AliasSet::PointerRec &getEntryFor(Value *V) {
385     AliasSet::PointerRec *&Entry = PointerMap[ASTCallbackVH(V, this)];
386     if (Entry == 0)
387       Entry = new AliasSet::PointerRec(V);
388     return *Entry;
389   }
390
391   AliasSet &addPointer(Value *P, unsigned Size, AliasSet::AccessType E,
392                        bool &NewSet) {
393     NewSet = false;
394     AliasSet &AS = getAliasSetForPointer(P, Size, &NewSet);
395     AS.AccessTy |= E;
396     return AS;
397   }
398   AliasSet *findAliasSetForPointer(const Value *Ptr, unsigned Size);
399
400   AliasSet *findAliasSetForCallSite(CallSite CS);
401 };
402
403 inline raw_ostream& operator<<(raw_ostream &OS, const AliasSetTracker &AST) {
404   AST.print(OS);
405   return OS;
406 }
407
408 } // End llvm namespace
409
410 #endif