MemoryDependenceAnalysis.cpp revision 8a66a202f6c110273a7570b77e0b8bcb660fd92f
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/Instructions.h"
20#include "llvm/IntrinsicInst.h"
21#include "llvm/Function.h"
22#include "llvm/LLVMContext.h"
23#include "llvm/Analysis/AliasAnalysis.h"
24#include "llvm/Analysis/Dominators.h"
25#include "llvm/Analysis/InstructionSimplify.h"
26#include "llvm/Analysis/MemoryBuiltins.h"
27#include "llvm/Analysis/PHITransAddr.h"
28#include "llvm/ADT/Statistic.h"
29#include "llvm/ADT/STLExtras.h"
30#include "llvm/Support/PredIteratorCache.h"
31#include "llvm/Support/Debug.h"
32using namespace llvm;
33
34STATISTIC(NumCacheNonLocal, "Number of fully cached non-local responses");
35STATISTIC(NumCacheDirtyNonLocal, "Number of dirty cached non-local responses");
36STATISTIC(NumUncacheNonLocal, "Number of uncached non-local responses");
37
38STATISTIC(NumCacheNonLocalPtr,
39          "Number of fully cached non-local ptr responses");
40STATISTIC(NumCacheDirtyNonLocalPtr,
41          "Number of cached, but dirty, non-local ptr responses");
42STATISTIC(NumUncacheNonLocalPtr,
43          "Number of uncached non-local ptr responses");
44STATISTIC(NumCacheCompleteNonLocalPtr,
45          "Number of block queries that were completely cached");
46
47char MemoryDependenceAnalysis::ID = 0;
48
49// Register this pass...
50INITIALIZE_PASS_BEGIN(MemoryDependenceAnalysis, "memdep",
51                "Memory Dependence Analysis", false, true)
52INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
53INITIALIZE_PASS_END(MemoryDependenceAnalysis, "memdep",
54                      "Memory Dependence Analysis", false, true)
55
56MemoryDependenceAnalysis::MemoryDependenceAnalysis()
57: FunctionPass(ID), PredCache(0) {
58  initializeMemoryDependenceAnalysisPass(*PassRegistry::getPassRegistry());
59}
60MemoryDependenceAnalysis::~MemoryDependenceAnalysis() {
61}
62
63/// Clean up memory in between runs
64void MemoryDependenceAnalysis::releaseMemory() {
65  LocalDeps.clear();
66  NonLocalDeps.clear();
67  NonLocalPointerDeps.clear();
68  ReverseLocalDeps.clear();
69  ReverseNonLocalDeps.clear();
70  ReverseNonLocalPtrDeps.clear();
71  PredCache->clear();
72}
73
74
75
76/// getAnalysisUsage - Does not modify anything.  It uses Alias Analysis.
77///
78void MemoryDependenceAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
79  AU.setPreservesAll();
80  AU.addRequiredTransitive<AliasAnalysis>();
81}
82
83bool MemoryDependenceAnalysis::runOnFunction(Function &) {
84  AA = &getAnalysis<AliasAnalysis>();
85  if (PredCache == 0)
86    PredCache.reset(new PredIteratorCache());
87  return false;
88}
89
90/// RemoveFromReverseMap - This is a helper function that removes Val from
91/// 'Inst's set in ReverseMap.  If the set becomes empty, remove Inst's entry.
92template <typename KeyTy>
93static void RemoveFromReverseMap(DenseMap<Instruction*,
94                                 SmallPtrSet<KeyTy, 4> > &ReverseMap,
95                                 Instruction *Inst, KeyTy Val) {
96  typename DenseMap<Instruction*, SmallPtrSet<KeyTy, 4> >::iterator
97  InstIt = ReverseMap.find(Inst);
98  assert(InstIt != ReverseMap.end() && "Reverse map out of sync?");
99  bool Found = InstIt->second.erase(Val);
100  assert(Found && "Invalid reverse map!"); Found=Found;
101  if (InstIt->second.empty())
102    ReverseMap.erase(InstIt);
103}
104
105/// GetLocation - If the given instruction references a specific memory
106/// location, fill in Loc with the details, otherwise set Loc.Ptr to null.
107/// Return a ModRefInfo value describing the general behavior of the
108/// instruction.
109static
110AliasAnalysis::ModRefResult GetLocation(const Instruction *Inst,
111                                        AliasAnalysis::Location &Loc,
112                                        AliasAnalysis *AA) {
113  if (const LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
114    if (LI->isVolatile()) {
115      Loc = AliasAnalysis::Location();
116      return AliasAnalysis::ModRef;
117    }
118    Loc = AliasAnalysis::Location(LI->getPointerOperand(),
119                                  AA->getTypeStoreSize(LI->getType()),
120                                  LI->getMetadata(LLVMContext::MD_tbaa));
121    return AliasAnalysis::Ref;
122  }
123
124  if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
125    if (SI->isVolatile()) {
126      Loc = AliasAnalysis::Location();
127      return AliasAnalysis::ModRef;
128    }
129    Loc = AliasAnalysis::Location(SI->getPointerOperand(),
130                                  AA->getTypeStoreSize(SI->getValueOperand()
131                                                         ->getType()),
132                                  SI->getMetadata(LLVMContext::MD_tbaa));
133    return AliasAnalysis::Mod;
134  }
135
136  if (const VAArgInst *V = dyn_cast<VAArgInst>(Inst)) {
137    Loc = AliasAnalysis::Location(V->getPointerOperand(),
138                                  AA->getTypeStoreSize(V->getType()),
139                                  V->getMetadata(LLVMContext::MD_tbaa));
140    return AliasAnalysis::ModRef;
141  }
142
143  if (const CallInst *CI = isFreeCall(Inst)) {
144    // calls to free() deallocate the entire structure
145    Loc = AliasAnalysis::Location(CI->getArgOperand(0));
146    return AliasAnalysis::Mod;
147  }
148
149  if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst))
150    switch (II->getIntrinsicID()) {
151    case Intrinsic::lifetime_start:
152    case Intrinsic::lifetime_end:
153    case Intrinsic::invariant_start:
154      Loc = AliasAnalysis::Location(II->getArgOperand(1),
155                                    cast<ConstantInt>(II->getArgOperand(0))
156                                      ->getZExtValue(),
157                                    II->getMetadata(LLVMContext::MD_tbaa));
158      // These intrinsics don't really modify the memory, but returning Mod
159      // will allow them to be handled conservatively.
160      return AliasAnalysis::Mod;
161    case Intrinsic::invariant_end:
162      Loc = AliasAnalysis::Location(II->getArgOperand(2),
163                                    cast<ConstantInt>(II->getArgOperand(1))
164                                      ->getZExtValue(),
165                                    II->getMetadata(LLVMContext::MD_tbaa));
166      // These intrinsics don't really modify the memory, but returning Mod
167      // will allow them to be handled conservatively.
168      return AliasAnalysis::Mod;
169    default:
170      break;
171    }
172
173  // Otherwise, just do the coarse-grained thing that always works.
174  if (Inst->mayWriteToMemory())
175    return AliasAnalysis::ModRef;
176  if (Inst->mayReadFromMemory())
177    return AliasAnalysis::Ref;
178  return AliasAnalysis::NoModRef;
179}
180
181/// getCallSiteDependencyFrom - Private helper for finding the local
182/// dependencies of a call site.
183MemDepResult MemoryDependenceAnalysis::
184getCallSiteDependencyFrom(CallSite CS, bool isReadOnlyCall,
185                          BasicBlock::iterator ScanIt, BasicBlock *BB) {
186  // Walk backwards through the block, looking for dependencies
187  while (ScanIt != BB->begin()) {
188    Instruction *Inst = --ScanIt;
189
190    // If this inst is a memory op, get the pointer it accessed
191    AliasAnalysis::Location Loc;
192    AliasAnalysis::ModRefResult MR = GetLocation(Inst, Loc, AA);
193    if (Loc.Ptr) {
194      // A simple instruction.
195      if (AA->getModRefInfo(CS, Loc) != AliasAnalysis::NoModRef)
196        return MemDepResult::getClobber(Inst);
197      continue;
198    }
199
200    if (CallSite InstCS = cast<Value>(Inst)) {
201      // Debug intrinsics don't cause dependences.
202      if (isa<DbgInfoIntrinsic>(Inst)) continue;
203      // If these two calls do not interfere, look past it.
204      switch (AA->getModRefInfo(CS, InstCS)) {
205      case AliasAnalysis::NoModRef:
206        // If the two calls are the same, return InstCS as a Def, so that
207        // CS can be found redundant and eliminated.
208        if (isReadOnlyCall && !(MR & AliasAnalysis::Mod) &&
209            CS.getInstruction()->isIdenticalToWhenDefined(Inst))
210          return MemDepResult::getDef(Inst);
211
212        // Otherwise if the two calls don't interact (e.g. InstCS is readnone)
213        // keep scanning.
214        break;
215      default:
216        return MemDepResult::getClobber(Inst);
217      }
218    }
219  }
220
221  // No dependence found.  If this is the entry block of the function, it is a
222  // clobber, otherwise it is non-local.
223  if (BB != &BB->getParent()->getEntryBlock())
224    return MemDepResult::getNonLocal();
225  return MemDepResult::getClobber(ScanIt);
226}
227
228/// getPointerDependencyFrom - Return the instruction on which a memory
229/// location depends.  If isLoad is true, this routine ignores may-aliases with
230/// read-only operations.  If isLoad is false, this routine ignores may-aliases
231/// with reads from read-only locations.
232MemDepResult MemoryDependenceAnalysis::
233getPointerDependencyFrom(const AliasAnalysis::Location &MemLoc, bool isLoad,
234                         BasicBlock::iterator ScanIt, BasicBlock *BB) {
235
236  Value *InvariantTag = 0;
237
238  // Walk backwards through the basic block, looking for dependencies.
239  while (ScanIt != BB->begin()) {
240    Instruction *Inst = --ScanIt;
241
242    // If we're in an invariant region, no dependencies can be found before
243    // we pass an invariant-begin marker.
244    if (InvariantTag == Inst) {
245      InvariantTag = 0;
246      continue;
247    }
248
249    if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
250      // Debug intrinsics don't (and can't) cause dependences.
251      if (isa<DbgInfoIntrinsic>(II)) continue;
252
253      // If we pass an invariant-end marker, then we've just entered an
254      // invariant region and can start ignoring dependencies.
255      if (II->getIntrinsicID() == Intrinsic::invariant_end) {
256        // FIXME: This only considers queries directly on the invariant-tagged
257        // pointer, not on query pointers that are indexed off of them.  It'd
258        // be nice to handle that at some point.
259        AliasAnalysis::AliasResult R =
260          AA->alias(AliasAnalysis::Location(II->getArgOperand(2)), MemLoc);
261        if (R == AliasAnalysis::MustAlias)
262          InvariantTag = II->getArgOperand(0);
263
264        continue;
265      }
266
267      // If we reach a lifetime begin or end marker, then the query ends here
268      // because the value is undefined.
269      if (II->getIntrinsicID() == Intrinsic::lifetime_start) {
270        // FIXME: This only considers queries directly on the invariant-tagged
271        // pointer, not on query pointers that are indexed off of them.  It'd
272        // be nice to handle that at some point.
273        AliasAnalysis::AliasResult R =
274          AA->alias(AliasAnalysis::Location(II->getArgOperand(1)), MemLoc);
275        if (R == AliasAnalysis::MustAlias)
276          return MemDepResult::getDef(II);
277        continue;
278      }
279    }
280
281    // If we're querying on a load and we're in an invariant region, we're done
282    // at this point. Nothing a load depends on can live in an invariant region.
283    //
284    // FIXME: this will prevent us from returning load/load must-aliases, so GVN
285    // won't remove redundant loads.
286    if (isLoad && InvariantTag) continue;
287
288    // Values depend on loads if the pointers are must aliased.  This means that
289    // a load depends on another must aliased load from the same value.
290    if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
291      Value *Pointer = LI->getPointerOperand();
292      uint64_t PointerSize = AA->getTypeStoreSize(LI->getType());
293      MDNode *TBAATag = LI->getMetadata(LLVMContext::MD_tbaa);
294      AliasAnalysis::Location LoadLoc(Pointer, PointerSize, TBAATag);
295
296      // If we found a pointer, check if it could be the same as our pointer.
297      AliasAnalysis::AliasResult R = AA->alias(LoadLoc, MemLoc);
298      if (R == AliasAnalysis::NoAlias)
299        continue;
300
301      // May-alias loads don't depend on each other without a dependence.
302      if (isLoad && R == AliasAnalysis::MayAlias)
303        continue;
304
305      // Stores don't alias loads from read-only memory.
306      if (!isLoad && AA->pointsToConstantMemory(LoadLoc))
307        continue;
308
309      // Stores depend on may and must aliased loads, loads depend on must-alias
310      // loads.
311      return MemDepResult::getDef(Inst);
312    }
313
314    if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
315      // There can't be stores to the value we care about inside an
316      // invariant region.
317      if (InvariantTag) continue;
318
319      // If alias analysis can tell that this store is guaranteed to not modify
320      // the query pointer, ignore it.  Use getModRefInfo to handle cases where
321      // the query pointer points to constant memory etc.
322      if (AA->getModRefInfo(SI, MemLoc) == AliasAnalysis::NoModRef)
323        continue;
324
325      // Ok, this store might clobber the query pointer.  Check to see if it is
326      // a must alias: in this case, we want to return this as a def.
327      Value *Pointer = SI->getPointerOperand();
328      uint64_t PointerSize = AA->getTypeStoreSize(SI->getOperand(0)->getType());
329      MDNode *TBAATag = SI->getMetadata(LLVMContext::MD_tbaa);
330
331      // If we found a pointer, check if it could be the same as our pointer.
332      AliasAnalysis::AliasResult R =
333        AA->alias(AliasAnalysis::Location(Pointer, PointerSize, TBAATag),
334                  MemLoc);
335
336      if (R == AliasAnalysis::NoAlias)
337        continue;
338      if (R == AliasAnalysis::MayAlias)
339        return MemDepResult::getClobber(Inst);
340      return MemDepResult::getDef(Inst);
341    }
342
343    // If this is an allocation, and if we know that the accessed pointer is to
344    // the allocation, return Def.  This means that there is no dependence and
345    // the access can be optimized based on that.  For example, a load could
346    // turn into undef.
347    // Note: Only determine this to be a malloc if Inst is the malloc call, not
348    // a subsequent bitcast of the malloc call result.  There can be stores to
349    // the malloced memory between the malloc call and its bitcast uses, and we
350    // need to continue scanning until the malloc call.
351    if (isa<AllocaInst>(Inst) ||
352        (isa<CallInst>(Inst) && extractMallocCall(Inst))) {
353      const Value *AccessPtr = MemLoc.Ptr->getUnderlyingObject();
354
355      if (AccessPtr == Inst ||
356          AA->alias(Inst, 1, AccessPtr, 1) == AliasAnalysis::MustAlias)
357        return MemDepResult::getDef(Inst);
358      continue;
359    }
360
361    // See if this instruction (e.g. a call or vaarg) mod/ref's the pointer.
362    switch (AA->getModRefInfo(Inst, MemLoc)) {
363    case AliasAnalysis::NoModRef:
364      // If the call has no effect on the queried pointer, just ignore it.
365      continue;
366    case AliasAnalysis::Mod:
367      // If we're in an invariant region, we can ignore calls that ONLY
368      // modify the pointer.
369      if (InvariantTag) continue;
370      return MemDepResult::getClobber(Inst);
371    case AliasAnalysis::Ref:
372      // If the call is known to never store to the pointer, and if this is a
373      // load query, we can safely ignore it (scan past it).
374      if (isLoad)
375        continue;
376    default:
377      // Otherwise, there is a potential dependence.  Return a clobber.
378      return MemDepResult::getClobber(Inst);
379    }
380  }
381
382  // No dependence found.  If this is the entry block of the function, it is a
383  // clobber, otherwise it is non-local.
384  if (BB != &BB->getParent()->getEntryBlock())
385    return MemDepResult::getNonLocal();
386  return MemDepResult::getClobber(ScanIt);
387}
388
389/// getDependency - Return the instruction on which a memory operation
390/// depends.
391MemDepResult MemoryDependenceAnalysis::getDependency(Instruction *QueryInst) {
392  Instruction *ScanPos = QueryInst;
393
394  // Check for a cached result
395  MemDepResult &LocalCache = LocalDeps[QueryInst];
396
397  // If the cached entry is non-dirty, just return it.  Note that this depends
398  // on MemDepResult's default constructing to 'dirty'.
399  if (!LocalCache.isDirty())
400    return LocalCache;
401
402  // Otherwise, if we have a dirty entry, we know we can start the scan at that
403  // instruction, which may save us some work.
404  if (Instruction *Inst = LocalCache.getInst()) {
405    ScanPos = Inst;
406
407    RemoveFromReverseMap(ReverseLocalDeps, Inst, QueryInst);
408  }
409
410  BasicBlock *QueryParent = QueryInst->getParent();
411
412  // Do the scan.
413  if (BasicBlock::iterator(QueryInst) == QueryParent->begin()) {
414    // No dependence found.  If this is the entry block of the function, it is a
415    // clobber, otherwise it is non-local.
416    if (QueryParent != &QueryParent->getParent()->getEntryBlock())
417      LocalCache = MemDepResult::getNonLocal();
418    else
419      LocalCache = MemDepResult::getClobber(QueryInst);
420  } else {
421    AliasAnalysis::Location MemLoc;
422    AliasAnalysis::ModRefResult MR = GetLocation(QueryInst, MemLoc, AA);
423    if (MemLoc.Ptr) {
424      // If we can do a pointer scan, make it happen.
425      bool isLoad = !(MR & AliasAnalysis::Mod);
426      if (IntrinsicInst *II = dyn_cast<MemoryUseIntrinsic>(QueryInst)) {
427        isLoad |= II->getIntrinsicID() == Intrinsic::lifetime_end;
428      }
429      LocalCache = getPointerDependencyFrom(MemLoc, isLoad, ScanPos,
430                                            QueryParent);
431    } else if (isa<CallInst>(QueryInst) || isa<InvokeInst>(QueryInst)) {
432      CallSite QueryCS(QueryInst);
433      bool isReadOnly = AA->onlyReadsMemory(QueryCS);
434      LocalCache = getCallSiteDependencyFrom(QueryCS, isReadOnly, ScanPos,
435                                             QueryParent);
436    } else
437      // Non-memory instruction.
438      LocalCache = MemDepResult::getClobber(--BasicBlock::iterator(ScanPos));
439  }
440
441  // Remember the result!
442  if (Instruction *I = LocalCache.getInst())
443    ReverseLocalDeps[I].insert(QueryInst);
444
445  return LocalCache;
446}
447
448#ifndef NDEBUG
449/// AssertSorted - This method is used when -debug is specified to verify that
450/// cache arrays are properly kept sorted.
451static void AssertSorted(MemoryDependenceAnalysis::NonLocalDepInfo &Cache,
452                         int Count = -1) {
453  if (Count == -1) Count = Cache.size();
454  if (Count == 0) return;
455
456  for (unsigned i = 1; i != unsigned(Count); ++i)
457    assert(!(Cache[i] < Cache[i-1]) && "Cache isn't sorted!");
458}
459#endif
460
461/// getNonLocalCallDependency - Perform a full dependency query for the
462/// specified call, returning the set of blocks that the value is
463/// potentially live across.  The returned set of results will include a
464/// "NonLocal" result for all blocks where the value is live across.
465///
466/// This method assumes the instruction returns a "NonLocal" dependency
467/// within its own block.
468///
469/// This returns a reference to an internal data structure that may be
470/// invalidated on the next non-local query or when an instruction is
471/// removed.  Clients must copy this data if they want it around longer than
472/// that.
473const MemoryDependenceAnalysis::NonLocalDepInfo &
474MemoryDependenceAnalysis::getNonLocalCallDependency(CallSite QueryCS) {
475  assert(getDependency(QueryCS.getInstruction()).isNonLocal() &&
476 "getNonLocalCallDependency should only be used on calls with non-local deps!");
477  PerInstNLInfo &CacheP = NonLocalDeps[QueryCS.getInstruction()];
478  NonLocalDepInfo &Cache = CacheP.first;
479
480  /// DirtyBlocks - This is the set of blocks that need to be recomputed.  In
481  /// the cached case, this can happen due to instructions being deleted etc. In
482  /// the uncached case, this starts out as the set of predecessors we care
483  /// about.
484  SmallVector<BasicBlock*, 32> DirtyBlocks;
485
486  if (!Cache.empty()) {
487    // Okay, we have a cache entry.  If we know it is not dirty, just return it
488    // with no computation.
489    if (!CacheP.second) {
490      ++NumCacheNonLocal;
491      return Cache;
492    }
493
494    // If we already have a partially computed set of results, scan them to
495    // determine what is dirty, seeding our initial DirtyBlocks worklist.
496    for (NonLocalDepInfo::iterator I = Cache.begin(), E = Cache.end();
497       I != E; ++I)
498      if (I->getResult().isDirty())
499        DirtyBlocks.push_back(I->getBB());
500
501    // Sort the cache so that we can do fast binary search lookups below.
502    std::sort(Cache.begin(), Cache.end());
503
504    ++NumCacheDirtyNonLocal;
505    //cerr << "CACHED CASE: " << DirtyBlocks.size() << " dirty: "
506    //     << Cache.size() << " cached: " << *QueryInst;
507  } else {
508    // Seed DirtyBlocks with each of the preds of QueryInst's block.
509    BasicBlock *QueryBB = QueryCS.getInstruction()->getParent();
510    for (BasicBlock **PI = PredCache->GetPreds(QueryBB); *PI; ++PI)
511      DirtyBlocks.push_back(*PI);
512    ++NumUncacheNonLocal;
513  }
514
515  // isReadonlyCall - If this is a read-only call, we can be more aggressive.
516  bool isReadonlyCall = AA->onlyReadsMemory(QueryCS);
517
518  SmallPtrSet<BasicBlock*, 64> Visited;
519
520  unsigned NumSortedEntries = Cache.size();
521  DEBUG(AssertSorted(Cache));
522
523  // Iterate while we still have blocks to update.
524  while (!DirtyBlocks.empty()) {
525    BasicBlock *DirtyBB = DirtyBlocks.back();
526    DirtyBlocks.pop_back();
527
528    // Already processed this block?
529    if (!Visited.insert(DirtyBB))
530      continue;
531
532    // Do a binary search to see if we already have an entry for this block in
533    // the cache set.  If so, find it.
534    DEBUG(AssertSorted(Cache, NumSortedEntries));
535    NonLocalDepInfo::iterator Entry =
536      std::upper_bound(Cache.begin(), Cache.begin()+NumSortedEntries,
537                       NonLocalDepEntry(DirtyBB));
538    if (Entry != Cache.begin() && prior(Entry)->getBB() == DirtyBB)
539      --Entry;
540
541    NonLocalDepEntry *ExistingResult = 0;
542    if (Entry != Cache.begin()+NumSortedEntries &&
543        Entry->getBB() == DirtyBB) {
544      // If we already have an entry, and if it isn't already dirty, the block
545      // is done.
546      if (!Entry->getResult().isDirty())
547        continue;
548
549      // Otherwise, remember this slot so we can update the value.
550      ExistingResult = &*Entry;
551    }
552
553    // If the dirty entry has a pointer, start scanning from it so we don't have
554    // to rescan the entire block.
555    BasicBlock::iterator ScanPos = DirtyBB->end();
556    if (ExistingResult) {
557      if (Instruction *Inst = ExistingResult->getResult().getInst()) {
558        ScanPos = Inst;
559        // We're removing QueryInst's use of Inst.
560        RemoveFromReverseMap(ReverseNonLocalDeps, Inst,
561                             QueryCS.getInstruction());
562      }
563    }
564
565    // Find out if this block has a local dependency for QueryInst.
566    MemDepResult Dep;
567
568    if (ScanPos != DirtyBB->begin()) {
569      Dep = getCallSiteDependencyFrom(QueryCS, isReadonlyCall,ScanPos, DirtyBB);
570    } else if (DirtyBB != &DirtyBB->getParent()->getEntryBlock()) {
571      // No dependence found.  If this is the entry block of the function, it is
572      // a clobber, otherwise it is non-local.
573      Dep = MemDepResult::getNonLocal();
574    } else {
575      Dep = MemDepResult::getClobber(ScanPos);
576    }
577
578    // If we had a dirty entry for the block, update it.  Otherwise, just add
579    // a new entry.
580    if (ExistingResult)
581      ExistingResult->setResult(Dep);
582    else
583      Cache.push_back(NonLocalDepEntry(DirtyBB, Dep));
584
585    // If the block has a dependency (i.e. it isn't completely transparent to
586    // the value), remember the association!
587    if (!Dep.isNonLocal()) {
588      // Keep the ReverseNonLocalDeps map up to date so we can efficiently
589      // update this when we remove instructions.
590      if (Instruction *Inst = Dep.getInst())
591        ReverseNonLocalDeps[Inst].insert(QueryCS.getInstruction());
592    } else {
593
594      // If the block *is* completely transparent to the load, we need to check
595      // the predecessors of this block.  Add them to our worklist.
596      for (BasicBlock **PI = PredCache->GetPreds(DirtyBB); *PI; ++PI)
597        DirtyBlocks.push_back(*PI);
598    }
599  }
600
601  return Cache;
602}
603
604/// getNonLocalPointerDependency - Perform a full dependency query for an
605/// access to the specified (non-volatile) memory location, returning the
606/// set of instructions that either define or clobber the value.
607///
608/// This method assumes the pointer has a "NonLocal" dependency within its
609/// own block.
610///
611void MemoryDependenceAnalysis::
612getNonLocalPointerDependency(const AliasAnalysis::Location &Loc, bool isLoad,
613                             BasicBlock *FromBB,
614                             SmallVectorImpl<NonLocalDepResult> &Result) {
615  assert(Loc.Ptr->getType()->isPointerTy() &&
616         "Can't get pointer deps of a non-pointer!");
617  Result.clear();
618
619  PHITransAddr Address(const_cast<Value *>(Loc.Ptr), TD);
620
621  // This is the set of blocks we've inspected, and the pointer we consider in
622  // each block.  Because of critical edges, we currently bail out if querying
623  // a block with multiple different pointers.  This can happen during PHI
624  // translation.
625  DenseMap<BasicBlock*, Value*> Visited;
626  if (!getNonLocalPointerDepFromBB(Address, Loc, isLoad, FromBB,
627                                   Result, Visited, true))
628    return;
629  Result.clear();
630  Result.push_back(NonLocalDepResult(FromBB,
631                                     MemDepResult::getClobber(FromBB->begin()),
632                                     const_cast<Value *>(Loc.Ptr)));
633}
634
635/// GetNonLocalInfoForBlock - Compute the memdep value for BB with
636/// Pointer/PointeeSize using either cached information in Cache or by doing a
637/// lookup (which may use dirty cache info if available).  If we do a lookup,
638/// add the result to the cache.
639MemDepResult MemoryDependenceAnalysis::
640GetNonLocalInfoForBlock(const AliasAnalysis::Location &Loc,
641                        bool isLoad, BasicBlock *BB,
642                        NonLocalDepInfo *Cache, unsigned NumSortedEntries) {
643
644  // Do a binary search to see if we already have an entry for this block in
645  // the cache set.  If so, find it.
646  NonLocalDepInfo::iterator Entry =
647    std::upper_bound(Cache->begin(), Cache->begin()+NumSortedEntries,
648                     NonLocalDepEntry(BB));
649  if (Entry != Cache->begin() && (Entry-1)->getBB() == BB)
650    --Entry;
651
652  NonLocalDepEntry *ExistingResult = 0;
653  if (Entry != Cache->begin()+NumSortedEntries && Entry->getBB() == BB)
654    ExistingResult = &*Entry;
655
656  // If we have a cached entry, and it is non-dirty, use it as the value for
657  // this dependency.
658  if (ExistingResult && !ExistingResult->getResult().isDirty()) {
659    ++NumCacheNonLocalPtr;
660    return ExistingResult->getResult();
661  }
662
663  // Otherwise, we have to scan for the value.  If we have a dirty cache
664  // entry, start scanning from its position, otherwise we scan from the end
665  // of the block.
666  BasicBlock::iterator ScanPos = BB->end();
667  if (ExistingResult && ExistingResult->getResult().getInst()) {
668    assert(ExistingResult->getResult().getInst()->getParent() == BB &&
669           "Instruction invalidated?");
670    ++NumCacheDirtyNonLocalPtr;
671    ScanPos = ExistingResult->getResult().getInst();
672
673    // Eliminating the dirty entry from 'Cache', so update the reverse info.
674    ValueIsLoadPair CacheKey(Loc.Ptr, isLoad);
675    RemoveFromReverseMap(ReverseNonLocalPtrDeps, ScanPos, CacheKey);
676  } else {
677    ++NumUncacheNonLocalPtr;
678  }
679
680  // Scan the block for the dependency.
681  MemDepResult Dep = getPointerDependencyFrom(Loc, isLoad, ScanPos, BB);
682
683  // If we had a dirty entry for the block, update it.  Otherwise, just add
684  // a new entry.
685  if (ExistingResult)
686    ExistingResult->setResult(Dep);
687  else
688    Cache->push_back(NonLocalDepEntry(BB, Dep));
689
690  // If the block has a dependency (i.e. it isn't completely transparent to
691  // the value), remember the reverse association because we just added it
692  // to Cache!
693  if (Dep.isNonLocal())
694    return Dep;
695
696  // Keep the ReverseNonLocalPtrDeps map up to date so we can efficiently
697  // update MemDep when we remove instructions.
698  Instruction *Inst = Dep.getInst();
699  assert(Inst && "Didn't depend on anything?");
700  ValueIsLoadPair CacheKey(Loc.Ptr, isLoad);
701  ReverseNonLocalPtrDeps[Inst].insert(CacheKey);
702  return Dep;
703}
704
705/// SortNonLocalDepInfoCache - Sort the a NonLocalDepInfo cache, given a certain
706/// number of elements in the array that are already properly ordered.  This is
707/// optimized for the case when only a few entries are added.
708static void
709SortNonLocalDepInfoCache(MemoryDependenceAnalysis::NonLocalDepInfo &Cache,
710                         unsigned NumSortedEntries) {
711  switch (Cache.size() - NumSortedEntries) {
712  case 0:
713    // done, no new entries.
714    break;
715  case 2: {
716    // Two new entries, insert the last one into place.
717    NonLocalDepEntry Val = Cache.back();
718    Cache.pop_back();
719    MemoryDependenceAnalysis::NonLocalDepInfo::iterator Entry =
720      std::upper_bound(Cache.begin(), Cache.end()-1, Val);
721    Cache.insert(Entry, Val);
722    // FALL THROUGH.
723  }
724  case 1:
725    // One new entry, Just insert the new value at the appropriate position.
726    if (Cache.size() != 1) {
727      NonLocalDepEntry Val = Cache.back();
728      Cache.pop_back();
729      MemoryDependenceAnalysis::NonLocalDepInfo::iterator Entry =
730        std::upper_bound(Cache.begin(), Cache.end(), Val);
731      Cache.insert(Entry, Val);
732    }
733    break;
734  default:
735    // Added many values, do a full scale sort.
736    std::sort(Cache.begin(), Cache.end());
737    break;
738  }
739}
740
741/// getNonLocalPointerDepFromBB - Perform a dependency query based on
742/// pointer/pointeesize starting at the end of StartBB.  Add any clobber/def
743/// results to the results vector and keep track of which blocks are visited in
744/// 'Visited'.
745///
746/// This has special behavior for the first block queries (when SkipFirstBlock
747/// is true).  In this special case, it ignores the contents of the specified
748/// block and starts returning dependence info for its predecessors.
749///
750/// This function returns false on success, or true to indicate that it could
751/// not compute dependence information for some reason.  This should be treated
752/// as a clobber dependence on the first instruction in the predecessor block.
753bool MemoryDependenceAnalysis::
754getNonLocalPointerDepFromBB(const PHITransAddr &Pointer,
755                            const AliasAnalysis::Location &Loc,
756                            bool isLoad, BasicBlock *StartBB,
757                            SmallVectorImpl<NonLocalDepResult> &Result,
758                            DenseMap<BasicBlock*, Value*> &Visited,
759                            bool SkipFirstBlock) {
760
761  // Look up the cached info for Pointer.
762  ValueIsLoadPair CacheKey(Pointer.getAddr(), isLoad);
763
764  // Set up a temporary NLPI value. If the map doesn't yet have an entry for
765  // CacheKey, this value will be inserted as the associated value. Otherwise,
766  // it'll be ignored, and we'll have to check to see if the cached size and
767  // tbaa tag are consistent with the current query.
768  NonLocalPointerInfo InitialNLPI;
769  InitialNLPI.Size = Loc.Size;
770  InitialNLPI.TBAATag = Loc.TBAATag;
771
772  // Get the NLPI for CacheKey, inserting one into the map if it doesn't
773  // already have one.
774  std::pair<CachedNonLocalPointerInfo::iterator, bool> Pair =
775    NonLocalPointerDeps.insert(std::make_pair(CacheKey, InitialNLPI));
776  NonLocalPointerInfo *CacheInfo = &Pair.first->second;
777
778  // If we already have a cache entry for this CacheKey, we may need to do some
779  // work to reconcile the cache entry and the current query.
780  if (!Pair.second) {
781    if (CacheInfo->Size < Loc.Size) {
782      // The query's Size is greater than the cached one. Throw out the
783      // cached data and procede with the query at the greater size.
784      CacheInfo->Pair = BBSkipFirstBlockPair();
785      CacheInfo->Size = Loc.Size;
786      for (NonLocalDepInfo::iterator DI = CacheInfo->NonLocalDeps.begin(),
787           DE = CacheInfo->NonLocalDeps.end(); DI != DE; ++DI)
788        if (Instruction *Inst = DI->getResult().getInst())
789          RemoveFromReverseMap(ReverseNonLocalPtrDeps, Inst, CacheKey);
790      CacheInfo->NonLocalDeps.clear();
791    } else if (CacheInfo->Size > Loc.Size) {
792      // This query's Size is less than the cached one. Conservatively restart
793      // the query using the greater size.
794      return getNonLocalPointerDepFromBB(Pointer,
795                                         Loc.getWithNewSize(CacheInfo->Size),
796                                         isLoad, StartBB, Result, Visited,
797                                         SkipFirstBlock);
798    }
799
800    // If the query's TBAATag is inconsistent with the cached one,
801    // conservatively throw out the cached data and restart the query with
802    // no tag if needed.
803    if (CacheInfo->TBAATag != Loc.TBAATag) {
804      if (CacheInfo->TBAATag) {
805        CacheInfo->Pair = BBSkipFirstBlockPair();
806        CacheInfo->TBAATag = 0;
807        for (NonLocalDepInfo::iterator DI = CacheInfo->NonLocalDeps.begin(),
808             DE = CacheInfo->NonLocalDeps.end(); DI != DE; ++DI)
809          if (Instruction *Inst = DI->getResult().getInst())
810            RemoveFromReverseMap(ReverseNonLocalPtrDeps, Inst, CacheKey);
811        CacheInfo->NonLocalDeps.clear();
812      }
813      if (Loc.TBAATag)
814        return getNonLocalPointerDepFromBB(Pointer, Loc.getWithoutTBAATag(),
815                                           isLoad, StartBB, Result, Visited,
816                                           SkipFirstBlock);
817    }
818  }
819
820  NonLocalDepInfo *Cache = &CacheInfo->NonLocalDeps;
821
822  // If we have valid cached information for exactly the block we are
823  // investigating, just return it with no recomputation.
824  if (CacheInfo->Pair == BBSkipFirstBlockPair(StartBB, SkipFirstBlock)) {
825    // We have a fully cached result for this query then we can just return the
826    // cached results and populate the visited set.  However, we have to verify
827    // that we don't already have conflicting results for these blocks.  Check
828    // to ensure that if a block in the results set is in the visited set that
829    // it was for the same pointer query.
830    if (!Visited.empty()) {
831      for (NonLocalDepInfo::iterator I = Cache->begin(), E = Cache->end();
832           I != E; ++I) {
833        DenseMap<BasicBlock*, Value*>::iterator VI = Visited.find(I->getBB());
834        if (VI == Visited.end() || VI->second == Pointer.getAddr())
835          continue;
836
837        // We have a pointer mismatch in a block.  Just return clobber, saying
838        // that something was clobbered in this result.  We could also do a
839        // non-fully cached query, but there is little point in doing this.
840        return true;
841      }
842    }
843
844    Value *Addr = Pointer.getAddr();
845    for (NonLocalDepInfo::iterator I = Cache->begin(), E = Cache->end();
846         I != E; ++I) {
847      Visited.insert(std::make_pair(I->getBB(), Addr));
848      if (!I->getResult().isNonLocal())
849        Result.push_back(NonLocalDepResult(I->getBB(), I->getResult(), Addr));
850    }
851    ++NumCacheCompleteNonLocalPtr;
852    return false;
853  }
854
855  // Otherwise, either this is a new block, a block with an invalid cache
856  // pointer or one that we're about to invalidate by putting more info into it
857  // than its valid cache info.  If empty, the result will be valid cache info,
858  // otherwise it isn't.
859  if (Cache->empty())
860    CacheInfo->Pair = BBSkipFirstBlockPair(StartBB, SkipFirstBlock);
861  else
862    CacheInfo->Pair = BBSkipFirstBlockPair();
863
864  SmallVector<BasicBlock*, 32> Worklist;
865  Worklist.push_back(StartBB);
866
867  // Keep track of the entries that we know are sorted.  Previously cached
868  // entries will all be sorted.  The entries we add we only sort on demand (we
869  // don't insert every element into its sorted position).  We know that we
870  // won't get any reuse from currently inserted values, because we don't
871  // revisit blocks after we insert info for them.
872  unsigned NumSortedEntries = Cache->size();
873  DEBUG(AssertSorted(*Cache));
874
875  while (!Worklist.empty()) {
876    BasicBlock *BB = Worklist.pop_back_val();
877
878    // Skip the first block if we have it.
879    if (!SkipFirstBlock) {
880      // Analyze the dependency of *Pointer in FromBB.  See if we already have
881      // been here.
882      assert(Visited.count(BB) && "Should check 'visited' before adding to WL");
883
884      // Get the dependency info for Pointer in BB.  If we have cached
885      // information, we will use it, otherwise we compute it.
886      DEBUG(AssertSorted(*Cache, NumSortedEntries));
887      MemDepResult Dep = GetNonLocalInfoForBlock(Loc, isLoad, BB, Cache,
888                                                 NumSortedEntries);
889
890      // If we got a Def or Clobber, add this to the list of results.
891      if (!Dep.isNonLocal()) {
892        Result.push_back(NonLocalDepResult(BB, Dep, Pointer.getAddr()));
893        continue;
894      }
895    }
896
897    // If 'Pointer' is an instruction defined in this block, then we need to do
898    // phi translation to change it into a value live in the predecessor block.
899    // If not, we just add the predecessors to the worklist and scan them with
900    // the same Pointer.
901    if (!Pointer.NeedsPHITranslationFromBlock(BB)) {
902      SkipFirstBlock = false;
903      for (BasicBlock **PI = PredCache->GetPreds(BB); *PI; ++PI) {
904        // Verify that we haven't looked at this block yet.
905        std::pair<DenseMap<BasicBlock*,Value*>::iterator, bool>
906          InsertRes = Visited.insert(std::make_pair(*PI, Pointer.getAddr()));
907        if (InsertRes.second) {
908          // First time we've looked at *PI.
909          Worklist.push_back(*PI);
910          continue;
911        }
912
913        // If we have seen this block before, but it was with a different
914        // pointer then we have a phi translation failure and we have to treat
915        // this as a clobber.
916        if (InsertRes.first->second != Pointer.getAddr())
917          goto PredTranslationFailure;
918      }
919      continue;
920    }
921
922    // We do need to do phi translation, if we know ahead of time we can't phi
923    // translate this value, don't even try.
924    if (!Pointer.IsPotentiallyPHITranslatable())
925      goto PredTranslationFailure;
926
927    // We may have added values to the cache list before this PHI translation.
928    // If so, we haven't done anything to ensure that the cache remains sorted.
929    // Sort it now (if needed) so that recursive invocations of
930    // getNonLocalPointerDepFromBB and other routines that could reuse the cache
931    // value will only see properly sorted cache arrays.
932    if (Cache && NumSortedEntries != Cache->size()) {
933      SortNonLocalDepInfoCache(*Cache, NumSortedEntries);
934      NumSortedEntries = Cache->size();
935    }
936    Cache = 0;
937
938    for (BasicBlock **PI = PredCache->GetPreds(BB); *PI; ++PI) {
939      BasicBlock *Pred = *PI;
940
941      // Get the PHI translated pointer in this predecessor.  This can fail if
942      // not translatable, in which case the getAddr() returns null.
943      PHITransAddr PredPointer(Pointer);
944      PredPointer.PHITranslateValue(BB, Pred, 0);
945
946      Value *PredPtrVal = PredPointer.getAddr();
947
948      // Check to see if we have already visited this pred block with another
949      // pointer.  If so, we can't do this lookup.  This failure can occur
950      // with PHI translation when a critical edge exists and the PHI node in
951      // the successor translates to a pointer value different than the
952      // pointer the block was first analyzed with.
953      std::pair<DenseMap<BasicBlock*,Value*>::iterator, bool>
954        InsertRes = Visited.insert(std::make_pair(Pred, PredPtrVal));
955
956      if (!InsertRes.second) {
957        // If the predecessor was visited with PredPtr, then we already did
958        // the analysis and can ignore it.
959        if (InsertRes.first->second == PredPtrVal)
960          continue;
961
962        // Otherwise, the block was previously analyzed with a different
963        // pointer.  We can't represent the result of this case, so we just
964        // treat this as a phi translation failure.
965        goto PredTranslationFailure;
966      }
967
968      // If PHI translation was unable to find an available pointer in this
969      // predecessor, then we have to assume that the pointer is clobbered in
970      // that predecessor.  We can still do PRE of the load, which would insert
971      // a computation of the pointer in this predecessor.
972      if (PredPtrVal == 0) {
973        // Add the entry to the Result list.
974        NonLocalDepResult Entry(Pred,
975                                MemDepResult::getClobber(Pred->getTerminator()),
976                                PredPtrVal);
977        Result.push_back(Entry);
978
979        // Since we had a phi translation failure, the cache for CacheKey won't
980        // include all of the entries that we need to immediately satisfy future
981        // queries.  Mark this in NonLocalPointerDeps by setting the
982        // BBSkipFirstBlockPair pointer to null.  This requires reuse of the
983        // cached value to do more work but not miss the phi trans failure.
984        NonLocalPointerInfo &NLPI = NonLocalPointerDeps[CacheKey];
985        NLPI.Pair = BBSkipFirstBlockPair();
986        continue;
987      }
988
989      // FIXME: it is entirely possible that PHI translating will end up with
990      // the same value.  Consider PHI translating something like:
991      // X = phi [x, bb1], [y, bb2].  PHI translating for bb1 doesn't *need*
992      // to recurse here, pedantically speaking.
993
994      // If we have a problem phi translating, fall through to the code below
995      // to handle the failure condition.
996      if (getNonLocalPointerDepFromBB(PredPointer,
997                                      Loc.getWithNewPtr(PredPointer.getAddr()),
998                                      isLoad, Pred,
999                                      Result, Visited))
1000        goto PredTranslationFailure;
1001    }
1002
1003    // Refresh the CacheInfo/Cache pointer so that it isn't invalidated.
1004    CacheInfo = &NonLocalPointerDeps[CacheKey];
1005    Cache = &CacheInfo->NonLocalDeps;
1006    NumSortedEntries = Cache->size();
1007
1008    // Since we did phi translation, the "Cache" set won't contain all of the
1009    // results for the query.  This is ok (we can still use it to accelerate
1010    // specific block queries) but we can't do the fastpath "return all
1011    // results from the set"  Clear out the indicator for this.
1012    CacheInfo->Pair = BBSkipFirstBlockPair();
1013    SkipFirstBlock = false;
1014    continue;
1015
1016  PredTranslationFailure:
1017
1018    if (Cache == 0) {
1019      // Refresh the CacheInfo/Cache pointer if it got invalidated.
1020      CacheInfo = &NonLocalPointerDeps[CacheKey];
1021      Cache = &CacheInfo->NonLocalDeps;
1022      NumSortedEntries = Cache->size();
1023    }
1024
1025    // Since we failed phi translation, the "Cache" set won't contain all of the
1026    // results for the query.  This is ok (we can still use it to accelerate
1027    // specific block queries) but we can't do the fastpath "return all
1028    // results from the set".  Clear out the indicator for this.
1029    CacheInfo->Pair = BBSkipFirstBlockPair();
1030
1031    // If *nothing* works, mark the pointer as being clobbered by the first
1032    // instruction in this block.
1033    //
1034    // If this is the magic first block, return this as a clobber of the whole
1035    // incoming value.  Since we can't phi translate to one of the predecessors,
1036    // we have to bail out.
1037    if (SkipFirstBlock)
1038      return true;
1039
1040    for (NonLocalDepInfo::reverse_iterator I = Cache->rbegin(); ; ++I) {
1041      assert(I != Cache->rend() && "Didn't find current block??");
1042      if (I->getBB() != BB)
1043        continue;
1044
1045      assert(I->getResult().isNonLocal() &&
1046             "Should only be here with transparent block");
1047      I->setResult(MemDepResult::getClobber(BB->begin()));
1048      ReverseNonLocalPtrDeps[BB->begin()].insert(CacheKey);
1049      Result.push_back(NonLocalDepResult(I->getBB(), I->getResult(),
1050                                         Pointer.getAddr()));
1051      break;
1052    }
1053  }
1054
1055  // Okay, we're done now.  If we added new values to the cache, re-sort it.
1056  SortNonLocalDepInfoCache(*Cache, NumSortedEntries);
1057  DEBUG(AssertSorted(*Cache));
1058  return false;
1059}
1060
1061/// RemoveCachedNonLocalPointerDependencies - If P exists in
1062/// CachedNonLocalPointerInfo, remove it.
1063void MemoryDependenceAnalysis::
1064RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair P) {
1065  CachedNonLocalPointerInfo::iterator It =
1066    NonLocalPointerDeps.find(P);
1067  if (It == NonLocalPointerDeps.end()) return;
1068
1069  // Remove all of the entries in the BB->val map.  This involves removing
1070  // instructions from the reverse map.
1071  NonLocalDepInfo &PInfo = It->second.NonLocalDeps;
1072
1073  for (unsigned i = 0, e = PInfo.size(); i != e; ++i) {
1074    Instruction *Target = PInfo[i].getResult().getInst();
1075    if (Target == 0) continue;  // Ignore non-local dep results.
1076    assert(Target->getParent() == PInfo[i].getBB());
1077
1078    // Eliminating the dirty entry from 'Cache', so update the reverse info.
1079    RemoveFromReverseMap(ReverseNonLocalPtrDeps, Target, P);
1080  }
1081
1082  // Remove P from NonLocalPointerDeps (which deletes NonLocalDepInfo).
1083  NonLocalPointerDeps.erase(It);
1084}
1085
1086
1087/// invalidateCachedPointerInfo - This method is used to invalidate cached
1088/// information about the specified pointer, because it may be too
1089/// conservative in memdep.  This is an optional call that can be used when
1090/// the client detects an equivalence between the pointer and some other
1091/// value and replaces the other value with ptr. This can make Ptr available
1092/// in more places that cached info does not necessarily keep.
1093void MemoryDependenceAnalysis::invalidateCachedPointerInfo(Value *Ptr) {
1094  // If Ptr isn't really a pointer, just ignore it.
1095  if (!Ptr->getType()->isPointerTy()) return;
1096  // Flush store info for the pointer.
1097  RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(Ptr, false));
1098  // Flush load info for the pointer.
1099  RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(Ptr, true));
1100}
1101
1102/// invalidateCachedPredecessors - Clear the PredIteratorCache info.
1103/// This needs to be done when the CFG changes, e.g., due to splitting
1104/// critical edges.
1105void MemoryDependenceAnalysis::invalidateCachedPredecessors() {
1106  PredCache->clear();
1107}
1108
1109/// removeInstruction - Remove an instruction from the dependence analysis,
1110/// updating the dependence of instructions that previously depended on it.
1111/// This method attempts to keep the cache coherent using the reverse map.
1112void MemoryDependenceAnalysis::removeInstruction(Instruction *RemInst) {
1113  // Walk through the Non-local dependencies, removing this one as the value
1114  // for any cached queries.
1115  NonLocalDepMapType::iterator NLDI = NonLocalDeps.find(RemInst);
1116  if (NLDI != NonLocalDeps.end()) {
1117    NonLocalDepInfo &BlockMap = NLDI->second.first;
1118    for (NonLocalDepInfo::iterator DI = BlockMap.begin(), DE = BlockMap.end();
1119         DI != DE; ++DI)
1120      if (Instruction *Inst = DI->getResult().getInst())
1121        RemoveFromReverseMap(ReverseNonLocalDeps, Inst, RemInst);
1122    NonLocalDeps.erase(NLDI);
1123  }
1124
1125  // If we have a cached local dependence query for this instruction, remove it.
1126  //
1127  LocalDepMapType::iterator LocalDepEntry = LocalDeps.find(RemInst);
1128  if (LocalDepEntry != LocalDeps.end()) {
1129    // Remove us from DepInst's reverse set now that the local dep info is gone.
1130    if (Instruction *Inst = LocalDepEntry->second.getInst())
1131      RemoveFromReverseMap(ReverseLocalDeps, Inst, RemInst);
1132
1133    // Remove this local dependency info.
1134    LocalDeps.erase(LocalDepEntry);
1135  }
1136
1137  // If we have any cached pointer dependencies on this instruction, remove
1138  // them.  If the instruction has non-pointer type, then it can't be a pointer
1139  // base.
1140
1141  // Remove it from both the load info and the store info.  The instruction
1142  // can't be in either of these maps if it is non-pointer.
1143  if (RemInst->getType()->isPointerTy()) {
1144    RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(RemInst, false));
1145    RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(RemInst, true));
1146  }
1147
1148  // Loop over all of the things that depend on the instruction we're removing.
1149  //
1150  SmallVector<std::pair<Instruction*, Instruction*>, 8> ReverseDepsToAdd;
1151
1152  // If we find RemInst as a clobber or Def in any of the maps for other values,
1153  // we need to replace its entry with a dirty version of the instruction after
1154  // it.  If RemInst is a terminator, we use a null dirty value.
1155  //
1156  // Using a dirty version of the instruction after RemInst saves having to scan
1157  // the entire block to get to this point.
1158  MemDepResult NewDirtyVal;
1159  if (!RemInst->isTerminator())
1160    NewDirtyVal = MemDepResult::getDirty(++BasicBlock::iterator(RemInst));
1161
1162  ReverseDepMapType::iterator ReverseDepIt = ReverseLocalDeps.find(RemInst);
1163  if (ReverseDepIt != ReverseLocalDeps.end()) {
1164    SmallPtrSet<Instruction*, 4> &ReverseDeps = ReverseDepIt->second;
1165    // RemInst can't be the terminator if it has local stuff depending on it.
1166    assert(!ReverseDeps.empty() && !isa<TerminatorInst>(RemInst) &&
1167           "Nothing can locally depend on a terminator");
1168
1169    for (SmallPtrSet<Instruction*, 4>::iterator I = ReverseDeps.begin(),
1170         E = ReverseDeps.end(); I != E; ++I) {
1171      Instruction *InstDependingOnRemInst = *I;
1172      assert(InstDependingOnRemInst != RemInst &&
1173             "Already removed our local dep info");
1174
1175      LocalDeps[InstDependingOnRemInst] = NewDirtyVal;
1176
1177      // Make sure to remember that new things depend on NewDepInst.
1178      assert(NewDirtyVal.getInst() && "There is no way something else can have "
1179             "a local dep on this if it is a terminator!");
1180      ReverseDepsToAdd.push_back(std::make_pair(NewDirtyVal.getInst(),
1181                                                InstDependingOnRemInst));
1182    }
1183
1184    ReverseLocalDeps.erase(ReverseDepIt);
1185
1186    // Add new reverse deps after scanning the set, to avoid invalidating the
1187    // 'ReverseDeps' reference.
1188    while (!ReverseDepsToAdd.empty()) {
1189      ReverseLocalDeps[ReverseDepsToAdd.back().first]
1190        .insert(ReverseDepsToAdd.back().second);
1191      ReverseDepsToAdd.pop_back();
1192    }
1193  }
1194
1195  ReverseDepIt = ReverseNonLocalDeps.find(RemInst);
1196  if (ReverseDepIt != ReverseNonLocalDeps.end()) {
1197    SmallPtrSet<Instruction*, 4> &Set = ReverseDepIt->second;
1198    for (SmallPtrSet<Instruction*, 4>::iterator I = Set.begin(), E = Set.end();
1199         I != E; ++I) {
1200      assert(*I != RemInst && "Already removed NonLocalDep info for RemInst");
1201
1202      PerInstNLInfo &INLD = NonLocalDeps[*I];
1203      // The information is now dirty!
1204      INLD.second = true;
1205
1206      for (NonLocalDepInfo::iterator DI = INLD.first.begin(),
1207           DE = INLD.first.end(); DI != DE; ++DI) {
1208        if (DI->getResult().getInst() != RemInst) continue;
1209
1210        // Convert to a dirty entry for the subsequent instruction.
1211        DI->setResult(NewDirtyVal);
1212
1213        if (Instruction *NextI = NewDirtyVal.getInst())
1214          ReverseDepsToAdd.push_back(std::make_pair(NextI, *I));
1215      }
1216    }
1217
1218    ReverseNonLocalDeps.erase(ReverseDepIt);
1219
1220    // Add new reverse deps after scanning the set, to avoid invalidating 'Set'
1221    while (!ReverseDepsToAdd.empty()) {
1222      ReverseNonLocalDeps[ReverseDepsToAdd.back().first]
1223        .insert(ReverseDepsToAdd.back().second);
1224      ReverseDepsToAdd.pop_back();
1225    }
1226  }
1227
1228  // If the instruction is in ReverseNonLocalPtrDeps then it appears as a
1229  // value in the NonLocalPointerDeps info.
1230  ReverseNonLocalPtrDepTy::iterator ReversePtrDepIt =
1231    ReverseNonLocalPtrDeps.find(RemInst);
1232  if (ReversePtrDepIt != ReverseNonLocalPtrDeps.end()) {
1233    SmallPtrSet<ValueIsLoadPair, 4> &Set = ReversePtrDepIt->second;
1234    SmallVector<std::pair<Instruction*, ValueIsLoadPair>,8> ReversePtrDepsToAdd;
1235
1236    for (SmallPtrSet<ValueIsLoadPair, 4>::iterator I = Set.begin(),
1237         E = Set.end(); I != E; ++I) {
1238      ValueIsLoadPair P = *I;
1239      assert(P.getPointer() != RemInst &&
1240             "Already removed NonLocalPointerDeps info for RemInst");
1241
1242      NonLocalDepInfo &NLPDI = NonLocalPointerDeps[P].NonLocalDeps;
1243
1244      // The cache is not valid for any specific block anymore.
1245      NonLocalPointerDeps[P].Pair = BBSkipFirstBlockPair();
1246
1247      // Update any entries for RemInst to use the instruction after it.
1248      for (NonLocalDepInfo::iterator DI = NLPDI.begin(), DE = NLPDI.end();
1249           DI != DE; ++DI) {
1250        if (DI->getResult().getInst() != RemInst) continue;
1251
1252        // Convert to a dirty entry for the subsequent instruction.
1253        DI->setResult(NewDirtyVal);
1254
1255        if (Instruction *NewDirtyInst = NewDirtyVal.getInst())
1256          ReversePtrDepsToAdd.push_back(std::make_pair(NewDirtyInst, P));
1257      }
1258
1259      // Re-sort the NonLocalDepInfo.  Changing the dirty entry to its
1260      // subsequent value may invalidate the sortedness.
1261      std::sort(NLPDI.begin(), NLPDI.end());
1262    }
1263
1264    ReverseNonLocalPtrDeps.erase(ReversePtrDepIt);
1265
1266    while (!ReversePtrDepsToAdd.empty()) {
1267      ReverseNonLocalPtrDeps[ReversePtrDepsToAdd.back().first]
1268        .insert(ReversePtrDepsToAdd.back().second);
1269      ReversePtrDepsToAdd.pop_back();
1270    }
1271  }
1272
1273
1274  assert(!NonLocalDeps.count(RemInst) && "RemInst got reinserted?");
1275  AA->deleteValue(RemInst);
1276  DEBUG(verifyRemoved(RemInst));
1277}
1278/// verifyRemoved - Verify that the specified instruction does not occur
1279/// in our internal data structures.
1280void MemoryDependenceAnalysis::verifyRemoved(Instruction *D) const {
1281  for (LocalDepMapType::const_iterator I = LocalDeps.begin(),
1282       E = LocalDeps.end(); I != E; ++I) {
1283    assert(I->first != D && "Inst occurs in data structures");
1284    assert(I->second.getInst() != D &&
1285           "Inst occurs in data structures");
1286  }
1287
1288  for (CachedNonLocalPointerInfo::const_iterator I =NonLocalPointerDeps.begin(),
1289       E = NonLocalPointerDeps.end(); I != E; ++I) {
1290    assert(I->first.getPointer() != D && "Inst occurs in NLPD map key");
1291    const NonLocalDepInfo &Val = I->second.NonLocalDeps;
1292    for (NonLocalDepInfo::const_iterator II = Val.begin(), E = Val.end();
1293         II != E; ++II)
1294      assert(II->getResult().getInst() != D && "Inst occurs as NLPD value");
1295  }
1296
1297  for (NonLocalDepMapType::const_iterator I = NonLocalDeps.begin(),
1298       E = NonLocalDeps.end(); I != E; ++I) {
1299    assert(I->first != D && "Inst occurs in data structures");
1300    const PerInstNLInfo &INLD = I->second;
1301    for (NonLocalDepInfo::const_iterator II = INLD.first.begin(),
1302         EE = INLD.first.end(); II  != EE; ++II)
1303      assert(II->getResult().getInst() != D && "Inst occurs in data structures");
1304  }
1305
1306  for (ReverseDepMapType::const_iterator I = ReverseLocalDeps.begin(),
1307       E = ReverseLocalDeps.end(); I != E; ++I) {
1308    assert(I->first != D && "Inst occurs in data structures");
1309    for (SmallPtrSet<Instruction*, 4>::const_iterator II = I->second.begin(),
1310         EE = I->second.end(); II != EE; ++II)
1311      assert(*II != D && "Inst occurs in data structures");
1312  }
1313
1314  for (ReverseDepMapType::const_iterator I = ReverseNonLocalDeps.begin(),
1315       E = ReverseNonLocalDeps.end();
1316       I != E; ++I) {
1317    assert(I->first != D && "Inst occurs in data structures");
1318    for (SmallPtrSet<Instruction*, 4>::const_iterator II = I->second.begin(),
1319         EE = I->second.end(); II != EE; ++II)
1320      assert(*II != D && "Inst occurs in data structures");
1321  }
1322
1323  for (ReverseNonLocalPtrDepTy::const_iterator
1324       I = ReverseNonLocalPtrDeps.begin(),
1325       E = ReverseNonLocalPtrDeps.end(); I != E; ++I) {
1326    assert(I->first != D && "Inst occurs in rev NLPD map");
1327
1328    for (SmallPtrSet<ValueIsLoadPair, 4>::const_iterator II = I->second.begin(),
1329         E = I->second.end(); II != E; ++II)
1330      assert(*II != ValueIsLoadPair(D, false) &&
1331             *II != ValueIsLoadPair(D, true) &&
1332             "Inst occurs in ReverseNonLocalPtrDeps map");
1333  }
1334
1335}
1336