LLVM API Documentation

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