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/Instructions.h"
17 #include "llvm/IntrinsicInst.h"
18 #include "llvm/LLVMContext.h"
19 #include "llvm/Pass.h"
20 #include "llvm/Type.h"
21 #include "llvm/Target/TargetData.h"
22 #include "llvm/Assembly/Writer.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Support/ErrorHandling.h"
25 #include "llvm/Support/InstIterator.h"
26 #include "llvm/Support/raw_ostream.h"
29 /// mergeSetIn - Merge the specified alias set into this alias set.
31 void AliasSet::mergeSetIn(AliasSet &AS, AliasSetTracker &AST) {
32 assert(!AS.Forward && "Alias set is already forwarding!");
33 assert(!Forward && "This set is a forwarding set!!");
35 // Update the alias and access types of this set...
36 AccessTy |= AS.AccessTy;
37 AliasTy |= AS.AliasTy;
38 Volatile |= AS.Volatile;
40 if (AliasTy == MustAlias) {
41 // Check that these two merged sets really are must aliases. Since both
42 // used to be must-alias sets, we can just check any pointer from each set
44 AliasAnalysis &AA = AST.getAliasAnalysis();
45 PointerRec *L = getSomePointer();
46 PointerRec *R = AS.getSomePointer();
48 // If the pointers are not a must-alias pair, this set becomes a may alias.
49 if (AA.alias(L->getValue(), L->getSize(), R->getValue(), R->getSize())
50 != AliasAnalysis::MustAlias)
54 if (CallSites.empty()) { // Merge call sites...
55 if (!AS.CallSites.empty())
56 std::swap(CallSites, AS.CallSites);
57 } else if (!AS.CallSites.empty()) {
58 CallSites.insert(CallSites.end(), AS.CallSites.begin(), AS.CallSites.end());
62 AS.Forward = this; // Forward across AS now...
63 addRef(); // AS is now pointing to us...
65 // Merge the list of constituent pointers...
67 *PtrListEnd = AS.PtrList;
68 AS.PtrList->setPrevInList(PtrListEnd);
69 PtrListEnd = AS.PtrListEnd;
72 AS.PtrListEnd = &AS.PtrList;
73 assert(*AS.PtrListEnd == 0 && "End of list is not null?");
77 void AliasSetTracker::removeAliasSet(AliasSet *AS) {
78 if (AliasSet *Fwd = AS->Forward) {
85 void AliasSet::removeFromTracker(AliasSetTracker &AST) {
86 assert(RefCount == 0 && "Cannot remove non-dead alias set from tracker!");
87 AST.removeAliasSet(this);
90 void AliasSet::addPointer(AliasSetTracker &AST, PointerRec &Entry,
91 unsigned Size, const MDNode *TBAAInfo,
92 bool KnownMustAlias) {
93 assert(!Entry.hasAliasSet() && "Entry already in set!");
95 // Check to see if we have to downgrade to _may_ alias.
96 if (isMustAlias() && !KnownMustAlias)
97 if (PointerRec *P = getSomePointer()) {
98 AliasAnalysis &AA = AST.getAliasAnalysis();
99 AliasAnalysis::AliasResult Result =
100 AA.alias(AliasAnalysis::Location(P->getValue(), P->getSize(),
102 AliasAnalysis::Location(Entry.getValue(), Size, TBAAInfo));
103 if (Result == AliasAnalysis::MayAlias)
105 else // First entry of must alias must have maximum size!
106 P->updateSizeAndTBAAInfo(Size, TBAAInfo);
107 assert(Result != AliasAnalysis::NoAlias && "Cannot be part of must set!");
110 Entry.setAliasSet(this);
111 Entry.updateSizeAndTBAAInfo(Size, TBAAInfo);
113 // Add it to the end of the list...
114 assert(*PtrListEnd == 0 && "End of list is not null?");
115 *PtrListEnd = &Entry;
116 PtrListEnd = Entry.setPrevInList(PtrListEnd);
117 assert(*PtrListEnd == 0 && "End of list is not null?");
118 addRef(); // Entry points to alias set.
121 void AliasSet::addCallSite(CallSite CS, AliasAnalysis &AA) {
122 CallSites.push_back(CS.getInstruction());
124 AliasAnalysis::ModRefBehavior Behavior = AA.getModRefBehavior(CS);
125 if (Behavior == AliasAnalysis::DoesNotAccessMemory)
127 else if (Behavior == AliasAnalysis::OnlyReadsMemory) {
133 // FIXME: This should use mod/ref information to make this not suck so bad
138 /// aliasesPointer - Return true if the specified pointer "may" (or must)
139 /// alias one of the members in the set.
141 bool AliasSet::aliasesPointer(const Value *Ptr, unsigned Size,
142 const MDNode *TBAAInfo,
143 AliasAnalysis &AA) const {
144 if (AliasTy == MustAlias) {
145 assert(CallSites.empty() && "Illegal must alias set!");
147 // If this is a set of MustAliases, only check to see if the pointer aliases
148 // SOME value in the set.
149 PointerRec *SomePtr = getSomePointer();
150 assert(SomePtr && "Empty must-alias set??");
151 return AA.alias(AliasAnalysis::Location(SomePtr->getValue(),
153 SomePtr->getTBAAInfo()),
154 AliasAnalysis::Location(Ptr, Size, TBAAInfo));
157 // If this is a may-alias set, we have to check all of the pointers in the set
158 // to be sure it doesn't alias the set...
159 for (iterator I = begin(), E = end(); I != E; ++I)
160 if (AA.alias(AliasAnalysis::Location(Ptr, Size, TBAAInfo),
161 AliasAnalysis::Location(I.getPointer(), I.getSize(),
165 // Check the call sites list and invoke list...
166 if (!CallSites.empty()) {
167 for (unsigned i = 0, e = CallSites.size(); i != e; ++i)
168 if (AA.getModRefInfo(CallSites[i],
169 AliasAnalysis::Location(Ptr, Size, TBAAInfo)) !=
170 AliasAnalysis::NoModRef)
177 bool AliasSet::aliasesCallSite(CallSite CS, AliasAnalysis &AA) const {
178 if (AA.doesNotAccessMemory(CS))
181 for (unsigned i = 0, e = CallSites.size(); i != e; ++i) {
182 if (AA.getModRefInfo(getCallSite(i), CS) != AliasAnalysis::NoModRef ||
183 AA.getModRefInfo(CS, getCallSite(i)) != AliasAnalysis::NoModRef)
187 for (iterator I = begin(), E = end(); I != E; ++I)
188 if (AA.getModRefInfo(CS, I.getPointer(), I.getSize()) !=
189 AliasAnalysis::NoModRef)
195 void AliasSetTracker::clear() {
196 // Delete all the PointerRec entries.
197 for (PointerMapType::iterator I = PointerMap.begin(), E = PointerMap.end();
199 I->second->eraseFromList();
203 // The alias sets should all be clear now.
208 /// findAliasSetForPointer - Given a pointer, find the one alias set to put the
209 /// instruction referring to the pointer into. If there are multiple alias sets
210 /// that may alias the pointer, merge them together and return the unified set.
212 AliasSet *AliasSetTracker::findAliasSetForPointer(const Value *Ptr,
214 const MDNode *TBAAInfo) {
215 AliasSet *FoundSet = 0;
216 for (iterator I = begin(), E = end(); I != E; ++I) {
217 if (I->Forward || !I->aliasesPointer(Ptr, Size, TBAAInfo, AA)) continue;
219 if (FoundSet == 0) { // If this is the first alias set ptr can go into.
220 FoundSet = I; // Remember it.
221 } else { // Otherwise, we must merge the sets.
222 FoundSet->mergeSetIn(*I, *this); // Merge in contents.
229 /// containsPointer - Return true if the specified location is represented by
230 /// this alias set, false otherwise. This does not modify the AST object or
232 bool AliasSetTracker::containsPointer(Value *Ptr, unsigned Size,
233 const MDNode *TBAAInfo) const {
234 for (const_iterator I = begin(), E = end(); I != E; ++I)
235 if (!I->Forward && I->aliasesPointer(Ptr, Size, TBAAInfo, AA))
242 AliasSet *AliasSetTracker::findAliasSetForCallSite(CallSite CS) {
243 AliasSet *FoundSet = 0;
244 for (iterator I = begin(), E = end(); I != E; ++I) {
245 if (I->Forward || !I->aliasesCallSite(CS, AA))
248 if (FoundSet == 0) // If this is the first alias set ptr can go into.
249 FoundSet = I; // Remember it.
250 else if (!I->Forward) // Otherwise, we must merge the sets.
251 FoundSet->mergeSetIn(*I, *this); // Merge in contents.
259 /// getAliasSetForPointer - Return the alias set that the specified pointer
261 AliasSet &AliasSetTracker::getAliasSetForPointer(Value *Pointer, unsigned Size,
262 const MDNode *TBAAInfo,
264 AliasSet::PointerRec &Entry = getEntryFor(Pointer);
266 // Check to see if the pointer is already known.
267 if (Entry.hasAliasSet()) {
268 Entry.updateSizeAndTBAAInfo(Size, TBAAInfo);
270 return *Entry.getAliasSet(*this)->getForwardedTarget(*this);
273 if (AliasSet *AS = findAliasSetForPointer(Pointer, Size, TBAAInfo)) {
274 // Add it to the alias set it aliases.
275 AS->addPointer(*this, Entry, Size, TBAAInfo);
279 if (New) *New = true;
280 // Otherwise create a new alias set to hold the loaded pointer.
281 AliasSets.push_back(new AliasSet());
282 AliasSets.back().addPointer(*this, Entry, Size, TBAAInfo);
283 return AliasSets.back();
286 bool AliasSetTracker::add(Value *Ptr, unsigned Size, const MDNode *TBAAInfo) {
288 addPointer(Ptr, Size, TBAAInfo, AliasSet::NoModRef, NewPtr);
293 bool AliasSetTracker::add(LoadInst *LI) {
295 AliasSet &AS = addPointer(LI->getOperand(0),
296 AA.getTypeStoreSize(LI->getType()),
297 LI->getMetadata(LLVMContext::MD_tbaa),
298 AliasSet::Refs, NewPtr);
299 if (LI->isVolatile()) AS.setVolatile();
303 bool AliasSetTracker::add(StoreInst *SI) {
305 Value *Val = SI->getOperand(0);
306 AliasSet &AS = addPointer(SI->getOperand(1),
307 AA.getTypeStoreSize(Val->getType()),
308 SI->getMetadata(LLVMContext::MD_tbaa),
309 AliasSet::Mods, NewPtr);
310 if (SI->isVolatile()) AS.setVolatile();
314 bool AliasSetTracker::add(VAArgInst *VAAI) {
316 addPointer(VAAI->getOperand(0), AliasAnalysis::UnknownSize,
317 VAAI->getMetadata(LLVMContext::MD_tbaa),
318 AliasSet::ModRef, NewPtr);
323 bool AliasSetTracker::add(CallSite CS) {
324 if (isa<DbgInfoIntrinsic>(CS.getInstruction()))
325 return true; // Ignore DbgInfo Intrinsics.
326 if (AA.doesNotAccessMemory(CS))
327 return true; // doesn't alias anything
329 AliasSet *AS = findAliasSetForCallSite(CS);
331 AS->addCallSite(CS, AA);
334 AliasSets.push_back(new AliasSet());
335 AS = &AliasSets.back();
336 AS->addCallSite(CS, AA);
340 bool AliasSetTracker::add(Instruction *I) {
341 // Dispatch to one of the other add methods.
342 if (LoadInst *LI = dyn_cast<LoadInst>(I))
344 if (StoreInst *SI = dyn_cast<StoreInst>(I))
346 if (CallInst *CI = dyn_cast<CallInst>(I))
348 if (InvokeInst *II = dyn_cast<InvokeInst>(I))
350 if (VAArgInst *VAAI = dyn_cast<VAArgInst>(I))
355 void AliasSetTracker::add(BasicBlock &BB) {
356 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
360 void AliasSetTracker::add(const AliasSetTracker &AST) {
361 assert(&AA == &AST.AA &&
362 "Merging AliasSetTracker objects with different Alias Analyses!");
364 // Loop over all of the alias sets in AST, adding the pointers contained
365 // therein into the current alias sets. This can cause alias sets to be
366 // merged together in the current AST.
367 for (const_iterator I = AST.begin(), E = AST.end(); I != E; ++I) {
368 if (I->Forward) continue; // Ignore forwarding alias sets
370 AliasSet &AS = const_cast<AliasSet&>(*I);
372 // If there are any call sites in the alias set, add them to this AST.
373 for (unsigned i = 0, e = AS.CallSites.size(); i != e; ++i)
374 add(AS.CallSites[i]);
376 // Loop over all of the pointers in this alias set.
378 for (AliasSet::iterator ASI = AS.begin(), E = AS.end(); ASI != E; ++ASI) {
379 AliasSet &NewAS = addPointer(ASI.getPointer(), ASI.getSize(),
381 (AliasSet::AccessType)AS.AccessTy, X);
382 if (AS.isVolatile()) NewAS.setVolatile();
387 /// remove - Remove the specified (potentially non-empty) alias set from the
389 void AliasSetTracker::remove(AliasSet &AS) {
390 // Drop all call sites.
391 AS.CallSites.clear();
393 // Clear the alias set.
394 unsigned NumRefs = 0;
395 while (!AS.empty()) {
396 AliasSet::PointerRec *P = AS.PtrList;
398 Value *ValToRemove = P->getValue();
400 // Unlink and delete entry from the list of values.
403 // Remember how many references need to be dropped.
406 // Finally, remove the entry.
407 PointerMap.erase(ValToRemove);
410 // Stop using the alias set, removing it.
411 AS.RefCount -= NumRefs;
412 if (AS.RefCount == 0)
413 AS.removeFromTracker(*this);
417 AliasSetTracker::remove(Value *Ptr, unsigned Size, const MDNode *TBAAInfo) {
418 AliasSet *AS = findAliasSetForPointer(Ptr, Size, TBAAInfo);
419 if (!AS) return false;
424 bool AliasSetTracker::remove(LoadInst *LI) {
425 unsigned Size = AA.getTypeStoreSize(LI->getType());
426 const MDNode *TBAAInfo = LI->getMetadata(LLVMContext::MD_tbaa);
427 AliasSet *AS = findAliasSetForPointer(LI->getOperand(0), Size, TBAAInfo);
428 if (!AS) return false;
433 bool AliasSetTracker::remove(StoreInst *SI) {
434 unsigned Size = AA.getTypeStoreSize(SI->getOperand(0)->getType());
435 const MDNode *TBAAInfo = SI->getMetadata(LLVMContext::MD_tbaa);
436 AliasSet *AS = findAliasSetForPointer(SI->getOperand(1), Size, TBAAInfo);
437 if (!AS) return false;
442 bool AliasSetTracker::remove(VAArgInst *VAAI) {
443 AliasSet *AS = findAliasSetForPointer(VAAI->getOperand(0),
444 AliasAnalysis::UnknownSize,
445 VAAI->getMetadata(LLVMContext::MD_tbaa));
446 if (!AS) return false;
451 bool AliasSetTracker::remove(CallSite CS) {
452 if (AA.doesNotAccessMemory(CS))
453 return false; // doesn't alias anything
455 AliasSet *AS = findAliasSetForCallSite(CS);
456 if (!AS) return false;
461 bool AliasSetTracker::remove(Instruction *I) {
462 // Dispatch to one of the other remove methods...
463 if (LoadInst *LI = dyn_cast<LoadInst>(I))
465 if (StoreInst *SI = dyn_cast<StoreInst>(I))
467 if (CallInst *CI = dyn_cast<CallInst>(I))
469 if (VAArgInst *VAAI = dyn_cast<VAArgInst>(I))
475 // deleteValue method - This method is used to remove a pointer value from the
476 // AliasSetTracker entirely. It should be used when an instruction is deleted
477 // from the program to update the AST. If you don't use this, you would have
478 // dangling pointers to deleted instructions.
480 void AliasSetTracker::deleteValue(Value *PtrVal) {
481 // Notify the alias analysis implementation that this value is gone.
482 AA.deleteValue(PtrVal);
484 // If this is a call instruction, remove the callsite from the appropriate
485 // AliasSet (if present).
486 if (CallSite CS = PtrVal) {
487 if (!AA.doesNotAccessMemory(CS)) {
488 // Scan all the alias sets to see if this call site is contained.
489 for (iterator I = begin(), E = end(); I != E; ++I) {
490 if (I->Forward) continue;
492 I->removeCallSite(CS);
497 // First, look up the PointerRec for this pointer.
498 PointerMapType::iterator I = PointerMap.find(PtrVal);
499 if (I == PointerMap.end()) return; // Noop
501 // If we found one, remove the pointer from the alias set it is in.
502 AliasSet::PointerRec *PtrValEnt = I->second;
503 AliasSet *AS = PtrValEnt->getAliasSet(*this);
505 // Unlink and delete from the list of values.
506 PtrValEnt->eraseFromList();
508 // Stop using the alias set.
514 // copyValue - This method should be used whenever a preexisting value in the
515 // program is copied or cloned, introducing a new value. Note that it is ok for
516 // clients that use this method to introduce the same value multiple times: if
517 // the tracker already knows about a value, it will ignore the request.
519 void AliasSetTracker::copyValue(Value *From, Value *To) {
520 // Notify the alias analysis implementation that this value is copied.
521 AA.copyValue(From, To);
523 // First, look up the PointerRec for this pointer.
524 PointerMapType::iterator I = PointerMap.find(From);
525 if (I == PointerMap.end())
527 assert(I->second->hasAliasSet() && "Dead entry?");
529 AliasSet::PointerRec &Entry = getEntryFor(To);
530 if (Entry.hasAliasSet()) return; // Already in the tracker!
532 // Add it to the alias set it aliases...
533 I = PointerMap.find(From);
534 AliasSet *AS = I->second->getAliasSet(*this);
535 AS->addPointer(*this, Entry, I->second->getSize(),
536 I->second->getTBAAInfo(),
542 //===----------------------------------------------------------------------===//
543 // AliasSet/AliasSetTracker Printing Support
544 //===----------------------------------------------------------------------===//
546 void AliasSet::print(raw_ostream &OS) const {
547 OS << " AliasSet[" << (void*)this << ", " << RefCount << "] ";
548 OS << (AliasTy == MustAlias ? "must" : "may") << " alias, ";
550 case NoModRef: OS << "No access "; break;
551 case Refs : OS << "Ref "; break;
552 case Mods : OS << "Mod "; break;
553 case ModRef : OS << "Mod/Ref "; break;
554 default: llvm_unreachable("Bad value for AccessTy!");
556 if (isVolatile()) OS << "[volatile] ";
558 OS << " forwarding to " << (void*)Forward;
563 for (iterator I = begin(), E = end(); I != E; ++I) {
564 if (I != begin()) OS << ", ";
565 WriteAsOperand(OS << "(", I.getPointer());
566 OS << ", " << I.getSize() << ")";
569 if (!CallSites.empty()) {
570 OS << "\n " << CallSites.size() << " Call Sites: ";
571 for (unsigned i = 0, e = CallSites.size(); i != e; ++i) {
573 WriteAsOperand(OS, CallSites[i]);
579 void AliasSetTracker::print(raw_ostream &OS) const {
580 OS << "Alias Set Tracker: " << AliasSets.size() << " alias sets for "
581 << PointerMap.size() << " pointer values.\n";
582 for (const_iterator I = begin(), E = end(); I != E; ++I)
587 void AliasSet::dump() const { print(dbgs()); }
588 void AliasSetTracker::dump() const { print(dbgs()); }
590 //===----------------------------------------------------------------------===//
591 // ASTCallbackVH Class Implementation
592 //===----------------------------------------------------------------------===//
594 void AliasSetTracker::ASTCallbackVH::deleted() {
595 assert(AST && "ASTCallbackVH called with a null AliasSetTracker!");
596 AST->deleteValue(getValPtr());
600 AliasSetTracker::ASTCallbackVH::ASTCallbackVH(Value *V, AliasSetTracker *ast)
601 : CallbackVH(V), AST(ast) {}
603 AliasSetTracker::ASTCallbackVH &
604 AliasSetTracker::ASTCallbackVH::operator=(Value *V) {
605 return *this = ASTCallbackVH(V, AST);
608 //===----------------------------------------------------------------------===//
609 // AliasSetPrinter Pass
610 //===----------------------------------------------------------------------===//
613 class AliasSetPrinter : public FunctionPass {
614 AliasSetTracker *Tracker;
616 static char ID; // Pass identification, replacement for typeid
617 AliasSetPrinter() : FunctionPass(ID) {
618 initializeAliasSetPrinterPass(*PassRegistry::getPassRegistry());
621 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
622 AU.setPreservesAll();
623 AU.addRequired<AliasAnalysis>();
626 virtual bool runOnFunction(Function &F) {
627 Tracker = new AliasSetTracker(getAnalysis<AliasAnalysis>());
629 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
631 Tracker->print(errs());
638 char AliasSetPrinter::ID = 0;
639 INITIALIZE_PASS_BEGIN(AliasSetPrinter, "print-alias-sets",
640 "Alias Set Printer", false, true)
641 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
642 INITIALIZE_PASS_END(AliasSetPrinter, "print-alias-sets",
643 "Alias Set Printer", false, true)