MemoryDependenceAnalysis.cpp revision bc99be10b815e0bfc5102bd5746e9a80feebf6f4
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/Support/PredIteratorCache.h"
25#include "llvm/Support/Debug.h"
26#include "llvm/Target/TargetData.h"
27using namespace llvm;
28
29STATISTIC(NumCacheNonLocal, "Number of fully cached non-local responses");
30STATISTIC(NumCacheDirtyNonLocal, "Number of dirty cached non-local responses");
31STATISTIC(NumUncacheNonLocal, "Number of uncached non-local responses");
32
33STATISTIC(NumCacheNonLocalPtr,
34          "Number of fully cached non-local ptr responses");
35STATISTIC(NumCacheDirtyNonLocalPtr,
36          "Number of cached, but dirty, non-local ptr responses");
37STATISTIC(NumUncacheNonLocalPtr,
38          "Number of uncached non-local ptr responses");
39STATISTIC(NumCacheCompleteNonLocalPtr,
40          "Number of block queries that were completely cached");
41
42char MemoryDependenceAnalysis::ID = 0;
43
44// Register this pass...
45static RegisterPass<MemoryDependenceAnalysis> X("memdep",
46                                     "Memory Dependence Analysis", false, true);
47
48MemoryDependenceAnalysis::MemoryDependenceAnalysis()
49: FunctionPass(&ID), PredCache(0) {
50}
51MemoryDependenceAnalysis::~MemoryDependenceAnalysis() {
52}
53
54/// Clean up memory in between runs
55void MemoryDependenceAnalysis::releaseMemory() {
56  LocalDeps.clear();
57  NonLocalDeps.clear();
58  NonLocalPointerDeps.clear();
59  ReverseLocalDeps.clear();
60  ReverseNonLocalDeps.clear();
61  ReverseNonLocalPtrDeps.clear();
62  PredCache->clear();
63}
64
65
66
67/// getAnalysisUsage - Does not modify anything.  It uses Alias Analysis.
68///
69void MemoryDependenceAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
70  AU.setPreservesAll();
71  AU.addRequiredTransitive<AliasAnalysis>();
72  AU.addRequiredTransitive<TargetData>();
73}
74
75bool MemoryDependenceAnalysis::runOnFunction(Function &) {
76  AA = &getAnalysis<AliasAnalysis>();
77  TD = &getAnalysis<TargetData>();
78  if (PredCache == 0)
79    PredCache.reset(new PredIteratorCache());
80  return false;
81}
82
83/// RemoveFromReverseMap - This is a helper function that removes Val from
84/// 'Inst's set in ReverseMap.  If the set becomes empty, remove Inst's entry.
85template <typename KeyTy>
86static void RemoveFromReverseMap(DenseMap<Instruction*,
87                                 SmallPtrSet<KeyTy*, 4> > &ReverseMap,
88                                 Instruction *Inst, KeyTy *Val) {
89  typename DenseMap<Instruction*, SmallPtrSet<KeyTy*, 4> >::iterator
90  InstIt = ReverseMap.find(Inst);
91  assert(InstIt != ReverseMap.end() && "Reverse map out of sync?");
92  bool Found = InstIt->second.erase(Val);
93  assert(Found && "Invalid reverse map!"); Found=Found;
94  if (InstIt->second.empty())
95    ReverseMap.erase(InstIt);
96}
97
98
99/// getCallSiteDependencyFrom - Private helper for finding the local
100/// dependencies of a call site.
101MemDepResult MemoryDependenceAnalysis::
102getCallSiteDependencyFrom(CallSite CS, bool isReadOnlyCall,
103                          BasicBlock::iterator ScanIt, BasicBlock *BB) {
104  // Walk backwards through the block, looking for dependencies
105  while (ScanIt != BB->begin()) {
106    Instruction *Inst = --ScanIt;
107
108    // If this inst is a memory op, get the pointer it accessed
109    Value *Pointer = 0;
110    uint64_t PointerSize = 0;
111    if (StoreInst *S = dyn_cast<StoreInst>(Inst)) {
112      Pointer = S->getPointerOperand();
113      PointerSize = TD->getTypeStoreSize(S->getOperand(0)->getType());
114    } else if (VAArgInst *V = dyn_cast<VAArgInst>(Inst)) {
115      Pointer = V->getOperand(0);
116      PointerSize = TD->getTypeStoreSize(V->getType());
117    } else if (FreeInst *F = dyn_cast<FreeInst>(Inst)) {
118      Pointer = F->getPointerOperand();
119
120      // FreeInsts erase the entire structure
121      PointerSize = ~0ULL;
122    } else if (isa<CallInst>(Inst) || isa<InvokeInst>(Inst)) {
123      CallSite InstCS = CallSite::get(Inst);
124      // If these two calls do not interfere, look past it.
125      switch (AA->getModRefInfo(CS, InstCS)) {
126      case AliasAnalysis::NoModRef:
127        // If the two calls don't interact (e.g. InstCS is readnone) keep
128        // scanning.
129        continue;
130      case AliasAnalysis::Ref:
131        // If the two calls read the same memory locations and CS is a readonly
132        // function, then we have two cases: 1) the calls may not interfere with
133        // each other at all.  2) the calls may produce the same value.  In case
134        // #1 we want to ignore the values, in case #2, we want to return Inst
135        // as a Def dependence.  This allows us to CSE in cases like:
136        //   X = strlen(P);
137        //    memchr(...);
138        //   Y = strlen(P);  // Y = X
139        if (isReadOnlyCall) {
140          if (CS.getCalledFunction() != 0 &&
141              CS.getCalledFunction() == InstCS.getCalledFunction())
142            return MemDepResult::getDef(Inst);
143          // Ignore unrelated read/read call dependences.
144          continue;
145        }
146        // FALL THROUGH
147      default:
148        return MemDepResult::getClobber(Inst);
149      }
150    } else {
151      // Non-memory instruction.
152      continue;
153    }
154
155    if (AA->getModRefInfo(CS, Pointer, PointerSize) != AliasAnalysis::NoModRef)
156      return MemDepResult::getClobber(Inst);
157  }
158
159  // No dependence found.  If this is the entry block of the function, it is a
160  // clobber, otherwise it is non-local.
161  if (BB != &BB->getParent()->getEntryBlock())
162    return MemDepResult::getNonLocal();
163  return MemDepResult::getClobber(ScanIt);
164}
165
166/// getPointerDependencyFrom - Return the instruction on which a memory
167/// location depends.  If isLoad is true, this routine ignore may-aliases with
168/// read-only operations.
169MemDepResult MemoryDependenceAnalysis::
170getPointerDependencyFrom(Value *MemPtr, uint64_t MemSize, bool isLoad,
171                         BasicBlock::iterator ScanIt, BasicBlock *BB) {
172
173  // Walk backwards through the basic block, looking for dependencies.
174  while (ScanIt != BB->begin()) {
175    Instruction *Inst = --ScanIt;
176
177    // Values depend on loads if the pointers are must aliased.  This means that
178    // a load depends on another must aliased load from the same value.
179    if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
180      Value *Pointer = LI->getPointerOperand();
181      uint64_t PointerSize = TD->getTypeStoreSize(LI->getType());
182
183      // If we found a pointer, check if it could be the same as our pointer.
184      AliasAnalysis::AliasResult R =
185        AA->alias(Pointer, PointerSize, MemPtr, MemSize);
186      if (R == AliasAnalysis::NoAlias)
187        continue;
188
189      // May-alias loads don't depend on each other without a dependence.
190      if (isLoad && R == AliasAnalysis::MayAlias)
191        continue;
192      // Stores depend on may and must aliased loads, loads depend on must-alias
193      // loads.
194      return MemDepResult::getDef(Inst);
195    }
196
197    if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
198      Value *Pointer = SI->getPointerOperand();
199      uint64_t PointerSize = TD->getTypeStoreSize(SI->getOperand(0)->getType());
200
201      // If we found a pointer, check if it could be the same as our pointer.
202      AliasAnalysis::AliasResult R =
203        AA->alias(Pointer, PointerSize, MemPtr, MemSize);
204
205      if (R == AliasAnalysis::NoAlias)
206        continue;
207      if (R == AliasAnalysis::MayAlias)
208        return MemDepResult::getClobber(Inst);
209      return MemDepResult::getDef(Inst);
210    }
211
212    // If this is an allocation, and if we know that the accessed pointer is to
213    // the allocation, return Def.  This means that there is no dependence and
214    // the access can be optimized based on that.  For example, a load could
215    // turn into undef.
216    if (AllocationInst *AI = dyn_cast<AllocationInst>(Inst)) {
217      Value *AccessPtr = MemPtr->getUnderlyingObject();
218
219      if (AccessPtr == AI ||
220          AA->alias(AI, 1, AccessPtr, 1) == AliasAnalysis::MustAlias)
221        return MemDepResult::getDef(AI);
222      continue;
223    }
224
225    // See if this instruction (e.g. a call or vaarg) mod/ref's the pointer.
226    switch (AA->getModRefInfo(Inst, MemPtr, MemSize)) {
227    case AliasAnalysis::NoModRef:
228      // If the call has no effect on the queried pointer, just ignore it.
229      continue;
230    case AliasAnalysis::Ref:
231      // If the call is known to never store to the pointer, and if this is a
232      // load query, we can safely ignore it (scan past it).
233      if (isLoad)
234        continue;
235      // FALL THROUGH.
236    default:
237      // Otherwise, there is a potential dependence.  Return a clobber.
238      return MemDepResult::getClobber(Inst);
239    }
240  }
241
242  // No dependence found.  If this is the entry block of the function, it is a
243  // clobber, otherwise it is non-local.
244  if (BB != &BB->getParent()->getEntryBlock())
245    return MemDepResult::getNonLocal();
246  return MemDepResult::getClobber(ScanIt);
247}
248
249/// getDependency - Return the instruction on which a memory operation
250/// depends.
251MemDepResult MemoryDependenceAnalysis::getDependency(Instruction *QueryInst) {
252  Instruction *ScanPos = QueryInst;
253
254  // Check for a cached result
255  MemDepResult &LocalCache = LocalDeps[QueryInst];
256
257  // If the cached entry is non-dirty, just return it.  Note that this depends
258  // on MemDepResult's default constructing to 'dirty'.
259  if (!LocalCache.isDirty())
260    return LocalCache;
261
262  // Otherwise, if we have a dirty entry, we know we can start the scan at that
263  // instruction, which may save us some work.
264  if (Instruction *Inst = LocalCache.getInst()) {
265    ScanPos = Inst;
266
267    RemoveFromReverseMap(ReverseLocalDeps, Inst, QueryInst);
268  }
269
270  BasicBlock *QueryParent = QueryInst->getParent();
271
272  Value *MemPtr = 0;
273  uint64_t MemSize = 0;
274
275  // Do the scan.
276  if (BasicBlock::iterator(QueryInst) == QueryParent->begin()) {
277    // No dependence found.  If this is the entry block of the function, it is a
278    // clobber, otherwise it is non-local.
279    if (QueryParent != &QueryParent->getParent()->getEntryBlock())
280      LocalCache = MemDepResult::getNonLocal();
281    else
282      LocalCache = MemDepResult::getClobber(QueryInst);
283  } else if (StoreInst *SI = dyn_cast<StoreInst>(QueryInst)) {
284    // If this is a volatile store, don't mess around with it.  Just return the
285    // previous instruction as a clobber.
286    if (SI->isVolatile())
287      LocalCache = MemDepResult::getClobber(--BasicBlock::iterator(ScanPos));
288    else {
289      MemPtr = SI->getPointerOperand();
290      MemSize = TD->getTypeStoreSize(SI->getOperand(0)->getType());
291    }
292  } else if (LoadInst *LI = dyn_cast<LoadInst>(QueryInst)) {
293    // If this is a volatile load, don't mess around with it.  Just return the
294    // previous instruction as a clobber.
295    if (LI->isVolatile())
296      LocalCache = MemDepResult::getClobber(--BasicBlock::iterator(ScanPos));
297    else {
298      MemPtr = LI->getPointerOperand();
299      MemSize = TD->getTypeStoreSize(LI->getType());
300    }
301  } else if (isa<CallInst>(QueryInst) || isa<InvokeInst>(QueryInst)) {
302    CallSite QueryCS = CallSite::get(QueryInst);
303    bool isReadOnly = AA->onlyReadsMemory(QueryCS);
304    LocalCache = getCallSiteDependencyFrom(QueryCS, isReadOnly, ScanPos,
305                                           QueryParent);
306  } else if (FreeInst *FI = dyn_cast<FreeInst>(QueryInst)) {
307    MemPtr = FI->getPointerOperand();
308    // FreeInsts erase the entire structure, not just a field.
309    MemSize = ~0UL;
310  } else {
311    // Non-memory instruction.
312    LocalCache = MemDepResult::getClobber(--BasicBlock::iterator(ScanPos));
313  }
314
315  // If we need to do a pointer scan, make it happen.
316  if (MemPtr)
317    LocalCache = getPointerDependencyFrom(MemPtr, MemSize,
318                                          isa<LoadInst>(QueryInst),
319                                          ScanPos, QueryParent);
320
321  // Remember the result!
322  if (Instruction *I = LocalCache.getInst())
323    ReverseLocalDeps[I].insert(QueryInst);
324
325  return LocalCache;
326}
327
328/// getNonLocalCallDependency - Perform a full dependency query for the
329/// specified call, returning the set of blocks that the value is
330/// potentially live across.  The returned set of results will include a
331/// "NonLocal" result for all blocks where the value is live across.
332///
333/// This method assumes the instruction returns a "NonLocal" dependency
334/// within its own block.
335///
336/// This returns a reference to an internal data structure that may be
337/// invalidated on the next non-local query or when an instruction is
338/// removed.  Clients must copy this data if they want it around longer than
339/// that.
340const MemoryDependenceAnalysis::NonLocalDepInfo &
341MemoryDependenceAnalysis::getNonLocalCallDependency(CallSite QueryCS) {
342  assert(getDependency(QueryCS.getInstruction()).isNonLocal() &&
343 "getNonLocalCallDependency should only be used on calls with non-local deps!");
344  PerInstNLInfo &CacheP = NonLocalDeps[QueryCS.getInstruction()];
345  NonLocalDepInfo &Cache = CacheP.first;
346
347  /// DirtyBlocks - This is the set of blocks that need to be recomputed.  In
348  /// the cached case, this can happen due to instructions being deleted etc. In
349  /// the uncached case, this starts out as the set of predecessors we care
350  /// about.
351  SmallVector<BasicBlock*, 32> DirtyBlocks;
352
353  if (!Cache.empty()) {
354    // Okay, we have a cache entry.  If we know it is not dirty, just return it
355    // with no computation.
356    if (!CacheP.second) {
357      NumCacheNonLocal++;
358      return Cache;
359    }
360
361    // If we already have a partially computed set of results, scan them to
362    // determine what is dirty, seeding our initial DirtyBlocks worklist.
363    for (NonLocalDepInfo::iterator I = Cache.begin(), E = Cache.end();
364       I != E; ++I)
365      if (I->second.isDirty())
366        DirtyBlocks.push_back(I->first);
367
368    // Sort the cache so that we can do fast binary search lookups below.
369    std::sort(Cache.begin(), Cache.end());
370
371    ++NumCacheDirtyNonLocal;
372    //cerr << "CACHED CASE: " << DirtyBlocks.size() << " dirty: "
373    //     << Cache.size() << " cached: " << *QueryInst;
374  } else {
375    // Seed DirtyBlocks with each of the preds of QueryInst's block.
376    BasicBlock *QueryBB = QueryCS.getInstruction()->getParent();
377    for (BasicBlock **PI = PredCache->GetPreds(QueryBB); *PI; ++PI)
378      DirtyBlocks.push_back(*PI);
379    NumUncacheNonLocal++;
380  }
381
382  // isReadonlyCall - If this is a read-only call, we can be more aggressive.
383  bool isReadonlyCall = AA->onlyReadsMemory(QueryCS);
384
385  // Visited checked first, vector in sorted order.
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() && (&*Entry)[-1].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  // While we have blocks to analyze, get their values.
490  SmallPtrSet<BasicBlock*, 64> Visited;
491  getNonLocalPointerDepFromBB(Pointer, PointeeSize, isLoad, FromBB,
492                              Result, Visited);
493}
494
495/// GetNonLocalInfoForBlock - Compute the memdep value for BB with
496/// Pointer/PointeeSize using either cached information in Cache or by doing a
497/// lookup (which may use dirty cache info if available).  If we do a lookup,
498/// add the result to the cache.
499MemDepResult MemoryDependenceAnalysis::
500GetNonLocalInfoForBlock(Value *Pointer, uint64_t PointeeSize,
501                        bool isLoad, BasicBlock *BB,
502                        NonLocalDepInfo *Cache, unsigned NumSortedEntries) {
503
504  // Do a binary search to see if we already have an entry for this block in
505  // the cache set.  If so, find it.
506  NonLocalDepInfo::iterator Entry =
507    std::upper_bound(Cache->begin(), Cache->begin()+NumSortedEntries,
508                     std::make_pair(BB, MemDepResult()));
509  if (Entry != Cache->begin() && (&*Entry)[-1].first == BB)
510    --Entry;
511
512  MemDepResult *ExistingResult = 0;
513  if (Entry != Cache->begin()+NumSortedEntries && Entry->first == BB)
514    ExistingResult = &Entry->second;
515
516  // If we have a cached entry, and it is non-dirty, use it as the value for
517  // this dependency.
518  if (ExistingResult && !ExistingResult->isDirty()) {
519    ++NumCacheNonLocalPtr;
520    return *ExistingResult;
521  }
522
523  // Otherwise, we have to scan for the value.  If we have a dirty cache
524  // entry, start scanning from its position, otherwise we scan from the end
525  // of the block.
526  BasicBlock::iterator ScanPos = BB->end();
527  if (ExistingResult && ExistingResult->getInst()) {
528    assert(ExistingResult->getInst()->getParent() == BB &&
529           "Instruction invalidated?");
530    ++NumCacheDirtyNonLocalPtr;
531    ScanPos = ExistingResult->getInst();
532
533    // Eliminating the dirty entry from 'Cache', so update the reverse info.
534    ValueIsLoadPair CacheKey(Pointer, isLoad);
535    RemoveFromReverseMap(ReverseNonLocalPtrDeps, ScanPos,
536                         CacheKey.getOpaqueValue());
537  } else {
538    ++NumUncacheNonLocalPtr;
539  }
540
541  // Scan the block for the dependency.
542  MemDepResult Dep = getPointerDependencyFrom(Pointer, PointeeSize, isLoad,
543                                              ScanPos, BB);
544
545  // If we had a dirty entry for the block, update it.  Otherwise, just add
546  // a new entry.
547  if (ExistingResult)
548    *ExistingResult = Dep;
549  else
550    Cache->push_back(std::make_pair(BB, Dep));
551
552  // If the block has a dependency (i.e. it isn't completely transparent to
553  // the value), remember the reverse association because we just added it
554  // to Cache!
555  if (Dep.isNonLocal())
556    return Dep;
557
558  // Keep the ReverseNonLocalPtrDeps map up to date so we can efficiently
559  // update MemDep when we remove instructions.
560  Instruction *Inst = Dep.getInst();
561  assert(Inst && "Didn't depend on anything?");
562  ValueIsLoadPair CacheKey(Pointer, isLoad);
563  ReverseNonLocalPtrDeps[Inst].insert(CacheKey.getOpaqueValue());
564  return Dep;
565}
566
567
568/// getNonLocalPointerDepFromBB -
569void MemoryDependenceAnalysis::
570getNonLocalPointerDepFromBB(Value *Pointer, uint64_t PointeeSize,
571                            bool isLoad, BasicBlock *StartBB,
572                            SmallVectorImpl<NonLocalDepEntry> &Result,
573                            SmallPtrSet<BasicBlock*, 64> &Visited) {
574  // Look up the cached info for Pointer.
575  ValueIsLoadPair CacheKey(Pointer, isLoad);
576
577  std::pair<BasicBlock*, NonLocalDepInfo> &CacheInfo =
578    NonLocalPointerDeps[CacheKey];
579  NonLocalDepInfo *Cache = &CacheInfo.second;
580
581  // If we have valid cached information for exactly the block we are
582  // investigating, just return it with no recomputation.
583  if (CacheInfo.first == StartBB) {
584    for (NonLocalDepInfo::iterator I = Cache->begin(), E = Cache->end();
585         I != E; ++I)
586      if (!I->second.isNonLocal())
587        Result.push_back(*I);
588    ++NumCacheCompleteNonLocalPtr;
589    return;
590  }
591
592  // Otherwise, either this is a new block, a block with an invalid cache
593  // pointer or one that we're about to invalidate by putting more info into it
594  // than its valid cache info.  If empty, the result will be valid cache info,
595  // otherwise it isn't.
596  CacheInfo.first = Cache->empty() ? StartBB : 0;
597
598  SmallVector<BasicBlock*, 32> Worklist;
599  Worklist.push_back(StartBB);
600
601  // Keep track of the entries that we know are sorted.  Previously cached
602  // entries will all be sorted.  The entries we add we only sort on demand (we
603  // don't insert every element into its sorted position).  We know that we
604  // won't get any reuse from currently inserted values, because we don't
605  // revisit blocks after we insert info for them.
606  unsigned NumSortedEntries = Cache->size();
607
608  // SkipFirstBlock - If this is the very first block that we're processing, we
609  // don't want to scan or think about its body, because the client was supposed
610  // to do a local dependence query.  Instead, just start processing it by
611  // adding its predecessors to the worklist and iterating.
612  bool SkipFirstBlock = Visited.empty();
613
614  while (!Worklist.empty()) {
615    BasicBlock *BB = Worklist.pop_back_val();
616
617    // Skip the first block if we have it.
618    if (SkipFirstBlock) {
619      SkipFirstBlock = false;
620    } else {
621      // Analyze the dependency of *Pointer in FromBB.  See if we already have
622      // been here.
623      if (!Visited.insert(BB))
624        continue;
625
626      // Get the dependency info for Pointer in BB.  If we have cached
627      // information, we will use it, otherwise we compute it.
628      MemDepResult Dep = GetNonLocalInfoForBlock(Pointer, PointeeSize, isLoad,
629                                                 BB, Cache, NumSortedEntries);
630
631      // If we got a Def or Clobber, add this to the list of results.
632      if (!Dep.isNonLocal()) {
633        Result.push_back(NonLocalDepEntry(BB, Dep));
634        continue;
635      }
636    }
637
638    // Otherwise, we have to process all the predecessors of this block to scan
639    // them as well.
640    for (BasicBlock **PI = PredCache->GetPreds(BB); *PI; ++PI) {
641      // TODO: PHI TRANSLATE.
642      Worklist.push_back(*PI);
643    }
644  }
645
646  // Okay, we're done now.  If we added new values to the cache, re-sort it.
647  switch (Cache->size()-NumSortedEntries) {
648  case 0:
649    // done, no new entries.
650    break;
651  case 2: {
652    // Two new entries, insert the last one into place.
653    NonLocalDepEntry Val = Cache->back();
654    Cache->pop_back();
655    NonLocalDepInfo::iterator Entry =
656    std::upper_bound(Cache->begin(), Cache->end()-1, Val);
657    Cache->insert(Entry, Val);
658    // FALL THROUGH.
659  }
660  case 1: {
661    // One new entry, Just insert the new value at the appropriate position.
662    NonLocalDepEntry Val = Cache->back();
663    Cache->pop_back();
664    NonLocalDepInfo::iterator Entry =
665      std::upper_bound(Cache->begin(), Cache->end(), Val);
666    Cache->insert(Entry, Val);
667    break;
668  }
669  default:
670    // Added many values, do a full scale sort.
671    std::sort(Cache->begin(), Cache->end());
672  }
673}
674
675/// RemoveCachedNonLocalPointerDependencies - If P exists in
676/// CachedNonLocalPointerInfo, remove it.
677void MemoryDependenceAnalysis::
678RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair P) {
679  CachedNonLocalPointerInfo::iterator It =
680    NonLocalPointerDeps.find(P);
681  if (It == NonLocalPointerDeps.end()) return;
682
683  // Remove all of the entries in the BB->val map.  This involves removing
684  // instructions from the reverse map.
685  NonLocalDepInfo &PInfo = It->second.second;
686
687  for (unsigned i = 0, e = PInfo.size(); i != e; ++i) {
688    Instruction *Target = PInfo[i].second.getInst();
689    if (Target == 0) continue;  // Ignore non-local dep results.
690    assert(Target->getParent() == PInfo[i].first && Target != P.getPointer());
691
692    // Eliminating the dirty entry from 'Cache', so update the reverse info.
693    RemoveFromReverseMap(ReverseNonLocalPtrDeps, Target, P.getOpaqueValue());
694  }
695
696  // Remove P from NonLocalPointerDeps (which deletes NonLocalDepInfo).
697  NonLocalPointerDeps.erase(It);
698}
699
700
701/// invalidateCachedPointerInfo - This method is used to invalidate cached
702/// information about the specified pointer, because it may be too
703/// conservative in memdep.  This is an optional call that can be used when
704/// the client detects an equivalence between the pointer and some other
705/// value and replaces the other value with ptr. This can make Ptr available
706/// in more places that cached info does not necessarily keep.
707void MemoryDependenceAnalysis::invalidateCachedPointerInfo(Value *Ptr) {
708  // If Ptr isn't really a pointer, just ignore it.
709  if (!isa<PointerType>(Ptr->getType())) return;
710  // Flush store info for the pointer.
711  RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(Ptr, false));
712  // Flush load info for the pointer.
713  RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(Ptr, true));
714}
715
716/// removeInstruction - Remove an instruction from the dependence analysis,
717/// updating the dependence of instructions that previously depended on it.
718/// This method attempts to keep the cache coherent using the reverse map.
719void MemoryDependenceAnalysis::removeInstruction(Instruction *RemInst) {
720  // Walk through the Non-local dependencies, removing this one as the value
721  // for any cached queries.
722  NonLocalDepMapType::iterator NLDI = NonLocalDeps.find(RemInst);
723  if (NLDI != NonLocalDeps.end()) {
724    NonLocalDepInfo &BlockMap = NLDI->second.first;
725    for (NonLocalDepInfo::iterator DI = BlockMap.begin(), DE = BlockMap.end();
726         DI != DE; ++DI)
727      if (Instruction *Inst = DI->second.getInst())
728        RemoveFromReverseMap(ReverseNonLocalDeps, Inst, RemInst);
729    NonLocalDeps.erase(NLDI);
730  }
731
732  // If we have a cached local dependence query for this instruction, remove it.
733  //
734  LocalDepMapType::iterator LocalDepEntry = LocalDeps.find(RemInst);
735  if (LocalDepEntry != LocalDeps.end()) {
736    // Remove us from DepInst's reverse set now that the local dep info is gone.
737    if (Instruction *Inst = LocalDepEntry->second.getInst())
738      RemoveFromReverseMap(ReverseLocalDeps, Inst, RemInst);
739
740    // Remove this local dependency info.
741    LocalDeps.erase(LocalDepEntry);
742  }
743
744  // If we have any cached pointer dependencies on this instruction, remove
745  // them.  If the instruction has non-pointer type, then it can't be a pointer
746  // base.
747
748  // Remove it from both the load info and the store info.  The instruction
749  // can't be in either of these maps if it is non-pointer.
750  if (isa<PointerType>(RemInst->getType())) {
751    RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(RemInst, false));
752    RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(RemInst, true));
753  }
754
755  // Loop over all of the things that depend on the instruction we're removing.
756  //
757  SmallVector<std::pair<Instruction*, Instruction*>, 8> ReverseDepsToAdd;
758
759  // If we find RemInst as a clobber or Def in any of the maps for other values,
760  // we need to replace its entry with a dirty version of the instruction after
761  // it.  If RemInst is a terminator, we use a null dirty value.
762  //
763  // Using a dirty version of the instruction after RemInst saves having to scan
764  // the entire block to get to this point.
765  MemDepResult NewDirtyVal;
766  if (!RemInst->isTerminator())
767    NewDirtyVal = MemDepResult::getDirty(++BasicBlock::iterator(RemInst));
768
769  ReverseDepMapType::iterator ReverseDepIt = ReverseLocalDeps.find(RemInst);
770  if (ReverseDepIt != ReverseLocalDeps.end()) {
771    SmallPtrSet<Instruction*, 4> &ReverseDeps = ReverseDepIt->second;
772    // RemInst can't be the terminator if it has local stuff depending on it.
773    assert(!ReverseDeps.empty() && !isa<TerminatorInst>(RemInst) &&
774           "Nothing can locally depend on a terminator");
775
776    for (SmallPtrSet<Instruction*, 4>::iterator I = ReverseDeps.begin(),
777         E = ReverseDeps.end(); I != E; ++I) {
778      Instruction *InstDependingOnRemInst = *I;
779      assert(InstDependingOnRemInst != RemInst &&
780             "Already removed our local dep info");
781
782      LocalDeps[InstDependingOnRemInst] = NewDirtyVal;
783
784      // Make sure to remember that new things depend on NewDepInst.
785      assert(NewDirtyVal.getInst() && "There is no way something else can have "
786             "a local dep on this if it is a terminator!");
787      ReverseDepsToAdd.push_back(std::make_pair(NewDirtyVal.getInst(),
788                                                InstDependingOnRemInst));
789    }
790
791    ReverseLocalDeps.erase(ReverseDepIt);
792
793    // Add new reverse deps after scanning the set, to avoid invalidating the
794    // 'ReverseDeps' reference.
795    while (!ReverseDepsToAdd.empty()) {
796      ReverseLocalDeps[ReverseDepsToAdd.back().first]
797        .insert(ReverseDepsToAdd.back().second);
798      ReverseDepsToAdd.pop_back();
799    }
800  }
801
802  ReverseDepIt = ReverseNonLocalDeps.find(RemInst);
803  if (ReverseDepIt != ReverseNonLocalDeps.end()) {
804    SmallPtrSet<Instruction*, 4> &Set = ReverseDepIt->second;
805    for (SmallPtrSet<Instruction*, 4>::iterator I = Set.begin(), E = Set.end();
806         I != E; ++I) {
807      assert(*I != RemInst && "Already removed NonLocalDep info for RemInst");
808
809      PerInstNLInfo &INLD = NonLocalDeps[*I];
810      // The information is now dirty!
811      INLD.second = true;
812
813      for (NonLocalDepInfo::iterator DI = INLD.first.begin(),
814           DE = INLD.first.end(); DI != DE; ++DI) {
815        if (DI->second.getInst() != RemInst) continue;
816
817        // Convert to a dirty entry for the subsequent instruction.
818        DI->second = NewDirtyVal;
819
820        if (Instruction *NextI = NewDirtyVal.getInst())
821          ReverseDepsToAdd.push_back(std::make_pair(NextI, *I));
822      }
823    }
824
825    ReverseNonLocalDeps.erase(ReverseDepIt);
826
827    // Add new reverse deps after scanning the set, to avoid invalidating 'Set'
828    while (!ReverseDepsToAdd.empty()) {
829      ReverseNonLocalDeps[ReverseDepsToAdd.back().first]
830        .insert(ReverseDepsToAdd.back().second);
831      ReverseDepsToAdd.pop_back();
832    }
833  }
834
835  // If the instruction is in ReverseNonLocalPtrDeps then it appears as a
836  // value in the NonLocalPointerDeps info.
837  ReverseNonLocalPtrDepTy::iterator ReversePtrDepIt =
838    ReverseNonLocalPtrDeps.find(RemInst);
839  if (ReversePtrDepIt != ReverseNonLocalPtrDeps.end()) {
840    SmallPtrSet<void*, 4> &Set = ReversePtrDepIt->second;
841    SmallVector<std::pair<Instruction*, ValueIsLoadPair>,8> ReversePtrDepsToAdd;
842
843    for (SmallPtrSet<void*, 4>::iterator I = Set.begin(), E = Set.end();
844         I != E; ++I) {
845      ValueIsLoadPair P;
846      P.setFromOpaqueValue(*I);
847      assert(P.getPointer() != RemInst &&
848             "Already removed NonLocalPointerDeps info for RemInst");
849
850      NonLocalDepInfo &NLPDI = NonLocalPointerDeps[P].second;
851
852      // The cache is not valid for any specific block anymore.
853      NonLocalPointerDeps[P].first = 0;
854
855      // Update any entries for RemInst to use the instruction after it.
856      for (NonLocalDepInfo::iterator DI = NLPDI.begin(), DE = NLPDI.end();
857           DI != DE; ++DI) {
858        if (DI->second.getInst() != RemInst) continue;
859
860        // Convert to a dirty entry for the subsequent instruction.
861        DI->second = NewDirtyVal;
862
863        if (Instruction *NewDirtyInst = NewDirtyVal.getInst())
864          ReversePtrDepsToAdd.push_back(std::make_pair(NewDirtyInst, P));
865      }
866    }
867
868    ReverseNonLocalPtrDeps.erase(ReversePtrDepIt);
869
870    while (!ReversePtrDepsToAdd.empty()) {
871      ReverseNonLocalPtrDeps[ReversePtrDepsToAdd.back().first]
872        .insert(ReversePtrDepsToAdd.back().second.getOpaqueValue());
873      ReversePtrDepsToAdd.pop_back();
874    }
875  }
876
877
878  assert(!NonLocalDeps.count(RemInst) && "RemInst got reinserted?");
879  AA->deleteValue(RemInst);
880  DEBUG(verifyRemoved(RemInst));
881}
882/// verifyRemoved - Verify that the specified instruction does not occur
883/// in our internal data structures.
884void MemoryDependenceAnalysis::verifyRemoved(Instruction *D) const {
885  for (LocalDepMapType::const_iterator I = LocalDeps.begin(),
886       E = LocalDeps.end(); I != E; ++I) {
887    assert(I->first != D && "Inst occurs in data structures");
888    assert(I->second.getInst() != D &&
889           "Inst occurs in data structures");
890  }
891
892  for (CachedNonLocalPointerInfo::const_iterator I =NonLocalPointerDeps.begin(),
893       E = NonLocalPointerDeps.end(); I != E; ++I) {
894    assert(I->first.getPointer() != D && "Inst occurs in NLPD map key");
895    const NonLocalDepInfo &Val = I->second.second;
896    for (NonLocalDepInfo::const_iterator II = Val.begin(), E = Val.end();
897         II != E; ++II)
898      assert(II->second.getInst() != D && "Inst occurs as NLPD value");
899  }
900
901  for (NonLocalDepMapType::const_iterator I = NonLocalDeps.begin(),
902       E = NonLocalDeps.end(); I != E; ++I) {
903    assert(I->first != D && "Inst occurs in data structures");
904    const PerInstNLInfo &INLD = I->second;
905    for (NonLocalDepInfo::const_iterator II = INLD.first.begin(),
906         EE = INLD.first.end(); II  != EE; ++II)
907      assert(II->second.getInst() != D && "Inst occurs in data structures");
908  }
909
910  for (ReverseDepMapType::const_iterator I = ReverseLocalDeps.begin(),
911       E = ReverseLocalDeps.end(); I != E; ++I) {
912    assert(I->first != D && "Inst occurs in data structures");
913    for (SmallPtrSet<Instruction*, 4>::const_iterator II = I->second.begin(),
914         EE = I->second.end(); II != EE; ++II)
915      assert(*II != D && "Inst occurs in data structures");
916  }
917
918  for (ReverseDepMapType::const_iterator I = ReverseNonLocalDeps.begin(),
919       E = ReverseNonLocalDeps.end();
920       I != E; ++I) {
921    assert(I->first != D && "Inst occurs in data structures");
922    for (SmallPtrSet<Instruction*, 4>::const_iterator II = I->second.begin(),
923         EE = I->second.end(); II != EE; ++II)
924      assert(*II != D && "Inst occurs in data structures");
925  }
926
927  for (ReverseNonLocalPtrDepTy::const_iterator
928       I = ReverseNonLocalPtrDeps.begin(),
929       E = ReverseNonLocalPtrDeps.end(); I != E; ++I) {
930    assert(I->first != D && "Inst occurs in rev NLPD map");
931
932    for (SmallPtrSet<void*, 4>::const_iterator II = I->second.begin(),
933         E = I->second.end(); II != E; ++II)
934      assert(*II != ValueIsLoadPair(D, false).getOpaqueValue() &&
935             *II != ValueIsLoadPair(D, true).getOpaqueValue() &&
936             "Inst occurs in ReverseNonLocalPtrDeps map");
937  }
938
939}
940