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/InstructionSimplify.h" 260b57cec5SDimitry Andric #include "llvm/Analysis/MemoryBuiltins.h" 270b57cec5SDimitry Andric #include "llvm/Analysis/MemoryLocation.h" 28480093f4SDimitry Andric #include "llvm/Analysis/PhiValues.h" 290b57cec5SDimitry Andric #include "llvm/Analysis/TargetLibraryInfo.h" 300b57cec5SDimitry Andric #include "llvm/Analysis/ValueTracking.h" 310b57cec5SDimitry Andric #include "llvm/IR/Argument.h" 320b57cec5SDimitry Andric #include "llvm/IR/Attributes.h" 330b57cec5SDimitry Andric #include "llvm/IR/Constant.h" 340b57cec5SDimitry Andric #include "llvm/IR/Constants.h" 350b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h" 360b57cec5SDimitry Andric #include "llvm/IR/DerivedTypes.h" 370b57cec5SDimitry Andric #include "llvm/IR/Dominators.h" 380b57cec5SDimitry Andric #include "llvm/IR/Function.h" 390b57cec5SDimitry Andric #include "llvm/IR/GetElementPtrTypeIterator.h" 400b57cec5SDimitry Andric #include "llvm/IR/GlobalAlias.h" 410b57cec5SDimitry Andric #include "llvm/IR/GlobalVariable.h" 420b57cec5SDimitry Andric #include "llvm/IR/InstrTypes.h" 430b57cec5SDimitry Andric #include "llvm/IR/Instruction.h" 440b57cec5SDimitry Andric #include "llvm/IR/Instructions.h" 450b57cec5SDimitry Andric #include "llvm/IR/IntrinsicInst.h" 460b57cec5SDimitry Andric #include "llvm/IR/Intrinsics.h" 470b57cec5SDimitry Andric #include "llvm/IR/Metadata.h" 480b57cec5SDimitry Andric #include "llvm/IR/Operator.h" 490b57cec5SDimitry Andric #include "llvm/IR/Type.h" 500b57cec5SDimitry Andric #include "llvm/IR/User.h" 510b57cec5SDimitry Andric #include "llvm/IR/Value.h" 52480093f4SDimitry Andric #include "llvm/InitializePasses.h" 530b57cec5SDimitry Andric #include "llvm/Pass.h" 540b57cec5SDimitry Andric #include "llvm/Support/Casting.h" 550b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h" 560b57cec5SDimitry Andric #include "llvm/Support/Compiler.h" 570b57cec5SDimitry Andric #include "llvm/Support/KnownBits.h" 580b57cec5SDimitry Andric #include <cassert> 590b57cec5SDimitry Andric #include <cstdint> 600b57cec5SDimitry Andric #include <cstdlib> 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 710b57cec5SDimitry Andric /// By default, even on 32-bit architectures we use 64-bit integers for 720b57cec5SDimitry Andric /// calculations. This will allow us to more-aggressively decompose indexing 730b57cec5SDimitry Andric /// expressions calculated using i64 values (e.g., long long in C) which is 740b57cec5SDimitry Andric /// common enough to worry about. 755ffd83dbSDimitry Andric static cl::opt<bool> ForceAtLeast64Bits("basic-aa-force-at-least-64b", 760b57cec5SDimitry Andric cl::Hidden, cl::init(true)); 775ffd83dbSDimitry Andric static cl::opt<bool> DoubleCalcBits("basic-aa-double-calc-bits", 780b57cec5SDimitry Andric cl::Hidden, cl::init(false)); 790b57cec5SDimitry Andric 800b57cec5SDimitry Andric /// SearchLimitReached / SearchTimes shows how often the limit of 810b57cec5SDimitry Andric /// to decompose GEPs is reached. It will affect the precision 820b57cec5SDimitry Andric /// of basic alias analysis. 830b57cec5SDimitry Andric STATISTIC(SearchLimitReached, "Number of times the limit to " 840b57cec5SDimitry Andric "decompose GEPs is reached"); 850b57cec5SDimitry Andric STATISTIC(SearchTimes, "Number of times a GEP is decomposed"); 860b57cec5SDimitry Andric 870b57cec5SDimitry Andric /// Cutoff after which to stop analysing a set of phi nodes potentially involved 880b57cec5SDimitry Andric /// in a cycle. Because we are analysing 'through' phi nodes, we need to be 890b57cec5SDimitry Andric /// careful with value equivalence. We use reachability to make sure a value 900b57cec5SDimitry Andric /// cannot be involved in a cycle. 910b57cec5SDimitry Andric const unsigned MaxNumPhiBBsValueReachabilityCheck = 20; 920b57cec5SDimitry Andric 930b57cec5SDimitry Andric // The max limit of the search depth in DecomposeGEPExpression() and 94e8d8bef9SDimitry Andric // getUnderlyingObject(), both functions need to use the same search 950b57cec5SDimitry Andric // depth otherwise the algorithm in aliasGEP will assert. 960b57cec5SDimitry Andric static const unsigned MaxLookupSearchDepth = 6; 970b57cec5SDimitry Andric 980b57cec5SDimitry Andric bool BasicAAResult::invalidate(Function &Fn, const PreservedAnalyses &PA, 990b57cec5SDimitry Andric FunctionAnalysisManager::Invalidator &Inv) { 1000b57cec5SDimitry Andric // We don't care if this analysis itself is preserved, it has no state. But 1010b57cec5SDimitry Andric // we need to check that the analyses it depends on have been. Note that we 1020b57cec5SDimitry Andric // may be created without handles to some analyses and in that case don't 1030b57cec5SDimitry Andric // depend on them. 1040b57cec5SDimitry Andric if (Inv.invalidate<AssumptionAnalysis>(Fn, PA) || 1050b57cec5SDimitry Andric (DT && Inv.invalidate<DominatorTreeAnalysis>(Fn, PA)) || 1060b57cec5SDimitry Andric (PV && Inv.invalidate<PhiValuesAnalysis>(Fn, PA))) 1070b57cec5SDimitry Andric return true; 1080b57cec5SDimitry Andric 1090b57cec5SDimitry Andric // Otherwise this analysis result remains valid. 1100b57cec5SDimitry Andric return false; 1110b57cec5SDimitry Andric } 1120b57cec5SDimitry Andric 1130b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 1140b57cec5SDimitry Andric // Useful predicates 1150b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 1160b57cec5SDimitry Andric 1170b57cec5SDimitry Andric /// Returns true if the pointer is one which would have been considered an 1180b57cec5SDimitry Andric /// escape by isNonEscapingLocalObject. 1190b57cec5SDimitry Andric static bool isEscapeSource(const Value *V) { 1200b57cec5SDimitry Andric if (isa<CallBase>(V)) 1210b57cec5SDimitry Andric return true; 1220b57cec5SDimitry Andric 1230b57cec5SDimitry Andric if (isa<Argument>(V)) 1240b57cec5SDimitry Andric return true; 1250b57cec5SDimitry Andric 1260b57cec5SDimitry Andric // The load case works because isNonEscapingLocalObject considers all 1270b57cec5SDimitry Andric // stores to be escapes (it passes true for the StoreCaptures argument 1280b57cec5SDimitry Andric // to PointerMayBeCaptured). 1290b57cec5SDimitry Andric if (isa<LoadInst>(V)) 1300b57cec5SDimitry Andric return true; 1310b57cec5SDimitry Andric 132fe6060f1SDimitry Andric // The inttoptr case works because isNonEscapingLocalObject considers all 133fe6060f1SDimitry Andric // means of converting or equating a pointer to an int (ptrtoint, ptr store 134fe6060f1SDimitry Andric // which could be followed by an integer load, ptr<->int compare) as 135fe6060f1SDimitry Andric // escaping, and objects located at well-known addresses via platform-specific 136fe6060f1SDimitry Andric // means cannot be considered non-escaping local objects. 137fe6060f1SDimitry Andric if (isa<IntToPtrInst>(V)) 138fe6060f1SDimitry Andric return true; 139fe6060f1SDimitry Andric 1400b57cec5SDimitry Andric return false; 1410b57cec5SDimitry Andric } 1420b57cec5SDimitry Andric 1430b57cec5SDimitry Andric /// Returns the size of the object specified by V or UnknownSize if unknown. 1440b57cec5SDimitry Andric static uint64_t getObjectSize(const Value *V, const DataLayout &DL, 1450b57cec5SDimitry Andric const TargetLibraryInfo &TLI, 1460b57cec5SDimitry Andric bool NullIsValidLoc, 1470b57cec5SDimitry Andric bool RoundToAlign = false) { 1480b57cec5SDimitry Andric uint64_t Size; 1490b57cec5SDimitry Andric ObjectSizeOpts Opts; 1500b57cec5SDimitry Andric Opts.RoundToAlign = RoundToAlign; 1510b57cec5SDimitry Andric Opts.NullIsUnknownSize = NullIsValidLoc; 1520b57cec5SDimitry Andric if (getObjectSize(V, Size, DL, &TLI, Opts)) 1530b57cec5SDimitry Andric return Size; 1540b57cec5SDimitry Andric return MemoryLocation::UnknownSize; 1550b57cec5SDimitry Andric } 1560b57cec5SDimitry Andric 1570b57cec5SDimitry Andric /// Returns true if we can prove that the object specified by V is smaller than 1580b57cec5SDimitry Andric /// Size. 1590b57cec5SDimitry Andric static bool isObjectSmallerThan(const Value *V, uint64_t Size, 1600b57cec5SDimitry Andric const DataLayout &DL, 1610b57cec5SDimitry Andric const TargetLibraryInfo &TLI, 1620b57cec5SDimitry Andric bool NullIsValidLoc) { 1630b57cec5SDimitry Andric // Note that the meanings of the "object" are slightly different in the 1640b57cec5SDimitry Andric // following contexts: 1650b57cec5SDimitry Andric // c1: llvm::getObjectSize() 1660b57cec5SDimitry Andric // c2: llvm.objectsize() intrinsic 1670b57cec5SDimitry Andric // c3: isObjectSmallerThan() 1680b57cec5SDimitry Andric // c1 and c2 share the same meaning; however, the meaning of "object" in c3 1690b57cec5SDimitry Andric // refers to the "entire object". 1700b57cec5SDimitry Andric // 1710b57cec5SDimitry Andric // Consider this example: 1720b57cec5SDimitry Andric // char *p = (char*)malloc(100) 1730b57cec5SDimitry Andric // char *q = p+80; 1740b57cec5SDimitry Andric // 1750b57cec5SDimitry Andric // In the context of c1 and c2, the "object" pointed by q refers to the 1760b57cec5SDimitry Andric // stretch of memory of q[0:19]. So, getObjectSize(q) should return 20. 1770b57cec5SDimitry Andric // 1780b57cec5SDimitry Andric // However, in the context of c3, the "object" refers to the chunk of memory 1790b57cec5SDimitry Andric // being allocated. So, the "object" has 100 bytes, and q points to the middle 1800b57cec5SDimitry Andric // the "object". In case q is passed to isObjectSmallerThan() as the 1st 1810b57cec5SDimitry Andric // parameter, before the llvm::getObjectSize() is called to get the size of 1820b57cec5SDimitry Andric // entire object, we should: 1830b57cec5SDimitry Andric // - either rewind the pointer q to the base-address of the object in 1840b57cec5SDimitry Andric // question (in this case rewind to p), or 1850b57cec5SDimitry Andric // - just give up. It is up to caller to make sure the pointer is pointing 1860b57cec5SDimitry Andric // to the base address the object. 1870b57cec5SDimitry Andric // 1880b57cec5SDimitry Andric // We go for 2nd option for simplicity. 1890b57cec5SDimitry Andric if (!isIdentifiedObject(V)) 1900b57cec5SDimitry Andric return false; 1910b57cec5SDimitry Andric 1920b57cec5SDimitry Andric // This function needs to use the aligned object size because we allow 1930b57cec5SDimitry Andric // reads a bit past the end given sufficient alignment. 1940b57cec5SDimitry Andric uint64_t ObjectSize = getObjectSize(V, DL, TLI, NullIsValidLoc, 1950b57cec5SDimitry Andric /*RoundToAlign*/ true); 1960b57cec5SDimitry Andric 1970b57cec5SDimitry Andric return ObjectSize != MemoryLocation::UnknownSize && ObjectSize < Size; 1980b57cec5SDimitry Andric } 1990b57cec5SDimitry Andric 2008bcb0991SDimitry Andric /// Return the minimal extent from \p V to the end of the underlying object, 2018bcb0991SDimitry Andric /// assuming the result is used in an aliasing query. E.g., we do use the query 2028bcb0991SDimitry Andric /// location size and the fact that null pointers cannot alias here. 2038bcb0991SDimitry Andric static uint64_t getMinimalExtentFrom(const Value &V, 2048bcb0991SDimitry Andric const LocationSize &LocSize, 2058bcb0991SDimitry Andric const DataLayout &DL, 2068bcb0991SDimitry Andric bool NullIsValidLoc) { 2078bcb0991SDimitry Andric // If we have dereferenceability information we know a lower bound for the 2088bcb0991SDimitry Andric // extent as accesses for a lower offset would be valid. We need to exclude 2098bcb0991SDimitry Andric // the "or null" part if null is a valid pointer. 210fe6060f1SDimitry Andric bool CanBeNull, CanBeFreed; 211fe6060f1SDimitry Andric uint64_t DerefBytes = 212fe6060f1SDimitry Andric V.getPointerDereferenceableBytes(DL, CanBeNull, CanBeFreed); 2138bcb0991SDimitry Andric DerefBytes = (CanBeNull && NullIsValidLoc) ? 0 : DerefBytes; 214fe6060f1SDimitry Andric DerefBytes = CanBeFreed ? 0 : DerefBytes; 2158bcb0991SDimitry Andric // If queried with a precise location size, we assume that location size to be 2168bcb0991SDimitry Andric // accessed, thus valid. 2178bcb0991SDimitry Andric if (LocSize.isPrecise()) 2188bcb0991SDimitry Andric DerefBytes = std::max(DerefBytes, LocSize.getValue()); 2198bcb0991SDimitry Andric return DerefBytes; 2208bcb0991SDimitry Andric } 2218bcb0991SDimitry Andric 2220b57cec5SDimitry Andric /// Returns true if we can prove that the object specified by V has size Size. 2230b57cec5SDimitry Andric static bool isObjectSize(const Value *V, uint64_t Size, const DataLayout &DL, 2240b57cec5SDimitry Andric const TargetLibraryInfo &TLI, bool NullIsValidLoc) { 2250b57cec5SDimitry Andric uint64_t ObjectSize = getObjectSize(V, DL, TLI, NullIsValidLoc); 2260b57cec5SDimitry Andric return ObjectSize != MemoryLocation::UnknownSize && ObjectSize == Size; 2270b57cec5SDimitry Andric } 2280b57cec5SDimitry Andric 2290b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 2300b57cec5SDimitry Andric // GetElementPtr Instruction Decomposition and Analysis 2310b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 2320b57cec5SDimitry Andric 233fe6060f1SDimitry Andric namespace { 234fe6060f1SDimitry Andric /// Represents zext(sext(V)). 235fe6060f1SDimitry Andric struct ExtendedValue { 236fe6060f1SDimitry Andric const Value *V; 237fe6060f1SDimitry Andric unsigned ZExtBits; 238fe6060f1SDimitry Andric unsigned SExtBits; 239fe6060f1SDimitry Andric 240fe6060f1SDimitry Andric explicit ExtendedValue(const Value *V, unsigned ZExtBits = 0, 241fe6060f1SDimitry Andric unsigned SExtBits = 0) 242fe6060f1SDimitry Andric : V(V), ZExtBits(ZExtBits), SExtBits(SExtBits) {} 243fe6060f1SDimitry Andric 244fe6060f1SDimitry Andric unsigned getBitWidth() const { 245fe6060f1SDimitry Andric return V->getType()->getPrimitiveSizeInBits() + ZExtBits + SExtBits; 246fe6060f1SDimitry Andric } 247fe6060f1SDimitry Andric 248fe6060f1SDimitry Andric ExtendedValue withValue(const Value *NewV) const { 249fe6060f1SDimitry Andric return ExtendedValue(NewV, ZExtBits, SExtBits); 250fe6060f1SDimitry Andric } 251fe6060f1SDimitry Andric 252fe6060f1SDimitry Andric ExtendedValue withZExtOfValue(const Value *NewV) const { 253fe6060f1SDimitry Andric unsigned ExtendBy = V->getType()->getPrimitiveSizeInBits() - 254fe6060f1SDimitry Andric NewV->getType()->getPrimitiveSizeInBits(); 255fe6060f1SDimitry Andric // zext(sext(zext(NewV))) == zext(zext(zext(NewV))) 256fe6060f1SDimitry Andric return ExtendedValue(NewV, ZExtBits + SExtBits + ExtendBy, 0); 257fe6060f1SDimitry Andric } 258fe6060f1SDimitry Andric 259fe6060f1SDimitry Andric ExtendedValue withSExtOfValue(const Value *NewV) const { 260fe6060f1SDimitry Andric unsigned ExtendBy = V->getType()->getPrimitiveSizeInBits() - 261fe6060f1SDimitry Andric NewV->getType()->getPrimitiveSizeInBits(); 262fe6060f1SDimitry Andric // zext(sext(sext(NewV))) 263fe6060f1SDimitry Andric return ExtendedValue(NewV, ZExtBits, SExtBits + ExtendBy); 264fe6060f1SDimitry Andric } 265fe6060f1SDimitry Andric 266fe6060f1SDimitry Andric APInt evaluateWith(APInt N) const { 267fe6060f1SDimitry Andric assert(N.getBitWidth() == V->getType()->getPrimitiveSizeInBits() && 268fe6060f1SDimitry Andric "Incompatible bit width"); 269fe6060f1SDimitry Andric if (SExtBits) N = N.sext(N.getBitWidth() + SExtBits); 270fe6060f1SDimitry Andric if (ZExtBits) N = N.zext(N.getBitWidth() + ZExtBits); 271fe6060f1SDimitry Andric return N; 272fe6060f1SDimitry Andric } 273fe6060f1SDimitry Andric 274fe6060f1SDimitry Andric bool canDistributeOver(bool NUW, bool NSW) const { 275fe6060f1SDimitry Andric // zext(x op<nuw> y) == zext(x) op<nuw> zext(y) 276fe6060f1SDimitry Andric // sext(x op<nsw> y) == sext(x) op<nsw> sext(y) 277fe6060f1SDimitry Andric return (!ZExtBits || NUW) && (!SExtBits || NSW); 278fe6060f1SDimitry Andric } 279fe6060f1SDimitry Andric }; 280fe6060f1SDimitry Andric 281fe6060f1SDimitry Andric /// Represents zext(sext(V)) * Scale + Offset. 282fe6060f1SDimitry Andric struct LinearExpression { 283fe6060f1SDimitry Andric ExtendedValue Val; 284fe6060f1SDimitry Andric APInt Scale; 285fe6060f1SDimitry Andric APInt Offset; 286fe6060f1SDimitry Andric 287fe6060f1SDimitry Andric /// True if all operations in this expression are NSW. 288fe6060f1SDimitry Andric bool IsNSW; 289fe6060f1SDimitry Andric 290fe6060f1SDimitry Andric LinearExpression(const ExtendedValue &Val, const APInt &Scale, 291fe6060f1SDimitry Andric const APInt &Offset, bool IsNSW) 292fe6060f1SDimitry Andric : Val(Val), Scale(Scale), Offset(Offset), IsNSW(IsNSW) {} 293fe6060f1SDimitry Andric 294fe6060f1SDimitry Andric LinearExpression(const ExtendedValue &Val) : Val(Val), IsNSW(true) { 295fe6060f1SDimitry Andric unsigned BitWidth = Val.getBitWidth(); 296fe6060f1SDimitry Andric Scale = APInt(BitWidth, 1); 297fe6060f1SDimitry Andric Offset = APInt(BitWidth, 0); 298fe6060f1SDimitry Andric } 299fe6060f1SDimitry Andric }; 300fe6060f1SDimitry Andric } 301fe6060f1SDimitry Andric 3020b57cec5SDimitry Andric /// Analyzes the specified value as a linear expression: "A*V + B", where A and 3030b57cec5SDimitry Andric /// B are constant integers. 304fe6060f1SDimitry Andric static LinearExpression GetLinearExpression( 305fe6060f1SDimitry Andric const ExtendedValue &Val, const DataLayout &DL, unsigned Depth, 306fe6060f1SDimitry Andric AssumptionCache *AC, DominatorTree *DT) { 3070b57cec5SDimitry Andric // Limit our recursion depth. 308fe6060f1SDimitry Andric if (Depth == 6) 309fe6060f1SDimitry Andric return Val; 3100b57cec5SDimitry Andric 311fe6060f1SDimitry Andric if (const ConstantInt *Const = dyn_cast<ConstantInt>(Val.V)) 312fe6060f1SDimitry Andric return LinearExpression(Val, APInt(Val.getBitWidth(), 0), 313fe6060f1SDimitry Andric Val.evaluateWith(Const->getValue()), true); 3140b57cec5SDimitry Andric 315fe6060f1SDimitry Andric if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(Val.V)) { 3160b57cec5SDimitry Andric if (ConstantInt *RHSC = dyn_cast<ConstantInt>(BOp->getOperand(1))) { 317fe6060f1SDimitry Andric APInt RHS = Val.evaluateWith(RHSC->getValue()); 318fe6060f1SDimitry Andric // The only non-OBO case we deal with is or, and only limited to the 319fe6060f1SDimitry Andric // case where it is both nuw and nsw. 320fe6060f1SDimitry Andric bool NUW = true, NSW = true; 321fe6060f1SDimitry Andric if (isa<OverflowingBinaryOperator>(BOp)) { 322fe6060f1SDimitry Andric NUW &= BOp->hasNoUnsignedWrap(); 323fe6060f1SDimitry Andric NSW &= BOp->hasNoSignedWrap(); 324fe6060f1SDimitry Andric } 325fe6060f1SDimitry Andric if (!Val.canDistributeOver(NUW, NSW)) 326fe6060f1SDimitry Andric return Val; 3270b57cec5SDimitry Andric 328fe6060f1SDimitry Andric LinearExpression E(Val); 3290b57cec5SDimitry Andric switch (BOp->getOpcode()) { 3300b57cec5SDimitry Andric default: 3310b57cec5SDimitry Andric // We don't understand this instruction, so we can't decompose it any 3320b57cec5SDimitry Andric // further. 333fe6060f1SDimitry Andric return Val; 3340b57cec5SDimitry Andric case Instruction::Or: 3350b57cec5SDimitry Andric // X|C == X+C if all the bits in C are unset in X. Otherwise we can't 3360b57cec5SDimitry Andric // analyze it. 3370b57cec5SDimitry Andric if (!MaskedValueIsZero(BOp->getOperand(0), RHSC->getValue(), DL, 0, AC, 338fe6060f1SDimitry Andric BOp, DT)) 339fe6060f1SDimitry Andric return Val; 3400b57cec5SDimitry Andric 341fe6060f1SDimitry Andric LLVM_FALLTHROUGH; 342fe6060f1SDimitry Andric case Instruction::Add: { 343fe6060f1SDimitry Andric E = GetLinearExpression(Val.withValue(BOp->getOperand(0)), DL, 344fe6060f1SDimitry Andric Depth + 1, AC, DT); 345fe6060f1SDimitry Andric E.Offset += RHS; 346fe6060f1SDimitry Andric E.IsNSW &= NSW; 347fe6060f1SDimitry Andric break; 348fe6060f1SDimitry Andric } 349fe6060f1SDimitry Andric case Instruction::Sub: { 350fe6060f1SDimitry Andric E = GetLinearExpression(Val.withValue(BOp->getOperand(0)), DL, 351fe6060f1SDimitry Andric Depth + 1, AC, DT); 352fe6060f1SDimitry Andric E.Offset -= RHS; 353fe6060f1SDimitry Andric E.IsNSW &= NSW; 354fe6060f1SDimitry Andric break; 355fe6060f1SDimitry Andric } 356fe6060f1SDimitry Andric case Instruction::Mul: { 357fe6060f1SDimitry Andric E = GetLinearExpression(Val.withValue(BOp->getOperand(0)), DL, 358fe6060f1SDimitry Andric Depth + 1, AC, DT); 359fe6060f1SDimitry Andric E.Offset *= RHS; 360fe6060f1SDimitry Andric E.Scale *= RHS; 361fe6060f1SDimitry Andric E.IsNSW &= NSW; 362fe6060f1SDimitry Andric break; 363fe6060f1SDimitry Andric } 364fe6060f1SDimitry Andric case Instruction::Shl: 3650b57cec5SDimitry Andric // We're trying to linearize an expression of the kind: 3660b57cec5SDimitry Andric // shl i8 -128, 36 3670b57cec5SDimitry Andric // where the shift count exceeds the bitwidth of the type. 3680b57cec5SDimitry Andric // We can't decompose this further (the expression would return 3690b57cec5SDimitry Andric // a poison value). 370fe6060f1SDimitry Andric if (RHS.getLimitedValue() > Val.getBitWidth()) 371fe6060f1SDimitry Andric return Val; 3720b57cec5SDimitry Andric 373fe6060f1SDimitry Andric E = GetLinearExpression(Val.withValue(BOp->getOperand(0)), DL, 374fe6060f1SDimitry Andric Depth + 1, AC, DT); 375fe6060f1SDimitry Andric E.Offset <<= RHS.getLimitedValue(); 376fe6060f1SDimitry Andric E.Scale <<= RHS.getLimitedValue(); 377fe6060f1SDimitry Andric E.IsNSW &= NSW; 378fe6060f1SDimitry Andric break; 3790b57cec5SDimitry Andric } 380fe6060f1SDimitry Andric return E; 3810b57cec5SDimitry Andric } 3820b57cec5SDimitry Andric } 3830b57cec5SDimitry Andric 384fe6060f1SDimitry Andric if (isa<ZExtInst>(Val.V)) 385fe6060f1SDimitry Andric return GetLinearExpression( 386fe6060f1SDimitry Andric Val.withZExtOfValue(cast<CastInst>(Val.V)->getOperand(0)), 387fe6060f1SDimitry Andric DL, Depth + 1, AC, DT); 3880b57cec5SDimitry Andric 389fe6060f1SDimitry Andric if (isa<SExtInst>(Val.V)) 390fe6060f1SDimitry Andric return GetLinearExpression( 391fe6060f1SDimitry Andric Val.withSExtOfValue(cast<CastInst>(Val.V)->getOperand(0)), 392fe6060f1SDimitry Andric DL, Depth + 1, AC, DT); 3930b57cec5SDimitry Andric 394fe6060f1SDimitry Andric return Val; 3950b57cec5SDimitry Andric } 3960b57cec5SDimitry Andric 3970b57cec5SDimitry Andric /// To ensure a pointer offset fits in an integer of size PointerSize 3980b57cec5SDimitry Andric /// (in bits) when that size is smaller than the maximum pointer size. This is 3990b57cec5SDimitry Andric /// an issue, for example, in particular for 32b pointers with negative indices 4000b57cec5SDimitry Andric /// that rely on two's complement wrap-arounds for precise alias information 4010b57cec5SDimitry Andric /// where the maximum pointer size is 64b. 4025ffd83dbSDimitry Andric static APInt adjustToPointerSize(const APInt &Offset, unsigned PointerSize) { 4030b57cec5SDimitry Andric assert(PointerSize <= Offset.getBitWidth() && "Invalid PointerSize!"); 4040b57cec5SDimitry Andric unsigned ShiftBits = Offset.getBitWidth() - PointerSize; 4050b57cec5SDimitry Andric return (Offset << ShiftBits).ashr(ShiftBits); 4060b57cec5SDimitry Andric } 4070b57cec5SDimitry Andric 4080b57cec5SDimitry Andric static unsigned getMaxPointerSize(const DataLayout &DL) { 4090b57cec5SDimitry Andric unsigned MaxPointerSize = DL.getMaxPointerSizeInBits(); 4100b57cec5SDimitry Andric if (MaxPointerSize < 64 && ForceAtLeast64Bits) MaxPointerSize = 64; 4110b57cec5SDimitry Andric if (DoubleCalcBits) MaxPointerSize *= 2; 4120b57cec5SDimitry Andric 4130b57cec5SDimitry Andric return MaxPointerSize; 4140b57cec5SDimitry Andric } 4150b57cec5SDimitry Andric 4160b57cec5SDimitry Andric /// If V is a symbolic pointer expression, decompose it into a base pointer 4170b57cec5SDimitry Andric /// with a constant offset and a number of scaled symbolic offsets. 4180b57cec5SDimitry Andric /// 4190b57cec5SDimitry Andric /// The scaled symbolic offsets (represented by pairs of a Value* and a scale 4200b57cec5SDimitry Andric /// in the VarIndices vector) are Value*'s that are known to be scaled by the 4210b57cec5SDimitry Andric /// specified amount, but which may have other unrepresented high bits. As 4220b57cec5SDimitry Andric /// such, the gep cannot necessarily be reconstructed from its decomposed form. 4230b57cec5SDimitry Andric /// 424e8d8bef9SDimitry Andric /// This function is capable of analyzing everything that getUnderlyingObject 425e8d8bef9SDimitry Andric /// can look through. To be able to do that getUnderlyingObject and 426e8d8bef9SDimitry Andric /// DecomposeGEPExpression must use the same search depth 427e8d8bef9SDimitry Andric /// (MaxLookupSearchDepth). 428e8d8bef9SDimitry Andric BasicAAResult::DecomposedGEP 429e8d8bef9SDimitry Andric BasicAAResult::DecomposeGEPExpression(const Value *V, const DataLayout &DL, 430e8d8bef9SDimitry Andric AssumptionCache *AC, DominatorTree *DT) { 4310b57cec5SDimitry Andric // Limit recursion depth to limit compile time in crazy cases. 4320b57cec5SDimitry Andric unsigned MaxLookup = MaxLookupSearchDepth; 4330b57cec5SDimitry Andric SearchTimes++; 434e8d8bef9SDimitry Andric const Instruction *CxtI = dyn_cast<Instruction>(V); 4350b57cec5SDimitry Andric 4360b57cec5SDimitry Andric unsigned MaxPointerSize = getMaxPointerSize(DL); 437e8d8bef9SDimitry Andric DecomposedGEP Decomposed; 438e8d8bef9SDimitry Andric Decomposed.Offset = APInt(MaxPointerSize, 0); 439e8d8bef9SDimitry Andric Decomposed.HasCompileTimeConstantScale = true; 4400b57cec5SDimitry Andric do { 4410b57cec5SDimitry Andric // See if this is a bitcast or GEP. 4420b57cec5SDimitry Andric const Operator *Op = dyn_cast<Operator>(V); 4430b57cec5SDimitry Andric if (!Op) { 4440b57cec5SDimitry Andric // The only non-operator case we can handle are GlobalAliases. 4450b57cec5SDimitry Andric if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) { 4460b57cec5SDimitry Andric if (!GA->isInterposable()) { 4470b57cec5SDimitry Andric V = GA->getAliasee(); 4480b57cec5SDimitry Andric continue; 4490b57cec5SDimitry Andric } 4500b57cec5SDimitry Andric } 4510b57cec5SDimitry Andric Decomposed.Base = V; 452e8d8bef9SDimitry Andric return Decomposed; 4530b57cec5SDimitry Andric } 4540b57cec5SDimitry Andric 4550b57cec5SDimitry Andric if (Op->getOpcode() == Instruction::BitCast || 4560b57cec5SDimitry Andric Op->getOpcode() == Instruction::AddrSpaceCast) { 4570b57cec5SDimitry Andric V = Op->getOperand(0); 4580b57cec5SDimitry Andric continue; 4590b57cec5SDimitry Andric } 4600b57cec5SDimitry Andric 4610b57cec5SDimitry Andric const GEPOperator *GEPOp = dyn_cast<GEPOperator>(Op); 4620b57cec5SDimitry Andric if (!GEPOp) { 4635ffd83dbSDimitry Andric if (const auto *PHI = dyn_cast<PHINode>(V)) { 4645ffd83dbSDimitry Andric // Look through single-arg phi nodes created by LCSSA. 4655ffd83dbSDimitry Andric if (PHI->getNumIncomingValues() == 1) { 4665ffd83dbSDimitry Andric V = PHI->getIncomingValue(0); 4675ffd83dbSDimitry Andric continue; 4685ffd83dbSDimitry Andric } 4695ffd83dbSDimitry Andric } else if (const auto *Call = dyn_cast<CallBase>(V)) { 4700b57cec5SDimitry Andric // CaptureTracking can know about special capturing properties of some 4710b57cec5SDimitry Andric // intrinsics like launder.invariant.group, that can't be expressed with 4720b57cec5SDimitry Andric // the attributes, but have properties like returning aliasing pointer. 4730b57cec5SDimitry Andric // Because some analysis may assume that nocaptured pointer is not 4740b57cec5SDimitry Andric // returned from some special intrinsic (because function would have to 4750b57cec5SDimitry Andric // be marked with returns attribute), it is crucial to use this function 4760b57cec5SDimitry Andric // because it should be in sync with CaptureTracking. Not using it may 4770b57cec5SDimitry Andric // cause weird miscompilations where 2 aliasing pointers are assumed to 4780b57cec5SDimitry Andric // noalias. 4798bcb0991SDimitry Andric if (auto *RP = getArgumentAliasingToReturnedPointer(Call, false)) { 4800b57cec5SDimitry Andric V = RP; 4810b57cec5SDimitry Andric continue; 4820b57cec5SDimitry Andric } 4830b57cec5SDimitry Andric } 4840b57cec5SDimitry Andric 4850b57cec5SDimitry Andric Decomposed.Base = V; 486e8d8bef9SDimitry Andric return Decomposed; 4870b57cec5SDimitry Andric } 4880b57cec5SDimitry Andric 489fe6060f1SDimitry Andric // Track whether we've seen at least one in bounds gep, and if so, whether 490fe6060f1SDimitry Andric // all geps parsed were in bounds. 491fe6060f1SDimitry Andric if (Decomposed.InBounds == None) 492fe6060f1SDimitry Andric Decomposed.InBounds = GEPOp->isInBounds(); 493fe6060f1SDimitry Andric else if (!GEPOp->isInBounds()) 494fe6060f1SDimitry Andric Decomposed.InBounds = false; 495fe6060f1SDimitry Andric 4960b57cec5SDimitry Andric // Don't attempt to analyze GEPs over unsized objects. 4970b57cec5SDimitry Andric if (!GEPOp->getSourceElementType()->isSized()) { 4980b57cec5SDimitry Andric Decomposed.Base = V; 499e8d8bef9SDimitry Andric return Decomposed; 5000b57cec5SDimitry Andric } 5010b57cec5SDimitry Andric 5025ffd83dbSDimitry Andric // Don't attempt to analyze GEPs if index scale is not a compile-time 5035ffd83dbSDimitry Andric // constant. 5045ffd83dbSDimitry Andric if (isa<ScalableVectorType>(GEPOp->getSourceElementType())) { 5055ffd83dbSDimitry Andric Decomposed.Base = V; 5065ffd83dbSDimitry Andric Decomposed.HasCompileTimeConstantScale = false; 507e8d8bef9SDimitry Andric return Decomposed; 5085ffd83dbSDimitry Andric } 5095ffd83dbSDimitry Andric 5100b57cec5SDimitry Andric unsigned AS = GEPOp->getPointerAddressSpace(); 5110b57cec5SDimitry Andric // Walk the indices of the GEP, accumulating them into BaseOff/VarIndices. 5120b57cec5SDimitry Andric gep_type_iterator GTI = gep_type_begin(GEPOp); 5130b57cec5SDimitry Andric unsigned PointerSize = DL.getPointerSizeInBits(AS); 5140b57cec5SDimitry Andric // Assume all GEP operands are constants until proven otherwise. 5150b57cec5SDimitry Andric bool GepHasConstantOffset = true; 5160b57cec5SDimitry Andric for (User::const_op_iterator I = GEPOp->op_begin() + 1, E = GEPOp->op_end(); 5170b57cec5SDimitry Andric I != E; ++I, ++GTI) { 5180b57cec5SDimitry Andric const Value *Index = *I; 5190b57cec5SDimitry Andric // Compute the (potentially symbolic) offset in bytes for this index. 5200b57cec5SDimitry Andric if (StructType *STy = GTI.getStructTypeOrNull()) { 5210b57cec5SDimitry Andric // For a struct, add the member offset. 5220b57cec5SDimitry Andric unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue(); 5230b57cec5SDimitry Andric if (FieldNo == 0) 5240b57cec5SDimitry Andric continue; 5250b57cec5SDimitry Andric 526e8d8bef9SDimitry Andric Decomposed.Offset += DL.getStructLayout(STy)->getElementOffset(FieldNo); 5270b57cec5SDimitry Andric continue; 5280b57cec5SDimitry Andric } 5290b57cec5SDimitry Andric 5300b57cec5SDimitry Andric // For an array/pointer, add the element offset, explicitly scaled. 5310b57cec5SDimitry Andric if (const ConstantInt *CIdx = dyn_cast<ConstantInt>(Index)) { 5320b57cec5SDimitry Andric if (CIdx->isZero()) 5330b57cec5SDimitry Andric continue; 534e8d8bef9SDimitry Andric Decomposed.Offset += 535e8d8bef9SDimitry Andric DL.getTypeAllocSize(GTI.getIndexedType()).getFixedSize() * 536e8d8bef9SDimitry Andric CIdx->getValue().sextOrTrunc(MaxPointerSize); 5370b57cec5SDimitry Andric continue; 5380b57cec5SDimitry Andric } 5390b57cec5SDimitry Andric 5400b57cec5SDimitry Andric GepHasConstantOffset = false; 5410b57cec5SDimitry Andric 5425ffd83dbSDimitry Andric APInt Scale(MaxPointerSize, 5435ffd83dbSDimitry Andric DL.getTypeAllocSize(GTI.getIndexedType()).getFixedSize()); 5440b57cec5SDimitry Andric // If the integer type is smaller than the pointer size, it is implicitly 5450b57cec5SDimitry Andric // sign extended to pointer size. 5460b57cec5SDimitry Andric unsigned Width = Index->getType()->getIntegerBitWidth(); 547fe6060f1SDimitry Andric unsigned SExtBits = PointerSize > Width ? PointerSize - Width : 0; 548fe6060f1SDimitry Andric LinearExpression LE = GetLinearExpression( 549fe6060f1SDimitry Andric ExtendedValue(Index, 0, SExtBits), DL, 0, AC, DT); 5500b57cec5SDimitry Andric 5510b57cec5SDimitry Andric // The GEP index scale ("Scale") scales C1*V+C2, yielding (C1*V+C2)*Scale. 5520b57cec5SDimitry Andric // This gives us an aggregate computation of (C1*Scale)*V + C2*Scale. 5530b57cec5SDimitry Andric 5540b57cec5SDimitry Andric // It can be the case that, even through C1*V+C2 does not overflow for 5550b57cec5SDimitry Andric // relevant values of V, (C2*Scale) can overflow. In that case, we cannot 5560b57cec5SDimitry Andric // decompose the expression in this way. 5570b57cec5SDimitry Andric // 5580b57cec5SDimitry Andric // FIXME: C1*Scale and the other operations in the decomposed 5590b57cec5SDimitry Andric // (C1*Scale)*V+C2*Scale can also overflow. We should check for this 5600b57cec5SDimitry Andric // possibility. 561e8d8bef9SDimitry Andric bool Overflow; 562fe6060f1SDimitry Andric APInt ScaledOffset = LE.Offset.sextOrTrunc(MaxPointerSize) 563e8d8bef9SDimitry Andric .smul_ov(Scale, Overflow); 564e8d8bef9SDimitry Andric if (Overflow) { 565fe6060f1SDimitry Andric LE = LinearExpression(ExtendedValue(Index, 0, SExtBits)); 5660b57cec5SDimitry Andric } else { 567e8d8bef9SDimitry Andric Decomposed.Offset += ScaledOffset; 568fe6060f1SDimitry Andric Scale *= LE.Scale.sextOrTrunc(MaxPointerSize); 5690b57cec5SDimitry Andric } 5700b57cec5SDimitry Andric 5710b57cec5SDimitry Andric // If we already had an occurrence of this index variable, merge this 5720b57cec5SDimitry Andric // scale into it. For example, we want to handle: 5730b57cec5SDimitry Andric // A[x][x] -> x*16 + x*4 -> x*20 5740b57cec5SDimitry Andric // This also ensures that 'x' only appears in the index list once. 5750b57cec5SDimitry Andric for (unsigned i = 0, e = Decomposed.VarIndices.size(); i != e; ++i) { 576fe6060f1SDimitry Andric if (Decomposed.VarIndices[i].V == LE.Val.V && 577fe6060f1SDimitry Andric Decomposed.VarIndices[i].ZExtBits == LE.Val.ZExtBits && 578fe6060f1SDimitry Andric Decomposed.VarIndices[i].SExtBits == LE.Val.SExtBits) { 5790b57cec5SDimitry Andric Scale += Decomposed.VarIndices[i].Scale; 5800b57cec5SDimitry Andric Decomposed.VarIndices.erase(Decomposed.VarIndices.begin() + i); 5810b57cec5SDimitry Andric break; 5820b57cec5SDimitry Andric } 5830b57cec5SDimitry Andric } 5840b57cec5SDimitry Andric 5850b57cec5SDimitry Andric // Make sure that we have a scale that makes sense for this target's 5860b57cec5SDimitry Andric // pointer size. 5870b57cec5SDimitry Andric Scale = adjustToPointerSize(Scale, PointerSize); 5880b57cec5SDimitry Andric 5890b57cec5SDimitry Andric if (!!Scale) { 590fe6060f1SDimitry Andric VariableGEPIndex Entry = { 591fe6060f1SDimitry Andric LE.Val.V, LE.Val.ZExtBits, LE.Val.SExtBits, Scale, CxtI, LE.IsNSW}; 5920b57cec5SDimitry Andric Decomposed.VarIndices.push_back(Entry); 5930b57cec5SDimitry Andric } 5940b57cec5SDimitry Andric } 5950b57cec5SDimitry Andric 5960b57cec5SDimitry Andric // Take care of wrap-arounds 597e8d8bef9SDimitry Andric if (GepHasConstantOffset) 598e8d8bef9SDimitry Andric Decomposed.Offset = adjustToPointerSize(Decomposed.Offset, PointerSize); 5990b57cec5SDimitry Andric 6000b57cec5SDimitry Andric // Analyze the base pointer next. 6010b57cec5SDimitry Andric V = GEPOp->getOperand(0); 6020b57cec5SDimitry Andric } while (--MaxLookup); 6030b57cec5SDimitry Andric 6040b57cec5SDimitry Andric // If the chain of expressions is too deep, just return early. 6050b57cec5SDimitry Andric Decomposed.Base = V; 6060b57cec5SDimitry Andric SearchLimitReached++; 607e8d8bef9SDimitry Andric return Decomposed; 6080b57cec5SDimitry Andric } 6090b57cec5SDimitry Andric 6100b57cec5SDimitry Andric /// Returns whether the given pointer value points to memory that is local to 6110b57cec5SDimitry Andric /// the function, with global constants being considered local to all 6120b57cec5SDimitry Andric /// functions. 6130b57cec5SDimitry Andric bool BasicAAResult::pointsToConstantMemory(const MemoryLocation &Loc, 6140b57cec5SDimitry Andric AAQueryInfo &AAQI, bool OrLocal) { 6150b57cec5SDimitry Andric assert(Visited.empty() && "Visited must be cleared after use!"); 6160b57cec5SDimitry Andric 6170b57cec5SDimitry Andric unsigned MaxLookup = 8; 6180b57cec5SDimitry Andric SmallVector<const Value *, 16> Worklist; 6190b57cec5SDimitry Andric Worklist.push_back(Loc.Ptr); 6200b57cec5SDimitry Andric do { 621e8d8bef9SDimitry Andric const Value *V = getUnderlyingObject(Worklist.pop_back_val()); 6220b57cec5SDimitry Andric if (!Visited.insert(V).second) { 6230b57cec5SDimitry Andric Visited.clear(); 6240b57cec5SDimitry Andric return AAResultBase::pointsToConstantMemory(Loc, AAQI, OrLocal); 6250b57cec5SDimitry Andric } 6260b57cec5SDimitry Andric 6270b57cec5SDimitry Andric // An alloca instruction defines local memory. 6280b57cec5SDimitry Andric if (OrLocal && isa<AllocaInst>(V)) 6290b57cec5SDimitry Andric continue; 6300b57cec5SDimitry Andric 6310b57cec5SDimitry Andric // A global constant counts as local memory for our purposes. 6320b57cec5SDimitry Andric if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) { 6330b57cec5SDimitry Andric // Note: this doesn't require GV to be "ODR" because it isn't legal for a 6340b57cec5SDimitry Andric // global to be marked constant in some modules and non-constant in 6350b57cec5SDimitry Andric // others. GV may even be a declaration, not a definition. 6360b57cec5SDimitry Andric if (!GV->isConstant()) { 6370b57cec5SDimitry Andric Visited.clear(); 6380b57cec5SDimitry Andric return AAResultBase::pointsToConstantMemory(Loc, AAQI, OrLocal); 6390b57cec5SDimitry Andric } 6400b57cec5SDimitry Andric continue; 6410b57cec5SDimitry Andric } 6420b57cec5SDimitry Andric 6430b57cec5SDimitry Andric // If both select values point to local memory, then so does the select. 6440b57cec5SDimitry Andric if (const SelectInst *SI = dyn_cast<SelectInst>(V)) { 6450b57cec5SDimitry Andric Worklist.push_back(SI->getTrueValue()); 6460b57cec5SDimitry Andric Worklist.push_back(SI->getFalseValue()); 6470b57cec5SDimitry Andric continue; 6480b57cec5SDimitry Andric } 6490b57cec5SDimitry Andric 6500b57cec5SDimitry Andric // If all values incoming to a phi node point to local memory, then so does 6510b57cec5SDimitry Andric // the phi. 6520b57cec5SDimitry Andric if (const PHINode *PN = dyn_cast<PHINode>(V)) { 6530b57cec5SDimitry Andric // Don't bother inspecting phi nodes with many operands. 6540b57cec5SDimitry Andric if (PN->getNumIncomingValues() > MaxLookup) { 6550b57cec5SDimitry Andric Visited.clear(); 6560b57cec5SDimitry Andric return AAResultBase::pointsToConstantMemory(Loc, AAQI, OrLocal); 6570b57cec5SDimitry Andric } 658e8d8bef9SDimitry Andric append_range(Worklist, PN->incoming_values()); 6590b57cec5SDimitry Andric continue; 6600b57cec5SDimitry Andric } 6610b57cec5SDimitry Andric 6620b57cec5SDimitry Andric // Otherwise be conservative. 6630b57cec5SDimitry Andric Visited.clear(); 6640b57cec5SDimitry Andric return AAResultBase::pointsToConstantMemory(Loc, AAQI, OrLocal); 6650b57cec5SDimitry Andric } while (!Worklist.empty() && --MaxLookup); 6660b57cec5SDimitry Andric 6670b57cec5SDimitry Andric Visited.clear(); 6680b57cec5SDimitry Andric return Worklist.empty(); 6690b57cec5SDimitry Andric } 6700b57cec5SDimitry Andric 671fe6060f1SDimitry Andric static bool isIntrinsicCall(const CallBase *Call, Intrinsic::ID IID) { 672fe6060f1SDimitry Andric const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Call); 673fe6060f1SDimitry Andric return II && II->getIntrinsicID() == IID; 674fe6060f1SDimitry Andric } 675fe6060f1SDimitry Andric 6760b57cec5SDimitry Andric /// Returns the behavior when calling the given call site. 6770b57cec5SDimitry Andric FunctionModRefBehavior BasicAAResult::getModRefBehavior(const CallBase *Call) { 6780b57cec5SDimitry Andric if (Call->doesNotAccessMemory()) 6790b57cec5SDimitry Andric // Can't do better than this. 6800b57cec5SDimitry Andric return FMRB_DoesNotAccessMemory; 6810b57cec5SDimitry Andric 6820b57cec5SDimitry Andric FunctionModRefBehavior Min = FMRB_UnknownModRefBehavior; 6830b57cec5SDimitry Andric 6840b57cec5SDimitry Andric // If the callsite knows it only reads memory, don't return worse 6850b57cec5SDimitry Andric // than that. 6860b57cec5SDimitry Andric if (Call->onlyReadsMemory()) 6870b57cec5SDimitry Andric Min = FMRB_OnlyReadsMemory; 6880b57cec5SDimitry Andric else if (Call->doesNotReadMemory()) 6895ffd83dbSDimitry Andric Min = FMRB_OnlyWritesMemory; 6900b57cec5SDimitry Andric 6910b57cec5SDimitry Andric if (Call->onlyAccessesArgMemory()) 6920b57cec5SDimitry Andric Min = FunctionModRefBehavior(Min & FMRB_OnlyAccessesArgumentPointees); 6930b57cec5SDimitry Andric else if (Call->onlyAccessesInaccessibleMemory()) 6940b57cec5SDimitry Andric Min = FunctionModRefBehavior(Min & FMRB_OnlyAccessesInaccessibleMem); 6950b57cec5SDimitry Andric else if (Call->onlyAccessesInaccessibleMemOrArgMem()) 6960b57cec5SDimitry Andric Min = FunctionModRefBehavior(Min & FMRB_OnlyAccessesInaccessibleOrArgMem); 6970b57cec5SDimitry Andric 6980b57cec5SDimitry Andric // If the call has operand bundles then aliasing attributes from the function 6990b57cec5SDimitry Andric // it calls do not directly apply to the call. This can be made more precise 7000b57cec5SDimitry Andric // in the future. 7010b57cec5SDimitry Andric if (!Call->hasOperandBundles()) 7020b57cec5SDimitry Andric if (const Function *F = Call->getCalledFunction()) 7030b57cec5SDimitry Andric Min = 7040b57cec5SDimitry Andric FunctionModRefBehavior(Min & getBestAAResults().getModRefBehavior(F)); 7050b57cec5SDimitry Andric 7060b57cec5SDimitry Andric return Min; 7070b57cec5SDimitry Andric } 7080b57cec5SDimitry Andric 7090b57cec5SDimitry Andric /// Returns the behavior when calling the given function. For use when the call 7100b57cec5SDimitry Andric /// site is not known. 7110b57cec5SDimitry Andric FunctionModRefBehavior BasicAAResult::getModRefBehavior(const Function *F) { 7120b57cec5SDimitry Andric // If the function declares it doesn't access memory, we can't do better. 7130b57cec5SDimitry Andric if (F->doesNotAccessMemory()) 7140b57cec5SDimitry Andric return FMRB_DoesNotAccessMemory; 7150b57cec5SDimitry Andric 7160b57cec5SDimitry Andric FunctionModRefBehavior Min = FMRB_UnknownModRefBehavior; 7170b57cec5SDimitry Andric 7180b57cec5SDimitry Andric // If the function declares it only reads memory, go with that. 7190b57cec5SDimitry Andric if (F->onlyReadsMemory()) 7200b57cec5SDimitry Andric Min = FMRB_OnlyReadsMemory; 7210b57cec5SDimitry Andric else if (F->doesNotReadMemory()) 7225ffd83dbSDimitry Andric Min = FMRB_OnlyWritesMemory; 7230b57cec5SDimitry Andric 7240b57cec5SDimitry Andric if (F->onlyAccessesArgMemory()) 7250b57cec5SDimitry Andric Min = FunctionModRefBehavior(Min & FMRB_OnlyAccessesArgumentPointees); 7260b57cec5SDimitry Andric else if (F->onlyAccessesInaccessibleMemory()) 7270b57cec5SDimitry Andric Min = FunctionModRefBehavior(Min & FMRB_OnlyAccessesInaccessibleMem); 7280b57cec5SDimitry Andric else if (F->onlyAccessesInaccessibleMemOrArgMem()) 7290b57cec5SDimitry Andric Min = FunctionModRefBehavior(Min & FMRB_OnlyAccessesInaccessibleOrArgMem); 7300b57cec5SDimitry Andric 7310b57cec5SDimitry Andric return Min; 7320b57cec5SDimitry Andric } 7330b57cec5SDimitry Andric 7340b57cec5SDimitry Andric /// Returns true if this is a writeonly (i.e Mod only) parameter. 7350b57cec5SDimitry Andric static bool isWriteOnlyParam(const CallBase *Call, unsigned ArgIdx, 7360b57cec5SDimitry Andric const TargetLibraryInfo &TLI) { 7370b57cec5SDimitry Andric if (Call->paramHasAttr(ArgIdx, Attribute::WriteOnly)) 7380b57cec5SDimitry Andric return true; 7390b57cec5SDimitry Andric 7400b57cec5SDimitry Andric // We can bound the aliasing properties of memset_pattern16 just as we can 7410b57cec5SDimitry Andric // for memcpy/memset. This is particularly important because the 7420b57cec5SDimitry Andric // LoopIdiomRecognizer likes to turn loops into calls to memset_pattern16 7430b57cec5SDimitry Andric // whenever possible. 7440b57cec5SDimitry Andric // FIXME Consider handling this in InferFunctionAttr.cpp together with other 7450b57cec5SDimitry Andric // attributes. 7460b57cec5SDimitry Andric LibFunc F; 7470b57cec5SDimitry Andric if (Call->getCalledFunction() && 7480b57cec5SDimitry Andric TLI.getLibFunc(*Call->getCalledFunction(), F) && 7490b57cec5SDimitry Andric F == LibFunc_memset_pattern16 && TLI.has(F)) 7500b57cec5SDimitry Andric if (ArgIdx == 0) 7510b57cec5SDimitry Andric return true; 7520b57cec5SDimitry Andric 7530b57cec5SDimitry Andric // TODO: memset_pattern4, memset_pattern8 7540b57cec5SDimitry Andric // TODO: _chk variants 7550b57cec5SDimitry Andric // TODO: strcmp, strcpy 7560b57cec5SDimitry Andric 7570b57cec5SDimitry Andric return false; 7580b57cec5SDimitry Andric } 7590b57cec5SDimitry Andric 7600b57cec5SDimitry Andric ModRefInfo BasicAAResult::getArgModRefInfo(const CallBase *Call, 7610b57cec5SDimitry Andric unsigned ArgIdx) { 7620b57cec5SDimitry Andric // Checking for known builtin intrinsics and target library functions. 7630b57cec5SDimitry Andric if (isWriteOnlyParam(Call, ArgIdx, TLI)) 7640b57cec5SDimitry Andric return ModRefInfo::Mod; 7650b57cec5SDimitry Andric 7660b57cec5SDimitry Andric if (Call->paramHasAttr(ArgIdx, Attribute::ReadOnly)) 7670b57cec5SDimitry Andric return ModRefInfo::Ref; 7680b57cec5SDimitry Andric 7690b57cec5SDimitry Andric if (Call->paramHasAttr(ArgIdx, Attribute::ReadNone)) 7700b57cec5SDimitry Andric return ModRefInfo::NoModRef; 7710b57cec5SDimitry Andric 7720b57cec5SDimitry Andric return AAResultBase::getArgModRefInfo(Call, ArgIdx); 7730b57cec5SDimitry Andric } 7740b57cec5SDimitry Andric 7750b57cec5SDimitry Andric #ifndef NDEBUG 7760b57cec5SDimitry Andric static const Function *getParent(const Value *V) { 7770b57cec5SDimitry Andric if (const Instruction *inst = dyn_cast<Instruction>(V)) { 7780b57cec5SDimitry Andric if (!inst->getParent()) 7790b57cec5SDimitry Andric return nullptr; 7800b57cec5SDimitry Andric return inst->getParent()->getParent(); 7810b57cec5SDimitry Andric } 7820b57cec5SDimitry Andric 7830b57cec5SDimitry Andric if (const Argument *arg = dyn_cast<Argument>(V)) 7840b57cec5SDimitry Andric return arg->getParent(); 7850b57cec5SDimitry Andric 7860b57cec5SDimitry Andric return nullptr; 7870b57cec5SDimitry Andric } 7880b57cec5SDimitry Andric 7890b57cec5SDimitry Andric static bool notDifferentParent(const Value *O1, const Value *O2) { 7900b57cec5SDimitry Andric 7910b57cec5SDimitry Andric const Function *F1 = getParent(O1); 7920b57cec5SDimitry Andric const Function *F2 = getParent(O2); 7930b57cec5SDimitry Andric 7940b57cec5SDimitry Andric return !F1 || !F2 || F1 == F2; 7950b57cec5SDimitry Andric } 7960b57cec5SDimitry Andric #endif 7970b57cec5SDimitry Andric 7980b57cec5SDimitry Andric AliasResult BasicAAResult::alias(const MemoryLocation &LocA, 7990b57cec5SDimitry Andric const MemoryLocation &LocB, 8000b57cec5SDimitry Andric AAQueryInfo &AAQI) { 8010b57cec5SDimitry Andric assert(notDifferentParent(LocA.Ptr, LocB.Ptr) && 8020b57cec5SDimitry Andric "BasicAliasAnalysis doesn't support interprocedural queries."); 803fe6060f1SDimitry Andric return aliasCheck(LocA.Ptr, LocA.Size, LocB.Ptr, LocB.Size, AAQI); 8040b57cec5SDimitry Andric } 8050b57cec5SDimitry Andric 8060b57cec5SDimitry Andric /// Checks to see if the specified callsite can clobber the specified memory 8070b57cec5SDimitry Andric /// object. 8080b57cec5SDimitry Andric /// 8090b57cec5SDimitry Andric /// Since we only look at local properties of this function, we really can't 8100b57cec5SDimitry Andric /// say much about this query. We do, however, use simple "address taken" 8110b57cec5SDimitry Andric /// analysis on local objects. 8120b57cec5SDimitry Andric ModRefInfo BasicAAResult::getModRefInfo(const CallBase *Call, 8130b57cec5SDimitry Andric const MemoryLocation &Loc, 8140b57cec5SDimitry Andric AAQueryInfo &AAQI) { 8150b57cec5SDimitry Andric assert(notDifferentParent(Call, Loc.Ptr) && 8160b57cec5SDimitry Andric "AliasAnalysis query involving multiple functions!"); 8170b57cec5SDimitry Andric 818e8d8bef9SDimitry Andric const Value *Object = getUnderlyingObject(Loc.Ptr); 8190b57cec5SDimitry Andric 8200b57cec5SDimitry Andric // Calls marked 'tail' cannot read or write allocas from the current frame 8210b57cec5SDimitry Andric // because the current frame might be destroyed by the time they run. However, 8220b57cec5SDimitry Andric // a tail call may use an alloca with byval. Calling with byval copies the 8230b57cec5SDimitry Andric // contents of the alloca into argument registers or stack slots, so there is 8240b57cec5SDimitry Andric // no lifetime issue. 8250b57cec5SDimitry Andric if (isa<AllocaInst>(Object)) 8260b57cec5SDimitry Andric if (const CallInst *CI = dyn_cast<CallInst>(Call)) 8270b57cec5SDimitry Andric if (CI->isTailCall() && 8280b57cec5SDimitry Andric !CI->getAttributes().hasAttrSomewhere(Attribute::ByVal)) 8290b57cec5SDimitry Andric return ModRefInfo::NoModRef; 8300b57cec5SDimitry Andric 8310b57cec5SDimitry Andric // Stack restore is able to modify unescaped dynamic allocas. Assume it may 8320b57cec5SDimitry Andric // modify them even though the alloca is not escaped. 8330b57cec5SDimitry Andric if (auto *AI = dyn_cast<AllocaInst>(Object)) 8340b57cec5SDimitry Andric if (!AI->isStaticAlloca() && isIntrinsicCall(Call, Intrinsic::stackrestore)) 8350b57cec5SDimitry Andric return ModRefInfo::Mod; 8360b57cec5SDimitry Andric 8370b57cec5SDimitry Andric // If the pointer is to a locally allocated object that does not escape, 8380b57cec5SDimitry Andric // then the call can not mod/ref the pointer unless the call takes the pointer 8390b57cec5SDimitry Andric // as an argument, and itself doesn't capture it. 8400b57cec5SDimitry Andric if (!isa<Constant>(Object) && Call != Object && 8410b57cec5SDimitry Andric isNonEscapingLocalObject(Object, &AAQI.IsCapturedCache)) { 8420b57cec5SDimitry Andric 8430b57cec5SDimitry Andric // Optimistically assume that call doesn't touch Object and check this 8440b57cec5SDimitry Andric // assumption in the following loop. 8450b57cec5SDimitry Andric ModRefInfo Result = ModRefInfo::NoModRef; 8460b57cec5SDimitry Andric bool IsMustAlias = true; 8470b57cec5SDimitry Andric 8480b57cec5SDimitry Andric unsigned OperandNo = 0; 8490b57cec5SDimitry Andric for (auto CI = Call->data_operands_begin(), CE = Call->data_operands_end(); 8500b57cec5SDimitry Andric CI != CE; ++CI, ++OperandNo) { 8510b57cec5SDimitry Andric // Only look at the no-capture or byval pointer arguments. If this 8520b57cec5SDimitry Andric // pointer were passed to arguments that were neither of these, then it 8530b57cec5SDimitry Andric // couldn't be no-capture. 8540b57cec5SDimitry Andric if (!(*CI)->getType()->isPointerTy() || 8550b57cec5SDimitry Andric (!Call->doesNotCapture(OperandNo) && 8560b57cec5SDimitry Andric OperandNo < Call->getNumArgOperands() && 8570b57cec5SDimitry Andric !Call->isByValArgument(OperandNo))) 8580b57cec5SDimitry Andric continue; 8590b57cec5SDimitry Andric 8600b57cec5SDimitry Andric // Call doesn't access memory through this operand, so we don't care 8610b57cec5SDimitry Andric // if it aliases with Object. 8620b57cec5SDimitry Andric if (Call->doesNotAccessMemory(OperandNo)) 8630b57cec5SDimitry Andric continue; 8640b57cec5SDimitry Andric 8650b57cec5SDimitry Andric // If this is a no-capture pointer argument, see if we can tell that it 8660b57cec5SDimitry Andric // is impossible to alias the pointer we're checking. 867e8d8bef9SDimitry Andric AliasResult AR = getBestAAResults().alias( 868e8d8bef9SDimitry Andric MemoryLocation::getBeforeOrAfter(*CI), 869e8d8bef9SDimitry Andric MemoryLocation::getBeforeOrAfter(Object), AAQI); 870fe6060f1SDimitry Andric if (AR != AliasResult::MustAlias) 8710b57cec5SDimitry Andric IsMustAlias = false; 8720b57cec5SDimitry Andric // Operand doesn't alias 'Object', continue looking for other aliases 873fe6060f1SDimitry Andric if (AR == AliasResult::NoAlias) 8740b57cec5SDimitry Andric continue; 8750b57cec5SDimitry Andric // Operand aliases 'Object', but call doesn't modify it. Strengthen 8760b57cec5SDimitry Andric // initial assumption and keep looking in case if there are more aliases. 8770b57cec5SDimitry Andric if (Call->onlyReadsMemory(OperandNo)) { 8780b57cec5SDimitry Andric Result = setRef(Result); 8790b57cec5SDimitry Andric continue; 8800b57cec5SDimitry Andric } 8810b57cec5SDimitry Andric // Operand aliases 'Object' but call only writes into it. 8820b57cec5SDimitry Andric if (Call->doesNotReadMemory(OperandNo)) { 8830b57cec5SDimitry Andric Result = setMod(Result); 8840b57cec5SDimitry Andric continue; 8850b57cec5SDimitry Andric } 8860b57cec5SDimitry Andric // This operand aliases 'Object' and call reads and writes into it. 8870b57cec5SDimitry Andric // Setting ModRef will not yield an early return below, MustAlias is not 8880b57cec5SDimitry Andric // used further. 8890b57cec5SDimitry Andric Result = ModRefInfo::ModRef; 8900b57cec5SDimitry Andric break; 8910b57cec5SDimitry Andric } 8920b57cec5SDimitry Andric 8930b57cec5SDimitry Andric // No operand aliases, reset Must bit. Add below if at least one aliases 8940b57cec5SDimitry Andric // and all aliases found are MustAlias. 8950b57cec5SDimitry Andric if (isNoModRef(Result)) 8960b57cec5SDimitry Andric IsMustAlias = false; 8970b57cec5SDimitry Andric 8980b57cec5SDimitry Andric // Early return if we improved mod ref information 8990b57cec5SDimitry Andric if (!isModAndRefSet(Result)) { 9000b57cec5SDimitry Andric if (isNoModRef(Result)) 9010b57cec5SDimitry Andric return ModRefInfo::NoModRef; 9020b57cec5SDimitry Andric return IsMustAlias ? setMust(Result) : clearMust(Result); 9030b57cec5SDimitry Andric } 9040b57cec5SDimitry Andric } 9050b57cec5SDimitry Andric 9065ffd83dbSDimitry Andric // If the call is malloc/calloc like, we can assume that it doesn't 9070b57cec5SDimitry Andric // modify any IR visible value. This is only valid because we assume these 9080b57cec5SDimitry Andric // routines do not read values visible in the IR. TODO: Consider special 9090b57cec5SDimitry Andric // casing realloc and strdup routines which access only their arguments as 9100b57cec5SDimitry Andric // well. Or alternatively, replace all of this with inaccessiblememonly once 9110b57cec5SDimitry Andric // that's implemented fully. 9120b57cec5SDimitry Andric if (isMallocOrCallocLikeFn(Call, &TLI)) { 9130b57cec5SDimitry Andric // Be conservative if the accessed pointer may alias the allocation - 9140b57cec5SDimitry Andric // fallback to the generic handling below. 915fe6060f1SDimitry Andric if (getBestAAResults().alias(MemoryLocation::getBeforeOrAfter(Call), Loc, 916fe6060f1SDimitry Andric AAQI) == AliasResult::NoAlias) 9170b57cec5SDimitry Andric return ModRefInfo::NoModRef; 9180b57cec5SDimitry Andric } 9190b57cec5SDimitry Andric 920e8d8bef9SDimitry Andric // The semantics of memcpy intrinsics either exactly overlap or do not 921e8d8bef9SDimitry Andric // overlap, i.e., source and destination of any given memcpy are either 922e8d8bef9SDimitry Andric // no-alias or must-alias. 9230b57cec5SDimitry Andric if (auto *Inst = dyn_cast<AnyMemCpyInst>(Call)) { 924e8d8bef9SDimitry Andric AliasResult SrcAA = 925e8d8bef9SDimitry Andric getBestAAResults().alias(MemoryLocation::getForSource(Inst), Loc, AAQI); 926e8d8bef9SDimitry Andric AliasResult DestAA = 927e8d8bef9SDimitry Andric getBestAAResults().alias(MemoryLocation::getForDest(Inst), Loc, AAQI); 9280b57cec5SDimitry Andric // It's also possible for Loc to alias both src and dest, or neither. 9290b57cec5SDimitry Andric ModRefInfo rv = ModRefInfo::NoModRef; 930fe6060f1SDimitry Andric if (SrcAA != AliasResult::NoAlias) 9310b57cec5SDimitry Andric rv = setRef(rv); 932fe6060f1SDimitry Andric if (DestAA != AliasResult::NoAlias) 9330b57cec5SDimitry Andric rv = setMod(rv); 9340b57cec5SDimitry Andric return rv; 9350b57cec5SDimitry Andric } 9360b57cec5SDimitry Andric 937fe6060f1SDimitry Andric // Guard intrinsics are marked as arbitrarily writing so that proper control 938fe6060f1SDimitry Andric // dependencies are maintained but they never mods any particular memory 939fe6060f1SDimitry Andric // location. 9400b57cec5SDimitry Andric // 9410b57cec5SDimitry Andric // *Unlike* assumes, guard intrinsics are modeled as reading memory since the 9420b57cec5SDimitry Andric // heap state at the point the guard is issued needs to be consistent in case 9430b57cec5SDimitry Andric // the guard invokes the "deopt" continuation. 9440b57cec5SDimitry Andric if (isIntrinsicCall(Call, Intrinsic::experimental_guard)) 9450b57cec5SDimitry Andric return ModRefInfo::Ref; 946e8d8bef9SDimitry Andric // The same applies to deoptimize which is essentially a guard(false). 947e8d8bef9SDimitry Andric if (isIntrinsicCall(Call, Intrinsic::experimental_deoptimize)) 948e8d8bef9SDimitry Andric return ModRefInfo::Ref; 9490b57cec5SDimitry Andric 9500b57cec5SDimitry Andric // Like assumes, invariant.start intrinsics were also marked as arbitrarily 9510b57cec5SDimitry Andric // writing so that proper control dependencies are maintained but they never 9520b57cec5SDimitry Andric // mod any particular memory location visible to the IR. 9530b57cec5SDimitry Andric // *Unlike* assumes (which are now modeled as NoModRef), invariant.start 9540b57cec5SDimitry Andric // intrinsic is now modeled as reading memory. This prevents hoisting the 9550b57cec5SDimitry Andric // invariant.start intrinsic over stores. Consider: 9560b57cec5SDimitry Andric // *ptr = 40; 9570b57cec5SDimitry Andric // *ptr = 50; 9580b57cec5SDimitry Andric // invariant_start(ptr) 9590b57cec5SDimitry Andric // int val = *ptr; 9600b57cec5SDimitry Andric // print(val); 9610b57cec5SDimitry Andric // 9620b57cec5SDimitry Andric // This cannot be transformed to: 9630b57cec5SDimitry Andric // 9640b57cec5SDimitry Andric // *ptr = 40; 9650b57cec5SDimitry Andric // invariant_start(ptr) 9660b57cec5SDimitry Andric // *ptr = 50; 9670b57cec5SDimitry Andric // int val = *ptr; 9680b57cec5SDimitry Andric // print(val); 9690b57cec5SDimitry Andric // 9700b57cec5SDimitry Andric // The transformation will cause the second store to be ignored (based on 9710b57cec5SDimitry Andric // rules of invariant.start) and print 40, while the first program always 9720b57cec5SDimitry Andric // prints 50. 9730b57cec5SDimitry Andric if (isIntrinsicCall(Call, Intrinsic::invariant_start)) 9740b57cec5SDimitry Andric return ModRefInfo::Ref; 9750b57cec5SDimitry Andric 9760b57cec5SDimitry Andric // The AAResultBase base class has some smarts, lets use them. 9770b57cec5SDimitry Andric return AAResultBase::getModRefInfo(Call, Loc, AAQI); 9780b57cec5SDimitry Andric } 9790b57cec5SDimitry Andric 9800b57cec5SDimitry Andric ModRefInfo BasicAAResult::getModRefInfo(const CallBase *Call1, 9810b57cec5SDimitry Andric const CallBase *Call2, 9820b57cec5SDimitry Andric AAQueryInfo &AAQI) { 983fe6060f1SDimitry Andric // Guard intrinsics are marked as arbitrarily writing so that proper control 984fe6060f1SDimitry Andric // dependencies are maintained but they never mods any particular memory 985fe6060f1SDimitry Andric // location. 9860b57cec5SDimitry Andric // 9870b57cec5SDimitry Andric // *Unlike* assumes, guard intrinsics are modeled as reading memory since the 9880b57cec5SDimitry Andric // heap state at the point the guard is issued needs to be consistent in case 9890b57cec5SDimitry Andric // the guard invokes the "deopt" continuation. 9900b57cec5SDimitry Andric 9910b57cec5SDimitry Andric // NB! This function is *not* commutative, so we special case two 9920b57cec5SDimitry Andric // possibilities for guard intrinsics. 9930b57cec5SDimitry Andric 9940b57cec5SDimitry Andric if (isIntrinsicCall(Call1, Intrinsic::experimental_guard)) 9950b57cec5SDimitry Andric return isModSet(createModRefInfo(getModRefBehavior(Call2))) 9960b57cec5SDimitry Andric ? ModRefInfo::Ref 9970b57cec5SDimitry Andric : ModRefInfo::NoModRef; 9980b57cec5SDimitry Andric 9990b57cec5SDimitry Andric if (isIntrinsicCall(Call2, Intrinsic::experimental_guard)) 10000b57cec5SDimitry Andric return isModSet(createModRefInfo(getModRefBehavior(Call1))) 10010b57cec5SDimitry Andric ? ModRefInfo::Mod 10020b57cec5SDimitry Andric : ModRefInfo::NoModRef; 10030b57cec5SDimitry Andric 10040b57cec5SDimitry Andric // The AAResultBase base class has some smarts, lets use them. 10050b57cec5SDimitry Andric return AAResultBase::getModRefInfo(Call1, Call2, AAQI); 10060b57cec5SDimitry Andric } 10070b57cec5SDimitry Andric 1008fe6060f1SDimitry Andric /// Return true if we know V to the base address of the corresponding memory 1009fe6060f1SDimitry Andric /// object. This implies that any address less than V must be out of bounds 1010fe6060f1SDimitry Andric /// for the underlying object. Note that just being isIdentifiedObject() is 1011fe6060f1SDimitry Andric /// not enough - For example, a negative offset from a noalias argument or call 1012fe6060f1SDimitry Andric /// can be inbounds w.r.t the actual underlying object. 1013fe6060f1SDimitry Andric static bool isBaseOfObject(const Value *V) { 1014fe6060f1SDimitry Andric // TODO: We can handle other cases here 1015fe6060f1SDimitry Andric // 1) For GC languages, arguments to functions are often required to be 1016fe6060f1SDimitry Andric // base pointers. 1017fe6060f1SDimitry Andric // 2) Result of allocation routines are often base pointers. Leverage TLI. 1018fe6060f1SDimitry Andric return (isa<AllocaInst>(V) || isa<GlobalVariable>(V)); 10190b57cec5SDimitry Andric } 10200b57cec5SDimitry Andric 10210b57cec5SDimitry Andric /// Provides a bunch of ad-hoc rules to disambiguate a GEP instruction against 10220b57cec5SDimitry Andric /// another pointer. 10230b57cec5SDimitry Andric /// 10240b57cec5SDimitry Andric /// We know that V1 is a GEP, but we don't know anything about V2. 1025e8d8bef9SDimitry Andric /// UnderlyingV1 is getUnderlyingObject(GEP1), UnderlyingV2 is the same for 10260b57cec5SDimitry Andric /// V2. 10270b57cec5SDimitry Andric AliasResult BasicAAResult::aliasGEP( 1028fe6060f1SDimitry Andric const GEPOperator *GEP1, LocationSize V1Size, 1029fe6060f1SDimitry Andric const Value *V2, LocationSize V2Size, 10300b57cec5SDimitry Andric const Value *UnderlyingV1, const Value *UnderlyingV2, AAQueryInfo &AAQI) { 1031fe6060f1SDimitry Andric if (!V1Size.hasValue() && !V2Size.hasValue()) { 1032fe6060f1SDimitry Andric // TODO: This limitation exists for compile-time reasons. Relax it if we 1033fe6060f1SDimitry Andric // can avoid exponential pathological cases. 1034fe6060f1SDimitry Andric if (!isa<GEPOperator>(V2)) 1035fe6060f1SDimitry Andric return AliasResult::MayAlias; 1036fe6060f1SDimitry Andric 1037fe6060f1SDimitry Andric // If both accesses have unknown size, we can only check whether the base 1038fe6060f1SDimitry Andric // objects don't alias. 1039fe6060f1SDimitry Andric AliasResult BaseAlias = getBestAAResults().alias( 1040fe6060f1SDimitry Andric MemoryLocation::getBeforeOrAfter(UnderlyingV1), 1041fe6060f1SDimitry Andric MemoryLocation::getBeforeOrAfter(UnderlyingV2), AAQI); 1042fe6060f1SDimitry Andric return BaseAlias == AliasResult::NoAlias ? AliasResult::NoAlias 1043fe6060f1SDimitry Andric : AliasResult::MayAlias; 1044fe6060f1SDimitry Andric } 1045fe6060f1SDimitry Andric 1046e8d8bef9SDimitry Andric DecomposedGEP DecompGEP1 = DecomposeGEPExpression(GEP1, DL, &AC, DT); 1047e8d8bef9SDimitry Andric DecomposedGEP DecompGEP2 = DecomposeGEPExpression(V2, DL, &AC, DT); 10480b57cec5SDimitry Andric 10495ffd83dbSDimitry Andric // Don't attempt to analyze the decomposed GEP if index scale is not a 10505ffd83dbSDimitry Andric // compile-time constant. 10515ffd83dbSDimitry Andric if (!DecompGEP1.HasCompileTimeConstantScale || 10525ffd83dbSDimitry Andric !DecompGEP2.HasCompileTimeConstantScale) 1053fe6060f1SDimitry Andric return AliasResult::MayAlias; 10545ffd83dbSDimitry Andric 10550b57cec5SDimitry Andric assert(DecompGEP1.Base == UnderlyingV1 && DecompGEP2.Base == UnderlyingV2 && 10560b57cec5SDimitry Andric "DecomposeGEPExpression returned a result different from " 1057e8d8bef9SDimitry Andric "getUnderlyingObject"); 10580b57cec5SDimitry Andric 10590b57cec5SDimitry Andric // Subtract the GEP2 pointer from the GEP1 pointer to find out their 10600b57cec5SDimitry Andric // symbolic difference. 1061e8d8bef9SDimitry Andric DecompGEP1.Offset -= DecompGEP2.Offset; 10620b57cec5SDimitry Andric GetIndexDifference(DecompGEP1.VarIndices, DecompGEP2.VarIndices); 10630b57cec5SDimitry Andric 1064fe6060f1SDimitry Andric // If an inbounds GEP would have to start from an out of bounds address 1065fe6060f1SDimitry Andric // for the two to alias, then we can assume noalias. 1066fe6060f1SDimitry Andric if (*DecompGEP1.InBounds && DecompGEP1.VarIndices.empty() && 1067fe6060f1SDimitry Andric V2Size.hasValue() && DecompGEP1.Offset.sge(V2Size.getValue()) && 1068fe6060f1SDimitry Andric isBaseOfObject(DecompGEP2.Base)) 1069fe6060f1SDimitry Andric return AliasResult::NoAlias; 10700b57cec5SDimitry Andric 1071fe6060f1SDimitry Andric if (isa<GEPOperator>(V2)) { 1072fe6060f1SDimitry Andric // Symmetric case to above. 1073fe6060f1SDimitry Andric if (*DecompGEP2.InBounds && DecompGEP1.VarIndices.empty() && 1074fe6060f1SDimitry Andric V1Size.hasValue() && DecompGEP1.Offset.sle(-V1Size.getValue()) && 1075fe6060f1SDimitry Andric isBaseOfObject(DecompGEP1.Base)) 1076fe6060f1SDimitry Andric return AliasResult::NoAlias; 10770b57cec5SDimitry Andric } 10780b57cec5SDimitry Andric 1079fe6060f1SDimitry Andric // For GEPs with identical offsets, we can preserve the size and AAInfo 1080fe6060f1SDimitry Andric // when performing the alias check on the underlying objects. 1081e8d8bef9SDimitry Andric if (DecompGEP1.Offset == 0 && DecompGEP1.VarIndices.empty()) 1082fe6060f1SDimitry Andric return getBestAAResults().alias( 1083fe6060f1SDimitry Andric MemoryLocation(UnderlyingV1, V1Size), 1084fe6060f1SDimitry Andric MemoryLocation(UnderlyingV2, V2Size), AAQI); 1085fe6060f1SDimitry Andric 1086fe6060f1SDimitry Andric // Do the base pointers alias? 1087fe6060f1SDimitry Andric AliasResult BaseAlias = getBestAAResults().alias( 1088fe6060f1SDimitry Andric MemoryLocation::getBeforeOrAfter(UnderlyingV1), 1089fe6060f1SDimitry Andric MemoryLocation::getBeforeOrAfter(UnderlyingV2), AAQI); 1090fe6060f1SDimitry Andric 1091fe6060f1SDimitry Andric // If we get a No or May, then return it immediately, no amount of analysis 1092fe6060f1SDimitry Andric // will improve this situation. 1093fe6060f1SDimitry Andric if (BaseAlias != AliasResult::MustAlias) { 1094fe6060f1SDimitry Andric assert(BaseAlias == AliasResult::NoAlias || 1095fe6060f1SDimitry Andric BaseAlias == AliasResult::MayAlias); 1096fe6060f1SDimitry Andric return BaseAlias; 1097fe6060f1SDimitry Andric } 10980b57cec5SDimitry Andric 10990b57cec5SDimitry Andric // If there is a constant difference between the pointers, but the difference 11000b57cec5SDimitry Andric // is less than the size of the associated memory object, then we know 11010b57cec5SDimitry Andric // that the objects are partially overlapping. If the difference is 11020b57cec5SDimitry Andric // greater, we know they do not overlap. 1103e8d8bef9SDimitry Andric if (DecompGEP1.Offset != 0 && DecompGEP1.VarIndices.empty()) { 1104fe6060f1SDimitry Andric APInt &Off = DecompGEP1.Offset; 1105fe6060f1SDimitry Andric 1106fe6060f1SDimitry Andric // Initialize for Off >= 0 (V2 <= GEP1) case. 1107fe6060f1SDimitry Andric const Value *LeftPtr = V2; 1108fe6060f1SDimitry Andric const Value *RightPtr = GEP1; 1109fe6060f1SDimitry Andric LocationSize VLeftSize = V2Size; 1110fe6060f1SDimitry Andric LocationSize VRightSize = V1Size; 1111fe6060f1SDimitry Andric const bool Swapped = Off.isNegative(); 1112fe6060f1SDimitry Andric 1113fe6060f1SDimitry Andric if (Swapped) { 1114fe6060f1SDimitry Andric // Swap if we have the situation where: 11150b57cec5SDimitry Andric // + + 11160b57cec5SDimitry Andric // | BaseOffset | 11170b57cec5SDimitry Andric // ---------------->| 11180b57cec5SDimitry Andric // |-->V1Size |-------> V2Size 11190b57cec5SDimitry Andric // GEP1 V2 1120fe6060f1SDimitry Andric std::swap(LeftPtr, RightPtr); 1121fe6060f1SDimitry Andric std::swap(VLeftSize, VRightSize); 1122fe6060f1SDimitry Andric Off = -Off; 11230b57cec5SDimitry Andric } 1124fe6060f1SDimitry Andric 1125fe6060f1SDimitry Andric if (VLeftSize.hasValue()) { 1126fe6060f1SDimitry Andric const uint64_t LSize = VLeftSize.getValue(); 1127fe6060f1SDimitry Andric if (Off.ult(LSize)) { 1128fe6060f1SDimitry Andric // Conservatively drop processing if a phi was visited and/or offset is 1129fe6060f1SDimitry Andric // too big. 1130fe6060f1SDimitry Andric AliasResult AR = AliasResult::PartialAlias; 1131fe6060f1SDimitry Andric if (VRightSize.hasValue() && Off.ule(INT32_MAX) && 1132fe6060f1SDimitry Andric (Off + VRightSize.getValue()).ule(LSize)) { 1133fe6060f1SDimitry Andric // Memory referenced by right pointer is nested. Save the offset in 1134fe6060f1SDimitry Andric // cache. Note that originally offset estimated as GEP1-V2, but 1135fe6060f1SDimitry Andric // AliasResult contains the shift that represents GEP1+Offset=V2. 1136fe6060f1SDimitry Andric AR.setOffset(-Off.getSExtValue()); 1137fe6060f1SDimitry Andric AR.swap(Swapped); 1138fe6060f1SDimitry Andric } 1139fe6060f1SDimitry Andric return AR; 1140fe6060f1SDimitry Andric } 1141fe6060f1SDimitry Andric return AliasResult::NoAlias; 11420b57cec5SDimitry Andric } 11430b57cec5SDimitry Andric } 11440b57cec5SDimitry Andric 11450b57cec5SDimitry Andric if (!DecompGEP1.VarIndices.empty()) { 1146e8d8bef9SDimitry Andric APInt GCD; 1147e8d8bef9SDimitry Andric bool AllNonNegative = DecompGEP1.Offset.isNonNegative(); 1148e8d8bef9SDimitry Andric bool AllNonPositive = DecompGEP1.Offset.isNonPositive(); 11490b57cec5SDimitry Andric for (unsigned i = 0, e = DecompGEP1.VarIndices.size(); i != e; ++i) { 1150fe6060f1SDimitry Andric APInt Scale = DecompGEP1.VarIndices[i].Scale; 1151fe6060f1SDimitry Andric APInt ScaleForGCD = DecompGEP1.VarIndices[i].Scale; 1152fe6060f1SDimitry Andric if (!DecompGEP1.VarIndices[i].IsNSW) 1153fe6060f1SDimitry Andric ScaleForGCD = APInt::getOneBitSet(Scale.getBitWidth(), 1154fe6060f1SDimitry Andric Scale.countTrailingZeros()); 1155fe6060f1SDimitry Andric 1156e8d8bef9SDimitry Andric if (i == 0) 1157fe6060f1SDimitry Andric GCD = ScaleForGCD.abs(); 1158e8d8bef9SDimitry Andric else 1159fe6060f1SDimitry Andric GCD = APIntOps::GreatestCommonDivisor(GCD, ScaleForGCD.abs()); 11600b57cec5SDimitry Andric 1161e8d8bef9SDimitry Andric if (AllNonNegative || AllNonPositive) { 11620b57cec5SDimitry Andric // If the Value could change between cycles, then any reasoning about 11630b57cec5SDimitry Andric // the Value this cycle may not hold in the next cycle. We'll just 11640b57cec5SDimitry Andric // give up if we can't determine conditions that hold for every cycle: 11650b57cec5SDimitry Andric const Value *V = DecompGEP1.VarIndices[i].V; 1166e8d8bef9SDimitry Andric const Instruction *CxtI = DecompGEP1.VarIndices[i].CxtI; 11670b57cec5SDimitry Andric 1168e8d8bef9SDimitry Andric KnownBits Known = computeKnownBits(V, DL, 0, &AC, CxtI, DT); 11690b57cec5SDimitry Andric bool SignKnownZero = Known.isNonNegative(); 11700b57cec5SDimitry Andric bool SignKnownOne = Known.isNegative(); 11710b57cec5SDimitry Andric 11720b57cec5SDimitry Andric // Zero-extension widens the variable, and so forces the sign 11730b57cec5SDimitry Andric // bit to zero. 11740b57cec5SDimitry Andric bool IsZExt = DecompGEP1.VarIndices[i].ZExtBits > 0 || isa<ZExtInst>(V); 11750b57cec5SDimitry Andric SignKnownZero |= IsZExt; 11760b57cec5SDimitry Andric SignKnownOne &= !IsZExt; 11770b57cec5SDimitry Andric 1178e8d8bef9SDimitry Andric AllNonNegative &= (SignKnownZero && Scale.isNonNegative()) || 1179e8d8bef9SDimitry Andric (SignKnownOne && Scale.isNonPositive()); 1180e8d8bef9SDimitry Andric AllNonPositive &= (SignKnownZero && Scale.isNonPositive()) || 1181e8d8bef9SDimitry Andric (SignKnownOne && Scale.isNonNegative()); 11820b57cec5SDimitry Andric } 11830b57cec5SDimitry Andric } 11840b57cec5SDimitry Andric 1185e8d8bef9SDimitry Andric // We now have accesses at two offsets from the same base: 1186e8d8bef9SDimitry Andric // 1. (...)*GCD + DecompGEP1.Offset with size V1Size 1187e8d8bef9SDimitry Andric // 2. 0 with size V2Size 1188e8d8bef9SDimitry Andric // Using arithmetic modulo GCD, the accesses are at 1189e8d8bef9SDimitry Andric // [ModOffset..ModOffset+V1Size) and [0..V2Size). If the first access fits 1190e8d8bef9SDimitry Andric // into the range [V2Size..GCD), then we know they cannot overlap. 1191e8d8bef9SDimitry Andric APInt ModOffset = DecompGEP1.Offset.srem(GCD); 1192e8d8bef9SDimitry Andric if (ModOffset.isNegative()) 1193e8d8bef9SDimitry Andric ModOffset += GCD; // We want mod, not rem. 1194e8d8bef9SDimitry Andric if (V1Size.hasValue() && V2Size.hasValue() && 1195e8d8bef9SDimitry Andric ModOffset.uge(V2Size.getValue()) && 1196e8d8bef9SDimitry Andric (GCD - ModOffset).uge(V1Size.getValue())) 1197fe6060f1SDimitry Andric return AliasResult::NoAlias; 11980b57cec5SDimitry Andric 1199e8d8bef9SDimitry Andric // If we know all the variables are non-negative, then the total offset is 1200e8d8bef9SDimitry Andric // also non-negative and >= DecompGEP1.Offset. We have the following layout: 1201e8d8bef9SDimitry Andric // [0, V2Size) ... [TotalOffset, TotalOffer+V1Size] 1202e8d8bef9SDimitry Andric // If DecompGEP1.Offset >= V2Size, the accesses don't alias. 1203e8d8bef9SDimitry Andric if (AllNonNegative && V2Size.hasValue() && 1204e8d8bef9SDimitry Andric DecompGEP1.Offset.uge(V2Size.getValue())) 1205fe6060f1SDimitry Andric return AliasResult::NoAlias; 1206e8d8bef9SDimitry Andric // Similarly, if the variables are non-positive, then the total offset is 1207e8d8bef9SDimitry Andric // also non-positive and <= DecompGEP1.Offset. We have the following layout: 1208e8d8bef9SDimitry Andric // [TotalOffset, TotalOffset+V1Size) ... [0, V2Size) 1209e8d8bef9SDimitry Andric // If -DecompGEP1.Offset >= V1Size, the accesses don't alias. 1210e8d8bef9SDimitry Andric if (AllNonPositive && V1Size.hasValue() && 1211e8d8bef9SDimitry Andric (-DecompGEP1.Offset).uge(V1Size.getValue())) 1212fe6060f1SDimitry Andric return AliasResult::NoAlias; 1213e8d8bef9SDimitry Andric 1214e8d8bef9SDimitry Andric if (V1Size.hasValue() && V2Size.hasValue()) { 1215e8d8bef9SDimitry Andric // Try to determine whether abs(VarIndex) > 0. 1216e8d8bef9SDimitry Andric Optional<APInt> MinAbsVarIndex; 1217e8d8bef9SDimitry Andric if (DecompGEP1.VarIndices.size() == 1) { 1218e8d8bef9SDimitry Andric // VarIndex = Scale*V. If V != 0 then abs(VarIndex) >= abs(Scale). 1219e8d8bef9SDimitry Andric const VariableGEPIndex &Var = DecompGEP1.VarIndices[0]; 1220e8d8bef9SDimitry Andric if (isKnownNonZero(Var.V, DL, 0, &AC, Var.CxtI, DT)) 1221e8d8bef9SDimitry Andric MinAbsVarIndex = Var.Scale.abs(); 1222e8d8bef9SDimitry Andric } else if (DecompGEP1.VarIndices.size() == 2) { 1223e8d8bef9SDimitry Andric // VarIndex = Scale*V0 + (-Scale)*V1. 1224e8d8bef9SDimitry Andric // If V0 != V1 then abs(VarIndex) >= abs(Scale). 1225e8d8bef9SDimitry Andric // Check that VisitedPhiBBs is empty, to avoid reasoning about 1226e8d8bef9SDimitry Andric // inequality of values across loop iterations. 1227e8d8bef9SDimitry Andric const VariableGEPIndex &Var0 = DecompGEP1.VarIndices[0]; 1228e8d8bef9SDimitry Andric const VariableGEPIndex &Var1 = DecompGEP1.VarIndices[1]; 1229e8d8bef9SDimitry Andric if (Var0.Scale == -Var1.Scale && Var0.ZExtBits == Var1.ZExtBits && 1230e8d8bef9SDimitry Andric Var0.SExtBits == Var1.SExtBits && VisitedPhiBBs.empty() && 1231e8d8bef9SDimitry Andric isKnownNonEqual(Var0.V, Var1.V, DL, &AC, /* CxtI */ nullptr, DT)) 1232e8d8bef9SDimitry Andric MinAbsVarIndex = Var0.Scale.abs(); 1233e8d8bef9SDimitry Andric } 1234e8d8bef9SDimitry Andric 1235e8d8bef9SDimitry Andric if (MinAbsVarIndex) { 1236e8d8bef9SDimitry Andric // The constant offset will have added at least +/-MinAbsVarIndex to it. 1237e8d8bef9SDimitry Andric APInt OffsetLo = DecompGEP1.Offset - *MinAbsVarIndex; 1238e8d8bef9SDimitry Andric APInt OffsetHi = DecompGEP1.Offset + *MinAbsVarIndex; 1239e8d8bef9SDimitry Andric // Check that an access at OffsetLo or lower, and an access at OffsetHi 1240e8d8bef9SDimitry Andric // or higher both do not alias. 1241e8d8bef9SDimitry Andric if (OffsetLo.isNegative() && (-OffsetLo).uge(V1Size.getValue()) && 1242e8d8bef9SDimitry Andric OffsetHi.isNonNegative() && OffsetHi.uge(V2Size.getValue())) 1243fe6060f1SDimitry Andric return AliasResult::NoAlias; 1244e8d8bef9SDimitry Andric } 1245e8d8bef9SDimitry Andric } 12460b57cec5SDimitry Andric 12470b57cec5SDimitry Andric if (constantOffsetHeuristic(DecompGEP1.VarIndices, V1Size, V2Size, 1248e8d8bef9SDimitry Andric DecompGEP1.Offset, &AC, DT)) 1249fe6060f1SDimitry Andric return AliasResult::NoAlias; 12500b57cec5SDimitry Andric } 12510b57cec5SDimitry Andric 12520b57cec5SDimitry Andric // Statically, we can see that the base objects are the same, but the 12530b57cec5SDimitry Andric // pointers have dynamic offsets which we can't resolve. And none of our 12540b57cec5SDimitry Andric // little tricks above worked. 1255fe6060f1SDimitry Andric return AliasResult::MayAlias; 12560b57cec5SDimitry Andric } 12570b57cec5SDimitry Andric 12580b57cec5SDimitry Andric static AliasResult MergeAliasResults(AliasResult A, AliasResult B) { 12590b57cec5SDimitry Andric // If the results agree, take it. 12600b57cec5SDimitry Andric if (A == B) 12610b57cec5SDimitry Andric return A; 12620b57cec5SDimitry Andric // A mix of PartialAlias and MustAlias is PartialAlias. 1263fe6060f1SDimitry Andric if ((A == AliasResult::PartialAlias && B == AliasResult::MustAlias) || 1264fe6060f1SDimitry Andric (B == AliasResult::PartialAlias && A == AliasResult::MustAlias)) 1265fe6060f1SDimitry Andric return AliasResult::PartialAlias; 12660b57cec5SDimitry Andric // Otherwise, we don't know anything. 1267fe6060f1SDimitry Andric return AliasResult::MayAlias; 12680b57cec5SDimitry Andric } 12690b57cec5SDimitry Andric 12700b57cec5SDimitry Andric /// Provides a bunch of ad-hoc rules to disambiguate a Select instruction 12710b57cec5SDimitry Andric /// against another. 12720b57cec5SDimitry Andric AliasResult 12730b57cec5SDimitry Andric BasicAAResult::aliasSelect(const SelectInst *SI, LocationSize SISize, 1274fe6060f1SDimitry Andric const Value *V2, LocationSize V2Size, 1275e8d8bef9SDimitry Andric AAQueryInfo &AAQI) { 12760b57cec5SDimitry Andric // If the values are Selects with the same condition, we can do a more precise 12770b57cec5SDimitry Andric // check: just check for aliases between the values on corresponding arms. 12780b57cec5SDimitry Andric if (const SelectInst *SI2 = dyn_cast<SelectInst>(V2)) 12790b57cec5SDimitry Andric if (SI->getCondition() == SI2->getCondition()) { 1280e8d8bef9SDimitry Andric AliasResult Alias = getBestAAResults().alias( 1281fe6060f1SDimitry Andric MemoryLocation(SI->getTrueValue(), SISize), 1282fe6060f1SDimitry Andric MemoryLocation(SI2->getTrueValue(), V2Size), AAQI); 1283fe6060f1SDimitry Andric if (Alias == AliasResult::MayAlias) 1284fe6060f1SDimitry Andric return AliasResult::MayAlias; 1285e8d8bef9SDimitry Andric AliasResult ThisAlias = getBestAAResults().alias( 1286fe6060f1SDimitry Andric MemoryLocation(SI->getFalseValue(), SISize), 1287fe6060f1SDimitry Andric MemoryLocation(SI2->getFalseValue(), V2Size), AAQI); 12880b57cec5SDimitry Andric return MergeAliasResults(ThisAlias, Alias); 12890b57cec5SDimitry Andric } 12900b57cec5SDimitry Andric 12910b57cec5SDimitry Andric // If both arms of the Select node NoAlias or MustAlias V2, then returns 12920b57cec5SDimitry Andric // NoAlias / MustAlias. Otherwise, returns MayAlias. 1293e8d8bef9SDimitry Andric AliasResult Alias = getBestAAResults().alias( 1294fe6060f1SDimitry Andric MemoryLocation(V2, V2Size), 1295fe6060f1SDimitry Andric MemoryLocation(SI->getTrueValue(), SISize), AAQI); 1296fe6060f1SDimitry Andric if (Alias == AliasResult::MayAlias) 1297fe6060f1SDimitry Andric return AliasResult::MayAlias; 12980b57cec5SDimitry Andric 1299e8d8bef9SDimitry Andric AliasResult ThisAlias = getBestAAResults().alias( 1300fe6060f1SDimitry Andric MemoryLocation(V2, V2Size), 1301fe6060f1SDimitry Andric MemoryLocation(SI->getFalseValue(), SISize), AAQI); 13020b57cec5SDimitry Andric return MergeAliasResults(ThisAlias, Alias); 13030b57cec5SDimitry Andric } 13040b57cec5SDimitry Andric 13050b57cec5SDimitry Andric /// Provide a bunch of ad-hoc rules to disambiguate a PHI instruction against 13060b57cec5SDimitry Andric /// another. 13070b57cec5SDimitry Andric AliasResult BasicAAResult::aliasPHI(const PHINode *PN, LocationSize PNSize, 1308fe6060f1SDimitry Andric const Value *V2, LocationSize V2Size, 1309e8d8bef9SDimitry Andric AAQueryInfo &AAQI) { 1310fe6060f1SDimitry Andric if (!PN->getNumIncomingValues()) 1311fe6060f1SDimitry Andric return AliasResult::NoAlias; 13120b57cec5SDimitry Andric // If the values are PHIs in the same block, we can do a more precise 13130b57cec5SDimitry Andric // as well as efficient check: just check for aliases between the values 13140b57cec5SDimitry Andric // on corresponding edges. 13150b57cec5SDimitry Andric if (const PHINode *PN2 = dyn_cast<PHINode>(V2)) 13160b57cec5SDimitry Andric if (PN2->getParent() == PN->getParent()) { 1317e8d8bef9SDimitry Andric Optional<AliasResult> Alias; 13180b57cec5SDimitry Andric for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 1319e8d8bef9SDimitry Andric AliasResult ThisAlias = getBestAAResults().alias( 1320fe6060f1SDimitry Andric MemoryLocation(PN->getIncomingValue(i), PNSize), 1321e8d8bef9SDimitry Andric MemoryLocation( 1322fe6060f1SDimitry Andric PN2->getIncomingValueForBlock(PN->getIncomingBlock(i)), V2Size), 1323e8d8bef9SDimitry Andric AAQI); 1324e8d8bef9SDimitry Andric if (Alias) 1325e8d8bef9SDimitry Andric *Alias = MergeAliasResults(*Alias, ThisAlias); 1326e8d8bef9SDimitry Andric else 1327e8d8bef9SDimitry Andric Alias = ThisAlias; 1328fe6060f1SDimitry Andric if (*Alias == AliasResult::MayAlias) 13290b57cec5SDimitry Andric break; 13300b57cec5SDimitry Andric } 1331e8d8bef9SDimitry Andric return *Alias; 13320b57cec5SDimitry Andric } 13330b57cec5SDimitry Andric 13340b57cec5SDimitry Andric SmallVector<Value *, 4> V1Srcs; 1335e8d8bef9SDimitry Andric // If a phi operand recurses back to the phi, we can still determine NoAlias 1336e8d8bef9SDimitry Andric // if we don't alias the underlying objects of the other phi operands, as we 1337e8d8bef9SDimitry Andric // know that the recursive phi needs to be based on them in some way. 13380b57cec5SDimitry Andric bool isRecursive = false; 1339979e22ffSDimitry Andric auto CheckForRecPhi = [&](Value *PV) { 1340979e22ffSDimitry Andric if (!EnableRecPhiAnalysis) 1341979e22ffSDimitry Andric return false; 1342e8d8bef9SDimitry Andric if (getUnderlyingObject(PV) == PN) { 1343979e22ffSDimitry Andric isRecursive = true; 1344979e22ffSDimitry Andric return true; 1345979e22ffSDimitry Andric } 1346979e22ffSDimitry Andric return false; 1347979e22ffSDimitry Andric }; 1348979e22ffSDimitry Andric 13490b57cec5SDimitry Andric if (PV) { 13500b57cec5SDimitry Andric // If we have PhiValues then use it to get the underlying phi values. 13510b57cec5SDimitry Andric const PhiValues::ValueSet &PhiValueSet = PV->getValuesForPhi(PN); 13520b57cec5SDimitry Andric // If we have more phi values than the search depth then return MayAlias 13530b57cec5SDimitry Andric // conservatively to avoid compile time explosion. The worst possible case 13540b57cec5SDimitry Andric // is if both sides are PHI nodes. In which case, this is O(m x n) time 13550b57cec5SDimitry Andric // where 'm' and 'n' are the number of PHI sources. 13560b57cec5SDimitry Andric if (PhiValueSet.size() > MaxLookupSearchDepth) 1357fe6060f1SDimitry Andric return AliasResult::MayAlias; 13580b57cec5SDimitry Andric // Add the values to V1Srcs 13590b57cec5SDimitry Andric for (Value *PV1 : PhiValueSet) { 1360979e22ffSDimitry Andric if (CheckForRecPhi(PV1)) 13610b57cec5SDimitry Andric continue; 13620b57cec5SDimitry Andric V1Srcs.push_back(PV1); 13630b57cec5SDimitry Andric } 13640b57cec5SDimitry Andric } else { 13650b57cec5SDimitry Andric // If we don't have PhiInfo then just look at the operands of the phi itself 13660b57cec5SDimitry Andric // FIXME: Remove this once we can guarantee that we have PhiInfo always 13670b57cec5SDimitry Andric SmallPtrSet<Value *, 4> UniqueSrc; 1368fe6060f1SDimitry Andric Value *OnePhi = nullptr; 13690b57cec5SDimitry Andric for (Value *PV1 : PN->incoming_values()) { 1370fe6060f1SDimitry Andric if (isa<PHINode>(PV1)) { 1371fe6060f1SDimitry Andric if (OnePhi && OnePhi != PV1) { 1372fe6060f1SDimitry Andric // To control potential compile time explosion, we choose to be 1373fe6060f1SDimitry Andric // conserviate when we have more than one Phi input. It is important 1374fe6060f1SDimitry Andric // that we handle the single phi case as that lets us handle LCSSA 1375fe6060f1SDimitry Andric // phi nodes and (combined with the recursive phi handling) simple 1376fe6060f1SDimitry Andric // pointer induction variable patterns. 1377fe6060f1SDimitry Andric return AliasResult::MayAlias; 1378fe6060f1SDimitry Andric } 1379fe6060f1SDimitry Andric OnePhi = PV1; 1380fe6060f1SDimitry Andric } 13810b57cec5SDimitry Andric 1382979e22ffSDimitry Andric if (CheckForRecPhi(PV1)) 13830b57cec5SDimitry Andric continue; 13840b57cec5SDimitry Andric 13850b57cec5SDimitry Andric if (UniqueSrc.insert(PV1).second) 13860b57cec5SDimitry Andric V1Srcs.push_back(PV1); 13870b57cec5SDimitry Andric } 1388fe6060f1SDimitry Andric 1389fe6060f1SDimitry Andric if (OnePhi && UniqueSrc.size() > 1) 1390fe6060f1SDimitry Andric // Out of an abundance of caution, allow only the trivial lcssa and 1391fe6060f1SDimitry Andric // recursive phi cases. 1392fe6060f1SDimitry Andric return AliasResult::MayAlias; 13930b57cec5SDimitry Andric } 13940b57cec5SDimitry Andric 13950b57cec5SDimitry Andric // If V1Srcs is empty then that means that the phi has no underlying non-phi 13960b57cec5SDimitry Andric // value. This should only be possible in blocks unreachable from the entry 13970b57cec5SDimitry Andric // block, but return MayAlias just in case. 13980b57cec5SDimitry Andric if (V1Srcs.empty()) 1399fe6060f1SDimitry Andric return AliasResult::MayAlias; 14000b57cec5SDimitry Andric 1401e8d8bef9SDimitry Andric // If this PHI node is recursive, indicate that the pointer may be moved 1402e8d8bef9SDimitry Andric // across iterations. We can only prove NoAlias if different underlying 1403e8d8bef9SDimitry Andric // objects are involved. 14040b57cec5SDimitry Andric if (isRecursive) 1405e8d8bef9SDimitry Andric PNSize = LocationSize::beforeOrAfterPointer(); 14060b57cec5SDimitry Andric 1407e8d8bef9SDimitry Andric // In the recursive alias queries below, we may compare values from two 1408e8d8bef9SDimitry Andric // different loop iterations. Keep track of visited phi blocks, which will 1409e8d8bef9SDimitry Andric // be used when determining value equivalence. 1410e8d8bef9SDimitry Andric bool BlockInserted = VisitedPhiBBs.insert(PN->getParent()).second; 1411e8d8bef9SDimitry Andric auto _ = make_scope_exit([&]() { 1412e8d8bef9SDimitry Andric if (BlockInserted) 1413e8d8bef9SDimitry Andric VisitedPhiBBs.erase(PN->getParent()); 1414e8d8bef9SDimitry Andric }); 1415e8d8bef9SDimitry Andric 1416e8d8bef9SDimitry Andric // If we inserted a block into VisitedPhiBBs, alias analysis results that 1417e8d8bef9SDimitry Andric // have been cached earlier may no longer be valid. Perform recursive queries 1418e8d8bef9SDimitry Andric // with a new AAQueryInfo. 1419fe6060f1SDimitry Andric AAQueryInfo NewAAQI = AAQI.withEmptyCache(); 1420e8d8bef9SDimitry Andric AAQueryInfo *UseAAQI = BlockInserted ? &NewAAQI : &AAQI; 1421e8d8bef9SDimitry Andric 1422e8d8bef9SDimitry Andric AliasResult Alias = getBestAAResults().alias( 1423fe6060f1SDimitry Andric MemoryLocation(V2, V2Size), 1424fe6060f1SDimitry Andric MemoryLocation(V1Srcs[0], PNSize), *UseAAQI); 14250b57cec5SDimitry Andric 14260b57cec5SDimitry Andric // Early exit if the check of the first PHI source against V2 is MayAlias. 14270b57cec5SDimitry Andric // Other results are not possible. 1428fe6060f1SDimitry Andric if (Alias == AliasResult::MayAlias) 1429fe6060f1SDimitry Andric return AliasResult::MayAlias; 14305ffd83dbSDimitry Andric // With recursive phis we cannot guarantee that MustAlias/PartialAlias will 14315ffd83dbSDimitry Andric // remain valid to all elements and needs to conservatively return MayAlias. 1432fe6060f1SDimitry Andric if (isRecursive && Alias != AliasResult::NoAlias) 1433fe6060f1SDimitry Andric return AliasResult::MayAlias; 14340b57cec5SDimitry Andric 14350b57cec5SDimitry Andric // If all sources of the PHI node NoAlias or MustAlias V2, then returns 14360b57cec5SDimitry Andric // NoAlias / MustAlias. Otherwise, returns MayAlias. 14370b57cec5SDimitry Andric for (unsigned i = 1, e = V1Srcs.size(); i != e; ++i) { 14380b57cec5SDimitry Andric Value *V = V1Srcs[i]; 14390b57cec5SDimitry Andric 1440e8d8bef9SDimitry Andric AliasResult ThisAlias = getBestAAResults().alias( 1441fe6060f1SDimitry Andric MemoryLocation(V2, V2Size), MemoryLocation(V, PNSize), *UseAAQI); 14420b57cec5SDimitry Andric Alias = MergeAliasResults(ThisAlias, Alias); 1443fe6060f1SDimitry Andric if (Alias == AliasResult::MayAlias) 14440b57cec5SDimitry Andric break; 14450b57cec5SDimitry Andric } 14460b57cec5SDimitry Andric 14470b57cec5SDimitry Andric return Alias; 14480b57cec5SDimitry Andric } 14490b57cec5SDimitry Andric 14500b57cec5SDimitry Andric /// Provides a bunch of ad-hoc rules to disambiguate in common cases, such as 14510b57cec5SDimitry Andric /// array references. 14520b57cec5SDimitry Andric AliasResult BasicAAResult::aliasCheck(const Value *V1, LocationSize V1Size, 1453e8d8bef9SDimitry Andric const Value *V2, LocationSize V2Size, 1454e8d8bef9SDimitry Andric AAQueryInfo &AAQI) { 14550b57cec5SDimitry Andric // If either of the memory references is empty, it doesn't matter what the 14560b57cec5SDimitry Andric // pointer values are. 14570b57cec5SDimitry Andric if (V1Size.isZero() || V2Size.isZero()) 1458fe6060f1SDimitry Andric return AliasResult::NoAlias; 14590b57cec5SDimitry Andric 14600b57cec5SDimitry Andric // Strip off any casts if they exist. 1461fe6060f1SDimitry Andric V1 = V1->stripPointerCastsForAliasAnalysis(); 1462fe6060f1SDimitry Andric V2 = V2->stripPointerCastsForAliasAnalysis(); 14630b57cec5SDimitry Andric 14640b57cec5SDimitry Andric // If V1 or V2 is undef, the result is NoAlias because we can always pick a 14650b57cec5SDimitry Andric // value for undef that aliases nothing in the program. 14660b57cec5SDimitry Andric if (isa<UndefValue>(V1) || isa<UndefValue>(V2)) 1467fe6060f1SDimitry Andric return AliasResult::NoAlias; 14680b57cec5SDimitry Andric 14690b57cec5SDimitry Andric // Are we checking for alias of the same value? 14700b57cec5SDimitry Andric // Because we look 'through' phi nodes, we could look at "Value" pointers from 14710b57cec5SDimitry Andric // different iterations. We must therefore make sure that this is not the 14720b57cec5SDimitry Andric // case. The function isValueEqualInPotentialCycles ensures that this cannot 14730b57cec5SDimitry Andric // happen by looking at the visited phi nodes and making sure they cannot 14740b57cec5SDimitry Andric // reach the value. 14750b57cec5SDimitry Andric if (isValueEqualInPotentialCycles(V1, V2)) 1476fe6060f1SDimitry Andric return AliasResult::MustAlias; 14770b57cec5SDimitry Andric 14780b57cec5SDimitry Andric if (!V1->getType()->isPointerTy() || !V2->getType()->isPointerTy()) 1479fe6060f1SDimitry Andric return AliasResult::NoAlias; // Scalars cannot alias each other 14800b57cec5SDimitry Andric 14810b57cec5SDimitry Andric // Figure out what objects these things are pointing to if we can. 1482e8d8bef9SDimitry Andric const Value *O1 = getUnderlyingObject(V1, MaxLookupSearchDepth); 1483e8d8bef9SDimitry Andric const Value *O2 = getUnderlyingObject(V2, MaxLookupSearchDepth); 14840b57cec5SDimitry Andric 14850b57cec5SDimitry Andric // Null values in the default address space don't point to any object, so they 14860b57cec5SDimitry Andric // don't alias any other pointer. 14870b57cec5SDimitry Andric if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O1)) 14880b57cec5SDimitry Andric if (!NullPointerIsDefined(&F, CPN->getType()->getAddressSpace())) 1489fe6060f1SDimitry Andric return AliasResult::NoAlias; 14900b57cec5SDimitry Andric if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O2)) 14910b57cec5SDimitry Andric if (!NullPointerIsDefined(&F, CPN->getType()->getAddressSpace())) 1492fe6060f1SDimitry Andric return AliasResult::NoAlias; 14930b57cec5SDimitry Andric 14940b57cec5SDimitry Andric if (O1 != O2) { 14950b57cec5SDimitry Andric // If V1/V2 point to two different objects, we know that we have no alias. 14960b57cec5SDimitry Andric if (isIdentifiedObject(O1) && isIdentifiedObject(O2)) 1497fe6060f1SDimitry Andric return AliasResult::NoAlias; 14980b57cec5SDimitry Andric 14990b57cec5SDimitry Andric // Constant pointers can't alias with non-const isIdentifiedObject objects. 15000b57cec5SDimitry Andric if ((isa<Constant>(O1) && isIdentifiedObject(O2) && !isa<Constant>(O2)) || 15010b57cec5SDimitry Andric (isa<Constant>(O2) && isIdentifiedObject(O1) && !isa<Constant>(O1))) 1502fe6060f1SDimitry Andric return AliasResult::NoAlias; 15030b57cec5SDimitry Andric 15040b57cec5SDimitry Andric // Function arguments can't alias with things that are known to be 15050b57cec5SDimitry Andric // unambigously identified at the function level. 15060b57cec5SDimitry Andric if ((isa<Argument>(O1) && isIdentifiedFunctionLocal(O2)) || 15070b57cec5SDimitry Andric (isa<Argument>(O2) && isIdentifiedFunctionLocal(O1))) 1508fe6060f1SDimitry Andric return AliasResult::NoAlias; 15090b57cec5SDimitry Andric 15100b57cec5SDimitry Andric // If one pointer is the result of a call/invoke or load and the other is a 15110b57cec5SDimitry Andric // non-escaping local object within the same function, then we know the 15120b57cec5SDimitry Andric // object couldn't escape to a point where the call could return it. 15130b57cec5SDimitry Andric // 15140b57cec5SDimitry Andric // Note that if the pointers are in different functions, there are a 15150b57cec5SDimitry Andric // variety of complications. A call with a nocapture argument may still 15160b57cec5SDimitry Andric // temporary store the nocapture argument's value in a temporary memory 15170b57cec5SDimitry Andric // location if that memory location doesn't escape. Or it may pass a 15180b57cec5SDimitry Andric // nocapture value to other functions as long as they don't capture it. 15190b57cec5SDimitry Andric if (isEscapeSource(O1) && 15200b57cec5SDimitry Andric isNonEscapingLocalObject(O2, &AAQI.IsCapturedCache)) 1521fe6060f1SDimitry Andric return AliasResult::NoAlias; 15220b57cec5SDimitry Andric if (isEscapeSource(O2) && 15230b57cec5SDimitry Andric isNonEscapingLocalObject(O1, &AAQI.IsCapturedCache)) 1524fe6060f1SDimitry Andric return AliasResult::NoAlias; 15250b57cec5SDimitry Andric } 15260b57cec5SDimitry Andric 15270b57cec5SDimitry Andric // If the size of one access is larger than the entire object on the other 15280b57cec5SDimitry Andric // side, then we know such behavior is undefined and can assume no alias. 15290b57cec5SDimitry Andric bool NullIsValidLocation = NullPointerIsDefined(&F); 15308bcb0991SDimitry Andric if ((isObjectSmallerThan( 15318bcb0991SDimitry Andric O2, getMinimalExtentFrom(*V1, V1Size, DL, NullIsValidLocation), DL, 15328bcb0991SDimitry Andric TLI, NullIsValidLocation)) || 15338bcb0991SDimitry Andric (isObjectSmallerThan( 15348bcb0991SDimitry Andric O1, getMinimalExtentFrom(*V2, V2Size, DL, NullIsValidLocation), DL, 15358bcb0991SDimitry Andric TLI, NullIsValidLocation))) 1536fe6060f1SDimitry Andric return AliasResult::NoAlias; 15370b57cec5SDimitry Andric 1538e8d8bef9SDimitry Andric // If one the accesses may be before the accessed pointer, canonicalize this 1539e8d8bef9SDimitry Andric // by using unknown after-pointer sizes for both accesses. This is 1540e8d8bef9SDimitry Andric // equivalent, because regardless of which pointer is lower, one of them 1541e8d8bef9SDimitry Andric // will always came after the other, as long as the underlying objects aren't 1542e8d8bef9SDimitry Andric // disjoint. We do this so that the rest of BasicAA does not have to deal 1543e8d8bef9SDimitry Andric // with accesses before the base pointer, and to improve cache utilization by 1544e8d8bef9SDimitry Andric // merging equivalent states. 1545e8d8bef9SDimitry Andric if (V1Size.mayBeBeforePointer() || V2Size.mayBeBeforePointer()) { 1546e8d8bef9SDimitry Andric V1Size = LocationSize::afterPointer(); 1547e8d8bef9SDimitry Andric V2Size = LocationSize::afterPointer(); 1548e8d8bef9SDimitry Andric } 1549e8d8bef9SDimitry Andric 1550fe6060f1SDimitry Andric // FIXME: If this depth limit is hit, then we may cache sub-optimal results 1551fe6060f1SDimitry Andric // for recursive queries. For this reason, this limit is chosen to be large 1552fe6060f1SDimitry Andric // enough to be very rarely hit, while still being small enough to avoid 1553fe6060f1SDimitry Andric // stack overflows. 1554fe6060f1SDimitry Andric if (AAQI.Depth >= 512) 1555fe6060f1SDimitry Andric return AliasResult::MayAlias; 1556fe6060f1SDimitry Andric 15570b57cec5SDimitry Andric // Check the cache before climbing up use-def chains. This also terminates 15580b57cec5SDimitry Andric // otherwise infinitely recursive queries. 1559fe6060f1SDimitry Andric AAQueryInfo::LocPair Locs({V1, V1Size}, {V2, V2Size}); 1560fe6060f1SDimitry Andric const bool Swapped = V1 > V2; 1561fe6060f1SDimitry Andric if (Swapped) 15620b57cec5SDimitry Andric std::swap(Locs.first, Locs.second); 1563e8d8bef9SDimitry Andric const auto &Pair = AAQI.AliasCache.try_emplace( 1564fe6060f1SDimitry Andric Locs, AAQueryInfo::CacheEntry{AliasResult::NoAlias, 0}); 1565e8d8bef9SDimitry Andric if (!Pair.second) { 1566e8d8bef9SDimitry Andric auto &Entry = Pair.first->second; 1567e8d8bef9SDimitry Andric if (!Entry.isDefinitive()) { 1568e8d8bef9SDimitry Andric // Remember that we used an assumption. 1569e8d8bef9SDimitry Andric ++Entry.NumAssumptionUses; 1570e8d8bef9SDimitry Andric ++AAQI.NumAssumptionUses; 15710b57cec5SDimitry Andric } 1572fe6060f1SDimitry Andric // Cache contains sorted {V1,V2} pairs but we should return original order. 1573fe6060f1SDimitry Andric auto Result = Entry.Result; 1574fe6060f1SDimitry Andric Result.swap(Swapped); 1575fe6060f1SDimitry Andric return Result; 1576e8d8bef9SDimitry Andric } 1577e8d8bef9SDimitry Andric 1578e8d8bef9SDimitry Andric int OrigNumAssumptionUses = AAQI.NumAssumptionUses; 1579e8d8bef9SDimitry Andric unsigned OrigNumAssumptionBasedResults = AAQI.AssumptionBasedResults.size(); 1580fe6060f1SDimitry Andric AliasResult Result = 1581fe6060f1SDimitry Andric aliasCheckRecursive(V1, V1Size, V2, V2Size, AAQI, O1, O2); 1582e8d8bef9SDimitry Andric 1583e8d8bef9SDimitry Andric auto It = AAQI.AliasCache.find(Locs); 1584e8d8bef9SDimitry Andric assert(It != AAQI.AliasCache.end() && "Must be in cache"); 1585e8d8bef9SDimitry Andric auto &Entry = It->second; 1586e8d8bef9SDimitry Andric 1587e8d8bef9SDimitry Andric // Check whether a NoAlias assumption has been used, but disproven. 1588fe6060f1SDimitry Andric bool AssumptionDisproven = 1589fe6060f1SDimitry Andric Entry.NumAssumptionUses > 0 && Result != AliasResult::NoAlias; 1590e8d8bef9SDimitry Andric if (AssumptionDisproven) 1591fe6060f1SDimitry Andric Result = AliasResult::MayAlias; 1592e8d8bef9SDimitry Andric 1593e8d8bef9SDimitry Andric // This is a definitive result now, when considered as a root query. 1594e8d8bef9SDimitry Andric AAQI.NumAssumptionUses -= Entry.NumAssumptionUses; 1595e8d8bef9SDimitry Andric Entry.Result = Result; 1596fe6060f1SDimitry Andric // Cache contains sorted {V1,V2} pairs. 1597fe6060f1SDimitry Andric Entry.Result.swap(Swapped); 1598e8d8bef9SDimitry Andric Entry.NumAssumptionUses = -1; 1599e8d8bef9SDimitry Andric 1600e8d8bef9SDimitry Andric // If the assumption has been disproven, remove any results that may have 1601e8d8bef9SDimitry Andric // been based on this assumption. Do this after the Entry updates above to 1602e8d8bef9SDimitry Andric // avoid iterator invalidation. 1603e8d8bef9SDimitry Andric if (AssumptionDisproven) 1604e8d8bef9SDimitry Andric while (AAQI.AssumptionBasedResults.size() > OrigNumAssumptionBasedResults) 1605e8d8bef9SDimitry Andric AAQI.AliasCache.erase(AAQI.AssumptionBasedResults.pop_back_val()); 1606e8d8bef9SDimitry Andric 1607e8d8bef9SDimitry Andric // The result may still be based on assumptions higher up in the chain. 1608e8d8bef9SDimitry Andric // Remember it, so it can be purged from the cache later. 1609fe6060f1SDimitry Andric if (OrigNumAssumptionUses != AAQI.NumAssumptionUses && 1610fe6060f1SDimitry Andric Result != AliasResult::MayAlias) 1611e8d8bef9SDimitry Andric AAQI.AssumptionBasedResults.push_back(Locs); 1612e8d8bef9SDimitry Andric return Result; 1613e8d8bef9SDimitry Andric } 1614e8d8bef9SDimitry Andric 1615e8d8bef9SDimitry Andric AliasResult BasicAAResult::aliasCheckRecursive( 1616fe6060f1SDimitry Andric const Value *V1, LocationSize V1Size, 1617fe6060f1SDimitry Andric const Value *V2, LocationSize V2Size, 1618e8d8bef9SDimitry Andric AAQueryInfo &AAQI, const Value *O1, const Value *O2) { 16190b57cec5SDimitry Andric if (const GEPOperator *GV1 = dyn_cast<GEPOperator>(V1)) { 1620fe6060f1SDimitry Andric AliasResult Result = aliasGEP(GV1, V1Size, V2, V2Size, O1, O2, AAQI); 1621fe6060f1SDimitry Andric if (Result != AliasResult::MayAlias) 1622e8d8bef9SDimitry Andric return Result; 1623e8d8bef9SDimitry Andric } else if (const GEPOperator *GV2 = dyn_cast<GEPOperator>(V2)) { 1624fe6060f1SDimitry Andric AliasResult Result = aliasGEP(GV2, V2Size, V1, V1Size, O2, O1, AAQI); 1625fe6060f1SDimitry Andric if (Result != AliasResult::MayAlias) 16260b57cec5SDimitry Andric return Result; 16270b57cec5SDimitry Andric } 16280b57cec5SDimitry Andric 16290b57cec5SDimitry Andric if (const PHINode *PN = dyn_cast<PHINode>(V1)) { 1630fe6060f1SDimitry Andric AliasResult Result = aliasPHI(PN, V1Size, V2, V2Size, AAQI); 1631fe6060f1SDimitry Andric if (Result != AliasResult::MayAlias) 1632e8d8bef9SDimitry Andric return Result; 1633e8d8bef9SDimitry Andric } else if (const PHINode *PN = dyn_cast<PHINode>(V2)) { 1634fe6060f1SDimitry Andric AliasResult Result = aliasPHI(PN, V2Size, V1, V1Size, AAQI); 1635fe6060f1SDimitry Andric if (Result != AliasResult::MayAlias) 1636e8d8bef9SDimitry Andric return Result; 16370b57cec5SDimitry Andric } 16380b57cec5SDimitry Andric 16390b57cec5SDimitry Andric if (const SelectInst *S1 = dyn_cast<SelectInst>(V1)) { 1640fe6060f1SDimitry Andric AliasResult Result = aliasSelect(S1, V1Size, V2, V2Size, AAQI); 1641fe6060f1SDimitry Andric if (Result != AliasResult::MayAlias) 1642e8d8bef9SDimitry Andric return Result; 1643e8d8bef9SDimitry Andric } else if (const SelectInst *S2 = dyn_cast<SelectInst>(V2)) { 1644fe6060f1SDimitry Andric AliasResult Result = aliasSelect(S2, V2Size, V1, V1Size, AAQI); 1645fe6060f1SDimitry Andric if (Result != AliasResult::MayAlias) 1646e8d8bef9SDimitry Andric return Result; 16470b57cec5SDimitry Andric } 16480b57cec5SDimitry Andric 16490b57cec5SDimitry Andric // If both pointers are pointing into the same object and one of them 16500b57cec5SDimitry Andric // accesses the entire object, then the accesses must overlap in some way. 1651e8d8bef9SDimitry Andric if (O1 == O2) { 1652e8d8bef9SDimitry Andric bool NullIsValidLocation = NullPointerIsDefined(&F); 16530b57cec5SDimitry Andric if (V1Size.isPrecise() && V2Size.isPrecise() && 16540b57cec5SDimitry Andric (isObjectSize(O1, V1Size.getValue(), DL, TLI, NullIsValidLocation) || 1655e8d8bef9SDimitry Andric isObjectSize(O2, V2Size.getValue(), DL, TLI, NullIsValidLocation))) 1656fe6060f1SDimitry Andric return AliasResult::PartialAlias; 16570b57cec5SDimitry Andric } 16580b57cec5SDimitry Andric 1659fe6060f1SDimitry Andric return AliasResult::MayAlias; 16600b57cec5SDimitry Andric } 16610b57cec5SDimitry Andric 16620b57cec5SDimitry Andric /// Check whether two Values can be considered equivalent. 16630b57cec5SDimitry Andric /// 16640b57cec5SDimitry Andric /// In addition to pointer equivalence of \p V1 and \p V2 this checks whether 16650b57cec5SDimitry Andric /// they can not be part of a cycle in the value graph by looking at all 16660b57cec5SDimitry Andric /// visited phi nodes an making sure that the phis cannot reach the value. We 16670b57cec5SDimitry Andric /// have to do this because we are looking through phi nodes (That is we say 16680b57cec5SDimitry Andric /// noalias(V, phi(VA, VB)) if noalias(V, VA) and noalias(V, VB). 16690b57cec5SDimitry Andric bool BasicAAResult::isValueEqualInPotentialCycles(const Value *V, 16700b57cec5SDimitry Andric const Value *V2) { 16710b57cec5SDimitry Andric if (V != V2) 16720b57cec5SDimitry Andric return false; 16730b57cec5SDimitry Andric 16740b57cec5SDimitry Andric const Instruction *Inst = dyn_cast<Instruction>(V); 16750b57cec5SDimitry Andric if (!Inst) 16760b57cec5SDimitry Andric return true; 16770b57cec5SDimitry Andric 16780b57cec5SDimitry Andric if (VisitedPhiBBs.empty()) 16790b57cec5SDimitry Andric return true; 16800b57cec5SDimitry Andric 16810b57cec5SDimitry Andric if (VisitedPhiBBs.size() > MaxNumPhiBBsValueReachabilityCheck) 16820b57cec5SDimitry Andric return false; 16830b57cec5SDimitry Andric 16840b57cec5SDimitry Andric // Make sure that the visited phis cannot reach the Value. This ensures that 16850b57cec5SDimitry Andric // the Values cannot come from different iterations of a potential cycle the 16860b57cec5SDimitry Andric // phi nodes could be involved in. 16870b57cec5SDimitry Andric for (auto *P : VisitedPhiBBs) 1688fe6060f1SDimitry Andric if (isPotentiallyReachable(&P->front(), Inst, nullptr, DT)) 16890b57cec5SDimitry Andric return false; 16900b57cec5SDimitry Andric 16910b57cec5SDimitry Andric return true; 16920b57cec5SDimitry Andric } 16930b57cec5SDimitry Andric 16940b57cec5SDimitry Andric /// Computes the symbolic difference between two de-composed GEPs. 16950b57cec5SDimitry Andric /// 16960b57cec5SDimitry Andric /// Dest and Src are the variable indices from two decomposed GetElementPtr 16970b57cec5SDimitry Andric /// instructions GEP1 and GEP2 which have common base pointers. 16980b57cec5SDimitry Andric void BasicAAResult::GetIndexDifference( 16990b57cec5SDimitry Andric SmallVectorImpl<VariableGEPIndex> &Dest, 17000b57cec5SDimitry Andric const SmallVectorImpl<VariableGEPIndex> &Src) { 17010b57cec5SDimitry Andric if (Src.empty()) 17020b57cec5SDimitry Andric return; 17030b57cec5SDimitry Andric 17040b57cec5SDimitry Andric for (unsigned i = 0, e = Src.size(); i != e; ++i) { 17050b57cec5SDimitry Andric const Value *V = Src[i].V; 17060b57cec5SDimitry Andric unsigned ZExtBits = Src[i].ZExtBits, SExtBits = Src[i].SExtBits; 17070b57cec5SDimitry Andric APInt Scale = Src[i].Scale; 17080b57cec5SDimitry Andric 17090b57cec5SDimitry Andric // Find V in Dest. This is N^2, but pointer indices almost never have more 17100b57cec5SDimitry Andric // than a few variable indexes. 17110b57cec5SDimitry Andric for (unsigned j = 0, e = Dest.size(); j != e; ++j) { 17120b57cec5SDimitry Andric if (!isValueEqualInPotentialCycles(Dest[j].V, V) || 17130b57cec5SDimitry Andric Dest[j].ZExtBits != ZExtBits || Dest[j].SExtBits != SExtBits) 17140b57cec5SDimitry Andric continue; 17150b57cec5SDimitry Andric 17160b57cec5SDimitry Andric // If we found it, subtract off Scale V's from the entry in Dest. If it 17170b57cec5SDimitry Andric // goes to zero, remove the entry. 1718fe6060f1SDimitry Andric if (Dest[j].Scale != Scale) { 17190b57cec5SDimitry Andric Dest[j].Scale -= Scale; 1720fe6060f1SDimitry Andric Dest[j].IsNSW = false; 1721fe6060f1SDimitry Andric } else 17220b57cec5SDimitry Andric Dest.erase(Dest.begin() + j); 17230b57cec5SDimitry Andric Scale = 0; 17240b57cec5SDimitry Andric break; 17250b57cec5SDimitry Andric } 17260b57cec5SDimitry Andric 17270b57cec5SDimitry Andric // If we didn't consume this entry, add it to the end of the Dest list. 17280b57cec5SDimitry Andric if (!!Scale) { 1729fe6060f1SDimitry Andric VariableGEPIndex Entry = {V, ZExtBits, SExtBits, 1730fe6060f1SDimitry Andric -Scale, Src[i].CxtI, Src[i].IsNSW}; 17310b57cec5SDimitry Andric Dest.push_back(Entry); 17320b57cec5SDimitry Andric } 17330b57cec5SDimitry Andric } 17340b57cec5SDimitry Andric } 17350b57cec5SDimitry Andric 17360b57cec5SDimitry Andric bool BasicAAResult::constantOffsetHeuristic( 17370b57cec5SDimitry Andric const SmallVectorImpl<VariableGEPIndex> &VarIndices, 17385ffd83dbSDimitry Andric LocationSize MaybeV1Size, LocationSize MaybeV2Size, const APInt &BaseOffset, 17390b57cec5SDimitry Andric AssumptionCache *AC, DominatorTree *DT) { 1740e8d8bef9SDimitry Andric if (VarIndices.size() != 2 || !MaybeV1Size.hasValue() || 1741e8d8bef9SDimitry Andric !MaybeV2Size.hasValue()) 17420b57cec5SDimitry Andric return false; 17430b57cec5SDimitry Andric 17440b57cec5SDimitry Andric const uint64_t V1Size = MaybeV1Size.getValue(); 17450b57cec5SDimitry Andric const uint64_t V2Size = MaybeV2Size.getValue(); 17460b57cec5SDimitry Andric 17470b57cec5SDimitry Andric const VariableGEPIndex &Var0 = VarIndices[0], &Var1 = VarIndices[1]; 17480b57cec5SDimitry Andric 17490b57cec5SDimitry Andric if (Var0.ZExtBits != Var1.ZExtBits || Var0.SExtBits != Var1.SExtBits || 1750fe6060f1SDimitry Andric Var0.Scale != -Var1.Scale || Var0.V->getType() != Var1.V->getType()) 17510b57cec5SDimitry Andric return false; 17520b57cec5SDimitry Andric 17530b57cec5SDimitry Andric // We'll strip off the Extensions of Var0 and Var1 and do another round 17540b57cec5SDimitry Andric // of GetLinearExpression decomposition. In the example above, if Var0 17550b57cec5SDimitry Andric // is zext(%x + 1) we should get V1 == %x and V1Offset == 1. 17560b57cec5SDimitry Andric 1757fe6060f1SDimitry Andric LinearExpression E0 = 1758fe6060f1SDimitry Andric GetLinearExpression(ExtendedValue(Var0.V), DL, 0, AC, DT); 1759fe6060f1SDimitry Andric LinearExpression E1 = 1760fe6060f1SDimitry Andric GetLinearExpression(ExtendedValue(Var1.V), DL, 0, AC, DT); 1761fe6060f1SDimitry Andric if (E0.Scale != E1.Scale || E0.Val.ZExtBits != E1.Val.ZExtBits || 1762fe6060f1SDimitry Andric E0.Val.SExtBits != E1.Val.SExtBits || 1763fe6060f1SDimitry Andric !isValueEqualInPotentialCycles(E0.Val.V, E1.Val.V)) 17640b57cec5SDimitry Andric return false; 17650b57cec5SDimitry Andric 17660b57cec5SDimitry Andric // We have a hit - Var0 and Var1 only differ by a constant offset! 17670b57cec5SDimitry Andric 17680b57cec5SDimitry Andric // If we've been sext'ed then zext'd the maximum difference between Var0 and 17690b57cec5SDimitry Andric // Var1 is possible to calculate, but we're just interested in the absolute 17700b57cec5SDimitry Andric // minimum difference between the two. The minimum distance may occur due to 17710b57cec5SDimitry Andric // wrapping; consider "add i3 %i, 5": if %i == 7 then 7 + 5 mod 8 == 4, and so 17720b57cec5SDimitry Andric // the minimum distance between %i and %i + 5 is 3. 1773fe6060f1SDimitry Andric APInt MinDiff = E0.Offset - E1.Offset, Wrapped = -MinDiff; 17740b57cec5SDimitry Andric MinDiff = APIntOps::umin(MinDiff, Wrapped); 17750b57cec5SDimitry Andric APInt MinDiffBytes = 17760b57cec5SDimitry Andric MinDiff.zextOrTrunc(Var0.Scale.getBitWidth()) * Var0.Scale.abs(); 17770b57cec5SDimitry Andric 17780b57cec5SDimitry Andric // We can't definitely say whether GEP1 is before or after V2 due to wrapping 17790b57cec5SDimitry Andric // arithmetic (i.e. for some values of GEP1 and V2 GEP1 < V2, and for other 17800b57cec5SDimitry Andric // values GEP1 > V2). We'll therefore only declare NoAlias if both V1Size and 17810b57cec5SDimitry Andric // V2Size can fit in the MinDiffBytes gap. 17820b57cec5SDimitry Andric return MinDiffBytes.uge(V1Size + BaseOffset.abs()) && 17830b57cec5SDimitry Andric MinDiffBytes.uge(V2Size + BaseOffset.abs()); 17840b57cec5SDimitry Andric } 17850b57cec5SDimitry Andric 17860b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 17870b57cec5SDimitry Andric // BasicAliasAnalysis Pass 17880b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 17890b57cec5SDimitry Andric 17900b57cec5SDimitry Andric AnalysisKey BasicAA::Key; 17910b57cec5SDimitry Andric 17920b57cec5SDimitry Andric BasicAAResult BasicAA::run(Function &F, FunctionAnalysisManager &AM) { 1793e8d8bef9SDimitry Andric auto &TLI = AM.getResult<TargetLibraryAnalysis>(F); 1794e8d8bef9SDimitry Andric auto &AC = AM.getResult<AssumptionAnalysis>(F); 1795e8d8bef9SDimitry Andric auto *DT = &AM.getResult<DominatorTreeAnalysis>(F); 1796e8d8bef9SDimitry Andric auto *PV = AM.getCachedResult<PhiValuesAnalysis>(F); 1797fe6060f1SDimitry Andric return BasicAAResult(F.getParent()->getDataLayout(), F, TLI, AC, DT, PV); 17980b57cec5SDimitry Andric } 17990b57cec5SDimitry Andric 18000b57cec5SDimitry Andric BasicAAWrapperPass::BasicAAWrapperPass() : FunctionPass(ID) { 18010b57cec5SDimitry Andric initializeBasicAAWrapperPassPass(*PassRegistry::getPassRegistry()); 18020b57cec5SDimitry Andric } 18030b57cec5SDimitry Andric 18040b57cec5SDimitry Andric char BasicAAWrapperPass::ID = 0; 18050b57cec5SDimitry Andric 18060b57cec5SDimitry Andric void BasicAAWrapperPass::anchor() {} 18070b57cec5SDimitry Andric 18085ffd83dbSDimitry Andric INITIALIZE_PASS_BEGIN(BasicAAWrapperPass, "basic-aa", 1809*b32fb2a4SDimitry Andric "Basic Alias Analysis (stateless AA impl)", true, true) 18100b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 18110b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 18120b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 1813*b32fb2a4SDimitry Andric INITIALIZE_PASS_DEPENDENCY(PhiValuesWrapperPass) 18145ffd83dbSDimitry Andric INITIALIZE_PASS_END(BasicAAWrapperPass, "basic-aa", 1815*b32fb2a4SDimitry Andric "Basic Alias Analysis (stateless AA impl)", true, true) 18160b57cec5SDimitry Andric 18170b57cec5SDimitry Andric FunctionPass *llvm::createBasicAAWrapperPass() { 18180b57cec5SDimitry Andric return new BasicAAWrapperPass(); 18190b57cec5SDimitry Andric } 18200b57cec5SDimitry Andric 18210b57cec5SDimitry Andric bool BasicAAWrapperPass::runOnFunction(Function &F) { 18220b57cec5SDimitry Andric auto &ACT = getAnalysis<AssumptionCacheTracker>(); 18230b57cec5SDimitry Andric auto &TLIWP = getAnalysis<TargetLibraryInfoWrapperPass>(); 18240b57cec5SDimitry Andric auto &DTWP = getAnalysis<DominatorTreeWrapperPass>(); 18250b57cec5SDimitry Andric auto *PVWP = getAnalysisIfAvailable<PhiValuesWrapperPass>(); 18260b57cec5SDimitry Andric 18278bcb0991SDimitry Andric Result.reset(new BasicAAResult(F.getParent()->getDataLayout(), F, 18288bcb0991SDimitry Andric TLIWP.getTLI(F), ACT.getAssumptionCache(F), 18298bcb0991SDimitry Andric &DTWP.getDomTree(), 18300b57cec5SDimitry Andric PVWP ? &PVWP->getResult() : nullptr)); 18310b57cec5SDimitry Andric 18320b57cec5SDimitry Andric return false; 18330b57cec5SDimitry Andric } 18340b57cec5SDimitry Andric 18350b57cec5SDimitry Andric void BasicAAWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { 18360b57cec5SDimitry Andric AU.setPreservesAll(); 1837e8d8bef9SDimitry Andric AU.addRequiredTransitive<AssumptionCacheTracker>(); 1838e8d8bef9SDimitry Andric AU.addRequiredTransitive<DominatorTreeWrapperPass>(); 1839e8d8bef9SDimitry Andric AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>(); 18400b57cec5SDimitry Andric AU.addUsedIfAvailable<PhiValuesWrapperPass>(); 18410b57cec5SDimitry Andric } 18420b57cec5SDimitry Andric 18430b57cec5SDimitry Andric BasicAAResult llvm::createLegacyPMBasicAAResult(Pass &P, Function &F) { 18440b57cec5SDimitry Andric return BasicAAResult( 18458bcb0991SDimitry Andric F.getParent()->getDataLayout(), F, 18468bcb0991SDimitry Andric P.getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F), 18470b57cec5SDimitry Andric P.getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F)); 18480b57cec5SDimitry Andric } 1849