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