1 //===- AliasSetTracker.cpp - Alias Sets Tracker implementation-------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the AliasSetTracker and AliasSet classes.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Analysis/AliasSetTracker.h"
15 #include "llvm/Analysis/AliasAnalysis.h"
16 #include "llvm/IR/DataLayout.h"
17 #include "llvm/IR/InstIterator.h"
18 #include "llvm/IR/Instructions.h"
19 #include "llvm/IR/IntrinsicInst.h"
20 #include "llvm/IR/LLVMContext.h"
21 #include "llvm/IR/Type.h"
22 #include "llvm/Pass.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Support/ErrorHandling.h"
25 #include "llvm/Support/raw_ostream.h"
28 /// mergeSetIn - Merge the specified alias set into this alias set.
30 void AliasSet::mergeSetIn(AliasSet &AS, AliasSetTracker &AST) {
31 assert(!AS.Forward && "Alias set is already forwarding!");
32 assert(!Forward && "This set is a forwarding set!!");
34 // Update the alias and access types of this set...
35 AccessTy |= AS.AccessTy;
36 AliasTy |= AS.AliasTy;
37 Volatile |= AS.Volatile;
39 if (AliasTy == MustAlias) {
40 // Check that these two merged sets really are must aliases. Since both
41 // used to be must-alias sets, we can just check any pointer from each set
43 AliasAnalysis &AA = AST.getAliasAnalysis();
44 PointerRec *L = getSomePointer();
45 PointerRec *R = AS.getSomePointer();
47 // If the pointers are not a must-alias pair, this set becomes a may alias.
48 if (AA.alias(AliasAnalysis::Location(L->getValue(),
51 AliasAnalysis::Location(R->getValue(),
54 != AliasAnalysis::MustAlias)
58 if (UnknownInsts.empty()) { // Merge call sites...
59 if (!AS.UnknownInsts.empty())
60 std::swap(UnknownInsts, AS.UnknownInsts);
61 } else if (!AS.UnknownInsts.empty()) {
62 UnknownInsts.insert(UnknownInsts.end(), AS.UnknownInsts.begin(), AS.UnknownInsts.end());
63 AS.UnknownInsts.clear();
66 AS.Forward = this; // Forward across AS now...
67 addRef(); // AS is now pointing to us...
69 // Merge the list of constituent pointers...
71 *PtrListEnd = AS.PtrList;
72 AS.PtrList->setPrevInList(PtrListEnd);
73 PtrListEnd = AS.PtrListEnd;
76 AS.PtrListEnd = &AS.PtrList;
77 assert(*AS.PtrListEnd == nullptr && "End of list is not null?");
81 void AliasSetTracker::removeAliasSet(AliasSet *AS) {
82 if (AliasSet *Fwd = AS->Forward) {
84 AS->Forward = nullptr;
89 void AliasSet::removeFromTracker(AliasSetTracker &AST) {
90 assert(RefCount == 0 && "Cannot remove non-dead alias set from tracker!");
91 AST.removeAliasSet(this);
94 void AliasSet::addPointer(AliasSetTracker &AST, PointerRec &Entry,
95 uint64_t Size, const AAMDNodes &AAInfo,
96 bool KnownMustAlias) {
97 assert(!Entry.hasAliasSet() && "Entry already in set!");
99 // Check to see if we have to downgrade to _may_ alias.
100 if (isMustAlias() && !KnownMustAlias)
101 if (PointerRec *P = getSomePointer()) {
102 AliasAnalysis &AA = AST.getAliasAnalysis();
103 AliasAnalysis::AliasResult Result =
104 AA.alias(AliasAnalysis::Location(P->getValue(), P->getSize(),
106 AliasAnalysis::Location(Entry.getValue(), Size, AAInfo));
107 if (Result != AliasAnalysis::MustAlias)
109 else // First entry of must alias must have maximum size!
110 P->updateSizeAndAAInfo(Size, AAInfo);
111 assert(Result != AliasAnalysis::NoAlias && "Cannot be part of must set!");
114 Entry.setAliasSet(this);
115 Entry.updateSizeAndAAInfo(Size, AAInfo);
117 // Add it to the end of the list...
118 assert(*PtrListEnd == nullptr && "End of list is not null?");
119 *PtrListEnd = &Entry;
120 PtrListEnd = Entry.setPrevInList(PtrListEnd);
121 assert(*PtrListEnd == nullptr && "End of list is not null?");
122 addRef(); // Entry points to alias set.
125 void AliasSet::addUnknownInst(Instruction *I, AliasAnalysis &AA) {
126 UnknownInsts.push_back(I);
128 if (!I->mayWriteToMemory()) {
134 // FIXME: This should use mod/ref information to make this not suck so bad
139 /// aliasesPointer - Return true if the specified pointer "may" (or must)
140 /// alias one of the members in the set.
142 bool AliasSet::aliasesPointer(const Value *Ptr, uint64_t Size,
143 const AAMDNodes &AAInfo,
144 AliasAnalysis &AA) const {
145 if (AliasTy == MustAlias) {
146 assert(UnknownInsts.empty() && "Illegal must alias set!");
148 // If this is a set of MustAliases, only check to see if the pointer aliases
149 // SOME value in the set.
150 PointerRec *SomePtr = getSomePointer();
151 assert(SomePtr && "Empty must-alias set??");
152 return AA.alias(AliasAnalysis::Location(SomePtr->getValue(),
154 SomePtr->getAAInfo()),
155 AliasAnalysis::Location(Ptr, Size, AAInfo));
158 // If this is a may-alias set, we have to check all of the pointers in the set
159 // to be sure it doesn't alias the set...
160 for (iterator I = begin(), E = end(); I != E; ++I)
161 if (AA.alias(AliasAnalysis::Location(Ptr, Size, AAInfo),
162 AliasAnalysis::Location(I.getPointer(), I.getSize(),
166 // Check the unknown instructions...
167 if (!UnknownInsts.empty()) {
168 for (unsigned i = 0, e = UnknownInsts.size(); i != e; ++i)
169 if (AA.getModRefInfo(UnknownInsts[i],
170 AliasAnalysis::Location(Ptr, Size, AAInfo)) !=
171 AliasAnalysis::NoModRef)
178 bool AliasSet::aliasesUnknownInst(Instruction *Inst, AliasAnalysis &AA) const {
179 if (!Inst->mayReadOrWriteMemory())
182 for (unsigned i = 0, e = UnknownInsts.size(); i != e; ++i) {
183 CallSite C1 = getUnknownInst(i), C2 = Inst;
185 AA.getModRefInfo(C1, C2) != AliasAnalysis::NoModRef ||
186 AA.getModRefInfo(C2, C1) != AliasAnalysis::NoModRef)
190 for (iterator I = begin(), E = end(); I != E; ++I)
191 if (AA.getModRefInfo(Inst, AliasAnalysis::Location(I.getPointer(),
194 AliasAnalysis::NoModRef)
200 void AliasSetTracker::clear() {
201 // Delete all the PointerRec entries.
202 for (PointerMapType::iterator I = PointerMap.begin(), E = PointerMap.end();
204 I->second->eraseFromList();
208 // The alias sets should all be clear now.
213 /// findAliasSetForPointer - Given a pointer, find the one alias set to put the
214 /// instruction referring to the pointer into. If there are multiple alias sets
215 /// that may alias the pointer, merge them together and return the unified set.
217 AliasSet *AliasSetTracker::findAliasSetForPointer(const Value *Ptr,
219 const AAMDNodes &AAInfo) {
220 AliasSet *FoundSet = nullptr;
221 for (iterator I = begin(), E = end(); I != E; ++I) {
222 if (I->Forward || !I->aliasesPointer(Ptr, Size, AAInfo, AA)) continue;
224 if (!FoundSet) { // If this is the first alias set ptr can go into.
225 FoundSet = I; // Remember it.
226 } else { // Otherwise, we must merge the sets.
227 FoundSet->mergeSetIn(*I, *this); // Merge in contents.
234 /// containsPointer - Return true if the specified location is represented by
235 /// this alias set, false otherwise. This does not modify the AST object or
237 bool AliasSetTracker::containsPointer(Value *Ptr, uint64_t Size,
238 const AAMDNodes &AAInfo) const {
239 for (const_iterator I = begin(), E = end(); I != E; ++I)
240 if (!I->Forward && I->aliasesPointer(Ptr, Size, AAInfo, AA))
247 AliasSet *AliasSetTracker::findAliasSetForUnknownInst(Instruction *Inst) {
248 AliasSet *FoundSet = nullptr;
249 for (iterator I = begin(), E = end(); I != E; ++I) {
250 if (I->Forward || !I->aliasesUnknownInst(Inst, AA))
253 if (!FoundSet) // If this is the first alias set ptr can go into.
254 FoundSet = I; // Remember it.
255 else if (!I->Forward) // Otherwise, we must merge the sets.
256 FoundSet->mergeSetIn(*I, *this); // Merge in contents.
264 /// getAliasSetForPointer - Return the alias set that the specified pointer
266 AliasSet &AliasSetTracker::getAliasSetForPointer(Value *Pointer, uint64_t Size,
267 const AAMDNodes &AAInfo,
269 AliasSet::PointerRec &Entry = getEntryFor(Pointer);
271 // Check to see if the pointer is already known.
272 if (Entry.hasAliasSet()) {
273 Entry.updateSizeAndAAInfo(Size, AAInfo);
275 return *Entry.getAliasSet(*this)->getForwardedTarget(*this);
278 if (AliasSet *AS = findAliasSetForPointer(Pointer, Size, AAInfo)) {
279 // Add it to the alias set it aliases.
280 AS->addPointer(*this, Entry, Size, AAInfo);
284 if (New) *New = true;
285 // Otherwise create a new alias set to hold the loaded pointer.
286 AliasSets.push_back(new AliasSet());
287 AliasSets.back().addPointer(*this, Entry, Size, AAInfo);
288 return AliasSets.back();
291 bool AliasSetTracker::add(Value *Ptr, uint64_t Size, const AAMDNodes &AAInfo) {
293 addPointer(Ptr, Size, AAInfo, AliasSet::NoModRef, NewPtr);
298 bool AliasSetTracker::add(LoadInst *LI) {
299 if (LI->getOrdering() > Monotonic) return addUnknown(LI);
302 LI->getAAMetadata(AAInfo);
304 AliasSet::AccessType ATy = AliasSet::Refs;
306 AliasSet &AS = addPointer(LI->getOperand(0),
307 AA.getTypeStoreSize(LI->getType()),
308 AAInfo, ATy, NewPtr);
309 if (LI->isVolatile()) AS.setVolatile();
313 bool AliasSetTracker::add(StoreInst *SI) {
314 if (SI->getOrdering() > Monotonic) return addUnknown(SI);
317 SI->getAAMetadata(AAInfo);
319 AliasSet::AccessType ATy = AliasSet::Mods;
321 Value *Val = SI->getOperand(0);
322 AliasSet &AS = addPointer(SI->getOperand(1),
323 AA.getTypeStoreSize(Val->getType()),
324 AAInfo, ATy, NewPtr);
325 if (SI->isVolatile()) AS.setVolatile();
329 bool AliasSetTracker::add(VAArgInst *VAAI) {
331 VAAI->getAAMetadata(AAInfo);
334 addPointer(VAAI->getOperand(0), AliasAnalysis::UnknownSize,
335 AAInfo, AliasSet::ModRef, NewPtr);
340 bool AliasSetTracker::addUnknown(Instruction *Inst) {
341 if (isa<DbgInfoIntrinsic>(Inst))
342 return true; // Ignore DbgInfo Intrinsics.
343 if (!Inst->mayReadOrWriteMemory())
344 return true; // doesn't alias anything
346 AliasSet *AS = findAliasSetForUnknownInst(Inst);
348 AS->addUnknownInst(Inst, AA);
351 AliasSets.push_back(new AliasSet());
352 AS = &AliasSets.back();
353 AS->addUnknownInst(Inst, AA);
357 bool AliasSetTracker::add(Instruction *I) {
358 // Dispatch to one of the other add methods.
359 if (LoadInst *LI = dyn_cast<LoadInst>(I))
361 if (StoreInst *SI = dyn_cast<StoreInst>(I))
363 if (VAArgInst *VAAI = dyn_cast<VAArgInst>(I))
365 return addUnknown(I);
368 void AliasSetTracker::add(BasicBlock &BB) {
369 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
373 void AliasSetTracker::add(const AliasSetTracker &AST) {
374 assert(&AA == &AST.AA &&
375 "Merging AliasSetTracker objects with different Alias Analyses!");
377 // Loop over all of the alias sets in AST, adding the pointers contained
378 // therein into the current alias sets. This can cause alias sets to be
379 // merged together in the current AST.
380 for (const_iterator I = AST.begin(), E = AST.end(); I != E; ++I) {
381 if (I->Forward) continue; // Ignore forwarding alias sets
383 AliasSet &AS = const_cast<AliasSet&>(*I);
385 // If there are any call sites in the alias set, add them to this AST.
386 for (unsigned i = 0, e = AS.UnknownInsts.size(); i != e; ++i)
387 add(AS.UnknownInsts[i]);
389 // Loop over all of the pointers in this alias set.
391 for (AliasSet::iterator ASI = AS.begin(), E = AS.end(); ASI != E; ++ASI) {
392 AliasSet &NewAS = addPointer(ASI.getPointer(), ASI.getSize(),
394 (AliasSet::AccessType)AS.AccessTy, X);
395 if (AS.isVolatile()) NewAS.setVolatile();
400 /// remove - Remove the specified (potentially non-empty) alias set from the
402 void AliasSetTracker::remove(AliasSet &AS) {
403 // Drop all call sites.
404 AS.UnknownInsts.clear();
406 // Clear the alias set.
407 unsigned NumRefs = 0;
408 while (!AS.empty()) {
409 AliasSet::PointerRec *P = AS.PtrList;
411 Value *ValToRemove = P->getValue();
413 // Unlink and delete entry from the list of values.
416 // Remember how many references need to be dropped.
419 // Finally, remove the entry.
420 PointerMap.erase(ValToRemove);
423 // Stop using the alias set, removing it.
424 AS.RefCount -= NumRefs;
425 if (AS.RefCount == 0)
426 AS.removeFromTracker(*this);
430 AliasSetTracker::remove(Value *Ptr, uint64_t Size, const AAMDNodes &AAInfo) {
431 AliasSet *AS = findAliasSetForPointer(Ptr, Size, AAInfo);
432 if (!AS) return false;
437 bool AliasSetTracker::remove(LoadInst *LI) {
438 uint64_t Size = AA.getTypeStoreSize(LI->getType());
441 LI->getAAMetadata(AAInfo);
443 AliasSet *AS = findAliasSetForPointer(LI->getOperand(0), Size, AAInfo);
444 if (!AS) return false;
449 bool AliasSetTracker::remove(StoreInst *SI) {
450 uint64_t Size = AA.getTypeStoreSize(SI->getOperand(0)->getType());
453 SI->getAAMetadata(AAInfo);
455 AliasSet *AS = findAliasSetForPointer(SI->getOperand(1), Size, AAInfo);
456 if (!AS) return false;
461 bool AliasSetTracker::remove(VAArgInst *VAAI) {
463 VAAI->getAAMetadata(AAInfo);
465 AliasSet *AS = findAliasSetForPointer(VAAI->getOperand(0),
466 AliasAnalysis::UnknownSize, AAInfo);
467 if (!AS) return false;
472 bool AliasSetTracker::removeUnknown(Instruction *I) {
473 if (!I->mayReadOrWriteMemory())
474 return false; // doesn't alias anything
476 AliasSet *AS = findAliasSetForUnknownInst(I);
477 if (!AS) return false;
482 bool AliasSetTracker::remove(Instruction *I) {
483 // Dispatch to one of the other remove methods...
484 if (LoadInst *LI = dyn_cast<LoadInst>(I))
486 if (StoreInst *SI = dyn_cast<StoreInst>(I))
488 if (VAArgInst *VAAI = dyn_cast<VAArgInst>(I))
490 return removeUnknown(I);
494 // deleteValue method - This method is used to remove a pointer value from the
495 // AliasSetTracker entirely. It should be used when an instruction is deleted
496 // from the program to update the AST. If you don't use this, you would have
497 // dangling pointers to deleted instructions.
499 void AliasSetTracker::deleteValue(Value *PtrVal) {
500 // Notify the alias analysis implementation that this value is gone.
501 AA.deleteValue(PtrVal);
503 // If this is a call instruction, remove the callsite from the appropriate
504 // AliasSet (if present).
505 if (Instruction *Inst = dyn_cast<Instruction>(PtrVal)) {
506 if (Inst->mayReadOrWriteMemory()) {
507 // Scan all the alias sets to see if this call site is contained.
508 for (iterator I = begin(), E = end(); I != E; ++I) {
509 if (I->Forward) continue;
511 I->removeUnknownInst(Inst);
516 // First, look up the PointerRec for this pointer.
517 PointerMapType::iterator I = PointerMap.find_as(PtrVal);
518 if (I == PointerMap.end()) return; // Noop
520 // If we found one, remove the pointer from the alias set it is in.
521 AliasSet::PointerRec *PtrValEnt = I->second;
522 AliasSet *AS = PtrValEnt->getAliasSet(*this);
524 // Unlink and delete from the list of values.
525 PtrValEnt->eraseFromList();
527 // Stop using the alias set.
533 // copyValue - This method should be used whenever a preexisting value in the
534 // program is copied or cloned, introducing a new value. Note that it is ok for
535 // clients that use this method to introduce the same value multiple times: if
536 // the tracker already knows about a value, it will ignore the request.
538 void AliasSetTracker::copyValue(Value *From, Value *To) {
539 // Notify the alias analysis implementation that this value is copied.
540 AA.copyValue(From, To);
542 // First, look up the PointerRec for this pointer.
543 PointerMapType::iterator I = PointerMap.find_as(From);
544 if (I == PointerMap.end())
546 assert(I->second->hasAliasSet() && "Dead entry?");
548 AliasSet::PointerRec &Entry = getEntryFor(To);
549 if (Entry.hasAliasSet()) return; // Already in the tracker!
551 // Add it to the alias set it aliases...
552 I = PointerMap.find_as(From);
553 AliasSet *AS = I->second->getAliasSet(*this);
554 AS->addPointer(*this, Entry, I->second->getSize(),
555 I->second->getAAInfo(),
561 //===----------------------------------------------------------------------===//
562 // AliasSet/AliasSetTracker Printing Support
563 //===----------------------------------------------------------------------===//
565 void AliasSet::print(raw_ostream &OS) const {
566 OS << " AliasSet[" << (const void*)this << ", " << RefCount << "] ";
567 OS << (AliasTy == MustAlias ? "must" : "may") << " alias, ";
569 case NoModRef: OS << "No access "; break;
570 case Refs : OS << "Ref "; break;
571 case Mods : OS << "Mod "; break;
572 case ModRef : OS << "Mod/Ref "; break;
573 default: llvm_unreachable("Bad value for AccessTy!");
575 if (isVolatile()) OS << "[volatile] ";
577 OS << " forwarding to " << (void*)Forward;
582 for (iterator I = begin(), E = end(); I != E; ++I) {
583 if (I != begin()) OS << ", ";
584 I.getPointer()->printAsOperand(OS << "(");
585 OS << ", " << I.getSize() << ")";
588 if (!UnknownInsts.empty()) {
589 OS << "\n " << UnknownInsts.size() << " Unknown instructions: ";
590 for (unsigned i = 0, e = UnknownInsts.size(); i != e; ++i) {
592 UnknownInsts[i]->printAsOperand(OS);
598 void AliasSetTracker::print(raw_ostream &OS) const {
599 OS << "Alias Set Tracker: " << AliasSets.size() << " alias sets for "
600 << PointerMap.size() << " pointer values.\n";
601 for (const_iterator I = begin(), E = end(); I != E; ++I)
606 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
607 void AliasSet::dump() const { print(dbgs()); }
608 void AliasSetTracker::dump() const { print(dbgs()); }
611 //===----------------------------------------------------------------------===//
612 // ASTCallbackVH Class Implementation
613 //===----------------------------------------------------------------------===//
615 void AliasSetTracker::ASTCallbackVH::deleted() {
616 assert(AST && "ASTCallbackVH called with a null AliasSetTracker!");
617 AST->deleteValue(getValPtr());
621 void AliasSetTracker::ASTCallbackVH::allUsesReplacedWith(Value *V) {
622 AST->copyValue(getValPtr(), V);
625 AliasSetTracker::ASTCallbackVH::ASTCallbackVH(Value *V, AliasSetTracker *ast)
626 : CallbackVH(V), AST(ast) {}
628 AliasSetTracker::ASTCallbackVH &
629 AliasSetTracker::ASTCallbackVH::operator=(Value *V) {
630 return *this = ASTCallbackVH(V, AST);
633 //===----------------------------------------------------------------------===//
634 // AliasSetPrinter Pass
635 //===----------------------------------------------------------------------===//
638 class AliasSetPrinter : public FunctionPass {
639 AliasSetTracker *Tracker;
641 static char ID; // Pass identification, replacement for typeid
642 AliasSetPrinter() : FunctionPass(ID) {
643 initializeAliasSetPrinterPass(*PassRegistry::getPassRegistry());
646 void getAnalysisUsage(AnalysisUsage &AU) const override {
647 AU.setPreservesAll();
648 AU.addRequired<AliasAnalysis>();
651 bool runOnFunction(Function &F) override {
652 Tracker = new AliasSetTracker(getAnalysis<AliasAnalysis>());
654 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
656 Tracker->print(errs());
663 char AliasSetPrinter::ID = 0;
664 INITIALIZE_PASS_BEGIN(AliasSetPrinter, "print-alias-sets",
665 "Alias Set Printer", false, true)
666 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
667 INITIALIZE_PASS_END(AliasSetPrinter, "print-alias-sets",
668 "Alias Set Printer", false, true)