AliasSetTracker.h revision a818c30d664cd4ba4b9ed69fb2048a6ea55ec9cd
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/iterator.h"
24#include "llvm/ADT/ilist.h"
25#include "llvm/ADT/ilist_node.h"
26#include <vector>
27
28namespace llvm {
29
30class AliasAnalysis;
31class LoadInst;
32class StoreInst;
33class FreeInst;
34class VAArgInst;
35class AliasSetTracker;
36class AliasSet;
37
38class AliasSet : public ilist_node<AliasSet> {
39  friend class AliasSetTracker;
40
41  class PointerRec {
42    Value *Val;  // The pointer this record corresponds to.
43    PointerRec **PrevInList, *NextInList;
44    AliasSet *AS;
45    unsigned Size;
46  public:
47    PointerRec(Value *V)
48      : Val(V), PrevInList(0), NextInList(0), AS(0), Size(0) {}
49
50    Value *getValue() const { return Val; }
51
52    PointerRec *getNext() const { return NextInList; }
53    bool hasAliasSet() const { return AS != 0; }
54
55    PointerRec** setPrevInList(PointerRec **PIL) {
56      PrevInList = PIL;
57      return &NextInList;
58    }
59
60    void updateSize(unsigned NewSize) {
61      if (NewSize > Size) Size = NewSize;
62    }
63
64    unsigned getSize() const { return Size; }
65
66    AliasSet *getAliasSet(AliasSetTracker &AST) {
67      assert(AS && "No AliasSet yet!");
68      if (AS->Forward) {
69        AliasSet *OldAS = AS;
70        AS = OldAS->getForwardedTarget(AST);
71        AS->addRef();
72        OldAS->dropRef(AST);
73      }
74      return AS;
75    }
76
77    void setAliasSet(AliasSet *as) {
78      assert(AS == 0 && "Already have an alias set!");
79      AS = as;
80    }
81
82    void eraseFromList() {
83      if (NextInList) NextInList->PrevInList = PrevInList;
84      *PrevInList = NextInList;
85      if (AS->PtrListEnd == &NextInList) {
86        AS->PtrListEnd = PrevInList;
87        assert(*AS->PtrListEnd == 0 && "List not terminated right!");
88      }
89      delete this;
90    }
91  };
92
93  PointerRec *PtrList, **PtrListEnd;  // Doubly linked list of nodes.
94  AliasSet *Forward;             // Forwarding pointer.
95  AliasSet *Next, *Prev;         // Doubly linked list of AliasSets.
96
97  std::vector<CallSite> CallSites; // All calls & invokes in this alias set.
98
99  // RefCount - Number of nodes pointing to this AliasSet plus the number of
100  // AliasSets forwarding to it.
101  unsigned RefCount : 28;
102
103  /// AccessType - Keep track of whether this alias set merely refers to the
104  /// locations of memory, whether it modifies the memory, or whether it does
105  /// both.  The lattice goes from "NoModRef" to either Refs or Mods, then to
106  /// ModRef as necessary.
107  ///
108  enum AccessType {
109    NoModRef = 0, Refs = 1,         // Ref = bit 1
110    Mods     = 2, ModRef = 3        // Mod = bit 2
111  };
112  unsigned AccessTy : 2;
113
114  /// AliasType - Keep track the relationships between the pointers in the set.
115  /// Lattice goes from MustAlias to MayAlias.
116  ///
117  enum AliasType {
118    MustAlias = 0, MayAlias = 1
119  };
120  unsigned AliasTy : 1;
121
122  // Volatile - True if this alias set contains volatile loads or stores.
123  bool Volatile : 1;
124
125  void addRef() { ++RefCount; }
126  void dropRef(AliasSetTracker &AST) {
127    assert(RefCount >= 1 && "Invalid reference count detected!");
128    if (--RefCount == 0)
129      removeFromTracker(AST);
130  }
131
132public:
133  /// Accessors...
134  bool isRef() const { return AccessTy & Refs; }
135  bool isMod() const { return AccessTy & Mods; }
136  bool isMustAlias() const { return AliasTy == MustAlias; }
137  bool isMayAlias()  const { return AliasTy == MayAlias; }
138
139  // isVolatile - Return true if this alias set contains volatile loads or
140  // stores.
141  bool isVolatile() const { return Volatile; }
142
143  /// isForwardingAliasSet - Return true if this alias set should be ignored as
144  /// part of the AliasSetTracker object.
145  bool isForwardingAliasSet() const { return Forward; }
146
147  /// mergeSetIn - Merge the specified alias set into this alias set...
148  ///
149  void mergeSetIn(AliasSet &AS, AliasSetTracker &AST);
150
151  // Alias Set iteration - Allow access to all of the pointer which are part of
152  // this alias set...
153  class iterator;
154  iterator begin() const { return iterator(PtrList); }
155  iterator end()   const { return iterator(); }
156  bool empty() const { return PtrList == 0; }
157
158  void print(std::ostream &OS) const;
159  void print(std::ostream *OS) const { if (OS) print(*OS); }
160  void dump() const;
161
162  /// Define an iterator for alias sets... this is just a forward iterator.
163  class iterator : public forward_iterator<PointerRec, ptrdiff_t> {
164    PointerRec *CurNode;
165  public:
166    explicit iterator(PointerRec *CN = 0) : CurNode(CN) {}
167
168    bool operator==(const iterator& x) const {
169      return CurNode == x.CurNode;
170    }
171    bool operator!=(const iterator& x) const { return !operator==(x); }
172
173    const iterator &operator=(const iterator &I) {
174      CurNode = I.CurNode;
175      return *this;
176    }
177
178    value_type &operator*() const {
179      assert(CurNode && "Dereferencing AliasSet.end()!");
180      return *CurNode;
181    }
182    value_type *operator->() const { return &operator*(); }
183
184    Value *getPointer() const { return CurNode->getValue(); }
185    unsigned getSize() const { return CurNode->getSize(); }
186
187    iterator& operator++() {                // Preincrement
188      assert(CurNode && "Advancing past AliasSet.end()!");
189      CurNode = CurNode->getNext();
190      return *this;
191    }
192    iterator operator++(int) { // Postincrement
193      iterator tmp = *this; ++*this; return tmp;
194    }
195  };
196
197private:
198  // Can only be created by AliasSetTracker. Also, ilist creates one
199  // to serve as a sentinel.
200  friend struct ilist_sentinel_traits<AliasSet>;
201  AliasSet() : PtrList(0), PtrListEnd(&PtrList), Forward(0), RefCount(0),
202               AccessTy(NoModRef), AliasTy(MustAlias), Volatile(false) {
203  }
204
205  AliasSet(const AliasSet &AS);        // do not implement
206  void operator=(const AliasSet &AS);  // do not implement
207
208  PointerRec *getSomePointer() const {
209    return PtrList;
210  }
211
212  /// getForwardedTarget - Return the real alias set this represents.  If this
213  /// has been merged with another set and is forwarding, return the ultimate
214  /// destination set.  This also implements the union-find collapsing as well.
215  AliasSet *getForwardedTarget(AliasSetTracker &AST) {
216    if (!Forward) return this;
217
218    AliasSet *Dest = Forward->getForwardedTarget(AST);
219    if (Dest != Forward) {
220      Dest->addRef();
221      Forward->dropRef(AST);
222      Forward = Dest;
223    }
224    return Dest;
225  }
226
227  void removeFromTracker(AliasSetTracker &AST);
228
229  void addPointer(AliasSetTracker &AST, PointerRec &Entry, unsigned Size,
230                  bool KnownMustAlias = false);
231  void addCallSite(CallSite CS, AliasAnalysis &AA);
232  void removeCallSite(CallSite CS) {
233    for (size_t i = 0, e = CallSites.size(); i != e; ++i)
234      if (CallSites[i].getInstruction() == CS.getInstruction()) {
235        CallSites[i] = CallSites.back();
236        CallSites.pop_back();
237      }
238  }
239  void setVolatile() { Volatile = true; }
240
241  /// aliasesPointer - Return true if the specified pointer "may" (or must)
242  /// alias one of the members in the set.
243  ///
244  bool aliasesPointer(const Value *Ptr, unsigned Size, AliasAnalysis &AA) const;
245  bool aliasesCallSite(CallSite CS, AliasAnalysis &AA) const;
246};
247
248inline std::ostream& operator<<(std::ostream &OS, const AliasSet &AS) {
249  AS.print(OS);
250  return OS;
251}
252
253
254class AliasSetTracker {
255  /// CallbackVH - A CallbackVH to arrange for AliasSetTracker to be
256  /// notified whenever a Value is deleted.
257  class ASTCallbackVH : public CallbackVH {
258    AliasSetTracker *AST;
259    virtual void deleted();
260  public:
261    ASTCallbackVH(Value *V, AliasSetTracker *AST = 0);
262    ASTCallbackVH &operator=(Value *V);
263  };
264  /// ASTCallbackVHDenseMapInfo - Traits to tell DenseMap that ASTCallbackVH
265  /// is not a POD (it needs its destructor called).
266  struct ASTCallbackVHDenseMapInfo : public DenseMapInfo<Value *> {
267    static bool isPod() { return false; }
268  };
269
270  AliasAnalysis &AA;
271  ilist<AliasSet> AliasSets;
272
273  typedef DenseMap<ASTCallbackVH, AliasSet::PointerRec*,
274                   ASTCallbackVHDenseMapInfo>
275    PointerMapType;
276
277  // Map from pointers to their node
278  PointerMapType PointerMap;
279
280public:
281  /// AliasSetTracker ctor - Create an empty collection of AliasSets, and use
282  /// the specified alias analysis object to disambiguate load and store
283  /// addresses.
284  explicit AliasSetTracker(AliasAnalysis &aa) : AA(aa) {}
285  ~AliasSetTracker() { clear(); }
286
287  /// add methods - These methods are used to add different types of
288  /// instructions to the alias sets.  Adding a new instruction can result in
289  /// one of three actions happening:
290  ///
291  ///   1. If the instruction doesn't alias any other sets, create a new set.
292  ///   2. If the instruction aliases exactly one set, add it to the set
293  ///   3. If the instruction aliases multiple sets, merge the sets, and add
294  ///      the instruction to the result.
295  ///
296  /// These methods return true if inserting the instruction resulted in the
297  /// addition of a new alias set (i.e., the pointer did not alias anything).
298  ///
299  bool add(Value *Ptr, unsigned Size);  // Add a location
300  bool add(LoadInst *LI);
301  bool add(StoreInst *SI);
302  bool add(FreeInst *FI);
303  bool add(VAArgInst *VAAI);
304  bool add(CallSite CS);          // Call/Invoke instructions
305  bool add(CallInst *CI)   { return add(CallSite(CI)); }
306  bool add(InvokeInst *II) { return add(CallSite(II)); }
307  bool add(Instruction *I);       // Dispatch to one of the other add methods...
308  void add(BasicBlock &BB);       // Add all instructions in basic block
309  void add(const AliasSetTracker &AST); // Add alias relations from another AST
310
311  /// remove methods - These methods are used to remove all entries that might
312  /// be aliased by the specified instruction.  These methods return true if any
313  /// alias sets were eliminated.
314  bool remove(Value *Ptr, unsigned Size);  // Remove a location
315  bool remove(LoadInst *LI);
316  bool remove(StoreInst *SI);
317  bool remove(FreeInst *FI);
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(std::ostream &OS) const;
378  void print(std::ostream *OS) const { if (OS) print(*OS); }
379  void dump() const;
380
381private:
382  friend class AliasSet;
383  void removeAliasSet(AliasSet *AS);
384
385  // getEntryFor - Just like operator[] on the map, except that it creates an
386  // entry for the pointer if it doesn't already exist.
387  AliasSet::PointerRec &getEntryFor(Value *V) {
388    AliasSet::PointerRec *&Entry = PointerMap[ASTCallbackVH(V, this)];
389    if (Entry == 0)
390      Entry = new AliasSet::PointerRec(V);
391    return *Entry;
392  }
393
394  AliasSet &addPointer(Value *P, unsigned Size, AliasSet::AccessType E,
395                       bool &NewSet) {
396    NewSet = false;
397    AliasSet &AS = getAliasSetForPointer(P, Size, &NewSet);
398    AS.AccessTy |= E;
399    return AS;
400  }
401  AliasSet *findAliasSetForPointer(const Value *Ptr, unsigned Size);
402
403  AliasSet *findAliasSetForCallSite(CallSite CS);
404};
405
406inline std::ostream& operator<<(std::ostream &OS, const AliasSetTracker &AST) {
407  AST.print(OS);
408  return OS;
409}
410
411} // End llvm namespace
412
413#endif
414