LLVM  mainline
MemoryDependenceAnalysis.cpp
Go to the documentation of this file.
00001 //===- MemoryDependenceAnalysis.cpp - Mem Deps Implementation -------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements an analysis that determines, for a given memory
00011 // operation, what preceding memory operations it depends on.  It builds on
00012 // alias analysis information, and tries to provide a lazy, caching interface to
00013 // a common kind of alias information query.
00014 //
00015 //===----------------------------------------------------------------------===//
00016 
00017 #include "llvm/Analysis/MemoryDependenceAnalysis.h"
00018 #include "llvm/ADT/STLExtras.h"
00019 #include "llvm/ADT/Statistic.h"
00020 #include "llvm/Analysis/AliasAnalysis.h"
00021 #include "llvm/Analysis/AssumptionCache.h"
00022 #include "llvm/Analysis/InstructionSimplify.h"
00023 #include "llvm/Analysis/MemoryBuiltins.h"
00024 #include "llvm/Analysis/PHITransAddr.h"
00025 #include "llvm/Analysis/ValueTracking.h"
00026 #include "llvm/IR/DataLayout.h"
00027 #include "llvm/IR/Dominators.h"
00028 #include "llvm/IR/Function.h"
00029 #include "llvm/IR/Instructions.h"
00030 #include "llvm/IR/IntrinsicInst.h"
00031 #include "llvm/IR/LLVMContext.h"
00032 #include "llvm/IR/PredIteratorCache.h"
00033 #include "llvm/Support/Debug.h"
00034 using namespace llvm;
00035 
00036 #define DEBUG_TYPE "memdep"
00037 
00038 STATISTIC(NumCacheNonLocal, "Number of fully cached non-local responses");
00039 STATISTIC(NumCacheDirtyNonLocal, "Number of dirty cached non-local responses");
00040 STATISTIC(NumUncacheNonLocal, "Number of uncached non-local responses");
00041 
00042 STATISTIC(NumCacheNonLocalPtr,
00043           "Number of fully cached non-local ptr responses");
00044 STATISTIC(NumCacheDirtyNonLocalPtr,
00045           "Number of cached, but dirty, non-local ptr responses");
00046 STATISTIC(NumUncacheNonLocalPtr,
00047           "Number of uncached non-local ptr responses");
00048 STATISTIC(NumCacheCompleteNonLocalPtr,
00049           "Number of block queries that were completely cached");
00050 
00051 // Limit for the number of instructions to scan in a block.
00052 static const unsigned int BlockScanLimit = 100;
00053 
00054 // Limit on the number of memdep results to process.
00055 static const unsigned int NumResultsLimit = 100;
00056 
00057 char MemoryDependenceAnalysis::ID = 0;
00058 
00059 // Register this pass...
00060 INITIALIZE_PASS_BEGIN(MemoryDependenceAnalysis, "memdep",
00061                 "Memory Dependence Analysis", false, true)
00062 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
00063 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
00064 INITIALIZE_PASS_END(MemoryDependenceAnalysis, "memdep",
00065                       "Memory Dependence Analysis", false, true)
00066 
00067 MemoryDependenceAnalysis::MemoryDependenceAnalysis()
00068     : FunctionPass(ID) {
00069   initializeMemoryDependenceAnalysisPass(*PassRegistry::getPassRegistry());
00070 }
00071 MemoryDependenceAnalysis::~MemoryDependenceAnalysis() {
00072 }
00073 
00074 /// Clean up memory in between runs
00075 void MemoryDependenceAnalysis::releaseMemory() {
00076   LocalDeps.clear();
00077   NonLocalDeps.clear();
00078   NonLocalPointerDeps.clear();
00079   ReverseLocalDeps.clear();
00080   ReverseNonLocalDeps.clear();
00081   ReverseNonLocalPtrDeps.clear();
00082   PredCache.clear();
00083 }
00084 
00085 /// getAnalysisUsage - Does not modify anything.  It uses Alias Analysis.
00086 ///
00087 void MemoryDependenceAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
00088   AU.setPreservesAll();
00089   AU.addRequired<AssumptionCacheTracker>();
00090   AU.addRequiredTransitive<AliasAnalysis>();
00091 }
00092 
00093 bool MemoryDependenceAnalysis::runOnFunction(Function &F) {
00094   AA = &getAnalysis<AliasAnalysis>();
00095   AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
00096   DominatorTreeWrapperPass *DTWP =
00097       getAnalysisIfAvailable<DominatorTreeWrapperPass>();
00098   DT = DTWP ? &DTWP->getDomTree() : nullptr;
00099   return false;
00100 }
00101 
00102 /// RemoveFromReverseMap - This is a helper function that removes Val from
00103 /// 'Inst's set in ReverseMap.  If the set becomes empty, remove Inst's entry.
00104 template <typename KeyTy>
00105 static void RemoveFromReverseMap(DenseMap<Instruction*,
00106                                  SmallPtrSet<KeyTy, 4> > &ReverseMap,
00107                                  Instruction *Inst, KeyTy Val) {
00108   typename DenseMap<Instruction*, SmallPtrSet<KeyTy, 4> >::iterator
00109   InstIt = ReverseMap.find(Inst);
00110   assert(InstIt != ReverseMap.end() && "Reverse map out of sync?");
00111   bool Found = InstIt->second.erase(Val);
00112   assert(Found && "Invalid reverse map!"); (void)Found;
00113   if (InstIt->second.empty())
00114     ReverseMap.erase(InstIt);
00115 }
00116 
00117 /// GetLocation - If the given instruction references a specific memory
00118 /// location, fill in Loc with the details, otherwise set Loc.Ptr to null.
00119 /// Return a ModRefInfo value describing the general behavior of the
00120 /// instruction.
00121 static AliasAnalysis::ModRefResult
00122 GetLocation(const Instruction *Inst, MemoryLocation &Loc, AliasAnalysis *AA) {
00123   if (const LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
00124     if (LI->isUnordered()) {
00125       Loc = MemoryLocation::get(LI);
00126       return AliasAnalysis::Ref;
00127     }
00128     if (LI->getOrdering() == Monotonic) {
00129       Loc = MemoryLocation::get(LI);
00130       return AliasAnalysis::ModRef;
00131     }
00132     Loc = MemoryLocation();
00133     return AliasAnalysis::ModRef;
00134   }
00135 
00136   if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
00137     if (SI->isUnordered()) {
00138       Loc = MemoryLocation::get(SI);
00139       return AliasAnalysis::Mod;
00140     }
00141     if (SI->getOrdering() == Monotonic) {
00142       Loc = MemoryLocation::get(SI);
00143       return AliasAnalysis::ModRef;
00144     }
00145     Loc = MemoryLocation();
00146     return AliasAnalysis::ModRef;
00147   }
00148 
00149   if (const VAArgInst *V = dyn_cast<VAArgInst>(Inst)) {
00150     Loc = MemoryLocation::get(V);
00151     return AliasAnalysis::ModRef;
00152   }
00153 
00154   if (const CallInst *CI = isFreeCall(Inst, AA->getTargetLibraryInfo())) {
00155     // calls to free() deallocate the entire structure
00156     Loc = MemoryLocation(CI->getArgOperand(0));
00157     return AliasAnalysis::Mod;
00158   }
00159 
00160   if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
00161     AAMDNodes AAInfo;
00162 
00163     switch (II->getIntrinsicID()) {
00164     case Intrinsic::lifetime_start:
00165     case Intrinsic::lifetime_end:
00166     case Intrinsic::invariant_start:
00167       II->getAAMetadata(AAInfo);
00168       Loc = MemoryLocation(
00169           II->getArgOperand(1),
00170           cast<ConstantInt>(II->getArgOperand(0))->getZExtValue(), AAInfo);
00171       // These intrinsics don't really modify the memory, but returning Mod
00172       // will allow them to be handled conservatively.
00173       return AliasAnalysis::Mod;
00174     case Intrinsic::invariant_end:
00175       II->getAAMetadata(AAInfo);
00176       Loc = MemoryLocation(
00177           II->getArgOperand(2),
00178           cast<ConstantInt>(II->getArgOperand(1))->getZExtValue(), AAInfo);
00179       // These intrinsics don't really modify the memory, but returning Mod
00180       // will allow them to be handled conservatively.
00181       return AliasAnalysis::Mod;
00182     default:
00183       break;
00184     }
00185   }
00186 
00187   // Otherwise, just do the coarse-grained thing that always works.
00188   if (Inst->mayWriteToMemory())
00189     return AliasAnalysis::ModRef;
00190   if (Inst->mayReadFromMemory())
00191     return AliasAnalysis::Ref;
00192   return AliasAnalysis::NoModRef;
00193 }
00194 
00195 /// getCallSiteDependencyFrom - Private helper for finding the local
00196 /// dependencies of a call site.
00197 MemDepResult MemoryDependenceAnalysis::
00198 getCallSiteDependencyFrom(CallSite CS, bool isReadOnlyCall,
00199                           BasicBlock::iterator ScanIt, BasicBlock *BB) {
00200   unsigned Limit = BlockScanLimit;
00201 
00202   // Walk backwards through the block, looking for dependencies
00203   while (ScanIt != BB->begin()) {
00204     // Limit the amount of scanning we do so we don't end up with quadratic
00205     // running time on extreme testcases.
00206     --Limit;
00207     if (!Limit)
00208       return MemDepResult::getUnknown();
00209 
00210     Instruction *Inst = --ScanIt;
00211 
00212     // If this inst is a memory op, get the pointer it accessed
00213     MemoryLocation Loc;
00214     AliasAnalysis::ModRefResult MR = GetLocation(Inst, Loc, AA);
00215     if (Loc.Ptr) {
00216       // A simple instruction.
00217       if (AA->getModRefInfo(CS, Loc) != AliasAnalysis::NoModRef)
00218         return MemDepResult::getClobber(Inst);
00219       continue;
00220     }
00221 
00222     if (auto InstCS = CallSite(Inst)) {
00223       // Debug intrinsics don't cause dependences.
00224       if (isa<DbgInfoIntrinsic>(Inst)) continue;
00225       // If these two calls do not interfere, look past it.
00226       switch (AA->getModRefInfo(CS, InstCS)) {
00227       case AliasAnalysis::NoModRef:
00228         // If the two calls are the same, return InstCS as a Def, so that
00229         // CS can be found redundant and eliminated.
00230         if (isReadOnlyCall && !(MR & AliasAnalysis::Mod) &&
00231             CS.getInstruction()->isIdenticalToWhenDefined(Inst))
00232           return MemDepResult::getDef(Inst);
00233 
00234         // Otherwise if the two calls don't interact (e.g. InstCS is readnone)
00235         // keep scanning.
00236         continue;
00237       default:
00238         return MemDepResult::getClobber(Inst);
00239       }
00240     }
00241 
00242     // If we could not obtain a pointer for the instruction and the instruction
00243     // touches memory then assume that this is a dependency.
00244     if (MR != AliasAnalysis::NoModRef)
00245       return MemDepResult::getClobber(Inst);
00246   }
00247 
00248   // No dependence found.  If this is the entry block of the function, it is
00249   // unknown, otherwise it is non-local.
00250   if (BB != &BB->getParent()->getEntryBlock())
00251     return MemDepResult::getNonLocal();
00252   return MemDepResult::getNonFuncLocal();
00253 }
00254 
00255 /// isLoadLoadClobberIfExtendedToFullWidth - Return true if LI is a load that
00256 /// would fully overlap MemLoc if done as a wider legal integer load.
00257 ///
00258 /// MemLocBase, MemLocOffset are lazily computed here the first time the
00259 /// base/offs of memloc is needed.
00260 static bool isLoadLoadClobberIfExtendedToFullWidth(const MemoryLocation &MemLoc,
00261                                                    const Value *&MemLocBase,
00262                                                    int64_t &MemLocOffs,
00263                                                    const LoadInst *LI) {
00264   const DataLayout &DL = LI->getModule()->getDataLayout();
00265 
00266   // If we haven't already computed the base/offset of MemLoc, do so now.
00267   if (!MemLocBase)
00268     MemLocBase = GetPointerBaseWithConstantOffset(MemLoc.Ptr, MemLocOffs, DL);
00269 
00270   unsigned Size = MemoryDependenceAnalysis::getLoadLoadClobberFullWidthSize(
00271       MemLocBase, MemLocOffs, MemLoc.Size, LI);
00272   return Size != 0;
00273 }
00274 
00275 /// getLoadLoadClobberFullWidthSize - This is a little bit of analysis that
00276 /// looks at a memory location for a load (specified by MemLocBase, Offs,
00277 /// and Size) and compares it against a load.  If the specified load could
00278 /// be safely widened to a larger integer load that is 1) still efficient,
00279 /// 2) safe for the target, and 3) would provide the specified memory
00280 /// location value, then this function returns the size in bytes of the
00281 /// load width to use.  If not, this returns zero.
00282 unsigned MemoryDependenceAnalysis::getLoadLoadClobberFullWidthSize(
00283     const Value *MemLocBase, int64_t MemLocOffs, unsigned MemLocSize,
00284     const LoadInst *LI) {
00285   // We can only extend simple integer loads.
00286   if (!isa<IntegerType>(LI->getType()) || !LI->isSimple()) return 0;
00287 
00288   // Load widening is hostile to ThreadSanitizer: it may cause false positives
00289   // or make the reports more cryptic (access sizes are wrong).
00290   if (LI->getParent()->getParent()->hasFnAttribute(Attribute::SanitizeThread))
00291     return 0;
00292 
00293   const DataLayout &DL = LI->getModule()->getDataLayout();
00294 
00295   // Get the base of this load.
00296   int64_t LIOffs = 0;
00297   const Value *LIBase =
00298       GetPointerBaseWithConstantOffset(LI->getPointerOperand(), LIOffs, DL);
00299 
00300   // If the two pointers are not based on the same pointer, we can't tell that
00301   // they are related.
00302   if (LIBase != MemLocBase) return 0;
00303 
00304   // Okay, the two values are based on the same pointer, but returned as
00305   // no-alias.  This happens when we have things like two byte loads at "P+1"
00306   // and "P+3".  Check to see if increasing the size of the "LI" load up to its
00307   // alignment (or the largest native integer type) will allow us to load all
00308   // the bits required by MemLoc.
00309 
00310   // If MemLoc is before LI, then no widening of LI will help us out.
00311   if (MemLocOffs < LIOffs) return 0;
00312 
00313   // Get the alignment of the load in bytes.  We assume that it is safe to load
00314   // any legal integer up to this size without a problem.  For example, if we're
00315   // looking at an i8 load on x86-32 that is known 1024 byte aligned, we can
00316   // widen it up to an i32 load.  If it is known 2-byte aligned, we can widen it
00317   // to i16.
00318   unsigned LoadAlign = LI->getAlignment();
00319 
00320   int64_t MemLocEnd = MemLocOffs+MemLocSize;
00321 
00322   // If no amount of rounding up will let MemLoc fit into LI, then bail out.
00323   if (LIOffs+LoadAlign < MemLocEnd) return 0;
00324 
00325   // This is the size of the load to try.  Start with the next larger power of
00326   // two.
00327   unsigned NewLoadByteSize = LI->getType()->getPrimitiveSizeInBits()/8U;
00328   NewLoadByteSize = NextPowerOf2(NewLoadByteSize);
00329 
00330   while (1) {
00331     // If this load size is bigger than our known alignment or would not fit
00332     // into a native integer register, then we fail.
00333     if (NewLoadByteSize > LoadAlign ||
00334         !DL.fitsInLegalInteger(NewLoadByteSize*8))
00335       return 0;
00336 
00337     if (LIOffs + NewLoadByteSize > MemLocEnd &&
00338         LI->getParent()->getParent()->hasFnAttribute(
00339             Attribute::SanitizeAddress))
00340       // We will be reading past the location accessed by the original program.
00341       // While this is safe in a regular build, Address Safety analysis tools
00342       // may start reporting false warnings. So, don't do widening.
00343       return 0;
00344 
00345     // If a load of this width would include all of MemLoc, then we succeed.
00346     if (LIOffs+NewLoadByteSize >= MemLocEnd)
00347       return NewLoadByteSize;
00348 
00349     NewLoadByteSize <<= 1;
00350   }
00351 }
00352 
00353 static bool isVolatile(Instruction *Inst) {
00354   if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
00355     return LI->isVolatile();
00356   else if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
00357     return SI->isVolatile();
00358   else if (AtomicCmpXchgInst *AI = dyn_cast<AtomicCmpXchgInst>(Inst))
00359     return AI->isVolatile();
00360   return false;
00361 }
00362 
00363 
00364 /// getPointerDependencyFrom - Return the instruction on which a memory
00365 /// location depends.  If isLoad is true, this routine ignores may-aliases with
00366 /// read-only operations.  If isLoad is false, this routine ignores may-aliases
00367 /// with reads from read-only locations.  If possible, pass the query
00368 /// instruction as well; this function may take advantage of the metadata
00369 /// annotated to the query instruction to refine the result.
00370 MemDepResult MemoryDependenceAnalysis::getPointerDependencyFrom(
00371     const MemoryLocation &MemLoc, bool isLoad, BasicBlock::iterator ScanIt,
00372     BasicBlock *BB, Instruction *QueryInst) {
00373 
00374   const Value *MemLocBase = nullptr;
00375   int64_t MemLocOffset = 0;
00376   unsigned Limit = BlockScanLimit;
00377   bool isInvariantLoad = false;
00378 
00379   // We must be careful with atomic accesses, as they may allow another thread
00380   //   to touch this location, cloberring it. We are conservative: if the
00381   //   QueryInst is not a simple (non-atomic) memory access, we automatically
00382   //   return getClobber.
00383   // If it is simple, we know based on the results of
00384   // "Compiler testing via a theory of sound optimisations in the C11/C++11
00385   //   memory model" in PLDI 2013, that a non-atomic location can only be
00386   //   clobbered between a pair of a release and an acquire action, with no
00387   //   access to the location in between.
00388   // Here is an example for giving the general intuition behind this rule.
00389   // In the following code:
00390   //   store x 0;
00391   //   release action; [1]
00392   //   acquire action; [4]
00393   //   %val = load x;
00394   // It is unsafe to replace %val by 0 because another thread may be running:
00395   //   acquire action; [2]
00396   //   store x 42;
00397   //   release action; [3]
00398   // with synchronization from 1 to 2 and from 3 to 4, resulting in %val
00399   // being 42. A key property of this program however is that if either
00400   // 1 or 4 were missing, there would be a race between the store of 42
00401   // either the store of 0 or the load (making the whole progam racy).
00402   // The paper mentionned above shows that the same property is respected
00403   // by every program that can detect any optimisation of that kind: either
00404   // it is racy (undefined) or there is a release followed by an acquire
00405   // between the pair of accesses under consideration.
00406 
00407   // If the load is invariant, we "know" that it doesn't alias *any* write. We
00408   // do want to respect mustalias results since defs are useful for value
00409   // forwarding, but any mayalias write can be assumed to be noalias.
00410   // Arguably, this logic should be pushed inside AliasAnalysis itself.
00411   if (isLoad && QueryInst) {
00412     LoadInst *LI = dyn_cast<LoadInst>(QueryInst);
00413     if (LI && LI->getMetadata(LLVMContext::MD_invariant_load) != nullptr)
00414       isInvariantLoad = true;
00415   }
00416 
00417   const DataLayout &DL = BB->getModule()->getDataLayout();
00418 
00419   // Walk backwards through the basic block, looking for dependencies.
00420   while (ScanIt != BB->begin()) {
00421     Instruction *Inst = --ScanIt;
00422 
00423     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst))
00424       // Debug intrinsics don't (and can't) cause dependencies.
00425       if (isa<DbgInfoIntrinsic>(II)) continue;
00426 
00427     // Limit the amount of scanning we do so we don't end up with quadratic
00428     // running time on extreme testcases.
00429     --Limit;
00430     if (!Limit)
00431       return MemDepResult::getUnknown();
00432 
00433     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
00434       // If we reach a lifetime begin or end marker, then the query ends here
00435       // because the value is undefined.
00436       if (II->getIntrinsicID() == Intrinsic::lifetime_start) {
00437         // FIXME: This only considers queries directly on the invariant-tagged
00438         // pointer, not on query pointers that are indexed off of them.  It'd
00439         // be nice to handle that at some point (the right approach is to use
00440         // GetPointerBaseWithConstantOffset).
00441         if (AA->isMustAlias(MemoryLocation(II->getArgOperand(1)), MemLoc))
00442           return MemDepResult::getDef(II);
00443         continue;
00444       }
00445     }
00446 
00447     // Values depend on loads if the pointers are must aliased.  This means that
00448     // a load depends on another must aliased load from the same value.
00449     // One exception is atomic loads: a value can depend on an atomic load that it
00450     // does not alias with when this atomic load indicates that another thread may
00451     // be accessing the location.
00452     if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
00453 
00454       // While volatile access cannot be eliminated, they do not have to clobber
00455       // non-aliasing locations, as normal accesses, for example, can be safely
00456       // reordered with volatile accesses.
00457       if (LI->isVolatile()) {
00458         if (!QueryInst)
00459           // Original QueryInst *may* be volatile
00460           return MemDepResult::getClobber(LI);
00461         if (isVolatile(QueryInst))
00462           // Ordering required if QueryInst is itself volatile
00463           return MemDepResult::getClobber(LI);
00464         // Otherwise, volatile doesn't imply any special ordering
00465       }
00466       
00467       // Atomic loads have complications involved.
00468       // A Monotonic (or higher) load is OK if the query inst is itself not atomic.
00469       // FIXME: This is overly conservative.
00470       if (LI->isAtomic() && LI->getOrdering() > Unordered) {
00471         if (!QueryInst)
00472           return MemDepResult::getClobber(LI);
00473         if (LI->getOrdering() != Monotonic)
00474           return MemDepResult::getClobber(LI);
00475         if (auto *QueryLI = dyn_cast<LoadInst>(QueryInst)) {
00476           if (!QueryLI->isSimple())
00477             return MemDepResult::getClobber(LI);
00478         } else if (auto *QuerySI = dyn_cast<StoreInst>(QueryInst)) {
00479           if (!QuerySI->isSimple())
00480             return MemDepResult::getClobber(LI);
00481         } else if (QueryInst->mayReadOrWriteMemory()) {
00482           return MemDepResult::getClobber(LI);
00483         }
00484       }
00485 
00486       MemoryLocation LoadLoc = MemoryLocation::get(LI);
00487 
00488       // If we found a pointer, check if it could be the same as our pointer.
00489       AliasResult R = AA->alias(LoadLoc, MemLoc);
00490 
00491       if (isLoad) {
00492         if (R == NoAlias) {
00493           // If this is an over-aligned integer load (for example,
00494           // "load i8* %P, align 4") see if it would obviously overlap with the
00495           // queried location if widened to a larger load (e.g. if the queried
00496           // location is 1 byte at P+1).  If so, return it as a load/load
00497           // clobber result, allowing the client to decide to widen the load if
00498           // it wants to.
00499           if (IntegerType *ITy = dyn_cast<IntegerType>(LI->getType())) {
00500             if (LI->getAlignment() * 8 > ITy->getPrimitiveSizeInBits() &&
00501                 isLoadLoadClobberIfExtendedToFullWidth(MemLoc, MemLocBase,
00502                                                        MemLocOffset, LI))
00503               return MemDepResult::getClobber(Inst);
00504           }
00505           continue;
00506         }
00507 
00508         // Must aliased loads are defs of each other.
00509         if (R == MustAlias)
00510           return MemDepResult::getDef(Inst);
00511 
00512 #if 0 // FIXME: Temporarily disabled. GVN is cleverly rewriting loads
00513       // in terms of clobbering loads, but since it does this by looking
00514       // at the clobbering load directly, it doesn't know about any
00515       // phi translation that may have happened along the way.
00516 
00517         // If we have a partial alias, then return this as a clobber for the
00518         // client to handle.
00519         if (R == PartialAlias)
00520           return MemDepResult::getClobber(Inst);
00521 #endif
00522 
00523         // Random may-alias loads don't depend on each other without a
00524         // dependence.
00525         continue;
00526       }
00527 
00528       // Stores don't depend on other no-aliased accesses.
00529       if (R == NoAlias)
00530         continue;
00531 
00532       // Stores don't alias loads from read-only memory.
00533       if (AA->pointsToConstantMemory(LoadLoc))
00534         continue;
00535 
00536       // Stores depend on may/must aliased loads.
00537       return MemDepResult::getDef(Inst);
00538     }
00539 
00540     if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
00541       // Atomic stores have complications involved.
00542       // A Monotonic store is OK if the query inst is itself not atomic.
00543       // FIXME: This is overly conservative.
00544       if (!SI->isUnordered()) {
00545         if (!QueryInst)
00546           return MemDepResult::getClobber(SI);
00547         if (SI->getOrdering() != Monotonic)
00548           return MemDepResult::getClobber(SI);
00549         if (auto *QueryLI = dyn_cast<LoadInst>(QueryInst)) {
00550           if (!QueryLI->isSimple())
00551             return MemDepResult::getClobber(SI);
00552         } else if (auto *QuerySI = dyn_cast<StoreInst>(QueryInst)) {
00553           if (!QuerySI->isSimple())
00554             return MemDepResult::getClobber(SI);
00555         } else if (QueryInst->mayReadOrWriteMemory()) {
00556           return MemDepResult::getClobber(SI);
00557         }
00558       }
00559 
00560       // FIXME: this is overly conservative.
00561       // While volatile access cannot be eliminated, they do not have to clobber
00562       // non-aliasing locations, as normal accesses can for example be reordered
00563       // with volatile accesses.
00564       if (SI->isVolatile())
00565         return MemDepResult::getClobber(SI);
00566 
00567       // If alias analysis can tell that this store is guaranteed to not modify
00568       // the query pointer, ignore it.  Use getModRefInfo to handle cases where
00569       // the query pointer points to constant memory etc.
00570       if (AA->getModRefInfo(SI, MemLoc) == AliasAnalysis::NoModRef)
00571         continue;
00572 
00573       // Ok, this store might clobber the query pointer.  Check to see if it is
00574       // a must alias: in this case, we want to return this as a def.
00575       MemoryLocation StoreLoc = MemoryLocation::get(SI);
00576 
00577       // If we found a pointer, check if it could be the same as our pointer.
00578       AliasResult R = AA->alias(StoreLoc, MemLoc);
00579 
00580       if (R == NoAlias)
00581         continue;
00582       if (R == MustAlias)
00583         return MemDepResult::getDef(Inst);
00584       if (isInvariantLoad)
00585        continue;
00586       return MemDepResult::getClobber(Inst);
00587     }
00588 
00589     // If this is an allocation, and if we know that the accessed pointer is to
00590     // the allocation, return Def.  This means that there is no dependence and
00591     // the access can be optimized based on that.  For example, a load could
00592     // turn into undef.
00593     // Note: Only determine this to be a malloc if Inst is the malloc call, not
00594     // a subsequent bitcast of the malloc call result.  There can be stores to
00595     // the malloced memory between the malloc call and its bitcast uses, and we
00596     // need to continue scanning until the malloc call.
00597     const TargetLibraryInfo *TLI = AA->getTargetLibraryInfo();
00598     if (isa<AllocaInst>(Inst) || isNoAliasFn(Inst, TLI)) {
00599       const Value *AccessPtr = GetUnderlyingObject(MemLoc.Ptr, DL);
00600 
00601       if (AccessPtr == Inst || AA->isMustAlias(Inst, AccessPtr))
00602         return MemDepResult::getDef(Inst);
00603       if (isInvariantLoad)
00604         continue;
00605       // Be conservative if the accessed pointer may alias the allocation.
00606       if (AA->alias(Inst, AccessPtr) != NoAlias)
00607         return MemDepResult::getClobber(Inst);
00608       // If the allocation is not aliased and does not read memory (like
00609       // strdup), it is safe to ignore.
00610       if (isa<AllocaInst>(Inst) ||
00611           isMallocLikeFn(Inst, TLI) || isCallocLikeFn(Inst, TLI))
00612         continue;
00613     }
00614 
00615     if (isInvariantLoad)
00616        continue;
00617 
00618     // See if this instruction (e.g. a call or vaarg) mod/ref's the pointer.
00619     AliasAnalysis::ModRefResult MR = AA->getModRefInfo(Inst, MemLoc);
00620     // If necessary, perform additional analysis.
00621     if (MR == AliasAnalysis::ModRef)
00622       MR = AA->callCapturesBefore(Inst, MemLoc, DT);
00623     switch (MR) {
00624     case AliasAnalysis::NoModRef:
00625       // If the call has no effect on the queried pointer, just ignore it.
00626       continue;
00627     case AliasAnalysis::Mod:
00628       return MemDepResult::getClobber(Inst);
00629     case AliasAnalysis::Ref:
00630       // If the call is known to never store to the pointer, and if this is a
00631       // load query, we can safely ignore it (scan past it).
00632       if (isLoad)
00633         continue;
00634     default:
00635       // Otherwise, there is a potential dependence.  Return a clobber.
00636       return MemDepResult::getClobber(Inst);
00637     }
00638   }
00639 
00640   // No dependence found.  If this is the entry block of the function, it is
00641   // unknown, otherwise it is non-local.
00642   if (BB != &BB->getParent()->getEntryBlock())
00643     return MemDepResult::getNonLocal();
00644   return MemDepResult::getNonFuncLocal();
00645 }
00646 
00647 /// getDependency - Return the instruction on which a memory operation
00648 /// depends.
00649 MemDepResult MemoryDependenceAnalysis::getDependency(Instruction *QueryInst) {
00650   Instruction *ScanPos = QueryInst;
00651 
00652   // Check for a cached result
00653   MemDepResult &LocalCache = LocalDeps[QueryInst];
00654 
00655   // If the cached entry is non-dirty, just return it.  Note that this depends
00656   // on MemDepResult's default constructing to 'dirty'.
00657   if (!LocalCache.isDirty())
00658     return LocalCache;
00659 
00660   // Otherwise, if we have a dirty entry, we know we can start the scan at that
00661   // instruction, which may save us some work.
00662   if (Instruction *Inst = LocalCache.getInst()) {
00663     ScanPos = Inst;
00664 
00665     RemoveFromReverseMap(ReverseLocalDeps, Inst, QueryInst);
00666   }
00667 
00668   BasicBlock *QueryParent = QueryInst->getParent();
00669 
00670   // Do the scan.
00671   if (BasicBlock::iterator(QueryInst) == QueryParent->begin()) {
00672     // No dependence found.  If this is the entry block of the function, it is
00673     // unknown, otherwise it is non-local.
00674     if (QueryParent != &QueryParent->getParent()->getEntryBlock())
00675       LocalCache = MemDepResult::getNonLocal();
00676     else
00677       LocalCache = MemDepResult::getNonFuncLocal();
00678   } else {
00679     MemoryLocation MemLoc;
00680     AliasAnalysis::ModRefResult MR = GetLocation(QueryInst, MemLoc, AA);
00681     if (MemLoc.Ptr) {
00682       // If we can do a pointer scan, make it happen.
00683       bool isLoad = !(MR & AliasAnalysis::Mod);
00684       if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(QueryInst))
00685         isLoad |= II->getIntrinsicID() == Intrinsic::lifetime_start;
00686 
00687       LocalCache = getPointerDependencyFrom(MemLoc, isLoad, ScanPos,
00688                                             QueryParent, QueryInst);
00689     } else if (isa<CallInst>(QueryInst) || isa<InvokeInst>(QueryInst)) {
00690       CallSite QueryCS(QueryInst);
00691       bool isReadOnly = AA->onlyReadsMemory(QueryCS);
00692       LocalCache = getCallSiteDependencyFrom(QueryCS, isReadOnly, ScanPos,
00693                                              QueryParent);
00694     } else
00695       // Non-memory instruction.
00696       LocalCache = MemDepResult::getUnknown();
00697   }
00698 
00699   // Remember the result!
00700   if (Instruction *I = LocalCache.getInst())
00701     ReverseLocalDeps[I].insert(QueryInst);
00702 
00703   return LocalCache;
00704 }
00705 
00706 #ifndef NDEBUG
00707 /// AssertSorted - This method is used when -debug is specified to verify that
00708 /// cache arrays are properly kept sorted.
00709 static void AssertSorted(MemoryDependenceAnalysis::NonLocalDepInfo &Cache,
00710                          int Count = -1) {
00711   if (Count == -1) Count = Cache.size();
00712   if (Count == 0) return;
00713 
00714   for (unsigned i = 1; i != unsigned(Count); ++i)
00715     assert(!(Cache[i] < Cache[i-1]) && "Cache isn't sorted!");
00716 }
00717 #endif
00718 
00719 /// getNonLocalCallDependency - Perform a full dependency query for the
00720 /// specified call, returning the set of blocks that the value is
00721 /// potentially live across.  The returned set of results will include a
00722 /// "NonLocal" result for all blocks where the value is live across.
00723 ///
00724 /// This method assumes the instruction returns a "NonLocal" dependency
00725 /// within its own block.
00726 ///
00727 /// This returns a reference to an internal data structure that may be
00728 /// invalidated on the next non-local query or when an instruction is
00729 /// removed.  Clients must copy this data if they want it around longer than
00730 /// that.
00731 const MemoryDependenceAnalysis::NonLocalDepInfo &
00732 MemoryDependenceAnalysis::getNonLocalCallDependency(CallSite QueryCS) {
00733   assert(getDependency(QueryCS.getInstruction()).isNonLocal() &&
00734  "getNonLocalCallDependency should only be used on calls with non-local deps!");
00735   PerInstNLInfo &CacheP = NonLocalDeps[QueryCS.getInstruction()];
00736   NonLocalDepInfo &Cache = CacheP.first;
00737 
00738   /// DirtyBlocks - This is the set of blocks that need to be recomputed.  In
00739   /// the cached case, this can happen due to instructions being deleted etc. In
00740   /// the uncached case, this starts out as the set of predecessors we care
00741   /// about.
00742   SmallVector<BasicBlock*, 32> DirtyBlocks;
00743 
00744   if (!Cache.empty()) {
00745     // Okay, we have a cache entry.  If we know it is not dirty, just return it
00746     // with no computation.
00747     if (!CacheP.second) {
00748       ++NumCacheNonLocal;
00749       return Cache;
00750     }
00751 
00752     // If we already have a partially computed set of results, scan them to
00753     // determine what is dirty, seeding our initial DirtyBlocks worklist.
00754     for (NonLocalDepInfo::iterator I = Cache.begin(), E = Cache.end();
00755        I != E; ++I)
00756       if (I->getResult().isDirty())
00757         DirtyBlocks.push_back(I->getBB());
00758 
00759     // Sort the cache so that we can do fast binary search lookups below.
00760     std::sort(Cache.begin(), Cache.end());
00761 
00762     ++NumCacheDirtyNonLocal;
00763     //cerr << "CACHED CASE: " << DirtyBlocks.size() << " dirty: "
00764     //     << Cache.size() << " cached: " << *QueryInst;
00765   } else {
00766     // Seed DirtyBlocks with each of the preds of QueryInst's block.
00767     BasicBlock *QueryBB = QueryCS.getInstruction()->getParent();
00768     for (BasicBlock *Pred : PredCache.get(QueryBB))
00769       DirtyBlocks.push_back(Pred);
00770     ++NumUncacheNonLocal;
00771   }
00772 
00773   // isReadonlyCall - If this is a read-only call, we can be more aggressive.
00774   bool isReadonlyCall = AA->onlyReadsMemory(QueryCS);
00775 
00776   SmallPtrSet<BasicBlock*, 64> Visited;
00777 
00778   unsigned NumSortedEntries = Cache.size();
00779   DEBUG(AssertSorted(Cache));
00780 
00781   // Iterate while we still have blocks to update.
00782   while (!DirtyBlocks.empty()) {
00783     BasicBlock *DirtyBB = DirtyBlocks.back();
00784     DirtyBlocks.pop_back();
00785 
00786     // Already processed this block?
00787     if (!Visited.insert(DirtyBB).second)
00788       continue;
00789 
00790     // Do a binary search to see if we already have an entry for this block in
00791     // the cache set.  If so, find it.
00792     DEBUG(AssertSorted(Cache, NumSortedEntries));
00793     NonLocalDepInfo::iterator Entry =
00794       std::upper_bound(Cache.begin(), Cache.begin()+NumSortedEntries,
00795                        NonLocalDepEntry(DirtyBB));
00796     if (Entry != Cache.begin() && std::prev(Entry)->getBB() == DirtyBB)
00797       --Entry;
00798 
00799     NonLocalDepEntry *ExistingResult = nullptr;
00800     if (Entry != Cache.begin()+NumSortedEntries &&
00801         Entry->getBB() == DirtyBB) {
00802       // If we already have an entry, and if it isn't already dirty, the block
00803       // is done.
00804       if (!Entry->getResult().isDirty())
00805         continue;
00806 
00807       // Otherwise, remember this slot so we can update the value.
00808       ExistingResult = &*Entry;
00809     }
00810 
00811     // If the dirty entry has a pointer, start scanning from it so we don't have
00812     // to rescan the entire block.
00813     BasicBlock::iterator ScanPos = DirtyBB->end();
00814     if (ExistingResult) {
00815       if (Instruction *Inst = ExistingResult->getResult().getInst()) {
00816         ScanPos = Inst;
00817         // We're removing QueryInst's use of Inst.
00818         RemoveFromReverseMap(ReverseNonLocalDeps, Inst,
00819                              QueryCS.getInstruction());
00820       }
00821     }
00822 
00823     // Find out if this block has a local dependency for QueryInst.
00824     MemDepResult Dep;
00825 
00826     if (ScanPos != DirtyBB->begin()) {
00827       Dep = getCallSiteDependencyFrom(QueryCS, isReadonlyCall,ScanPos, DirtyBB);
00828     } else if (DirtyBB != &DirtyBB->getParent()->getEntryBlock()) {
00829       // No dependence found.  If this is the entry block of the function, it is
00830       // a clobber, otherwise it is unknown.
00831       Dep = MemDepResult::getNonLocal();
00832     } else {
00833       Dep = MemDepResult::getNonFuncLocal();
00834     }
00835 
00836     // If we had a dirty entry for the block, update it.  Otherwise, just add
00837     // a new entry.
00838     if (ExistingResult)
00839       ExistingResult->setResult(Dep);
00840     else
00841       Cache.push_back(NonLocalDepEntry(DirtyBB, Dep));
00842 
00843     // If the block has a dependency (i.e. it isn't completely transparent to
00844     // the value), remember the association!
00845     if (!Dep.isNonLocal()) {
00846       // Keep the ReverseNonLocalDeps map up to date so we can efficiently
00847       // update this when we remove instructions.
00848       if (Instruction *Inst = Dep.getInst())
00849         ReverseNonLocalDeps[Inst].insert(QueryCS.getInstruction());
00850     } else {
00851 
00852       // If the block *is* completely transparent to the load, we need to check
00853       // the predecessors of this block.  Add them to our worklist.
00854       for (BasicBlock *Pred : PredCache.get(DirtyBB))
00855         DirtyBlocks.push_back(Pred);
00856     }
00857   }
00858 
00859   return Cache;
00860 }
00861 
00862 /// getNonLocalPointerDependency - Perform a full dependency query for an
00863 /// access to the specified (non-volatile) memory location, returning the
00864 /// set of instructions that either define or clobber the value.
00865 ///
00866 /// This method assumes the pointer has a "NonLocal" dependency within its
00867 /// own block.
00868 ///
00869 void MemoryDependenceAnalysis::
00870 getNonLocalPointerDependency(Instruction *QueryInst,
00871                              SmallVectorImpl<NonLocalDepResult> &Result) {
00872   const MemoryLocation Loc = MemoryLocation::get(QueryInst);
00873   bool isLoad = isa<LoadInst>(QueryInst);
00874   BasicBlock *FromBB = QueryInst->getParent();
00875   assert(FromBB);
00876 
00877   assert(Loc.Ptr->getType()->isPointerTy() &&
00878          "Can't get pointer deps of a non-pointer!");
00879   Result.clear();
00880   
00881   // This routine does not expect to deal with volatile instructions.
00882   // Doing so would require piping through the QueryInst all the way through.
00883   // TODO: volatiles can't be elided, but they can be reordered with other
00884   // non-volatile accesses.
00885 
00886   // We currently give up on any instruction which is ordered, but we do handle
00887   // atomic instructions which are unordered.
00888   // TODO: Handle ordered instructions
00889   auto isOrdered = [](Instruction *Inst) {
00890     if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
00891       return !LI->isUnordered();
00892     } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
00893       return !SI->isUnordered();
00894     }
00895     return false;
00896   };
00897   if (isVolatile(QueryInst) || isOrdered(QueryInst)) {
00898     Result.push_back(NonLocalDepResult(FromBB,
00899                                        MemDepResult::getUnknown(),
00900                                        const_cast<Value *>(Loc.Ptr)));
00901     return;
00902   }
00903   const DataLayout &DL = FromBB->getModule()->getDataLayout();
00904   PHITransAddr Address(const_cast<Value *>(Loc.Ptr), DL, AC);
00905 
00906   // This is the set of blocks we've inspected, and the pointer we consider in
00907   // each block.  Because of critical edges, we currently bail out if querying
00908   // a block with multiple different pointers.  This can happen during PHI
00909   // translation.
00910   DenseMap<BasicBlock*, Value*> Visited;
00911   if (!getNonLocalPointerDepFromBB(QueryInst, Address, Loc, isLoad, FromBB,
00912                                    Result, Visited, true))
00913     return;
00914   Result.clear();
00915   Result.push_back(NonLocalDepResult(FromBB,
00916                                      MemDepResult::getUnknown(),
00917                                      const_cast<Value *>(Loc.Ptr)));
00918 }
00919 
00920 /// GetNonLocalInfoForBlock - Compute the memdep value for BB with
00921 /// Pointer/PointeeSize using either cached information in Cache or by doing a
00922 /// lookup (which may use dirty cache info if available).  If we do a lookup,
00923 /// add the result to the cache.
00924 MemDepResult MemoryDependenceAnalysis::GetNonLocalInfoForBlock(
00925     Instruction *QueryInst, const MemoryLocation &Loc, bool isLoad,
00926     BasicBlock *BB, NonLocalDepInfo *Cache, unsigned NumSortedEntries) {
00927 
00928   // Do a binary search to see if we already have an entry for this block in
00929   // the cache set.  If so, find it.
00930   NonLocalDepInfo::iterator Entry =
00931     std::upper_bound(Cache->begin(), Cache->begin()+NumSortedEntries,
00932                      NonLocalDepEntry(BB));
00933   if (Entry != Cache->begin() && (Entry-1)->getBB() == BB)
00934     --Entry;
00935 
00936   NonLocalDepEntry *ExistingResult = nullptr;
00937   if (Entry != Cache->begin()+NumSortedEntries && Entry->getBB() == BB)
00938     ExistingResult = &*Entry;
00939 
00940   // If we have a cached entry, and it is non-dirty, use it as the value for
00941   // this dependency.
00942   if (ExistingResult && !ExistingResult->getResult().isDirty()) {
00943     ++NumCacheNonLocalPtr;
00944     return ExistingResult->getResult();
00945   }
00946 
00947   // Otherwise, we have to scan for the value.  If we have a dirty cache
00948   // entry, start scanning from its position, otherwise we scan from the end
00949   // of the block.
00950   BasicBlock::iterator ScanPos = BB->end();
00951   if (ExistingResult && ExistingResult->getResult().getInst()) {
00952     assert(ExistingResult->getResult().getInst()->getParent() == BB &&
00953            "Instruction invalidated?");
00954     ++NumCacheDirtyNonLocalPtr;
00955     ScanPos = ExistingResult->getResult().getInst();
00956 
00957     // Eliminating the dirty entry from 'Cache', so update the reverse info.
00958     ValueIsLoadPair CacheKey(Loc.Ptr, isLoad);
00959     RemoveFromReverseMap(ReverseNonLocalPtrDeps, ScanPos, CacheKey);
00960   } else {
00961     ++NumUncacheNonLocalPtr;
00962   }
00963 
00964   // Scan the block for the dependency.
00965   MemDepResult Dep = getPointerDependencyFrom(Loc, isLoad, ScanPos, BB,
00966                                               QueryInst);
00967 
00968   // If we had a dirty entry for the block, update it.  Otherwise, just add
00969   // a new entry.
00970   if (ExistingResult)
00971     ExistingResult->setResult(Dep);
00972   else
00973     Cache->push_back(NonLocalDepEntry(BB, Dep));
00974 
00975   // If the block has a dependency (i.e. it isn't completely transparent to
00976   // the value), remember the reverse association because we just added it
00977   // to Cache!
00978   if (!Dep.isDef() && !Dep.isClobber())
00979     return Dep;
00980 
00981   // Keep the ReverseNonLocalPtrDeps map up to date so we can efficiently
00982   // update MemDep when we remove instructions.
00983   Instruction *Inst = Dep.getInst();
00984   assert(Inst && "Didn't depend on anything?");
00985   ValueIsLoadPair CacheKey(Loc.Ptr, isLoad);
00986   ReverseNonLocalPtrDeps[Inst].insert(CacheKey);
00987   return Dep;
00988 }
00989 
00990 /// SortNonLocalDepInfoCache - Sort the NonLocalDepInfo cache, given a certain
00991 /// number of elements in the array that are already properly ordered.  This is
00992 /// optimized for the case when only a few entries are added.
00993 static void
00994 SortNonLocalDepInfoCache(MemoryDependenceAnalysis::NonLocalDepInfo &Cache,
00995                          unsigned NumSortedEntries) {
00996   switch (Cache.size() - NumSortedEntries) {
00997   case 0:
00998     // done, no new entries.
00999     break;
01000   case 2: {
01001     // Two new entries, insert the last one into place.
01002     NonLocalDepEntry Val = Cache.back();
01003     Cache.pop_back();
01004     MemoryDependenceAnalysis::NonLocalDepInfo::iterator Entry =
01005       std::upper_bound(Cache.begin(), Cache.end()-1, Val);
01006     Cache.insert(Entry, Val);
01007     // FALL THROUGH.
01008   }
01009   case 1:
01010     // One new entry, Just insert the new value at the appropriate position.
01011     if (Cache.size() != 1) {
01012       NonLocalDepEntry Val = Cache.back();
01013       Cache.pop_back();
01014       MemoryDependenceAnalysis::NonLocalDepInfo::iterator Entry =
01015         std::upper_bound(Cache.begin(), Cache.end(), Val);
01016       Cache.insert(Entry, Val);
01017     }
01018     break;
01019   default:
01020     // Added many values, do a full scale sort.
01021     std::sort(Cache.begin(), Cache.end());
01022     break;
01023   }
01024 }
01025 
01026 /// getNonLocalPointerDepFromBB - Perform a dependency query based on
01027 /// pointer/pointeesize starting at the end of StartBB.  Add any clobber/def
01028 /// results to the results vector and keep track of which blocks are visited in
01029 /// 'Visited'.
01030 ///
01031 /// This has special behavior for the first block queries (when SkipFirstBlock
01032 /// is true).  In this special case, it ignores the contents of the specified
01033 /// block and starts returning dependence info for its predecessors.
01034 ///
01035 /// This function returns false on success, or true to indicate that it could
01036 /// not compute dependence information for some reason.  This should be treated
01037 /// as a clobber dependence on the first instruction in the predecessor block.
01038 bool MemoryDependenceAnalysis::getNonLocalPointerDepFromBB(
01039     Instruction *QueryInst, const PHITransAddr &Pointer,
01040     const MemoryLocation &Loc, bool isLoad, BasicBlock *StartBB,
01041     SmallVectorImpl<NonLocalDepResult> &Result,
01042     DenseMap<BasicBlock *, Value *> &Visited, bool SkipFirstBlock) {
01043   // Look up the cached info for Pointer.
01044   ValueIsLoadPair CacheKey(Pointer.getAddr(), isLoad);
01045 
01046   // Set up a temporary NLPI value. If the map doesn't yet have an entry for
01047   // CacheKey, this value will be inserted as the associated value. Otherwise,
01048   // it'll be ignored, and we'll have to check to see if the cached size and
01049   // aa tags are consistent with the current query.
01050   NonLocalPointerInfo InitialNLPI;
01051   InitialNLPI.Size = Loc.Size;
01052   InitialNLPI.AATags = Loc.AATags;
01053 
01054   // Get the NLPI for CacheKey, inserting one into the map if it doesn't
01055   // already have one.
01056   std::pair<CachedNonLocalPointerInfo::iterator, bool> Pair =
01057     NonLocalPointerDeps.insert(std::make_pair(CacheKey, InitialNLPI));
01058   NonLocalPointerInfo *CacheInfo = &Pair.first->second;
01059 
01060   // If we already have a cache entry for this CacheKey, we may need to do some
01061   // work to reconcile the cache entry and the current query.
01062   if (!Pair.second) {
01063     if (CacheInfo->Size < Loc.Size) {
01064       // The query's Size is greater than the cached one. Throw out the
01065       // cached data and proceed with the query at the greater size.
01066       CacheInfo->Pair = BBSkipFirstBlockPair();
01067       CacheInfo->Size = Loc.Size;
01068       for (NonLocalDepInfo::iterator DI = CacheInfo->NonLocalDeps.begin(),
01069            DE = CacheInfo->NonLocalDeps.end(); DI != DE; ++DI)
01070         if (Instruction *Inst = DI->getResult().getInst())
01071           RemoveFromReverseMap(ReverseNonLocalPtrDeps, Inst, CacheKey);
01072       CacheInfo->NonLocalDeps.clear();
01073     } else if (CacheInfo->Size > Loc.Size) {
01074       // This query's Size is less than the cached one. Conservatively restart
01075       // the query using the greater size.
01076       return getNonLocalPointerDepFromBB(QueryInst, Pointer,
01077                                          Loc.getWithNewSize(CacheInfo->Size),
01078                                          isLoad, StartBB, Result, Visited,
01079                                          SkipFirstBlock);
01080     }
01081 
01082     // If the query's AATags are inconsistent with the cached one,
01083     // conservatively throw out the cached data and restart the query with
01084     // no tag if needed.
01085     if (CacheInfo->AATags != Loc.AATags) {
01086       if (CacheInfo->AATags) {
01087         CacheInfo->Pair = BBSkipFirstBlockPair();
01088         CacheInfo->AATags = AAMDNodes();
01089         for (NonLocalDepInfo::iterator DI = CacheInfo->NonLocalDeps.begin(),
01090              DE = CacheInfo->NonLocalDeps.end(); DI != DE; ++DI)
01091           if (Instruction *Inst = DI->getResult().getInst())
01092             RemoveFromReverseMap(ReverseNonLocalPtrDeps, Inst, CacheKey);
01093         CacheInfo->NonLocalDeps.clear();
01094       }
01095       if (Loc.AATags)
01096         return getNonLocalPointerDepFromBB(QueryInst,
01097                                            Pointer, Loc.getWithoutAATags(),
01098                                            isLoad, StartBB, Result, Visited,
01099                                            SkipFirstBlock);
01100     }
01101   }
01102 
01103   NonLocalDepInfo *Cache = &CacheInfo->NonLocalDeps;
01104 
01105   // If we have valid cached information for exactly the block we are
01106   // investigating, just return it with no recomputation.
01107   if (CacheInfo->Pair == BBSkipFirstBlockPair(StartBB, SkipFirstBlock)) {
01108     // We have a fully cached result for this query then we can just return the
01109     // cached results and populate the visited set.  However, we have to verify
01110     // that we don't already have conflicting results for these blocks.  Check
01111     // to ensure that if a block in the results set is in the visited set that
01112     // it was for the same pointer query.
01113     if (!Visited.empty()) {
01114       for (NonLocalDepInfo::iterator I = Cache->begin(), E = Cache->end();
01115            I != E; ++I) {
01116         DenseMap<BasicBlock*, Value*>::iterator VI = Visited.find(I->getBB());
01117         if (VI == Visited.end() || VI->second == Pointer.getAddr())
01118           continue;
01119 
01120         // We have a pointer mismatch in a block.  Just return clobber, saying
01121         // that something was clobbered in this result.  We could also do a
01122         // non-fully cached query, but there is little point in doing this.
01123         return true;
01124       }
01125     }
01126 
01127     Value *Addr = Pointer.getAddr();
01128     for (NonLocalDepInfo::iterator I = Cache->begin(), E = Cache->end();
01129          I != E; ++I) {
01130       Visited.insert(std::make_pair(I->getBB(), Addr));
01131       if (I->getResult().isNonLocal()) {
01132         continue;
01133       }
01134 
01135       if (!DT) {
01136         Result.push_back(NonLocalDepResult(I->getBB(),
01137                                            MemDepResult::getUnknown(),
01138                                            Addr));
01139       } else if (DT->isReachableFromEntry(I->getBB())) {
01140         Result.push_back(NonLocalDepResult(I->getBB(), I->getResult(), Addr));
01141       }
01142     }
01143     ++NumCacheCompleteNonLocalPtr;
01144     return false;
01145   }
01146 
01147   // Otherwise, either this is a new block, a block with an invalid cache
01148   // pointer or one that we're about to invalidate by putting more info into it
01149   // than its valid cache info.  If empty, the result will be valid cache info,
01150   // otherwise it isn't.
01151   if (Cache->empty())
01152     CacheInfo->Pair = BBSkipFirstBlockPair(StartBB, SkipFirstBlock);
01153   else
01154     CacheInfo->Pair = BBSkipFirstBlockPair();
01155 
01156   SmallVector<BasicBlock*, 32> Worklist;
01157   Worklist.push_back(StartBB);
01158 
01159   // PredList used inside loop.
01160   SmallVector<std::pair<BasicBlock*, PHITransAddr>, 16> PredList;
01161 
01162   // Keep track of the entries that we know are sorted.  Previously cached
01163   // entries will all be sorted.  The entries we add we only sort on demand (we
01164   // don't insert every element into its sorted position).  We know that we
01165   // won't get any reuse from currently inserted values, because we don't
01166   // revisit blocks after we insert info for them.
01167   unsigned NumSortedEntries = Cache->size();
01168   DEBUG(AssertSorted(*Cache));
01169 
01170   while (!Worklist.empty()) {
01171     BasicBlock *BB = Worklist.pop_back_val();
01172 
01173     // If we do process a large number of blocks it becomes very expensive and
01174     // likely it isn't worth worrying about
01175     if (Result.size() > NumResultsLimit) {
01176       Worklist.clear();
01177       // Sort it now (if needed) so that recursive invocations of
01178       // getNonLocalPointerDepFromBB and other routines that could reuse the
01179       // cache value will only see properly sorted cache arrays.
01180       if (Cache && NumSortedEntries != Cache->size()) {
01181         SortNonLocalDepInfoCache(*Cache, NumSortedEntries);
01182       }
01183       // Since we bail out, the "Cache" set won't contain all of the
01184       // results for the query.  This is ok (we can still use it to accelerate
01185       // specific block queries) but we can't do the fastpath "return all
01186       // results from the set".  Clear out the indicator for this.
01187       CacheInfo->Pair = BBSkipFirstBlockPair();
01188       return true;
01189     }
01190 
01191     // Skip the first block if we have it.
01192     if (!SkipFirstBlock) {
01193       // Analyze the dependency of *Pointer in FromBB.  See if we already have
01194       // been here.
01195       assert(Visited.count(BB) && "Should check 'visited' before adding to WL");
01196 
01197       // Get the dependency info for Pointer in BB.  If we have cached
01198       // information, we will use it, otherwise we compute it.
01199       DEBUG(AssertSorted(*Cache, NumSortedEntries));
01200       MemDepResult Dep = GetNonLocalInfoForBlock(QueryInst,
01201                                                  Loc, isLoad, BB, Cache,
01202                                                  NumSortedEntries);
01203 
01204       // If we got a Def or Clobber, add this to the list of results.
01205       if (!Dep.isNonLocal()) {
01206         if (!DT) {
01207           Result.push_back(NonLocalDepResult(BB,
01208                                              MemDepResult::getUnknown(),
01209                                              Pointer.getAddr()));
01210           continue;
01211         } else if (DT->isReachableFromEntry(BB)) {
01212           Result.push_back(NonLocalDepResult(BB, Dep, Pointer.getAddr()));
01213           continue;
01214         }
01215       }
01216     }
01217 
01218     // If 'Pointer' is an instruction defined in this block, then we need to do
01219     // phi translation to change it into a value live in the predecessor block.
01220     // If not, we just add the predecessors to the worklist and scan them with
01221     // the same Pointer.
01222     if (!Pointer.NeedsPHITranslationFromBlock(BB)) {
01223       SkipFirstBlock = false;
01224       SmallVector<BasicBlock*, 16> NewBlocks;
01225       for (BasicBlock *Pred : PredCache.get(BB)) {
01226         // Verify that we haven't looked at this block yet.
01227         std::pair<DenseMap<BasicBlock*,Value*>::iterator, bool>
01228           InsertRes = Visited.insert(std::make_pair(Pred, Pointer.getAddr()));
01229         if (InsertRes.second) {
01230           // First time we've looked at *PI.
01231           NewBlocks.push_back(Pred);
01232           continue;
01233         }
01234 
01235         // If we have seen this block before, but it was with a different
01236         // pointer then we have a phi translation failure and we have to treat
01237         // this as a clobber.
01238         if (InsertRes.first->second != Pointer.getAddr()) {
01239           // Make sure to clean up the Visited map before continuing on to
01240           // PredTranslationFailure.
01241           for (unsigned i = 0; i < NewBlocks.size(); i++)
01242             Visited.erase(NewBlocks[i]);
01243           goto PredTranslationFailure;
01244         }
01245       }
01246       Worklist.append(NewBlocks.begin(), NewBlocks.end());
01247       continue;
01248     }
01249 
01250     // We do need to do phi translation, if we know ahead of time we can't phi
01251     // translate this value, don't even try.
01252     if (!Pointer.IsPotentiallyPHITranslatable())
01253       goto PredTranslationFailure;
01254 
01255     // We may have added values to the cache list before this PHI translation.
01256     // If so, we haven't done anything to ensure that the cache remains sorted.
01257     // Sort it now (if needed) so that recursive invocations of
01258     // getNonLocalPointerDepFromBB and other routines that could reuse the cache
01259     // value will only see properly sorted cache arrays.
01260     if (Cache && NumSortedEntries != Cache->size()) {
01261       SortNonLocalDepInfoCache(*Cache, NumSortedEntries);
01262       NumSortedEntries = Cache->size();
01263     }
01264     Cache = nullptr;
01265 
01266     PredList.clear();
01267     for (BasicBlock *Pred : PredCache.get(BB)) {
01268       PredList.push_back(std::make_pair(Pred, Pointer));
01269 
01270       // Get the PHI translated pointer in this predecessor.  This can fail if
01271       // not translatable, in which case the getAddr() returns null.
01272       PHITransAddr &PredPointer = PredList.back().second;
01273       PredPointer.PHITranslateValue(BB, Pred, DT, /*MustDominate=*/false);
01274       Value *PredPtrVal = PredPointer.getAddr();
01275 
01276       // Check to see if we have already visited this pred block with another
01277       // pointer.  If so, we can't do this lookup.  This failure can occur
01278       // with PHI translation when a critical edge exists and the PHI node in
01279       // the successor translates to a pointer value different than the
01280       // pointer the block was first analyzed with.
01281       std::pair<DenseMap<BasicBlock*,Value*>::iterator, bool>
01282         InsertRes = Visited.insert(std::make_pair(Pred, PredPtrVal));
01283 
01284       if (!InsertRes.second) {
01285         // We found the pred; take it off the list of preds to visit.
01286         PredList.pop_back();
01287 
01288         // If the predecessor was visited with PredPtr, then we already did
01289         // the analysis and can ignore it.
01290         if (InsertRes.first->second == PredPtrVal)
01291           continue;
01292 
01293         // Otherwise, the block was previously analyzed with a different
01294         // pointer.  We can't represent the result of this case, so we just
01295         // treat this as a phi translation failure.
01296 
01297         // Make sure to clean up the Visited map before continuing on to
01298         // PredTranslationFailure.
01299         for (unsigned i = 0, n = PredList.size(); i < n; ++i)
01300           Visited.erase(PredList[i].first);
01301 
01302         goto PredTranslationFailure;
01303       }
01304     }
01305 
01306     // Actually process results here; this need to be a separate loop to avoid
01307     // calling getNonLocalPointerDepFromBB for blocks we don't want to return
01308     // any results for.  (getNonLocalPointerDepFromBB will modify our
01309     // datastructures in ways the code after the PredTranslationFailure label
01310     // doesn't expect.)
01311     for (unsigned i = 0, n = PredList.size(); i < n; ++i) {
01312       BasicBlock *Pred = PredList[i].first;
01313       PHITransAddr &PredPointer = PredList[i].second;
01314       Value *PredPtrVal = PredPointer.getAddr();
01315 
01316       bool CanTranslate = true;
01317       // If PHI translation was unable to find an available pointer in this
01318       // predecessor, then we have to assume that the pointer is clobbered in
01319       // that predecessor.  We can still do PRE of the load, which would insert
01320       // a computation of the pointer in this predecessor.
01321       if (!PredPtrVal)
01322         CanTranslate = false;
01323 
01324       // FIXME: it is entirely possible that PHI translating will end up with
01325       // the same value.  Consider PHI translating something like:
01326       // X = phi [x, bb1], [y, bb2].  PHI translating for bb1 doesn't *need*
01327       // to recurse here, pedantically speaking.
01328 
01329       // If getNonLocalPointerDepFromBB fails here, that means the cached
01330       // result conflicted with the Visited list; we have to conservatively
01331       // assume it is unknown, but this also does not block PRE of the load.
01332       if (!CanTranslate ||
01333           getNonLocalPointerDepFromBB(QueryInst, PredPointer,
01334                                       Loc.getWithNewPtr(PredPtrVal),
01335                                       isLoad, Pred,
01336                                       Result, Visited)) {
01337         // Add the entry to the Result list.
01338         NonLocalDepResult Entry(Pred, MemDepResult::getUnknown(), PredPtrVal);
01339         Result.push_back(Entry);
01340 
01341         // Since we had a phi translation failure, the cache for CacheKey won't
01342         // include all of the entries that we need to immediately satisfy future
01343         // queries.  Mark this in NonLocalPointerDeps by setting the
01344         // BBSkipFirstBlockPair pointer to null.  This requires reuse of the
01345         // cached value to do more work but not miss the phi trans failure.
01346         NonLocalPointerInfo &NLPI = NonLocalPointerDeps[CacheKey];
01347         NLPI.Pair = BBSkipFirstBlockPair();
01348         continue;
01349       }
01350     }
01351 
01352     // Refresh the CacheInfo/Cache pointer so that it isn't invalidated.
01353     CacheInfo = &NonLocalPointerDeps[CacheKey];
01354     Cache = &CacheInfo->NonLocalDeps;
01355     NumSortedEntries = Cache->size();
01356 
01357     // Since we did phi translation, the "Cache" set won't contain all of the
01358     // results for the query.  This is ok (we can still use it to accelerate
01359     // specific block queries) but we can't do the fastpath "return all
01360     // results from the set"  Clear out the indicator for this.
01361     CacheInfo->Pair = BBSkipFirstBlockPair();
01362     SkipFirstBlock = false;
01363     continue;
01364 
01365   PredTranslationFailure:
01366     // The following code is "failure"; we can't produce a sane translation
01367     // for the given block.  It assumes that we haven't modified any of
01368     // our datastructures while processing the current block.
01369 
01370     if (!Cache) {
01371       // Refresh the CacheInfo/Cache pointer if it got invalidated.
01372       CacheInfo = &NonLocalPointerDeps[CacheKey];
01373       Cache = &CacheInfo->NonLocalDeps;
01374       NumSortedEntries = Cache->size();
01375     }
01376 
01377     // Since we failed phi translation, the "Cache" set won't contain all of the
01378     // results for the query.  This is ok (we can still use it to accelerate
01379     // specific block queries) but we can't do the fastpath "return all
01380     // results from the set".  Clear out the indicator for this.
01381     CacheInfo->Pair = BBSkipFirstBlockPair();
01382 
01383     // If *nothing* works, mark the pointer as unknown.
01384     //
01385     // If this is the magic first block, return this as a clobber of the whole
01386     // incoming value.  Since we can't phi translate to one of the predecessors,
01387     // we have to bail out.
01388     if (SkipFirstBlock)
01389       return true;
01390 
01391     for (NonLocalDepInfo::reverse_iterator I = Cache->rbegin(); ; ++I) {
01392       assert(I != Cache->rend() && "Didn't find current block??");
01393       if (I->getBB() != BB)
01394         continue;
01395 
01396       assert((I->getResult().isNonLocal() || !DT->isReachableFromEntry(BB)) &&
01397              "Should only be here with transparent block");
01398       I->setResult(MemDepResult::getUnknown());
01399       Result.push_back(NonLocalDepResult(I->getBB(), I->getResult(),
01400                                          Pointer.getAddr()));
01401       break;
01402     }
01403   }
01404 
01405   // Okay, we're done now.  If we added new values to the cache, re-sort it.
01406   SortNonLocalDepInfoCache(*Cache, NumSortedEntries);
01407   DEBUG(AssertSorted(*Cache));
01408   return false;
01409 }
01410 
01411 /// RemoveCachedNonLocalPointerDependencies - If P exists in
01412 /// CachedNonLocalPointerInfo, remove it.
01413 void MemoryDependenceAnalysis::
01414 RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair P) {
01415   CachedNonLocalPointerInfo::iterator It =
01416     NonLocalPointerDeps.find(P);
01417   if (It == NonLocalPointerDeps.end()) return;
01418 
01419   // Remove all of the entries in the BB->val map.  This involves removing
01420   // instructions from the reverse map.
01421   NonLocalDepInfo &PInfo = It->second.NonLocalDeps;
01422 
01423   for (unsigned i = 0, e = PInfo.size(); i != e; ++i) {
01424     Instruction *Target = PInfo[i].getResult().getInst();
01425     if (!Target) continue;  // Ignore non-local dep results.
01426     assert(Target->getParent() == PInfo[i].getBB());
01427 
01428     // Eliminating the dirty entry from 'Cache', so update the reverse info.
01429     RemoveFromReverseMap(ReverseNonLocalPtrDeps, Target, P);
01430   }
01431 
01432   // Remove P from NonLocalPointerDeps (which deletes NonLocalDepInfo).
01433   NonLocalPointerDeps.erase(It);
01434 }
01435 
01436 
01437 /// invalidateCachedPointerInfo - This method is used to invalidate cached
01438 /// information about the specified pointer, because it may be too
01439 /// conservative in memdep.  This is an optional call that can be used when
01440 /// the client detects an equivalence between the pointer and some other
01441 /// value and replaces the other value with ptr. This can make Ptr available
01442 /// in more places that cached info does not necessarily keep.
01443 void MemoryDependenceAnalysis::invalidateCachedPointerInfo(Value *Ptr) {
01444   // If Ptr isn't really a pointer, just ignore it.
01445   if (!Ptr->getType()->isPointerTy()) return;
01446   // Flush store info for the pointer.
01447   RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(Ptr, false));
01448   // Flush load info for the pointer.
01449   RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(Ptr, true));
01450 }
01451 
01452 /// invalidateCachedPredecessors - Clear the PredIteratorCache info.
01453 /// This needs to be done when the CFG changes, e.g., due to splitting
01454 /// critical edges.
01455 void MemoryDependenceAnalysis::invalidateCachedPredecessors() {
01456   PredCache.clear();
01457 }
01458 
01459 /// removeInstruction - Remove an instruction from the dependence analysis,
01460 /// updating the dependence of instructions that previously depended on it.
01461 /// This method attempts to keep the cache coherent using the reverse map.
01462 void MemoryDependenceAnalysis::removeInstruction(Instruction *RemInst) {
01463   // Walk through the Non-local dependencies, removing this one as the value
01464   // for any cached queries.
01465   NonLocalDepMapType::iterator NLDI = NonLocalDeps.find(RemInst);
01466   if (NLDI != NonLocalDeps.end()) {
01467     NonLocalDepInfo &BlockMap = NLDI->second.first;
01468     for (NonLocalDepInfo::iterator DI = BlockMap.begin(), DE = BlockMap.end();
01469          DI != DE; ++DI)
01470       if (Instruction *Inst = DI->getResult().getInst())
01471         RemoveFromReverseMap(ReverseNonLocalDeps, Inst, RemInst);
01472     NonLocalDeps.erase(NLDI);
01473   }
01474 
01475   // If we have a cached local dependence query for this instruction, remove it.
01476   //
01477   LocalDepMapType::iterator LocalDepEntry = LocalDeps.find(RemInst);
01478   if (LocalDepEntry != LocalDeps.end()) {
01479     // Remove us from DepInst's reverse set now that the local dep info is gone.
01480     if (Instruction *Inst = LocalDepEntry->second.getInst())
01481       RemoveFromReverseMap(ReverseLocalDeps, Inst, RemInst);
01482 
01483     // Remove this local dependency info.
01484     LocalDeps.erase(LocalDepEntry);
01485   }
01486 
01487   // If we have any cached pointer dependencies on this instruction, remove
01488   // them.  If the instruction has non-pointer type, then it can't be a pointer
01489   // base.
01490 
01491   // Remove it from both the load info and the store info.  The instruction
01492   // can't be in either of these maps if it is non-pointer.
01493   if (RemInst->getType()->isPointerTy()) {
01494     RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(RemInst, false));
01495     RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(RemInst, true));
01496   }
01497 
01498   // Loop over all of the things that depend on the instruction we're removing.
01499   //
01500   SmallVector<std::pair<Instruction*, Instruction*>, 8> ReverseDepsToAdd;
01501 
01502   // If we find RemInst as a clobber or Def in any of the maps for other values,
01503   // we need to replace its entry with a dirty version of the instruction after
01504   // it.  If RemInst is a terminator, we use a null dirty value.
01505   //
01506   // Using a dirty version of the instruction after RemInst saves having to scan
01507   // the entire block to get to this point.
01508   MemDepResult NewDirtyVal;
01509   if (!RemInst->isTerminator())
01510     NewDirtyVal = MemDepResult::getDirty(++BasicBlock::iterator(RemInst));
01511 
01512   ReverseDepMapType::iterator ReverseDepIt = ReverseLocalDeps.find(RemInst);
01513   if (ReverseDepIt != ReverseLocalDeps.end()) {
01514     // RemInst can't be the terminator if it has local stuff depending on it.
01515     assert(!ReverseDepIt->second.empty() && !isa<TerminatorInst>(RemInst) &&
01516            "Nothing can locally depend on a terminator");
01517 
01518     for (Instruction *InstDependingOnRemInst : ReverseDepIt->second) {
01519       assert(InstDependingOnRemInst != RemInst &&
01520              "Already removed our local dep info");
01521 
01522       LocalDeps[InstDependingOnRemInst] = NewDirtyVal;
01523 
01524       // Make sure to remember that new things depend on NewDepInst.
01525       assert(NewDirtyVal.getInst() && "There is no way something else can have "
01526              "a local dep on this if it is a terminator!");
01527       ReverseDepsToAdd.push_back(std::make_pair(NewDirtyVal.getInst(),
01528                                                 InstDependingOnRemInst));
01529     }
01530 
01531     ReverseLocalDeps.erase(ReverseDepIt);
01532 
01533     // Add new reverse deps after scanning the set, to avoid invalidating the
01534     // 'ReverseDeps' reference.
01535     while (!ReverseDepsToAdd.empty()) {
01536       ReverseLocalDeps[ReverseDepsToAdd.back().first]
01537         .insert(ReverseDepsToAdd.back().second);
01538       ReverseDepsToAdd.pop_back();
01539     }
01540   }
01541 
01542   ReverseDepIt = ReverseNonLocalDeps.find(RemInst);
01543   if (ReverseDepIt != ReverseNonLocalDeps.end()) {
01544     for (Instruction *I : ReverseDepIt->second) {
01545       assert(I != RemInst && "Already removed NonLocalDep info for RemInst");
01546 
01547       PerInstNLInfo &INLD = NonLocalDeps[I];
01548       // The information is now dirty!
01549       INLD.second = true;
01550 
01551       for (NonLocalDepInfo::iterator DI = INLD.first.begin(),
01552            DE = INLD.first.end(); DI != DE; ++DI) {
01553         if (DI->getResult().getInst() != RemInst) continue;
01554 
01555         // Convert to a dirty entry for the subsequent instruction.
01556         DI->setResult(NewDirtyVal);
01557 
01558         if (Instruction *NextI = NewDirtyVal.getInst())
01559           ReverseDepsToAdd.push_back(std::make_pair(NextI, I));
01560       }
01561     }
01562 
01563     ReverseNonLocalDeps.erase(ReverseDepIt);
01564 
01565     // Add new reverse deps after scanning the set, to avoid invalidating 'Set'
01566     while (!ReverseDepsToAdd.empty()) {
01567       ReverseNonLocalDeps[ReverseDepsToAdd.back().first]
01568         .insert(ReverseDepsToAdd.back().second);
01569       ReverseDepsToAdd.pop_back();
01570     }
01571   }
01572 
01573   // If the instruction is in ReverseNonLocalPtrDeps then it appears as a
01574   // value in the NonLocalPointerDeps info.
01575   ReverseNonLocalPtrDepTy::iterator ReversePtrDepIt =
01576     ReverseNonLocalPtrDeps.find(RemInst);
01577   if (ReversePtrDepIt != ReverseNonLocalPtrDeps.end()) {
01578     SmallVector<std::pair<Instruction*, ValueIsLoadPair>,8> ReversePtrDepsToAdd;
01579 
01580     for (ValueIsLoadPair P : ReversePtrDepIt->second) {
01581       assert(P.getPointer() != RemInst &&
01582              "Already removed NonLocalPointerDeps info for RemInst");
01583 
01584       NonLocalDepInfo &NLPDI = NonLocalPointerDeps[P].NonLocalDeps;
01585 
01586       // The cache is not valid for any specific block anymore.
01587       NonLocalPointerDeps[P].Pair = BBSkipFirstBlockPair();
01588 
01589       // Update any entries for RemInst to use the instruction after it.
01590       for (NonLocalDepInfo::iterator DI = NLPDI.begin(), DE = NLPDI.end();
01591            DI != DE; ++DI) {
01592         if (DI->getResult().getInst() != RemInst) continue;
01593 
01594         // Convert to a dirty entry for the subsequent instruction.
01595         DI->setResult(NewDirtyVal);
01596 
01597         if (Instruction *NewDirtyInst = NewDirtyVal.getInst())
01598           ReversePtrDepsToAdd.push_back(std::make_pair(NewDirtyInst, P));
01599       }
01600 
01601       // Re-sort the NonLocalDepInfo.  Changing the dirty entry to its
01602       // subsequent value may invalidate the sortedness.
01603       std::sort(NLPDI.begin(), NLPDI.end());
01604     }
01605 
01606     ReverseNonLocalPtrDeps.erase(ReversePtrDepIt);
01607 
01608     while (!ReversePtrDepsToAdd.empty()) {
01609       ReverseNonLocalPtrDeps[ReversePtrDepsToAdd.back().first]
01610         .insert(ReversePtrDepsToAdd.back().second);
01611       ReversePtrDepsToAdd.pop_back();
01612     }
01613   }
01614 
01615 
01616   assert(!NonLocalDeps.count(RemInst) && "RemInst got reinserted?");
01617   AA->deleteValue(RemInst);
01618   DEBUG(verifyRemoved(RemInst));
01619 }
01620 /// verifyRemoved - Verify that the specified instruction does not occur
01621 /// in our internal data structures. This function verifies by asserting in
01622 /// debug builds.
01623 void MemoryDependenceAnalysis::verifyRemoved(Instruction *D) const {
01624 #ifndef NDEBUG
01625   for (LocalDepMapType::const_iterator I = LocalDeps.begin(),
01626        E = LocalDeps.end(); I != E; ++I) {
01627     assert(I->first != D && "Inst occurs in data structures");
01628     assert(I->second.getInst() != D &&
01629            "Inst occurs in data structures");
01630   }
01631 
01632   for (CachedNonLocalPointerInfo::const_iterator I =NonLocalPointerDeps.begin(),
01633        E = NonLocalPointerDeps.end(); I != E; ++I) {
01634     assert(I->first.getPointer() != D && "Inst occurs in NLPD map key");
01635     const NonLocalDepInfo &Val = I->second.NonLocalDeps;
01636     for (NonLocalDepInfo::const_iterator II = Val.begin(), E = Val.end();
01637          II != E; ++II)
01638       assert(II->getResult().getInst() != D && "Inst occurs as NLPD value");
01639   }
01640 
01641   for (NonLocalDepMapType::const_iterator I = NonLocalDeps.begin(),
01642        E = NonLocalDeps.end(); I != E; ++I) {
01643     assert(I->first != D && "Inst occurs in data structures");
01644     const PerInstNLInfo &INLD = I->second;
01645     for (NonLocalDepInfo::const_iterator II = INLD.first.begin(),
01646          EE = INLD.first.end(); II  != EE; ++II)
01647       assert(II->getResult().getInst() != D && "Inst occurs in data structures");
01648   }
01649 
01650   for (ReverseDepMapType::const_iterator I = ReverseLocalDeps.begin(),
01651        E = ReverseLocalDeps.end(); I != E; ++I) {
01652     assert(I->first != D && "Inst occurs in data structures");
01653     for (Instruction *Inst : I->second)
01654       assert(Inst != D && "Inst occurs in data structures");
01655   }
01656 
01657   for (ReverseDepMapType::const_iterator I = ReverseNonLocalDeps.begin(),
01658        E = ReverseNonLocalDeps.end();
01659        I != E; ++I) {
01660     assert(I->first != D && "Inst occurs in data structures");
01661     for (Instruction *Inst : I->second)
01662       assert(Inst != D && "Inst occurs in data structures");
01663   }
01664 
01665   for (ReverseNonLocalPtrDepTy::const_iterator
01666        I = ReverseNonLocalPtrDeps.begin(),
01667        E = ReverseNonLocalPtrDeps.end(); I != E; ++I) {
01668     assert(I->first != D && "Inst occurs in rev NLPD map");
01669 
01670     for (ValueIsLoadPair P : I->second)
01671       assert(P != ValueIsLoadPair(D, false) &&
01672              P != ValueIsLoadPair(D, true) &&
01673              "Inst occurs in ReverseNonLocalPtrDeps map");
01674   }
01675 #endif
01676 }