1 //==- AliasAnalysis.cpp - Generic Alias Analysis Interface 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 generic AliasAnalysis interface which is used as the 10 // common interface used by all clients and implementations of alias analysis. 11 // 12 // This file also implements the default version of the AliasAnalysis interface 13 // that is to be used when no other implementation is specified. This does some 14 // simple tests that detect obvious cases: two different global pointers cannot 15 // alias, a global cannot alias a malloc, two different mallocs cannot alias, 16 // etc. 17 // 18 // This alias analysis implementation really isn't very good for anything, but 19 // it is very fast, and makes a nice clean default implementation. Because it 20 // handles lots of little corner cases, other, more complex, alias analysis 21 // implementations may choose to rely on this pass to resolve these simple and 22 // easy cases. 23 // 24 //===----------------------------------------------------------------------===// 25 26 #include "llvm/Analysis/AliasAnalysis.h" 27 #include "llvm/ADT/Statistic.h" 28 #include "llvm/Analysis/BasicAliasAnalysis.h" 29 #include "llvm/Analysis/CFLAndersAliasAnalysis.h" 30 #include "llvm/Analysis/CFLSteensAliasAnalysis.h" 31 #include "llvm/Analysis/CaptureTracking.h" 32 #include "llvm/Analysis/GlobalsModRef.h" 33 #include "llvm/Analysis/MemoryLocation.h" 34 #include "llvm/Analysis/ObjCARCAliasAnalysis.h" 35 #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h" 36 #include "llvm/Analysis/ScopedNoAliasAA.h" 37 #include "llvm/Analysis/TargetLibraryInfo.h" 38 #include "llvm/Analysis/TypeBasedAliasAnalysis.h" 39 #include "llvm/Analysis/ValueTracking.h" 40 #include "llvm/IR/Argument.h" 41 #include "llvm/IR/Attributes.h" 42 #include "llvm/IR/BasicBlock.h" 43 #include "llvm/IR/Instruction.h" 44 #include "llvm/IR/Instructions.h" 45 #include "llvm/IR/Module.h" 46 #include "llvm/IR/Type.h" 47 #include "llvm/IR/Value.h" 48 #include "llvm/InitializePasses.h" 49 #include "llvm/Pass.h" 50 #include "llvm/Support/AtomicOrdering.h" 51 #include "llvm/Support/Casting.h" 52 #include "llvm/Support/CommandLine.h" 53 #include <algorithm> 54 #include <cassert> 55 #include <functional> 56 #include <iterator> 57 58 #define DEBUG_TYPE "aa" 59 60 using namespace llvm; 61 62 STATISTIC(NumNoAlias, "Number of NoAlias results"); 63 STATISTIC(NumMayAlias, "Number of MayAlias results"); 64 STATISTIC(NumMustAlias, "Number of MustAlias results"); 65 66 namespace llvm { 67 /// Allow disabling BasicAA from the AA results. This is particularly useful 68 /// when testing to isolate a single AA implementation. 69 cl::opt<bool> DisableBasicAA("disable-basic-aa", cl::Hidden, cl::init(false)); 70 } // namespace llvm 71 72 #ifndef NDEBUG 73 /// Print a trace of alias analysis queries and their results. 74 static cl::opt<bool> EnableAATrace("aa-trace", cl::Hidden, cl::init(false)); 75 #else 76 static const bool EnableAATrace = false; 77 #endif 78 79 AAResults::AAResults(AAResults &&Arg) 80 : TLI(Arg.TLI), AAs(std::move(Arg.AAs)), AADeps(std::move(Arg.AADeps)) { 81 for (auto &AA : AAs) 82 AA->setAAResults(this); 83 } 84 85 AAResults::~AAResults() { 86 // FIXME; It would be nice to at least clear out the pointers back to this 87 // aggregation here, but we end up with non-nesting lifetimes in the legacy 88 // pass manager that prevent this from working. In the legacy pass manager 89 // we'll end up with dangling references here in some cases. 90 #if 0 91 for (auto &AA : AAs) 92 AA->setAAResults(nullptr); 93 #endif 94 } 95 96 bool AAResults::invalidate(Function &F, const PreservedAnalyses &PA, 97 FunctionAnalysisManager::Invalidator &Inv) { 98 // AAResults preserves the AAManager by default, due to the stateless nature 99 // of AliasAnalysis. There is no need to check whether it has been preserved 100 // explicitly. Check if any module dependency was invalidated and caused the 101 // AAManager to be invalidated. Invalidate ourselves in that case. 102 auto PAC = PA.getChecker<AAManager>(); 103 if (!PAC.preservedWhenStateless()) 104 return true; 105 106 // Check if any of the function dependencies were invalidated, and invalidate 107 // ourselves in that case. 108 for (AnalysisKey *ID : AADeps) 109 if (Inv.invalidate(ID, F, PA)) 110 return true; 111 112 // Everything we depend on is still fine, so are we. Nothing to invalidate. 113 return false; 114 } 115 116 //===----------------------------------------------------------------------===// 117 // Default chaining methods 118 //===----------------------------------------------------------------------===// 119 120 AliasResult AAResults::alias(const MemoryLocation &LocA, 121 const MemoryLocation &LocB) { 122 SimpleAAQueryInfo AAQIP; 123 return alias(LocA, LocB, AAQIP); 124 } 125 126 AliasResult AAResults::alias(const MemoryLocation &LocA, 127 const MemoryLocation &LocB, AAQueryInfo &AAQI) { 128 AliasResult Result = AliasResult::MayAlias; 129 130 if (EnableAATrace) { 131 for (unsigned I = 0; I < AAQI.Depth; ++I) 132 dbgs() << " "; 133 dbgs() << "Start " << *LocA.Ptr << " @ " << LocA.Size << ", " 134 << *LocB.Ptr << " @ " << LocB.Size << "\n"; 135 } 136 137 AAQI.Depth++; 138 for (const auto &AA : AAs) { 139 Result = AA->alias(LocA, LocB, AAQI); 140 if (Result != AliasResult::MayAlias) 141 break; 142 } 143 AAQI.Depth--; 144 145 if (EnableAATrace) { 146 for (unsigned I = 0; I < AAQI.Depth; ++I) 147 dbgs() << " "; 148 dbgs() << "End " << *LocA.Ptr << " @ " << LocA.Size << ", " 149 << *LocB.Ptr << " @ " << LocB.Size << " = " << Result << "\n"; 150 } 151 152 if (AAQI.Depth == 0) { 153 if (Result == AliasResult::NoAlias) 154 ++NumNoAlias; 155 else if (Result == AliasResult::MustAlias) 156 ++NumMustAlias; 157 else 158 ++NumMayAlias; 159 } 160 return Result; 161 } 162 163 bool AAResults::pointsToConstantMemory(const MemoryLocation &Loc, 164 bool OrLocal) { 165 SimpleAAQueryInfo AAQIP; 166 return pointsToConstantMemory(Loc, AAQIP, OrLocal); 167 } 168 169 bool AAResults::pointsToConstantMemory(const MemoryLocation &Loc, 170 AAQueryInfo &AAQI, bool OrLocal) { 171 for (const auto &AA : AAs) 172 if (AA->pointsToConstantMemory(Loc, AAQI, OrLocal)) 173 return true; 174 175 return false; 176 } 177 178 ModRefInfo AAResults::getArgModRefInfo(const CallBase *Call, unsigned ArgIdx) { 179 ModRefInfo Result = ModRefInfo::ModRef; 180 181 for (const auto &AA : AAs) { 182 Result = intersectModRef(Result, AA->getArgModRefInfo(Call, ArgIdx)); 183 184 // Early-exit the moment we reach the bottom of the lattice. 185 if (isNoModRef(Result)) 186 return ModRefInfo::NoModRef; 187 } 188 189 return Result; 190 } 191 192 ModRefInfo AAResults::getModRefInfo(Instruction *I, const CallBase *Call2) { 193 SimpleAAQueryInfo AAQIP; 194 return getModRefInfo(I, Call2, AAQIP); 195 } 196 197 ModRefInfo AAResults::getModRefInfo(Instruction *I, const CallBase *Call2, 198 AAQueryInfo &AAQI) { 199 // We may have two calls. 200 if (const auto *Call1 = dyn_cast<CallBase>(I)) { 201 // Check if the two calls modify the same memory. 202 return getModRefInfo(Call1, Call2, AAQI); 203 } 204 // If this is a fence, just return ModRef. 205 if (I->isFenceLike()) 206 return ModRefInfo::ModRef; 207 // Otherwise, check if the call modifies or references the 208 // location this memory access defines. The best we can say 209 // is that if the call references what this instruction 210 // defines, it must be clobbered by this location. 211 const MemoryLocation DefLoc = MemoryLocation::get(I); 212 ModRefInfo MR = getModRefInfo(Call2, DefLoc, AAQI); 213 if (isModOrRefSet(MR)) 214 return setModAndRef(MR); 215 return ModRefInfo::NoModRef; 216 } 217 218 ModRefInfo AAResults::getModRefInfo(const CallBase *Call, 219 const MemoryLocation &Loc) { 220 SimpleAAQueryInfo AAQIP; 221 return getModRefInfo(Call, Loc, AAQIP); 222 } 223 224 ModRefInfo AAResults::getModRefInfo(const CallBase *Call, 225 const MemoryLocation &Loc, 226 AAQueryInfo &AAQI) { 227 ModRefInfo Result = ModRefInfo::ModRef; 228 229 for (const auto &AA : AAs) { 230 Result = intersectModRef(Result, AA->getModRefInfo(Call, Loc, AAQI)); 231 232 // Early-exit the moment we reach the bottom of the lattice. 233 if (isNoModRef(Result)) 234 return ModRefInfo::NoModRef; 235 } 236 237 // Try to refine the mod-ref info further using other API entry points to the 238 // aggregate set of AA results. 239 auto MRB = getModRefBehavior(Call); 240 if (onlyAccessesInaccessibleMem(MRB)) 241 return ModRefInfo::NoModRef; 242 243 if (onlyReadsMemory(MRB)) 244 Result = clearMod(Result); 245 else if (onlyWritesMemory(MRB)) 246 Result = clearRef(Result); 247 248 if (onlyAccessesArgPointees(MRB) || onlyAccessesInaccessibleOrArgMem(MRB)) { 249 bool IsMustAlias = true; 250 ModRefInfo AllArgsMask = ModRefInfo::NoModRef; 251 if (doesAccessArgPointees(MRB)) { 252 for (const auto &I : llvm::enumerate(Call->args())) { 253 const Value *Arg = I.value(); 254 if (!Arg->getType()->isPointerTy()) 255 continue; 256 unsigned ArgIdx = I.index(); 257 MemoryLocation ArgLoc = 258 MemoryLocation::getForArgument(Call, ArgIdx, TLI); 259 AliasResult ArgAlias = alias(ArgLoc, Loc, AAQI); 260 if (ArgAlias != AliasResult::NoAlias) { 261 ModRefInfo ArgMask = getArgModRefInfo(Call, ArgIdx); 262 AllArgsMask = unionModRef(AllArgsMask, ArgMask); 263 } 264 // Conservatively clear IsMustAlias unless only MustAlias is found. 265 IsMustAlias &= (ArgAlias == AliasResult::MustAlias); 266 } 267 } 268 // Return NoModRef if no alias found with any argument. 269 if (isNoModRef(AllArgsMask)) 270 return ModRefInfo::NoModRef; 271 // Logical & between other AA analyses and argument analysis. 272 Result = intersectModRef(Result, AllArgsMask); 273 // If only MustAlias found above, set Must bit. 274 Result = IsMustAlias ? setMust(Result) : clearMust(Result); 275 } 276 277 // If Loc is a constant memory location, the call definitely could not 278 // modify the memory location. 279 if (isModSet(Result) && pointsToConstantMemory(Loc, AAQI, /*OrLocal*/ false)) 280 Result = clearMod(Result); 281 282 return Result; 283 } 284 285 ModRefInfo AAResults::getModRefInfo(const CallBase *Call1, 286 const CallBase *Call2) { 287 SimpleAAQueryInfo AAQIP; 288 return getModRefInfo(Call1, Call2, AAQIP); 289 } 290 291 ModRefInfo AAResults::getModRefInfo(const CallBase *Call1, 292 const CallBase *Call2, AAQueryInfo &AAQI) { 293 ModRefInfo Result = ModRefInfo::ModRef; 294 295 for (const auto &AA : AAs) { 296 Result = intersectModRef(Result, AA->getModRefInfo(Call1, Call2, AAQI)); 297 298 // Early-exit the moment we reach the bottom of the lattice. 299 if (isNoModRef(Result)) 300 return ModRefInfo::NoModRef; 301 } 302 303 // Try to refine the mod-ref info further using other API entry points to the 304 // aggregate set of AA results. 305 306 // If Call1 or Call2 are readnone, they don't interact. 307 auto Call1B = getModRefBehavior(Call1); 308 if (Call1B == FMRB_DoesNotAccessMemory) 309 return ModRefInfo::NoModRef; 310 311 auto Call2B = getModRefBehavior(Call2); 312 if (Call2B == FMRB_DoesNotAccessMemory) 313 return ModRefInfo::NoModRef; 314 315 // If they both only read from memory, there is no dependence. 316 if (onlyReadsMemory(Call1B) && onlyReadsMemory(Call2B)) 317 return ModRefInfo::NoModRef; 318 319 // If Call1 only reads memory, the only dependence on Call2 can be 320 // from Call1 reading memory written by Call2. 321 if (onlyReadsMemory(Call1B)) 322 Result = clearMod(Result); 323 else if (onlyWritesMemory(Call1B)) 324 Result = clearRef(Result); 325 326 // If Call2 only access memory through arguments, accumulate the mod/ref 327 // information from Call1's references to the memory referenced by 328 // Call2's arguments. 329 if (onlyAccessesArgPointees(Call2B)) { 330 if (!doesAccessArgPointees(Call2B)) 331 return ModRefInfo::NoModRef; 332 ModRefInfo R = ModRefInfo::NoModRef; 333 bool IsMustAlias = true; 334 for (auto I = Call2->arg_begin(), E = Call2->arg_end(); I != E; ++I) { 335 const Value *Arg = *I; 336 if (!Arg->getType()->isPointerTy()) 337 continue; 338 unsigned Call2ArgIdx = std::distance(Call2->arg_begin(), I); 339 auto Call2ArgLoc = 340 MemoryLocation::getForArgument(Call2, Call2ArgIdx, TLI); 341 342 // ArgModRefC2 indicates what Call2 might do to Call2ArgLoc, and the 343 // dependence of Call1 on that location is the inverse: 344 // - If Call2 modifies location, dependence exists if Call1 reads or 345 // writes. 346 // - If Call2 only reads location, dependence exists if Call1 writes. 347 ModRefInfo ArgModRefC2 = getArgModRefInfo(Call2, Call2ArgIdx); 348 ModRefInfo ArgMask = ModRefInfo::NoModRef; 349 if (isModSet(ArgModRefC2)) 350 ArgMask = ModRefInfo::ModRef; 351 else if (isRefSet(ArgModRefC2)) 352 ArgMask = ModRefInfo::Mod; 353 354 // ModRefC1 indicates what Call1 might do to Call2ArgLoc, and we use 355 // above ArgMask to update dependence info. 356 ModRefInfo ModRefC1 = getModRefInfo(Call1, Call2ArgLoc, AAQI); 357 ArgMask = intersectModRef(ArgMask, ModRefC1); 358 359 // Conservatively clear IsMustAlias unless only MustAlias is found. 360 IsMustAlias &= isMustSet(ModRefC1); 361 362 R = intersectModRef(unionModRef(R, ArgMask), Result); 363 if (R == Result) { 364 // On early exit, not all args were checked, cannot set Must. 365 if (I + 1 != E) 366 IsMustAlias = false; 367 break; 368 } 369 } 370 371 if (isNoModRef(R)) 372 return ModRefInfo::NoModRef; 373 374 // If MustAlias found above, set Must bit. 375 return IsMustAlias ? setMust(R) : clearMust(R); 376 } 377 378 // If Call1 only accesses memory through arguments, check if Call2 references 379 // any of the memory referenced by Call1's arguments. If not, return NoModRef. 380 if (onlyAccessesArgPointees(Call1B)) { 381 if (!doesAccessArgPointees(Call1B)) 382 return ModRefInfo::NoModRef; 383 ModRefInfo R = ModRefInfo::NoModRef; 384 bool IsMustAlias = true; 385 for (auto I = Call1->arg_begin(), E = Call1->arg_end(); I != E; ++I) { 386 const Value *Arg = *I; 387 if (!Arg->getType()->isPointerTy()) 388 continue; 389 unsigned Call1ArgIdx = std::distance(Call1->arg_begin(), I); 390 auto Call1ArgLoc = 391 MemoryLocation::getForArgument(Call1, Call1ArgIdx, TLI); 392 393 // ArgModRefC1 indicates what Call1 might do to Call1ArgLoc; if Call1 394 // might Mod Call1ArgLoc, then we care about either a Mod or a Ref by 395 // Call2. If Call1 might Ref, then we care only about a Mod by Call2. 396 ModRefInfo ArgModRefC1 = getArgModRefInfo(Call1, Call1ArgIdx); 397 ModRefInfo ModRefC2 = getModRefInfo(Call2, Call1ArgLoc, AAQI); 398 if ((isModSet(ArgModRefC1) && isModOrRefSet(ModRefC2)) || 399 (isRefSet(ArgModRefC1) && isModSet(ModRefC2))) 400 R = intersectModRef(unionModRef(R, ArgModRefC1), Result); 401 402 // Conservatively clear IsMustAlias unless only MustAlias is found. 403 IsMustAlias &= isMustSet(ModRefC2); 404 405 if (R == Result) { 406 // On early exit, not all args were checked, cannot set Must. 407 if (I + 1 != E) 408 IsMustAlias = false; 409 break; 410 } 411 } 412 413 if (isNoModRef(R)) 414 return ModRefInfo::NoModRef; 415 416 // If MustAlias found above, set Must bit. 417 return IsMustAlias ? setMust(R) : clearMust(R); 418 } 419 420 return Result; 421 } 422 423 FunctionModRefBehavior AAResults::getModRefBehavior(const CallBase *Call) { 424 FunctionModRefBehavior Result = FMRB_UnknownModRefBehavior; 425 426 for (const auto &AA : AAs) { 427 Result = FunctionModRefBehavior(Result & AA->getModRefBehavior(Call)); 428 429 // Early-exit the moment we reach the bottom of the lattice. 430 if (Result == FMRB_DoesNotAccessMemory) 431 return Result; 432 } 433 434 return Result; 435 } 436 437 FunctionModRefBehavior AAResults::getModRefBehavior(const Function *F) { 438 FunctionModRefBehavior Result = FMRB_UnknownModRefBehavior; 439 440 for (const auto &AA : AAs) { 441 Result = FunctionModRefBehavior(Result & AA->getModRefBehavior(F)); 442 443 // Early-exit the moment we reach the bottom of the lattice. 444 if (Result == FMRB_DoesNotAccessMemory) 445 return Result; 446 } 447 448 return Result; 449 } 450 451 raw_ostream &llvm::operator<<(raw_ostream &OS, AliasResult AR) { 452 switch (AR) { 453 case AliasResult::NoAlias: 454 OS << "NoAlias"; 455 break; 456 case AliasResult::MustAlias: 457 OS << "MustAlias"; 458 break; 459 case AliasResult::MayAlias: 460 OS << "MayAlias"; 461 break; 462 case AliasResult::PartialAlias: 463 OS << "PartialAlias"; 464 if (AR.hasOffset()) 465 OS << " (off " << AR.getOffset() << ")"; 466 break; 467 } 468 return OS; 469 } 470 471 //===----------------------------------------------------------------------===// 472 // Helper method implementation 473 //===----------------------------------------------------------------------===// 474 475 ModRefInfo AAResults::getModRefInfo(const LoadInst *L, 476 const MemoryLocation &Loc) { 477 SimpleAAQueryInfo AAQIP; 478 return getModRefInfo(L, Loc, AAQIP); 479 } 480 ModRefInfo AAResults::getModRefInfo(const LoadInst *L, 481 const MemoryLocation &Loc, 482 AAQueryInfo &AAQI) { 483 // Be conservative in the face of atomic. 484 if (isStrongerThan(L->getOrdering(), AtomicOrdering::Unordered)) 485 return ModRefInfo::ModRef; 486 487 // If the load address doesn't alias the given address, it doesn't read 488 // or write the specified memory. 489 if (Loc.Ptr) { 490 AliasResult AR = alias(MemoryLocation::get(L), Loc, AAQI); 491 if (AR == AliasResult::NoAlias) 492 return ModRefInfo::NoModRef; 493 if (AR == AliasResult::MustAlias) 494 return ModRefInfo::MustRef; 495 } 496 // Otherwise, a load just reads. 497 return ModRefInfo::Ref; 498 } 499 500 ModRefInfo AAResults::getModRefInfo(const StoreInst *S, 501 const MemoryLocation &Loc) { 502 SimpleAAQueryInfo AAQIP; 503 return getModRefInfo(S, Loc, AAQIP); 504 } 505 ModRefInfo AAResults::getModRefInfo(const StoreInst *S, 506 const MemoryLocation &Loc, 507 AAQueryInfo &AAQI) { 508 // Be conservative in the face of atomic. 509 if (isStrongerThan(S->getOrdering(), AtomicOrdering::Unordered)) 510 return ModRefInfo::ModRef; 511 512 if (Loc.Ptr) { 513 AliasResult AR = alias(MemoryLocation::get(S), Loc, AAQI); 514 // If the store address cannot alias the pointer in question, then the 515 // specified memory cannot be modified by the store. 516 if (AR == AliasResult::NoAlias) 517 return ModRefInfo::NoModRef; 518 519 // If the pointer is a pointer to constant memory, then it could not have 520 // been modified by this store. 521 if (pointsToConstantMemory(Loc, AAQI)) 522 return ModRefInfo::NoModRef; 523 524 // If the store address aliases the pointer as must alias, set Must. 525 if (AR == AliasResult::MustAlias) 526 return ModRefInfo::MustMod; 527 } 528 529 // Otherwise, a store just writes. 530 return ModRefInfo::Mod; 531 } 532 533 ModRefInfo AAResults::getModRefInfo(const FenceInst *S, const MemoryLocation &Loc) { 534 SimpleAAQueryInfo AAQIP; 535 return getModRefInfo(S, Loc, AAQIP); 536 } 537 538 ModRefInfo AAResults::getModRefInfo(const FenceInst *S, 539 const MemoryLocation &Loc, 540 AAQueryInfo &AAQI) { 541 // If we know that the location is a constant memory location, the fence 542 // cannot modify this location. 543 if (Loc.Ptr && pointsToConstantMemory(Loc, AAQI)) 544 return ModRefInfo::Ref; 545 return ModRefInfo::ModRef; 546 } 547 548 ModRefInfo AAResults::getModRefInfo(const VAArgInst *V, 549 const MemoryLocation &Loc) { 550 SimpleAAQueryInfo AAQIP; 551 return getModRefInfo(V, Loc, AAQIP); 552 } 553 554 ModRefInfo AAResults::getModRefInfo(const VAArgInst *V, 555 const MemoryLocation &Loc, 556 AAQueryInfo &AAQI) { 557 if (Loc.Ptr) { 558 AliasResult AR = alias(MemoryLocation::get(V), Loc, AAQI); 559 // If the va_arg address cannot alias the pointer in question, then the 560 // specified memory cannot be accessed by the va_arg. 561 if (AR == AliasResult::NoAlias) 562 return ModRefInfo::NoModRef; 563 564 // If the pointer is a pointer to constant memory, then it could not have 565 // been modified by this va_arg. 566 if (pointsToConstantMemory(Loc, AAQI)) 567 return ModRefInfo::NoModRef; 568 569 // If the va_arg aliases the pointer as must alias, set Must. 570 if (AR == AliasResult::MustAlias) 571 return ModRefInfo::MustModRef; 572 } 573 574 // Otherwise, a va_arg reads and writes. 575 return ModRefInfo::ModRef; 576 } 577 578 ModRefInfo AAResults::getModRefInfo(const CatchPadInst *CatchPad, 579 const MemoryLocation &Loc) { 580 SimpleAAQueryInfo AAQIP; 581 return getModRefInfo(CatchPad, Loc, AAQIP); 582 } 583 584 ModRefInfo AAResults::getModRefInfo(const CatchPadInst *CatchPad, 585 const MemoryLocation &Loc, 586 AAQueryInfo &AAQI) { 587 if (Loc.Ptr) { 588 // If the pointer is a pointer to constant memory, 589 // then it could not have been modified by this catchpad. 590 if (pointsToConstantMemory(Loc, AAQI)) 591 return ModRefInfo::NoModRef; 592 } 593 594 // Otherwise, a catchpad reads and writes. 595 return ModRefInfo::ModRef; 596 } 597 598 ModRefInfo AAResults::getModRefInfo(const CatchReturnInst *CatchRet, 599 const MemoryLocation &Loc) { 600 SimpleAAQueryInfo AAQIP; 601 return getModRefInfo(CatchRet, Loc, AAQIP); 602 } 603 604 ModRefInfo AAResults::getModRefInfo(const CatchReturnInst *CatchRet, 605 const MemoryLocation &Loc, 606 AAQueryInfo &AAQI) { 607 if (Loc.Ptr) { 608 // If the pointer is a pointer to constant memory, 609 // then it could not have been modified by this catchpad. 610 if (pointsToConstantMemory(Loc, AAQI)) 611 return ModRefInfo::NoModRef; 612 } 613 614 // Otherwise, a catchret reads and writes. 615 return ModRefInfo::ModRef; 616 } 617 618 ModRefInfo AAResults::getModRefInfo(const AtomicCmpXchgInst *CX, 619 const MemoryLocation &Loc) { 620 SimpleAAQueryInfo AAQIP; 621 return getModRefInfo(CX, Loc, AAQIP); 622 } 623 624 ModRefInfo AAResults::getModRefInfo(const AtomicCmpXchgInst *CX, 625 const MemoryLocation &Loc, 626 AAQueryInfo &AAQI) { 627 // Acquire/Release cmpxchg has properties that matter for arbitrary addresses. 628 if (isStrongerThanMonotonic(CX->getSuccessOrdering())) 629 return ModRefInfo::ModRef; 630 631 if (Loc.Ptr) { 632 AliasResult AR = alias(MemoryLocation::get(CX), Loc, AAQI); 633 // If the cmpxchg address does not alias the location, it does not access 634 // it. 635 if (AR == AliasResult::NoAlias) 636 return ModRefInfo::NoModRef; 637 638 // If the cmpxchg address aliases the pointer as must alias, set Must. 639 if (AR == AliasResult::MustAlias) 640 return ModRefInfo::MustModRef; 641 } 642 643 return ModRefInfo::ModRef; 644 } 645 646 ModRefInfo AAResults::getModRefInfo(const AtomicRMWInst *RMW, 647 const MemoryLocation &Loc) { 648 SimpleAAQueryInfo AAQIP; 649 return getModRefInfo(RMW, Loc, AAQIP); 650 } 651 652 ModRefInfo AAResults::getModRefInfo(const AtomicRMWInst *RMW, 653 const MemoryLocation &Loc, 654 AAQueryInfo &AAQI) { 655 // Acquire/Release atomicrmw has properties that matter for arbitrary addresses. 656 if (isStrongerThanMonotonic(RMW->getOrdering())) 657 return ModRefInfo::ModRef; 658 659 if (Loc.Ptr) { 660 AliasResult AR = alias(MemoryLocation::get(RMW), Loc, AAQI); 661 // If the atomicrmw address does not alias the location, it does not access 662 // it. 663 if (AR == AliasResult::NoAlias) 664 return ModRefInfo::NoModRef; 665 666 // If the atomicrmw address aliases the pointer as must alias, set Must. 667 if (AR == AliasResult::MustAlias) 668 return ModRefInfo::MustModRef; 669 } 670 671 return ModRefInfo::ModRef; 672 } 673 674 ModRefInfo AAResults::getModRefInfo(const Instruction *I, 675 const Optional<MemoryLocation> &OptLoc, 676 AAQueryInfo &AAQIP) { 677 if (OptLoc == None) { 678 if (const auto *Call = dyn_cast<CallBase>(I)) { 679 return createModRefInfo(getModRefBehavior(Call)); 680 } 681 } 682 683 const MemoryLocation &Loc = OptLoc.getValueOr(MemoryLocation()); 684 685 switch (I->getOpcode()) { 686 case Instruction::VAArg: 687 return getModRefInfo((const VAArgInst *)I, Loc, AAQIP); 688 case Instruction::Load: 689 return getModRefInfo((const LoadInst *)I, Loc, AAQIP); 690 case Instruction::Store: 691 return getModRefInfo((const StoreInst *)I, Loc, AAQIP); 692 case Instruction::Fence: 693 return getModRefInfo((const FenceInst *)I, Loc, AAQIP); 694 case Instruction::AtomicCmpXchg: 695 return getModRefInfo((const AtomicCmpXchgInst *)I, Loc, AAQIP); 696 case Instruction::AtomicRMW: 697 return getModRefInfo((const AtomicRMWInst *)I, Loc, AAQIP); 698 case Instruction::Call: 699 case Instruction::CallBr: 700 case Instruction::Invoke: 701 return getModRefInfo((const CallBase *)I, Loc, AAQIP); 702 case Instruction::CatchPad: 703 return getModRefInfo((const CatchPadInst *)I, Loc, AAQIP); 704 case Instruction::CatchRet: 705 return getModRefInfo((const CatchReturnInst *)I, Loc, AAQIP); 706 default: 707 assert(!I->mayReadOrWriteMemory() && 708 "Unhandled memory access instruction!"); 709 return ModRefInfo::NoModRef; 710 } 711 } 712 713 /// Return information about whether a particular call site modifies 714 /// or reads the specified memory location \p MemLoc before instruction \p I 715 /// in a BasicBlock. 716 /// FIXME: this is really just shoring-up a deficiency in alias analysis. 717 /// BasicAA isn't willing to spend linear time determining whether an alloca 718 /// was captured before or after this particular call, while we are. However, 719 /// with a smarter AA in place, this test is just wasting compile time. 720 ModRefInfo AAResults::callCapturesBefore(const Instruction *I, 721 const MemoryLocation &MemLoc, 722 DominatorTree *DT, 723 AAQueryInfo &AAQI) { 724 if (!DT) 725 return ModRefInfo::ModRef; 726 727 const Value *Object = getUnderlyingObject(MemLoc.Ptr); 728 if (!isIdentifiedFunctionLocal(Object)) 729 return ModRefInfo::ModRef; 730 731 const auto *Call = dyn_cast<CallBase>(I); 732 if (!Call || Call == Object) 733 return ModRefInfo::ModRef; 734 735 if (PointerMayBeCapturedBefore(Object, /* ReturnCaptures */ true, 736 /* StoreCaptures */ true, I, DT, 737 /* include Object */ true)) 738 return ModRefInfo::ModRef; 739 740 unsigned ArgNo = 0; 741 ModRefInfo R = ModRefInfo::NoModRef; 742 bool IsMustAlias = true; 743 // Set flag only if no May found and all operands processed. 744 for (auto CI = Call->data_operands_begin(), CE = Call->data_operands_end(); 745 CI != CE; ++CI, ++ArgNo) { 746 // Only look at the no-capture or byval pointer arguments. If this 747 // pointer were passed to arguments that were neither of these, then it 748 // couldn't be no-capture. 749 if (!(*CI)->getType()->isPointerTy() || 750 (!Call->doesNotCapture(ArgNo) && ArgNo < Call->arg_size() && 751 !Call->isByValArgument(ArgNo))) 752 continue; 753 754 AliasResult AR = alias( 755 MemoryLocation::getBeforeOrAfter(*CI), 756 MemoryLocation::getBeforeOrAfter(Object), AAQI); 757 // If this is a no-capture pointer argument, see if we can tell that it 758 // is impossible to alias the pointer we're checking. If not, we have to 759 // assume that the call could touch the pointer, even though it doesn't 760 // escape. 761 if (AR != AliasResult::MustAlias) 762 IsMustAlias = false; 763 if (AR == AliasResult::NoAlias) 764 continue; 765 if (Call->doesNotAccessMemory(ArgNo)) 766 continue; 767 if (Call->onlyReadsMemory(ArgNo)) { 768 R = ModRefInfo::Ref; 769 continue; 770 } 771 // Not returning MustModRef since we have not seen all the arguments. 772 return ModRefInfo::ModRef; 773 } 774 return IsMustAlias ? setMust(R) : clearMust(R); 775 } 776 777 /// canBasicBlockModify - Return true if it is possible for execution of the 778 /// specified basic block to modify the location Loc. 779 /// 780 bool AAResults::canBasicBlockModify(const BasicBlock &BB, 781 const MemoryLocation &Loc) { 782 return canInstructionRangeModRef(BB.front(), BB.back(), Loc, ModRefInfo::Mod); 783 } 784 785 /// canInstructionRangeModRef - Return true if it is possible for the 786 /// execution of the specified instructions to mod\ref (according to the 787 /// mode) the location Loc. The instructions to consider are all 788 /// of the instructions in the range of [I1,I2] INCLUSIVE. 789 /// I1 and I2 must be in the same basic block. 790 bool AAResults::canInstructionRangeModRef(const Instruction &I1, 791 const Instruction &I2, 792 const MemoryLocation &Loc, 793 const ModRefInfo Mode) { 794 assert(I1.getParent() == I2.getParent() && 795 "Instructions not in same basic block!"); 796 BasicBlock::const_iterator I = I1.getIterator(); 797 BasicBlock::const_iterator E = I2.getIterator(); 798 ++E; // Convert from inclusive to exclusive range. 799 800 for (; I != E; ++I) // Check every instruction in range 801 if (isModOrRefSet(intersectModRef(getModRefInfo(&*I, Loc), Mode))) 802 return true; 803 return false; 804 } 805 806 // Provide a definition for the root virtual destructor. 807 AAResults::Concept::~Concept() = default; 808 809 // Provide a definition for the static object used to identify passes. 810 AnalysisKey AAManager::Key; 811 812 ExternalAAWrapperPass::ExternalAAWrapperPass() : ImmutablePass(ID) { 813 initializeExternalAAWrapperPassPass(*PassRegistry::getPassRegistry()); 814 } 815 816 ExternalAAWrapperPass::ExternalAAWrapperPass(CallbackT CB) 817 : ImmutablePass(ID), CB(std::move(CB)) { 818 initializeExternalAAWrapperPassPass(*PassRegistry::getPassRegistry()); 819 } 820 821 char ExternalAAWrapperPass::ID = 0; 822 823 INITIALIZE_PASS(ExternalAAWrapperPass, "external-aa", "External Alias Analysis", 824 false, true) 825 826 ImmutablePass * 827 llvm::createExternalAAWrapperPass(ExternalAAWrapperPass::CallbackT Callback) { 828 return new ExternalAAWrapperPass(std::move(Callback)); 829 } 830 831 AAResultsWrapperPass::AAResultsWrapperPass() : FunctionPass(ID) { 832 initializeAAResultsWrapperPassPass(*PassRegistry::getPassRegistry()); 833 } 834 835 char AAResultsWrapperPass::ID = 0; 836 837 INITIALIZE_PASS_BEGIN(AAResultsWrapperPass, "aa", 838 "Function Alias Analysis Results", false, true) 839 INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass) 840 INITIALIZE_PASS_DEPENDENCY(CFLAndersAAWrapperPass) 841 INITIALIZE_PASS_DEPENDENCY(CFLSteensAAWrapperPass) 842 INITIALIZE_PASS_DEPENDENCY(ExternalAAWrapperPass) 843 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass) 844 INITIALIZE_PASS_DEPENDENCY(ObjCARCAAWrapperPass) 845 INITIALIZE_PASS_DEPENDENCY(SCEVAAWrapperPass) 846 INITIALIZE_PASS_DEPENDENCY(ScopedNoAliasAAWrapperPass) 847 INITIALIZE_PASS_DEPENDENCY(TypeBasedAAWrapperPass) 848 INITIALIZE_PASS_END(AAResultsWrapperPass, "aa", 849 "Function Alias Analysis Results", false, true) 850 851 FunctionPass *llvm::createAAResultsWrapperPass() { 852 return new AAResultsWrapperPass(); 853 } 854 855 /// Run the wrapper pass to rebuild an aggregation over known AA passes. 856 /// 857 /// This is the legacy pass manager's interface to the new-style AA results 858 /// aggregation object. Because this is somewhat shoe-horned into the legacy 859 /// pass manager, we hard code all the specific alias analyses available into 860 /// it. While the particular set enabled is configured via commandline flags, 861 /// adding a new alias analysis to LLVM will require adding support for it to 862 /// this list. 863 bool AAResultsWrapperPass::runOnFunction(Function &F) { 864 // NB! This *must* be reset before adding new AA results to the new 865 // AAResults object because in the legacy pass manager, each instance 866 // of these will refer to the *same* immutable analyses, registering and 867 // unregistering themselves with them. We need to carefully tear down the 868 // previous object first, in this case replacing it with an empty one, before 869 // registering new results. 870 AAR.reset( 871 new AAResults(getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F))); 872 873 // BasicAA is always available for function analyses. Also, we add it first 874 // so that it can trump TBAA results when it proves MustAlias. 875 // FIXME: TBAA should have an explicit mode to support this and then we 876 // should reconsider the ordering here. 877 if (!DisableBasicAA) 878 AAR->addAAResult(getAnalysis<BasicAAWrapperPass>().getResult()); 879 880 // Populate the results with the currently available AAs. 881 if (auto *WrapperPass = getAnalysisIfAvailable<ScopedNoAliasAAWrapperPass>()) 882 AAR->addAAResult(WrapperPass->getResult()); 883 if (auto *WrapperPass = getAnalysisIfAvailable<TypeBasedAAWrapperPass>()) 884 AAR->addAAResult(WrapperPass->getResult()); 885 if (auto *WrapperPass = 886 getAnalysisIfAvailable<objcarc::ObjCARCAAWrapperPass>()) 887 AAR->addAAResult(WrapperPass->getResult()); 888 if (auto *WrapperPass = getAnalysisIfAvailable<GlobalsAAWrapperPass>()) 889 AAR->addAAResult(WrapperPass->getResult()); 890 if (auto *WrapperPass = getAnalysisIfAvailable<SCEVAAWrapperPass>()) 891 AAR->addAAResult(WrapperPass->getResult()); 892 if (auto *WrapperPass = getAnalysisIfAvailable<CFLAndersAAWrapperPass>()) 893 AAR->addAAResult(WrapperPass->getResult()); 894 if (auto *WrapperPass = getAnalysisIfAvailable<CFLSteensAAWrapperPass>()) 895 AAR->addAAResult(WrapperPass->getResult()); 896 897 // If available, run an external AA providing callback over the results as 898 // well. 899 if (auto *WrapperPass = getAnalysisIfAvailable<ExternalAAWrapperPass>()) 900 if (WrapperPass->CB) 901 WrapperPass->CB(*this, F, *AAR); 902 903 // Analyses don't mutate the IR, so return false. 904 return false; 905 } 906 907 void AAResultsWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { 908 AU.setPreservesAll(); 909 AU.addRequiredTransitive<BasicAAWrapperPass>(); 910 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>(); 911 912 // We also need to mark all the alias analysis passes we will potentially 913 // probe in runOnFunction as used here to ensure the legacy pass manager 914 // preserves them. This hard coding of lists of alias analyses is specific to 915 // the legacy pass manager. 916 AU.addUsedIfAvailable<ScopedNoAliasAAWrapperPass>(); 917 AU.addUsedIfAvailable<TypeBasedAAWrapperPass>(); 918 AU.addUsedIfAvailable<objcarc::ObjCARCAAWrapperPass>(); 919 AU.addUsedIfAvailable<GlobalsAAWrapperPass>(); 920 AU.addUsedIfAvailable<SCEVAAWrapperPass>(); 921 AU.addUsedIfAvailable<CFLAndersAAWrapperPass>(); 922 AU.addUsedIfAvailable<CFLSteensAAWrapperPass>(); 923 AU.addUsedIfAvailable<ExternalAAWrapperPass>(); 924 } 925 926 AAManager::Result AAManager::run(Function &F, FunctionAnalysisManager &AM) { 927 Result R(AM.getResult<TargetLibraryAnalysis>(F)); 928 for (auto &Getter : ResultGetters) 929 (*Getter)(F, AM, R); 930 return R; 931 } 932 933 AAResults llvm::createLegacyPMAAResults(Pass &P, Function &F, 934 BasicAAResult &BAR) { 935 AAResults AAR(P.getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F)); 936 937 // Add in our explicitly constructed BasicAA results. 938 if (!DisableBasicAA) 939 AAR.addAAResult(BAR); 940 941 // Populate the results with the other currently available AAs. 942 if (auto *WrapperPass = 943 P.getAnalysisIfAvailable<ScopedNoAliasAAWrapperPass>()) 944 AAR.addAAResult(WrapperPass->getResult()); 945 if (auto *WrapperPass = P.getAnalysisIfAvailable<TypeBasedAAWrapperPass>()) 946 AAR.addAAResult(WrapperPass->getResult()); 947 if (auto *WrapperPass = 948 P.getAnalysisIfAvailable<objcarc::ObjCARCAAWrapperPass>()) 949 AAR.addAAResult(WrapperPass->getResult()); 950 if (auto *WrapperPass = P.getAnalysisIfAvailable<GlobalsAAWrapperPass>()) 951 AAR.addAAResult(WrapperPass->getResult()); 952 if (auto *WrapperPass = P.getAnalysisIfAvailable<CFLAndersAAWrapperPass>()) 953 AAR.addAAResult(WrapperPass->getResult()); 954 if (auto *WrapperPass = P.getAnalysisIfAvailable<CFLSteensAAWrapperPass>()) 955 AAR.addAAResult(WrapperPass->getResult()); 956 if (auto *WrapperPass = P.getAnalysisIfAvailable<ExternalAAWrapperPass>()) 957 if (WrapperPass->CB) 958 WrapperPass->CB(P, F, AAR); 959 960 return AAR; 961 } 962 963 bool llvm::isNoAliasCall(const Value *V) { 964 if (const auto *Call = dyn_cast<CallBase>(V)) 965 return Call->hasRetAttr(Attribute::NoAlias); 966 return false; 967 } 968 969 static bool isNoAliasOrByValArgument(const Value *V) { 970 if (const Argument *A = dyn_cast<Argument>(V)) 971 return A->hasNoAliasAttr() || A->hasByValAttr(); 972 return false; 973 } 974 975 bool llvm::isIdentifiedObject(const Value *V) { 976 if (isa<AllocaInst>(V)) 977 return true; 978 if (isa<GlobalValue>(V) && !isa<GlobalAlias>(V)) 979 return true; 980 if (isNoAliasCall(V)) 981 return true; 982 if (isNoAliasOrByValArgument(V)) 983 return true; 984 return false; 985 } 986 987 bool llvm::isIdentifiedFunctionLocal(const Value *V) { 988 return isa<AllocaInst>(V) || isNoAliasCall(V) || isNoAliasOrByValArgument(V); 989 } 990 991 bool llvm::isNotVisibleOnUnwind(const Value *Object, 992 bool &RequiresNoCaptureBeforeUnwind) { 993 RequiresNoCaptureBeforeUnwind = false; 994 995 // Alloca goes out of scope on unwind. 996 if (isa<AllocaInst>(Object)) 997 return true; 998 999 // Byval goes out of scope on unwind. 1000 if (auto *A = dyn_cast<Argument>(Object)) 1001 return A->hasByValAttr(); 1002 1003 // A noalias return is not accessible from any other code. If the pointer 1004 // does not escape prior to the unwind, then the caller cannot access the 1005 // memory either. 1006 if (isNoAliasCall(Object)) { 1007 RequiresNoCaptureBeforeUnwind = true; 1008 return true; 1009 } 1010 1011 return false; 1012 } 1013 1014 void llvm::getAAResultsAnalysisUsage(AnalysisUsage &AU) { 1015 // This function needs to be in sync with llvm::createLegacyPMAAResults -- if 1016 // more alias analyses are added to llvm::createLegacyPMAAResults, they need 1017 // to be added here also. 1018 AU.addRequired<TargetLibraryInfoWrapperPass>(); 1019 AU.addUsedIfAvailable<ScopedNoAliasAAWrapperPass>(); 1020 AU.addUsedIfAvailable<TypeBasedAAWrapperPass>(); 1021 AU.addUsedIfAvailable<objcarc::ObjCARCAAWrapperPass>(); 1022 AU.addUsedIfAvailable<GlobalsAAWrapperPass>(); 1023 AU.addUsedIfAvailable<CFLAndersAAWrapperPass>(); 1024 AU.addUsedIfAvailable<CFLSteensAAWrapperPass>(); 1025 AU.addUsedIfAvailable<ExternalAAWrapperPass>(); 1026 } 1027