1 //==- AliasAnalysis.cpp - Generic Alias Analysis Interface Implementation --==//
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
7 //===----------------------------------------------------------------------===//
9 // This file implements the generic AliasAnalysis interface which is used as the
10 // common interface used by all clients and implementations of alias analysis.
12 // This file also implements the default version of the AliasAnalysis interface
13 // that is to be used when no other implementation is specified. This does some
14 // simple tests that detect obvious cases: two different global pointers cannot
15 // alias, a global cannot alias a malloc, two different mallocs cannot alias,
18 // This alias analysis implementation really isn't very good for anything, but
19 // it is very fast, and makes a nice clean default implementation. Because it
20 // handles lots of little corner cases, other, more complex, alias analysis
21 // implementations may choose to rely on this pass to resolve these simple and
24 //===----------------------------------------------------------------------===//
26 #include "llvm/Analysis/AliasAnalysis.h"
27 #include "llvm/ADT/Statistic.h"
28 #include "llvm/Analysis/BasicAliasAnalysis.h"
29 #include "llvm/Analysis/CaptureTracking.h"
30 #include "llvm/Analysis/GlobalsModRef.h"
31 #include "llvm/Analysis/MemoryLocation.h"
32 #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
33 #include "llvm/Analysis/ScopedNoAliasAA.h"
34 #include "llvm/Analysis/TargetLibraryInfo.h"
35 #include "llvm/Analysis/TypeBasedAliasAnalysis.h"
36 #include "llvm/Analysis/ValueTracking.h"
37 #include "llvm/IR/Argument.h"
38 #include "llvm/IR/Attributes.h"
39 #include "llvm/IR/BasicBlock.h"
40 #include "llvm/IR/Instruction.h"
41 #include "llvm/IR/Instructions.h"
42 #include "llvm/IR/Type.h"
43 #include "llvm/IR/Value.h"
44 #include "llvm/InitializePasses.h"
45 #include "llvm/Pass.h"
46 #include "llvm/Support/AtomicOrdering.h"
47 #include "llvm/Support/Casting.h"
48 #include "llvm/Support/CommandLine.h"
53 #define DEBUG_TYPE "aa"
57 STATISTIC(NumNoAlias
, "Number of NoAlias results");
58 STATISTIC(NumMayAlias
, "Number of MayAlias results");
59 STATISTIC(NumMustAlias
, "Number of MustAlias results");
62 /// Allow disabling BasicAA from the AA results. This is particularly useful
63 /// when testing to isolate a single AA implementation.
64 cl::opt
<bool> DisableBasicAA("disable-basic-aa", cl::Hidden
, cl::init(false));
68 /// Print a trace of alias analysis queries and their results.
69 static cl::opt
<bool> EnableAATrace("aa-trace", cl::Hidden
, cl::init(false));
71 static const bool EnableAATrace
= false;
74 AAResults::AAResults(const TargetLibraryInfo
&TLI
) : TLI(TLI
) {}
76 AAResults::AAResults(AAResults
&&Arg
)
77 : TLI(Arg
.TLI
), AAs(std::move(Arg
.AAs
)), AADeps(std::move(Arg
.AADeps
)) {}
79 AAResults::~AAResults() {}
81 bool AAResults::invalidate(Function
&F
, const PreservedAnalyses
&PA
,
82 FunctionAnalysisManager::Invalidator
&Inv
) {
83 // AAResults preserves the AAManager by default, due to the stateless nature
84 // of AliasAnalysis. There is no need to check whether it has been preserved
85 // explicitly. Check if any module dependency was invalidated and caused the
86 // AAManager to be invalidated. Invalidate ourselves in that case.
87 auto PAC
= PA
.getChecker
<AAManager
>();
88 if (!PAC
.preservedWhenStateless())
91 // Check if any of the function dependencies were invalidated, and invalidate
92 // ourselves in that case.
93 for (AnalysisKey
*ID
: AADeps
)
94 if (Inv
.invalidate(ID
, F
, PA
))
97 // Everything we depend on is still fine, so are we. Nothing to invalidate.
101 //===----------------------------------------------------------------------===//
102 // Default chaining methods
103 //===----------------------------------------------------------------------===//
105 AliasResult
AAResults::alias(const MemoryLocation
&LocA
,
106 const MemoryLocation
&LocB
) {
107 SimpleAAQueryInfo
AAQIP(*this);
108 return alias(LocA
, LocB
, AAQIP
, nullptr);
111 AliasResult
AAResults::alias(const MemoryLocation
&LocA
,
112 const MemoryLocation
&LocB
, AAQueryInfo
&AAQI
,
113 const Instruction
*CtxI
) {
114 AliasResult Result
= AliasResult::MayAlias
;
117 for (unsigned I
= 0; I
< AAQI
.Depth
; ++I
)
119 dbgs() << "Start " << *LocA
.Ptr
<< " @ " << LocA
.Size
<< ", "
120 << *LocB
.Ptr
<< " @ " << LocB
.Size
<< "\n";
124 for (const auto &AA
: AAs
) {
125 Result
= AA
->alias(LocA
, LocB
, AAQI
, CtxI
);
126 if (Result
!= AliasResult::MayAlias
)
132 for (unsigned I
= 0; I
< AAQI
.Depth
; ++I
)
134 dbgs() << "End " << *LocA
.Ptr
<< " @ " << LocA
.Size
<< ", "
135 << *LocB
.Ptr
<< " @ " << LocB
.Size
<< " = " << Result
<< "\n";
138 if (AAQI
.Depth
== 0) {
139 if (Result
== AliasResult::NoAlias
)
141 else if (Result
== AliasResult::MustAlias
)
149 ModRefInfo
AAResults::getModRefInfoMask(const MemoryLocation
&Loc
,
151 SimpleAAQueryInfo
AAQIP(*this);
152 return getModRefInfoMask(Loc
, AAQIP
, IgnoreLocals
);
155 ModRefInfo
AAResults::getModRefInfoMask(const MemoryLocation
&Loc
,
156 AAQueryInfo
&AAQI
, bool IgnoreLocals
) {
157 ModRefInfo Result
= ModRefInfo::ModRef
;
159 for (const auto &AA
: AAs
) {
160 Result
&= AA
->getModRefInfoMask(Loc
, AAQI
, IgnoreLocals
);
162 // Early-exit the moment we reach the bottom of the lattice.
163 if (isNoModRef(Result
))
164 return ModRefInfo::NoModRef
;
170 ModRefInfo
AAResults::getArgModRefInfo(const CallBase
*Call
, unsigned ArgIdx
) {
171 ModRefInfo Result
= ModRefInfo::ModRef
;
173 for (const auto &AA
: AAs
) {
174 Result
&= AA
->getArgModRefInfo(Call
, ArgIdx
);
176 // Early-exit the moment we reach the bottom of the lattice.
177 if (isNoModRef(Result
))
178 return ModRefInfo::NoModRef
;
184 ModRefInfo
AAResults::getModRefInfo(const Instruction
*I
,
185 const CallBase
*Call2
) {
186 SimpleAAQueryInfo
AAQIP(*this);
187 return getModRefInfo(I
, Call2
, AAQIP
);
190 ModRefInfo
AAResults::getModRefInfo(const Instruction
*I
, const CallBase
*Call2
,
192 // We may have two calls.
193 if (const auto *Call1
= dyn_cast
<CallBase
>(I
)) {
194 // Check if the two calls modify the same memory.
195 return getModRefInfo(Call1
, Call2
, AAQI
);
197 // If this is a fence, just return ModRef.
198 if (I
->isFenceLike())
199 return ModRefInfo::ModRef
;
200 // Otherwise, check if the call modifies or references the
201 // location this memory access defines. The best we can say
202 // is that if the call references what this instruction
203 // defines, it must be clobbered by this location.
204 const MemoryLocation DefLoc
= MemoryLocation::get(I
);
205 ModRefInfo MR
= getModRefInfo(Call2
, DefLoc
, AAQI
);
206 if (isModOrRefSet(MR
))
207 return ModRefInfo::ModRef
;
208 return ModRefInfo::NoModRef
;
211 ModRefInfo
AAResults::getModRefInfo(const CallBase
*Call
,
212 const MemoryLocation
&Loc
,
214 ModRefInfo Result
= ModRefInfo::ModRef
;
216 for (const auto &AA
: AAs
) {
217 Result
&= AA
->getModRefInfo(Call
, Loc
, AAQI
);
219 // Early-exit the moment we reach the bottom of the lattice.
220 if (isNoModRef(Result
))
221 return ModRefInfo::NoModRef
;
224 // Try to refine the mod-ref info further using other API entry points to the
225 // aggregate set of AA results.
227 // We can completely ignore inaccessible memory here, because MemoryLocations
228 // can only reference accessible memory.
229 auto ME
= getMemoryEffects(Call
, AAQI
)
230 .getWithoutLoc(IRMemLocation::InaccessibleMem
);
231 if (ME
.doesNotAccessMemory())
232 return ModRefInfo::NoModRef
;
234 ModRefInfo ArgMR
= ME
.getModRef(IRMemLocation::ArgMem
);
235 ModRefInfo OtherMR
= ME
.getWithoutLoc(IRMemLocation::ArgMem
).getModRef();
236 if ((ArgMR
| OtherMR
) != OtherMR
) {
237 // Refine the modref info for argument memory. We only bother to do this
238 // if ArgMR is not a subset of OtherMR, otherwise this won't have an impact
239 // on the final result.
240 ModRefInfo AllArgsMask
= ModRefInfo::NoModRef
;
241 for (const auto &I
: llvm::enumerate(Call
->args())) {
242 const Value
*Arg
= I
.value();
243 if (!Arg
->getType()->isPointerTy())
245 unsigned ArgIdx
= I
.index();
246 MemoryLocation ArgLoc
= MemoryLocation::getForArgument(Call
, ArgIdx
, TLI
);
247 AliasResult ArgAlias
= alias(ArgLoc
, Loc
, AAQI
, Call
);
248 if (ArgAlias
!= AliasResult::NoAlias
)
249 AllArgsMask
|= getArgModRefInfo(Call
, ArgIdx
);
251 ArgMR
&= AllArgsMask
;
254 Result
&= ArgMR
| OtherMR
;
256 // Apply the ModRef mask. This ensures that if Loc is a constant memory
257 // location, we take into account the fact that the call definitely could not
258 // modify the memory location.
259 if (!isNoModRef(Result
))
260 Result
&= getModRefInfoMask(Loc
);
265 ModRefInfo
AAResults::getModRefInfo(const CallBase
*Call1
,
266 const CallBase
*Call2
, AAQueryInfo
&AAQI
) {
267 ModRefInfo Result
= ModRefInfo::ModRef
;
269 for (const auto &AA
: AAs
) {
270 Result
&= AA
->getModRefInfo(Call1
, Call2
, AAQI
);
272 // Early-exit the moment we reach the bottom of the lattice.
273 if (isNoModRef(Result
))
274 return ModRefInfo::NoModRef
;
277 // Try to refine the mod-ref info further using other API entry points to the
278 // aggregate set of AA results.
280 // If Call1 or Call2 are readnone, they don't interact.
281 auto Call1B
= getMemoryEffects(Call1
, AAQI
);
282 if (Call1B
.doesNotAccessMemory())
283 return ModRefInfo::NoModRef
;
285 auto Call2B
= getMemoryEffects(Call2
, AAQI
);
286 if (Call2B
.doesNotAccessMemory())
287 return ModRefInfo::NoModRef
;
289 // If they both only read from memory, there is no dependence.
290 if (Call1B
.onlyReadsMemory() && Call2B
.onlyReadsMemory())
291 return ModRefInfo::NoModRef
;
293 // If Call1 only reads memory, the only dependence on Call2 can be
294 // from Call1 reading memory written by Call2.
295 if (Call1B
.onlyReadsMemory())
296 Result
&= ModRefInfo::Ref
;
297 else if (Call1B
.onlyWritesMemory())
298 Result
&= ModRefInfo::Mod
;
300 // If Call2 only access memory through arguments, accumulate the mod/ref
301 // information from Call1's references to the memory referenced by
302 // Call2's arguments.
303 if (Call2B
.onlyAccessesArgPointees()) {
304 if (!Call2B
.doesAccessArgPointees())
305 return ModRefInfo::NoModRef
;
306 ModRefInfo R
= ModRefInfo::NoModRef
;
307 for (auto I
= Call2
->arg_begin(), E
= Call2
->arg_end(); I
!= E
; ++I
) {
308 const Value
*Arg
= *I
;
309 if (!Arg
->getType()->isPointerTy())
311 unsigned Call2ArgIdx
= std::distance(Call2
->arg_begin(), I
);
313 MemoryLocation::getForArgument(Call2
, Call2ArgIdx
, TLI
);
315 // ArgModRefC2 indicates what Call2 might do to Call2ArgLoc, and the
316 // dependence of Call1 on that location is the inverse:
317 // - If Call2 modifies location, dependence exists if Call1 reads or
319 // - If Call2 only reads location, dependence exists if Call1 writes.
320 ModRefInfo ArgModRefC2
= getArgModRefInfo(Call2
, Call2ArgIdx
);
321 ModRefInfo ArgMask
= ModRefInfo::NoModRef
;
322 if (isModSet(ArgModRefC2
))
323 ArgMask
= ModRefInfo::ModRef
;
324 else if (isRefSet(ArgModRefC2
))
325 ArgMask
= ModRefInfo::Mod
;
327 // ModRefC1 indicates what Call1 might do to Call2ArgLoc, and we use
328 // above ArgMask to update dependence info.
329 ArgMask
&= getModRefInfo(Call1
, Call2ArgLoc
, AAQI
);
331 R
= (R
| ArgMask
) & Result
;
339 // If Call1 only accesses memory through arguments, check if Call2 references
340 // any of the memory referenced by Call1's arguments. If not, return NoModRef.
341 if (Call1B
.onlyAccessesArgPointees()) {
342 if (!Call1B
.doesAccessArgPointees())
343 return ModRefInfo::NoModRef
;
344 ModRefInfo R
= ModRefInfo::NoModRef
;
345 for (auto I
= Call1
->arg_begin(), E
= Call1
->arg_end(); I
!= E
; ++I
) {
346 const Value
*Arg
= *I
;
347 if (!Arg
->getType()->isPointerTy())
349 unsigned Call1ArgIdx
= std::distance(Call1
->arg_begin(), I
);
351 MemoryLocation::getForArgument(Call1
, Call1ArgIdx
, TLI
);
353 // ArgModRefC1 indicates what Call1 might do to Call1ArgLoc; if Call1
354 // might Mod Call1ArgLoc, then we care about either a Mod or a Ref by
355 // Call2. If Call1 might Ref, then we care only about a Mod by Call2.
356 ModRefInfo ArgModRefC1
= getArgModRefInfo(Call1
, Call1ArgIdx
);
357 ModRefInfo ModRefC2
= getModRefInfo(Call2
, Call1ArgLoc
, AAQI
);
358 if ((isModSet(ArgModRefC1
) && isModOrRefSet(ModRefC2
)) ||
359 (isRefSet(ArgModRefC1
) && isModSet(ModRefC2
)))
360 R
= (R
| ArgModRefC1
) & Result
;
372 MemoryEffects
AAResults::getMemoryEffects(const CallBase
*Call
,
374 MemoryEffects Result
= MemoryEffects::unknown();
376 for (const auto &AA
: AAs
) {
377 Result
&= AA
->getMemoryEffects(Call
, AAQI
);
379 // Early-exit the moment we reach the bottom of the lattice.
380 if (Result
.doesNotAccessMemory())
387 MemoryEffects
AAResults::getMemoryEffects(const CallBase
*Call
) {
388 SimpleAAQueryInfo
AAQI(*this);
389 return getMemoryEffects(Call
, AAQI
);
392 MemoryEffects
AAResults::getMemoryEffects(const Function
*F
) {
393 MemoryEffects Result
= MemoryEffects::unknown();
395 for (const auto &AA
: AAs
) {
396 Result
&= AA
->getMemoryEffects(F
);
398 // Early-exit the moment we reach the bottom of the lattice.
399 if (Result
.doesNotAccessMemory())
406 raw_ostream
&llvm::operator<<(raw_ostream
&OS
, AliasResult AR
) {
408 case AliasResult::NoAlias
:
411 case AliasResult::MustAlias
:
414 case AliasResult::MayAlias
:
417 case AliasResult::PartialAlias
:
418 OS
<< "PartialAlias";
420 OS
<< " (off " << AR
.getOffset() << ")";
426 //===----------------------------------------------------------------------===//
427 // Helper method implementation
428 //===----------------------------------------------------------------------===//
430 ModRefInfo
AAResults::getModRefInfo(const LoadInst
*L
,
431 const MemoryLocation
&Loc
,
433 // Be conservative in the face of atomic.
434 if (isStrongerThan(L
->getOrdering(), AtomicOrdering::Unordered
))
435 return ModRefInfo::ModRef
;
437 // If the load address doesn't alias the given address, it doesn't read
438 // or write the specified memory.
440 AliasResult AR
= alias(MemoryLocation::get(L
), Loc
, AAQI
, L
);
441 if (AR
== AliasResult::NoAlias
)
442 return ModRefInfo::NoModRef
;
444 // Otherwise, a load just reads.
445 return ModRefInfo::Ref
;
448 ModRefInfo
AAResults::getModRefInfo(const StoreInst
*S
,
449 const MemoryLocation
&Loc
,
451 // Be conservative in the face of atomic.
452 if (isStrongerThan(S
->getOrdering(), AtomicOrdering::Unordered
))
453 return ModRefInfo::ModRef
;
456 AliasResult AR
= alias(MemoryLocation::get(S
), Loc
, AAQI
, S
);
457 // If the store address cannot alias the pointer in question, then the
458 // specified memory cannot be modified by the store.
459 if (AR
== AliasResult::NoAlias
)
460 return ModRefInfo::NoModRef
;
462 // Examine the ModRef mask. If Mod isn't present, then return NoModRef.
463 // This ensures that if Loc is a constant memory location, we take into
464 // account the fact that the store definitely could not modify the memory
466 if (!isModSet(getModRefInfoMask(Loc
)))
467 return ModRefInfo::NoModRef
;
470 // Otherwise, a store just writes.
471 return ModRefInfo::Mod
;
474 ModRefInfo
AAResults::getModRefInfo(const FenceInst
*S
,
475 const MemoryLocation
&Loc
,
477 // All we know about a fence instruction is what we get from the ModRef
478 // mask: if Loc is a constant memory location, the fence definitely could
481 return getModRefInfoMask(Loc
);
482 return ModRefInfo::ModRef
;
485 ModRefInfo
AAResults::getModRefInfo(const VAArgInst
*V
,
486 const MemoryLocation
&Loc
,
489 AliasResult AR
= alias(MemoryLocation::get(V
), Loc
, AAQI
, V
);
490 // If the va_arg address cannot alias the pointer in question, then the
491 // specified memory cannot be accessed by the va_arg.
492 if (AR
== AliasResult::NoAlias
)
493 return ModRefInfo::NoModRef
;
495 // If the pointer is a pointer to invariant memory, then it could not have
496 // been modified by this va_arg.
497 return getModRefInfoMask(Loc
, AAQI
);
500 // Otherwise, a va_arg reads and writes.
501 return ModRefInfo::ModRef
;
504 ModRefInfo
AAResults::getModRefInfo(const CatchPadInst
*CatchPad
,
505 const MemoryLocation
&Loc
,
508 // If the pointer is a pointer to invariant memory,
509 // then it could not have been modified by this catchpad.
510 return getModRefInfoMask(Loc
, AAQI
);
513 // Otherwise, a catchpad reads and writes.
514 return ModRefInfo::ModRef
;
517 ModRefInfo
AAResults::getModRefInfo(const CatchReturnInst
*CatchRet
,
518 const MemoryLocation
&Loc
,
521 // If the pointer is a pointer to invariant memory,
522 // then it could not have been modified by this catchpad.
523 return getModRefInfoMask(Loc
, AAQI
);
526 // Otherwise, a catchret reads and writes.
527 return ModRefInfo::ModRef
;
530 ModRefInfo
AAResults::getModRefInfo(const AtomicCmpXchgInst
*CX
,
531 const MemoryLocation
&Loc
,
533 // Acquire/Release cmpxchg has properties that matter for arbitrary addresses.
534 if (isStrongerThanMonotonic(CX
->getSuccessOrdering()))
535 return ModRefInfo::ModRef
;
538 AliasResult AR
= alias(MemoryLocation::get(CX
), Loc
, AAQI
, CX
);
539 // If the cmpxchg address does not alias the location, it does not access
541 if (AR
== AliasResult::NoAlias
)
542 return ModRefInfo::NoModRef
;
545 return ModRefInfo::ModRef
;
548 ModRefInfo
AAResults::getModRefInfo(const AtomicRMWInst
*RMW
,
549 const MemoryLocation
&Loc
,
551 // Acquire/Release atomicrmw has properties that matter for arbitrary addresses.
552 if (isStrongerThanMonotonic(RMW
->getOrdering()))
553 return ModRefInfo::ModRef
;
556 AliasResult AR
= alias(MemoryLocation::get(RMW
), Loc
, AAQI
, RMW
);
557 // If the atomicrmw address does not alias the location, it does not access
559 if (AR
== AliasResult::NoAlias
)
560 return ModRefInfo::NoModRef
;
563 return ModRefInfo::ModRef
;
566 ModRefInfo
AAResults::getModRefInfo(const Instruction
*I
,
567 const std::optional
<MemoryLocation
> &OptLoc
,
568 AAQueryInfo
&AAQIP
) {
569 if (OptLoc
== std::nullopt
) {
570 if (const auto *Call
= dyn_cast
<CallBase
>(I
))
571 return getMemoryEffects(Call
, AAQIP
).getModRef();
574 const MemoryLocation
&Loc
= OptLoc
.value_or(MemoryLocation());
576 switch (I
->getOpcode()) {
577 case Instruction::VAArg
:
578 return getModRefInfo((const VAArgInst
*)I
, Loc
, AAQIP
);
579 case Instruction::Load
:
580 return getModRefInfo((const LoadInst
*)I
, Loc
, AAQIP
);
581 case Instruction::Store
:
582 return getModRefInfo((const StoreInst
*)I
, Loc
, AAQIP
);
583 case Instruction::Fence
:
584 return getModRefInfo((const FenceInst
*)I
, Loc
, AAQIP
);
585 case Instruction::AtomicCmpXchg
:
586 return getModRefInfo((const AtomicCmpXchgInst
*)I
, Loc
, AAQIP
);
587 case Instruction::AtomicRMW
:
588 return getModRefInfo((const AtomicRMWInst
*)I
, Loc
, AAQIP
);
589 case Instruction::Call
:
590 case Instruction::CallBr
:
591 case Instruction::Invoke
:
592 return getModRefInfo((const CallBase
*)I
, Loc
, AAQIP
);
593 case Instruction::CatchPad
:
594 return getModRefInfo((const CatchPadInst
*)I
, Loc
, AAQIP
);
595 case Instruction::CatchRet
:
596 return getModRefInfo((const CatchReturnInst
*)I
, Loc
, AAQIP
);
598 assert(!I
->mayReadOrWriteMemory() &&
599 "Unhandled memory access instruction!");
600 return ModRefInfo::NoModRef
;
604 /// Return information about whether a particular call site modifies
605 /// or reads the specified memory location \p MemLoc before instruction \p I
607 /// FIXME: this is really just shoring-up a deficiency in alias analysis.
608 /// BasicAA isn't willing to spend linear time determining whether an alloca
609 /// was captured before or after this particular call, while we are. However,
610 /// with a smarter AA in place, this test is just wasting compile time.
611 ModRefInfo
AAResults::callCapturesBefore(const Instruction
*I
,
612 const MemoryLocation
&MemLoc
,
616 return ModRefInfo::ModRef
;
618 const Value
*Object
= getUnderlyingObject(MemLoc
.Ptr
);
619 if (!isIdentifiedFunctionLocal(Object
))
620 return ModRefInfo::ModRef
;
622 const auto *Call
= dyn_cast
<CallBase
>(I
);
623 if (!Call
|| Call
== Object
)
624 return ModRefInfo::ModRef
;
626 if (PointerMayBeCapturedBefore(Object
, /* ReturnCaptures */ true,
627 /* StoreCaptures */ true, I
, DT
,
628 /* include Object */ true))
629 return ModRefInfo::ModRef
;
632 ModRefInfo R
= ModRefInfo::NoModRef
;
633 // Set flag only if no May found and all operands processed.
634 for (auto CI
= Call
->data_operands_begin(), CE
= Call
->data_operands_end();
635 CI
!= CE
; ++CI
, ++ArgNo
) {
636 // Only look at the no-capture or byval pointer arguments. If this
637 // pointer were passed to arguments that were neither of these, then it
638 // couldn't be no-capture.
639 if (!(*CI
)->getType()->isPointerTy() || !Call
->doesNotCapture(ArgNo
))
643 alias(MemoryLocation::getBeforeOrAfter(*CI
),
644 MemoryLocation::getBeforeOrAfter(Object
), AAQI
, Call
);
645 // If this is a no-capture pointer argument, see if we can tell that it
646 // is impossible to alias the pointer we're checking. If not, we have to
647 // assume that the call could touch the pointer, even though it doesn't
649 if (AR
== AliasResult::NoAlias
)
651 if (Call
->doesNotAccessMemory(ArgNo
))
653 if (Call
->onlyReadsMemory(ArgNo
)) {
657 return ModRefInfo::ModRef
;
662 /// canBasicBlockModify - Return true if it is possible for execution of the
663 /// specified basic block to modify the location Loc.
665 bool AAResults::canBasicBlockModify(const BasicBlock
&BB
,
666 const MemoryLocation
&Loc
) {
667 return canInstructionRangeModRef(BB
.front(), BB
.back(), Loc
, ModRefInfo::Mod
);
670 /// canInstructionRangeModRef - Return true if it is possible for the
671 /// execution of the specified instructions to mod\ref (according to the
672 /// mode) the location Loc. The instructions to consider are all
673 /// of the instructions in the range of [I1,I2] INCLUSIVE.
674 /// I1 and I2 must be in the same basic block.
675 bool AAResults::canInstructionRangeModRef(const Instruction
&I1
,
676 const Instruction
&I2
,
677 const MemoryLocation
&Loc
,
678 const ModRefInfo Mode
) {
679 assert(I1
.getParent() == I2
.getParent() &&
680 "Instructions not in same basic block!");
681 BasicBlock::const_iterator I
= I1
.getIterator();
682 BasicBlock::const_iterator E
= I2
.getIterator();
683 ++E
; // Convert from inclusive to exclusive range.
685 for (; I
!= E
; ++I
) // Check every instruction in range
686 if (isModOrRefSet(getModRefInfo(&*I
, Loc
) & Mode
))
691 // Provide a definition for the root virtual destructor.
692 AAResults::Concept::~Concept() = default;
694 // Provide a definition for the static object used to identify passes.
695 AnalysisKey
AAManager::Key
;
697 ExternalAAWrapperPass::ExternalAAWrapperPass() : ImmutablePass(ID
) {
698 initializeExternalAAWrapperPassPass(*PassRegistry::getPassRegistry());
701 ExternalAAWrapperPass::ExternalAAWrapperPass(CallbackT CB
)
702 : ImmutablePass(ID
), CB(std::move(CB
)) {
703 initializeExternalAAWrapperPassPass(*PassRegistry::getPassRegistry());
706 char ExternalAAWrapperPass::ID
= 0;
708 INITIALIZE_PASS(ExternalAAWrapperPass
, "external-aa", "External Alias Analysis",
712 llvm::createExternalAAWrapperPass(ExternalAAWrapperPass::CallbackT Callback
) {
713 return new ExternalAAWrapperPass(std::move(Callback
));
716 AAResultsWrapperPass::AAResultsWrapperPass() : FunctionPass(ID
) {
717 initializeAAResultsWrapperPassPass(*PassRegistry::getPassRegistry());
720 char AAResultsWrapperPass::ID
= 0;
722 INITIALIZE_PASS_BEGIN(AAResultsWrapperPass
, "aa",
723 "Function Alias Analysis Results", false, true)
724 INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass
)
725 INITIALIZE_PASS_DEPENDENCY(ExternalAAWrapperPass
)
726 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass
)
727 INITIALIZE_PASS_DEPENDENCY(SCEVAAWrapperPass
)
728 INITIALIZE_PASS_DEPENDENCY(ScopedNoAliasAAWrapperPass
)
729 INITIALIZE_PASS_DEPENDENCY(TypeBasedAAWrapperPass
)
730 INITIALIZE_PASS_END(AAResultsWrapperPass
, "aa",
731 "Function Alias Analysis Results", false, true)
733 /// Run the wrapper pass to rebuild an aggregation over known AA passes.
735 /// This is the legacy pass manager's interface to the new-style AA results
736 /// aggregation object. Because this is somewhat shoe-horned into the legacy
737 /// pass manager, we hard code all the specific alias analyses available into
738 /// it. While the particular set enabled is configured via commandline flags,
739 /// adding a new alias analysis to LLVM will require adding support for it to
741 bool AAResultsWrapperPass::runOnFunction(Function
&F
) {
742 // NB! This *must* be reset before adding new AA results to the new
743 // AAResults object because in the legacy pass manager, each instance
744 // of these will refer to the *same* immutable analyses, registering and
745 // unregistering themselves with them. We need to carefully tear down the
746 // previous object first, in this case replacing it with an empty one, before
747 // registering new results.
749 new AAResults(getAnalysis
<TargetLibraryInfoWrapperPass
>().getTLI(F
)));
751 // BasicAA is always available for function analyses. Also, we add it first
752 // so that it can trump TBAA results when it proves MustAlias.
753 // FIXME: TBAA should have an explicit mode to support this and then we
754 // should reconsider the ordering here.
756 AAR
->addAAResult(getAnalysis
<BasicAAWrapperPass
>().getResult());
758 // Populate the results with the currently available AAs.
759 if (auto *WrapperPass
= getAnalysisIfAvailable
<ScopedNoAliasAAWrapperPass
>())
760 AAR
->addAAResult(WrapperPass
->getResult());
761 if (auto *WrapperPass
= getAnalysisIfAvailable
<TypeBasedAAWrapperPass
>())
762 AAR
->addAAResult(WrapperPass
->getResult());
763 if (auto *WrapperPass
= getAnalysisIfAvailable
<GlobalsAAWrapperPass
>())
764 AAR
->addAAResult(WrapperPass
->getResult());
765 if (auto *WrapperPass
= getAnalysisIfAvailable
<SCEVAAWrapperPass
>())
766 AAR
->addAAResult(WrapperPass
->getResult());
768 // If available, run an external AA providing callback over the results as
770 if (auto *WrapperPass
= getAnalysisIfAvailable
<ExternalAAWrapperPass
>())
772 WrapperPass
->CB(*this, F
, *AAR
);
774 // Analyses don't mutate the IR, so return false.
778 void AAResultsWrapperPass::getAnalysisUsage(AnalysisUsage
&AU
) const {
779 AU
.setPreservesAll();
780 AU
.addRequiredTransitive
<BasicAAWrapperPass
>();
781 AU
.addRequiredTransitive
<TargetLibraryInfoWrapperPass
>();
783 // We also need to mark all the alias analysis passes we will potentially
784 // probe in runOnFunction as used here to ensure the legacy pass manager
785 // preserves them. This hard coding of lists of alias analyses is specific to
786 // the legacy pass manager.
787 AU
.addUsedIfAvailable
<ScopedNoAliasAAWrapperPass
>();
788 AU
.addUsedIfAvailable
<TypeBasedAAWrapperPass
>();
789 AU
.addUsedIfAvailable
<GlobalsAAWrapperPass
>();
790 AU
.addUsedIfAvailable
<SCEVAAWrapperPass
>();
791 AU
.addUsedIfAvailable
<ExternalAAWrapperPass
>();
794 AAManager::Result
AAManager::run(Function
&F
, FunctionAnalysisManager
&AM
) {
795 Result
R(AM
.getResult
<TargetLibraryAnalysis
>(F
));
796 for (auto &Getter
: ResultGetters
)
801 bool llvm::isNoAliasCall(const Value
*V
) {
802 if (const auto *Call
= dyn_cast
<CallBase
>(V
))
803 return Call
->hasRetAttr(Attribute::NoAlias
);
807 static bool isNoAliasOrByValArgument(const Value
*V
) {
808 if (const Argument
*A
= dyn_cast
<Argument
>(V
))
809 return A
->hasNoAliasAttr() || A
->hasByValAttr();
813 bool llvm::isIdentifiedObject(const Value
*V
) {
814 if (isa
<AllocaInst
>(V
))
816 if (isa
<GlobalValue
>(V
) && !isa
<GlobalAlias
>(V
))
818 if (isNoAliasCall(V
))
820 if (isNoAliasOrByValArgument(V
))
825 bool llvm::isIdentifiedFunctionLocal(const Value
*V
) {
826 return isa
<AllocaInst
>(V
) || isNoAliasCall(V
) || isNoAliasOrByValArgument(V
);
829 bool llvm::isBaseOfObject(const Value
*V
) {
830 // TODO: We can handle other cases here
831 // 1) For GC languages, arguments to functions are often required to be
833 // 2) Result of allocation routines are often base pointers. Leverage TLI.
834 return (isa
<AllocaInst
>(V
) || isa
<GlobalVariable
>(V
));
837 bool llvm::isEscapeSource(const Value
*V
) {
838 if (auto *CB
= dyn_cast
<CallBase
>(V
))
839 return !isIntrinsicReturningPointerAliasingArgumentWithoutCapturing(CB
,
842 // The load case works because isNonEscapingLocalObject considers all
843 // stores to be escapes (it passes true for the StoreCaptures argument
844 // to PointerMayBeCaptured).
845 if (isa
<LoadInst
>(V
))
848 // The inttoptr case works because isNonEscapingLocalObject considers all
849 // means of converting or equating a pointer to an int (ptrtoint, ptr store
850 // which could be followed by an integer load, ptr<->int compare) as
851 // escaping, and objects located at well-known addresses via platform-specific
852 // means cannot be considered non-escaping local objects.
853 if (isa
<IntToPtrInst
>(V
))
856 // Same for inttoptr constant expressions.
857 if (auto *CE
= dyn_cast
<ConstantExpr
>(V
))
858 if (CE
->getOpcode() == Instruction::IntToPtr
)
864 bool llvm::isNotVisibleOnUnwind(const Value
*Object
,
865 bool &RequiresNoCaptureBeforeUnwind
) {
866 RequiresNoCaptureBeforeUnwind
= false;
868 // Alloca goes out of scope on unwind.
869 if (isa
<AllocaInst
>(Object
))
872 // Byval goes out of scope on unwind.
873 if (auto *A
= dyn_cast
<Argument
>(Object
))
874 return A
->hasByValAttr() || A
->hasAttribute(Attribute::DeadOnUnwind
);
876 // A noalias return is not accessible from any other code. If the pointer
877 // does not escape prior to the unwind, then the caller cannot access the
879 if (isNoAliasCall(Object
)) {
880 RequiresNoCaptureBeforeUnwind
= true;
887 // We don't consider globals as writable: While the physical memory is writable,
888 // we may not have provenance to perform the write.
889 bool llvm::isWritableObject(const Value
*Object
,
890 bool &ExplicitlyDereferenceableOnly
) {
891 ExplicitlyDereferenceableOnly
= false;
893 // TODO: Alloca might not be writable after its lifetime ends.
894 // See https://github.com/llvm/llvm-project/issues/51838.
895 if (isa
<AllocaInst
>(Object
))
898 if (auto *A
= dyn_cast
<Argument
>(Object
)) {
899 // Also require noalias, otherwise writability at function entry cannot be
900 // generalized to writability at other program points, even if the pointer
902 if (A
->hasAttribute(Attribute::Writable
) && A
->hasNoAliasAttr()) {
903 ExplicitlyDereferenceableOnly
= true;
907 return A
->hasByValAttr();
910 // TODO: Noalias shouldn't imply writability, this should check for an
911 // allocator function instead.
912 return isNoAliasCall(Object
);