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