Path: blob/main/contrib/llvm-project/llvm/lib/Analysis/AliasAnalysis.cpp
35233 views
//==- AliasAnalysis.cpp - Generic Alias Analysis Interface Implementation --==//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This file implements the generic AliasAnalysis interface which is used as the9// common interface used by all clients and implementations of alias analysis.10//11// This file also implements the default version of the AliasAnalysis interface12// that is to be used when no other implementation is specified. This does some13// simple tests that detect obvious cases: two different global pointers cannot14// alias, a global cannot alias a malloc, two different mallocs cannot alias,15// etc.16//17// This alias analysis implementation really isn't very good for anything, but18// it is very fast, and makes a nice clean default implementation. Because it19// handles lots of little corner cases, other, more complex, alias analysis20// implementations may choose to rely on this pass to resolve these simple and21// easy cases.22//23//===----------------------------------------------------------------------===//2425#include "llvm/Analysis/AliasAnalysis.h"26#include "llvm/ADT/Statistic.h"27#include "llvm/Analysis/BasicAliasAnalysis.h"28#include "llvm/Analysis/CaptureTracking.h"29#include "llvm/Analysis/GlobalsModRef.h"30#include "llvm/Analysis/MemoryLocation.h"31#include "llvm/Analysis/ObjCARCAliasAnalysis.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"49#include <algorithm>50#include <cassert>51#include <functional>52#include <iterator>5354#define DEBUG_TYPE "aa"5556using namespace llvm;5758STATISTIC(NumNoAlias, "Number of NoAlias results");59STATISTIC(NumMayAlias, "Number of MayAlias results");60STATISTIC(NumMustAlias, "Number of MustAlias results");6162namespace llvm {63/// Allow disabling BasicAA from the AA results. This is particularly useful64/// when testing to isolate a single AA implementation.65cl::opt<bool> DisableBasicAA("disable-basic-aa", cl::Hidden, cl::init(false));66} // namespace llvm6768#ifndef NDEBUG69/// Print a trace of alias analysis queries and their results.70static cl::opt<bool> EnableAATrace("aa-trace", cl::Hidden, cl::init(false));71#else72static const bool EnableAATrace = false;73#endif7475AAResults::AAResults(const TargetLibraryInfo &TLI) : TLI(TLI) {}7677AAResults::AAResults(AAResults &&Arg)78: TLI(Arg.TLI), AAs(std::move(Arg.AAs)), AADeps(std::move(Arg.AADeps)) {}7980AAResults::~AAResults() {}8182bool AAResults::invalidate(Function &F, const PreservedAnalyses &PA,83FunctionAnalysisManager::Invalidator &Inv) {84// AAResults preserves the AAManager by default, due to the stateless nature85// of AliasAnalysis. There is no need to check whether it has been preserved86// explicitly. Check if any module dependency was invalidated and caused the87// AAManager to be invalidated. Invalidate ourselves in that case.88auto PAC = PA.getChecker<AAManager>();89if (!PAC.preservedWhenStateless())90return true;9192// Check if any of the function dependencies were invalidated, and invalidate93// ourselves in that case.94for (AnalysisKey *ID : AADeps)95if (Inv.invalidate(ID, F, PA))96return true;9798// Everything we depend on is still fine, so are we. Nothing to invalidate.99return false;100}101102//===----------------------------------------------------------------------===//103// Default chaining methods104//===----------------------------------------------------------------------===//105106AliasResult AAResults::alias(const MemoryLocation &LocA,107const MemoryLocation &LocB) {108SimpleAAQueryInfo AAQIP(*this);109return alias(LocA, LocB, AAQIP, nullptr);110}111112AliasResult AAResults::alias(const MemoryLocation &LocA,113const MemoryLocation &LocB, AAQueryInfo &AAQI,114const Instruction *CtxI) {115AliasResult Result = AliasResult::MayAlias;116117if (EnableAATrace) {118for (unsigned I = 0; I < AAQI.Depth; ++I)119dbgs() << " ";120dbgs() << "Start " << *LocA.Ptr << " @ " << LocA.Size << ", "121<< *LocB.Ptr << " @ " << LocB.Size << "\n";122}123124AAQI.Depth++;125for (const auto &AA : AAs) {126Result = AA->alias(LocA, LocB, AAQI, CtxI);127if (Result != AliasResult::MayAlias)128break;129}130AAQI.Depth--;131132if (EnableAATrace) {133for (unsigned I = 0; I < AAQI.Depth; ++I)134dbgs() << " ";135dbgs() << "End " << *LocA.Ptr << " @ " << LocA.Size << ", "136<< *LocB.Ptr << " @ " << LocB.Size << " = " << Result << "\n";137}138139if (AAQI.Depth == 0) {140if (Result == AliasResult::NoAlias)141++NumNoAlias;142else if (Result == AliasResult::MustAlias)143++NumMustAlias;144else145++NumMayAlias;146}147return Result;148}149150ModRefInfo AAResults::getModRefInfoMask(const MemoryLocation &Loc,151bool IgnoreLocals) {152SimpleAAQueryInfo AAQIP(*this);153return getModRefInfoMask(Loc, AAQIP, IgnoreLocals);154}155156ModRefInfo AAResults::getModRefInfoMask(const MemoryLocation &Loc,157AAQueryInfo &AAQI, bool IgnoreLocals) {158ModRefInfo Result = ModRefInfo::ModRef;159160for (const auto &AA : AAs) {161Result &= AA->getModRefInfoMask(Loc, AAQI, IgnoreLocals);162163// Early-exit the moment we reach the bottom of the lattice.164if (isNoModRef(Result))165return ModRefInfo::NoModRef;166}167168return Result;169}170171ModRefInfo AAResults::getArgModRefInfo(const CallBase *Call, unsigned ArgIdx) {172ModRefInfo Result = ModRefInfo::ModRef;173174for (const auto &AA : AAs) {175Result &= AA->getArgModRefInfo(Call, ArgIdx);176177// Early-exit the moment we reach the bottom of the lattice.178if (isNoModRef(Result))179return ModRefInfo::NoModRef;180}181182return Result;183}184185ModRefInfo AAResults::getModRefInfo(const Instruction *I,186const CallBase *Call2) {187SimpleAAQueryInfo AAQIP(*this);188return getModRefInfo(I, Call2, AAQIP);189}190191ModRefInfo AAResults::getModRefInfo(const Instruction *I, const CallBase *Call2,192AAQueryInfo &AAQI) {193// We may have two calls.194if (const auto *Call1 = dyn_cast<CallBase>(I)) {195// Check if the two calls modify the same memory.196return getModRefInfo(Call1, Call2, AAQI);197}198// If this is a fence, just return ModRef.199if (I->isFenceLike())200return ModRefInfo::ModRef;201// Otherwise, check if the call modifies or references the202// location this memory access defines. The best we can say203// is that if the call references what this instruction204// defines, it must be clobbered by this location.205const MemoryLocation DefLoc = MemoryLocation::get(I);206ModRefInfo MR = getModRefInfo(Call2, DefLoc, AAQI);207if (isModOrRefSet(MR))208return ModRefInfo::ModRef;209return ModRefInfo::NoModRef;210}211212ModRefInfo AAResults::getModRefInfo(const CallBase *Call,213const MemoryLocation &Loc,214AAQueryInfo &AAQI) {215ModRefInfo Result = ModRefInfo::ModRef;216217for (const auto &AA : AAs) {218Result &= AA->getModRefInfo(Call, Loc, AAQI);219220// Early-exit the moment we reach the bottom of the lattice.221if (isNoModRef(Result))222return ModRefInfo::NoModRef;223}224225// Try to refine the mod-ref info further using other API entry points to the226// aggregate set of AA results.227228// We can completely ignore inaccessible memory here, because MemoryLocations229// can only reference accessible memory.230auto ME = getMemoryEffects(Call, AAQI)231.getWithoutLoc(IRMemLocation::InaccessibleMem);232if (ME.doesNotAccessMemory())233return ModRefInfo::NoModRef;234235ModRefInfo ArgMR = ME.getModRef(IRMemLocation::ArgMem);236ModRefInfo OtherMR = ME.getWithoutLoc(IRMemLocation::ArgMem).getModRef();237if ((ArgMR | OtherMR) != OtherMR) {238// Refine the modref info for argument memory. We only bother to do this239// if ArgMR is not a subset of OtherMR, otherwise this won't have an impact240// on the final result.241ModRefInfo AllArgsMask = ModRefInfo::NoModRef;242for (const auto &I : llvm::enumerate(Call->args())) {243const Value *Arg = I.value();244if (!Arg->getType()->isPointerTy())245continue;246unsigned ArgIdx = I.index();247MemoryLocation ArgLoc = MemoryLocation::getForArgument(Call, ArgIdx, TLI);248AliasResult ArgAlias = alias(ArgLoc, Loc, AAQI, Call);249if (ArgAlias != AliasResult::NoAlias)250AllArgsMask |= getArgModRefInfo(Call, ArgIdx);251}252ArgMR &= AllArgsMask;253}254255Result &= ArgMR | OtherMR;256257// Apply the ModRef mask. This ensures that if Loc is a constant memory258// location, we take into account the fact that the call definitely could not259// modify the memory location.260if (!isNoModRef(Result))261Result &= getModRefInfoMask(Loc);262263return Result;264}265266ModRefInfo AAResults::getModRefInfo(const CallBase *Call1,267const CallBase *Call2, AAQueryInfo &AAQI) {268ModRefInfo Result = ModRefInfo::ModRef;269270for (const auto &AA : AAs) {271Result &= AA->getModRefInfo(Call1, Call2, AAQI);272273// Early-exit the moment we reach the bottom of the lattice.274if (isNoModRef(Result))275return ModRefInfo::NoModRef;276}277278// Try to refine the mod-ref info further using other API entry points to the279// aggregate set of AA results.280281// If Call1 or Call2 are readnone, they don't interact.282auto Call1B = getMemoryEffects(Call1, AAQI);283if (Call1B.doesNotAccessMemory())284return ModRefInfo::NoModRef;285286auto Call2B = getMemoryEffects(Call2, AAQI);287if (Call2B.doesNotAccessMemory())288return ModRefInfo::NoModRef;289290// If they both only read from memory, there is no dependence.291if (Call1B.onlyReadsMemory() && Call2B.onlyReadsMemory())292return ModRefInfo::NoModRef;293294// If Call1 only reads memory, the only dependence on Call2 can be295// from Call1 reading memory written by Call2.296if (Call1B.onlyReadsMemory())297Result &= ModRefInfo::Ref;298else if (Call1B.onlyWritesMemory())299Result &= ModRefInfo::Mod;300301// If Call2 only access memory through arguments, accumulate the mod/ref302// information from Call1's references to the memory referenced by303// Call2's arguments.304if (Call2B.onlyAccessesArgPointees()) {305if (!Call2B.doesAccessArgPointees())306return ModRefInfo::NoModRef;307ModRefInfo R = ModRefInfo::NoModRef;308for (auto I = Call2->arg_begin(), E = Call2->arg_end(); I != E; ++I) {309const Value *Arg = *I;310if (!Arg->getType()->isPointerTy())311continue;312unsigned Call2ArgIdx = std::distance(Call2->arg_begin(), I);313auto Call2ArgLoc =314MemoryLocation::getForArgument(Call2, Call2ArgIdx, TLI);315316// ArgModRefC2 indicates what Call2 might do to Call2ArgLoc, and the317// dependence of Call1 on that location is the inverse:318// - If Call2 modifies location, dependence exists if Call1 reads or319// writes.320// - If Call2 only reads location, dependence exists if Call1 writes.321ModRefInfo ArgModRefC2 = getArgModRefInfo(Call2, Call2ArgIdx);322ModRefInfo ArgMask = ModRefInfo::NoModRef;323if (isModSet(ArgModRefC2))324ArgMask = ModRefInfo::ModRef;325else if (isRefSet(ArgModRefC2))326ArgMask = ModRefInfo::Mod;327328// ModRefC1 indicates what Call1 might do to Call2ArgLoc, and we use329// above ArgMask to update dependence info.330ArgMask &= getModRefInfo(Call1, Call2ArgLoc, AAQI);331332R = (R | ArgMask) & Result;333if (R == Result)334break;335}336337return R;338}339340// If Call1 only accesses memory through arguments, check if Call2 references341// any of the memory referenced by Call1's arguments. If not, return NoModRef.342if (Call1B.onlyAccessesArgPointees()) {343if (!Call1B.doesAccessArgPointees())344return ModRefInfo::NoModRef;345ModRefInfo R = ModRefInfo::NoModRef;346for (auto I = Call1->arg_begin(), E = Call1->arg_end(); I != E; ++I) {347const Value *Arg = *I;348if (!Arg->getType()->isPointerTy())349continue;350unsigned Call1ArgIdx = std::distance(Call1->arg_begin(), I);351auto Call1ArgLoc =352MemoryLocation::getForArgument(Call1, Call1ArgIdx, TLI);353354// ArgModRefC1 indicates what Call1 might do to Call1ArgLoc; if Call1355// might Mod Call1ArgLoc, then we care about either a Mod or a Ref by356// Call2. If Call1 might Ref, then we care only about a Mod by Call2.357ModRefInfo ArgModRefC1 = getArgModRefInfo(Call1, Call1ArgIdx);358ModRefInfo ModRefC2 = getModRefInfo(Call2, Call1ArgLoc, AAQI);359if ((isModSet(ArgModRefC1) && isModOrRefSet(ModRefC2)) ||360(isRefSet(ArgModRefC1) && isModSet(ModRefC2)))361R = (R | ArgModRefC1) & Result;362363if (R == Result)364break;365}366367return R;368}369370return Result;371}372373MemoryEffects AAResults::getMemoryEffects(const CallBase *Call,374AAQueryInfo &AAQI) {375MemoryEffects Result = MemoryEffects::unknown();376377for (const auto &AA : AAs) {378Result &= AA->getMemoryEffects(Call, AAQI);379380// Early-exit the moment we reach the bottom of the lattice.381if (Result.doesNotAccessMemory())382return Result;383}384385return Result;386}387388MemoryEffects AAResults::getMemoryEffects(const CallBase *Call) {389SimpleAAQueryInfo AAQI(*this);390return getMemoryEffects(Call, AAQI);391}392393MemoryEffects AAResults::getMemoryEffects(const Function *F) {394MemoryEffects Result = MemoryEffects::unknown();395396for (const auto &AA : AAs) {397Result &= AA->getMemoryEffects(F);398399// Early-exit the moment we reach the bottom of the lattice.400if (Result.doesNotAccessMemory())401return Result;402}403404return Result;405}406407raw_ostream &llvm::operator<<(raw_ostream &OS, AliasResult AR) {408switch (AR) {409case AliasResult::NoAlias:410OS << "NoAlias";411break;412case AliasResult::MustAlias:413OS << "MustAlias";414break;415case AliasResult::MayAlias:416OS << "MayAlias";417break;418case AliasResult::PartialAlias:419OS << "PartialAlias";420if (AR.hasOffset())421OS << " (off " << AR.getOffset() << ")";422break;423}424return OS;425}426427raw_ostream &llvm::operator<<(raw_ostream &OS, ModRefInfo MR) {428switch (MR) {429case ModRefInfo::NoModRef:430OS << "NoModRef";431break;432case ModRefInfo::Ref:433OS << "Ref";434break;435case ModRefInfo::Mod:436OS << "Mod";437break;438case ModRefInfo::ModRef:439OS << "ModRef";440break;441}442return OS;443}444445raw_ostream &llvm::operator<<(raw_ostream &OS, MemoryEffects ME) {446for (IRMemLocation Loc : MemoryEffects::locations()) {447switch (Loc) {448case IRMemLocation::ArgMem:449OS << "ArgMem: ";450break;451case IRMemLocation::InaccessibleMem:452OS << "InaccessibleMem: ";453break;454case IRMemLocation::Other:455OS << "Other: ";456break;457}458OS << ME.getModRef(Loc) << ", ";459}460return OS;461}462463//===----------------------------------------------------------------------===//464// Helper method implementation465//===----------------------------------------------------------------------===//466467ModRefInfo AAResults::getModRefInfo(const LoadInst *L,468const MemoryLocation &Loc,469AAQueryInfo &AAQI) {470// Be conservative in the face of atomic.471if (isStrongerThan(L->getOrdering(), AtomicOrdering::Unordered))472return ModRefInfo::ModRef;473474// If the load address doesn't alias the given address, it doesn't read475// or write the specified memory.476if (Loc.Ptr) {477AliasResult AR = alias(MemoryLocation::get(L), Loc, AAQI, L);478if (AR == AliasResult::NoAlias)479return ModRefInfo::NoModRef;480}481// Otherwise, a load just reads.482return ModRefInfo::Ref;483}484485ModRefInfo AAResults::getModRefInfo(const StoreInst *S,486const MemoryLocation &Loc,487AAQueryInfo &AAQI) {488// Be conservative in the face of atomic.489if (isStrongerThan(S->getOrdering(), AtomicOrdering::Unordered))490return ModRefInfo::ModRef;491492if (Loc.Ptr) {493AliasResult AR = alias(MemoryLocation::get(S), Loc, AAQI, S);494// If the store address cannot alias the pointer in question, then the495// specified memory cannot be modified by the store.496if (AR == AliasResult::NoAlias)497return ModRefInfo::NoModRef;498499// Examine the ModRef mask. If Mod isn't present, then return NoModRef.500// This ensures that if Loc is a constant memory location, we take into501// account the fact that the store definitely could not modify the memory502// location.503if (!isModSet(getModRefInfoMask(Loc)))504return ModRefInfo::NoModRef;505}506507// Otherwise, a store just writes.508return ModRefInfo::Mod;509}510511ModRefInfo AAResults::getModRefInfo(const FenceInst *S,512const MemoryLocation &Loc,513AAQueryInfo &AAQI) {514// All we know about a fence instruction is what we get from the ModRef515// mask: if Loc is a constant memory location, the fence definitely could516// not modify it.517if (Loc.Ptr)518return getModRefInfoMask(Loc);519return ModRefInfo::ModRef;520}521522ModRefInfo AAResults::getModRefInfo(const VAArgInst *V,523const MemoryLocation &Loc,524AAQueryInfo &AAQI) {525if (Loc.Ptr) {526AliasResult AR = alias(MemoryLocation::get(V), Loc, AAQI, V);527// If the va_arg address cannot alias the pointer in question, then the528// specified memory cannot be accessed by the va_arg.529if (AR == AliasResult::NoAlias)530return ModRefInfo::NoModRef;531532// If the pointer is a pointer to invariant memory, then it could not have533// been modified by this va_arg.534return getModRefInfoMask(Loc, AAQI);535}536537// Otherwise, a va_arg reads and writes.538return ModRefInfo::ModRef;539}540541ModRefInfo AAResults::getModRefInfo(const CatchPadInst *CatchPad,542const MemoryLocation &Loc,543AAQueryInfo &AAQI) {544if (Loc.Ptr) {545// If the pointer is a pointer to invariant memory,546// then it could not have been modified by this catchpad.547return getModRefInfoMask(Loc, AAQI);548}549550// Otherwise, a catchpad reads and writes.551return ModRefInfo::ModRef;552}553554ModRefInfo AAResults::getModRefInfo(const CatchReturnInst *CatchRet,555const MemoryLocation &Loc,556AAQueryInfo &AAQI) {557if (Loc.Ptr) {558// If the pointer is a pointer to invariant memory,559// then it could not have been modified by this catchpad.560return getModRefInfoMask(Loc, AAQI);561}562563// Otherwise, a catchret reads and writes.564return ModRefInfo::ModRef;565}566567ModRefInfo AAResults::getModRefInfo(const AtomicCmpXchgInst *CX,568const MemoryLocation &Loc,569AAQueryInfo &AAQI) {570// Acquire/Release cmpxchg has properties that matter for arbitrary addresses.571if (isStrongerThanMonotonic(CX->getSuccessOrdering()))572return ModRefInfo::ModRef;573574if (Loc.Ptr) {575AliasResult AR = alias(MemoryLocation::get(CX), Loc, AAQI, CX);576// If the cmpxchg address does not alias the location, it does not access577// it.578if (AR == AliasResult::NoAlias)579return ModRefInfo::NoModRef;580}581582return ModRefInfo::ModRef;583}584585ModRefInfo AAResults::getModRefInfo(const AtomicRMWInst *RMW,586const MemoryLocation &Loc,587AAQueryInfo &AAQI) {588// Acquire/Release atomicrmw has properties that matter for arbitrary addresses.589if (isStrongerThanMonotonic(RMW->getOrdering()))590return ModRefInfo::ModRef;591592if (Loc.Ptr) {593AliasResult AR = alias(MemoryLocation::get(RMW), Loc, AAQI, RMW);594// If the atomicrmw address does not alias the location, it does not access595// it.596if (AR == AliasResult::NoAlias)597return ModRefInfo::NoModRef;598}599600return ModRefInfo::ModRef;601}602603ModRefInfo AAResults::getModRefInfo(const Instruction *I,604const std::optional<MemoryLocation> &OptLoc,605AAQueryInfo &AAQIP) {606if (OptLoc == std::nullopt) {607if (const auto *Call = dyn_cast<CallBase>(I))608return getMemoryEffects(Call, AAQIP).getModRef();609}610611const MemoryLocation &Loc = OptLoc.value_or(MemoryLocation());612613switch (I->getOpcode()) {614case Instruction::VAArg:615return getModRefInfo((const VAArgInst *)I, Loc, AAQIP);616case Instruction::Load:617return getModRefInfo((const LoadInst *)I, Loc, AAQIP);618case Instruction::Store:619return getModRefInfo((const StoreInst *)I, Loc, AAQIP);620case Instruction::Fence:621return getModRefInfo((const FenceInst *)I, Loc, AAQIP);622case Instruction::AtomicCmpXchg:623return getModRefInfo((const AtomicCmpXchgInst *)I, Loc, AAQIP);624case Instruction::AtomicRMW:625return getModRefInfo((const AtomicRMWInst *)I, Loc, AAQIP);626case Instruction::Call:627case Instruction::CallBr:628case Instruction::Invoke:629return getModRefInfo((const CallBase *)I, Loc, AAQIP);630case Instruction::CatchPad:631return getModRefInfo((const CatchPadInst *)I, Loc, AAQIP);632case Instruction::CatchRet:633return getModRefInfo((const CatchReturnInst *)I, Loc, AAQIP);634default:635assert(!I->mayReadOrWriteMemory() &&636"Unhandled memory access instruction!");637return ModRefInfo::NoModRef;638}639}640641/// Return information about whether a particular call site modifies642/// or reads the specified memory location \p MemLoc before instruction \p I643/// in a BasicBlock.644/// FIXME: this is really just shoring-up a deficiency in alias analysis.645/// BasicAA isn't willing to spend linear time determining whether an alloca646/// was captured before or after this particular call, while we are. However,647/// with a smarter AA in place, this test is just wasting compile time.648ModRefInfo AAResults::callCapturesBefore(const Instruction *I,649const MemoryLocation &MemLoc,650DominatorTree *DT,651AAQueryInfo &AAQI) {652if (!DT)653return ModRefInfo::ModRef;654655const Value *Object = getUnderlyingObject(MemLoc.Ptr);656if (!isIdentifiedFunctionLocal(Object))657return ModRefInfo::ModRef;658659const auto *Call = dyn_cast<CallBase>(I);660if (!Call || Call == Object)661return ModRefInfo::ModRef;662663if (PointerMayBeCapturedBefore(Object, /* ReturnCaptures */ true,664/* StoreCaptures */ true, I, DT,665/* include Object */ true))666return ModRefInfo::ModRef;667668unsigned ArgNo = 0;669ModRefInfo R = ModRefInfo::NoModRef;670// Set flag only if no May found and all operands processed.671for (auto CI = Call->data_operands_begin(), CE = Call->data_operands_end();672CI != CE; ++CI, ++ArgNo) {673// Only look at the no-capture or byval pointer arguments. If this674// pointer were passed to arguments that were neither of these, then it675// couldn't be no-capture.676if (!(*CI)->getType()->isPointerTy() ||677(!Call->doesNotCapture(ArgNo) && ArgNo < Call->arg_size() &&678!Call->isByValArgument(ArgNo)))679continue;680681AliasResult AR =682alias(MemoryLocation::getBeforeOrAfter(*CI),683MemoryLocation::getBeforeOrAfter(Object), AAQI, Call);684// If this is a no-capture pointer argument, see if we can tell that it685// is impossible to alias the pointer we're checking. If not, we have to686// assume that the call could touch the pointer, even though it doesn't687// escape.688if (AR == AliasResult::NoAlias)689continue;690if (Call->doesNotAccessMemory(ArgNo))691continue;692if (Call->onlyReadsMemory(ArgNo)) {693R = ModRefInfo::Ref;694continue;695}696return ModRefInfo::ModRef;697}698return R;699}700701/// canBasicBlockModify - Return true if it is possible for execution of the702/// specified basic block to modify the location Loc.703///704bool AAResults::canBasicBlockModify(const BasicBlock &BB,705const MemoryLocation &Loc) {706return canInstructionRangeModRef(BB.front(), BB.back(), Loc, ModRefInfo::Mod);707}708709/// canInstructionRangeModRef - Return true if it is possible for the710/// execution of the specified instructions to mod\ref (according to the711/// mode) the location Loc. The instructions to consider are all712/// of the instructions in the range of [I1,I2] INCLUSIVE.713/// I1 and I2 must be in the same basic block.714bool AAResults::canInstructionRangeModRef(const Instruction &I1,715const Instruction &I2,716const MemoryLocation &Loc,717const ModRefInfo Mode) {718assert(I1.getParent() == I2.getParent() &&719"Instructions not in same basic block!");720BasicBlock::const_iterator I = I1.getIterator();721BasicBlock::const_iterator E = I2.getIterator();722++E; // Convert from inclusive to exclusive range.723724for (; I != E; ++I) // Check every instruction in range725if (isModOrRefSet(getModRefInfo(&*I, Loc) & Mode))726return true;727return false;728}729730// Provide a definition for the root virtual destructor.731AAResults::Concept::~Concept() = default;732733// Provide a definition for the static object used to identify passes.734AnalysisKey AAManager::Key;735736ExternalAAWrapperPass::ExternalAAWrapperPass() : ImmutablePass(ID) {737initializeExternalAAWrapperPassPass(*PassRegistry::getPassRegistry());738}739740ExternalAAWrapperPass::ExternalAAWrapperPass(CallbackT CB)741: ImmutablePass(ID), CB(std::move(CB)) {742initializeExternalAAWrapperPassPass(*PassRegistry::getPassRegistry());743}744745char ExternalAAWrapperPass::ID = 0;746747INITIALIZE_PASS(ExternalAAWrapperPass, "external-aa", "External Alias Analysis",748false, true)749750ImmutablePass *751llvm::createExternalAAWrapperPass(ExternalAAWrapperPass::CallbackT Callback) {752return new ExternalAAWrapperPass(std::move(Callback));753}754755AAResultsWrapperPass::AAResultsWrapperPass() : FunctionPass(ID) {756initializeAAResultsWrapperPassPass(*PassRegistry::getPassRegistry());757}758759char AAResultsWrapperPass::ID = 0;760761INITIALIZE_PASS_BEGIN(AAResultsWrapperPass, "aa",762"Function Alias Analysis Results", false, true)763INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass)764INITIALIZE_PASS_DEPENDENCY(ExternalAAWrapperPass)765INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)766INITIALIZE_PASS_DEPENDENCY(SCEVAAWrapperPass)767INITIALIZE_PASS_DEPENDENCY(ScopedNoAliasAAWrapperPass)768INITIALIZE_PASS_DEPENDENCY(TypeBasedAAWrapperPass)769INITIALIZE_PASS_END(AAResultsWrapperPass, "aa",770"Function Alias Analysis Results", false, true)771772/// Run the wrapper pass to rebuild an aggregation over known AA passes.773///774/// This is the legacy pass manager's interface to the new-style AA results775/// aggregation object. Because this is somewhat shoe-horned into the legacy776/// pass manager, we hard code all the specific alias analyses available into777/// it. While the particular set enabled is configured via commandline flags,778/// adding a new alias analysis to LLVM will require adding support for it to779/// this list.780bool AAResultsWrapperPass::runOnFunction(Function &F) {781// NB! This *must* be reset before adding new AA results to the new782// AAResults object because in the legacy pass manager, each instance783// of these will refer to the *same* immutable analyses, registering and784// unregistering themselves with them. We need to carefully tear down the785// previous object first, in this case replacing it with an empty one, before786// registering new results.787AAR.reset(788new AAResults(getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F)));789790// BasicAA is always available for function analyses. Also, we add it first791// so that it can trump TBAA results when it proves MustAlias.792// FIXME: TBAA should have an explicit mode to support this and then we793// should reconsider the ordering here.794if (!DisableBasicAA)795AAR->addAAResult(getAnalysis<BasicAAWrapperPass>().getResult());796797// Populate the results with the currently available AAs.798if (auto *WrapperPass = getAnalysisIfAvailable<ScopedNoAliasAAWrapperPass>())799AAR->addAAResult(WrapperPass->getResult());800if (auto *WrapperPass = getAnalysisIfAvailable<TypeBasedAAWrapperPass>())801AAR->addAAResult(WrapperPass->getResult());802if (auto *WrapperPass = getAnalysisIfAvailable<GlobalsAAWrapperPass>())803AAR->addAAResult(WrapperPass->getResult());804if (auto *WrapperPass = getAnalysisIfAvailable<SCEVAAWrapperPass>())805AAR->addAAResult(WrapperPass->getResult());806807// If available, run an external AA providing callback over the results as808// well.809if (auto *WrapperPass = getAnalysisIfAvailable<ExternalAAWrapperPass>())810if (WrapperPass->CB)811WrapperPass->CB(*this, F, *AAR);812813// Analyses don't mutate the IR, so return false.814return false;815}816817void AAResultsWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {818AU.setPreservesAll();819AU.addRequiredTransitive<BasicAAWrapperPass>();820AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>();821822// We also need to mark all the alias analysis passes we will potentially823// probe in runOnFunction as used here to ensure the legacy pass manager824// preserves them. This hard coding of lists of alias analyses is specific to825// the legacy pass manager.826AU.addUsedIfAvailable<ScopedNoAliasAAWrapperPass>();827AU.addUsedIfAvailable<TypeBasedAAWrapperPass>();828AU.addUsedIfAvailable<GlobalsAAWrapperPass>();829AU.addUsedIfAvailable<SCEVAAWrapperPass>();830AU.addUsedIfAvailable<ExternalAAWrapperPass>();831}832833AAManager::Result AAManager::run(Function &F, FunctionAnalysisManager &AM) {834Result R(AM.getResult<TargetLibraryAnalysis>(F));835for (auto &Getter : ResultGetters)836(*Getter)(F, AM, R);837return R;838}839840bool llvm::isNoAliasCall(const Value *V) {841if (const auto *Call = dyn_cast<CallBase>(V))842return Call->hasRetAttr(Attribute::NoAlias);843return false;844}845846static bool isNoAliasOrByValArgument(const Value *V) {847if (const Argument *A = dyn_cast<Argument>(V))848return A->hasNoAliasAttr() || A->hasByValAttr();849return false;850}851852bool llvm::isIdentifiedObject(const Value *V) {853if (isa<AllocaInst>(V))854return true;855if (isa<GlobalValue>(V) && !isa<GlobalAlias>(V))856return true;857if (isNoAliasCall(V))858return true;859if (isNoAliasOrByValArgument(V))860return true;861return false;862}863864bool llvm::isIdentifiedFunctionLocal(const Value *V) {865return isa<AllocaInst>(V) || isNoAliasCall(V) || isNoAliasOrByValArgument(V);866}867868bool llvm::isEscapeSource(const Value *V) {869if (auto *CB = dyn_cast<CallBase>(V))870return !isIntrinsicReturningPointerAliasingArgumentWithoutCapturing(CB,871true);872873// The load case works because isNonEscapingLocalObject considers all874// stores to be escapes (it passes true for the StoreCaptures argument875// to PointerMayBeCaptured).876if (isa<LoadInst>(V))877return true;878879// The inttoptr case works because isNonEscapingLocalObject considers all880// means of converting or equating a pointer to an int (ptrtoint, ptr store881// which could be followed by an integer load, ptr<->int compare) as882// escaping, and objects located at well-known addresses via platform-specific883// means cannot be considered non-escaping local objects.884if (isa<IntToPtrInst>(V))885return true;886887// Same for inttoptr constant expressions.888if (auto *CE = dyn_cast<ConstantExpr>(V))889if (CE->getOpcode() == Instruction::IntToPtr)890return true;891892return false;893}894895bool llvm::isNotVisibleOnUnwind(const Value *Object,896bool &RequiresNoCaptureBeforeUnwind) {897RequiresNoCaptureBeforeUnwind = false;898899// Alloca goes out of scope on unwind.900if (isa<AllocaInst>(Object))901return true;902903// Byval goes out of scope on unwind.904if (auto *A = dyn_cast<Argument>(Object))905return A->hasByValAttr() || A->hasAttribute(Attribute::DeadOnUnwind);906907// A noalias return is not accessible from any other code. If the pointer908// does not escape prior to the unwind, then the caller cannot access the909// memory either.910if (isNoAliasCall(Object)) {911RequiresNoCaptureBeforeUnwind = true;912return true;913}914915return false;916}917918// We don't consider globals as writable: While the physical memory is writable,919// we may not have provenance to perform the write.920bool llvm::isWritableObject(const Value *Object,921bool &ExplicitlyDereferenceableOnly) {922ExplicitlyDereferenceableOnly = false;923924// TODO: Alloca might not be writable after its lifetime ends.925// See https://github.com/llvm/llvm-project/issues/51838.926if (isa<AllocaInst>(Object))927return true;928929if (auto *A = dyn_cast<Argument>(Object)) {930if (A->hasAttribute(Attribute::Writable)) {931ExplicitlyDereferenceableOnly = true;932return true;933}934935return A->hasByValAttr();936}937938// TODO: Noalias shouldn't imply writability, this should check for an939// allocator function instead.940return isNoAliasCall(Object);941}942943944