MemoryDependenceAnalysis.cpp revision 9e59c64c14cfe55e7cc9086c6bff8cfeecac361e
1//===- MemoryDependenceAnalysis.cpp - Mem Deps Implementation  --*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements an analysis that determines, for a given memory
11// operation, what preceding memory operations it depends on.  It builds on
12// alias analysis information, and tries to provide a lazy, caching interface to
13// a common kind of alias information query.
14//
15//===----------------------------------------------------------------------===//
16
17#define DEBUG_TYPE "memdep"
18#include "llvm/Analysis/MemoryDependenceAnalysis.h"
19#include "llvm/Constants.h"
20#include "llvm/Instructions.h"
21#include "llvm/Function.h"
22#include "llvm/Analysis/AliasAnalysis.h"
23#include "llvm/ADT/Statistic.h"
24#include "llvm/ADT/STLExtras.h"
25#include "llvm/Support/PredIteratorCache.h"
26#include "llvm/Support/Debug.h"
27#include "llvm/Target/TargetData.h"
28using namespace llvm;
29
30STATISTIC(NumCacheNonLocal, "Number of fully cached non-local responses");
31STATISTIC(NumCacheDirtyNonLocal, "Number of dirty cached non-local responses");
32STATISTIC(NumUncacheNonLocal, "Number of uncached non-local responses");
33
34STATISTIC(NumCacheNonLocalPtr,
35          "Number of fully cached non-local ptr responses");
36STATISTIC(NumCacheDirtyNonLocalPtr,
37          "Number of cached, but dirty, non-local ptr responses");
38STATISTIC(NumUncacheNonLocalPtr,
39          "Number of uncached non-local ptr responses");
40STATISTIC(NumCacheCompleteNonLocalPtr,
41          "Number of block queries that were completely cached");
42
43char MemoryDependenceAnalysis::ID = 0;
44
45// Register this pass...
46static RegisterPass<MemoryDependenceAnalysis> X("memdep",
47                                     "Memory Dependence Analysis", false, true);
48
49MemoryDependenceAnalysis::MemoryDependenceAnalysis()
50: FunctionPass(&ID), PredCache(0) {
51}
52MemoryDependenceAnalysis::~MemoryDependenceAnalysis() {
53}
54
55/// Clean up memory in between runs
56void MemoryDependenceAnalysis::releaseMemory() {
57  LocalDeps.clear();
58  NonLocalDeps.clear();
59  NonLocalPointerDeps.clear();
60  ReverseLocalDeps.clear();
61  ReverseNonLocalDeps.clear();
62  ReverseNonLocalPtrDeps.clear();
63  PredCache->clear();
64}
65
66
67
68/// getAnalysisUsage - Does not modify anything.  It uses Alias Analysis.
69///
70void MemoryDependenceAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
71  AU.setPreservesAll();
72  AU.addRequiredTransitive<AliasAnalysis>();
73  AU.addRequiredTransitive<TargetData>();
74}
75
76bool MemoryDependenceAnalysis::runOnFunction(Function &) {
77  AA = &getAnalysis<AliasAnalysis>();
78  TD = &getAnalysis<TargetData>();
79  if (PredCache == 0)
80    PredCache.reset(new PredIteratorCache());
81  return false;
82}
83
84/// RemoveFromReverseMap - This is a helper function that removes Val from
85/// 'Inst's set in ReverseMap.  If the set becomes empty, remove Inst's entry.
86template <typename KeyTy>
87static void RemoveFromReverseMap(DenseMap<Instruction*,
88                                 SmallPtrSet<KeyTy*, 4> > &ReverseMap,
89                                 Instruction *Inst, KeyTy *Val) {
90  typename DenseMap<Instruction*, SmallPtrSet<KeyTy*, 4> >::iterator
91  InstIt = ReverseMap.find(Inst);
92  assert(InstIt != ReverseMap.end() && "Reverse map out of sync?");
93  bool Found = InstIt->second.erase(Val);
94  assert(Found && "Invalid reverse map!"); Found=Found;
95  if (InstIt->second.empty())
96    ReverseMap.erase(InstIt);
97}
98
99
100/// getCallSiteDependencyFrom - Private helper for finding the local
101/// dependencies of a call site.
102MemDepResult MemoryDependenceAnalysis::
103getCallSiteDependencyFrom(CallSite CS, bool isReadOnlyCall,
104                          BasicBlock::iterator ScanIt, BasicBlock *BB) {
105  // Walk backwards through the block, looking for dependencies
106  while (ScanIt != BB->begin()) {
107    Instruction *Inst = --ScanIt;
108
109    // If this inst is a memory op, get the pointer it accessed
110    Value *Pointer = 0;
111    uint64_t PointerSize = 0;
112    if (StoreInst *S = dyn_cast<StoreInst>(Inst)) {
113      Pointer = S->getPointerOperand();
114      PointerSize = TD->getTypeStoreSize(S->getOperand(0)->getType());
115    } else if (VAArgInst *V = dyn_cast<VAArgInst>(Inst)) {
116      Pointer = V->getOperand(0);
117      PointerSize = TD->getTypeStoreSize(V->getType());
118    } else if (FreeInst *F = dyn_cast<FreeInst>(Inst)) {
119      Pointer = F->getPointerOperand();
120
121      // FreeInsts erase the entire structure
122      PointerSize = ~0ULL;
123    } else if (isa<CallInst>(Inst) || isa<InvokeInst>(Inst)) {
124      CallSite InstCS = CallSite::get(Inst);
125      // If these two calls do not interfere, look past it.
126      switch (AA->getModRefInfo(CS, InstCS)) {
127      case AliasAnalysis::NoModRef:
128        // If the two calls don't interact (e.g. InstCS is readnone) keep
129        // scanning.
130        continue;
131      case AliasAnalysis::Ref:
132        // If the two calls read the same memory locations and CS is a readonly
133        // function, then we have two cases: 1) the calls may not interfere with
134        // each other at all.  2) the calls may produce the same value.  In case
135        // #1 we want to ignore the values, in case #2, we want to return Inst
136        // as a Def dependence.  This allows us to CSE in cases like:
137        //   X = strlen(P);
138        //    memchr(...);
139        //   Y = strlen(P);  // Y = X
140        if (isReadOnlyCall) {
141          if (CS.getCalledFunction() != 0 &&
142              CS.getCalledFunction() == InstCS.getCalledFunction())
143            return MemDepResult::getDef(Inst);
144          // Ignore unrelated read/read call dependences.
145          continue;
146        }
147        // FALL THROUGH
148      default:
149        return MemDepResult::getClobber(Inst);
150      }
151    } else {
152      // Non-memory instruction.
153      continue;
154    }
155
156    if (AA->getModRefInfo(CS, Pointer, PointerSize) != AliasAnalysis::NoModRef)
157      return MemDepResult::getClobber(Inst);
158  }
159
160  // No dependence found.  If this is the entry block of the function, it is a
161  // clobber, otherwise it is non-local.
162  if (BB != &BB->getParent()->getEntryBlock())
163    return MemDepResult::getNonLocal();
164  return MemDepResult::getClobber(ScanIt);
165}
166
167/// getPointerDependencyFrom - Return the instruction on which a memory
168/// location depends.  If isLoad is true, this routine ignore may-aliases with
169/// read-only operations.
170MemDepResult MemoryDependenceAnalysis::
171getPointerDependencyFrom(Value *MemPtr, uint64_t MemSize, bool isLoad,
172                         BasicBlock::iterator ScanIt, BasicBlock *BB) {
173
174  // Walk backwards through the basic block, looking for dependencies.
175  while (ScanIt != BB->begin()) {
176    Instruction *Inst = --ScanIt;
177
178    // Values depend on loads if the pointers are must aliased.  This means that
179    // a load depends on another must aliased load from the same value.
180    if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
181      Value *Pointer = LI->getPointerOperand();
182      uint64_t PointerSize = TD->getTypeStoreSize(LI->getType());
183
184      // If we found a pointer, check if it could be the same as our pointer.
185      AliasAnalysis::AliasResult R =
186        AA->alias(Pointer, PointerSize, MemPtr, MemSize);
187      if (R == AliasAnalysis::NoAlias)
188        continue;
189
190      // May-alias loads don't depend on each other without a dependence.
191      if (isLoad && R == AliasAnalysis::MayAlias)
192        continue;
193      // Stores depend on may and must aliased loads, loads depend on must-alias
194      // loads.
195      return MemDepResult::getDef(Inst);
196    }
197
198    if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
199      Value *Pointer = SI->getPointerOperand();
200      uint64_t PointerSize = TD->getTypeStoreSize(SI->getOperand(0)->getType());
201
202      // If we found a pointer, check if it could be the same as our pointer.
203      AliasAnalysis::AliasResult R =
204        AA->alias(Pointer, PointerSize, MemPtr, MemSize);
205
206      if (R == AliasAnalysis::NoAlias)
207        continue;
208      if (R == AliasAnalysis::MayAlias)
209        return MemDepResult::getClobber(Inst);
210      return MemDepResult::getDef(Inst);
211    }
212
213    // If this is an allocation, and if we know that the accessed pointer is to
214    // the allocation, return Def.  This means that there is no dependence and
215    // the access can be optimized based on that.  For example, a load could
216    // turn into undef.
217    if (AllocationInst *AI = dyn_cast<AllocationInst>(Inst)) {
218      Value *AccessPtr = MemPtr->getUnderlyingObject();
219
220      if (AccessPtr == AI ||
221          AA->alias(AI, 1, AccessPtr, 1) == AliasAnalysis::MustAlias)
222        return MemDepResult::getDef(AI);
223      continue;
224    }
225
226    // See if this instruction (e.g. a call or vaarg) mod/ref's the pointer.
227    switch (AA->getModRefInfo(Inst, MemPtr, MemSize)) {
228    case AliasAnalysis::NoModRef:
229      // If the call has no effect on the queried pointer, just ignore it.
230      continue;
231    case AliasAnalysis::Ref:
232      // If the call is known to never store to the pointer, and if this is a
233      // load query, we can safely ignore it (scan past it).
234      if (isLoad)
235        continue;
236      // FALL THROUGH.
237    default:
238      // Otherwise, there is a potential dependence.  Return a clobber.
239      return MemDepResult::getClobber(Inst);
240    }
241  }
242
243  // No dependence found.  If this is the entry block of the function, it is a
244  // clobber, otherwise it is non-local.
245  if (BB != &BB->getParent()->getEntryBlock())
246    return MemDepResult::getNonLocal();
247  return MemDepResult::getClobber(ScanIt);
248}
249
250/// getDependency - Return the instruction on which a memory operation
251/// depends.
252MemDepResult MemoryDependenceAnalysis::getDependency(Instruction *QueryInst) {
253  Instruction *ScanPos = QueryInst;
254
255  // Check for a cached result
256  MemDepResult &LocalCache = LocalDeps[QueryInst];
257
258  // If the cached entry is non-dirty, just return it.  Note that this depends
259  // on MemDepResult's default constructing to 'dirty'.
260  if (!LocalCache.isDirty())
261    return LocalCache;
262
263  // Otherwise, if we have a dirty entry, we know we can start the scan at that
264  // instruction, which may save us some work.
265  if (Instruction *Inst = LocalCache.getInst()) {
266    ScanPos = Inst;
267
268    RemoveFromReverseMap(ReverseLocalDeps, Inst, QueryInst);
269  }
270
271  BasicBlock *QueryParent = QueryInst->getParent();
272
273  Value *MemPtr = 0;
274  uint64_t MemSize = 0;
275
276  // Do the scan.
277  if (BasicBlock::iterator(QueryInst) == QueryParent->begin()) {
278    // No dependence found.  If this is the entry block of the function, it is a
279    // clobber, otherwise it is non-local.
280    if (QueryParent != &QueryParent->getParent()->getEntryBlock())
281      LocalCache = MemDepResult::getNonLocal();
282    else
283      LocalCache = MemDepResult::getClobber(QueryInst);
284  } else if (StoreInst *SI = dyn_cast<StoreInst>(QueryInst)) {
285    // If this is a volatile store, don't mess around with it.  Just return the
286    // previous instruction as a clobber.
287    if (SI->isVolatile())
288      LocalCache = MemDepResult::getClobber(--BasicBlock::iterator(ScanPos));
289    else {
290      MemPtr = SI->getPointerOperand();
291      MemSize = TD->getTypeStoreSize(SI->getOperand(0)->getType());
292    }
293  } else if (LoadInst *LI = dyn_cast<LoadInst>(QueryInst)) {
294    // If this is a volatile load, don't mess around with it.  Just return the
295    // previous instruction as a clobber.
296    if (LI->isVolatile())
297      LocalCache = MemDepResult::getClobber(--BasicBlock::iterator(ScanPos));
298    else {
299      MemPtr = LI->getPointerOperand();
300      MemSize = TD->getTypeStoreSize(LI->getType());
301    }
302  } else if (isa<CallInst>(QueryInst) || isa<InvokeInst>(QueryInst)) {
303    CallSite QueryCS = CallSite::get(QueryInst);
304    bool isReadOnly = AA->onlyReadsMemory(QueryCS);
305    LocalCache = getCallSiteDependencyFrom(QueryCS, isReadOnly, ScanPos,
306                                           QueryParent);
307  } else if (FreeInst *FI = dyn_cast<FreeInst>(QueryInst)) {
308    MemPtr = FI->getPointerOperand();
309    // FreeInsts erase the entire structure, not just a field.
310    MemSize = ~0UL;
311  } else {
312    // Non-memory instruction.
313    LocalCache = MemDepResult::getClobber(--BasicBlock::iterator(ScanPos));
314  }
315
316  // If we need to do a pointer scan, make it happen.
317  if (MemPtr)
318    LocalCache = getPointerDependencyFrom(MemPtr, MemSize,
319                                          isa<LoadInst>(QueryInst),
320                                          ScanPos, QueryParent);
321
322  // Remember the result!
323  if (Instruction *I = LocalCache.getInst())
324    ReverseLocalDeps[I].insert(QueryInst);
325
326  return LocalCache;
327}
328
329/// getNonLocalCallDependency - Perform a full dependency query for the
330/// specified call, returning the set of blocks that the value is
331/// potentially live across.  The returned set of results will include a
332/// "NonLocal" result for all blocks where the value is live across.
333///
334/// This method assumes the instruction returns a "NonLocal" dependency
335/// within its own block.
336///
337/// This returns a reference to an internal data structure that may be
338/// invalidated on the next non-local query or when an instruction is
339/// removed.  Clients must copy this data if they want it around longer than
340/// that.
341const MemoryDependenceAnalysis::NonLocalDepInfo &
342MemoryDependenceAnalysis::getNonLocalCallDependency(CallSite QueryCS) {
343  assert(getDependency(QueryCS.getInstruction()).isNonLocal() &&
344 "getNonLocalCallDependency should only be used on calls with non-local deps!");
345  PerInstNLInfo &CacheP = NonLocalDeps[QueryCS.getInstruction()];
346  NonLocalDepInfo &Cache = CacheP.first;
347
348  /// DirtyBlocks - This is the set of blocks that need to be recomputed.  In
349  /// the cached case, this can happen due to instructions being deleted etc. In
350  /// the uncached case, this starts out as the set of predecessors we care
351  /// about.
352  SmallVector<BasicBlock*, 32> DirtyBlocks;
353
354  if (!Cache.empty()) {
355    // Okay, we have a cache entry.  If we know it is not dirty, just return it
356    // with no computation.
357    if (!CacheP.second) {
358      NumCacheNonLocal++;
359      return Cache;
360    }
361
362    // If we already have a partially computed set of results, scan them to
363    // determine what is dirty, seeding our initial DirtyBlocks worklist.
364    for (NonLocalDepInfo::iterator I = Cache.begin(), E = Cache.end();
365       I != E; ++I)
366      if (I->second.isDirty())
367        DirtyBlocks.push_back(I->first);
368
369    // Sort the cache so that we can do fast binary search lookups below.
370    std::sort(Cache.begin(), Cache.end());
371
372    ++NumCacheDirtyNonLocal;
373    //cerr << "CACHED CASE: " << DirtyBlocks.size() << " dirty: "
374    //     << Cache.size() << " cached: " << *QueryInst;
375  } else {
376    // Seed DirtyBlocks with each of the preds of QueryInst's block.
377    BasicBlock *QueryBB = QueryCS.getInstruction()->getParent();
378    for (BasicBlock **PI = PredCache->GetPreds(QueryBB); *PI; ++PI)
379      DirtyBlocks.push_back(*PI);
380    NumUncacheNonLocal++;
381  }
382
383  // isReadonlyCall - If this is a read-only call, we can be more aggressive.
384  bool isReadonlyCall = AA->onlyReadsMemory(QueryCS);
385
386  SmallPtrSet<BasicBlock*, 64> Visited;
387
388  unsigned NumSortedEntries = Cache.size();
389
390  // Iterate while we still have blocks to update.
391  while (!DirtyBlocks.empty()) {
392    BasicBlock *DirtyBB = DirtyBlocks.back();
393    DirtyBlocks.pop_back();
394
395    // Already processed this block?
396    if (!Visited.insert(DirtyBB))
397      continue;
398
399    // Do a binary search to see if we already have an entry for this block in
400    // the cache set.  If so, find it.
401    NonLocalDepInfo::iterator Entry =
402      std::upper_bound(Cache.begin(), Cache.begin()+NumSortedEntries,
403                       std::make_pair(DirtyBB, MemDepResult()));
404    if (Entry != Cache.begin() && prior(Entry)->first == DirtyBB)
405      --Entry;
406
407    MemDepResult *ExistingResult = 0;
408    if (Entry != Cache.begin()+NumSortedEntries &&
409        Entry->first == DirtyBB) {
410      // If we already have an entry, and if it isn't already dirty, the block
411      // is done.
412      if (!Entry->second.isDirty())
413        continue;
414
415      // Otherwise, remember this slot so we can update the value.
416      ExistingResult = &Entry->second;
417    }
418
419    // If the dirty entry has a pointer, start scanning from it so we don't have
420    // to rescan the entire block.
421    BasicBlock::iterator ScanPos = DirtyBB->end();
422    if (ExistingResult) {
423      if (Instruction *Inst = ExistingResult->getInst()) {
424        ScanPos = Inst;
425        // We're removing QueryInst's use of Inst.
426        RemoveFromReverseMap(ReverseNonLocalDeps, Inst,
427                             QueryCS.getInstruction());
428      }
429    }
430
431    // Find out if this block has a local dependency for QueryInst.
432    MemDepResult Dep;
433
434    if (ScanPos != DirtyBB->begin()) {
435      Dep = getCallSiteDependencyFrom(QueryCS, isReadonlyCall,ScanPos, DirtyBB);
436    } else if (DirtyBB != &DirtyBB->getParent()->getEntryBlock()) {
437      // No dependence found.  If this is the entry block of the function, it is
438      // a clobber, otherwise it is non-local.
439      Dep = MemDepResult::getNonLocal();
440    } else {
441      Dep = MemDepResult::getClobber(ScanPos);
442    }
443
444    // If we had a dirty entry for the block, update it.  Otherwise, just add
445    // a new entry.
446    if (ExistingResult)
447      *ExistingResult = Dep;
448    else
449      Cache.push_back(std::make_pair(DirtyBB, Dep));
450
451    // If the block has a dependency (i.e. it isn't completely transparent to
452    // the value), remember the association!
453    if (!Dep.isNonLocal()) {
454      // Keep the ReverseNonLocalDeps map up to date so we can efficiently
455      // update this when we remove instructions.
456      if (Instruction *Inst = Dep.getInst())
457        ReverseNonLocalDeps[Inst].insert(QueryCS.getInstruction());
458    } else {
459
460      // If the block *is* completely transparent to the load, we need to check
461      // the predecessors of this block.  Add them to our worklist.
462      for (BasicBlock **PI = PredCache->GetPreds(DirtyBB); *PI; ++PI)
463        DirtyBlocks.push_back(*PI);
464    }
465  }
466
467  return Cache;
468}
469
470/// getNonLocalPointerDependency - Perform a full dependency query for an
471/// access to the specified (non-volatile) memory location, returning the
472/// set of instructions that either define or clobber the value.
473///
474/// This method assumes the pointer has a "NonLocal" dependency within its
475/// own block.
476///
477void MemoryDependenceAnalysis::
478getNonLocalPointerDependency(Value *Pointer, bool isLoad, BasicBlock *FromBB,
479                             SmallVectorImpl<NonLocalDepEntry> &Result) {
480  assert(isa<PointerType>(Pointer->getType()) &&
481         "Can't get pointer deps of a non-pointer!");
482  Result.clear();
483
484  // We know that the pointer value is live into FromBB find the def/clobbers
485  // from presecessors.
486  const Type *EltTy = cast<PointerType>(Pointer->getType())->getElementType();
487  uint64_t PointeeSize = TD->getTypeStoreSize(EltTy);
488
489  // This is the set of blocks we've inspected, and the pointer we consider in
490  // each block.  Because of critical edges, we currently bail out if querying
491  // a block with multiple different pointers.  This can happen during PHI
492  // translation.
493  DenseMap<BasicBlock*, Value*> Visited;
494  if (!getNonLocalPointerDepFromBB(Pointer, PointeeSize, isLoad, FromBB,
495                                   Result, Visited, true))
496    return;
497  Result.push_back(std::make_pair(FromBB,
498                                  MemDepResult::getClobber(FromBB->begin())));
499}
500
501/// GetNonLocalInfoForBlock - Compute the memdep value for BB with
502/// Pointer/PointeeSize using either cached information in Cache or by doing a
503/// lookup (which may use dirty cache info if available).  If we do a lookup,
504/// add the result to the cache.
505MemDepResult MemoryDependenceAnalysis::
506GetNonLocalInfoForBlock(Value *Pointer, uint64_t PointeeSize,
507                        bool isLoad, BasicBlock *BB,
508                        NonLocalDepInfo *Cache, unsigned NumSortedEntries) {
509
510  // Do a binary search to see if we already have an entry for this block in
511  // the cache set.  If so, find it.
512  NonLocalDepInfo::iterator Entry =
513    std::upper_bound(Cache->begin(), Cache->begin()+NumSortedEntries,
514                     std::make_pair(BB, MemDepResult()));
515  if (Entry != Cache->begin() && prior(Entry)->first == BB)
516    --Entry;
517
518  MemDepResult *ExistingResult = 0;
519  if (Entry != Cache->begin()+NumSortedEntries && Entry->first == BB)
520    ExistingResult = &Entry->second;
521
522  // If we have a cached entry, and it is non-dirty, use it as the value for
523  // this dependency.
524  if (ExistingResult && !ExistingResult->isDirty()) {
525    ++NumCacheNonLocalPtr;
526    return *ExistingResult;
527  }
528
529  // Otherwise, we have to scan for the value.  If we have a dirty cache
530  // entry, start scanning from its position, otherwise we scan from the end
531  // of the block.
532  BasicBlock::iterator ScanPos = BB->end();
533  if (ExistingResult && ExistingResult->getInst()) {
534    assert(ExistingResult->getInst()->getParent() == BB &&
535           "Instruction invalidated?");
536    ++NumCacheDirtyNonLocalPtr;
537    ScanPos = ExistingResult->getInst();
538
539    // Eliminating the dirty entry from 'Cache', so update the reverse info.
540    ValueIsLoadPair CacheKey(Pointer, isLoad);
541    RemoveFromReverseMap(ReverseNonLocalPtrDeps, ScanPos,
542                         CacheKey.getOpaqueValue());
543  } else {
544    ++NumUncacheNonLocalPtr;
545  }
546
547  // Scan the block for the dependency.
548  MemDepResult Dep = getPointerDependencyFrom(Pointer, PointeeSize, isLoad,
549                                              ScanPos, BB);
550
551  // If we had a dirty entry for the block, update it.  Otherwise, just add
552  // a new entry.
553  if (ExistingResult)
554    *ExistingResult = Dep;
555  else
556    Cache->push_back(std::make_pair(BB, Dep));
557
558  // If the block has a dependency (i.e. it isn't completely transparent to
559  // the value), remember the reverse association because we just added it
560  // to Cache!
561  if (Dep.isNonLocal())
562    return Dep;
563
564  // Keep the ReverseNonLocalPtrDeps map up to date so we can efficiently
565  // update MemDep when we remove instructions.
566  Instruction *Inst = Dep.getInst();
567  assert(Inst && "Didn't depend on anything?");
568  ValueIsLoadPair CacheKey(Pointer, isLoad);
569  ReverseNonLocalPtrDeps[Inst].insert(CacheKey.getOpaqueValue());
570  return Dep;
571}
572
573
574/// getNonLocalPointerDepFromBB - Perform a dependency query based on
575/// pointer/pointeesize starting at the end of StartBB.  Add any clobber/def
576/// results to the results vector and keep track of which blocks are visited in
577/// 'Visited'.
578///
579/// This has special behavior for the first block queries (when SkipFirstBlock
580/// is true).  In this special case, it ignores the contents of the specified
581/// block and starts returning dependence info for its predecessors.
582///
583/// This function returns false on success, or true to indicate that it could
584/// not compute dependence information for some reason.  This should be treated
585/// as a clobber dependence on the first instruction in the predecessor block.
586bool MemoryDependenceAnalysis::
587getNonLocalPointerDepFromBB(Value *Pointer, uint64_t PointeeSize,
588                            bool isLoad, BasicBlock *StartBB,
589                            SmallVectorImpl<NonLocalDepEntry> &Result,
590                            DenseMap<BasicBlock*, Value*> &Visited,
591                            bool SkipFirstBlock) {
592
593  // Look up the cached info for Pointer.
594  ValueIsLoadPair CacheKey(Pointer, isLoad);
595
596  std::pair<BBSkipFirstBlockPair, NonLocalDepInfo> *CacheInfo =
597    &NonLocalPointerDeps[CacheKey];
598  NonLocalDepInfo *Cache = &CacheInfo->second;
599
600  // If we have valid cached information for exactly the block we are
601  // investigating, just return it with no recomputation.
602  if (CacheInfo->first == BBSkipFirstBlockPair(StartBB, SkipFirstBlock)) {
603    for (NonLocalDepInfo::iterator I = Cache->begin(), E = Cache->end();
604         I != E; ++I)
605      if (!I->second.isNonLocal())
606        Result.push_back(*I);
607    ++NumCacheCompleteNonLocalPtr;
608    return false;
609  }
610
611  // Otherwise, either this is a new block, a block with an invalid cache
612  // pointer or one that we're about to invalidate by putting more info into it
613  // than its valid cache info.  If empty, the result will be valid cache info,
614  // otherwise it isn't.
615  if (Cache->empty())
616    CacheInfo->first = BBSkipFirstBlockPair(StartBB, SkipFirstBlock);
617  else
618    CacheInfo->first = BBSkipFirstBlockPair();
619
620  SmallVector<BasicBlock*, 32> Worklist;
621  Worklist.push_back(StartBB);
622
623  // Keep track of the entries that we know are sorted.  Previously cached
624  // entries will all be sorted.  The entries we add we only sort on demand (we
625  // don't insert every element into its sorted position).  We know that we
626  // won't get any reuse from currently inserted values, because we don't
627  // revisit blocks after we insert info for them.
628  unsigned NumSortedEntries = Cache->size();
629
630  while (!Worklist.empty()) {
631    BasicBlock *BB = Worklist.pop_back_val();
632
633    // Skip the first block if we have it.
634    if (!SkipFirstBlock) {
635      // Analyze the dependency of *Pointer in FromBB.  See if we already have
636      // been here.
637      assert(Visited.count(BB) && "Should check 'visited' before adding to WL");
638
639      // Get the dependency info for Pointer in BB.  If we have cached
640      // information, we will use it, otherwise we compute it.
641      MemDepResult Dep = GetNonLocalInfoForBlock(Pointer, PointeeSize, isLoad,
642                                                 BB, Cache, NumSortedEntries);
643
644      // If we got a Def or Clobber, add this to the list of results.
645      if (!Dep.isNonLocal()) {
646        Result.push_back(NonLocalDepEntry(BB, Dep));
647        continue;
648      }
649    }
650
651    // If 'Pointer' is an instruction defined in this block, then we need to do
652    // phi translation to change it into a value live in the predecessor block.
653    // If phi translation fails, then we can't continue dependence analysis.
654    Instruction *PtrInst = dyn_cast<Instruction>(Pointer);
655    bool NeedsPHITranslation = PtrInst && PtrInst->getParent() == BB;
656
657    // If no PHI translation is needed, just add all the predecessors of this
658    // block to scan them as well.
659    if (!NeedsPHITranslation) {
660      SkipFirstBlock = false;
661      for (BasicBlock **PI = PredCache->GetPreds(BB); *PI; ++PI) {
662        // Verify that we haven't looked at this block yet.
663        std::pair<DenseMap<BasicBlock*,Value*>::iterator, bool>
664          InsertRes = Visited.insert(std::make_pair(*PI, Pointer));
665        if (InsertRes.second) {
666          // First time we've looked at *PI.
667          Worklist.push_back(*PI);
668          continue;
669        }
670
671        // If we have seen this block before, but it was with a different
672        // pointer then we have a phi translation failure and we have to treat
673        // this as a clobber.
674        if (InsertRes.first->second != Pointer)
675          goto PredTranslationFailure;
676      }
677      continue;
678    }
679
680    // If we do need to do phi translation, then there are a bunch of different
681    // cases, because we have to find a Value* live in the predecessor block. We
682    // know that PtrInst is defined in this block at least.
683
684    // If this is directly a PHI node, just use the incoming values for each
685    // pred as the phi translated version.
686    if (PHINode *PtrPHI = dyn_cast<PHINode>(PtrInst)) {
687      for (BasicBlock **PI = PredCache->GetPreds(BB); *PI; ++PI){
688        BasicBlock *Pred = *PI;
689        Value *PredPtr = PtrPHI->getIncomingValueForBlock(Pred);
690
691        // Check to see if we have already visited this pred block with another
692        // pointer.  If so, we can't do this lookup.  This failure can occur
693        // with PHI translation when a critical edge exists and the PHI node in
694        // the successor translates to a pointer value different than the
695        // pointer the block was first analyzed with.
696        std::pair<DenseMap<BasicBlock*,Value*>::iterator, bool>
697          InsertRes = Visited.insert(std::make_pair(Pred, PredPtr));
698
699        if (!InsertRes.second) {
700          // If the predecessor was visited with PredPtr, then we already did
701          // the analysis and can ignore it.
702          if (InsertRes.first->second == PredPtr)
703            continue;
704
705          // Otherwise, the block was previously analyzed with a different
706          // pointer.  We can't represent the result of this case, so we just
707          // treat this as a phi translation failure.
708          goto PredTranslationFailure;
709        }
710
711        // If we have a problem phi translating, fall through to the code below
712        // to handle the failure condition.
713        if (getNonLocalPointerDepFromBB(PredPtr, PointeeSize, isLoad, Pred,
714                                        Result, Visited))
715          goto PredTranslationFailure;
716      }
717
718      // Refresh the CacheInfo/Cache pointer so that it isn't invalidated.
719      CacheInfo = &NonLocalPointerDeps[CacheKey];
720      Cache = &CacheInfo->second;
721
722      // Since we did phi translation, the "Cache" set won't contain all of the
723      // results for the query.  This is ok (we can still use it to accelerate
724      // specific block queries) but we can't do the fastpath "return all
725      // results from the set"  Clear out the indicator for this.
726      CacheInfo->first = BBSkipFirstBlockPair();
727      SkipFirstBlock = false;
728      continue;
729    }
730
731    // TODO: BITCAST, GEP.
732
733    //   cerr << "MEMDEP: Could not PHI translate: " << *Pointer;
734    //   if (isa<BitCastInst>(PtrInst) || isa<GetElementPtrInst>(PtrInst))
735    //     cerr << "OP:\t\t\t\t" << *PtrInst->getOperand(0);
736  PredTranslationFailure:
737
738    // Refresh the CacheInfo/Cache pointer so that it isn't invalidated.
739    CacheInfo = &NonLocalPointerDeps[CacheKey];
740    Cache = &CacheInfo->second;
741
742    // Since we did phi translation, the "Cache" set won't contain all of the
743    // results for the query.  This is ok (we can still use it to accelerate
744    // specific block queries) but we can't do the fastpath "return all
745    // results from the set"  Clear out the indicator for this.
746    CacheInfo->first = BBSkipFirstBlockPair();
747
748    // If *nothing* works, mark the pointer as being clobbered by the first
749    // instruction in this block.
750    //
751    // If this is the magic first block, return this as a clobber of the whole
752    // incoming value.  Since we can't phi translate to one of the predecessors,
753    // we have to bail out.
754    if (SkipFirstBlock)
755      return true;
756
757    for (NonLocalDepInfo::reverse_iterator I = Cache->rbegin(); ; ++I) {
758      assert(I != Cache->rend() && "Didn't find current block??");
759      if (I->first != BB)
760        continue;
761
762      assert(I->second.isNonLocal() &&
763             "Should only be here with transparent block");
764      I->second = MemDepResult::getClobber(BB->begin());
765      ReverseNonLocalPtrDeps[BB->begin()].insert(CacheKey.getOpaqueValue());
766      Result.push_back(*I);
767      break;
768    }
769  }
770
771  // Okay, we're done now.  If we added new values to the cache, re-sort it.
772  switch (Cache->size()-NumSortedEntries) {
773  case 0:
774    // done, no new entries.
775    break;
776  case 2: {
777    // Two new entries, insert the last one into place.
778    NonLocalDepEntry Val = Cache->back();
779    Cache->pop_back();
780    NonLocalDepInfo::iterator Entry =
781    std::upper_bound(Cache->begin(), Cache->end()-1, Val);
782    Cache->insert(Entry, Val);
783    // FALL THROUGH.
784  }
785  case 1:
786    // One new entry, Just insert the new value at the appropriate position.
787    if (Cache->size() != 1) {
788      NonLocalDepEntry Val = Cache->back();
789      Cache->pop_back();
790      NonLocalDepInfo::iterator Entry =
791        std::upper_bound(Cache->begin(), Cache->end(), Val);
792      Cache->insert(Entry, Val);
793    }
794    break;
795  default:
796    // Added many values, do a full scale sort.
797    std::sort(Cache->begin(), Cache->end());
798  }
799
800  return false;
801}
802
803/// RemoveCachedNonLocalPointerDependencies - If P exists in
804/// CachedNonLocalPointerInfo, remove it.
805void MemoryDependenceAnalysis::
806RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair P) {
807  CachedNonLocalPointerInfo::iterator It =
808    NonLocalPointerDeps.find(P);
809  if (It == NonLocalPointerDeps.end()) return;
810
811  // Remove all of the entries in the BB->val map.  This involves removing
812  // instructions from the reverse map.
813  NonLocalDepInfo &PInfo = It->second.second;
814
815  for (unsigned i = 0, e = PInfo.size(); i != e; ++i) {
816    Instruction *Target = PInfo[i].second.getInst();
817    if (Target == 0) continue;  // Ignore non-local dep results.
818    assert(Target->getParent() == PInfo[i].first);
819
820    // Eliminating the dirty entry from 'Cache', so update the reverse info.
821    RemoveFromReverseMap(ReverseNonLocalPtrDeps, Target, P.getOpaqueValue());
822  }
823
824  // Remove P from NonLocalPointerDeps (which deletes NonLocalDepInfo).
825  NonLocalPointerDeps.erase(It);
826}
827
828
829/// invalidateCachedPointerInfo - This method is used to invalidate cached
830/// information about the specified pointer, because it may be too
831/// conservative in memdep.  This is an optional call that can be used when
832/// the client detects an equivalence between the pointer and some other
833/// value and replaces the other value with ptr. This can make Ptr available
834/// in more places that cached info does not necessarily keep.
835void MemoryDependenceAnalysis::invalidateCachedPointerInfo(Value *Ptr) {
836  // If Ptr isn't really a pointer, just ignore it.
837  if (!isa<PointerType>(Ptr->getType())) return;
838  // Flush store info for the pointer.
839  RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(Ptr, false));
840  // Flush load info for the pointer.
841  RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(Ptr, true));
842}
843
844/// removeInstruction - Remove an instruction from the dependence analysis,
845/// updating the dependence of instructions that previously depended on it.
846/// This method attempts to keep the cache coherent using the reverse map.
847void MemoryDependenceAnalysis::removeInstruction(Instruction *RemInst) {
848  // Walk through the Non-local dependencies, removing this one as the value
849  // for any cached queries.
850  NonLocalDepMapType::iterator NLDI = NonLocalDeps.find(RemInst);
851  if (NLDI != NonLocalDeps.end()) {
852    NonLocalDepInfo &BlockMap = NLDI->second.first;
853    for (NonLocalDepInfo::iterator DI = BlockMap.begin(), DE = BlockMap.end();
854         DI != DE; ++DI)
855      if (Instruction *Inst = DI->second.getInst())
856        RemoveFromReverseMap(ReverseNonLocalDeps, Inst, RemInst);
857    NonLocalDeps.erase(NLDI);
858  }
859
860  // If we have a cached local dependence query for this instruction, remove it.
861  //
862  LocalDepMapType::iterator LocalDepEntry = LocalDeps.find(RemInst);
863  if (LocalDepEntry != LocalDeps.end()) {
864    // Remove us from DepInst's reverse set now that the local dep info is gone.
865    if (Instruction *Inst = LocalDepEntry->second.getInst())
866      RemoveFromReverseMap(ReverseLocalDeps, Inst, RemInst);
867
868    // Remove this local dependency info.
869    LocalDeps.erase(LocalDepEntry);
870  }
871
872  // If we have any cached pointer dependencies on this instruction, remove
873  // them.  If the instruction has non-pointer type, then it can't be a pointer
874  // base.
875
876  // Remove it from both the load info and the store info.  The instruction
877  // can't be in either of these maps if it is non-pointer.
878  if (isa<PointerType>(RemInst->getType())) {
879    RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(RemInst, false));
880    RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(RemInst, true));
881  }
882
883  // Loop over all of the things that depend on the instruction we're removing.
884  //
885  SmallVector<std::pair<Instruction*, Instruction*>, 8> ReverseDepsToAdd;
886
887  // If we find RemInst as a clobber or Def in any of the maps for other values,
888  // we need to replace its entry with a dirty version of the instruction after
889  // it.  If RemInst is a terminator, we use a null dirty value.
890  //
891  // Using a dirty version of the instruction after RemInst saves having to scan
892  // the entire block to get to this point.
893  MemDepResult NewDirtyVal;
894  if (!RemInst->isTerminator())
895    NewDirtyVal = MemDepResult::getDirty(++BasicBlock::iterator(RemInst));
896
897  ReverseDepMapType::iterator ReverseDepIt = ReverseLocalDeps.find(RemInst);
898  if (ReverseDepIt != ReverseLocalDeps.end()) {
899    SmallPtrSet<Instruction*, 4> &ReverseDeps = ReverseDepIt->second;
900    // RemInst can't be the terminator if it has local stuff depending on it.
901    assert(!ReverseDeps.empty() && !isa<TerminatorInst>(RemInst) &&
902           "Nothing can locally depend on a terminator");
903
904    for (SmallPtrSet<Instruction*, 4>::iterator I = ReverseDeps.begin(),
905         E = ReverseDeps.end(); I != E; ++I) {
906      Instruction *InstDependingOnRemInst = *I;
907      assert(InstDependingOnRemInst != RemInst &&
908             "Already removed our local dep info");
909
910      LocalDeps[InstDependingOnRemInst] = NewDirtyVal;
911
912      // Make sure to remember that new things depend on NewDepInst.
913      assert(NewDirtyVal.getInst() && "There is no way something else can have "
914             "a local dep on this if it is a terminator!");
915      ReverseDepsToAdd.push_back(std::make_pair(NewDirtyVal.getInst(),
916                                                InstDependingOnRemInst));
917    }
918
919    ReverseLocalDeps.erase(ReverseDepIt);
920
921    // Add new reverse deps after scanning the set, to avoid invalidating the
922    // 'ReverseDeps' reference.
923    while (!ReverseDepsToAdd.empty()) {
924      ReverseLocalDeps[ReverseDepsToAdd.back().first]
925        .insert(ReverseDepsToAdd.back().second);
926      ReverseDepsToAdd.pop_back();
927    }
928  }
929
930  ReverseDepIt = ReverseNonLocalDeps.find(RemInst);
931  if (ReverseDepIt != ReverseNonLocalDeps.end()) {
932    SmallPtrSet<Instruction*, 4> &Set = ReverseDepIt->second;
933    for (SmallPtrSet<Instruction*, 4>::iterator I = Set.begin(), E = Set.end();
934         I != E; ++I) {
935      assert(*I != RemInst && "Already removed NonLocalDep info for RemInst");
936
937      PerInstNLInfo &INLD = NonLocalDeps[*I];
938      // The information is now dirty!
939      INLD.second = true;
940
941      for (NonLocalDepInfo::iterator DI = INLD.first.begin(),
942           DE = INLD.first.end(); DI != DE; ++DI) {
943        if (DI->second.getInst() != RemInst) continue;
944
945        // Convert to a dirty entry for the subsequent instruction.
946        DI->second = NewDirtyVal;
947
948        if (Instruction *NextI = NewDirtyVal.getInst())
949          ReverseDepsToAdd.push_back(std::make_pair(NextI, *I));
950      }
951    }
952
953    ReverseNonLocalDeps.erase(ReverseDepIt);
954
955    // Add new reverse deps after scanning the set, to avoid invalidating 'Set'
956    while (!ReverseDepsToAdd.empty()) {
957      ReverseNonLocalDeps[ReverseDepsToAdd.back().first]
958        .insert(ReverseDepsToAdd.back().second);
959      ReverseDepsToAdd.pop_back();
960    }
961  }
962
963  // If the instruction is in ReverseNonLocalPtrDeps then it appears as a
964  // value in the NonLocalPointerDeps info.
965  ReverseNonLocalPtrDepTy::iterator ReversePtrDepIt =
966    ReverseNonLocalPtrDeps.find(RemInst);
967  if (ReversePtrDepIt != ReverseNonLocalPtrDeps.end()) {
968    SmallPtrSet<void*, 4> &Set = ReversePtrDepIt->second;
969    SmallVector<std::pair<Instruction*, ValueIsLoadPair>,8> ReversePtrDepsToAdd;
970
971    for (SmallPtrSet<void*, 4>::iterator I = Set.begin(), E = Set.end();
972         I != E; ++I) {
973      ValueIsLoadPair P;
974      P.setFromOpaqueValue(*I);
975      assert(P.getPointer() != RemInst &&
976             "Already removed NonLocalPointerDeps info for RemInst");
977
978      NonLocalDepInfo &NLPDI = NonLocalPointerDeps[P].second;
979
980      // The cache is not valid for any specific block anymore.
981      NonLocalPointerDeps[P].first = BBSkipFirstBlockPair();
982
983      // Update any entries for RemInst to use the instruction after it.
984      for (NonLocalDepInfo::iterator DI = NLPDI.begin(), DE = NLPDI.end();
985           DI != DE; ++DI) {
986        if (DI->second.getInst() != RemInst) continue;
987
988        // Convert to a dirty entry for the subsequent instruction.
989        DI->second = NewDirtyVal;
990
991        if (Instruction *NewDirtyInst = NewDirtyVal.getInst())
992          ReversePtrDepsToAdd.push_back(std::make_pair(NewDirtyInst, P));
993      }
994    }
995
996    ReverseNonLocalPtrDeps.erase(ReversePtrDepIt);
997
998    while (!ReversePtrDepsToAdd.empty()) {
999      ReverseNonLocalPtrDeps[ReversePtrDepsToAdd.back().first]
1000        .insert(ReversePtrDepsToAdd.back().second.getOpaqueValue());
1001      ReversePtrDepsToAdd.pop_back();
1002    }
1003  }
1004
1005
1006  assert(!NonLocalDeps.count(RemInst) && "RemInst got reinserted?");
1007  AA->deleteValue(RemInst);
1008  DEBUG(verifyRemoved(RemInst));
1009}
1010/// verifyRemoved - Verify that the specified instruction does not occur
1011/// in our internal data structures.
1012void MemoryDependenceAnalysis::verifyRemoved(Instruction *D) const {
1013  for (LocalDepMapType::const_iterator I = LocalDeps.begin(),
1014       E = LocalDeps.end(); I != E; ++I) {
1015    assert(I->first != D && "Inst occurs in data structures");
1016    assert(I->second.getInst() != D &&
1017           "Inst occurs in data structures");
1018  }
1019
1020  for (CachedNonLocalPointerInfo::const_iterator I =NonLocalPointerDeps.begin(),
1021       E = NonLocalPointerDeps.end(); I != E; ++I) {
1022    assert(I->first.getPointer() != D && "Inst occurs in NLPD map key");
1023    const NonLocalDepInfo &Val = I->second.second;
1024    for (NonLocalDepInfo::const_iterator II = Val.begin(), E = Val.end();
1025         II != E; ++II)
1026      assert(II->second.getInst() != D && "Inst occurs as NLPD value");
1027  }
1028
1029  for (NonLocalDepMapType::const_iterator I = NonLocalDeps.begin(),
1030       E = NonLocalDeps.end(); I != E; ++I) {
1031    assert(I->first != D && "Inst occurs in data structures");
1032    const PerInstNLInfo &INLD = I->second;
1033    for (NonLocalDepInfo::const_iterator II = INLD.first.begin(),
1034         EE = INLD.first.end(); II  != EE; ++II)
1035      assert(II->second.getInst() != D && "Inst occurs in data structures");
1036  }
1037
1038  for (ReverseDepMapType::const_iterator I = ReverseLocalDeps.begin(),
1039       E = ReverseLocalDeps.end(); I != E; ++I) {
1040    assert(I->first != D && "Inst occurs in data structures");
1041    for (SmallPtrSet<Instruction*, 4>::const_iterator II = I->second.begin(),
1042         EE = I->second.end(); II != EE; ++II)
1043      assert(*II != D && "Inst occurs in data structures");
1044  }
1045
1046  for (ReverseDepMapType::const_iterator I = ReverseNonLocalDeps.begin(),
1047       E = ReverseNonLocalDeps.end();
1048       I != E; ++I) {
1049    assert(I->first != D && "Inst occurs in data structures");
1050    for (SmallPtrSet<Instruction*, 4>::const_iterator II = I->second.begin(),
1051         EE = I->second.end(); II != EE; ++II)
1052      assert(*II != D && "Inst occurs in data structures");
1053  }
1054
1055  for (ReverseNonLocalPtrDepTy::const_iterator
1056       I = ReverseNonLocalPtrDeps.begin(),
1057       E = ReverseNonLocalPtrDeps.end(); I != E; ++I) {
1058    assert(I->first != D && "Inst occurs in rev NLPD map");
1059
1060    for (SmallPtrSet<void*, 4>::const_iterator II = I->second.begin(),
1061         E = I->second.end(); II != E; ++II)
1062      assert(*II != ValueIsLoadPair(D, false).getOpaqueValue() &&
1063             *II != ValueIsLoadPair(D, true).getOpaqueValue() &&
1064             "Inst occurs in ReverseNonLocalPtrDeps map");
1065  }
1066
1067}
1068