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