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