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