LLVM  5.0.0
AliasSetTracker.h
Go to the documentation of this file.
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 interfaces
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/ADT/DenseMap.h"
21 #include "llvm/ADT/ilist.h"
22 #include "llvm/ADT/ilist_node.h"
24 #include "llvm/IR/Metadata.h"
25 #include "llvm/IR/ValueHandle.h"
26 #include <vector>
27 
28 namespace llvm {
29 
30 class LoadInst;
31 class StoreInst;
32 class VAArgInst;
33 class MemSetInst;
34 class AliasSetTracker;
35 class AliasSet;
36 
37 class AliasSet : public ilist_node<AliasSet> {
38  friend class AliasSetTracker;
39 
40  class PointerRec {
41  Value *Val; // The pointer this record corresponds to.
42  PointerRec **PrevInList, *NextInList;
43  AliasSet *AS;
44  uint64_t Size;
45  AAMDNodes AAInfo;
46 
47  public:
48  PointerRec(Value *V)
49  : Val(V), PrevInList(nullptr), NextInList(nullptr), AS(nullptr), Size(0),
50  AAInfo(DenseMapInfo<AAMDNodes>::getEmptyKey()) {}
51 
52  Value *getValue() const { return Val; }
53 
54  PointerRec *getNext() const { return NextInList; }
55  bool hasAliasSet() const { return AS != nullptr; }
56 
57  PointerRec** setPrevInList(PointerRec **PIL) {
58  PrevInList = PIL;
59  return &NextInList;
60  }
61 
62  bool updateSizeAndAAInfo(uint64_t NewSize, const AAMDNodes &NewAAInfo) {
63  bool SizeChanged = false;
64  if (NewSize > Size) {
65  Size = NewSize;
66  SizeChanged = true;
67  }
68 
70  // We don't have a AAInfo yet. Set it to NewAAInfo.
71  AAInfo = NewAAInfo;
72  else {
73  AAMDNodes Intersection(AAInfo.intersect(NewAAInfo));
74  if (!Intersection) {
75  // NewAAInfo conflicts with AAInfo.
77  return SizeChanged;
78  }
79  AAInfo = Intersection;
80  }
81  return SizeChanged;
82  }
83 
84  uint64_t getSize() const { return Size; }
85 
86  /// Return the AAInfo, or null if there is no information or conflicting
87  /// information.
88  AAMDNodes getAAInfo() const {
89  // If we have missing or conflicting AAInfo, return null.
90  if (AAInfo == DenseMapInfo<AAMDNodes>::getEmptyKey() ||
92  return AAMDNodes();
93  return AAInfo;
94  }
95 
96  AliasSet *getAliasSet(AliasSetTracker &AST) {
97  assert(AS && "No AliasSet yet!");
98  if (AS->Forward) {
99  AliasSet *OldAS = AS;
100  AS = OldAS->getForwardedTarget(AST);
101  AS->addRef();
102  OldAS->dropRef(AST);
103  }
104  return AS;
105  }
106 
107  void setAliasSet(AliasSet *as) {
108  assert(!AS && "Already have an alias set!");
109  AS = as;
110  }
111 
112  void eraseFromList() {
113  if (NextInList) NextInList->PrevInList = PrevInList;
114  *PrevInList = NextInList;
115  if (AS->PtrListEnd == &NextInList) {
116  AS->PtrListEnd = PrevInList;
117  assert(*AS->PtrListEnd == nullptr && "List not terminated right!");
118  }
119  delete this;
120  }
121  };
122 
123  // Doubly linked list of nodes.
124  PointerRec *PtrList, **PtrListEnd;
125  // Forwarding pointer.
126  AliasSet *Forward;
127 
128  /// All instructions without a specific address in this alias set.
129  /// In rare cases this vector can have a null'ed out WeakVH
130  /// instances (can happen if some other loop pass deletes an
131  /// instruction in this list).
132  std::vector<WeakVH> UnknownInsts;
133 
134  /// Number of nodes pointing to this AliasSet plus the number of AliasSets
135  /// forwarding to it.
136  unsigned RefCount : 27;
137 
138  // Signifies that this set should be considered to alias any pointer.
139  // Use when the tracker holding this set is saturated.
140  unsigned AliasAny : 1;
141 
142  /// The kinds of access this alias set models.
143  ///
144  /// We keep track of whether this alias set merely refers to the locations of
145  /// memory (and not any particular access), whether it modifies or references
146  /// the memory, or whether it does both. The lattice goes from "NoAccess" to
147  /// either RefAccess or ModAccess, then to ModRefAccess as necessary.
148  enum AccessLattice {
149  NoAccess = 0,
150  RefAccess = 1,
151  ModAccess = 2,
152  ModRefAccess = RefAccess | ModAccess
153  };
154  unsigned Access : 2;
155 
156  /// The kind of alias relationship between pointers of the set.
157  ///
158  /// These represent conservatively correct alias results between any members
159  /// of the set. We represent these independently of the values of alias
160  /// results in order to pack it into a single bit. Lattice goes from
161  /// MustAlias to MayAlias.
162  enum AliasLattice {
163  SetMustAlias = 0, SetMayAlias = 1
164  };
165  unsigned Alias : 1;
166 
167  /// True if this alias set contains volatile loads or stores.
168  unsigned Volatile : 1;
169 
170  unsigned SetSize;
171 
172  void addRef() { ++RefCount; }
173 
174  void dropRef(AliasSetTracker &AST) {
175  assert(RefCount >= 1 && "Invalid reference count detected!");
176  if (--RefCount == 0)
177  removeFromTracker(AST);
178  }
179 
180  Instruction *getUnknownInst(unsigned i) const {
181  assert(i < UnknownInsts.size());
182  return cast_or_null<Instruction>(UnknownInsts[i]);
183  }
184 
185 public:
186  /// Accessors...
187  bool isRef() const { return Access & RefAccess; }
188  bool isMod() const { return Access & ModAccess; }
189  bool isMustAlias() const { return Alias == SetMustAlias; }
190  bool isMayAlias() const { return Alias == SetMayAlias; }
191 
192  /// Return true if this alias set contains volatile loads or stores.
193  bool isVolatile() const { return Volatile; }
194 
195  /// Return true if this alias set should be ignored as part of the
196  /// AliasSetTracker object.
197  bool isForwardingAliasSet() const { return Forward; }
198 
199  /// Merge the specified alias set into this alias set.
200  void mergeSetIn(AliasSet &AS, AliasSetTracker &AST);
201 
202  // Alias Set iteration - Allow access to all of the pointers which are part of
203  // this alias set.
204  class iterator;
205  iterator begin() const { return iterator(PtrList); }
206  iterator end() const { return iterator(); }
207  bool empty() const { return PtrList == nullptr; }
208 
209  // Unfortunately, ilist::size() is linear, so we have to add code to keep
210  // track of the list's exact size.
211  unsigned size() { return SetSize; }
212 
213  void print(raw_ostream &OS) const;
214  void dump() const;
215 
216  /// Define an iterator for alias sets... this is just a forward iterator.
217  class iterator : public std::iterator<std::forward_iterator_tag,
218  PointerRec, ptrdiff_t> {
219  PointerRec *CurNode;
220 
221  public:
222  explicit iterator(PointerRec *CN = nullptr) : CurNode(CN) {}
223 
224  bool operator==(const iterator& x) const {
225  return CurNode == x.CurNode;
226  }
227  bool operator!=(const iterator& x) const { return !operator==(x); }
228 
229  value_type &operator*() const {
230  assert(CurNode && "Dereferencing AliasSet.end()!");
231  return *CurNode;
232  }
233  value_type *operator->() const { return &operator*(); }
234 
235  Value *getPointer() const { return CurNode->getValue(); }
236  uint64_t getSize() const { return CurNode->getSize(); }
237  AAMDNodes getAAInfo() const { return CurNode->getAAInfo(); }
238 
239  iterator& operator++() { // Preincrement
240  assert(CurNode && "Advancing past AliasSet.end()!");
241  CurNode = CurNode->getNext();
242  return *this;
243  }
244  iterator operator++(int) { // Postincrement
245  iterator tmp = *this; ++*this; return tmp;
246  }
247  };
248 
249 private:
250  // Can only be created by AliasSetTracker.
251  AliasSet()
252  : PtrList(nullptr), PtrListEnd(&PtrList), Forward(nullptr), RefCount(0),
253  AliasAny(false), Access(NoAccess), Alias(SetMustAlias),
254  Volatile(false), SetSize(0) {}
255 
256  AliasSet(const AliasSet &AS) = delete;
257  void operator=(const AliasSet &AS) = delete;
258 
259  PointerRec *getSomePointer() const {
260  return PtrList;
261  }
262 
263  /// Return the real alias set this represents. If this has been merged with
264  /// another set and is forwarding, return the ultimate destination set. This
265  /// also implements the union-find collapsing as well.
266  AliasSet *getForwardedTarget(AliasSetTracker &AST) {
267  if (!Forward) return this;
268 
269  AliasSet *Dest = Forward->getForwardedTarget(AST);
270  if (Dest != Forward) {
271  Dest->addRef();
272  Forward->dropRef(AST);
273  Forward = Dest;
274  }
275  return Dest;
276  }
277 
278  void removeFromTracker(AliasSetTracker &AST);
279 
280  void addPointer(AliasSetTracker &AST, PointerRec &Entry, uint64_t Size,
281  const AAMDNodes &AAInfo,
282  bool KnownMustAlias = false);
283  void addUnknownInst(Instruction *I, AliasAnalysis &AA);
284  void removeUnknownInst(AliasSetTracker &AST, Instruction *I) {
285  bool WasEmpty = UnknownInsts.empty();
286  for (size_t i = 0, e = UnknownInsts.size(); i != e; ++i)
287  if (UnknownInsts[i] == I) {
288  UnknownInsts[i] = UnknownInsts.back();
289  UnknownInsts.pop_back();
290  --i; --e; // Revisit the moved entry.
291  }
292  if (!WasEmpty && UnknownInsts.empty())
293  dropRef(AST);
294  }
295  void setVolatile() { Volatile = true; }
296 
297 public:
298  /// Return true if the specified pointer "may" (or must) alias one of the
299  /// members in the set.
300  bool aliasesPointer(const Value *Ptr, uint64_t Size, const AAMDNodes &AAInfo,
301  AliasAnalysis &AA) const;
302  bool aliasesUnknownInst(const Instruction *Inst, AliasAnalysis &AA) const;
303 };
304 
305 inline raw_ostream& operator<<(raw_ostream &OS, const AliasSet &AS) {
306  AS.print(OS);
307  return OS;
308 }
309 
311  /// A CallbackVH to arrange for AliasSetTracker to be notified whenever a
312  /// Value is deleted.
313  class ASTCallbackVH final : public CallbackVH {
314  AliasSetTracker *AST;
315  void deleted() override;
316  void allUsesReplacedWith(Value *) override;
317 
318  public:
319  ASTCallbackVH(Value *V, AliasSetTracker *AST = nullptr);
320  ASTCallbackVH &operator=(Value *V);
321  };
322  /// Traits to tell DenseMap that tell us how to compare and hash the value
323  /// handle.
324  struct ASTCallbackVHDenseMapInfo : public DenseMapInfo<Value *> {};
325 
326  AliasAnalysis &AA;
327  ilist<AliasSet> AliasSets;
328 
329  typedef DenseMap<ASTCallbackVH, AliasSet::PointerRec*,
330  ASTCallbackVHDenseMapInfo>
332 
333  // Map from pointers to their node
334  PointerMapType PointerMap;
335 
336 public:
337  /// Create an empty collection of AliasSets, and use the specified alias
338  /// analysis object to disambiguate load and store addresses.
340  : AA(aa), TotalMayAliasSetSize(0), AliasAnyAS(nullptr) {}
342 
343  /// These methods are used to add different types of instructions to the alias
344  /// sets. Adding a new instruction can result in one of three actions
345  /// happening:
346  ///
347  /// 1. If the instruction doesn't alias any other sets, create a new set.
348  /// 2. If the instruction aliases exactly one set, add it to the set
349  /// 3. If the instruction aliases multiple sets, merge the sets, and add
350  /// the instruction to the result.
351  ///
352  /// These methods return true if inserting the instruction resulted in the
353  /// addition of a new alias set (i.e., the pointer did not alias anything).
354  ///
355  void add(Value *Ptr, uint64_t Size, const AAMDNodes &AAInfo); // Add a loc.
356  void add(LoadInst *LI);
357  void add(StoreInst *SI);
358  void add(VAArgInst *VAAI);
359  void add(MemSetInst *MSI);
360  void add(MemTransferInst *MTI);
361  void add(Instruction *I); // Dispatch to one of the other add methods...
362  void add(BasicBlock &BB); // Add all instructions in basic block
363  void add(const AliasSetTracker &AST); // Add alias relations from another AST
364  void addUnknown(Instruction *I);
365 
366  void clear();
367 
368  /// Return the alias sets that are active.
369  const ilist<AliasSet> &getAliasSets() const { return AliasSets; }
370 
371  /// Return the alias set that the specified pointer lives in. If the New
372  /// argument is non-null, this method sets the value to true if a new alias
373  /// set is created to contain the pointer (because the pointer didn't alias
374  /// anything).
376  const AAMDNodes &AAInfo);
377 
378  /// Return the alias set containing the location specified if one exists,
379  /// otherwise return null.
381  const AAMDNodes &AAInfo) {
382  return mergeAliasSetsForPointer(P, Size, AAInfo);
383  }
384 
385  /// Return true if the specified instruction "may" (or must) alias one of the
386  /// members in any of the sets.
387  bool containsUnknown(const Instruction *I) const;
388 
389  /// Return the underlying alias analysis object used by this tracker.
390  AliasAnalysis &getAliasAnalysis() const { return AA; }
391 
392  /// This method is used to remove a pointer value from the AliasSetTracker
393  /// entirely. It should be used when an instruction is deleted from the
394  /// program to update the AST. If you don't use this, you would have dangling
395  /// pointers to deleted instructions.
396  void deleteValue(Value *PtrVal);
397 
398  /// This method should be used whenever a preexisting value in the program is
399  /// copied or cloned, introducing a new value. Note that it is ok for clients
400  /// that use this method to introduce the same value multiple times: if the
401  /// tracker already knows about a value, it will ignore the request.
402  void copyValue(Value *From, Value *To);
403 
406 
407  const_iterator begin() const { return AliasSets.begin(); }
408  const_iterator end() const { return AliasSets.end(); }
409 
410  iterator begin() { return AliasSets.begin(); }
411  iterator end() { return AliasSets.end(); }
412 
413  void print(raw_ostream &OS) const;
414  void dump() const;
415 
416 private:
417  friend class AliasSet;
418 
419  // The total number of pointers contained in all "may" alias sets.
420  unsigned TotalMayAliasSetSize;
421 
422  // A non-null value signifies this AST is saturated. A saturated AST lumps
423  // all pointers into a single "May" set.
424  AliasSet *AliasAnyAS;
425 
426  void removeAliasSet(AliasSet *AS);
427 
428  /// Just like operator[] on the map, except that it creates an entry for the
429  /// pointer if it doesn't already exist.
430  AliasSet::PointerRec &getEntryFor(Value *V) {
431  AliasSet::PointerRec *&Entry = PointerMap[ASTCallbackVH(V, this)];
432  if (!Entry)
433  Entry = new AliasSet::PointerRec(V);
434  return *Entry;
435  }
436 
437  AliasSet &addPointer(Value *P, uint64_t Size, const AAMDNodes &AAInfo,
438  AliasSet::AccessLattice E);
439  AliasSet *mergeAliasSetsForPointer(const Value *Ptr, uint64_t Size,
440  const AAMDNodes &AAInfo);
441 
442  /// Merge all alias sets into a single set that is considered to alias any
443  /// pointer.
444  AliasSet &mergeAllAliasSets();
445 
446  AliasSet *findAliasSetForUnknownInst(Instruction *Inst);
447 };
448 
450  AST.print(OS);
451  return OS;
452 }
453 
454 } // End llvm namespace
455 
456 #endif
bool operator==(const iterator &x) const
void mergeSetIn(AliasSet &AS, AliasSetTracker &AST)
Merge the specified alias set into this alias set.
bool operator!=(const iterator &x) const
bool isForwardingAliasSet() const
Return true if this alias set should be ignored as part of the AliasSetTracker object.
AAResults AliasAnalysis
Temporary typedef for legacy code that uses a generic AliasAnalysis pointer or reference.
const ilist< AliasSet > & getAliasSets() const
Return the alias sets that are active.
Define an iterator for alias sets... this is just a forward iterator.
iterator begin() const
This file contains the declarations for metadata subclasses.
This class wraps the llvm.memset intrinsic.
ilist< AliasSet >::const_iterator const_iterator
An instruction for reading from memory.
Definition: Instructions.h:164
static AAMDNodes getEmptyKey()
Definition: Metadata.h:681
bool isMustAlias() const
const_iterator end() const
bool aliasesPointer(const Value *Ptr, uint64_t Size, const AAMDNodes &AAInfo, AliasAnalysis &AA) const
Return true if the specified pointer "may" (or must) alias one of the members in the set...
const_iterator begin() const
bool isRef() const
Accessors...
friend class AliasSetTracker
value_type * operator->() const
An instruction for storing to memory.
Definition: Instructions.h:306
bool isMod() const
bool aliasesUnknownInst(const Instruction *Inst, AliasAnalysis &AA) const
Function Alias Analysis false
#define P(N)
iterator end() const
LLVM Basic Block Representation.
Definition: BasicBlock.h:59
bool isVolatile() const
Return true if this alias set contains volatile loads or stores.
bool empty() const
AliasSetTracker(AliasAnalysis &aa)
Create an empty collection of AliasSets, and use the specified alias analysis object to disambiguate ...
This class represents the va_arg llvm instruction, which returns an argument of the specified type gi...
void print(raw_ostream &OS) const
bool isMayAlias() const
An intrusive list with ownership and callbacks specified/controlled by ilist_traits, only with API safe for polymorphic types.
Definition: ilist.h:403
AliasSet * getAliasSetForPointerIfExists(const Value *P, uint64_t Size, const AAMDNodes &AAInfo)
Return the alias set containing the location specified if one exists, otherwise return null...
Iterator for intrusive lists based on ilist_node.
#define E
Definition: LargeTest.cpp:27
AliasAnalysis & getAliasAnalysis() const
Return the underlying alias analysis object used by this tracker.
void copyValue(Value *From, Value *To)
This method should be used whenever a preexisting value in the program is copied or cloned...
A collection of metadata nodes that might be associated with a memory access used by the alias-analys...
Definition: Metadata.h:642
bool containsUnknown(const Instruction *I) const
Return true if the specified instruction "may" (or must) alias one of the members in any of the sets...
void add(Value *Ptr, uint64_t Size, const AAMDNodes &AAInfo)
These methods are used to add different types of instructions to the alias sets.
void print(raw_ostream &OS) const
AAMDNodes getAAInfo() const
constexpr char Size[]
Key for Kernel::Arg::Metadata::mSize.
ilist< AliasSet >::iterator iterator
Value * getPointer() const
This class wraps the llvm.memcpy/memmove intrinsics.
AliasSet & getAliasSetForPointer(Value *P, uint64_t Size, const AAMDNodes &AAInfo)
Return the alias set that the specified pointer lives in.
static AAMDNodes getTombstoneKey()
Definition: Metadata.h:686
#define I(x, y, z)
Definition: MD5.cpp:58
uint64_t getSize() const
value_type & operator*() const
void dump() const
raw_ostream & operator<<(raw_ostream &OS, const APInt &I)
Definition: APInt.h:2018
iterator(PointerRec *CN=nullptr)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
LLVM Value Representation.
Definition: Value.h:73
This class implements an extremely fast bulk output stream that can only output to a stream...
Definition: raw_ostream.h:44
Value handle with callbacks on RAUW and destruction.
Definition: ValueHandle.h:389
void addUnknown(Instruction *I)
int * Ptr
void deleteValue(Value *PtrVal)
This method is used to remove a pointer value from the AliasSetTracker entirely.