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