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