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