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/None.h" 42 #include "llvm/ADT/Optional.h" 43 #include "llvm/ADT/SmallVector.h" 44 #include "llvm/Analysis/MemoryLocation.h" 45 #include "llvm/IR/PassManager.h" 46 #include "llvm/Pass.h" 47 #include <cstdint> 48 #include <functional> 49 #include <memory> 50 #include <vector> 51 52 namespace llvm { 53 54 class AnalysisUsage; 55 class AtomicCmpXchgInst; 56 class BasicAAResult; 57 class BasicBlock; 58 class CatchPadInst; 59 class CatchReturnInst; 60 class DominatorTree; 61 class FenceInst; 62 class Function; 63 class InvokeInst; 64 class LoopInfo; 65 class PreservedAnalyses; 66 class TargetLibraryInfo; 67 class Value; 68 69 /// The possible results of an alias query. 70 /// 71 /// These results are always computed between two MemoryLocation objects as 72 /// a query to some alias analysis. 73 /// 74 /// Note that these are unscoped enumerations because we would like to support 75 /// implicitly testing a result for the existence of any possible aliasing with 76 /// a conversion to bool, but an "enum class" doesn't support this. The 77 /// canonical names from the literature are suffixed and unique anyways, and so 78 /// they serve as global constants in LLVM for these results. 79 /// 80 /// See docs/AliasAnalysis.html for more information on the specific meanings 81 /// of these values. 82 class AliasResult { 83 private: 84 static const int OffsetBits = 23; 85 static const int AliasBits = 8; 86 static_assert(AliasBits + 1 + OffsetBits <= 32, 87 "AliasResult size is intended to be 4 bytes!"); 88 89 unsigned int Alias : AliasBits; 90 unsigned int HasOffset : 1; 91 signed int Offset : OffsetBits; 92 93 public: 94 enum Kind : uint8_t { 95 /// The two locations do not alias at all. 96 /// 97 /// This value is arranged to convert to false, while all other values 98 /// convert to true. This allows a boolean context to convert the result to 99 /// a binary flag indicating whether there is the possibility of aliasing. 100 NoAlias = 0, 101 /// The two locations may or may not alias. This is the least precise 102 /// result. 103 MayAlias, 104 /// The two locations alias, but only due to a partial overlap. 105 PartialAlias, 106 /// The two locations precisely alias each other. 107 MustAlias, 108 }; 109 static_assert(MustAlias < (1 << AliasBits), 110 "Not enough bit field size for the enum!"); 111 112 explicit AliasResult() = delete; 113 constexpr AliasResult(const Kind &Alias) 114 : Alias(Alias), HasOffset(false), Offset(0) {} 115 116 operator Kind() const { return static_cast<Kind>(Alias); } 117 118 constexpr bool hasOffset() const { return HasOffset; } 119 constexpr int32_t getOffset() const { 120 assert(HasOffset && "No offset!"); 121 return Offset; 122 } 123 void setOffset(int32_t NewOffset) { 124 if (isInt<OffsetBits>(NewOffset)) { 125 HasOffset = true; 126 Offset = NewOffset; 127 } 128 } 129 130 /// Helper for processing AliasResult for swapped memory location pairs. 131 void swap(bool DoSwap = true) { 132 if (DoSwap && hasOffset()) 133 setOffset(-getOffset()); 134 } 135 }; 136 137 static_assert(sizeof(AliasResult) == 4, 138 "AliasResult size is intended to be 4 bytes!"); 139 140 /// << operator for AliasResult. 141 raw_ostream &operator<<(raw_ostream &OS, AliasResult AR); 142 143 /// Flags indicating whether a memory access modifies or references memory. 144 /// 145 /// This is no access at all, a modification, a reference, or both 146 /// a modification and a reference. These are specifically structured such that 147 /// they form a three bit matrix and bit-tests for 'mod' or 'ref' or 'must' 148 /// work with any of the possible values. 149 enum class ModRefInfo : uint8_t { 150 /// Must is provided for completeness, but no routines will return only 151 /// Must today. See definition of Must below. 152 Must = 0, 153 /// The access may reference the value stored in memory, 154 /// a mustAlias relation was found, and no mayAlias or partialAlias found. 155 MustRef = 1, 156 /// The access may modify the value stored in memory, 157 /// a mustAlias relation was found, and no mayAlias or partialAlias found. 158 MustMod = 2, 159 /// The access may reference, modify or both the value stored in memory, 160 /// a mustAlias relation was found, and no mayAlias or partialAlias found. 161 MustModRef = MustRef | MustMod, 162 /// The access neither references nor modifies the value stored in memory. 163 NoModRef = 4, 164 /// The access may reference the value stored in memory. 165 Ref = NoModRef | MustRef, 166 /// The access may modify the value stored in memory. 167 Mod = NoModRef | MustMod, 168 /// The access may reference and may modify the value stored in memory. 169 ModRef = Ref | Mod, 170 171 /// About Must: 172 /// Must is set in a best effort manner. 173 /// We usually do not try our best to infer Must, instead it is merely 174 /// another piece of "free" information that is presented when available. 175 /// Must set means there was certainly a MustAlias found. For calls, 176 /// where multiple arguments are checked (argmemonly), this translates to 177 /// only MustAlias or NoAlias was found. 178 /// Must is not set for RAR accesses, even if the two locations must 179 /// alias. The reason is that two read accesses translate to an early return 180 /// of NoModRef. An additional alias check to set Must may be 181 /// expensive. Other cases may also not set Must(e.g. callCapturesBefore). 182 /// We refer to Must being *set* when the most significant bit is *cleared*. 183 /// Conversely we *clear* Must information by *setting* the Must bit to 1. 184 }; 185 186 LLVM_NODISCARD inline bool isNoModRef(const ModRefInfo MRI) { 187 return (static_cast<int>(MRI) & static_cast<int>(ModRefInfo::MustModRef)) == 188 static_cast<int>(ModRefInfo::Must); 189 } 190 LLVM_NODISCARD inline bool isModOrRefSet(const ModRefInfo MRI) { 191 return static_cast<int>(MRI) & static_cast<int>(ModRefInfo::MustModRef); 192 } 193 LLVM_NODISCARD inline bool isModAndRefSet(const ModRefInfo MRI) { 194 return (static_cast<int>(MRI) & static_cast<int>(ModRefInfo::MustModRef)) == 195 static_cast<int>(ModRefInfo::MustModRef); 196 } 197 LLVM_NODISCARD inline bool isModSet(const ModRefInfo MRI) { 198 return static_cast<int>(MRI) & static_cast<int>(ModRefInfo::MustMod); 199 } 200 LLVM_NODISCARD inline bool isRefSet(const ModRefInfo MRI) { 201 return static_cast<int>(MRI) & static_cast<int>(ModRefInfo::MustRef); 202 } 203 LLVM_NODISCARD inline bool isMustSet(const ModRefInfo MRI) { 204 return !(static_cast<int>(MRI) & static_cast<int>(ModRefInfo::NoModRef)); 205 } 206 207 LLVM_NODISCARD inline ModRefInfo setMod(const ModRefInfo MRI) { 208 return ModRefInfo(static_cast<int>(MRI) | 209 static_cast<int>(ModRefInfo::MustMod)); 210 } 211 LLVM_NODISCARD inline ModRefInfo setRef(const ModRefInfo MRI) { 212 return ModRefInfo(static_cast<int>(MRI) | 213 static_cast<int>(ModRefInfo::MustRef)); 214 } 215 LLVM_NODISCARD inline ModRefInfo setMust(const ModRefInfo MRI) { 216 return ModRefInfo(static_cast<int>(MRI) & 217 static_cast<int>(ModRefInfo::MustModRef)); 218 } 219 LLVM_NODISCARD inline ModRefInfo setModAndRef(const ModRefInfo MRI) { 220 return ModRefInfo(static_cast<int>(MRI) | 221 static_cast<int>(ModRefInfo::MustModRef)); 222 } 223 LLVM_NODISCARD inline ModRefInfo clearMod(const ModRefInfo MRI) { 224 return ModRefInfo(static_cast<int>(MRI) & static_cast<int>(ModRefInfo::Ref)); 225 } 226 LLVM_NODISCARD inline ModRefInfo clearRef(const ModRefInfo MRI) { 227 return ModRefInfo(static_cast<int>(MRI) & static_cast<int>(ModRefInfo::Mod)); 228 } 229 LLVM_NODISCARD inline ModRefInfo clearMust(const ModRefInfo MRI) { 230 return ModRefInfo(static_cast<int>(MRI) | 231 static_cast<int>(ModRefInfo::NoModRef)); 232 } 233 LLVM_NODISCARD inline ModRefInfo unionModRef(const ModRefInfo MRI1, 234 const ModRefInfo MRI2) { 235 return ModRefInfo(static_cast<int>(MRI1) | static_cast<int>(MRI2)); 236 } 237 LLVM_NODISCARD inline ModRefInfo intersectModRef(const ModRefInfo MRI1, 238 const ModRefInfo MRI2) { 239 return ModRefInfo(static_cast<int>(MRI1) & static_cast<int>(MRI2)); 240 } 241 242 /// The locations at which a function might access memory. 243 /// 244 /// These are primarily used in conjunction with the \c AccessKind bits to 245 /// describe both the nature of access and the locations of access for a 246 /// function call. 247 enum FunctionModRefLocation { 248 /// Base case is no access to memory. 249 FMRL_Nowhere = 0, 250 /// Access to memory via argument pointers. 251 FMRL_ArgumentPointees = 8, 252 /// Memory that is inaccessible via LLVM IR. 253 FMRL_InaccessibleMem = 16, 254 /// Access to any memory. 255 FMRL_Anywhere = 32 | FMRL_InaccessibleMem | FMRL_ArgumentPointees 256 }; 257 258 /// Summary of how a function affects memory in the program. 259 /// 260 /// Loads from constant globals are not considered memory accesses for this 261 /// interface. Also, functions may freely modify stack space local to their 262 /// invocation without having to report it through these interfaces. 263 enum FunctionModRefBehavior { 264 /// This function does not perform any non-local loads or stores to memory. 265 /// 266 /// This property corresponds to the GCC 'const' attribute. 267 /// This property corresponds to the LLVM IR 'readnone' attribute. 268 /// This property corresponds to the IntrNoMem LLVM intrinsic flag. 269 FMRB_DoesNotAccessMemory = 270 FMRL_Nowhere | static_cast<int>(ModRefInfo::NoModRef), 271 272 /// The only memory references in this function (if it has any) are 273 /// non-volatile loads from objects pointed to by its pointer-typed 274 /// arguments, with arbitrary offsets. 275 /// 276 /// This property corresponds to the combination of the IntrReadMem 277 /// and IntrArgMemOnly LLVM intrinsic flags. 278 FMRB_OnlyReadsArgumentPointees = 279 FMRL_ArgumentPointees | static_cast<int>(ModRefInfo::Ref), 280 281 /// The only memory references in this function (if it has any) are 282 /// non-volatile stores from objects pointed to by its pointer-typed 283 /// arguments, with arbitrary offsets. 284 /// 285 /// This property corresponds to the combination of the IntrWriteMem 286 /// and IntrArgMemOnly LLVM intrinsic flags. 287 FMRB_OnlyWritesArgumentPointees = 288 FMRL_ArgumentPointees | static_cast<int>(ModRefInfo::Mod), 289 290 /// The only memory references in this function (if it has any) are 291 /// non-volatile loads and stores from objects pointed to by its 292 /// pointer-typed arguments, with arbitrary offsets. 293 /// 294 /// This property corresponds to the IntrArgMemOnly LLVM intrinsic flag. 295 FMRB_OnlyAccessesArgumentPointees = 296 FMRL_ArgumentPointees | static_cast<int>(ModRefInfo::ModRef), 297 298 /// The only memory references in this function (if it has any) are 299 /// reads of memory that is otherwise inaccessible via LLVM IR. 300 /// 301 /// This property corresponds to the LLVM IR inaccessiblememonly attribute. 302 FMRB_OnlyReadsInaccessibleMem = 303 FMRL_InaccessibleMem | static_cast<int>(ModRefInfo::Ref), 304 305 /// The only memory references in this function (if it has any) are 306 /// writes to memory that is otherwise inaccessible via LLVM IR. 307 /// 308 /// This property corresponds to the LLVM IR inaccessiblememonly attribute. 309 FMRB_OnlyWritesInaccessibleMem = 310 FMRL_InaccessibleMem | static_cast<int>(ModRefInfo::Mod), 311 312 /// The only memory references in this function (if it has any) are 313 /// references of memory that is otherwise inaccessible via LLVM IR. 314 /// 315 /// This property corresponds to the LLVM IR inaccessiblememonly attribute. 316 FMRB_OnlyAccessesInaccessibleMem = 317 FMRL_InaccessibleMem | static_cast<int>(ModRefInfo::ModRef), 318 319 /// The function may perform non-volatile loads from objects pointed 320 /// to by its pointer-typed arguments, with arbitrary offsets, and 321 /// it may also perform loads of memory that is otherwise 322 /// inaccessible via LLVM IR. 323 /// 324 /// This property corresponds to the LLVM IR 325 /// inaccessiblemem_or_argmemonly attribute. 326 FMRB_OnlyReadsInaccessibleOrArgMem = FMRL_InaccessibleMem | 327 FMRL_ArgumentPointees | 328 static_cast<int>(ModRefInfo::Ref), 329 330 /// The function may perform non-volatile stores to objects pointed 331 /// to by its pointer-typed arguments, with arbitrary offsets, and 332 /// it may also perform stores of memory that is otherwise 333 /// inaccessible via LLVM IR. 334 /// 335 /// This property corresponds to the LLVM IR 336 /// inaccessiblemem_or_argmemonly attribute. 337 FMRB_OnlyWritesInaccessibleOrArgMem = FMRL_InaccessibleMem | 338 FMRL_ArgumentPointees | 339 static_cast<int>(ModRefInfo::Mod), 340 341 /// The function may perform non-volatile loads and stores of objects 342 /// pointed to by its pointer-typed arguments, with arbitrary offsets, and 343 /// it may also perform loads and stores of memory that is otherwise 344 /// inaccessible via LLVM IR. 345 /// 346 /// This property corresponds to the LLVM IR 347 /// inaccessiblemem_or_argmemonly attribute. 348 FMRB_OnlyAccessesInaccessibleOrArgMem = FMRL_InaccessibleMem | 349 FMRL_ArgumentPointees | 350 static_cast<int>(ModRefInfo::ModRef), 351 352 /// This function does not perform any non-local stores or volatile loads, 353 /// but may read from any memory location. 354 /// 355 /// This property corresponds to the GCC 'pure' attribute. 356 /// This property corresponds to the LLVM IR 'readonly' attribute. 357 /// This property corresponds to the IntrReadMem LLVM intrinsic flag. 358 FMRB_OnlyReadsMemory = FMRL_Anywhere | static_cast<int>(ModRefInfo::Ref), 359 360 // This function does not read from memory anywhere, but may write to any 361 // memory location. 362 // 363 // This property corresponds to the LLVM IR 'writeonly' attribute. 364 // This property corresponds to the IntrWriteMem LLVM intrinsic flag. 365 FMRB_OnlyWritesMemory = FMRL_Anywhere | static_cast<int>(ModRefInfo::Mod), 366 367 /// This indicates that the function could not be classified into one of the 368 /// behaviors above. 369 FMRB_UnknownModRefBehavior = 370 FMRL_Anywhere | static_cast<int>(ModRefInfo::ModRef) 371 }; 372 373 // Wrapper method strips bits significant only in FunctionModRefBehavior, 374 // to obtain a valid ModRefInfo. The benefit of using the wrapper is that if 375 // ModRefInfo enum changes, the wrapper can be updated to & with the new enum 376 // entry with all bits set to 1. 377 LLVM_NODISCARD inline ModRefInfo 378 createModRefInfo(const FunctionModRefBehavior FMRB) { 379 return ModRefInfo(FMRB & static_cast<int>(ModRefInfo::ModRef)); 380 } 381 382 /// Virtual base class for providers of capture information. 383 struct CaptureInfo { 384 virtual ~CaptureInfo() = 0; 385 virtual bool isNotCapturedBeforeOrAt(const Value *Object, 386 const Instruction *I) = 0; 387 }; 388 389 /// Context-free CaptureInfo provider, which computes and caches whether an 390 /// object is captured in the function at all, but does not distinguish whether 391 /// it was captured before or after the context instruction. 392 class SimpleCaptureInfo final : public CaptureInfo { 393 SmallDenseMap<const Value *, bool, 8> IsCapturedCache; 394 395 public: 396 bool isNotCapturedBeforeOrAt(const Value *Object, 397 const Instruction *I) override; 398 }; 399 400 /// Context-sensitive CaptureInfo provider, which computes and caches the 401 /// earliest common dominator closure of all captures. It provides a good 402 /// approximation to a precise "captures before" analysis. 403 class EarliestEscapeInfo final : public CaptureInfo { 404 DominatorTree &DT; 405 const LoopInfo &LI; 406 407 /// Map from identified local object to an instruction before which it does 408 /// not escape, or nullptr if it never escapes. The "earliest" instruction 409 /// may be a conservative approximation, e.g. the first instruction in the 410 /// function is always a legal choice. 411 DenseMap<const Value *, Instruction *> EarliestEscapes; 412 413 /// Reverse map from instruction to the objects it is the earliest escape for. 414 /// This is used for cache invalidation purposes. 415 DenseMap<Instruction *, TinyPtrVector<const Value *>> Inst2Obj; 416 417 public: 418 EarliestEscapeInfo(DominatorTree &DT, const LoopInfo &LI) : DT(DT), LI(LI) {} 419 420 bool isNotCapturedBeforeOrAt(const Value *Object, 421 const Instruction *I) override; 422 423 void removeInstruction(Instruction *I); 424 }; 425 426 /// Reduced version of MemoryLocation that only stores a pointer and size. 427 /// Used for caching AATags independent BasicAA results. 428 struct AACacheLoc { 429 const Value *Ptr; 430 LocationSize Size; 431 }; 432 433 template <> struct DenseMapInfo<AACacheLoc> { 434 static inline AACacheLoc getEmptyKey() { 435 return {DenseMapInfo<const Value *>::getEmptyKey(), 436 DenseMapInfo<LocationSize>::getEmptyKey()}; 437 } 438 static inline AACacheLoc getTombstoneKey() { 439 return {DenseMapInfo<const Value *>::getTombstoneKey(), 440 DenseMapInfo<LocationSize>::getTombstoneKey()}; 441 } 442 static unsigned getHashValue(const AACacheLoc &Val) { 443 return DenseMapInfo<const Value *>::getHashValue(Val.Ptr) ^ 444 DenseMapInfo<LocationSize>::getHashValue(Val.Size); 445 } 446 static bool isEqual(const AACacheLoc &LHS, const AACacheLoc &RHS) { 447 return LHS.Ptr == RHS.Ptr && LHS.Size == RHS.Size; 448 } 449 }; 450 451 /// This class stores info we want to provide to or retain within an alias 452 /// query. By default, the root query is stateless and starts with a freshly 453 /// constructed info object. Specific alias analyses can use this query info to 454 /// store per-query state that is important for recursive or nested queries to 455 /// avoid recomputing. To enable preserving this state across multiple queries 456 /// where safe (due to the IR not changing), use a `BatchAAResults` wrapper. 457 /// The information stored in an `AAQueryInfo` is currently limitted to the 458 /// caches used by BasicAA, but can further be extended to fit other AA needs. 459 class AAQueryInfo { 460 public: 461 using LocPair = std::pair<AACacheLoc, AACacheLoc>; 462 struct CacheEntry { 463 AliasResult Result; 464 /// Number of times a NoAlias assumption has been used. 465 /// 0 for assumptions that have not been used, -1 for definitive results. 466 int NumAssumptionUses; 467 /// Whether this is a definitive (non-assumption) result. 468 bool isDefinitive() const { return NumAssumptionUses < 0; } 469 }; 470 using AliasCacheT = SmallDenseMap<LocPair, CacheEntry, 8>; 471 AliasCacheT AliasCache; 472 473 CaptureInfo *CI; 474 475 /// Query depth used to distinguish recursive queries. 476 unsigned Depth = 0; 477 478 /// How many active NoAlias assumption uses there are. 479 int NumAssumptionUses = 0; 480 481 /// Location pairs for which an assumption based result is currently stored. 482 /// Used to remove all potentially incorrect results from the cache if an 483 /// assumption is disproven. 484 SmallVector<AAQueryInfo::LocPair, 4> AssumptionBasedResults; 485 486 AAQueryInfo(CaptureInfo *CI) : CI(CI) {} 487 488 /// Create a new AAQueryInfo based on this one, but with the cache cleared. 489 /// This is used for recursive queries across phis, where cache results may 490 /// not be valid. 491 AAQueryInfo withEmptyCache() { 492 AAQueryInfo NewAAQI(CI); 493 NewAAQI.Depth = Depth; 494 return NewAAQI; 495 } 496 }; 497 498 /// AAQueryInfo that uses SimpleCaptureInfo. 499 class SimpleAAQueryInfo : public AAQueryInfo { 500 SimpleCaptureInfo CI; 501 502 public: 503 SimpleAAQueryInfo() : AAQueryInfo(&CI) {} 504 }; 505 506 class BatchAAResults; 507 508 class AAResults { 509 public: 510 // Make these results default constructable and movable. We have to spell 511 // these out because MSVC won't synthesize them. 512 AAResults(const TargetLibraryInfo &TLI) : TLI(TLI) {} 513 AAResults(AAResults &&Arg); 514 ~AAResults(); 515 516 /// Register a specific AA result. 517 template <typename AAResultT> void addAAResult(AAResultT &AAResult) { 518 // FIXME: We should use a much lighter weight system than the usual 519 // polymorphic pattern because we don't own AAResult. It should 520 // ideally involve two pointers and no separate allocation. 521 AAs.emplace_back(new Model<AAResultT>(AAResult, *this)); 522 } 523 524 /// Register a function analysis ID that the results aggregation depends on. 525 /// 526 /// This is used in the new pass manager to implement the invalidation logic 527 /// where we must invalidate the results aggregation if any of our component 528 /// analyses become invalid. 529 void addAADependencyID(AnalysisKey *ID) { AADeps.push_back(ID); } 530 531 /// Handle invalidation events in the new pass manager. 532 /// 533 /// The aggregation is invalidated if any of the underlying analyses is 534 /// invalidated. 535 bool invalidate(Function &F, const PreservedAnalyses &PA, 536 FunctionAnalysisManager::Invalidator &Inv); 537 538 //===--------------------------------------------------------------------===// 539 /// \name Alias Queries 540 /// @{ 541 542 /// The main low level interface to the alias analysis implementation. 543 /// Returns an AliasResult indicating whether the two pointers are aliased to 544 /// each other. This is the interface that must be implemented by specific 545 /// alias analysis implementations. 546 AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB); 547 548 /// A convenience wrapper around the primary \c alias interface. 549 AliasResult alias(const Value *V1, LocationSize V1Size, const Value *V2, 550 LocationSize V2Size) { 551 return alias(MemoryLocation(V1, V1Size), MemoryLocation(V2, V2Size)); 552 } 553 554 /// A convenience wrapper around the primary \c alias interface. 555 AliasResult alias(const Value *V1, const Value *V2) { 556 return alias(MemoryLocation::getBeforeOrAfter(V1), 557 MemoryLocation::getBeforeOrAfter(V2)); 558 } 559 560 /// A trivial helper function to check to see if the specified pointers are 561 /// no-alias. 562 bool isNoAlias(const MemoryLocation &LocA, const MemoryLocation &LocB) { 563 return alias(LocA, LocB) == AliasResult::NoAlias; 564 } 565 566 /// A convenience wrapper around the \c isNoAlias helper interface. 567 bool isNoAlias(const Value *V1, LocationSize V1Size, const Value *V2, 568 LocationSize V2Size) { 569 return isNoAlias(MemoryLocation(V1, V1Size), MemoryLocation(V2, V2Size)); 570 } 571 572 /// A convenience wrapper around the \c isNoAlias helper interface. 573 bool isNoAlias(const Value *V1, const Value *V2) { 574 return isNoAlias(MemoryLocation::getBeforeOrAfter(V1), 575 MemoryLocation::getBeforeOrAfter(V2)); 576 } 577 578 /// A trivial helper function to check to see if the specified pointers are 579 /// must-alias. 580 bool isMustAlias(const MemoryLocation &LocA, const MemoryLocation &LocB) { 581 return alias(LocA, LocB) == AliasResult::MustAlias; 582 } 583 584 /// A convenience wrapper around the \c isMustAlias helper interface. 585 bool isMustAlias(const Value *V1, const Value *V2) { 586 return alias(V1, LocationSize::precise(1), V2, LocationSize::precise(1)) == 587 AliasResult::MustAlias; 588 } 589 590 /// Checks whether the given location points to constant memory, or if 591 /// \p OrLocal is true whether it points to a local alloca. 592 bool pointsToConstantMemory(const MemoryLocation &Loc, bool OrLocal = false); 593 594 /// A convenience wrapper around the primary \c pointsToConstantMemory 595 /// interface. 596 bool pointsToConstantMemory(const Value *P, bool OrLocal = false) { 597 return pointsToConstantMemory(MemoryLocation::getBeforeOrAfter(P), OrLocal); 598 } 599 600 /// @} 601 //===--------------------------------------------------------------------===// 602 /// \name Simple mod/ref information 603 /// @{ 604 605 /// Get the ModRef info associated with a pointer argument of a call. The 606 /// result's bits are set to indicate the allowed aliasing ModRef kinds. Note 607 /// that these bits do not necessarily account for the overall behavior of 608 /// the function, but rather only provide additional per-argument 609 /// information. This never sets ModRefInfo::Must. 610 ModRefInfo getArgModRefInfo(const CallBase *Call, unsigned ArgIdx); 611 612 /// Return the behavior of the given call site. 613 FunctionModRefBehavior getModRefBehavior(const CallBase *Call); 614 615 /// Return the behavior when calling the given function. 616 FunctionModRefBehavior getModRefBehavior(const Function *F); 617 618 /// Checks if the specified call is known to never read or write memory. 619 /// 620 /// Note that if the call only reads from known-constant memory, it is also 621 /// legal to return true. Also, calls that unwind the stack are legal for 622 /// this predicate. 623 /// 624 /// Many optimizations (such as CSE and LICM) can be performed on such calls 625 /// without worrying about aliasing properties, and many calls have this 626 /// property (e.g. calls to 'sin' and 'cos'). 627 /// 628 /// This property corresponds to the GCC 'const' attribute. 629 bool doesNotAccessMemory(const CallBase *Call) { 630 return getModRefBehavior(Call) == FMRB_DoesNotAccessMemory; 631 } 632 633 /// Checks if the specified function is known to never read or write memory. 634 /// 635 /// Note that if the function only reads from known-constant memory, it is 636 /// also legal to return true. Also, function that unwind the stack are legal 637 /// for this predicate. 638 /// 639 /// Many optimizations (such as CSE and LICM) can be performed on such calls 640 /// to such functions without worrying about aliasing properties, and many 641 /// functions have this property (e.g. 'sin' and 'cos'). 642 /// 643 /// This property corresponds to the GCC 'const' attribute. 644 bool doesNotAccessMemory(const Function *F) { 645 return getModRefBehavior(F) == FMRB_DoesNotAccessMemory; 646 } 647 648 /// Checks if the specified call is known to only read from non-volatile 649 /// memory (or not access memory at all). 650 /// 651 /// Calls that unwind the stack are legal for this predicate. 652 /// 653 /// This property allows many common optimizations to be performed in the 654 /// absence of interfering store instructions, such as CSE of strlen calls. 655 /// 656 /// This property corresponds to the GCC 'pure' attribute. 657 bool onlyReadsMemory(const CallBase *Call) { 658 return onlyReadsMemory(getModRefBehavior(Call)); 659 } 660 661 /// Checks if the specified function is known to only read from non-volatile 662 /// memory (or not access memory at all). 663 /// 664 /// Functions that unwind the stack are legal for this predicate. 665 /// 666 /// This property allows many common optimizations to be performed in the 667 /// absence of interfering store instructions, such as CSE of strlen calls. 668 /// 669 /// This property corresponds to the GCC 'pure' attribute. 670 bool onlyReadsMemory(const Function *F) { 671 return onlyReadsMemory(getModRefBehavior(F)); 672 } 673 674 /// Checks if functions with the specified behavior are known to only read 675 /// from non-volatile memory (or not access memory at all). 676 static bool onlyReadsMemory(FunctionModRefBehavior MRB) { 677 return !isModSet(createModRefInfo(MRB)); 678 } 679 680 /// Checks if functions with the specified behavior are known to only write 681 /// memory (or not access memory at all). 682 static bool doesNotReadMemory(FunctionModRefBehavior MRB) { 683 return !isRefSet(createModRefInfo(MRB)); 684 } 685 686 /// Checks if functions with the specified behavior are known to read and 687 /// write at most from objects pointed to by their pointer-typed arguments 688 /// (with arbitrary offsets). 689 static bool onlyAccessesArgPointees(FunctionModRefBehavior MRB) { 690 return !((unsigned)MRB & FMRL_Anywhere & ~FMRL_ArgumentPointees); 691 } 692 693 /// Checks if functions with the specified behavior are known to potentially 694 /// read or write from objects pointed to be their pointer-typed arguments 695 /// (with arbitrary offsets). 696 static bool doesAccessArgPointees(FunctionModRefBehavior MRB) { 697 return isModOrRefSet(createModRefInfo(MRB)) && 698 ((unsigned)MRB & FMRL_ArgumentPointees); 699 } 700 701 /// Checks if functions with the specified behavior are known to read and 702 /// write at most from memory that is inaccessible from LLVM IR. 703 static bool onlyAccessesInaccessibleMem(FunctionModRefBehavior MRB) { 704 return !((unsigned)MRB & FMRL_Anywhere & ~FMRL_InaccessibleMem); 705 } 706 707 /// Checks if functions with the specified behavior are known to potentially 708 /// read or write from memory that is inaccessible from LLVM IR. 709 static bool doesAccessInaccessibleMem(FunctionModRefBehavior MRB) { 710 return isModOrRefSet(createModRefInfo(MRB)) && 711 ((unsigned)MRB & FMRL_InaccessibleMem); 712 } 713 714 /// Checks if functions with the specified behavior are known to read and 715 /// write at most from memory that is inaccessible from LLVM IR or objects 716 /// pointed to by their pointer-typed arguments (with arbitrary offsets). 717 static bool onlyAccessesInaccessibleOrArgMem(FunctionModRefBehavior MRB) { 718 return !((unsigned)MRB & FMRL_Anywhere & 719 ~(FMRL_InaccessibleMem | FMRL_ArgumentPointees)); 720 } 721 722 /// getModRefInfo (for call sites) - Return information about whether 723 /// a particular call site modifies or reads the specified memory location. 724 ModRefInfo getModRefInfo(const CallBase *Call, const MemoryLocation &Loc); 725 726 /// getModRefInfo (for call sites) - A convenience wrapper. 727 ModRefInfo getModRefInfo(const CallBase *Call, const Value *P, 728 LocationSize Size) { 729 return getModRefInfo(Call, MemoryLocation(P, Size)); 730 } 731 732 /// getModRefInfo (for loads) - Return information about whether 733 /// a particular load modifies or reads the specified memory location. 734 ModRefInfo getModRefInfo(const LoadInst *L, const MemoryLocation &Loc); 735 736 /// getModRefInfo (for loads) - A convenience wrapper. 737 ModRefInfo getModRefInfo(const LoadInst *L, const Value *P, 738 LocationSize Size) { 739 return getModRefInfo(L, MemoryLocation(P, Size)); 740 } 741 742 /// getModRefInfo (for stores) - Return information about whether 743 /// a particular store modifies or reads the specified memory location. 744 ModRefInfo getModRefInfo(const StoreInst *S, const MemoryLocation &Loc); 745 746 /// getModRefInfo (for stores) - A convenience wrapper. 747 ModRefInfo getModRefInfo(const StoreInst *S, const Value *P, 748 LocationSize Size) { 749 return getModRefInfo(S, MemoryLocation(P, Size)); 750 } 751 752 /// getModRefInfo (for fences) - Return information about whether 753 /// a particular store modifies or reads the specified memory location. 754 ModRefInfo getModRefInfo(const FenceInst *S, const MemoryLocation &Loc); 755 756 /// getModRefInfo (for fences) - A convenience wrapper. 757 ModRefInfo getModRefInfo(const FenceInst *S, const Value *P, 758 LocationSize Size) { 759 return getModRefInfo(S, MemoryLocation(P, Size)); 760 } 761 762 /// getModRefInfo (for cmpxchges) - Return information about whether 763 /// a particular cmpxchg modifies or reads the specified memory location. 764 ModRefInfo getModRefInfo(const AtomicCmpXchgInst *CX, 765 const MemoryLocation &Loc); 766 767 /// getModRefInfo (for cmpxchges) - A convenience wrapper. 768 ModRefInfo getModRefInfo(const AtomicCmpXchgInst *CX, const Value *P, 769 LocationSize Size) { 770 return getModRefInfo(CX, MemoryLocation(P, Size)); 771 } 772 773 /// getModRefInfo (for atomicrmws) - Return information about whether 774 /// a particular atomicrmw modifies or reads the specified memory location. 775 ModRefInfo getModRefInfo(const AtomicRMWInst *RMW, const MemoryLocation &Loc); 776 777 /// getModRefInfo (for atomicrmws) - A convenience wrapper. 778 ModRefInfo getModRefInfo(const AtomicRMWInst *RMW, const Value *P, 779 LocationSize Size) { 780 return getModRefInfo(RMW, MemoryLocation(P, Size)); 781 } 782 783 /// getModRefInfo (for va_args) - Return information about whether 784 /// a particular va_arg modifies or reads the specified memory location. 785 ModRefInfo getModRefInfo(const VAArgInst *I, const MemoryLocation &Loc); 786 787 /// getModRefInfo (for va_args) - A convenience wrapper. 788 ModRefInfo getModRefInfo(const VAArgInst *I, const Value *P, 789 LocationSize Size) { 790 return getModRefInfo(I, MemoryLocation(P, Size)); 791 } 792 793 /// getModRefInfo (for catchpads) - Return information about whether 794 /// a particular catchpad modifies or reads the specified memory location. 795 ModRefInfo getModRefInfo(const CatchPadInst *I, const MemoryLocation &Loc); 796 797 /// getModRefInfo (for catchpads) - A convenience wrapper. 798 ModRefInfo getModRefInfo(const CatchPadInst *I, const Value *P, 799 LocationSize Size) { 800 return getModRefInfo(I, MemoryLocation(P, Size)); 801 } 802 803 /// getModRefInfo (for catchrets) - Return information about whether 804 /// a particular catchret modifies or reads the specified memory location. 805 ModRefInfo getModRefInfo(const CatchReturnInst *I, const MemoryLocation &Loc); 806 807 /// getModRefInfo (for catchrets) - A convenience wrapper. 808 ModRefInfo getModRefInfo(const CatchReturnInst *I, const Value *P, 809 LocationSize Size) { 810 return getModRefInfo(I, MemoryLocation(P, Size)); 811 } 812 813 /// Check whether or not an instruction may read or write the optionally 814 /// specified memory location. 815 /// 816 /// 817 /// An instruction that doesn't read or write memory may be trivially LICM'd 818 /// for example. 819 /// 820 /// For function calls, this delegates to the alias-analysis specific 821 /// call-site mod-ref behavior queries. Otherwise it delegates to the specific 822 /// helpers above. 823 ModRefInfo getModRefInfo(const Instruction *I, 824 const Optional<MemoryLocation> &OptLoc) { 825 SimpleAAQueryInfo AAQIP; 826 return getModRefInfo(I, OptLoc, AAQIP); 827 } 828 829 /// A convenience wrapper for constructing the memory location. 830 ModRefInfo getModRefInfo(const Instruction *I, const Value *P, 831 LocationSize Size) { 832 return getModRefInfo(I, MemoryLocation(P, Size)); 833 } 834 835 /// Return information about whether a call and an instruction may refer to 836 /// the same memory locations. 837 ModRefInfo getModRefInfo(Instruction *I, const CallBase *Call); 838 839 /// Return information about whether two call sites may refer to the same set 840 /// of memory locations. See the AA documentation for details: 841 /// http://llvm.org/docs/AliasAnalysis.html#ModRefInfo 842 ModRefInfo getModRefInfo(const CallBase *Call1, const CallBase *Call2); 843 844 /// Return information about whether a particular call site modifies 845 /// or reads the specified memory location \p MemLoc before instruction \p I 846 /// in a BasicBlock. 847 /// Early exits in callCapturesBefore may lead to ModRefInfo::Must not being 848 /// set. 849 ModRefInfo callCapturesBefore(const Instruction *I, 850 const MemoryLocation &MemLoc, 851 DominatorTree *DT) { 852 SimpleAAQueryInfo AAQIP; 853 return callCapturesBefore(I, MemLoc, DT, AAQIP); 854 } 855 856 /// A convenience wrapper to synthesize a memory location. 857 ModRefInfo callCapturesBefore(const Instruction *I, const Value *P, 858 LocationSize Size, DominatorTree *DT) { 859 return callCapturesBefore(I, MemoryLocation(P, Size), DT); 860 } 861 862 /// @} 863 //===--------------------------------------------------------------------===// 864 /// \name Higher level methods for querying mod/ref information. 865 /// @{ 866 867 /// Check if it is possible for execution of the specified basic block to 868 /// modify the location Loc. 869 bool canBasicBlockModify(const BasicBlock &BB, const MemoryLocation &Loc); 870 871 /// A convenience wrapper synthesizing a memory location. 872 bool canBasicBlockModify(const BasicBlock &BB, const Value *P, 873 LocationSize Size) { 874 return canBasicBlockModify(BB, MemoryLocation(P, Size)); 875 } 876 877 /// Check if it is possible for the execution of the specified instructions 878 /// to mod\ref (according to the mode) the location Loc. 879 /// 880 /// The instructions to consider are all of the instructions in the range of 881 /// [I1,I2] INCLUSIVE. I1 and I2 must be in the same basic block. 882 bool canInstructionRangeModRef(const Instruction &I1, const Instruction &I2, 883 const MemoryLocation &Loc, 884 const ModRefInfo Mode); 885 886 /// A convenience wrapper synthesizing a memory location. 887 bool canInstructionRangeModRef(const Instruction &I1, const Instruction &I2, 888 const Value *Ptr, LocationSize Size, 889 const ModRefInfo Mode) { 890 return canInstructionRangeModRef(I1, I2, MemoryLocation(Ptr, Size), Mode); 891 } 892 893 private: 894 AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB, 895 AAQueryInfo &AAQI); 896 bool pointsToConstantMemory(const MemoryLocation &Loc, AAQueryInfo &AAQI, 897 bool OrLocal = false); 898 ModRefInfo getModRefInfo(Instruction *I, const CallBase *Call2, 899 AAQueryInfo &AAQIP); 900 ModRefInfo getModRefInfo(const CallBase *Call, const MemoryLocation &Loc, 901 AAQueryInfo &AAQI); 902 ModRefInfo getModRefInfo(const CallBase *Call1, const CallBase *Call2, 903 AAQueryInfo &AAQI); 904 ModRefInfo getModRefInfo(const VAArgInst *V, const MemoryLocation &Loc, 905 AAQueryInfo &AAQI); 906 ModRefInfo getModRefInfo(const LoadInst *L, const MemoryLocation &Loc, 907 AAQueryInfo &AAQI); 908 ModRefInfo getModRefInfo(const StoreInst *S, const MemoryLocation &Loc, 909 AAQueryInfo &AAQI); 910 ModRefInfo getModRefInfo(const FenceInst *S, const MemoryLocation &Loc, 911 AAQueryInfo &AAQI); 912 ModRefInfo getModRefInfo(const AtomicCmpXchgInst *CX, 913 const MemoryLocation &Loc, AAQueryInfo &AAQI); 914 ModRefInfo getModRefInfo(const AtomicRMWInst *RMW, const MemoryLocation &Loc, 915 AAQueryInfo &AAQI); 916 ModRefInfo getModRefInfo(const CatchPadInst *I, const MemoryLocation &Loc, 917 AAQueryInfo &AAQI); 918 ModRefInfo getModRefInfo(const CatchReturnInst *I, const MemoryLocation &Loc, 919 AAQueryInfo &AAQI); 920 ModRefInfo getModRefInfo(const Instruction *I, 921 const Optional<MemoryLocation> &OptLoc, 922 AAQueryInfo &AAQIP); 923 ModRefInfo callCapturesBefore(const Instruction *I, 924 const MemoryLocation &MemLoc, DominatorTree *DT, 925 AAQueryInfo &AAQIP); 926 927 class Concept; 928 929 template <typename T> class Model; 930 931 template <typename T> friend class AAResultBase; 932 933 const TargetLibraryInfo &TLI; 934 935 std::vector<std::unique_ptr<Concept>> AAs; 936 937 std::vector<AnalysisKey *> AADeps; 938 939 friend class BatchAAResults; 940 }; 941 942 /// This class is a wrapper over an AAResults, and it is intended to be used 943 /// only when there are no IR changes inbetween queries. BatchAAResults is 944 /// reusing the same `AAQueryInfo` to preserve the state across queries, 945 /// esentially making AA work in "batch mode". The internal state cannot be 946 /// cleared, so to go "out-of-batch-mode", the user must either use AAResults, 947 /// or create a new BatchAAResults. 948 class BatchAAResults { 949 AAResults &AA; 950 AAQueryInfo AAQI; 951 SimpleCaptureInfo SimpleCI; 952 953 public: 954 BatchAAResults(AAResults &AAR) : AA(AAR), AAQI(&SimpleCI) {} 955 BatchAAResults(AAResults &AAR, CaptureInfo *CI) : AA(AAR), AAQI(CI) {} 956 957 AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB) { 958 return AA.alias(LocA, LocB, AAQI); 959 } 960 bool pointsToConstantMemory(const MemoryLocation &Loc, bool OrLocal = false) { 961 return AA.pointsToConstantMemory(Loc, AAQI, OrLocal); 962 } 963 ModRefInfo getModRefInfo(const CallBase *Call, const MemoryLocation &Loc) { 964 return AA.getModRefInfo(Call, Loc, AAQI); 965 } 966 ModRefInfo getModRefInfo(const CallBase *Call1, const CallBase *Call2) { 967 return AA.getModRefInfo(Call1, Call2, AAQI); 968 } 969 ModRefInfo getModRefInfo(const Instruction *I, 970 const Optional<MemoryLocation> &OptLoc) { 971 return AA.getModRefInfo(I, OptLoc, AAQI); 972 } 973 ModRefInfo getModRefInfo(Instruction *I, const CallBase *Call2) { 974 return AA.getModRefInfo(I, Call2, AAQI); 975 } 976 ModRefInfo getArgModRefInfo(const CallBase *Call, unsigned ArgIdx) { 977 return AA.getArgModRefInfo(Call, ArgIdx); 978 } 979 FunctionModRefBehavior getModRefBehavior(const CallBase *Call) { 980 return AA.getModRefBehavior(Call); 981 } 982 bool isMustAlias(const MemoryLocation &LocA, const MemoryLocation &LocB) { 983 return alias(LocA, LocB) == AliasResult::MustAlias; 984 } 985 bool isMustAlias(const Value *V1, const Value *V2) { 986 return alias(MemoryLocation(V1, LocationSize::precise(1)), 987 MemoryLocation(V2, LocationSize::precise(1))) == 988 AliasResult::MustAlias; 989 } 990 ModRefInfo callCapturesBefore(const Instruction *I, 991 const MemoryLocation &MemLoc, 992 DominatorTree *DT) { 993 return AA.callCapturesBefore(I, MemLoc, DT, AAQI); 994 } 995 }; 996 997 /// Temporary typedef for legacy code that uses a generic \c AliasAnalysis 998 /// pointer or reference. 999 using AliasAnalysis = AAResults; 1000 1001 /// A private abstract base class describing the concept of an individual alias 1002 /// analysis implementation. 1003 /// 1004 /// This interface is implemented by any \c Model instantiation. It is also the 1005 /// interface which a type used to instantiate the model must provide. 1006 /// 1007 /// All of these methods model methods by the same name in the \c 1008 /// AAResults class. Only differences and specifics to how the 1009 /// implementations are called are documented here. 1010 class AAResults::Concept { 1011 public: 1012 virtual ~Concept() = 0; 1013 1014 /// An update API used internally by the AAResults to provide 1015 /// a handle back to the top level aggregation. 1016 virtual void setAAResults(AAResults *NewAAR) = 0; 1017 1018 //===--------------------------------------------------------------------===// 1019 /// \name Alias Queries 1020 /// @{ 1021 1022 /// The main low level interface to the alias analysis implementation. 1023 /// Returns an AliasResult indicating whether the two pointers are aliased to 1024 /// each other. This is the interface that must be implemented by specific 1025 /// alias analysis implementations. 1026 virtual AliasResult alias(const MemoryLocation &LocA, 1027 const MemoryLocation &LocB, AAQueryInfo &AAQI) = 0; 1028 1029 /// Checks whether the given location points to constant memory, or if 1030 /// \p OrLocal is true whether it points to a local alloca. 1031 virtual bool pointsToConstantMemory(const MemoryLocation &Loc, 1032 AAQueryInfo &AAQI, bool OrLocal) = 0; 1033 1034 /// @} 1035 //===--------------------------------------------------------------------===// 1036 /// \name Simple mod/ref information 1037 /// @{ 1038 1039 /// Get the ModRef info associated with a pointer argument of a callsite. The 1040 /// result's bits are set to indicate the allowed aliasing ModRef kinds. Note 1041 /// that these bits do not necessarily account for the overall behavior of 1042 /// the function, but rather only provide additional per-argument 1043 /// information. 1044 virtual ModRefInfo getArgModRefInfo(const CallBase *Call, 1045 unsigned ArgIdx) = 0; 1046 1047 /// Return the behavior of the given call site. 1048 virtual FunctionModRefBehavior getModRefBehavior(const CallBase *Call) = 0; 1049 1050 /// Return the behavior when calling the given function. 1051 virtual FunctionModRefBehavior getModRefBehavior(const Function *F) = 0; 1052 1053 /// getModRefInfo (for call sites) - Return information about whether 1054 /// a particular call site modifies or reads the specified memory location. 1055 virtual ModRefInfo getModRefInfo(const CallBase *Call, 1056 const MemoryLocation &Loc, 1057 AAQueryInfo &AAQI) = 0; 1058 1059 /// Return information about whether two call sites may refer to the same set 1060 /// of memory locations. See the AA documentation for details: 1061 /// http://llvm.org/docs/AliasAnalysis.html#ModRefInfo 1062 virtual ModRefInfo getModRefInfo(const CallBase *Call1, const CallBase *Call2, 1063 AAQueryInfo &AAQI) = 0; 1064 1065 /// @} 1066 }; 1067 1068 /// A private class template which derives from \c Concept and wraps some other 1069 /// type. 1070 /// 1071 /// This models the concept by directly forwarding each interface point to the 1072 /// wrapped type which must implement a compatible interface. This provides 1073 /// a type erased binding. 1074 template <typename AAResultT> class AAResults::Model final : public Concept { 1075 AAResultT &Result; 1076 1077 public: 1078 explicit Model(AAResultT &Result, AAResults &AAR) : Result(Result) { 1079 Result.setAAResults(&AAR); 1080 } 1081 ~Model() override = default; 1082 1083 void setAAResults(AAResults *NewAAR) override { Result.setAAResults(NewAAR); } 1084 1085 AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB, 1086 AAQueryInfo &AAQI) override { 1087 return Result.alias(LocA, LocB, AAQI); 1088 } 1089 1090 bool pointsToConstantMemory(const MemoryLocation &Loc, AAQueryInfo &AAQI, 1091 bool OrLocal) override { 1092 return Result.pointsToConstantMemory(Loc, AAQI, OrLocal); 1093 } 1094 1095 ModRefInfo getArgModRefInfo(const CallBase *Call, unsigned ArgIdx) override { 1096 return Result.getArgModRefInfo(Call, ArgIdx); 1097 } 1098 1099 FunctionModRefBehavior getModRefBehavior(const CallBase *Call) override { 1100 return Result.getModRefBehavior(Call); 1101 } 1102 1103 FunctionModRefBehavior getModRefBehavior(const Function *F) override { 1104 return Result.getModRefBehavior(F); 1105 } 1106 1107 ModRefInfo getModRefInfo(const CallBase *Call, const MemoryLocation &Loc, 1108 AAQueryInfo &AAQI) override { 1109 return Result.getModRefInfo(Call, Loc, AAQI); 1110 } 1111 1112 ModRefInfo getModRefInfo(const CallBase *Call1, const CallBase *Call2, 1113 AAQueryInfo &AAQI) override { 1114 return Result.getModRefInfo(Call1, Call2, AAQI); 1115 } 1116 }; 1117 1118 /// A CRTP-driven "mixin" base class to help implement the function alias 1119 /// analysis results concept. 1120 /// 1121 /// Because of the nature of many alias analysis implementations, they often 1122 /// only implement a subset of the interface. This base class will attempt to 1123 /// implement the remaining portions of the interface in terms of simpler forms 1124 /// of the interface where possible, and otherwise provide conservatively 1125 /// correct fallback implementations. 1126 /// 1127 /// Implementors of an alias analysis should derive from this CRTP, and then 1128 /// override specific methods that they wish to customize. There is no need to 1129 /// use virtual anywhere, the CRTP base class does static dispatch to the 1130 /// derived type passed into it. 1131 template <typename DerivedT> class AAResultBase { 1132 // Expose some parts of the interface only to the AAResults::Model 1133 // for wrapping. Specifically, this allows the model to call our 1134 // setAAResults method without exposing it as a fully public API. 1135 friend class AAResults::Model<DerivedT>; 1136 1137 /// A pointer to the AAResults object that this AAResult is 1138 /// aggregated within. May be null if not aggregated. 1139 AAResults *AAR = nullptr; 1140 1141 /// Helper to dispatch calls back through the derived type. 1142 DerivedT &derived() { return static_cast<DerivedT &>(*this); } 1143 1144 /// A setter for the AAResults pointer, which is used to satisfy the 1145 /// AAResults::Model contract. 1146 void setAAResults(AAResults *NewAAR) { AAR = NewAAR; } 1147 1148 protected: 1149 /// This proxy class models a common pattern where we delegate to either the 1150 /// top-level \c AAResults aggregation if one is registered, or to the 1151 /// current result if none are registered. 1152 class AAResultsProxy { 1153 AAResults *AAR; 1154 DerivedT &CurrentResult; 1155 1156 public: 1157 AAResultsProxy(AAResults *AAR, DerivedT &CurrentResult) 1158 : AAR(AAR), CurrentResult(CurrentResult) {} 1159 1160 AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB, 1161 AAQueryInfo &AAQI) { 1162 return AAR ? AAR->alias(LocA, LocB, AAQI) 1163 : CurrentResult.alias(LocA, LocB, AAQI); 1164 } 1165 1166 bool pointsToConstantMemory(const MemoryLocation &Loc, AAQueryInfo &AAQI, 1167 bool OrLocal) { 1168 return AAR ? AAR->pointsToConstantMemory(Loc, AAQI, OrLocal) 1169 : CurrentResult.pointsToConstantMemory(Loc, AAQI, OrLocal); 1170 } 1171 1172 ModRefInfo getArgModRefInfo(const CallBase *Call, unsigned ArgIdx) { 1173 return AAR ? AAR->getArgModRefInfo(Call, ArgIdx) 1174 : CurrentResult.getArgModRefInfo(Call, ArgIdx); 1175 } 1176 1177 FunctionModRefBehavior getModRefBehavior(const CallBase *Call) { 1178 return AAR ? AAR->getModRefBehavior(Call) 1179 : CurrentResult.getModRefBehavior(Call); 1180 } 1181 1182 FunctionModRefBehavior getModRefBehavior(const Function *F) { 1183 return AAR ? AAR->getModRefBehavior(F) : CurrentResult.getModRefBehavior(F); 1184 } 1185 1186 ModRefInfo getModRefInfo(const CallBase *Call, const MemoryLocation &Loc, 1187 AAQueryInfo &AAQI) { 1188 return AAR ? AAR->getModRefInfo(Call, Loc, AAQI) 1189 : CurrentResult.getModRefInfo(Call, Loc, AAQI); 1190 } 1191 1192 ModRefInfo getModRefInfo(const CallBase *Call1, const CallBase *Call2, 1193 AAQueryInfo &AAQI) { 1194 return AAR ? AAR->getModRefInfo(Call1, Call2, AAQI) 1195 : CurrentResult.getModRefInfo(Call1, Call2, AAQI); 1196 } 1197 }; 1198 1199 explicit AAResultBase() = default; 1200 1201 // Provide all the copy and move constructors so that derived types aren't 1202 // constrained. 1203 AAResultBase(const AAResultBase &Arg) {} 1204 AAResultBase(AAResultBase &&Arg) {} 1205 1206 /// Get a proxy for the best AA result set to query at this time. 1207 /// 1208 /// When this result is part of a larger aggregation, this will proxy to that 1209 /// aggregation. When this result is used in isolation, it will just delegate 1210 /// back to the derived class's implementation. 1211 /// 1212 /// Note that callers of this need to take considerable care to not cause 1213 /// performance problems when they use this routine, in the case of a large 1214 /// number of alias analyses being aggregated, it can be expensive to walk 1215 /// back across the chain. 1216 AAResultsProxy getBestAAResults() { return AAResultsProxy(AAR, derived()); } 1217 1218 public: 1219 AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB, 1220 AAQueryInfo &AAQI) { 1221 return AliasResult::MayAlias; 1222 } 1223 1224 bool pointsToConstantMemory(const MemoryLocation &Loc, AAQueryInfo &AAQI, 1225 bool OrLocal) { 1226 return false; 1227 } 1228 1229 ModRefInfo getArgModRefInfo(const CallBase *Call, unsigned ArgIdx) { 1230 return ModRefInfo::ModRef; 1231 } 1232 1233 FunctionModRefBehavior getModRefBehavior(const CallBase *Call) { 1234 return FMRB_UnknownModRefBehavior; 1235 } 1236 1237 FunctionModRefBehavior getModRefBehavior(const Function *F) { 1238 return FMRB_UnknownModRefBehavior; 1239 } 1240 1241 ModRefInfo getModRefInfo(const CallBase *Call, const MemoryLocation &Loc, 1242 AAQueryInfo &AAQI) { 1243 return ModRefInfo::ModRef; 1244 } 1245 1246 ModRefInfo getModRefInfo(const CallBase *Call1, const CallBase *Call2, 1247 AAQueryInfo &AAQI) { 1248 return ModRefInfo::ModRef; 1249 } 1250 }; 1251 1252 /// Return true if this pointer is returned by a noalias function. 1253 bool isNoAliasCall(const Value *V); 1254 1255 /// Return true if this pointer refers to a distinct and identifiable object. 1256 /// This returns true for: 1257 /// Global Variables and Functions (but not Global Aliases) 1258 /// Allocas 1259 /// ByVal and NoAlias Arguments 1260 /// NoAlias returns (e.g. calls to malloc) 1261 /// 1262 bool isIdentifiedObject(const Value *V); 1263 1264 /// Return true if V is umabigously identified at the function-level. 1265 /// Different IdentifiedFunctionLocals can't alias. 1266 /// Further, an IdentifiedFunctionLocal can not alias with any function 1267 /// arguments other than itself, which is not necessarily true for 1268 /// IdentifiedObjects. 1269 bool isIdentifiedFunctionLocal(const Value *V); 1270 1271 /// A manager for alias analyses. 1272 /// 1273 /// This class can have analyses registered with it and when run, it will run 1274 /// all of them and aggregate their results into single AA results interface 1275 /// that dispatches across all of the alias analysis results available. 1276 /// 1277 /// Note that the order in which analyses are registered is very significant. 1278 /// That is the order in which the results will be aggregated and queried. 1279 /// 1280 /// This manager effectively wraps the AnalysisManager for registering alias 1281 /// analyses. When you register your alias analysis with this manager, it will 1282 /// ensure the analysis itself is registered with its AnalysisManager. 1283 /// 1284 /// The result of this analysis is only invalidated if one of the particular 1285 /// aggregated AA results end up being invalidated. This removes the need to 1286 /// explicitly preserve the results of `AAManager`. Note that analyses should no 1287 /// longer be registered once the `AAManager` is run. 1288 class AAManager : public AnalysisInfoMixin<AAManager> { 1289 public: 1290 using Result = AAResults; 1291 1292 /// Register a specific AA result. 1293 template <typename AnalysisT> void registerFunctionAnalysis() { 1294 ResultGetters.push_back(&getFunctionAAResultImpl<AnalysisT>); 1295 } 1296 1297 /// Register a specific AA result. 1298 template <typename AnalysisT> void registerModuleAnalysis() { 1299 ResultGetters.push_back(&getModuleAAResultImpl<AnalysisT>); 1300 } 1301 1302 Result run(Function &F, FunctionAnalysisManager &AM); 1303 1304 private: 1305 friend AnalysisInfoMixin<AAManager>; 1306 1307 static AnalysisKey Key; 1308 1309 SmallVector<void (*)(Function &F, FunctionAnalysisManager &AM, 1310 AAResults &AAResults), 1311 4> ResultGetters; 1312 1313 template <typename AnalysisT> 1314 static void getFunctionAAResultImpl(Function &F, 1315 FunctionAnalysisManager &AM, 1316 AAResults &AAResults) { 1317 AAResults.addAAResult(AM.template getResult<AnalysisT>(F)); 1318 AAResults.addAADependencyID(AnalysisT::ID()); 1319 } 1320 1321 template <typename AnalysisT> 1322 static void getModuleAAResultImpl(Function &F, FunctionAnalysisManager &AM, 1323 AAResults &AAResults) { 1324 auto &MAMProxy = AM.getResult<ModuleAnalysisManagerFunctionProxy>(F); 1325 if (auto *R = 1326 MAMProxy.template getCachedResult<AnalysisT>(*F.getParent())) { 1327 AAResults.addAAResult(*R); 1328 MAMProxy 1329 .template registerOuterAnalysisInvalidation<AnalysisT, AAManager>(); 1330 } 1331 } 1332 }; 1333 1334 /// A wrapper pass to provide the legacy pass manager access to a suitably 1335 /// prepared AAResults object. 1336 class AAResultsWrapperPass : public FunctionPass { 1337 std::unique_ptr<AAResults> AAR; 1338 1339 public: 1340 static char ID; 1341 1342 AAResultsWrapperPass(); 1343 1344 AAResults &getAAResults() { return *AAR; } 1345 const AAResults &getAAResults() const { return *AAR; } 1346 1347 bool runOnFunction(Function &F) override; 1348 1349 void getAnalysisUsage(AnalysisUsage &AU) const override; 1350 }; 1351 1352 /// A wrapper pass for external alias analyses. This just squirrels away the 1353 /// callback used to run any analyses and register their results. 1354 struct ExternalAAWrapperPass : ImmutablePass { 1355 using CallbackT = std::function<void(Pass &, Function &, AAResults &)>; 1356 1357 CallbackT CB; 1358 1359 static char ID; 1360 1361 ExternalAAWrapperPass(); 1362 1363 explicit ExternalAAWrapperPass(CallbackT CB); 1364 1365 void getAnalysisUsage(AnalysisUsage &AU) const override { 1366 AU.setPreservesAll(); 1367 } 1368 }; 1369 1370 FunctionPass *createAAResultsWrapperPass(); 1371 1372 /// A wrapper pass around a callback which can be used to populate the 1373 /// AAResults in the AAResultsWrapperPass from an external AA. 1374 /// 1375 /// The callback provided here will be used each time we prepare an AAResults 1376 /// object, and will receive a reference to the function wrapper pass, the 1377 /// function, and the AAResults object to populate. This should be used when 1378 /// setting up a custom pass pipeline to inject a hook into the AA results. 1379 ImmutablePass *createExternalAAWrapperPass( 1380 std::function<void(Pass &, Function &, AAResults &)> Callback); 1381 1382 /// A helper for the legacy pass manager to create a \c AAResults 1383 /// object populated to the best of our ability for a particular function when 1384 /// inside of a \c ModulePass or a \c CallGraphSCCPass. 1385 /// 1386 /// If a \c ModulePass or a \c CallGraphSCCPass calls \p 1387 /// createLegacyPMAAResults, it also needs to call \p addUsedAAAnalyses in \p 1388 /// getAnalysisUsage. 1389 AAResults createLegacyPMAAResults(Pass &P, Function &F, BasicAAResult &BAR); 1390 1391 /// A helper for the legacy pass manager to populate \p AU to add uses to make 1392 /// sure the analyses required by \p createLegacyPMAAResults are available. 1393 void getAAResultsAnalysisUsage(AnalysisUsage &AU); 1394 1395 } // end namespace llvm 1396 1397 #endif // LLVM_ANALYSIS_ALIASANALYSIS_H 1398