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