LLVM API Documentation

MemoryDependenceAnalysis.cpp

Go to the documentation of this file.
00001 //===- MemoryDependenceAnalysis.cpp - Mem Deps Implementation  --*- C++ -*-===//
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 #define DEBUG_TYPE "memdep"
00018 #include "llvm/Analysis/MemoryDependenceAnalysis.h"
00019 #include "llvm/Constants.h"
00020 #include "llvm/Instructions.h"
00021 #include "llvm/Function.h"
00022 #include "llvm/Analysis/AliasAnalysis.h"
00023 #include "llvm/ADT/Statistic.h"
00024 #include "llvm/ADT/STLExtras.h"
00025 #include "llvm/Support/PredIteratorCache.h"
00026 #include "llvm/Support/Debug.h"
00027 #include "llvm/Target/TargetData.h"
00028 using namespace llvm;
00029 
00030 STATISTIC(NumCacheNonLocal, "Number of fully cached non-local responses");
00031 STATISTIC(NumCacheDirtyNonLocal, "Number of dirty cached non-local responses");
00032 STATISTIC(NumUncacheNonLocal, "Number of uncached non-local responses");
00033 
00034 STATISTIC(NumCacheNonLocalPtr,
00035           "Number of fully cached non-local ptr responses");
00036 STATISTIC(NumCacheDirtyNonLocalPtr,
00037           "Number of cached, but dirty, non-local ptr responses");
00038 STATISTIC(NumUncacheNonLocalPtr,
00039           "Number of uncached non-local ptr responses");
00040 STATISTIC(NumCacheCompleteNonLocalPtr,
00041           "Number of block queries that were completely cached");
00042 
00043 char MemoryDependenceAnalysis::ID = 0;
00044   
00045 // Register this pass...
00046 static RegisterPass<MemoryDependenceAnalysis> X("memdep",
00047                                      "Memory Dependence Analysis", false, true);
00048 
00049 MemoryDependenceAnalysis::MemoryDependenceAnalysis()
00050 : FunctionPass(&ID), PredCache(0) {
00051 }
00052 MemoryDependenceAnalysis::~MemoryDependenceAnalysis() {
00053 }
00054 
00055 /// Clean up memory in between runs
00056 void MemoryDependenceAnalysis::releaseMemory() {
00057   LocalDeps.clear();
00058   NonLocalDeps.clear();
00059   NonLocalPointerDeps.clear();
00060   ReverseLocalDeps.clear();
00061   ReverseNonLocalDeps.clear();
00062   ReverseNonLocalPtrDeps.clear();
00063   PredCache->clear();
00064 }
00065 
00066 
00067 
00068 /// getAnalysisUsage - Does not modify anything.  It uses Alias Analysis.
00069 ///
00070 void MemoryDependenceAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
00071   AU.setPreservesAll();
00072   AU.addRequiredTransitive<AliasAnalysis>();
00073   AU.addRequiredTransitive<TargetData>();
00074 }
00075 
00076 bool MemoryDependenceAnalysis::runOnFunction(Function &) {
00077   AA = &getAnalysis<AliasAnalysis>();
00078   TD = &getAnalysis<TargetData>();
00079   if (PredCache == 0)
00080     PredCache.reset(new PredIteratorCache());
00081   return false;
00082 }
00083 
00084 /// RemoveFromReverseMap - This is a helper function that removes Val from
00085 /// 'Inst's set in ReverseMap.  If the set becomes empty, remove Inst's entry.
00086 template <typename KeyTy>
00087 static void RemoveFromReverseMap(DenseMap<Instruction*, 
00088                                  SmallPtrSet<KeyTy*, 4> > &ReverseMap,
00089                                  Instruction *Inst, KeyTy *Val) {
00090   typename DenseMap<Instruction*, SmallPtrSet<KeyTy*, 4> >::iterator
00091   InstIt = ReverseMap.find(Inst);
00092   assert(InstIt != ReverseMap.end() && "Reverse map out of sync?");
00093   bool Found = InstIt->second.erase(Val);
00094   assert(Found && "Invalid reverse map!"); Found=Found;
00095   if (InstIt->second.empty())
00096     ReverseMap.erase(InstIt);
00097 }
00098 
00099 
00100 /// getCallSiteDependencyFrom - Private helper for finding the local
00101 /// dependencies of a call site.
00102 MemDepResult MemoryDependenceAnalysis::
00103 getCallSiteDependencyFrom(CallSite CS, bool isReadOnlyCall,
00104                           BasicBlock::iterator ScanIt, BasicBlock *BB) {
00105   // Walk backwards through the block, looking for dependencies
00106   while (ScanIt != BB->begin()) {
00107     Instruction *Inst = --ScanIt;
00108     
00109     // If this inst is a memory op, get the pointer it accessed
00110     Value *Pointer = 0;
00111     uint64_t PointerSize = 0;
00112     if (StoreInst *S = dyn_cast<StoreInst>(Inst)) {
00113       Pointer = S->getPointerOperand();
00114       PointerSize = TD->getTypeStoreSize(S->getOperand(0)->getType());
00115     } else if (VAArgInst *V = dyn_cast<VAArgInst>(Inst)) {
00116       Pointer = V->getOperand(0);
00117       PointerSize = TD->getTypeStoreSize(V->getType());
00118     } else if (FreeInst *F = dyn_cast<FreeInst>(Inst)) {
00119       Pointer = F->getPointerOperand();
00120       
00121       // FreeInsts erase the entire structure
00122       PointerSize = ~0ULL;
00123     } else if (isa<CallInst>(Inst) || isa<InvokeInst>(Inst)) {
00124       CallSite InstCS = CallSite::get(Inst);
00125       // If these two calls do not interfere, look past it.
00126       switch (AA->getModRefInfo(CS, InstCS)) {
00127       case AliasAnalysis::NoModRef:
00128         // If the two calls don't interact (e.g. InstCS is readnone) keep
00129         // scanning.
00130         continue;
00131       case AliasAnalysis::Ref:
00132         // If the two calls read the same memory locations and CS is a readonly
00133         // function, then we have two cases: 1) the calls may not interfere with
00134         // each other at all.  2) the calls may produce the same value.  In case
00135         // #1 we want to ignore the values, in case #2, we want to return Inst
00136         // as a Def dependence.  This allows us to CSE in cases like:
00137         //   X = strlen(P);
00138         //    memchr(...);
00139         //   Y = strlen(P);  // Y = X
00140         if (isReadOnlyCall) {
00141           if (CS.getCalledFunction() != 0 &&
00142               CS.getCalledFunction() == InstCS.getCalledFunction())
00143             return MemDepResult::getDef(Inst);
00144           // Ignore unrelated read/read call dependences.
00145           continue;
00146         }
00147         // FALL THROUGH
00148       default:
00149         return MemDepResult::getClobber(Inst);
00150       }
00151     } else {
00152       // Non-memory instruction.
00153       continue;
00154     }
00155     
00156     if (AA->getModRefInfo(CS, Pointer, PointerSize) != AliasAnalysis::NoModRef)
00157       return MemDepResult::getClobber(Inst);
00158   }
00159   
00160   // No dependence found.  If this is the entry block of the function, it is a
00161   // clobber, otherwise it is non-local.
00162   if (BB != &BB->getParent()->getEntryBlock())
00163     return MemDepResult::getNonLocal();
00164   return MemDepResult::getClobber(ScanIt);
00165 }
00166 
00167 /// getPointerDependencyFrom - Return the instruction on which a memory
00168 /// location depends.  If isLoad is true, this routine ignore may-aliases with
00169 /// read-only operations.
00170 MemDepResult MemoryDependenceAnalysis::
00171 getPointerDependencyFrom(Value *MemPtr, uint64_t MemSize, bool isLoad,
00172                          BasicBlock::iterator ScanIt, BasicBlock *BB) {
00173 
00174   // Walk backwards through the basic block, looking for dependencies.
00175   while (ScanIt != BB->begin()) {
00176     Instruction *Inst = --ScanIt;
00177 
00178     // Values depend on loads if the pointers are must aliased.  This means that
00179     // a load depends on another must aliased load from the same value.
00180     if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
00181       Value *Pointer = LI->getPointerOperand();
00182       uint64_t PointerSize = TD->getTypeStoreSize(LI->getType());
00183       
00184       // If we found a pointer, check if it could be the same as our pointer.
00185       AliasAnalysis::AliasResult R =
00186         AA->alias(Pointer, PointerSize, MemPtr, MemSize);
00187       if (R == AliasAnalysis::NoAlias)
00188         continue;
00189       
00190       // May-alias loads don't depend on each other without a dependence.
00191       if (isLoad && R == AliasAnalysis::MayAlias)
00192         continue;
00193       // Stores depend on may and must aliased loads, loads depend on must-alias
00194       // loads.
00195       return MemDepResult::getDef(Inst);
00196     }
00197     
00198     if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
00199       Value *Pointer = SI->getPointerOperand();
00200       uint64_t PointerSize = TD->getTypeStoreSize(SI->getOperand(0)->getType());
00201 
00202       // If we found a pointer, check if it could be the same as our pointer.
00203       AliasAnalysis::AliasResult R =
00204         AA->alias(Pointer, PointerSize, MemPtr, MemSize);
00205       
00206       if (R == AliasAnalysis::NoAlias)
00207         continue;
00208       if (R == AliasAnalysis::MayAlias)
00209         return MemDepResult::getClobber(Inst);
00210       return MemDepResult::getDef(Inst);
00211     }
00212 
00213     // If this is an allocation, and if we know that the accessed pointer is to
00214     // the allocation, return Def.  This means that there is no dependence and
00215     // the access can be optimized based on that.  For example, a load could
00216     // turn into undef.
00217     if (AllocationInst *AI = dyn_cast<AllocationInst>(Inst)) {
00218       Value *AccessPtr = MemPtr->getUnderlyingObject();
00219       
00220       if (AccessPtr == AI ||
00221           AA->alias(AI, 1, AccessPtr, 1) == AliasAnalysis::MustAlias)
00222         return MemDepResult::getDef(AI);
00223       continue;
00224     }
00225     
00226     // See if this instruction (e.g. a call or vaarg) mod/ref's the pointer.
00227     switch (AA->getModRefInfo(Inst, MemPtr, MemSize)) {
00228     case AliasAnalysis::NoModRef:
00229       // If the call has no effect on the queried pointer, just ignore it.
00230       continue;
00231     case AliasAnalysis::Ref:
00232       // If the call is known to never store to the pointer, and if this is a
00233       // load query, we can safely ignore it (scan past it).
00234       if (isLoad)
00235         continue;
00236       // FALL THROUGH.
00237     default:
00238       // Otherwise, there is a potential dependence.  Return a clobber.
00239       return MemDepResult::getClobber(Inst);
00240     }
00241   }
00242   
00243   // No dependence found.  If this is the entry block of the function, it is a
00244   // clobber, otherwise it is non-local.
00245   if (BB != &BB->getParent()->getEntryBlock())
00246     return MemDepResult::getNonLocal();
00247   return MemDepResult::getClobber(ScanIt);
00248 }
00249 
00250 /// getDependency - Return the instruction on which a memory operation
00251 /// depends.
00252 MemDepResult MemoryDependenceAnalysis::getDependency(Instruction *QueryInst) {
00253   Instruction *ScanPos = QueryInst;
00254   
00255   // Check for a cached result
00256   MemDepResult &LocalCache = LocalDeps[QueryInst];
00257   
00258   // If the cached entry is non-dirty, just return it.  Note that this depends
00259   // on MemDepResult's default constructing to 'dirty'.
00260   if (!LocalCache.isDirty())
00261     return LocalCache;
00262     
00263   // Otherwise, if we have a dirty entry, we know we can start the scan at that
00264   // instruction, which may save us some work.
00265   if (Instruction *Inst = LocalCache.getInst()) {
00266     ScanPos = Inst;
00267    
00268     RemoveFromReverseMap(ReverseLocalDeps, Inst, QueryInst);
00269   }
00270   
00271   BasicBlock *QueryParent = QueryInst->getParent();
00272   
00273   Value *MemPtr = 0;
00274   uint64_t MemSize = 0;
00275   
00276   // Do the scan.
00277   if (BasicBlock::iterator(QueryInst) == QueryParent->begin()) {
00278     // No dependence found.  If this is the entry block of the function, it is a
00279     // clobber, otherwise it is non-local.
00280     if (QueryParent != &QueryParent->getParent()->getEntryBlock())
00281       LocalCache = MemDepResult::getNonLocal();
00282     else
00283       LocalCache = MemDepResult::getClobber(QueryInst);
00284   } else if (StoreInst *SI = dyn_cast<StoreInst>(QueryInst)) {
00285     // If this is a volatile store, don't mess around with it.  Just return the
00286     // previous instruction as a clobber.
00287     if (SI->isVolatile())
00288       LocalCache = MemDepResult::getClobber(--BasicBlock::iterator(ScanPos));
00289     else {
00290       MemPtr = SI->getPointerOperand();
00291       MemSize = TD->getTypeStoreSize(SI->getOperand(0)->getType());
00292     }
00293   } else if (LoadInst *LI = dyn_cast<LoadInst>(QueryInst)) {
00294     // If this is a volatile load, don't mess around with it.  Just return the
00295     // previous instruction as a clobber.
00296     if (LI->isVolatile())
00297       LocalCache = MemDepResult::getClobber(--BasicBlock::iterator(ScanPos));
00298     else {
00299       MemPtr = LI->getPointerOperand();
00300       MemSize = TD->getTypeStoreSize(LI->getType());
00301     }
00302   } else if (isa<CallInst>(QueryInst) || isa<InvokeInst>(QueryInst)) {
00303     CallSite QueryCS = CallSite::get(QueryInst);
00304     bool isReadOnly = AA->onlyReadsMemory(QueryCS);
00305     LocalCache = getCallSiteDependencyFrom(QueryCS, isReadOnly, ScanPos,
00306                                            QueryParent);
00307   } else if (FreeInst *FI = dyn_cast<FreeInst>(QueryInst)) {
00308     MemPtr = FI->getPointerOperand();
00309     // FreeInsts erase the entire structure, not just a field.
00310     MemSize = ~0UL;
00311   } else {
00312     // Non-memory instruction.
00313     LocalCache = MemDepResult::getClobber(--BasicBlock::iterator(ScanPos));
00314   }
00315   
00316   // If we need to do a pointer scan, make it happen.
00317   if (MemPtr)
00318     LocalCache = getPointerDependencyFrom(MemPtr, MemSize, 
00319                                           isa<LoadInst>(QueryInst),
00320                                           ScanPos, QueryParent);
00321   
00322   // Remember the result!
00323   if (Instruction *I = LocalCache.getInst())
00324     ReverseLocalDeps[I].insert(QueryInst);
00325   
00326   return LocalCache;
00327 }
00328 
00329 #ifndef NDEBUG
00330 /// AssertSorted - This method is used when -debug is specified to verify that
00331 /// cache arrays are properly kept sorted.
00332 static void AssertSorted(MemoryDependenceAnalysis::NonLocalDepInfo &Cache,
00333                          int Count = -1) {
00334   if (Count == -1) Count = Cache.size();
00335   if (Count == 0) return;
00336 
00337   for (unsigned i = 1; i != unsigned(Count); ++i)
00338     assert(Cache[i-1] <= Cache[i] && "Cache isn't sorted!");
00339 }
00340 #endif
00341 
00342 /// getNonLocalCallDependency - Perform a full dependency query for the
00343 /// specified call, returning the set of blocks that the value is
00344 /// potentially live across.  The returned set of results will include a
00345 /// "NonLocal" result for all blocks where the value is live across.
00346 ///
00347 /// This method assumes the instruction returns a "NonLocal" dependency
00348 /// within its own block.
00349 ///
00350 /// This returns a reference to an internal data structure that may be
00351 /// invalidated on the next non-local query or when an instruction is
00352 /// removed.  Clients must copy this data if they want it around longer than
00353 /// that.
00354 const MemoryDependenceAnalysis::NonLocalDepInfo &
00355 MemoryDependenceAnalysis::getNonLocalCallDependency(CallSite QueryCS) {
00356   assert(getDependency(QueryCS.getInstruction()).isNonLocal() &&
00357  "getNonLocalCallDependency should only be used on calls with non-local deps!");
00358   PerInstNLInfo &CacheP = NonLocalDeps[QueryCS.getInstruction()];
00359   NonLocalDepInfo &Cache = CacheP.first;
00360 
00361   /// DirtyBlocks - This is the set of blocks that need to be recomputed.  In
00362   /// the cached case, this can happen due to instructions being deleted etc. In
00363   /// the uncached case, this starts out as the set of predecessors we care
00364   /// about.
00365   SmallVector<BasicBlock*, 32> DirtyBlocks;
00366   
00367   if (!Cache.empty()) {
00368     // Okay, we have a cache entry.  If we know it is not dirty, just return it
00369     // with no computation.
00370     if (!CacheP.second) {
00371       NumCacheNonLocal++;
00372       return Cache;
00373     }
00374     
00375     // If we already have a partially computed set of results, scan them to
00376     // determine what is dirty, seeding our initial DirtyBlocks worklist.
00377     for (NonLocalDepInfo::iterator I = Cache.begin(), E = Cache.end();
00378        I != E; ++I)
00379       if (I->second.isDirty())
00380         DirtyBlocks.push_back(I->first);
00381     
00382     // Sort the cache so that we can do fast binary search lookups below.
00383     std::sort(Cache.begin(), Cache.end());
00384     
00385     ++NumCacheDirtyNonLocal;
00386     //cerr << "CACHED CASE: " << DirtyBlocks.size() << " dirty: "
00387     //     << Cache.size() << " cached: " << *QueryInst;
00388   } else {
00389     // Seed DirtyBlocks with each of the preds of QueryInst's block.
00390     BasicBlock *QueryBB = QueryCS.getInstruction()->getParent();
00391     for (BasicBlock **PI = PredCache->GetPreds(QueryBB); *PI; ++PI)
00392       DirtyBlocks.push_back(*PI);
00393     NumUncacheNonLocal++;
00394   }
00395   
00396   // isReadonlyCall - If this is a read-only call, we can be more aggressive.
00397   bool isReadonlyCall = AA->onlyReadsMemory(QueryCS);
00398 
00399   SmallPtrSet<BasicBlock*, 64> Visited;
00400   
00401   unsigned NumSortedEntries = Cache.size();
00402   DEBUG(AssertSorted(Cache));
00403   
00404   // Iterate while we still have blocks to update.
00405   while (!DirtyBlocks.empty()) {
00406     BasicBlock *DirtyBB = DirtyBlocks.back();
00407     DirtyBlocks.pop_back();
00408     
00409     // Already processed this block?
00410     if (!Visited.insert(DirtyBB))
00411       continue;
00412     
00413     // Do a binary search to see if we already have an entry for this block in
00414     // the cache set.  If so, find it.
00415     DEBUG(AssertSorted(Cache, NumSortedEntries));
00416     NonLocalDepInfo::iterator Entry = 
00417       std::upper_bound(Cache.begin(), Cache.begin()+NumSortedEntries,
00418                        std::make_pair(DirtyBB, MemDepResult()));
00419     if (Entry != Cache.begin() && prior(Entry)->first == DirtyBB)
00420       --Entry;
00421     
00422     MemDepResult *ExistingResult = 0;
00423     if (Entry != Cache.begin()+NumSortedEntries && 
00424         Entry->first == DirtyBB) {
00425       // If we already have an entry, and if it isn't already dirty, the block
00426       // is done.
00427       if (!Entry->second.isDirty())
00428         continue;
00429       
00430       // Otherwise, remember this slot so we can update the value.
00431       ExistingResult = &Entry->second;
00432     }
00433     
00434     // If the dirty entry has a pointer, start scanning from it so we don't have
00435     // to rescan the entire block.
00436     BasicBlock::iterator ScanPos = DirtyBB->end();
00437     if (ExistingResult) {
00438       if (Instruction *Inst = ExistingResult->getInst()) {
00439         ScanPos = Inst;
00440         // We're removing QueryInst's use of Inst.
00441         RemoveFromReverseMap(ReverseNonLocalDeps, Inst,
00442                              QueryCS.getInstruction());
00443       }
00444     }
00445     
00446     // Find out if this block has a local dependency for QueryInst.
00447     MemDepResult Dep;
00448     
00449     if (ScanPos != DirtyBB->begin()) {
00450       Dep = getCallSiteDependencyFrom(QueryCS, isReadonlyCall,ScanPos, DirtyBB);
00451     } else if (DirtyBB != &DirtyBB->getParent()->getEntryBlock()) {
00452       // No dependence found.  If this is the entry block of the function, it is
00453       // a clobber, otherwise it is non-local.
00454       Dep = MemDepResult::getNonLocal();
00455     } else {
00456       Dep = MemDepResult::getClobber(ScanPos);
00457     }
00458     
00459     // If we had a dirty entry for the block, update it.  Otherwise, just add
00460     // a new entry.
00461     if (ExistingResult)
00462       *ExistingResult = Dep;
00463     else
00464       Cache.push_back(std::make_pair(DirtyBB, Dep));
00465     
00466     // If the block has a dependency (i.e. it isn't completely transparent to
00467     // the value), remember the association!
00468     if (!Dep.isNonLocal()) {
00469       // Keep the ReverseNonLocalDeps map up to date so we can efficiently
00470       // update this when we remove instructions.
00471       if (Instruction *Inst = Dep.getInst())
00472         ReverseNonLocalDeps[Inst].insert(QueryCS.getInstruction());
00473     } else {
00474     
00475       // If the block *is* completely transparent to the load, we need to check
00476       // the predecessors of this block.  Add them to our worklist.
00477       for (BasicBlock **PI = PredCache->GetPreds(DirtyBB); *PI; ++PI)
00478         DirtyBlocks.push_back(*PI);
00479     }
00480   }
00481   
00482   return Cache;
00483 }
00484 
00485 /// getNonLocalPointerDependency - Perform a full dependency query for an
00486 /// access to the specified (non-volatile) memory location, returning the
00487 /// set of instructions that either define or clobber the value.
00488 ///
00489 /// This method assumes the pointer has a "NonLocal" dependency within its
00490 /// own block.
00491 ///
00492 void MemoryDependenceAnalysis::
00493 getNonLocalPointerDependency(Value *Pointer, bool isLoad, BasicBlock *FromBB,
00494                              SmallVectorImpl<NonLocalDepEntry> &Result) {
00495   assert(isa<PointerType>(Pointer->getType()) &&
00496          "Can't get pointer deps of a non-pointer!");
00497   Result.clear();
00498   
00499   // We know that the pointer value is live into FromBB find the def/clobbers
00500   // from presecessors.
00501   const Type *EltTy = cast<PointerType>(Pointer->getType())->getElementType();
00502   uint64_t PointeeSize = TD->getTypeStoreSize(EltTy);
00503   
00504   // This is the set of blocks we've inspected, and the pointer we consider in
00505   // each block.  Because of critical edges, we currently bail out if querying
00506   // a block with multiple different pointers.  This can happen during PHI
00507   // translation.
00508   DenseMap<BasicBlock*, Value*> Visited;
00509   if (!getNonLocalPointerDepFromBB(Pointer, PointeeSize, isLoad, FromBB,
00510                                    Result, Visited, true))
00511     return;
00512   Result.clear();
00513   Result.push_back(std::make_pair(FromBB,
00514                                   MemDepResult::getClobber(FromBB->begin())));
00515 }
00516 
00517 /// GetNonLocalInfoForBlock - Compute the memdep value for BB with
00518 /// Pointer/PointeeSize using either cached information in Cache or by doing a
00519 /// lookup (which may use dirty cache info if available).  If we do a lookup,
00520 /// add the result to the cache.
00521 MemDepResult MemoryDependenceAnalysis::
00522 GetNonLocalInfoForBlock(Value *Pointer, uint64_t PointeeSize,
00523                         bool isLoad, BasicBlock *BB,
00524                         NonLocalDepInfo *Cache, unsigned NumSortedEntries) {
00525   
00526   // Do a binary search to see if we already have an entry for this block in
00527   // the cache set.  If so, find it.
00528   NonLocalDepInfo::iterator Entry =
00529     std::upper_bound(Cache->begin(), Cache->begin()+NumSortedEntries,
00530                      std::make_pair(BB, MemDepResult()));
00531   if (Entry != Cache->begin() && prior(Entry)->first == BB)
00532     --Entry;
00533   
00534   MemDepResult *ExistingResult = 0;
00535   if (Entry != Cache->begin()+NumSortedEntries && Entry->first == BB)
00536     ExistingResult = &Entry->second;
00537   
00538   // If we have a cached entry, and it is non-dirty, use it as the value for
00539   // this dependency.
00540   if (ExistingResult && !ExistingResult->isDirty()) {
00541     ++NumCacheNonLocalPtr;
00542     return *ExistingResult;
00543   }    
00544   
00545   // Otherwise, we have to scan for the value.  If we have a dirty cache
00546   // entry, start scanning from its position, otherwise we scan from the end
00547   // of the block.
00548   BasicBlock::iterator ScanPos = BB->end();
00549   if (ExistingResult && ExistingResult->getInst()) {
00550     assert(ExistingResult->getInst()->getParent() == BB &&
00551            "Instruction invalidated?");
00552     ++NumCacheDirtyNonLocalPtr;
00553     ScanPos = ExistingResult->getInst();
00554     
00555     // Eliminating the dirty entry from 'Cache', so update the reverse info.
00556     ValueIsLoadPair CacheKey(Pointer, isLoad);
00557     RemoveFromReverseMap(ReverseNonLocalPtrDeps, ScanPos,
00558                          CacheKey.getOpaqueValue());
00559   } else {
00560     ++NumUncacheNonLocalPtr;
00561   }
00562   
00563   // Scan the block for the dependency.
00564   MemDepResult Dep = getPointerDependencyFrom(Pointer, PointeeSize, isLoad, 
00565                                               ScanPos, BB);
00566   
00567   // If we had a dirty entry for the block, update it.  Otherwise, just add
00568   // a new entry.
00569   if (ExistingResult)
00570     *ExistingResult = Dep;
00571   else
00572     Cache->push_back(std::make_pair(BB, Dep));
00573   
00574   // If the block has a dependency (i.e. it isn't completely transparent to
00575   // the value), remember the reverse association because we just added it
00576   // to Cache!
00577   if (Dep.isNonLocal())
00578     return Dep;
00579   
00580   // Keep the ReverseNonLocalPtrDeps map up to date so we can efficiently
00581   // update MemDep when we remove instructions.
00582   Instruction *Inst = Dep.getInst();
00583   assert(Inst && "Didn't depend on anything?");
00584   ValueIsLoadPair CacheKey(Pointer, isLoad);
00585   ReverseNonLocalPtrDeps[Inst].insert(CacheKey.getOpaqueValue());
00586   return Dep;
00587 }
00588 
00589 
00590 /// getNonLocalPointerDepFromBB - Perform a dependency query based on
00591 /// pointer/pointeesize starting at the end of StartBB.  Add any clobber/def
00592 /// results to the results vector and keep track of which blocks are visited in
00593 /// 'Visited'.
00594 ///
00595 /// This has special behavior for the first block queries (when SkipFirstBlock
00596 /// is true).  In this special case, it ignores the contents of the specified
00597 /// block and starts returning dependence info for its predecessors.
00598 ///
00599 /// This function returns false on success, or true to indicate that it could
00600 /// not compute dependence information for some reason.  This should be treated
00601 /// as a clobber dependence on the first instruction in the predecessor block.
00602 bool MemoryDependenceAnalysis::
00603 getNonLocalPointerDepFromBB(Value *Pointer, uint64_t PointeeSize,
00604                             bool isLoad, BasicBlock *StartBB,
00605                             SmallVectorImpl<NonLocalDepEntry> &Result,
00606                             DenseMap<BasicBlock*, Value*> &Visited,
00607                             bool SkipFirstBlock) {
00608   
00609   // Look up the cached info for Pointer.
00610   ValueIsLoadPair CacheKey(Pointer, isLoad);
00611   
00612   std::pair<BBSkipFirstBlockPair, NonLocalDepInfo> *CacheInfo =
00613     &NonLocalPointerDeps[CacheKey];
00614   NonLocalDepInfo *Cache = &CacheInfo->second;
00615 
00616   // If we have valid cached information for exactly the block we are
00617   // investigating, just return it with no recomputation.
00618   if (CacheInfo->first == BBSkipFirstBlockPair(StartBB, SkipFirstBlock)) {
00619     // We have a fully cached result for this query then we can just return the
00620     // cached results and populate the visited set.  However, we have to verify
00621     // that we don't already have conflicting results for these blocks.  Check
00622     // to ensure that if a block in the results set is in the visited set that
00623     // it was for the same pointer query.
00624     if (!Visited.empty()) {
00625       for (NonLocalDepInfo::iterator I = Cache->begin(), E = Cache->end();
00626            I != E; ++I) {
00627         DenseMap<BasicBlock*, Value*>::iterator VI = Visited.find(I->first);
00628         if (VI == Visited.end() || VI->second == Pointer) continue;
00629         
00630         // We have a pointer mismatch in a block.  Just return clobber, saying
00631         // that something was clobbered in this result.  We could also do a
00632         // non-fully cached query, but there is little point in doing this.
00633         return true;
00634       }
00635     }
00636     
00637     for (NonLocalDepInfo::iterator I = Cache->begin(), E = Cache->end();
00638          I != E; ++I) {
00639       Visited.insert(std::make_pair(I->first, Pointer));
00640       if (!I->second.isNonLocal())
00641         Result.push_back(*I);
00642     }
00643     ++NumCacheCompleteNonLocalPtr;
00644     return false;
00645   }
00646   
00647   // Otherwise, either this is a new block, a block with an invalid cache
00648   // pointer or one that we're about to invalidate by putting more info into it
00649   // than its valid cache info.  If empty, the result will be valid cache info,
00650   // otherwise it isn't.
00651   if (Cache->empty())
00652     CacheInfo->first = BBSkipFirstBlockPair(StartBB, SkipFirstBlock);
00653   else
00654     CacheInfo->first = BBSkipFirstBlockPair();
00655   
00656   SmallVector<BasicBlock*, 32> Worklist;
00657   Worklist.push_back(StartBB);
00658   
00659   // Keep track of the entries that we know are sorted.  Previously cached
00660   // entries will all be sorted.  The entries we add we only sort on demand (we
00661   // don't insert every element into its sorted position).  We know that we
00662   // won't get any reuse from currently inserted values, because we don't
00663   // revisit blocks after we insert info for them.
00664   unsigned NumSortedEntries = Cache->size();
00665   DEBUG(AssertSorted(*Cache));
00666   
00667   while (!Worklist.empty()) {
00668     BasicBlock *BB = Worklist.pop_back_val();
00669     
00670     // Skip the first block if we have it.
00671     if (!SkipFirstBlock) {
00672       // Analyze the dependency of *Pointer in FromBB.  See if we already have
00673       // been here.
00674       assert(Visited.count(BB) && "Should check 'visited' before adding to WL");
00675 
00676       // Get the dependency info for Pointer in BB.  If we have cached
00677       // information, we will use it, otherwise we compute it.
00678       DEBUG(AssertSorted(*Cache, NumSortedEntries));
00679       MemDepResult Dep = GetNonLocalInfoForBlock(Pointer, PointeeSize, isLoad,
00680                                                  BB, Cache, NumSortedEntries);
00681       
00682       // If we got a Def or Clobber, add this to the list of results.
00683       if (!Dep.isNonLocal()) {
00684         Result.push_back(NonLocalDepEntry(BB, Dep));
00685         continue;
00686       }
00687     }
00688     
00689     // If 'Pointer' is an instruction defined in this block, then we need to do
00690     // phi translation to change it into a value live in the predecessor block.
00691     // If phi translation fails, then we can't continue dependence analysis.
00692     Instruction *PtrInst = dyn_cast<Instruction>(Pointer);
00693     bool NeedsPHITranslation = PtrInst && PtrInst->getParent() == BB;
00694     
00695     // If no PHI translation is needed, just add all the predecessors of this
00696     // block to scan them as well.
00697     if (!NeedsPHITranslation) {
00698       SkipFirstBlock = false;
00699       for (BasicBlock **PI = PredCache->GetPreds(BB); *PI; ++PI) {
00700         // Verify that we haven't looked at this block yet.
00701         std::pair<DenseMap<BasicBlock*,Value*>::iterator, bool>
00702           InsertRes = Visited.insert(std::make_pair(*PI, Pointer));
00703         if (InsertRes.second) {
00704           // First time we've looked at *PI.
00705           Worklist.push_back(*PI);
00706           continue;
00707         }
00708         
00709         // If we have seen this block before, but it was with a different
00710         // pointer then we have a phi translation failure and we have to treat
00711         // this as a clobber.
00712         if (InsertRes.first->second != Pointer)
00713           goto PredTranslationFailure;
00714       }
00715       continue;
00716     }
00717     
00718     // If we do need to do phi translation, then there are a bunch of different
00719     // cases, because we have to find a Value* live in the predecessor block. We
00720     // know that PtrInst is defined in this block at least.
00721     
00722     // If this is directly a PHI node, just use the incoming values for each
00723     // pred as the phi translated version.
00724     if (PHINode *PtrPHI = dyn_cast<PHINode>(PtrInst)) {
00725       for (BasicBlock **PI = PredCache->GetPreds(BB); *PI; ++PI) {
00726         BasicBlock *Pred = *PI;
00727         Value *PredPtr = PtrPHI->getIncomingValueForBlock(Pred);
00728         
00729         // Check to see if we have already visited this pred block with another
00730         // pointer.  If so, we can't do this lookup.  This failure can occur
00731         // with PHI translation when a critical edge exists and the PHI node in
00732         // the successor translates to a pointer value different than the
00733         // pointer the block was first analyzed with.
00734         std::pair<DenseMap<BasicBlock*,Value*>::iterator, bool>
00735           InsertRes = Visited.insert(std::make_pair(Pred, PredPtr));
00736 
00737         if (!InsertRes.second) {
00738           // If the predecessor was visited with PredPtr, then we already did
00739           // the analysis and can ignore it.
00740           if (InsertRes.first->second == PredPtr)
00741             continue;
00742           
00743           // Otherwise, the block was previously analyzed with a different
00744           // pointer.  We can't represent the result of this case, so we just
00745           // treat this as a phi translation failure.
00746           goto PredTranslationFailure;
00747         }
00748 
00749         // We may have added values to the cache list before this PHI
00750         // translation.  If so, we haven't done anything to ensure that the
00751         // cache remains sorted.  Sort it now (if needed) so that recursive
00752         // invocations of getNonLocalPointerDepFromBB that could reuse the cache
00753         // value will only see properly sorted cache arrays.
00754         if (Cache && NumSortedEntries != Cache->size())
00755           std::sort(Cache->begin(), Cache->end());
00756         Cache = 0;
00757         
00758         // FIXME: it is entirely possible that PHI translating will end up with
00759         // the same value.  Consider PHI translating something like:
00760         // X = phi [x, bb1], [y, bb2].  PHI translating for bb1 doesn't *need*
00761         // to recurse here, pedantically speaking.
00762         
00763         // If we have a problem phi translating, fall through to the code below
00764         // to handle the failure condition.
00765         if (getNonLocalPointerDepFromBB(PredPtr, PointeeSize, isLoad, Pred,
00766                                         Result, Visited))
00767           goto PredTranslationFailure;
00768       }
00769 
00770       // Refresh the CacheInfo/Cache pointer so that it isn't invalidated.
00771       CacheInfo = &NonLocalPointerDeps[CacheKey];
00772       Cache = &CacheInfo->second;
00773       NumSortedEntries = Cache->size();
00774       
00775       // Since we did phi translation, the "Cache" set won't contain all of the
00776       // results for the query.  This is ok (we can still use it to accelerate
00777       // specific block queries) but we can't do the fastpath "return all
00778       // results from the set"  Clear out the indicator for this.
00779       CacheInfo->first = BBSkipFirstBlockPair();
00780       SkipFirstBlock = false;
00781       continue;
00782     }
00783     
00784     // TODO: BITCAST, GEP.
00785     
00786     //   cerr << "MEMDEP: Could not PHI translate: " << *Pointer;
00787     //   if (isa<BitCastInst>(PtrInst) || isa<GetElementPtrInst>(PtrInst))
00788     //     cerr << "OP:\t\t\t\t" << *PtrInst->getOperand(0);
00789   PredTranslationFailure:
00790     
00791     if (Cache == 0) {
00792       // Refresh the CacheInfo/Cache pointer if it got invalidated.
00793       CacheInfo = &NonLocalPointerDeps[CacheKey];
00794       Cache = &CacheInfo->second;
00795       NumSortedEntries = Cache->size();
00796     } else if (NumSortedEntries != Cache->size()) {
00797       std::sort(Cache->begin(), Cache->end());
00798       NumSortedEntries = Cache->size();
00799     }
00800 
00801     // Since we did phi translation, the "Cache" set won't contain all of the
00802     // results for the query.  This is ok (we can still use it to accelerate
00803     // specific block queries) but we can't do the fastpath "return all
00804     // results from the set"  Clear out the indicator for this.
00805     CacheInfo->first = BBSkipFirstBlockPair();
00806     
00807     // If *nothing* works, mark the pointer as being clobbered by the first
00808     // instruction in this block.
00809     //
00810     // If this is the magic first block, return this as a clobber of the whole
00811     // incoming value.  Since we can't phi translate to one of the predecessors,
00812     // we have to bail out.
00813     if (SkipFirstBlock)
00814       return true;
00815     
00816     for (NonLocalDepInfo::reverse_iterator I = Cache->rbegin(); ; ++I) {
00817       assert(I != Cache->rend() && "Didn't find current block??");
00818       if (I->first != BB)
00819         continue;
00820       
00821       assert(I->second.isNonLocal() &&
00822              "Should only be here with transparent block");
00823       I->second = MemDepResult::getClobber(BB->begin());
00824       ReverseNonLocalPtrDeps[BB->begin()].insert(CacheKey.getOpaqueValue());
00825       Result.push_back(*I);
00826       break;
00827     }
00828   }
00829 
00830   // Okay, we're done now.  If we added new values to the cache, re-sort it.
00831   switch (Cache->size()-NumSortedEntries) {
00832   case 0:
00833     // done, no new entries.
00834     break;
00835   case 2: {
00836     // Two new entries, insert the last one into place.
00837     NonLocalDepEntry Val = Cache->back();
00838     Cache->pop_back();
00839     NonLocalDepInfo::iterator Entry =
00840     std::upper_bound(Cache->begin(), Cache->end()-1, Val);
00841     Cache->insert(Entry, Val);
00842     // FALL THROUGH.
00843   }
00844   case 1:
00845     // One new entry, Just insert the new value at the appropriate position.
00846     if (Cache->size() != 1) {
00847       NonLocalDepEntry Val = Cache->back();
00848       Cache->pop_back();
00849       NonLocalDepInfo::iterator Entry =
00850         std::upper_bound(Cache->begin(), Cache->end(), Val);
00851       Cache->insert(Entry, Val);
00852     }
00853     break;
00854   default:
00855     // Added many values, do a full scale sort.
00856     std::sort(Cache->begin(), Cache->end());
00857   }
00858   DEBUG(AssertSorted(*Cache));
00859   return false;
00860 }
00861 
00862 /// RemoveCachedNonLocalPointerDependencies - If P exists in
00863 /// CachedNonLocalPointerInfo, remove it.
00864 void MemoryDependenceAnalysis::
00865 RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair P) {
00866   CachedNonLocalPointerInfo::iterator It = 
00867     NonLocalPointerDeps.find(P);
00868   if (It == NonLocalPointerDeps.end()) return;
00869   
00870   // Remove all of the entries in the BB->val map.  This involves removing
00871   // instructions from the reverse map.
00872   NonLocalDepInfo &PInfo = It->second.second;
00873   
00874   for (unsigned i = 0, e = PInfo.size(); i != e; ++i) {
00875     Instruction *Target = PInfo[i].second.getInst();
00876     if (Target == 0) continue;  // Ignore non-local dep results.
00877     assert(Target->getParent() == PInfo[i].first);
00878     
00879     // Eliminating the dirty entry from 'Cache', so update the reverse info.
00880     RemoveFromReverseMap(ReverseNonLocalPtrDeps, Target, P.getOpaqueValue());
00881   }
00882   
00883   // Remove P from NonLocalPointerDeps (which deletes NonLocalDepInfo).
00884   NonLocalPointerDeps.erase(It);
00885 }
00886 
00887 
00888 /// invalidateCachedPointerInfo - This method is used to invalidate cached
00889 /// information about the specified pointer, because it may be too
00890 /// conservative in memdep.  This is an optional call that can be used when
00891 /// the client detects an equivalence between the pointer and some other
00892 /// value and replaces the other value with ptr. This can make Ptr available
00893 /// in more places that cached info does not necessarily keep.
00894 void MemoryDependenceAnalysis::invalidateCachedPointerInfo(Value *Ptr) {
00895   // If Ptr isn't really a pointer, just ignore it.
00896   if (!isa<PointerType>(Ptr->getType())) return;
00897   // Flush store info for the pointer.
00898   RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(Ptr, false));
00899   // Flush load info for the pointer.
00900   RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(Ptr, true));
00901 }
00902 
00903 /// removeInstruction - Remove an instruction from the dependence analysis,
00904 /// updating the dependence of instructions that previously depended on it.
00905 /// This method attempts to keep the cache coherent using the reverse map.
00906 void MemoryDependenceAnalysis::removeInstruction(Instruction *RemInst) {
00907   // Walk through the Non-local dependencies, removing this one as the value
00908   // for any cached queries.
00909   NonLocalDepMapType::iterator NLDI = NonLocalDeps.find(RemInst);
00910   if (NLDI != NonLocalDeps.end()) {
00911     NonLocalDepInfo &BlockMap = NLDI->second.first;
00912     for (NonLocalDepInfo::iterator DI = BlockMap.begin(), DE = BlockMap.end();
00913          DI != DE; ++DI)
00914       if (Instruction *Inst = DI->second.getInst())
00915         RemoveFromReverseMap(ReverseNonLocalDeps, Inst, RemInst);
00916     NonLocalDeps.erase(NLDI);
00917   }
00918 
00919   // If we have a cached local dependence query for this instruction, remove it.
00920   //
00921   LocalDepMapType::iterator LocalDepEntry = LocalDeps.find(RemInst);
00922   if (LocalDepEntry != LocalDeps.end()) {
00923     // Remove us from DepInst's reverse set now that the local dep info is gone.
00924     if (Instruction *Inst = LocalDepEntry->second.getInst())
00925       RemoveFromReverseMap(ReverseLocalDeps, Inst, RemInst);
00926 
00927     // Remove this local dependency info.
00928     LocalDeps.erase(LocalDepEntry);
00929   }
00930   
00931   // If we have any cached pointer dependencies on this instruction, remove
00932   // them.  If the instruction has non-pointer type, then it can't be a pointer
00933   // base.
00934   
00935   // Remove it from both the load info and the store info.  The instruction
00936   // can't be in either of these maps if it is non-pointer.
00937   if (isa<PointerType>(RemInst->getType())) {
00938     RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(RemInst, false));
00939     RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(RemInst, true));
00940   }
00941   
00942   // Loop over all of the things that depend on the instruction we're removing.
00943   // 
00944   SmallVector<std::pair<Instruction*, Instruction*>, 8> ReverseDepsToAdd;
00945 
00946   // If we find RemInst as a clobber or Def in any of the maps for other values,
00947   // we need to replace its entry with a dirty version of the instruction after
00948   // it.  If RemInst is a terminator, we use a null dirty value.
00949   //
00950   // Using a dirty version of the instruction after RemInst saves having to scan
00951   // the entire block to get to this point.
00952   MemDepResult NewDirtyVal;
00953   if (!RemInst->isTerminator())
00954     NewDirtyVal = MemDepResult::getDirty(++BasicBlock::iterator(RemInst));
00955   
00956   ReverseDepMapType::iterator ReverseDepIt = ReverseLocalDeps.find(RemInst);
00957   if (ReverseDepIt != ReverseLocalDeps.end()) {
00958     SmallPtrSet<Instruction*, 4> &ReverseDeps = ReverseDepIt->second;
00959     // RemInst can't be the terminator if it has local stuff depending on it.
00960     assert(!ReverseDeps.empty() && !isa<TerminatorInst>(RemInst) &&
00961            "Nothing can locally depend on a terminator");
00962     
00963     for (SmallPtrSet<Instruction*, 4>::iterator I = ReverseDeps.begin(),
00964          E = ReverseDeps.end(); I != E; ++I) {
00965       Instruction *InstDependingOnRemInst = *I;
00966       assert(InstDependingOnRemInst != RemInst &&
00967              "Already removed our local dep info");
00968                         
00969       LocalDeps[InstDependingOnRemInst] = NewDirtyVal;
00970       
00971       // Make sure to remember that new things depend on NewDepInst.
00972       assert(NewDirtyVal.getInst() && "There is no way something else can have "
00973              "a local dep on this if it is a terminator!");
00974       ReverseDepsToAdd.push_back(std::make_pair(NewDirtyVal.getInst(), 
00975                                                 InstDependingOnRemInst));
00976     }
00977     
00978     ReverseLocalDeps.erase(ReverseDepIt);
00979 
00980     // Add new reverse deps after scanning the set, to avoid invalidating the
00981     // 'ReverseDeps' reference.
00982     while (!ReverseDepsToAdd.empty()) {
00983       ReverseLocalDeps[ReverseDepsToAdd.back().first]
00984         .insert(ReverseDepsToAdd.back().second);
00985       ReverseDepsToAdd.pop_back();
00986     }
00987   }
00988   
00989   ReverseDepIt = ReverseNonLocalDeps.find(RemInst);
00990   if (ReverseDepIt != ReverseNonLocalDeps.end()) {
00991     SmallPtrSet<Instruction*, 4> &Set = ReverseDepIt->second;
00992     for (SmallPtrSet<Instruction*, 4>::iterator I = Set.begin(), E = Set.end();
00993          I != E; ++I) {
00994       assert(*I != RemInst && "Already removed NonLocalDep info for RemInst");
00995       
00996       PerInstNLInfo &INLD = NonLocalDeps[*I];
00997       // The information is now dirty!
00998       INLD.second = true;
00999       
01000       for (NonLocalDepInfo::iterator DI = INLD.first.begin(), 
01001            DE = INLD.first.end(); DI != DE; ++DI) {
01002         if (DI->second.getInst() != RemInst) continue;
01003         
01004         // Convert to a dirty entry for the subsequent instruction.
01005         DI->second = NewDirtyVal;
01006         
01007         if (Instruction *NextI = NewDirtyVal.getInst())
01008           ReverseDepsToAdd.push_back(std::make_pair(NextI, *I));
01009       }
01010     }
01011 
01012     ReverseNonLocalDeps.erase(ReverseDepIt);
01013 
01014     // Add new reverse deps after scanning the set, to avoid invalidating 'Set'
01015     while (!ReverseDepsToAdd.empty()) {
01016       ReverseNonLocalDeps[ReverseDepsToAdd.back().first]
01017         .insert(ReverseDepsToAdd.back().second);
01018       ReverseDepsToAdd.pop_back();
01019     }
01020   }
01021   
01022   // If the instruction is in ReverseNonLocalPtrDeps then it appears as a
01023   // value in the NonLocalPointerDeps info.
01024   ReverseNonLocalPtrDepTy::iterator ReversePtrDepIt =
01025     ReverseNonLocalPtrDeps.find(RemInst);
01026   if (ReversePtrDepIt != ReverseNonLocalPtrDeps.end()) {
01027     SmallPtrSet<void*, 4> &Set = ReversePtrDepIt->second;
01028     SmallVector<std::pair<Instruction*, ValueIsLoadPair>,8> ReversePtrDepsToAdd;
01029     
01030     for (SmallPtrSet<void*, 4>::iterator I = Set.begin(), E = Set.end();
01031          I != E; ++I) {
01032       ValueIsLoadPair P;
01033       P.setFromOpaqueValue(*I);
01034       assert(P.getPointer() != RemInst &&
01035              "Already removed NonLocalPointerDeps info for RemInst");
01036       
01037       NonLocalDepInfo &NLPDI = NonLocalPointerDeps[P].second;
01038       
01039       // The cache is not valid for any specific block anymore.
01040       NonLocalPointerDeps[P].first = BBSkipFirstBlockPair();
01041       
01042       // Update any entries for RemInst to use the instruction after it.
01043       for (NonLocalDepInfo::iterator DI = NLPDI.begin(), DE = NLPDI.end();
01044            DI != DE; ++DI) {
01045         if (DI->second.getInst() != RemInst) continue;
01046         
01047         // Convert to a dirty entry for the subsequent instruction.
01048         DI->second = NewDirtyVal;
01049         
01050         if (Instruction *NewDirtyInst = NewDirtyVal.getInst())
01051           ReversePtrDepsToAdd.push_back(std::make_pair(NewDirtyInst, P));
01052       }
01053       
01054       // Re-sort the NonLocalDepInfo.  Changing the dirty entry to its
01055       // subsequent value may invalidate the sortedness.
01056       std::sort(NLPDI.begin(), NLPDI.end());
01057     }
01058     
01059     ReverseNonLocalPtrDeps.erase(ReversePtrDepIt);
01060     
01061     while (!ReversePtrDepsToAdd.empty()) {
01062       ReverseNonLocalPtrDeps[ReversePtrDepsToAdd.back().first]
01063         .insert(ReversePtrDepsToAdd.back().second.getOpaqueValue());
01064       ReversePtrDepsToAdd.pop_back();
01065     }
01066   }
01067   
01068   
01069   assert(!NonLocalDeps.count(RemInst) && "RemInst got reinserted?");
01070   AA->deleteValue(RemInst);
01071   DEBUG(verifyRemoved(RemInst));
01072 }
01073 /// verifyRemoved - Verify that the specified instruction does not occur
01074 /// in our internal data structures.
01075 void MemoryDependenceAnalysis::verifyRemoved(Instruction *D) const {
01076   for (LocalDepMapType::const_iterator I = LocalDeps.begin(),
01077        E = LocalDeps.end(); I != E; ++I) {
01078     assert(I->first != D && "Inst occurs in data structures");
01079     assert(I->second.getInst() != D &&
01080            "Inst occurs in data structures");
01081   }
01082   
01083   for (CachedNonLocalPointerInfo::const_iterator I =NonLocalPointerDeps.begin(),
01084        E = NonLocalPointerDeps.end(); I != E; ++I) {
01085     assert(I->first.getPointer() != D && "Inst occurs in NLPD map key");
01086     const NonLocalDepInfo &Val = I->second.second;
01087     for (NonLocalDepInfo::const_iterator II = Val.begin(), E = Val.end();
01088          II != E; ++II)
01089       assert(II->second.getInst() != D && "Inst occurs as NLPD value");
01090   }
01091   
01092   for (NonLocalDepMapType::const_iterator I = NonLocalDeps.begin(),
01093        E = NonLocalDeps.end(); I != E; ++I) {
01094     assert(I->first != D && "Inst occurs in data structures");
01095     const PerInstNLInfo &INLD = I->second;
01096     for (NonLocalDepInfo::const_iterator II = INLD.first.begin(),
01097          EE = INLD.first.end(); II  != EE; ++II)
01098       assert(II->second.getInst() != D && "Inst occurs in data structures");
01099   }
01100   
01101   for (ReverseDepMapType::const_iterator I = ReverseLocalDeps.begin(),
01102        E = ReverseLocalDeps.end(); I != E; ++I) {
01103     assert(I->first != D && "Inst occurs in data structures");
01104     for (SmallPtrSet<Instruction*, 4>::const_iterator II = I->second.begin(),
01105          EE = I->second.end(); II != EE; ++II)
01106       assert(*II != D && "Inst occurs in data structures");
01107   }
01108   
01109   for (ReverseDepMapType::const_iterator I = ReverseNonLocalDeps.begin(),
01110        E = ReverseNonLocalDeps.end();
01111        I != E; ++I) {
01112     assert(I->first != D && "Inst occurs in data structures");
01113     for (SmallPtrSet<Instruction*, 4>::const_iterator II = I->second.begin(),
01114          EE = I->second.end(); II != EE; ++II)
01115       assert(*II != D && "Inst occurs in data structures");
01116   }
01117   
01118   for (ReverseNonLocalPtrDepTy::const_iterator
01119        I = ReverseNonLocalPtrDeps.begin(),
01120        E = ReverseNonLocalPtrDeps.end(); I != E; ++I) {
01121     assert(I->first != D && "Inst occurs in rev NLPD map");
01122     
01123     for (SmallPtrSet<void*, 4>::const_iterator II = I->second.begin(),
01124          E = I->second.end(); II != E; ++II)
01125       assert(*II != ValueIsLoadPair(D, false).getOpaqueValue() &&
01126              *II != ValueIsLoadPair(D, true).getOpaqueValue() &&
01127              "Inst occurs in ReverseNonLocalPtrDeps map");
01128   }
01129   
01130 }