10b57cec5SDimitry Andric //===- BasicAliasAnalysis.cpp - Stateless Alias Analysis Impl -------------===// 20b57cec5SDimitry Andric // 30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information. 50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 60b57cec5SDimitry Andric // 70b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 80b57cec5SDimitry Andric // 90b57cec5SDimitry Andric // This file defines the primary stateless implementation of the 100b57cec5SDimitry Andric // Alias Analysis interface that implements identities (two different 110b57cec5SDimitry Andric // globals cannot alias, etc), but does no stateful analysis. 120b57cec5SDimitry Andric // 130b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 140b57cec5SDimitry Andric 150b57cec5SDimitry Andric #include "llvm/Analysis/BasicAliasAnalysis.h" 160b57cec5SDimitry Andric #include "llvm/ADT/APInt.h" 17e8d8bef9SDimitry Andric #include "llvm/ADT/ScopeExit.h" 180b57cec5SDimitry Andric #include "llvm/ADT/SmallPtrSet.h" 190b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h" 200b57cec5SDimitry Andric #include "llvm/ADT/Statistic.h" 210b57cec5SDimitry Andric #include "llvm/Analysis/AliasAnalysis.h" 220b57cec5SDimitry Andric #include "llvm/Analysis/AssumptionCache.h" 230b57cec5SDimitry Andric #include "llvm/Analysis/CFG.h" 240b57cec5SDimitry Andric #include "llvm/Analysis/CaptureTracking.h" 250b57cec5SDimitry Andric #include "llvm/Analysis/MemoryBuiltins.h" 260b57cec5SDimitry Andric #include "llvm/Analysis/MemoryLocation.h" 270b57cec5SDimitry Andric #include "llvm/Analysis/TargetLibraryInfo.h" 280b57cec5SDimitry Andric #include "llvm/Analysis/ValueTracking.h" 290b57cec5SDimitry Andric #include "llvm/IR/Argument.h" 300b57cec5SDimitry Andric #include "llvm/IR/Attributes.h" 310b57cec5SDimitry Andric #include "llvm/IR/Constant.h" 32349cc55cSDimitry Andric #include "llvm/IR/ConstantRange.h" 330b57cec5SDimitry Andric #include "llvm/IR/Constants.h" 340b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h" 350b57cec5SDimitry Andric #include "llvm/IR/DerivedTypes.h" 360b57cec5SDimitry Andric #include "llvm/IR/Dominators.h" 370b57cec5SDimitry Andric #include "llvm/IR/Function.h" 380b57cec5SDimitry Andric #include "llvm/IR/GetElementPtrTypeIterator.h" 390b57cec5SDimitry Andric #include "llvm/IR/GlobalAlias.h" 400b57cec5SDimitry Andric #include "llvm/IR/GlobalVariable.h" 410b57cec5SDimitry Andric #include "llvm/IR/InstrTypes.h" 420b57cec5SDimitry Andric #include "llvm/IR/Instruction.h" 430b57cec5SDimitry Andric #include "llvm/IR/Instructions.h" 440b57cec5SDimitry Andric #include "llvm/IR/IntrinsicInst.h" 450b57cec5SDimitry Andric #include "llvm/IR/Intrinsics.h" 460b57cec5SDimitry Andric #include "llvm/IR/Operator.h" 470b57cec5SDimitry Andric #include "llvm/IR/Type.h" 480b57cec5SDimitry Andric #include "llvm/IR/User.h" 490b57cec5SDimitry Andric #include "llvm/IR/Value.h" 50480093f4SDimitry Andric #include "llvm/InitializePasses.h" 510b57cec5SDimitry Andric #include "llvm/Pass.h" 520b57cec5SDimitry Andric #include "llvm/Support/Casting.h" 530b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h" 540b57cec5SDimitry Andric #include "llvm/Support/Compiler.h" 550b57cec5SDimitry Andric #include "llvm/Support/KnownBits.h" 56bdd1243dSDimitry Andric #include "llvm/Support/SaveAndRestore.h" 570b57cec5SDimitry Andric #include <cassert> 580b57cec5SDimitry Andric #include <cstdint> 590b57cec5SDimitry Andric #include <cstdlib> 60bdd1243dSDimitry Andric #include <optional> 610b57cec5SDimitry Andric #include <utility> 620b57cec5SDimitry Andric 630b57cec5SDimitry Andric #define DEBUG_TYPE "basicaa" 640b57cec5SDimitry Andric 650b57cec5SDimitry Andric using namespace llvm; 660b57cec5SDimitry Andric 670b57cec5SDimitry Andric /// Enable analysis of recursive PHI nodes. 685ffd83dbSDimitry Andric static cl::opt<bool> EnableRecPhiAnalysis("basic-aa-recphi", cl::Hidden, 69e8d8bef9SDimitry Andric cl::init(true)); 700b57cec5SDimitry Andric 71bdd1243dSDimitry Andric static cl::opt<bool> EnableSeparateStorageAnalysis("basic-aa-separate-storage", 72bdd1243dSDimitry Andric cl::Hidden, cl::init(false)); 73bdd1243dSDimitry Andric 740b57cec5SDimitry Andric /// SearchLimitReached / SearchTimes shows how often the limit of 750b57cec5SDimitry Andric /// to decompose GEPs is reached. It will affect the precision 760b57cec5SDimitry Andric /// of basic alias analysis. 770b57cec5SDimitry Andric STATISTIC(SearchLimitReached, "Number of times the limit to " 780b57cec5SDimitry Andric "decompose GEPs is reached"); 790b57cec5SDimitry Andric STATISTIC(SearchTimes, "Number of times a GEP is decomposed"); 800b57cec5SDimitry Andric 810b57cec5SDimitry Andric // The max limit of the search depth in DecomposeGEPExpression() and 82349cc55cSDimitry Andric // getUnderlyingObject(). 830b57cec5SDimitry Andric static const unsigned MaxLookupSearchDepth = 6; 840b57cec5SDimitry Andric 850b57cec5SDimitry Andric bool BasicAAResult::invalidate(Function &Fn, const PreservedAnalyses &PA, 860b57cec5SDimitry Andric FunctionAnalysisManager::Invalidator &Inv) { 870b57cec5SDimitry Andric // We don't care if this analysis itself is preserved, it has no state. But 880b57cec5SDimitry Andric // we need to check that the analyses it depends on have been. Note that we 890b57cec5SDimitry Andric // may be created without handles to some analyses and in that case don't 900b57cec5SDimitry Andric // depend on them. 910b57cec5SDimitry Andric if (Inv.invalidate<AssumptionAnalysis>(Fn, PA) || 92bdd1243dSDimitry Andric (DT && Inv.invalidate<DominatorTreeAnalysis>(Fn, PA))) 930b57cec5SDimitry Andric return true; 940b57cec5SDimitry Andric 950b57cec5SDimitry Andric // Otherwise this analysis result remains valid. 960b57cec5SDimitry Andric return false; 970b57cec5SDimitry Andric } 980b57cec5SDimitry Andric 990b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 1000b57cec5SDimitry Andric // Useful predicates 1010b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 1020b57cec5SDimitry Andric 1030b57cec5SDimitry Andric /// Returns the size of the object specified by V or UnknownSize if unknown. 1040b57cec5SDimitry Andric static uint64_t getObjectSize(const Value *V, const DataLayout &DL, 1050b57cec5SDimitry Andric const TargetLibraryInfo &TLI, 1060b57cec5SDimitry Andric bool NullIsValidLoc, 1070b57cec5SDimitry Andric bool RoundToAlign = false) { 1080b57cec5SDimitry Andric uint64_t Size; 1090b57cec5SDimitry Andric ObjectSizeOpts Opts; 1100b57cec5SDimitry Andric Opts.RoundToAlign = RoundToAlign; 1110b57cec5SDimitry Andric Opts.NullIsUnknownSize = NullIsValidLoc; 1120b57cec5SDimitry Andric if (getObjectSize(V, Size, DL, &TLI, Opts)) 1130b57cec5SDimitry Andric return Size; 1140b57cec5SDimitry Andric return MemoryLocation::UnknownSize; 1150b57cec5SDimitry Andric } 1160b57cec5SDimitry Andric 1170b57cec5SDimitry Andric /// Returns true if we can prove that the object specified by V is smaller than 1180b57cec5SDimitry Andric /// Size. 1190b57cec5SDimitry Andric static bool isObjectSmallerThan(const Value *V, uint64_t Size, 1200b57cec5SDimitry Andric const DataLayout &DL, 1210b57cec5SDimitry Andric const TargetLibraryInfo &TLI, 1220b57cec5SDimitry Andric bool NullIsValidLoc) { 1230b57cec5SDimitry Andric // Note that the meanings of the "object" are slightly different in the 1240b57cec5SDimitry Andric // following contexts: 1250b57cec5SDimitry Andric // c1: llvm::getObjectSize() 1260b57cec5SDimitry Andric // c2: llvm.objectsize() intrinsic 1270b57cec5SDimitry Andric // c3: isObjectSmallerThan() 1280b57cec5SDimitry Andric // c1 and c2 share the same meaning; however, the meaning of "object" in c3 1290b57cec5SDimitry Andric // refers to the "entire object". 1300b57cec5SDimitry Andric // 1310b57cec5SDimitry Andric // Consider this example: 1320b57cec5SDimitry Andric // char *p = (char*)malloc(100) 1330b57cec5SDimitry Andric // char *q = p+80; 1340b57cec5SDimitry Andric // 1350b57cec5SDimitry Andric // In the context of c1 and c2, the "object" pointed by q refers to the 1360b57cec5SDimitry Andric // stretch of memory of q[0:19]. So, getObjectSize(q) should return 20. 1370b57cec5SDimitry Andric // 1380b57cec5SDimitry Andric // However, in the context of c3, the "object" refers to the chunk of memory 1390b57cec5SDimitry Andric // being allocated. So, the "object" has 100 bytes, and q points to the middle 1400b57cec5SDimitry Andric // the "object". In case q is passed to isObjectSmallerThan() as the 1st 1410b57cec5SDimitry Andric // parameter, before the llvm::getObjectSize() is called to get the size of 1420b57cec5SDimitry Andric // entire object, we should: 1430b57cec5SDimitry Andric // - either rewind the pointer q to the base-address of the object in 1440b57cec5SDimitry Andric // question (in this case rewind to p), or 1450b57cec5SDimitry Andric // - just give up. It is up to caller to make sure the pointer is pointing 1460b57cec5SDimitry Andric // to the base address the object. 1470b57cec5SDimitry Andric // 1480b57cec5SDimitry Andric // We go for 2nd option for simplicity. 1490b57cec5SDimitry Andric if (!isIdentifiedObject(V)) 1500b57cec5SDimitry Andric return false; 1510b57cec5SDimitry Andric 1520b57cec5SDimitry Andric // This function needs to use the aligned object size because we allow 1530b57cec5SDimitry Andric // reads a bit past the end given sufficient alignment. 1540b57cec5SDimitry Andric uint64_t ObjectSize = getObjectSize(V, DL, TLI, NullIsValidLoc, 1550b57cec5SDimitry Andric /*RoundToAlign*/ true); 1560b57cec5SDimitry Andric 1570b57cec5SDimitry Andric return ObjectSize != MemoryLocation::UnknownSize && ObjectSize < Size; 1580b57cec5SDimitry Andric } 1590b57cec5SDimitry Andric 1608bcb0991SDimitry Andric /// Return the minimal extent from \p V to the end of the underlying object, 1618bcb0991SDimitry Andric /// assuming the result is used in an aliasing query. E.g., we do use the query 1628bcb0991SDimitry Andric /// location size and the fact that null pointers cannot alias here. 1638bcb0991SDimitry Andric static uint64_t getMinimalExtentFrom(const Value &V, 1648bcb0991SDimitry Andric const LocationSize &LocSize, 1658bcb0991SDimitry Andric const DataLayout &DL, 1668bcb0991SDimitry Andric bool NullIsValidLoc) { 1678bcb0991SDimitry Andric // If we have dereferenceability information we know a lower bound for the 1688bcb0991SDimitry Andric // extent as accesses for a lower offset would be valid. We need to exclude 169349cc55cSDimitry Andric // the "or null" part if null is a valid pointer. We can ignore frees, as an 170349cc55cSDimitry Andric // access after free would be undefined behavior. 171fe6060f1SDimitry Andric bool CanBeNull, CanBeFreed; 172fe6060f1SDimitry Andric uint64_t DerefBytes = 173fe6060f1SDimitry Andric V.getPointerDereferenceableBytes(DL, CanBeNull, CanBeFreed); 1748bcb0991SDimitry Andric DerefBytes = (CanBeNull && NullIsValidLoc) ? 0 : DerefBytes; 1758bcb0991SDimitry Andric // If queried with a precise location size, we assume that location size to be 1768bcb0991SDimitry Andric // accessed, thus valid. 1778bcb0991SDimitry Andric if (LocSize.isPrecise()) 1788bcb0991SDimitry Andric DerefBytes = std::max(DerefBytes, LocSize.getValue()); 1798bcb0991SDimitry Andric return DerefBytes; 1808bcb0991SDimitry Andric } 1818bcb0991SDimitry Andric 1820b57cec5SDimitry Andric /// Returns true if we can prove that the object specified by V has size Size. 1830b57cec5SDimitry Andric static bool isObjectSize(const Value *V, uint64_t Size, const DataLayout &DL, 1840b57cec5SDimitry Andric const TargetLibraryInfo &TLI, bool NullIsValidLoc) { 1850b57cec5SDimitry Andric uint64_t ObjectSize = getObjectSize(V, DL, TLI, NullIsValidLoc); 1860b57cec5SDimitry Andric return ObjectSize != MemoryLocation::UnknownSize && ObjectSize == Size; 1870b57cec5SDimitry Andric } 1880b57cec5SDimitry Andric 1890b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 190349cc55cSDimitry Andric // CaptureInfo implementations 191349cc55cSDimitry Andric //===----------------------------------------------------------------------===// 192349cc55cSDimitry Andric 193349cc55cSDimitry Andric CaptureInfo::~CaptureInfo() = default; 194349cc55cSDimitry Andric 195349cc55cSDimitry Andric bool SimpleCaptureInfo::isNotCapturedBeforeOrAt(const Value *Object, 196349cc55cSDimitry Andric const Instruction *I) { 197349cc55cSDimitry Andric return isNonEscapingLocalObject(Object, &IsCapturedCache); 198349cc55cSDimitry Andric } 199349cc55cSDimitry Andric 200349cc55cSDimitry Andric bool EarliestEscapeInfo::isNotCapturedBeforeOrAt(const Value *Object, 201349cc55cSDimitry Andric const Instruction *I) { 202349cc55cSDimitry Andric if (!isIdentifiedFunctionLocal(Object)) 203349cc55cSDimitry Andric return false; 204349cc55cSDimitry Andric 205349cc55cSDimitry Andric auto Iter = EarliestEscapes.insert({Object, nullptr}); 206349cc55cSDimitry Andric if (Iter.second) { 207349cc55cSDimitry Andric Instruction *EarliestCapture = FindEarliestCapture( 208349cc55cSDimitry Andric Object, *const_cast<Function *>(I->getFunction()), 20981ad6265SDimitry Andric /*ReturnCaptures=*/false, /*StoreCaptures=*/true, DT, EphValues); 210349cc55cSDimitry Andric if (EarliestCapture) { 211349cc55cSDimitry Andric auto Ins = Inst2Obj.insert({EarliestCapture, {}}); 212349cc55cSDimitry Andric Ins.first->second.push_back(Object); 213349cc55cSDimitry Andric } 214349cc55cSDimitry Andric Iter.first->second = EarliestCapture; 215349cc55cSDimitry Andric } 216349cc55cSDimitry Andric 217349cc55cSDimitry Andric // No capturing instruction. 218349cc55cSDimitry Andric if (!Iter.first->second) 219349cc55cSDimitry Andric return true; 220349cc55cSDimitry Andric 221349cc55cSDimitry Andric return I != Iter.first->second && 222349cc55cSDimitry Andric !isPotentiallyReachable(Iter.first->second, I, nullptr, &DT, &LI); 223349cc55cSDimitry Andric } 224349cc55cSDimitry Andric 225349cc55cSDimitry Andric void EarliestEscapeInfo::removeInstruction(Instruction *I) { 226349cc55cSDimitry Andric auto Iter = Inst2Obj.find(I); 227349cc55cSDimitry Andric if (Iter != Inst2Obj.end()) { 228349cc55cSDimitry Andric for (const Value *Obj : Iter->second) 229349cc55cSDimitry Andric EarliestEscapes.erase(Obj); 230349cc55cSDimitry Andric Inst2Obj.erase(I); 231349cc55cSDimitry Andric } 232349cc55cSDimitry Andric } 233349cc55cSDimitry Andric 234349cc55cSDimitry Andric //===----------------------------------------------------------------------===// 2350b57cec5SDimitry Andric // GetElementPtr Instruction Decomposition and Analysis 2360b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 2370b57cec5SDimitry Andric 238fe6060f1SDimitry Andric namespace { 239349cc55cSDimitry Andric /// Represents zext(sext(trunc(V))). 240349cc55cSDimitry Andric struct CastedValue { 241fe6060f1SDimitry Andric const Value *V; 242349cc55cSDimitry Andric unsigned ZExtBits = 0; 243349cc55cSDimitry Andric unsigned SExtBits = 0; 244349cc55cSDimitry Andric unsigned TruncBits = 0; 245fe6060f1SDimitry Andric 246349cc55cSDimitry Andric explicit CastedValue(const Value *V) : V(V) {} 247349cc55cSDimitry Andric explicit CastedValue(const Value *V, unsigned ZExtBits, unsigned SExtBits, 248349cc55cSDimitry Andric unsigned TruncBits) 249349cc55cSDimitry Andric : V(V), ZExtBits(ZExtBits), SExtBits(SExtBits), TruncBits(TruncBits) {} 250fe6060f1SDimitry Andric 251fe6060f1SDimitry Andric unsigned getBitWidth() const { 252349cc55cSDimitry Andric return V->getType()->getPrimitiveSizeInBits() - TruncBits + ZExtBits + 253349cc55cSDimitry Andric SExtBits; 254fe6060f1SDimitry Andric } 255fe6060f1SDimitry Andric 256349cc55cSDimitry Andric CastedValue withValue(const Value *NewV) const { 257349cc55cSDimitry Andric return CastedValue(NewV, ZExtBits, SExtBits, TruncBits); 258fe6060f1SDimitry Andric } 259fe6060f1SDimitry Andric 260349cc55cSDimitry Andric /// Replace V with zext(NewV) 261349cc55cSDimitry Andric CastedValue withZExtOfValue(const Value *NewV) const { 262fe6060f1SDimitry Andric unsigned ExtendBy = V->getType()->getPrimitiveSizeInBits() - 263fe6060f1SDimitry Andric NewV->getType()->getPrimitiveSizeInBits(); 264349cc55cSDimitry Andric if (ExtendBy <= TruncBits) 265349cc55cSDimitry Andric return CastedValue(NewV, ZExtBits, SExtBits, TruncBits - ExtendBy); 266349cc55cSDimitry Andric 267fe6060f1SDimitry Andric // zext(sext(zext(NewV))) == zext(zext(zext(NewV))) 268349cc55cSDimitry Andric ExtendBy -= TruncBits; 269349cc55cSDimitry Andric return CastedValue(NewV, ZExtBits + SExtBits + ExtendBy, 0, 0); 270fe6060f1SDimitry Andric } 271fe6060f1SDimitry Andric 272349cc55cSDimitry Andric /// Replace V with sext(NewV) 273349cc55cSDimitry Andric CastedValue withSExtOfValue(const Value *NewV) const { 274fe6060f1SDimitry Andric unsigned ExtendBy = V->getType()->getPrimitiveSizeInBits() - 275fe6060f1SDimitry Andric NewV->getType()->getPrimitiveSizeInBits(); 276349cc55cSDimitry Andric if (ExtendBy <= TruncBits) 277349cc55cSDimitry Andric return CastedValue(NewV, ZExtBits, SExtBits, TruncBits - ExtendBy); 278349cc55cSDimitry Andric 279fe6060f1SDimitry Andric // zext(sext(sext(NewV))) 280349cc55cSDimitry Andric ExtendBy -= TruncBits; 281349cc55cSDimitry Andric return CastedValue(NewV, ZExtBits, SExtBits + ExtendBy, 0); 282fe6060f1SDimitry Andric } 283fe6060f1SDimitry Andric 284fe6060f1SDimitry Andric APInt evaluateWith(APInt N) const { 285fe6060f1SDimitry Andric assert(N.getBitWidth() == V->getType()->getPrimitiveSizeInBits() && 286fe6060f1SDimitry Andric "Incompatible bit width"); 287349cc55cSDimitry Andric if (TruncBits) N = N.trunc(N.getBitWidth() - TruncBits); 288fe6060f1SDimitry Andric if (SExtBits) N = N.sext(N.getBitWidth() + SExtBits); 289fe6060f1SDimitry Andric if (ZExtBits) N = N.zext(N.getBitWidth() + ZExtBits); 290fe6060f1SDimitry Andric return N; 291fe6060f1SDimitry Andric } 292fe6060f1SDimitry Andric 293349cc55cSDimitry Andric ConstantRange evaluateWith(ConstantRange N) const { 294349cc55cSDimitry Andric assert(N.getBitWidth() == V->getType()->getPrimitiveSizeInBits() && 295349cc55cSDimitry Andric "Incompatible bit width"); 296349cc55cSDimitry Andric if (TruncBits) N = N.truncate(N.getBitWidth() - TruncBits); 297349cc55cSDimitry Andric if (SExtBits) N = N.signExtend(N.getBitWidth() + SExtBits); 298349cc55cSDimitry Andric if (ZExtBits) N = N.zeroExtend(N.getBitWidth() + ZExtBits); 299349cc55cSDimitry Andric return N; 300349cc55cSDimitry Andric } 301349cc55cSDimitry Andric 302fe6060f1SDimitry Andric bool canDistributeOver(bool NUW, bool NSW) const { 303fe6060f1SDimitry Andric // zext(x op<nuw> y) == zext(x) op<nuw> zext(y) 304fe6060f1SDimitry Andric // sext(x op<nsw> y) == sext(x) op<nsw> sext(y) 305349cc55cSDimitry Andric // trunc(x op y) == trunc(x) op trunc(y) 306fe6060f1SDimitry Andric return (!ZExtBits || NUW) && (!SExtBits || NSW); 307fe6060f1SDimitry Andric } 308349cc55cSDimitry Andric 309349cc55cSDimitry Andric bool hasSameCastsAs(const CastedValue &Other) const { 310349cc55cSDimitry Andric return ZExtBits == Other.ZExtBits && SExtBits == Other.SExtBits && 311349cc55cSDimitry Andric TruncBits == Other.TruncBits; 312349cc55cSDimitry Andric } 313fe6060f1SDimitry Andric }; 314fe6060f1SDimitry Andric 315349cc55cSDimitry Andric /// Represents zext(sext(trunc(V))) * Scale + Offset. 316fe6060f1SDimitry Andric struct LinearExpression { 317349cc55cSDimitry Andric CastedValue Val; 318fe6060f1SDimitry Andric APInt Scale; 319fe6060f1SDimitry Andric APInt Offset; 320fe6060f1SDimitry Andric 321fe6060f1SDimitry Andric /// True if all operations in this expression are NSW. 322fe6060f1SDimitry Andric bool IsNSW; 323fe6060f1SDimitry Andric 324349cc55cSDimitry Andric LinearExpression(const CastedValue &Val, const APInt &Scale, 325fe6060f1SDimitry Andric const APInt &Offset, bool IsNSW) 326fe6060f1SDimitry Andric : Val(Val), Scale(Scale), Offset(Offset), IsNSW(IsNSW) {} 327fe6060f1SDimitry Andric 328349cc55cSDimitry Andric LinearExpression(const CastedValue &Val) : Val(Val), IsNSW(true) { 329fe6060f1SDimitry Andric unsigned BitWidth = Val.getBitWidth(); 330fe6060f1SDimitry Andric Scale = APInt(BitWidth, 1); 331fe6060f1SDimitry Andric Offset = APInt(BitWidth, 0); 332fe6060f1SDimitry Andric } 333349cc55cSDimitry Andric 334349cc55cSDimitry Andric LinearExpression mul(const APInt &Other, bool MulIsNSW) const { 335349cc55cSDimitry Andric // The check for zero offset is necessary, because generally 336349cc55cSDimitry Andric // (X +nsw Y) *nsw Z does not imply (X *nsw Z) +nsw (Y *nsw Z). 337349cc55cSDimitry Andric bool NSW = IsNSW && (Other.isOne() || (MulIsNSW && Offset.isZero())); 338349cc55cSDimitry Andric return LinearExpression(Val, Scale * Other, Offset * Other, NSW); 339349cc55cSDimitry Andric } 340fe6060f1SDimitry Andric }; 341fe6060f1SDimitry Andric } 342fe6060f1SDimitry Andric 3430b57cec5SDimitry Andric /// Analyzes the specified value as a linear expression: "A*V + B", where A and 3440b57cec5SDimitry Andric /// B are constant integers. 345fe6060f1SDimitry Andric static LinearExpression GetLinearExpression( 346349cc55cSDimitry Andric const CastedValue &Val, const DataLayout &DL, unsigned Depth, 347fe6060f1SDimitry Andric AssumptionCache *AC, DominatorTree *DT) { 3480b57cec5SDimitry Andric // Limit our recursion depth. 349fe6060f1SDimitry Andric if (Depth == 6) 350fe6060f1SDimitry Andric return Val; 3510b57cec5SDimitry Andric 352fe6060f1SDimitry Andric if (const ConstantInt *Const = dyn_cast<ConstantInt>(Val.V)) 353fe6060f1SDimitry Andric return LinearExpression(Val, APInt(Val.getBitWidth(), 0), 354fe6060f1SDimitry Andric Val.evaluateWith(Const->getValue()), true); 3550b57cec5SDimitry Andric 356fe6060f1SDimitry Andric if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(Val.V)) { 3570b57cec5SDimitry Andric if (ConstantInt *RHSC = dyn_cast<ConstantInt>(BOp->getOperand(1))) { 358fe6060f1SDimitry Andric APInt RHS = Val.evaluateWith(RHSC->getValue()); 359fe6060f1SDimitry Andric // The only non-OBO case we deal with is or, and only limited to the 360fe6060f1SDimitry Andric // case where it is both nuw and nsw. 361fe6060f1SDimitry Andric bool NUW = true, NSW = true; 362fe6060f1SDimitry Andric if (isa<OverflowingBinaryOperator>(BOp)) { 363fe6060f1SDimitry Andric NUW &= BOp->hasNoUnsignedWrap(); 364fe6060f1SDimitry Andric NSW &= BOp->hasNoSignedWrap(); 365fe6060f1SDimitry Andric } 366fe6060f1SDimitry Andric if (!Val.canDistributeOver(NUW, NSW)) 367fe6060f1SDimitry Andric return Val; 3680b57cec5SDimitry Andric 369349cc55cSDimitry Andric // While we can distribute over trunc, we cannot preserve nowrap flags 370349cc55cSDimitry Andric // in that case. 371349cc55cSDimitry Andric if (Val.TruncBits) 372349cc55cSDimitry Andric NUW = NSW = false; 373349cc55cSDimitry Andric 374fe6060f1SDimitry Andric LinearExpression E(Val); 3750b57cec5SDimitry Andric switch (BOp->getOpcode()) { 3760b57cec5SDimitry Andric default: 3770b57cec5SDimitry Andric // We don't understand this instruction, so we can't decompose it any 3780b57cec5SDimitry Andric // further. 379fe6060f1SDimitry Andric return Val; 3800b57cec5SDimitry Andric case Instruction::Or: 3810b57cec5SDimitry Andric // X|C == X+C if all the bits in C are unset in X. Otherwise we can't 3820b57cec5SDimitry Andric // analyze it. 3830b57cec5SDimitry Andric if (!MaskedValueIsZero(BOp->getOperand(0), RHSC->getValue(), DL, 0, AC, 384fe6060f1SDimitry Andric BOp, DT)) 385fe6060f1SDimitry Andric return Val; 3860b57cec5SDimitry Andric 387bdd1243dSDimitry Andric [[fallthrough]]; 388fe6060f1SDimitry Andric case Instruction::Add: { 389fe6060f1SDimitry Andric E = GetLinearExpression(Val.withValue(BOp->getOperand(0)), DL, 390fe6060f1SDimitry Andric Depth + 1, AC, DT); 391fe6060f1SDimitry Andric E.Offset += RHS; 392fe6060f1SDimitry Andric E.IsNSW &= NSW; 393fe6060f1SDimitry Andric break; 394fe6060f1SDimitry Andric } 395fe6060f1SDimitry Andric case Instruction::Sub: { 396fe6060f1SDimitry Andric E = GetLinearExpression(Val.withValue(BOp->getOperand(0)), DL, 397fe6060f1SDimitry Andric Depth + 1, AC, DT); 398fe6060f1SDimitry Andric E.Offset -= RHS; 399fe6060f1SDimitry Andric E.IsNSW &= NSW; 400fe6060f1SDimitry Andric break; 401fe6060f1SDimitry Andric } 402349cc55cSDimitry Andric case Instruction::Mul: 403fe6060f1SDimitry Andric E = GetLinearExpression(Val.withValue(BOp->getOperand(0)), DL, 404349cc55cSDimitry Andric Depth + 1, AC, DT) 405349cc55cSDimitry Andric .mul(RHS, NSW); 406fe6060f1SDimitry Andric break; 407fe6060f1SDimitry Andric case Instruction::Shl: 4080b57cec5SDimitry Andric // We're trying to linearize an expression of the kind: 4090b57cec5SDimitry Andric // shl i8 -128, 36 4100b57cec5SDimitry Andric // where the shift count exceeds the bitwidth of the type. 4110b57cec5SDimitry Andric // We can't decompose this further (the expression would return 4120b57cec5SDimitry Andric // a poison value). 413fe6060f1SDimitry Andric if (RHS.getLimitedValue() > Val.getBitWidth()) 414fe6060f1SDimitry Andric return Val; 4150b57cec5SDimitry Andric 416fe6060f1SDimitry Andric E = GetLinearExpression(Val.withValue(BOp->getOperand(0)), DL, 417fe6060f1SDimitry Andric Depth + 1, AC, DT); 418fe6060f1SDimitry Andric E.Offset <<= RHS.getLimitedValue(); 419fe6060f1SDimitry Andric E.Scale <<= RHS.getLimitedValue(); 420fe6060f1SDimitry Andric E.IsNSW &= NSW; 421fe6060f1SDimitry Andric break; 4220b57cec5SDimitry Andric } 423fe6060f1SDimitry Andric return E; 4240b57cec5SDimitry Andric } 4250b57cec5SDimitry Andric } 4260b57cec5SDimitry Andric 427fe6060f1SDimitry Andric if (isa<ZExtInst>(Val.V)) 428fe6060f1SDimitry Andric return GetLinearExpression( 429fe6060f1SDimitry Andric Val.withZExtOfValue(cast<CastInst>(Val.V)->getOperand(0)), 430fe6060f1SDimitry Andric DL, Depth + 1, AC, DT); 4310b57cec5SDimitry Andric 432fe6060f1SDimitry Andric if (isa<SExtInst>(Val.V)) 433fe6060f1SDimitry Andric return GetLinearExpression( 434fe6060f1SDimitry Andric Val.withSExtOfValue(cast<CastInst>(Val.V)->getOperand(0)), 435fe6060f1SDimitry Andric DL, Depth + 1, AC, DT); 4360b57cec5SDimitry Andric 437fe6060f1SDimitry Andric return Val; 4380b57cec5SDimitry Andric } 4390b57cec5SDimitry Andric 440349cc55cSDimitry Andric /// To ensure a pointer offset fits in an integer of size IndexSize 441349cc55cSDimitry Andric /// (in bits) when that size is smaller than the maximum index size. This is 4420b57cec5SDimitry Andric /// an issue, for example, in particular for 32b pointers with negative indices 4430b57cec5SDimitry Andric /// that rely on two's complement wrap-arounds for precise alias information 444349cc55cSDimitry Andric /// where the maximum index size is 64b. 445349cc55cSDimitry Andric static APInt adjustToIndexSize(const APInt &Offset, unsigned IndexSize) { 446349cc55cSDimitry Andric assert(IndexSize <= Offset.getBitWidth() && "Invalid IndexSize!"); 447349cc55cSDimitry Andric unsigned ShiftBits = Offset.getBitWidth() - IndexSize; 4480b57cec5SDimitry Andric return (Offset << ShiftBits).ashr(ShiftBits); 4490b57cec5SDimitry Andric } 4500b57cec5SDimitry Andric 451349cc55cSDimitry Andric namespace { 452349cc55cSDimitry Andric // A linear transformation of a Value; this class represents 453349cc55cSDimitry Andric // ZExt(SExt(Trunc(V, TruncBits), SExtBits), ZExtBits) * Scale. 454349cc55cSDimitry Andric struct VariableGEPIndex { 455349cc55cSDimitry Andric CastedValue Val; 456349cc55cSDimitry Andric APInt Scale; 4570b57cec5SDimitry Andric 458349cc55cSDimitry Andric // Context instruction to use when querying information about this index. 459349cc55cSDimitry Andric const Instruction *CxtI; 460349cc55cSDimitry Andric 461349cc55cSDimitry Andric /// True if all operations in this expression are NSW. 462349cc55cSDimitry Andric bool IsNSW; 463349cc55cSDimitry Andric 464349cc55cSDimitry Andric void dump() const { 465349cc55cSDimitry Andric print(dbgs()); 466349cc55cSDimitry Andric dbgs() << "\n"; 4670b57cec5SDimitry Andric } 468349cc55cSDimitry Andric void print(raw_ostream &OS) const { 469349cc55cSDimitry Andric OS << "(V=" << Val.V->getName() 470349cc55cSDimitry Andric << ", zextbits=" << Val.ZExtBits 471349cc55cSDimitry Andric << ", sextbits=" << Val.SExtBits 472349cc55cSDimitry Andric << ", truncbits=" << Val.TruncBits 473349cc55cSDimitry Andric << ", scale=" << Scale << ")"; 474349cc55cSDimitry Andric } 475349cc55cSDimitry Andric }; 476349cc55cSDimitry Andric } 477349cc55cSDimitry Andric 478349cc55cSDimitry Andric // Represents the internal structure of a GEP, decomposed into a base pointer, 479349cc55cSDimitry Andric // constant offsets, and variable scaled indices. 480349cc55cSDimitry Andric struct BasicAAResult::DecomposedGEP { 481349cc55cSDimitry Andric // Base pointer of the GEP 482349cc55cSDimitry Andric const Value *Base; 483349cc55cSDimitry Andric // Total constant offset from base. 484349cc55cSDimitry Andric APInt Offset; 485349cc55cSDimitry Andric // Scaled variable (non-constant) indices. 486349cc55cSDimitry Andric SmallVector<VariableGEPIndex, 4> VarIndices; 487349cc55cSDimitry Andric // Are all operations inbounds GEPs or non-indexing operations? 488bdd1243dSDimitry Andric // (std::nullopt iff expression doesn't involve any geps) 489bdd1243dSDimitry Andric std::optional<bool> InBounds; 490349cc55cSDimitry Andric 491349cc55cSDimitry Andric void dump() const { 492349cc55cSDimitry Andric print(dbgs()); 493349cc55cSDimitry Andric dbgs() << "\n"; 494349cc55cSDimitry Andric } 495349cc55cSDimitry Andric void print(raw_ostream &OS) const { 496349cc55cSDimitry Andric OS << "(DecomposedGEP Base=" << Base->getName() 497349cc55cSDimitry Andric << ", Offset=" << Offset 498349cc55cSDimitry Andric << ", VarIndices=["; 499349cc55cSDimitry Andric for (size_t i = 0; i < VarIndices.size(); i++) { 500349cc55cSDimitry Andric if (i != 0) 501349cc55cSDimitry Andric OS << ", "; 502349cc55cSDimitry Andric VarIndices[i].print(OS); 503349cc55cSDimitry Andric } 504349cc55cSDimitry Andric OS << "])"; 505349cc55cSDimitry Andric } 506349cc55cSDimitry Andric }; 507349cc55cSDimitry Andric 5080b57cec5SDimitry Andric 5090b57cec5SDimitry Andric /// If V is a symbolic pointer expression, decompose it into a base pointer 5100b57cec5SDimitry Andric /// with a constant offset and a number of scaled symbolic offsets. 5110b57cec5SDimitry Andric /// 5120b57cec5SDimitry Andric /// The scaled symbolic offsets (represented by pairs of a Value* and a scale 5130b57cec5SDimitry Andric /// in the VarIndices vector) are Value*'s that are known to be scaled by the 5140b57cec5SDimitry Andric /// specified amount, but which may have other unrepresented high bits. As 5150b57cec5SDimitry Andric /// such, the gep cannot necessarily be reconstructed from its decomposed form. 516e8d8bef9SDimitry Andric BasicAAResult::DecomposedGEP 517e8d8bef9SDimitry Andric BasicAAResult::DecomposeGEPExpression(const Value *V, const DataLayout &DL, 518e8d8bef9SDimitry Andric AssumptionCache *AC, DominatorTree *DT) { 5190b57cec5SDimitry Andric // Limit recursion depth to limit compile time in crazy cases. 5200b57cec5SDimitry Andric unsigned MaxLookup = MaxLookupSearchDepth; 5210b57cec5SDimitry Andric SearchTimes++; 522e8d8bef9SDimitry Andric const Instruction *CxtI = dyn_cast<Instruction>(V); 5230b57cec5SDimitry Andric 524349cc55cSDimitry Andric unsigned MaxIndexSize = DL.getMaxIndexSizeInBits(); 525e8d8bef9SDimitry Andric DecomposedGEP Decomposed; 526349cc55cSDimitry Andric Decomposed.Offset = APInt(MaxIndexSize, 0); 5270b57cec5SDimitry Andric do { 5280b57cec5SDimitry Andric // See if this is a bitcast or GEP. 5290b57cec5SDimitry Andric const Operator *Op = dyn_cast<Operator>(V); 5300b57cec5SDimitry Andric if (!Op) { 5310b57cec5SDimitry Andric // The only non-operator case we can handle are GlobalAliases. 5320b57cec5SDimitry Andric if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) { 5330b57cec5SDimitry Andric if (!GA->isInterposable()) { 5340b57cec5SDimitry Andric V = GA->getAliasee(); 5350b57cec5SDimitry Andric continue; 5360b57cec5SDimitry Andric } 5370b57cec5SDimitry Andric } 5380b57cec5SDimitry Andric Decomposed.Base = V; 539e8d8bef9SDimitry Andric return Decomposed; 5400b57cec5SDimitry Andric } 5410b57cec5SDimitry Andric 5420b57cec5SDimitry Andric if (Op->getOpcode() == Instruction::BitCast || 5430b57cec5SDimitry Andric Op->getOpcode() == Instruction::AddrSpaceCast) { 5440b57cec5SDimitry Andric V = Op->getOperand(0); 5450b57cec5SDimitry Andric continue; 5460b57cec5SDimitry Andric } 5470b57cec5SDimitry Andric 5480b57cec5SDimitry Andric const GEPOperator *GEPOp = dyn_cast<GEPOperator>(Op); 5490b57cec5SDimitry Andric if (!GEPOp) { 5505ffd83dbSDimitry Andric if (const auto *PHI = dyn_cast<PHINode>(V)) { 5515ffd83dbSDimitry Andric // Look through single-arg phi nodes created by LCSSA. 5525ffd83dbSDimitry Andric if (PHI->getNumIncomingValues() == 1) { 5535ffd83dbSDimitry Andric V = PHI->getIncomingValue(0); 5545ffd83dbSDimitry Andric continue; 5555ffd83dbSDimitry Andric } 5565ffd83dbSDimitry Andric } else if (const auto *Call = dyn_cast<CallBase>(V)) { 5570b57cec5SDimitry Andric // CaptureTracking can know about special capturing properties of some 5580b57cec5SDimitry Andric // intrinsics like launder.invariant.group, that can't be expressed with 5590b57cec5SDimitry Andric // the attributes, but have properties like returning aliasing pointer. 5600b57cec5SDimitry Andric // Because some analysis may assume that nocaptured pointer is not 5610b57cec5SDimitry Andric // returned from some special intrinsic (because function would have to 5620b57cec5SDimitry Andric // be marked with returns attribute), it is crucial to use this function 5630b57cec5SDimitry Andric // because it should be in sync with CaptureTracking. Not using it may 5640b57cec5SDimitry Andric // cause weird miscompilations where 2 aliasing pointers are assumed to 5650b57cec5SDimitry Andric // noalias. 5668bcb0991SDimitry Andric if (auto *RP = getArgumentAliasingToReturnedPointer(Call, false)) { 5670b57cec5SDimitry Andric V = RP; 5680b57cec5SDimitry Andric continue; 5690b57cec5SDimitry Andric } 5700b57cec5SDimitry Andric } 5710b57cec5SDimitry Andric 5720b57cec5SDimitry Andric Decomposed.Base = V; 573e8d8bef9SDimitry Andric return Decomposed; 5740b57cec5SDimitry Andric } 5750b57cec5SDimitry Andric 576fe6060f1SDimitry Andric // Track whether we've seen at least one in bounds gep, and if so, whether 577fe6060f1SDimitry Andric // all geps parsed were in bounds. 578bdd1243dSDimitry Andric if (Decomposed.InBounds == std::nullopt) 579fe6060f1SDimitry Andric Decomposed.InBounds = GEPOp->isInBounds(); 580fe6060f1SDimitry Andric else if (!GEPOp->isInBounds()) 581fe6060f1SDimitry Andric Decomposed.InBounds = false; 582fe6060f1SDimitry Andric 583349cc55cSDimitry Andric assert(GEPOp->getSourceElementType()->isSized() && "GEP must be sized"); 5840b57cec5SDimitry Andric 5850b57cec5SDimitry Andric unsigned AS = GEPOp->getPointerAddressSpace(); 5860b57cec5SDimitry Andric // Walk the indices of the GEP, accumulating them into BaseOff/VarIndices. 5870b57cec5SDimitry Andric gep_type_iterator GTI = gep_type_begin(GEPOp); 588349cc55cSDimitry Andric unsigned IndexSize = DL.getIndexSizeInBits(AS); 5890b57cec5SDimitry Andric // Assume all GEP operands are constants until proven otherwise. 5900b57cec5SDimitry Andric bool GepHasConstantOffset = true; 5910b57cec5SDimitry Andric for (User::const_op_iterator I = GEPOp->op_begin() + 1, E = GEPOp->op_end(); 5920b57cec5SDimitry Andric I != E; ++I, ++GTI) { 5930b57cec5SDimitry Andric const Value *Index = *I; 5940b57cec5SDimitry Andric // Compute the (potentially symbolic) offset in bytes for this index. 5950b57cec5SDimitry Andric if (StructType *STy = GTI.getStructTypeOrNull()) { 5960b57cec5SDimitry Andric // For a struct, add the member offset. 5970b57cec5SDimitry Andric unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue(); 5980b57cec5SDimitry Andric if (FieldNo == 0) 5990b57cec5SDimitry Andric continue; 6000b57cec5SDimitry Andric 601e8d8bef9SDimitry Andric Decomposed.Offset += DL.getStructLayout(STy)->getElementOffset(FieldNo); 6020b57cec5SDimitry Andric continue; 6030b57cec5SDimitry Andric } 6040b57cec5SDimitry Andric 6050b57cec5SDimitry Andric // For an array/pointer, add the element offset, explicitly scaled. 6060b57cec5SDimitry Andric if (const ConstantInt *CIdx = dyn_cast<ConstantInt>(Index)) { 6070b57cec5SDimitry Andric if (CIdx->isZero()) 6080b57cec5SDimitry Andric continue; 609bdd1243dSDimitry Andric 610bdd1243dSDimitry Andric // Don't attempt to analyze GEPs if the scalable index is not zero. 611bdd1243dSDimitry Andric TypeSize AllocTypeSize = DL.getTypeAllocSize(GTI.getIndexedType()); 612bdd1243dSDimitry Andric if (AllocTypeSize.isScalable()) { 613bdd1243dSDimitry Andric Decomposed.Base = V; 614bdd1243dSDimitry Andric return Decomposed; 615bdd1243dSDimitry Andric } 616bdd1243dSDimitry Andric 617bdd1243dSDimitry Andric Decomposed.Offset += AllocTypeSize.getFixedValue() * 618349cc55cSDimitry Andric CIdx->getValue().sextOrTrunc(MaxIndexSize); 6190b57cec5SDimitry Andric continue; 6200b57cec5SDimitry Andric } 6210b57cec5SDimitry Andric 622bdd1243dSDimitry Andric TypeSize AllocTypeSize = DL.getTypeAllocSize(GTI.getIndexedType()); 623bdd1243dSDimitry Andric if (AllocTypeSize.isScalable()) { 624bdd1243dSDimitry Andric Decomposed.Base = V; 625bdd1243dSDimitry Andric return Decomposed; 626bdd1243dSDimitry Andric } 627bdd1243dSDimitry Andric 6280b57cec5SDimitry Andric GepHasConstantOffset = false; 6290b57cec5SDimitry Andric 630349cc55cSDimitry Andric // If the integer type is smaller than the index size, it is implicitly 631349cc55cSDimitry Andric // sign extended or truncated to index size. 6320b57cec5SDimitry Andric unsigned Width = Index->getType()->getIntegerBitWidth(); 633349cc55cSDimitry Andric unsigned SExtBits = IndexSize > Width ? IndexSize - Width : 0; 634349cc55cSDimitry Andric unsigned TruncBits = IndexSize < Width ? Width - IndexSize : 0; 635fe6060f1SDimitry Andric LinearExpression LE = GetLinearExpression( 636349cc55cSDimitry Andric CastedValue(Index, 0, SExtBits, TruncBits), DL, 0, AC, DT); 6370b57cec5SDimitry Andric 638349cc55cSDimitry Andric // Scale by the type size. 639bdd1243dSDimitry Andric unsigned TypeSize = AllocTypeSize.getFixedValue(); 640349cc55cSDimitry Andric LE = LE.mul(APInt(IndexSize, TypeSize), GEPOp->isInBounds()); 64181ad6265SDimitry Andric Decomposed.Offset += LE.Offset.sext(MaxIndexSize); 64281ad6265SDimitry Andric APInt Scale = LE.Scale.sext(MaxIndexSize); 6430b57cec5SDimitry Andric 6440b57cec5SDimitry Andric // If we already had an occurrence of this index variable, merge this 6450b57cec5SDimitry Andric // scale into it. For example, we want to handle: 6460b57cec5SDimitry Andric // A[x][x] -> x*16 + x*4 -> x*20 6470b57cec5SDimitry Andric // This also ensures that 'x' only appears in the index list once. 6480b57cec5SDimitry Andric for (unsigned i = 0, e = Decomposed.VarIndices.size(); i != e; ++i) { 649349cc55cSDimitry Andric if (Decomposed.VarIndices[i].Val.V == LE.Val.V && 650349cc55cSDimitry Andric Decomposed.VarIndices[i].Val.hasSameCastsAs(LE.Val)) { 6510b57cec5SDimitry Andric Scale += Decomposed.VarIndices[i].Scale; 6520b57cec5SDimitry Andric Decomposed.VarIndices.erase(Decomposed.VarIndices.begin() + i); 6530b57cec5SDimitry Andric break; 6540b57cec5SDimitry Andric } 6550b57cec5SDimitry Andric } 6560b57cec5SDimitry Andric 6570b57cec5SDimitry Andric // Make sure that we have a scale that makes sense for this target's 658349cc55cSDimitry Andric // index size. 659349cc55cSDimitry Andric Scale = adjustToIndexSize(Scale, IndexSize); 6600b57cec5SDimitry Andric 6610b57cec5SDimitry Andric if (!!Scale) { 662349cc55cSDimitry Andric VariableGEPIndex Entry = {LE.Val, Scale, CxtI, LE.IsNSW}; 6630b57cec5SDimitry Andric Decomposed.VarIndices.push_back(Entry); 6640b57cec5SDimitry Andric } 6650b57cec5SDimitry Andric } 6660b57cec5SDimitry Andric 6670b57cec5SDimitry Andric // Take care of wrap-arounds 668e8d8bef9SDimitry Andric if (GepHasConstantOffset) 669349cc55cSDimitry Andric Decomposed.Offset = adjustToIndexSize(Decomposed.Offset, IndexSize); 6700b57cec5SDimitry Andric 6710b57cec5SDimitry Andric // Analyze the base pointer next. 6720b57cec5SDimitry Andric V = GEPOp->getOperand(0); 6730b57cec5SDimitry Andric } while (--MaxLookup); 6740b57cec5SDimitry Andric 6750b57cec5SDimitry Andric // If the chain of expressions is too deep, just return early. 6760b57cec5SDimitry Andric Decomposed.Base = V; 6770b57cec5SDimitry Andric SearchLimitReached++; 678e8d8bef9SDimitry Andric return Decomposed; 6790b57cec5SDimitry Andric } 6800b57cec5SDimitry Andric 681bdd1243dSDimitry Andric ModRefInfo BasicAAResult::getModRefInfoMask(const MemoryLocation &Loc, 682bdd1243dSDimitry Andric AAQueryInfo &AAQI, 683bdd1243dSDimitry Andric bool IgnoreLocals) { 6840b57cec5SDimitry Andric assert(Visited.empty() && "Visited must be cleared after use!"); 685bdd1243dSDimitry Andric auto _ = make_scope_exit([&] { Visited.clear(); }); 6860b57cec5SDimitry Andric 6870b57cec5SDimitry Andric unsigned MaxLookup = 8; 6880b57cec5SDimitry Andric SmallVector<const Value *, 16> Worklist; 6890b57cec5SDimitry Andric Worklist.push_back(Loc.Ptr); 690bdd1243dSDimitry Andric ModRefInfo Result = ModRefInfo::NoModRef; 691bdd1243dSDimitry Andric 6920b57cec5SDimitry Andric do { 693e8d8bef9SDimitry Andric const Value *V = getUnderlyingObject(Worklist.pop_back_val()); 694bdd1243dSDimitry Andric if (!Visited.insert(V).second) 6950b57cec5SDimitry Andric continue; 6960b57cec5SDimitry Andric 697bdd1243dSDimitry Andric // Ignore allocas if we were instructed to do so. 698bdd1243dSDimitry Andric if (IgnoreLocals && isa<AllocaInst>(V)) 699bdd1243dSDimitry Andric continue; 700bdd1243dSDimitry Andric 701bdd1243dSDimitry Andric // If the location points to memory that is known to be invariant for 702bdd1243dSDimitry Andric // the life of the underlying SSA value, then we can exclude Mod from 703bdd1243dSDimitry Andric // the set of valid memory effects. 704bdd1243dSDimitry Andric // 705bdd1243dSDimitry Andric // An argument that is marked readonly and noalias is known to be 706bdd1243dSDimitry Andric // invariant while that function is executing. 707bdd1243dSDimitry Andric if (const Argument *Arg = dyn_cast<Argument>(V)) { 708bdd1243dSDimitry Andric if (Arg->hasNoAliasAttr() && Arg->onlyReadsMemory()) { 709bdd1243dSDimitry Andric Result |= ModRefInfo::Ref; 710bdd1243dSDimitry Andric continue; 711bdd1243dSDimitry Andric } 712bdd1243dSDimitry Andric } 713bdd1243dSDimitry Andric 714bdd1243dSDimitry Andric // A global constant can't be mutated. 7150b57cec5SDimitry Andric if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) { 7160b57cec5SDimitry Andric // Note: this doesn't require GV to be "ODR" because it isn't legal for a 7170b57cec5SDimitry Andric // global to be marked constant in some modules and non-constant in 7180b57cec5SDimitry Andric // others. GV may even be a declaration, not a definition. 719bdd1243dSDimitry Andric if (!GV->isConstant()) 720bdd1243dSDimitry Andric return AAResultBase::getModRefInfoMask(Loc, AAQI, IgnoreLocals); 7210b57cec5SDimitry Andric continue; 7220b57cec5SDimitry Andric } 7230b57cec5SDimitry Andric 7240b57cec5SDimitry Andric // If both select values point to local memory, then so does the select. 7250b57cec5SDimitry Andric if (const SelectInst *SI = dyn_cast<SelectInst>(V)) { 7260b57cec5SDimitry Andric Worklist.push_back(SI->getTrueValue()); 7270b57cec5SDimitry Andric Worklist.push_back(SI->getFalseValue()); 7280b57cec5SDimitry Andric continue; 7290b57cec5SDimitry Andric } 7300b57cec5SDimitry Andric 7310b57cec5SDimitry Andric // If all values incoming to a phi node point to local memory, then so does 7320b57cec5SDimitry Andric // the phi. 7330b57cec5SDimitry Andric if (const PHINode *PN = dyn_cast<PHINode>(V)) { 7340b57cec5SDimitry Andric // Don't bother inspecting phi nodes with many operands. 735bdd1243dSDimitry Andric if (PN->getNumIncomingValues() > MaxLookup) 736bdd1243dSDimitry Andric return AAResultBase::getModRefInfoMask(Loc, AAQI, IgnoreLocals); 737e8d8bef9SDimitry Andric append_range(Worklist, PN->incoming_values()); 7380b57cec5SDimitry Andric continue; 7390b57cec5SDimitry Andric } 7400b57cec5SDimitry Andric 7410b57cec5SDimitry Andric // Otherwise be conservative. 742bdd1243dSDimitry Andric return AAResultBase::getModRefInfoMask(Loc, AAQI, IgnoreLocals); 7430b57cec5SDimitry Andric } while (!Worklist.empty() && --MaxLookup); 7440b57cec5SDimitry Andric 745bdd1243dSDimitry Andric // If we hit the maximum number of instructions to examine, be conservative. 746bdd1243dSDimitry Andric if (!Worklist.empty()) 747bdd1243dSDimitry Andric return AAResultBase::getModRefInfoMask(Loc, AAQI, IgnoreLocals); 748bdd1243dSDimitry Andric 749bdd1243dSDimitry Andric return Result; 7500b57cec5SDimitry Andric } 7510b57cec5SDimitry Andric 752fe6060f1SDimitry Andric static bool isIntrinsicCall(const CallBase *Call, Intrinsic::ID IID) { 753fe6060f1SDimitry Andric const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Call); 754fe6060f1SDimitry Andric return II && II->getIntrinsicID() == IID; 755fe6060f1SDimitry Andric } 756fe6060f1SDimitry Andric 7570b57cec5SDimitry Andric /// Returns the behavior when calling the given call site. 758bdd1243dSDimitry Andric MemoryEffects BasicAAResult::getMemoryEffects(const CallBase *Call, 759bdd1243dSDimitry Andric AAQueryInfo &AAQI) { 760bdd1243dSDimitry Andric MemoryEffects Min = Call->getAttributes().getMemoryEffects(); 7610b57cec5SDimitry Andric 762bdd1243dSDimitry Andric if (const Function *F = dyn_cast<Function>(Call->getCalledOperand())) { 763bdd1243dSDimitry Andric MemoryEffects FuncME = AAQI.AAR.getMemoryEffects(F); 764bdd1243dSDimitry Andric // Operand bundles on the call may also read or write memory, in addition 765bdd1243dSDimitry Andric // to the behavior of the called function. 766bdd1243dSDimitry Andric if (Call->hasReadingOperandBundles()) 767bdd1243dSDimitry Andric FuncME |= MemoryEffects::readOnly(); 768bdd1243dSDimitry Andric if (Call->hasClobberingOperandBundles()) 769bdd1243dSDimitry Andric FuncME |= MemoryEffects::writeOnly(); 770bdd1243dSDimitry Andric Min &= FuncME; 771bdd1243dSDimitry Andric } 7720b57cec5SDimitry Andric 7730b57cec5SDimitry Andric return Min; 7740b57cec5SDimitry Andric } 7750b57cec5SDimitry Andric 7760b57cec5SDimitry Andric /// Returns the behavior when calling the given function. For use when the call 7770b57cec5SDimitry Andric /// site is not known. 778bdd1243dSDimitry Andric MemoryEffects BasicAAResult::getMemoryEffects(const Function *F) { 779bdd1243dSDimitry Andric switch (F->getIntrinsicID()) { 780bdd1243dSDimitry Andric case Intrinsic::experimental_guard: 781bdd1243dSDimitry Andric case Intrinsic::experimental_deoptimize: 782bdd1243dSDimitry Andric // These intrinsics can read arbitrary memory, and additionally modref 783bdd1243dSDimitry Andric // inaccessible memory to model control dependence. 784bdd1243dSDimitry Andric return MemoryEffects::readOnly() | 785bdd1243dSDimitry Andric MemoryEffects::inaccessibleMemOnly(ModRefInfo::ModRef); 7860b57cec5SDimitry Andric } 7870b57cec5SDimitry Andric 788bdd1243dSDimitry Andric return F->getMemoryEffects(); 7890b57cec5SDimitry Andric } 7900b57cec5SDimitry Andric 7910b57cec5SDimitry Andric ModRefInfo BasicAAResult::getArgModRefInfo(const CallBase *Call, 7920b57cec5SDimitry Andric unsigned ArgIdx) { 793bdd1243dSDimitry Andric if (Call->paramHasAttr(ArgIdx, Attribute::WriteOnly)) 7940b57cec5SDimitry Andric return ModRefInfo::Mod; 7950b57cec5SDimitry Andric 7960b57cec5SDimitry Andric if (Call->paramHasAttr(ArgIdx, Attribute::ReadOnly)) 7970b57cec5SDimitry Andric return ModRefInfo::Ref; 7980b57cec5SDimitry Andric 7990b57cec5SDimitry Andric if (Call->paramHasAttr(ArgIdx, Attribute::ReadNone)) 8000b57cec5SDimitry Andric return ModRefInfo::NoModRef; 8010b57cec5SDimitry Andric 8020b57cec5SDimitry Andric return AAResultBase::getArgModRefInfo(Call, ArgIdx); 8030b57cec5SDimitry Andric } 8040b57cec5SDimitry Andric 8050b57cec5SDimitry Andric #ifndef NDEBUG 8060b57cec5SDimitry Andric static const Function *getParent(const Value *V) { 8070b57cec5SDimitry Andric if (const Instruction *inst = dyn_cast<Instruction>(V)) { 8080b57cec5SDimitry Andric if (!inst->getParent()) 8090b57cec5SDimitry Andric return nullptr; 8100b57cec5SDimitry Andric return inst->getParent()->getParent(); 8110b57cec5SDimitry Andric } 8120b57cec5SDimitry Andric 8130b57cec5SDimitry Andric if (const Argument *arg = dyn_cast<Argument>(V)) 8140b57cec5SDimitry Andric return arg->getParent(); 8150b57cec5SDimitry Andric 8160b57cec5SDimitry Andric return nullptr; 8170b57cec5SDimitry Andric } 8180b57cec5SDimitry Andric 8190b57cec5SDimitry Andric static bool notDifferentParent(const Value *O1, const Value *O2) { 8200b57cec5SDimitry Andric 8210b57cec5SDimitry Andric const Function *F1 = getParent(O1); 8220b57cec5SDimitry Andric const Function *F2 = getParent(O2); 8230b57cec5SDimitry Andric 8240b57cec5SDimitry Andric return !F1 || !F2 || F1 == F2; 8250b57cec5SDimitry Andric } 8260b57cec5SDimitry Andric #endif 8270b57cec5SDimitry Andric 8280b57cec5SDimitry Andric AliasResult BasicAAResult::alias(const MemoryLocation &LocA, 829bdd1243dSDimitry Andric const MemoryLocation &LocB, AAQueryInfo &AAQI, 830bdd1243dSDimitry Andric const Instruction *CtxI) { 8310b57cec5SDimitry Andric assert(notDifferentParent(LocA.Ptr, LocB.Ptr) && 8320b57cec5SDimitry Andric "BasicAliasAnalysis doesn't support interprocedural queries."); 833bdd1243dSDimitry Andric return aliasCheck(LocA.Ptr, LocA.Size, LocB.Ptr, LocB.Size, AAQI, CtxI); 8340b57cec5SDimitry Andric } 8350b57cec5SDimitry Andric 8360b57cec5SDimitry Andric /// Checks to see if the specified callsite can clobber the specified memory 8370b57cec5SDimitry Andric /// object. 8380b57cec5SDimitry Andric /// 8390b57cec5SDimitry Andric /// Since we only look at local properties of this function, we really can't 8400b57cec5SDimitry Andric /// say much about this query. We do, however, use simple "address taken" 8410b57cec5SDimitry Andric /// analysis on local objects. 8420b57cec5SDimitry Andric ModRefInfo BasicAAResult::getModRefInfo(const CallBase *Call, 8430b57cec5SDimitry Andric const MemoryLocation &Loc, 8440b57cec5SDimitry Andric AAQueryInfo &AAQI) { 8450b57cec5SDimitry Andric assert(notDifferentParent(Call, Loc.Ptr) && 8460b57cec5SDimitry Andric "AliasAnalysis query involving multiple functions!"); 8470b57cec5SDimitry Andric 848e8d8bef9SDimitry Andric const Value *Object = getUnderlyingObject(Loc.Ptr); 8490b57cec5SDimitry Andric 8500b57cec5SDimitry Andric // Calls marked 'tail' cannot read or write allocas from the current frame 8510b57cec5SDimitry Andric // because the current frame might be destroyed by the time they run. However, 8520b57cec5SDimitry Andric // a tail call may use an alloca with byval. Calling with byval copies the 8530b57cec5SDimitry Andric // contents of the alloca into argument registers or stack slots, so there is 8540b57cec5SDimitry Andric // no lifetime issue. 8550b57cec5SDimitry Andric if (isa<AllocaInst>(Object)) 8560b57cec5SDimitry Andric if (const CallInst *CI = dyn_cast<CallInst>(Call)) 8570b57cec5SDimitry Andric if (CI->isTailCall() && 8580b57cec5SDimitry Andric !CI->getAttributes().hasAttrSomewhere(Attribute::ByVal)) 8590b57cec5SDimitry Andric return ModRefInfo::NoModRef; 8600b57cec5SDimitry Andric 8610b57cec5SDimitry Andric // Stack restore is able to modify unescaped dynamic allocas. Assume it may 8620b57cec5SDimitry Andric // modify them even though the alloca is not escaped. 8630b57cec5SDimitry Andric if (auto *AI = dyn_cast<AllocaInst>(Object)) 8640b57cec5SDimitry Andric if (!AI->isStaticAlloca() && isIntrinsicCall(Call, Intrinsic::stackrestore)) 8650b57cec5SDimitry Andric return ModRefInfo::Mod; 8660b57cec5SDimitry Andric 8670b57cec5SDimitry Andric // If the pointer is to a locally allocated object that does not escape, 8680b57cec5SDimitry Andric // then the call can not mod/ref the pointer unless the call takes the pointer 8690b57cec5SDimitry Andric // as an argument, and itself doesn't capture it. 8700b57cec5SDimitry Andric if (!isa<Constant>(Object) && Call != Object && 871349cc55cSDimitry Andric AAQI.CI->isNotCapturedBeforeOrAt(Object, Call)) { 8720b57cec5SDimitry Andric 8730b57cec5SDimitry Andric // Optimistically assume that call doesn't touch Object and check this 8740b57cec5SDimitry Andric // assumption in the following loop. 8750b57cec5SDimitry Andric ModRefInfo Result = ModRefInfo::NoModRef; 8760b57cec5SDimitry Andric 8770b57cec5SDimitry Andric unsigned OperandNo = 0; 8780b57cec5SDimitry Andric for (auto CI = Call->data_operands_begin(), CE = Call->data_operands_end(); 8790b57cec5SDimitry Andric CI != CE; ++CI, ++OperandNo) { 8800b57cec5SDimitry Andric // Only look at the no-capture or byval pointer arguments. If this 8810b57cec5SDimitry Andric // pointer were passed to arguments that were neither of these, then it 8820b57cec5SDimitry Andric // couldn't be no-capture. 8830b57cec5SDimitry Andric if (!(*CI)->getType()->isPointerTy() || 884349cc55cSDimitry Andric (!Call->doesNotCapture(OperandNo) && OperandNo < Call->arg_size() && 8850b57cec5SDimitry Andric !Call->isByValArgument(OperandNo))) 8860b57cec5SDimitry Andric continue; 8870b57cec5SDimitry Andric 8880b57cec5SDimitry Andric // Call doesn't access memory through this operand, so we don't care 8890b57cec5SDimitry Andric // if it aliases with Object. 8900b57cec5SDimitry Andric if (Call->doesNotAccessMemory(OperandNo)) 8910b57cec5SDimitry Andric continue; 8920b57cec5SDimitry Andric 8930b57cec5SDimitry Andric // If this is a no-capture pointer argument, see if we can tell that it 8940b57cec5SDimitry Andric // is impossible to alias the pointer we're checking. 895bdd1243dSDimitry Andric AliasResult AR = 896bdd1243dSDimitry Andric AAQI.AAR.alias(MemoryLocation::getBeforeOrAfter(*CI), 897e8d8bef9SDimitry Andric MemoryLocation::getBeforeOrAfter(Object), AAQI); 8980b57cec5SDimitry Andric // Operand doesn't alias 'Object', continue looking for other aliases 899fe6060f1SDimitry Andric if (AR == AliasResult::NoAlias) 9000b57cec5SDimitry Andric continue; 9010b57cec5SDimitry Andric // Operand aliases 'Object', but call doesn't modify it. Strengthen 9020b57cec5SDimitry Andric // initial assumption and keep looking in case if there are more aliases. 9030b57cec5SDimitry Andric if (Call->onlyReadsMemory(OperandNo)) { 904bdd1243dSDimitry Andric Result |= ModRefInfo::Ref; 9050b57cec5SDimitry Andric continue; 9060b57cec5SDimitry Andric } 9070b57cec5SDimitry Andric // Operand aliases 'Object' but call only writes into it. 90804eeddc0SDimitry Andric if (Call->onlyWritesMemory(OperandNo)) { 909bdd1243dSDimitry Andric Result |= ModRefInfo::Mod; 9100b57cec5SDimitry Andric continue; 9110b57cec5SDimitry Andric } 9120b57cec5SDimitry Andric // This operand aliases 'Object' and call reads and writes into it. 9130b57cec5SDimitry Andric // Setting ModRef will not yield an early return below, MustAlias is not 9140b57cec5SDimitry Andric // used further. 9150b57cec5SDimitry Andric Result = ModRefInfo::ModRef; 9160b57cec5SDimitry Andric break; 9170b57cec5SDimitry Andric } 9180b57cec5SDimitry Andric 9190b57cec5SDimitry Andric // Early return if we improved mod ref information 920bdd1243dSDimitry Andric if (!isModAndRefSet(Result)) 921bdd1243dSDimitry Andric return Result; 9220b57cec5SDimitry Andric } 9230b57cec5SDimitry Andric 9245ffd83dbSDimitry Andric // If the call is malloc/calloc like, we can assume that it doesn't 9250b57cec5SDimitry Andric // modify any IR visible value. This is only valid because we assume these 9260b57cec5SDimitry Andric // routines do not read values visible in the IR. TODO: Consider special 9270b57cec5SDimitry Andric // casing realloc and strdup routines which access only their arguments as 9280b57cec5SDimitry Andric // well. Or alternatively, replace all of this with inaccessiblememonly once 9290b57cec5SDimitry Andric // that's implemented fully. 9300b57cec5SDimitry Andric if (isMallocOrCallocLikeFn(Call, &TLI)) { 9310b57cec5SDimitry Andric // Be conservative if the accessed pointer may alias the allocation - 9320b57cec5SDimitry Andric // fallback to the generic handling below. 933bdd1243dSDimitry Andric if (AAQI.AAR.alias(MemoryLocation::getBeforeOrAfter(Call), Loc, AAQI) == 934bdd1243dSDimitry Andric AliasResult::NoAlias) 9350b57cec5SDimitry Andric return ModRefInfo::NoModRef; 9360b57cec5SDimitry Andric } 9370b57cec5SDimitry Andric 9380b57cec5SDimitry Andric // Like assumes, invariant.start intrinsics were also marked as arbitrarily 9390b57cec5SDimitry Andric // writing so that proper control dependencies are maintained but they never 9400b57cec5SDimitry Andric // mod any particular memory location visible to the IR. 9410b57cec5SDimitry Andric // *Unlike* assumes (which are now modeled as NoModRef), invariant.start 9420b57cec5SDimitry Andric // intrinsic is now modeled as reading memory. This prevents hoisting the 9430b57cec5SDimitry Andric // invariant.start intrinsic over stores. Consider: 9440b57cec5SDimitry Andric // *ptr = 40; 9450b57cec5SDimitry Andric // *ptr = 50; 9460b57cec5SDimitry Andric // invariant_start(ptr) 9470b57cec5SDimitry Andric // int val = *ptr; 9480b57cec5SDimitry Andric // print(val); 9490b57cec5SDimitry Andric // 9500b57cec5SDimitry Andric // This cannot be transformed to: 9510b57cec5SDimitry Andric // 9520b57cec5SDimitry Andric // *ptr = 40; 9530b57cec5SDimitry Andric // invariant_start(ptr) 9540b57cec5SDimitry Andric // *ptr = 50; 9550b57cec5SDimitry Andric // int val = *ptr; 9560b57cec5SDimitry Andric // print(val); 9570b57cec5SDimitry Andric // 9580b57cec5SDimitry Andric // The transformation will cause the second store to be ignored (based on 9590b57cec5SDimitry Andric // rules of invariant.start) and print 40, while the first program always 9600b57cec5SDimitry Andric // prints 50. 9610b57cec5SDimitry Andric if (isIntrinsicCall(Call, Intrinsic::invariant_start)) 9620b57cec5SDimitry Andric return ModRefInfo::Ref; 9630b57cec5SDimitry Andric 9640b57cec5SDimitry Andric // The AAResultBase base class has some smarts, lets use them. 9650b57cec5SDimitry Andric return AAResultBase::getModRefInfo(Call, Loc, AAQI); 9660b57cec5SDimitry Andric } 9670b57cec5SDimitry Andric 9680b57cec5SDimitry Andric ModRefInfo BasicAAResult::getModRefInfo(const CallBase *Call1, 9690b57cec5SDimitry Andric const CallBase *Call2, 9700b57cec5SDimitry Andric AAQueryInfo &AAQI) { 971fe6060f1SDimitry Andric // Guard intrinsics are marked as arbitrarily writing so that proper control 972fe6060f1SDimitry Andric // dependencies are maintained but they never mods any particular memory 973fe6060f1SDimitry Andric // location. 9740b57cec5SDimitry Andric // 9750b57cec5SDimitry Andric // *Unlike* assumes, guard intrinsics are modeled as reading memory since the 9760b57cec5SDimitry Andric // heap state at the point the guard is issued needs to be consistent in case 9770b57cec5SDimitry Andric // the guard invokes the "deopt" continuation. 9780b57cec5SDimitry Andric 9790b57cec5SDimitry Andric // NB! This function is *not* commutative, so we special case two 9800b57cec5SDimitry Andric // possibilities for guard intrinsics. 9810b57cec5SDimitry Andric 9820b57cec5SDimitry Andric if (isIntrinsicCall(Call1, Intrinsic::experimental_guard)) 983bdd1243dSDimitry Andric return isModSet(getMemoryEffects(Call2, AAQI).getModRef()) 9840b57cec5SDimitry Andric ? ModRefInfo::Ref 9850b57cec5SDimitry Andric : ModRefInfo::NoModRef; 9860b57cec5SDimitry Andric 9870b57cec5SDimitry Andric if (isIntrinsicCall(Call2, Intrinsic::experimental_guard)) 988bdd1243dSDimitry Andric return isModSet(getMemoryEffects(Call1, AAQI).getModRef()) 9890b57cec5SDimitry Andric ? ModRefInfo::Mod 9900b57cec5SDimitry Andric : ModRefInfo::NoModRef; 9910b57cec5SDimitry Andric 9920b57cec5SDimitry Andric // The AAResultBase base class has some smarts, lets use them. 9930b57cec5SDimitry Andric return AAResultBase::getModRefInfo(Call1, Call2, AAQI); 9940b57cec5SDimitry Andric } 9950b57cec5SDimitry Andric 996fe6060f1SDimitry Andric /// Return true if we know V to the base address of the corresponding memory 997fe6060f1SDimitry Andric /// object. This implies that any address less than V must be out of bounds 998fe6060f1SDimitry Andric /// for the underlying object. Note that just being isIdentifiedObject() is 999fe6060f1SDimitry Andric /// not enough - For example, a negative offset from a noalias argument or call 1000fe6060f1SDimitry Andric /// can be inbounds w.r.t the actual underlying object. 1001fe6060f1SDimitry Andric static bool isBaseOfObject(const Value *V) { 1002fe6060f1SDimitry Andric // TODO: We can handle other cases here 1003fe6060f1SDimitry Andric // 1) For GC languages, arguments to functions are often required to be 1004fe6060f1SDimitry Andric // base pointers. 1005fe6060f1SDimitry Andric // 2) Result of allocation routines are often base pointers. Leverage TLI. 1006fe6060f1SDimitry Andric return (isa<AllocaInst>(V) || isa<GlobalVariable>(V)); 10070b57cec5SDimitry Andric } 10080b57cec5SDimitry Andric 10090b57cec5SDimitry Andric /// Provides a bunch of ad-hoc rules to disambiguate a GEP instruction against 10100b57cec5SDimitry Andric /// another pointer. 10110b57cec5SDimitry Andric /// 10120b57cec5SDimitry Andric /// We know that V1 is a GEP, but we don't know anything about V2. 1013e8d8bef9SDimitry Andric /// UnderlyingV1 is getUnderlyingObject(GEP1), UnderlyingV2 is the same for 10140b57cec5SDimitry Andric /// V2. 10150b57cec5SDimitry Andric AliasResult BasicAAResult::aliasGEP( 1016fe6060f1SDimitry Andric const GEPOperator *GEP1, LocationSize V1Size, 1017fe6060f1SDimitry Andric const Value *V2, LocationSize V2Size, 10180b57cec5SDimitry Andric const Value *UnderlyingV1, const Value *UnderlyingV2, AAQueryInfo &AAQI) { 1019fe6060f1SDimitry Andric if (!V1Size.hasValue() && !V2Size.hasValue()) { 1020fe6060f1SDimitry Andric // TODO: This limitation exists for compile-time reasons. Relax it if we 1021fe6060f1SDimitry Andric // can avoid exponential pathological cases. 1022fe6060f1SDimitry Andric if (!isa<GEPOperator>(V2)) 1023fe6060f1SDimitry Andric return AliasResult::MayAlias; 1024fe6060f1SDimitry Andric 1025fe6060f1SDimitry Andric // If both accesses have unknown size, we can only check whether the base 1026fe6060f1SDimitry Andric // objects don't alias. 1027bdd1243dSDimitry Andric AliasResult BaseAlias = 1028bdd1243dSDimitry Andric AAQI.AAR.alias(MemoryLocation::getBeforeOrAfter(UnderlyingV1), 1029fe6060f1SDimitry Andric MemoryLocation::getBeforeOrAfter(UnderlyingV2), AAQI); 1030fe6060f1SDimitry Andric return BaseAlias == AliasResult::NoAlias ? AliasResult::NoAlias 1031fe6060f1SDimitry Andric : AliasResult::MayAlias; 1032fe6060f1SDimitry Andric } 1033fe6060f1SDimitry Andric 1034e8d8bef9SDimitry Andric DecomposedGEP DecompGEP1 = DecomposeGEPExpression(GEP1, DL, &AC, DT); 1035e8d8bef9SDimitry Andric DecomposedGEP DecompGEP2 = DecomposeGEPExpression(V2, DL, &AC, DT); 10360b57cec5SDimitry Andric 1037349cc55cSDimitry Andric // Bail if we were not able to decompose anything. 1038349cc55cSDimitry Andric if (DecompGEP1.Base == GEP1 && DecompGEP2.Base == V2) 1039fe6060f1SDimitry Andric return AliasResult::MayAlias; 10405ffd83dbSDimitry Andric 10410b57cec5SDimitry Andric // Subtract the GEP2 pointer from the GEP1 pointer to find out their 10420b57cec5SDimitry Andric // symbolic difference. 1043bdd1243dSDimitry Andric subtractDecomposedGEPs(DecompGEP1, DecompGEP2, AAQI); 10440b57cec5SDimitry Andric 1045fe6060f1SDimitry Andric // If an inbounds GEP would have to start from an out of bounds address 1046fe6060f1SDimitry Andric // for the two to alias, then we can assume noalias. 1047fe6060f1SDimitry Andric if (*DecompGEP1.InBounds && DecompGEP1.VarIndices.empty() && 1048fe6060f1SDimitry Andric V2Size.hasValue() && DecompGEP1.Offset.sge(V2Size.getValue()) && 1049fe6060f1SDimitry Andric isBaseOfObject(DecompGEP2.Base)) 1050fe6060f1SDimitry Andric return AliasResult::NoAlias; 10510b57cec5SDimitry Andric 1052fe6060f1SDimitry Andric if (isa<GEPOperator>(V2)) { 1053fe6060f1SDimitry Andric // Symmetric case to above. 1054fe6060f1SDimitry Andric if (*DecompGEP2.InBounds && DecompGEP1.VarIndices.empty() && 1055fe6060f1SDimitry Andric V1Size.hasValue() && DecompGEP1.Offset.sle(-V1Size.getValue()) && 1056fe6060f1SDimitry Andric isBaseOfObject(DecompGEP1.Base)) 1057fe6060f1SDimitry Andric return AliasResult::NoAlias; 10580b57cec5SDimitry Andric } 10590b57cec5SDimitry Andric 1060fe6060f1SDimitry Andric // For GEPs with identical offsets, we can preserve the size and AAInfo 1061fe6060f1SDimitry Andric // when performing the alias check on the underlying objects. 1062e8d8bef9SDimitry Andric if (DecompGEP1.Offset == 0 && DecompGEP1.VarIndices.empty()) 1063bdd1243dSDimitry Andric return AAQI.AAR.alias(MemoryLocation(DecompGEP1.Base, V1Size), 1064bdd1243dSDimitry Andric MemoryLocation(DecompGEP2.Base, V2Size), AAQI); 1065fe6060f1SDimitry Andric 1066fe6060f1SDimitry Andric // Do the base pointers alias? 1067bdd1243dSDimitry Andric AliasResult BaseAlias = 1068bdd1243dSDimitry Andric AAQI.AAR.alias(MemoryLocation::getBeforeOrAfter(DecompGEP1.Base), 1069349cc55cSDimitry Andric MemoryLocation::getBeforeOrAfter(DecompGEP2.Base), AAQI); 1070fe6060f1SDimitry Andric 1071fe6060f1SDimitry Andric // If we get a No or May, then return it immediately, no amount of analysis 1072fe6060f1SDimitry Andric // will improve this situation. 1073fe6060f1SDimitry Andric if (BaseAlias != AliasResult::MustAlias) { 1074fe6060f1SDimitry Andric assert(BaseAlias == AliasResult::NoAlias || 1075fe6060f1SDimitry Andric BaseAlias == AliasResult::MayAlias); 1076fe6060f1SDimitry Andric return BaseAlias; 1077fe6060f1SDimitry Andric } 10780b57cec5SDimitry Andric 10790b57cec5SDimitry Andric // If there is a constant difference between the pointers, but the difference 10800b57cec5SDimitry Andric // is less than the size of the associated memory object, then we know 10810b57cec5SDimitry Andric // that the objects are partially overlapping. If the difference is 10820b57cec5SDimitry Andric // greater, we know they do not overlap. 1083349cc55cSDimitry Andric if (DecompGEP1.VarIndices.empty()) { 1084fe6060f1SDimitry Andric APInt &Off = DecompGEP1.Offset; 1085fe6060f1SDimitry Andric 1086fe6060f1SDimitry Andric // Initialize for Off >= 0 (V2 <= GEP1) case. 1087fe6060f1SDimitry Andric const Value *LeftPtr = V2; 1088fe6060f1SDimitry Andric const Value *RightPtr = GEP1; 1089fe6060f1SDimitry Andric LocationSize VLeftSize = V2Size; 1090fe6060f1SDimitry Andric LocationSize VRightSize = V1Size; 1091fe6060f1SDimitry Andric const bool Swapped = Off.isNegative(); 1092fe6060f1SDimitry Andric 1093fe6060f1SDimitry Andric if (Swapped) { 1094fe6060f1SDimitry Andric // Swap if we have the situation where: 10950b57cec5SDimitry Andric // + + 10960b57cec5SDimitry Andric // | BaseOffset | 10970b57cec5SDimitry Andric // ---------------->| 10980b57cec5SDimitry Andric // |-->V1Size |-------> V2Size 10990b57cec5SDimitry Andric // GEP1 V2 1100fe6060f1SDimitry Andric std::swap(LeftPtr, RightPtr); 1101fe6060f1SDimitry Andric std::swap(VLeftSize, VRightSize); 1102fe6060f1SDimitry Andric Off = -Off; 11030b57cec5SDimitry Andric } 1104fe6060f1SDimitry Andric 1105349cc55cSDimitry Andric if (!VLeftSize.hasValue()) 1106349cc55cSDimitry Andric return AliasResult::MayAlias; 1107349cc55cSDimitry Andric 1108fe6060f1SDimitry Andric const uint64_t LSize = VLeftSize.getValue(); 1109fe6060f1SDimitry Andric if (Off.ult(LSize)) { 1110fe6060f1SDimitry Andric // Conservatively drop processing if a phi was visited and/or offset is 1111fe6060f1SDimitry Andric // too big. 1112fe6060f1SDimitry Andric AliasResult AR = AliasResult::PartialAlias; 1113fe6060f1SDimitry Andric if (VRightSize.hasValue() && Off.ule(INT32_MAX) && 1114fe6060f1SDimitry Andric (Off + VRightSize.getValue()).ule(LSize)) { 1115fe6060f1SDimitry Andric // Memory referenced by right pointer is nested. Save the offset in 1116fe6060f1SDimitry Andric // cache. Note that originally offset estimated as GEP1-V2, but 1117fe6060f1SDimitry Andric // AliasResult contains the shift that represents GEP1+Offset=V2. 1118fe6060f1SDimitry Andric AR.setOffset(-Off.getSExtValue()); 1119fe6060f1SDimitry Andric AR.swap(Swapped); 1120fe6060f1SDimitry Andric } 1121fe6060f1SDimitry Andric return AR; 1122fe6060f1SDimitry Andric } 1123fe6060f1SDimitry Andric return AliasResult::NoAlias; 11240b57cec5SDimitry Andric } 11250b57cec5SDimitry Andric 1126349cc55cSDimitry Andric // We need to know both acess sizes for all the following heuristics. 1127349cc55cSDimitry Andric if (!V1Size.hasValue() || !V2Size.hasValue()) 1128349cc55cSDimitry Andric return AliasResult::MayAlias; 1129349cc55cSDimitry Andric 1130e8d8bef9SDimitry Andric APInt GCD; 1131349cc55cSDimitry Andric ConstantRange OffsetRange = ConstantRange(DecompGEP1.Offset); 11320b57cec5SDimitry Andric for (unsigned i = 0, e = DecompGEP1.VarIndices.size(); i != e; ++i) { 1133349cc55cSDimitry Andric const VariableGEPIndex &Index = DecompGEP1.VarIndices[i]; 1134349cc55cSDimitry Andric const APInt &Scale = Index.Scale; 1135349cc55cSDimitry Andric APInt ScaleForGCD = Scale; 1136349cc55cSDimitry Andric if (!Index.IsNSW) 1137fe6060f1SDimitry Andric ScaleForGCD = APInt::getOneBitSet(Scale.getBitWidth(), 1138fe6060f1SDimitry Andric Scale.countTrailingZeros()); 1139fe6060f1SDimitry Andric 1140e8d8bef9SDimitry Andric if (i == 0) 1141fe6060f1SDimitry Andric GCD = ScaleForGCD.abs(); 1142e8d8bef9SDimitry Andric else 1143fe6060f1SDimitry Andric GCD = APIntOps::GreatestCommonDivisor(GCD, ScaleForGCD.abs()); 11440b57cec5SDimitry Andric 114504eeddc0SDimitry Andric ConstantRange CR = computeConstantRange(Index.Val.V, /* ForSigned */ false, 114604eeddc0SDimitry Andric true, &AC, Index.CxtI); 1147349cc55cSDimitry Andric KnownBits Known = 1148349cc55cSDimitry Andric computeKnownBits(Index.Val.V, DL, 0, &AC, Index.CxtI, DT); 1149349cc55cSDimitry Andric CR = CR.intersectWith( 1150349cc55cSDimitry Andric ConstantRange::fromKnownBits(Known, /* Signed */ true), 1151349cc55cSDimitry Andric ConstantRange::Signed); 1152349cc55cSDimitry Andric CR = Index.Val.evaluateWith(CR).sextOrTrunc(OffsetRange.getBitWidth()); 11530b57cec5SDimitry Andric 1154349cc55cSDimitry Andric assert(OffsetRange.getBitWidth() == Scale.getBitWidth() && 1155349cc55cSDimitry Andric "Bit widths are normalized to MaxIndexSize"); 1156349cc55cSDimitry Andric if (Index.IsNSW) 1157349cc55cSDimitry Andric OffsetRange = OffsetRange.add(CR.smul_sat(ConstantRange(Scale))); 1158349cc55cSDimitry Andric else 1159349cc55cSDimitry Andric OffsetRange = OffsetRange.add(CR.smul_fast(ConstantRange(Scale))); 11600b57cec5SDimitry Andric } 11610b57cec5SDimitry Andric 1162e8d8bef9SDimitry Andric // We now have accesses at two offsets from the same base: 1163e8d8bef9SDimitry Andric // 1. (...)*GCD + DecompGEP1.Offset with size V1Size 1164e8d8bef9SDimitry Andric // 2. 0 with size V2Size 1165e8d8bef9SDimitry Andric // Using arithmetic modulo GCD, the accesses are at 1166e8d8bef9SDimitry Andric // [ModOffset..ModOffset+V1Size) and [0..V2Size). If the first access fits 1167e8d8bef9SDimitry Andric // into the range [V2Size..GCD), then we know they cannot overlap. 1168e8d8bef9SDimitry Andric APInt ModOffset = DecompGEP1.Offset.srem(GCD); 1169e8d8bef9SDimitry Andric if (ModOffset.isNegative()) 1170e8d8bef9SDimitry Andric ModOffset += GCD; // We want mod, not rem. 1171349cc55cSDimitry Andric if (ModOffset.uge(V2Size.getValue()) && 1172e8d8bef9SDimitry Andric (GCD - ModOffset).uge(V1Size.getValue())) 1173fe6060f1SDimitry Andric return AliasResult::NoAlias; 11740b57cec5SDimitry Andric 1175349cc55cSDimitry Andric // Compute ranges of potentially accessed bytes for both accesses. If the 1176349cc55cSDimitry Andric // interseciton is empty, there can be no overlap. 1177349cc55cSDimitry Andric unsigned BW = OffsetRange.getBitWidth(); 1178349cc55cSDimitry Andric ConstantRange Range1 = OffsetRange.add( 1179349cc55cSDimitry Andric ConstantRange(APInt(BW, 0), APInt(BW, V1Size.getValue()))); 1180349cc55cSDimitry Andric ConstantRange Range2 = 1181349cc55cSDimitry Andric ConstantRange(APInt(BW, 0), APInt(BW, V2Size.getValue())); 1182349cc55cSDimitry Andric if (Range1.intersectWith(Range2).isEmptySet()) 1183fe6060f1SDimitry Andric return AliasResult::NoAlias; 1184e8d8bef9SDimitry Andric 1185349cc55cSDimitry Andric // Try to determine the range of values for VarIndex such that 1186349cc55cSDimitry Andric // VarIndex <= -MinAbsVarIndex || MinAbsVarIndex <= VarIndex. 1187bdd1243dSDimitry Andric std::optional<APInt> MinAbsVarIndex; 1188e8d8bef9SDimitry Andric if (DecompGEP1.VarIndices.size() == 1) { 1189349cc55cSDimitry Andric // VarIndex = Scale*V. 1190e8d8bef9SDimitry Andric const VariableGEPIndex &Var = DecompGEP1.VarIndices[0]; 1191349cc55cSDimitry Andric if (Var.Val.TruncBits == 0 && 1192349cc55cSDimitry Andric isKnownNonZero(Var.Val.V, DL, 0, &AC, Var.CxtI, DT)) { 119381ad6265SDimitry Andric // If V != 0, then abs(VarIndex) > 0. 119481ad6265SDimitry Andric MinAbsVarIndex = APInt(Var.Scale.getBitWidth(), 1); 119581ad6265SDimitry Andric 119681ad6265SDimitry Andric // Check if abs(V*Scale) >= abs(Scale) holds in the presence of 119781ad6265SDimitry Andric // potentially wrapping math. 119881ad6265SDimitry Andric auto MultiplyByScaleNoWrap = [](const VariableGEPIndex &Var) { 119981ad6265SDimitry Andric if (Var.IsNSW) 120081ad6265SDimitry Andric return true; 120181ad6265SDimitry Andric 120281ad6265SDimitry Andric int ValOrigBW = Var.Val.V->getType()->getPrimitiveSizeInBits(); 120381ad6265SDimitry Andric // If Scale is small enough so that abs(V*Scale) >= abs(Scale) holds. 120481ad6265SDimitry Andric // The max value of abs(V) is 2^ValOrigBW - 1. Multiplying with a 120581ad6265SDimitry Andric // constant smaller than 2^(bitwidth(Val) - ValOrigBW) won't wrap. 120681ad6265SDimitry Andric int MaxScaleValueBW = Var.Val.getBitWidth() - ValOrigBW; 120781ad6265SDimitry Andric if (MaxScaleValueBW <= 0) 120881ad6265SDimitry Andric return false; 120981ad6265SDimitry Andric return Var.Scale.ule( 121081ad6265SDimitry Andric APInt::getMaxValue(MaxScaleValueBW).zext(Var.Scale.getBitWidth())); 121181ad6265SDimitry Andric }; 121281ad6265SDimitry Andric // Refine MinAbsVarIndex, if abs(Scale*V) >= abs(Scale) holds in the 121381ad6265SDimitry Andric // presence of potentially wrapping math. 121481ad6265SDimitry Andric if (MultiplyByScaleNoWrap(Var)) { 1215349cc55cSDimitry Andric // If V != 0 then abs(VarIndex) >= abs(Scale). 1216e8d8bef9SDimitry Andric MinAbsVarIndex = Var.Scale.abs(); 1217349cc55cSDimitry Andric } 121881ad6265SDimitry Andric } 1219e8d8bef9SDimitry Andric } else if (DecompGEP1.VarIndices.size() == 2) { 1220e8d8bef9SDimitry Andric // VarIndex = Scale*V0 + (-Scale)*V1. 1221e8d8bef9SDimitry Andric // If V0 != V1 then abs(VarIndex) >= abs(Scale). 1222bdd1243dSDimitry Andric // Check that MayBeCrossIteration is false, to avoid reasoning about 1223e8d8bef9SDimitry Andric // inequality of values across loop iterations. 1224e8d8bef9SDimitry Andric const VariableGEPIndex &Var0 = DecompGEP1.VarIndices[0]; 1225e8d8bef9SDimitry Andric const VariableGEPIndex &Var1 = DecompGEP1.VarIndices[1]; 1226349cc55cSDimitry Andric if (Var0.Scale == -Var1.Scale && Var0.Val.TruncBits == 0 && 1227bdd1243dSDimitry Andric Var0.Val.hasSameCastsAs(Var1.Val) && !AAQI.MayBeCrossIteration && 1228349cc55cSDimitry Andric isKnownNonEqual(Var0.Val.V, Var1.Val.V, DL, &AC, /* CxtI */ nullptr, 1229349cc55cSDimitry Andric DT)) 1230e8d8bef9SDimitry Andric MinAbsVarIndex = Var0.Scale.abs(); 1231e8d8bef9SDimitry Andric } 1232e8d8bef9SDimitry Andric 1233e8d8bef9SDimitry Andric if (MinAbsVarIndex) { 1234e8d8bef9SDimitry Andric // The constant offset will have added at least +/-MinAbsVarIndex to it. 1235e8d8bef9SDimitry Andric APInt OffsetLo = DecompGEP1.Offset - *MinAbsVarIndex; 1236e8d8bef9SDimitry Andric APInt OffsetHi = DecompGEP1.Offset + *MinAbsVarIndex; 1237349cc55cSDimitry Andric // We know that Offset <= OffsetLo || Offset >= OffsetHi 1238e8d8bef9SDimitry Andric if (OffsetLo.isNegative() && (-OffsetLo).uge(V1Size.getValue()) && 1239e8d8bef9SDimitry Andric OffsetHi.isNonNegative() && OffsetHi.uge(V2Size.getValue())) 1240fe6060f1SDimitry Andric return AliasResult::NoAlias; 1241e8d8bef9SDimitry Andric } 12420b57cec5SDimitry Andric 1243bdd1243dSDimitry Andric if (constantOffsetHeuristic(DecompGEP1, V1Size, V2Size, &AC, DT, AAQI)) 1244fe6060f1SDimitry Andric return AliasResult::NoAlias; 12450b57cec5SDimitry Andric 12460b57cec5SDimitry Andric // Statically, we can see that the base objects are the same, but the 12470b57cec5SDimitry Andric // pointers have dynamic offsets which we can't resolve. And none of our 12480b57cec5SDimitry Andric // little tricks above worked. 1249fe6060f1SDimitry Andric return AliasResult::MayAlias; 12500b57cec5SDimitry Andric } 12510b57cec5SDimitry Andric 12520b57cec5SDimitry Andric static AliasResult MergeAliasResults(AliasResult A, AliasResult B) { 12530b57cec5SDimitry Andric // If the results agree, take it. 12540b57cec5SDimitry Andric if (A == B) 12550b57cec5SDimitry Andric return A; 12560b57cec5SDimitry Andric // A mix of PartialAlias and MustAlias is PartialAlias. 1257fe6060f1SDimitry Andric if ((A == AliasResult::PartialAlias && B == AliasResult::MustAlias) || 1258fe6060f1SDimitry Andric (B == AliasResult::PartialAlias && A == AliasResult::MustAlias)) 1259fe6060f1SDimitry Andric return AliasResult::PartialAlias; 12600b57cec5SDimitry Andric // Otherwise, we don't know anything. 1261fe6060f1SDimitry Andric return AliasResult::MayAlias; 12620b57cec5SDimitry Andric } 12630b57cec5SDimitry Andric 12640b57cec5SDimitry Andric /// Provides a bunch of ad-hoc rules to disambiguate a Select instruction 12650b57cec5SDimitry Andric /// against another. 12660b57cec5SDimitry Andric AliasResult 12670b57cec5SDimitry Andric BasicAAResult::aliasSelect(const SelectInst *SI, LocationSize SISize, 1268fe6060f1SDimitry Andric const Value *V2, LocationSize V2Size, 1269e8d8bef9SDimitry Andric AAQueryInfo &AAQI) { 12700b57cec5SDimitry Andric // If the values are Selects with the same condition, we can do a more precise 12710b57cec5SDimitry Andric // check: just check for aliases between the values on corresponding arms. 12720b57cec5SDimitry Andric if (const SelectInst *SI2 = dyn_cast<SelectInst>(V2)) 1273bdd1243dSDimitry Andric if (isValueEqualInPotentialCycles(SI->getCondition(), SI2->getCondition(), 1274bdd1243dSDimitry Andric AAQI)) { 1275bdd1243dSDimitry Andric AliasResult Alias = 1276bdd1243dSDimitry Andric AAQI.AAR.alias(MemoryLocation(SI->getTrueValue(), SISize), 1277fe6060f1SDimitry Andric MemoryLocation(SI2->getTrueValue(), V2Size), AAQI); 1278fe6060f1SDimitry Andric if (Alias == AliasResult::MayAlias) 1279fe6060f1SDimitry Andric return AliasResult::MayAlias; 1280bdd1243dSDimitry Andric AliasResult ThisAlias = 1281bdd1243dSDimitry Andric AAQI.AAR.alias(MemoryLocation(SI->getFalseValue(), SISize), 1282fe6060f1SDimitry Andric MemoryLocation(SI2->getFalseValue(), V2Size), AAQI); 12830b57cec5SDimitry Andric return MergeAliasResults(ThisAlias, Alias); 12840b57cec5SDimitry Andric } 12850b57cec5SDimitry Andric 12860b57cec5SDimitry Andric // If both arms of the Select node NoAlias or MustAlias V2, then returns 12870b57cec5SDimitry Andric // NoAlias / MustAlias. Otherwise, returns MayAlias. 1288bdd1243dSDimitry Andric AliasResult Alias = AAQI.AAR.alias(MemoryLocation(SI->getTrueValue(), SISize), 128981ad6265SDimitry Andric MemoryLocation(V2, V2Size), AAQI); 1290fe6060f1SDimitry Andric if (Alias == AliasResult::MayAlias) 1291fe6060f1SDimitry Andric return AliasResult::MayAlias; 12920b57cec5SDimitry Andric 129381ad6265SDimitry Andric AliasResult ThisAlias = 1294bdd1243dSDimitry Andric AAQI.AAR.alias(MemoryLocation(SI->getFalseValue(), SISize), 129581ad6265SDimitry Andric MemoryLocation(V2, V2Size), AAQI); 12960b57cec5SDimitry Andric return MergeAliasResults(ThisAlias, Alias); 12970b57cec5SDimitry Andric } 12980b57cec5SDimitry Andric 12990b57cec5SDimitry Andric /// Provide a bunch of ad-hoc rules to disambiguate a PHI instruction against 13000b57cec5SDimitry Andric /// another. 13010b57cec5SDimitry Andric AliasResult BasicAAResult::aliasPHI(const PHINode *PN, LocationSize PNSize, 1302fe6060f1SDimitry Andric const Value *V2, LocationSize V2Size, 1303e8d8bef9SDimitry Andric AAQueryInfo &AAQI) { 1304fe6060f1SDimitry Andric if (!PN->getNumIncomingValues()) 1305fe6060f1SDimitry Andric return AliasResult::NoAlias; 13060b57cec5SDimitry Andric // If the values are PHIs in the same block, we can do a more precise 13070b57cec5SDimitry Andric // as well as efficient check: just check for aliases between the values 13080b57cec5SDimitry Andric // on corresponding edges. 13090b57cec5SDimitry Andric if (const PHINode *PN2 = dyn_cast<PHINode>(V2)) 13100b57cec5SDimitry Andric if (PN2->getParent() == PN->getParent()) { 1311bdd1243dSDimitry Andric std::optional<AliasResult> Alias; 13120b57cec5SDimitry Andric for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 1313bdd1243dSDimitry Andric AliasResult ThisAlias = AAQI.AAR.alias( 1314fe6060f1SDimitry Andric MemoryLocation(PN->getIncomingValue(i), PNSize), 1315e8d8bef9SDimitry Andric MemoryLocation( 1316fe6060f1SDimitry Andric PN2->getIncomingValueForBlock(PN->getIncomingBlock(i)), V2Size), 1317e8d8bef9SDimitry Andric AAQI); 1318e8d8bef9SDimitry Andric if (Alias) 1319e8d8bef9SDimitry Andric *Alias = MergeAliasResults(*Alias, ThisAlias); 1320e8d8bef9SDimitry Andric else 1321e8d8bef9SDimitry Andric Alias = ThisAlias; 1322fe6060f1SDimitry Andric if (*Alias == AliasResult::MayAlias) 13230b57cec5SDimitry Andric break; 13240b57cec5SDimitry Andric } 1325e8d8bef9SDimitry Andric return *Alias; 13260b57cec5SDimitry Andric } 13270b57cec5SDimitry Andric 13280b57cec5SDimitry Andric SmallVector<Value *, 4> V1Srcs; 1329e8d8bef9SDimitry Andric // If a phi operand recurses back to the phi, we can still determine NoAlias 1330e8d8bef9SDimitry Andric // if we don't alias the underlying objects of the other phi operands, as we 1331e8d8bef9SDimitry Andric // know that the recursive phi needs to be based on them in some way. 13320b57cec5SDimitry Andric bool isRecursive = false; 1333979e22ffSDimitry Andric auto CheckForRecPhi = [&](Value *PV) { 1334979e22ffSDimitry Andric if (!EnableRecPhiAnalysis) 1335979e22ffSDimitry Andric return false; 1336e8d8bef9SDimitry Andric if (getUnderlyingObject(PV) == PN) { 1337979e22ffSDimitry Andric isRecursive = true; 1338979e22ffSDimitry Andric return true; 1339979e22ffSDimitry Andric } 1340979e22ffSDimitry Andric return false; 1341979e22ffSDimitry Andric }; 1342979e22ffSDimitry Andric 13430b57cec5SDimitry Andric SmallPtrSet<Value *, 4> UniqueSrc; 1344fe6060f1SDimitry Andric Value *OnePhi = nullptr; 13450b57cec5SDimitry Andric for (Value *PV1 : PN->incoming_values()) { 1346bdd1243dSDimitry Andric // Skip the phi itself being the incoming value. 1347bdd1243dSDimitry Andric if (PV1 == PN) 1348bdd1243dSDimitry Andric continue; 1349bdd1243dSDimitry Andric 1350fe6060f1SDimitry Andric if (isa<PHINode>(PV1)) { 1351fe6060f1SDimitry Andric if (OnePhi && OnePhi != PV1) { 1352fe6060f1SDimitry Andric // To control potential compile time explosion, we choose to be 1353fe6060f1SDimitry Andric // conserviate when we have more than one Phi input. It is important 1354fe6060f1SDimitry Andric // that we handle the single phi case as that lets us handle LCSSA 1355fe6060f1SDimitry Andric // phi nodes and (combined with the recursive phi handling) simple 1356fe6060f1SDimitry Andric // pointer induction variable patterns. 1357fe6060f1SDimitry Andric return AliasResult::MayAlias; 1358fe6060f1SDimitry Andric } 1359fe6060f1SDimitry Andric OnePhi = PV1; 1360fe6060f1SDimitry Andric } 13610b57cec5SDimitry Andric 1362979e22ffSDimitry Andric if (CheckForRecPhi(PV1)) 13630b57cec5SDimitry Andric continue; 13640b57cec5SDimitry Andric 13650b57cec5SDimitry Andric if (UniqueSrc.insert(PV1).second) 13660b57cec5SDimitry Andric V1Srcs.push_back(PV1); 13670b57cec5SDimitry Andric } 1368fe6060f1SDimitry Andric 1369fe6060f1SDimitry Andric if (OnePhi && UniqueSrc.size() > 1) 1370fe6060f1SDimitry Andric // Out of an abundance of caution, allow only the trivial lcssa and 1371fe6060f1SDimitry Andric // recursive phi cases. 1372fe6060f1SDimitry Andric return AliasResult::MayAlias; 13730b57cec5SDimitry Andric 13740b57cec5SDimitry Andric // If V1Srcs is empty then that means that the phi has no underlying non-phi 13750b57cec5SDimitry Andric // value. This should only be possible in blocks unreachable from the entry 13760b57cec5SDimitry Andric // block, but return MayAlias just in case. 13770b57cec5SDimitry Andric if (V1Srcs.empty()) 1378fe6060f1SDimitry Andric return AliasResult::MayAlias; 13790b57cec5SDimitry Andric 1380e8d8bef9SDimitry Andric // If this PHI node is recursive, indicate that the pointer may be moved 1381e8d8bef9SDimitry Andric // across iterations. We can only prove NoAlias if different underlying 1382e8d8bef9SDimitry Andric // objects are involved. 13830b57cec5SDimitry Andric if (isRecursive) 1384e8d8bef9SDimitry Andric PNSize = LocationSize::beforeOrAfterPointer(); 13850b57cec5SDimitry Andric 1386e8d8bef9SDimitry Andric // In the recursive alias queries below, we may compare values from two 1387bdd1243dSDimitry Andric // different loop iterations. 1388bdd1243dSDimitry Andric SaveAndRestore SavedMayBeCrossIteration(AAQI.MayBeCrossIteration, true); 1389e8d8bef9SDimitry Andric 1390bdd1243dSDimitry Andric AliasResult Alias = AAQI.AAR.alias(MemoryLocation(V1Srcs[0], PNSize), 1391bdd1243dSDimitry Andric MemoryLocation(V2, V2Size), AAQI); 13920b57cec5SDimitry Andric 13930b57cec5SDimitry Andric // Early exit if the check of the first PHI source against V2 is MayAlias. 13940b57cec5SDimitry Andric // Other results are not possible. 1395fe6060f1SDimitry Andric if (Alias == AliasResult::MayAlias) 1396fe6060f1SDimitry Andric return AliasResult::MayAlias; 13975ffd83dbSDimitry Andric // With recursive phis we cannot guarantee that MustAlias/PartialAlias will 13985ffd83dbSDimitry Andric // remain valid to all elements and needs to conservatively return MayAlias. 1399fe6060f1SDimitry Andric if (isRecursive && Alias != AliasResult::NoAlias) 1400fe6060f1SDimitry Andric return AliasResult::MayAlias; 14010b57cec5SDimitry Andric 14020b57cec5SDimitry Andric // If all sources of the PHI node NoAlias or MustAlias V2, then returns 14030b57cec5SDimitry Andric // NoAlias / MustAlias. Otherwise, returns MayAlias. 14040b57cec5SDimitry Andric for (unsigned i = 1, e = V1Srcs.size(); i != e; ++i) { 14050b57cec5SDimitry Andric Value *V = V1Srcs[i]; 14060b57cec5SDimitry Andric 1407bdd1243dSDimitry Andric AliasResult ThisAlias = AAQI.AAR.alias( 1408bdd1243dSDimitry Andric MemoryLocation(V, PNSize), MemoryLocation(V2, V2Size), AAQI); 14090b57cec5SDimitry Andric Alias = MergeAliasResults(ThisAlias, Alias); 1410fe6060f1SDimitry Andric if (Alias == AliasResult::MayAlias) 14110b57cec5SDimitry Andric break; 14120b57cec5SDimitry Andric } 14130b57cec5SDimitry Andric 14140b57cec5SDimitry Andric return Alias; 14150b57cec5SDimitry Andric } 14160b57cec5SDimitry Andric 14170b57cec5SDimitry Andric /// Provides a bunch of ad-hoc rules to disambiguate in common cases, such as 14180b57cec5SDimitry Andric /// array references. 14190b57cec5SDimitry Andric AliasResult BasicAAResult::aliasCheck(const Value *V1, LocationSize V1Size, 1420e8d8bef9SDimitry Andric const Value *V2, LocationSize V2Size, 1421bdd1243dSDimitry Andric AAQueryInfo &AAQI, 1422bdd1243dSDimitry Andric const Instruction *CtxI) { 14230b57cec5SDimitry Andric // If either of the memory references is empty, it doesn't matter what the 14240b57cec5SDimitry Andric // pointer values are. 14250b57cec5SDimitry Andric if (V1Size.isZero() || V2Size.isZero()) 1426fe6060f1SDimitry Andric return AliasResult::NoAlias; 14270b57cec5SDimitry Andric 14280b57cec5SDimitry Andric // Strip off any casts if they exist. 1429fe6060f1SDimitry Andric V1 = V1->stripPointerCastsForAliasAnalysis(); 1430fe6060f1SDimitry Andric V2 = V2->stripPointerCastsForAliasAnalysis(); 14310b57cec5SDimitry Andric 14320b57cec5SDimitry Andric // If V1 or V2 is undef, the result is NoAlias because we can always pick a 14330b57cec5SDimitry Andric // value for undef that aliases nothing in the program. 14340b57cec5SDimitry Andric if (isa<UndefValue>(V1) || isa<UndefValue>(V2)) 1435fe6060f1SDimitry Andric return AliasResult::NoAlias; 14360b57cec5SDimitry Andric 14370b57cec5SDimitry Andric // Are we checking for alias of the same value? 14380b57cec5SDimitry Andric // Because we look 'through' phi nodes, we could look at "Value" pointers from 14390b57cec5SDimitry Andric // different iterations. We must therefore make sure that this is not the 14400b57cec5SDimitry Andric // case. The function isValueEqualInPotentialCycles ensures that this cannot 14410b57cec5SDimitry Andric // happen by looking at the visited phi nodes and making sure they cannot 14420b57cec5SDimitry Andric // reach the value. 1443bdd1243dSDimitry Andric if (isValueEqualInPotentialCycles(V1, V2, AAQI)) 1444fe6060f1SDimitry Andric return AliasResult::MustAlias; 14450b57cec5SDimitry Andric 14460b57cec5SDimitry Andric if (!V1->getType()->isPointerTy() || !V2->getType()->isPointerTy()) 1447fe6060f1SDimitry Andric return AliasResult::NoAlias; // Scalars cannot alias each other 14480b57cec5SDimitry Andric 14490b57cec5SDimitry Andric // Figure out what objects these things are pointing to if we can. 1450e8d8bef9SDimitry Andric const Value *O1 = getUnderlyingObject(V1, MaxLookupSearchDepth); 1451e8d8bef9SDimitry Andric const Value *O2 = getUnderlyingObject(V2, MaxLookupSearchDepth); 14520b57cec5SDimitry Andric 14530b57cec5SDimitry Andric // Null values in the default address space don't point to any object, so they 14540b57cec5SDimitry Andric // don't alias any other pointer. 14550b57cec5SDimitry Andric if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O1)) 14560b57cec5SDimitry Andric if (!NullPointerIsDefined(&F, CPN->getType()->getAddressSpace())) 1457fe6060f1SDimitry Andric return AliasResult::NoAlias; 14580b57cec5SDimitry Andric if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O2)) 14590b57cec5SDimitry Andric if (!NullPointerIsDefined(&F, CPN->getType()->getAddressSpace())) 1460fe6060f1SDimitry Andric return AliasResult::NoAlias; 14610b57cec5SDimitry Andric 14620b57cec5SDimitry Andric if (O1 != O2) { 14630b57cec5SDimitry Andric // If V1/V2 point to two different objects, we know that we have no alias. 14640b57cec5SDimitry Andric if (isIdentifiedObject(O1) && isIdentifiedObject(O2)) 1465fe6060f1SDimitry Andric return AliasResult::NoAlias; 14660b57cec5SDimitry Andric 14670b57cec5SDimitry Andric // Constant pointers can't alias with non-const isIdentifiedObject objects. 14680b57cec5SDimitry Andric if ((isa<Constant>(O1) && isIdentifiedObject(O2) && !isa<Constant>(O2)) || 14690b57cec5SDimitry Andric (isa<Constant>(O2) && isIdentifiedObject(O1) && !isa<Constant>(O1))) 1470fe6060f1SDimitry Andric return AliasResult::NoAlias; 14710b57cec5SDimitry Andric 14720b57cec5SDimitry Andric // Function arguments can't alias with things that are known to be 14730b57cec5SDimitry Andric // unambigously identified at the function level. 14740b57cec5SDimitry Andric if ((isa<Argument>(O1) && isIdentifiedFunctionLocal(O2)) || 14750b57cec5SDimitry Andric (isa<Argument>(O2) && isIdentifiedFunctionLocal(O1))) 1476fe6060f1SDimitry Andric return AliasResult::NoAlias; 14770b57cec5SDimitry Andric 14780b57cec5SDimitry Andric // If one pointer is the result of a call/invoke or load and the other is a 14790b57cec5SDimitry Andric // non-escaping local object within the same function, then we know the 14800b57cec5SDimitry Andric // object couldn't escape to a point where the call could return it. 14810b57cec5SDimitry Andric // 14820b57cec5SDimitry Andric // Note that if the pointers are in different functions, there are a 14830b57cec5SDimitry Andric // variety of complications. A call with a nocapture argument may still 14840b57cec5SDimitry Andric // temporary store the nocapture argument's value in a temporary memory 14850b57cec5SDimitry Andric // location if that memory location doesn't escape. Or it may pass a 14860b57cec5SDimitry Andric // nocapture value to other functions as long as they don't capture it. 14870b57cec5SDimitry Andric if (isEscapeSource(O1) && 1488349cc55cSDimitry Andric AAQI.CI->isNotCapturedBeforeOrAt(O2, cast<Instruction>(O1))) 1489fe6060f1SDimitry Andric return AliasResult::NoAlias; 14900b57cec5SDimitry Andric if (isEscapeSource(O2) && 1491349cc55cSDimitry Andric AAQI.CI->isNotCapturedBeforeOrAt(O1, cast<Instruction>(O2))) 1492fe6060f1SDimitry Andric return AliasResult::NoAlias; 14930b57cec5SDimitry Andric } 14940b57cec5SDimitry Andric 14950b57cec5SDimitry Andric // If the size of one access is larger than the entire object on the other 14960b57cec5SDimitry Andric // side, then we know such behavior is undefined and can assume no alias. 14970b57cec5SDimitry Andric bool NullIsValidLocation = NullPointerIsDefined(&F); 14988bcb0991SDimitry Andric if ((isObjectSmallerThan( 14998bcb0991SDimitry Andric O2, getMinimalExtentFrom(*V1, V1Size, DL, NullIsValidLocation), DL, 15008bcb0991SDimitry Andric TLI, NullIsValidLocation)) || 15018bcb0991SDimitry Andric (isObjectSmallerThan( 15028bcb0991SDimitry Andric O1, getMinimalExtentFrom(*V2, V2Size, DL, NullIsValidLocation), DL, 15038bcb0991SDimitry Andric TLI, NullIsValidLocation))) 1504fe6060f1SDimitry Andric return AliasResult::NoAlias; 15050b57cec5SDimitry Andric 1506bdd1243dSDimitry Andric if (CtxI && EnableSeparateStorageAnalysis) { 1507bdd1243dSDimitry Andric for (auto &AssumeVH : AC.assumptions()) { 1508bdd1243dSDimitry Andric if (!AssumeVH) 1509bdd1243dSDimitry Andric continue; 1510bdd1243dSDimitry Andric 1511bdd1243dSDimitry Andric AssumeInst *Assume = cast<AssumeInst>(AssumeVH); 1512bdd1243dSDimitry Andric 1513bdd1243dSDimitry Andric for (unsigned Idx = 0; Idx < Assume->getNumOperandBundles(); Idx++) { 1514bdd1243dSDimitry Andric OperandBundleUse OBU = Assume->getOperandBundleAt(Idx); 1515bdd1243dSDimitry Andric if (OBU.getTagName() == "separate_storage") { 1516bdd1243dSDimitry Andric assert(OBU.Inputs.size() == 2); 1517bdd1243dSDimitry Andric const Value *Hint1 = OBU.Inputs[0].get(); 1518bdd1243dSDimitry Andric const Value *Hint2 = OBU.Inputs[1].get(); 1519bdd1243dSDimitry Andric const Value *HintO1 = getUnderlyingObject(Hint1); 1520bdd1243dSDimitry Andric const Value *HintO2 = getUnderlyingObject(Hint2); 1521bdd1243dSDimitry Andric 1522bdd1243dSDimitry Andric if (((O1 == HintO1 && O2 == HintO2) || 1523bdd1243dSDimitry Andric (O1 == HintO2 && O2 == HintO1)) && 1524bdd1243dSDimitry Andric isValidAssumeForContext(Assume, CtxI, DT)) 1525bdd1243dSDimitry Andric return AliasResult::NoAlias; 1526bdd1243dSDimitry Andric } 1527bdd1243dSDimitry Andric } 1528bdd1243dSDimitry Andric } 1529bdd1243dSDimitry Andric } 1530bdd1243dSDimitry Andric 1531e8d8bef9SDimitry Andric // If one the accesses may be before the accessed pointer, canonicalize this 1532e8d8bef9SDimitry Andric // by using unknown after-pointer sizes for both accesses. This is 1533e8d8bef9SDimitry Andric // equivalent, because regardless of which pointer is lower, one of them 1534e8d8bef9SDimitry Andric // will always came after the other, as long as the underlying objects aren't 1535e8d8bef9SDimitry Andric // disjoint. We do this so that the rest of BasicAA does not have to deal 1536e8d8bef9SDimitry Andric // with accesses before the base pointer, and to improve cache utilization by 1537e8d8bef9SDimitry Andric // merging equivalent states. 1538e8d8bef9SDimitry Andric if (V1Size.mayBeBeforePointer() || V2Size.mayBeBeforePointer()) { 1539e8d8bef9SDimitry Andric V1Size = LocationSize::afterPointer(); 1540e8d8bef9SDimitry Andric V2Size = LocationSize::afterPointer(); 1541e8d8bef9SDimitry Andric } 1542e8d8bef9SDimitry Andric 1543fe6060f1SDimitry Andric // FIXME: If this depth limit is hit, then we may cache sub-optimal results 1544fe6060f1SDimitry Andric // for recursive queries. For this reason, this limit is chosen to be large 1545fe6060f1SDimitry Andric // enough to be very rarely hit, while still being small enough to avoid 1546fe6060f1SDimitry Andric // stack overflows. 1547fe6060f1SDimitry Andric if (AAQI.Depth >= 512) 1548fe6060f1SDimitry Andric return AliasResult::MayAlias; 1549fe6060f1SDimitry Andric 15500b57cec5SDimitry Andric // Check the cache before climbing up use-def chains. This also terminates 1551bdd1243dSDimitry Andric // otherwise infinitely recursive queries. Include MayBeCrossIteration in the 1552bdd1243dSDimitry Andric // cache key, because some cases where MayBeCrossIteration==false returns 1553bdd1243dSDimitry Andric // MustAlias or NoAlias may become MayAlias under MayBeCrossIteration==true. 1554bdd1243dSDimitry Andric AAQueryInfo::LocPair Locs({V1, V1Size, AAQI.MayBeCrossIteration}, 1555bdd1243dSDimitry Andric {V2, V2Size, AAQI.MayBeCrossIteration}); 1556fe6060f1SDimitry Andric const bool Swapped = V1 > V2; 1557fe6060f1SDimitry Andric if (Swapped) 15580b57cec5SDimitry Andric std::swap(Locs.first, Locs.second); 1559e8d8bef9SDimitry Andric const auto &Pair = AAQI.AliasCache.try_emplace( 1560fe6060f1SDimitry Andric Locs, AAQueryInfo::CacheEntry{AliasResult::NoAlias, 0}); 1561e8d8bef9SDimitry Andric if (!Pair.second) { 1562e8d8bef9SDimitry Andric auto &Entry = Pair.first->second; 1563e8d8bef9SDimitry Andric if (!Entry.isDefinitive()) { 1564e8d8bef9SDimitry Andric // Remember that we used an assumption. 1565e8d8bef9SDimitry Andric ++Entry.NumAssumptionUses; 1566e8d8bef9SDimitry Andric ++AAQI.NumAssumptionUses; 15670b57cec5SDimitry Andric } 1568fe6060f1SDimitry Andric // Cache contains sorted {V1,V2} pairs but we should return original order. 1569fe6060f1SDimitry Andric auto Result = Entry.Result; 1570fe6060f1SDimitry Andric Result.swap(Swapped); 1571fe6060f1SDimitry Andric return Result; 1572e8d8bef9SDimitry Andric } 1573e8d8bef9SDimitry Andric 1574e8d8bef9SDimitry Andric int OrigNumAssumptionUses = AAQI.NumAssumptionUses; 1575e8d8bef9SDimitry Andric unsigned OrigNumAssumptionBasedResults = AAQI.AssumptionBasedResults.size(); 1576fe6060f1SDimitry Andric AliasResult Result = 1577fe6060f1SDimitry Andric aliasCheckRecursive(V1, V1Size, V2, V2Size, AAQI, O1, O2); 1578e8d8bef9SDimitry Andric 1579e8d8bef9SDimitry Andric auto It = AAQI.AliasCache.find(Locs); 1580e8d8bef9SDimitry Andric assert(It != AAQI.AliasCache.end() && "Must be in cache"); 1581e8d8bef9SDimitry Andric auto &Entry = It->second; 1582e8d8bef9SDimitry Andric 1583e8d8bef9SDimitry Andric // Check whether a NoAlias assumption has been used, but disproven. 1584fe6060f1SDimitry Andric bool AssumptionDisproven = 1585fe6060f1SDimitry Andric Entry.NumAssumptionUses > 0 && Result != AliasResult::NoAlias; 1586e8d8bef9SDimitry Andric if (AssumptionDisproven) 1587fe6060f1SDimitry Andric Result = AliasResult::MayAlias; 1588e8d8bef9SDimitry Andric 1589e8d8bef9SDimitry Andric // This is a definitive result now, when considered as a root query. 1590e8d8bef9SDimitry Andric AAQI.NumAssumptionUses -= Entry.NumAssumptionUses; 1591e8d8bef9SDimitry Andric Entry.Result = Result; 1592fe6060f1SDimitry Andric // Cache contains sorted {V1,V2} pairs. 1593fe6060f1SDimitry Andric Entry.Result.swap(Swapped); 1594e8d8bef9SDimitry Andric Entry.NumAssumptionUses = -1; 1595e8d8bef9SDimitry Andric 1596e8d8bef9SDimitry Andric // If the assumption has been disproven, remove any results that may have 1597e8d8bef9SDimitry Andric // been based on this assumption. Do this after the Entry updates above to 1598e8d8bef9SDimitry Andric // avoid iterator invalidation. 1599e8d8bef9SDimitry Andric if (AssumptionDisproven) 1600e8d8bef9SDimitry Andric while (AAQI.AssumptionBasedResults.size() > OrigNumAssumptionBasedResults) 1601e8d8bef9SDimitry Andric AAQI.AliasCache.erase(AAQI.AssumptionBasedResults.pop_back_val()); 1602e8d8bef9SDimitry Andric 1603e8d8bef9SDimitry Andric // The result may still be based on assumptions higher up in the chain. 1604e8d8bef9SDimitry Andric // Remember it, so it can be purged from the cache later. 1605fe6060f1SDimitry Andric if (OrigNumAssumptionUses != AAQI.NumAssumptionUses && 1606fe6060f1SDimitry Andric Result != AliasResult::MayAlias) 1607e8d8bef9SDimitry Andric AAQI.AssumptionBasedResults.push_back(Locs); 1608e8d8bef9SDimitry Andric return Result; 1609e8d8bef9SDimitry Andric } 1610e8d8bef9SDimitry Andric 1611e8d8bef9SDimitry Andric AliasResult BasicAAResult::aliasCheckRecursive( 1612fe6060f1SDimitry Andric const Value *V1, LocationSize V1Size, 1613fe6060f1SDimitry Andric const Value *V2, LocationSize V2Size, 1614e8d8bef9SDimitry Andric AAQueryInfo &AAQI, const Value *O1, const Value *O2) { 16150b57cec5SDimitry Andric if (const GEPOperator *GV1 = dyn_cast<GEPOperator>(V1)) { 1616fe6060f1SDimitry Andric AliasResult Result = aliasGEP(GV1, V1Size, V2, V2Size, O1, O2, AAQI); 1617fe6060f1SDimitry Andric if (Result != AliasResult::MayAlias) 1618e8d8bef9SDimitry Andric return Result; 1619e8d8bef9SDimitry Andric } else if (const GEPOperator *GV2 = dyn_cast<GEPOperator>(V2)) { 1620fe6060f1SDimitry Andric AliasResult Result = aliasGEP(GV2, V2Size, V1, V1Size, O2, O1, AAQI); 16210eae32dcSDimitry Andric Result.swap(); 1622fe6060f1SDimitry Andric if (Result != AliasResult::MayAlias) 16230b57cec5SDimitry Andric return Result; 16240b57cec5SDimitry Andric } 16250b57cec5SDimitry Andric 16260b57cec5SDimitry Andric if (const PHINode *PN = dyn_cast<PHINode>(V1)) { 1627fe6060f1SDimitry Andric AliasResult Result = aliasPHI(PN, V1Size, V2, V2Size, AAQI); 1628fe6060f1SDimitry Andric if (Result != AliasResult::MayAlias) 1629e8d8bef9SDimitry Andric return Result; 1630e8d8bef9SDimitry Andric } else if (const PHINode *PN = dyn_cast<PHINode>(V2)) { 1631fe6060f1SDimitry Andric AliasResult Result = aliasPHI(PN, V2Size, V1, V1Size, AAQI); 16320eae32dcSDimitry Andric Result.swap(); 1633fe6060f1SDimitry Andric if (Result != AliasResult::MayAlias) 1634e8d8bef9SDimitry Andric return Result; 16350b57cec5SDimitry Andric } 16360b57cec5SDimitry Andric 16370b57cec5SDimitry Andric if (const SelectInst *S1 = dyn_cast<SelectInst>(V1)) { 1638fe6060f1SDimitry Andric AliasResult Result = aliasSelect(S1, V1Size, V2, V2Size, AAQI); 1639fe6060f1SDimitry Andric if (Result != AliasResult::MayAlias) 1640e8d8bef9SDimitry Andric return Result; 1641e8d8bef9SDimitry Andric } else if (const SelectInst *S2 = dyn_cast<SelectInst>(V2)) { 1642fe6060f1SDimitry Andric AliasResult Result = aliasSelect(S2, V2Size, V1, V1Size, AAQI); 16430eae32dcSDimitry Andric Result.swap(); 1644fe6060f1SDimitry Andric if (Result != AliasResult::MayAlias) 1645e8d8bef9SDimitry Andric return Result; 16460b57cec5SDimitry Andric } 16470b57cec5SDimitry Andric 16480b57cec5SDimitry Andric // If both pointers are pointing into the same object and one of them 16490b57cec5SDimitry Andric // accesses the entire object, then the accesses must overlap in some way. 1650e8d8bef9SDimitry Andric if (O1 == O2) { 1651e8d8bef9SDimitry Andric bool NullIsValidLocation = NullPointerIsDefined(&F); 16520b57cec5SDimitry Andric if (V1Size.isPrecise() && V2Size.isPrecise() && 16530b57cec5SDimitry Andric (isObjectSize(O1, V1Size.getValue(), DL, TLI, NullIsValidLocation) || 1654e8d8bef9SDimitry Andric isObjectSize(O2, V2Size.getValue(), DL, TLI, NullIsValidLocation))) 1655fe6060f1SDimitry Andric return AliasResult::PartialAlias; 16560b57cec5SDimitry Andric } 16570b57cec5SDimitry Andric 1658fe6060f1SDimitry Andric return AliasResult::MayAlias; 16590b57cec5SDimitry Andric } 16600b57cec5SDimitry Andric 16610b57cec5SDimitry Andric /// Check whether two Values can be considered equivalent. 16620b57cec5SDimitry Andric /// 1663bdd1243dSDimitry Andric /// If the values may come from different cycle iterations, this will also 1664bdd1243dSDimitry Andric /// check that the values are not part of cycle. We have to do this because we 1665bdd1243dSDimitry Andric /// are looking through phi nodes, that is we say 16660b57cec5SDimitry Andric /// noalias(V, phi(VA, VB)) if noalias(V, VA) and noalias(V, VB). 16670b57cec5SDimitry Andric bool BasicAAResult::isValueEqualInPotentialCycles(const Value *V, 1668bdd1243dSDimitry Andric const Value *V2, 1669bdd1243dSDimitry Andric const AAQueryInfo &AAQI) { 16700b57cec5SDimitry Andric if (V != V2) 16710b57cec5SDimitry Andric return false; 16720b57cec5SDimitry Andric 1673bdd1243dSDimitry Andric if (!AAQI.MayBeCrossIteration) 1674bdd1243dSDimitry Andric return true; 1675bdd1243dSDimitry Andric 1676bdd1243dSDimitry Andric // Non-instructions and instructions in the entry block cannot be part of 1677bdd1243dSDimitry Andric // a loop. 16780b57cec5SDimitry Andric const Instruction *Inst = dyn_cast<Instruction>(V); 1679bdd1243dSDimitry Andric if (!Inst || Inst->getParent()->isEntryBlock()) 16800b57cec5SDimitry Andric return true; 16810b57cec5SDimitry Andric 1682bdd1243dSDimitry Andric // Check whether the instruction is part of a cycle, by checking whether the 1683bdd1243dSDimitry Andric // block can (non-trivially) reach itself. 1684bdd1243dSDimitry Andric BasicBlock *BB = const_cast<BasicBlock *>(Inst->getParent()); 1685bdd1243dSDimitry Andric SmallVector<BasicBlock *> Succs(successors(BB)); 1686bdd1243dSDimitry Andric return !Succs.empty() && 1687bdd1243dSDimitry Andric !isPotentiallyReachableFromMany(Succs, BB, nullptr, DT); 16880b57cec5SDimitry Andric } 16890b57cec5SDimitry Andric 16900b57cec5SDimitry Andric /// Computes the symbolic difference between two de-composed GEPs. 1691349cc55cSDimitry Andric void BasicAAResult::subtractDecomposedGEPs(DecomposedGEP &DestGEP, 1692bdd1243dSDimitry Andric const DecomposedGEP &SrcGEP, 1693bdd1243dSDimitry Andric const AAQueryInfo &AAQI) { 1694349cc55cSDimitry Andric DestGEP.Offset -= SrcGEP.Offset; 1695349cc55cSDimitry Andric for (const VariableGEPIndex &Src : SrcGEP.VarIndices) { 16960b57cec5SDimitry Andric // Find V in Dest. This is N^2, but pointer indices almost never have more 16970b57cec5SDimitry Andric // than a few variable indexes. 1698349cc55cSDimitry Andric bool Found = false; 1699349cc55cSDimitry Andric for (auto I : enumerate(DestGEP.VarIndices)) { 1700349cc55cSDimitry Andric VariableGEPIndex &Dest = I.value(); 1701bdd1243dSDimitry Andric if (!isValueEqualInPotentialCycles(Dest.Val.V, Src.Val.V, AAQI) || 1702349cc55cSDimitry Andric !Dest.Val.hasSameCastsAs(Src.Val)) 17030b57cec5SDimitry Andric continue; 17040b57cec5SDimitry Andric 17050b57cec5SDimitry Andric // If we found it, subtract off Scale V's from the entry in Dest. If it 17060b57cec5SDimitry Andric // goes to zero, remove the entry. 1707349cc55cSDimitry Andric if (Dest.Scale != Src.Scale) { 1708349cc55cSDimitry Andric Dest.Scale -= Src.Scale; 1709349cc55cSDimitry Andric Dest.IsNSW = false; 1710349cc55cSDimitry Andric } else { 1711349cc55cSDimitry Andric DestGEP.VarIndices.erase(DestGEP.VarIndices.begin() + I.index()); 1712349cc55cSDimitry Andric } 1713349cc55cSDimitry Andric Found = true; 17140b57cec5SDimitry Andric break; 17150b57cec5SDimitry Andric } 17160b57cec5SDimitry Andric 17170b57cec5SDimitry Andric // If we didn't consume this entry, add it to the end of the Dest list. 1718349cc55cSDimitry Andric if (!Found) { 1719349cc55cSDimitry Andric VariableGEPIndex Entry = {Src.Val, -Src.Scale, Src.CxtI, Src.IsNSW}; 1720349cc55cSDimitry Andric DestGEP.VarIndices.push_back(Entry); 17210b57cec5SDimitry Andric } 17220b57cec5SDimitry Andric } 17230b57cec5SDimitry Andric } 17240b57cec5SDimitry Andric 1725bdd1243dSDimitry Andric bool BasicAAResult::constantOffsetHeuristic(const DecomposedGEP &GEP, 1726bdd1243dSDimitry Andric LocationSize MaybeV1Size, 1727bdd1243dSDimitry Andric LocationSize MaybeV2Size, 1728bdd1243dSDimitry Andric AssumptionCache *AC, 1729bdd1243dSDimitry Andric DominatorTree *DT, 1730bdd1243dSDimitry Andric const AAQueryInfo &AAQI) { 1731349cc55cSDimitry Andric if (GEP.VarIndices.size() != 2 || !MaybeV1Size.hasValue() || 1732e8d8bef9SDimitry Andric !MaybeV2Size.hasValue()) 17330b57cec5SDimitry Andric return false; 17340b57cec5SDimitry Andric 17350b57cec5SDimitry Andric const uint64_t V1Size = MaybeV1Size.getValue(); 17360b57cec5SDimitry Andric const uint64_t V2Size = MaybeV2Size.getValue(); 17370b57cec5SDimitry Andric 1738349cc55cSDimitry Andric const VariableGEPIndex &Var0 = GEP.VarIndices[0], &Var1 = GEP.VarIndices[1]; 17390b57cec5SDimitry Andric 1740349cc55cSDimitry Andric if (Var0.Val.TruncBits != 0 || !Var0.Val.hasSameCastsAs(Var1.Val) || 1741349cc55cSDimitry Andric Var0.Scale != -Var1.Scale || 1742349cc55cSDimitry Andric Var0.Val.V->getType() != Var1.Val.V->getType()) 17430b57cec5SDimitry Andric return false; 17440b57cec5SDimitry Andric 17450b57cec5SDimitry Andric // We'll strip off the Extensions of Var0 and Var1 and do another round 17460b57cec5SDimitry Andric // of GetLinearExpression decomposition. In the example above, if Var0 17470b57cec5SDimitry Andric // is zext(%x + 1) we should get V1 == %x and V1Offset == 1. 17480b57cec5SDimitry Andric 1749fe6060f1SDimitry Andric LinearExpression E0 = 1750349cc55cSDimitry Andric GetLinearExpression(CastedValue(Var0.Val.V), DL, 0, AC, DT); 1751fe6060f1SDimitry Andric LinearExpression E1 = 1752349cc55cSDimitry Andric GetLinearExpression(CastedValue(Var1.Val.V), DL, 0, AC, DT); 1753349cc55cSDimitry Andric if (E0.Scale != E1.Scale || !E0.Val.hasSameCastsAs(E1.Val) || 1754bdd1243dSDimitry Andric !isValueEqualInPotentialCycles(E0.Val.V, E1.Val.V, AAQI)) 17550b57cec5SDimitry Andric return false; 17560b57cec5SDimitry Andric 17570b57cec5SDimitry Andric // We have a hit - Var0 and Var1 only differ by a constant offset! 17580b57cec5SDimitry Andric 17590b57cec5SDimitry Andric // If we've been sext'ed then zext'd the maximum difference between Var0 and 17600b57cec5SDimitry Andric // Var1 is possible to calculate, but we're just interested in the absolute 17610b57cec5SDimitry Andric // minimum difference between the two. The minimum distance may occur due to 17620b57cec5SDimitry Andric // wrapping; consider "add i3 %i, 5": if %i == 7 then 7 + 5 mod 8 == 4, and so 17630b57cec5SDimitry Andric // the minimum distance between %i and %i + 5 is 3. 1764fe6060f1SDimitry Andric APInt MinDiff = E0.Offset - E1.Offset, Wrapped = -MinDiff; 17650b57cec5SDimitry Andric MinDiff = APIntOps::umin(MinDiff, Wrapped); 17660b57cec5SDimitry Andric APInt MinDiffBytes = 17670b57cec5SDimitry Andric MinDiff.zextOrTrunc(Var0.Scale.getBitWidth()) * Var0.Scale.abs(); 17680b57cec5SDimitry Andric 17690b57cec5SDimitry Andric // We can't definitely say whether GEP1 is before or after V2 due to wrapping 17700b57cec5SDimitry Andric // arithmetic (i.e. for some values of GEP1 and V2 GEP1 < V2, and for other 17710b57cec5SDimitry Andric // values GEP1 > V2). We'll therefore only declare NoAlias if both V1Size and 17720b57cec5SDimitry Andric // V2Size can fit in the MinDiffBytes gap. 1773349cc55cSDimitry Andric return MinDiffBytes.uge(V1Size + GEP.Offset.abs()) && 1774349cc55cSDimitry Andric MinDiffBytes.uge(V2Size + GEP.Offset.abs()); 17750b57cec5SDimitry Andric } 17760b57cec5SDimitry Andric 17770b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 17780b57cec5SDimitry Andric // BasicAliasAnalysis Pass 17790b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 17800b57cec5SDimitry Andric 17810b57cec5SDimitry Andric AnalysisKey BasicAA::Key; 17820b57cec5SDimitry Andric 17830b57cec5SDimitry Andric BasicAAResult BasicAA::run(Function &F, FunctionAnalysisManager &AM) { 1784e8d8bef9SDimitry Andric auto &TLI = AM.getResult<TargetLibraryAnalysis>(F); 1785e8d8bef9SDimitry Andric auto &AC = AM.getResult<AssumptionAnalysis>(F); 1786e8d8bef9SDimitry Andric auto *DT = &AM.getResult<DominatorTreeAnalysis>(F); 1787bdd1243dSDimitry Andric return BasicAAResult(F.getParent()->getDataLayout(), F, TLI, AC, DT); 17880b57cec5SDimitry Andric } 17890b57cec5SDimitry Andric 17900b57cec5SDimitry Andric BasicAAWrapperPass::BasicAAWrapperPass() : FunctionPass(ID) { 17910b57cec5SDimitry Andric initializeBasicAAWrapperPassPass(*PassRegistry::getPassRegistry()); 17920b57cec5SDimitry Andric } 17930b57cec5SDimitry Andric 17940b57cec5SDimitry Andric char BasicAAWrapperPass::ID = 0; 17950b57cec5SDimitry Andric 17960b57cec5SDimitry Andric void BasicAAWrapperPass::anchor() {} 17970b57cec5SDimitry Andric 17985ffd83dbSDimitry Andric INITIALIZE_PASS_BEGIN(BasicAAWrapperPass, "basic-aa", 1799*b32fb2a4SDimitry Andric "Basic Alias Analysis (stateless AA impl)", true, true) 18000b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 18010b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 18020b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 18035ffd83dbSDimitry Andric INITIALIZE_PASS_END(BasicAAWrapperPass, "basic-aa", 1804*b32fb2a4SDimitry Andric "Basic Alias Analysis (stateless AA impl)", true, true) 18050b57cec5SDimitry Andric 18060b57cec5SDimitry Andric FunctionPass *llvm::createBasicAAWrapperPass() { 18070b57cec5SDimitry Andric return new BasicAAWrapperPass(); 18080b57cec5SDimitry Andric } 18090b57cec5SDimitry Andric 18100b57cec5SDimitry Andric bool BasicAAWrapperPass::runOnFunction(Function &F) { 18110b57cec5SDimitry Andric auto &ACT = getAnalysis<AssumptionCacheTracker>(); 18120b57cec5SDimitry Andric auto &TLIWP = getAnalysis<TargetLibraryInfoWrapperPass>(); 18130b57cec5SDimitry Andric auto &DTWP = getAnalysis<DominatorTreeWrapperPass>(); 18140b57cec5SDimitry Andric 18158bcb0991SDimitry Andric Result.reset(new BasicAAResult(F.getParent()->getDataLayout(), F, 18168bcb0991SDimitry Andric TLIWP.getTLI(F), ACT.getAssumptionCache(F), 1817bdd1243dSDimitry Andric &DTWP.getDomTree())); 18180b57cec5SDimitry Andric 18190b57cec5SDimitry Andric return false; 18200b57cec5SDimitry Andric } 18210b57cec5SDimitry Andric 18220b57cec5SDimitry Andric void BasicAAWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { 18230b57cec5SDimitry Andric AU.setPreservesAll(); 1824e8d8bef9SDimitry Andric AU.addRequiredTransitive<AssumptionCacheTracker>(); 1825e8d8bef9SDimitry Andric AU.addRequiredTransitive<DominatorTreeWrapperPass>(); 1826e8d8bef9SDimitry Andric AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>(); 18270b57cec5SDimitry Andric } 18280b57cec5SDimitry Andric 18290b57cec5SDimitry Andric BasicAAResult llvm::createLegacyPMBasicAAResult(Pass &P, Function &F) { 18300b57cec5SDimitry Andric return BasicAAResult( 18318bcb0991SDimitry Andric F.getParent()->getDataLayout(), F, 18328bcb0991SDimitry Andric P.getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F), 18330b57cec5SDimitry Andric P.getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F)); 18340b57cec5SDimitry Andric } 1835