1 //===- llvm/Analysis/AliasAnalysis.h - Alias Analysis Interface -*- C++ -*-===// 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 defines the generic AliasAnalysis interface, which is used as the 10 // common interface used by all clients of alias analysis information, and 11 // implemented by all alias analysis implementations. Mod/Ref information is 12 // also captured by this interface. 13 // 14 // Implementations of this interface must implement the various virtual methods, 15 // which automatically provides functionality for the entire suite of client 16 // APIs. 17 // 18 // This API identifies memory regions with the MemoryLocation class. The pointer 19 // component specifies the base memory address of the region. The Size specifies 20 // the maximum size (in address units) of the memory region, or 21 // MemoryLocation::UnknownSize if the size is not known. The TBAA tag 22 // identifies the "type" of the memory reference; see the 23 // TypeBasedAliasAnalysis class for details. 24 // 25 // Some non-obvious details include: 26 // - Pointers that point to two completely different objects in memory never 27 // alias, regardless of the value of the Size component. 28 // - NoAlias doesn't imply inequal pointers. The most obvious example of this 29 // is two pointers to constant memory. Even if they are equal, constant 30 // memory is never stored to, so there will never be any dependencies. 31 // In this and other situations, the pointers may be both NoAlias and 32 // MustAlias at the same time. The current API can only return one result, 33 // though this is rarely a problem in practice. 34 // 35 //===----------------------------------------------------------------------===// 36 37 #ifndef LLVM_ANALYSIS_ALIASANALYSIS_H 38 #define LLVM_ANALYSIS_ALIASANALYSIS_H 39 40 #include "llvm/ADT/DenseMap.h" 41 #include "llvm/ADT/Sequence.h" 42 #include "llvm/ADT/SmallVector.h" 43 #include "llvm/Analysis/MemoryLocation.h" 44 #include "llvm/IR/PassManager.h" 45 #include "llvm/Pass.h" 46 #include "llvm/Support/ModRef.h" 47 #include <cstdint> 48 #include <functional> 49 #include <memory> 50 #include <optional> 51 #include <vector> 52 53 namespace llvm { 54 55 class AnalysisUsage; 56 class AtomicCmpXchgInst; 57 class BasicBlock; 58 class CatchPadInst; 59 class CatchReturnInst; 60 class DominatorTree; 61 class FenceInst; 62 class Function; 63 class LoopInfo; 64 class PreservedAnalyses; 65 class TargetLibraryInfo; 66 class Value; 67 68 /// The possible results of an alias query. 69 /// 70 /// These results are always computed between two MemoryLocation objects as 71 /// a query to some alias analysis. 72 /// 73 /// Note that these are unscoped enumerations because we would like to support 74 /// implicitly testing a result for the existence of any possible aliasing with 75 /// a conversion to bool, but an "enum class" doesn't support this. The 76 /// canonical names from the literature are suffixed and unique anyways, and so 77 /// they serve as global constants in LLVM for these results. 78 /// 79 /// See docs/AliasAnalysis.html for more information on the specific meanings 80 /// of these values. 81 class AliasResult { 82 private: 83 static const int OffsetBits = 23; 84 static const int AliasBits = 8; 85 static_assert(AliasBits + 1 + OffsetBits <= 32, 86 "AliasResult size is intended to be 4 bytes!"); 87 88 unsigned int Alias : AliasBits; 89 unsigned int HasOffset : 1; 90 signed int Offset : OffsetBits; 91 92 public: 93 enum Kind : uint8_t { 94 /// The two locations do not alias at all. 95 /// 96 /// This value is arranged to convert to false, while all other values 97 /// convert to true. This allows a boolean context to convert the result to 98 /// a binary flag indicating whether there is the possibility of aliasing. 99 NoAlias = 0, 100 /// The two locations may or may not alias. This is the least precise 101 /// result. 102 MayAlias, 103 /// The two locations alias, but only due to a partial overlap. 104 PartialAlias, 105 /// The two locations precisely alias each other. 106 MustAlias, 107 }; 108 static_assert(MustAlias < (1 << AliasBits), 109 "Not enough bit field size for the enum!"); 110 111 explicit AliasResult() = delete; AliasResult(const Kind & Alias)112 constexpr AliasResult(const Kind &Alias) 113 : Alias(Alias), HasOffset(false), Offset(0) {} 114 Kind()115 operator Kind() const { return static_cast<Kind>(Alias); } 116 117 bool operator==(const AliasResult &Other) const { 118 return Alias == Other.Alias && HasOffset == Other.HasOffset && 119 Offset == Other.Offset; 120 } 121 bool operator!=(const AliasResult &Other) const { return !(*this == Other); } 122 123 bool operator==(Kind K) const { return Alias == K; } 124 bool operator!=(Kind K) const { return !(*this == K); } 125 hasOffset()126 constexpr bool hasOffset() const { return HasOffset; } getOffset()127 constexpr int32_t getOffset() const { 128 assert(HasOffset && "No offset!"); 129 return Offset; 130 } setOffset(int32_t NewOffset)131 void setOffset(int32_t NewOffset) { 132 if (isInt<OffsetBits>(NewOffset)) { 133 HasOffset = true; 134 Offset = NewOffset; 135 } 136 } 137 138 /// Helper for processing AliasResult for swapped memory location pairs. 139 void swap(bool DoSwap = true) { 140 if (DoSwap && hasOffset()) 141 setOffset(-getOffset()); 142 } 143 }; 144 145 static_assert(sizeof(AliasResult) == 4, 146 "AliasResult size is intended to be 4 bytes!"); 147 148 /// << operator for AliasResult. 149 raw_ostream &operator<<(raw_ostream &OS, AliasResult AR); 150 151 /// Virtual base class for providers of capture information. 152 struct CaptureInfo { 153 virtual ~CaptureInfo() = 0; 154 155 /// Check whether Object is not captured before instruction I. If OrAt is 156 /// true, captures by instruction I itself are also considered. 157 virtual bool isNotCapturedBefore(const Value *Object, const Instruction *I, 158 bool OrAt) = 0; 159 }; 160 161 /// Context-free CaptureInfo provider, which computes and caches whether an 162 /// object is captured in the function at all, but does not distinguish whether 163 /// it was captured before or after the context instruction. 164 class SimpleCaptureInfo final : public CaptureInfo { 165 SmallDenseMap<const Value *, bool, 8> IsCapturedCache; 166 167 public: 168 bool isNotCapturedBefore(const Value *Object, const Instruction *I, 169 bool OrAt) override; 170 }; 171 172 /// Context-sensitive CaptureInfo provider, which computes and caches the 173 /// earliest common dominator closure of all captures. It provides a good 174 /// approximation to a precise "captures before" analysis. 175 class EarliestEscapeInfo final : public CaptureInfo { 176 DominatorTree &DT; 177 const LoopInfo *LI; 178 179 /// Map from identified local object to an instruction before which it does 180 /// not escape, or nullptr if it never escapes. The "earliest" instruction 181 /// may be a conservative approximation, e.g. the first instruction in the 182 /// function is always a legal choice. 183 DenseMap<const Value *, Instruction *> EarliestEscapes; 184 185 /// Reverse map from instruction to the objects it is the earliest escape for. 186 /// This is used for cache invalidation purposes. 187 DenseMap<Instruction *, TinyPtrVector<const Value *>> Inst2Obj; 188 189 public: 190 EarliestEscapeInfo(DominatorTree &DT, const LoopInfo *LI = nullptr) DT(DT)191 : DT(DT), LI(LI) {} 192 193 bool isNotCapturedBefore(const Value *Object, const Instruction *I, 194 bool OrAt) override; 195 196 void removeInstruction(Instruction *I); 197 }; 198 199 /// Cache key for BasicAA results. It only includes the pointer and size from 200 /// MemoryLocation, as BasicAA is AATags independent. Additionally, it includes 201 /// the value of MayBeCrossIteration, which may affect BasicAA results. 202 struct AACacheLoc { 203 using PtrTy = PointerIntPair<const Value *, 1, bool>; 204 PtrTy Ptr; 205 LocationSize Size; 206 AACacheLocAACacheLoc207 AACacheLoc(PtrTy Ptr, LocationSize Size) : Ptr(Ptr), Size(Size) {} AACacheLocAACacheLoc208 AACacheLoc(const Value *Ptr, LocationSize Size, bool MayBeCrossIteration) 209 : Ptr(Ptr, MayBeCrossIteration), Size(Size) {} 210 }; 211 212 template <> struct DenseMapInfo<AACacheLoc> { 213 static inline AACacheLoc getEmptyKey() { 214 return {DenseMapInfo<AACacheLoc::PtrTy>::getEmptyKey(), 215 DenseMapInfo<LocationSize>::getEmptyKey()}; 216 } 217 static inline AACacheLoc getTombstoneKey() { 218 return {DenseMapInfo<AACacheLoc::PtrTy>::getTombstoneKey(), 219 DenseMapInfo<LocationSize>::getTombstoneKey()}; 220 } 221 static unsigned getHashValue(const AACacheLoc &Val) { 222 return DenseMapInfo<AACacheLoc::PtrTy>::getHashValue(Val.Ptr) ^ 223 DenseMapInfo<LocationSize>::getHashValue(Val.Size); 224 } 225 static bool isEqual(const AACacheLoc &LHS, const AACacheLoc &RHS) { 226 return LHS.Ptr == RHS.Ptr && LHS.Size == RHS.Size; 227 } 228 }; 229 230 class AAResults; 231 232 /// This class stores info we want to provide to or retain within an alias 233 /// query. By default, the root query is stateless and starts with a freshly 234 /// constructed info object. Specific alias analyses can use this query info to 235 /// store per-query state that is important for recursive or nested queries to 236 /// avoid recomputing. To enable preserving this state across multiple queries 237 /// where safe (due to the IR not changing), use a `BatchAAResults` wrapper. 238 /// The information stored in an `AAQueryInfo` is currently limitted to the 239 /// caches used by BasicAA, but can further be extended to fit other AA needs. 240 class AAQueryInfo { 241 public: 242 using LocPair = std::pair<AACacheLoc, AACacheLoc>; 243 struct CacheEntry { 244 AliasResult Result; 245 /// Number of times a NoAlias assumption has been used. 246 /// 0 for assumptions that have not been used, -1 for definitive results. 247 int NumAssumptionUses; 248 /// Whether this is a definitive (non-assumption) result. 249 bool isDefinitive() const { return NumAssumptionUses < 0; } 250 }; 251 252 // Alias analysis result aggregration using which this query is performed. 253 // Can be used to perform recursive queries. 254 AAResults &AAR; 255 256 using AliasCacheT = SmallDenseMap<LocPair, CacheEntry, 8>; 257 AliasCacheT AliasCache; 258 259 CaptureInfo *CI; 260 261 /// Query depth used to distinguish recursive queries. 262 unsigned Depth = 0; 263 264 /// How many active NoAlias assumption uses there are. 265 int NumAssumptionUses = 0; 266 267 /// Location pairs for which an assumption based result is currently stored. 268 /// Used to remove all potentially incorrect results from the cache if an 269 /// assumption is disproven. 270 SmallVector<AAQueryInfo::LocPair, 4> AssumptionBasedResults; 271 272 /// Tracks whether the accesses may be on different cycle iterations. 273 /// 274 /// When interpret "Value" pointer equality as value equality we need to make 275 /// sure that the "Value" is not part of a cycle. Otherwise, two uses could 276 /// come from different "iterations" of a cycle and see different values for 277 /// the same "Value" pointer. 278 /// 279 /// The following example shows the problem: 280 /// %p = phi(%alloca1, %addr2) 281 /// %l = load %ptr 282 /// %addr1 = gep, %alloca2, 0, %l 283 /// %addr2 = gep %alloca2, 0, (%l + 1) 284 /// alias(%p, %addr1) -> MayAlias ! 285 /// store %l, ... 286 bool MayBeCrossIteration = false; 287 288 AAQueryInfo(AAResults &AAR, CaptureInfo *CI) : AAR(AAR), CI(CI) {} 289 }; 290 291 /// AAQueryInfo that uses SimpleCaptureInfo. 292 class SimpleAAQueryInfo : public AAQueryInfo { 293 SimpleCaptureInfo CI; 294 295 public: 296 SimpleAAQueryInfo(AAResults &AAR) : AAQueryInfo(AAR, &CI) {} 297 }; 298 299 class BatchAAResults; 300 301 class AAResults { 302 public: 303 // Make these results default constructable and movable. We have to spell 304 // these out because MSVC won't synthesize them. 305 AAResults(const TargetLibraryInfo &TLI) : TLI(TLI) {} 306 AAResults(AAResults &&Arg); 307 ~AAResults(); 308 309 /// Register a specific AA result. 310 template <typename AAResultT> void addAAResult(AAResultT &AAResult) { 311 // FIXME: We should use a much lighter weight system than the usual 312 // polymorphic pattern because we don't own AAResult. It should 313 // ideally involve two pointers and no separate allocation. 314 AAs.emplace_back(new Model<AAResultT>(AAResult, *this)); 315 } 316 317 /// Register a function analysis ID that the results aggregation depends on. 318 /// 319 /// This is used in the new pass manager to implement the invalidation logic 320 /// where we must invalidate the results aggregation if any of our component 321 /// analyses become invalid. 322 void addAADependencyID(AnalysisKey *ID) { AADeps.push_back(ID); } 323 324 /// Handle invalidation events in the new pass manager. 325 /// 326 /// The aggregation is invalidated if any of the underlying analyses is 327 /// invalidated. 328 bool invalidate(Function &F, const PreservedAnalyses &PA, 329 FunctionAnalysisManager::Invalidator &Inv); 330 331 //===--------------------------------------------------------------------===// 332 /// \name Alias Queries 333 /// @{ 334 335 /// The main low level interface to the alias analysis implementation. 336 /// Returns an AliasResult indicating whether the two pointers are aliased to 337 /// each other. This is the interface that must be implemented by specific 338 /// alias analysis implementations. 339 AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB); 340 341 /// A convenience wrapper around the primary \c alias interface. 342 AliasResult alias(const Value *V1, LocationSize V1Size, const Value *V2, 343 LocationSize V2Size) { 344 return alias(MemoryLocation(V1, V1Size), MemoryLocation(V2, V2Size)); 345 } 346 347 /// A convenience wrapper around the primary \c alias interface. 348 AliasResult alias(const Value *V1, const Value *V2) { 349 return alias(MemoryLocation::getBeforeOrAfter(V1), 350 MemoryLocation::getBeforeOrAfter(V2)); 351 } 352 353 /// A trivial helper function to check to see if the specified pointers are 354 /// no-alias. 355 bool isNoAlias(const MemoryLocation &LocA, const MemoryLocation &LocB) { 356 return alias(LocA, LocB) == AliasResult::NoAlias; 357 } 358 359 /// A convenience wrapper around the \c isNoAlias helper interface. 360 bool isNoAlias(const Value *V1, LocationSize V1Size, const Value *V2, 361 LocationSize V2Size) { 362 return isNoAlias(MemoryLocation(V1, V1Size), MemoryLocation(V2, V2Size)); 363 } 364 365 /// A convenience wrapper around the \c isNoAlias helper interface. 366 bool isNoAlias(const Value *V1, const Value *V2) { 367 return isNoAlias(MemoryLocation::getBeforeOrAfter(V1), 368 MemoryLocation::getBeforeOrAfter(V2)); 369 } 370 371 /// A trivial helper function to check to see if the specified pointers are 372 /// must-alias. 373 bool isMustAlias(const MemoryLocation &LocA, const MemoryLocation &LocB) { 374 return alias(LocA, LocB) == AliasResult::MustAlias; 375 } 376 377 /// A convenience wrapper around the \c isMustAlias helper interface. 378 bool isMustAlias(const Value *V1, const Value *V2) { 379 return alias(V1, LocationSize::precise(1), V2, LocationSize::precise(1)) == 380 AliasResult::MustAlias; 381 } 382 383 /// Checks whether the given location points to constant memory, or if 384 /// \p OrLocal is true whether it points to a local alloca. 385 bool pointsToConstantMemory(const MemoryLocation &Loc, bool OrLocal = false) { 386 return isNoModRef(getModRefInfoMask(Loc, OrLocal)); 387 } 388 389 /// A convenience wrapper around the primary \c pointsToConstantMemory 390 /// interface. 391 bool pointsToConstantMemory(const Value *P, bool OrLocal = false) { 392 return pointsToConstantMemory(MemoryLocation::getBeforeOrAfter(P), OrLocal); 393 } 394 395 /// @} 396 //===--------------------------------------------------------------------===// 397 /// \name Simple mod/ref information 398 /// @{ 399 400 /// Returns a bitmask that should be unconditionally applied to the ModRef 401 /// info of a memory location. This allows us to eliminate Mod and/or Ref 402 /// from the ModRef info based on the knowledge that the memory location 403 /// points to constant and/or locally-invariant memory. 404 /// 405 /// If IgnoreLocals is true, then this method returns NoModRef for memory 406 /// that points to a local alloca. 407 ModRefInfo getModRefInfoMask(const MemoryLocation &Loc, 408 bool IgnoreLocals = false); 409 410 /// A convenience wrapper around the primary \c getModRefInfoMask 411 /// interface. 412 ModRefInfo getModRefInfoMask(const Value *P, bool IgnoreLocals = false) { 413 return getModRefInfoMask(MemoryLocation::getBeforeOrAfter(P), IgnoreLocals); 414 } 415 416 /// Get the ModRef info associated with a pointer argument of a call. The 417 /// result's bits are set to indicate the allowed aliasing ModRef kinds. Note 418 /// that these bits do not necessarily account for the overall behavior of 419 /// the function, but rather only provide additional per-argument 420 /// information. 421 ModRefInfo getArgModRefInfo(const CallBase *Call, unsigned ArgIdx); 422 423 /// Return the behavior of the given call site. 424 MemoryEffects getMemoryEffects(const CallBase *Call); 425 426 /// Return the behavior when calling the given function. 427 MemoryEffects getMemoryEffects(const Function *F); 428 429 /// Checks if the specified call is known to never read or write memory. 430 /// 431 /// Note that if the call only reads from known-constant memory, it is also 432 /// legal to return true. Also, calls that unwind the stack are legal for 433 /// this predicate. 434 /// 435 /// Many optimizations (such as CSE and LICM) can be performed on such calls 436 /// without worrying about aliasing properties, and many calls have this 437 /// property (e.g. calls to 'sin' and 'cos'). 438 /// 439 /// This property corresponds to the GCC 'const' attribute. 440 bool doesNotAccessMemory(const CallBase *Call) { 441 return getMemoryEffects(Call).doesNotAccessMemory(); 442 } 443 444 /// Checks if the specified function is known to never read or write memory. 445 /// 446 /// Note that if the function only reads from known-constant memory, it is 447 /// also legal to return true. Also, function that unwind the stack are legal 448 /// for this predicate. 449 /// 450 /// Many optimizations (such as CSE and LICM) can be performed on such calls 451 /// to such functions without worrying about aliasing properties, and many 452 /// functions have this property (e.g. 'sin' and 'cos'). 453 /// 454 /// This property corresponds to the GCC 'const' attribute. 455 bool doesNotAccessMemory(const Function *F) { 456 return getMemoryEffects(F).doesNotAccessMemory(); 457 } 458 459 /// Checks if the specified call is known to only read from non-volatile 460 /// memory (or not access memory at all). 461 /// 462 /// Calls that unwind the stack are legal for this predicate. 463 /// 464 /// This property allows many common optimizations to be performed in the 465 /// absence of interfering store instructions, such as CSE of strlen calls. 466 /// 467 /// This property corresponds to the GCC 'pure' attribute. 468 bool onlyReadsMemory(const CallBase *Call) { 469 return getMemoryEffects(Call).onlyReadsMemory(); 470 } 471 472 /// Checks if the specified function is known to only read from non-volatile 473 /// memory (or not access memory at all). 474 /// 475 /// Functions that unwind the stack are legal for this predicate. 476 /// 477 /// This property allows many common optimizations to be performed in the 478 /// absence of interfering store instructions, such as CSE of strlen calls. 479 /// 480 /// This property corresponds to the GCC 'pure' attribute. 481 bool onlyReadsMemory(const Function *F) { 482 return getMemoryEffects(F).onlyReadsMemory(); 483 } 484 485 /// Check whether or not an instruction may read or write the optionally 486 /// specified memory location. 487 /// 488 /// 489 /// An instruction that doesn't read or write memory may be trivially LICM'd 490 /// for example. 491 /// 492 /// For function calls, this delegates to the alias-analysis specific 493 /// call-site mod-ref behavior queries. Otherwise it delegates to the specific 494 /// helpers above. 495 ModRefInfo getModRefInfo(const Instruction *I, 496 const std::optional<MemoryLocation> &OptLoc) { 497 SimpleAAQueryInfo AAQIP(*this); 498 return getModRefInfo(I, OptLoc, AAQIP); 499 } 500 501 /// A convenience wrapper for constructing the memory location. 502 ModRefInfo getModRefInfo(const Instruction *I, const Value *P, 503 LocationSize Size) { 504 return getModRefInfo(I, MemoryLocation(P, Size)); 505 } 506 507 /// Return information about whether a call and an instruction may refer to 508 /// the same memory locations. 509 ModRefInfo getModRefInfo(const Instruction *I, const CallBase *Call); 510 511 /// Return information about whether a particular call site modifies 512 /// or reads the specified memory location \p MemLoc before instruction \p I 513 /// in a BasicBlock. 514 ModRefInfo callCapturesBefore(const Instruction *I, 515 const MemoryLocation &MemLoc, 516 DominatorTree *DT) { 517 SimpleAAQueryInfo AAQIP(*this); 518 return callCapturesBefore(I, MemLoc, DT, AAQIP); 519 } 520 521 /// A convenience wrapper to synthesize a memory location. 522 ModRefInfo callCapturesBefore(const Instruction *I, const Value *P, 523 LocationSize Size, DominatorTree *DT) { 524 return callCapturesBefore(I, MemoryLocation(P, Size), DT); 525 } 526 527 /// @} 528 //===--------------------------------------------------------------------===// 529 /// \name Higher level methods for querying mod/ref information. 530 /// @{ 531 532 /// Check if it is possible for execution of the specified basic block to 533 /// modify the location Loc. 534 bool canBasicBlockModify(const BasicBlock &BB, const MemoryLocation &Loc); 535 536 /// A convenience wrapper synthesizing a memory location. 537 bool canBasicBlockModify(const BasicBlock &BB, const Value *P, 538 LocationSize Size) { 539 return canBasicBlockModify(BB, MemoryLocation(P, Size)); 540 } 541 542 /// Check if it is possible for the execution of the specified instructions 543 /// to mod\ref (according to the mode) the location Loc. 544 /// 545 /// The instructions to consider are all of the instructions in the range of 546 /// [I1,I2] INCLUSIVE. I1 and I2 must be in the same basic block. 547 bool canInstructionRangeModRef(const Instruction &I1, const Instruction &I2, 548 const MemoryLocation &Loc, 549 const ModRefInfo Mode); 550 551 /// A convenience wrapper synthesizing a memory location. 552 bool canInstructionRangeModRef(const Instruction &I1, const Instruction &I2, 553 const Value *Ptr, LocationSize Size, 554 const ModRefInfo Mode) { 555 return canInstructionRangeModRef(I1, I2, MemoryLocation(Ptr, Size), Mode); 556 } 557 558 // CtxI can be nullptr, in which case the query is whether or not the aliasing 559 // relationship holds through the entire function. 560 AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB, 561 AAQueryInfo &AAQI, const Instruction *CtxI = nullptr); 562 563 bool pointsToConstantMemory(const MemoryLocation &Loc, AAQueryInfo &AAQI, 564 bool OrLocal = false); 565 ModRefInfo getModRefInfoMask(const MemoryLocation &Loc, AAQueryInfo &AAQI, 566 bool IgnoreLocals = false); 567 ModRefInfo getModRefInfo(const Instruction *I, const CallBase *Call2, 568 AAQueryInfo &AAQIP); 569 ModRefInfo getModRefInfo(const CallBase *Call, const MemoryLocation &Loc, 570 AAQueryInfo &AAQI); 571 ModRefInfo getModRefInfo(const CallBase *Call1, const CallBase *Call2, 572 AAQueryInfo &AAQI); 573 ModRefInfo getModRefInfo(const VAArgInst *V, const MemoryLocation &Loc, 574 AAQueryInfo &AAQI); 575 ModRefInfo getModRefInfo(const LoadInst *L, const MemoryLocation &Loc, 576 AAQueryInfo &AAQI); 577 ModRefInfo getModRefInfo(const StoreInst *S, const MemoryLocation &Loc, 578 AAQueryInfo &AAQI); 579 ModRefInfo getModRefInfo(const FenceInst *S, const MemoryLocation &Loc, 580 AAQueryInfo &AAQI); 581 ModRefInfo getModRefInfo(const AtomicCmpXchgInst *CX, 582 const MemoryLocation &Loc, AAQueryInfo &AAQI); 583 ModRefInfo getModRefInfo(const AtomicRMWInst *RMW, const MemoryLocation &Loc, 584 AAQueryInfo &AAQI); 585 ModRefInfo getModRefInfo(const CatchPadInst *I, const MemoryLocation &Loc, 586 AAQueryInfo &AAQI); 587 ModRefInfo getModRefInfo(const CatchReturnInst *I, const MemoryLocation &Loc, 588 AAQueryInfo &AAQI); 589 ModRefInfo getModRefInfo(const Instruction *I, 590 const std::optional<MemoryLocation> &OptLoc, 591 AAQueryInfo &AAQIP); 592 ModRefInfo callCapturesBefore(const Instruction *I, 593 const MemoryLocation &MemLoc, DominatorTree *DT, 594 AAQueryInfo &AAQIP); 595 MemoryEffects getMemoryEffects(const CallBase *Call, AAQueryInfo &AAQI); 596 597 private: 598 class Concept; 599 600 template <typename T> class Model; 601 602 friend class AAResultBase; 603 604 const TargetLibraryInfo &TLI; 605 606 std::vector<std::unique_ptr<Concept>> AAs; 607 608 std::vector<AnalysisKey *> AADeps; 609 610 friend class BatchAAResults; 611 }; 612 613 /// This class is a wrapper over an AAResults, and it is intended to be used 614 /// only when there are no IR changes inbetween queries. BatchAAResults is 615 /// reusing the same `AAQueryInfo` to preserve the state across queries, 616 /// esentially making AA work in "batch mode". The internal state cannot be 617 /// cleared, so to go "out-of-batch-mode", the user must either use AAResults, 618 /// or create a new BatchAAResults. 619 class BatchAAResults { 620 AAResults &AA; 621 AAQueryInfo AAQI; 622 SimpleCaptureInfo SimpleCI; 623 624 public: 625 BatchAAResults(AAResults &AAR) : AA(AAR), AAQI(AAR, &SimpleCI) {} 626 BatchAAResults(AAResults &AAR, CaptureInfo *CI) : AA(AAR), AAQI(AAR, CI) {} 627 628 AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB) { 629 return AA.alias(LocA, LocB, AAQI); 630 } 631 bool pointsToConstantMemory(const MemoryLocation &Loc, bool OrLocal = false) { 632 return AA.pointsToConstantMemory(Loc, AAQI, OrLocal); 633 } 634 ModRefInfo getModRefInfoMask(const MemoryLocation &Loc, 635 bool IgnoreLocals = false) { 636 return AA.getModRefInfoMask(Loc, AAQI, IgnoreLocals); 637 } 638 ModRefInfo getModRefInfo(const Instruction *I, 639 const std::optional<MemoryLocation> &OptLoc) { 640 return AA.getModRefInfo(I, OptLoc, AAQI); 641 } 642 ModRefInfo getModRefInfo(const Instruction *I, const CallBase *Call2) { 643 return AA.getModRefInfo(I, Call2, AAQI); 644 } 645 ModRefInfo getArgModRefInfo(const CallBase *Call, unsigned ArgIdx) { 646 return AA.getArgModRefInfo(Call, ArgIdx); 647 } 648 MemoryEffects getMemoryEffects(const CallBase *Call) { 649 return AA.getMemoryEffects(Call, AAQI); 650 } 651 bool isMustAlias(const MemoryLocation &LocA, const MemoryLocation &LocB) { 652 return alias(LocA, LocB) == AliasResult::MustAlias; 653 } 654 bool isMustAlias(const Value *V1, const Value *V2) { 655 return alias(MemoryLocation(V1, LocationSize::precise(1)), 656 MemoryLocation(V2, LocationSize::precise(1))) == 657 AliasResult::MustAlias; 658 } 659 ModRefInfo callCapturesBefore(const Instruction *I, 660 const MemoryLocation &MemLoc, 661 DominatorTree *DT) { 662 return AA.callCapturesBefore(I, MemLoc, DT, AAQI); 663 } 664 665 /// Assume that values may come from different cycle iterations. 666 void enableCrossIterationMode() { 667 AAQI.MayBeCrossIteration = true; 668 } 669 }; 670 671 /// Temporary typedef for legacy code that uses a generic \c AliasAnalysis 672 /// pointer or reference. 673 using AliasAnalysis = AAResults; 674 675 /// A private abstract base class describing the concept of an individual alias 676 /// analysis implementation. 677 /// 678 /// This interface is implemented by any \c Model instantiation. It is also the 679 /// interface which a type used to instantiate the model must provide. 680 /// 681 /// All of these methods model methods by the same name in the \c 682 /// AAResults class. Only differences and specifics to how the 683 /// implementations are called are documented here. 684 class AAResults::Concept { 685 public: 686 virtual ~Concept() = 0; 687 688 //===--------------------------------------------------------------------===// 689 /// \name Alias Queries 690 /// @{ 691 692 /// The main low level interface to the alias analysis implementation. 693 /// Returns an AliasResult indicating whether the two pointers are aliased to 694 /// each other. This is the interface that must be implemented by specific 695 /// alias analysis implementations. 696 virtual AliasResult alias(const MemoryLocation &LocA, 697 const MemoryLocation &LocB, AAQueryInfo &AAQI, 698 const Instruction *CtxI) = 0; 699 700 /// @} 701 //===--------------------------------------------------------------------===// 702 /// \name Simple mod/ref information 703 /// @{ 704 705 /// Returns a bitmask that should be unconditionally applied to the ModRef 706 /// info of a memory location. This allows us to eliminate Mod and/or Ref from 707 /// the ModRef info based on the knowledge that the memory location points to 708 /// constant and/or locally-invariant memory. 709 virtual ModRefInfo getModRefInfoMask(const MemoryLocation &Loc, 710 AAQueryInfo &AAQI, 711 bool IgnoreLocals) = 0; 712 713 /// Get the ModRef info associated with a pointer argument of a callsite. The 714 /// result's bits are set to indicate the allowed aliasing ModRef kinds. Note 715 /// that these bits do not necessarily account for the overall behavior of 716 /// the function, but rather only provide additional per-argument 717 /// information. 718 virtual ModRefInfo getArgModRefInfo(const CallBase *Call, 719 unsigned ArgIdx) = 0; 720 721 /// Return the behavior of the given call site. 722 virtual MemoryEffects getMemoryEffects(const CallBase *Call, 723 AAQueryInfo &AAQI) = 0; 724 725 /// Return the behavior when calling the given function. 726 virtual MemoryEffects getMemoryEffects(const Function *F) = 0; 727 728 /// getModRefInfo (for call sites) - Return information about whether 729 /// a particular call site modifies or reads the specified memory location. 730 virtual ModRefInfo getModRefInfo(const CallBase *Call, 731 const MemoryLocation &Loc, 732 AAQueryInfo &AAQI) = 0; 733 734 /// Return information about whether two call sites may refer to the same set 735 /// of memory locations. See the AA documentation for details: 736 /// http://llvm.org/docs/AliasAnalysis.html#ModRefInfo 737 virtual ModRefInfo getModRefInfo(const CallBase *Call1, const CallBase *Call2, 738 AAQueryInfo &AAQI) = 0; 739 740 /// @} 741 }; 742 743 /// A private class template which derives from \c Concept and wraps some other 744 /// type. 745 /// 746 /// This models the concept by directly forwarding each interface point to the 747 /// wrapped type which must implement a compatible interface. This provides 748 /// a type erased binding. 749 template <typename AAResultT> class AAResults::Model final : public Concept { 750 AAResultT &Result; 751 752 public: 753 explicit Model(AAResultT &Result, AAResults &AAR) : Result(Result) {} 754 ~Model() override = default; 755 756 AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB, 757 AAQueryInfo &AAQI, const Instruction *CtxI) override { 758 return Result.alias(LocA, LocB, AAQI, CtxI); 759 } 760 761 ModRefInfo getModRefInfoMask(const MemoryLocation &Loc, AAQueryInfo &AAQI, 762 bool IgnoreLocals) override { 763 return Result.getModRefInfoMask(Loc, AAQI, IgnoreLocals); 764 } 765 766 ModRefInfo getArgModRefInfo(const CallBase *Call, unsigned ArgIdx) override { 767 return Result.getArgModRefInfo(Call, ArgIdx); 768 } 769 770 MemoryEffects getMemoryEffects(const CallBase *Call, 771 AAQueryInfo &AAQI) override { 772 return Result.getMemoryEffects(Call, AAQI); 773 } 774 775 MemoryEffects getMemoryEffects(const Function *F) override { 776 return Result.getMemoryEffects(F); 777 } 778 779 ModRefInfo getModRefInfo(const CallBase *Call, const MemoryLocation &Loc, 780 AAQueryInfo &AAQI) override { 781 return Result.getModRefInfo(Call, Loc, AAQI); 782 } 783 784 ModRefInfo getModRefInfo(const CallBase *Call1, const CallBase *Call2, 785 AAQueryInfo &AAQI) override { 786 return Result.getModRefInfo(Call1, Call2, AAQI); 787 } 788 }; 789 790 /// A base class to help implement the function alias analysis results concept. 791 /// 792 /// Because of the nature of many alias analysis implementations, they often 793 /// only implement a subset of the interface. This base class will attempt to 794 /// implement the remaining portions of the interface in terms of simpler forms 795 /// of the interface where possible, and otherwise provide conservatively 796 /// correct fallback implementations. 797 /// 798 /// Implementors of an alias analysis should derive from this class, and then 799 /// override specific methods that they wish to customize. There is no need to 800 /// use virtual anywhere. 801 class AAResultBase { 802 protected: 803 explicit AAResultBase() = default; 804 805 // Provide all the copy and move constructors so that derived types aren't 806 // constrained. 807 AAResultBase(const AAResultBase &Arg) {} 808 AAResultBase(AAResultBase &&Arg) {} 809 810 public: 811 AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB, 812 AAQueryInfo &AAQI, const Instruction *I) { 813 return AliasResult::MayAlias; 814 } 815 816 ModRefInfo getModRefInfoMask(const MemoryLocation &Loc, AAQueryInfo &AAQI, 817 bool IgnoreLocals) { 818 return ModRefInfo::ModRef; 819 } 820 821 ModRefInfo getArgModRefInfo(const CallBase *Call, unsigned ArgIdx) { 822 return ModRefInfo::ModRef; 823 } 824 825 MemoryEffects getMemoryEffects(const CallBase *Call, AAQueryInfo &AAQI) { 826 return MemoryEffects::unknown(); 827 } 828 829 MemoryEffects getMemoryEffects(const Function *F) { 830 return MemoryEffects::unknown(); 831 } 832 833 ModRefInfo getModRefInfo(const CallBase *Call, const MemoryLocation &Loc, 834 AAQueryInfo &AAQI) { 835 return ModRefInfo::ModRef; 836 } 837 838 ModRefInfo getModRefInfo(const CallBase *Call1, const CallBase *Call2, 839 AAQueryInfo &AAQI) { 840 return ModRefInfo::ModRef; 841 } 842 }; 843 844 /// Return true if this pointer is returned by a noalias function. 845 bool isNoAliasCall(const Value *V); 846 847 /// Return true if this pointer refers to a distinct and identifiable object. 848 /// This returns true for: 849 /// Global Variables and Functions (but not Global Aliases) 850 /// Allocas 851 /// ByVal and NoAlias Arguments 852 /// NoAlias returns (e.g. calls to malloc) 853 /// 854 bool isIdentifiedObject(const Value *V); 855 856 /// Return true if V is umabigously identified at the function-level. 857 /// Different IdentifiedFunctionLocals can't alias. 858 /// Further, an IdentifiedFunctionLocal can not alias with any function 859 /// arguments other than itself, which is not necessarily true for 860 /// IdentifiedObjects. 861 bool isIdentifiedFunctionLocal(const Value *V); 862 863 /// Returns true if the pointer is one which would have been considered an 864 /// escape by isNonEscapingLocalObject. 865 bool isEscapeSource(const Value *V); 866 867 /// Return true if Object memory is not visible after an unwind, in the sense 868 /// that program semantics cannot depend on Object containing any particular 869 /// value on unwind. If the RequiresNoCaptureBeforeUnwind out parameter is set 870 /// to true, then the memory is only not visible if the object has not been 871 /// captured prior to the unwind. Otherwise it is not visible even if captured. 872 bool isNotVisibleOnUnwind(const Value *Object, 873 bool &RequiresNoCaptureBeforeUnwind); 874 875 /// Return true if the Object is writable, in the sense that any location based 876 /// on this pointer that can be loaded can also be stored to without trapping. 877 /// Additionally, at the point Object is declared, stores can be introduced 878 /// without data races. At later points, this is only the case if the pointer 879 /// can not escape to a different thread. 880 /// 881 /// If ExplicitlyDereferenceableOnly is set to true, this property only holds 882 /// for the part of Object that is explicitly marked as dereferenceable, e.g. 883 /// using the dereferenceable(N) attribute. It does not necessarily hold for 884 /// parts that are only known to be dereferenceable due to the presence of 885 /// loads. 886 bool isWritableObject(const Value *Object, bool &ExplicitlyDereferenceableOnly); 887 888 /// A manager for alias analyses. 889 /// 890 /// This class can have analyses registered with it and when run, it will run 891 /// all of them and aggregate their results into single AA results interface 892 /// that dispatches across all of the alias analysis results available. 893 /// 894 /// Note that the order in which analyses are registered is very significant. 895 /// That is the order in which the results will be aggregated and queried. 896 /// 897 /// This manager effectively wraps the AnalysisManager for registering alias 898 /// analyses. When you register your alias analysis with this manager, it will 899 /// ensure the analysis itself is registered with its AnalysisManager. 900 /// 901 /// The result of this analysis is only invalidated if one of the particular 902 /// aggregated AA results end up being invalidated. This removes the need to 903 /// explicitly preserve the results of `AAManager`. Note that analyses should no 904 /// longer be registered once the `AAManager` is run. 905 class AAManager : public AnalysisInfoMixin<AAManager> { 906 public: 907 using Result = AAResults; 908 909 /// Register a specific AA result. 910 template <typename AnalysisT> void registerFunctionAnalysis() { 911 ResultGetters.push_back(&getFunctionAAResultImpl<AnalysisT>); 912 } 913 914 /// Register a specific AA result. 915 template <typename AnalysisT> void registerModuleAnalysis() { 916 ResultGetters.push_back(&getModuleAAResultImpl<AnalysisT>); 917 } 918 919 Result run(Function &F, FunctionAnalysisManager &AM); 920 921 private: 922 friend AnalysisInfoMixin<AAManager>; 923 924 static AnalysisKey Key; 925 926 SmallVector<void (*)(Function &F, FunctionAnalysisManager &AM, 927 AAResults &AAResults), 928 4> ResultGetters; 929 930 template <typename AnalysisT> 931 static void getFunctionAAResultImpl(Function &F, 932 FunctionAnalysisManager &AM, 933 AAResults &AAResults) { 934 AAResults.addAAResult(AM.template getResult<AnalysisT>(F)); 935 AAResults.addAADependencyID(AnalysisT::ID()); 936 } 937 938 template <typename AnalysisT> 939 static void getModuleAAResultImpl(Function &F, FunctionAnalysisManager &AM, 940 AAResults &AAResults) { 941 auto &MAMProxy = AM.getResult<ModuleAnalysisManagerFunctionProxy>(F); 942 if (auto *R = 943 MAMProxy.template getCachedResult<AnalysisT>(*F.getParent())) { 944 AAResults.addAAResult(*R); 945 MAMProxy 946 .template registerOuterAnalysisInvalidation<AnalysisT, AAManager>(); 947 } 948 } 949 }; 950 951 /// A wrapper pass to provide the legacy pass manager access to a suitably 952 /// prepared AAResults object. 953 class AAResultsWrapperPass : public FunctionPass { 954 std::unique_ptr<AAResults> AAR; 955 956 public: 957 static char ID; 958 959 AAResultsWrapperPass(); 960 961 AAResults &getAAResults() { return *AAR; } 962 const AAResults &getAAResults() const { return *AAR; } 963 964 bool runOnFunction(Function &F) override; 965 966 void getAnalysisUsage(AnalysisUsage &AU) const override; 967 }; 968 969 /// A wrapper pass for external alias analyses. This just squirrels away the 970 /// callback used to run any analyses and register their results. 971 struct ExternalAAWrapperPass : ImmutablePass { 972 using CallbackT = std::function<void(Pass &, Function &, AAResults &)>; 973 974 CallbackT CB; 975 976 static char ID; 977 978 ExternalAAWrapperPass(); 979 980 explicit ExternalAAWrapperPass(CallbackT CB); 981 982 void getAnalysisUsage(AnalysisUsage &AU) const override { 983 AU.setPreservesAll(); 984 } 985 }; 986 987 /// A wrapper pass around a callback which can be used to populate the 988 /// AAResults in the AAResultsWrapperPass from an external AA. 989 /// 990 /// The callback provided here will be used each time we prepare an AAResults 991 /// object, and will receive a reference to the function wrapper pass, the 992 /// function, and the AAResults object to populate. This should be used when 993 /// setting up a custom pass pipeline to inject a hook into the AA results. 994 ImmutablePass *createExternalAAWrapperPass( 995 std::function<void(Pass &, Function &, AAResults &)> Callback); 996 997 } // end namespace llvm 998 999 #endif // LLVM_ANALYSIS_ALIASANALYSIS_H 1000