1 //===- llvm/Analysis/AliasAnalysis.h - Alias Analysis Interface -*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the generic AliasAnalysis interface, which is used as the
10 // common interface used by all clients of alias analysis information, and
11 // implemented by all alias analysis implementations. Mod/Ref information is
12 // also captured by this interface.
13 //
14 // Implementations of this interface must implement the various virtual methods,
15 // which automatically provides functionality for the entire suite of client
16 // APIs.
17 //
18 // This API identifies memory regions with the MemoryLocation class. The pointer
19 // component specifies the base memory address of the region. The Size specifies
20 // the maximum size (in address units) of the memory region, or
21 // MemoryLocation::UnknownSize if the size is not known. The TBAA tag
22 // identifies the "type" of the memory reference; see the
23 // TypeBasedAliasAnalysis class for details.
24 //
25 // Some non-obvious details include:
26 // - Pointers that point to two completely different objects in memory never
27 // alias, regardless of the value of the Size component.
28 // - NoAlias doesn't imply inequal pointers. The most obvious example of this
29 // is two pointers to constant memory. Even if they are equal, constant
30 // memory is never stored to, so there will never be any dependencies.
31 // In this and other situations, the pointers may be both NoAlias and
32 // MustAlias at the same time. The current API can only return one result,
33 // though this is rarely a problem in practice.
34 //
35 //===----------------------------------------------------------------------===//
36
37 #ifndef LLVM_ANALYSIS_ALIASANALYSIS_H
38 #define LLVM_ANALYSIS_ALIASANALYSIS_H
39
40 #include "llvm/ADT/DenseMap.h"
41 #include "llvm/ADT/None.h"
42 #include "llvm/ADT/Optional.h"
43 #include "llvm/ADT/SmallVector.h"
44 #include "llvm/Analysis/MemoryLocation.h"
45 #include "llvm/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 using FunctionModRefBehavior = int;
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 constexpr FunctionModRefBehavior 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 constexpr FunctionModRefBehavior 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 constexpr FunctionModRefBehavior 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 constexpr FunctionModRefBehavior 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 constexpr FunctionModRefBehavior FMRB_OnlyAccessesInaccessibleOrArgMem =
256 FMRL_InaccessibleMem | 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 constexpr FunctionModRefBehavior FMRB_OnlyReadsMemory =
266 FMRL_Anywhere | static_cast<int>(ModRefInfo::Ref);
267
268 // This function does not read from memory anywhere, but may write to any
269 // memory location.
270 //
271 // This property corresponds to the LLVM IR 'writeonly' attribute.
272 // This property corresponds to the IntrWriteMem LLVM intrinsic flag.
273 constexpr FunctionModRefBehavior FMRB_DoesNotReadMemory =
274 FMRL_Anywhere | static_cast<int>(ModRefInfo::Mod);
275
276 /// This indicates that the function could not be classified into one of the
277 /// behaviors above.
278 constexpr FunctionModRefBehavior FMRB_UnknownModRefBehavior =
279 FMRL_Anywhere | static_cast<int>(ModRefInfo::ModRef);
280
281 // Wrapper method strips bits significant only in FunctionModRefBehavior,
282 // to obtain a valid ModRefInfo. The benefit of using the wrapper is that if
283 // ModRefInfo enum changes, the wrapper can be updated to & with the new enum
284 // entry with all bits set to 1.
285 LLVM_NODISCARD inline ModRefInfo
createModRefInfo(const FunctionModRefBehavior FMRB)286 createModRefInfo(const FunctionModRefBehavior FMRB) {
287 return ModRefInfo(FMRB & static_cast<int>(ModRefInfo::ModRef));
288 }
289
290 /// This class stores info we want to provide to or retain within an alias
291 /// query. By default, the root query is stateless and starts with a freshly
292 /// constructed info object. Specific alias analyses can use this query info to
293 /// store per-query state that is important for recursive or nested queries to
294 /// avoid recomputing. To enable preserving this state across multiple queries
295 /// where safe (due to the IR not changing), use a `BatchAAResults` wrapper.
296 /// The information stored in an `AAQueryInfo` is currently limitted to the
297 /// caches used by BasicAA, but can further be extended to fit other AA needs.
298 class AAQueryInfo {
299 public:
300 using LocPair = std::pair<MemoryLocation, MemoryLocation>;
301 using AliasCacheT = SmallDenseMap<LocPair, AliasResult, 8>;
302 AliasCacheT AliasCache;
303
304 using IsCapturedCacheT = SmallDenseMap<const Value *, bool, 8>;
305 IsCapturedCacheT IsCapturedCache;
306
AAQueryInfo()307 AAQueryInfo() : AliasCache(), IsCapturedCache() {}
308 };
309
310 class BatchAAResults;
311
312 class AAResults {
313 public:
314 // Make these results default constructable and movable. We have to spell
315 // these out because MSVC won't synthesize them.
AAResults(const TargetLibraryInfo & TLI)316 AAResults(const TargetLibraryInfo &TLI) : TLI(TLI) {}
317 AAResults(AAResults &&Arg);
318 ~AAResults();
319
320 /// Register a specific AA result.
addAAResult(AAResultT & AAResult)321 template <typename AAResultT> void addAAResult(AAResultT &AAResult) {
322 // FIXME: We should use a much lighter weight system than the usual
323 // polymorphic pattern because we don't own AAResult. It should
324 // ideally involve two pointers and no separate allocation.
325 AAs.emplace_back(new Model<AAResultT>(AAResult, *this));
326 }
327
328 /// Register a function analysis ID that the results aggregation depends on.
329 ///
330 /// This is used in the new pass manager to implement the invalidation logic
331 /// where we must invalidate the results aggregation if any of our component
332 /// analyses become invalid.
addAADependencyID(AnalysisKey * ID)333 void addAADependencyID(AnalysisKey *ID) { AADeps.push_back(ID); }
334
335 /// Handle invalidation events in the new pass manager.
336 ///
337 /// The aggregation is invalidated if any of the underlying analyses is
338 /// invalidated.
339 bool invalidate(Function &F, const PreservedAnalyses &PA,
340 FunctionAnalysisManager::Invalidator &Inv);
341
342 //===--------------------------------------------------------------------===//
343 /// \name Alias Queries
344 /// @{
345
346 /// The main low level interface to the alias analysis implementation.
347 /// Returns an AliasResult indicating whether the two pointers are aliased to
348 /// each other. This is the interface that must be implemented by specific
349 /// alias analysis implementations.
350 AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB);
351
352 /// A convenience wrapper around the primary \c alias interface.
alias(const Value * V1,LocationSize V1Size,const Value * V2,LocationSize V2Size)353 AliasResult alias(const Value *V1, LocationSize V1Size, const Value *V2,
354 LocationSize V2Size) {
355 return alias(MemoryLocation(V1, V1Size), MemoryLocation(V2, V2Size));
356 }
357
358 /// A convenience wrapper around the primary \c alias interface.
alias(const Value * V1,const Value * V2)359 AliasResult alias(const Value *V1, const Value *V2) {
360 return alias(V1, LocationSize::unknown(), V2, LocationSize::unknown());
361 }
362
363 /// A trivial helper function to check to see if the specified pointers are
364 /// no-alias.
isNoAlias(const MemoryLocation & LocA,const MemoryLocation & LocB)365 bool isNoAlias(const MemoryLocation &LocA, const MemoryLocation &LocB) {
366 return alias(LocA, LocB) == NoAlias;
367 }
368
369 /// A convenience wrapper around the \c isNoAlias helper interface.
isNoAlias(const Value * V1,LocationSize V1Size,const Value * V2,LocationSize V2Size)370 bool isNoAlias(const Value *V1, LocationSize V1Size, const Value *V2,
371 LocationSize V2Size) {
372 return isNoAlias(MemoryLocation(V1, V1Size), MemoryLocation(V2, V2Size));
373 }
374
375 /// A convenience wrapper around the \c isNoAlias helper interface.
isNoAlias(const Value * V1,const Value * V2)376 bool isNoAlias(const Value *V1, const Value *V2) {
377 return isNoAlias(MemoryLocation(V1), MemoryLocation(V2));
378 }
379
380 /// A trivial helper function to check to see if the specified pointers are
381 /// must-alias.
isMustAlias(const MemoryLocation & LocA,const MemoryLocation & LocB)382 bool isMustAlias(const MemoryLocation &LocA, const MemoryLocation &LocB) {
383 return alias(LocA, LocB) == MustAlias;
384 }
385
386 /// A convenience wrapper around the \c isMustAlias helper interface.
isMustAlias(const Value * V1,const Value * V2)387 bool isMustAlias(const Value *V1, const Value *V2) {
388 return alias(V1, LocationSize::precise(1), V2, LocationSize::precise(1)) ==
389 MustAlias;
390 }
391
392 /// Checks whether the given location points to constant memory, or if
393 /// \p OrLocal is true whether it points to a local alloca.
394 bool pointsToConstantMemory(const MemoryLocation &Loc, bool OrLocal = false);
395
396 /// A convenience wrapper around the primary \c pointsToConstantMemory
397 /// interface.
398 bool pointsToConstantMemory(const Value *P, bool OrLocal = false) {
399 return pointsToConstantMemory(MemoryLocation(P), OrLocal);
400 }
401
402 /// @}
403 //===--------------------------------------------------------------------===//
404 /// \name Simple mod/ref information
405 /// @{
406
407 /// Get the ModRef info associated with a pointer argument of a call. The
408 /// result's bits are set to indicate the allowed aliasing ModRef kinds. Note
409 /// that these bits do not necessarily account for the overall behavior of
410 /// the function, but rather only provide additional per-argument
411 /// information. This never sets ModRefInfo::Must.
412 ModRefInfo getArgModRefInfo(const CallBase *Call, unsigned ArgIdx);
413
414 /// Return the behavior of the given call site.
415 FunctionModRefBehavior getModRefBehavior(const CallBase *Call);
416
417 /// Return the behavior when calling the given function.
418 FunctionModRefBehavior getModRefBehavior(const Function *F);
419
420 /// Checks if the specified call is known to never read or write memory.
421 ///
422 /// Note that if the call only reads from known-constant memory, it is also
423 /// legal to return true. Also, calls that unwind the stack are legal for
424 /// this predicate.
425 ///
426 /// Many optimizations (such as CSE and LICM) can be performed on such calls
427 /// without worrying about aliasing properties, and many calls have this
428 /// property (e.g. calls to 'sin' and 'cos').
429 ///
430 /// This property corresponds to the GCC 'const' attribute.
doesNotAccessMemory(const CallBase * Call)431 bool doesNotAccessMemory(const CallBase *Call) {
432 return getModRefBehavior(Call) == FMRB_DoesNotAccessMemory;
433 }
434
435 /// Checks if the specified function is known to never read or write memory.
436 ///
437 /// Note that if the function only reads from known-constant memory, it is
438 /// also legal to return true. Also, function that unwind the stack are legal
439 /// for this predicate.
440 ///
441 /// Many optimizations (such as CSE and LICM) can be performed on such calls
442 /// to such functions without worrying about aliasing properties, and many
443 /// functions have this property (e.g. 'sin' and 'cos').
444 ///
445 /// This property corresponds to the GCC 'const' attribute.
doesNotAccessMemory(const Function * F)446 bool doesNotAccessMemory(const Function *F) {
447 return getModRefBehavior(F) == FMRB_DoesNotAccessMemory;
448 }
449
450 /// Checks if the specified call is known to only read from non-volatile
451 /// memory (or not access memory at all).
452 ///
453 /// Calls that unwind the stack are legal for this predicate.
454 ///
455 /// This property allows many common optimizations to be performed in the
456 /// absence of interfering store instructions, such as CSE of strlen calls.
457 ///
458 /// This property corresponds to the GCC 'pure' attribute.
onlyReadsMemory(const CallBase * Call)459 bool onlyReadsMemory(const CallBase *Call) {
460 return onlyReadsMemory(getModRefBehavior(Call));
461 }
462
463 /// Checks if the specified function is known to only read from non-volatile
464 /// memory (or not access memory at all).
465 ///
466 /// Functions that unwind the stack are legal for this predicate.
467 ///
468 /// This property allows many common optimizations to be performed in the
469 /// absence of interfering store instructions, such as CSE of strlen calls.
470 ///
471 /// This property corresponds to the GCC 'pure' attribute.
onlyReadsMemory(const Function * F)472 bool onlyReadsMemory(const Function *F) {
473 return onlyReadsMemory(getModRefBehavior(F));
474 }
475
476 /// Checks if functions with the specified behavior are known to only read
477 /// from non-volatile memory (or not access memory at all).
onlyReadsMemory(FunctionModRefBehavior MRB)478 static bool onlyReadsMemory(FunctionModRefBehavior MRB) {
479 return !isModSet(createModRefInfo(MRB));
480 }
481
482 /// Checks if functions with the specified behavior are known to only write
483 /// memory (or not access memory at all).
doesNotReadMemory(FunctionModRefBehavior MRB)484 static bool doesNotReadMemory(FunctionModRefBehavior MRB) {
485 return !isRefSet(createModRefInfo(MRB));
486 }
487
488 /// Checks if functions with the specified behavior are known to read and
489 /// write at most from objects pointed to by their pointer-typed arguments
490 /// (with arbitrary offsets).
onlyAccessesArgPointees(FunctionModRefBehavior MRB)491 static bool onlyAccessesArgPointees(FunctionModRefBehavior MRB) {
492 return !(MRB & FMRL_Anywhere & ~FMRL_ArgumentPointees);
493 }
494
495 /// Checks if functions with the specified behavior are known to potentially
496 /// read or write from objects pointed to be their pointer-typed arguments
497 /// (with arbitrary offsets).
doesAccessArgPointees(FunctionModRefBehavior MRB)498 static bool doesAccessArgPointees(FunctionModRefBehavior MRB) {
499 return isModOrRefSet(createModRefInfo(MRB)) &&
500 (MRB & FMRL_ArgumentPointees);
501 }
502
503 /// Checks if functions with the specified behavior are known to read and
504 /// write at most from memory that is inaccessible from LLVM IR.
onlyAccessesInaccessibleMem(FunctionModRefBehavior MRB)505 static bool onlyAccessesInaccessibleMem(FunctionModRefBehavior MRB) {
506 return !(MRB & FMRL_Anywhere & ~FMRL_InaccessibleMem);
507 }
508
509 /// Checks if functions with the specified behavior are known to potentially
510 /// read or write from memory that is inaccessible from LLVM IR.
doesAccessInaccessibleMem(FunctionModRefBehavior MRB)511 static bool doesAccessInaccessibleMem(FunctionModRefBehavior MRB) {
512 return isModOrRefSet(createModRefInfo(MRB)) && (MRB & FMRL_InaccessibleMem);
513 }
514
515 /// Checks if functions with the specified behavior are known to read and
516 /// write at most from memory that is inaccessible from LLVM IR or objects
517 /// pointed to by their pointer-typed arguments (with arbitrary offsets).
onlyAccessesInaccessibleOrArgMem(FunctionModRefBehavior MRB)518 static bool onlyAccessesInaccessibleOrArgMem(FunctionModRefBehavior MRB) {
519 return !(MRB & FMRL_Anywhere &
520 ~(FMRL_InaccessibleMem | FMRL_ArgumentPointees));
521 }
522
523 /// getModRefInfo (for call sites) - Return information about whether
524 /// a particular call site modifies or reads the specified memory location.
525 ModRefInfo getModRefInfo(const CallBase *Call, const MemoryLocation &Loc);
526
527 /// getModRefInfo (for call sites) - A convenience wrapper.
getModRefInfo(const CallBase * Call,const Value * P,LocationSize Size)528 ModRefInfo getModRefInfo(const CallBase *Call, const Value *P,
529 LocationSize Size) {
530 return getModRefInfo(Call, MemoryLocation(P, Size));
531 }
532
533 /// getModRefInfo (for loads) - Return information about whether
534 /// a particular load modifies or reads the specified memory location.
535 ModRefInfo getModRefInfo(const LoadInst *L, const MemoryLocation &Loc);
536
537 /// getModRefInfo (for loads) - A convenience wrapper.
getModRefInfo(const LoadInst * L,const Value * P,LocationSize Size)538 ModRefInfo getModRefInfo(const LoadInst *L, const Value *P,
539 LocationSize Size) {
540 return getModRefInfo(L, MemoryLocation(P, Size));
541 }
542
543 /// getModRefInfo (for stores) - Return information about whether
544 /// a particular store modifies or reads the specified memory location.
545 ModRefInfo getModRefInfo(const StoreInst *S, const MemoryLocation &Loc);
546
547 /// getModRefInfo (for stores) - A convenience wrapper.
getModRefInfo(const StoreInst * S,const Value * P,LocationSize Size)548 ModRefInfo getModRefInfo(const StoreInst *S, const Value *P,
549 LocationSize Size) {
550 return getModRefInfo(S, MemoryLocation(P, Size));
551 }
552
553 /// getModRefInfo (for fences) - Return information about whether
554 /// a particular store modifies or reads the specified memory location.
555 ModRefInfo getModRefInfo(const FenceInst *S, const MemoryLocation &Loc);
556
557 /// getModRefInfo (for fences) - A convenience wrapper.
getModRefInfo(const FenceInst * S,const Value * P,LocationSize Size)558 ModRefInfo getModRefInfo(const FenceInst *S, const Value *P,
559 LocationSize Size) {
560 return getModRefInfo(S, MemoryLocation(P, Size));
561 }
562
563 /// getModRefInfo (for cmpxchges) - Return information about whether
564 /// a particular cmpxchg modifies or reads the specified memory location.
565 ModRefInfo getModRefInfo(const AtomicCmpXchgInst *CX,
566 const MemoryLocation &Loc);
567
568 /// getModRefInfo (for cmpxchges) - A convenience wrapper.
getModRefInfo(const AtomicCmpXchgInst * CX,const Value * P,LocationSize Size)569 ModRefInfo getModRefInfo(const AtomicCmpXchgInst *CX, const Value *P,
570 LocationSize Size) {
571 return getModRefInfo(CX, MemoryLocation(P, Size));
572 }
573
574 /// getModRefInfo (for atomicrmws) - Return information about whether
575 /// a particular atomicrmw modifies or reads the specified memory location.
576 ModRefInfo getModRefInfo(const AtomicRMWInst *RMW, const MemoryLocation &Loc);
577
578 /// getModRefInfo (for atomicrmws) - A convenience wrapper.
getModRefInfo(const AtomicRMWInst * RMW,const Value * P,LocationSize Size)579 ModRefInfo getModRefInfo(const AtomicRMWInst *RMW, const Value *P,
580 LocationSize Size) {
581 return getModRefInfo(RMW, MemoryLocation(P, Size));
582 }
583
584 /// getModRefInfo (for va_args) - Return information about whether
585 /// a particular va_arg modifies or reads the specified memory location.
586 ModRefInfo getModRefInfo(const VAArgInst *I, const MemoryLocation &Loc);
587
588 /// getModRefInfo (for va_args) - A convenience wrapper.
getModRefInfo(const VAArgInst * I,const Value * P,LocationSize Size)589 ModRefInfo getModRefInfo(const VAArgInst *I, const Value *P,
590 LocationSize Size) {
591 return getModRefInfo(I, MemoryLocation(P, Size));
592 }
593
594 /// getModRefInfo (for catchpads) - Return information about whether
595 /// a particular catchpad modifies or reads the specified memory location.
596 ModRefInfo getModRefInfo(const CatchPadInst *I, const MemoryLocation &Loc);
597
598 /// getModRefInfo (for catchpads) - A convenience wrapper.
getModRefInfo(const CatchPadInst * I,const Value * P,LocationSize Size)599 ModRefInfo getModRefInfo(const CatchPadInst *I, const Value *P,
600 LocationSize Size) {
601 return getModRefInfo(I, MemoryLocation(P, Size));
602 }
603
604 /// getModRefInfo (for catchrets) - Return information about whether
605 /// a particular catchret modifies or reads the specified memory location.
606 ModRefInfo getModRefInfo(const CatchReturnInst *I, const MemoryLocation &Loc);
607
608 /// getModRefInfo (for catchrets) - A convenience wrapper.
getModRefInfo(const CatchReturnInst * I,const Value * P,LocationSize Size)609 ModRefInfo getModRefInfo(const CatchReturnInst *I, const Value *P,
610 LocationSize Size) {
611 return getModRefInfo(I, MemoryLocation(P, Size));
612 }
613
614 /// Check whether or not an instruction may read or write the optionally
615 /// specified memory location.
616 ///
617 ///
618 /// An instruction that doesn't read or write memory may be trivially LICM'd
619 /// for example.
620 ///
621 /// For function calls, this delegates to the alias-analysis specific
622 /// call-site mod-ref behavior queries. Otherwise it delegates to the specific
623 /// helpers above.
getModRefInfo(const Instruction * I,const Optional<MemoryLocation> & OptLoc)624 ModRefInfo getModRefInfo(const Instruction *I,
625 const Optional<MemoryLocation> &OptLoc) {
626 AAQueryInfo AAQIP;
627 return getModRefInfo(I, OptLoc, AAQIP);
628 }
629
630 /// A convenience wrapper for constructing the memory location.
getModRefInfo(const Instruction * I,const Value * P,LocationSize Size)631 ModRefInfo getModRefInfo(const Instruction *I, const Value *P,
632 LocationSize Size) {
633 return getModRefInfo(I, MemoryLocation(P, Size));
634 }
635
636 /// Return information about whether a call and an instruction may refer to
637 /// the same memory locations.
638 ModRefInfo getModRefInfo(Instruction *I, const CallBase *Call);
639
640 /// Return information about whether two call sites may refer to the same set
641 /// of memory locations. See the AA documentation for details:
642 /// http://llvm.org/docs/AliasAnalysis.html#ModRefInfo
643 ModRefInfo getModRefInfo(const CallBase *Call1, const CallBase *Call2);
644
645 /// Return information about whether a particular call site modifies
646 /// or reads the specified memory location \p MemLoc before instruction \p I
647 /// in a BasicBlock. An ordered basic block \p OBB can be used to speed up
648 /// instruction ordering queries inside the BasicBlock containing \p I.
649 /// Early exits in callCapturesBefore may lead to ModRefInfo::Must not being
650 /// set.
651 ModRefInfo callCapturesBefore(const Instruction *I,
652 const MemoryLocation &MemLoc, DominatorTree *DT,
653 OrderedBasicBlock *OBB = nullptr);
654
655 /// A convenience wrapper to synthesize a memory location.
656 ModRefInfo callCapturesBefore(const Instruction *I, const Value *P,
657 LocationSize Size, DominatorTree *DT,
658 OrderedBasicBlock *OBB = nullptr) {
659 return callCapturesBefore(I, MemoryLocation(P, Size), DT, OBB);
660 }
661
662 /// @}
663 //===--------------------------------------------------------------------===//
664 /// \name Higher level methods for querying mod/ref information.
665 /// @{
666
667 /// Check if it is possible for execution of the specified basic block to
668 /// modify the location Loc.
669 bool canBasicBlockModify(const BasicBlock &BB, const MemoryLocation &Loc);
670
671 /// A convenience wrapper synthesizing a memory location.
canBasicBlockModify(const BasicBlock & BB,const Value * P,LocationSize Size)672 bool canBasicBlockModify(const BasicBlock &BB, const Value *P,
673 LocationSize Size) {
674 return canBasicBlockModify(BB, MemoryLocation(P, Size));
675 }
676
677 /// Check if it is possible for the execution of the specified instructions
678 /// to mod\ref (according to the mode) the location Loc.
679 ///
680 /// The instructions to consider are all of the instructions in the range of
681 /// [I1,I2] INCLUSIVE. I1 and I2 must be in the same basic block.
682 bool canInstructionRangeModRef(const Instruction &I1, const Instruction &I2,
683 const MemoryLocation &Loc,
684 const ModRefInfo Mode);
685
686 /// A convenience wrapper synthesizing a memory location.
canInstructionRangeModRef(const Instruction & I1,const Instruction & I2,const Value * Ptr,LocationSize Size,const ModRefInfo Mode)687 bool canInstructionRangeModRef(const Instruction &I1, const Instruction &I2,
688 const Value *Ptr, LocationSize Size,
689 const ModRefInfo Mode) {
690 return canInstructionRangeModRef(I1, I2, MemoryLocation(Ptr, Size), Mode);
691 }
692
693 private:
694 AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB,
695 AAQueryInfo &AAQI);
696 bool pointsToConstantMemory(const MemoryLocation &Loc, AAQueryInfo &AAQI,
697 bool OrLocal = false);
698 ModRefInfo getModRefInfo(Instruction *I, const CallBase *Call2,
699 AAQueryInfo &AAQIP);
700 ModRefInfo getModRefInfo(const CallBase *Call, const MemoryLocation &Loc,
701 AAQueryInfo &AAQI);
702 ModRefInfo getModRefInfo(const CallBase *Call1, const CallBase *Call2,
703 AAQueryInfo &AAQI);
704 ModRefInfo getModRefInfo(const VAArgInst *V, const MemoryLocation &Loc,
705 AAQueryInfo &AAQI);
706 ModRefInfo getModRefInfo(const LoadInst *L, const MemoryLocation &Loc,
707 AAQueryInfo &AAQI);
708 ModRefInfo getModRefInfo(const StoreInst *S, const MemoryLocation &Loc,
709 AAQueryInfo &AAQI);
710 ModRefInfo getModRefInfo(const FenceInst *S, const MemoryLocation &Loc,
711 AAQueryInfo &AAQI);
712 ModRefInfo getModRefInfo(const AtomicCmpXchgInst *CX,
713 const MemoryLocation &Loc, AAQueryInfo &AAQI);
714 ModRefInfo getModRefInfo(const AtomicRMWInst *RMW, const MemoryLocation &Loc,
715 AAQueryInfo &AAQI);
716 ModRefInfo getModRefInfo(const CatchPadInst *I, const MemoryLocation &Loc,
717 AAQueryInfo &AAQI);
718 ModRefInfo getModRefInfo(const CatchReturnInst *I, const MemoryLocation &Loc,
719 AAQueryInfo &AAQI);
getModRefInfo(const Instruction * I,const Optional<MemoryLocation> & OptLoc,AAQueryInfo & AAQIP)720 ModRefInfo getModRefInfo(const Instruction *I,
721 const Optional<MemoryLocation> &OptLoc,
722 AAQueryInfo &AAQIP) {
723 if (OptLoc == None) {
724 if (const auto *Call = dyn_cast<CallBase>(I)) {
725 return createModRefInfo(getModRefBehavior(Call));
726 }
727 }
728
729 const MemoryLocation &Loc = OptLoc.getValueOr(MemoryLocation());
730
731 switch (I->getOpcode()) {
732 case Instruction::VAArg:
733 return getModRefInfo((const VAArgInst *)I, Loc, AAQIP);
734 case Instruction::Load:
735 return getModRefInfo((const LoadInst *)I, Loc, AAQIP);
736 case Instruction::Store:
737 return getModRefInfo((const StoreInst *)I, Loc, AAQIP);
738 case Instruction::Fence:
739 return getModRefInfo((const FenceInst *)I, Loc, AAQIP);
740 case Instruction::AtomicCmpXchg:
741 return getModRefInfo((const AtomicCmpXchgInst *)I, Loc, AAQIP);
742 case Instruction::AtomicRMW:
743 return getModRefInfo((const AtomicRMWInst *)I, Loc, AAQIP);
744 case Instruction::Call:
745 return getModRefInfo((const CallInst *)I, Loc, AAQIP);
746 case Instruction::Invoke:
747 return getModRefInfo((const InvokeInst *)I, Loc, AAQIP);
748 case Instruction::CatchPad:
749 return getModRefInfo((const CatchPadInst *)I, Loc, AAQIP);
750 case Instruction::CatchRet:
751 return getModRefInfo((const CatchReturnInst *)I, Loc, AAQIP);
752 default:
753 return ModRefInfo::NoModRef;
754 }
755 }
756
757 class Concept;
758
759 template <typename T> class Model;
760
761 template <typename T> friend class AAResultBase;
762
763 const TargetLibraryInfo &TLI;
764
765 std::vector<std::unique_ptr<Concept>> AAs;
766
767 std::vector<AnalysisKey *> AADeps;
768
769 friend class BatchAAResults;
770 };
771
772 /// This class is a wrapper over an AAResults, and it is intended to be used
773 /// only when there are no IR changes inbetween queries. BatchAAResults is
774 /// reusing the same `AAQueryInfo` to preserve the state across queries,
775 /// esentially making AA work in "batch mode". The internal state cannot be
776 /// cleared, so to go "out-of-batch-mode", the user must either use AAResults,
777 /// or create a new BatchAAResults.
778 class BatchAAResults {
779 AAResults &AA;
780 AAQueryInfo AAQI;
781
782 public:
BatchAAResults(AAResults & AAR)783 BatchAAResults(AAResults &AAR) : AA(AAR), AAQI() {}
alias(const MemoryLocation & LocA,const MemoryLocation & LocB)784 AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB) {
785 return AA.alias(LocA, LocB, AAQI);
786 }
787 bool pointsToConstantMemory(const MemoryLocation &Loc, bool OrLocal = false) {
788 return AA.pointsToConstantMemory(Loc, AAQI, OrLocal);
789 }
getModRefInfo(const CallBase * Call,const MemoryLocation & Loc)790 ModRefInfo getModRefInfo(const CallBase *Call, const MemoryLocation &Loc) {
791 return AA.getModRefInfo(Call, Loc, AAQI);
792 }
getModRefInfo(const CallBase * Call1,const CallBase * Call2)793 ModRefInfo getModRefInfo(const CallBase *Call1, const CallBase *Call2) {
794 return AA.getModRefInfo(Call1, Call2, AAQI);
795 }
getModRefInfo(const Instruction * I,const Optional<MemoryLocation> & OptLoc)796 ModRefInfo getModRefInfo(const Instruction *I,
797 const Optional<MemoryLocation> &OptLoc) {
798 return AA.getModRefInfo(I, OptLoc, AAQI);
799 }
getModRefInfo(Instruction * I,const CallBase * Call2)800 ModRefInfo getModRefInfo(Instruction *I, const CallBase *Call2) {
801 return AA.getModRefInfo(I, Call2, AAQI);
802 }
getArgModRefInfo(const CallBase * Call,unsigned ArgIdx)803 ModRefInfo getArgModRefInfo(const CallBase *Call, unsigned ArgIdx) {
804 return AA.getArgModRefInfo(Call, ArgIdx);
805 }
getModRefBehavior(const CallBase * Call)806 FunctionModRefBehavior getModRefBehavior(const CallBase *Call) {
807 return AA.getModRefBehavior(Call);
808 }
809 };
810
811 /// Temporary typedef for legacy code that uses a generic \c AliasAnalysis
812 /// pointer or reference.
813 using AliasAnalysis = AAResults;
814
815 /// A private abstract base class describing the concept of an individual alias
816 /// analysis implementation.
817 ///
818 /// This interface is implemented by any \c Model instantiation. It is also the
819 /// interface which a type used to instantiate the model must provide.
820 ///
821 /// All of these methods model methods by the same name in the \c
822 /// AAResults class. Only differences and specifics to how the
823 /// implementations are called are documented here.
824 class AAResults::Concept {
825 public:
826 virtual ~Concept() = 0;
827
828 /// An update API used internally by the AAResults to provide
829 /// a handle back to the top level aggregation.
830 virtual void setAAResults(AAResults *NewAAR) = 0;
831
832 //===--------------------------------------------------------------------===//
833 /// \name Alias Queries
834 /// @{
835
836 /// The main low level interface to the alias analysis implementation.
837 /// Returns an AliasResult indicating whether the two pointers are aliased to
838 /// each other. This is the interface that must be implemented by specific
839 /// alias analysis implementations.
840 virtual AliasResult alias(const MemoryLocation &LocA,
841 const MemoryLocation &LocB, AAQueryInfo &AAQI) = 0;
842
843 /// Checks whether the given location points to constant memory, or if
844 /// \p OrLocal is true whether it points to a local alloca.
845 virtual bool pointsToConstantMemory(const MemoryLocation &Loc,
846 AAQueryInfo &AAQI, bool OrLocal) = 0;
847
848 /// @}
849 //===--------------------------------------------------------------------===//
850 /// \name Simple mod/ref information
851 /// @{
852
853 /// Get the ModRef info associated with a pointer argument of a callsite. The
854 /// result's bits are set to indicate the allowed aliasing ModRef kinds. Note
855 /// that these bits do not necessarily account for the overall behavior of
856 /// the function, but rather only provide additional per-argument
857 /// information.
858 virtual ModRefInfo getArgModRefInfo(const CallBase *Call,
859 unsigned ArgIdx) = 0;
860
861 /// Return the behavior of the given call site.
862 virtual FunctionModRefBehavior getModRefBehavior(const CallBase *Call) = 0;
863
864 /// Return the behavior when calling the given function.
865 virtual FunctionModRefBehavior getModRefBehavior(const Function *F) = 0;
866
867 /// getModRefInfo (for call sites) - Return information about whether
868 /// a particular call site modifies or reads the specified memory location.
869 virtual ModRefInfo getModRefInfo(const CallBase *Call,
870 const MemoryLocation &Loc,
871 AAQueryInfo &AAQI) = 0;
872
873 /// Return information about whether two call sites may refer to the same set
874 /// of memory locations. See the AA documentation for details:
875 /// http://llvm.org/docs/AliasAnalysis.html#ModRefInfo
876 virtual ModRefInfo getModRefInfo(const CallBase *Call1, const CallBase *Call2,
877 AAQueryInfo &AAQI) = 0;
878
879 /// @}
880 };
881
882 /// A private class template which derives from \c Concept and wraps some other
883 /// type.
884 ///
885 /// This models the concept by directly forwarding each interface point to the
886 /// wrapped type which must implement a compatible interface. This provides
887 /// a type erased binding.
888 template <typename AAResultT> class AAResults::Model final : public Concept {
889 AAResultT &Result;
890
891 public:
Model(AAResultT & Result,AAResults & AAR)892 explicit Model(AAResultT &Result, AAResults &AAR) : Result(Result) {
893 Result.setAAResults(&AAR);
894 }
895 ~Model() override = default;
896
setAAResults(AAResults * NewAAR)897 void setAAResults(AAResults *NewAAR) override { Result.setAAResults(NewAAR); }
898
alias(const MemoryLocation & LocA,const MemoryLocation & LocB,AAQueryInfo & AAQI)899 AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB,
900 AAQueryInfo &AAQI) override {
901 return Result.alias(LocA, LocB, AAQI);
902 }
903
pointsToConstantMemory(const MemoryLocation & Loc,AAQueryInfo & AAQI,bool OrLocal)904 bool pointsToConstantMemory(const MemoryLocation &Loc, AAQueryInfo &AAQI,
905 bool OrLocal) override {
906 return Result.pointsToConstantMemory(Loc, AAQI, OrLocal);
907 }
908
getArgModRefInfo(const CallBase * Call,unsigned ArgIdx)909 ModRefInfo getArgModRefInfo(const CallBase *Call, unsigned ArgIdx) override {
910 return Result.getArgModRefInfo(Call, ArgIdx);
911 }
912
getModRefBehavior(const CallBase * Call)913 FunctionModRefBehavior getModRefBehavior(const CallBase *Call) override {
914 return Result.getModRefBehavior(Call);
915 }
916
getModRefBehavior(const Function * F)917 FunctionModRefBehavior getModRefBehavior(const Function *F) override {
918 return Result.getModRefBehavior(F);
919 }
920
getModRefInfo(const CallBase * Call,const MemoryLocation & Loc,AAQueryInfo & AAQI)921 ModRefInfo getModRefInfo(const CallBase *Call, const MemoryLocation &Loc,
922 AAQueryInfo &AAQI) override {
923 return Result.getModRefInfo(Call, Loc, AAQI);
924 }
925
getModRefInfo(const CallBase * Call1,const CallBase * Call2,AAQueryInfo & AAQI)926 ModRefInfo getModRefInfo(const CallBase *Call1, const CallBase *Call2,
927 AAQueryInfo &AAQI) override {
928 return Result.getModRefInfo(Call1, Call2, AAQI);
929 }
930 };
931
932 /// A CRTP-driven "mixin" base class to help implement the function alias
933 /// analysis results concept.
934 ///
935 /// Because of the nature of many alias analysis implementations, they often
936 /// only implement a subset of the interface. This base class will attempt to
937 /// implement the remaining portions of the interface in terms of simpler forms
938 /// of the interface where possible, and otherwise provide conservatively
939 /// correct fallback implementations.
940 ///
941 /// Implementors of an alias analysis should derive from this CRTP, and then
942 /// override specific methods that they wish to customize. There is no need to
943 /// use virtual anywhere, the CRTP base class does static dispatch to the
944 /// derived type passed into it.
945 template <typename DerivedT> class AAResultBase {
946 // Expose some parts of the interface only to the AAResults::Model
947 // for wrapping. Specifically, this allows the model to call our
948 // setAAResults method without exposing it as a fully public API.
949 friend class AAResults::Model<DerivedT>;
950
951 /// A pointer to the AAResults object that this AAResult is
952 /// aggregated within. May be null if not aggregated.
953 AAResults *AAR = nullptr;
954
955 /// Helper to dispatch calls back through the derived type.
derived()956 DerivedT &derived() { return static_cast<DerivedT &>(*this); }
957
958 /// A setter for the AAResults pointer, which is used to satisfy the
959 /// AAResults::Model contract.
setAAResults(AAResults * NewAAR)960 void setAAResults(AAResults *NewAAR) { AAR = NewAAR; }
961
962 protected:
963 /// This proxy class models a common pattern where we delegate to either the
964 /// top-level \c AAResults aggregation if one is registered, or to the
965 /// current result if none are registered.
966 class AAResultsProxy {
967 AAResults *AAR;
968 DerivedT &CurrentResult;
969
970 public:
AAResultsProxy(AAResults * AAR,DerivedT & CurrentResult)971 AAResultsProxy(AAResults *AAR, DerivedT &CurrentResult)
972 : AAR(AAR), CurrentResult(CurrentResult) {}
973
alias(const MemoryLocation & LocA,const MemoryLocation & LocB,AAQueryInfo & AAQI)974 AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB,
975 AAQueryInfo &AAQI) {
976 return AAR ? AAR->alias(LocA, LocB, AAQI)
977 : CurrentResult.alias(LocA, LocB, AAQI);
978 }
979
pointsToConstantMemory(const MemoryLocation & Loc,AAQueryInfo & AAQI,bool OrLocal)980 bool pointsToConstantMemory(const MemoryLocation &Loc, AAQueryInfo &AAQI,
981 bool OrLocal) {
982 return AAR ? AAR->pointsToConstantMemory(Loc, AAQI, OrLocal)
983 : CurrentResult.pointsToConstantMemory(Loc, AAQI, OrLocal);
984 }
985
getArgModRefInfo(const CallBase * Call,unsigned ArgIdx)986 ModRefInfo getArgModRefInfo(const CallBase *Call, unsigned ArgIdx) {
987 return AAR ? AAR->getArgModRefInfo(Call, ArgIdx)
988 : CurrentResult.getArgModRefInfo(Call, ArgIdx);
989 }
990
getModRefBehavior(const CallBase * Call)991 FunctionModRefBehavior getModRefBehavior(const CallBase *Call) {
992 return AAR ? AAR->getModRefBehavior(Call)
993 : CurrentResult.getModRefBehavior(Call);
994 }
995
getModRefBehavior(const Function * F)996 FunctionModRefBehavior getModRefBehavior(const Function *F) {
997 return AAR ? AAR->getModRefBehavior(F) : CurrentResult.getModRefBehavior(F);
998 }
999
getModRefInfo(const CallBase * Call,const MemoryLocation & Loc,AAQueryInfo & AAQI)1000 ModRefInfo getModRefInfo(const CallBase *Call, const MemoryLocation &Loc,
1001 AAQueryInfo &AAQI) {
1002 return AAR ? AAR->getModRefInfo(Call, Loc, AAQI)
1003 : CurrentResult.getModRefInfo(Call, Loc, AAQI);
1004 }
1005
getModRefInfo(const CallBase * Call1,const CallBase * Call2,AAQueryInfo & AAQI)1006 ModRefInfo getModRefInfo(const CallBase *Call1, const CallBase *Call2,
1007 AAQueryInfo &AAQI) {
1008 return AAR ? AAR->getModRefInfo(Call1, Call2, AAQI)
1009 : CurrentResult.getModRefInfo(Call1, Call2, AAQI);
1010 }
1011 };
1012
1013 explicit AAResultBase() = default;
1014
1015 // Provide all the copy and move constructors so that derived types aren't
1016 // constrained.
AAResultBase(const AAResultBase & Arg)1017 AAResultBase(const AAResultBase &Arg) {}
AAResultBase(AAResultBase && Arg)1018 AAResultBase(AAResultBase &&Arg) {}
1019
1020 /// Get a proxy for the best AA result set to query at this time.
1021 ///
1022 /// When this result is part of a larger aggregation, this will proxy to that
1023 /// aggregation. When this result is used in isolation, it will just delegate
1024 /// back to the derived class's implementation.
1025 ///
1026 /// Note that callers of this need to take considerable care to not cause
1027 /// performance problems when they use this routine, in the case of a large
1028 /// number of alias analyses being aggregated, it can be expensive to walk
1029 /// back across the chain.
getBestAAResults()1030 AAResultsProxy getBestAAResults() { return AAResultsProxy(AAR, derived()); }
1031
1032 public:
alias(const MemoryLocation & LocA,const MemoryLocation & LocB,AAQueryInfo & AAQI)1033 AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB,
1034 AAQueryInfo &AAQI) {
1035 return MayAlias;
1036 }
1037
pointsToConstantMemory(const MemoryLocation & Loc,AAQueryInfo & AAQI,bool OrLocal)1038 bool pointsToConstantMemory(const MemoryLocation &Loc, AAQueryInfo &AAQI,
1039 bool OrLocal) {
1040 return false;
1041 }
1042
getArgModRefInfo(const CallBase * Call,unsigned ArgIdx)1043 ModRefInfo getArgModRefInfo(const CallBase *Call, unsigned ArgIdx) {
1044 return ModRefInfo::ModRef;
1045 }
1046
getModRefBehavior(const CallBase * Call)1047 FunctionModRefBehavior getModRefBehavior(const CallBase *Call) {
1048 return FMRB_UnknownModRefBehavior;
1049 }
1050
getModRefBehavior(const Function * F)1051 FunctionModRefBehavior getModRefBehavior(const Function *F) {
1052 return FMRB_UnknownModRefBehavior;
1053 }
1054
getModRefInfo(const CallBase * Call,const MemoryLocation & Loc,AAQueryInfo & AAQI)1055 ModRefInfo getModRefInfo(const CallBase *Call, const MemoryLocation &Loc,
1056 AAQueryInfo &AAQI) {
1057 return ModRefInfo::ModRef;
1058 }
1059
getModRefInfo(const CallBase * Call1,const CallBase * Call2,AAQueryInfo & AAQI)1060 ModRefInfo getModRefInfo(const CallBase *Call1, const CallBase *Call2,
1061 AAQueryInfo &AAQI) {
1062 return ModRefInfo::ModRef;
1063 }
1064 };
1065
1066 /// Return true if this pointer is returned by a noalias function.
1067 bool isNoAliasCall(const Value *V);
1068
1069 /// Return true if this is an argument with the noalias attribute.
1070 bool isNoAliasArgument(const Value *V);
1071
1072 /// Return true if this pointer refers to a distinct and identifiable object.
1073 /// This returns true for:
1074 /// Global Variables and Functions (but not Global Aliases)
1075 /// Allocas
1076 /// ByVal and NoAlias Arguments
1077 /// NoAlias returns (e.g. calls to malloc)
1078 ///
1079 bool isIdentifiedObject(const Value *V);
1080
1081 /// Return true if V is umabigously identified at the function-level.
1082 /// Different IdentifiedFunctionLocals can't alias.
1083 /// Further, an IdentifiedFunctionLocal can not alias with any function
1084 /// arguments other than itself, which is not necessarily true for
1085 /// IdentifiedObjects.
1086 bool isIdentifiedFunctionLocal(const Value *V);
1087
1088 /// A manager for alias analyses.
1089 ///
1090 /// This class can have analyses registered with it and when run, it will run
1091 /// all of them and aggregate their results into single AA results interface
1092 /// that dispatches across all of the alias analysis results available.
1093 ///
1094 /// Note that the order in which analyses are registered is very significant.
1095 /// That is the order in which the results will be aggregated and queried.
1096 ///
1097 /// This manager effectively wraps the AnalysisManager for registering alias
1098 /// analyses. When you register your alias analysis with this manager, it will
1099 /// ensure the analysis itself is registered with its AnalysisManager.
1100 ///
1101 /// The result of this analysis is only invalidated if one of the particular
1102 /// aggregated AA results end up being invalidated. This removes the need to
1103 /// explicitly preserve the results of `AAManager`. Note that analyses should no
1104 /// longer be registered once the `AAManager` is run.
1105 class AAManager : public AnalysisInfoMixin<AAManager> {
1106 public:
1107 using Result = AAResults;
1108
1109 /// Register a specific AA result.
registerFunctionAnalysis()1110 template <typename AnalysisT> void registerFunctionAnalysis() {
1111 ResultGetters.push_back(&getFunctionAAResultImpl<AnalysisT>);
1112 }
1113
1114 /// Register a specific AA result.
registerModuleAnalysis()1115 template <typename AnalysisT> void registerModuleAnalysis() {
1116 ResultGetters.push_back(&getModuleAAResultImpl<AnalysisT>);
1117 }
1118
run(Function & F,FunctionAnalysisManager & AM)1119 Result run(Function &F, FunctionAnalysisManager &AM) {
1120 Result R(AM.getResult<TargetLibraryAnalysis>(F));
1121 for (auto &Getter : ResultGetters)
1122 (*Getter)(F, AM, R);
1123 return R;
1124 }
1125
1126 private:
1127 friend AnalysisInfoMixin<AAManager>;
1128
1129 static AnalysisKey Key;
1130
1131 SmallVector<void (*)(Function &F, FunctionAnalysisManager &AM,
1132 AAResults &AAResults),
1133 4> ResultGetters;
1134
1135 template <typename AnalysisT>
getFunctionAAResultImpl(Function & F,FunctionAnalysisManager & AM,AAResults & AAResults)1136 static void getFunctionAAResultImpl(Function &F,
1137 FunctionAnalysisManager &AM,
1138 AAResults &AAResults) {
1139 AAResults.addAAResult(AM.template getResult<AnalysisT>(F));
1140 AAResults.addAADependencyID(AnalysisT::ID());
1141 }
1142
1143 template <typename AnalysisT>
getModuleAAResultImpl(Function & F,FunctionAnalysisManager & AM,AAResults & AAResults)1144 static void getModuleAAResultImpl(Function &F, FunctionAnalysisManager &AM,
1145 AAResults &AAResults) {
1146 auto &MAMProxy = AM.getResult<ModuleAnalysisManagerFunctionProxy>(F);
1147 auto &MAM = MAMProxy.getManager();
1148 if (auto *R = MAM.template getCachedResult<AnalysisT>(*F.getParent())) {
1149 AAResults.addAAResult(*R);
1150 MAMProxy
1151 .template registerOuterAnalysisInvalidation<AnalysisT, AAManager>();
1152 }
1153 }
1154 };
1155
1156 /// A wrapper pass to provide the legacy pass manager access to a suitably
1157 /// prepared AAResults object.
1158 class AAResultsWrapperPass : public FunctionPass {
1159 std::unique_ptr<AAResults> AAR;
1160
1161 public:
1162 static char ID;
1163
1164 AAResultsWrapperPass();
1165
getAAResults()1166 AAResults &getAAResults() { return *AAR; }
getAAResults()1167 const AAResults &getAAResults() const { return *AAR; }
1168
1169 bool runOnFunction(Function &F) override;
1170
1171 void getAnalysisUsage(AnalysisUsage &AU) const override;
1172 };
1173
1174 /// A wrapper pass for external alias analyses. This just squirrels away the
1175 /// callback used to run any analyses and register their results.
1176 struct ExternalAAWrapperPass : ImmutablePass {
1177 using CallbackT = std::function<void(Pass &, Function &, AAResults &)>;
1178
1179 CallbackT CB;
1180
1181 static char ID;
1182
1183 ExternalAAWrapperPass();
1184
1185 explicit ExternalAAWrapperPass(CallbackT CB);
1186
getAnalysisUsageExternalAAWrapperPass1187 void getAnalysisUsage(AnalysisUsage &AU) const override {
1188 AU.setPreservesAll();
1189 }
1190 };
1191
1192 FunctionPass *createAAResultsWrapperPass();
1193
1194 /// A wrapper pass around a callback which can be used to populate the
1195 /// AAResults in the AAResultsWrapperPass from an external AA.
1196 ///
1197 /// The callback provided here will be used each time we prepare an AAResults
1198 /// object, and will receive a reference to the function wrapper pass, the
1199 /// function, and the AAResults object to populate. This should be used when
1200 /// setting up a custom pass pipeline to inject a hook into the AA results.
1201 ImmutablePass *createExternalAAWrapperPass(
1202 std::function<void(Pass &, Function &, AAResults &)> Callback);
1203
1204 /// A helper for the legacy pass manager to create a \c AAResults
1205 /// object populated to the best of our ability for a particular function when
1206 /// inside of a \c ModulePass or a \c CallGraphSCCPass.
1207 ///
1208 /// If a \c ModulePass or a \c CallGraphSCCPass calls \p
1209 /// createLegacyPMAAResults, it also needs to call \p addUsedAAAnalyses in \p
1210 /// getAnalysisUsage.
1211 AAResults createLegacyPMAAResults(Pass &P, Function &F, BasicAAResult &BAR);
1212
1213 /// A helper for the legacy pass manager to populate \p AU to add uses to make
1214 /// sure the analyses required by \p createLegacyPMAAResults are available.
1215 void getAAResultsAnalysisUsage(AnalysisUsage &AU);
1216
1217 } // end namespace llvm
1218
1219 #endif // LLVM_ANALYSIS_ALIASANALYSIS_H
1220