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