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