1f785676fSDimitry Andric //===- MemoryDependenceAnalysis.cpp - Mem Deps Implementation -------------===// 2f22ef01cSRoman Divacky // 3f22ef01cSRoman Divacky // The LLVM Compiler Infrastructure 4f22ef01cSRoman Divacky // 5f22ef01cSRoman Divacky // This file is distributed under the University of Illinois Open Source 6f22ef01cSRoman Divacky // License. See LICENSE.TXT for details. 7f22ef01cSRoman Divacky // 8f22ef01cSRoman Divacky //===----------------------------------------------------------------------===// 9f22ef01cSRoman Divacky // 10f22ef01cSRoman Divacky // This file implements an analysis that determines, for a given memory 11f22ef01cSRoman Divacky // operation, what preceding memory operations it depends on. It builds on 12f22ef01cSRoman Divacky // alias analysis information, and tries to provide a lazy, caching interface to 13f22ef01cSRoman Divacky // a common kind of alias information query. 14f22ef01cSRoman Divacky // 15f22ef01cSRoman Divacky //===----------------------------------------------------------------------===// 16f22ef01cSRoman Divacky 17f22ef01cSRoman Divacky #include "llvm/Analysis/MemoryDependenceAnalysis.h" 18139f7f9bSDimitry Andric #include "llvm/ADT/STLExtras.h" 19139f7f9bSDimitry Andric #include "llvm/ADT/Statistic.h" 20f22ef01cSRoman Divacky #include "llvm/Analysis/AliasAnalysis.h" 2139d628a0SDimitry Andric #include "llvm/Analysis/AssumptionCache.h" 22f22ef01cSRoman Divacky #include "llvm/Analysis/InstructionSimplify.h" 23f22ef01cSRoman Divacky #include "llvm/Analysis/MemoryBuiltins.h" 24f22ef01cSRoman Divacky #include "llvm/Analysis/PHITransAddr.h" 257d523365SDimitry Andric #include "llvm/Analysis/OrderedBasicBlock.h" 262754fe60SDimitry Andric #include "llvm/Analysis/ValueTracking.h" 277d523365SDimitry Andric #include "llvm/Analysis/TargetLibraryInfo.h" 28139f7f9bSDimitry Andric #include "llvm/IR/DataLayout.h" 2991bc56edSDimitry Andric #include "llvm/IR/Dominators.h" 30139f7f9bSDimitry Andric #include "llvm/IR/Function.h" 31139f7f9bSDimitry Andric #include "llvm/IR/Instructions.h" 32139f7f9bSDimitry Andric #include "llvm/IR/IntrinsicInst.h" 33139f7f9bSDimitry Andric #include "llvm/IR/LLVMContext.h" 3491bc56edSDimitry Andric #include "llvm/IR/PredIteratorCache.h" 35f22ef01cSRoman Divacky #include "llvm/Support/Debug.h" 36f22ef01cSRoman Divacky using namespace llvm; 37f22ef01cSRoman Divacky 3891bc56edSDimitry Andric #define DEBUG_TYPE "memdep" 3991bc56edSDimitry Andric 40f22ef01cSRoman Divacky STATISTIC(NumCacheNonLocal, "Number of fully cached non-local responses"); 41f22ef01cSRoman Divacky STATISTIC(NumCacheDirtyNonLocal, "Number of dirty cached non-local responses"); 42f22ef01cSRoman Divacky STATISTIC(NumUncacheNonLocal, "Number of uncached non-local responses"); 43f22ef01cSRoman Divacky 44f22ef01cSRoman Divacky STATISTIC(NumCacheNonLocalPtr, 45f22ef01cSRoman Divacky "Number of fully cached non-local ptr responses"); 46f22ef01cSRoman Divacky STATISTIC(NumCacheDirtyNonLocalPtr, 47f22ef01cSRoman Divacky "Number of cached, but dirty, non-local ptr responses"); 48f22ef01cSRoman Divacky STATISTIC(NumUncacheNonLocalPtr, 49f22ef01cSRoman Divacky "Number of uncached non-local ptr responses"); 50f22ef01cSRoman Divacky STATISTIC(NumCacheCompleteNonLocalPtr, 51f22ef01cSRoman Divacky "Number of block queries that were completely cached"); 52f22ef01cSRoman Divacky 5317a519f9SDimitry Andric // Limit for the number of instructions to scan in a block. 547d523365SDimitry Andric 557d523365SDimitry Andric static cl::opt<unsigned> BlockScanLimit( 567d523365SDimitry Andric "memdep-block-scan-limit", cl::Hidden, cl::init(100), 577d523365SDimitry Andric cl::desc("The number of instructions to scan in a block in memory " 587d523365SDimitry Andric "dependency analysis (default = 100)")); 5939d628a0SDimitry Andric 6039d628a0SDimitry Andric // Limit on the number of memdep results to process. 6139d628a0SDimitry Andric static const unsigned int NumResultsLimit = 100; 6217a519f9SDimitry Andric 63f22ef01cSRoman Divacky char MemoryDependenceAnalysis::ID = 0; 64f22ef01cSRoman Divacky 65f22ef01cSRoman Divacky // Register this pass... 662754fe60SDimitry Andric INITIALIZE_PASS_BEGIN(MemoryDependenceAnalysis, "memdep", 672754fe60SDimitry Andric "Memory Dependence Analysis", false, true) 6839d628a0SDimitry Andric INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 697d523365SDimitry Andric INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) 707d523365SDimitry Andric INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 712754fe60SDimitry Andric INITIALIZE_PASS_END(MemoryDependenceAnalysis, "memdep", 722754fe60SDimitry Andric "Memory Dependence Analysis", false, true) 73f22ef01cSRoman Divacky 74f22ef01cSRoman Divacky MemoryDependenceAnalysis::MemoryDependenceAnalysis() 75ff0cc061SDimitry Andric : FunctionPass(ID) { 762754fe60SDimitry Andric initializeMemoryDependenceAnalysisPass(*PassRegistry::getPassRegistry()); 77f22ef01cSRoman Divacky } 78f22ef01cSRoman Divacky MemoryDependenceAnalysis::~MemoryDependenceAnalysis() { 79f22ef01cSRoman Divacky } 80f22ef01cSRoman Divacky 81f22ef01cSRoman Divacky /// Clean up memory in between runs 82f22ef01cSRoman Divacky void MemoryDependenceAnalysis::releaseMemory() { 83f22ef01cSRoman Divacky LocalDeps.clear(); 84f22ef01cSRoman Divacky NonLocalDeps.clear(); 85f22ef01cSRoman Divacky NonLocalPointerDeps.clear(); 86f22ef01cSRoman Divacky ReverseLocalDeps.clear(); 87f22ef01cSRoman Divacky ReverseNonLocalDeps.clear(); 88f22ef01cSRoman Divacky ReverseNonLocalPtrDeps.clear(); 89ff0cc061SDimitry Andric PredCache.clear(); 90f22ef01cSRoman Divacky } 91f22ef01cSRoman Divacky 92f22ef01cSRoman Divacky /// getAnalysisUsage - Does not modify anything. It uses Alias Analysis. 93f22ef01cSRoman Divacky /// 94f22ef01cSRoman Divacky void MemoryDependenceAnalysis::getAnalysisUsage(AnalysisUsage &AU) const { 95f22ef01cSRoman Divacky AU.setPreservesAll(); 9639d628a0SDimitry Andric AU.addRequired<AssumptionCacheTracker>(); 977d523365SDimitry Andric AU.addRequiredTransitive<AAResultsWrapperPass>(); 987d523365SDimitry Andric AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>(); 99f22ef01cSRoman Divacky } 100f22ef01cSRoman Divacky 10139d628a0SDimitry Andric bool MemoryDependenceAnalysis::runOnFunction(Function &F) { 1027d523365SDimitry Andric AA = &getAnalysis<AAResultsWrapperPass>().getAAResults(); 10339d628a0SDimitry Andric AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F); 10491bc56edSDimitry Andric DominatorTreeWrapperPass *DTWP = 10591bc56edSDimitry Andric getAnalysisIfAvailable<DominatorTreeWrapperPass>(); 10691bc56edSDimitry Andric DT = DTWP ? &DTWP->getDomTree() : nullptr; 1077d523365SDimitry Andric TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(); 108f22ef01cSRoman Divacky return false; 109f22ef01cSRoman Divacky } 110f22ef01cSRoman Divacky 111f22ef01cSRoman Divacky /// RemoveFromReverseMap - This is a helper function that removes Val from 112f22ef01cSRoman Divacky /// 'Inst's set in ReverseMap. If the set becomes empty, remove Inst's entry. 113f22ef01cSRoman Divacky template <typename KeyTy> 114f22ef01cSRoman Divacky static void RemoveFromReverseMap(DenseMap<Instruction*, 115f22ef01cSRoman Divacky SmallPtrSet<KeyTy, 4> > &ReverseMap, 116f22ef01cSRoman Divacky Instruction *Inst, KeyTy Val) { 117f22ef01cSRoman Divacky typename DenseMap<Instruction*, SmallPtrSet<KeyTy, 4> >::iterator 118f22ef01cSRoman Divacky InstIt = ReverseMap.find(Inst); 119f22ef01cSRoman Divacky assert(InstIt != ReverseMap.end() && "Reverse map out of sync?"); 120f22ef01cSRoman Divacky bool Found = InstIt->second.erase(Val); 1212754fe60SDimitry Andric assert(Found && "Invalid reverse map!"); (void)Found; 122f22ef01cSRoman Divacky if (InstIt->second.empty()) 123f22ef01cSRoman Divacky ReverseMap.erase(InstIt); 124f22ef01cSRoman Divacky } 125f22ef01cSRoman Divacky 1262754fe60SDimitry Andric /// GetLocation - If the given instruction references a specific memory 1272754fe60SDimitry Andric /// location, fill in Loc with the details, otherwise set Loc.Ptr to null. 1282754fe60SDimitry Andric /// Return a ModRefInfo value describing the general behavior of the 1292754fe60SDimitry Andric /// instruction. 1307d523365SDimitry Andric static ModRefInfo GetLocation(const Instruction *Inst, MemoryLocation &Loc, 1317d523365SDimitry Andric const TargetLibraryInfo &TLI) { 1322754fe60SDimitry Andric if (const LoadInst *LI = dyn_cast<LoadInst>(Inst)) { 1336122f3e6SDimitry Andric if (LI->isUnordered()) { 13497bc6c73SDimitry Andric Loc = MemoryLocation::get(LI); 1357d523365SDimitry Andric return MRI_Ref; 136139f7f9bSDimitry Andric } 137139f7f9bSDimitry Andric if (LI->getOrdering() == Monotonic) { 13897bc6c73SDimitry Andric Loc = MemoryLocation::get(LI); 1397d523365SDimitry Andric return MRI_ModRef; 1406122f3e6SDimitry Andric } 1418f0fd8f6SDimitry Andric Loc = MemoryLocation(); 1427d523365SDimitry Andric return MRI_ModRef; 1432754fe60SDimitry Andric } 1442754fe60SDimitry Andric 1452754fe60SDimitry Andric if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) { 1466122f3e6SDimitry Andric if (SI->isUnordered()) { 14797bc6c73SDimitry Andric Loc = MemoryLocation::get(SI); 1487d523365SDimitry Andric return MRI_Mod; 149139f7f9bSDimitry Andric } 150139f7f9bSDimitry Andric if (SI->getOrdering() == Monotonic) { 15197bc6c73SDimitry Andric Loc = MemoryLocation::get(SI); 1527d523365SDimitry Andric return MRI_ModRef; 1536122f3e6SDimitry Andric } 1548f0fd8f6SDimitry Andric Loc = MemoryLocation(); 1557d523365SDimitry Andric return MRI_ModRef; 1562754fe60SDimitry Andric } 1572754fe60SDimitry Andric 1582754fe60SDimitry Andric if (const VAArgInst *V = dyn_cast<VAArgInst>(Inst)) { 15997bc6c73SDimitry Andric Loc = MemoryLocation::get(V); 1607d523365SDimitry Andric return MRI_ModRef; 1612754fe60SDimitry Andric } 1622754fe60SDimitry Andric 1637d523365SDimitry Andric if (const CallInst *CI = isFreeCall(Inst, &TLI)) { 1642754fe60SDimitry Andric // calls to free() deallocate the entire structure 1658f0fd8f6SDimitry Andric Loc = MemoryLocation(CI->getArgOperand(0)); 1667d523365SDimitry Andric return MRI_Mod; 1672754fe60SDimitry Andric } 1682754fe60SDimitry Andric 16939d628a0SDimitry Andric if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) { 17039d628a0SDimitry Andric AAMDNodes AAInfo; 17139d628a0SDimitry Andric 1722754fe60SDimitry Andric switch (II->getIntrinsicID()) { 1732754fe60SDimitry Andric case Intrinsic::lifetime_start: 1742754fe60SDimitry Andric case Intrinsic::lifetime_end: 1752754fe60SDimitry Andric case Intrinsic::invariant_start: 17639d628a0SDimitry Andric II->getAAMetadata(AAInfo); 1778f0fd8f6SDimitry Andric Loc = MemoryLocation( 1788f0fd8f6SDimitry Andric II->getArgOperand(1), 1798f0fd8f6SDimitry Andric cast<ConstantInt>(II->getArgOperand(0))->getZExtValue(), AAInfo); 1802754fe60SDimitry Andric // These intrinsics don't really modify the memory, but returning Mod 1812754fe60SDimitry Andric // will allow them to be handled conservatively. 1827d523365SDimitry Andric return MRI_Mod; 1832754fe60SDimitry Andric case Intrinsic::invariant_end: 18439d628a0SDimitry Andric II->getAAMetadata(AAInfo); 1858f0fd8f6SDimitry Andric Loc = MemoryLocation( 1868f0fd8f6SDimitry Andric II->getArgOperand(2), 1878f0fd8f6SDimitry Andric cast<ConstantInt>(II->getArgOperand(1))->getZExtValue(), AAInfo); 1882754fe60SDimitry Andric // These intrinsics don't really modify the memory, but returning Mod 1892754fe60SDimitry Andric // will allow them to be handled conservatively. 1907d523365SDimitry Andric return MRI_Mod; 1912754fe60SDimitry Andric default: 1922754fe60SDimitry Andric break; 1932754fe60SDimitry Andric } 19439d628a0SDimitry Andric } 1952754fe60SDimitry Andric 1962754fe60SDimitry Andric // Otherwise, just do the coarse-grained thing that always works. 1972754fe60SDimitry Andric if (Inst->mayWriteToMemory()) 1987d523365SDimitry Andric return MRI_ModRef; 1992754fe60SDimitry Andric if (Inst->mayReadFromMemory()) 2007d523365SDimitry Andric return MRI_Ref; 2017d523365SDimitry Andric return MRI_NoModRef; 2022754fe60SDimitry Andric } 203f22ef01cSRoman Divacky 204f22ef01cSRoman Divacky /// getCallSiteDependencyFrom - Private helper for finding the local 205f22ef01cSRoman Divacky /// dependencies of a call site. 206f22ef01cSRoman Divacky MemDepResult MemoryDependenceAnalysis:: 207f22ef01cSRoman Divacky getCallSiteDependencyFrom(CallSite CS, bool isReadOnlyCall, 208f22ef01cSRoman Divacky BasicBlock::iterator ScanIt, BasicBlock *BB) { 20917a519f9SDimitry Andric unsigned Limit = BlockScanLimit; 21017a519f9SDimitry Andric 211f22ef01cSRoman Divacky // Walk backwards through the block, looking for dependencies 212f22ef01cSRoman Divacky while (ScanIt != BB->begin()) { 21317a519f9SDimitry Andric // Limit the amount of scanning we do so we don't end up with quadratic 21417a519f9SDimitry Andric // running time on extreme testcases. 21517a519f9SDimitry Andric --Limit; 21617a519f9SDimitry Andric if (!Limit) 21717a519f9SDimitry Andric return MemDepResult::getUnknown(); 21817a519f9SDimitry Andric 2197d523365SDimitry Andric Instruction *Inst = &*--ScanIt; 220f22ef01cSRoman Divacky 221f22ef01cSRoman Divacky // If this inst is a memory op, get the pointer it accessed 2228f0fd8f6SDimitry Andric MemoryLocation Loc; 2237d523365SDimitry Andric ModRefInfo MR = GetLocation(Inst, Loc, *TLI); 2242754fe60SDimitry Andric if (Loc.Ptr) { 2252754fe60SDimitry Andric // A simple instruction. 2267d523365SDimitry Andric if (AA->getModRefInfo(CS, Loc) != MRI_NoModRef) 2272754fe60SDimitry Andric return MemDepResult::getClobber(Inst); 2282754fe60SDimitry Andric continue; 2292754fe60SDimitry Andric } 2302754fe60SDimitry Andric 231ff0cc061SDimitry Andric if (auto InstCS = CallSite(Inst)) { 232f22ef01cSRoman Divacky // Debug intrinsics don't cause dependences. 233f22ef01cSRoman Divacky if (isa<DbgInfoIntrinsic>(Inst)) continue; 234f22ef01cSRoman Divacky // If these two calls do not interfere, look past it. 235f22ef01cSRoman Divacky switch (AA->getModRefInfo(CS, InstCS)) { 2367d523365SDimitry Andric case MRI_NoModRef: 237e580952dSDimitry Andric // If the two calls are the same, return InstCS as a Def, so that 238e580952dSDimitry Andric // CS can be found redundant and eliminated. 2397d523365SDimitry Andric if (isReadOnlyCall && !(MR & MRI_Mod) && 240e580952dSDimitry Andric CS.getInstruction()->isIdenticalToWhenDefined(Inst)) 241f22ef01cSRoman Divacky return MemDepResult::getDef(Inst); 242e580952dSDimitry Andric 243e580952dSDimitry Andric // Otherwise if the two calls don't interact (e.g. InstCS is readnone) 244e580952dSDimitry Andric // keep scanning. 2457ae0e2c9SDimitry Andric continue; 246f22ef01cSRoman Divacky default: 247f22ef01cSRoman Divacky return MemDepResult::getClobber(Inst); 248f22ef01cSRoman Divacky } 249f22ef01cSRoman Divacky } 2507ae0e2c9SDimitry Andric 2517ae0e2c9SDimitry Andric // If we could not obtain a pointer for the instruction and the instruction 2527ae0e2c9SDimitry Andric // touches memory then assume that this is a dependency. 2537d523365SDimitry Andric if (MR != MRI_NoModRef) 2547ae0e2c9SDimitry Andric return MemDepResult::getClobber(Inst); 255f22ef01cSRoman Divacky } 256f22ef01cSRoman Divacky 25717a519f9SDimitry Andric // No dependence found. If this is the entry block of the function, it is 25817a519f9SDimitry Andric // unknown, otherwise it is non-local. 259f22ef01cSRoman Divacky if (BB != &BB->getParent()->getEntryBlock()) 260f22ef01cSRoman Divacky return MemDepResult::getNonLocal(); 2616122f3e6SDimitry Andric return MemDepResult::getNonFuncLocal(); 262f22ef01cSRoman Divacky } 263f22ef01cSRoman Divacky 2643b0f4066SDimitry Andric /// isLoadLoadClobberIfExtendedToFullWidth - Return true if LI is a load that 2653b0f4066SDimitry Andric /// would fully overlap MemLoc if done as a wider legal integer load. 2663b0f4066SDimitry Andric /// 2673b0f4066SDimitry Andric /// MemLocBase, MemLocOffset are lazily computed here the first time the 2683b0f4066SDimitry Andric /// base/offs of memloc is needed. 2698f0fd8f6SDimitry Andric static bool isLoadLoadClobberIfExtendedToFullWidth(const MemoryLocation &MemLoc, 2708f0fd8f6SDimitry Andric const Value *&MemLocBase, 2718f0fd8f6SDimitry Andric int64_t &MemLocOffs, 2728f0fd8f6SDimitry Andric const LoadInst *LI) { 273ff0cc061SDimitry Andric const DataLayout &DL = LI->getModule()->getDataLayout(); 2743b0f4066SDimitry Andric 2753b0f4066SDimitry Andric // If we haven't already computed the base/offset of MemLoc, do so now. 27691bc56edSDimitry Andric if (!MemLocBase) 27791bc56edSDimitry Andric MemLocBase = GetPointerBaseWithConstantOffset(MemLoc.Ptr, MemLocOffs, DL); 2783b0f4066SDimitry Andric 279ff0cc061SDimitry Andric unsigned Size = MemoryDependenceAnalysis::getLoadLoadClobberFullWidthSize( 280ff0cc061SDimitry Andric MemLocBase, MemLocOffs, MemLoc.Size, LI); 2813b0f4066SDimitry Andric return Size != 0; 2823b0f4066SDimitry Andric } 2833b0f4066SDimitry Andric 2843b0f4066SDimitry Andric /// getLoadLoadClobberFullWidthSize - This is a little bit of analysis that 2853b0f4066SDimitry Andric /// looks at a memory location for a load (specified by MemLocBase, Offs, 2863b0f4066SDimitry Andric /// and Size) and compares it against a load. If the specified load could 2873b0f4066SDimitry Andric /// be safely widened to a larger integer load that is 1) still efficient, 2883b0f4066SDimitry Andric /// 2) safe for the target, and 3) would provide the specified memory 2893b0f4066SDimitry Andric /// location value, then this function returns the size in bytes of the 2903b0f4066SDimitry Andric /// load width to use. If not, this returns zero. 291ff0cc061SDimitry Andric unsigned MemoryDependenceAnalysis::getLoadLoadClobberFullWidthSize( 292ff0cc061SDimitry Andric const Value *MemLocBase, int64_t MemLocOffs, unsigned MemLocSize, 293ff0cc061SDimitry Andric const LoadInst *LI) { 2946122f3e6SDimitry Andric // We can only extend simple integer loads. 2956122f3e6SDimitry Andric if (!isa<IntegerType>(LI->getType()) || !LI->isSimple()) return 0; 2963b0f4066SDimitry Andric 297139f7f9bSDimitry Andric // Load widening is hostile to ThreadSanitizer: it may cause false positives 298139f7f9bSDimitry Andric // or make the reports more cryptic (access sizes are wrong). 299ff0cc061SDimitry Andric if (LI->getParent()->getParent()->hasFnAttribute(Attribute::SanitizeThread)) 300139f7f9bSDimitry Andric return 0; 301139f7f9bSDimitry Andric 302ff0cc061SDimitry Andric const DataLayout &DL = LI->getModule()->getDataLayout(); 303ff0cc061SDimitry Andric 3043b0f4066SDimitry Andric // Get the base of this load. 3053b0f4066SDimitry Andric int64_t LIOffs = 0; 3063b0f4066SDimitry Andric const Value *LIBase = 307ff0cc061SDimitry Andric GetPointerBaseWithConstantOffset(LI->getPointerOperand(), LIOffs, DL); 3083b0f4066SDimitry Andric 3093b0f4066SDimitry Andric // If the two pointers are not based on the same pointer, we can't tell that 3103b0f4066SDimitry Andric // they are related. 3113b0f4066SDimitry Andric if (LIBase != MemLocBase) return 0; 3123b0f4066SDimitry Andric 3133b0f4066SDimitry Andric // Okay, the two values are based on the same pointer, but returned as 3143b0f4066SDimitry Andric // no-alias. This happens when we have things like two byte loads at "P+1" 3153b0f4066SDimitry Andric // and "P+3". Check to see if increasing the size of the "LI" load up to its 3163b0f4066SDimitry Andric // alignment (or the largest native integer type) will allow us to load all 3173b0f4066SDimitry Andric // the bits required by MemLoc. 3183b0f4066SDimitry Andric 3193b0f4066SDimitry Andric // If MemLoc is before LI, then no widening of LI will help us out. 3203b0f4066SDimitry Andric if (MemLocOffs < LIOffs) return 0; 3213b0f4066SDimitry Andric 3223b0f4066SDimitry Andric // Get the alignment of the load in bytes. We assume that it is safe to load 3233b0f4066SDimitry Andric // any legal integer up to this size without a problem. For example, if we're 3243b0f4066SDimitry Andric // looking at an i8 load on x86-32 that is known 1024 byte aligned, we can 3253b0f4066SDimitry Andric // widen it up to an i32 load. If it is known 2-byte aligned, we can widen it 3263b0f4066SDimitry Andric // to i16. 3273b0f4066SDimitry Andric unsigned LoadAlign = LI->getAlignment(); 3283b0f4066SDimitry Andric 3293b0f4066SDimitry Andric int64_t MemLocEnd = MemLocOffs+MemLocSize; 3303b0f4066SDimitry Andric 3313b0f4066SDimitry Andric // If no amount of rounding up will let MemLoc fit into LI, then bail out. 3323b0f4066SDimitry Andric if (LIOffs+LoadAlign < MemLocEnd) return 0; 3333b0f4066SDimitry Andric 3343b0f4066SDimitry Andric // This is the size of the load to try. Start with the next larger power of 3353b0f4066SDimitry Andric // two. 3363b0f4066SDimitry Andric unsigned NewLoadByteSize = LI->getType()->getPrimitiveSizeInBits()/8U; 3373b0f4066SDimitry Andric NewLoadByteSize = NextPowerOf2(NewLoadByteSize); 3383b0f4066SDimitry Andric 3393b0f4066SDimitry Andric while (1) { 3403b0f4066SDimitry Andric // If this load size is bigger than our known alignment or would not fit 3413b0f4066SDimitry Andric // into a native integer register, then we fail. 3423b0f4066SDimitry Andric if (NewLoadByteSize > LoadAlign || 34391bc56edSDimitry Andric !DL.fitsInLegalInteger(NewLoadByteSize*8)) 3443b0f4066SDimitry Andric return 0; 3453b0f4066SDimitry Andric 346dff0c46cSDimitry Andric if (LIOffs + NewLoadByteSize > MemLocEnd && 347ff0cc061SDimitry Andric LI->getParent()->getParent()->hasFnAttribute( 348ff0cc061SDimitry Andric Attribute::SanitizeAddress)) 349dff0c46cSDimitry Andric // We will be reading past the location accessed by the original program. 350dff0c46cSDimitry Andric // While this is safe in a regular build, Address Safety analysis tools 351dff0c46cSDimitry Andric // may start reporting false warnings. So, don't do widening. 352dff0c46cSDimitry Andric return 0; 353dff0c46cSDimitry Andric 3543b0f4066SDimitry Andric // If a load of this width would include all of MemLoc, then we succeed. 3553b0f4066SDimitry Andric if (LIOffs+NewLoadByteSize >= MemLocEnd) 3563b0f4066SDimitry Andric return NewLoadByteSize; 3573b0f4066SDimitry Andric 3583b0f4066SDimitry Andric NewLoadByteSize <<= 1; 3593b0f4066SDimitry Andric } 360dff0c46cSDimitry Andric } 3613b0f4066SDimitry Andric 362ff0cc061SDimitry Andric static bool isVolatile(Instruction *Inst) { 363ff0cc061SDimitry Andric if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) 364ff0cc061SDimitry Andric return LI->isVolatile(); 365ff0cc061SDimitry Andric else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) 366ff0cc061SDimitry Andric return SI->isVolatile(); 367ff0cc061SDimitry Andric else if (AtomicCmpXchgInst *AI = dyn_cast<AtomicCmpXchgInst>(Inst)) 368ff0cc061SDimitry Andric return AI->isVolatile(); 369ff0cc061SDimitry Andric return false; 370ff0cc061SDimitry Andric } 371ff0cc061SDimitry Andric 372ff0cc061SDimitry Andric 373f22ef01cSRoman Divacky /// getPointerDependencyFrom - Return the instruction on which a memory 3742754fe60SDimitry Andric /// location depends. If isLoad is true, this routine ignores may-aliases with 3752754fe60SDimitry Andric /// read-only operations. If isLoad is false, this routine ignores may-aliases 376139f7f9bSDimitry Andric /// with reads from read-only locations. If possible, pass the query 377139f7f9bSDimitry Andric /// instruction as well; this function may take advantage of the metadata 378139f7f9bSDimitry Andric /// annotated to the query instruction to refine the result. 3798f0fd8f6SDimitry Andric MemDepResult MemoryDependenceAnalysis::getPointerDependencyFrom( 3808f0fd8f6SDimitry Andric const MemoryLocation &MemLoc, bool isLoad, BasicBlock::iterator ScanIt, 3818f0fd8f6SDimitry Andric BasicBlock *BB, Instruction *QueryInst) { 382f22ef01cSRoman Divacky 3837d523365SDimitry Andric if (QueryInst != nullptr) { 3847d523365SDimitry Andric if (auto *LI = dyn_cast<LoadInst>(QueryInst)) { 3857d523365SDimitry Andric MemDepResult invariantGroupDependency = 3867d523365SDimitry Andric getInvariantGroupPointerDependency(LI, BB); 3877d523365SDimitry Andric 3887d523365SDimitry Andric if (invariantGroupDependency.isDef()) 3897d523365SDimitry Andric return invariantGroupDependency; 3907d523365SDimitry Andric } 3917d523365SDimitry Andric } 3927d523365SDimitry Andric return getSimplePointerDependencyFrom(MemLoc, isLoad, ScanIt, BB, QueryInst); 3937d523365SDimitry Andric } 3947d523365SDimitry Andric 3957d523365SDimitry Andric MemDepResult 3967d523365SDimitry Andric MemoryDependenceAnalysis::getInvariantGroupPointerDependency(LoadInst *LI, 3977d523365SDimitry Andric BasicBlock *BB) { 3987d523365SDimitry Andric Value *LoadOperand = LI->getPointerOperand(); 3997d523365SDimitry Andric // It's is not safe to walk the use list of global value, because function 4007d523365SDimitry Andric // passes aren't allowed to look outside their functions. 4017d523365SDimitry Andric if (isa<GlobalValue>(LoadOperand)) 4027d523365SDimitry Andric return MemDepResult::getUnknown(); 4037d523365SDimitry Andric 4047d523365SDimitry Andric auto *InvariantGroupMD = LI->getMetadata(LLVMContext::MD_invariant_group); 4057d523365SDimitry Andric if (!InvariantGroupMD) 4067d523365SDimitry Andric return MemDepResult::getUnknown(); 4077d523365SDimitry Andric 4087d523365SDimitry Andric MemDepResult Result = MemDepResult::getUnknown(); 4097d523365SDimitry Andric llvm::SmallSet<Value *, 14> Seen; 4107d523365SDimitry Andric // Queue to process all pointers that are equivalent to load operand. 4117d523365SDimitry Andric llvm::SmallVector<Value *, 8> LoadOperandsQueue; 4127d523365SDimitry Andric LoadOperandsQueue.push_back(LoadOperand); 4137d523365SDimitry Andric while (!LoadOperandsQueue.empty()) { 4147d523365SDimitry Andric Value *Ptr = LoadOperandsQueue.pop_back_val(); 4157d523365SDimitry Andric if (isa<GlobalValue>(Ptr)) 4167d523365SDimitry Andric continue; 4177d523365SDimitry Andric 4187d523365SDimitry Andric if (auto *BCI = dyn_cast<BitCastInst>(Ptr)) { 4197d523365SDimitry Andric if (!Seen.count(BCI->getOperand(0))) { 4207d523365SDimitry Andric LoadOperandsQueue.push_back(BCI->getOperand(0)); 4217d523365SDimitry Andric Seen.insert(BCI->getOperand(0)); 4227d523365SDimitry Andric } 4237d523365SDimitry Andric } 4247d523365SDimitry Andric 4257d523365SDimitry Andric for (Use &Us : Ptr->uses()) { 4267d523365SDimitry Andric auto *U = dyn_cast<Instruction>(Us.getUser()); 4277d523365SDimitry Andric if (!U || U == LI || !DT->dominates(U, LI)) 4287d523365SDimitry Andric continue; 4297d523365SDimitry Andric 4307d523365SDimitry Andric if (auto *BCI = dyn_cast<BitCastInst>(U)) { 4317d523365SDimitry Andric if (!Seen.count(BCI)) { 4327d523365SDimitry Andric LoadOperandsQueue.push_back(BCI); 4337d523365SDimitry Andric Seen.insert(BCI); 4347d523365SDimitry Andric } 4357d523365SDimitry Andric continue; 4367d523365SDimitry Andric } 4377d523365SDimitry Andric // If we hit load/store with the same invariant.group metadata (and the 4387d523365SDimitry Andric // same pointer operand) we can assume that value pointed by pointer 4397d523365SDimitry Andric // operand didn't change. 4407d523365SDimitry Andric if ((isa<LoadInst>(U) || isa<StoreInst>(U)) && U->getParent() == BB && 4417d523365SDimitry Andric U->getMetadata(LLVMContext::MD_invariant_group) == InvariantGroupMD) 4427d523365SDimitry Andric return MemDepResult::getDef(U); 4437d523365SDimitry Andric } 4447d523365SDimitry Andric } 4457d523365SDimitry Andric return Result; 4467d523365SDimitry Andric } 4477d523365SDimitry Andric 4487d523365SDimitry Andric MemDepResult MemoryDependenceAnalysis::getSimplePointerDependencyFrom( 4497d523365SDimitry Andric const MemoryLocation &MemLoc, bool isLoad, BasicBlock::iterator ScanIt, 4507d523365SDimitry Andric BasicBlock *BB, Instruction *QueryInst) { 4517d523365SDimitry Andric 45291bc56edSDimitry Andric const Value *MemLocBase = nullptr; 4533b0f4066SDimitry Andric int64_t MemLocOffset = 0; 45417a519f9SDimitry Andric unsigned Limit = BlockScanLimit; 455139f7f9bSDimitry Andric bool isInvariantLoad = false; 45639d628a0SDimitry Andric 45739d628a0SDimitry Andric // We must be careful with atomic accesses, as they may allow another thread 45839d628a0SDimitry Andric // to touch this location, cloberring it. We are conservative: if the 45939d628a0SDimitry Andric // QueryInst is not a simple (non-atomic) memory access, we automatically 46039d628a0SDimitry Andric // return getClobber. 46139d628a0SDimitry Andric // If it is simple, we know based on the results of 46239d628a0SDimitry Andric // "Compiler testing via a theory of sound optimisations in the C11/C++11 46339d628a0SDimitry Andric // memory model" in PLDI 2013, that a non-atomic location can only be 46439d628a0SDimitry Andric // clobbered between a pair of a release and an acquire action, with no 46539d628a0SDimitry Andric // access to the location in between. 46639d628a0SDimitry Andric // Here is an example for giving the general intuition behind this rule. 46739d628a0SDimitry Andric // In the following code: 46839d628a0SDimitry Andric // store x 0; 46939d628a0SDimitry Andric // release action; [1] 47039d628a0SDimitry Andric // acquire action; [4] 47139d628a0SDimitry Andric // %val = load x; 47239d628a0SDimitry Andric // It is unsafe to replace %val by 0 because another thread may be running: 47339d628a0SDimitry Andric // acquire action; [2] 47439d628a0SDimitry Andric // store x 42; 47539d628a0SDimitry Andric // release action; [3] 47639d628a0SDimitry Andric // with synchronization from 1 to 2 and from 3 to 4, resulting in %val 47739d628a0SDimitry Andric // being 42. A key property of this program however is that if either 47839d628a0SDimitry Andric // 1 or 4 were missing, there would be a race between the store of 42 47939d628a0SDimitry Andric // either the store of 0 or the load (making the whole progam racy). 4804d0b32cdSDimitry Andric // The paper mentioned above shows that the same property is respected 48139d628a0SDimitry Andric // by every program that can detect any optimisation of that kind: either 48239d628a0SDimitry Andric // it is racy (undefined) or there is a release followed by an acquire 48339d628a0SDimitry Andric // between the pair of accesses under consideration. 48439d628a0SDimitry Andric 485ff0cc061SDimitry Andric // If the load is invariant, we "know" that it doesn't alias *any* write. We 486ff0cc061SDimitry Andric // do want to respect mustalias results since defs are useful for value 487ff0cc061SDimitry Andric // forwarding, but any mayalias write can be assumed to be noalias. 488ff0cc061SDimitry Andric // Arguably, this logic should be pushed inside AliasAnalysis itself. 489139f7f9bSDimitry Andric if (isLoad && QueryInst) { 490139f7f9bSDimitry Andric LoadInst *LI = dyn_cast<LoadInst>(QueryInst); 49191bc56edSDimitry Andric if (LI && LI->getMetadata(LLVMContext::MD_invariant_load) != nullptr) 492139f7f9bSDimitry Andric isInvariantLoad = true; 493139f7f9bSDimitry Andric } 49417a519f9SDimitry Andric 495ff0cc061SDimitry Andric const DataLayout &DL = BB->getModule()->getDataLayout(); 496ff0cc061SDimitry Andric 4977d523365SDimitry Andric // Create a numbered basic block to lazily compute and cache instruction 4987d523365SDimitry Andric // positions inside a BB. This is used to provide fast queries for relative 4997d523365SDimitry Andric // position between two instructions in a BB and can be used by 5007d523365SDimitry Andric // AliasAnalysis::callCapturesBefore. 5017d523365SDimitry Andric OrderedBasicBlock OBB(BB); 5027d523365SDimitry Andric 503f22ef01cSRoman Divacky // Walk backwards through the basic block, looking for dependencies. 504f22ef01cSRoman Divacky while (ScanIt != BB->begin()) { 5057d523365SDimitry Andric Instruction *Inst = &*--ScanIt; 506f785676fSDimitry Andric 507f785676fSDimitry Andric if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) 508f785676fSDimitry Andric // Debug intrinsics don't (and can't) cause dependencies. 509f785676fSDimitry Andric if (isa<DbgInfoIntrinsic>(II)) continue; 510f785676fSDimitry Andric 51117a519f9SDimitry Andric // Limit the amount of scanning we do so we don't end up with quadratic 51217a519f9SDimitry Andric // running time on extreme testcases. 51317a519f9SDimitry Andric --Limit; 51417a519f9SDimitry Andric if (!Limit) 51517a519f9SDimitry Andric return MemDepResult::getUnknown(); 51617a519f9SDimitry Andric 517f22ef01cSRoman Divacky if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) { 518f22ef01cSRoman Divacky // If we reach a lifetime begin or end marker, then the query ends here 519f22ef01cSRoman Divacky // because the value is undefined. 5202754fe60SDimitry Andric if (II->getIntrinsicID() == Intrinsic::lifetime_start) { 521f22ef01cSRoman Divacky // FIXME: This only considers queries directly on the invariant-tagged 522f22ef01cSRoman Divacky // pointer, not on query pointers that are indexed off of them. It'd 5233b0f4066SDimitry Andric // be nice to handle that at some point (the right approach is to use 5243b0f4066SDimitry Andric // GetPointerBaseWithConstantOffset). 5258f0fd8f6SDimitry Andric if (AA->isMustAlias(MemoryLocation(II->getArgOperand(1)), MemLoc)) 526f22ef01cSRoman Divacky return MemDepResult::getDef(II); 5272754fe60SDimitry Andric continue; 528f22ef01cSRoman Divacky } 529f22ef01cSRoman Divacky } 530f22ef01cSRoman Divacky 531f22ef01cSRoman Divacky // Values depend on loads if the pointers are must aliased. This means that 532f22ef01cSRoman Divacky // a load depends on another must aliased load from the same value. 53339d628a0SDimitry Andric // One exception is atomic loads: a value can depend on an atomic load that it 53439d628a0SDimitry Andric // does not alias with when this atomic load indicates that another thread may 53539d628a0SDimitry Andric // be accessing the location. 536f22ef01cSRoman Divacky if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) { 537ff0cc061SDimitry Andric 538ff0cc061SDimitry Andric // While volatile access cannot be eliminated, they do not have to clobber 539ff0cc061SDimitry Andric // non-aliasing locations, as normal accesses, for example, can be safely 540ff0cc061SDimitry Andric // reordered with volatile accesses. 541ff0cc061SDimitry Andric if (LI->isVolatile()) { 542ff0cc061SDimitry Andric if (!QueryInst) 543ff0cc061SDimitry Andric // Original QueryInst *may* be volatile 544ff0cc061SDimitry Andric return MemDepResult::getClobber(LI); 545ff0cc061SDimitry Andric if (isVolatile(QueryInst)) 546ff0cc061SDimitry Andric // Ordering required if QueryInst is itself volatile 547ff0cc061SDimitry Andric return MemDepResult::getClobber(LI); 548ff0cc061SDimitry Andric // Otherwise, volatile doesn't imply any special ordering 549ff0cc061SDimitry Andric } 550ff0cc061SDimitry Andric 5516122f3e6SDimitry Andric // Atomic loads have complications involved. 55239d628a0SDimitry Andric // A Monotonic (or higher) load is OK if the query inst is itself not atomic. 5536122f3e6SDimitry Andric // FIXME: This is overly conservative. 554ff0cc061SDimitry Andric if (LI->isAtomic() && LI->getOrdering() > Unordered) { 55539d628a0SDimitry Andric if (!QueryInst) 55639d628a0SDimitry Andric return MemDepResult::getClobber(LI); 557ff0cc061SDimitry Andric if (LI->getOrdering() != Monotonic) 558ff0cc061SDimitry Andric return MemDepResult::getClobber(LI); 55939d628a0SDimitry Andric if (auto *QueryLI = dyn_cast<LoadInst>(QueryInst)) { 56039d628a0SDimitry Andric if (!QueryLI->isSimple()) 56139d628a0SDimitry Andric return MemDepResult::getClobber(LI); 56239d628a0SDimitry Andric } else if (auto *QuerySI = dyn_cast<StoreInst>(QueryInst)) { 56339d628a0SDimitry Andric if (!QuerySI->isSimple()) 56439d628a0SDimitry Andric return MemDepResult::getClobber(LI); 56539d628a0SDimitry Andric } else if (QueryInst->mayReadOrWriteMemory()) { 56639d628a0SDimitry Andric return MemDepResult::getClobber(LI); 56739d628a0SDimitry Andric } 56839d628a0SDimitry Andric } 56939d628a0SDimitry Andric 5708f0fd8f6SDimitry Andric MemoryLocation LoadLoc = MemoryLocation::get(LI); 571f22ef01cSRoman Divacky 572f22ef01cSRoman Divacky // If we found a pointer, check if it could be the same as our pointer. 5733dac3a9bSDimitry Andric AliasResult R = AA->alias(LoadLoc, MemLoc); 5743b0f4066SDimitry Andric 5753b0f4066SDimitry Andric if (isLoad) { 5763dac3a9bSDimitry Andric if (R == NoAlias) { 5773b0f4066SDimitry Andric // If this is an over-aligned integer load (for example, 5783b0f4066SDimitry Andric // "load i8* %P, align 4") see if it would obviously overlap with the 5793b0f4066SDimitry Andric // queried location if widened to a larger load (e.g. if the queried 5803b0f4066SDimitry Andric // location is 1 byte at P+1). If so, return it as a load/load 5813b0f4066SDimitry Andric // clobber result, allowing the client to decide to widen the load if 5823b0f4066SDimitry Andric // it wants to. 583ff0cc061SDimitry Andric if (IntegerType *ITy = dyn_cast<IntegerType>(LI->getType())) { 5843b0f4066SDimitry Andric if (LI->getAlignment() * 8 > ITy->getPrimitiveSizeInBits() && 5853b0f4066SDimitry Andric isLoadLoadClobberIfExtendedToFullWidth(MemLoc, MemLocBase, 586ff0cc061SDimitry Andric MemLocOffset, LI)) 5873b0f4066SDimitry Andric return MemDepResult::getClobber(Inst); 588ff0cc061SDimitry Andric } 5893b0f4066SDimitry Andric continue; 5903b0f4066SDimitry Andric } 5913b0f4066SDimitry Andric 5923b0f4066SDimitry Andric // Must aliased loads are defs of each other. 5933dac3a9bSDimitry Andric if (R == MustAlias) 5943b0f4066SDimitry Andric return MemDepResult::getDef(Inst); 5953b0f4066SDimitry Andric 596bd5abe19SDimitry Andric #if 0 // FIXME: Temporarily disabled. GVN is cleverly rewriting loads 597bd5abe19SDimitry Andric // in terms of clobbering loads, but since it does this by looking 598bd5abe19SDimitry Andric // at the clobbering load directly, it doesn't know about any 599bd5abe19SDimitry Andric // phi translation that may have happened along the way. 600bd5abe19SDimitry Andric 6013b0f4066SDimitry Andric // If we have a partial alias, then return this as a clobber for the 6023b0f4066SDimitry Andric // client to handle. 6033dac3a9bSDimitry Andric if (R == PartialAlias) 6043b0f4066SDimitry Andric return MemDepResult::getClobber(Inst); 605bd5abe19SDimitry Andric #endif 6063b0f4066SDimitry Andric 6073b0f4066SDimitry Andric // Random may-alias loads don't depend on each other without a 6083b0f4066SDimitry Andric // dependence. 6093b0f4066SDimitry Andric continue; 6103b0f4066SDimitry Andric } 6113b0f4066SDimitry Andric 6123b0f4066SDimitry Andric // Stores don't depend on other no-aliased accesses. 6133dac3a9bSDimitry Andric if (R == NoAlias) 614f22ef01cSRoman Divacky continue; 615f22ef01cSRoman Divacky 6162754fe60SDimitry Andric // Stores don't alias loads from read-only memory. 6173b0f4066SDimitry Andric if (AA->pointsToConstantMemory(LoadLoc)) 6182754fe60SDimitry Andric continue; 6192754fe60SDimitry Andric 6203b0f4066SDimitry Andric // Stores depend on may/must aliased loads. 621f22ef01cSRoman Divacky return MemDepResult::getDef(Inst); 622f22ef01cSRoman Divacky } 623f22ef01cSRoman Divacky 624f22ef01cSRoman Divacky if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) { 6256122f3e6SDimitry Andric // Atomic stores have complications involved. 62639d628a0SDimitry Andric // A Monotonic store is OK if the query inst is itself not atomic. 6276122f3e6SDimitry Andric // FIXME: This is overly conservative. 62839d628a0SDimitry Andric if (!SI->isUnordered()) { 62939d628a0SDimitry Andric if (!QueryInst) 63039d628a0SDimitry Andric return MemDepResult::getClobber(SI); 631ff0cc061SDimitry Andric if (SI->getOrdering() != Monotonic) 632ff0cc061SDimitry Andric return MemDepResult::getClobber(SI); 63339d628a0SDimitry Andric if (auto *QueryLI = dyn_cast<LoadInst>(QueryInst)) { 63439d628a0SDimitry Andric if (!QueryLI->isSimple()) 63539d628a0SDimitry Andric return MemDepResult::getClobber(SI); 63639d628a0SDimitry Andric } else if (auto *QuerySI = dyn_cast<StoreInst>(QueryInst)) { 63739d628a0SDimitry Andric if (!QuerySI->isSimple()) 63839d628a0SDimitry Andric return MemDepResult::getClobber(SI); 63939d628a0SDimitry Andric } else if (QueryInst->mayReadOrWriteMemory()) { 64039d628a0SDimitry Andric return MemDepResult::getClobber(SI); 64139d628a0SDimitry Andric } 64239d628a0SDimitry Andric } 64339d628a0SDimitry Andric 64439d628a0SDimitry Andric // FIXME: this is overly conservative. 64539d628a0SDimitry Andric // While volatile access cannot be eliminated, they do not have to clobber 64639d628a0SDimitry Andric // non-aliasing locations, as normal accesses can for example be reordered 64739d628a0SDimitry Andric // with volatile accesses. 64839d628a0SDimitry Andric if (SI->isVolatile()) 6496122f3e6SDimitry Andric return MemDepResult::getClobber(SI); 6506122f3e6SDimitry Andric 651f22ef01cSRoman Divacky // If alias analysis can tell that this store is guaranteed to not modify 652f22ef01cSRoman Divacky // the query pointer, ignore it. Use getModRefInfo to handle cases where 653f22ef01cSRoman Divacky // the query pointer points to constant memory etc. 6547d523365SDimitry Andric if (AA->getModRefInfo(SI, MemLoc) == MRI_NoModRef) 655f22ef01cSRoman Divacky continue; 656f22ef01cSRoman Divacky 657f22ef01cSRoman Divacky // Ok, this store might clobber the query pointer. Check to see if it is 658f22ef01cSRoman Divacky // a must alias: in this case, we want to return this as a def. 6598f0fd8f6SDimitry Andric MemoryLocation StoreLoc = MemoryLocation::get(SI); 660f22ef01cSRoman Divacky 661f22ef01cSRoman Divacky // If we found a pointer, check if it could be the same as our pointer. 6623dac3a9bSDimitry Andric AliasResult R = AA->alias(StoreLoc, MemLoc); 663f22ef01cSRoman Divacky 6643dac3a9bSDimitry Andric if (R == NoAlias) 665f22ef01cSRoman Divacky continue; 6663dac3a9bSDimitry Andric if (R == MustAlias) 667f22ef01cSRoman Divacky return MemDepResult::getDef(Inst); 668139f7f9bSDimitry Andric if (isInvariantLoad) 669139f7f9bSDimitry Andric continue; 6702754fe60SDimitry Andric return MemDepResult::getClobber(Inst); 671f22ef01cSRoman Divacky } 672f22ef01cSRoman Divacky 673f22ef01cSRoman Divacky // If this is an allocation, and if we know that the accessed pointer is to 674f22ef01cSRoman Divacky // the allocation, return Def. This means that there is no dependence and 675f22ef01cSRoman Divacky // the access can be optimized based on that. For example, a load could 676f22ef01cSRoman Divacky // turn into undef. 677f22ef01cSRoman Divacky // Note: Only determine this to be a malloc if Inst is the malloc call, not 678f22ef01cSRoman Divacky // a subsequent bitcast of the malloc call result. There can be stores to 679f22ef01cSRoman Divacky // the malloced memory between the malloc call and its bitcast uses, and we 680f22ef01cSRoman Divacky // need to continue scanning until the malloc call. 6813861d79fSDimitry Andric if (isa<AllocaInst>(Inst) || isNoAliasFn(Inst, TLI)) { 68291bc56edSDimitry Andric const Value *AccessPtr = GetUnderlyingObject(MemLoc.Ptr, DL); 683f22ef01cSRoman Divacky 6843b0f4066SDimitry Andric if (AccessPtr == Inst || AA->isMustAlias(Inst, AccessPtr)) 685f22ef01cSRoman Divacky return MemDepResult::getDef(Inst); 686ff0cc061SDimitry Andric if (isInvariantLoad) 687ff0cc061SDimitry Andric continue; 6884d0b32cdSDimitry Andric // Be conservative if the accessed pointer may alias the allocation - 6894d0b32cdSDimitry Andric // fallback to the generic handling below. 6904d0b32cdSDimitry Andric if ((AA->alias(Inst, AccessPtr) == NoAlias) && 6913861d79fSDimitry Andric // If the allocation is not aliased and does not read memory (like 6923861d79fSDimitry Andric // strdup), it is safe to ignore. 6934d0b32cdSDimitry Andric (isa<AllocaInst>(Inst) || isMallocLikeFn(Inst, TLI) || 6944d0b32cdSDimitry Andric isCallocLikeFn(Inst, TLI))) 695f22ef01cSRoman Divacky continue; 696f22ef01cSRoman Divacky } 697f22ef01cSRoman Divacky 698ff0cc061SDimitry Andric if (isInvariantLoad) 699ff0cc061SDimitry Andric continue; 700ff0cc061SDimitry Andric 701f22ef01cSRoman Divacky // See if this instruction (e.g. a call or vaarg) mod/ref's the pointer. 7027d523365SDimitry Andric ModRefInfo MR = AA->getModRefInfo(Inst, MemLoc); 7037ae0e2c9SDimitry Andric // If necessary, perform additional analysis. 7047d523365SDimitry Andric if (MR == MRI_ModRef) 7057d523365SDimitry Andric MR = AA->callCapturesBefore(Inst, MemLoc, DT, &OBB); 7067ae0e2c9SDimitry Andric switch (MR) { 7077d523365SDimitry Andric case MRI_NoModRef: 708f22ef01cSRoman Divacky // If the call has no effect on the queried pointer, just ignore it. 709f22ef01cSRoman Divacky continue; 7107d523365SDimitry Andric case MRI_Mod: 711f22ef01cSRoman Divacky return MemDepResult::getClobber(Inst); 7127d523365SDimitry Andric case MRI_Ref: 713f22ef01cSRoman Divacky // If the call is known to never store to the pointer, and if this is a 714f22ef01cSRoman Divacky // load query, we can safely ignore it (scan past it). 715f22ef01cSRoman Divacky if (isLoad) 716f22ef01cSRoman Divacky continue; 717f22ef01cSRoman Divacky default: 718f22ef01cSRoman Divacky // Otherwise, there is a potential dependence. Return a clobber. 719f22ef01cSRoman Divacky return MemDepResult::getClobber(Inst); 720f22ef01cSRoman Divacky } 721f22ef01cSRoman Divacky } 722f22ef01cSRoman Divacky 72317a519f9SDimitry Andric // No dependence found. If this is the entry block of the function, it is 72417a519f9SDimitry Andric // unknown, otherwise it is non-local. 725f22ef01cSRoman Divacky if (BB != &BB->getParent()->getEntryBlock()) 726f22ef01cSRoman Divacky return MemDepResult::getNonLocal(); 7276122f3e6SDimitry Andric return MemDepResult::getNonFuncLocal(); 728f22ef01cSRoman Divacky } 729f22ef01cSRoman Divacky 730f22ef01cSRoman Divacky /// getDependency - Return the instruction on which a memory operation 731f22ef01cSRoman Divacky /// depends. 732f22ef01cSRoman Divacky MemDepResult MemoryDependenceAnalysis::getDependency(Instruction *QueryInst) { 733f22ef01cSRoman Divacky Instruction *ScanPos = QueryInst; 734f22ef01cSRoman Divacky 735f22ef01cSRoman Divacky // Check for a cached result 736f22ef01cSRoman Divacky MemDepResult &LocalCache = LocalDeps[QueryInst]; 737f22ef01cSRoman Divacky 738f22ef01cSRoman Divacky // If the cached entry is non-dirty, just return it. Note that this depends 739f22ef01cSRoman Divacky // on MemDepResult's default constructing to 'dirty'. 740f22ef01cSRoman Divacky if (!LocalCache.isDirty()) 741f22ef01cSRoman Divacky return LocalCache; 742f22ef01cSRoman Divacky 743f22ef01cSRoman Divacky // Otherwise, if we have a dirty entry, we know we can start the scan at that 744f22ef01cSRoman Divacky // instruction, which may save us some work. 745f22ef01cSRoman Divacky if (Instruction *Inst = LocalCache.getInst()) { 746f22ef01cSRoman Divacky ScanPos = Inst; 747f22ef01cSRoman Divacky 748f22ef01cSRoman Divacky RemoveFromReverseMap(ReverseLocalDeps, Inst, QueryInst); 749f22ef01cSRoman Divacky } 750f22ef01cSRoman Divacky 751f22ef01cSRoman Divacky BasicBlock *QueryParent = QueryInst->getParent(); 752f22ef01cSRoman Divacky 753f22ef01cSRoman Divacky // Do the scan. 754f22ef01cSRoman Divacky if (BasicBlock::iterator(QueryInst) == QueryParent->begin()) { 75517a519f9SDimitry Andric // No dependence found. If this is the entry block of the function, it is 75617a519f9SDimitry Andric // unknown, otherwise it is non-local. 757f22ef01cSRoman Divacky if (QueryParent != &QueryParent->getParent()->getEntryBlock()) 758f22ef01cSRoman Divacky LocalCache = MemDepResult::getNonLocal(); 759f22ef01cSRoman Divacky else 7606122f3e6SDimitry Andric LocalCache = MemDepResult::getNonFuncLocal(); 7612754fe60SDimitry Andric } else { 7628f0fd8f6SDimitry Andric MemoryLocation MemLoc; 7637d523365SDimitry Andric ModRefInfo MR = GetLocation(QueryInst, MemLoc, *TLI); 7642754fe60SDimitry Andric if (MemLoc.Ptr) { 7652754fe60SDimitry Andric // If we can do a pointer scan, make it happen. 7667d523365SDimitry Andric bool isLoad = !(MR & MRI_Mod); 7672754fe60SDimitry Andric if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(QueryInst)) 768bd5abe19SDimitry Andric isLoad |= II->getIntrinsicID() == Intrinsic::lifetime_start; 769f22ef01cSRoman Divacky 7707d523365SDimitry Andric LocalCache = getPointerDependencyFrom( 7717d523365SDimitry Andric MemLoc, isLoad, ScanPos->getIterator(), QueryParent, QueryInst); 7722754fe60SDimitry Andric } else if (isa<CallInst>(QueryInst) || isa<InvokeInst>(QueryInst)) { 773e580952dSDimitry Andric CallSite QueryCS(QueryInst); 774f22ef01cSRoman Divacky bool isReadOnly = AA->onlyReadsMemory(QueryCS); 7757d523365SDimitry Andric LocalCache = getCallSiteDependencyFrom( 7767d523365SDimitry Andric QueryCS, isReadOnly, ScanPos->getIterator(), QueryParent); 7772754fe60SDimitry Andric } else 778f22ef01cSRoman Divacky // Non-memory instruction. 77917a519f9SDimitry Andric LocalCache = MemDepResult::getUnknown(); 780f22ef01cSRoman Divacky } 781f22ef01cSRoman Divacky 782f22ef01cSRoman Divacky // Remember the result! 783f22ef01cSRoman Divacky if (Instruction *I = LocalCache.getInst()) 784f22ef01cSRoman Divacky ReverseLocalDeps[I].insert(QueryInst); 785f22ef01cSRoman Divacky 786f22ef01cSRoman Divacky return LocalCache; 787f22ef01cSRoman Divacky } 788f22ef01cSRoman Divacky 789f22ef01cSRoman Divacky #ifndef NDEBUG 790f22ef01cSRoman Divacky /// AssertSorted - This method is used when -debug is specified to verify that 791f22ef01cSRoman Divacky /// cache arrays are properly kept sorted. 792f22ef01cSRoman Divacky static void AssertSorted(MemoryDependenceAnalysis::NonLocalDepInfo &Cache, 793f22ef01cSRoman Divacky int Count = -1) { 794f22ef01cSRoman Divacky if (Count == -1) Count = Cache.size(); 7954d0b32cdSDimitry Andric assert(std::is_sorted(Cache.begin(), Cache.begin() + Count) && 7964d0b32cdSDimitry Andric "Cache isn't sorted!"); 797f22ef01cSRoman Divacky } 798f22ef01cSRoman Divacky #endif 799f22ef01cSRoman Divacky 800f22ef01cSRoman Divacky /// getNonLocalCallDependency - Perform a full dependency query for the 801f22ef01cSRoman Divacky /// specified call, returning the set of blocks that the value is 802f22ef01cSRoman Divacky /// potentially live across. The returned set of results will include a 803f22ef01cSRoman Divacky /// "NonLocal" result for all blocks where the value is live across. 804f22ef01cSRoman Divacky /// 805f22ef01cSRoman Divacky /// This method assumes the instruction returns a "NonLocal" dependency 806f22ef01cSRoman Divacky /// within its own block. 807f22ef01cSRoman Divacky /// 808f22ef01cSRoman Divacky /// This returns a reference to an internal data structure that may be 809f22ef01cSRoman Divacky /// invalidated on the next non-local query or when an instruction is 810f22ef01cSRoman Divacky /// removed. Clients must copy this data if they want it around longer than 811f22ef01cSRoman Divacky /// that. 812f22ef01cSRoman Divacky const MemoryDependenceAnalysis::NonLocalDepInfo & 813f22ef01cSRoman Divacky MemoryDependenceAnalysis::getNonLocalCallDependency(CallSite QueryCS) { 814f22ef01cSRoman Divacky assert(getDependency(QueryCS.getInstruction()).isNonLocal() && 815f22ef01cSRoman Divacky "getNonLocalCallDependency should only be used on calls with non-local deps!"); 816f22ef01cSRoman Divacky PerInstNLInfo &CacheP = NonLocalDeps[QueryCS.getInstruction()]; 817f22ef01cSRoman Divacky NonLocalDepInfo &Cache = CacheP.first; 818f22ef01cSRoman Divacky 819f22ef01cSRoman Divacky /// DirtyBlocks - This is the set of blocks that need to be recomputed. In 820f22ef01cSRoman Divacky /// the cached case, this can happen due to instructions being deleted etc. In 821f22ef01cSRoman Divacky /// the uncached case, this starts out as the set of predecessors we care 822f22ef01cSRoman Divacky /// about. 823f22ef01cSRoman Divacky SmallVector<BasicBlock*, 32> DirtyBlocks; 824f22ef01cSRoman Divacky 825f22ef01cSRoman Divacky if (!Cache.empty()) { 826f22ef01cSRoman Divacky // Okay, we have a cache entry. If we know it is not dirty, just return it 827f22ef01cSRoman Divacky // with no computation. 828f22ef01cSRoman Divacky if (!CacheP.second) { 829ffd1746dSEd Schouten ++NumCacheNonLocal; 830f22ef01cSRoman Divacky return Cache; 831f22ef01cSRoman Divacky } 832f22ef01cSRoman Divacky 833f22ef01cSRoman Divacky // If we already have a partially computed set of results, scan them to 834f22ef01cSRoman Divacky // determine what is dirty, seeding our initial DirtyBlocks worklist. 835f22ef01cSRoman Divacky for (NonLocalDepInfo::iterator I = Cache.begin(), E = Cache.end(); 836f22ef01cSRoman Divacky I != E; ++I) 837f22ef01cSRoman Divacky if (I->getResult().isDirty()) 838f22ef01cSRoman Divacky DirtyBlocks.push_back(I->getBB()); 839f22ef01cSRoman Divacky 840f22ef01cSRoman Divacky // Sort the cache so that we can do fast binary search lookups below. 841f22ef01cSRoman Divacky std::sort(Cache.begin(), Cache.end()); 842f22ef01cSRoman Divacky 843f22ef01cSRoman Divacky ++NumCacheDirtyNonLocal; 844f22ef01cSRoman Divacky //cerr << "CACHED CASE: " << DirtyBlocks.size() << " dirty: " 845f22ef01cSRoman Divacky // << Cache.size() << " cached: " << *QueryInst; 846f22ef01cSRoman Divacky } else { 847f22ef01cSRoman Divacky // Seed DirtyBlocks with each of the preds of QueryInst's block. 848f22ef01cSRoman Divacky BasicBlock *QueryBB = QueryCS.getInstruction()->getParent(); 849ff0cc061SDimitry Andric for (BasicBlock *Pred : PredCache.get(QueryBB)) 850ff0cc061SDimitry Andric DirtyBlocks.push_back(Pred); 851ffd1746dSEd Schouten ++NumUncacheNonLocal; 852f22ef01cSRoman Divacky } 853f22ef01cSRoman Divacky 854f22ef01cSRoman Divacky // isReadonlyCall - If this is a read-only call, we can be more aggressive. 855f22ef01cSRoman Divacky bool isReadonlyCall = AA->onlyReadsMemory(QueryCS); 856f22ef01cSRoman Divacky 857f22ef01cSRoman Divacky SmallPtrSet<BasicBlock*, 64> Visited; 858f22ef01cSRoman Divacky 859f22ef01cSRoman Divacky unsigned NumSortedEntries = Cache.size(); 860f22ef01cSRoman Divacky DEBUG(AssertSorted(Cache)); 861f22ef01cSRoman Divacky 862f22ef01cSRoman Divacky // Iterate while we still have blocks to update. 863f22ef01cSRoman Divacky while (!DirtyBlocks.empty()) { 864f22ef01cSRoman Divacky BasicBlock *DirtyBB = DirtyBlocks.back(); 865f22ef01cSRoman Divacky DirtyBlocks.pop_back(); 866f22ef01cSRoman Divacky 867f22ef01cSRoman Divacky // Already processed this block? 86839d628a0SDimitry Andric if (!Visited.insert(DirtyBB).second) 869f22ef01cSRoman Divacky continue; 870f22ef01cSRoman Divacky 871f22ef01cSRoman Divacky // Do a binary search to see if we already have an entry for this block in 872f22ef01cSRoman Divacky // the cache set. If so, find it. 873f22ef01cSRoman Divacky DEBUG(AssertSorted(Cache, NumSortedEntries)); 874f22ef01cSRoman Divacky NonLocalDepInfo::iterator Entry = 875f22ef01cSRoman Divacky std::upper_bound(Cache.begin(), Cache.begin()+NumSortedEntries, 876f22ef01cSRoman Divacky NonLocalDepEntry(DirtyBB)); 87791bc56edSDimitry Andric if (Entry != Cache.begin() && std::prev(Entry)->getBB() == DirtyBB) 878f22ef01cSRoman Divacky --Entry; 879f22ef01cSRoman Divacky 88091bc56edSDimitry Andric NonLocalDepEntry *ExistingResult = nullptr; 881f22ef01cSRoman Divacky if (Entry != Cache.begin()+NumSortedEntries && 882f22ef01cSRoman Divacky Entry->getBB() == DirtyBB) { 883f22ef01cSRoman Divacky // If we already have an entry, and if it isn't already dirty, the block 884f22ef01cSRoman Divacky // is done. 885f22ef01cSRoman Divacky if (!Entry->getResult().isDirty()) 886f22ef01cSRoman Divacky continue; 887f22ef01cSRoman Divacky 888f22ef01cSRoman Divacky // Otherwise, remember this slot so we can update the value. 889f22ef01cSRoman Divacky ExistingResult = &*Entry; 890f22ef01cSRoman Divacky } 891f22ef01cSRoman Divacky 892f22ef01cSRoman Divacky // If the dirty entry has a pointer, start scanning from it so we don't have 893f22ef01cSRoman Divacky // to rescan the entire block. 894f22ef01cSRoman Divacky BasicBlock::iterator ScanPos = DirtyBB->end(); 895f22ef01cSRoman Divacky if (ExistingResult) { 896f22ef01cSRoman Divacky if (Instruction *Inst = ExistingResult->getResult().getInst()) { 8977d523365SDimitry Andric ScanPos = Inst->getIterator(); 898f22ef01cSRoman Divacky // We're removing QueryInst's use of Inst. 899f22ef01cSRoman Divacky RemoveFromReverseMap(ReverseNonLocalDeps, Inst, 900f22ef01cSRoman Divacky QueryCS.getInstruction()); 901f22ef01cSRoman Divacky } 902f22ef01cSRoman Divacky } 903f22ef01cSRoman Divacky 904f22ef01cSRoman Divacky // Find out if this block has a local dependency for QueryInst. 905f22ef01cSRoman Divacky MemDepResult Dep; 906f22ef01cSRoman Divacky 907f22ef01cSRoman Divacky if (ScanPos != DirtyBB->begin()) { 908f22ef01cSRoman Divacky Dep = getCallSiteDependencyFrom(QueryCS, isReadonlyCall,ScanPos, DirtyBB); 909f22ef01cSRoman Divacky } else if (DirtyBB != &DirtyBB->getParent()->getEntryBlock()) { 910f22ef01cSRoman Divacky // No dependence found. If this is the entry block of the function, it is 91117a519f9SDimitry Andric // a clobber, otherwise it is unknown. 912f22ef01cSRoman Divacky Dep = MemDepResult::getNonLocal(); 913f22ef01cSRoman Divacky } else { 9146122f3e6SDimitry Andric Dep = MemDepResult::getNonFuncLocal(); 915f22ef01cSRoman Divacky } 916f22ef01cSRoman Divacky 917f22ef01cSRoman Divacky // If we had a dirty entry for the block, update it. Otherwise, just add 918f22ef01cSRoman Divacky // a new entry. 919f22ef01cSRoman Divacky if (ExistingResult) 920f22ef01cSRoman Divacky ExistingResult->setResult(Dep); 921f22ef01cSRoman Divacky else 922f22ef01cSRoman Divacky Cache.push_back(NonLocalDepEntry(DirtyBB, Dep)); 923f22ef01cSRoman Divacky 924f22ef01cSRoman Divacky // If the block has a dependency (i.e. it isn't completely transparent to 925f22ef01cSRoman Divacky // the value), remember the association! 926f22ef01cSRoman Divacky if (!Dep.isNonLocal()) { 927f22ef01cSRoman Divacky // Keep the ReverseNonLocalDeps map up to date so we can efficiently 928f22ef01cSRoman Divacky // update this when we remove instructions. 929f22ef01cSRoman Divacky if (Instruction *Inst = Dep.getInst()) 930f22ef01cSRoman Divacky ReverseNonLocalDeps[Inst].insert(QueryCS.getInstruction()); 931f22ef01cSRoman Divacky } else { 932f22ef01cSRoman Divacky 933f22ef01cSRoman Divacky // If the block *is* completely transparent to the load, we need to check 934f22ef01cSRoman Divacky // the predecessors of this block. Add them to our worklist. 935ff0cc061SDimitry Andric for (BasicBlock *Pred : PredCache.get(DirtyBB)) 936ff0cc061SDimitry Andric DirtyBlocks.push_back(Pred); 937f22ef01cSRoman Divacky } 938f22ef01cSRoman Divacky } 939f22ef01cSRoman Divacky 940f22ef01cSRoman Divacky return Cache; 941f22ef01cSRoman Divacky } 942f22ef01cSRoman Divacky 943f22ef01cSRoman Divacky /// getNonLocalPointerDependency - Perform a full dependency query for an 944f22ef01cSRoman Divacky /// access to the specified (non-volatile) memory location, returning the 945f22ef01cSRoman Divacky /// set of instructions that either define or clobber the value. 946f22ef01cSRoman Divacky /// 947f22ef01cSRoman Divacky /// This method assumes the pointer has a "NonLocal" dependency within its 948f22ef01cSRoman Divacky /// own block. 949f22ef01cSRoman Divacky /// 950f22ef01cSRoman Divacky void MemoryDependenceAnalysis:: 95139d628a0SDimitry Andric getNonLocalPointerDependency(Instruction *QueryInst, 952f22ef01cSRoman Divacky SmallVectorImpl<NonLocalDepResult> &Result) { 9538f0fd8f6SDimitry Andric const MemoryLocation Loc = MemoryLocation::get(QueryInst); 95439d628a0SDimitry Andric bool isLoad = isa<LoadInst>(QueryInst); 95539d628a0SDimitry Andric BasicBlock *FromBB = QueryInst->getParent(); 95639d628a0SDimitry Andric assert(FromBB); 95739d628a0SDimitry Andric 9582754fe60SDimitry Andric assert(Loc.Ptr->getType()->isPointerTy() && 959f22ef01cSRoman Divacky "Can't get pointer deps of a non-pointer!"); 960f22ef01cSRoman Divacky Result.clear(); 961f22ef01cSRoman Divacky 96239d628a0SDimitry Andric // This routine does not expect to deal with volatile instructions. 96339d628a0SDimitry Andric // Doing so would require piping through the QueryInst all the way through. 96439d628a0SDimitry Andric // TODO: volatiles can't be elided, but they can be reordered with other 96539d628a0SDimitry Andric // non-volatile accesses. 966ff0cc061SDimitry Andric 96739d628a0SDimitry Andric // We currently give up on any instruction which is ordered, but we do handle 96839d628a0SDimitry Andric // atomic instructions which are unordered. 96939d628a0SDimitry Andric // TODO: Handle ordered instructions 97039d628a0SDimitry Andric auto isOrdered = [](Instruction *Inst) { 97139d628a0SDimitry Andric if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) { 97239d628a0SDimitry Andric return !LI->isUnordered(); 97339d628a0SDimitry Andric } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) { 97439d628a0SDimitry Andric return !SI->isUnordered(); 97539d628a0SDimitry Andric } 97639d628a0SDimitry Andric return false; 97739d628a0SDimitry Andric }; 97839d628a0SDimitry Andric if (isVolatile(QueryInst) || isOrdered(QueryInst)) { 97939d628a0SDimitry Andric Result.push_back(NonLocalDepResult(FromBB, 98039d628a0SDimitry Andric MemDepResult::getUnknown(), 98139d628a0SDimitry Andric const_cast<Value *>(Loc.Ptr))); 98239d628a0SDimitry Andric return; 98339d628a0SDimitry Andric } 984ff0cc061SDimitry Andric const DataLayout &DL = FromBB->getModule()->getDataLayout(); 98539d628a0SDimitry Andric PHITransAddr Address(const_cast<Value *>(Loc.Ptr), DL, AC); 986f22ef01cSRoman Divacky 987f22ef01cSRoman Divacky // This is the set of blocks we've inspected, and the pointer we consider in 988f22ef01cSRoman Divacky // each block. Because of critical edges, we currently bail out if querying 989f22ef01cSRoman Divacky // a block with multiple different pointers. This can happen during PHI 990f22ef01cSRoman Divacky // translation. 991f22ef01cSRoman Divacky DenseMap<BasicBlock*, Value*> Visited; 992ff0cc061SDimitry Andric if (!getNonLocalPointerDepFromBB(QueryInst, Address, Loc, isLoad, FromBB, 993f22ef01cSRoman Divacky Result, Visited, true)) 994f22ef01cSRoman Divacky return; 995f22ef01cSRoman Divacky Result.clear(); 996f22ef01cSRoman Divacky Result.push_back(NonLocalDepResult(FromBB, 99717a519f9SDimitry Andric MemDepResult::getUnknown(), 9982754fe60SDimitry Andric const_cast<Value *>(Loc.Ptr))); 999f22ef01cSRoman Divacky } 1000f22ef01cSRoman Divacky 1001f22ef01cSRoman Divacky /// GetNonLocalInfoForBlock - Compute the memdep value for BB with 1002f22ef01cSRoman Divacky /// Pointer/PointeeSize using either cached information in Cache or by doing a 1003f22ef01cSRoman Divacky /// lookup (which may use dirty cache info if available). If we do a lookup, 1004f22ef01cSRoman Divacky /// add the result to the cache. 10058f0fd8f6SDimitry Andric MemDepResult MemoryDependenceAnalysis::GetNonLocalInfoForBlock( 10068f0fd8f6SDimitry Andric Instruction *QueryInst, const MemoryLocation &Loc, bool isLoad, 10078f0fd8f6SDimitry Andric BasicBlock *BB, NonLocalDepInfo *Cache, unsigned NumSortedEntries) { 1008f22ef01cSRoman Divacky 1009f22ef01cSRoman Divacky // Do a binary search to see if we already have an entry for this block in 1010f22ef01cSRoman Divacky // the cache set. If so, find it. 1011f22ef01cSRoman Divacky NonLocalDepInfo::iterator Entry = 1012f22ef01cSRoman Divacky std::upper_bound(Cache->begin(), Cache->begin()+NumSortedEntries, 1013f22ef01cSRoman Divacky NonLocalDepEntry(BB)); 1014f22ef01cSRoman Divacky if (Entry != Cache->begin() && (Entry-1)->getBB() == BB) 1015f22ef01cSRoman Divacky --Entry; 1016f22ef01cSRoman Divacky 101791bc56edSDimitry Andric NonLocalDepEntry *ExistingResult = nullptr; 1018f22ef01cSRoman Divacky if (Entry != Cache->begin()+NumSortedEntries && Entry->getBB() == BB) 1019f22ef01cSRoman Divacky ExistingResult = &*Entry; 1020f22ef01cSRoman Divacky 1021f22ef01cSRoman Divacky // If we have a cached entry, and it is non-dirty, use it as the value for 1022f22ef01cSRoman Divacky // this dependency. 1023f22ef01cSRoman Divacky if (ExistingResult && !ExistingResult->getResult().isDirty()) { 1024f22ef01cSRoman Divacky ++NumCacheNonLocalPtr; 1025f22ef01cSRoman Divacky return ExistingResult->getResult(); 1026f22ef01cSRoman Divacky } 1027f22ef01cSRoman Divacky 1028f22ef01cSRoman Divacky // Otherwise, we have to scan for the value. If we have a dirty cache 1029f22ef01cSRoman Divacky // entry, start scanning from its position, otherwise we scan from the end 1030f22ef01cSRoman Divacky // of the block. 1031f22ef01cSRoman Divacky BasicBlock::iterator ScanPos = BB->end(); 1032f22ef01cSRoman Divacky if (ExistingResult && ExistingResult->getResult().getInst()) { 1033f22ef01cSRoman Divacky assert(ExistingResult->getResult().getInst()->getParent() == BB && 1034f22ef01cSRoman Divacky "Instruction invalidated?"); 1035f22ef01cSRoman Divacky ++NumCacheDirtyNonLocalPtr; 10367d523365SDimitry Andric ScanPos = ExistingResult->getResult().getInst()->getIterator(); 1037f22ef01cSRoman Divacky 1038f22ef01cSRoman Divacky // Eliminating the dirty entry from 'Cache', so update the reverse info. 10392754fe60SDimitry Andric ValueIsLoadPair CacheKey(Loc.Ptr, isLoad); 10407d523365SDimitry Andric RemoveFromReverseMap(ReverseNonLocalPtrDeps, &*ScanPos, CacheKey); 1041f22ef01cSRoman Divacky } else { 1042f22ef01cSRoman Divacky ++NumUncacheNonLocalPtr; 1043f22ef01cSRoman Divacky } 1044f22ef01cSRoman Divacky 1045f22ef01cSRoman Divacky // Scan the block for the dependency. 1046ff0cc061SDimitry Andric MemDepResult Dep = getPointerDependencyFrom(Loc, isLoad, ScanPos, BB, 1047ff0cc061SDimitry Andric QueryInst); 1048f22ef01cSRoman Divacky 1049f22ef01cSRoman Divacky // If we had a dirty entry for the block, update it. Otherwise, just add 1050f22ef01cSRoman Divacky // a new entry. 1051f22ef01cSRoman Divacky if (ExistingResult) 1052f22ef01cSRoman Divacky ExistingResult->setResult(Dep); 1053f22ef01cSRoman Divacky else 1054f22ef01cSRoman Divacky Cache->push_back(NonLocalDepEntry(BB, Dep)); 1055f22ef01cSRoman Divacky 1056f22ef01cSRoman Divacky // If the block has a dependency (i.e. it isn't completely transparent to 1057f22ef01cSRoman Divacky // the value), remember the reverse association because we just added it 1058f22ef01cSRoman Divacky // to Cache! 10596122f3e6SDimitry Andric if (!Dep.isDef() && !Dep.isClobber()) 1060f22ef01cSRoman Divacky return Dep; 1061f22ef01cSRoman Divacky 1062f22ef01cSRoman Divacky // Keep the ReverseNonLocalPtrDeps map up to date so we can efficiently 1063f22ef01cSRoman Divacky // update MemDep when we remove instructions. 1064f22ef01cSRoman Divacky Instruction *Inst = Dep.getInst(); 1065f22ef01cSRoman Divacky assert(Inst && "Didn't depend on anything?"); 10662754fe60SDimitry Andric ValueIsLoadPair CacheKey(Loc.Ptr, isLoad); 1067f22ef01cSRoman Divacky ReverseNonLocalPtrDeps[Inst].insert(CacheKey); 1068f22ef01cSRoman Divacky return Dep; 1069f22ef01cSRoman Divacky } 1070f22ef01cSRoman Divacky 107139d628a0SDimitry Andric /// SortNonLocalDepInfoCache - Sort the NonLocalDepInfo cache, given a certain 1072f22ef01cSRoman Divacky /// number of elements in the array that are already properly ordered. This is 1073f22ef01cSRoman Divacky /// optimized for the case when only a few entries are added. 1074f22ef01cSRoman Divacky static void 1075f22ef01cSRoman Divacky SortNonLocalDepInfoCache(MemoryDependenceAnalysis::NonLocalDepInfo &Cache, 1076f22ef01cSRoman Divacky unsigned NumSortedEntries) { 1077f22ef01cSRoman Divacky switch (Cache.size() - NumSortedEntries) { 1078f22ef01cSRoman Divacky case 0: 1079f22ef01cSRoman Divacky // done, no new entries. 1080f22ef01cSRoman Divacky break; 1081f22ef01cSRoman Divacky case 2: { 1082f22ef01cSRoman Divacky // Two new entries, insert the last one into place. 1083f22ef01cSRoman Divacky NonLocalDepEntry Val = Cache.back(); 1084f22ef01cSRoman Divacky Cache.pop_back(); 1085f22ef01cSRoman Divacky MemoryDependenceAnalysis::NonLocalDepInfo::iterator Entry = 1086f22ef01cSRoman Divacky std::upper_bound(Cache.begin(), Cache.end()-1, Val); 1087f22ef01cSRoman Divacky Cache.insert(Entry, Val); 1088f22ef01cSRoman Divacky // FALL THROUGH. 1089f22ef01cSRoman Divacky } 1090f22ef01cSRoman Divacky case 1: 1091f22ef01cSRoman Divacky // One new entry, Just insert the new value at the appropriate position. 1092f22ef01cSRoman Divacky if (Cache.size() != 1) { 1093f22ef01cSRoman Divacky NonLocalDepEntry Val = Cache.back(); 1094f22ef01cSRoman Divacky Cache.pop_back(); 1095f22ef01cSRoman Divacky MemoryDependenceAnalysis::NonLocalDepInfo::iterator Entry = 1096f22ef01cSRoman Divacky std::upper_bound(Cache.begin(), Cache.end(), Val); 1097f22ef01cSRoman Divacky Cache.insert(Entry, Val); 1098f22ef01cSRoman Divacky } 1099f22ef01cSRoman Divacky break; 1100f22ef01cSRoman Divacky default: 1101f22ef01cSRoman Divacky // Added many values, do a full scale sort. 1102f22ef01cSRoman Divacky std::sort(Cache.begin(), Cache.end()); 1103f22ef01cSRoman Divacky break; 1104f22ef01cSRoman Divacky } 1105f22ef01cSRoman Divacky } 1106f22ef01cSRoman Divacky 1107f22ef01cSRoman Divacky /// getNonLocalPointerDepFromBB - Perform a dependency query based on 1108f22ef01cSRoman Divacky /// pointer/pointeesize starting at the end of StartBB. Add any clobber/def 1109f22ef01cSRoman Divacky /// results to the results vector and keep track of which blocks are visited in 1110f22ef01cSRoman Divacky /// 'Visited'. 1111f22ef01cSRoman Divacky /// 1112f22ef01cSRoman Divacky /// This has special behavior for the first block queries (when SkipFirstBlock 1113f22ef01cSRoman Divacky /// is true). In this special case, it ignores the contents of the specified 1114f22ef01cSRoman Divacky /// block and starts returning dependence info for its predecessors. 1115f22ef01cSRoman Divacky /// 1116f22ef01cSRoman Divacky /// This function returns false on success, or true to indicate that it could 1117f22ef01cSRoman Divacky /// not compute dependence information for some reason. This should be treated 1118f22ef01cSRoman Divacky /// as a clobber dependence on the first instruction in the predecessor block. 11198f0fd8f6SDimitry Andric bool MemoryDependenceAnalysis::getNonLocalPointerDepFromBB( 11208f0fd8f6SDimitry Andric Instruction *QueryInst, const PHITransAddr &Pointer, 11218f0fd8f6SDimitry Andric const MemoryLocation &Loc, bool isLoad, BasicBlock *StartBB, 1122f22ef01cSRoman Divacky SmallVectorImpl<NonLocalDepResult> &Result, 11238f0fd8f6SDimitry Andric DenseMap<BasicBlock *, Value *> &Visited, bool SkipFirstBlock) { 1124f22ef01cSRoman Divacky // Look up the cached info for Pointer. 1125f22ef01cSRoman Divacky ValueIsLoadPair CacheKey(Pointer.getAddr(), isLoad); 1126f22ef01cSRoman Divacky 11272754fe60SDimitry Andric // Set up a temporary NLPI value. If the map doesn't yet have an entry for 11282754fe60SDimitry Andric // CacheKey, this value will be inserted as the associated value. Otherwise, 11292754fe60SDimitry Andric // it'll be ignored, and we'll have to check to see if the cached size and 113039d628a0SDimitry Andric // aa tags are consistent with the current query. 11312754fe60SDimitry Andric NonLocalPointerInfo InitialNLPI; 11322754fe60SDimitry Andric InitialNLPI.Size = Loc.Size; 113339d628a0SDimitry Andric InitialNLPI.AATags = Loc.AATags; 11342754fe60SDimitry Andric 11352754fe60SDimitry Andric // Get the NLPI for CacheKey, inserting one into the map if it doesn't 11362754fe60SDimitry Andric // already have one. 11372754fe60SDimitry Andric std::pair<CachedNonLocalPointerInfo::iterator, bool> Pair = 11382754fe60SDimitry Andric NonLocalPointerDeps.insert(std::make_pair(CacheKey, InitialNLPI)); 11392754fe60SDimitry Andric NonLocalPointerInfo *CacheInfo = &Pair.first->second; 11402754fe60SDimitry Andric 11412754fe60SDimitry Andric // If we already have a cache entry for this CacheKey, we may need to do some 11422754fe60SDimitry Andric // work to reconcile the cache entry and the current query. 11432754fe60SDimitry Andric if (!Pair.second) { 11442754fe60SDimitry Andric if (CacheInfo->Size < Loc.Size) { 11452754fe60SDimitry Andric // The query's Size is greater than the cached one. Throw out the 11467ae0e2c9SDimitry Andric // cached data and proceed with the query at the greater size. 11472754fe60SDimitry Andric CacheInfo->Pair = BBSkipFirstBlockPair(); 11482754fe60SDimitry Andric CacheInfo->Size = Loc.Size; 11492754fe60SDimitry Andric for (NonLocalDepInfo::iterator DI = CacheInfo->NonLocalDeps.begin(), 11502754fe60SDimitry Andric DE = CacheInfo->NonLocalDeps.end(); DI != DE; ++DI) 11512754fe60SDimitry Andric if (Instruction *Inst = DI->getResult().getInst()) 11522754fe60SDimitry Andric RemoveFromReverseMap(ReverseNonLocalPtrDeps, Inst, CacheKey); 11532754fe60SDimitry Andric CacheInfo->NonLocalDeps.clear(); 11542754fe60SDimitry Andric } else if (CacheInfo->Size > Loc.Size) { 11552754fe60SDimitry Andric // This query's Size is less than the cached one. Conservatively restart 11562754fe60SDimitry Andric // the query using the greater size. 1157ff0cc061SDimitry Andric return getNonLocalPointerDepFromBB(QueryInst, Pointer, 11582754fe60SDimitry Andric Loc.getWithNewSize(CacheInfo->Size), 11592754fe60SDimitry Andric isLoad, StartBB, Result, Visited, 11602754fe60SDimitry Andric SkipFirstBlock); 11612754fe60SDimitry Andric } 11622754fe60SDimitry Andric 116339d628a0SDimitry Andric // If the query's AATags are inconsistent with the cached one, 11642754fe60SDimitry Andric // conservatively throw out the cached data and restart the query with 11652754fe60SDimitry Andric // no tag if needed. 116639d628a0SDimitry Andric if (CacheInfo->AATags != Loc.AATags) { 116739d628a0SDimitry Andric if (CacheInfo->AATags) { 11682754fe60SDimitry Andric CacheInfo->Pair = BBSkipFirstBlockPair(); 116939d628a0SDimitry Andric CacheInfo->AATags = AAMDNodes(); 11702754fe60SDimitry Andric for (NonLocalDepInfo::iterator DI = CacheInfo->NonLocalDeps.begin(), 11712754fe60SDimitry Andric DE = CacheInfo->NonLocalDeps.end(); DI != DE; ++DI) 11722754fe60SDimitry Andric if (Instruction *Inst = DI->getResult().getInst()) 11732754fe60SDimitry Andric RemoveFromReverseMap(ReverseNonLocalPtrDeps, Inst, CacheKey); 11742754fe60SDimitry Andric CacheInfo->NonLocalDeps.clear(); 11752754fe60SDimitry Andric } 117639d628a0SDimitry Andric if (Loc.AATags) 1177ff0cc061SDimitry Andric return getNonLocalPointerDepFromBB(QueryInst, 1178ff0cc061SDimitry Andric Pointer, Loc.getWithoutAATags(), 11792754fe60SDimitry Andric isLoad, StartBB, Result, Visited, 11802754fe60SDimitry Andric SkipFirstBlock); 11812754fe60SDimitry Andric } 11822754fe60SDimitry Andric } 11832754fe60SDimitry Andric 11842754fe60SDimitry Andric NonLocalDepInfo *Cache = &CacheInfo->NonLocalDeps; 1185f22ef01cSRoman Divacky 1186f22ef01cSRoman Divacky // If we have valid cached information for exactly the block we are 1187f22ef01cSRoman Divacky // investigating, just return it with no recomputation. 11882754fe60SDimitry Andric if (CacheInfo->Pair == BBSkipFirstBlockPair(StartBB, SkipFirstBlock)) { 1189f22ef01cSRoman Divacky // We have a fully cached result for this query then we can just return the 1190f22ef01cSRoman Divacky // cached results and populate the visited set. However, we have to verify 1191f22ef01cSRoman Divacky // that we don't already have conflicting results for these blocks. Check 1192f22ef01cSRoman Divacky // to ensure that if a block in the results set is in the visited set that 1193f22ef01cSRoman Divacky // it was for the same pointer query. 1194f22ef01cSRoman Divacky if (!Visited.empty()) { 1195f22ef01cSRoman Divacky for (NonLocalDepInfo::iterator I = Cache->begin(), E = Cache->end(); 1196f22ef01cSRoman Divacky I != E; ++I) { 1197f22ef01cSRoman Divacky DenseMap<BasicBlock*, Value*>::iterator VI = Visited.find(I->getBB()); 1198f22ef01cSRoman Divacky if (VI == Visited.end() || VI->second == Pointer.getAddr()) 1199f22ef01cSRoman Divacky continue; 1200f22ef01cSRoman Divacky 1201f22ef01cSRoman Divacky // We have a pointer mismatch in a block. Just return clobber, saying 1202f22ef01cSRoman Divacky // that something was clobbered in this result. We could also do a 1203f22ef01cSRoman Divacky // non-fully cached query, but there is little point in doing this. 1204f22ef01cSRoman Divacky return true; 1205f22ef01cSRoman Divacky } 1206f22ef01cSRoman Divacky } 1207f22ef01cSRoman Divacky 1208f22ef01cSRoman Divacky Value *Addr = Pointer.getAddr(); 1209f22ef01cSRoman Divacky for (NonLocalDepInfo::iterator I = Cache->begin(), E = Cache->end(); 1210f22ef01cSRoman Divacky I != E; ++I) { 1211f22ef01cSRoman Divacky Visited.insert(std::make_pair(I->getBB(), Addr)); 1212284c1978SDimitry Andric if (I->getResult().isNonLocal()) { 1213284c1978SDimitry Andric continue; 1214284c1978SDimitry Andric } 1215284c1978SDimitry Andric 1216284c1978SDimitry Andric if (!DT) { 1217284c1978SDimitry Andric Result.push_back(NonLocalDepResult(I->getBB(), 1218284c1978SDimitry Andric MemDepResult::getUnknown(), 1219284c1978SDimitry Andric Addr)); 1220284c1978SDimitry Andric } else if (DT->isReachableFromEntry(I->getBB())) { 1221f22ef01cSRoman Divacky Result.push_back(NonLocalDepResult(I->getBB(), I->getResult(), Addr)); 1222f22ef01cSRoman Divacky } 1223284c1978SDimitry Andric } 1224f22ef01cSRoman Divacky ++NumCacheCompleteNonLocalPtr; 1225f22ef01cSRoman Divacky return false; 1226f22ef01cSRoman Divacky } 1227f22ef01cSRoman Divacky 1228f22ef01cSRoman Divacky // Otherwise, either this is a new block, a block with an invalid cache 1229f22ef01cSRoman Divacky // pointer or one that we're about to invalidate by putting more info into it 1230f22ef01cSRoman Divacky // than its valid cache info. If empty, the result will be valid cache info, 1231f22ef01cSRoman Divacky // otherwise it isn't. 1232f22ef01cSRoman Divacky if (Cache->empty()) 12332754fe60SDimitry Andric CacheInfo->Pair = BBSkipFirstBlockPair(StartBB, SkipFirstBlock); 1234f22ef01cSRoman Divacky else 12352754fe60SDimitry Andric CacheInfo->Pair = BBSkipFirstBlockPair(); 1236f22ef01cSRoman Divacky 1237f22ef01cSRoman Divacky SmallVector<BasicBlock*, 32> Worklist; 1238f22ef01cSRoman Divacky Worklist.push_back(StartBB); 1239f22ef01cSRoman Divacky 1240bd5abe19SDimitry Andric // PredList used inside loop. 1241bd5abe19SDimitry Andric SmallVector<std::pair<BasicBlock*, PHITransAddr>, 16> PredList; 1242bd5abe19SDimitry Andric 1243f22ef01cSRoman Divacky // Keep track of the entries that we know are sorted. Previously cached 1244f22ef01cSRoman Divacky // entries will all be sorted. The entries we add we only sort on demand (we 1245f22ef01cSRoman Divacky // don't insert every element into its sorted position). We know that we 1246f22ef01cSRoman Divacky // won't get any reuse from currently inserted values, because we don't 1247f22ef01cSRoman Divacky // revisit blocks after we insert info for them. 1248f22ef01cSRoman Divacky unsigned NumSortedEntries = Cache->size(); 1249f22ef01cSRoman Divacky DEBUG(AssertSorted(*Cache)); 1250f22ef01cSRoman Divacky 1251f22ef01cSRoman Divacky while (!Worklist.empty()) { 1252f22ef01cSRoman Divacky BasicBlock *BB = Worklist.pop_back_val(); 1253f22ef01cSRoman Divacky 125439d628a0SDimitry Andric // If we do process a large number of blocks it becomes very expensive and 125539d628a0SDimitry Andric // likely it isn't worth worrying about 125639d628a0SDimitry Andric if (Result.size() > NumResultsLimit) { 125739d628a0SDimitry Andric Worklist.clear(); 125839d628a0SDimitry Andric // Sort it now (if needed) so that recursive invocations of 125939d628a0SDimitry Andric // getNonLocalPointerDepFromBB and other routines that could reuse the 126039d628a0SDimitry Andric // cache value will only see properly sorted cache arrays. 126139d628a0SDimitry Andric if (Cache && NumSortedEntries != Cache->size()) { 126239d628a0SDimitry Andric SortNonLocalDepInfoCache(*Cache, NumSortedEntries); 126339d628a0SDimitry Andric } 126439d628a0SDimitry Andric // Since we bail out, the "Cache" set won't contain all of the 126539d628a0SDimitry Andric // results for the query. This is ok (we can still use it to accelerate 126639d628a0SDimitry Andric // specific block queries) but we can't do the fastpath "return all 126739d628a0SDimitry Andric // results from the set". Clear out the indicator for this. 126839d628a0SDimitry Andric CacheInfo->Pair = BBSkipFirstBlockPair(); 126939d628a0SDimitry Andric return true; 127039d628a0SDimitry Andric } 127139d628a0SDimitry Andric 1272f22ef01cSRoman Divacky // Skip the first block if we have it. 1273f22ef01cSRoman Divacky if (!SkipFirstBlock) { 1274f22ef01cSRoman Divacky // Analyze the dependency of *Pointer in FromBB. See if we already have 1275f22ef01cSRoman Divacky // been here. 1276f22ef01cSRoman Divacky assert(Visited.count(BB) && "Should check 'visited' before adding to WL"); 1277f22ef01cSRoman Divacky 1278f22ef01cSRoman Divacky // Get the dependency info for Pointer in BB. If we have cached 1279f22ef01cSRoman Divacky // information, we will use it, otherwise we compute it. 1280f22ef01cSRoman Divacky DEBUG(AssertSorted(*Cache, NumSortedEntries)); 1281ff0cc061SDimitry Andric MemDepResult Dep = GetNonLocalInfoForBlock(QueryInst, 1282ff0cc061SDimitry Andric Loc, isLoad, BB, Cache, 1283f22ef01cSRoman Divacky NumSortedEntries); 1284f22ef01cSRoman Divacky 1285f22ef01cSRoman Divacky // If we got a Def or Clobber, add this to the list of results. 1286284c1978SDimitry Andric if (!Dep.isNonLocal()) { 1287284c1978SDimitry Andric if (!DT) { 1288284c1978SDimitry Andric Result.push_back(NonLocalDepResult(BB, 1289284c1978SDimitry Andric MemDepResult::getUnknown(), 1290284c1978SDimitry Andric Pointer.getAddr())); 1291284c1978SDimitry Andric continue; 1292284c1978SDimitry Andric } else if (DT->isReachableFromEntry(BB)) { 1293f22ef01cSRoman Divacky Result.push_back(NonLocalDepResult(BB, Dep, Pointer.getAddr())); 1294f22ef01cSRoman Divacky continue; 1295f22ef01cSRoman Divacky } 1296f22ef01cSRoman Divacky } 1297284c1978SDimitry Andric } 1298f22ef01cSRoman Divacky 1299f22ef01cSRoman Divacky // If 'Pointer' is an instruction defined in this block, then we need to do 1300f22ef01cSRoman Divacky // phi translation to change it into a value live in the predecessor block. 1301f22ef01cSRoman Divacky // If not, we just add the predecessors to the worklist and scan them with 1302f22ef01cSRoman Divacky // the same Pointer. 1303f22ef01cSRoman Divacky if (!Pointer.NeedsPHITranslationFromBlock(BB)) { 1304f22ef01cSRoman Divacky SkipFirstBlock = false; 1305bd5abe19SDimitry Andric SmallVector<BasicBlock*, 16> NewBlocks; 1306ff0cc061SDimitry Andric for (BasicBlock *Pred : PredCache.get(BB)) { 1307f22ef01cSRoman Divacky // Verify that we haven't looked at this block yet. 1308f22ef01cSRoman Divacky std::pair<DenseMap<BasicBlock*,Value*>::iterator, bool> 1309ff0cc061SDimitry Andric InsertRes = Visited.insert(std::make_pair(Pred, Pointer.getAddr())); 1310f22ef01cSRoman Divacky if (InsertRes.second) { 1311f22ef01cSRoman Divacky // First time we've looked at *PI. 1312ff0cc061SDimitry Andric NewBlocks.push_back(Pred); 1313f22ef01cSRoman Divacky continue; 1314f22ef01cSRoman Divacky } 1315f22ef01cSRoman Divacky 1316f22ef01cSRoman Divacky // If we have seen this block before, but it was with a different 1317f22ef01cSRoman Divacky // pointer then we have a phi translation failure and we have to treat 1318f22ef01cSRoman Divacky // this as a clobber. 1319bd5abe19SDimitry Andric if (InsertRes.first->second != Pointer.getAddr()) { 1320bd5abe19SDimitry Andric // Make sure to clean up the Visited map before continuing on to 1321bd5abe19SDimitry Andric // PredTranslationFailure. 1322bd5abe19SDimitry Andric for (unsigned i = 0; i < NewBlocks.size(); i++) 1323bd5abe19SDimitry Andric Visited.erase(NewBlocks[i]); 1324f22ef01cSRoman Divacky goto PredTranslationFailure; 1325f22ef01cSRoman Divacky } 1326bd5abe19SDimitry Andric } 1327bd5abe19SDimitry Andric Worklist.append(NewBlocks.begin(), NewBlocks.end()); 1328f22ef01cSRoman Divacky continue; 1329f22ef01cSRoman Divacky } 1330f22ef01cSRoman Divacky 1331f22ef01cSRoman Divacky // We do need to do phi translation, if we know ahead of time we can't phi 1332f22ef01cSRoman Divacky // translate this value, don't even try. 1333f22ef01cSRoman Divacky if (!Pointer.IsPotentiallyPHITranslatable()) 1334f22ef01cSRoman Divacky goto PredTranslationFailure; 1335f22ef01cSRoman Divacky 1336f22ef01cSRoman Divacky // We may have added values to the cache list before this PHI translation. 1337f22ef01cSRoman Divacky // If so, we haven't done anything to ensure that the cache remains sorted. 1338f22ef01cSRoman Divacky // Sort it now (if needed) so that recursive invocations of 1339f22ef01cSRoman Divacky // getNonLocalPointerDepFromBB and other routines that could reuse the cache 1340f22ef01cSRoman Divacky // value will only see properly sorted cache arrays. 1341f22ef01cSRoman Divacky if (Cache && NumSortedEntries != Cache->size()) { 1342f22ef01cSRoman Divacky SortNonLocalDepInfoCache(*Cache, NumSortedEntries); 1343f22ef01cSRoman Divacky NumSortedEntries = Cache->size(); 1344f22ef01cSRoman Divacky } 134591bc56edSDimitry Andric Cache = nullptr; 1346f22ef01cSRoman Divacky 1347bd5abe19SDimitry Andric PredList.clear(); 1348ff0cc061SDimitry Andric for (BasicBlock *Pred : PredCache.get(BB)) { 1349bd5abe19SDimitry Andric PredList.push_back(std::make_pair(Pred, Pointer)); 1350f22ef01cSRoman Divacky 1351f22ef01cSRoman Divacky // Get the PHI translated pointer in this predecessor. This can fail if 1352f22ef01cSRoman Divacky // not translatable, in which case the getAddr() returns null. 1353bd5abe19SDimitry Andric PHITransAddr &PredPointer = PredList.back().second; 135497bc6c73SDimitry Andric PredPointer.PHITranslateValue(BB, Pred, DT, /*MustDominate=*/false); 1355f22ef01cSRoman Divacky Value *PredPtrVal = PredPointer.getAddr(); 1356f22ef01cSRoman Divacky 1357f22ef01cSRoman Divacky // Check to see if we have already visited this pred block with another 1358f22ef01cSRoman Divacky // pointer. If so, we can't do this lookup. This failure can occur 1359f22ef01cSRoman Divacky // with PHI translation when a critical edge exists and the PHI node in 1360f22ef01cSRoman Divacky // the successor translates to a pointer value different than the 1361f22ef01cSRoman Divacky // pointer the block was first analyzed with. 1362f22ef01cSRoman Divacky std::pair<DenseMap<BasicBlock*,Value*>::iterator, bool> 1363f22ef01cSRoman Divacky InsertRes = Visited.insert(std::make_pair(Pred, PredPtrVal)); 1364f22ef01cSRoman Divacky 1365f22ef01cSRoman Divacky if (!InsertRes.second) { 1366bd5abe19SDimitry Andric // We found the pred; take it off the list of preds to visit. 1367bd5abe19SDimitry Andric PredList.pop_back(); 1368bd5abe19SDimitry Andric 1369f22ef01cSRoman Divacky // If the predecessor was visited with PredPtr, then we already did 1370f22ef01cSRoman Divacky // the analysis and can ignore it. 1371f22ef01cSRoman Divacky if (InsertRes.first->second == PredPtrVal) 1372f22ef01cSRoman Divacky continue; 1373f22ef01cSRoman Divacky 1374f22ef01cSRoman Divacky // Otherwise, the block was previously analyzed with a different 1375f22ef01cSRoman Divacky // pointer. We can't represent the result of this case, so we just 1376f22ef01cSRoman Divacky // treat this as a phi translation failure. 1377bd5abe19SDimitry Andric 1378bd5abe19SDimitry Andric // Make sure to clean up the Visited map before continuing on to 1379bd5abe19SDimitry Andric // PredTranslationFailure. 1380139f7f9bSDimitry Andric for (unsigned i = 0, n = PredList.size(); i < n; ++i) 1381bd5abe19SDimitry Andric Visited.erase(PredList[i].first); 1382bd5abe19SDimitry Andric 1383f22ef01cSRoman Divacky goto PredTranslationFailure; 1384f22ef01cSRoman Divacky } 1385bd5abe19SDimitry Andric } 1386f22ef01cSRoman Divacky 1387bd5abe19SDimitry Andric // Actually process results here; this need to be a separate loop to avoid 1388bd5abe19SDimitry Andric // calling getNonLocalPointerDepFromBB for blocks we don't want to return 1389bd5abe19SDimitry Andric // any results for. (getNonLocalPointerDepFromBB will modify our 1390bd5abe19SDimitry Andric // datastructures in ways the code after the PredTranslationFailure label 1391bd5abe19SDimitry Andric // doesn't expect.) 1392139f7f9bSDimitry Andric for (unsigned i = 0, n = PredList.size(); i < n; ++i) { 1393bd5abe19SDimitry Andric BasicBlock *Pred = PredList[i].first; 1394bd5abe19SDimitry Andric PHITransAddr &PredPointer = PredList[i].second; 1395bd5abe19SDimitry Andric Value *PredPtrVal = PredPointer.getAddr(); 1396bd5abe19SDimitry Andric 1397bd5abe19SDimitry Andric bool CanTranslate = true; 1398f22ef01cSRoman Divacky // If PHI translation was unable to find an available pointer in this 1399f22ef01cSRoman Divacky // predecessor, then we have to assume that the pointer is clobbered in 1400f22ef01cSRoman Divacky // that predecessor. We can still do PRE of the load, which would insert 1401f22ef01cSRoman Divacky // a computation of the pointer in this predecessor. 140291bc56edSDimitry Andric if (!PredPtrVal) 1403bd5abe19SDimitry Andric CanTranslate = false; 1404bd5abe19SDimitry Andric 1405bd5abe19SDimitry Andric // FIXME: it is entirely possible that PHI translating will end up with 1406bd5abe19SDimitry Andric // the same value. Consider PHI translating something like: 1407bd5abe19SDimitry Andric // X = phi [x, bb1], [y, bb2]. PHI translating for bb1 doesn't *need* 1408bd5abe19SDimitry Andric // to recurse here, pedantically speaking. 1409bd5abe19SDimitry Andric 1410bd5abe19SDimitry Andric // If getNonLocalPointerDepFromBB fails here, that means the cached 1411bd5abe19SDimitry Andric // result conflicted with the Visited list; we have to conservatively 141217a519f9SDimitry Andric // assume it is unknown, but this also does not block PRE of the load. 1413bd5abe19SDimitry Andric if (!CanTranslate || 1414ff0cc061SDimitry Andric getNonLocalPointerDepFromBB(QueryInst, PredPointer, 1415bd5abe19SDimitry Andric Loc.getWithNewPtr(PredPtrVal), 1416bd5abe19SDimitry Andric isLoad, Pred, 1417bd5abe19SDimitry Andric Result, Visited)) { 1418f22ef01cSRoman Divacky // Add the entry to the Result list. 141917a519f9SDimitry Andric NonLocalDepResult Entry(Pred, MemDepResult::getUnknown(), PredPtrVal); 1420f22ef01cSRoman Divacky Result.push_back(Entry); 1421f22ef01cSRoman Divacky 1422f22ef01cSRoman Divacky // Since we had a phi translation failure, the cache for CacheKey won't 1423f22ef01cSRoman Divacky // include all of the entries that we need to immediately satisfy future 1424f22ef01cSRoman Divacky // queries. Mark this in NonLocalPointerDeps by setting the 1425f22ef01cSRoman Divacky // BBSkipFirstBlockPair pointer to null. This requires reuse of the 1426f22ef01cSRoman Divacky // cached value to do more work but not miss the phi trans failure. 14272754fe60SDimitry Andric NonLocalPointerInfo &NLPI = NonLocalPointerDeps[CacheKey]; 14282754fe60SDimitry Andric NLPI.Pair = BBSkipFirstBlockPair(); 1429f22ef01cSRoman Divacky continue; 1430f22ef01cSRoman Divacky } 1431f22ef01cSRoman Divacky } 1432f22ef01cSRoman Divacky 1433f22ef01cSRoman Divacky // Refresh the CacheInfo/Cache pointer so that it isn't invalidated. 1434f22ef01cSRoman Divacky CacheInfo = &NonLocalPointerDeps[CacheKey]; 14352754fe60SDimitry Andric Cache = &CacheInfo->NonLocalDeps; 1436f22ef01cSRoman Divacky NumSortedEntries = Cache->size(); 1437f22ef01cSRoman Divacky 1438f22ef01cSRoman Divacky // Since we did phi translation, the "Cache" set won't contain all of the 1439f22ef01cSRoman Divacky // results for the query. This is ok (we can still use it to accelerate 1440f22ef01cSRoman Divacky // specific block queries) but we can't do the fastpath "return all 1441f22ef01cSRoman Divacky // results from the set" Clear out the indicator for this. 14422754fe60SDimitry Andric CacheInfo->Pair = BBSkipFirstBlockPair(); 1443f22ef01cSRoman Divacky SkipFirstBlock = false; 1444f22ef01cSRoman Divacky continue; 1445f22ef01cSRoman Divacky 1446f22ef01cSRoman Divacky PredTranslationFailure: 1447bd5abe19SDimitry Andric // The following code is "failure"; we can't produce a sane translation 1448bd5abe19SDimitry Andric // for the given block. It assumes that we haven't modified any of 1449bd5abe19SDimitry Andric // our datastructures while processing the current block. 1450f22ef01cSRoman Divacky 145191bc56edSDimitry Andric if (!Cache) { 1452f22ef01cSRoman Divacky // Refresh the CacheInfo/Cache pointer if it got invalidated. 1453f22ef01cSRoman Divacky CacheInfo = &NonLocalPointerDeps[CacheKey]; 14542754fe60SDimitry Andric Cache = &CacheInfo->NonLocalDeps; 1455f22ef01cSRoman Divacky NumSortedEntries = Cache->size(); 1456f22ef01cSRoman Divacky } 1457f22ef01cSRoman Divacky 1458f22ef01cSRoman Divacky // Since we failed phi translation, the "Cache" set won't contain all of the 1459f22ef01cSRoman Divacky // results for the query. This is ok (we can still use it to accelerate 1460f22ef01cSRoman Divacky // specific block queries) but we can't do the fastpath "return all 1461f22ef01cSRoman Divacky // results from the set". Clear out the indicator for this. 14622754fe60SDimitry Andric CacheInfo->Pair = BBSkipFirstBlockPair(); 1463f22ef01cSRoman Divacky 146417a519f9SDimitry Andric // If *nothing* works, mark the pointer as unknown. 1465f22ef01cSRoman Divacky // 1466f22ef01cSRoman Divacky // If this is the magic first block, return this as a clobber of the whole 1467f22ef01cSRoman Divacky // incoming value. Since we can't phi translate to one of the predecessors, 1468f22ef01cSRoman Divacky // we have to bail out. 1469f22ef01cSRoman Divacky if (SkipFirstBlock) 1470f22ef01cSRoman Divacky return true; 1471f22ef01cSRoman Divacky 1472f22ef01cSRoman Divacky for (NonLocalDepInfo::reverse_iterator I = Cache->rbegin(); ; ++I) { 1473f22ef01cSRoman Divacky assert(I != Cache->rend() && "Didn't find current block??"); 1474f22ef01cSRoman Divacky if (I->getBB() != BB) 1475f22ef01cSRoman Divacky continue; 1476f22ef01cSRoman Divacky 147739d628a0SDimitry Andric assert((I->getResult().isNonLocal() || !DT->isReachableFromEntry(BB)) && 1478f22ef01cSRoman Divacky "Should only be here with transparent block"); 147917a519f9SDimitry Andric I->setResult(MemDepResult::getUnknown()); 1480f22ef01cSRoman Divacky Result.push_back(NonLocalDepResult(I->getBB(), I->getResult(), 1481f22ef01cSRoman Divacky Pointer.getAddr())); 1482f22ef01cSRoman Divacky break; 1483f22ef01cSRoman Divacky } 1484f22ef01cSRoman Divacky } 1485f22ef01cSRoman Divacky 1486f22ef01cSRoman Divacky // Okay, we're done now. If we added new values to the cache, re-sort it. 1487f22ef01cSRoman Divacky SortNonLocalDepInfoCache(*Cache, NumSortedEntries); 1488f22ef01cSRoman Divacky DEBUG(AssertSorted(*Cache)); 1489f22ef01cSRoman Divacky return false; 1490f22ef01cSRoman Divacky } 1491f22ef01cSRoman Divacky 1492f22ef01cSRoman Divacky /// RemoveCachedNonLocalPointerDependencies - If P exists in 1493f22ef01cSRoman Divacky /// CachedNonLocalPointerInfo, remove it. 1494f22ef01cSRoman Divacky void MemoryDependenceAnalysis:: 1495f22ef01cSRoman Divacky RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair P) { 1496f22ef01cSRoman Divacky CachedNonLocalPointerInfo::iterator It = 1497f22ef01cSRoman Divacky NonLocalPointerDeps.find(P); 1498f22ef01cSRoman Divacky if (It == NonLocalPointerDeps.end()) return; 1499f22ef01cSRoman Divacky 1500f22ef01cSRoman Divacky // Remove all of the entries in the BB->val map. This involves removing 1501f22ef01cSRoman Divacky // instructions from the reverse map. 15022754fe60SDimitry Andric NonLocalDepInfo &PInfo = It->second.NonLocalDeps; 1503f22ef01cSRoman Divacky 1504f22ef01cSRoman Divacky for (unsigned i = 0, e = PInfo.size(); i != e; ++i) { 1505f22ef01cSRoman Divacky Instruction *Target = PInfo[i].getResult().getInst(); 150691bc56edSDimitry Andric if (!Target) continue; // Ignore non-local dep results. 1507f22ef01cSRoman Divacky assert(Target->getParent() == PInfo[i].getBB()); 1508f22ef01cSRoman Divacky 1509f22ef01cSRoman Divacky // Eliminating the dirty entry from 'Cache', so update the reverse info. 1510f22ef01cSRoman Divacky RemoveFromReverseMap(ReverseNonLocalPtrDeps, Target, P); 1511f22ef01cSRoman Divacky } 1512f22ef01cSRoman Divacky 1513f22ef01cSRoman Divacky // Remove P from NonLocalPointerDeps (which deletes NonLocalDepInfo). 1514f22ef01cSRoman Divacky NonLocalPointerDeps.erase(It); 1515f22ef01cSRoman Divacky } 1516f22ef01cSRoman Divacky 1517f22ef01cSRoman Divacky 1518f22ef01cSRoman Divacky /// invalidateCachedPointerInfo - This method is used to invalidate cached 1519f22ef01cSRoman Divacky /// information about the specified pointer, because it may be too 1520f22ef01cSRoman Divacky /// conservative in memdep. This is an optional call that can be used when 1521f22ef01cSRoman Divacky /// the client detects an equivalence between the pointer and some other 1522f22ef01cSRoman Divacky /// value and replaces the other value with ptr. This can make Ptr available 1523f22ef01cSRoman Divacky /// in more places that cached info does not necessarily keep. 1524f22ef01cSRoman Divacky void MemoryDependenceAnalysis::invalidateCachedPointerInfo(Value *Ptr) { 1525f22ef01cSRoman Divacky // If Ptr isn't really a pointer, just ignore it. 1526f22ef01cSRoman Divacky if (!Ptr->getType()->isPointerTy()) return; 1527f22ef01cSRoman Divacky // Flush store info for the pointer. 1528f22ef01cSRoman Divacky RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(Ptr, false)); 1529f22ef01cSRoman Divacky // Flush load info for the pointer. 1530f22ef01cSRoman Divacky RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(Ptr, true)); 1531f22ef01cSRoman Divacky } 1532f22ef01cSRoman Divacky 1533f22ef01cSRoman Divacky /// invalidateCachedPredecessors - Clear the PredIteratorCache info. 1534f22ef01cSRoman Divacky /// This needs to be done when the CFG changes, e.g., due to splitting 1535f22ef01cSRoman Divacky /// critical edges. 1536f22ef01cSRoman Divacky void MemoryDependenceAnalysis::invalidateCachedPredecessors() { 1537ff0cc061SDimitry Andric PredCache.clear(); 1538f22ef01cSRoman Divacky } 1539f22ef01cSRoman Divacky 1540f22ef01cSRoman Divacky /// removeInstruction - Remove an instruction from the dependence analysis, 1541f22ef01cSRoman Divacky /// updating the dependence of instructions that previously depended on it. 1542f22ef01cSRoman Divacky /// This method attempts to keep the cache coherent using the reverse map. 1543f22ef01cSRoman Divacky void MemoryDependenceAnalysis::removeInstruction(Instruction *RemInst) { 1544f22ef01cSRoman Divacky // Walk through the Non-local dependencies, removing this one as the value 1545f22ef01cSRoman Divacky // for any cached queries. 1546f22ef01cSRoman Divacky NonLocalDepMapType::iterator NLDI = NonLocalDeps.find(RemInst); 1547f22ef01cSRoman Divacky if (NLDI != NonLocalDeps.end()) { 1548f22ef01cSRoman Divacky NonLocalDepInfo &BlockMap = NLDI->second.first; 1549f22ef01cSRoman Divacky for (NonLocalDepInfo::iterator DI = BlockMap.begin(), DE = BlockMap.end(); 1550f22ef01cSRoman Divacky DI != DE; ++DI) 1551f22ef01cSRoman Divacky if (Instruction *Inst = DI->getResult().getInst()) 1552f22ef01cSRoman Divacky RemoveFromReverseMap(ReverseNonLocalDeps, Inst, RemInst); 1553f22ef01cSRoman Divacky NonLocalDeps.erase(NLDI); 1554f22ef01cSRoman Divacky } 1555f22ef01cSRoman Divacky 1556f22ef01cSRoman Divacky // If we have a cached local dependence query for this instruction, remove it. 1557f22ef01cSRoman Divacky // 1558f22ef01cSRoman Divacky LocalDepMapType::iterator LocalDepEntry = LocalDeps.find(RemInst); 1559f22ef01cSRoman Divacky if (LocalDepEntry != LocalDeps.end()) { 1560f22ef01cSRoman Divacky // Remove us from DepInst's reverse set now that the local dep info is gone. 1561f22ef01cSRoman Divacky if (Instruction *Inst = LocalDepEntry->second.getInst()) 1562f22ef01cSRoman Divacky RemoveFromReverseMap(ReverseLocalDeps, Inst, RemInst); 1563f22ef01cSRoman Divacky 1564f22ef01cSRoman Divacky // Remove this local dependency info. 1565f22ef01cSRoman Divacky LocalDeps.erase(LocalDepEntry); 1566f22ef01cSRoman Divacky } 1567f22ef01cSRoman Divacky 1568f22ef01cSRoman Divacky // If we have any cached pointer dependencies on this instruction, remove 1569f22ef01cSRoman Divacky // them. If the instruction has non-pointer type, then it can't be a pointer 1570f22ef01cSRoman Divacky // base. 1571f22ef01cSRoman Divacky 1572f22ef01cSRoman Divacky // Remove it from both the load info and the store info. The instruction 1573f22ef01cSRoman Divacky // can't be in either of these maps if it is non-pointer. 1574f22ef01cSRoman Divacky if (RemInst->getType()->isPointerTy()) { 1575f22ef01cSRoman Divacky RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(RemInst, false)); 1576f22ef01cSRoman Divacky RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(RemInst, true)); 1577f22ef01cSRoman Divacky } 1578f22ef01cSRoman Divacky 1579f22ef01cSRoman Divacky // Loop over all of the things that depend on the instruction we're removing. 1580f22ef01cSRoman Divacky // 1581f22ef01cSRoman Divacky SmallVector<std::pair<Instruction*, Instruction*>, 8> ReverseDepsToAdd; 1582f22ef01cSRoman Divacky 1583f22ef01cSRoman Divacky // If we find RemInst as a clobber or Def in any of the maps for other values, 1584f22ef01cSRoman Divacky // we need to replace its entry with a dirty version of the instruction after 1585f22ef01cSRoman Divacky // it. If RemInst is a terminator, we use a null dirty value. 1586f22ef01cSRoman Divacky // 1587f22ef01cSRoman Divacky // Using a dirty version of the instruction after RemInst saves having to scan 1588f22ef01cSRoman Divacky // the entire block to get to this point. 1589f22ef01cSRoman Divacky MemDepResult NewDirtyVal; 1590f22ef01cSRoman Divacky if (!RemInst->isTerminator()) 15917d523365SDimitry Andric NewDirtyVal = MemDepResult::getDirty(&*++RemInst->getIterator()); 1592f22ef01cSRoman Divacky 1593f22ef01cSRoman Divacky ReverseDepMapType::iterator ReverseDepIt = ReverseLocalDeps.find(RemInst); 1594f22ef01cSRoman Divacky if (ReverseDepIt != ReverseLocalDeps.end()) { 1595f22ef01cSRoman Divacky // RemInst can't be the terminator if it has local stuff depending on it. 159639d628a0SDimitry Andric assert(!ReverseDepIt->second.empty() && !isa<TerminatorInst>(RemInst) && 1597f22ef01cSRoman Divacky "Nothing can locally depend on a terminator"); 1598f22ef01cSRoman Divacky 159939d628a0SDimitry Andric for (Instruction *InstDependingOnRemInst : ReverseDepIt->second) { 1600f22ef01cSRoman Divacky assert(InstDependingOnRemInst != RemInst && 1601f22ef01cSRoman Divacky "Already removed our local dep info"); 1602f22ef01cSRoman Divacky 1603f22ef01cSRoman Divacky LocalDeps[InstDependingOnRemInst] = NewDirtyVal; 1604f22ef01cSRoman Divacky 1605f22ef01cSRoman Divacky // Make sure to remember that new things depend on NewDepInst. 1606f22ef01cSRoman Divacky assert(NewDirtyVal.getInst() && "There is no way something else can have " 1607f22ef01cSRoman Divacky "a local dep on this if it is a terminator!"); 1608f22ef01cSRoman Divacky ReverseDepsToAdd.push_back(std::make_pair(NewDirtyVal.getInst(), 1609f22ef01cSRoman Divacky InstDependingOnRemInst)); 1610f22ef01cSRoman Divacky } 1611f22ef01cSRoman Divacky 1612f22ef01cSRoman Divacky ReverseLocalDeps.erase(ReverseDepIt); 1613f22ef01cSRoman Divacky 1614f22ef01cSRoman Divacky // Add new reverse deps after scanning the set, to avoid invalidating the 1615f22ef01cSRoman Divacky // 'ReverseDeps' reference. 1616f22ef01cSRoman Divacky while (!ReverseDepsToAdd.empty()) { 1617f22ef01cSRoman Divacky ReverseLocalDeps[ReverseDepsToAdd.back().first] 1618f22ef01cSRoman Divacky .insert(ReverseDepsToAdd.back().second); 1619f22ef01cSRoman Divacky ReverseDepsToAdd.pop_back(); 1620f22ef01cSRoman Divacky } 1621f22ef01cSRoman Divacky } 1622f22ef01cSRoman Divacky 1623f22ef01cSRoman Divacky ReverseDepIt = ReverseNonLocalDeps.find(RemInst); 1624f22ef01cSRoman Divacky if (ReverseDepIt != ReverseNonLocalDeps.end()) { 162539d628a0SDimitry Andric for (Instruction *I : ReverseDepIt->second) { 162639d628a0SDimitry Andric assert(I != RemInst && "Already removed NonLocalDep info for RemInst"); 1627f22ef01cSRoman Divacky 162839d628a0SDimitry Andric PerInstNLInfo &INLD = NonLocalDeps[I]; 1629f22ef01cSRoman Divacky // The information is now dirty! 1630f22ef01cSRoman Divacky INLD.second = true; 1631f22ef01cSRoman Divacky 1632f22ef01cSRoman Divacky for (NonLocalDepInfo::iterator DI = INLD.first.begin(), 1633f22ef01cSRoman Divacky DE = INLD.first.end(); DI != DE; ++DI) { 1634f22ef01cSRoman Divacky if (DI->getResult().getInst() != RemInst) continue; 1635f22ef01cSRoman Divacky 1636f22ef01cSRoman Divacky // Convert to a dirty entry for the subsequent instruction. 1637f22ef01cSRoman Divacky DI->setResult(NewDirtyVal); 1638f22ef01cSRoman Divacky 1639f22ef01cSRoman Divacky if (Instruction *NextI = NewDirtyVal.getInst()) 164039d628a0SDimitry Andric ReverseDepsToAdd.push_back(std::make_pair(NextI, I)); 1641f22ef01cSRoman Divacky } 1642f22ef01cSRoman Divacky } 1643f22ef01cSRoman Divacky 1644f22ef01cSRoman Divacky ReverseNonLocalDeps.erase(ReverseDepIt); 1645f22ef01cSRoman Divacky 1646f22ef01cSRoman Divacky // Add new reverse deps after scanning the set, to avoid invalidating 'Set' 1647f22ef01cSRoman Divacky while (!ReverseDepsToAdd.empty()) { 1648f22ef01cSRoman Divacky ReverseNonLocalDeps[ReverseDepsToAdd.back().first] 1649f22ef01cSRoman Divacky .insert(ReverseDepsToAdd.back().second); 1650f22ef01cSRoman Divacky ReverseDepsToAdd.pop_back(); 1651f22ef01cSRoman Divacky } 1652f22ef01cSRoman Divacky } 1653f22ef01cSRoman Divacky 1654f22ef01cSRoman Divacky // If the instruction is in ReverseNonLocalPtrDeps then it appears as a 1655f22ef01cSRoman Divacky // value in the NonLocalPointerDeps info. 1656f22ef01cSRoman Divacky ReverseNonLocalPtrDepTy::iterator ReversePtrDepIt = 1657f22ef01cSRoman Divacky ReverseNonLocalPtrDeps.find(RemInst); 1658f22ef01cSRoman Divacky if (ReversePtrDepIt != ReverseNonLocalPtrDeps.end()) { 1659f22ef01cSRoman Divacky SmallVector<std::pair<Instruction*, ValueIsLoadPair>,8> ReversePtrDepsToAdd; 1660f22ef01cSRoman Divacky 166139d628a0SDimitry Andric for (ValueIsLoadPair P : ReversePtrDepIt->second) { 1662f22ef01cSRoman Divacky assert(P.getPointer() != RemInst && 1663f22ef01cSRoman Divacky "Already removed NonLocalPointerDeps info for RemInst"); 1664f22ef01cSRoman Divacky 16652754fe60SDimitry Andric NonLocalDepInfo &NLPDI = NonLocalPointerDeps[P].NonLocalDeps; 1666f22ef01cSRoman Divacky 1667f22ef01cSRoman Divacky // The cache is not valid for any specific block anymore. 16682754fe60SDimitry Andric NonLocalPointerDeps[P].Pair = BBSkipFirstBlockPair(); 1669f22ef01cSRoman Divacky 1670f22ef01cSRoman Divacky // Update any entries for RemInst to use the instruction after it. 1671f22ef01cSRoman Divacky for (NonLocalDepInfo::iterator DI = NLPDI.begin(), DE = NLPDI.end(); 1672f22ef01cSRoman Divacky DI != DE; ++DI) { 1673f22ef01cSRoman Divacky if (DI->getResult().getInst() != RemInst) continue; 1674f22ef01cSRoman Divacky 1675f22ef01cSRoman Divacky // Convert to a dirty entry for the subsequent instruction. 1676f22ef01cSRoman Divacky DI->setResult(NewDirtyVal); 1677f22ef01cSRoman Divacky 1678f22ef01cSRoman Divacky if (Instruction *NewDirtyInst = NewDirtyVal.getInst()) 1679f22ef01cSRoman Divacky ReversePtrDepsToAdd.push_back(std::make_pair(NewDirtyInst, P)); 1680f22ef01cSRoman Divacky } 1681f22ef01cSRoman Divacky 1682f22ef01cSRoman Divacky // Re-sort the NonLocalDepInfo. Changing the dirty entry to its 1683f22ef01cSRoman Divacky // subsequent value may invalidate the sortedness. 1684f22ef01cSRoman Divacky std::sort(NLPDI.begin(), NLPDI.end()); 1685f22ef01cSRoman Divacky } 1686f22ef01cSRoman Divacky 1687f22ef01cSRoman Divacky ReverseNonLocalPtrDeps.erase(ReversePtrDepIt); 1688f22ef01cSRoman Divacky 1689f22ef01cSRoman Divacky while (!ReversePtrDepsToAdd.empty()) { 1690f22ef01cSRoman Divacky ReverseNonLocalPtrDeps[ReversePtrDepsToAdd.back().first] 1691f22ef01cSRoman Divacky .insert(ReversePtrDepsToAdd.back().second); 1692f22ef01cSRoman Divacky ReversePtrDepsToAdd.pop_back(); 1693f22ef01cSRoman Divacky } 1694f22ef01cSRoman Divacky } 1695f22ef01cSRoman Divacky 1696f22ef01cSRoman Divacky 1697f22ef01cSRoman Divacky assert(!NonLocalDeps.count(RemInst) && "RemInst got reinserted?"); 1698f22ef01cSRoman Divacky DEBUG(verifyRemoved(RemInst)); 1699f22ef01cSRoman Divacky } 1700f22ef01cSRoman Divacky /// verifyRemoved - Verify that the specified instruction does not occur 170139d628a0SDimitry Andric /// in our internal data structures. This function verifies by asserting in 170239d628a0SDimitry Andric /// debug builds. 1703f22ef01cSRoman Divacky void MemoryDependenceAnalysis::verifyRemoved(Instruction *D) const { 170439d628a0SDimitry Andric #ifndef NDEBUG 1705f22ef01cSRoman Divacky for (LocalDepMapType::const_iterator I = LocalDeps.begin(), 1706f22ef01cSRoman Divacky E = LocalDeps.end(); I != E; ++I) { 1707f22ef01cSRoman Divacky assert(I->first != D && "Inst occurs in data structures"); 1708f22ef01cSRoman Divacky assert(I->second.getInst() != D && 1709f22ef01cSRoman Divacky "Inst occurs in data structures"); 1710f22ef01cSRoman Divacky } 1711f22ef01cSRoman Divacky 1712f22ef01cSRoman Divacky for (CachedNonLocalPointerInfo::const_iterator I =NonLocalPointerDeps.begin(), 1713f22ef01cSRoman Divacky E = NonLocalPointerDeps.end(); I != E; ++I) { 1714f22ef01cSRoman Divacky assert(I->first.getPointer() != D && "Inst occurs in NLPD map key"); 17152754fe60SDimitry Andric const NonLocalDepInfo &Val = I->second.NonLocalDeps; 1716f22ef01cSRoman Divacky for (NonLocalDepInfo::const_iterator II = Val.begin(), E = Val.end(); 1717f22ef01cSRoman Divacky II != E; ++II) 1718f22ef01cSRoman Divacky assert(II->getResult().getInst() != D && "Inst occurs as NLPD value"); 1719f22ef01cSRoman Divacky } 1720f22ef01cSRoman Divacky 1721f22ef01cSRoman Divacky for (NonLocalDepMapType::const_iterator I = NonLocalDeps.begin(), 1722f22ef01cSRoman Divacky E = NonLocalDeps.end(); I != E; ++I) { 1723f22ef01cSRoman Divacky assert(I->first != D && "Inst occurs in data structures"); 1724f22ef01cSRoman Divacky const PerInstNLInfo &INLD = I->second; 1725f22ef01cSRoman Divacky for (NonLocalDepInfo::const_iterator II = INLD.first.begin(), 1726f22ef01cSRoman Divacky EE = INLD.first.end(); II != EE; ++II) 1727f22ef01cSRoman Divacky assert(II->getResult().getInst() != D && "Inst occurs in data structures"); 1728f22ef01cSRoman Divacky } 1729f22ef01cSRoman Divacky 1730f22ef01cSRoman Divacky for (ReverseDepMapType::const_iterator I = ReverseLocalDeps.begin(), 1731f22ef01cSRoman Divacky E = ReverseLocalDeps.end(); I != E; ++I) { 1732f22ef01cSRoman Divacky assert(I->first != D && "Inst occurs in data structures"); 173339d628a0SDimitry Andric for (Instruction *Inst : I->second) 173439d628a0SDimitry Andric assert(Inst != D && "Inst occurs in data structures"); 1735f22ef01cSRoman Divacky } 1736f22ef01cSRoman Divacky 1737f22ef01cSRoman Divacky for (ReverseDepMapType::const_iterator I = ReverseNonLocalDeps.begin(), 1738f22ef01cSRoman Divacky E = ReverseNonLocalDeps.end(); 1739f22ef01cSRoman Divacky I != E; ++I) { 1740f22ef01cSRoman Divacky assert(I->first != D && "Inst occurs in data structures"); 174139d628a0SDimitry Andric for (Instruction *Inst : I->second) 174239d628a0SDimitry Andric assert(Inst != D && "Inst occurs in data structures"); 1743f22ef01cSRoman Divacky } 1744f22ef01cSRoman Divacky 1745f22ef01cSRoman Divacky for (ReverseNonLocalPtrDepTy::const_iterator 1746f22ef01cSRoman Divacky I = ReverseNonLocalPtrDeps.begin(), 1747f22ef01cSRoman Divacky E = ReverseNonLocalPtrDeps.end(); I != E; ++I) { 1748f22ef01cSRoman Divacky assert(I->first != D && "Inst occurs in rev NLPD map"); 1749f22ef01cSRoman Divacky 175039d628a0SDimitry Andric for (ValueIsLoadPair P : I->second) 175139d628a0SDimitry Andric assert(P != ValueIsLoadPair(D, false) && 175239d628a0SDimitry Andric P != ValueIsLoadPair(D, true) && 1753f22ef01cSRoman Divacky "Inst occurs in ReverseNonLocalPtrDeps map"); 1754f22ef01cSRoman Divacky } 175539d628a0SDimitry Andric #endif 1756f22ef01cSRoman Divacky } 1757