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