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