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