1 //===- llvm/Analysis/AliasAnalysis.h - Alias Analysis Interface -*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the generic AliasAnalysis interface, which is used as the
11 // common interface used by all clients of alias analysis information, and
12 // implemented by all alias analysis implementations.  Mod/Ref information is
13 // also captured by this interface.
14 //
15 // Implementations of this interface must implement the various virtual methods,
16 // which automatically provides functionality for the entire suite of client
17 // APIs.
18 //
19 // This API identifies memory regions with the MemoryLocation class. The pointer
20 // component specifies the base memory address of the region. The Size specifies
21 // the maximum size (in address units) of the memory region, or
22 // MemoryLocation::UnknownSize if the size is not known. The TBAA tag
23 // identifies the "type" of the memory reference; see the
24 // TypeBasedAliasAnalysis class for details.
25 //
26 // Some non-obvious details include:
27 //  - Pointers that point to two completely different objects in memory never
28 //    alias, regardless of the value of the Size component.
29 //  - NoAlias doesn't imply inequal pointers. The most obvious example of this
30 //    is two pointers to constant memory. Even if they are equal, constant
31 //    memory is never stored to, so there will never be any dependencies.
32 //    In this and other situations, the pointers may be both NoAlias and
33 //    MustAlias at the same time. The current API can only return one result,
34 //    though this is rarely a problem in practice.
35 //
36 //===----------------------------------------------------------------------===//
37 
38 #ifndef LLVM_ANALYSIS_ALIASANALYSIS_H
39 #define LLVM_ANALYSIS_ALIASANALYSIS_H
40 
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/Analysis/TargetLibraryInfo.h"
46 #include "llvm/IR/Function.h"
47 #include "llvm/IR/Instruction.h"
48 #include "llvm/IR/Instructions.h"
49 #include "llvm/IR/PassManager.h"
50 #include "llvm/Pass.h"
51 #include <cstdint>
52 #include <functional>
53 #include <memory>
54 #include <vector>
55 
56 namespace llvm {
57 
58 class AnalysisUsage;
59 class BasicAAResult;
60 class BasicBlock;
61 class DominatorTree;
62 class OrderedBasicBlock;
63 class Value;
64 
65 /// The possible results of an alias query.
66 ///
67 /// These results are always computed between two MemoryLocation objects as
68 /// a query to some alias analysis.
69 ///
70 /// Note that these are unscoped enumerations because we would like to support
71 /// implicitly testing a result for the existence of any possible aliasing with
72 /// a conversion to bool, but an "enum class" doesn't support this. The
73 /// canonical names from the literature are suffixed and unique anyways, and so
74 /// they serve as global constants in LLVM for these results.
75 ///
76 /// See docs/AliasAnalysis.html for more information on the specific meanings
77 /// of these values.
78 enum AliasResult : uint8_t {
79   /// The two locations do not alias at all.
80   ///
81   /// This value is arranged to convert to false, while all other values
82   /// convert to true. This allows a boolean context to convert the result to
83   /// a binary flag indicating whether there is the possibility of aliasing.
84   NoAlias = 0,
85   /// The two locations may or may not alias. This is the least precise result.
86   MayAlias,
87   /// The two locations alias, but only due to a partial overlap.
88   PartialAlias,
89   /// The two locations precisely alias each other.
90   MustAlias,
91 };
92 
93 /// << operator for AliasResult.
94 raw_ostream &operator<<(raw_ostream &OS, AliasResult AR);
95 
96 /// Flags indicating whether a memory access modifies or references memory.
97 ///
98 /// This is no access at all, a modification, a reference, or both
99 /// a modification and a reference. These are specifically structured such that
100 /// they form a three bit matrix and bit-tests for 'mod' or 'ref' or 'must'
101 /// work with any of the possible values.
102 enum class ModRefInfo : uint8_t {
103   /// Must is provided for completeness, but no routines will return only
104   /// Must today. See definition of Must below.
105   Must = 0,
106   /// The access may reference the value stored in memory,
107   /// a mustAlias relation was found, and no mayAlias or partialAlias found.
108   MustRef = 1,
109   /// The access may modify the value stored in memory,
110   /// a mustAlias relation was found, and no mayAlias or partialAlias found.
111   MustMod = 2,
112   /// The access may reference, modify or both the value stored in memory,
113   /// a mustAlias relation was found, and no mayAlias or partialAlias found.
114   MustModRef = MustRef | MustMod,
115   /// The access neither references nor modifies the value stored in memory.
116   NoModRef = 4,
117   /// The access may reference the value stored in memory.
118   Ref = NoModRef | MustRef,
119   /// The access may modify the value stored in memory.
120   Mod = NoModRef | MustMod,
121   /// The access may reference and may modify the value stored in memory.
122   ModRef = Ref | Mod,
123 
124   /// About Must:
125   /// Must is set in a best effort manner.
126   /// We usually do not try our best to infer Must, instead it is merely
127   /// another piece of "free" information that is presented when available.
128   /// Must set means there was certainly a MustAlias found. For calls,
129   /// where multiple arguments are checked (argmemonly), this translates to
130   /// only MustAlias or NoAlias was found.
131   /// Must is not set for RAR accesses, even if the two locations must
132   /// alias. The reason is that two read accesses translate to an early return
133   /// of NoModRef. An additional alias check to set Must may be
134   /// expensive. Other cases may also not set Must(e.g. callCapturesBefore).
135   /// We refer to Must being *set* when the most significant bit is *cleared*.
136   /// Conversely we *clear* Must information by *setting* the Must bit to 1.
137 };
138 
isNoModRef(const ModRefInfo MRI)139 LLVM_NODISCARD inline bool isNoModRef(const ModRefInfo MRI) {
140   return (static_cast<int>(MRI) & static_cast<int>(ModRefInfo::MustModRef)) ==
141          static_cast<int>(ModRefInfo::Must);
142 }
isModOrRefSet(const ModRefInfo MRI)143 LLVM_NODISCARD inline bool isModOrRefSet(const ModRefInfo MRI) {
144   return static_cast<int>(MRI) & static_cast<int>(ModRefInfo::MustModRef);
145 }
isModAndRefSet(const ModRefInfo MRI)146 LLVM_NODISCARD inline bool isModAndRefSet(const ModRefInfo MRI) {
147   return (static_cast<int>(MRI) & static_cast<int>(ModRefInfo::MustModRef)) ==
148          static_cast<int>(ModRefInfo::MustModRef);
149 }
isModSet(const ModRefInfo MRI)150 LLVM_NODISCARD inline bool isModSet(const ModRefInfo MRI) {
151   return static_cast<int>(MRI) & static_cast<int>(ModRefInfo::MustMod);
152 }
isRefSet(const ModRefInfo MRI)153 LLVM_NODISCARD inline bool isRefSet(const ModRefInfo MRI) {
154   return static_cast<int>(MRI) & static_cast<int>(ModRefInfo::MustRef);
155 }
isMustSet(const ModRefInfo MRI)156 LLVM_NODISCARD inline bool isMustSet(const ModRefInfo MRI) {
157   return !(static_cast<int>(MRI) & static_cast<int>(ModRefInfo::NoModRef));
158 }
159 
setMod(const ModRefInfo MRI)160 LLVM_NODISCARD inline ModRefInfo setMod(const ModRefInfo MRI) {
161   return ModRefInfo(static_cast<int>(MRI) |
162                     static_cast<int>(ModRefInfo::MustMod));
163 }
setRef(const ModRefInfo MRI)164 LLVM_NODISCARD inline ModRefInfo setRef(const ModRefInfo MRI) {
165   return ModRefInfo(static_cast<int>(MRI) |
166                     static_cast<int>(ModRefInfo::MustRef));
167 }
setMust(const ModRefInfo MRI)168 LLVM_NODISCARD inline ModRefInfo setMust(const ModRefInfo MRI) {
169   return ModRefInfo(static_cast<int>(MRI) &
170                     static_cast<int>(ModRefInfo::MustModRef));
171 }
setModAndRef(const ModRefInfo MRI)172 LLVM_NODISCARD inline ModRefInfo setModAndRef(const ModRefInfo MRI) {
173   return ModRefInfo(static_cast<int>(MRI) |
174                     static_cast<int>(ModRefInfo::MustModRef));
175 }
clearMod(const ModRefInfo MRI)176 LLVM_NODISCARD inline ModRefInfo clearMod(const ModRefInfo MRI) {
177   return ModRefInfo(static_cast<int>(MRI) & static_cast<int>(ModRefInfo::Ref));
178 }
clearRef(const ModRefInfo MRI)179 LLVM_NODISCARD inline ModRefInfo clearRef(const ModRefInfo MRI) {
180   return ModRefInfo(static_cast<int>(MRI) & static_cast<int>(ModRefInfo::Mod));
181 }
clearMust(const ModRefInfo MRI)182 LLVM_NODISCARD inline ModRefInfo clearMust(const ModRefInfo MRI) {
183   return ModRefInfo(static_cast<int>(MRI) |
184                     static_cast<int>(ModRefInfo::NoModRef));
185 }
unionModRef(const ModRefInfo MRI1,const ModRefInfo MRI2)186 LLVM_NODISCARD inline ModRefInfo unionModRef(const ModRefInfo MRI1,
187                                              const ModRefInfo MRI2) {
188   return ModRefInfo(static_cast<int>(MRI1) | static_cast<int>(MRI2));
189 }
intersectModRef(const ModRefInfo MRI1,const ModRefInfo MRI2)190 LLVM_NODISCARD inline ModRefInfo intersectModRef(const ModRefInfo MRI1,
191                                                  const ModRefInfo MRI2) {
192   return ModRefInfo(static_cast<int>(MRI1) & static_cast<int>(MRI2));
193 }
194 
195 /// The locations at which a function might access memory.
196 ///
197 /// These are primarily used in conjunction with the \c AccessKind bits to
198 /// describe both the nature of access and the locations of access for a
199 /// function call.
200 enum FunctionModRefLocation {
201   /// Base case is no access to memory.
202   FMRL_Nowhere = 0,
203   /// Access to memory via argument pointers.
204   FMRL_ArgumentPointees = 8,
205   /// Memory that is inaccessible via LLVM IR.
206   FMRL_InaccessibleMem = 16,
207   /// Access to any memory.
208   FMRL_Anywhere = 32 | FMRL_InaccessibleMem | FMRL_ArgumentPointees
209 };
210 
211 /// Summary of how a function affects memory in the program.
212 ///
213 /// Loads from constant globals are not considered memory accesses for this
214 /// interface. Also, functions may freely modify stack space local to their
215 /// invocation without having to report it through these interfaces.
216 enum FunctionModRefBehavior {
217   /// This function does not perform any non-local loads or stores to memory.
218   ///
219   /// This property corresponds to the GCC 'const' attribute.
220   /// This property corresponds to the LLVM IR 'readnone' attribute.
221   /// This property corresponds to the IntrNoMem LLVM intrinsic flag.
222   FMRB_DoesNotAccessMemory =
223       FMRL_Nowhere | static_cast<int>(ModRefInfo::NoModRef),
224 
225   /// The only memory references in this function (if it has any) are
226   /// non-volatile loads from objects pointed to by its pointer-typed
227   /// arguments, with arbitrary offsets.
228   ///
229   /// This property corresponds to the IntrReadArgMem LLVM intrinsic flag.
230   FMRB_OnlyReadsArgumentPointees =
231       FMRL_ArgumentPointees | static_cast<int>(ModRefInfo::Ref),
232 
233   /// The only memory references in this function (if it has any) are
234   /// non-volatile loads and stores from objects pointed to by its
235   /// pointer-typed arguments, with arbitrary offsets.
236   ///
237   /// This property corresponds to the IntrArgMemOnly LLVM intrinsic flag.
238   FMRB_OnlyAccessesArgumentPointees =
239       FMRL_ArgumentPointees | static_cast<int>(ModRefInfo::ModRef),
240 
241   /// The only memory references in this function (if it has any) are
242   /// references of memory that is otherwise inaccessible via LLVM IR.
243   ///
244   /// This property corresponds to the LLVM IR inaccessiblememonly attribute.
245   FMRB_OnlyAccessesInaccessibleMem =
246       FMRL_InaccessibleMem | static_cast<int>(ModRefInfo::ModRef),
247 
248   /// The function may perform non-volatile loads and stores of objects
249   /// pointed to by its pointer-typed arguments, with arbitrary offsets, and
250   /// it may also perform loads and stores of memory that is otherwise
251   /// inaccessible via LLVM IR.
252   ///
253   /// This property corresponds to the LLVM IR
254   /// inaccessiblemem_or_argmemonly attribute.
255   FMRB_OnlyAccessesInaccessibleOrArgMem = FMRL_InaccessibleMem |
256                                           FMRL_ArgumentPointees |
257                                           static_cast<int>(ModRefInfo::ModRef),
258 
259   /// This function does not perform any non-local stores or volatile loads,
260   /// but may read from any memory location.
261   ///
262   /// This property corresponds to the GCC 'pure' attribute.
263   /// This property corresponds to the LLVM IR 'readonly' attribute.
264   /// This property corresponds to the IntrReadMem LLVM intrinsic flag.
265   FMRB_OnlyReadsMemory = FMRL_Anywhere | static_cast<int>(ModRefInfo::Ref),
266 
267   // This function does not read from memory anywhere, but may write to any
268   // memory location.
269   //
270   // This property corresponds to the LLVM IR 'writeonly' attribute.
271   // This property corresponds to the IntrWriteMem LLVM intrinsic flag.
272   FMRB_DoesNotReadMemory = FMRL_Anywhere | static_cast<int>(ModRefInfo::Mod),
273 
274   /// This indicates that the function could not be classified into one of the
275   /// behaviors above.
276   FMRB_UnknownModRefBehavior =
277       FMRL_Anywhere | static_cast<int>(ModRefInfo::ModRef)
278 };
279 
280 // Wrapper method strips bits significant only in FunctionModRefBehavior,
281 // to obtain a valid ModRefInfo. The benefit of using the wrapper is that if
282 // ModRefInfo enum changes, the wrapper can be updated to & with the new enum
283 // entry with all bits set to 1.
284 LLVM_NODISCARD inline ModRefInfo
createModRefInfo(const FunctionModRefBehavior FMRB)285 createModRefInfo(const FunctionModRefBehavior FMRB) {
286   return ModRefInfo(FMRB & static_cast<int>(ModRefInfo::ModRef));
287 }
288 
289 class AAResults {
290 public:
291   // Make these results default constructable and movable. We have to spell
292   // these out because MSVC won't synthesize them.
AAResults(const TargetLibraryInfo & TLI)293   AAResults(const TargetLibraryInfo &TLI) : TLI(TLI) {}
294   AAResults(AAResults &&Arg);
295   ~AAResults();
296 
297   /// Register a specific AA result.
addAAResult(AAResultT & AAResult)298   template <typename AAResultT> void addAAResult(AAResultT &AAResult) {
299     // FIXME: We should use a much lighter weight system than the usual
300     // polymorphic pattern because we don't own AAResult. It should
301     // ideally involve two pointers and no separate allocation.
302     AAs.emplace_back(new Model<AAResultT>(AAResult, *this));
303   }
304 
305   /// Register a function analysis ID that the results aggregation depends on.
306   ///
307   /// This is used in the new pass manager to implement the invalidation logic
308   /// where we must invalidate the results aggregation if any of our component
309   /// analyses become invalid.
addAADependencyID(AnalysisKey * ID)310   void addAADependencyID(AnalysisKey *ID) { AADeps.push_back(ID); }
311 
312   /// Handle invalidation events in the new pass manager.
313   ///
314   /// The aggregation is invalidated if any of the underlying analyses is
315   /// invalidated.
316   bool invalidate(Function &F, const PreservedAnalyses &PA,
317                   FunctionAnalysisManager::Invalidator &Inv);
318 
319   //===--------------------------------------------------------------------===//
320   /// \name Alias Queries
321   /// @{
322 
323   /// The main low level interface to the alias analysis implementation.
324   /// Returns an AliasResult indicating whether the two pointers are aliased to
325   /// each other. This is the interface that must be implemented by specific
326   /// alias analysis implementations.
327   AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB);
328 
329   /// A convenience wrapper around the primary \c alias interface.
alias(const Value * V1,LocationSize V1Size,const Value * V2,LocationSize V2Size)330   AliasResult alias(const Value *V1, LocationSize V1Size, const Value *V2,
331                     LocationSize V2Size) {
332     return alias(MemoryLocation(V1, V1Size), MemoryLocation(V2, V2Size));
333   }
334 
335   /// A convenience wrapper around the primary \c alias interface.
alias(const Value * V1,const Value * V2)336   AliasResult alias(const Value *V1, const Value *V2) {
337     return alias(V1, LocationSize::unknown(), V2, LocationSize::unknown());
338   }
339 
340   /// A trivial helper function to check to see if the specified pointers are
341   /// no-alias.
isNoAlias(const MemoryLocation & LocA,const MemoryLocation & LocB)342   bool isNoAlias(const MemoryLocation &LocA, const MemoryLocation &LocB) {
343     return alias(LocA, LocB) == NoAlias;
344   }
345 
346   /// A convenience wrapper around the \c isNoAlias helper interface.
isNoAlias(const Value * V1,LocationSize V1Size,const Value * V2,LocationSize V2Size)347   bool isNoAlias(const Value *V1, LocationSize V1Size, const Value *V2,
348                  LocationSize V2Size) {
349     return isNoAlias(MemoryLocation(V1, V1Size), MemoryLocation(V2, V2Size));
350   }
351 
352   /// A convenience wrapper around the \c isNoAlias helper interface.
isNoAlias(const Value * V1,const Value * V2)353   bool isNoAlias(const Value *V1, const Value *V2) {
354     return isNoAlias(MemoryLocation(V1), MemoryLocation(V2));
355   }
356 
357   /// A trivial helper function to check to see if the specified pointers are
358   /// must-alias.
isMustAlias(const MemoryLocation & LocA,const MemoryLocation & LocB)359   bool isMustAlias(const MemoryLocation &LocA, const MemoryLocation &LocB) {
360     return alias(LocA, LocB) == MustAlias;
361   }
362 
363   /// A convenience wrapper around the \c isMustAlias helper interface.
isMustAlias(const Value * V1,const Value * V2)364   bool isMustAlias(const Value *V1, const Value *V2) {
365     return alias(V1, LocationSize::precise(1), V2, LocationSize::precise(1)) ==
366            MustAlias;
367   }
368 
369   /// Checks whether the given location points to constant memory, or if
370   /// \p OrLocal is true whether it points to a local alloca.
371   bool pointsToConstantMemory(const MemoryLocation &Loc, bool OrLocal = false);
372 
373   /// A convenience wrapper around the primary \c pointsToConstantMemory
374   /// interface.
375   bool pointsToConstantMemory(const Value *P, bool OrLocal = false) {
376     return pointsToConstantMemory(MemoryLocation(P), OrLocal);
377   }
378 
379   /// @}
380   //===--------------------------------------------------------------------===//
381   /// \name Simple mod/ref information
382   /// @{
383 
384   /// Get the ModRef info associated with a pointer argument of a call. The
385   /// result's bits are set to indicate the allowed aliasing ModRef kinds. Note
386   /// that these bits do not necessarily account for the overall behavior of
387   /// the function, but rather only provide additional per-argument
388   /// information. This never sets ModRefInfo::Must.
389   ModRefInfo getArgModRefInfo(const CallBase *Call, unsigned ArgIdx);
390 
391   /// Return the behavior of the given call site.
392   FunctionModRefBehavior getModRefBehavior(const CallBase *Call);
393 
394   /// Return the behavior when calling the given function.
395   FunctionModRefBehavior getModRefBehavior(const Function *F);
396 
397   /// Checks if the specified call is known to never read or write memory.
398   ///
399   /// Note that if the call only reads from known-constant memory, it is also
400   /// legal to return true. Also, calls that unwind the stack are legal for
401   /// this predicate.
402   ///
403   /// Many optimizations (such as CSE and LICM) can be performed on such calls
404   /// without worrying about aliasing properties, and many calls have this
405   /// property (e.g. calls to 'sin' and 'cos').
406   ///
407   /// This property corresponds to the GCC 'const' attribute.
doesNotAccessMemory(const CallBase * Call)408   bool doesNotAccessMemory(const CallBase *Call) {
409     return getModRefBehavior(Call) == FMRB_DoesNotAccessMemory;
410   }
411 
412   /// Checks if the specified function is known to never read or write memory.
413   ///
414   /// Note that if the function only reads from known-constant memory, it is
415   /// also legal to return true. Also, function that unwind the stack are legal
416   /// for this predicate.
417   ///
418   /// Many optimizations (such as CSE and LICM) can be performed on such calls
419   /// to such functions without worrying about aliasing properties, and many
420   /// functions have this property (e.g. 'sin' and 'cos').
421   ///
422   /// This property corresponds to the GCC 'const' attribute.
doesNotAccessMemory(const Function * F)423   bool doesNotAccessMemory(const Function *F) {
424     return getModRefBehavior(F) == FMRB_DoesNotAccessMemory;
425   }
426 
427   /// Checks if the specified call is known to only read from non-volatile
428   /// memory (or not access memory at all).
429   ///
430   /// Calls that unwind the stack are legal for this predicate.
431   ///
432   /// This property allows many common optimizations to be performed in the
433   /// absence of interfering store instructions, such as CSE of strlen calls.
434   ///
435   /// This property corresponds to the GCC 'pure' attribute.
onlyReadsMemory(const CallBase * Call)436   bool onlyReadsMemory(const CallBase *Call) {
437     return onlyReadsMemory(getModRefBehavior(Call));
438   }
439 
440   /// Checks if the specified function is known to only read from non-volatile
441   /// memory (or not access memory at all).
442   ///
443   /// Functions that unwind the stack are legal for this predicate.
444   ///
445   /// This property allows many common optimizations to be performed in the
446   /// absence of interfering store instructions, such as CSE of strlen calls.
447   ///
448   /// This property corresponds to the GCC 'pure' attribute.
onlyReadsMemory(const Function * F)449   bool onlyReadsMemory(const Function *F) {
450     return onlyReadsMemory(getModRefBehavior(F));
451   }
452 
453   /// Checks if functions with the specified behavior are known to only read
454   /// from non-volatile memory (or not access memory at all).
onlyReadsMemory(FunctionModRefBehavior MRB)455   static bool onlyReadsMemory(FunctionModRefBehavior MRB) {
456     return !isModSet(createModRefInfo(MRB));
457   }
458 
459   /// Checks if functions with the specified behavior are known to only write
460   /// memory (or not access memory at all).
doesNotReadMemory(FunctionModRefBehavior MRB)461   static bool doesNotReadMemory(FunctionModRefBehavior MRB) {
462     return !isRefSet(createModRefInfo(MRB));
463   }
464 
465   /// Checks if functions with the specified behavior are known to read and
466   /// write at most from objects pointed to by their pointer-typed arguments
467   /// (with arbitrary offsets).
onlyAccessesArgPointees(FunctionModRefBehavior MRB)468   static bool onlyAccessesArgPointees(FunctionModRefBehavior MRB) {
469     return !(MRB & FMRL_Anywhere & ~FMRL_ArgumentPointees);
470   }
471 
472   /// Checks if functions with the specified behavior are known to potentially
473   /// read or write from objects pointed to be their pointer-typed arguments
474   /// (with arbitrary offsets).
doesAccessArgPointees(FunctionModRefBehavior MRB)475   static bool doesAccessArgPointees(FunctionModRefBehavior MRB) {
476     return isModOrRefSet(createModRefInfo(MRB)) &&
477            (MRB & FMRL_ArgumentPointees);
478   }
479 
480   /// Checks if functions with the specified behavior are known to read and
481   /// write at most from memory that is inaccessible from LLVM IR.
onlyAccessesInaccessibleMem(FunctionModRefBehavior MRB)482   static bool onlyAccessesInaccessibleMem(FunctionModRefBehavior MRB) {
483     return !(MRB & FMRL_Anywhere & ~FMRL_InaccessibleMem);
484   }
485 
486   /// Checks if functions with the specified behavior are known to potentially
487   /// read or write from memory that is inaccessible from LLVM IR.
doesAccessInaccessibleMem(FunctionModRefBehavior MRB)488   static bool doesAccessInaccessibleMem(FunctionModRefBehavior MRB) {
489     return isModOrRefSet(createModRefInfo(MRB)) && (MRB & FMRL_InaccessibleMem);
490   }
491 
492   /// Checks if functions with the specified behavior are known to read and
493   /// write at most from memory that is inaccessible from LLVM IR or objects
494   /// pointed to by their pointer-typed arguments (with arbitrary offsets).
onlyAccessesInaccessibleOrArgMem(FunctionModRefBehavior MRB)495   static bool onlyAccessesInaccessibleOrArgMem(FunctionModRefBehavior MRB) {
496     return !(MRB & FMRL_Anywhere &
497              ~(FMRL_InaccessibleMem | FMRL_ArgumentPointees));
498   }
499 
500   /// getModRefInfo (for call sites) - Return information about whether
501   /// a particular call site modifies or reads the specified memory location.
502   ModRefInfo getModRefInfo(const CallBase *Call, const MemoryLocation &Loc);
503 
504   /// getModRefInfo (for call sites) - A convenience wrapper.
getModRefInfo(const CallBase * Call,const Value * P,LocationSize Size)505   ModRefInfo getModRefInfo(const CallBase *Call, const Value *P,
506                            LocationSize Size) {
507     return getModRefInfo(Call, MemoryLocation(P, Size));
508   }
509 
510   /// getModRefInfo (for loads) - Return information about whether
511   /// a particular load modifies or reads the specified memory location.
512   ModRefInfo getModRefInfo(const LoadInst *L, const MemoryLocation &Loc);
513 
514   /// getModRefInfo (for loads) - A convenience wrapper.
getModRefInfo(const LoadInst * L,const Value * P,LocationSize Size)515   ModRefInfo getModRefInfo(const LoadInst *L, const Value *P,
516                            LocationSize Size) {
517     return getModRefInfo(L, MemoryLocation(P, Size));
518   }
519 
520   /// getModRefInfo (for stores) - Return information about whether
521   /// a particular store modifies or reads the specified memory location.
522   ModRefInfo getModRefInfo(const StoreInst *S, const MemoryLocation &Loc);
523 
524   /// getModRefInfo (for stores) - A convenience wrapper.
getModRefInfo(const StoreInst * S,const Value * P,LocationSize Size)525   ModRefInfo getModRefInfo(const StoreInst *S, const Value *P,
526                            LocationSize Size) {
527     return getModRefInfo(S, MemoryLocation(P, Size));
528   }
529 
530   /// getModRefInfo (for fences) - Return information about whether
531   /// a particular store modifies or reads the specified memory location.
532   ModRefInfo getModRefInfo(const FenceInst *S, const MemoryLocation &Loc);
533 
534   /// getModRefInfo (for fences) - A convenience wrapper.
getModRefInfo(const FenceInst * S,const Value * P,LocationSize Size)535   ModRefInfo getModRefInfo(const FenceInst *S, const Value *P,
536                            LocationSize Size) {
537     return getModRefInfo(S, MemoryLocation(P, Size));
538   }
539 
540   /// getModRefInfo (for cmpxchges) - Return information about whether
541   /// a particular cmpxchg modifies or reads the specified memory location.
542   ModRefInfo getModRefInfo(const AtomicCmpXchgInst *CX,
543                            const MemoryLocation &Loc);
544 
545   /// getModRefInfo (for cmpxchges) - A convenience wrapper.
getModRefInfo(const AtomicCmpXchgInst * CX,const Value * P,LocationSize Size)546   ModRefInfo getModRefInfo(const AtomicCmpXchgInst *CX, const Value *P,
547                            LocationSize Size) {
548     return getModRefInfo(CX, MemoryLocation(P, Size));
549   }
550 
551   /// getModRefInfo (for atomicrmws) - Return information about whether
552   /// a particular atomicrmw modifies or reads the specified memory location.
553   ModRefInfo getModRefInfo(const AtomicRMWInst *RMW, const MemoryLocation &Loc);
554 
555   /// getModRefInfo (for atomicrmws) - A convenience wrapper.
getModRefInfo(const AtomicRMWInst * RMW,const Value * P,LocationSize Size)556   ModRefInfo getModRefInfo(const AtomicRMWInst *RMW, const Value *P,
557                            LocationSize Size) {
558     return getModRefInfo(RMW, MemoryLocation(P, Size));
559   }
560 
561   /// getModRefInfo (for va_args) - Return information about whether
562   /// a particular va_arg modifies or reads the specified memory location.
563   ModRefInfo getModRefInfo(const VAArgInst *I, const MemoryLocation &Loc);
564 
565   /// getModRefInfo (for va_args) - A convenience wrapper.
getModRefInfo(const VAArgInst * I,const Value * P,LocationSize Size)566   ModRefInfo getModRefInfo(const VAArgInst *I, const Value *P,
567                            LocationSize Size) {
568     return getModRefInfo(I, MemoryLocation(P, Size));
569   }
570 
571   /// getModRefInfo (for catchpads) - Return information about whether
572   /// a particular catchpad modifies or reads the specified memory location.
573   ModRefInfo getModRefInfo(const CatchPadInst *I, const MemoryLocation &Loc);
574 
575   /// getModRefInfo (for catchpads) - A convenience wrapper.
getModRefInfo(const CatchPadInst * I,const Value * P,LocationSize Size)576   ModRefInfo getModRefInfo(const CatchPadInst *I, const Value *P,
577                            LocationSize Size) {
578     return getModRefInfo(I, MemoryLocation(P, Size));
579   }
580 
581   /// getModRefInfo (for catchrets) - Return information about whether
582   /// a particular catchret modifies or reads the specified memory location.
583   ModRefInfo getModRefInfo(const CatchReturnInst *I, const MemoryLocation &Loc);
584 
585   /// getModRefInfo (for catchrets) - A convenience wrapper.
getModRefInfo(const CatchReturnInst * I,const Value * P,LocationSize Size)586   ModRefInfo getModRefInfo(const CatchReturnInst *I, const Value *P,
587                            LocationSize Size) {
588     return getModRefInfo(I, MemoryLocation(P, Size));
589   }
590 
591   /// Check whether or not an instruction may read or write the optionally
592   /// specified memory location.
593   ///
594   ///
595   /// An instruction that doesn't read or write memory may be trivially LICM'd
596   /// for example.
597   ///
598   /// For function calls, this delegates to the alias-analysis specific
599   /// call-site mod-ref behavior queries. Otherwise it delegates to the specific
600   /// helpers above.
getModRefInfo(const Instruction * I,const Optional<MemoryLocation> & OptLoc)601   ModRefInfo getModRefInfo(const Instruction *I,
602                            const Optional<MemoryLocation> &OptLoc) {
603     if (OptLoc == None) {
604       if (const auto *Call = dyn_cast<CallBase>(I)) {
605         return createModRefInfo(getModRefBehavior(Call));
606       }
607     }
608 
609     const MemoryLocation &Loc = OptLoc.getValueOr(MemoryLocation());
610 
611     switch (I->getOpcode()) {
612     case Instruction::VAArg:  return getModRefInfo((const VAArgInst*)I, Loc);
613     case Instruction::Load:   return getModRefInfo((const LoadInst*)I,  Loc);
614     case Instruction::Store:  return getModRefInfo((const StoreInst*)I, Loc);
615     case Instruction::Fence:  return getModRefInfo((const FenceInst*)I, Loc);
616     case Instruction::AtomicCmpXchg:
617       return getModRefInfo((const AtomicCmpXchgInst*)I, Loc);
618     case Instruction::AtomicRMW:
619       return getModRefInfo((const AtomicRMWInst*)I, Loc);
620     case Instruction::Call:   return getModRefInfo((const CallInst*)I,  Loc);
621     case Instruction::Invoke: return getModRefInfo((const InvokeInst*)I,Loc);
622     case Instruction::CatchPad:
623       return getModRefInfo((const CatchPadInst *)I, Loc);
624     case Instruction::CatchRet:
625       return getModRefInfo((const CatchReturnInst *)I, Loc);
626     default:
627       return ModRefInfo::NoModRef;
628     }
629   }
630 
631   /// A convenience wrapper for constructing the memory location.
getModRefInfo(const Instruction * I,const Value * P,LocationSize Size)632   ModRefInfo getModRefInfo(const Instruction *I, const Value *P,
633                            LocationSize Size) {
634     return getModRefInfo(I, MemoryLocation(P, Size));
635   }
636 
637   /// Return information about whether a call and an instruction may refer to
638   /// the same memory locations.
639   ModRefInfo getModRefInfo(Instruction *I, const CallBase *Call);
640 
641   /// Return information about whether two call sites may refer to the same set
642   /// of memory locations. See the AA documentation for details:
643   ///   http://llvm.org/docs/AliasAnalysis.html#ModRefInfo
644   ModRefInfo getModRefInfo(const CallBase *Call1, const CallBase *Call2);
645 
646   /// Return information about whether a particular call site modifies
647   /// or reads the specified memory location \p MemLoc before instruction \p I
648   /// in a BasicBlock. An ordered basic block \p OBB can be used to speed up
649   /// instruction ordering queries inside the BasicBlock containing \p I.
650   /// Early exits in callCapturesBefore may lead to ModRefInfo::Must not being
651   /// set.
652   ModRefInfo callCapturesBefore(const Instruction *I,
653                                 const MemoryLocation &MemLoc, DominatorTree *DT,
654                                 OrderedBasicBlock *OBB = nullptr);
655 
656   /// A convenience wrapper to synthesize a memory location.
657   ModRefInfo callCapturesBefore(const Instruction *I, const Value *P,
658                                 LocationSize Size, DominatorTree *DT,
659                                 OrderedBasicBlock *OBB = nullptr) {
660     return callCapturesBefore(I, MemoryLocation(P, Size), DT, OBB);
661   }
662 
663   /// @}
664   //===--------------------------------------------------------------------===//
665   /// \name Higher level methods for querying mod/ref information.
666   /// @{
667 
668   /// Check if it is possible for execution of the specified basic block to
669   /// modify the location Loc.
670   bool canBasicBlockModify(const BasicBlock &BB, const MemoryLocation &Loc);
671 
672   /// A convenience wrapper synthesizing a memory location.
canBasicBlockModify(const BasicBlock & BB,const Value * P,LocationSize Size)673   bool canBasicBlockModify(const BasicBlock &BB, const Value *P,
674                            LocationSize Size) {
675     return canBasicBlockModify(BB, MemoryLocation(P, Size));
676   }
677 
678   /// Check if it is possible for the execution of the specified instructions
679   /// to mod\ref (according to the mode) the location Loc.
680   ///
681   /// The instructions to consider are all of the instructions in the range of
682   /// [I1,I2] INCLUSIVE. I1 and I2 must be in the same basic block.
683   bool canInstructionRangeModRef(const Instruction &I1, const Instruction &I2,
684                                  const MemoryLocation &Loc,
685                                  const ModRefInfo Mode);
686 
687   /// A convenience wrapper synthesizing a memory location.
canInstructionRangeModRef(const Instruction & I1,const Instruction & I2,const Value * Ptr,LocationSize Size,const ModRefInfo Mode)688   bool canInstructionRangeModRef(const Instruction &I1, const Instruction &I2,
689                                  const Value *Ptr, LocationSize Size,
690                                  const ModRefInfo Mode) {
691     return canInstructionRangeModRef(I1, I2, MemoryLocation(Ptr, Size), Mode);
692   }
693 
694 private:
695   class Concept;
696 
697   template <typename T> class Model;
698 
699   template <typename T> friend class AAResultBase;
700 
701   const TargetLibraryInfo &TLI;
702 
703   std::vector<std::unique_ptr<Concept>> AAs;
704 
705   std::vector<AnalysisKey *> AADeps;
706 };
707 
708 /// Temporary typedef for legacy code that uses a generic \c AliasAnalysis
709 /// pointer or reference.
710 using AliasAnalysis = AAResults;
711 
712 /// A private abstract base class describing the concept of an individual alias
713 /// analysis implementation.
714 ///
715 /// This interface is implemented by any \c Model instantiation. It is also the
716 /// interface which a type used to instantiate the model must provide.
717 ///
718 /// All of these methods model methods by the same name in the \c
719 /// AAResults class. Only differences and specifics to how the
720 /// implementations are called are documented here.
721 class AAResults::Concept {
722 public:
723   virtual ~Concept() = 0;
724 
725   /// An update API used internally by the AAResults to provide
726   /// a handle back to the top level aggregation.
727   virtual void setAAResults(AAResults *NewAAR) = 0;
728 
729   //===--------------------------------------------------------------------===//
730   /// \name Alias Queries
731   /// @{
732 
733   /// The main low level interface to the alias analysis implementation.
734   /// Returns an AliasResult indicating whether the two pointers are aliased to
735   /// each other. This is the interface that must be implemented by specific
736   /// alias analysis implementations.
737   virtual AliasResult alias(const MemoryLocation &LocA,
738                             const MemoryLocation &LocB) = 0;
739 
740   /// Checks whether the given location points to constant memory, or if
741   /// \p OrLocal is true whether it points to a local alloca.
742   virtual bool pointsToConstantMemory(const MemoryLocation &Loc,
743                                       bool OrLocal) = 0;
744 
745   /// @}
746   //===--------------------------------------------------------------------===//
747   /// \name Simple mod/ref information
748   /// @{
749 
750   /// Get the ModRef info associated with a pointer argument of a callsite. The
751   /// result's bits are set to indicate the allowed aliasing ModRef kinds. Note
752   /// that these bits do not necessarily account for the overall behavior of
753   /// the function, but rather only provide additional per-argument
754   /// information.
755   virtual ModRefInfo getArgModRefInfo(const CallBase *Call,
756                                       unsigned ArgIdx) = 0;
757 
758   /// Return the behavior of the given call site.
759   virtual FunctionModRefBehavior getModRefBehavior(const CallBase *Call) = 0;
760 
761   /// Return the behavior when calling the given function.
762   virtual FunctionModRefBehavior getModRefBehavior(const Function *F) = 0;
763 
764   /// getModRefInfo (for call sites) - Return information about whether
765   /// a particular call site modifies or reads the specified memory location.
766   virtual ModRefInfo getModRefInfo(const CallBase *Call,
767                                    const MemoryLocation &Loc) = 0;
768 
769   /// Return information about whether two call sites may refer to the same set
770   /// of memory locations. See the AA documentation for details:
771   ///   http://llvm.org/docs/AliasAnalysis.html#ModRefInfo
772   virtual ModRefInfo getModRefInfo(const CallBase *Call1,
773                                    const CallBase *Call2) = 0;
774 
775   /// @}
776 };
777 
778 /// A private class template which derives from \c Concept and wraps some other
779 /// type.
780 ///
781 /// This models the concept by directly forwarding each interface point to the
782 /// wrapped type which must implement a compatible interface. This provides
783 /// a type erased binding.
784 template <typename AAResultT> class AAResults::Model final : public Concept {
785   AAResultT &Result;
786 
787 public:
Model(AAResultT & Result,AAResults & AAR)788   explicit Model(AAResultT &Result, AAResults &AAR) : Result(Result) {
789     Result.setAAResults(&AAR);
790   }
791   ~Model() override = default;
792 
setAAResults(AAResults * NewAAR)793   void setAAResults(AAResults *NewAAR) override { Result.setAAResults(NewAAR); }
794 
alias(const MemoryLocation & LocA,const MemoryLocation & LocB)795   AliasResult alias(const MemoryLocation &LocA,
796                     const MemoryLocation &LocB) override {
797     return Result.alias(LocA, LocB);
798   }
799 
pointsToConstantMemory(const MemoryLocation & Loc,bool OrLocal)800   bool pointsToConstantMemory(const MemoryLocation &Loc,
801                               bool OrLocal) override {
802     return Result.pointsToConstantMemory(Loc, OrLocal);
803   }
804 
getArgModRefInfo(const CallBase * Call,unsigned ArgIdx)805   ModRefInfo getArgModRefInfo(const CallBase *Call, unsigned ArgIdx) override {
806     return Result.getArgModRefInfo(Call, ArgIdx);
807   }
808 
getModRefBehavior(const CallBase * Call)809   FunctionModRefBehavior getModRefBehavior(const CallBase *Call) override {
810     return Result.getModRefBehavior(Call);
811   }
812 
getModRefBehavior(const Function * F)813   FunctionModRefBehavior getModRefBehavior(const Function *F) override {
814     return Result.getModRefBehavior(F);
815   }
816 
getModRefInfo(const CallBase * Call,const MemoryLocation & Loc)817   ModRefInfo getModRefInfo(const CallBase *Call,
818                            const MemoryLocation &Loc) override {
819     return Result.getModRefInfo(Call, Loc);
820   }
821 
getModRefInfo(const CallBase * Call1,const CallBase * Call2)822   ModRefInfo getModRefInfo(const CallBase *Call1,
823                            const CallBase *Call2) override {
824     return Result.getModRefInfo(Call1, Call2);
825   }
826 };
827 
828 /// A CRTP-driven "mixin" base class to help implement the function alias
829 /// analysis results concept.
830 ///
831 /// Because of the nature of many alias analysis implementations, they often
832 /// only implement a subset of the interface. This base class will attempt to
833 /// implement the remaining portions of the interface in terms of simpler forms
834 /// of the interface where possible, and otherwise provide conservatively
835 /// correct fallback implementations.
836 ///
837 /// Implementors of an alias analysis should derive from this CRTP, and then
838 /// override specific methods that they wish to customize. There is no need to
839 /// use virtual anywhere, the CRTP base class does static dispatch to the
840 /// derived type passed into it.
841 template <typename DerivedT> class AAResultBase {
842   // Expose some parts of the interface only to the AAResults::Model
843   // for wrapping. Specifically, this allows the model to call our
844   // setAAResults method without exposing it as a fully public API.
845   friend class AAResults::Model<DerivedT>;
846 
847   /// A pointer to the AAResults object that this AAResult is
848   /// aggregated within. May be null if not aggregated.
849   AAResults *AAR;
850 
851   /// Helper to dispatch calls back through the derived type.
derived()852   DerivedT &derived() { return static_cast<DerivedT &>(*this); }
853 
854   /// A setter for the AAResults pointer, which is used to satisfy the
855   /// AAResults::Model contract.
setAAResults(AAResults * NewAAR)856   void setAAResults(AAResults *NewAAR) { AAR = NewAAR; }
857 
858 protected:
859   /// This proxy class models a common pattern where we delegate to either the
860   /// top-level \c AAResults aggregation if one is registered, or to the
861   /// current result if none are registered.
862   class AAResultsProxy {
863     AAResults *AAR;
864     DerivedT &CurrentResult;
865 
866   public:
AAResultsProxy(AAResults * AAR,DerivedT & CurrentResult)867     AAResultsProxy(AAResults *AAR, DerivedT &CurrentResult)
868         : AAR(AAR), CurrentResult(CurrentResult) {}
869 
alias(const MemoryLocation & LocA,const MemoryLocation & LocB)870     AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB) {
871       return AAR ? AAR->alias(LocA, LocB) : CurrentResult.alias(LocA, LocB);
872     }
873 
pointsToConstantMemory(const MemoryLocation & Loc,bool OrLocal)874     bool pointsToConstantMemory(const MemoryLocation &Loc, bool OrLocal) {
875       return AAR ? AAR->pointsToConstantMemory(Loc, OrLocal)
876                  : CurrentResult.pointsToConstantMemory(Loc, OrLocal);
877     }
878 
getArgModRefInfo(const CallBase * Call,unsigned ArgIdx)879     ModRefInfo getArgModRefInfo(const CallBase *Call, unsigned ArgIdx) {
880       return AAR ? AAR->getArgModRefInfo(Call, ArgIdx)
881                  : CurrentResult.getArgModRefInfo(Call, ArgIdx);
882     }
883 
getModRefBehavior(const CallBase * Call)884     FunctionModRefBehavior getModRefBehavior(const CallBase *Call) {
885       return AAR ? AAR->getModRefBehavior(Call)
886                  : CurrentResult.getModRefBehavior(Call);
887     }
888 
getModRefBehavior(const Function * F)889     FunctionModRefBehavior getModRefBehavior(const Function *F) {
890       return AAR ? AAR->getModRefBehavior(F) : CurrentResult.getModRefBehavior(F);
891     }
892 
getModRefInfo(const CallBase * Call,const MemoryLocation & Loc)893     ModRefInfo getModRefInfo(const CallBase *Call, const MemoryLocation &Loc) {
894       return AAR ? AAR->getModRefInfo(Call, Loc)
895                  : CurrentResult.getModRefInfo(Call, Loc);
896     }
897 
getModRefInfo(const CallBase * Call1,const CallBase * Call2)898     ModRefInfo getModRefInfo(const CallBase *Call1, const CallBase *Call2) {
899       return AAR ? AAR->getModRefInfo(Call1, Call2)
900                  : CurrentResult.getModRefInfo(Call1, Call2);
901     }
902   };
903 
904   explicit AAResultBase() = default;
905 
906   // Provide all the copy and move constructors so that derived types aren't
907   // constrained.
AAResultBase(const AAResultBase & Arg)908   AAResultBase(const AAResultBase &Arg) {}
AAResultBase(AAResultBase && Arg)909   AAResultBase(AAResultBase &&Arg) {}
910 
911   /// Get a proxy for the best AA result set to query at this time.
912   ///
913   /// When this result is part of a larger aggregation, this will proxy to that
914   /// aggregation. When this result is used in isolation, it will just delegate
915   /// back to the derived class's implementation.
916   ///
917   /// Note that callers of this need to take considerable care to not cause
918   /// performance problems when they use this routine, in the case of a large
919   /// number of alias analyses being aggregated, it can be expensive to walk
920   /// back across the chain.
getBestAAResults()921   AAResultsProxy getBestAAResults() { return AAResultsProxy(AAR, derived()); }
922 
923 public:
alias(const MemoryLocation & LocA,const MemoryLocation & LocB)924   AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB) {
925     return MayAlias;
926   }
927 
pointsToConstantMemory(const MemoryLocation & Loc,bool OrLocal)928   bool pointsToConstantMemory(const MemoryLocation &Loc, bool OrLocal) {
929     return false;
930   }
931 
getArgModRefInfo(const CallBase * Call,unsigned ArgIdx)932   ModRefInfo getArgModRefInfo(const CallBase *Call, unsigned ArgIdx) {
933     return ModRefInfo::ModRef;
934   }
935 
getModRefBehavior(const CallBase * Call)936   FunctionModRefBehavior getModRefBehavior(const CallBase *Call) {
937     return FMRB_UnknownModRefBehavior;
938   }
939 
getModRefBehavior(const Function * F)940   FunctionModRefBehavior getModRefBehavior(const Function *F) {
941     return FMRB_UnknownModRefBehavior;
942   }
943 
getModRefInfo(const CallBase * Call,const MemoryLocation & Loc)944   ModRefInfo getModRefInfo(const CallBase *Call, const MemoryLocation &Loc) {
945     return ModRefInfo::ModRef;
946   }
947 
getModRefInfo(const CallBase * Call1,const CallBase * Call2)948   ModRefInfo getModRefInfo(const CallBase *Call1, const CallBase *Call2) {
949     return ModRefInfo::ModRef;
950   }
951 };
952 
953 /// Return true if this pointer is returned by a noalias function.
954 bool isNoAliasCall(const Value *V);
955 
956 /// Return true if this is an argument with the noalias attribute.
957 bool isNoAliasArgument(const Value *V);
958 
959 /// Return true if this pointer refers to a distinct and identifiable object.
960 /// This returns true for:
961 ///    Global Variables and Functions (but not Global Aliases)
962 ///    Allocas
963 ///    ByVal and NoAlias Arguments
964 ///    NoAlias returns (e.g. calls to malloc)
965 ///
966 bool isIdentifiedObject(const Value *V);
967 
968 /// Return true if V is umabigously identified at the function-level.
969 /// Different IdentifiedFunctionLocals can't alias.
970 /// Further, an IdentifiedFunctionLocal can not alias with any function
971 /// arguments other than itself, which is not necessarily true for
972 /// IdentifiedObjects.
973 bool isIdentifiedFunctionLocal(const Value *V);
974 
975 /// A manager for alias analyses.
976 ///
977 /// This class can have analyses registered with it and when run, it will run
978 /// all of them and aggregate their results into single AA results interface
979 /// that dispatches across all of the alias analysis results available.
980 ///
981 /// Note that the order in which analyses are registered is very significant.
982 /// That is the order in which the results will be aggregated and queried.
983 ///
984 /// This manager effectively wraps the AnalysisManager for registering alias
985 /// analyses. When you register your alias analysis with this manager, it will
986 /// ensure the analysis itself is registered with its AnalysisManager.
987 class AAManager : public AnalysisInfoMixin<AAManager> {
988 public:
989   using Result = AAResults;
990 
991   /// Register a specific AA result.
registerFunctionAnalysis()992   template <typename AnalysisT> void registerFunctionAnalysis() {
993     ResultGetters.push_back(&getFunctionAAResultImpl<AnalysisT>);
994   }
995 
996   /// Register a specific AA result.
registerModuleAnalysis()997   template <typename AnalysisT> void registerModuleAnalysis() {
998     ResultGetters.push_back(&getModuleAAResultImpl<AnalysisT>);
999   }
1000 
run(Function & F,FunctionAnalysisManager & AM)1001   Result run(Function &F, FunctionAnalysisManager &AM) {
1002     Result R(AM.getResult<TargetLibraryAnalysis>(F));
1003     for (auto &Getter : ResultGetters)
1004       (*Getter)(F, AM, R);
1005     return R;
1006   }
1007 
1008 private:
1009   friend AnalysisInfoMixin<AAManager>;
1010 
1011   static AnalysisKey Key;
1012 
1013   SmallVector<void (*)(Function &F, FunctionAnalysisManager &AM,
1014                        AAResults &AAResults),
1015               4> ResultGetters;
1016 
1017   template <typename AnalysisT>
getFunctionAAResultImpl(Function & F,FunctionAnalysisManager & AM,AAResults & AAResults)1018   static void getFunctionAAResultImpl(Function &F,
1019                                       FunctionAnalysisManager &AM,
1020                                       AAResults &AAResults) {
1021     AAResults.addAAResult(AM.template getResult<AnalysisT>(F));
1022     AAResults.addAADependencyID(AnalysisT::ID());
1023   }
1024 
1025   template <typename AnalysisT>
getModuleAAResultImpl(Function & F,FunctionAnalysisManager & AM,AAResults & AAResults)1026   static void getModuleAAResultImpl(Function &F, FunctionAnalysisManager &AM,
1027                                     AAResults &AAResults) {
1028     auto &MAMProxy = AM.getResult<ModuleAnalysisManagerFunctionProxy>(F);
1029     auto &MAM = MAMProxy.getManager();
1030     if (auto *R = MAM.template getCachedResult<AnalysisT>(*F.getParent())) {
1031       AAResults.addAAResult(*R);
1032       MAMProxy
1033           .template registerOuterAnalysisInvalidation<AnalysisT, AAManager>();
1034     }
1035   }
1036 };
1037 
1038 /// A wrapper pass to provide the legacy pass manager access to a suitably
1039 /// prepared AAResults object.
1040 class AAResultsWrapperPass : public FunctionPass {
1041   std::unique_ptr<AAResults> AAR;
1042 
1043 public:
1044   static char ID;
1045 
1046   AAResultsWrapperPass();
1047 
getAAResults()1048   AAResults &getAAResults() { return *AAR; }
getAAResults()1049   const AAResults &getAAResults() const { return *AAR; }
1050 
1051   bool runOnFunction(Function &F) override;
1052 
1053   void getAnalysisUsage(AnalysisUsage &AU) const override;
1054 };
1055 
1056 /// A wrapper pass for external alias analyses. This just squirrels away the
1057 /// callback used to run any analyses and register their results.
1058 struct ExternalAAWrapperPass : ImmutablePass {
1059   using CallbackT = std::function<void(Pass &, Function &, AAResults &)>;
1060 
1061   CallbackT CB;
1062 
1063   static char ID;
1064 
ExternalAAWrapperPassExternalAAWrapperPass1065   ExternalAAWrapperPass() : ImmutablePass(ID) {
1066     initializeExternalAAWrapperPassPass(*PassRegistry::getPassRegistry());
1067   }
1068 
ExternalAAWrapperPassExternalAAWrapperPass1069   explicit ExternalAAWrapperPass(CallbackT CB)
1070       : ImmutablePass(ID), CB(std::move(CB)) {
1071     initializeExternalAAWrapperPassPass(*PassRegistry::getPassRegistry());
1072   }
1073 
getAnalysisUsageExternalAAWrapperPass1074   void getAnalysisUsage(AnalysisUsage &AU) const override {
1075     AU.setPreservesAll();
1076   }
1077 };
1078 
1079 FunctionPass *createAAResultsWrapperPass();
1080 
1081 /// A wrapper pass around a callback which can be used to populate the
1082 /// AAResults in the AAResultsWrapperPass from an external AA.
1083 ///
1084 /// The callback provided here will be used each time we prepare an AAResults
1085 /// object, and will receive a reference to the function wrapper pass, the
1086 /// function, and the AAResults object to populate. This should be used when
1087 /// setting up a custom pass pipeline to inject a hook into the AA results.
1088 ImmutablePass *createExternalAAWrapperPass(
1089     std::function<void(Pass &, Function &, AAResults &)> Callback);
1090 
1091 /// A helper for the legacy pass manager to create a \c AAResults
1092 /// object populated to the best of our ability for a particular function when
1093 /// inside of a \c ModulePass or a \c CallGraphSCCPass.
1094 ///
1095 /// If a \c ModulePass or a \c CallGraphSCCPass calls \p
1096 /// createLegacyPMAAResults, it also needs to call \p addUsedAAAnalyses in \p
1097 /// getAnalysisUsage.
1098 AAResults createLegacyPMAAResults(Pass &P, Function &F, BasicAAResult &BAR);
1099 
1100 /// A helper for the legacy pass manager to populate \p AU to add uses to make
1101 /// sure the analyses required by \p createLegacyPMAAResults are available.
1102 void getAAResultsAnalysisUsage(AnalysisUsage &AU);
1103 
1104 } // end namespace llvm
1105 
1106 #endif // LLVM_ANALYSIS_ALIASANALYSIS_H
1107