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/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/Module.h" 21 #include "llvm/IR/LLVMContext.h" 22 #include "llvm/IR/Type.h" 23 #include "llvm/Pass.h" 24 #include "llvm/Support/Debug.h" 25 #include "llvm/Support/ErrorHandling.h" 26 #include "llvm/Support/raw_ostream.h" 27 using namespace llvm; 28 29 /// mergeSetIn - Merge the specified alias set into this alias set. 30 /// 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!!"); 34 35 // Update the alias and access types of this set... 36 Access |= AS.Access; 37 Alias |= AS.Alias; 38 Volatile |= AS.Volatile; 39 40 if (Alias == SetMustAlias) { 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 43 // for aliasing. 44 AliasAnalysis &AA = AST.getAliasAnalysis(); 45 PointerRec *L = getSomePointer(); 46 PointerRec *R = AS.getSomePointer(); 47 48 // If the pointers are not a must-alias pair, this set becomes a may alias. 49 if (AA.alias(MemoryLocation(L->getValue(), L->getSize(), L->getAAInfo()), 50 MemoryLocation(R->getValue(), R->getSize(), R->getAAInfo())) != 51 MustAlias) 52 Alias = SetMayAlias; 53 } 54 55 bool ASHadUnknownInsts = !AS.UnknownInsts.empty(); 56 if (UnknownInsts.empty()) { // Merge call sites... 57 if (ASHadUnknownInsts) { 58 std::swap(UnknownInsts, AS.UnknownInsts); 59 addRef(); 60 } 61 } else if (ASHadUnknownInsts) { 62 UnknownInsts.insert(UnknownInsts.end(), AS.UnknownInsts.begin(), AS.UnknownInsts.end()); 63 AS.UnknownInsts.clear(); 64 } 65 66 AS.Forward = this; // Forward across AS now... 67 addRef(); // AS is now pointing to us... 68 69 // Merge the list of constituent pointers... 70 if (AS.PtrList) { 71 *PtrListEnd = AS.PtrList; 72 AS.PtrList->setPrevInList(PtrListEnd); 73 PtrListEnd = AS.PtrListEnd; 74 75 AS.PtrList = nullptr; 76 AS.PtrListEnd = &AS.PtrList; 77 assert(*AS.PtrListEnd == nullptr && "End of list is not null?"); 78 } 79 if (ASHadUnknownInsts) 80 AS.dropRef(AST); 81 } 82 83 void AliasSetTracker::removeAliasSet(AliasSet *AS) { 84 if (AliasSet *Fwd = AS->Forward) { 85 Fwd->dropRef(*this); 86 AS->Forward = nullptr; 87 } 88 AliasSets.erase(AS); 89 } 90 91 void AliasSet::removeFromTracker(AliasSetTracker &AST) { 92 assert(RefCount == 0 && "Cannot remove non-dead alias set from tracker!"); 93 AST.removeAliasSet(this); 94 } 95 96 void AliasSet::addPointer(AliasSetTracker &AST, PointerRec &Entry, 97 uint64_t Size, const AAMDNodes &AAInfo, 98 bool KnownMustAlias) { 99 assert(!Entry.hasAliasSet() && "Entry already in set!"); 100 101 // Check to see if we have to downgrade to _may_ alias. 102 if (isMustAlias() && !KnownMustAlias) 103 if (PointerRec *P = getSomePointer()) { 104 AliasAnalysis &AA = AST.getAliasAnalysis(); 105 AliasResult Result = 106 AA.alias(MemoryLocation(P->getValue(), P->getSize(), P->getAAInfo()), 107 MemoryLocation(Entry.getValue(), Size, AAInfo)); 108 if (Result != MustAlias) 109 Alias = SetMayAlias; 110 else // First entry of must alias must have maximum size! 111 P->updateSizeAndAAInfo(Size, AAInfo); 112 assert(Result != NoAlias && "Cannot be part of must set!"); 113 } 114 115 Entry.setAliasSet(this); 116 Entry.updateSizeAndAAInfo(Size, AAInfo); 117 118 // Add it to the end of the list... 119 assert(*PtrListEnd == nullptr && "End of list is not null?"); 120 *PtrListEnd = &Entry; 121 PtrListEnd = Entry.setPrevInList(PtrListEnd); 122 assert(*PtrListEnd == nullptr && "End of list is not null?"); 123 addRef(); // Entry points to alias set. 124 } 125 126 void AliasSet::addUnknownInst(Instruction *I, AliasAnalysis &AA) { 127 if (UnknownInsts.empty()) 128 addRef(); 129 UnknownInsts.emplace_back(I); 130 131 if (!I->mayWriteToMemory()) { 132 Alias = SetMayAlias; 133 Access |= RefAccess; 134 return; 135 } 136 137 // FIXME: This should use mod/ref information to make this not suck so bad 138 Alias = SetMayAlias; 139 Access = ModRefAccess; 140 } 141 142 /// aliasesPointer - Return true if the specified pointer "may" (or must) 143 /// alias one of the members in the set. 144 /// 145 bool AliasSet::aliasesPointer(const Value *Ptr, uint64_t Size, 146 const AAMDNodes &AAInfo, 147 AliasAnalysis &AA) const { 148 if (Alias == SetMustAlias) { 149 assert(UnknownInsts.empty() && "Illegal must alias set!"); 150 151 // If this is a set of MustAliases, only check to see if the pointer aliases 152 // SOME value in the set. 153 PointerRec *SomePtr = getSomePointer(); 154 assert(SomePtr && "Empty must-alias set??"); 155 return AA.alias(MemoryLocation(SomePtr->getValue(), SomePtr->getSize(), 156 SomePtr->getAAInfo()), 157 MemoryLocation(Ptr, Size, AAInfo)); 158 } 159 160 // If this is a may-alias set, we have to check all of the pointers in the set 161 // to be sure it doesn't alias the set... 162 for (iterator I = begin(), E = end(); I != E; ++I) 163 if (AA.alias(MemoryLocation(Ptr, Size, AAInfo), 164 MemoryLocation(I.getPointer(), I.getSize(), I.getAAInfo()))) 165 return true; 166 167 // Check the unknown instructions... 168 if (!UnknownInsts.empty()) { 169 for (unsigned i = 0, e = UnknownInsts.size(); i != e; ++i) 170 if (AA.getModRefInfo(UnknownInsts[i], 171 MemoryLocation(Ptr, Size, AAInfo)) != MRI_NoModRef) 172 return true; 173 } 174 175 return false; 176 } 177 178 bool AliasSet::aliasesUnknownInst(const Instruction *Inst, 179 AliasAnalysis &AA) const { 180 if (!Inst->mayReadOrWriteMemory()) 181 return false; 182 183 for (unsigned i = 0, e = UnknownInsts.size(); i != e; ++i) { 184 ImmutableCallSite C1(getUnknownInst(i)), C2(Inst); 185 if (!C1 || !C2 || AA.getModRefInfo(C1, C2) != MRI_NoModRef || 186 AA.getModRefInfo(C2, C1) != MRI_NoModRef) 187 return true; 188 } 189 190 for (iterator I = begin(), E = end(); I != E; ++I) 191 if (AA.getModRefInfo(Inst, MemoryLocation(I.getPointer(), I.getSize(), 192 I.getAAInfo())) != MRI_NoModRef) 193 return true; 194 195 return false; 196 } 197 198 void AliasSetTracker::clear() { 199 // Delete all the PointerRec entries. 200 for (PointerMapType::iterator I = PointerMap.begin(), E = PointerMap.end(); 201 I != E; ++I) 202 I->second->eraseFromList(); 203 204 PointerMap.clear(); 205 206 // The alias sets should all be clear now. 207 AliasSets.clear(); 208 } 209 210 211 /// mergeAliasSetsForPointer - Given a pointer, merge all alias sets that may 212 /// alias the pointer. Return the unified set, or nullptr if no set that aliases 213 /// the pointer was found. 214 AliasSet *AliasSetTracker::mergeAliasSetsForPointer(const Value *Ptr, 215 uint64_t Size, 216 const AAMDNodes &AAInfo) { 217 AliasSet *FoundSet = nullptr; 218 for (iterator I = begin(), E = end(); I != E;) { 219 iterator Cur = I++; 220 if (Cur->Forward || !Cur->aliasesPointer(Ptr, Size, AAInfo, AA)) continue; 221 222 if (!FoundSet) { // If this is the first alias set ptr can go into. 223 FoundSet = &*Cur; // Remember it. 224 } else { // Otherwise, we must merge the sets. 225 FoundSet->mergeSetIn(*Cur, *this); // Merge in contents. 226 } 227 } 228 229 return FoundSet; 230 } 231 232 bool AliasSetTracker::containsUnknown(const Instruction *Inst) const { 233 for (const AliasSet &AS : *this) 234 if (!AS.Forward && AS.aliasesUnknownInst(Inst, AA)) 235 return true; 236 return false; 237 } 238 239 AliasSet *AliasSetTracker::findAliasSetForUnknownInst(Instruction *Inst) { 240 AliasSet *FoundSet = nullptr; 241 for (iterator I = begin(), E = end(); I != E;) { 242 iterator Cur = I++; 243 if (Cur->Forward || !Cur->aliasesUnknownInst(Inst, AA)) 244 continue; 245 if (!FoundSet) // If this is the first alias set ptr can go into. 246 FoundSet = &*Cur; // Remember it. 247 else if (!Cur->Forward) // Otherwise, we must merge the sets. 248 FoundSet->mergeSetIn(*Cur, *this); // Merge in contents. 249 } 250 return FoundSet; 251 } 252 253 254 255 256 /// getAliasSetForPointer - Return the alias set that the specified pointer 257 /// lives in. 258 AliasSet &AliasSetTracker::getAliasSetForPointer(Value *Pointer, uint64_t Size, 259 const AAMDNodes &AAInfo, 260 bool *New) { 261 AliasSet::PointerRec &Entry = getEntryFor(Pointer); 262 263 // Check to see if the pointer is already known. 264 if (Entry.hasAliasSet()) { 265 // If the size changed, we may need to merge several alias sets. 266 // Note that we can *not* return the result of mergeAliasSetsForPointer 267 // due to a quirk of alias analysis behavior. Since alias(undef, undef) 268 // is NoAlias, mergeAliasSetsForPointer(undef, ...) will not find the 269 // the right set for undef, even if it exists. 270 if (Entry.updateSizeAndAAInfo(Size, AAInfo)) 271 mergeAliasSetsForPointer(Pointer, Size, AAInfo); 272 // Return the set! 273 return *Entry.getAliasSet(*this)->getForwardedTarget(*this); 274 } 275 276 if (AliasSet *AS = mergeAliasSetsForPointer(Pointer, Size, AAInfo)) { 277 // Add it to the alias set it aliases. 278 AS->addPointer(*this, Entry, Size, AAInfo); 279 return *AS; 280 } 281 282 if (New) *New = true; 283 // Otherwise create a new alias set to hold the loaded pointer. 284 AliasSets.push_back(new AliasSet()); 285 AliasSets.back().addPointer(*this, Entry, Size, AAInfo); 286 return AliasSets.back(); 287 } 288 289 bool AliasSetTracker::add(Value *Ptr, uint64_t Size, const AAMDNodes &AAInfo) { 290 bool NewPtr; 291 addPointer(Ptr, Size, AAInfo, AliasSet::NoAccess, NewPtr); 292 return NewPtr; 293 } 294 295 296 bool AliasSetTracker::add(LoadInst *LI) { 297 if (isStrongerThanMonotonic(LI->getOrdering())) return addUnknown(LI); 298 299 AAMDNodes AAInfo; 300 LI->getAAMetadata(AAInfo); 301 302 AliasSet::AccessLattice Access = AliasSet::RefAccess; 303 bool NewPtr; 304 const DataLayout &DL = LI->getModule()->getDataLayout(); 305 AliasSet &AS = addPointer(LI->getOperand(0), 306 DL.getTypeStoreSize(LI->getType()), 307 AAInfo, Access, NewPtr); 308 if (LI->isVolatile()) AS.setVolatile(); 309 return NewPtr; 310 } 311 312 bool AliasSetTracker::add(StoreInst *SI) { 313 if (isStrongerThanMonotonic(SI->getOrdering())) return addUnknown(SI); 314 315 AAMDNodes AAInfo; 316 SI->getAAMetadata(AAInfo); 317 318 AliasSet::AccessLattice Access = AliasSet::ModAccess; 319 bool NewPtr; 320 const DataLayout &DL = SI->getModule()->getDataLayout(); 321 Value *Val = SI->getOperand(0); 322 AliasSet &AS = addPointer(SI->getOperand(1), 323 DL.getTypeStoreSize(Val->getType()), 324 AAInfo, Access, NewPtr); 325 if (SI->isVolatile()) AS.setVolatile(); 326 return NewPtr; 327 } 328 329 bool AliasSetTracker::add(VAArgInst *VAAI) { 330 AAMDNodes AAInfo; 331 VAAI->getAAMetadata(AAInfo); 332 333 bool NewPtr; 334 addPointer(VAAI->getOperand(0), MemoryLocation::UnknownSize, AAInfo, 335 AliasSet::ModRefAccess, NewPtr); 336 return NewPtr; 337 } 338 339 bool AliasSetTracker::add(MemSetInst *MSI) { 340 AAMDNodes AAInfo; 341 MSI->getAAMetadata(AAInfo); 342 343 bool NewPtr; 344 uint64_t Len; 345 346 if (ConstantInt *C = dyn_cast<ConstantInt>(MSI->getLength())) 347 Len = C->getZExtValue(); 348 else 349 Len = MemoryLocation::UnknownSize; 350 351 AliasSet &AS = 352 addPointer(MSI->getRawDest(), Len, AAInfo, AliasSet::ModAccess, NewPtr); 353 if (MSI->isVolatile()) 354 AS.setVolatile(); 355 return NewPtr; 356 } 357 358 bool AliasSetTracker::addUnknown(Instruction *Inst) { 359 if (isa<DbgInfoIntrinsic>(Inst)) 360 return true; // Ignore DbgInfo Intrinsics. 361 if (!Inst->mayReadOrWriteMemory()) 362 return true; // doesn't alias anything 363 364 AliasSet *AS = findAliasSetForUnknownInst(Inst); 365 if (AS) { 366 AS->addUnknownInst(Inst, AA); 367 return false; 368 } 369 AliasSets.push_back(new AliasSet()); 370 AS = &AliasSets.back(); 371 AS->addUnknownInst(Inst, AA); 372 return true; 373 } 374 375 bool AliasSetTracker::add(Instruction *I) { 376 // Dispatch to one of the other add methods. 377 if (LoadInst *LI = dyn_cast<LoadInst>(I)) 378 return add(LI); 379 if (StoreInst *SI = dyn_cast<StoreInst>(I)) 380 return add(SI); 381 if (VAArgInst *VAAI = dyn_cast<VAArgInst>(I)) 382 return add(VAAI); 383 if (MemSetInst *MSI = dyn_cast<MemSetInst>(I)) 384 return add(MSI); 385 return addUnknown(I); 386 // FIXME: add support of memcpy and memmove. 387 } 388 389 void AliasSetTracker::add(BasicBlock &BB) { 390 for (auto &I : BB) 391 add(&I); 392 } 393 394 void AliasSetTracker::add(const AliasSetTracker &AST) { 395 assert(&AA == &AST.AA && 396 "Merging AliasSetTracker objects with different Alias Analyses!"); 397 398 // Loop over all of the alias sets in AST, adding the pointers contained 399 // therein into the current alias sets. This can cause alias sets to be 400 // merged together in the current AST. 401 for (const AliasSet &AS : AST) { 402 if (AS.Forward) 403 continue; // Ignore forwarding alias sets 404 405 // If there are any call sites in the alias set, add them to this AST. 406 for (unsigned i = 0, e = AS.UnknownInsts.size(); i != e; ++i) 407 add(AS.UnknownInsts[i]); 408 409 // Loop over all of the pointers in this alias set. 410 bool X; 411 for (AliasSet::iterator ASI = AS.begin(), E = AS.end(); ASI != E; ++ASI) { 412 AliasSet &NewAS = addPointer(ASI.getPointer(), ASI.getSize(), 413 ASI.getAAInfo(), 414 (AliasSet::AccessLattice)AS.Access, X); 415 if (AS.isVolatile()) NewAS.setVolatile(); 416 } 417 } 418 } 419 420 // deleteValue method - This method is used to remove a pointer value from the 421 // AliasSetTracker entirely. It should be used when an instruction is deleted 422 // from the program to update the AST. If you don't use this, you would have 423 // dangling pointers to deleted instructions. 424 // 425 void AliasSetTracker::deleteValue(Value *PtrVal) { 426 // If this is a call instruction, remove the callsite from the appropriate 427 // AliasSet (if present). 428 if (Instruction *Inst = dyn_cast<Instruction>(PtrVal)) { 429 if (Inst->mayReadOrWriteMemory()) { 430 // Scan all the alias sets to see if this call site is contained. 431 for (iterator I = begin(), E = end(); I != E;) { 432 iterator Cur = I++; 433 if (!Cur->Forward) 434 Cur->removeUnknownInst(*this, Inst); 435 } 436 } 437 } 438 439 // First, look up the PointerRec for this pointer. 440 PointerMapType::iterator I = PointerMap.find_as(PtrVal); 441 if (I == PointerMap.end()) return; // Noop 442 443 // If we found one, remove the pointer from the alias set it is in. 444 AliasSet::PointerRec *PtrValEnt = I->second; 445 AliasSet *AS = PtrValEnt->getAliasSet(*this); 446 447 // Unlink and delete from the list of values. 448 PtrValEnt->eraseFromList(); 449 450 // Stop using the alias set. 451 AS->dropRef(*this); 452 453 PointerMap.erase(I); 454 } 455 456 // copyValue - This method should be used whenever a preexisting value in the 457 // program is copied or cloned, introducing a new value. Note that it is ok for 458 // clients that use this method to introduce the same value multiple times: if 459 // the tracker already knows about a value, it will ignore the request. 460 // 461 void AliasSetTracker::copyValue(Value *From, Value *To) { 462 // First, look up the PointerRec for this pointer. 463 PointerMapType::iterator I = PointerMap.find_as(From); 464 if (I == PointerMap.end()) 465 return; // Noop 466 assert(I->second->hasAliasSet() && "Dead entry?"); 467 468 AliasSet::PointerRec &Entry = getEntryFor(To); 469 if (Entry.hasAliasSet()) return; // Already in the tracker! 470 471 // getEntryFor above may invalidate iterator \c I, so reinitialize it. 472 I = PointerMap.find_as(From); 473 // Add it to the alias set it aliases... 474 AliasSet *AS = I->second->getAliasSet(*this); 475 AS->addPointer(*this, Entry, I->second->getSize(), 476 I->second->getAAInfo(), 477 true); 478 } 479 480 481 482 //===----------------------------------------------------------------------===// 483 // AliasSet/AliasSetTracker Printing Support 484 //===----------------------------------------------------------------------===// 485 486 void AliasSet::print(raw_ostream &OS) const { 487 OS << " AliasSet[" << (const void*)this << ", " << RefCount << "] "; 488 OS << (Alias == SetMustAlias ? "must" : "may") << " alias, "; 489 switch (Access) { 490 case NoAccess: OS << "No access "; break; 491 case RefAccess: OS << "Ref "; break; 492 case ModAccess: OS << "Mod "; break; 493 case ModRefAccess: OS << "Mod/Ref "; break; 494 default: llvm_unreachable("Bad value for Access!"); 495 } 496 if (isVolatile()) OS << "[volatile] "; 497 if (Forward) 498 OS << " forwarding to " << (void*)Forward; 499 500 501 if (!empty()) { 502 OS << "Pointers: "; 503 for (iterator I = begin(), E = end(); I != E; ++I) { 504 if (I != begin()) OS << ", "; 505 I.getPointer()->printAsOperand(OS << "("); 506 OS << ", " << I.getSize() << ")"; 507 } 508 } 509 if (!UnknownInsts.empty()) { 510 OS << "\n " << UnknownInsts.size() << " Unknown instructions: "; 511 for (unsigned i = 0, e = UnknownInsts.size(); i != e; ++i) { 512 if (i) OS << ", "; 513 UnknownInsts[i]->printAsOperand(OS); 514 } 515 } 516 OS << "\n"; 517 } 518 519 void AliasSetTracker::print(raw_ostream &OS) const { 520 OS << "Alias Set Tracker: " << AliasSets.size() << " alias sets for " 521 << PointerMap.size() << " pointer values.\n"; 522 for (const AliasSet &AS : *this) 523 AS.print(OS); 524 OS << "\n"; 525 } 526 527 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 528 LLVM_DUMP_METHOD void AliasSet::dump() const { print(dbgs()); } 529 LLVM_DUMP_METHOD void AliasSetTracker::dump() const { print(dbgs()); } 530 #endif 531 532 //===----------------------------------------------------------------------===// 533 // ASTCallbackVH Class Implementation 534 //===----------------------------------------------------------------------===// 535 536 void AliasSetTracker::ASTCallbackVH::deleted() { 537 assert(AST && "ASTCallbackVH called with a null AliasSetTracker!"); 538 AST->deleteValue(getValPtr()); 539 // this now dangles! 540 } 541 542 void AliasSetTracker::ASTCallbackVH::allUsesReplacedWith(Value *V) { 543 AST->copyValue(getValPtr(), V); 544 } 545 546 AliasSetTracker::ASTCallbackVH::ASTCallbackVH(Value *V, AliasSetTracker *ast) 547 : CallbackVH(V), AST(ast) {} 548 549 AliasSetTracker::ASTCallbackVH & 550 AliasSetTracker::ASTCallbackVH::operator=(Value *V) { 551 return *this = ASTCallbackVH(V, AST); 552 } 553 554 //===----------------------------------------------------------------------===// 555 // AliasSetPrinter Pass 556 //===----------------------------------------------------------------------===// 557 558 namespace { 559 class AliasSetPrinter : public FunctionPass { 560 AliasSetTracker *Tracker; 561 public: 562 static char ID; // Pass identification, replacement for typeid 563 AliasSetPrinter() : FunctionPass(ID) { 564 initializeAliasSetPrinterPass(*PassRegistry::getPassRegistry()); 565 } 566 567 void getAnalysisUsage(AnalysisUsage &AU) const override { 568 AU.setPreservesAll(); 569 AU.addRequired<AAResultsWrapperPass>(); 570 } 571 572 bool runOnFunction(Function &F) override { 573 auto &AAWP = getAnalysis<AAResultsWrapperPass>(); 574 Tracker = new AliasSetTracker(AAWP.getAAResults()); 575 576 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I) 577 Tracker->add(&*I); 578 Tracker->print(errs()); 579 delete Tracker; 580 return false; 581 } 582 }; 583 } 584 585 char AliasSetPrinter::ID = 0; 586 INITIALIZE_PASS_BEGIN(AliasSetPrinter, "print-alias-sets", 587 "Alias Set Printer", false, true) 588 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) 589 INITIALIZE_PASS_END(AliasSetPrinter, "print-alias-sets", 590 "Alias Set Printer", false, true) 591