xref: /llvm-project/llvm/lib/Analysis/AliasSetTracker.cpp (revision 90bffb3eb98fea5730e33a8aa9a56369ffbed4c9)
1 //===- AliasSetTracker.cpp - Alias Sets Tracker implementation-------------===//
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 implements the AliasSetTracker and AliasSet classes.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/Analysis/AliasSetTracker.h"
15 #include "llvm/Analysis/AliasAnalysis.h"
16 #include "llvm/Analysis/MemoryLocation.h"
17 #include "llvm/Config/llvm-config.h"
18 #include "llvm/IR/CallSite.h"
19 #include "llvm/IR/Constants.h"
20 #include "llvm/IR/DataLayout.h"
21 #include "llvm/IR/Function.h"
22 #include "llvm/IR/InstIterator.h"
23 #include "llvm/IR/Instruction.h"
24 #include "llvm/IR/Instructions.h"
25 #include "llvm/IR/IntrinsicInst.h"
26 #include "llvm/IR/Module.h"
27 #include "llvm/IR/Value.h"
28 #include "llvm/Pass.h"
29 #include "llvm/Support/AtomicOrdering.h"
30 #include "llvm/Support/Casting.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Compiler.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include <cassert>
37 #include <cstdint>
38 #include <vector>
39 
40 using namespace llvm;
41 
42 static cl::opt<unsigned>
43     SaturationThreshold("alias-set-saturation-threshold", cl::Hidden,
44                         cl::init(250),
45                         cl::desc("The maximum number of pointers may-alias "
46                                  "sets may contain before degradation"));
47 
48 /// mergeSetIn - Merge the specified alias set into this alias set.
49 ///
50 void AliasSet::mergeSetIn(AliasSet &AS, AliasSetTracker &AST) {
51   assert(!AS.Forward && "Alias set is already forwarding!");
52   assert(!Forward && "This set is a forwarding set!!");
53 
54   bool WasMustAlias = (Alias == SetMustAlias);
55   // Update the alias and access types of this set...
56   Access |= AS.Access;
57   Alias  |= AS.Alias;
58   Volatile |= AS.Volatile;
59 
60   if (Alias == SetMustAlias) {
61     // Check that these two merged sets really are must aliases.  Since both
62     // used to be must-alias sets, we can just check any pointer from each set
63     // for aliasing.
64     AliasAnalysis &AA = AST.getAliasAnalysis();
65     PointerRec *L = getSomePointer();
66     PointerRec *R = AS.getSomePointer();
67 
68     // If the pointers are not a must-alias pair, this set becomes a may alias.
69     if (AA.alias(MemoryLocation(L->getValue(), L->getSize(), L->getAAInfo()),
70                  MemoryLocation(R->getValue(), R->getSize(), R->getAAInfo())) !=
71         MustAlias)
72       Alias = SetMayAlias;
73   }
74 
75   if (Alias == SetMayAlias) {
76     if (WasMustAlias)
77       AST.TotalMayAliasSetSize += size();
78     if (AS.Alias == SetMustAlias)
79       AST.TotalMayAliasSetSize += AS.size();
80   }
81 
82   bool ASHadUnknownInsts = !AS.UnknownInsts.empty();
83   if (UnknownInsts.empty()) {            // Merge call sites...
84     if (ASHadUnknownInsts) {
85       std::swap(UnknownInsts, AS.UnknownInsts);
86       addRef();
87     }
88   } else if (ASHadUnknownInsts) {
89     UnknownInsts.insert(UnknownInsts.end(), AS.UnknownInsts.begin(), AS.UnknownInsts.end());
90     AS.UnknownInsts.clear();
91   }
92 
93   AS.Forward = this; // Forward across AS now...
94   addRef();          // AS is now pointing to us...
95 
96   // Merge the list of constituent pointers...
97   if (AS.PtrList) {
98     SetSize += AS.size();
99     AS.SetSize = 0;
100     *PtrListEnd = AS.PtrList;
101     AS.PtrList->setPrevInList(PtrListEnd);
102     PtrListEnd = AS.PtrListEnd;
103 
104     AS.PtrList = nullptr;
105     AS.PtrListEnd = &AS.PtrList;
106     assert(*AS.PtrListEnd == nullptr && "End of list is not null?");
107   }
108   if (ASHadUnknownInsts)
109     AS.dropRef(AST);
110 }
111 
112 void AliasSetTracker::removeAliasSet(AliasSet *AS) {
113   if (AliasSet *Fwd = AS->Forward) {
114     Fwd->dropRef(*this);
115     AS->Forward = nullptr;
116   }
117 
118   if (AS->Alias == AliasSet::SetMayAlias)
119     TotalMayAliasSetSize -= AS->size();
120 
121   AliasSets.erase(AS);
122 }
123 
124 void AliasSet::removeFromTracker(AliasSetTracker &AST) {
125   assert(RefCount == 0 && "Cannot remove non-dead alias set from tracker!");
126   AST.removeAliasSet(this);
127 }
128 
129 void AliasSet::addPointer(AliasSetTracker &AST, PointerRec &Entry,
130                           LocationSize Size, const AAMDNodes &AAInfo,
131                           bool KnownMustAlias) {
132   assert(!Entry.hasAliasSet() && "Entry already in set!");
133 
134   // Check to see if we have to downgrade to _may_ alias.
135   if (isMustAlias() && !KnownMustAlias)
136     if (PointerRec *P = getSomePointer()) {
137       AliasAnalysis &AA = AST.getAliasAnalysis();
138       AliasResult Result =
139           AA.alias(MemoryLocation(P->getValue(), P->getSize(), P->getAAInfo()),
140                    MemoryLocation(Entry.getValue(), Size, AAInfo));
141       if (Result != MustAlias) {
142         Alias = SetMayAlias;
143         AST.TotalMayAliasSetSize += size();
144       } else {
145         // First entry of must alias must have maximum size!
146         P->updateSizeAndAAInfo(Size, AAInfo);
147       }
148       assert(Result != NoAlias && "Cannot be part of must set!");
149     }
150 
151   Entry.setAliasSet(this);
152   Entry.updateSizeAndAAInfo(Size, AAInfo);
153 
154   // Add it to the end of the list...
155   ++SetSize;
156   assert(*PtrListEnd == nullptr && "End of list is not null?");
157   *PtrListEnd = &Entry;
158   PtrListEnd = Entry.setPrevInList(PtrListEnd);
159   assert(*PtrListEnd == nullptr && "End of list is not null?");
160   // Entry points to alias set.
161   addRef();
162 
163   if (Alias == SetMayAlias)
164     AST.TotalMayAliasSetSize++;
165 }
166 
167 void AliasSet::addUnknownInst(Instruction *I, AliasAnalysis &AA) {
168   if (UnknownInsts.empty())
169     addRef();
170   UnknownInsts.emplace_back(I);
171 
172   if (!I->mayWriteToMemory()) {
173     Alias = SetMayAlias;
174     Access |= RefAccess;
175     return;
176   }
177 
178   // FIXME: This should use mod/ref information to make this not suck so bad
179   Alias = SetMayAlias;
180   Access = ModRefAccess;
181 }
182 
183 /// aliasesPointer - Return true if the specified pointer "may" (or must)
184 /// alias one of the members in the set.
185 ///
186 bool AliasSet::aliasesPointer(const Value *Ptr, LocationSize Size,
187                               const AAMDNodes &AAInfo,
188                               AliasAnalysis &AA) const {
189   if (AliasAny)
190     return true;
191 
192   if (Alias == SetMustAlias) {
193     assert(UnknownInsts.empty() && "Illegal must alias set!");
194 
195     // If this is a set of MustAliases, only check to see if the pointer aliases
196     // SOME value in the set.
197     PointerRec *SomePtr = getSomePointer();
198     assert(SomePtr && "Empty must-alias set??");
199     return AA.alias(MemoryLocation(SomePtr->getValue(), SomePtr->getSize(),
200                                    SomePtr->getAAInfo()),
201                     MemoryLocation(Ptr, Size, AAInfo));
202   }
203 
204   // If this is a may-alias set, we have to check all of the pointers in the set
205   // to be sure it doesn't alias the set...
206   for (iterator I = begin(), E = end(); I != E; ++I)
207     if (AA.alias(MemoryLocation(Ptr, Size, AAInfo),
208                  MemoryLocation(I.getPointer(), I.getSize(), I.getAAInfo())))
209       return true;
210 
211   // Check the unknown instructions...
212   if (!UnknownInsts.empty()) {
213     for (unsigned i = 0, e = UnknownInsts.size(); i != e; ++i)
214       if (auto *Inst = getUnknownInst(i))
215         if (isModOrRefSet(
216                 AA.getModRefInfo(Inst, MemoryLocation(Ptr, Size, AAInfo))))
217           return true;
218   }
219 
220   return false;
221 }
222 
223 bool AliasSet::aliasesUnknownInst(const Instruction *Inst,
224                                   AliasAnalysis &AA) const {
225 
226   if (AliasAny)
227     return true;
228 
229   if (!Inst->mayReadOrWriteMemory())
230     return false;
231 
232   for (unsigned i = 0, e = UnknownInsts.size(); i != e; ++i) {
233     if (auto *UnknownInst = getUnknownInst(i)) {
234       ImmutableCallSite C1(UnknownInst), C2(Inst);
235       if (!C1 || !C2 || isModOrRefSet(AA.getModRefInfo(C1, C2)) ||
236           isModOrRefSet(AA.getModRefInfo(C2, C1)))
237         return true;
238     }
239   }
240 
241   for (iterator I = begin(), E = end(); I != E; ++I)
242     if (isModOrRefSet(AA.getModRefInfo(
243             Inst, MemoryLocation(I.getPointer(), I.getSize(), I.getAAInfo()))))
244       return true;
245 
246   return false;
247 }
248 
249 void AliasSetTracker::clear() {
250   // Delete all the PointerRec entries.
251   for (PointerMapType::iterator I = PointerMap.begin(), E = PointerMap.end();
252        I != E; ++I)
253     I->second->eraseFromList();
254 
255   PointerMap.clear();
256 
257   // The alias sets should all be clear now.
258   AliasSets.clear();
259 }
260 
261 
262 /// mergeAliasSetsForPointer - Given a pointer, merge all alias sets that may
263 /// alias the pointer. Return the unified set, or nullptr if no set that aliases
264 /// the pointer was found.
265 AliasSet *AliasSetTracker::mergeAliasSetsForPointer(const Value *Ptr,
266                                                     LocationSize Size,
267                                                     const AAMDNodes &AAInfo) {
268   AliasSet *FoundSet = nullptr;
269   for (iterator I = begin(), E = end(); I != E;) {
270     iterator Cur = I++;
271     if (Cur->Forward || !Cur->aliasesPointer(Ptr, Size, AAInfo, AA)) continue;
272 
273     if (!FoundSet) {      // If this is the first alias set ptr can go into.
274       FoundSet = &*Cur;   // Remember it.
275     } else {              // Otherwise, we must merge the sets.
276       FoundSet->mergeSetIn(*Cur, *this);     // Merge in contents.
277     }
278   }
279 
280   return FoundSet;
281 }
282 
283 bool AliasSetTracker::containsUnknown(const Instruction *Inst) const {
284   for (const AliasSet &AS : *this)
285     if (!AS.Forward && AS.aliasesUnknownInst(Inst, AA))
286       return true;
287   return false;
288 }
289 
290 AliasSet *AliasSetTracker::findAliasSetForUnknownInst(Instruction *Inst) {
291   AliasSet *FoundSet = nullptr;
292   for (iterator I = begin(), E = end(); I != E;) {
293     iterator Cur = I++;
294     if (Cur->Forward || !Cur->aliasesUnknownInst(Inst, AA))
295       continue;
296     if (!FoundSet)            // If this is the first alias set ptr can go into.
297       FoundSet = &*Cur;       // Remember it.
298     else if (!Cur->Forward)   // Otherwise, we must merge the sets.
299       FoundSet->mergeSetIn(*Cur, *this);     // Merge in contents.
300   }
301   return FoundSet;
302 }
303 
304 /// getAliasSetForPointer - Return the alias set that the specified pointer
305 /// lives in.
306 AliasSet &AliasSetTracker::getAliasSetForPointer(Value *Pointer,
307                                                  LocationSize Size,
308                                                  const AAMDNodes &AAInfo) {
309   AliasSet::PointerRec &Entry = getEntryFor(Pointer);
310 
311   if (AliasAnyAS) {
312     // At this point, the AST is saturated, so we only have one active alias
313     // set. That means we already know which alias set we want to return, and
314     // just need to add the pointer to that set to keep the data structure
315     // consistent.
316     // This, of course, means that we will never need a merge here.
317     if (Entry.hasAliasSet()) {
318       Entry.updateSizeAndAAInfo(Size, AAInfo);
319       assert(Entry.getAliasSet(*this) == AliasAnyAS &&
320              "Entry in saturated AST must belong to only alias set");
321     } else {
322       AliasAnyAS->addPointer(*this, Entry, Size, AAInfo);
323     }
324     return *AliasAnyAS;
325   }
326 
327   // Check to see if the pointer is already known.
328   if (Entry.hasAliasSet()) {
329     // If the size changed, we may need to merge several alias sets.
330     // Note that we can *not* return the result of mergeAliasSetsForPointer
331     // due to a quirk of alias analysis behavior. Since alias(undef, undef)
332     // is NoAlias, mergeAliasSetsForPointer(undef, ...) will not find the
333     // the right set for undef, even if it exists.
334     if (Entry.updateSizeAndAAInfo(Size, AAInfo))
335       mergeAliasSetsForPointer(Pointer, Size, AAInfo);
336     // Return the set!
337     return *Entry.getAliasSet(*this)->getForwardedTarget(*this);
338   }
339 
340   if (AliasSet *AS = mergeAliasSetsForPointer(Pointer, Size, AAInfo)) {
341     // Add it to the alias set it aliases.
342     AS->addPointer(*this, Entry, Size, AAInfo);
343     return *AS;
344   }
345 
346   // Otherwise create a new alias set to hold the loaded pointer.
347   AliasSets.push_back(new AliasSet());
348   AliasSets.back().addPointer(*this, Entry, Size, AAInfo);
349   return AliasSets.back();
350 }
351 
352 void AliasSetTracker::add(Value *Ptr, LocationSize Size,
353                           const AAMDNodes &AAInfo) {
354   addPointer(Ptr, Size, AAInfo, AliasSet::NoAccess);
355 }
356 
357 void AliasSetTracker::add(LoadInst *LI) {
358   if (isStrongerThanMonotonic(LI->getOrdering())) return addUnknown(LI);
359 
360   AliasSet &AS = addPointer(MemoryLocation::get(LI), AliasSet::RefAccess);
361   if (LI->isVolatile()) AS.setVolatile();
362 }
363 
364 void AliasSetTracker::add(StoreInst *SI) {
365   if (isStrongerThanMonotonic(SI->getOrdering())) return addUnknown(SI);
366 
367   AliasSet &AS = addPointer(MemoryLocation::get(SI), AliasSet::ModAccess);
368   if (SI->isVolatile()) AS.setVolatile();
369 }
370 
371 void AliasSetTracker::add(VAArgInst *VAAI) {
372   addPointer(MemoryLocation::get(VAAI), AliasSet::ModRefAccess);
373 }
374 
375 void AliasSetTracker::add(AnyMemSetInst *MSI) {
376   auto MemLoc = MemoryLocation::getForDest(MSI);
377   AliasSet &AS = addPointer(MemLoc, AliasSet::ModAccess);
378   auto *MS = dyn_cast<MemSetInst>(MSI);
379   if (MS && MS->isVolatile())
380     AS.setVolatile();
381 }
382 
383 void AliasSetTracker::add(AnyMemTransferInst *MTI) {
384   auto SrcLoc = MemoryLocation::getForSource(MTI);
385   AliasSet &ASSrc = addPointer(SrcLoc, AliasSet::RefAccess);
386 
387   auto DestLoc = MemoryLocation::getForDest(MTI);
388   AliasSet &ASDst = addPointer(DestLoc, AliasSet::ModAccess);
389 
390   auto* MT = dyn_cast<MemTransferInst>(MTI);
391   if (MT && MT->isVolatile()) {
392     ASSrc.setVolatile();
393     ASDst.setVolatile();
394   }
395 }
396 
397 void AliasSetTracker::addUnknown(Instruction *Inst) {
398   if (isa<DbgInfoIntrinsic>(Inst))
399     return; // Ignore DbgInfo Intrinsics.
400 
401   if (auto *II = dyn_cast<IntrinsicInst>(Inst)) {
402     // These intrinsics will show up as affecting memory, but they are just
403     // markers.
404     switch (II->getIntrinsicID()) {
405     default:
406       break;
407       // FIXME: Add lifetime/invariant intrinsics (See: PR30807).
408     case Intrinsic::assume:
409     case Intrinsic::sideeffect:
410       return;
411     }
412   }
413   if (!Inst->mayReadOrWriteMemory())
414     return; // doesn't alias anything
415 
416   AliasSet *AS = findAliasSetForUnknownInst(Inst);
417   if (AS) {
418     AS->addUnknownInst(Inst, AA);
419     return;
420   }
421   AliasSets.push_back(new AliasSet());
422   AS = &AliasSets.back();
423   AS->addUnknownInst(Inst, AA);
424 }
425 
426 void AliasSetTracker::add(Instruction *I) {
427   // Dispatch to one of the other add methods.
428   if (LoadInst *LI = dyn_cast<LoadInst>(I))
429     return add(LI);
430   if (StoreInst *SI = dyn_cast<StoreInst>(I))
431     return add(SI);
432   if (VAArgInst *VAAI = dyn_cast<VAArgInst>(I))
433     return add(VAAI);
434   if (AnyMemSetInst *MSI = dyn_cast<AnyMemSetInst>(I))
435     return add(MSI);
436   if (AnyMemTransferInst *MTI = dyn_cast<AnyMemTransferInst>(I))
437     return add(MTI);
438   return addUnknown(I);
439 }
440 
441 void AliasSetTracker::add(BasicBlock &BB) {
442   for (auto &I : BB)
443     add(&I);
444 }
445 
446 void AliasSetTracker::add(const AliasSetTracker &AST) {
447   assert(&AA == &AST.AA &&
448          "Merging AliasSetTracker objects with different Alias Analyses!");
449 
450   // Loop over all of the alias sets in AST, adding the pointers contained
451   // therein into the current alias sets.  This can cause alias sets to be
452   // merged together in the current AST.
453   for (const AliasSet &AS : AST) {
454     if (AS.Forward)
455       continue; // Ignore forwarding alias sets
456 
457     // If there are any call sites in the alias set, add them to this AST.
458     for (unsigned i = 0, e = AS.UnknownInsts.size(); i != e; ++i)
459       if (auto *Inst = AS.getUnknownInst(i))
460         add(Inst);
461 
462     // Loop over all of the pointers in this alias set.
463     for (AliasSet::iterator ASI = AS.begin(), E = AS.end(); ASI != E; ++ASI) {
464       AliasSet &NewAS =
465           addPointer(ASI.getPointer(), ASI.getSize(), ASI.getAAInfo(),
466                      (AliasSet::AccessLattice)AS.Access);
467       if (AS.isVolatile()) NewAS.setVolatile();
468     }
469   }
470 }
471 
472 // deleteValue method - This method is used to remove a pointer value from the
473 // AliasSetTracker entirely.  It should be used when an instruction is deleted
474 // from the program to update the AST.  If you don't use this, you would have
475 // dangling pointers to deleted instructions.
476 //
477 void AliasSetTracker::deleteValue(Value *PtrVal) {
478   // First, look up the PointerRec for this pointer.
479   PointerMapType::iterator I = PointerMap.find_as(PtrVal);
480   if (I == PointerMap.end()) return;  // Noop
481 
482   // If we found one, remove the pointer from the alias set it is in.
483   AliasSet::PointerRec *PtrValEnt = I->second;
484   AliasSet *AS = PtrValEnt->getAliasSet(*this);
485 
486   // Unlink and delete from the list of values.
487   PtrValEnt->eraseFromList();
488 
489   if (AS->Alias == AliasSet::SetMayAlias) {
490     AS->SetSize--;
491     TotalMayAliasSetSize--;
492   }
493 
494   // Stop using the alias set.
495   AS->dropRef(*this);
496 
497   PointerMap.erase(I);
498 }
499 
500 // copyValue - This method should be used whenever a preexisting value in the
501 // program is copied or cloned, introducing a new value.  Note that it is ok for
502 // clients that use this method to introduce the same value multiple times: if
503 // the tracker already knows about a value, it will ignore the request.
504 //
505 void AliasSetTracker::copyValue(Value *From, Value *To) {
506   // First, look up the PointerRec for this pointer.
507   PointerMapType::iterator I = PointerMap.find_as(From);
508   if (I == PointerMap.end())
509     return;  // Noop
510   assert(I->second->hasAliasSet() && "Dead entry?");
511 
512   AliasSet::PointerRec &Entry = getEntryFor(To);
513   if (Entry.hasAliasSet()) return;    // Already in the tracker!
514 
515   // getEntryFor above may invalidate iterator \c I, so reinitialize it.
516   I = PointerMap.find_as(From);
517   // Add it to the alias set it aliases...
518   AliasSet *AS = I->second->getAliasSet(*this);
519   AS->addPointer(*this, Entry, I->second->getSize(),
520                  I->second->getAAInfo(),
521                  true);
522 }
523 
524 AliasSet &AliasSetTracker::mergeAllAliasSets() {
525   assert(!AliasAnyAS && (TotalMayAliasSetSize > SaturationThreshold) &&
526          "Full merge should happen once, when the saturation threshold is "
527          "reached");
528 
529   // Collect all alias sets, so that we can drop references with impunity
530   // without worrying about iterator invalidation.
531   std::vector<AliasSet *> ASVector;
532   ASVector.reserve(SaturationThreshold);
533   for (iterator I = begin(), E = end(); I != E; I++)
534     ASVector.push_back(&*I);
535 
536   // Copy all instructions and pointers into a new set, and forward all other
537   // sets to it.
538   AliasSets.push_back(new AliasSet());
539   AliasAnyAS = &AliasSets.back();
540   AliasAnyAS->Alias = AliasSet::SetMayAlias;
541   AliasAnyAS->Access = AliasSet::ModRefAccess;
542   AliasAnyAS->AliasAny = true;
543 
544   for (auto Cur : ASVector) {
545     // If Cur was already forwarding, just forward to the new AS instead.
546     AliasSet *FwdTo = Cur->Forward;
547     if (FwdTo) {
548       Cur->Forward = AliasAnyAS;
549       AliasAnyAS->addRef();
550       FwdTo->dropRef(*this);
551       continue;
552     }
553 
554     // Otherwise, perform the actual merge.
555     AliasAnyAS->mergeSetIn(*Cur, *this);
556   }
557 
558   return *AliasAnyAS;
559 }
560 
561 AliasSet &AliasSetTracker::addPointer(Value *P, LocationSize Size,
562                                       const AAMDNodes &AAInfo,
563                                       AliasSet::AccessLattice E) {
564   AliasSet &AS = getAliasSetForPointer(P, Size, AAInfo);
565   AS.Access |= E;
566 
567   if (!AliasAnyAS && (TotalMayAliasSetSize > SaturationThreshold)) {
568     // The AST is now saturated. From here on, we conservatively consider all
569     // pointers to alias each-other.
570     return mergeAllAliasSets();
571   }
572 
573   return AS;
574 }
575 
576 //===----------------------------------------------------------------------===//
577 //               AliasSet/AliasSetTracker Printing Support
578 //===----------------------------------------------------------------------===//
579 
580 void AliasSet::print(raw_ostream &OS) const {
581   OS << "  AliasSet[" << (const void*)this << ", " << RefCount << "] ";
582   OS << (Alias == SetMustAlias ? "must" : "may") << " alias, ";
583   switch (Access) {
584   case NoAccess:     OS << "No access "; break;
585   case RefAccess:    OS << "Ref       "; break;
586   case ModAccess:    OS << "Mod       "; break;
587   case ModRefAccess: OS << "Mod/Ref   "; break;
588   default: llvm_unreachable("Bad value for Access!");
589   }
590   if (isVolatile()) OS << "[volatile] ";
591   if (Forward)
592     OS << " forwarding to " << (void*)Forward;
593 
594   if (!empty()) {
595     OS << "Pointers: ";
596     for (iterator I = begin(), E = end(); I != E; ++I) {
597       if (I != begin()) OS << ", ";
598       I.getPointer()->printAsOperand(OS << "(");
599       OS << ", " << I.getSize() << ")";
600     }
601   }
602   if (!UnknownInsts.empty()) {
603     OS << "\n    " << UnknownInsts.size() << " Unknown instructions: ";
604     for (unsigned i = 0, e = UnknownInsts.size(); i != e; ++i) {
605       if (i) OS << ", ";
606       if (auto *I = getUnknownInst(i)) {
607         if (I->hasName())
608           I->printAsOperand(OS);
609         else
610           I->print(OS);
611       }
612     }
613   }
614   OS << "\n";
615 }
616 
617 void AliasSetTracker::print(raw_ostream &OS) const {
618   OS << "Alias Set Tracker: " << AliasSets.size() << " alias sets for "
619      << PointerMap.size() << " pointer values.\n";
620   for (const AliasSet &AS : *this)
621     AS.print(OS);
622   OS << "\n";
623 }
624 
625 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
626 LLVM_DUMP_METHOD void AliasSet::dump() const { print(dbgs()); }
627 LLVM_DUMP_METHOD void AliasSetTracker::dump() const { print(dbgs()); }
628 #endif
629 
630 //===----------------------------------------------------------------------===//
631 //                     ASTCallbackVH Class Implementation
632 //===----------------------------------------------------------------------===//
633 
634 void AliasSetTracker::ASTCallbackVH::deleted() {
635   assert(AST && "ASTCallbackVH called with a null AliasSetTracker!");
636   AST->deleteValue(getValPtr());
637   // this now dangles!
638 }
639 
640 void AliasSetTracker::ASTCallbackVH::allUsesReplacedWith(Value *V) {
641   AST->copyValue(getValPtr(), V);
642 }
643 
644 AliasSetTracker::ASTCallbackVH::ASTCallbackVH(Value *V, AliasSetTracker *ast)
645   : CallbackVH(V), AST(ast) {}
646 
647 AliasSetTracker::ASTCallbackVH &
648 AliasSetTracker::ASTCallbackVH::operator=(Value *V) {
649   return *this = ASTCallbackVH(V, AST);
650 }
651 
652 //===----------------------------------------------------------------------===//
653 //                            AliasSetPrinter Pass
654 //===----------------------------------------------------------------------===//
655 
656 namespace {
657 
658   class AliasSetPrinter : public FunctionPass {
659     AliasSetTracker *Tracker;
660 
661   public:
662     static char ID; // Pass identification, replacement for typeid
663 
664     AliasSetPrinter() : FunctionPass(ID) {
665       initializeAliasSetPrinterPass(*PassRegistry::getPassRegistry());
666     }
667 
668     void getAnalysisUsage(AnalysisUsage &AU) const override {
669       AU.setPreservesAll();
670       AU.addRequired<AAResultsWrapperPass>();
671     }
672 
673     bool runOnFunction(Function &F) override {
674       auto &AAWP = getAnalysis<AAResultsWrapperPass>();
675       Tracker = new AliasSetTracker(AAWP.getAAResults());
676       errs() << "Alias sets for function '" << F.getName() << "':\n";
677       for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
678         Tracker->add(&*I);
679       Tracker->print(errs());
680       delete Tracker;
681       return false;
682     }
683   };
684 
685 } // end anonymous namespace
686 
687 char AliasSetPrinter::ID = 0;
688 
689 INITIALIZE_PASS_BEGIN(AliasSetPrinter, "print-alias-sets",
690                 "Alias Set Printer", false, true)
691 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
692 INITIALIZE_PASS_END(AliasSetPrinter, "print-alias-sets",
693                 "Alias Set Printer", false, true)
694