AliasSetTracker.h revision 4bbf4ee1491637c247e195e19e3e4a8ee5ad72fa
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
27namespace llvm {
28
29class AliasAnalysis;
30class LoadInst;
31class StoreInst;
32class VAArgInst;
33class AliasSetTracker;
34class AliasSet;
35
36class 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  std::vector<CallSite> CallSites; // All calls & invokes in this alias set.
96
97  // RefCount - Number of nodes pointing to this AliasSet plus the number of
98  // AliasSets forwarding to it.
99  unsigned RefCount : 28;
100
101  /// AccessType - Keep track of whether this alias set merely refers to the
102  /// locations of memory, whether it modifies the memory, or whether it does
103  /// both.  The lattice goes from "NoModRef" to either Refs or Mods, then to
104  /// ModRef as necessary.
105  ///
106  enum AccessType {
107    NoModRef = 0, Refs = 1,         // Ref = bit 1
108    Mods     = 2, ModRef = 3        // Mod = bit 2
109  };
110  unsigned AccessTy : 2;
111
112  /// AliasType - Keep track the relationships between the pointers in the set.
113  /// Lattice goes from MustAlias to MayAlias.
114  ///
115  enum AliasType {
116    MustAlias = 0, MayAlias = 1
117  };
118  unsigned AliasTy : 1;
119
120  // Volatile - True if this alias set contains volatile loads or stores.
121  bool Volatile : 1;
122
123  void addRef() { ++RefCount; }
124  void dropRef(AliasSetTracker &AST) {
125    assert(RefCount >= 1 && "Invalid reference count detected!");
126    if (--RefCount == 0)
127      removeFromTracker(AST);
128  }
129
130public:
131  /// Accessors...
132  bool isRef() const { return AccessTy & Refs; }
133  bool isMod() const { return AccessTy & Mods; }
134  bool isMustAlias() const { return AliasTy == MustAlias; }
135  bool isMayAlias()  const { return AliasTy == MayAlias; }
136
137  // isVolatile - Return true if this alias set contains volatile loads or
138  // stores.
139  bool isVolatile() const { return Volatile; }
140
141  /// isForwardingAliasSet - Return true if this alias set should be ignored as
142  /// part of the AliasSetTracker object.
143  bool isForwardingAliasSet() const { return Forward; }
144
145  /// mergeSetIn - Merge the specified alias set into this alias set...
146  ///
147  void mergeSetIn(AliasSet &AS, AliasSetTracker &AST);
148
149  // Alias Set iteration - Allow access to all of the pointer which are part of
150  // this alias set...
151  class iterator;
152  iterator begin() const { return iterator(PtrList); }
153  iterator end()   const { return iterator(); }
154  bool empty() const { return PtrList == 0; }
155
156  void print(raw_ostream &OS) const;
157  void dump() const;
158
159  /// Define an iterator for alias sets... this is just a forward iterator.
160  class iterator : public std::iterator<std::forward_iterator_tag,
161                                        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
195private:
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
246inline raw_ostream& operator<<(raw_ostream &OS, const AliasSet &AS) {
247  AS.print(OS);
248  return OS;
249}
250
251
252class 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 tell us how to
263  /// compare and hash the value handle.
264  struct ASTCallbackVHDenseMapInfo : public DenseMapInfo<Value *> {};
265
266  AliasAnalysis &AA;
267  ilist<AliasSet> AliasSets;
268
269  typedef DenseMap<ASTCallbackVH, AliasSet::PointerRec*,
270                   ASTCallbackVHDenseMapInfo>
271    PointerMapType;
272
273  // Map from pointers to their node
274  PointerMapType PointerMap;
275
276public:
277  /// AliasSetTracker ctor - Create an empty collection of AliasSets, and use
278  /// the specified alias analysis object to disambiguate load and store
279  /// addresses.
280  explicit AliasSetTracker(AliasAnalysis &aa) : AA(aa) {}
281  ~AliasSetTracker() { clear(); }
282
283  /// add methods - These methods are used to add different types of
284  /// instructions to the alias sets.  Adding a new instruction can result in
285  /// one of three actions happening:
286  ///
287  ///   1. If the instruction doesn't alias any other sets, create a new set.
288  ///   2. If the instruction aliases exactly one set, add it to the set
289  ///   3. If the instruction aliases multiple sets, merge the sets, and add
290  ///      the instruction to the result.
291  ///
292  /// These methods return true if inserting the instruction resulted in the
293  /// addition of a new alias set (i.e., the pointer did not alias anything).
294  ///
295  bool add(Value *Ptr, unsigned Size);  // Add a location
296  bool add(LoadInst *LI);
297  bool add(StoreInst *SI);
298  bool add(VAArgInst *VAAI);
299  bool add(CallSite CS);          // Call/Invoke instructions
300  bool add(CallInst *CI)   { return add(CallSite(CI)); }
301  bool add(InvokeInst *II) { return add(CallSite(II)); }
302  bool add(Instruction *I);       // Dispatch to one of the other add methods...
303  void add(BasicBlock &BB);       // Add all instructions in basic block
304  void add(const AliasSetTracker &AST); // Add alias relations from another AST
305
306  /// remove methods - These methods are used to remove all entries that might
307  /// be aliased by the specified instruction.  These methods return true if any
308  /// alias sets were eliminated.
309  bool remove(Value *Ptr, unsigned Size);  // Remove a location
310  bool remove(LoadInst *LI);
311  bool remove(StoreInst *SI);
312  bool remove(VAArgInst *VAAI);
313  bool remove(CallSite CS);
314  bool remove(CallInst *CI)   { return remove(CallSite(CI)); }
315  bool remove(InvokeInst *II) { return remove(CallSite(II)); }
316  bool remove(Instruction *I);
317  void remove(AliasSet &AS);
318
319  void clear();
320
321  /// getAliasSets - Return the alias sets that are active.
322  ///
323  const ilist<AliasSet> &getAliasSets() const { return AliasSets; }
324
325  /// getAliasSetForPointer - Return the alias set that the specified pointer
326  /// lives in.  If the New argument is non-null, this method sets the value to
327  /// true if a new alias set is created to contain the pointer (because the
328  /// pointer didn't alias anything).
329  AliasSet &getAliasSetForPointer(Value *P, unsigned Size, bool *New = 0);
330
331  /// getAliasSetForPointerIfExists - Return the alias set containing the
332  /// location specified if one exists, otherwise return null.
333  AliasSet *getAliasSetForPointerIfExists(Value *P, unsigned Size) {
334    return findAliasSetForPointer(P, Size);
335  }
336
337  /// containsPointer - Return true if the specified location is represented by
338  /// this alias set, false otherwise.  This does not modify the AST object or
339  /// alias sets.
340  bool containsPointer(Value *P, unsigned Size) const;
341
342  /// getAliasAnalysis - Return the underlying alias analysis object used by
343  /// this tracker.
344  AliasAnalysis &getAliasAnalysis() const { return AA; }
345
346  /// deleteValue method - This method is used to remove a pointer value from
347  /// the AliasSetTracker entirely.  It should be used when an instruction is
348  /// deleted from the program to update the AST.  If you don't use this, you
349  /// would have dangling pointers to deleted instructions.
350  ///
351  void deleteValue(Value *PtrVal);
352
353  /// copyValue - This method should be used whenever a preexisting value in the
354  /// program is copied or cloned, introducing a new value.  Note that it is ok
355  /// for clients that use this method to introduce the same value multiple
356  /// times: if the tracker already knows about a value, it will ignore the
357  /// request.
358  ///
359  void copyValue(Value *From, Value *To);
360
361
362  typedef ilist<AliasSet>::iterator iterator;
363  typedef ilist<AliasSet>::const_iterator const_iterator;
364
365  const_iterator begin() const { return AliasSets.begin(); }
366  const_iterator end()   const { return AliasSets.end(); }
367
368  iterator begin() { return AliasSets.begin(); }
369  iterator end()   { return AliasSets.end(); }
370
371  void print(raw_ostream &OS) const;
372  void dump() const;
373
374private:
375  friend class AliasSet;
376  void removeAliasSet(AliasSet *AS);
377
378  // getEntryFor - Just like operator[] on the map, except that it creates an
379  // entry for the pointer if it doesn't already exist.
380  AliasSet::PointerRec &getEntryFor(Value *V) {
381    AliasSet::PointerRec *&Entry = PointerMap[ASTCallbackVH(V, this)];
382    if (Entry == 0)
383      Entry = new AliasSet::PointerRec(V);
384    return *Entry;
385  }
386
387  AliasSet &addPointer(Value *P, unsigned Size, AliasSet::AccessType E,
388                       bool &NewSet) {
389    NewSet = false;
390    AliasSet &AS = getAliasSetForPointer(P, Size, &NewSet);
391    AS.AccessTy |= E;
392    return AS;
393  }
394  AliasSet *findAliasSetForPointer(const Value *Ptr, unsigned Size);
395
396  AliasSet *findAliasSetForCallSite(CallSite CS);
397};
398
399inline raw_ostream& operator<<(raw_ostream &OS, const AliasSetTracker &AST) {
400  AST.print(OS);
401  return OS;
402}
403
404} // End llvm namespace
405
406#endif
407