Path: blob/main/contrib/llvm-project/llvm/lib/Analysis/BasicAliasAnalysis.cpp
35233 views
//===- BasicAliasAnalysis.cpp - Stateless Alias Analysis Impl -------------===//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 defines the primary stateless implementation of the9// Alias Analysis interface that implements identities (two different10// globals cannot alias, etc), but does no stateful analysis.11//12//===----------------------------------------------------------------------===//1314#include "llvm/Analysis/BasicAliasAnalysis.h"15#include "llvm/ADT/APInt.h"16#include "llvm/ADT/ScopeExit.h"17#include "llvm/ADT/SmallPtrSet.h"18#include "llvm/ADT/SmallVector.h"19#include "llvm/ADT/Statistic.h"20#include "llvm/Analysis/AliasAnalysis.h"21#include "llvm/Analysis/AssumptionCache.h"22#include "llvm/Analysis/CFG.h"23#include "llvm/Analysis/CaptureTracking.h"24#include "llvm/Analysis/MemoryBuiltins.h"25#include "llvm/Analysis/MemoryLocation.h"26#include "llvm/Analysis/TargetLibraryInfo.h"27#include "llvm/Analysis/ValueTracking.h"28#include "llvm/IR/Argument.h"29#include "llvm/IR/Attributes.h"30#include "llvm/IR/Constant.h"31#include "llvm/IR/ConstantRange.h"32#include "llvm/IR/Constants.h"33#include "llvm/IR/DataLayout.h"34#include "llvm/IR/DerivedTypes.h"35#include "llvm/IR/Dominators.h"36#include "llvm/IR/Function.h"37#include "llvm/IR/GetElementPtrTypeIterator.h"38#include "llvm/IR/GlobalAlias.h"39#include "llvm/IR/GlobalVariable.h"40#include "llvm/IR/InstrTypes.h"41#include "llvm/IR/Instruction.h"42#include "llvm/IR/Instructions.h"43#include "llvm/IR/IntrinsicInst.h"44#include "llvm/IR/Intrinsics.h"45#include "llvm/IR/Operator.h"46#include "llvm/IR/PatternMatch.h"47#include "llvm/IR/Type.h"48#include "llvm/IR/User.h"49#include "llvm/IR/Value.h"50#include "llvm/InitializePasses.h"51#include "llvm/Pass.h"52#include "llvm/Support/Casting.h"53#include "llvm/Support/CommandLine.h"54#include "llvm/Support/Compiler.h"55#include "llvm/Support/KnownBits.h"56#include "llvm/Support/SaveAndRestore.h"57#include <cassert>58#include <cstdint>59#include <cstdlib>60#include <optional>61#include <utility>6263#define DEBUG_TYPE "basicaa"6465using namespace llvm;6667/// Enable analysis of recursive PHI nodes.68static cl::opt<bool> EnableRecPhiAnalysis("basic-aa-recphi", cl::Hidden,69cl::init(true));7071static cl::opt<bool> EnableSeparateStorageAnalysis("basic-aa-separate-storage",72cl::Hidden, cl::init(true));7374/// SearchLimitReached / SearchTimes shows how often the limit of75/// to decompose GEPs is reached. It will affect the precision76/// of basic alias analysis.77STATISTIC(SearchLimitReached, "Number of times the limit to "78"decompose GEPs is reached");79STATISTIC(SearchTimes, "Number of times a GEP is decomposed");8081// The max limit of the search depth in DecomposeGEPExpression() and82// getUnderlyingObject().83static const unsigned MaxLookupSearchDepth = 6;8485bool BasicAAResult::invalidate(Function &Fn, const PreservedAnalyses &PA,86FunctionAnalysisManager::Invalidator &Inv) {87// We don't care if this analysis itself is preserved, it has no state. But88// we need to check that the analyses it depends on have been. Note that we89// may be created without handles to some analyses and in that case don't90// depend on them.91if (Inv.invalidate<AssumptionAnalysis>(Fn, PA) ||92(DT_ && Inv.invalidate<DominatorTreeAnalysis>(Fn, PA)))93return true;9495// Otherwise this analysis result remains valid.96return false;97}9899//===----------------------------------------------------------------------===//100// Useful predicates101//===----------------------------------------------------------------------===//102103/// Returns the size of the object specified by V or UnknownSize if unknown.104static std::optional<TypeSize> getObjectSize(const Value *V,105const DataLayout &DL,106const TargetLibraryInfo &TLI,107bool NullIsValidLoc,108bool RoundToAlign = false) {109uint64_t Size;110ObjectSizeOpts Opts;111Opts.RoundToAlign = RoundToAlign;112Opts.NullIsUnknownSize = NullIsValidLoc;113if (getObjectSize(V, Size, DL, &TLI, Opts))114return TypeSize::getFixed(Size);115return std::nullopt;116}117118/// Returns true if we can prove that the object specified by V is smaller than119/// Size.120static bool isObjectSmallerThan(const Value *V, TypeSize Size,121const DataLayout &DL,122const TargetLibraryInfo &TLI,123bool NullIsValidLoc) {124// Note that the meanings of the "object" are slightly different in the125// following contexts:126// c1: llvm::getObjectSize()127// c2: llvm.objectsize() intrinsic128// c3: isObjectSmallerThan()129// c1 and c2 share the same meaning; however, the meaning of "object" in c3130// refers to the "entire object".131//132// Consider this example:133// char *p = (char*)malloc(100)134// char *q = p+80;135//136// In the context of c1 and c2, the "object" pointed by q refers to the137// stretch of memory of q[0:19]. So, getObjectSize(q) should return 20.138//139// However, in the context of c3, the "object" refers to the chunk of memory140// being allocated. So, the "object" has 100 bytes, and q points to the middle141// the "object". In case q is passed to isObjectSmallerThan() as the 1st142// parameter, before the llvm::getObjectSize() is called to get the size of143// entire object, we should:144// - either rewind the pointer q to the base-address of the object in145// question (in this case rewind to p), or146// - just give up. It is up to caller to make sure the pointer is pointing147// to the base address the object.148//149// We go for 2nd option for simplicity.150if (!isIdentifiedObject(V))151return false;152153// This function needs to use the aligned object size because we allow154// reads a bit past the end given sufficient alignment.155std::optional<TypeSize> ObjectSize = getObjectSize(V, DL, TLI, NullIsValidLoc,156/*RoundToAlign*/ true);157158return ObjectSize && TypeSize::isKnownLT(*ObjectSize, Size);159}160161/// Return the minimal extent from \p V to the end of the underlying object,162/// assuming the result is used in an aliasing query. E.g., we do use the query163/// location size and the fact that null pointers cannot alias here.164static TypeSize getMinimalExtentFrom(const Value &V,165const LocationSize &LocSize,166const DataLayout &DL,167bool NullIsValidLoc) {168// If we have dereferenceability information we know a lower bound for the169// extent as accesses for a lower offset would be valid. We need to exclude170// the "or null" part if null is a valid pointer. We can ignore frees, as an171// access after free would be undefined behavior.172bool CanBeNull, CanBeFreed;173uint64_t DerefBytes =174V.getPointerDereferenceableBytes(DL, CanBeNull, CanBeFreed);175DerefBytes = (CanBeNull && NullIsValidLoc) ? 0 : DerefBytes;176// If queried with a precise location size, we assume that location size to be177// accessed, thus valid.178if (LocSize.isPrecise())179DerefBytes = std::max(DerefBytes, LocSize.getValue().getKnownMinValue());180return TypeSize::getFixed(DerefBytes);181}182183/// Returns true if we can prove that the object specified by V has size Size.184static bool isObjectSize(const Value *V, TypeSize Size, const DataLayout &DL,185const TargetLibraryInfo &TLI, bool NullIsValidLoc) {186std::optional<TypeSize> ObjectSize =187getObjectSize(V, DL, TLI, NullIsValidLoc);188return ObjectSize && *ObjectSize == Size;189}190191/// Return true if both V1 and V2 are VScale192static bool areBothVScale(const Value *V1, const Value *V2) {193return PatternMatch::match(V1, PatternMatch::m_VScale()) &&194PatternMatch::match(V2, PatternMatch::m_VScale());195}196197//===----------------------------------------------------------------------===//198// CaptureInfo implementations199//===----------------------------------------------------------------------===//200201CaptureInfo::~CaptureInfo() = default;202203bool SimpleCaptureInfo::isNotCapturedBefore(const Value *Object,204const Instruction *I, bool OrAt) {205return isNonEscapingLocalObject(Object, &IsCapturedCache);206}207208static bool isNotInCycle(const Instruction *I, const DominatorTree *DT,209const LoopInfo *LI) {210BasicBlock *BB = const_cast<BasicBlock *>(I->getParent());211SmallVector<BasicBlock *> Succs(successors(BB));212return Succs.empty() ||213!isPotentiallyReachableFromMany(Succs, BB, nullptr, DT, LI);214}215216bool EarliestEscapeInfo::isNotCapturedBefore(const Value *Object,217const Instruction *I, bool OrAt) {218if (!isIdentifiedFunctionLocal(Object))219return false;220221auto Iter = EarliestEscapes.insert({Object, nullptr});222if (Iter.second) {223Instruction *EarliestCapture = FindEarliestCapture(224Object, *const_cast<Function *>(DT.getRoot()->getParent()),225/*ReturnCaptures=*/false, /*StoreCaptures=*/true, DT);226if (EarliestCapture) {227auto Ins = Inst2Obj.insert({EarliestCapture, {}});228Ins.first->second.push_back(Object);229}230Iter.first->second = EarliestCapture;231}232233// No capturing instruction.234if (!Iter.first->second)235return true;236237// No context instruction means any use is capturing.238if (!I)239return false;240241if (I == Iter.first->second) {242if (OrAt)243return false;244return isNotInCycle(I, &DT, LI);245}246247return !isPotentiallyReachable(Iter.first->second, I, nullptr, &DT, LI);248}249250void EarliestEscapeInfo::removeInstruction(Instruction *I) {251auto Iter = Inst2Obj.find(I);252if (Iter != Inst2Obj.end()) {253for (const Value *Obj : Iter->second)254EarliestEscapes.erase(Obj);255Inst2Obj.erase(I);256}257}258259//===----------------------------------------------------------------------===//260// GetElementPtr Instruction Decomposition and Analysis261//===----------------------------------------------------------------------===//262263namespace {264/// Represents zext(sext(trunc(V))).265struct CastedValue {266const Value *V;267unsigned ZExtBits = 0;268unsigned SExtBits = 0;269unsigned TruncBits = 0;270/// Whether trunc(V) is non-negative.271bool IsNonNegative = false;272273explicit CastedValue(const Value *V) : V(V) {}274explicit CastedValue(const Value *V, unsigned ZExtBits, unsigned SExtBits,275unsigned TruncBits, bool IsNonNegative)276: V(V), ZExtBits(ZExtBits), SExtBits(SExtBits), TruncBits(TruncBits),277IsNonNegative(IsNonNegative) {}278279unsigned getBitWidth() const {280return V->getType()->getPrimitiveSizeInBits() - TruncBits + ZExtBits +281SExtBits;282}283284CastedValue withValue(const Value *NewV, bool PreserveNonNeg) const {285return CastedValue(NewV, ZExtBits, SExtBits, TruncBits,286IsNonNegative && PreserveNonNeg);287}288289/// Replace V with zext(NewV)290CastedValue withZExtOfValue(const Value *NewV, bool ZExtNonNegative) const {291unsigned ExtendBy = V->getType()->getPrimitiveSizeInBits() -292NewV->getType()->getPrimitiveSizeInBits();293if (ExtendBy <= TruncBits)294// zext<nneg>(trunc(zext(NewV))) == zext<nneg>(trunc(NewV))295// The nneg can be preserved on the outer zext here.296return CastedValue(NewV, ZExtBits, SExtBits, TruncBits - ExtendBy,297IsNonNegative);298299// zext(sext(zext(NewV))) == zext(zext(zext(NewV)))300ExtendBy -= TruncBits;301// zext<nneg>(zext(NewV)) == zext(NewV)302// zext(zext<nneg>(NewV)) == zext<nneg>(NewV)303// The nneg can be preserved from the inner zext here but must be dropped304// from the outer.305return CastedValue(NewV, ZExtBits + SExtBits + ExtendBy, 0, 0,306ZExtNonNegative);307}308309/// Replace V with sext(NewV)310CastedValue withSExtOfValue(const Value *NewV) const {311unsigned ExtendBy = V->getType()->getPrimitiveSizeInBits() -312NewV->getType()->getPrimitiveSizeInBits();313if (ExtendBy <= TruncBits)314// zext<nneg>(trunc(sext(NewV))) == zext<nneg>(trunc(NewV))315// The nneg can be preserved on the outer zext here316return CastedValue(NewV, ZExtBits, SExtBits, TruncBits - ExtendBy,317IsNonNegative);318319// zext(sext(sext(NewV)))320ExtendBy -= TruncBits;321// zext<nneg>(sext(sext(NewV))) = zext<nneg>(sext(NewV))322// The nneg can be preserved on the outer zext here323return CastedValue(NewV, ZExtBits, SExtBits + ExtendBy, 0, IsNonNegative);324}325326APInt evaluateWith(APInt N) const {327assert(N.getBitWidth() == V->getType()->getPrimitiveSizeInBits() &&328"Incompatible bit width");329if (TruncBits) N = N.trunc(N.getBitWidth() - TruncBits);330if (SExtBits) N = N.sext(N.getBitWidth() + SExtBits);331if (ZExtBits) N = N.zext(N.getBitWidth() + ZExtBits);332return N;333}334335ConstantRange evaluateWith(ConstantRange N) const {336assert(N.getBitWidth() == V->getType()->getPrimitiveSizeInBits() &&337"Incompatible bit width");338if (TruncBits) N = N.truncate(N.getBitWidth() - TruncBits);339if (SExtBits) N = N.signExtend(N.getBitWidth() + SExtBits);340if (ZExtBits) N = N.zeroExtend(N.getBitWidth() + ZExtBits);341return N;342}343344bool canDistributeOver(bool NUW, bool NSW) const {345// zext(x op<nuw> y) == zext(x) op<nuw> zext(y)346// sext(x op<nsw> y) == sext(x) op<nsw> sext(y)347// trunc(x op y) == trunc(x) op trunc(y)348return (!ZExtBits || NUW) && (!SExtBits || NSW);349}350351bool hasSameCastsAs(const CastedValue &Other) const {352if (ZExtBits == Other.ZExtBits && SExtBits == Other.SExtBits &&353TruncBits == Other.TruncBits)354return true;355// If either CastedValue has a nneg zext then the sext/zext bits are356// interchangable for that value.357if (IsNonNegative || Other.IsNonNegative)358return (ZExtBits + SExtBits == Other.ZExtBits + Other.SExtBits &&359TruncBits == Other.TruncBits);360return false;361}362};363364/// Represents zext(sext(trunc(V))) * Scale + Offset.365struct LinearExpression {366CastedValue Val;367APInt Scale;368APInt Offset;369370/// True if all operations in this expression are NSW.371bool IsNSW;372373LinearExpression(const CastedValue &Val, const APInt &Scale,374const APInt &Offset, bool IsNSW)375: Val(Val), Scale(Scale), Offset(Offset), IsNSW(IsNSW) {}376377LinearExpression(const CastedValue &Val) : Val(Val), IsNSW(true) {378unsigned BitWidth = Val.getBitWidth();379Scale = APInt(BitWidth, 1);380Offset = APInt(BitWidth, 0);381}382383LinearExpression mul(const APInt &Other, bool MulIsNSW) const {384// The check for zero offset is necessary, because generally385// (X +nsw Y) *nsw Z does not imply (X *nsw Z) +nsw (Y *nsw Z).386bool NSW = IsNSW && (Other.isOne() || (MulIsNSW && Offset.isZero()));387return LinearExpression(Val, Scale * Other, Offset * Other, NSW);388}389};390}391392/// Analyzes the specified value as a linear expression: "A*V + B", where A and393/// B are constant integers.394static LinearExpression GetLinearExpression(395const CastedValue &Val, const DataLayout &DL, unsigned Depth,396AssumptionCache *AC, DominatorTree *DT) {397// Limit our recursion depth.398if (Depth == 6)399return Val;400401if (const ConstantInt *Const = dyn_cast<ConstantInt>(Val.V))402return LinearExpression(Val, APInt(Val.getBitWidth(), 0),403Val.evaluateWith(Const->getValue()), true);404405if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(Val.V)) {406if (ConstantInt *RHSC = dyn_cast<ConstantInt>(BOp->getOperand(1))) {407APInt RHS = Val.evaluateWith(RHSC->getValue());408// The only non-OBO case we deal with is or, and only limited to the409// case where it is both nuw and nsw.410bool NUW = true, NSW = true;411if (isa<OverflowingBinaryOperator>(BOp)) {412NUW &= BOp->hasNoUnsignedWrap();413NSW &= BOp->hasNoSignedWrap();414}415if (!Val.canDistributeOver(NUW, NSW))416return Val;417418// While we can distribute over trunc, we cannot preserve nowrap flags419// in that case.420if (Val.TruncBits)421NUW = NSW = false;422423LinearExpression E(Val);424switch (BOp->getOpcode()) {425default:426// We don't understand this instruction, so we can't decompose it any427// further.428return Val;429case Instruction::Or:430// X|C == X+C if it is disjoint. Otherwise we can't analyze it.431if (!cast<PossiblyDisjointInst>(BOp)->isDisjoint())432return Val;433434[[fallthrough]];435case Instruction::Add: {436E = GetLinearExpression(Val.withValue(BOp->getOperand(0), false), DL,437Depth + 1, AC, DT);438E.Offset += RHS;439E.IsNSW &= NSW;440break;441}442case Instruction::Sub: {443E = GetLinearExpression(Val.withValue(BOp->getOperand(0), false), DL,444Depth + 1, AC, DT);445E.Offset -= RHS;446E.IsNSW &= NSW;447break;448}449case Instruction::Mul:450E = GetLinearExpression(Val.withValue(BOp->getOperand(0), false), DL,451Depth + 1, AC, DT)452.mul(RHS, NSW);453break;454case Instruction::Shl:455// We're trying to linearize an expression of the kind:456// shl i8 -128, 36457// where the shift count exceeds the bitwidth of the type.458// We can't decompose this further (the expression would return459// a poison value).460if (RHS.getLimitedValue() > Val.getBitWidth())461return Val;462463E = GetLinearExpression(Val.withValue(BOp->getOperand(0), NSW), DL,464Depth + 1, AC, DT);465E.Offset <<= RHS.getLimitedValue();466E.Scale <<= RHS.getLimitedValue();467E.IsNSW &= NSW;468break;469}470return E;471}472}473474if (const auto *ZExt = dyn_cast<ZExtInst>(Val.V))475return GetLinearExpression(476Val.withZExtOfValue(ZExt->getOperand(0), ZExt->hasNonNeg()), DL,477Depth + 1, AC, DT);478479if (isa<SExtInst>(Val.V))480return GetLinearExpression(481Val.withSExtOfValue(cast<CastInst>(Val.V)->getOperand(0)),482DL, Depth + 1, AC, DT);483484return Val;485}486487/// To ensure a pointer offset fits in an integer of size IndexSize488/// (in bits) when that size is smaller than the maximum index size. This is489/// an issue, for example, in particular for 32b pointers with negative indices490/// that rely on two's complement wrap-arounds for precise alias information491/// where the maximum index size is 64b.492static void adjustToIndexSize(APInt &Offset, unsigned IndexSize) {493assert(IndexSize <= Offset.getBitWidth() && "Invalid IndexSize!");494unsigned ShiftBits = Offset.getBitWidth() - IndexSize;495if (ShiftBits != 0) {496Offset <<= ShiftBits;497Offset.ashrInPlace(ShiftBits);498}499}500501namespace {502// A linear transformation of a Value; this class represents503// ZExt(SExt(Trunc(V, TruncBits), SExtBits), ZExtBits) * Scale.504struct VariableGEPIndex {505CastedValue Val;506APInt Scale;507508// Context instruction to use when querying information about this index.509const Instruction *CxtI;510511/// True if all operations in this expression are NSW.512bool IsNSW;513514/// True if the index should be subtracted rather than added. We don't simply515/// negate the Scale, to avoid losing the NSW flag: X - INT_MIN*1 may be516/// non-wrapping, while X + INT_MIN*(-1) wraps.517bool IsNegated;518519bool hasNegatedScaleOf(const VariableGEPIndex &Other) const {520if (IsNegated == Other.IsNegated)521return Scale == -Other.Scale;522return Scale == Other.Scale;523}524525void dump() const {526print(dbgs());527dbgs() << "\n";528}529void print(raw_ostream &OS) const {530OS << "(V=" << Val.V->getName()531<< ", zextbits=" << Val.ZExtBits532<< ", sextbits=" << Val.SExtBits533<< ", truncbits=" << Val.TruncBits534<< ", scale=" << Scale535<< ", nsw=" << IsNSW536<< ", negated=" << IsNegated << ")";537}538};539}540541// Represents the internal structure of a GEP, decomposed into a base pointer,542// constant offsets, and variable scaled indices.543struct BasicAAResult::DecomposedGEP {544// Base pointer of the GEP545const Value *Base;546// Total constant offset from base.547APInt Offset;548// Scaled variable (non-constant) indices.549SmallVector<VariableGEPIndex, 4> VarIndices;550// Are all operations inbounds GEPs or non-indexing operations?551// (std::nullopt iff expression doesn't involve any geps)552std::optional<bool> InBounds;553554void dump() const {555print(dbgs());556dbgs() << "\n";557}558void print(raw_ostream &OS) const {559OS << "(DecomposedGEP Base=" << Base->getName()560<< ", Offset=" << Offset561<< ", VarIndices=[";562for (size_t i = 0; i < VarIndices.size(); i++) {563if (i != 0)564OS << ", ";565VarIndices[i].print(OS);566}567OS << "])";568}569};570571572/// If V is a symbolic pointer expression, decompose it into a base pointer573/// with a constant offset and a number of scaled symbolic offsets.574///575/// The scaled symbolic offsets (represented by pairs of a Value* and a scale576/// in the VarIndices vector) are Value*'s that are known to be scaled by the577/// specified amount, but which may have other unrepresented high bits. As578/// such, the gep cannot necessarily be reconstructed from its decomposed form.579BasicAAResult::DecomposedGEP580BasicAAResult::DecomposeGEPExpression(const Value *V, const DataLayout &DL,581AssumptionCache *AC, DominatorTree *DT) {582// Limit recursion depth to limit compile time in crazy cases.583unsigned MaxLookup = MaxLookupSearchDepth;584SearchTimes++;585const Instruction *CxtI = dyn_cast<Instruction>(V);586587unsigned MaxIndexSize = DL.getMaxIndexSizeInBits();588DecomposedGEP Decomposed;589Decomposed.Offset = APInt(MaxIndexSize, 0);590do {591// See if this is a bitcast or GEP.592const Operator *Op = dyn_cast<Operator>(V);593if (!Op) {594// The only non-operator case we can handle are GlobalAliases.595if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {596if (!GA->isInterposable()) {597V = GA->getAliasee();598continue;599}600}601Decomposed.Base = V;602return Decomposed;603}604605if (Op->getOpcode() == Instruction::BitCast ||606Op->getOpcode() == Instruction::AddrSpaceCast) {607V = Op->getOperand(0);608continue;609}610611const GEPOperator *GEPOp = dyn_cast<GEPOperator>(Op);612if (!GEPOp) {613if (const auto *PHI = dyn_cast<PHINode>(V)) {614// Look through single-arg phi nodes created by LCSSA.615if (PHI->getNumIncomingValues() == 1) {616V = PHI->getIncomingValue(0);617continue;618}619} else if (const auto *Call = dyn_cast<CallBase>(V)) {620// CaptureTracking can know about special capturing properties of some621// intrinsics like launder.invariant.group, that can't be expressed with622// the attributes, but have properties like returning aliasing pointer.623// Because some analysis may assume that nocaptured pointer is not624// returned from some special intrinsic (because function would have to625// be marked with returns attribute), it is crucial to use this function626// because it should be in sync with CaptureTracking. Not using it may627// cause weird miscompilations where 2 aliasing pointers are assumed to628// noalias.629if (auto *RP = getArgumentAliasingToReturnedPointer(Call, false)) {630V = RP;631continue;632}633}634635Decomposed.Base = V;636return Decomposed;637}638639// Track whether we've seen at least one in bounds gep, and if so, whether640// all geps parsed were in bounds.641if (Decomposed.InBounds == std::nullopt)642Decomposed.InBounds = GEPOp->isInBounds();643else if (!GEPOp->isInBounds())644Decomposed.InBounds = false;645646assert(GEPOp->getSourceElementType()->isSized() && "GEP must be sized");647648unsigned AS = GEPOp->getPointerAddressSpace();649// Walk the indices of the GEP, accumulating them into BaseOff/VarIndices.650gep_type_iterator GTI = gep_type_begin(GEPOp);651unsigned IndexSize = DL.getIndexSizeInBits(AS);652// Assume all GEP operands are constants until proven otherwise.653bool GepHasConstantOffset = true;654for (User::const_op_iterator I = GEPOp->op_begin() + 1, E = GEPOp->op_end();655I != E; ++I, ++GTI) {656const Value *Index = *I;657// Compute the (potentially symbolic) offset in bytes for this index.658if (StructType *STy = GTI.getStructTypeOrNull()) {659// For a struct, add the member offset.660unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();661if (FieldNo == 0)662continue;663664Decomposed.Offset += DL.getStructLayout(STy)->getElementOffset(FieldNo);665continue;666}667668// For an array/pointer, add the element offset, explicitly scaled.669if (const ConstantInt *CIdx = dyn_cast<ConstantInt>(Index)) {670if (CIdx->isZero())671continue;672673// Don't attempt to analyze GEPs if the scalable index is not zero.674TypeSize AllocTypeSize = GTI.getSequentialElementStride(DL);675if (AllocTypeSize.isScalable()) {676Decomposed.Base = V;677return Decomposed;678}679680Decomposed.Offset += AllocTypeSize.getFixedValue() *681CIdx->getValue().sextOrTrunc(MaxIndexSize);682continue;683}684685TypeSize AllocTypeSize = GTI.getSequentialElementStride(DL);686if (AllocTypeSize.isScalable()) {687Decomposed.Base = V;688return Decomposed;689}690691GepHasConstantOffset = false;692693// If the integer type is smaller than the index size, it is implicitly694// sign extended or truncated to index size.695unsigned Width = Index->getType()->getIntegerBitWidth();696unsigned SExtBits = IndexSize > Width ? IndexSize - Width : 0;697unsigned TruncBits = IndexSize < Width ? Width - IndexSize : 0;698LinearExpression LE = GetLinearExpression(699CastedValue(Index, 0, SExtBits, TruncBits, false), DL, 0, AC, DT);700701// Scale by the type size.702unsigned TypeSize = AllocTypeSize.getFixedValue();703LE = LE.mul(APInt(IndexSize, TypeSize), GEPOp->isInBounds());704Decomposed.Offset += LE.Offset.sext(MaxIndexSize);705APInt Scale = LE.Scale.sext(MaxIndexSize);706707// If we already had an occurrence of this index variable, merge this708// scale into it. For example, we want to handle:709// A[x][x] -> x*16 + x*4 -> x*20710// This also ensures that 'x' only appears in the index list once.711for (unsigned i = 0, e = Decomposed.VarIndices.size(); i != e; ++i) {712if ((Decomposed.VarIndices[i].Val.V == LE.Val.V ||713areBothVScale(Decomposed.VarIndices[i].Val.V, LE.Val.V)) &&714Decomposed.VarIndices[i].Val.hasSameCastsAs(LE.Val)) {715Scale += Decomposed.VarIndices[i].Scale;716LE.IsNSW = false; // We cannot guarantee nsw for the merge.717Decomposed.VarIndices.erase(Decomposed.VarIndices.begin() + i);718break;719}720}721722// Make sure that we have a scale that makes sense for this target's723// index size.724adjustToIndexSize(Scale, IndexSize);725726if (!!Scale) {727VariableGEPIndex Entry = {LE.Val, Scale, CxtI, LE.IsNSW,728/* IsNegated */ false};729Decomposed.VarIndices.push_back(Entry);730}731}732733// Take care of wrap-arounds734if (GepHasConstantOffset)735adjustToIndexSize(Decomposed.Offset, IndexSize);736737// Analyze the base pointer next.738V = GEPOp->getOperand(0);739} while (--MaxLookup);740741// If the chain of expressions is too deep, just return early.742Decomposed.Base = V;743SearchLimitReached++;744return Decomposed;745}746747ModRefInfo BasicAAResult::getModRefInfoMask(const MemoryLocation &Loc,748AAQueryInfo &AAQI,749bool IgnoreLocals) {750assert(Visited.empty() && "Visited must be cleared after use!");751auto _ = make_scope_exit([&] { Visited.clear(); });752753unsigned MaxLookup = 8;754SmallVector<const Value *, 16> Worklist;755Worklist.push_back(Loc.Ptr);756ModRefInfo Result = ModRefInfo::NoModRef;757758do {759const Value *V = getUnderlyingObject(Worklist.pop_back_val());760if (!Visited.insert(V).second)761continue;762763// Ignore allocas if we were instructed to do so.764if (IgnoreLocals && isa<AllocaInst>(V))765continue;766767// If the location points to memory that is known to be invariant for768// the life of the underlying SSA value, then we can exclude Mod from769// the set of valid memory effects.770//771// An argument that is marked readonly and noalias is known to be772// invariant while that function is executing.773if (const Argument *Arg = dyn_cast<Argument>(V)) {774if (Arg->hasNoAliasAttr() && Arg->onlyReadsMemory()) {775Result |= ModRefInfo::Ref;776continue;777}778}779780// A global constant can't be mutated.781if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {782// Note: this doesn't require GV to be "ODR" because it isn't legal for a783// global to be marked constant in some modules and non-constant in784// others. GV may even be a declaration, not a definition.785if (!GV->isConstant())786return ModRefInfo::ModRef;787continue;788}789790// If both select values point to local memory, then so does the select.791if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {792Worklist.push_back(SI->getTrueValue());793Worklist.push_back(SI->getFalseValue());794continue;795}796797// If all values incoming to a phi node point to local memory, then so does798// the phi.799if (const PHINode *PN = dyn_cast<PHINode>(V)) {800// Don't bother inspecting phi nodes with many operands.801if (PN->getNumIncomingValues() > MaxLookup)802return ModRefInfo::ModRef;803append_range(Worklist, PN->incoming_values());804continue;805}806807// Otherwise be conservative.808return ModRefInfo::ModRef;809} while (!Worklist.empty() && --MaxLookup);810811// If we hit the maximum number of instructions to examine, be conservative.812if (!Worklist.empty())813return ModRefInfo::ModRef;814815return Result;816}817818static bool isIntrinsicCall(const CallBase *Call, Intrinsic::ID IID) {819const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Call);820return II && II->getIntrinsicID() == IID;821}822823/// Returns the behavior when calling the given call site.824MemoryEffects BasicAAResult::getMemoryEffects(const CallBase *Call,825AAQueryInfo &AAQI) {826MemoryEffects Min = Call->getAttributes().getMemoryEffects();827828if (const Function *F = dyn_cast<Function>(Call->getCalledOperand())) {829MemoryEffects FuncME = AAQI.AAR.getMemoryEffects(F);830// Operand bundles on the call may also read or write memory, in addition831// to the behavior of the called function.832if (Call->hasReadingOperandBundles())833FuncME |= MemoryEffects::readOnly();834if (Call->hasClobberingOperandBundles())835FuncME |= MemoryEffects::writeOnly();836Min &= FuncME;837}838839return Min;840}841842/// Returns the behavior when calling the given function. For use when the call843/// site is not known.844MemoryEffects BasicAAResult::getMemoryEffects(const Function *F) {845switch (F->getIntrinsicID()) {846case Intrinsic::experimental_guard:847case Intrinsic::experimental_deoptimize:848// These intrinsics can read arbitrary memory, and additionally modref849// inaccessible memory to model control dependence.850return MemoryEffects::readOnly() |851MemoryEffects::inaccessibleMemOnly(ModRefInfo::ModRef);852}853854return F->getMemoryEffects();855}856857ModRefInfo BasicAAResult::getArgModRefInfo(const CallBase *Call,858unsigned ArgIdx) {859if (Call->paramHasAttr(ArgIdx, Attribute::WriteOnly))860return ModRefInfo::Mod;861862if (Call->paramHasAttr(ArgIdx, Attribute::ReadOnly))863return ModRefInfo::Ref;864865if (Call->paramHasAttr(ArgIdx, Attribute::ReadNone))866return ModRefInfo::NoModRef;867868return ModRefInfo::ModRef;869}870871#ifndef NDEBUG872static const Function *getParent(const Value *V) {873if (const Instruction *inst = dyn_cast<Instruction>(V)) {874if (!inst->getParent())875return nullptr;876return inst->getParent()->getParent();877}878879if (const Argument *arg = dyn_cast<Argument>(V))880return arg->getParent();881882return nullptr;883}884885static bool notDifferentParent(const Value *O1, const Value *O2) {886887const Function *F1 = getParent(O1);888const Function *F2 = getParent(O2);889890return !F1 || !F2 || F1 == F2;891}892#endif893894AliasResult BasicAAResult::alias(const MemoryLocation &LocA,895const MemoryLocation &LocB, AAQueryInfo &AAQI,896const Instruction *CtxI) {897assert(notDifferentParent(LocA.Ptr, LocB.Ptr) &&898"BasicAliasAnalysis doesn't support interprocedural queries.");899return aliasCheck(LocA.Ptr, LocA.Size, LocB.Ptr, LocB.Size, AAQI, CtxI);900}901902/// Checks to see if the specified callsite can clobber the specified memory903/// object.904///905/// Since we only look at local properties of this function, we really can't906/// say much about this query. We do, however, use simple "address taken"907/// analysis on local objects.908ModRefInfo BasicAAResult::getModRefInfo(const CallBase *Call,909const MemoryLocation &Loc,910AAQueryInfo &AAQI) {911assert(notDifferentParent(Call, Loc.Ptr) &&912"AliasAnalysis query involving multiple functions!");913914const Value *Object = getUnderlyingObject(Loc.Ptr);915916// Calls marked 'tail' cannot read or write allocas from the current frame917// because the current frame might be destroyed by the time they run. However,918// a tail call may use an alloca with byval. Calling with byval copies the919// contents of the alloca into argument registers or stack slots, so there is920// no lifetime issue.921if (isa<AllocaInst>(Object))922if (const CallInst *CI = dyn_cast<CallInst>(Call))923if (CI->isTailCall() &&924!CI->getAttributes().hasAttrSomewhere(Attribute::ByVal))925return ModRefInfo::NoModRef;926927// Stack restore is able to modify unescaped dynamic allocas. Assume it may928// modify them even though the alloca is not escaped.929if (auto *AI = dyn_cast<AllocaInst>(Object))930if (!AI->isStaticAlloca() && isIntrinsicCall(Call, Intrinsic::stackrestore))931return ModRefInfo::Mod;932933// A call can access a locally allocated object either because it is passed as934// an argument to the call, or because it has escaped prior to the call.935//936// Make sure the object has not escaped here, and then check that none of the937// call arguments alias the object below.938if (!isa<Constant>(Object) && Call != Object &&939AAQI.CI->isNotCapturedBefore(Object, Call, /*OrAt*/ false)) {940941// Optimistically assume that call doesn't touch Object and check this942// assumption in the following loop.943ModRefInfo Result = ModRefInfo::NoModRef;944945unsigned OperandNo = 0;946for (auto CI = Call->data_operands_begin(), CE = Call->data_operands_end();947CI != CE; ++CI, ++OperandNo) {948if (!(*CI)->getType()->isPointerTy())949continue;950951// Call doesn't access memory through this operand, so we don't care952// if it aliases with Object.953if (Call->doesNotAccessMemory(OperandNo))954continue;955956// If this is a no-capture pointer argument, see if we can tell that it957// is impossible to alias the pointer we're checking.958AliasResult AR =959AAQI.AAR.alias(MemoryLocation::getBeforeOrAfter(*CI),960MemoryLocation::getBeforeOrAfter(Object), AAQI);961// Operand doesn't alias 'Object', continue looking for other aliases962if (AR == AliasResult::NoAlias)963continue;964// Operand aliases 'Object', but call doesn't modify it. Strengthen965// initial assumption and keep looking in case if there are more aliases.966if (Call->onlyReadsMemory(OperandNo)) {967Result |= ModRefInfo::Ref;968continue;969}970// Operand aliases 'Object' but call only writes into it.971if (Call->onlyWritesMemory(OperandNo)) {972Result |= ModRefInfo::Mod;973continue;974}975// This operand aliases 'Object' and call reads and writes into it.976// Setting ModRef will not yield an early return below, MustAlias is not977// used further.978Result = ModRefInfo::ModRef;979break;980}981982// Early return if we improved mod ref information983if (!isModAndRefSet(Result))984return Result;985}986987// If the call is malloc/calloc like, we can assume that it doesn't988// modify any IR visible value. This is only valid because we assume these989// routines do not read values visible in the IR. TODO: Consider special990// casing realloc and strdup routines which access only their arguments as991// well. Or alternatively, replace all of this with inaccessiblememonly once992// that's implemented fully.993if (isMallocOrCallocLikeFn(Call, &TLI)) {994// Be conservative if the accessed pointer may alias the allocation -995// fallback to the generic handling below.996if (AAQI.AAR.alias(MemoryLocation::getBeforeOrAfter(Call), Loc, AAQI) ==997AliasResult::NoAlias)998return ModRefInfo::NoModRef;999}10001001// Like assumes, invariant.start intrinsics were also marked as arbitrarily1002// writing so that proper control dependencies are maintained but they never1003// mod any particular memory location visible to the IR.1004// *Unlike* assumes (which are now modeled as NoModRef), invariant.start1005// intrinsic is now modeled as reading memory. This prevents hoisting the1006// invariant.start intrinsic over stores. Consider:1007// *ptr = 40;1008// *ptr = 50;1009// invariant_start(ptr)1010// int val = *ptr;1011// print(val);1012//1013// This cannot be transformed to:1014//1015// *ptr = 40;1016// invariant_start(ptr)1017// *ptr = 50;1018// int val = *ptr;1019// print(val);1020//1021// The transformation will cause the second store to be ignored (based on1022// rules of invariant.start) and print 40, while the first program always1023// prints 50.1024if (isIntrinsicCall(Call, Intrinsic::invariant_start))1025return ModRefInfo::Ref;10261027// Be conservative.1028return ModRefInfo::ModRef;1029}10301031ModRefInfo BasicAAResult::getModRefInfo(const CallBase *Call1,1032const CallBase *Call2,1033AAQueryInfo &AAQI) {1034// Guard intrinsics are marked as arbitrarily writing so that proper control1035// dependencies are maintained but they never mods any particular memory1036// location.1037//1038// *Unlike* assumes, guard intrinsics are modeled as reading memory since the1039// heap state at the point the guard is issued needs to be consistent in case1040// the guard invokes the "deopt" continuation.10411042// NB! This function is *not* commutative, so we special case two1043// possibilities for guard intrinsics.10441045if (isIntrinsicCall(Call1, Intrinsic::experimental_guard))1046return isModSet(getMemoryEffects(Call2, AAQI).getModRef())1047? ModRefInfo::Ref1048: ModRefInfo::NoModRef;10491050if (isIntrinsicCall(Call2, Intrinsic::experimental_guard))1051return isModSet(getMemoryEffects(Call1, AAQI).getModRef())1052? ModRefInfo::Mod1053: ModRefInfo::NoModRef;10541055// Be conservative.1056return ModRefInfo::ModRef;1057}10581059/// Return true if we know V to the base address of the corresponding memory1060/// object. This implies that any address less than V must be out of bounds1061/// for the underlying object. Note that just being isIdentifiedObject() is1062/// not enough - For example, a negative offset from a noalias argument or call1063/// can be inbounds w.r.t the actual underlying object.1064static bool isBaseOfObject(const Value *V) {1065// TODO: We can handle other cases here1066// 1) For GC languages, arguments to functions are often required to be1067// base pointers.1068// 2) Result of allocation routines are often base pointers. Leverage TLI.1069return (isa<AllocaInst>(V) || isa<GlobalVariable>(V));1070}10711072/// Provides a bunch of ad-hoc rules to disambiguate a GEP instruction against1073/// another pointer.1074///1075/// We know that V1 is a GEP, but we don't know anything about V2.1076/// UnderlyingV1 is getUnderlyingObject(GEP1), UnderlyingV2 is the same for1077/// V2.1078AliasResult BasicAAResult::aliasGEP(1079const GEPOperator *GEP1, LocationSize V1Size,1080const Value *V2, LocationSize V2Size,1081const Value *UnderlyingV1, const Value *UnderlyingV2, AAQueryInfo &AAQI) {1082if (!V1Size.hasValue() && !V2Size.hasValue()) {1083// TODO: This limitation exists for compile-time reasons. Relax it if we1084// can avoid exponential pathological cases.1085if (!isa<GEPOperator>(V2))1086return AliasResult::MayAlias;10871088// If both accesses have unknown size, we can only check whether the base1089// objects don't alias.1090AliasResult BaseAlias =1091AAQI.AAR.alias(MemoryLocation::getBeforeOrAfter(UnderlyingV1),1092MemoryLocation::getBeforeOrAfter(UnderlyingV2), AAQI);1093return BaseAlias == AliasResult::NoAlias ? AliasResult::NoAlias1094: AliasResult::MayAlias;1095}10961097DominatorTree *DT = getDT(AAQI);1098DecomposedGEP DecompGEP1 = DecomposeGEPExpression(GEP1, DL, &AC, DT);1099DecomposedGEP DecompGEP2 = DecomposeGEPExpression(V2, DL, &AC, DT);11001101// Bail if we were not able to decompose anything.1102if (DecompGEP1.Base == GEP1 && DecompGEP2.Base == V2)1103return AliasResult::MayAlias;11041105// Subtract the GEP2 pointer from the GEP1 pointer to find out their1106// symbolic difference.1107subtractDecomposedGEPs(DecompGEP1, DecompGEP2, AAQI);11081109// If an inbounds GEP would have to start from an out of bounds address1110// for the two to alias, then we can assume noalias.1111// TODO: Remove !isScalable() once BasicAA fully support scalable location1112// size1113if (*DecompGEP1.InBounds && DecompGEP1.VarIndices.empty() &&1114V2Size.hasValue() && !V2Size.isScalable() &&1115DecompGEP1.Offset.sge(V2Size.getValue()) &&1116isBaseOfObject(DecompGEP2.Base))1117return AliasResult::NoAlias;11181119if (isa<GEPOperator>(V2)) {1120// Symmetric case to above.1121if (*DecompGEP2.InBounds && DecompGEP1.VarIndices.empty() &&1122V1Size.hasValue() && !V1Size.isScalable() &&1123DecompGEP1.Offset.sle(-V1Size.getValue()) &&1124isBaseOfObject(DecompGEP1.Base))1125return AliasResult::NoAlias;1126}11271128// For GEPs with identical offsets, we can preserve the size and AAInfo1129// when performing the alias check on the underlying objects.1130if (DecompGEP1.Offset == 0 && DecompGEP1.VarIndices.empty())1131return AAQI.AAR.alias(MemoryLocation(DecompGEP1.Base, V1Size),1132MemoryLocation(DecompGEP2.Base, V2Size), AAQI);11331134// Do the base pointers alias?1135AliasResult BaseAlias =1136AAQI.AAR.alias(MemoryLocation::getBeforeOrAfter(DecompGEP1.Base),1137MemoryLocation::getBeforeOrAfter(DecompGEP2.Base), AAQI);11381139// If we get a No or May, then return it immediately, no amount of analysis1140// will improve this situation.1141if (BaseAlias != AliasResult::MustAlias) {1142assert(BaseAlias == AliasResult::NoAlias ||1143BaseAlias == AliasResult::MayAlias);1144return BaseAlias;1145}11461147// If there is a constant difference between the pointers, but the difference1148// is less than the size of the associated memory object, then we know1149// that the objects are partially overlapping. If the difference is1150// greater, we know they do not overlap.1151if (DecompGEP1.VarIndices.empty()) {1152APInt &Off = DecompGEP1.Offset;11531154// Initialize for Off >= 0 (V2 <= GEP1) case.1155const Value *LeftPtr = V2;1156const Value *RightPtr = GEP1;1157LocationSize VLeftSize = V2Size;1158LocationSize VRightSize = V1Size;1159const bool Swapped = Off.isNegative();11601161if (Swapped) {1162// Swap if we have the situation where:1163// + +1164// | BaseOffset |1165// ---------------->|1166// |-->V1Size |-------> V2Size1167// GEP1 V21168std::swap(LeftPtr, RightPtr);1169std::swap(VLeftSize, VRightSize);1170Off = -Off;1171}11721173if (!VLeftSize.hasValue())1174return AliasResult::MayAlias;11751176const TypeSize LSize = VLeftSize.getValue();1177if (!LSize.isScalable()) {1178if (Off.ult(LSize)) {1179// Conservatively drop processing if a phi was visited and/or offset is1180// too big.1181AliasResult AR = AliasResult::PartialAlias;1182if (VRightSize.hasValue() && !VRightSize.isScalable() &&1183Off.ule(INT32_MAX) && (Off + VRightSize.getValue()).ule(LSize)) {1184// Memory referenced by right pointer is nested. Save the offset in1185// cache. Note that originally offset estimated as GEP1-V2, but1186// AliasResult contains the shift that represents GEP1+Offset=V2.1187AR.setOffset(-Off.getSExtValue());1188AR.swap(Swapped);1189}1190return AR;1191}1192return AliasResult::NoAlias;1193} else {1194// We can use the getVScaleRange to prove that Off >= (CR.upper * LSize).1195ConstantRange CR = getVScaleRange(&F, Off.getBitWidth());1196bool Overflow;1197APInt UpperRange = CR.getUnsignedMax().umul_ov(1198APInt(Off.getBitWidth(), LSize.getKnownMinValue()), Overflow);1199if (!Overflow && Off.uge(UpperRange))1200return AliasResult::NoAlias;1201}1202}12031204// VScale Alias Analysis - Given one scalable offset between accesses and a1205// scalable typesize, we can divide each side by vscale, treating both values1206// as a constant. We prove that Offset/vscale >= TypeSize/vscale.1207if (DecompGEP1.VarIndices.size() == 1 &&1208DecompGEP1.VarIndices[0].Val.TruncBits == 0 &&1209DecompGEP1.Offset.isZero() &&1210PatternMatch::match(DecompGEP1.VarIndices[0].Val.V,1211PatternMatch::m_VScale())) {1212const VariableGEPIndex &ScalableVar = DecompGEP1.VarIndices[0];1213APInt Scale =1214ScalableVar.IsNegated ? -ScalableVar.Scale : ScalableVar.Scale;1215LocationSize VLeftSize = Scale.isNegative() ? V1Size : V2Size;12161217// Check if the offset is known to not overflow, if it does then attempt to1218// prove it with the known values of vscale_range.1219bool Overflows = !DecompGEP1.VarIndices[0].IsNSW;1220if (Overflows) {1221ConstantRange CR = getVScaleRange(&F, Scale.getBitWidth());1222(void)CR.getSignedMax().smul_ov(Scale, Overflows);1223}12241225if (!Overflows) {1226// Note that we do not check that the typesize is scalable, as vscale >= 11227// so noalias still holds so long as the dependency distance is at least1228// as big as the typesize.1229if (VLeftSize.hasValue() &&1230Scale.abs().uge(VLeftSize.getValue().getKnownMinValue()))1231return AliasResult::NoAlias;1232}1233}12341235// Bail on analysing scalable LocationSize1236if (V1Size.isScalable() || V2Size.isScalable())1237return AliasResult::MayAlias;12381239// We need to know both acess sizes for all the following heuristics.1240if (!V1Size.hasValue() || !V2Size.hasValue())1241return AliasResult::MayAlias;12421243APInt GCD;1244ConstantRange OffsetRange = ConstantRange(DecompGEP1.Offset);1245for (unsigned i = 0, e = DecompGEP1.VarIndices.size(); i != e; ++i) {1246const VariableGEPIndex &Index = DecompGEP1.VarIndices[i];1247const APInt &Scale = Index.Scale;1248APInt ScaleForGCD = Scale;1249if (!Index.IsNSW)1250ScaleForGCD =1251APInt::getOneBitSet(Scale.getBitWidth(), Scale.countr_zero());12521253if (i == 0)1254GCD = ScaleForGCD.abs();1255else1256GCD = APIntOps::GreatestCommonDivisor(GCD, ScaleForGCD.abs());12571258ConstantRange CR = computeConstantRange(Index.Val.V, /* ForSigned */ false,1259true, &AC, Index.CxtI);1260KnownBits Known =1261computeKnownBits(Index.Val.V, DL, 0, &AC, Index.CxtI, DT);1262CR = CR.intersectWith(1263ConstantRange::fromKnownBits(Known, /* Signed */ true),1264ConstantRange::Signed);1265CR = Index.Val.evaluateWith(CR).sextOrTrunc(OffsetRange.getBitWidth());12661267assert(OffsetRange.getBitWidth() == Scale.getBitWidth() &&1268"Bit widths are normalized to MaxIndexSize");1269if (Index.IsNSW)1270CR = CR.smul_sat(ConstantRange(Scale));1271else1272CR = CR.smul_fast(ConstantRange(Scale));12731274if (Index.IsNegated)1275OffsetRange = OffsetRange.sub(CR);1276else1277OffsetRange = OffsetRange.add(CR);1278}12791280// We now have accesses at two offsets from the same base:1281// 1. (...)*GCD + DecompGEP1.Offset with size V1Size1282// 2. 0 with size V2Size1283// Using arithmetic modulo GCD, the accesses are at1284// [ModOffset..ModOffset+V1Size) and [0..V2Size). If the first access fits1285// into the range [V2Size..GCD), then we know they cannot overlap.1286APInt ModOffset = DecompGEP1.Offset.srem(GCD);1287if (ModOffset.isNegative())1288ModOffset += GCD; // We want mod, not rem.1289if (ModOffset.uge(V2Size.getValue()) &&1290(GCD - ModOffset).uge(V1Size.getValue()))1291return AliasResult::NoAlias;12921293// Compute ranges of potentially accessed bytes for both accesses. If the1294// interseciton is empty, there can be no overlap.1295unsigned BW = OffsetRange.getBitWidth();1296ConstantRange Range1 = OffsetRange.add(1297ConstantRange(APInt(BW, 0), APInt(BW, V1Size.getValue())));1298ConstantRange Range2 =1299ConstantRange(APInt(BW, 0), APInt(BW, V2Size.getValue()));1300if (Range1.intersectWith(Range2).isEmptySet())1301return AliasResult::NoAlias;13021303// Try to determine the range of values for VarIndex such that1304// VarIndex <= -MinAbsVarIndex || MinAbsVarIndex <= VarIndex.1305std::optional<APInt> MinAbsVarIndex;1306if (DecompGEP1.VarIndices.size() == 1) {1307// VarIndex = Scale*V.1308const VariableGEPIndex &Var = DecompGEP1.VarIndices[0];1309if (Var.Val.TruncBits == 0 &&1310isKnownNonZero(Var.Val.V, SimplifyQuery(DL, DT, &AC, Var.CxtI))) {1311// Check if abs(V*Scale) >= abs(Scale) holds in the presence of1312// potentially wrapping math.1313auto MultiplyByScaleNoWrap = [](const VariableGEPIndex &Var) {1314if (Var.IsNSW)1315return true;13161317int ValOrigBW = Var.Val.V->getType()->getPrimitiveSizeInBits();1318// If Scale is small enough so that abs(V*Scale) >= abs(Scale) holds.1319// The max value of abs(V) is 2^ValOrigBW - 1. Multiplying with a1320// constant smaller than 2^(bitwidth(Val) - ValOrigBW) won't wrap.1321int MaxScaleValueBW = Var.Val.getBitWidth() - ValOrigBW;1322if (MaxScaleValueBW <= 0)1323return false;1324return Var.Scale.ule(1325APInt::getMaxValue(MaxScaleValueBW).zext(Var.Scale.getBitWidth()));1326};1327// Refine MinAbsVarIndex, if abs(Scale*V) >= abs(Scale) holds in the1328// presence of potentially wrapping math.1329if (MultiplyByScaleNoWrap(Var)) {1330// If V != 0 then abs(VarIndex) >= abs(Scale).1331MinAbsVarIndex = Var.Scale.abs();1332}1333}1334} else if (DecompGEP1.VarIndices.size() == 2) {1335// VarIndex = Scale*V0 + (-Scale)*V1.1336// If V0 != V1 then abs(VarIndex) >= abs(Scale).1337// Check that MayBeCrossIteration is false, to avoid reasoning about1338// inequality of values across loop iterations.1339const VariableGEPIndex &Var0 = DecompGEP1.VarIndices[0];1340const VariableGEPIndex &Var1 = DecompGEP1.VarIndices[1];1341if (Var0.hasNegatedScaleOf(Var1) && Var0.Val.TruncBits == 0 &&1342Var0.Val.hasSameCastsAs(Var1.Val) && !AAQI.MayBeCrossIteration &&1343isKnownNonEqual(Var0.Val.V, Var1.Val.V, DL, &AC, /* CxtI */ nullptr,1344DT))1345MinAbsVarIndex = Var0.Scale.abs();1346}13471348if (MinAbsVarIndex) {1349// The constant offset will have added at least +/-MinAbsVarIndex to it.1350APInt OffsetLo = DecompGEP1.Offset - *MinAbsVarIndex;1351APInt OffsetHi = DecompGEP1.Offset + *MinAbsVarIndex;1352// We know that Offset <= OffsetLo || Offset >= OffsetHi1353if (OffsetLo.isNegative() && (-OffsetLo).uge(V1Size.getValue()) &&1354OffsetHi.isNonNegative() && OffsetHi.uge(V2Size.getValue()))1355return AliasResult::NoAlias;1356}13571358if (constantOffsetHeuristic(DecompGEP1, V1Size, V2Size, &AC, DT, AAQI))1359return AliasResult::NoAlias;13601361// Statically, we can see that the base objects are the same, but the1362// pointers have dynamic offsets which we can't resolve. And none of our1363// little tricks above worked.1364return AliasResult::MayAlias;1365}13661367static AliasResult MergeAliasResults(AliasResult A, AliasResult B) {1368// If the results agree, take it.1369if (A == B)1370return A;1371// A mix of PartialAlias and MustAlias is PartialAlias.1372if ((A == AliasResult::PartialAlias && B == AliasResult::MustAlias) ||1373(B == AliasResult::PartialAlias && A == AliasResult::MustAlias))1374return AliasResult::PartialAlias;1375// Otherwise, we don't know anything.1376return AliasResult::MayAlias;1377}13781379/// Provides a bunch of ad-hoc rules to disambiguate a Select instruction1380/// against another.1381AliasResult1382BasicAAResult::aliasSelect(const SelectInst *SI, LocationSize SISize,1383const Value *V2, LocationSize V2Size,1384AAQueryInfo &AAQI) {1385// If the values are Selects with the same condition, we can do a more precise1386// check: just check for aliases between the values on corresponding arms.1387if (const SelectInst *SI2 = dyn_cast<SelectInst>(V2))1388if (isValueEqualInPotentialCycles(SI->getCondition(), SI2->getCondition(),1389AAQI)) {1390AliasResult Alias =1391AAQI.AAR.alias(MemoryLocation(SI->getTrueValue(), SISize),1392MemoryLocation(SI2->getTrueValue(), V2Size), AAQI);1393if (Alias == AliasResult::MayAlias)1394return AliasResult::MayAlias;1395AliasResult ThisAlias =1396AAQI.AAR.alias(MemoryLocation(SI->getFalseValue(), SISize),1397MemoryLocation(SI2->getFalseValue(), V2Size), AAQI);1398return MergeAliasResults(ThisAlias, Alias);1399}14001401// If both arms of the Select node NoAlias or MustAlias V2, then returns1402// NoAlias / MustAlias. Otherwise, returns MayAlias.1403AliasResult Alias = AAQI.AAR.alias(MemoryLocation(SI->getTrueValue(), SISize),1404MemoryLocation(V2, V2Size), AAQI);1405if (Alias == AliasResult::MayAlias)1406return AliasResult::MayAlias;14071408AliasResult ThisAlias =1409AAQI.AAR.alias(MemoryLocation(SI->getFalseValue(), SISize),1410MemoryLocation(V2, V2Size), AAQI);1411return MergeAliasResults(ThisAlias, Alias);1412}14131414/// Provide a bunch of ad-hoc rules to disambiguate a PHI instruction against1415/// another.1416AliasResult BasicAAResult::aliasPHI(const PHINode *PN, LocationSize PNSize,1417const Value *V2, LocationSize V2Size,1418AAQueryInfo &AAQI) {1419if (!PN->getNumIncomingValues())1420return AliasResult::NoAlias;1421// If the values are PHIs in the same block, we can do a more precise1422// as well as efficient check: just check for aliases between the values1423// on corresponding edges.1424if (const PHINode *PN2 = dyn_cast<PHINode>(V2))1425if (PN2->getParent() == PN->getParent()) {1426std::optional<AliasResult> Alias;1427for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {1428AliasResult ThisAlias = AAQI.AAR.alias(1429MemoryLocation(PN->getIncomingValue(i), PNSize),1430MemoryLocation(1431PN2->getIncomingValueForBlock(PN->getIncomingBlock(i)), V2Size),1432AAQI);1433if (Alias)1434*Alias = MergeAliasResults(*Alias, ThisAlias);1435else1436Alias = ThisAlias;1437if (*Alias == AliasResult::MayAlias)1438break;1439}1440return *Alias;1441}14421443SmallVector<Value *, 4> V1Srcs;1444// If a phi operand recurses back to the phi, we can still determine NoAlias1445// if we don't alias the underlying objects of the other phi operands, as we1446// know that the recursive phi needs to be based on them in some way.1447bool isRecursive = false;1448auto CheckForRecPhi = [&](Value *PV) {1449if (!EnableRecPhiAnalysis)1450return false;1451if (getUnderlyingObject(PV) == PN) {1452isRecursive = true;1453return true;1454}1455return false;1456};14571458SmallPtrSet<Value *, 4> UniqueSrc;1459Value *OnePhi = nullptr;1460for (Value *PV1 : PN->incoming_values()) {1461// Skip the phi itself being the incoming value.1462if (PV1 == PN)1463continue;14641465if (isa<PHINode>(PV1)) {1466if (OnePhi && OnePhi != PV1) {1467// To control potential compile time explosion, we choose to be1468// conserviate when we have more than one Phi input. It is important1469// that we handle the single phi case as that lets us handle LCSSA1470// phi nodes and (combined with the recursive phi handling) simple1471// pointer induction variable patterns.1472return AliasResult::MayAlias;1473}1474OnePhi = PV1;1475}14761477if (CheckForRecPhi(PV1))1478continue;14791480if (UniqueSrc.insert(PV1).second)1481V1Srcs.push_back(PV1);1482}14831484if (OnePhi && UniqueSrc.size() > 1)1485// Out of an abundance of caution, allow only the trivial lcssa and1486// recursive phi cases.1487return AliasResult::MayAlias;14881489// If V1Srcs is empty then that means that the phi has no underlying non-phi1490// value. This should only be possible in blocks unreachable from the entry1491// block, but return MayAlias just in case.1492if (V1Srcs.empty())1493return AliasResult::MayAlias;14941495// If this PHI node is recursive, indicate that the pointer may be moved1496// across iterations. We can only prove NoAlias if different underlying1497// objects are involved.1498if (isRecursive)1499PNSize = LocationSize::beforeOrAfterPointer();15001501// In the recursive alias queries below, we may compare values from two1502// different loop iterations.1503SaveAndRestore SavedMayBeCrossIteration(AAQI.MayBeCrossIteration, true);15041505AliasResult Alias = AAQI.AAR.alias(MemoryLocation(V1Srcs[0], PNSize),1506MemoryLocation(V2, V2Size), AAQI);15071508// Early exit if the check of the first PHI source against V2 is MayAlias.1509// Other results are not possible.1510if (Alias == AliasResult::MayAlias)1511return AliasResult::MayAlias;1512// With recursive phis we cannot guarantee that MustAlias/PartialAlias will1513// remain valid to all elements and needs to conservatively return MayAlias.1514if (isRecursive && Alias != AliasResult::NoAlias)1515return AliasResult::MayAlias;15161517// If all sources of the PHI node NoAlias or MustAlias V2, then returns1518// NoAlias / MustAlias. Otherwise, returns MayAlias.1519for (unsigned i = 1, e = V1Srcs.size(); i != e; ++i) {1520Value *V = V1Srcs[i];15211522AliasResult ThisAlias = AAQI.AAR.alias(1523MemoryLocation(V, PNSize), MemoryLocation(V2, V2Size), AAQI);1524Alias = MergeAliasResults(ThisAlias, Alias);1525if (Alias == AliasResult::MayAlias)1526break;1527}15281529return Alias;1530}15311532/// Provides a bunch of ad-hoc rules to disambiguate in common cases, such as1533/// array references.1534AliasResult BasicAAResult::aliasCheck(const Value *V1, LocationSize V1Size,1535const Value *V2, LocationSize V2Size,1536AAQueryInfo &AAQI,1537const Instruction *CtxI) {1538// If either of the memory references is empty, it doesn't matter what the1539// pointer values are.1540if (V1Size.isZero() || V2Size.isZero())1541return AliasResult::NoAlias;15421543// Strip off any casts if they exist.1544V1 = V1->stripPointerCastsForAliasAnalysis();1545V2 = V2->stripPointerCastsForAliasAnalysis();15461547// If V1 or V2 is undef, the result is NoAlias because we can always pick a1548// value for undef that aliases nothing in the program.1549if (isa<UndefValue>(V1) || isa<UndefValue>(V2))1550return AliasResult::NoAlias;15511552// Are we checking for alias of the same value?1553// Because we look 'through' phi nodes, we could look at "Value" pointers from1554// different iterations. We must therefore make sure that this is not the1555// case. The function isValueEqualInPotentialCycles ensures that this cannot1556// happen by looking at the visited phi nodes and making sure they cannot1557// reach the value.1558if (isValueEqualInPotentialCycles(V1, V2, AAQI))1559return AliasResult::MustAlias;15601561if (!V1->getType()->isPointerTy() || !V2->getType()->isPointerTy())1562return AliasResult::NoAlias; // Scalars cannot alias each other15631564// Figure out what objects these things are pointing to if we can.1565const Value *O1 = getUnderlyingObject(V1, MaxLookupSearchDepth);1566const Value *O2 = getUnderlyingObject(V2, MaxLookupSearchDepth);15671568// Null values in the default address space don't point to any object, so they1569// don't alias any other pointer.1570if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O1))1571if (!NullPointerIsDefined(&F, CPN->getType()->getAddressSpace()))1572return AliasResult::NoAlias;1573if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O2))1574if (!NullPointerIsDefined(&F, CPN->getType()->getAddressSpace()))1575return AliasResult::NoAlias;15761577if (O1 != O2) {1578// If V1/V2 point to two different objects, we know that we have no alias.1579if (isIdentifiedObject(O1) && isIdentifiedObject(O2))1580return AliasResult::NoAlias;15811582// Function arguments can't alias with things that are known to be1583// unambigously identified at the function level.1584if ((isa<Argument>(O1) && isIdentifiedFunctionLocal(O2)) ||1585(isa<Argument>(O2) && isIdentifiedFunctionLocal(O1)))1586return AliasResult::NoAlias;15871588// If one pointer is the result of a call/invoke or load and the other is a1589// non-escaping local object within the same function, then we know the1590// object couldn't escape to a point where the call could return it.1591//1592// Note that if the pointers are in different functions, there are a1593// variety of complications. A call with a nocapture argument may still1594// temporary store the nocapture argument's value in a temporary memory1595// location if that memory location doesn't escape. Or it may pass a1596// nocapture value to other functions as long as they don't capture it.1597if (isEscapeSource(O1) && AAQI.CI->isNotCapturedBefore(1598O2, dyn_cast<Instruction>(O1), /*OrAt*/ true))1599return AliasResult::NoAlias;1600if (isEscapeSource(O2) && AAQI.CI->isNotCapturedBefore(1601O1, dyn_cast<Instruction>(O2), /*OrAt*/ true))1602return AliasResult::NoAlias;1603}16041605// If the size of one access is larger than the entire object on the other1606// side, then we know such behavior is undefined and can assume no alias.1607bool NullIsValidLocation = NullPointerIsDefined(&F);1608if ((isObjectSmallerThan(1609O2, getMinimalExtentFrom(*V1, V1Size, DL, NullIsValidLocation), DL,1610TLI, NullIsValidLocation)) ||1611(isObjectSmallerThan(1612O1, getMinimalExtentFrom(*V2, V2Size, DL, NullIsValidLocation), DL,1613TLI, NullIsValidLocation)))1614return AliasResult::NoAlias;16151616if (EnableSeparateStorageAnalysis) {1617for (AssumptionCache::ResultElem &Elem : AC.assumptionsFor(O1)) {1618if (!Elem || Elem.Index == AssumptionCache::ExprResultIdx)1619continue;16201621AssumeInst *Assume = cast<AssumeInst>(Elem);1622OperandBundleUse OBU = Assume->getOperandBundleAt(Elem.Index);1623if (OBU.getTagName() == "separate_storage") {1624assert(OBU.Inputs.size() == 2);1625const Value *Hint1 = OBU.Inputs[0].get();1626const Value *Hint2 = OBU.Inputs[1].get();1627// This is often a no-op; instcombine rewrites this for us. No-op1628// getUnderlyingObject calls are fast, though.1629const Value *HintO1 = getUnderlyingObject(Hint1);1630const Value *HintO2 = getUnderlyingObject(Hint2);16311632DominatorTree *DT = getDT(AAQI);1633auto ValidAssumeForPtrContext = [&](const Value *Ptr) {1634if (const Instruction *PtrI = dyn_cast<Instruction>(Ptr)) {1635return isValidAssumeForContext(Assume, PtrI, DT,1636/* AllowEphemerals */ true);1637}1638if (const Argument *PtrA = dyn_cast<Argument>(Ptr)) {1639const Instruction *FirstI =1640&*PtrA->getParent()->getEntryBlock().begin();1641return isValidAssumeForContext(Assume, FirstI, DT,1642/* AllowEphemerals */ true);1643}1644return false;1645};16461647if ((O1 == HintO1 && O2 == HintO2) || (O1 == HintO2 && O2 == HintO1)) {1648// Note that we go back to V1 and V2 for the1649// ValidAssumeForPtrContext checks; they're dominated by O1 and O2,1650// so strictly more assumptions are valid for them.1651if ((CtxI && isValidAssumeForContext(Assume, CtxI, DT,1652/* AllowEphemerals */ true)) ||1653ValidAssumeForPtrContext(V1) || ValidAssumeForPtrContext(V2)) {1654return AliasResult::NoAlias;1655}1656}1657}1658}1659}16601661// If one the accesses may be before the accessed pointer, canonicalize this1662// by using unknown after-pointer sizes for both accesses. This is1663// equivalent, because regardless of which pointer is lower, one of them1664// will always came after the other, as long as the underlying objects aren't1665// disjoint. We do this so that the rest of BasicAA does not have to deal1666// with accesses before the base pointer, and to improve cache utilization by1667// merging equivalent states.1668if (V1Size.mayBeBeforePointer() || V2Size.mayBeBeforePointer()) {1669V1Size = LocationSize::afterPointer();1670V2Size = LocationSize::afterPointer();1671}16721673// FIXME: If this depth limit is hit, then we may cache sub-optimal results1674// for recursive queries. For this reason, this limit is chosen to be large1675// enough to be very rarely hit, while still being small enough to avoid1676// stack overflows.1677if (AAQI.Depth >= 512)1678return AliasResult::MayAlias;16791680// Check the cache before climbing up use-def chains. This also terminates1681// otherwise infinitely recursive queries. Include MayBeCrossIteration in the1682// cache key, because some cases where MayBeCrossIteration==false returns1683// MustAlias or NoAlias may become MayAlias under MayBeCrossIteration==true.1684AAQueryInfo::LocPair Locs({V1, V1Size, AAQI.MayBeCrossIteration},1685{V2, V2Size, AAQI.MayBeCrossIteration});1686const bool Swapped = V1 > V2;1687if (Swapped)1688std::swap(Locs.first, Locs.second);1689const auto &Pair = AAQI.AliasCache.try_emplace(1690Locs, AAQueryInfo::CacheEntry{AliasResult::NoAlias, 0});1691if (!Pair.second) {1692auto &Entry = Pair.first->second;1693if (!Entry.isDefinitive()) {1694// Remember that we used an assumption. This may either be a direct use1695// of an assumption, or a use of an entry that may itself be based on an1696// assumption.1697++AAQI.NumAssumptionUses;1698if (Entry.isAssumption())1699++Entry.NumAssumptionUses;1700}1701// Cache contains sorted {V1,V2} pairs but we should return original order.1702auto Result = Entry.Result;1703Result.swap(Swapped);1704return Result;1705}17061707int OrigNumAssumptionUses = AAQI.NumAssumptionUses;1708unsigned OrigNumAssumptionBasedResults = AAQI.AssumptionBasedResults.size();1709AliasResult Result =1710aliasCheckRecursive(V1, V1Size, V2, V2Size, AAQI, O1, O2);17111712auto It = AAQI.AliasCache.find(Locs);1713assert(It != AAQI.AliasCache.end() && "Must be in cache");1714auto &Entry = It->second;17151716// Check whether a NoAlias assumption has been used, but disproven.1717bool AssumptionDisproven =1718Entry.NumAssumptionUses > 0 && Result != AliasResult::NoAlias;1719if (AssumptionDisproven)1720Result = AliasResult::MayAlias;17211722// This is a definitive result now, when considered as a root query.1723AAQI.NumAssumptionUses -= Entry.NumAssumptionUses;1724Entry.Result = Result;1725// Cache contains sorted {V1,V2} pairs.1726Entry.Result.swap(Swapped);17271728// If the assumption has been disproven, remove any results that may have1729// been based on this assumption. Do this after the Entry updates above to1730// avoid iterator invalidation.1731if (AssumptionDisproven)1732while (AAQI.AssumptionBasedResults.size() > OrigNumAssumptionBasedResults)1733AAQI.AliasCache.erase(AAQI.AssumptionBasedResults.pop_back_val());17341735// The result may still be based on assumptions higher up in the chain.1736// Remember it, so it can be purged from the cache later.1737if (OrigNumAssumptionUses != AAQI.NumAssumptionUses &&1738Result != AliasResult::MayAlias) {1739AAQI.AssumptionBasedResults.push_back(Locs);1740Entry.NumAssumptionUses = AAQueryInfo::CacheEntry::AssumptionBased;1741} else {1742Entry.NumAssumptionUses = AAQueryInfo::CacheEntry::Definitive;1743}17441745// Depth is incremented before this function is called, so Depth==1 indicates1746// a root query.1747if (AAQI.Depth == 1) {1748// Any remaining assumption based results must be based on proven1749// assumptions, so convert them to definitive results.1750for (const auto &Loc : AAQI.AssumptionBasedResults) {1751auto It = AAQI.AliasCache.find(Loc);1752if (It != AAQI.AliasCache.end())1753It->second.NumAssumptionUses = AAQueryInfo::CacheEntry::Definitive;1754}1755AAQI.AssumptionBasedResults.clear();1756AAQI.NumAssumptionUses = 0;1757}1758return Result;1759}17601761AliasResult BasicAAResult::aliasCheckRecursive(1762const Value *V1, LocationSize V1Size,1763const Value *V2, LocationSize V2Size,1764AAQueryInfo &AAQI, const Value *O1, const Value *O2) {1765if (const GEPOperator *GV1 = dyn_cast<GEPOperator>(V1)) {1766AliasResult Result = aliasGEP(GV1, V1Size, V2, V2Size, O1, O2, AAQI);1767if (Result != AliasResult::MayAlias)1768return Result;1769} else if (const GEPOperator *GV2 = dyn_cast<GEPOperator>(V2)) {1770AliasResult Result = aliasGEP(GV2, V2Size, V1, V1Size, O2, O1, AAQI);1771Result.swap();1772if (Result != AliasResult::MayAlias)1773return Result;1774}17751776if (const PHINode *PN = dyn_cast<PHINode>(V1)) {1777AliasResult Result = aliasPHI(PN, V1Size, V2, V2Size, AAQI);1778if (Result != AliasResult::MayAlias)1779return Result;1780} else if (const PHINode *PN = dyn_cast<PHINode>(V2)) {1781AliasResult Result = aliasPHI(PN, V2Size, V1, V1Size, AAQI);1782Result.swap();1783if (Result != AliasResult::MayAlias)1784return Result;1785}17861787if (const SelectInst *S1 = dyn_cast<SelectInst>(V1)) {1788AliasResult Result = aliasSelect(S1, V1Size, V2, V2Size, AAQI);1789if (Result != AliasResult::MayAlias)1790return Result;1791} else if (const SelectInst *S2 = dyn_cast<SelectInst>(V2)) {1792AliasResult Result = aliasSelect(S2, V2Size, V1, V1Size, AAQI);1793Result.swap();1794if (Result != AliasResult::MayAlias)1795return Result;1796}17971798// If both pointers are pointing into the same object and one of them1799// accesses the entire object, then the accesses must overlap in some way.1800if (O1 == O2) {1801bool NullIsValidLocation = NullPointerIsDefined(&F);1802if (V1Size.isPrecise() && V2Size.isPrecise() &&1803(isObjectSize(O1, V1Size.getValue(), DL, TLI, NullIsValidLocation) ||1804isObjectSize(O2, V2Size.getValue(), DL, TLI, NullIsValidLocation)))1805return AliasResult::PartialAlias;1806}18071808return AliasResult::MayAlias;1809}18101811/// Check whether two Values can be considered equivalent.1812///1813/// If the values may come from different cycle iterations, this will also1814/// check that the values are not part of cycle. We have to do this because we1815/// are looking through phi nodes, that is we say1816/// noalias(V, phi(VA, VB)) if noalias(V, VA) and noalias(V, VB).1817bool BasicAAResult::isValueEqualInPotentialCycles(const Value *V,1818const Value *V2,1819const AAQueryInfo &AAQI) {1820if (V != V2)1821return false;18221823if (!AAQI.MayBeCrossIteration)1824return true;18251826// Non-instructions and instructions in the entry block cannot be part of1827// a loop.1828const Instruction *Inst = dyn_cast<Instruction>(V);1829if (!Inst || Inst->getParent()->isEntryBlock())1830return true;18311832return isNotInCycle(Inst, getDT(AAQI), /*LI*/ nullptr);1833}18341835/// Computes the symbolic difference between two de-composed GEPs.1836void BasicAAResult::subtractDecomposedGEPs(DecomposedGEP &DestGEP,1837const DecomposedGEP &SrcGEP,1838const AAQueryInfo &AAQI) {1839DestGEP.Offset -= SrcGEP.Offset;1840for (const VariableGEPIndex &Src : SrcGEP.VarIndices) {1841// Find V in Dest. This is N^2, but pointer indices almost never have more1842// than a few variable indexes.1843bool Found = false;1844for (auto I : enumerate(DestGEP.VarIndices)) {1845VariableGEPIndex &Dest = I.value();1846if ((!isValueEqualInPotentialCycles(Dest.Val.V, Src.Val.V, AAQI) &&1847!areBothVScale(Dest.Val.V, Src.Val.V)) ||1848!Dest.Val.hasSameCastsAs(Src.Val))1849continue;18501851// Normalize IsNegated if we're going to lose the NSW flag anyway.1852if (Dest.IsNegated) {1853Dest.Scale = -Dest.Scale;1854Dest.IsNegated = false;1855Dest.IsNSW = false;1856}18571858// If we found it, subtract off Scale V's from the entry in Dest. If it1859// goes to zero, remove the entry.1860if (Dest.Scale != Src.Scale) {1861Dest.Scale -= Src.Scale;1862Dest.IsNSW = false;1863} else {1864DestGEP.VarIndices.erase(DestGEP.VarIndices.begin() + I.index());1865}1866Found = true;1867break;1868}18691870// If we didn't consume this entry, add it to the end of the Dest list.1871if (!Found) {1872VariableGEPIndex Entry = {Src.Val, Src.Scale, Src.CxtI, Src.IsNSW,1873/* IsNegated */ true};1874DestGEP.VarIndices.push_back(Entry);1875}1876}1877}18781879bool BasicAAResult::constantOffsetHeuristic(const DecomposedGEP &GEP,1880LocationSize MaybeV1Size,1881LocationSize MaybeV2Size,1882AssumptionCache *AC,1883DominatorTree *DT,1884const AAQueryInfo &AAQI) {1885if (GEP.VarIndices.size() != 2 || !MaybeV1Size.hasValue() ||1886!MaybeV2Size.hasValue())1887return false;18881889const uint64_t V1Size = MaybeV1Size.getValue();1890const uint64_t V2Size = MaybeV2Size.getValue();18911892const VariableGEPIndex &Var0 = GEP.VarIndices[0], &Var1 = GEP.VarIndices[1];18931894if (Var0.Val.TruncBits != 0 || !Var0.Val.hasSameCastsAs(Var1.Val) ||1895!Var0.hasNegatedScaleOf(Var1) ||1896Var0.Val.V->getType() != Var1.Val.V->getType())1897return false;18981899// We'll strip off the Extensions of Var0 and Var1 and do another round1900// of GetLinearExpression decomposition. In the example above, if Var01901// is zext(%x + 1) we should get V1 == %x and V1Offset == 1.19021903LinearExpression E0 =1904GetLinearExpression(CastedValue(Var0.Val.V), DL, 0, AC, DT);1905LinearExpression E1 =1906GetLinearExpression(CastedValue(Var1.Val.V), DL, 0, AC, DT);1907if (E0.Scale != E1.Scale || !E0.Val.hasSameCastsAs(E1.Val) ||1908!isValueEqualInPotentialCycles(E0.Val.V, E1.Val.V, AAQI))1909return false;19101911// We have a hit - Var0 and Var1 only differ by a constant offset!19121913// If we've been sext'ed then zext'd the maximum difference between Var0 and1914// Var1 is possible to calculate, but we're just interested in the absolute1915// minimum difference between the two. The minimum distance may occur due to1916// wrapping; consider "add i3 %i, 5": if %i == 7 then 7 + 5 mod 8 == 4, and so1917// the minimum distance between %i and %i + 5 is 3.1918APInt MinDiff = E0.Offset - E1.Offset, Wrapped = -MinDiff;1919MinDiff = APIntOps::umin(MinDiff, Wrapped);1920APInt MinDiffBytes =1921MinDiff.zextOrTrunc(Var0.Scale.getBitWidth()) * Var0.Scale.abs();19221923// We can't definitely say whether GEP1 is before or after V2 due to wrapping1924// arithmetic (i.e. for some values of GEP1 and V2 GEP1 < V2, and for other1925// values GEP1 > V2). We'll therefore only declare NoAlias if both V1Size and1926// V2Size can fit in the MinDiffBytes gap.1927return MinDiffBytes.uge(V1Size + GEP.Offset.abs()) &&1928MinDiffBytes.uge(V2Size + GEP.Offset.abs());1929}19301931//===----------------------------------------------------------------------===//1932// BasicAliasAnalysis Pass1933//===----------------------------------------------------------------------===//19341935AnalysisKey BasicAA::Key;19361937BasicAAResult BasicAA::run(Function &F, FunctionAnalysisManager &AM) {1938auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);1939auto &AC = AM.getResult<AssumptionAnalysis>(F);1940auto *DT = &AM.getResult<DominatorTreeAnalysis>(F);1941return BasicAAResult(F.getDataLayout(), F, TLI, AC, DT);1942}19431944BasicAAWrapperPass::BasicAAWrapperPass() : FunctionPass(ID) {1945initializeBasicAAWrapperPassPass(*PassRegistry::getPassRegistry());1946}19471948char BasicAAWrapperPass::ID = 0;19491950void BasicAAWrapperPass::anchor() {}19511952INITIALIZE_PASS_BEGIN(BasicAAWrapperPass, "basic-aa",1953"Basic Alias Analysis (stateless AA impl)", true, true)1954INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)1955INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)1956INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)1957INITIALIZE_PASS_END(BasicAAWrapperPass, "basic-aa",1958"Basic Alias Analysis (stateless AA impl)", true, true)19591960FunctionPass *llvm::createBasicAAWrapperPass() {1961return new BasicAAWrapperPass();1962}19631964bool BasicAAWrapperPass::runOnFunction(Function &F) {1965auto &ACT = getAnalysis<AssumptionCacheTracker>();1966auto &TLIWP = getAnalysis<TargetLibraryInfoWrapperPass>();1967auto &DTWP = getAnalysis<DominatorTreeWrapperPass>();19681969Result.reset(new BasicAAResult(F.getDataLayout(), F,1970TLIWP.getTLI(F), ACT.getAssumptionCache(F),1971&DTWP.getDomTree()));19721973return false;1974}19751976void BasicAAWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {1977AU.setPreservesAll();1978AU.addRequiredTransitive<AssumptionCacheTracker>();1979AU.addRequiredTransitive<DominatorTreeWrapperPass>();1980AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>();1981}198219831984