1 //===- BasicAliasAnalysis.cpp - Stateless Alias Analysis Impl -------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file defines the primary stateless implementation of the 10 // Alias Analysis interface that implements identities (two different 11 // globals cannot alias, etc), but does no stateful analysis. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "llvm/Analysis/BasicAliasAnalysis.h" 16 #include "llvm/ADT/APInt.h" 17 #include "llvm/ADT/ScopeExit.h" 18 #include "llvm/ADT/SmallPtrSet.h" 19 #include "llvm/ADT/SmallVector.h" 20 #include "llvm/ADT/Statistic.h" 21 #include "llvm/Analysis/AliasAnalysis.h" 22 #include "llvm/Analysis/AssumptionCache.h" 23 #include "llvm/Analysis/CFG.h" 24 #include "llvm/Analysis/CaptureTracking.h" 25 #include "llvm/Analysis/InstructionSimplify.h" 26 #include "llvm/Analysis/MemoryBuiltins.h" 27 #include "llvm/Analysis/MemoryLocation.h" 28 #include "llvm/Analysis/PhiValues.h" 29 #include "llvm/Analysis/TargetLibraryInfo.h" 30 #include "llvm/Analysis/ValueTracking.h" 31 #include "llvm/IR/Argument.h" 32 #include "llvm/IR/Attributes.h" 33 #include "llvm/IR/Constant.h" 34 #include "llvm/IR/ConstantRange.h" 35 #include "llvm/IR/Constants.h" 36 #include "llvm/IR/DataLayout.h" 37 #include "llvm/IR/DerivedTypes.h" 38 #include "llvm/IR/Dominators.h" 39 #include "llvm/IR/Function.h" 40 #include "llvm/IR/GetElementPtrTypeIterator.h" 41 #include "llvm/IR/GlobalAlias.h" 42 #include "llvm/IR/GlobalVariable.h" 43 #include "llvm/IR/InstrTypes.h" 44 #include "llvm/IR/Instruction.h" 45 #include "llvm/IR/Instructions.h" 46 #include "llvm/IR/IntrinsicInst.h" 47 #include "llvm/IR/Intrinsics.h" 48 #include "llvm/IR/Metadata.h" 49 #include "llvm/IR/Operator.h" 50 #include "llvm/IR/Type.h" 51 #include "llvm/IR/User.h" 52 #include "llvm/IR/Value.h" 53 #include "llvm/InitializePasses.h" 54 #include "llvm/Pass.h" 55 #include "llvm/Support/Casting.h" 56 #include "llvm/Support/CommandLine.h" 57 #include "llvm/Support/Compiler.h" 58 #include "llvm/Support/KnownBits.h" 59 #include <cassert> 60 #include <cstdint> 61 #include <cstdlib> 62 #include <utility> 63 64 #define DEBUG_TYPE "basicaa" 65 66 using namespace llvm; 67 68 /// Enable analysis of recursive PHI nodes. 69 static cl::opt<bool> EnableRecPhiAnalysis("basic-aa-recphi", cl::Hidden, 70 cl::init(true)); 71 72 /// SearchLimitReached / SearchTimes shows how often the limit of 73 /// to decompose GEPs is reached. It will affect the precision 74 /// of basic alias analysis. 75 STATISTIC(SearchLimitReached, "Number of times the limit to " 76 "decompose GEPs is reached"); 77 STATISTIC(SearchTimes, "Number of times a GEP is decomposed"); 78 79 /// Cutoff after which to stop analysing a set of phi nodes potentially involved 80 /// in a cycle. Because we are analysing 'through' phi nodes, we need to be 81 /// careful with value equivalence. We use reachability to make sure a value 82 /// cannot be involved in a cycle. 83 const unsigned MaxNumPhiBBsValueReachabilityCheck = 20; 84 85 // The max limit of the search depth in DecomposeGEPExpression() and 86 // getUnderlyingObject(). 87 static const unsigned MaxLookupSearchDepth = 6; 88 89 bool BasicAAResult::invalidate(Function &Fn, const PreservedAnalyses &PA, 90 FunctionAnalysisManager::Invalidator &Inv) { 91 // We don't care if this analysis itself is preserved, it has no state. But 92 // we need to check that the analyses it depends on have been. Note that we 93 // may be created without handles to some analyses and in that case don't 94 // depend on them. 95 if (Inv.invalidate<AssumptionAnalysis>(Fn, PA) || 96 (DT && Inv.invalidate<DominatorTreeAnalysis>(Fn, PA)) || 97 (PV && Inv.invalidate<PhiValuesAnalysis>(Fn, PA))) 98 return true; 99 100 // Otherwise this analysis result remains valid. 101 return false; 102 } 103 104 //===----------------------------------------------------------------------===// 105 // Useful predicates 106 //===----------------------------------------------------------------------===// 107 108 /// Returns true if the pointer is one which would have been considered an 109 /// escape by isNonEscapingLocalObject. 110 static bool isEscapeSource(const Value *V) { 111 if (isa<CallBase>(V)) 112 return true; 113 114 // The load case works because isNonEscapingLocalObject considers all 115 // stores to be escapes (it passes true for the StoreCaptures argument 116 // to PointerMayBeCaptured). 117 if (isa<LoadInst>(V)) 118 return true; 119 120 // The inttoptr case works because isNonEscapingLocalObject considers all 121 // means of converting or equating a pointer to an int (ptrtoint, ptr store 122 // which could be followed by an integer load, ptr<->int compare) as 123 // escaping, and objects located at well-known addresses via platform-specific 124 // means cannot be considered non-escaping local objects. 125 if (isa<IntToPtrInst>(V)) 126 return true; 127 128 return false; 129 } 130 131 /// Returns the size of the object specified by V or UnknownSize if unknown. 132 static uint64_t getObjectSize(const Value *V, const DataLayout &DL, 133 const TargetLibraryInfo &TLI, 134 bool NullIsValidLoc, 135 bool RoundToAlign = false) { 136 uint64_t Size; 137 ObjectSizeOpts Opts; 138 Opts.RoundToAlign = RoundToAlign; 139 Opts.NullIsUnknownSize = NullIsValidLoc; 140 if (getObjectSize(V, Size, DL, &TLI, Opts)) 141 return Size; 142 return MemoryLocation::UnknownSize; 143 } 144 145 /// Returns true if we can prove that the object specified by V is smaller than 146 /// Size. 147 static bool isObjectSmallerThan(const Value *V, uint64_t Size, 148 const DataLayout &DL, 149 const TargetLibraryInfo &TLI, 150 bool NullIsValidLoc) { 151 // Note that the meanings of the "object" are slightly different in the 152 // following contexts: 153 // c1: llvm::getObjectSize() 154 // c2: llvm.objectsize() intrinsic 155 // c3: isObjectSmallerThan() 156 // c1 and c2 share the same meaning; however, the meaning of "object" in c3 157 // refers to the "entire object". 158 // 159 // Consider this example: 160 // char *p = (char*)malloc(100) 161 // char *q = p+80; 162 // 163 // In the context of c1 and c2, the "object" pointed by q refers to the 164 // stretch of memory of q[0:19]. So, getObjectSize(q) should return 20. 165 // 166 // However, in the context of c3, the "object" refers to the chunk of memory 167 // being allocated. So, the "object" has 100 bytes, and q points to the middle 168 // the "object". In case q is passed to isObjectSmallerThan() as the 1st 169 // parameter, before the llvm::getObjectSize() is called to get the size of 170 // entire object, we should: 171 // - either rewind the pointer q to the base-address of the object in 172 // question (in this case rewind to p), or 173 // - just give up. It is up to caller to make sure the pointer is pointing 174 // to the base address the object. 175 // 176 // We go for 2nd option for simplicity. 177 if (!isIdentifiedObject(V)) 178 return false; 179 180 // This function needs to use the aligned object size because we allow 181 // reads a bit past the end given sufficient alignment. 182 uint64_t ObjectSize = getObjectSize(V, DL, TLI, NullIsValidLoc, 183 /*RoundToAlign*/ true); 184 185 return ObjectSize != MemoryLocation::UnknownSize && ObjectSize < Size; 186 } 187 188 /// Return the minimal extent from \p V to the end of the underlying object, 189 /// assuming the result is used in an aliasing query. E.g., we do use the query 190 /// location size and the fact that null pointers cannot alias here. 191 static uint64_t getMinimalExtentFrom(const Value &V, 192 const LocationSize &LocSize, 193 const DataLayout &DL, 194 bool NullIsValidLoc) { 195 // If we have dereferenceability information we know a lower bound for the 196 // extent as accesses for a lower offset would be valid. We need to exclude 197 // the "or null" part if null is a valid pointer. We can ignore frees, as an 198 // access after free would be undefined behavior. 199 bool CanBeNull, CanBeFreed; 200 uint64_t DerefBytes = 201 V.getPointerDereferenceableBytes(DL, CanBeNull, CanBeFreed); 202 DerefBytes = (CanBeNull && NullIsValidLoc) ? 0 : DerefBytes; 203 // If queried with a precise location size, we assume that location size to be 204 // accessed, thus valid. 205 if (LocSize.isPrecise()) 206 DerefBytes = std::max(DerefBytes, LocSize.getValue()); 207 return DerefBytes; 208 } 209 210 /// Returns true if we can prove that the object specified by V has size Size. 211 static bool isObjectSize(const Value *V, uint64_t Size, const DataLayout &DL, 212 const TargetLibraryInfo &TLI, bool NullIsValidLoc) { 213 uint64_t ObjectSize = getObjectSize(V, DL, TLI, NullIsValidLoc); 214 return ObjectSize != MemoryLocation::UnknownSize && ObjectSize == Size; 215 } 216 217 //===----------------------------------------------------------------------===// 218 // CaptureInfo implementations 219 //===----------------------------------------------------------------------===// 220 221 CaptureInfo::~CaptureInfo() = default; 222 223 bool SimpleCaptureInfo::isNotCapturedBeforeOrAt(const Value *Object, 224 const Instruction *I) { 225 return isNonEscapingLocalObject(Object, &IsCapturedCache); 226 } 227 228 bool EarliestEscapeInfo::isNotCapturedBeforeOrAt(const Value *Object, 229 const Instruction *I) { 230 if (!isIdentifiedFunctionLocal(Object)) 231 return false; 232 233 auto Iter = EarliestEscapes.insert({Object, nullptr}); 234 if (Iter.second) { 235 Instruction *EarliestCapture = FindEarliestCapture( 236 Object, *const_cast<Function *>(I->getFunction()), 237 /*ReturnCaptures=*/false, /*StoreCaptures=*/true, DT); 238 if (EarliestCapture) { 239 auto Ins = Inst2Obj.insert({EarliestCapture, {}}); 240 Ins.first->second.push_back(Object); 241 } 242 Iter.first->second = EarliestCapture; 243 } 244 245 // No capturing instruction. 246 if (!Iter.first->second) 247 return true; 248 249 return I != Iter.first->second && 250 !isPotentiallyReachable(Iter.first->second, I, nullptr, &DT, &LI); 251 } 252 253 void EarliestEscapeInfo::removeInstruction(Instruction *I) { 254 auto Iter = Inst2Obj.find(I); 255 if (Iter != Inst2Obj.end()) { 256 for (const Value *Obj : Iter->second) 257 EarliestEscapes.erase(Obj); 258 Inst2Obj.erase(I); 259 } 260 } 261 262 //===----------------------------------------------------------------------===// 263 // GetElementPtr Instruction Decomposition and Analysis 264 //===----------------------------------------------------------------------===// 265 266 namespace { 267 /// Represents zext(sext(trunc(V))). 268 struct CastedValue { 269 const Value *V; 270 unsigned ZExtBits = 0; 271 unsigned SExtBits = 0; 272 unsigned TruncBits = 0; 273 274 explicit CastedValue(const Value *V) : V(V) {} 275 explicit CastedValue(const Value *V, unsigned ZExtBits, unsigned SExtBits, 276 unsigned TruncBits) 277 : V(V), ZExtBits(ZExtBits), SExtBits(SExtBits), TruncBits(TruncBits) {} 278 279 unsigned getBitWidth() const { 280 return V->getType()->getPrimitiveSizeInBits() - TruncBits + ZExtBits + 281 SExtBits; 282 } 283 284 CastedValue withValue(const Value *NewV) const { 285 return CastedValue(NewV, ZExtBits, SExtBits, TruncBits); 286 } 287 288 /// Replace V with zext(NewV) 289 CastedValue withZExtOfValue(const Value *NewV) const { 290 unsigned ExtendBy = V->getType()->getPrimitiveSizeInBits() - 291 NewV->getType()->getPrimitiveSizeInBits(); 292 if (ExtendBy <= TruncBits) 293 return CastedValue(NewV, ZExtBits, SExtBits, TruncBits - ExtendBy); 294 295 // zext(sext(zext(NewV))) == zext(zext(zext(NewV))) 296 ExtendBy -= TruncBits; 297 return CastedValue(NewV, ZExtBits + SExtBits + ExtendBy, 0, 0); 298 } 299 300 /// Replace V with sext(NewV) 301 CastedValue withSExtOfValue(const Value *NewV) const { 302 unsigned ExtendBy = V->getType()->getPrimitiveSizeInBits() - 303 NewV->getType()->getPrimitiveSizeInBits(); 304 if (ExtendBy <= TruncBits) 305 return CastedValue(NewV, ZExtBits, SExtBits, TruncBits - ExtendBy); 306 307 // zext(sext(sext(NewV))) 308 ExtendBy -= TruncBits; 309 return CastedValue(NewV, ZExtBits, SExtBits + ExtendBy, 0); 310 } 311 312 APInt evaluateWith(APInt N) const { 313 assert(N.getBitWidth() == V->getType()->getPrimitiveSizeInBits() && 314 "Incompatible bit width"); 315 if (TruncBits) N = N.trunc(N.getBitWidth() - TruncBits); 316 if (SExtBits) N = N.sext(N.getBitWidth() + SExtBits); 317 if (ZExtBits) N = N.zext(N.getBitWidth() + ZExtBits); 318 return N; 319 } 320 321 ConstantRange evaluateWith(ConstantRange N) const { 322 assert(N.getBitWidth() == V->getType()->getPrimitiveSizeInBits() && 323 "Incompatible bit width"); 324 if (TruncBits) N = N.truncate(N.getBitWidth() - TruncBits); 325 if (SExtBits) N = N.signExtend(N.getBitWidth() + SExtBits); 326 if (ZExtBits) N = N.zeroExtend(N.getBitWidth() + ZExtBits); 327 return N; 328 } 329 330 bool canDistributeOver(bool NUW, bool NSW) const { 331 // zext(x op<nuw> y) == zext(x) op<nuw> zext(y) 332 // sext(x op<nsw> y) == sext(x) op<nsw> sext(y) 333 // trunc(x op y) == trunc(x) op trunc(y) 334 return (!ZExtBits || NUW) && (!SExtBits || NSW); 335 } 336 337 bool hasSameCastsAs(const CastedValue &Other) const { 338 return ZExtBits == Other.ZExtBits && SExtBits == Other.SExtBits && 339 TruncBits == Other.TruncBits; 340 } 341 }; 342 343 /// Represents zext(sext(trunc(V))) * Scale + Offset. 344 struct LinearExpression { 345 CastedValue Val; 346 APInt Scale; 347 APInt Offset; 348 349 /// True if all operations in this expression are NSW. 350 bool IsNSW; 351 352 LinearExpression(const CastedValue &Val, const APInt &Scale, 353 const APInt &Offset, bool IsNSW) 354 : Val(Val), Scale(Scale), Offset(Offset), IsNSW(IsNSW) {} 355 356 LinearExpression(const CastedValue &Val) : Val(Val), IsNSW(true) { 357 unsigned BitWidth = Val.getBitWidth(); 358 Scale = APInt(BitWidth, 1); 359 Offset = APInt(BitWidth, 0); 360 } 361 362 LinearExpression mul(const APInt &Other, bool MulIsNSW) const { 363 // The check for zero offset is necessary, because generally 364 // (X +nsw Y) *nsw Z does not imply (X *nsw Z) +nsw (Y *nsw Z). 365 bool NSW = IsNSW && (Other.isOne() || (MulIsNSW && Offset.isZero())); 366 return LinearExpression(Val, Scale * Other, Offset * Other, NSW); 367 } 368 }; 369 } 370 371 /// Analyzes the specified value as a linear expression: "A*V + B", where A and 372 /// B are constant integers. 373 static LinearExpression GetLinearExpression( 374 const CastedValue &Val, const DataLayout &DL, unsigned Depth, 375 AssumptionCache *AC, DominatorTree *DT) { 376 // Limit our recursion depth. 377 if (Depth == 6) 378 return Val; 379 380 if (const ConstantInt *Const = dyn_cast<ConstantInt>(Val.V)) 381 return LinearExpression(Val, APInt(Val.getBitWidth(), 0), 382 Val.evaluateWith(Const->getValue()), true); 383 384 if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(Val.V)) { 385 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(BOp->getOperand(1))) { 386 APInt RHS = Val.evaluateWith(RHSC->getValue()); 387 // The only non-OBO case we deal with is or, and only limited to the 388 // case where it is both nuw and nsw. 389 bool NUW = true, NSW = true; 390 if (isa<OverflowingBinaryOperator>(BOp)) { 391 NUW &= BOp->hasNoUnsignedWrap(); 392 NSW &= BOp->hasNoSignedWrap(); 393 } 394 if (!Val.canDistributeOver(NUW, NSW)) 395 return Val; 396 397 // While we can distribute over trunc, we cannot preserve nowrap flags 398 // in that case. 399 if (Val.TruncBits) 400 NUW = NSW = false; 401 402 LinearExpression E(Val); 403 switch (BOp->getOpcode()) { 404 default: 405 // We don't understand this instruction, so we can't decompose it any 406 // further. 407 return Val; 408 case Instruction::Or: 409 // X|C == X+C if all the bits in C are unset in X. Otherwise we can't 410 // analyze it. 411 if (!MaskedValueIsZero(BOp->getOperand(0), RHSC->getValue(), DL, 0, AC, 412 BOp, DT)) 413 return Val; 414 415 LLVM_FALLTHROUGH; 416 case Instruction::Add: { 417 E = GetLinearExpression(Val.withValue(BOp->getOperand(0)), DL, 418 Depth + 1, AC, DT); 419 E.Offset += RHS; 420 E.IsNSW &= NSW; 421 break; 422 } 423 case Instruction::Sub: { 424 E = GetLinearExpression(Val.withValue(BOp->getOperand(0)), DL, 425 Depth + 1, AC, DT); 426 E.Offset -= RHS; 427 E.IsNSW &= NSW; 428 break; 429 } 430 case Instruction::Mul: 431 E = GetLinearExpression(Val.withValue(BOp->getOperand(0)), DL, 432 Depth + 1, AC, DT) 433 .mul(RHS, NSW); 434 break; 435 case Instruction::Shl: 436 // We're trying to linearize an expression of the kind: 437 // shl i8 -128, 36 438 // where the shift count exceeds the bitwidth of the type. 439 // We can't decompose this further (the expression would return 440 // a poison value). 441 if (RHS.getLimitedValue() > Val.getBitWidth()) 442 return Val; 443 444 E = GetLinearExpression(Val.withValue(BOp->getOperand(0)), DL, 445 Depth + 1, AC, DT); 446 E.Offset <<= RHS.getLimitedValue(); 447 E.Scale <<= RHS.getLimitedValue(); 448 E.IsNSW &= NSW; 449 break; 450 } 451 return E; 452 } 453 } 454 455 if (isa<ZExtInst>(Val.V)) 456 return GetLinearExpression( 457 Val.withZExtOfValue(cast<CastInst>(Val.V)->getOperand(0)), 458 DL, Depth + 1, AC, DT); 459 460 if (isa<SExtInst>(Val.V)) 461 return GetLinearExpression( 462 Val.withSExtOfValue(cast<CastInst>(Val.V)->getOperand(0)), 463 DL, Depth + 1, AC, DT); 464 465 return Val; 466 } 467 468 /// To ensure a pointer offset fits in an integer of size IndexSize 469 /// (in bits) when that size is smaller than the maximum index size. This is 470 /// an issue, for example, in particular for 32b pointers with negative indices 471 /// that rely on two's complement wrap-arounds for precise alias information 472 /// where the maximum index size is 64b. 473 static APInt adjustToIndexSize(const APInt &Offset, unsigned IndexSize) { 474 assert(IndexSize <= Offset.getBitWidth() && "Invalid IndexSize!"); 475 unsigned ShiftBits = Offset.getBitWidth() - IndexSize; 476 return (Offset << ShiftBits).ashr(ShiftBits); 477 } 478 479 namespace { 480 // A linear transformation of a Value; this class represents 481 // ZExt(SExt(Trunc(V, TruncBits), SExtBits), ZExtBits) * Scale. 482 struct VariableGEPIndex { 483 CastedValue Val; 484 APInt Scale; 485 486 // Context instruction to use when querying information about this index. 487 const Instruction *CxtI; 488 489 /// True if all operations in this expression are NSW. 490 bool IsNSW; 491 492 void dump() const { 493 print(dbgs()); 494 dbgs() << "\n"; 495 } 496 void print(raw_ostream &OS) const { 497 OS << "(V=" << Val.V->getName() 498 << ", zextbits=" << Val.ZExtBits 499 << ", sextbits=" << Val.SExtBits 500 << ", truncbits=" << Val.TruncBits 501 << ", scale=" << Scale << ")"; 502 } 503 }; 504 } 505 506 // Represents the internal structure of a GEP, decomposed into a base pointer, 507 // constant offsets, and variable scaled indices. 508 struct BasicAAResult::DecomposedGEP { 509 // Base pointer of the GEP 510 const Value *Base; 511 // Total constant offset from base. 512 APInt Offset; 513 // Scaled variable (non-constant) indices. 514 SmallVector<VariableGEPIndex, 4> VarIndices; 515 // Are all operations inbounds GEPs or non-indexing operations? 516 // (None iff expression doesn't involve any geps) 517 Optional<bool> InBounds; 518 519 void dump() const { 520 print(dbgs()); 521 dbgs() << "\n"; 522 } 523 void print(raw_ostream &OS) const { 524 OS << "(DecomposedGEP Base=" << Base->getName() 525 << ", Offset=" << Offset 526 << ", VarIndices=["; 527 for (size_t i = 0; i < VarIndices.size(); i++) { 528 if (i != 0) 529 OS << ", "; 530 VarIndices[i].print(OS); 531 } 532 OS << "])"; 533 } 534 }; 535 536 537 /// If V is a symbolic pointer expression, decompose it into a base pointer 538 /// with a constant offset and a number of scaled symbolic offsets. 539 /// 540 /// The scaled symbolic offsets (represented by pairs of a Value* and a scale 541 /// in the VarIndices vector) are Value*'s that are known to be scaled by the 542 /// specified amount, but which may have other unrepresented high bits. As 543 /// such, the gep cannot necessarily be reconstructed from its decomposed form. 544 BasicAAResult::DecomposedGEP 545 BasicAAResult::DecomposeGEPExpression(const Value *V, const DataLayout &DL, 546 AssumptionCache *AC, DominatorTree *DT) { 547 // Limit recursion depth to limit compile time in crazy cases. 548 unsigned MaxLookup = MaxLookupSearchDepth; 549 SearchTimes++; 550 const Instruction *CxtI = dyn_cast<Instruction>(V); 551 552 unsigned MaxIndexSize = DL.getMaxIndexSizeInBits(); 553 DecomposedGEP Decomposed; 554 Decomposed.Offset = APInt(MaxIndexSize, 0); 555 do { 556 // See if this is a bitcast or GEP. 557 const Operator *Op = dyn_cast<Operator>(V); 558 if (!Op) { 559 // The only non-operator case we can handle are GlobalAliases. 560 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) { 561 if (!GA->isInterposable()) { 562 V = GA->getAliasee(); 563 continue; 564 } 565 } 566 Decomposed.Base = V; 567 return Decomposed; 568 } 569 570 if (Op->getOpcode() == Instruction::BitCast || 571 Op->getOpcode() == Instruction::AddrSpaceCast) { 572 V = Op->getOperand(0); 573 continue; 574 } 575 576 const GEPOperator *GEPOp = dyn_cast<GEPOperator>(Op); 577 if (!GEPOp) { 578 if (const auto *PHI = dyn_cast<PHINode>(V)) { 579 // Look through single-arg phi nodes created by LCSSA. 580 if (PHI->getNumIncomingValues() == 1) { 581 V = PHI->getIncomingValue(0); 582 continue; 583 } 584 } else if (const auto *Call = dyn_cast<CallBase>(V)) { 585 // CaptureTracking can know about special capturing properties of some 586 // intrinsics like launder.invariant.group, that can't be expressed with 587 // the attributes, but have properties like returning aliasing pointer. 588 // Because some analysis may assume that nocaptured pointer is not 589 // returned from some special intrinsic (because function would have to 590 // be marked with returns attribute), it is crucial to use this function 591 // because it should be in sync with CaptureTracking. Not using it may 592 // cause weird miscompilations where 2 aliasing pointers are assumed to 593 // noalias. 594 if (auto *RP = getArgumentAliasingToReturnedPointer(Call, false)) { 595 V = RP; 596 continue; 597 } 598 } 599 600 Decomposed.Base = V; 601 return Decomposed; 602 } 603 604 // Track whether we've seen at least one in bounds gep, and if so, whether 605 // all geps parsed were in bounds. 606 if (Decomposed.InBounds == None) 607 Decomposed.InBounds = GEPOp->isInBounds(); 608 else if (!GEPOp->isInBounds()) 609 Decomposed.InBounds = false; 610 611 assert(GEPOp->getSourceElementType()->isSized() && "GEP must be sized"); 612 613 // Don't attempt to analyze GEPs if index scale is not a compile-time 614 // constant. 615 if (isa<ScalableVectorType>(GEPOp->getSourceElementType())) { 616 Decomposed.Base = V; 617 return Decomposed; 618 } 619 620 unsigned AS = GEPOp->getPointerAddressSpace(); 621 // Walk the indices of the GEP, accumulating them into BaseOff/VarIndices. 622 gep_type_iterator GTI = gep_type_begin(GEPOp); 623 unsigned IndexSize = DL.getIndexSizeInBits(AS); 624 // Assume all GEP operands are constants until proven otherwise. 625 bool GepHasConstantOffset = true; 626 for (User::const_op_iterator I = GEPOp->op_begin() + 1, E = GEPOp->op_end(); 627 I != E; ++I, ++GTI) { 628 const Value *Index = *I; 629 // Compute the (potentially symbolic) offset in bytes for this index. 630 if (StructType *STy = GTI.getStructTypeOrNull()) { 631 // For a struct, add the member offset. 632 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue(); 633 if (FieldNo == 0) 634 continue; 635 636 Decomposed.Offset += DL.getStructLayout(STy)->getElementOffset(FieldNo); 637 continue; 638 } 639 640 // For an array/pointer, add the element offset, explicitly scaled. 641 if (const ConstantInt *CIdx = dyn_cast<ConstantInt>(Index)) { 642 if (CIdx->isZero()) 643 continue; 644 Decomposed.Offset += 645 DL.getTypeAllocSize(GTI.getIndexedType()).getFixedSize() * 646 CIdx->getValue().sextOrTrunc(MaxIndexSize); 647 continue; 648 } 649 650 GepHasConstantOffset = false; 651 652 // If the integer type is smaller than the index size, it is implicitly 653 // sign extended or truncated to index size. 654 unsigned Width = Index->getType()->getIntegerBitWidth(); 655 unsigned SExtBits = IndexSize > Width ? IndexSize - Width : 0; 656 unsigned TruncBits = IndexSize < Width ? Width - IndexSize : 0; 657 LinearExpression LE = GetLinearExpression( 658 CastedValue(Index, 0, SExtBits, TruncBits), DL, 0, AC, DT); 659 660 // Scale by the type size. 661 unsigned TypeSize = 662 DL.getTypeAllocSize(GTI.getIndexedType()).getFixedSize(); 663 LE = LE.mul(APInt(IndexSize, TypeSize), GEPOp->isInBounds()); 664 Decomposed.Offset += LE.Offset.sextOrSelf(MaxIndexSize); 665 APInt Scale = LE.Scale.sextOrSelf(MaxIndexSize); 666 667 // If we already had an occurrence of this index variable, merge this 668 // scale into it. For example, we want to handle: 669 // A[x][x] -> x*16 + x*4 -> x*20 670 // This also ensures that 'x' only appears in the index list once. 671 for (unsigned i = 0, e = Decomposed.VarIndices.size(); i != e; ++i) { 672 if (Decomposed.VarIndices[i].Val.V == LE.Val.V && 673 Decomposed.VarIndices[i].Val.hasSameCastsAs(LE.Val)) { 674 Scale += Decomposed.VarIndices[i].Scale; 675 Decomposed.VarIndices.erase(Decomposed.VarIndices.begin() + i); 676 break; 677 } 678 } 679 680 // Make sure that we have a scale that makes sense for this target's 681 // index size. 682 Scale = adjustToIndexSize(Scale, IndexSize); 683 684 if (!!Scale) { 685 VariableGEPIndex Entry = {LE.Val, Scale, CxtI, LE.IsNSW}; 686 Decomposed.VarIndices.push_back(Entry); 687 } 688 } 689 690 // Take care of wrap-arounds 691 if (GepHasConstantOffset) 692 Decomposed.Offset = adjustToIndexSize(Decomposed.Offset, IndexSize); 693 694 // Analyze the base pointer next. 695 V = GEPOp->getOperand(0); 696 } while (--MaxLookup); 697 698 // If the chain of expressions is too deep, just return early. 699 Decomposed.Base = V; 700 SearchLimitReached++; 701 return Decomposed; 702 } 703 704 /// Returns whether the given pointer value points to memory that is local to 705 /// the function, with global constants being considered local to all 706 /// functions. 707 bool BasicAAResult::pointsToConstantMemory(const MemoryLocation &Loc, 708 AAQueryInfo &AAQI, bool OrLocal) { 709 assert(Visited.empty() && "Visited must be cleared after use!"); 710 711 unsigned MaxLookup = 8; 712 SmallVector<const Value *, 16> Worklist; 713 Worklist.push_back(Loc.Ptr); 714 do { 715 const Value *V = getUnderlyingObject(Worklist.pop_back_val()); 716 if (!Visited.insert(V).second) { 717 Visited.clear(); 718 return AAResultBase::pointsToConstantMemory(Loc, AAQI, OrLocal); 719 } 720 721 // An alloca instruction defines local memory. 722 if (OrLocal && isa<AllocaInst>(V)) 723 continue; 724 725 // A global constant counts as local memory for our purposes. 726 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) { 727 // Note: this doesn't require GV to be "ODR" because it isn't legal for a 728 // global to be marked constant in some modules and non-constant in 729 // others. GV may even be a declaration, not a definition. 730 if (!GV->isConstant()) { 731 Visited.clear(); 732 return AAResultBase::pointsToConstantMemory(Loc, AAQI, OrLocal); 733 } 734 continue; 735 } 736 737 // If both select values point to local memory, then so does the select. 738 if (const SelectInst *SI = dyn_cast<SelectInst>(V)) { 739 Worklist.push_back(SI->getTrueValue()); 740 Worklist.push_back(SI->getFalseValue()); 741 continue; 742 } 743 744 // If all values incoming to a phi node point to local memory, then so does 745 // the phi. 746 if (const PHINode *PN = dyn_cast<PHINode>(V)) { 747 // Don't bother inspecting phi nodes with many operands. 748 if (PN->getNumIncomingValues() > MaxLookup) { 749 Visited.clear(); 750 return AAResultBase::pointsToConstantMemory(Loc, AAQI, OrLocal); 751 } 752 append_range(Worklist, PN->incoming_values()); 753 continue; 754 } 755 756 // Otherwise be conservative. 757 Visited.clear(); 758 return AAResultBase::pointsToConstantMemory(Loc, AAQI, OrLocal); 759 } while (!Worklist.empty() && --MaxLookup); 760 761 Visited.clear(); 762 return Worklist.empty(); 763 } 764 765 static bool isIntrinsicCall(const CallBase *Call, Intrinsic::ID IID) { 766 const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Call); 767 return II && II->getIntrinsicID() == IID; 768 } 769 770 /// Returns the behavior when calling the given call site. 771 FunctionModRefBehavior BasicAAResult::getModRefBehavior(const CallBase *Call) { 772 if (Call->doesNotAccessMemory()) 773 // Can't do better than this. 774 return FMRB_DoesNotAccessMemory; 775 776 FunctionModRefBehavior Min = FMRB_UnknownModRefBehavior; 777 778 // If the callsite knows it only reads memory, don't return worse 779 // than that. 780 if (Call->onlyReadsMemory()) 781 Min = FMRB_OnlyReadsMemory; 782 else if (Call->onlyWritesMemory()) 783 Min = FMRB_OnlyWritesMemory; 784 785 if (Call->onlyAccessesArgMemory()) 786 Min = FunctionModRefBehavior(Min & FMRB_OnlyAccessesArgumentPointees); 787 else if (Call->onlyAccessesInaccessibleMemory()) 788 Min = FunctionModRefBehavior(Min & FMRB_OnlyAccessesInaccessibleMem); 789 else if (Call->onlyAccessesInaccessibleMemOrArgMem()) 790 Min = FunctionModRefBehavior(Min & FMRB_OnlyAccessesInaccessibleOrArgMem); 791 792 // If the call has operand bundles then aliasing attributes from the function 793 // it calls do not directly apply to the call. This can be made more precise 794 // in the future. 795 if (!Call->hasOperandBundles()) 796 if (const Function *F = Call->getCalledFunction()) 797 Min = 798 FunctionModRefBehavior(Min & getBestAAResults().getModRefBehavior(F)); 799 800 return Min; 801 } 802 803 /// Returns the behavior when calling the given function. For use when the call 804 /// site is not known. 805 FunctionModRefBehavior BasicAAResult::getModRefBehavior(const Function *F) { 806 // If the function declares it doesn't access memory, we can't do better. 807 if (F->doesNotAccessMemory()) 808 return FMRB_DoesNotAccessMemory; 809 810 FunctionModRefBehavior Min = FMRB_UnknownModRefBehavior; 811 812 // If the function declares it only reads memory, go with that. 813 if (F->onlyReadsMemory()) 814 Min = FMRB_OnlyReadsMemory; 815 else if (F->onlyWritesMemory()) 816 Min = FMRB_OnlyWritesMemory; 817 818 if (F->onlyAccessesArgMemory()) 819 Min = FunctionModRefBehavior(Min & FMRB_OnlyAccessesArgumentPointees); 820 else if (F->onlyAccessesInaccessibleMemory()) 821 Min = FunctionModRefBehavior(Min & FMRB_OnlyAccessesInaccessibleMem); 822 else if (F->onlyAccessesInaccessibleMemOrArgMem()) 823 Min = FunctionModRefBehavior(Min & FMRB_OnlyAccessesInaccessibleOrArgMem); 824 825 return Min; 826 } 827 828 /// Returns true if this is a writeonly (i.e Mod only) parameter. 829 static bool isWriteOnlyParam(const CallBase *Call, unsigned ArgIdx, 830 const TargetLibraryInfo &TLI) { 831 if (Call->paramHasAttr(ArgIdx, Attribute::WriteOnly)) 832 return true; 833 834 // We can bound the aliasing properties of memset_pattern16 just as we can 835 // for memcpy/memset. This is particularly important because the 836 // LoopIdiomRecognizer likes to turn loops into calls to memset_pattern16 837 // whenever possible. 838 // FIXME Consider handling this in InferFunctionAttr.cpp together with other 839 // attributes. 840 LibFunc F; 841 if (Call->getCalledFunction() && 842 TLI.getLibFunc(*Call->getCalledFunction(), F) && 843 F == LibFunc_memset_pattern16 && TLI.has(F)) 844 if (ArgIdx == 0) 845 return true; 846 847 // TODO: memset_pattern4, memset_pattern8 848 // TODO: _chk variants 849 // TODO: strcmp, strcpy 850 851 return false; 852 } 853 854 ModRefInfo BasicAAResult::getArgModRefInfo(const CallBase *Call, 855 unsigned ArgIdx) { 856 // Checking for known builtin intrinsics and target library functions. 857 if (isWriteOnlyParam(Call, ArgIdx, TLI)) 858 return ModRefInfo::Mod; 859 860 if (Call->paramHasAttr(ArgIdx, Attribute::ReadOnly)) 861 return ModRefInfo::Ref; 862 863 if (Call->paramHasAttr(ArgIdx, Attribute::ReadNone)) 864 return ModRefInfo::NoModRef; 865 866 return AAResultBase::getArgModRefInfo(Call, ArgIdx); 867 } 868 869 #ifndef NDEBUG 870 static const Function *getParent(const Value *V) { 871 if (const Instruction *inst = dyn_cast<Instruction>(V)) { 872 if (!inst->getParent()) 873 return nullptr; 874 return inst->getParent()->getParent(); 875 } 876 877 if (const Argument *arg = dyn_cast<Argument>(V)) 878 return arg->getParent(); 879 880 return nullptr; 881 } 882 883 static bool notDifferentParent(const Value *O1, const Value *O2) { 884 885 const Function *F1 = getParent(O1); 886 const Function *F2 = getParent(O2); 887 888 return !F1 || !F2 || F1 == F2; 889 } 890 #endif 891 892 AliasResult BasicAAResult::alias(const MemoryLocation &LocA, 893 const MemoryLocation &LocB, 894 AAQueryInfo &AAQI) { 895 assert(notDifferentParent(LocA.Ptr, LocB.Ptr) && 896 "BasicAliasAnalysis doesn't support interprocedural queries."); 897 return aliasCheck(LocA.Ptr, LocA.Size, LocB.Ptr, LocB.Size, AAQI); 898 } 899 900 /// Checks to see if the specified callsite can clobber the specified memory 901 /// object. 902 /// 903 /// Since we only look at local properties of this function, we really can't 904 /// say much about this query. We do, however, use simple "address taken" 905 /// analysis on local objects. 906 ModRefInfo BasicAAResult::getModRefInfo(const CallBase *Call, 907 const MemoryLocation &Loc, 908 AAQueryInfo &AAQI) { 909 assert(notDifferentParent(Call, Loc.Ptr) && 910 "AliasAnalysis query involving multiple functions!"); 911 912 const Value *Object = getUnderlyingObject(Loc.Ptr); 913 914 // Calls marked 'tail' cannot read or write allocas from the current frame 915 // because the current frame might be destroyed by the time they run. However, 916 // a tail call may use an alloca with byval. Calling with byval copies the 917 // contents of the alloca into argument registers or stack slots, so there is 918 // no lifetime issue. 919 if (isa<AllocaInst>(Object)) 920 if (const CallInst *CI = dyn_cast<CallInst>(Call)) 921 if (CI->isTailCall() && 922 !CI->getAttributes().hasAttrSomewhere(Attribute::ByVal)) 923 return ModRefInfo::NoModRef; 924 925 // Stack restore is able to modify unescaped dynamic allocas. Assume it may 926 // modify them even though the alloca is not escaped. 927 if (auto *AI = dyn_cast<AllocaInst>(Object)) 928 if (!AI->isStaticAlloca() && isIntrinsicCall(Call, Intrinsic::stackrestore)) 929 return ModRefInfo::Mod; 930 931 // If the pointer is to a locally allocated object that does not escape, 932 // then the call can not mod/ref the pointer unless the call takes the pointer 933 // as an argument, and itself doesn't capture it. 934 if (!isa<Constant>(Object) && Call != Object && 935 AAQI.CI->isNotCapturedBeforeOrAt(Object, Call)) { 936 937 // Optimistically assume that call doesn't touch Object and check this 938 // assumption in the following loop. 939 ModRefInfo Result = ModRefInfo::NoModRef; 940 bool IsMustAlias = true; 941 942 unsigned OperandNo = 0; 943 for (auto CI = Call->data_operands_begin(), CE = Call->data_operands_end(); 944 CI != CE; ++CI, ++OperandNo) { 945 // Only look at the no-capture or byval pointer arguments. If this 946 // pointer were passed to arguments that were neither of these, then it 947 // couldn't be no-capture. 948 if (!(*CI)->getType()->isPointerTy() || 949 (!Call->doesNotCapture(OperandNo) && OperandNo < Call->arg_size() && 950 !Call->isByValArgument(OperandNo))) 951 continue; 952 953 // Call doesn't access memory through this operand, so we don't care 954 // if it aliases with Object. 955 if (Call->doesNotAccessMemory(OperandNo)) 956 continue; 957 958 // If this is a no-capture pointer argument, see if we can tell that it 959 // is impossible to alias the pointer we're checking. 960 AliasResult AR = getBestAAResults().alias( 961 MemoryLocation::getBeforeOrAfter(*CI), 962 MemoryLocation::getBeforeOrAfter(Object), AAQI); 963 if (AR != AliasResult::MustAlias) 964 IsMustAlias = false; 965 // Operand doesn't alias 'Object', continue looking for other aliases 966 if (AR == AliasResult::NoAlias) 967 continue; 968 // Operand aliases 'Object', but call doesn't modify it. Strengthen 969 // initial assumption and keep looking in case if there are more aliases. 970 if (Call->onlyReadsMemory(OperandNo)) { 971 Result = setRef(Result); 972 continue; 973 } 974 // Operand aliases 'Object' but call only writes into it. 975 if (Call->onlyWritesMemory(OperandNo)) { 976 Result = setMod(Result); 977 continue; 978 } 979 // This operand aliases 'Object' and call reads and writes into it. 980 // Setting ModRef will not yield an early return below, MustAlias is not 981 // used further. 982 Result = ModRefInfo::ModRef; 983 break; 984 } 985 986 // No operand aliases, reset Must bit. Add below if at least one aliases 987 // and all aliases found are MustAlias. 988 if (isNoModRef(Result)) 989 IsMustAlias = false; 990 991 // Early return if we improved mod ref information 992 if (!isModAndRefSet(Result)) { 993 if (isNoModRef(Result)) 994 return ModRefInfo::NoModRef; 995 return IsMustAlias ? setMust(Result) : clearMust(Result); 996 } 997 } 998 999 // The semantics of memcpy intrinsics either exactly overlap or do not 1000 // overlap, i.e., source and destination of any given memcpy are either 1001 // no-alias or must-alias. 1002 if (auto *Inst = dyn_cast<AnyMemCpyInst>(Call)) { 1003 AliasResult SrcAA = 1004 getBestAAResults().alias(MemoryLocation::getForSource(Inst), Loc, AAQI); 1005 AliasResult DestAA = 1006 getBestAAResults().alias(MemoryLocation::getForDest(Inst), Loc, AAQI); 1007 // It's also possible for Loc to alias both src and dest, or neither. 1008 ModRefInfo rv = ModRefInfo::NoModRef; 1009 if (SrcAA != AliasResult::NoAlias) 1010 rv = setRef(rv); 1011 if (DestAA != AliasResult::NoAlias) 1012 rv = setMod(rv); 1013 return rv; 1014 } 1015 1016 // Guard intrinsics are marked as arbitrarily writing so that proper control 1017 // dependencies are maintained but they never mods any particular memory 1018 // location. 1019 // 1020 // *Unlike* assumes, guard intrinsics are modeled as reading memory since the 1021 // heap state at the point the guard is issued needs to be consistent in case 1022 // the guard invokes the "deopt" continuation. 1023 if (isIntrinsicCall(Call, Intrinsic::experimental_guard)) 1024 return ModRefInfo::Ref; 1025 // The same applies to deoptimize which is essentially a guard(false). 1026 if (isIntrinsicCall(Call, Intrinsic::experimental_deoptimize)) 1027 return ModRefInfo::Ref; 1028 1029 // Like assumes, invariant.start intrinsics were also marked as arbitrarily 1030 // writing so that proper control dependencies are maintained but they never 1031 // mod any particular memory location visible to the IR. 1032 // *Unlike* assumes (which are now modeled as NoModRef), invariant.start 1033 // intrinsic is now modeled as reading memory. This prevents hoisting the 1034 // invariant.start intrinsic over stores. Consider: 1035 // *ptr = 40; 1036 // *ptr = 50; 1037 // invariant_start(ptr) 1038 // int val = *ptr; 1039 // print(val); 1040 // 1041 // This cannot be transformed to: 1042 // 1043 // *ptr = 40; 1044 // invariant_start(ptr) 1045 // *ptr = 50; 1046 // int val = *ptr; 1047 // print(val); 1048 // 1049 // The transformation will cause the second store to be ignored (based on 1050 // rules of invariant.start) and print 40, while the first program always 1051 // prints 50. 1052 if (isIntrinsicCall(Call, Intrinsic::invariant_start)) 1053 return ModRefInfo::Ref; 1054 1055 // The AAResultBase base class has some smarts, lets use them. 1056 return AAResultBase::getModRefInfo(Call, Loc, AAQI); 1057 } 1058 1059 ModRefInfo BasicAAResult::getModRefInfo(const CallBase *Call1, 1060 const CallBase *Call2, 1061 AAQueryInfo &AAQI) { 1062 // Guard intrinsics are marked as arbitrarily writing so that proper control 1063 // dependencies are maintained but they never mods any particular memory 1064 // location. 1065 // 1066 // *Unlike* assumes, guard intrinsics are modeled as reading memory since the 1067 // heap state at the point the guard is issued needs to be consistent in case 1068 // the guard invokes the "deopt" continuation. 1069 1070 // NB! This function is *not* commutative, so we special case two 1071 // possibilities for guard intrinsics. 1072 1073 if (isIntrinsicCall(Call1, Intrinsic::experimental_guard)) 1074 return isModSet(createModRefInfo(getModRefBehavior(Call2))) 1075 ? ModRefInfo::Ref 1076 : ModRefInfo::NoModRef; 1077 1078 if (isIntrinsicCall(Call2, Intrinsic::experimental_guard)) 1079 return isModSet(createModRefInfo(getModRefBehavior(Call1))) 1080 ? ModRefInfo::Mod 1081 : ModRefInfo::NoModRef; 1082 1083 // The AAResultBase base class has some smarts, lets use them. 1084 return AAResultBase::getModRefInfo(Call1, Call2, AAQI); 1085 } 1086 1087 /// Return true if we know V to the base address of the corresponding memory 1088 /// object. This implies that any address less than V must be out of bounds 1089 /// for the underlying object. Note that just being isIdentifiedObject() is 1090 /// not enough - For example, a negative offset from a noalias argument or call 1091 /// can be inbounds w.r.t the actual underlying object. 1092 static bool isBaseOfObject(const Value *V) { 1093 // TODO: We can handle other cases here 1094 // 1) For GC languages, arguments to functions are often required to be 1095 // base pointers. 1096 // 2) Result of allocation routines are often base pointers. Leverage TLI. 1097 return (isa<AllocaInst>(V) || isa<GlobalVariable>(V)); 1098 } 1099 1100 /// Provides a bunch of ad-hoc rules to disambiguate a GEP instruction against 1101 /// another pointer. 1102 /// 1103 /// We know that V1 is a GEP, but we don't know anything about V2. 1104 /// UnderlyingV1 is getUnderlyingObject(GEP1), UnderlyingV2 is the same for 1105 /// V2. 1106 AliasResult BasicAAResult::aliasGEP( 1107 const GEPOperator *GEP1, LocationSize V1Size, 1108 const Value *V2, LocationSize V2Size, 1109 const Value *UnderlyingV1, const Value *UnderlyingV2, AAQueryInfo &AAQI) { 1110 if (!V1Size.hasValue() && !V2Size.hasValue()) { 1111 // TODO: This limitation exists for compile-time reasons. Relax it if we 1112 // can avoid exponential pathological cases. 1113 if (!isa<GEPOperator>(V2)) 1114 return AliasResult::MayAlias; 1115 1116 // If both accesses have unknown size, we can only check whether the base 1117 // objects don't alias. 1118 AliasResult BaseAlias = getBestAAResults().alias( 1119 MemoryLocation::getBeforeOrAfter(UnderlyingV1), 1120 MemoryLocation::getBeforeOrAfter(UnderlyingV2), AAQI); 1121 return BaseAlias == AliasResult::NoAlias ? AliasResult::NoAlias 1122 : AliasResult::MayAlias; 1123 } 1124 1125 DecomposedGEP DecompGEP1 = DecomposeGEPExpression(GEP1, DL, &AC, DT); 1126 DecomposedGEP DecompGEP2 = DecomposeGEPExpression(V2, DL, &AC, DT); 1127 1128 // Bail if we were not able to decompose anything. 1129 if (DecompGEP1.Base == GEP1 && DecompGEP2.Base == V2) 1130 return AliasResult::MayAlias; 1131 1132 // Subtract the GEP2 pointer from the GEP1 pointer to find out their 1133 // symbolic difference. 1134 subtractDecomposedGEPs(DecompGEP1, DecompGEP2); 1135 1136 // If an inbounds GEP would have to start from an out of bounds address 1137 // for the two to alias, then we can assume noalias. 1138 if (*DecompGEP1.InBounds && DecompGEP1.VarIndices.empty() && 1139 V2Size.hasValue() && DecompGEP1.Offset.sge(V2Size.getValue()) && 1140 isBaseOfObject(DecompGEP2.Base)) 1141 return AliasResult::NoAlias; 1142 1143 if (isa<GEPOperator>(V2)) { 1144 // Symmetric case to above. 1145 if (*DecompGEP2.InBounds && DecompGEP1.VarIndices.empty() && 1146 V1Size.hasValue() && DecompGEP1.Offset.sle(-V1Size.getValue()) && 1147 isBaseOfObject(DecompGEP1.Base)) 1148 return AliasResult::NoAlias; 1149 } 1150 1151 // For GEPs with identical offsets, we can preserve the size and AAInfo 1152 // when performing the alias check on the underlying objects. 1153 if (DecompGEP1.Offset == 0 && DecompGEP1.VarIndices.empty()) 1154 return getBestAAResults().alias(MemoryLocation(DecompGEP1.Base, V1Size), 1155 MemoryLocation(DecompGEP2.Base, V2Size), 1156 AAQI); 1157 1158 // Do the base pointers alias? 1159 AliasResult BaseAlias = getBestAAResults().alias( 1160 MemoryLocation::getBeforeOrAfter(DecompGEP1.Base), 1161 MemoryLocation::getBeforeOrAfter(DecompGEP2.Base), AAQI); 1162 1163 // If we get a No or May, then return it immediately, no amount of analysis 1164 // will improve this situation. 1165 if (BaseAlias != AliasResult::MustAlias) { 1166 assert(BaseAlias == AliasResult::NoAlias || 1167 BaseAlias == AliasResult::MayAlias); 1168 return BaseAlias; 1169 } 1170 1171 // If there is a constant difference between the pointers, but the difference 1172 // is less than the size of the associated memory object, then we know 1173 // that the objects are partially overlapping. If the difference is 1174 // greater, we know they do not overlap. 1175 if (DecompGEP1.VarIndices.empty()) { 1176 APInt &Off = DecompGEP1.Offset; 1177 1178 // Initialize for Off >= 0 (V2 <= GEP1) case. 1179 const Value *LeftPtr = V2; 1180 const Value *RightPtr = GEP1; 1181 LocationSize VLeftSize = V2Size; 1182 LocationSize VRightSize = V1Size; 1183 const bool Swapped = Off.isNegative(); 1184 1185 if (Swapped) { 1186 // Swap if we have the situation where: 1187 // + + 1188 // | BaseOffset | 1189 // ---------------->| 1190 // |-->V1Size |-------> V2Size 1191 // GEP1 V2 1192 std::swap(LeftPtr, RightPtr); 1193 std::swap(VLeftSize, VRightSize); 1194 Off = -Off; 1195 } 1196 1197 if (!VLeftSize.hasValue()) 1198 return AliasResult::MayAlias; 1199 1200 const uint64_t LSize = VLeftSize.getValue(); 1201 if (Off.ult(LSize)) { 1202 // Conservatively drop processing if a phi was visited and/or offset is 1203 // too big. 1204 AliasResult AR = AliasResult::PartialAlias; 1205 if (VRightSize.hasValue() && Off.ule(INT32_MAX) && 1206 (Off + VRightSize.getValue()).ule(LSize)) { 1207 // Memory referenced by right pointer is nested. Save the offset in 1208 // cache. Note that originally offset estimated as GEP1-V2, but 1209 // AliasResult contains the shift that represents GEP1+Offset=V2. 1210 AR.setOffset(-Off.getSExtValue()); 1211 AR.swap(Swapped); 1212 } 1213 return AR; 1214 } 1215 return AliasResult::NoAlias; 1216 } 1217 1218 // We need to know both acess sizes for all the following heuristics. 1219 if (!V1Size.hasValue() || !V2Size.hasValue()) 1220 return AliasResult::MayAlias; 1221 1222 APInt GCD; 1223 ConstantRange OffsetRange = ConstantRange(DecompGEP1.Offset); 1224 for (unsigned i = 0, e = DecompGEP1.VarIndices.size(); i != e; ++i) { 1225 const VariableGEPIndex &Index = DecompGEP1.VarIndices[i]; 1226 const APInt &Scale = Index.Scale; 1227 APInt ScaleForGCD = Scale; 1228 if (!Index.IsNSW) 1229 ScaleForGCD = APInt::getOneBitSet(Scale.getBitWidth(), 1230 Scale.countTrailingZeros()); 1231 1232 if (i == 0) 1233 GCD = ScaleForGCD.abs(); 1234 else 1235 GCD = APIntOps::GreatestCommonDivisor(GCD, ScaleForGCD.abs()); 1236 1237 ConstantRange CR = computeConstantRange(Index.Val.V, /* ForSigned */ false, 1238 true, &AC, Index.CxtI); 1239 KnownBits Known = 1240 computeKnownBits(Index.Val.V, DL, 0, &AC, Index.CxtI, DT); 1241 CR = CR.intersectWith( 1242 ConstantRange::fromKnownBits(Known, /* Signed */ true), 1243 ConstantRange::Signed); 1244 CR = Index.Val.evaluateWith(CR).sextOrTrunc(OffsetRange.getBitWidth()); 1245 1246 assert(OffsetRange.getBitWidth() == Scale.getBitWidth() && 1247 "Bit widths are normalized to MaxIndexSize"); 1248 if (Index.IsNSW) 1249 OffsetRange = OffsetRange.add(CR.smul_sat(ConstantRange(Scale))); 1250 else 1251 OffsetRange = OffsetRange.add(CR.smul_fast(ConstantRange(Scale))); 1252 } 1253 1254 // We now have accesses at two offsets from the same base: 1255 // 1. (...)*GCD + DecompGEP1.Offset with size V1Size 1256 // 2. 0 with size V2Size 1257 // Using arithmetic modulo GCD, the accesses are at 1258 // [ModOffset..ModOffset+V1Size) and [0..V2Size). If the first access fits 1259 // into the range [V2Size..GCD), then we know they cannot overlap. 1260 APInt ModOffset = DecompGEP1.Offset.srem(GCD); 1261 if (ModOffset.isNegative()) 1262 ModOffset += GCD; // We want mod, not rem. 1263 if (ModOffset.uge(V2Size.getValue()) && 1264 (GCD - ModOffset).uge(V1Size.getValue())) 1265 return AliasResult::NoAlias; 1266 1267 // Compute ranges of potentially accessed bytes for both accesses. If the 1268 // interseciton is empty, there can be no overlap. 1269 unsigned BW = OffsetRange.getBitWidth(); 1270 ConstantRange Range1 = OffsetRange.add( 1271 ConstantRange(APInt(BW, 0), APInt(BW, V1Size.getValue()))); 1272 ConstantRange Range2 = 1273 ConstantRange(APInt(BW, 0), APInt(BW, V2Size.getValue())); 1274 if (Range1.intersectWith(Range2).isEmptySet()) 1275 return AliasResult::NoAlias; 1276 1277 // Try to determine the range of values for VarIndex such that 1278 // VarIndex <= -MinAbsVarIndex || MinAbsVarIndex <= VarIndex. 1279 Optional<APInt> MinAbsVarIndex; 1280 if (DecompGEP1.VarIndices.size() == 1) { 1281 // VarIndex = Scale*V. 1282 const VariableGEPIndex &Var = DecompGEP1.VarIndices[0]; 1283 if (Var.Val.TruncBits == 0 && 1284 isKnownNonZero(Var.Val.V, DL, 0, &AC, Var.CxtI, DT)) { 1285 // If V != 0 then abs(VarIndex) >= abs(Scale). 1286 MinAbsVarIndex = Var.Scale.abs(); 1287 } 1288 } else if (DecompGEP1.VarIndices.size() == 2) { 1289 // VarIndex = Scale*V0 + (-Scale)*V1. 1290 // If V0 != V1 then abs(VarIndex) >= abs(Scale). 1291 // Check that VisitedPhiBBs is empty, to avoid reasoning about 1292 // inequality of values across loop iterations. 1293 const VariableGEPIndex &Var0 = DecompGEP1.VarIndices[0]; 1294 const VariableGEPIndex &Var1 = DecompGEP1.VarIndices[1]; 1295 if (Var0.Scale == -Var1.Scale && Var0.Val.TruncBits == 0 && 1296 Var0.Val.hasSameCastsAs(Var1.Val) && VisitedPhiBBs.empty() && 1297 isKnownNonEqual(Var0.Val.V, Var1.Val.V, DL, &AC, /* CxtI */ nullptr, 1298 DT)) 1299 MinAbsVarIndex = Var0.Scale.abs(); 1300 } 1301 1302 if (MinAbsVarIndex) { 1303 // The constant offset will have added at least +/-MinAbsVarIndex to it. 1304 APInt OffsetLo = DecompGEP1.Offset - *MinAbsVarIndex; 1305 APInt OffsetHi = DecompGEP1.Offset + *MinAbsVarIndex; 1306 // We know that Offset <= OffsetLo || Offset >= OffsetHi 1307 if (OffsetLo.isNegative() && (-OffsetLo).uge(V1Size.getValue()) && 1308 OffsetHi.isNonNegative() && OffsetHi.uge(V2Size.getValue())) 1309 return AliasResult::NoAlias; 1310 } 1311 1312 if (constantOffsetHeuristic(DecompGEP1, V1Size, V2Size, &AC, DT)) 1313 return AliasResult::NoAlias; 1314 1315 // Statically, we can see that the base objects are the same, but the 1316 // pointers have dynamic offsets which we can't resolve. And none of our 1317 // little tricks above worked. 1318 return AliasResult::MayAlias; 1319 } 1320 1321 static AliasResult MergeAliasResults(AliasResult A, AliasResult B) { 1322 // If the results agree, take it. 1323 if (A == B) 1324 return A; 1325 // A mix of PartialAlias and MustAlias is PartialAlias. 1326 if ((A == AliasResult::PartialAlias && B == AliasResult::MustAlias) || 1327 (B == AliasResult::PartialAlias && A == AliasResult::MustAlias)) 1328 return AliasResult::PartialAlias; 1329 // Otherwise, we don't know anything. 1330 return AliasResult::MayAlias; 1331 } 1332 1333 /// Provides a bunch of ad-hoc rules to disambiguate a Select instruction 1334 /// against another. 1335 AliasResult 1336 BasicAAResult::aliasSelect(const SelectInst *SI, LocationSize SISize, 1337 const Value *V2, LocationSize V2Size, 1338 AAQueryInfo &AAQI) { 1339 // If the values are Selects with the same condition, we can do a more precise 1340 // check: just check for aliases between the values on corresponding arms. 1341 if (const SelectInst *SI2 = dyn_cast<SelectInst>(V2)) 1342 if (SI->getCondition() == SI2->getCondition()) { 1343 AliasResult Alias = getBestAAResults().alias( 1344 MemoryLocation(SI->getTrueValue(), SISize), 1345 MemoryLocation(SI2->getTrueValue(), V2Size), AAQI); 1346 if (Alias == AliasResult::MayAlias) 1347 return AliasResult::MayAlias; 1348 AliasResult ThisAlias = getBestAAResults().alias( 1349 MemoryLocation(SI->getFalseValue(), SISize), 1350 MemoryLocation(SI2->getFalseValue(), V2Size), AAQI); 1351 return MergeAliasResults(ThisAlias, Alias); 1352 } 1353 1354 // If both arms of the Select node NoAlias or MustAlias V2, then returns 1355 // NoAlias / MustAlias. Otherwise, returns MayAlias. 1356 AliasResult Alias = getBestAAResults().alias( 1357 MemoryLocation(V2, V2Size), 1358 MemoryLocation(SI->getTrueValue(), SISize), AAQI); 1359 if (Alias == AliasResult::MayAlias) 1360 return AliasResult::MayAlias; 1361 1362 AliasResult ThisAlias = getBestAAResults().alias( 1363 MemoryLocation(V2, V2Size), 1364 MemoryLocation(SI->getFalseValue(), SISize), AAQI); 1365 return MergeAliasResults(ThisAlias, Alias); 1366 } 1367 1368 /// Provide a bunch of ad-hoc rules to disambiguate a PHI instruction against 1369 /// another. 1370 AliasResult BasicAAResult::aliasPHI(const PHINode *PN, LocationSize PNSize, 1371 const Value *V2, LocationSize V2Size, 1372 AAQueryInfo &AAQI) { 1373 if (!PN->getNumIncomingValues()) 1374 return AliasResult::NoAlias; 1375 // If the values are PHIs in the same block, we can do a more precise 1376 // as well as efficient check: just check for aliases between the values 1377 // on corresponding edges. 1378 if (const PHINode *PN2 = dyn_cast<PHINode>(V2)) 1379 if (PN2->getParent() == PN->getParent()) { 1380 Optional<AliasResult> Alias; 1381 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 1382 AliasResult ThisAlias = getBestAAResults().alias( 1383 MemoryLocation(PN->getIncomingValue(i), PNSize), 1384 MemoryLocation( 1385 PN2->getIncomingValueForBlock(PN->getIncomingBlock(i)), V2Size), 1386 AAQI); 1387 if (Alias) 1388 *Alias = MergeAliasResults(*Alias, ThisAlias); 1389 else 1390 Alias = ThisAlias; 1391 if (*Alias == AliasResult::MayAlias) 1392 break; 1393 } 1394 return *Alias; 1395 } 1396 1397 SmallVector<Value *, 4> V1Srcs; 1398 // If a phi operand recurses back to the phi, we can still determine NoAlias 1399 // if we don't alias the underlying objects of the other phi operands, as we 1400 // know that the recursive phi needs to be based on them in some way. 1401 bool isRecursive = false; 1402 auto CheckForRecPhi = [&](Value *PV) { 1403 if (!EnableRecPhiAnalysis) 1404 return false; 1405 if (getUnderlyingObject(PV) == PN) { 1406 isRecursive = true; 1407 return true; 1408 } 1409 return false; 1410 }; 1411 1412 if (PV) { 1413 // If we have PhiValues then use it to get the underlying phi values. 1414 const PhiValues::ValueSet &PhiValueSet = PV->getValuesForPhi(PN); 1415 // If we have more phi values than the search depth then return MayAlias 1416 // conservatively to avoid compile time explosion. The worst possible case 1417 // is if both sides are PHI nodes. In which case, this is O(m x n) time 1418 // where 'm' and 'n' are the number of PHI sources. 1419 if (PhiValueSet.size() > MaxLookupSearchDepth) 1420 return AliasResult::MayAlias; 1421 // Add the values to V1Srcs 1422 for (Value *PV1 : PhiValueSet) { 1423 if (CheckForRecPhi(PV1)) 1424 continue; 1425 V1Srcs.push_back(PV1); 1426 } 1427 } else { 1428 // If we don't have PhiInfo then just look at the operands of the phi itself 1429 // FIXME: Remove this once we can guarantee that we have PhiInfo always 1430 SmallPtrSet<Value *, 4> UniqueSrc; 1431 Value *OnePhi = nullptr; 1432 for (Value *PV1 : PN->incoming_values()) { 1433 if (isa<PHINode>(PV1)) { 1434 if (OnePhi && OnePhi != PV1) { 1435 // To control potential compile time explosion, we choose to be 1436 // conserviate when we have more than one Phi input. It is important 1437 // that we handle the single phi case as that lets us handle LCSSA 1438 // phi nodes and (combined with the recursive phi handling) simple 1439 // pointer induction variable patterns. 1440 return AliasResult::MayAlias; 1441 } 1442 OnePhi = PV1; 1443 } 1444 1445 if (CheckForRecPhi(PV1)) 1446 continue; 1447 1448 if (UniqueSrc.insert(PV1).second) 1449 V1Srcs.push_back(PV1); 1450 } 1451 1452 if (OnePhi && UniqueSrc.size() > 1) 1453 // Out of an abundance of caution, allow only the trivial lcssa and 1454 // recursive phi cases. 1455 return AliasResult::MayAlias; 1456 } 1457 1458 // If V1Srcs is empty then that means that the phi has no underlying non-phi 1459 // value. This should only be possible in blocks unreachable from the entry 1460 // block, but return MayAlias just in case. 1461 if (V1Srcs.empty()) 1462 return AliasResult::MayAlias; 1463 1464 // If this PHI node is recursive, indicate that the pointer may be moved 1465 // across iterations. We can only prove NoAlias if different underlying 1466 // objects are involved. 1467 if (isRecursive) 1468 PNSize = LocationSize::beforeOrAfterPointer(); 1469 1470 // In the recursive alias queries below, we may compare values from two 1471 // different loop iterations. Keep track of visited phi blocks, which will 1472 // be used when determining value equivalence. 1473 bool BlockInserted = VisitedPhiBBs.insert(PN->getParent()).second; 1474 auto _ = make_scope_exit([&]() { 1475 if (BlockInserted) 1476 VisitedPhiBBs.erase(PN->getParent()); 1477 }); 1478 1479 // If we inserted a block into VisitedPhiBBs, alias analysis results that 1480 // have been cached earlier may no longer be valid. Perform recursive queries 1481 // with a new AAQueryInfo. 1482 AAQueryInfo NewAAQI = AAQI.withEmptyCache(); 1483 AAQueryInfo *UseAAQI = BlockInserted ? &NewAAQI : &AAQI; 1484 1485 AliasResult Alias = getBestAAResults().alias( 1486 MemoryLocation(V2, V2Size), 1487 MemoryLocation(V1Srcs[0], PNSize), *UseAAQI); 1488 1489 // Early exit if the check of the first PHI source against V2 is MayAlias. 1490 // Other results are not possible. 1491 if (Alias == AliasResult::MayAlias) 1492 return AliasResult::MayAlias; 1493 // With recursive phis we cannot guarantee that MustAlias/PartialAlias will 1494 // remain valid to all elements and needs to conservatively return MayAlias. 1495 if (isRecursive && Alias != AliasResult::NoAlias) 1496 return AliasResult::MayAlias; 1497 1498 // If all sources of the PHI node NoAlias or MustAlias V2, then returns 1499 // NoAlias / MustAlias. Otherwise, returns MayAlias. 1500 for (unsigned i = 1, e = V1Srcs.size(); i != e; ++i) { 1501 Value *V = V1Srcs[i]; 1502 1503 AliasResult ThisAlias = getBestAAResults().alias( 1504 MemoryLocation(V2, V2Size), MemoryLocation(V, PNSize), *UseAAQI); 1505 Alias = MergeAliasResults(ThisAlias, Alias); 1506 if (Alias == AliasResult::MayAlias) 1507 break; 1508 } 1509 1510 return Alias; 1511 } 1512 1513 /// Provides a bunch of ad-hoc rules to disambiguate in common cases, such as 1514 /// array references. 1515 AliasResult BasicAAResult::aliasCheck(const Value *V1, LocationSize V1Size, 1516 const Value *V2, LocationSize V2Size, 1517 AAQueryInfo &AAQI) { 1518 // If either of the memory references is empty, it doesn't matter what the 1519 // pointer values are. 1520 if (V1Size.isZero() || V2Size.isZero()) 1521 return AliasResult::NoAlias; 1522 1523 // Strip off any casts if they exist. 1524 V1 = V1->stripPointerCastsForAliasAnalysis(); 1525 V2 = V2->stripPointerCastsForAliasAnalysis(); 1526 1527 // If V1 or V2 is undef, the result is NoAlias because we can always pick a 1528 // value for undef that aliases nothing in the program. 1529 if (isa<UndefValue>(V1) || isa<UndefValue>(V2)) 1530 return AliasResult::NoAlias; 1531 1532 // Are we checking for alias of the same value? 1533 // Because we look 'through' phi nodes, we could look at "Value" pointers from 1534 // different iterations. We must therefore make sure that this is not the 1535 // case. The function isValueEqualInPotentialCycles ensures that this cannot 1536 // happen by looking at the visited phi nodes and making sure they cannot 1537 // reach the value. 1538 if (isValueEqualInPotentialCycles(V1, V2)) 1539 return AliasResult::MustAlias; 1540 1541 if (!V1->getType()->isPointerTy() || !V2->getType()->isPointerTy()) 1542 return AliasResult::NoAlias; // Scalars cannot alias each other 1543 1544 // Figure out what objects these things are pointing to if we can. 1545 const Value *O1 = getUnderlyingObject(V1, MaxLookupSearchDepth); 1546 const Value *O2 = getUnderlyingObject(V2, MaxLookupSearchDepth); 1547 1548 // Null values in the default address space don't point to any object, so they 1549 // don't alias any other pointer. 1550 if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O1)) 1551 if (!NullPointerIsDefined(&F, CPN->getType()->getAddressSpace())) 1552 return AliasResult::NoAlias; 1553 if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O2)) 1554 if (!NullPointerIsDefined(&F, CPN->getType()->getAddressSpace())) 1555 return AliasResult::NoAlias; 1556 1557 if (O1 != O2) { 1558 // If V1/V2 point to two different objects, we know that we have no alias. 1559 if (isIdentifiedObject(O1) && isIdentifiedObject(O2)) 1560 return AliasResult::NoAlias; 1561 1562 // Constant pointers can't alias with non-const isIdentifiedObject objects. 1563 if ((isa<Constant>(O1) && isIdentifiedObject(O2) && !isa<Constant>(O2)) || 1564 (isa<Constant>(O2) && isIdentifiedObject(O1) && !isa<Constant>(O1))) 1565 return AliasResult::NoAlias; 1566 1567 // Function arguments can't alias with things that are known to be 1568 // unambigously identified at the function level. 1569 if ((isa<Argument>(O1) && isIdentifiedFunctionLocal(O2)) || 1570 (isa<Argument>(O2) && isIdentifiedFunctionLocal(O1))) 1571 return AliasResult::NoAlias; 1572 1573 // If one pointer is the result of a call/invoke or load and the other is a 1574 // non-escaping local object within the same function, then we know the 1575 // object couldn't escape to a point where the call could return it. 1576 // 1577 // Note that if the pointers are in different functions, there are a 1578 // variety of complications. A call with a nocapture argument may still 1579 // temporary store the nocapture argument's value in a temporary memory 1580 // location if that memory location doesn't escape. Or it may pass a 1581 // nocapture value to other functions as long as they don't capture it. 1582 if (isEscapeSource(O1) && 1583 AAQI.CI->isNotCapturedBeforeOrAt(O2, cast<Instruction>(O1))) 1584 return AliasResult::NoAlias; 1585 if (isEscapeSource(O2) && 1586 AAQI.CI->isNotCapturedBeforeOrAt(O1, cast<Instruction>(O2))) 1587 return AliasResult::NoAlias; 1588 } 1589 1590 // If the size of one access is larger than the entire object on the other 1591 // side, then we know such behavior is undefined and can assume no alias. 1592 bool NullIsValidLocation = NullPointerIsDefined(&F); 1593 if ((isObjectSmallerThan( 1594 O2, getMinimalExtentFrom(*V1, V1Size, DL, NullIsValidLocation), DL, 1595 TLI, NullIsValidLocation)) || 1596 (isObjectSmallerThan( 1597 O1, getMinimalExtentFrom(*V2, V2Size, DL, NullIsValidLocation), DL, 1598 TLI, NullIsValidLocation))) 1599 return AliasResult::NoAlias; 1600 1601 // If one the accesses may be before the accessed pointer, canonicalize this 1602 // by using unknown after-pointer sizes for both accesses. This is 1603 // equivalent, because regardless of which pointer is lower, one of them 1604 // will always came after the other, as long as the underlying objects aren't 1605 // disjoint. We do this so that the rest of BasicAA does not have to deal 1606 // with accesses before the base pointer, and to improve cache utilization by 1607 // merging equivalent states. 1608 if (V1Size.mayBeBeforePointer() || V2Size.mayBeBeforePointer()) { 1609 V1Size = LocationSize::afterPointer(); 1610 V2Size = LocationSize::afterPointer(); 1611 } 1612 1613 // FIXME: If this depth limit is hit, then we may cache sub-optimal results 1614 // for recursive queries. For this reason, this limit is chosen to be large 1615 // enough to be very rarely hit, while still being small enough to avoid 1616 // stack overflows. 1617 if (AAQI.Depth >= 512) 1618 return AliasResult::MayAlias; 1619 1620 // Check the cache before climbing up use-def chains. This also terminates 1621 // otherwise infinitely recursive queries. 1622 AAQueryInfo::LocPair Locs({V1, V1Size}, {V2, V2Size}); 1623 const bool Swapped = V1 > V2; 1624 if (Swapped) 1625 std::swap(Locs.first, Locs.second); 1626 const auto &Pair = AAQI.AliasCache.try_emplace( 1627 Locs, AAQueryInfo::CacheEntry{AliasResult::NoAlias, 0}); 1628 if (!Pair.second) { 1629 auto &Entry = Pair.first->second; 1630 if (!Entry.isDefinitive()) { 1631 // Remember that we used an assumption. 1632 ++Entry.NumAssumptionUses; 1633 ++AAQI.NumAssumptionUses; 1634 } 1635 // Cache contains sorted {V1,V2} pairs but we should return original order. 1636 auto Result = Entry.Result; 1637 Result.swap(Swapped); 1638 return Result; 1639 } 1640 1641 int OrigNumAssumptionUses = AAQI.NumAssumptionUses; 1642 unsigned OrigNumAssumptionBasedResults = AAQI.AssumptionBasedResults.size(); 1643 AliasResult Result = 1644 aliasCheckRecursive(V1, V1Size, V2, V2Size, AAQI, O1, O2); 1645 1646 auto It = AAQI.AliasCache.find(Locs); 1647 assert(It != AAQI.AliasCache.end() && "Must be in cache"); 1648 auto &Entry = It->second; 1649 1650 // Check whether a NoAlias assumption has been used, but disproven. 1651 bool AssumptionDisproven = 1652 Entry.NumAssumptionUses > 0 && Result != AliasResult::NoAlias; 1653 if (AssumptionDisproven) 1654 Result = AliasResult::MayAlias; 1655 1656 // This is a definitive result now, when considered as a root query. 1657 AAQI.NumAssumptionUses -= Entry.NumAssumptionUses; 1658 Entry.Result = Result; 1659 // Cache contains sorted {V1,V2} pairs. 1660 Entry.Result.swap(Swapped); 1661 Entry.NumAssumptionUses = -1; 1662 1663 // If the assumption has been disproven, remove any results that may have 1664 // been based on this assumption. Do this after the Entry updates above to 1665 // avoid iterator invalidation. 1666 if (AssumptionDisproven) 1667 while (AAQI.AssumptionBasedResults.size() > OrigNumAssumptionBasedResults) 1668 AAQI.AliasCache.erase(AAQI.AssumptionBasedResults.pop_back_val()); 1669 1670 // The result may still be based on assumptions higher up in the chain. 1671 // Remember it, so it can be purged from the cache later. 1672 if (OrigNumAssumptionUses != AAQI.NumAssumptionUses && 1673 Result != AliasResult::MayAlias) 1674 AAQI.AssumptionBasedResults.push_back(Locs); 1675 return Result; 1676 } 1677 1678 AliasResult BasicAAResult::aliasCheckRecursive( 1679 const Value *V1, LocationSize V1Size, 1680 const Value *V2, LocationSize V2Size, 1681 AAQueryInfo &AAQI, const Value *O1, const Value *O2) { 1682 if (const GEPOperator *GV1 = dyn_cast<GEPOperator>(V1)) { 1683 AliasResult Result = aliasGEP(GV1, V1Size, V2, V2Size, O1, O2, AAQI); 1684 if (Result != AliasResult::MayAlias) 1685 return Result; 1686 } else if (const GEPOperator *GV2 = dyn_cast<GEPOperator>(V2)) { 1687 AliasResult Result = aliasGEP(GV2, V2Size, V1, V1Size, O2, O1, AAQI); 1688 Result.swap(); 1689 if (Result != AliasResult::MayAlias) 1690 return Result; 1691 } 1692 1693 if (const PHINode *PN = dyn_cast<PHINode>(V1)) { 1694 AliasResult Result = aliasPHI(PN, V1Size, V2, V2Size, AAQI); 1695 if (Result != AliasResult::MayAlias) 1696 return Result; 1697 } else if (const PHINode *PN = dyn_cast<PHINode>(V2)) { 1698 AliasResult Result = aliasPHI(PN, V2Size, V1, V1Size, AAQI); 1699 Result.swap(); 1700 if (Result != AliasResult::MayAlias) 1701 return Result; 1702 } 1703 1704 if (const SelectInst *S1 = dyn_cast<SelectInst>(V1)) { 1705 AliasResult Result = aliasSelect(S1, V1Size, V2, V2Size, AAQI); 1706 if (Result != AliasResult::MayAlias) 1707 return Result; 1708 } else if (const SelectInst *S2 = dyn_cast<SelectInst>(V2)) { 1709 AliasResult Result = aliasSelect(S2, V2Size, V1, V1Size, AAQI); 1710 Result.swap(); 1711 if (Result != AliasResult::MayAlias) 1712 return Result; 1713 } 1714 1715 // If both pointers are pointing into the same object and one of them 1716 // accesses the entire object, then the accesses must overlap in some way. 1717 if (O1 == O2) { 1718 bool NullIsValidLocation = NullPointerIsDefined(&F); 1719 if (V1Size.isPrecise() && V2Size.isPrecise() && 1720 (isObjectSize(O1, V1Size.getValue(), DL, TLI, NullIsValidLocation) || 1721 isObjectSize(O2, V2Size.getValue(), DL, TLI, NullIsValidLocation))) 1722 return AliasResult::PartialAlias; 1723 } 1724 1725 return AliasResult::MayAlias; 1726 } 1727 1728 /// Check whether two Values can be considered equivalent. 1729 /// 1730 /// In addition to pointer equivalence of \p V1 and \p V2 this checks whether 1731 /// they can not be part of a cycle in the value graph by looking at all 1732 /// visited phi nodes an making sure that the phis cannot reach the value. We 1733 /// have to do this because we are looking through phi nodes (That is we say 1734 /// noalias(V, phi(VA, VB)) if noalias(V, VA) and noalias(V, VB). 1735 bool BasicAAResult::isValueEqualInPotentialCycles(const Value *V, 1736 const Value *V2) { 1737 if (V != V2) 1738 return false; 1739 1740 const Instruction *Inst = dyn_cast<Instruction>(V); 1741 if (!Inst) 1742 return true; 1743 1744 if (VisitedPhiBBs.empty()) 1745 return true; 1746 1747 if (VisitedPhiBBs.size() > MaxNumPhiBBsValueReachabilityCheck) 1748 return false; 1749 1750 // Make sure that the visited phis cannot reach the Value. This ensures that 1751 // the Values cannot come from different iterations of a potential cycle the 1752 // phi nodes could be involved in. 1753 for (auto *P : VisitedPhiBBs) 1754 if (isPotentiallyReachable(&P->front(), Inst, nullptr, DT)) 1755 return false; 1756 1757 return true; 1758 } 1759 1760 /// Computes the symbolic difference between two de-composed GEPs. 1761 void BasicAAResult::subtractDecomposedGEPs(DecomposedGEP &DestGEP, 1762 const DecomposedGEP &SrcGEP) { 1763 DestGEP.Offset -= SrcGEP.Offset; 1764 for (const VariableGEPIndex &Src : SrcGEP.VarIndices) { 1765 // Find V in Dest. This is N^2, but pointer indices almost never have more 1766 // than a few variable indexes. 1767 bool Found = false; 1768 for (auto I : enumerate(DestGEP.VarIndices)) { 1769 VariableGEPIndex &Dest = I.value(); 1770 if (!isValueEqualInPotentialCycles(Dest.Val.V, Src.Val.V) || 1771 !Dest.Val.hasSameCastsAs(Src.Val)) 1772 continue; 1773 1774 // If we found it, subtract off Scale V's from the entry in Dest. If it 1775 // goes to zero, remove the entry. 1776 if (Dest.Scale != Src.Scale) { 1777 Dest.Scale -= Src.Scale; 1778 Dest.IsNSW = false; 1779 } else { 1780 DestGEP.VarIndices.erase(DestGEP.VarIndices.begin() + I.index()); 1781 } 1782 Found = true; 1783 break; 1784 } 1785 1786 // If we didn't consume this entry, add it to the end of the Dest list. 1787 if (!Found) { 1788 VariableGEPIndex Entry = {Src.Val, -Src.Scale, Src.CxtI, Src.IsNSW}; 1789 DestGEP.VarIndices.push_back(Entry); 1790 } 1791 } 1792 } 1793 1794 bool BasicAAResult::constantOffsetHeuristic( 1795 const DecomposedGEP &GEP, LocationSize MaybeV1Size, 1796 LocationSize MaybeV2Size, AssumptionCache *AC, DominatorTree *DT) { 1797 if (GEP.VarIndices.size() != 2 || !MaybeV1Size.hasValue() || 1798 !MaybeV2Size.hasValue()) 1799 return false; 1800 1801 const uint64_t V1Size = MaybeV1Size.getValue(); 1802 const uint64_t V2Size = MaybeV2Size.getValue(); 1803 1804 const VariableGEPIndex &Var0 = GEP.VarIndices[0], &Var1 = GEP.VarIndices[1]; 1805 1806 if (Var0.Val.TruncBits != 0 || !Var0.Val.hasSameCastsAs(Var1.Val) || 1807 Var0.Scale != -Var1.Scale || 1808 Var0.Val.V->getType() != Var1.Val.V->getType()) 1809 return false; 1810 1811 // We'll strip off the Extensions of Var0 and Var1 and do another round 1812 // of GetLinearExpression decomposition. In the example above, if Var0 1813 // is zext(%x + 1) we should get V1 == %x and V1Offset == 1. 1814 1815 LinearExpression E0 = 1816 GetLinearExpression(CastedValue(Var0.Val.V), DL, 0, AC, DT); 1817 LinearExpression E1 = 1818 GetLinearExpression(CastedValue(Var1.Val.V), DL, 0, AC, DT); 1819 if (E0.Scale != E1.Scale || !E0.Val.hasSameCastsAs(E1.Val) || 1820 !isValueEqualInPotentialCycles(E0.Val.V, E1.Val.V)) 1821 return false; 1822 1823 // We have a hit - Var0 and Var1 only differ by a constant offset! 1824 1825 // If we've been sext'ed then zext'd the maximum difference between Var0 and 1826 // Var1 is possible to calculate, but we're just interested in the absolute 1827 // minimum difference between the two. The minimum distance may occur due to 1828 // wrapping; consider "add i3 %i, 5": if %i == 7 then 7 + 5 mod 8 == 4, and so 1829 // the minimum distance between %i and %i + 5 is 3. 1830 APInt MinDiff = E0.Offset - E1.Offset, Wrapped = -MinDiff; 1831 MinDiff = APIntOps::umin(MinDiff, Wrapped); 1832 APInt MinDiffBytes = 1833 MinDiff.zextOrTrunc(Var0.Scale.getBitWidth()) * Var0.Scale.abs(); 1834 1835 // We can't definitely say whether GEP1 is before or after V2 due to wrapping 1836 // arithmetic (i.e. for some values of GEP1 and V2 GEP1 < V2, and for other 1837 // values GEP1 > V2). We'll therefore only declare NoAlias if both V1Size and 1838 // V2Size can fit in the MinDiffBytes gap. 1839 return MinDiffBytes.uge(V1Size + GEP.Offset.abs()) && 1840 MinDiffBytes.uge(V2Size + GEP.Offset.abs()); 1841 } 1842 1843 //===----------------------------------------------------------------------===// 1844 // BasicAliasAnalysis Pass 1845 //===----------------------------------------------------------------------===// 1846 1847 AnalysisKey BasicAA::Key; 1848 1849 BasicAAResult BasicAA::run(Function &F, FunctionAnalysisManager &AM) { 1850 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F); 1851 auto &AC = AM.getResult<AssumptionAnalysis>(F); 1852 auto *DT = &AM.getResult<DominatorTreeAnalysis>(F); 1853 auto *PV = AM.getCachedResult<PhiValuesAnalysis>(F); 1854 return BasicAAResult(F.getParent()->getDataLayout(), F, TLI, AC, DT, PV); 1855 } 1856 1857 BasicAAWrapperPass::BasicAAWrapperPass() : FunctionPass(ID) { 1858 initializeBasicAAWrapperPassPass(*PassRegistry::getPassRegistry()); 1859 } 1860 1861 char BasicAAWrapperPass::ID = 0; 1862 1863 void BasicAAWrapperPass::anchor() {} 1864 1865 INITIALIZE_PASS_BEGIN(BasicAAWrapperPass, "basic-aa", 1866 "Basic Alias Analysis (stateless AA impl)", true, true) 1867 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 1868 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 1869 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 1870 INITIALIZE_PASS_DEPENDENCY(PhiValuesWrapperPass) 1871 INITIALIZE_PASS_END(BasicAAWrapperPass, "basic-aa", 1872 "Basic Alias Analysis (stateless AA impl)", true, true) 1873 1874 FunctionPass *llvm::createBasicAAWrapperPass() { 1875 return new BasicAAWrapperPass(); 1876 } 1877 1878 bool BasicAAWrapperPass::runOnFunction(Function &F) { 1879 auto &ACT = getAnalysis<AssumptionCacheTracker>(); 1880 auto &TLIWP = getAnalysis<TargetLibraryInfoWrapperPass>(); 1881 auto &DTWP = getAnalysis<DominatorTreeWrapperPass>(); 1882 auto *PVWP = getAnalysisIfAvailable<PhiValuesWrapperPass>(); 1883 1884 Result.reset(new BasicAAResult(F.getParent()->getDataLayout(), F, 1885 TLIWP.getTLI(F), ACT.getAssumptionCache(F), 1886 &DTWP.getDomTree(), 1887 PVWP ? &PVWP->getResult() : nullptr)); 1888 1889 return false; 1890 } 1891 1892 void BasicAAWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { 1893 AU.setPreservesAll(); 1894 AU.addRequiredTransitive<AssumptionCacheTracker>(); 1895 AU.addRequiredTransitive<DominatorTreeWrapperPass>(); 1896 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>(); 1897 AU.addUsedIfAvailable<PhiValuesWrapperPass>(); 1898 } 1899 1900 BasicAAResult llvm::createLegacyPMBasicAAResult(Pass &P, Function &F) { 1901 return BasicAAResult( 1902 F.getParent()->getDataLayout(), F, 1903 P.getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F), 1904 P.getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F)); 1905 } 1906