1 //===- MemoryDependenceAnalysis.cpp - Mem Deps Implementation -------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements an analysis that determines, for a given memory 11 // operation, what preceding memory operations it depends on. It builds on 12 // alias analysis information, and tries to provide a lazy, caching interface to 13 // a common kind of alias information query. 14 // 15 //===----------------------------------------------------------------------===// 16 17 #include "llvm/Analysis/MemoryDependenceAnalysis.h" 18 #include "llvm/ADT/DenseMap.h" 19 #include "llvm/ADT/STLExtras.h" 20 #include "llvm/ADT/SmallPtrSet.h" 21 #include "llvm/ADT/SmallVector.h" 22 #include "llvm/ADT/Statistic.h" 23 #include "llvm/Analysis/AliasAnalysis.h" 24 #include "llvm/Analysis/AssumptionCache.h" 25 #include "llvm/Analysis/MemoryBuiltins.h" 26 #include "llvm/Analysis/MemoryLocation.h" 27 #include "llvm/Analysis/OrderedBasicBlock.h" 28 #include "llvm/Analysis/PHITransAddr.h" 29 #include "llvm/Analysis/TargetLibraryInfo.h" 30 #include "llvm/Analysis/ValueTracking.h" 31 #include "llvm/IR/Attributes.h" 32 #include "llvm/IR/BasicBlock.h" 33 #include "llvm/IR/CallSite.h" 34 #include "llvm/IR/Constants.h" 35 #include "llvm/IR/DataLayout.h" 36 #include "llvm/IR/DerivedTypes.h" 37 #include "llvm/IR/Dominators.h" 38 #include "llvm/IR/Function.h" 39 #include "llvm/IR/InstrTypes.h" 40 #include "llvm/IR/Instruction.h" 41 #include "llvm/IR/Instructions.h" 42 #include "llvm/IR/IntrinsicInst.h" 43 #include "llvm/IR/LLVMContext.h" 44 #include "llvm/IR/Metadata.h" 45 #include "llvm/IR/Module.h" 46 #include "llvm/IR/PredIteratorCache.h" 47 #include "llvm/IR/Type.h" 48 #include "llvm/IR/Use.h" 49 #include "llvm/IR/User.h" 50 #include "llvm/IR/Value.h" 51 #include "llvm/Pass.h" 52 #include "llvm/Support/AtomicOrdering.h" 53 #include "llvm/Support/Casting.h" 54 #include "llvm/Support/CommandLine.h" 55 #include "llvm/Support/Compiler.h" 56 #include "llvm/Support/Debug.h" 57 #include "llvm/Support/MathExtras.h" 58 #include <algorithm> 59 #include <cassert> 60 #include <cstdint> 61 #include <iterator> 62 #include <utility> 63 64 using namespace llvm; 65 66 #define DEBUG_TYPE "memdep" 67 68 STATISTIC(NumCacheNonLocal, "Number of fully cached non-local responses"); 69 STATISTIC(NumCacheDirtyNonLocal, "Number of dirty cached non-local responses"); 70 STATISTIC(NumUncacheNonLocal, "Number of uncached non-local responses"); 71 72 STATISTIC(NumCacheNonLocalPtr, 73 "Number of fully cached non-local ptr responses"); 74 STATISTIC(NumCacheDirtyNonLocalPtr, 75 "Number of cached, but dirty, non-local ptr responses"); 76 STATISTIC(NumUncacheNonLocalPtr, "Number of uncached non-local ptr responses"); 77 STATISTIC(NumCacheCompleteNonLocalPtr, 78 "Number of block queries that were completely cached"); 79 80 // Limit for the number of instructions to scan in a block. 81 82 static cl::opt<unsigned> BlockScanLimit( 83 "memdep-block-scan-limit", cl::Hidden, cl::init(100), 84 cl::desc("The number of instructions to scan in a block in memory " 85 "dependency analysis (default = 100)")); 86 87 static cl::opt<unsigned> 88 BlockNumberLimit("memdep-block-number-limit", cl::Hidden, cl::init(1000), 89 cl::desc("The number of blocks to scan during memory " 90 "dependency analysis (default = 1000)")); 91 92 // Limit on the number of memdep results to process. 93 static const unsigned int NumResultsLimit = 100; 94 95 /// This is a helper function that removes Val from 'Inst's set in ReverseMap. 96 /// 97 /// If the set becomes empty, remove Inst's entry. 98 template <typename KeyTy> 99 static void 100 RemoveFromReverseMap(DenseMap<Instruction *, SmallPtrSet<KeyTy, 4>> &ReverseMap, 101 Instruction *Inst, KeyTy Val) { 102 typename DenseMap<Instruction *, SmallPtrSet<KeyTy, 4>>::iterator InstIt = 103 ReverseMap.find(Inst); 104 assert(InstIt != ReverseMap.end() && "Reverse map out of sync?"); 105 bool Found = InstIt->second.erase(Val); 106 assert(Found && "Invalid reverse map!"); 107 (void)Found; 108 if (InstIt->second.empty()) 109 ReverseMap.erase(InstIt); 110 } 111 112 /// If the given instruction references a specific memory location, fill in Loc 113 /// with the details, otherwise set Loc.Ptr to null. 114 /// 115 /// Returns a ModRefInfo value describing the general behavior of the 116 /// instruction. 117 static ModRefInfo GetLocation(const Instruction *Inst, MemoryLocation &Loc, 118 const TargetLibraryInfo &TLI) { 119 if (const LoadInst *LI = dyn_cast<LoadInst>(Inst)) { 120 if (LI->isUnordered()) { 121 Loc = MemoryLocation::get(LI); 122 return ModRefInfo::Ref; 123 } 124 if (LI->getOrdering() == AtomicOrdering::Monotonic) { 125 Loc = MemoryLocation::get(LI); 126 return ModRefInfo::ModRef; 127 } 128 Loc = MemoryLocation(); 129 return ModRefInfo::ModRef; 130 } 131 132 if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) { 133 if (SI->isUnordered()) { 134 Loc = MemoryLocation::get(SI); 135 return ModRefInfo::Mod; 136 } 137 if (SI->getOrdering() == AtomicOrdering::Monotonic) { 138 Loc = MemoryLocation::get(SI); 139 return ModRefInfo::ModRef; 140 } 141 Loc = MemoryLocation(); 142 return ModRefInfo::ModRef; 143 } 144 145 if (const VAArgInst *V = dyn_cast<VAArgInst>(Inst)) { 146 Loc = MemoryLocation::get(V); 147 return ModRefInfo::ModRef; 148 } 149 150 if (const CallInst *CI = isFreeCall(Inst, &TLI)) { 151 // calls to free() deallocate the entire structure 152 Loc = MemoryLocation(CI->getArgOperand(0)); 153 return ModRefInfo::Mod; 154 } 155 156 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) { 157 AAMDNodes AAInfo; 158 159 switch (II->getIntrinsicID()) { 160 case Intrinsic::lifetime_start: 161 case Intrinsic::lifetime_end: 162 case Intrinsic::invariant_start: 163 II->getAAMetadata(AAInfo); 164 Loc = MemoryLocation( 165 II->getArgOperand(1), 166 cast<ConstantInt>(II->getArgOperand(0))->getZExtValue(), AAInfo); 167 // These intrinsics don't really modify the memory, but returning Mod 168 // will allow them to be handled conservatively. 169 return ModRefInfo::Mod; 170 case Intrinsic::invariant_end: 171 II->getAAMetadata(AAInfo); 172 Loc = MemoryLocation( 173 II->getArgOperand(2), 174 cast<ConstantInt>(II->getArgOperand(1))->getZExtValue(), AAInfo); 175 // These intrinsics don't really modify the memory, but returning Mod 176 // will allow them to be handled conservatively. 177 return ModRefInfo::Mod; 178 default: 179 break; 180 } 181 } 182 183 // Otherwise, just do the coarse-grained thing that always works. 184 if (Inst->mayWriteToMemory()) 185 return ModRefInfo::ModRef; 186 if (Inst->mayReadFromMemory()) 187 return ModRefInfo::Ref; 188 return ModRefInfo::NoModRef; 189 } 190 191 /// Private helper for finding the local dependencies of a call site. 192 MemDepResult MemoryDependenceResults::getCallSiteDependencyFrom( 193 CallSite CS, bool isReadOnlyCall, BasicBlock::iterator ScanIt, 194 BasicBlock *BB) { 195 unsigned Limit = BlockScanLimit; 196 197 // Walk backwards through the block, looking for dependencies. 198 while (ScanIt != BB->begin()) { 199 Instruction *Inst = &*--ScanIt; 200 // Debug intrinsics don't cause dependences and should not affect Limit 201 if (isa<DbgInfoIntrinsic>(Inst)) 202 continue; 203 204 // Limit the amount of scanning we do so we don't end up with quadratic 205 // running time on extreme testcases. 206 --Limit; 207 if (!Limit) 208 return MemDepResult::getUnknown(); 209 210 // If this inst is a memory op, get the pointer it accessed 211 MemoryLocation Loc; 212 ModRefInfo MR = GetLocation(Inst, Loc, TLI); 213 if (Loc.Ptr) { 214 // A simple instruction. 215 if (isModOrRefSet(AA.getModRefInfo(CS, Loc))) 216 return MemDepResult::getClobber(Inst); 217 continue; 218 } 219 220 if (auto InstCS = CallSite(Inst)) { 221 // If these two calls do not interfere, look past it. 222 if (isNoModRef(AA.getModRefInfo(CS, InstCS))) { 223 // If the two calls are the same, return InstCS as a Def, so that 224 // CS can be found redundant and eliminated. 225 if (isReadOnlyCall && !isModSet(MR) && 226 CS.getInstruction()->isIdenticalToWhenDefined(Inst)) 227 return MemDepResult::getDef(Inst); 228 229 // Otherwise if the two calls don't interact (e.g. InstCS is readnone) 230 // keep scanning. 231 continue; 232 } else 233 return MemDepResult::getClobber(Inst); 234 } 235 236 // If we could not obtain a pointer for the instruction and the instruction 237 // touches memory then assume that this is a dependency. 238 if (isModOrRefSet(MR)) 239 return MemDepResult::getClobber(Inst); 240 } 241 242 // No dependence found. If this is the entry block of the function, it is 243 // unknown, otherwise it is non-local. 244 if (BB != &BB->getParent()->getEntryBlock()) 245 return MemDepResult::getNonLocal(); 246 return MemDepResult::getNonFuncLocal(); 247 } 248 249 unsigned MemoryDependenceResults::getLoadLoadClobberFullWidthSize( 250 const Value *MemLocBase, int64_t MemLocOffs, unsigned MemLocSize, 251 const LoadInst *LI) { 252 // We can only extend simple integer loads. 253 if (!isa<IntegerType>(LI->getType()) || !LI->isSimple()) 254 return 0; 255 256 // Load widening is hostile to ThreadSanitizer: it may cause false positives 257 // or make the reports more cryptic (access sizes are wrong). 258 if (LI->getParent()->getParent()->hasFnAttribute(Attribute::SanitizeThread)) 259 return 0; 260 261 const DataLayout &DL = LI->getModule()->getDataLayout(); 262 263 // Get the base of this load. 264 int64_t LIOffs = 0; 265 const Value *LIBase = 266 GetPointerBaseWithConstantOffset(LI->getPointerOperand(), LIOffs, DL); 267 268 // If the two pointers are not based on the same pointer, we can't tell that 269 // they are related. 270 if (LIBase != MemLocBase) 271 return 0; 272 273 // Okay, the two values are based on the same pointer, but returned as 274 // no-alias. This happens when we have things like two byte loads at "P+1" 275 // and "P+3". Check to see if increasing the size of the "LI" load up to its 276 // alignment (or the largest native integer type) will allow us to load all 277 // the bits required by MemLoc. 278 279 // If MemLoc is before LI, then no widening of LI will help us out. 280 if (MemLocOffs < LIOffs) 281 return 0; 282 283 // Get the alignment of the load in bytes. We assume that it is safe to load 284 // any legal integer up to this size without a problem. For example, if we're 285 // looking at an i8 load on x86-32 that is known 1024 byte aligned, we can 286 // widen it up to an i32 load. If it is known 2-byte aligned, we can widen it 287 // to i16. 288 unsigned LoadAlign = LI->getAlignment(); 289 290 int64_t MemLocEnd = MemLocOffs + MemLocSize; 291 292 // If no amount of rounding up will let MemLoc fit into LI, then bail out. 293 if (LIOffs + LoadAlign < MemLocEnd) 294 return 0; 295 296 // This is the size of the load to try. Start with the next larger power of 297 // two. 298 unsigned NewLoadByteSize = LI->getType()->getPrimitiveSizeInBits() / 8U; 299 NewLoadByteSize = NextPowerOf2(NewLoadByteSize); 300 301 while (true) { 302 // If this load size is bigger than our known alignment or would not fit 303 // into a native integer register, then we fail. 304 if (NewLoadByteSize > LoadAlign || 305 !DL.fitsInLegalInteger(NewLoadByteSize * 8)) 306 return 0; 307 308 if (LIOffs + NewLoadByteSize > MemLocEnd && 309 (LI->getParent()->getParent()->hasFnAttribute( 310 Attribute::SanitizeAddress) || 311 LI->getParent()->getParent()->hasFnAttribute( 312 Attribute::SanitizeHWAddress))) 313 // We will be reading past the location accessed by the original program. 314 // While this is safe in a regular build, Address Safety analysis tools 315 // may start reporting false warnings. So, don't do widening. 316 return 0; 317 318 // If a load of this width would include all of MemLoc, then we succeed. 319 if (LIOffs + NewLoadByteSize >= MemLocEnd) 320 return NewLoadByteSize; 321 322 NewLoadByteSize <<= 1; 323 } 324 } 325 326 static bool isVolatile(Instruction *Inst) { 327 if (auto *LI = dyn_cast<LoadInst>(Inst)) 328 return LI->isVolatile(); 329 if (auto *SI = dyn_cast<StoreInst>(Inst)) 330 return SI->isVolatile(); 331 if (auto *AI = dyn_cast<AtomicCmpXchgInst>(Inst)) 332 return AI->isVolatile(); 333 return false; 334 } 335 336 MemDepResult MemoryDependenceResults::getPointerDependencyFrom( 337 const MemoryLocation &MemLoc, bool isLoad, BasicBlock::iterator ScanIt, 338 BasicBlock *BB, Instruction *QueryInst, unsigned *Limit) { 339 MemDepResult InvariantGroupDependency = MemDepResult::getUnknown(); 340 if (QueryInst != nullptr) { 341 if (auto *LI = dyn_cast<LoadInst>(QueryInst)) { 342 InvariantGroupDependency = getInvariantGroupPointerDependency(LI, BB); 343 344 if (InvariantGroupDependency.isDef()) 345 return InvariantGroupDependency; 346 } 347 } 348 MemDepResult SimpleDep = getSimplePointerDependencyFrom( 349 MemLoc, isLoad, ScanIt, BB, QueryInst, Limit); 350 if (SimpleDep.isDef()) 351 return SimpleDep; 352 // Non-local invariant group dependency indicates there is non local Def 353 // (it only returns nonLocal if it finds nonLocal def), which is better than 354 // local clobber and everything else. 355 if (InvariantGroupDependency.isNonLocal()) 356 return InvariantGroupDependency; 357 358 assert(InvariantGroupDependency.isUnknown() && 359 "InvariantGroupDependency should be only unknown at this point"); 360 return SimpleDep; 361 } 362 363 MemDepResult 364 MemoryDependenceResults::getInvariantGroupPointerDependency(LoadInst *LI, 365 BasicBlock *BB) { 366 auto *InvariantGroupMD = LI->getMetadata(LLVMContext::MD_invariant_group); 367 if (!InvariantGroupMD) 368 return MemDepResult::getUnknown(); 369 370 // Take the ptr operand after all casts and geps 0. This way we can search 371 // cast graph down only. 372 Value *LoadOperand = LI->getPointerOperand()->stripPointerCasts(); 373 374 // It's is not safe to walk the use list of global value, because function 375 // passes aren't allowed to look outside their functions. 376 // FIXME: this could be fixed by filtering instructions from outside 377 // of current function. 378 if (isa<GlobalValue>(LoadOperand)) 379 return MemDepResult::getUnknown(); 380 381 // Queue to process all pointers that are equivalent to load operand. 382 SmallVector<const Value *, 8> LoadOperandsQueue; 383 LoadOperandsQueue.push_back(LoadOperand); 384 385 Instruction *ClosestDependency = nullptr; 386 // Order of instructions in uses list is unpredictible. In order to always 387 // get the same result, we will look for the closest dominance. 388 auto GetClosestDependency = [this](Instruction *Best, Instruction *Other) { 389 assert(Other && "Must call it with not null instruction"); 390 if (Best == nullptr || DT.dominates(Best, Other)) 391 return Other; 392 return Best; 393 }; 394 395 // FIXME: This loop is O(N^2) because dominates can be O(n) and in worst case 396 // we will see all the instructions. This should be fixed in MSSA. 397 while (!LoadOperandsQueue.empty()) { 398 const Value *Ptr = LoadOperandsQueue.pop_back_val(); 399 assert(Ptr && !isa<GlobalValue>(Ptr) && 400 "Null or GlobalValue should not be inserted"); 401 402 for (const Use &Us : Ptr->uses()) { 403 auto *U = dyn_cast<Instruction>(Us.getUser()); 404 if (!U || U == LI || !DT.dominates(U, LI)) 405 continue; 406 407 // Bitcast or gep with zeros are using Ptr. Add to queue to check it's 408 // users. U = bitcast Ptr 409 if (isa<BitCastInst>(U)) { 410 LoadOperandsQueue.push_back(U); 411 continue; 412 } 413 // Gep with zeros is equivalent to bitcast. 414 // FIXME: we are not sure if some bitcast should be canonicalized to gep 0 415 // or gep 0 to bitcast because of SROA, so there are 2 forms. When 416 // typeless pointers will be ready then both cases will be gone 417 // (and this BFS also won't be needed). 418 if (auto *GEP = dyn_cast<GetElementPtrInst>(U)) 419 if (GEP->hasAllZeroIndices()) { 420 LoadOperandsQueue.push_back(U); 421 continue; 422 } 423 424 // If we hit load/store with the same invariant.group metadata (and the 425 // same pointer operand) we can assume that value pointed by pointer 426 // operand didn't change. 427 if ((isa<LoadInst>(U) || isa<StoreInst>(U)) && 428 U->getMetadata(LLVMContext::MD_invariant_group) == InvariantGroupMD) 429 ClosestDependency = GetClosestDependency(ClosestDependency, U); 430 } 431 } 432 433 if (!ClosestDependency) 434 return MemDepResult::getUnknown(); 435 if (ClosestDependency->getParent() == BB) 436 return MemDepResult::getDef(ClosestDependency); 437 // Def(U) can't be returned here because it is non-local. If local 438 // dependency won't be found then return nonLocal counting that the 439 // user will call getNonLocalPointerDependency, which will return cached 440 // result. 441 NonLocalDefsCache.try_emplace( 442 LI, NonLocalDepResult(ClosestDependency->getParent(), 443 MemDepResult::getDef(ClosestDependency), nullptr)); 444 return MemDepResult::getNonLocal(); 445 } 446 447 MemDepResult MemoryDependenceResults::getSimplePointerDependencyFrom( 448 const MemoryLocation &MemLoc, bool isLoad, BasicBlock::iterator ScanIt, 449 BasicBlock *BB, Instruction *QueryInst, unsigned *Limit) { 450 bool isInvariantLoad = false; 451 452 if (!Limit) { 453 unsigned DefaultLimit = BlockScanLimit; 454 return getSimplePointerDependencyFrom(MemLoc, isLoad, ScanIt, BB, QueryInst, 455 &DefaultLimit); 456 } 457 458 // We must be careful with atomic accesses, as they may allow another thread 459 // to touch this location, clobbering it. We are conservative: if the 460 // QueryInst is not a simple (non-atomic) memory access, we automatically 461 // return getClobber. 462 // If it is simple, we know based on the results of 463 // "Compiler testing via a theory of sound optimisations in the C11/C++11 464 // memory model" in PLDI 2013, that a non-atomic location can only be 465 // clobbered between a pair of a release and an acquire action, with no 466 // access to the location in between. 467 // Here is an example for giving the general intuition behind this rule. 468 // In the following code: 469 // store x 0; 470 // release action; [1] 471 // acquire action; [4] 472 // %val = load x; 473 // It is unsafe to replace %val by 0 because another thread may be running: 474 // acquire action; [2] 475 // store x 42; 476 // release action; [3] 477 // with synchronization from 1 to 2 and from 3 to 4, resulting in %val 478 // being 42. A key property of this program however is that if either 479 // 1 or 4 were missing, there would be a race between the store of 42 480 // either the store of 0 or the load (making the whole program racy). 481 // The paper mentioned above shows that the same property is respected 482 // by every program that can detect any optimization of that kind: either 483 // it is racy (undefined) or there is a release followed by an acquire 484 // between the pair of accesses under consideration. 485 486 // If the load is invariant, we "know" that it doesn't alias *any* write. We 487 // do want to respect mustalias results since defs are useful for value 488 // forwarding, but any mayalias write can be assumed to be noalias. 489 // Arguably, this logic should be pushed inside AliasAnalysis itself. 490 if (isLoad && QueryInst) { 491 LoadInst *LI = dyn_cast<LoadInst>(QueryInst); 492 if (LI && LI->getMetadata(LLVMContext::MD_invariant_load) != nullptr) 493 isInvariantLoad = true; 494 } 495 496 const DataLayout &DL = BB->getModule()->getDataLayout(); 497 498 // Create a numbered basic block to lazily compute and cache instruction 499 // positions inside a BB. This is used to provide fast queries for relative 500 // position between two instructions in a BB and can be used by 501 // AliasAnalysis::callCapturesBefore. 502 OrderedBasicBlock OBB(BB); 503 504 // Return "true" if and only if the instruction I is either a non-simple 505 // load or a non-simple store. 506 auto isNonSimpleLoadOrStore = [](Instruction *I) -> bool { 507 if (auto *LI = dyn_cast<LoadInst>(I)) 508 return !LI->isSimple(); 509 if (auto *SI = dyn_cast<StoreInst>(I)) 510 return !SI->isSimple(); 511 return false; 512 }; 513 514 // Return "true" if I is not a load and not a store, but it does access 515 // memory. 516 auto isOtherMemAccess = [](Instruction *I) -> bool { 517 return !isa<LoadInst>(I) && !isa<StoreInst>(I) && I->mayReadOrWriteMemory(); 518 }; 519 520 // Walk backwards through the basic block, looking for dependencies. 521 while (ScanIt != BB->begin()) { 522 Instruction *Inst = &*--ScanIt; 523 524 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) 525 // Debug intrinsics don't (and can't) cause dependencies. 526 if (isa<DbgInfoIntrinsic>(II)) 527 continue; 528 529 // Limit the amount of scanning we do so we don't end up with quadratic 530 // running time on extreme testcases. 531 --*Limit; 532 if (!*Limit) 533 return MemDepResult::getUnknown(); 534 535 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) { 536 // If we reach a lifetime begin or end marker, then the query ends here 537 // because the value is undefined. 538 if (II->getIntrinsicID() == Intrinsic::lifetime_start) { 539 // FIXME: This only considers queries directly on the invariant-tagged 540 // pointer, not on query pointers that are indexed off of them. It'd 541 // be nice to handle that at some point (the right approach is to use 542 // GetPointerBaseWithConstantOffset). 543 if (AA.isMustAlias(MemoryLocation(II->getArgOperand(1)), MemLoc)) 544 return MemDepResult::getDef(II); 545 continue; 546 } 547 } 548 549 // Values depend on loads if the pointers are must aliased. This means 550 // that a load depends on another must aliased load from the same value. 551 // One exception is atomic loads: a value can depend on an atomic load that 552 // it does not alias with when this atomic load indicates that another 553 // thread may be accessing the location. 554 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) { 555 // While volatile access cannot be eliminated, they do not have to clobber 556 // non-aliasing locations, as normal accesses, for example, can be safely 557 // reordered with volatile accesses. 558 if (LI->isVolatile()) { 559 if (!QueryInst) 560 // Original QueryInst *may* be volatile 561 return MemDepResult::getClobber(LI); 562 if (isVolatile(QueryInst)) 563 // Ordering required if QueryInst is itself volatile 564 return MemDepResult::getClobber(LI); 565 // Otherwise, volatile doesn't imply any special ordering 566 } 567 568 // Atomic loads have complications involved. 569 // A Monotonic (or higher) load is OK if the query inst is itself not 570 // atomic. 571 // FIXME: This is overly conservative. 572 if (LI->isAtomic() && isStrongerThanUnordered(LI->getOrdering())) { 573 if (!QueryInst || isNonSimpleLoadOrStore(QueryInst) || 574 isOtherMemAccess(QueryInst)) 575 return MemDepResult::getClobber(LI); 576 if (LI->getOrdering() != AtomicOrdering::Monotonic) 577 return MemDepResult::getClobber(LI); 578 } 579 580 MemoryLocation LoadLoc = MemoryLocation::get(LI); 581 582 // If we found a pointer, check if it could be the same as our pointer. 583 AliasResult R = AA.alias(LoadLoc, MemLoc); 584 585 if (isLoad) { 586 if (R == NoAlias) 587 continue; 588 589 // Must aliased loads are defs of each other. 590 if (R == MustAlias) 591 return MemDepResult::getDef(Inst); 592 593 #if 0 // FIXME: Temporarily disabled. GVN is cleverly rewriting loads 594 // in terms of clobbering loads, but since it does this by looking 595 // at the clobbering load directly, it doesn't know about any 596 // phi translation that may have happened along the way. 597 598 // If we have a partial alias, then return this as a clobber for the 599 // client to handle. 600 if (R == PartialAlias) 601 return MemDepResult::getClobber(Inst); 602 #endif 603 604 // Random may-alias loads don't depend on each other without a 605 // dependence. 606 continue; 607 } 608 609 // Stores don't depend on other no-aliased accesses. 610 if (R == NoAlias) 611 continue; 612 613 // Stores don't alias loads from read-only memory. 614 if (AA.pointsToConstantMemory(LoadLoc)) 615 continue; 616 617 // Stores depend on may/must aliased loads. 618 return MemDepResult::getDef(Inst); 619 } 620 621 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) { 622 // Atomic stores have complications involved. 623 // A Monotonic store is OK if the query inst is itself not atomic. 624 // FIXME: This is overly conservative. 625 if (!SI->isUnordered() && SI->isAtomic()) { 626 if (!QueryInst || isNonSimpleLoadOrStore(QueryInst) || 627 isOtherMemAccess(QueryInst)) 628 return MemDepResult::getClobber(SI); 629 if (SI->getOrdering() != AtomicOrdering::Monotonic) 630 return MemDepResult::getClobber(SI); 631 } 632 633 // FIXME: this is overly conservative. 634 // While volatile access cannot be eliminated, they do not have to clobber 635 // non-aliasing locations, as normal accesses can for example be reordered 636 // with volatile accesses. 637 if (SI->isVolatile()) 638 if (!QueryInst || isNonSimpleLoadOrStore(QueryInst) || 639 isOtherMemAccess(QueryInst)) 640 return MemDepResult::getClobber(SI); 641 642 // If alias analysis can tell that this store is guaranteed to not modify 643 // the query pointer, ignore it. Use getModRefInfo to handle cases where 644 // the query pointer points to constant memory etc. 645 if (!isModOrRefSet(AA.getModRefInfo(SI, MemLoc))) 646 continue; 647 648 // Ok, this store might clobber the query pointer. Check to see if it is 649 // a must alias: in this case, we want to return this as a def. 650 // FIXME: Use ModRefInfo::Must bit from getModRefInfo call above. 651 MemoryLocation StoreLoc = MemoryLocation::get(SI); 652 653 // If we found a pointer, check if it could be the same as our pointer. 654 AliasResult R = AA.alias(StoreLoc, MemLoc); 655 656 if (R == NoAlias) 657 continue; 658 if (R == MustAlias) 659 return MemDepResult::getDef(Inst); 660 if (isInvariantLoad) 661 continue; 662 return MemDepResult::getClobber(Inst); 663 } 664 665 // If this is an allocation, and if we know that the accessed pointer is to 666 // the allocation, return Def. This means that there is no dependence and 667 // the access can be optimized based on that. For example, a load could 668 // turn into undef. Note that we can bypass the allocation itself when 669 // looking for a clobber in many cases; that's an alias property and is 670 // handled by BasicAA. 671 if (isa<AllocaInst>(Inst) || isNoAliasFn(Inst, &TLI)) { 672 const Value *AccessPtr = GetUnderlyingObject(MemLoc.Ptr, DL); 673 if (AccessPtr == Inst || AA.isMustAlias(Inst, AccessPtr)) 674 return MemDepResult::getDef(Inst); 675 } 676 677 if (isInvariantLoad) 678 continue; 679 680 // A release fence requires that all stores complete before it, but does 681 // not prevent the reordering of following loads or stores 'before' the 682 // fence. As a result, we look past it when finding a dependency for 683 // loads. DSE uses this to find preceeding stores to delete and thus we 684 // can't bypass the fence if the query instruction is a store. 685 if (FenceInst *FI = dyn_cast<FenceInst>(Inst)) 686 if (isLoad && FI->getOrdering() == AtomicOrdering::Release) 687 continue; 688 689 // See if this instruction (e.g. a call or vaarg) mod/ref's the pointer. 690 ModRefInfo MR = AA.getModRefInfo(Inst, MemLoc); 691 // If necessary, perform additional analysis. 692 if (isModAndRefSet(MR)) 693 MR = AA.callCapturesBefore(Inst, MemLoc, &DT, &OBB); 694 switch (clearMust(MR)) { 695 case ModRefInfo::NoModRef: 696 // If the call has no effect on the queried pointer, just ignore it. 697 continue; 698 case ModRefInfo::Mod: 699 return MemDepResult::getClobber(Inst); 700 case ModRefInfo::Ref: 701 // If the call is known to never store to the pointer, and if this is a 702 // load query, we can safely ignore it (scan past it). 703 if (isLoad) 704 continue; 705 LLVM_FALLTHROUGH; 706 default: 707 // Otherwise, there is a potential dependence. Return a clobber. 708 return MemDepResult::getClobber(Inst); 709 } 710 } 711 712 // No dependence found. If this is the entry block of the function, it is 713 // unknown, otherwise it is non-local. 714 if (BB != &BB->getParent()->getEntryBlock()) 715 return MemDepResult::getNonLocal(); 716 return MemDepResult::getNonFuncLocal(); 717 } 718 719 MemDepResult MemoryDependenceResults::getDependency(Instruction *QueryInst) { 720 Instruction *ScanPos = QueryInst; 721 722 // Check for a cached result 723 MemDepResult &LocalCache = LocalDeps[QueryInst]; 724 725 // If the cached entry is non-dirty, just return it. Note that this depends 726 // on MemDepResult's default constructing to 'dirty'. 727 if (!LocalCache.isDirty()) 728 return LocalCache; 729 730 // Otherwise, if we have a dirty entry, we know we can start the scan at that 731 // instruction, which may save us some work. 732 if (Instruction *Inst = LocalCache.getInst()) { 733 ScanPos = Inst; 734 735 RemoveFromReverseMap(ReverseLocalDeps, Inst, QueryInst); 736 } 737 738 BasicBlock *QueryParent = QueryInst->getParent(); 739 740 // Do the scan. 741 if (BasicBlock::iterator(QueryInst) == QueryParent->begin()) { 742 // No dependence found. If this is the entry block of the function, it is 743 // unknown, otherwise it is non-local. 744 if (QueryParent != &QueryParent->getParent()->getEntryBlock()) 745 LocalCache = MemDepResult::getNonLocal(); 746 else 747 LocalCache = MemDepResult::getNonFuncLocal(); 748 } else { 749 MemoryLocation MemLoc; 750 ModRefInfo MR = GetLocation(QueryInst, MemLoc, TLI); 751 if (MemLoc.Ptr) { 752 // If we can do a pointer scan, make it happen. 753 bool isLoad = !isModSet(MR); 754 if (auto *II = dyn_cast<IntrinsicInst>(QueryInst)) 755 isLoad |= II->getIntrinsicID() == Intrinsic::lifetime_start; 756 757 LocalCache = getPointerDependencyFrom( 758 MemLoc, isLoad, ScanPos->getIterator(), QueryParent, QueryInst); 759 } else if (isa<CallInst>(QueryInst) || isa<InvokeInst>(QueryInst)) { 760 CallSite QueryCS(QueryInst); 761 bool isReadOnly = AA.onlyReadsMemory(QueryCS); 762 LocalCache = getCallSiteDependencyFrom( 763 QueryCS, isReadOnly, ScanPos->getIterator(), QueryParent); 764 } else 765 // Non-memory instruction. 766 LocalCache = MemDepResult::getUnknown(); 767 } 768 769 // Remember the result! 770 if (Instruction *I = LocalCache.getInst()) 771 ReverseLocalDeps[I].insert(QueryInst); 772 773 return LocalCache; 774 } 775 776 #ifndef NDEBUG 777 /// This method is used when -debug is specified to verify that cache arrays 778 /// are properly kept sorted. 779 static void AssertSorted(MemoryDependenceResults::NonLocalDepInfo &Cache, 780 int Count = -1) { 781 if (Count == -1) 782 Count = Cache.size(); 783 assert(std::is_sorted(Cache.begin(), Cache.begin() + Count) && 784 "Cache isn't sorted!"); 785 } 786 #endif 787 788 const MemoryDependenceResults::NonLocalDepInfo & 789 MemoryDependenceResults::getNonLocalCallDependency(CallSite QueryCS) { 790 assert(getDependency(QueryCS.getInstruction()).isNonLocal() && 791 "getNonLocalCallDependency should only be used on calls with " 792 "non-local deps!"); 793 PerInstNLInfo &CacheP = NonLocalDeps[QueryCS.getInstruction()]; 794 NonLocalDepInfo &Cache = CacheP.first; 795 796 // This is the set of blocks that need to be recomputed. In the cached case, 797 // this can happen due to instructions being deleted etc. In the uncached 798 // case, this starts out as the set of predecessors we care about. 799 SmallVector<BasicBlock *, 32> DirtyBlocks; 800 801 if (!Cache.empty()) { 802 // Okay, we have a cache entry. If we know it is not dirty, just return it 803 // with no computation. 804 if (!CacheP.second) { 805 ++NumCacheNonLocal; 806 return Cache; 807 } 808 809 // If we already have a partially computed set of results, scan them to 810 // determine what is dirty, seeding our initial DirtyBlocks worklist. 811 for (auto &Entry : Cache) 812 if (Entry.getResult().isDirty()) 813 DirtyBlocks.push_back(Entry.getBB()); 814 815 // Sort the cache so that we can do fast binary search lookups below. 816 std::sort(Cache.begin(), Cache.end()); 817 818 ++NumCacheDirtyNonLocal; 819 // cerr << "CACHED CASE: " << DirtyBlocks.size() << " dirty: " 820 // << Cache.size() << " cached: " << *QueryInst; 821 } else { 822 // Seed DirtyBlocks with each of the preds of QueryInst's block. 823 BasicBlock *QueryBB = QueryCS.getInstruction()->getParent(); 824 for (BasicBlock *Pred : PredCache.get(QueryBB)) 825 DirtyBlocks.push_back(Pred); 826 ++NumUncacheNonLocal; 827 } 828 829 // isReadonlyCall - If this is a read-only call, we can be more aggressive. 830 bool isReadonlyCall = AA.onlyReadsMemory(QueryCS); 831 832 SmallPtrSet<BasicBlock *, 32> Visited; 833 834 unsigned NumSortedEntries = Cache.size(); 835 DEBUG(AssertSorted(Cache)); 836 837 // Iterate while we still have blocks to update. 838 while (!DirtyBlocks.empty()) { 839 BasicBlock *DirtyBB = DirtyBlocks.back(); 840 DirtyBlocks.pop_back(); 841 842 // Already processed this block? 843 if (!Visited.insert(DirtyBB).second) 844 continue; 845 846 // Do a binary search to see if we already have an entry for this block in 847 // the cache set. If so, find it. 848 DEBUG(AssertSorted(Cache, NumSortedEntries)); 849 NonLocalDepInfo::iterator Entry = 850 std::upper_bound(Cache.begin(), Cache.begin() + NumSortedEntries, 851 NonLocalDepEntry(DirtyBB)); 852 if (Entry != Cache.begin() && std::prev(Entry)->getBB() == DirtyBB) 853 --Entry; 854 855 NonLocalDepEntry *ExistingResult = nullptr; 856 if (Entry != Cache.begin() + NumSortedEntries && 857 Entry->getBB() == DirtyBB) { 858 // If we already have an entry, and if it isn't already dirty, the block 859 // is done. 860 if (!Entry->getResult().isDirty()) 861 continue; 862 863 // Otherwise, remember this slot so we can update the value. 864 ExistingResult = &*Entry; 865 } 866 867 // If the dirty entry has a pointer, start scanning from it so we don't have 868 // to rescan the entire block. 869 BasicBlock::iterator ScanPos = DirtyBB->end(); 870 if (ExistingResult) { 871 if (Instruction *Inst = ExistingResult->getResult().getInst()) { 872 ScanPos = Inst->getIterator(); 873 // We're removing QueryInst's use of Inst. 874 RemoveFromReverseMap(ReverseNonLocalDeps, Inst, 875 QueryCS.getInstruction()); 876 } 877 } 878 879 // Find out if this block has a local dependency for QueryInst. 880 MemDepResult Dep; 881 882 if (ScanPos != DirtyBB->begin()) { 883 Dep = 884 getCallSiteDependencyFrom(QueryCS, isReadonlyCall, ScanPos, DirtyBB); 885 } else if (DirtyBB != &DirtyBB->getParent()->getEntryBlock()) { 886 // No dependence found. If this is the entry block of the function, it is 887 // a clobber, otherwise it is unknown. 888 Dep = MemDepResult::getNonLocal(); 889 } else { 890 Dep = MemDepResult::getNonFuncLocal(); 891 } 892 893 // If we had a dirty entry for the block, update it. Otherwise, just add 894 // a new entry. 895 if (ExistingResult) 896 ExistingResult->setResult(Dep); 897 else 898 Cache.push_back(NonLocalDepEntry(DirtyBB, Dep)); 899 900 // If the block has a dependency (i.e. it isn't completely transparent to 901 // the value), remember the association! 902 if (!Dep.isNonLocal()) { 903 // Keep the ReverseNonLocalDeps map up to date so we can efficiently 904 // update this when we remove instructions. 905 if (Instruction *Inst = Dep.getInst()) 906 ReverseNonLocalDeps[Inst].insert(QueryCS.getInstruction()); 907 } else { 908 909 // If the block *is* completely transparent to the load, we need to check 910 // the predecessors of this block. Add them to our worklist. 911 for (BasicBlock *Pred : PredCache.get(DirtyBB)) 912 DirtyBlocks.push_back(Pred); 913 } 914 } 915 916 return Cache; 917 } 918 919 void MemoryDependenceResults::getNonLocalPointerDependency( 920 Instruction *QueryInst, SmallVectorImpl<NonLocalDepResult> &Result) { 921 const MemoryLocation Loc = MemoryLocation::get(QueryInst); 922 bool isLoad = isa<LoadInst>(QueryInst); 923 BasicBlock *FromBB = QueryInst->getParent(); 924 assert(FromBB); 925 926 assert(Loc.Ptr->getType()->isPointerTy() && 927 "Can't get pointer deps of a non-pointer!"); 928 Result.clear(); 929 { 930 // Check if there is cached Def with invariant.group. FIXME: cache might be 931 // invalid if cached instruction would be removed between call to 932 // getPointerDependencyFrom and this function. 933 auto NonLocalDefIt = NonLocalDefsCache.find(QueryInst); 934 if (NonLocalDefIt != NonLocalDefsCache.end()) { 935 Result.push_back(std::move(NonLocalDefIt->second)); 936 NonLocalDefsCache.erase(NonLocalDefIt); 937 return; 938 } 939 } 940 // This routine does not expect to deal with volatile instructions. 941 // Doing so would require piping through the QueryInst all the way through. 942 // TODO: volatiles can't be elided, but they can be reordered with other 943 // non-volatile accesses. 944 945 // We currently give up on any instruction which is ordered, but we do handle 946 // atomic instructions which are unordered. 947 // TODO: Handle ordered instructions 948 auto isOrdered = [](Instruction *Inst) { 949 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) { 950 return !LI->isUnordered(); 951 } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) { 952 return !SI->isUnordered(); 953 } 954 return false; 955 }; 956 if (isVolatile(QueryInst) || isOrdered(QueryInst)) { 957 Result.push_back(NonLocalDepResult(FromBB, MemDepResult::getUnknown(), 958 const_cast<Value *>(Loc.Ptr))); 959 return; 960 } 961 const DataLayout &DL = FromBB->getModule()->getDataLayout(); 962 PHITransAddr Address(const_cast<Value *>(Loc.Ptr), DL, &AC); 963 964 // This is the set of blocks we've inspected, and the pointer we consider in 965 // each block. Because of critical edges, we currently bail out if querying 966 // a block with multiple different pointers. This can happen during PHI 967 // translation. 968 DenseMap<BasicBlock *, Value *> Visited; 969 if (getNonLocalPointerDepFromBB(QueryInst, Address, Loc, isLoad, FromBB, 970 Result, Visited, true)) 971 return; 972 Result.clear(); 973 Result.push_back(NonLocalDepResult(FromBB, MemDepResult::getUnknown(), 974 const_cast<Value *>(Loc.Ptr))); 975 } 976 977 /// Compute the memdep value for BB with Pointer/PointeeSize using either 978 /// cached information in Cache or by doing a lookup (which may use dirty cache 979 /// info if available). 980 /// 981 /// If we do a lookup, add the result to the cache. 982 MemDepResult MemoryDependenceResults::GetNonLocalInfoForBlock( 983 Instruction *QueryInst, const MemoryLocation &Loc, bool isLoad, 984 BasicBlock *BB, NonLocalDepInfo *Cache, unsigned NumSortedEntries) { 985 986 // Do a binary search to see if we already have an entry for this block in 987 // the cache set. If so, find it. 988 NonLocalDepInfo::iterator Entry = std::upper_bound( 989 Cache->begin(), Cache->begin() + NumSortedEntries, NonLocalDepEntry(BB)); 990 if (Entry != Cache->begin() && (Entry - 1)->getBB() == BB) 991 --Entry; 992 993 NonLocalDepEntry *ExistingResult = nullptr; 994 if (Entry != Cache->begin() + NumSortedEntries && Entry->getBB() == BB) 995 ExistingResult = &*Entry; 996 997 // If we have a cached entry, and it is non-dirty, use it as the value for 998 // this dependency. 999 if (ExistingResult && !ExistingResult->getResult().isDirty()) { 1000 ++NumCacheNonLocalPtr; 1001 return ExistingResult->getResult(); 1002 } 1003 1004 // Otherwise, we have to scan for the value. If we have a dirty cache 1005 // entry, start scanning from its position, otherwise we scan from the end 1006 // of the block. 1007 BasicBlock::iterator ScanPos = BB->end(); 1008 if (ExistingResult && ExistingResult->getResult().getInst()) { 1009 assert(ExistingResult->getResult().getInst()->getParent() == BB && 1010 "Instruction invalidated?"); 1011 ++NumCacheDirtyNonLocalPtr; 1012 ScanPos = ExistingResult->getResult().getInst()->getIterator(); 1013 1014 // Eliminating the dirty entry from 'Cache', so update the reverse info. 1015 ValueIsLoadPair CacheKey(Loc.Ptr, isLoad); 1016 RemoveFromReverseMap(ReverseNonLocalPtrDeps, &*ScanPos, CacheKey); 1017 } else { 1018 ++NumUncacheNonLocalPtr; 1019 } 1020 1021 // Scan the block for the dependency. 1022 MemDepResult Dep = 1023 getPointerDependencyFrom(Loc, isLoad, ScanPos, BB, QueryInst); 1024 1025 // If we had a dirty entry for the block, update it. Otherwise, just add 1026 // a new entry. 1027 if (ExistingResult) 1028 ExistingResult->setResult(Dep); 1029 else 1030 Cache->push_back(NonLocalDepEntry(BB, Dep)); 1031 1032 // If the block has a dependency (i.e. it isn't completely transparent to 1033 // the value), remember the reverse association because we just added it 1034 // to Cache! 1035 if (!Dep.isDef() && !Dep.isClobber()) 1036 return Dep; 1037 1038 // Keep the ReverseNonLocalPtrDeps map up to date so we can efficiently 1039 // update MemDep when we remove instructions. 1040 Instruction *Inst = Dep.getInst(); 1041 assert(Inst && "Didn't depend on anything?"); 1042 ValueIsLoadPair CacheKey(Loc.Ptr, isLoad); 1043 ReverseNonLocalPtrDeps[Inst].insert(CacheKey); 1044 return Dep; 1045 } 1046 1047 /// Sort the NonLocalDepInfo cache, given a certain number of elements in the 1048 /// array that are already properly ordered. 1049 /// 1050 /// This is optimized for the case when only a few entries are added. 1051 static void 1052 SortNonLocalDepInfoCache(MemoryDependenceResults::NonLocalDepInfo &Cache, 1053 unsigned NumSortedEntries) { 1054 switch (Cache.size() - NumSortedEntries) { 1055 case 0: 1056 // done, no new entries. 1057 break; 1058 case 2: { 1059 // Two new entries, insert the last one into place. 1060 NonLocalDepEntry Val = Cache.back(); 1061 Cache.pop_back(); 1062 MemoryDependenceResults::NonLocalDepInfo::iterator Entry = 1063 std::upper_bound(Cache.begin(), Cache.end() - 1, Val); 1064 Cache.insert(Entry, Val); 1065 LLVM_FALLTHROUGH; 1066 } 1067 case 1: 1068 // One new entry, Just insert the new value at the appropriate position. 1069 if (Cache.size() != 1) { 1070 NonLocalDepEntry Val = Cache.back(); 1071 Cache.pop_back(); 1072 MemoryDependenceResults::NonLocalDepInfo::iterator Entry = 1073 std::upper_bound(Cache.begin(), Cache.end(), Val); 1074 Cache.insert(Entry, Val); 1075 } 1076 break; 1077 default: 1078 // Added many values, do a full scale sort. 1079 std::sort(Cache.begin(), Cache.end()); 1080 break; 1081 } 1082 } 1083 1084 /// Perform a dependency query based on pointer/pointeesize starting at the end 1085 /// of StartBB. 1086 /// 1087 /// Add any clobber/def results to the results vector and keep track of which 1088 /// blocks are visited in 'Visited'. 1089 /// 1090 /// This has special behavior for the first block queries (when SkipFirstBlock 1091 /// is true). In this special case, it ignores the contents of the specified 1092 /// block and starts returning dependence info for its predecessors. 1093 /// 1094 /// This function returns true on success, or false to indicate that it could 1095 /// not compute dependence information for some reason. This should be treated 1096 /// as a clobber dependence on the first instruction in the predecessor block. 1097 bool MemoryDependenceResults::getNonLocalPointerDepFromBB( 1098 Instruction *QueryInst, const PHITransAddr &Pointer, 1099 const MemoryLocation &Loc, bool isLoad, BasicBlock *StartBB, 1100 SmallVectorImpl<NonLocalDepResult> &Result, 1101 DenseMap<BasicBlock *, Value *> &Visited, bool SkipFirstBlock) { 1102 // Look up the cached info for Pointer. 1103 ValueIsLoadPair CacheKey(Pointer.getAddr(), isLoad); 1104 1105 // Set up a temporary NLPI value. If the map doesn't yet have an entry for 1106 // CacheKey, this value will be inserted as the associated value. Otherwise, 1107 // it'll be ignored, and we'll have to check to see if the cached size and 1108 // aa tags are consistent with the current query. 1109 NonLocalPointerInfo InitialNLPI; 1110 InitialNLPI.Size = Loc.Size; 1111 InitialNLPI.AATags = Loc.AATags; 1112 1113 // Get the NLPI for CacheKey, inserting one into the map if it doesn't 1114 // already have one. 1115 std::pair<CachedNonLocalPointerInfo::iterator, bool> Pair = 1116 NonLocalPointerDeps.insert(std::make_pair(CacheKey, InitialNLPI)); 1117 NonLocalPointerInfo *CacheInfo = &Pair.first->second; 1118 1119 // If we already have a cache entry for this CacheKey, we may need to do some 1120 // work to reconcile the cache entry and the current query. 1121 if (!Pair.second) { 1122 if (CacheInfo->Size < Loc.Size) { 1123 // The query's Size is greater than the cached one. Throw out the 1124 // cached data and proceed with the query at the greater size. 1125 CacheInfo->Pair = BBSkipFirstBlockPair(); 1126 CacheInfo->Size = Loc.Size; 1127 for (auto &Entry : CacheInfo->NonLocalDeps) 1128 if (Instruction *Inst = Entry.getResult().getInst()) 1129 RemoveFromReverseMap(ReverseNonLocalPtrDeps, Inst, CacheKey); 1130 CacheInfo->NonLocalDeps.clear(); 1131 } else if (CacheInfo->Size > Loc.Size) { 1132 // This query's Size is less than the cached one. Conservatively restart 1133 // the query using the greater size. 1134 return getNonLocalPointerDepFromBB( 1135 QueryInst, Pointer, Loc.getWithNewSize(CacheInfo->Size), isLoad, 1136 StartBB, Result, Visited, SkipFirstBlock); 1137 } 1138 1139 // If the query's AATags are inconsistent with the cached one, 1140 // conservatively throw out the cached data and restart the query with 1141 // no tag if needed. 1142 if (CacheInfo->AATags != Loc.AATags) { 1143 if (CacheInfo->AATags) { 1144 CacheInfo->Pair = BBSkipFirstBlockPair(); 1145 CacheInfo->AATags = AAMDNodes(); 1146 for (auto &Entry : CacheInfo->NonLocalDeps) 1147 if (Instruction *Inst = Entry.getResult().getInst()) 1148 RemoveFromReverseMap(ReverseNonLocalPtrDeps, Inst, CacheKey); 1149 CacheInfo->NonLocalDeps.clear(); 1150 } 1151 if (Loc.AATags) 1152 return getNonLocalPointerDepFromBB( 1153 QueryInst, Pointer, Loc.getWithoutAATags(), isLoad, StartBB, Result, 1154 Visited, SkipFirstBlock); 1155 } 1156 } 1157 1158 NonLocalDepInfo *Cache = &CacheInfo->NonLocalDeps; 1159 1160 // If we have valid cached information for exactly the block we are 1161 // investigating, just return it with no recomputation. 1162 if (CacheInfo->Pair == BBSkipFirstBlockPair(StartBB, SkipFirstBlock)) { 1163 // We have a fully cached result for this query then we can just return the 1164 // cached results and populate the visited set. However, we have to verify 1165 // that we don't already have conflicting results for these blocks. Check 1166 // to ensure that if a block in the results set is in the visited set that 1167 // it was for the same pointer query. 1168 if (!Visited.empty()) { 1169 for (auto &Entry : *Cache) { 1170 DenseMap<BasicBlock *, Value *>::iterator VI = 1171 Visited.find(Entry.getBB()); 1172 if (VI == Visited.end() || VI->second == Pointer.getAddr()) 1173 continue; 1174 1175 // We have a pointer mismatch in a block. Just return false, saying 1176 // that something was clobbered in this result. We could also do a 1177 // non-fully cached query, but there is little point in doing this. 1178 return false; 1179 } 1180 } 1181 1182 Value *Addr = Pointer.getAddr(); 1183 for (auto &Entry : *Cache) { 1184 Visited.insert(std::make_pair(Entry.getBB(), Addr)); 1185 if (Entry.getResult().isNonLocal()) { 1186 continue; 1187 } 1188 1189 if (DT.isReachableFromEntry(Entry.getBB())) { 1190 Result.push_back( 1191 NonLocalDepResult(Entry.getBB(), Entry.getResult(), Addr)); 1192 } 1193 } 1194 ++NumCacheCompleteNonLocalPtr; 1195 return true; 1196 } 1197 1198 // Otherwise, either this is a new block, a block with an invalid cache 1199 // pointer or one that we're about to invalidate by putting more info into it 1200 // than its valid cache info. If empty, the result will be valid cache info, 1201 // otherwise it isn't. 1202 if (Cache->empty()) 1203 CacheInfo->Pair = BBSkipFirstBlockPair(StartBB, SkipFirstBlock); 1204 else 1205 CacheInfo->Pair = BBSkipFirstBlockPair(); 1206 1207 SmallVector<BasicBlock *, 32> Worklist; 1208 Worklist.push_back(StartBB); 1209 1210 // PredList used inside loop. 1211 SmallVector<std::pair<BasicBlock *, PHITransAddr>, 16> PredList; 1212 1213 // Keep track of the entries that we know are sorted. Previously cached 1214 // entries will all be sorted. The entries we add we only sort on demand (we 1215 // don't insert every element into its sorted position). We know that we 1216 // won't get any reuse from currently inserted values, because we don't 1217 // revisit blocks after we insert info for them. 1218 unsigned NumSortedEntries = Cache->size(); 1219 unsigned WorklistEntries = BlockNumberLimit; 1220 bool GotWorklistLimit = false; 1221 DEBUG(AssertSorted(*Cache)); 1222 1223 while (!Worklist.empty()) { 1224 BasicBlock *BB = Worklist.pop_back_val(); 1225 1226 // If we do process a large number of blocks it becomes very expensive and 1227 // likely it isn't worth worrying about 1228 if (Result.size() > NumResultsLimit) { 1229 Worklist.clear(); 1230 // Sort it now (if needed) so that recursive invocations of 1231 // getNonLocalPointerDepFromBB and other routines that could reuse the 1232 // cache value will only see properly sorted cache arrays. 1233 if (Cache && NumSortedEntries != Cache->size()) { 1234 SortNonLocalDepInfoCache(*Cache, NumSortedEntries); 1235 } 1236 // Since we bail out, the "Cache" set won't contain all of the 1237 // results for the query. This is ok (we can still use it to accelerate 1238 // specific block queries) but we can't do the fastpath "return all 1239 // results from the set". Clear out the indicator for this. 1240 CacheInfo->Pair = BBSkipFirstBlockPair(); 1241 return false; 1242 } 1243 1244 // Skip the first block if we have it. 1245 if (!SkipFirstBlock) { 1246 // Analyze the dependency of *Pointer in FromBB. See if we already have 1247 // been here. 1248 assert(Visited.count(BB) && "Should check 'visited' before adding to WL"); 1249 1250 // Get the dependency info for Pointer in BB. If we have cached 1251 // information, we will use it, otherwise we compute it. 1252 DEBUG(AssertSorted(*Cache, NumSortedEntries)); 1253 MemDepResult Dep = GetNonLocalInfoForBlock(QueryInst, Loc, isLoad, BB, 1254 Cache, NumSortedEntries); 1255 1256 // If we got a Def or Clobber, add this to the list of results. 1257 if (!Dep.isNonLocal()) { 1258 if (DT.isReachableFromEntry(BB)) { 1259 Result.push_back(NonLocalDepResult(BB, Dep, Pointer.getAddr())); 1260 continue; 1261 } 1262 } 1263 } 1264 1265 // If 'Pointer' is an instruction defined in this block, then we need to do 1266 // phi translation to change it into a value live in the predecessor block. 1267 // If not, we just add the predecessors to the worklist and scan them with 1268 // the same Pointer. 1269 if (!Pointer.NeedsPHITranslationFromBlock(BB)) { 1270 SkipFirstBlock = false; 1271 SmallVector<BasicBlock *, 16> NewBlocks; 1272 for (BasicBlock *Pred : PredCache.get(BB)) { 1273 // Verify that we haven't looked at this block yet. 1274 std::pair<DenseMap<BasicBlock *, Value *>::iterator, bool> InsertRes = 1275 Visited.insert(std::make_pair(Pred, Pointer.getAddr())); 1276 if (InsertRes.second) { 1277 // First time we've looked at *PI. 1278 NewBlocks.push_back(Pred); 1279 continue; 1280 } 1281 1282 // If we have seen this block before, but it was with a different 1283 // pointer then we have a phi translation failure and we have to treat 1284 // this as a clobber. 1285 if (InsertRes.first->second != Pointer.getAddr()) { 1286 // Make sure to clean up the Visited map before continuing on to 1287 // PredTranslationFailure. 1288 for (unsigned i = 0; i < NewBlocks.size(); i++) 1289 Visited.erase(NewBlocks[i]); 1290 goto PredTranslationFailure; 1291 } 1292 } 1293 if (NewBlocks.size() > WorklistEntries) { 1294 // Make sure to clean up the Visited map before continuing on to 1295 // PredTranslationFailure. 1296 for (unsigned i = 0; i < NewBlocks.size(); i++) 1297 Visited.erase(NewBlocks[i]); 1298 GotWorklistLimit = true; 1299 goto PredTranslationFailure; 1300 } 1301 WorklistEntries -= NewBlocks.size(); 1302 Worklist.append(NewBlocks.begin(), NewBlocks.end()); 1303 continue; 1304 } 1305 1306 // We do need to do phi translation, if we know ahead of time we can't phi 1307 // translate this value, don't even try. 1308 if (!Pointer.IsPotentiallyPHITranslatable()) 1309 goto PredTranslationFailure; 1310 1311 // We may have added values to the cache list before this PHI translation. 1312 // If so, we haven't done anything to ensure that the cache remains sorted. 1313 // Sort it now (if needed) so that recursive invocations of 1314 // getNonLocalPointerDepFromBB and other routines that could reuse the cache 1315 // value will only see properly sorted cache arrays. 1316 if (Cache && NumSortedEntries != Cache->size()) { 1317 SortNonLocalDepInfoCache(*Cache, NumSortedEntries); 1318 NumSortedEntries = Cache->size(); 1319 } 1320 Cache = nullptr; 1321 1322 PredList.clear(); 1323 for (BasicBlock *Pred : PredCache.get(BB)) { 1324 PredList.push_back(std::make_pair(Pred, Pointer)); 1325 1326 // Get the PHI translated pointer in this predecessor. This can fail if 1327 // not translatable, in which case the getAddr() returns null. 1328 PHITransAddr &PredPointer = PredList.back().second; 1329 PredPointer.PHITranslateValue(BB, Pred, &DT, /*MustDominate=*/false); 1330 Value *PredPtrVal = PredPointer.getAddr(); 1331 1332 // Check to see if we have already visited this pred block with another 1333 // pointer. If so, we can't do this lookup. This failure can occur 1334 // with PHI translation when a critical edge exists and the PHI node in 1335 // the successor translates to a pointer value different than the 1336 // pointer the block was first analyzed with. 1337 std::pair<DenseMap<BasicBlock *, Value *>::iterator, bool> InsertRes = 1338 Visited.insert(std::make_pair(Pred, PredPtrVal)); 1339 1340 if (!InsertRes.second) { 1341 // We found the pred; take it off the list of preds to visit. 1342 PredList.pop_back(); 1343 1344 // If the predecessor was visited with PredPtr, then we already did 1345 // the analysis and can ignore it. 1346 if (InsertRes.first->second == PredPtrVal) 1347 continue; 1348 1349 // Otherwise, the block was previously analyzed with a different 1350 // pointer. We can't represent the result of this case, so we just 1351 // treat this as a phi translation failure. 1352 1353 // Make sure to clean up the Visited map before continuing on to 1354 // PredTranslationFailure. 1355 for (unsigned i = 0, n = PredList.size(); i < n; ++i) 1356 Visited.erase(PredList[i].first); 1357 1358 goto PredTranslationFailure; 1359 } 1360 } 1361 1362 // Actually process results here; this need to be a separate loop to avoid 1363 // calling getNonLocalPointerDepFromBB for blocks we don't want to return 1364 // any results for. (getNonLocalPointerDepFromBB will modify our 1365 // datastructures in ways the code after the PredTranslationFailure label 1366 // doesn't expect.) 1367 for (unsigned i = 0, n = PredList.size(); i < n; ++i) { 1368 BasicBlock *Pred = PredList[i].first; 1369 PHITransAddr &PredPointer = PredList[i].second; 1370 Value *PredPtrVal = PredPointer.getAddr(); 1371 1372 bool CanTranslate = true; 1373 // If PHI translation was unable to find an available pointer in this 1374 // predecessor, then we have to assume that the pointer is clobbered in 1375 // that predecessor. We can still do PRE of the load, which would insert 1376 // a computation of the pointer in this predecessor. 1377 if (!PredPtrVal) 1378 CanTranslate = false; 1379 1380 // FIXME: it is entirely possible that PHI translating will end up with 1381 // the same value. Consider PHI translating something like: 1382 // X = phi [x, bb1], [y, bb2]. PHI translating for bb1 doesn't *need* 1383 // to recurse here, pedantically speaking. 1384 1385 // If getNonLocalPointerDepFromBB fails here, that means the cached 1386 // result conflicted with the Visited list; we have to conservatively 1387 // assume it is unknown, but this also does not block PRE of the load. 1388 if (!CanTranslate || 1389 !getNonLocalPointerDepFromBB(QueryInst, PredPointer, 1390 Loc.getWithNewPtr(PredPtrVal), isLoad, 1391 Pred, Result, Visited)) { 1392 // Add the entry to the Result list. 1393 NonLocalDepResult Entry(Pred, MemDepResult::getUnknown(), PredPtrVal); 1394 Result.push_back(Entry); 1395 1396 // Since we had a phi translation failure, the cache for CacheKey won't 1397 // include all of the entries that we need to immediately satisfy future 1398 // queries. Mark this in NonLocalPointerDeps by setting the 1399 // BBSkipFirstBlockPair pointer to null. This requires reuse of the 1400 // cached value to do more work but not miss the phi trans failure. 1401 NonLocalPointerInfo &NLPI = NonLocalPointerDeps[CacheKey]; 1402 NLPI.Pair = BBSkipFirstBlockPair(); 1403 continue; 1404 } 1405 } 1406 1407 // Refresh the CacheInfo/Cache pointer so that it isn't invalidated. 1408 CacheInfo = &NonLocalPointerDeps[CacheKey]; 1409 Cache = &CacheInfo->NonLocalDeps; 1410 NumSortedEntries = Cache->size(); 1411 1412 // Since we did phi translation, the "Cache" set won't contain all of the 1413 // results for the query. This is ok (we can still use it to accelerate 1414 // specific block queries) but we can't do the fastpath "return all 1415 // results from the set" Clear out the indicator for this. 1416 CacheInfo->Pair = BBSkipFirstBlockPair(); 1417 SkipFirstBlock = false; 1418 continue; 1419 1420 PredTranslationFailure: 1421 // The following code is "failure"; we can't produce a sane translation 1422 // for the given block. It assumes that we haven't modified any of 1423 // our datastructures while processing the current block. 1424 1425 if (!Cache) { 1426 // Refresh the CacheInfo/Cache pointer if it got invalidated. 1427 CacheInfo = &NonLocalPointerDeps[CacheKey]; 1428 Cache = &CacheInfo->NonLocalDeps; 1429 NumSortedEntries = Cache->size(); 1430 } 1431 1432 // Since we failed phi translation, the "Cache" set won't contain all of the 1433 // results for the query. This is ok (we can still use it to accelerate 1434 // specific block queries) but we can't do the fastpath "return all 1435 // results from the set". Clear out the indicator for this. 1436 CacheInfo->Pair = BBSkipFirstBlockPair(); 1437 1438 // If *nothing* works, mark the pointer as unknown. 1439 // 1440 // If this is the magic first block, return this as a clobber of the whole 1441 // incoming value. Since we can't phi translate to one of the predecessors, 1442 // we have to bail out. 1443 if (SkipFirstBlock) 1444 return false; 1445 1446 bool foundBlock = false; 1447 for (NonLocalDepEntry &I : llvm::reverse(*Cache)) { 1448 if (I.getBB() != BB) 1449 continue; 1450 1451 assert((GotWorklistLimit || I.getResult().isNonLocal() || 1452 !DT.isReachableFromEntry(BB)) && 1453 "Should only be here with transparent block"); 1454 foundBlock = true; 1455 I.setResult(MemDepResult::getUnknown()); 1456 Result.push_back( 1457 NonLocalDepResult(I.getBB(), I.getResult(), Pointer.getAddr())); 1458 break; 1459 } 1460 (void)foundBlock; (void)GotWorklistLimit; 1461 assert((foundBlock || GotWorklistLimit) && "Current block not in cache?"); 1462 } 1463 1464 // Okay, we're done now. If we added new values to the cache, re-sort it. 1465 SortNonLocalDepInfoCache(*Cache, NumSortedEntries); 1466 DEBUG(AssertSorted(*Cache)); 1467 return true; 1468 } 1469 1470 /// If P exists in CachedNonLocalPointerInfo, remove it. 1471 void MemoryDependenceResults::RemoveCachedNonLocalPointerDependencies( 1472 ValueIsLoadPair P) { 1473 CachedNonLocalPointerInfo::iterator It = NonLocalPointerDeps.find(P); 1474 if (It == NonLocalPointerDeps.end()) 1475 return; 1476 1477 // Remove all of the entries in the BB->val map. This involves removing 1478 // instructions from the reverse map. 1479 NonLocalDepInfo &PInfo = It->second.NonLocalDeps; 1480 1481 for (unsigned i = 0, e = PInfo.size(); i != e; ++i) { 1482 Instruction *Target = PInfo[i].getResult().getInst(); 1483 if (!Target) 1484 continue; // Ignore non-local dep results. 1485 assert(Target->getParent() == PInfo[i].getBB()); 1486 1487 // Eliminating the dirty entry from 'Cache', so update the reverse info. 1488 RemoveFromReverseMap(ReverseNonLocalPtrDeps, Target, P); 1489 } 1490 1491 // Remove P from NonLocalPointerDeps (which deletes NonLocalDepInfo). 1492 NonLocalPointerDeps.erase(It); 1493 } 1494 1495 void MemoryDependenceResults::invalidateCachedPointerInfo(Value *Ptr) { 1496 // If Ptr isn't really a pointer, just ignore it. 1497 if (!Ptr->getType()->isPointerTy()) 1498 return; 1499 // Flush store info for the pointer. 1500 RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(Ptr, false)); 1501 // Flush load info for the pointer. 1502 RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(Ptr, true)); 1503 } 1504 1505 void MemoryDependenceResults::invalidateCachedPredecessors() { 1506 PredCache.clear(); 1507 } 1508 1509 void MemoryDependenceResults::removeInstruction(Instruction *RemInst) { 1510 // Walk through the Non-local dependencies, removing this one as the value 1511 // for any cached queries. 1512 NonLocalDepMapType::iterator NLDI = NonLocalDeps.find(RemInst); 1513 if (NLDI != NonLocalDeps.end()) { 1514 NonLocalDepInfo &BlockMap = NLDI->second.first; 1515 for (auto &Entry : BlockMap) 1516 if (Instruction *Inst = Entry.getResult().getInst()) 1517 RemoveFromReverseMap(ReverseNonLocalDeps, Inst, RemInst); 1518 NonLocalDeps.erase(NLDI); 1519 } 1520 1521 // If we have a cached local dependence query for this instruction, remove it. 1522 LocalDepMapType::iterator LocalDepEntry = LocalDeps.find(RemInst); 1523 if (LocalDepEntry != LocalDeps.end()) { 1524 // Remove us from DepInst's reverse set now that the local dep info is gone. 1525 if (Instruction *Inst = LocalDepEntry->second.getInst()) 1526 RemoveFromReverseMap(ReverseLocalDeps, Inst, RemInst); 1527 1528 // Remove this local dependency info. 1529 LocalDeps.erase(LocalDepEntry); 1530 } 1531 1532 // If we have any cached pointer dependencies on this instruction, remove 1533 // them. If the instruction has non-pointer type, then it can't be a pointer 1534 // base. 1535 1536 // Remove it from both the load info and the store info. The instruction 1537 // can't be in either of these maps if it is non-pointer. 1538 if (RemInst->getType()->isPointerTy()) { 1539 RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(RemInst, false)); 1540 RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(RemInst, true)); 1541 } 1542 1543 // Loop over all of the things that depend on the instruction we're removing. 1544 SmallVector<std::pair<Instruction *, Instruction *>, 8> ReverseDepsToAdd; 1545 1546 // If we find RemInst as a clobber or Def in any of the maps for other values, 1547 // we need to replace its entry with a dirty version of the instruction after 1548 // it. If RemInst is a terminator, we use a null dirty value. 1549 // 1550 // Using a dirty version of the instruction after RemInst saves having to scan 1551 // the entire block to get to this point. 1552 MemDepResult NewDirtyVal; 1553 if (!RemInst->isTerminator()) 1554 NewDirtyVal = MemDepResult::getDirty(&*++RemInst->getIterator()); 1555 1556 ReverseDepMapType::iterator ReverseDepIt = ReverseLocalDeps.find(RemInst); 1557 if (ReverseDepIt != ReverseLocalDeps.end()) { 1558 // RemInst can't be the terminator if it has local stuff depending on it. 1559 assert(!ReverseDepIt->second.empty() && !isa<TerminatorInst>(RemInst) && 1560 "Nothing can locally depend on a terminator"); 1561 1562 for (Instruction *InstDependingOnRemInst : ReverseDepIt->second) { 1563 assert(InstDependingOnRemInst != RemInst && 1564 "Already removed our local dep info"); 1565 1566 LocalDeps[InstDependingOnRemInst] = NewDirtyVal; 1567 1568 // Make sure to remember that new things depend on NewDepInst. 1569 assert(NewDirtyVal.getInst() && 1570 "There is no way something else can have " 1571 "a local dep on this if it is a terminator!"); 1572 ReverseDepsToAdd.push_back( 1573 std::make_pair(NewDirtyVal.getInst(), InstDependingOnRemInst)); 1574 } 1575 1576 ReverseLocalDeps.erase(ReverseDepIt); 1577 1578 // Add new reverse deps after scanning the set, to avoid invalidating the 1579 // 'ReverseDeps' reference. 1580 while (!ReverseDepsToAdd.empty()) { 1581 ReverseLocalDeps[ReverseDepsToAdd.back().first].insert( 1582 ReverseDepsToAdd.back().second); 1583 ReverseDepsToAdd.pop_back(); 1584 } 1585 } 1586 1587 ReverseDepIt = ReverseNonLocalDeps.find(RemInst); 1588 if (ReverseDepIt != ReverseNonLocalDeps.end()) { 1589 for (Instruction *I : ReverseDepIt->second) { 1590 assert(I != RemInst && "Already removed NonLocalDep info for RemInst"); 1591 1592 PerInstNLInfo &INLD = NonLocalDeps[I]; 1593 // The information is now dirty! 1594 INLD.second = true; 1595 1596 for (auto &Entry : INLD.first) { 1597 if (Entry.getResult().getInst() != RemInst) 1598 continue; 1599 1600 // Convert to a dirty entry for the subsequent instruction. 1601 Entry.setResult(NewDirtyVal); 1602 1603 if (Instruction *NextI = NewDirtyVal.getInst()) 1604 ReverseDepsToAdd.push_back(std::make_pair(NextI, I)); 1605 } 1606 } 1607 1608 ReverseNonLocalDeps.erase(ReverseDepIt); 1609 1610 // Add new reverse deps after scanning the set, to avoid invalidating 'Set' 1611 while (!ReverseDepsToAdd.empty()) { 1612 ReverseNonLocalDeps[ReverseDepsToAdd.back().first].insert( 1613 ReverseDepsToAdd.back().second); 1614 ReverseDepsToAdd.pop_back(); 1615 } 1616 } 1617 1618 // If the instruction is in ReverseNonLocalPtrDeps then it appears as a 1619 // value in the NonLocalPointerDeps info. 1620 ReverseNonLocalPtrDepTy::iterator ReversePtrDepIt = 1621 ReverseNonLocalPtrDeps.find(RemInst); 1622 if (ReversePtrDepIt != ReverseNonLocalPtrDeps.end()) { 1623 SmallVector<std::pair<Instruction *, ValueIsLoadPair>, 8> 1624 ReversePtrDepsToAdd; 1625 1626 for (ValueIsLoadPair P : ReversePtrDepIt->second) { 1627 assert(P.getPointer() != RemInst && 1628 "Already removed NonLocalPointerDeps info for RemInst"); 1629 1630 NonLocalDepInfo &NLPDI = NonLocalPointerDeps[P].NonLocalDeps; 1631 1632 // The cache is not valid for any specific block anymore. 1633 NonLocalPointerDeps[P].Pair = BBSkipFirstBlockPair(); 1634 1635 // Update any entries for RemInst to use the instruction after it. 1636 for (auto &Entry : NLPDI) { 1637 if (Entry.getResult().getInst() != RemInst) 1638 continue; 1639 1640 // Convert to a dirty entry for the subsequent instruction. 1641 Entry.setResult(NewDirtyVal); 1642 1643 if (Instruction *NewDirtyInst = NewDirtyVal.getInst()) 1644 ReversePtrDepsToAdd.push_back(std::make_pair(NewDirtyInst, P)); 1645 } 1646 1647 // Re-sort the NonLocalDepInfo. Changing the dirty entry to its 1648 // subsequent value may invalidate the sortedness. 1649 std::sort(NLPDI.begin(), NLPDI.end()); 1650 } 1651 1652 ReverseNonLocalPtrDeps.erase(ReversePtrDepIt); 1653 1654 while (!ReversePtrDepsToAdd.empty()) { 1655 ReverseNonLocalPtrDeps[ReversePtrDepsToAdd.back().first].insert( 1656 ReversePtrDepsToAdd.back().second); 1657 ReversePtrDepsToAdd.pop_back(); 1658 } 1659 } 1660 1661 assert(!NonLocalDeps.count(RemInst) && "RemInst got reinserted?"); 1662 DEBUG(verifyRemoved(RemInst)); 1663 } 1664 1665 /// Verify that the specified instruction does not occur in our internal data 1666 /// structures. 1667 /// 1668 /// This function verifies by asserting in debug builds. 1669 void MemoryDependenceResults::verifyRemoved(Instruction *D) const { 1670 #ifndef NDEBUG 1671 for (const auto &DepKV : LocalDeps) { 1672 assert(DepKV.first != D && "Inst occurs in data structures"); 1673 assert(DepKV.second.getInst() != D && "Inst occurs in data structures"); 1674 } 1675 1676 for (const auto &DepKV : NonLocalPointerDeps) { 1677 assert(DepKV.first.getPointer() != D && "Inst occurs in NLPD map key"); 1678 for (const auto &Entry : DepKV.second.NonLocalDeps) 1679 assert(Entry.getResult().getInst() != D && "Inst occurs as NLPD value"); 1680 } 1681 1682 for (const auto &DepKV : NonLocalDeps) { 1683 assert(DepKV.first != D && "Inst occurs in data structures"); 1684 const PerInstNLInfo &INLD = DepKV.second; 1685 for (const auto &Entry : INLD.first) 1686 assert(Entry.getResult().getInst() != D && 1687 "Inst occurs in data structures"); 1688 } 1689 1690 for (const auto &DepKV : ReverseLocalDeps) { 1691 assert(DepKV.first != D && "Inst occurs in data structures"); 1692 for (Instruction *Inst : DepKV.second) 1693 assert(Inst != D && "Inst occurs in data structures"); 1694 } 1695 1696 for (const auto &DepKV : ReverseNonLocalDeps) { 1697 assert(DepKV.first != D && "Inst occurs in data structures"); 1698 for (Instruction *Inst : DepKV.second) 1699 assert(Inst != D && "Inst occurs in data structures"); 1700 } 1701 1702 for (const auto &DepKV : ReverseNonLocalPtrDeps) { 1703 assert(DepKV.first != D && "Inst occurs in rev NLPD map"); 1704 1705 for (ValueIsLoadPair P : DepKV.second) 1706 assert(P != ValueIsLoadPair(D, false) && P != ValueIsLoadPair(D, true) && 1707 "Inst occurs in ReverseNonLocalPtrDeps map"); 1708 } 1709 #endif 1710 } 1711 1712 AnalysisKey MemoryDependenceAnalysis::Key; 1713 1714 MemoryDependenceResults 1715 MemoryDependenceAnalysis::run(Function &F, FunctionAnalysisManager &AM) { 1716 auto &AA = AM.getResult<AAManager>(F); 1717 auto &AC = AM.getResult<AssumptionAnalysis>(F); 1718 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F); 1719 auto &DT = AM.getResult<DominatorTreeAnalysis>(F); 1720 return MemoryDependenceResults(AA, AC, TLI, DT); 1721 } 1722 1723 char MemoryDependenceWrapperPass::ID = 0; 1724 1725 INITIALIZE_PASS_BEGIN(MemoryDependenceWrapperPass, "memdep", 1726 "Memory Dependence Analysis", false, true) 1727 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 1728 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) 1729 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 1730 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 1731 INITIALIZE_PASS_END(MemoryDependenceWrapperPass, "memdep", 1732 "Memory Dependence Analysis", false, true) 1733 1734 MemoryDependenceWrapperPass::MemoryDependenceWrapperPass() : FunctionPass(ID) { 1735 initializeMemoryDependenceWrapperPassPass(*PassRegistry::getPassRegistry()); 1736 } 1737 1738 MemoryDependenceWrapperPass::~MemoryDependenceWrapperPass() = default; 1739 1740 void MemoryDependenceWrapperPass::releaseMemory() { 1741 MemDep.reset(); 1742 } 1743 1744 void MemoryDependenceWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { 1745 AU.setPreservesAll(); 1746 AU.addRequired<AssumptionCacheTracker>(); 1747 AU.addRequired<DominatorTreeWrapperPass>(); 1748 AU.addRequiredTransitive<AAResultsWrapperPass>(); 1749 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>(); 1750 } 1751 1752 bool MemoryDependenceResults::invalidate(Function &F, const PreservedAnalyses &PA, 1753 FunctionAnalysisManager::Invalidator &Inv) { 1754 // Check whether our analysis is preserved. 1755 auto PAC = PA.getChecker<MemoryDependenceAnalysis>(); 1756 if (!PAC.preserved() && !PAC.preservedSet<AllAnalysesOn<Function>>()) 1757 // If not, give up now. 1758 return true; 1759 1760 // Check whether the analyses we depend on became invalid for any reason. 1761 if (Inv.invalidate<AAManager>(F, PA) || 1762 Inv.invalidate<AssumptionAnalysis>(F, PA) || 1763 Inv.invalidate<DominatorTreeAnalysis>(F, PA)) 1764 return true; 1765 1766 // Otherwise this analysis result remains valid. 1767 return false; 1768 } 1769 1770 unsigned MemoryDependenceResults::getDefaultBlockScanLimit() const { 1771 return BlockScanLimit; 1772 } 1773 1774 bool MemoryDependenceWrapperPass::runOnFunction(Function &F) { 1775 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults(); 1776 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F); 1777 auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(); 1778 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 1779 MemDep.emplace(AA, AC, TLI, DT); 1780 return false; 1781 } 1782