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(), I.getTBAAInfo())))
164 // Check the call sites list and invoke list...
165 if (!CallSites.empty()) {
166 for (unsigned i = 0, e = CallSites.size(); i != e; ++i)
167 if (AA.getModRefInfo(CallSites[i],
168 AliasAnalysis::Location(Ptr, Size, TBAAInfo)) !=
169 AliasAnalysis::NoModRef)
176 bool AliasSet::aliasesCallSite(CallSite CS, AliasAnalysis &AA) const {
177 if (AA.doesNotAccessMemory(CS))
180 for (unsigned i = 0, e = CallSites.size(); i != e; ++i) {
181 if (AA.getModRefInfo(getCallSite(i), CS) != AliasAnalysis::NoModRef ||
182 AA.getModRefInfo(CS, getCallSite(i)) != AliasAnalysis::NoModRef)
186 for (iterator I = begin(), E = end(); I != E; ++I)
187 if (AA.getModRefInfo(CS, I.getPointer(), I.getSize()) !=
188 AliasAnalysis::NoModRef)
194 void AliasSetTracker::clear() {
195 // Delete all the PointerRec entries.
196 for (PointerMapType::iterator I = PointerMap.begin(), E = PointerMap.end();
198 I->second->eraseFromList();
202 // The alias sets should all be clear now.
207 /// findAliasSetForPointer - Given a pointer, find the one alias set to put the
208 /// instruction referring to the pointer into. If there are multiple alias sets
209 /// that may alias the pointer, merge them together and return the unified set.
211 AliasSet *AliasSetTracker::findAliasSetForPointer(const Value *Ptr,
213 const MDNode *TBAAInfo) {
214 AliasSet *FoundSet = 0;
215 for (iterator I = begin(), E = end(); I != E; ++I) {
216 if (I->Forward || !I->aliasesPointer(Ptr, Size, TBAAInfo, AA)) continue;
218 if (FoundSet == 0) { // If this is the first alias set ptr can go into.
219 FoundSet = I; // Remember it.
220 } else { // Otherwise, we must merge the sets.
221 FoundSet->mergeSetIn(*I, *this); // Merge in contents.
228 /// containsPointer - Return true if the specified location is represented by
229 /// this alias set, false otherwise. This does not modify the AST object or
231 bool AliasSetTracker::containsPointer(Value *Ptr, unsigned Size,
232 const MDNode *TBAAInfo) const {
233 for (const_iterator I = begin(), E = end(); I != E; ++I)
234 if (!I->Forward && I->aliasesPointer(Ptr, Size, TBAAInfo, AA))
241 AliasSet *AliasSetTracker::findAliasSetForCallSite(CallSite CS) {
242 AliasSet *FoundSet = 0;
243 for (iterator I = begin(), E = end(); I != E; ++I) {
244 if (I->Forward || !I->aliasesCallSite(CS, AA))
247 if (FoundSet == 0) // If this is the first alias set ptr can go into.
248 FoundSet = I; // Remember it.
249 else if (!I->Forward) // Otherwise, we must merge the sets.
250 FoundSet->mergeSetIn(*I, *this); // Merge in contents.
258 /// getAliasSetForPointer - Return the alias set that the specified pointer
260 AliasSet &AliasSetTracker::getAliasSetForPointer(Value *Pointer, unsigned Size,
261 const MDNode *TBAAInfo,
263 AliasSet::PointerRec &Entry = getEntryFor(Pointer);
265 // Check to see if the pointer is already known.
266 if (Entry.hasAliasSet()) {
267 Entry.updateSizeAndTBAAInfo(Size, TBAAInfo);
269 return *Entry.getAliasSet(*this)->getForwardedTarget(*this);
272 if (AliasSet *AS = findAliasSetForPointer(Pointer, Size, TBAAInfo)) {
273 // Add it to the alias set it aliases.
274 AS->addPointer(*this, Entry, Size, TBAAInfo);
278 if (New) *New = true;
279 // Otherwise create a new alias set to hold the loaded pointer.
280 AliasSets.push_back(new AliasSet());
281 AliasSets.back().addPointer(*this, Entry, Size, TBAAInfo);
282 return AliasSets.back();
285 bool AliasSetTracker::add(Value *Ptr, unsigned Size, const MDNode *TBAAInfo) {
287 addPointer(Ptr, Size, TBAAInfo, AliasSet::NoModRef, NewPtr);
292 bool AliasSetTracker::add(LoadInst *LI) {
294 AliasSet &AS = addPointer(LI->getOperand(0),
295 AA.getTypeStoreSize(LI->getType()),
296 LI->getMetadata(LLVMContext::MD_tbaa),
297 AliasSet::Refs, NewPtr);
298 if (LI->isVolatile()) AS.setVolatile();
302 bool AliasSetTracker::add(StoreInst *SI) {
304 Value *Val = SI->getOperand(0);
305 AliasSet &AS = addPointer(SI->getOperand(1),
306 AA.getTypeStoreSize(Val->getType()),
307 SI->getMetadata(LLVMContext::MD_tbaa),
308 AliasSet::Mods, NewPtr);
309 if (SI->isVolatile()) AS.setVolatile();
313 bool AliasSetTracker::add(VAArgInst *VAAI) {
315 addPointer(VAAI->getOperand(0), AliasAnalysis::UnknownSize,
316 VAAI->getMetadata(LLVMContext::MD_tbaa),
317 AliasSet::ModRef, NewPtr);
322 bool AliasSetTracker::add(CallSite CS) {
323 if (isa<DbgInfoIntrinsic>(CS.getInstruction()))
324 return true; // Ignore DbgInfo Intrinsics.
325 if (AA.doesNotAccessMemory(CS))
326 return true; // doesn't alias anything
328 AliasSet *AS = findAliasSetForCallSite(CS);
330 AS->addCallSite(CS, AA);
333 AliasSets.push_back(new AliasSet());
334 AS = &AliasSets.back();
335 AS->addCallSite(CS, AA);
339 bool AliasSetTracker::add(Instruction *I) {
340 // Dispatch to one of the other add methods.
341 if (LoadInst *LI = dyn_cast<LoadInst>(I))
343 if (StoreInst *SI = dyn_cast<StoreInst>(I))
345 if (CallInst *CI = dyn_cast<CallInst>(I))
347 if (InvokeInst *II = dyn_cast<InvokeInst>(I))
349 if (VAArgInst *VAAI = dyn_cast<VAArgInst>(I))
354 void AliasSetTracker::add(BasicBlock &BB) {
355 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
359 void AliasSetTracker::add(const AliasSetTracker &AST) {
360 assert(&AA == &AST.AA &&
361 "Merging AliasSetTracker objects with different Alias Analyses!");
363 // Loop over all of the alias sets in AST, adding the pointers contained
364 // therein into the current alias sets. This can cause alias sets to be
365 // merged together in the current AST.
366 for (const_iterator I = AST.begin(), E = AST.end(); I != E; ++I) {
367 if (I->Forward) continue; // Ignore forwarding alias sets
369 AliasSet &AS = const_cast<AliasSet&>(*I);
371 // If there are any call sites in the alias set, add them to this AST.
372 for (unsigned i = 0, e = AS.CallSites.size(); i != e; ++i)
373 add(AS.CallSites[i]);
375 // Loop over all of the pointers in this alias set.
377 for (AliasSet::iterator ASI = AS.begin(), E = AS.end(); ASI != E; ++ASI) {
378 AliasSet &NewAS = addPointer(ASI.getPointer(), ASI.getSize(),
380 (AliasSet::AccessType)AS.AccessTy, X);
381 if (AS.isVolatile()) NewAS.setVolatile();
386 /// remove - Remove the specified (potentially non-empty) alias set from the
388 void AliasSetTracker::remove(AliasSet &AS) {
389 // Drop all call sites.
390 AS.CallSites.clear();
392 // Clear the alias set.
393 unsigned NumRefs = 0;
394 while (!AS.empty()) {
395 AliasSet::PointerRec *P = AS.PtrList;
397 Value *ValToRemove = P->getValue();
399 // Unlink and delete entry from the list of values.
402 // Remember how many references need to be dropped.
405 // Finally, remove the entry.
406 PointerMap.erase(ValToRemove);
409 // Stop using the alias set, removing it.
410 AS.RefCount -= NumRefs;
411 if (AS.RefCount == 0)
412 AS.removeFromTracker(*this);
416 AliasSetTracker::remove(Value *Ptr, unsigned Size, const MDNode *TBAAInfo) {
417 AliasSet *AS = findAliasSetForPointer(Ptr, Size, TBAAInfo);
418 if (!AS) return false;
423 bool AliasSetTracker::remove(LoadInst *LI) {
424 unsigned Size = AA.getTypeStoreSize(LI->getType());
425 const MDNode *TBAAInfo = LI->getMetadata(LLVMContext::MD_tbaa);
426 AliasSet *AS = findAliasSetForPointer(LI->getOperand(0), Size, TBAAInfo);
427 if (!AS) return false;
432 bool AliasSetTracker::remove(StoreInst *SI) {
433 unsigned Size = AA.getTypeStoreSize(SI->getOperand(0)->getType());
434 const MDNode *TBAAInfo = SI->getMetadata(LLVMContext::MD_tbaa);
435 AliasSet *AS = findAliasSetForPointer(SI->getOperand(1), Size, TBAAInfo);
436 if (!AS) return false;
441 bool AliasSetTracker::remove(VAArgInst *VAAI) {
442 AliasSet *AS = findAliasSetForPointer(VAAI->getOperand(0),
443 AliasAnalysis::UnknownSize,
444 VAAI->getMetadata(LLVMContext::MD_tbaa));
445 if (!AS) return false;
450 bool AliasSetTracker::remove(CallSite CS) {
451 if (AA.doesNotAccessMemory(CS))
452 return false; // doesn't alias anything
454 AliasSet *AS = findAliasSetForCallSite(CS);
455 if (!AS) return false;
460 bool AliasSetTracker::remove(Instruction *I) {
461 // Dispatch to one of the other remove methods...
462 if (LoadInst *LI = dyn_cast<LoadInst>(I))
464 if (StoreInst *SI = dyn_cast<StoreInst>(I))
466 if (CallInst *CI = dyn_cast<CallInst>(I))
468 if (VAArgInst *VAAI = dyn_cast<VAArgInst>(I))
474 // deleteValue method - This method is used to remove a pointer value from the
475 // AliasSetTracker entirely. It should be used when an instruction is deleted
476 // from the program to update the AST. If you don't use this, you would have
477 // dangling pointers to deleted instructions.
479 void AliasSetTracker::deleteValue(Value *PtrVal) {
480 // Notify the alias analysis implementation that this value is gone.
481 AA.deleteValue(PtrVal);
483 // If this is a call instruction, remove the callsite from the appropriate
484 // AliasSet (if present).
485 if (CallSite CS = PtrVal) {
486 if (!AA.doesNotAccessMemory(CS)) {
487 // Scan all the alias sets to see if this call site is contained.
488 for (iterator I = begin(), E = end(); I != E; ++I) {
489 if (I->Forward) continue;
491 I->removeCallSite(CS);
496 // First, look up the PointerRec for this pointer.
497 PointerMapType::iterator I = PointerMap.find(PtrVal);
498 if (I == PointerMap.end()) return; // Noop
500 // If we found one, remove the pointer from the alias set it is in.
501 AliasSet::PointerRec *PtrValEnt = I->second;
502 AliasSet *AS = PtrValEnt->getAliasSet(*this);
504 // Unlink and delete from the list of values.
505 PtrValEnt->eraseFromList();
507 // Stop using the alias set.
513 // copyValue - This method should be used whenever a preexisting value in the
514 // program is copied or cloned, introducing a new value. Note that it is ok for
515 // clients that use this method to introduce the same value multiple times: if
516 // the tracker already knows about a value, it will ignore the request.
518 void AliasSetTracker::copyValue(Value *From, Value *To) {
519 // Notify the alias analysis implementation that this value is copied.
520 AA.copyValue(From, To);
522 // First, look up the PointerRec for this pointer.
523 PointerMapType::iterator I = PointerMap.find(From);
524 if (I == PointerMap.end())
526 assert(I->second->hasAliasSet() && "Dead entry?");
528 AliasSet::PointerRec &Entry = getEntryFor(To);
529 if (Entry.hasAliasSet()) return; // Already in the tracker!
531 // Add it to the alias set it aliases...
532 I = PointerMap.find(From);
533 AliasSet *AS = I->second->getAliasSet(*this);
534 AS->addPointer(*this, Entry, I->second->getSize(), I->second->getTBAAInfo(),
540 //===----------------------------------------------------------------------===//
541 // AliasSet/AliasSetTracker Printing Support
542 //===----------------------------------------------------------------------===//
544 void AliasSet::print(raw_ostream &OS) const {
545 OS << " AliasSet[" << (void*)this << ", " << RefCount << "] ";
546 OS << (AliasTy == MustAlias ? "must" : "may") << " alias, ";
548 case NoModRef: OS << "No access "; break;
549 case Refs : OS << "Ref "; break;
550 case Mods : OS << "Mod "; break;
551 case ModRef : OS << "Mod/Ref "; break;
552 default: llvm_unreachable("Bad value for AccessTy!");
554 if (isVolatile()) OS << "[volatile] ";
556 OS << " forwarding to " << (void*)Forward;
561 for (iterator I = begin(), E = end(); I != E; ++I) {
562 if (I != begin()) OS << ", ";
563 WriteAsOperand(OS << "(", I.getPointer());
564 OS << ", " << I.getSize() << ")";
567 if (!CallSites.empty()) {
568 OS << "\n " << CallSites.size() << " Call Sites: ";
569 for (unsigned i = 0, e = CallSites.size(); i != e; ++i) {
571 WriteAsOperand(OS, CallSites[i]);
577 void AliasSetTracker::print(raw_ostream &OS) const {
578 OS << "Alias Set Tracker: " << AliasSets.size() << " alias sets for "
579 << PointerMap.size() << " pointer values.\n";
580 for (const_iterator I = begin(), E = end(); I != E; ++I)
585 void AliasSet::dump() const { print(dbgs()); }
586 void AliasSetTracker::dump() const { print(dbgs()); }
588 //===----------------------------------------------------------------------===//
589 // ASTCallbackVH Class Implementation
590 //===----------------------------------------------------------------------===//
592 void AliasSetTracker::ASTCallbackVH::deleted() {
593 assert(AST && "ASTCallbackVH called with a null AliasSetTracker!");
594 AST->deleteValue(getValPtr());
598 AliasSetTracker::ASTCallbackVH::ASTCallbackVH(Value *V, AliasSetTracker *ast)
599 : CallbackVH(V), AST(ast) {}
601 AliasSetTracker::ASTCallbackVH &
602 AliasSetTracker::ASTCallbackVH::operator=(Value *V) {
603 return *this = ASTCallbackVH(V, AST);
606 //===----------------------------------------------------------------------===//
607 // AliasSetPrinter Pass
608 //===----------------------------------------------------------------------===//
611 class AliasSetPrinter : public FunctionPass {
612 AliasSetTracker *Tracker;
614 static char ID; // Pass identification, replacement for typeid
615 AliasSetPrinter() : FunctionPass(ID) {}
617 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
618 AU.setPreservesAll();
619 AU.addRequired<AliasAnalysis>();
622 virtual bool runOnFunction(Function &F) {
623 Tracker = new AliasSetTracker(getAnalysis<AliasAnalysis>());
625 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
627 Tracker->print(errs());
634 char AliasSetPrinter::ID = 0;
635 INITIALIZE_PASS_BEGIN(AliasSetPrinter, "print-alias-sets",
636 "Alias Set Printer", false, true)
637 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
638 INITIALIZE_PASS_END(AliasSetPrinter, "print-alias-sets",
639 "Alias Set Printer", false, true)