blob: 0b185b1c7cfc72dd45d66c8f6eaa238939d383f7 [file] [log] [blame]
Owen Anderson78e02f72007-07-06 23:14:35 +00001//===- MemoryDependenceAnalysis.cpp - Mem Deps Implementation --*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Owen Anderson78e02f72007-07-06 23:14:35 +00007//
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
Owen Anderson80b1f092007-08-08 22:01:54 +000012// alias analysis information, and tries to provide a lazy, caching interface to
Owen Anderson78e02f72007-07-06 23:14:35 +000013// a common kind of alias information query.
14//
15//===----------------------------------------------------------------------===//
16
Chris Lattner0e575f42008-11-28 21:45:17 +000017#define DEBUG_TYPE "memdep"
Owen Anderson78e02f72007-07-06 23:14:35 +000018#include "llvm/Analysis/MemoryDependenceAnalysis.h"
Owen Anderson7a616a12007-07-10 17:25:03 +000019#include "llvm/Constants.h"
Owen Anderson78e02f72007-07-06 23:14:35 +000020#include "llvm/Instructions.h"
21#include "llvm/Function.h"
22#include "llvm/Analysis/AliasAnalysis.h"
Chris Lattnerbaad8882008-11-28 22:28:27 +000023#include "llvm/ADT/Statistic.h"
Chris Lattner4012fdd2008-12-09 06:28:49 +000024#include "llvm/Support/PredIteratorCache.h"
Chris Lattner0e575f42008-11-28 21:45:17 +000025#include "llvm/Support/Debug.h"
Owen Anderson78e02f72007-07-06 23:14:35 +000026#include "llvm/Target/TargetData.h"
Owen Anderson78e02f72007-07-06 23:14:35 +000027using namespace llvm;
28
Chris Lattnerbf145d62008-12-01 01:15:42 +000029STATISTIC(NumCacheNonLocal, "Number of fully cached non-local responses");
30STATISTIC(NumCacheDirtyNonLocal, "Number of dirty cached non-local responses");
Chris Lattner0ec48dd2008-11-29 22:02:15 +000031STATISTIC(NumUncacheNonLocal, "Number of uncached non-local responses");
Chris Lattner6290f5c2008-12-07 08:50:20 +000032
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");
Chris Lattner11dcd8d2008-12-08 07:31:50 +000039STATISTIC(NumCacheCompleteNonLocalPtr,
40 "Number of block queries that were completely cached");
Chris Lattner6290f5c2008-12-07 08:50:20 +000041
Owen Anderson78e02f72007-07-06 23:14:35 +000042char MemoryDependenceAnalysis::ID = 0;
43
Owen Anderson78e02f72007-07-06 23:14:35 +000044// Register this pass...
Owen Anderson776ee1f2007-07-10 20:21:08 +000045static RegisterPass<MemoryDependenceAnalysis> X("memdep",
Chris Lattner0e575f42008-11-28 21:45:17 +000046 "Memory Dependence Analysis", false, true);
Owen Anderson78e02f72007-07-06 23:14:35 +000047
Chris Lattner4012fdd2008-12-09 06:28:49 +000048MemoryDependenceAnalysis::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
Owen Anderson78e02f72007-07-06 23:14:35 +000067/// 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
Chris Lattnerd777d402008-11-30 19:24:31 +000075bool MemoryDependenceAnalysis::runOnFunction(Function &) {
76 AA = &getAnalysis<AliasAnalysis>();
77 TD = &getAnalysis<TargetData>();
Chris Lattner4012fdd2008-12-09 06:28:49 +000078 if (PredCache == 0)
79 PredCache.reset(new PredIteratorCache());
Chris Lattnerd777d402008-11-30 19:24:31 +000080 return false;
81}
82
Chris Lattnerd44745d2008-12-07 18:39:13 +000083/// 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
Chris Lattnerbf145d62008-12-01 01:15:42 +000098
Chris Lattner8ef57c52008-12-07 00:35:51 +000099/// getCallSiteDependencyFrom - Private helper for finding the local
100/// dependencies of a call site.
Chris Lattnerfd3dcbe2008-11-30 23:17:19 +0000101MemDepResult MemoryDependenceAnalysis::
Chris Lattner20d6f092008-12-09 21:19:42 +0000102getCallSiteDependencyFrom(CallSite CS, bool isReadOnlyCall,
103 BasicBlock::iterator ScanIt, BasicBlock *BB) {
Owen Anderson642a9e32007-08-08 22:26:03 +0000104 // Walk backwards through the block, looking for dependencies
Chris Lattner5391a1d2008-11-29 03:47:00 +0000105 while (ScanIt != BB->begin()) {
106 Instruction *Inst = --ScanIt;
Owen Anderson5f323202007-07-10 17:59:22 +0000107
108 // If this inst is a memory op, get the pointer it accessed
Chris Lattner00314b32008-11-29 09:15:21 +0000109 Value *Pointer = 0;
110 uint64_t PointerSize = 0;
111 if (StoreInst *S = dyn_cast<StoreInst>(Inst)) {
112 Pointer = S->getPointerOperand();
Chris Lattnerd777d402008-11-30 19:24:31 +0000113 PointerSize = TD->getTypeStoreSize(S->getOperand(0)->getType());
Chris Lattner00314b32008-11-29 09:15:21 +0000114 } else if (VAArgInst *V = dyn_cast<VAArgInst>(Inst)) {
115 Pointer = V->getOperand(0);
Chris Lattnerd777d402008-11-30 19:24:31 +0000116 PointerSize = TD->getTypeStoreSize(V->getType());
Chris Lattner00314b32008-11-29 09:15:21 +0000117 } else if (FreeInst *F = dyn_cast<FreeInst>(Inst)) {
118 Pointer = F->getPointerOperand();
Owen Anderson5f323202007-07-10 17:59:22 +0000119
120 // FreeInsts erase the entire structure
Chris Lattner6290f5c2008-12-07 08:50:20 +0000121 PointerSize = ~0ULL;
Chris Lattner00314b32008-11-29 09:15:21 +0000122 } else if (isa<CallInst>(Inst) || isa<InvokeInst>(Inst)) {
Chris Lattnerb51deb92008-12-05 21:04:20 +0000123 CallSite InstCS = CallSite::get(Inst);
124 // If these two calls do not interfere, look past it.
Chris Lattner20d6f092008-12-09 21:19:42 +0000125 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.
Chris Lattner00314b32008-11-29 09:15:21 +0000129 continue;
Chris Lattner20d6f092008-12-09 21:19:42 +0000130 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:
Chris Lattnerb51deb92008-12-05 21:04:20 +0000148 return MemDepResult::getClobber(Inst);
Chris Lattner20d6f092008-12-09 21:19:42 +0000149 }
Chris Lattnercfbb6342008-11-30 01:44:00 +0000150 } else {
151 // Non-memory instruction.
Owen Anderson202da142007-07-10 20:39:07 +0000152 continue;
Chris Lattnercfbb6342008-11-30 01:44:00 +0000153 }
Owen Anderson5f323202007-07-10 17:59:22 +0000154
Chris Lattnerb51deb92008-12-05 21:04:20 +0000155 if (AA->getModRefInfo(CS, Pointer, PointerSize) != AliasAnalysis::NoModRef)
156 return MemDepResult::getClobber(Inst);
Owen Anderson5f323202007-07-10 17:59:22 +0000157 }
158
Chris Lattner7ebcf032008-12-07 02:15:47 +0000159 // 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);
Owen Anderson5f323202007-07-10 17:59:22 +0000164}
165
Chris Lattnere79be942008-12-07 01:50:16 +0000166/// 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.
Chris Lattnerfd3dcbe2008-11-30 23:17:19 +0000169MemDepResult MemoryDependenceAnalysis::
Chris Lattnere79be942008-12-07 01:50:16 +0000170getPointerDependencyFrom(Value *MemPtr, uint64_t MemSize, bool isLoad,
171 BasicBlock::iterator ScanIt, BasicBlock *BB) {
Chris Lattner7ebcf032008-12-07 02:15:47 +0000172
Chris Lattner6290f5c2008-12-07 08:50:20 +0000173 // Walk backwards through the basic block, looking for dependencies.
Chris Lattner5391a1d2008-11-29 03:47:00 +0000174 while (ScanIt != BB->begin()) {
175 Instruction *Inst = --ScanIt;
Chris Lattnera161ab02008-11-29 09:09:48 +0000176
Chris Lattnercfbb6342008-11-30 01:44:00 +0000177 // 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.
Chris Lattnerb51deb92008-12-05 21:04:20 +0000179 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
Chris Lattnerb51deb92008-12-05 21:04:20 +0000180 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.
Chris Lattnera161ab02008-11-29 09:09:48 +0000184 AliasAnalysis::AliasResult R =
Chris Lattnerd777d402008-11-30 19:24:31 +0000185 AA->alias(Pointer, PointerSize, MemPtr, MemSize);
Chris Lattnera161ab02008-11-29 09:09:48 +0000186 if (R == AliasAnalysis::NoAlias)
187 continue;
188
189 // May-alias loads don't depend on each other without a dependence.
Chris Lattnere79be942008-12-07 01:50:16 +0000190 if (isLoad && R == AliasAnalysis::MayAlias)
Chris Lattnera161ab02008-11-29 09:09:48 +0000191 continue;
Chris Lattner6290f5c2008-12-07 08:50:20 +0000192 // Stores depend on may and must aliased loads, loads depend on must-alias
193 // loads.
Chris Lattnerb51deb92008-12-05 21:04:20 +0000194 return MemDepResult::getDef(Inst);
195 }
196
197 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
Chris Lattnerb51deb92008-12-05 21:04:20 +0000198 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);
Owen Anderson78e02f72007-07-06 23:14:35 +0000210 }
Chris Lattner237a8282008-11-30 01:39:32 +0000211
212 // If this is an allocation, and if we know that the accessed pointer is to
Chris Lattnerb51deb92008-12-05 21:04:20 +0000213 // the allocation, return Def. This means that there is no dependence and
Chris Lattner237a8282008-11-30 01:39:32 +0000214 // the access can be optimized based on that. For example, a load could
215 // turn into undef.
Chris Lattnera161ab02008-11-29 09:09:48 +0000216 if (AllocationInst *AI = dyn_cast<AllocationInst>(Inst)) {
Chris Lattner237a8282008-11-30 01:39:32 +0000217 Value *AccessPtr = MemPtr->getUnderlyingObject();
Owen Anderson78e02f72007-07-06 23:14:35 +0000218
Chris Lattner237a8282008-11-30 01:39:32 +0000219 if (AccessPtr == AI ||
Chris Lattnerd777d402008-11-30 19:24:31 +0000220 AA->alias(AI, 1, AccessPtr, 1) == AliasAnalysis::MustAlias)
Chris Lattnerb51deb92008-12-05 21:04:20 +0000221 return MemDepResult::getDef(AI);
Chris Lattner237a8282008-11-30 01:39:32 +0000222 continue;
Chris Lattnera161ab02008-11-29 09:09:48 +0000223 }
Chris Lattnera161ab02008-11-29 09:09:48 +0000224
Chris Lattnerb51deb92008-12-05 21:04:20 +0000225 // See if this instruction (e.g. a call or vaarg) mod/ref's the pointer.
Chris Lattner3579e442008-12-09 19:47:40 +0000226 switch (AA->getModRefInfo(Inst, MemPtr, MemSize)) {
227 case AliasAnalysis::NoModRef:
228 // If the call has no effect on the queried pointer, just ignore it.
Chris Lattner25a08142008-11-29 08:51:16 +0000229 continue;
Chris Lattner3579e442008-12-09 19:47:40 +0000230 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 }
Owen Anderson78e02f72007-07-06 23:14:35 +0000240 }
241
Chris Lattner7ebcf032008-12-07 02:15:47 +0000242 // 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);
Owen Anderson78e02f72007-07-06 23:14:35 +0000247}
248
Chris Lattner5391a1d2008-11-29 03:47:00 +0000249/// 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
Chris Lattnerfd3dcbe2008-11-30 23:17:19 +0000255 MemDepResult &LocalCache = LocalDeps[QueryInst];
Chris Lattner5391a1d2008-11-29 03:47:00 +0000256
Chris Lattner0ec48dd2008-11-29 22:02:15 +0000257 // If the cached entry is non-dirty, just return it. Note that this depends
Chris Lattnerfd3dcbe2008-11-30 23:17:19 +0000258 // on MemDepResult's default constructing to 'dirty'.
259 if (!LocalCache.isDirty())
260 return LocalCache;
Chris Lattner5391a1d2008-11-29 03:47:00 +0000261
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.
Chris Lattnerfd3dcbe2008-11-30 23:17:19 +0000264 if (Instruction *Inst = LocalCache.getInst()) {
Chris Lattner5391a1d2008-11-29 03:47:00 +0000265 ScanPos = Inst;
Chris Lattner4a69bad2008-11-30 02:52:26 +0000266
Chris Lattnerd44745d2008-12-07 18:39:13 +0000267 RemoveFromReverseMap(ReverseLocalDeps, Inst, QueryInst);
Chris Lattner4a69bad2008-11-30 02:52:26 +0000268 }
Chris Lattner5391a1d2008-11-29 03:47:00 +0000269
Chris Lattnere79be942008-12-07 01:50:16 +0000270 BasicBlock *QueryParent = QueryInst->getParent();
271
272 Value *MemPtr = 0;
273 uint64_t MemSize = 0;
274
Chris Lattner5391a1d2008-11-29 03:47:00 +0000275 // Do the scan.
Chris Lattnere79be942008-12-07 01:50:16 +0000276 if (BasicBlock::iterator(QueryInst) == QueryParent->begin()) {
Chris Lattner7ebcf032008-12-07 02:15:47 +0000277 // 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);
Chris Lattnere79be942008-12-07 01:50:16 +0000283 } 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)) {
Chris Lattner20d6f092008-12-09 21:19:42 +0000302 CallSite QueryCS = CallSite::get(QueryInst);
303 bool isReadOnly = AA->onlyReadsMemory(QueryCS);
304 LocalCache = getCallSiteDependencyFrom(QueryCS, isReadOnly, ScanPos,
Chris Lattnere79be942008-12-07 01:50:16 +0000305 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);
Chris Lattner5391a1d2008-11-29 03:47:00 +0000320
321 // Remember the result!
Chris Lattnerfd3dcbe2008-11-30 23:17:19 +0000322 if (Instruction *I = LocalCache.getInst())
Chris Lattner8c465272008-11-29 09:20:15 +0000323 ReverseLocalDeps[I].insert(QueryInst);
Chris Lattner5391a1d2008-11-29 03:47:00 +0000324
Chris Lattnerfd3dcbe2008-11-30 23:17:19 +0000325 return LocalCache;
Chris Lattner5391a1d2008-11-29 03:47:00 +0000326}
327
Chris Lattner1559b362008-12-09 19:38:05 +0000328/// getNonLocalCallDependency - Perform a full dependency query for the
329/// specified call, returning the set of blocks that the value is
Chris Lattner37d041c2008-11-30 01:18:27 +0000330/// potentially live across. The returned set of results will include a
331/// "NonLocal" result for all blocks where the value is live across.
332///
Chris Lattner1559b362008-12-09 19:38:05 +0000333/// This method assumes the instruction returns a "NonLocal" dependency
Chris Lattner37d041c2008-11-30 01:18:27 +0000334/// within its own block.
335///
Chris Lattner1559b362008-12-09 19:38:05 +0000336/// 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.
Chris Lattnerbf145d62008-12-01 01:15:42 +0000340const MemoryDependenceAnalysis::NonLocalDepInfo &
Chris Lattner1559b362008-12-09 19:38:05 +0000341MemoryDependenceAnalysis::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()];
Chris Lattnerbf145d62008-12-01 01:15:42 +0000345 NonLocalDepInfo &Cache = CacheP.first;
Chris Lattner37d041c2008-11-30 01:18:27 +0000346
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()) {
Chris Lattnerbf145d62008-12-01 01:15:42 +0000354 // 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
Chris Lattner37d041c2008-11-30 01:18:27 +0000361 // If we already have a partially computed set of results, scan them to
Chris Lattnerbf145d62008-12-01 01:15:42 +0000362 // 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);
Chris Lattner37d041c2008-11-30 01:18:27 +0000367
Chris Lattnerbf145d62008-12-01 01:15:42 +0000368 // Sort the cache so that we can do fast binary search lookups below.
369 std::sort(Cache.begin(), Cache.end());
Chris Lattner37d041c2008-11-30 01:18:27 +0000370
Chris Lattnerbf145d62008-12-01 01:15:42 +0000371 ++NumCacheDirtyNonLocal;
Chris Lattner37d041c2008-11-30 01:18:27 +0000372 //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.
Chris Lattner1559b362008-12-09 19:38:05 +0000376 BasicBlock *QueryBB = QueryCS.getInstruction()->getParent();
Chris Lattner511b36c2008-12-09 06:44:17 +0000377 for (BasicBlock **PI = PredCache->GetPreds(QueryBB); *PI; ++PI)
378 DirtyBlocks.push_back(*PI);
Chris Lattner37d041c2008-11-30 01:18:27 +0000379 NumUncacheNonLocal++;
380 }
381
Chris Lattner20d6f092008-12-09 21:19:42 +0000382 // isReadonlyCall - If this is a read-only call, we can be more aggressive.
383 bool isReadonlyCall = AA->onlyReadsMemory(QueryCS);
384
Chris Lattnerbf145d62008-12-01 01:15:42 +0000385 // Visited checked first, vector in sorted order.
386 SmallPtrSet<BasicBlock*, 64> Visited;
387
388 unsigned NumSortedEntries = Cache.size();
389
Chris Lattner37d041c2008-11-30 01:18:27 +0000390 // Iterate while we still have blocks to update.
391 while (!DirtyBlocks.empty()) {
392 BasicBlock *DirtyBB = DirtyBlocks.back();
393 DirtyBlocks.pop_back();
394
Chris Lattnerbf145d62008-12-01 01:15:42 +0000395 // Already processed this block?
396 if (!Visited.insert(DirtyBB))
397 continue;
Chris Lattner37d041c2008-11-30 01:18:27 +0000398
Chris Lattnerbf145d62008-12-01 01:15:42 +0000399 // 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
Chris Lattner37d041c2008-11-30 01:18:27 +0000419 // 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();
Chris Lattnerbf145d62008-12-01 01:15:42 +0000422 if (ExistingResult) {
423 if (Instruction *Inst = ExistingResult->getInst()) {
424 ScanPos = Inst;
Chris Lattnerbf145d62008-12-01 01:15:42 +0000425 // We're removing QueryInst's use of Inst.
Chris Lattner1559b362008-12-09 19:38:05 +0000426 RemoveFromReverseMap(ReverseNonLocalDeps, Inst,
427 QueryCS.getInstruction());
Chris Lattnerbf145d62008-12-01 01:15:42 +0000428 }
Chris Lattnerf68f3102008-11-30 02:28:25 +0000429 }
Chris Lattner37d041c2008-11-30 01:18:27 +0000430
Chris Lattner73ec3cd2008-11-30 01:26:32 +0000431 // Find out if this block has a local dependency for QueryInst.
Chris Lattnerd8dd9342008-12-07 01:21:14 +0000432 MemDepResult Dep;
Chris Lattnere79be942008-12-07 01:50:16 +0000433
Chris Lattner1559b362008-12-09 19:38:05 +0000434 if (ScanPos != DirtyBB->begin()) {
Chris Lattner20d6f092008-12-09 21:19:42 +0000435 Dep = getCallSiteDependencyFrom(QueryCS, isReadonlyCall,ScanPos, DirtyBB);
Chris Lattner1559b362008-12-09 19:38:05 +0000436 } 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();
Chris Lattnere79be942008-12-07 01:50:16 +0000440 } else {
Chris Lattner1559b362008-12-09 19:38:05 +0000441 Dep = MemDepResult::getClobber(ScanPos);
Chris Lattnere79be942008-12-07 01:50:16 +0000442 }
443
Chris Lattnerbf145d62008-12-01 01:15:42 +0000444 // 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
Chris Lattner37d041c2008-11-30 01:18:27 +0000451 // If the block has a dependency (i.e. it isn't completely transparent to
Chris Lattnerbf145d62008-12-01 01:15:42 +0000452 // the value), remember the association!
453 if (!Dep.isNonLocal()) {
Chris Lattner37d041c2008-11-30 01:18:27 +0000454 // Keep the ReverseNonLocalDeps map up to date so we can efficiently
455 // update this when we remove instructions.
Chris Lattnerbf145d62008-12-01 01:15:42 +0000456 if (Instruction *Inst = Dep.getInst())
Chris Lattner1559b362008-12-09 19:38:05 +0000457 ReverseNonLocalDeps[Inst].insert(QueryCS.getInstruction());
Chris Lattnerbf145d62008-12-01 01:15:42 +0000458 } else {
Chris Lattner37d041c2008-11-30 01:18:27 +0000459
Chris Lattnerbf145d62008-12-01 01:15:42 +0000460 // If the block *is* completely transparent to the load, we need to check
461 // the predecessors of this block. Add them to our worklist.
Chris Lattner511b36c2008-12-09 06:44:17 +0000462 for (BasicBlock **PI = PredCache->GetPreds(DirtyBB); *PI; ++PI)
463 DirtyBlocks.push_back(*PI);
Chris Lattnerbf145d62008-12-01 01:15:42 +0000464 }
Chris Lattner37d041c2008-11-30 01:18:27 +0000465 }
466
Chris Lattnerbf145d62008-12-01 01:15:42 +0000467 return Cache;
Chris Lattner37d041c2008-11-30 01:18:27 +0000468}
469
Chris Lattner7ebcf032008-12-07 02:15:47 +0000470/// 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) {
Chris Lattner3f7eb5b2008-12-07 18:45:15 +0000480 assert(isa<PointerType>(Pointer->getType()) &&
481 "Can't get pointer deps of a non-pointer!");
Chris Lattner9a193fd2008-12-07 02:56:57 +0000482 Result.clear();
483
Chris Lattner7ebcf032008-12-07 02:15:47 +0000484 // We know that the pointer value is live into FromBB find the def/clobbers
485 // from presecessors.
Chris Lattner7ebcf032008-12-07 02:15:47 +0000486 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;
Chris Lattner65633712008-12-09 07:52:59 +0000491 getNonLocalPointerDepFromBB(Pointer, PointeeSize, isLoad, FromBB,
492 Result, Visited);
Chris Lattner9a193fd2008-12-07 02:56:57 +0000493}
494
Chris Lattner9863c3f2008-12-09 07:47:11 +0000495/// 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 -
Chris Lattner9a193fd2008-12-07 02:56:57 +0000569void MemoryDependenceAnalysis::
Chris Lattner9863c3f2008-12-09 07:47:11 +0000570getNonLocalPointerDepFromBB(Value *Pointer, uint64_t PointeeSize,
571 bool isLoad, BasicBlock *StartBB,
572 SmallVectorImpl<NonLocalDepEntry> &Result,
573 SmallPtrSet<BasicBlock*, 64> &Visited) {
Chris Lattner6290f5c2008-12-07 08:50:20 +0000574 // Look up the cached info for Pointer.
575 ValueIsLoadPair CacheKey(Pointer, isLoad);
Chris Lattner11dcd8d2008-12-08 07:31:50 +0000576
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);
Chris Lattner6290f5c2008-12-07 08:50:20 +0000600
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
Chris Lattner65633712008-12-09 07:52:59 +0000608 // SkipFirstBlock - If this is the very first block that we're processing, we
Chris Lattner9f1e12a2008-12-09 08:38:36 +0000609 // don't want to scan or think about its body, because the client was supposed
Chris Lattner65633712008-12-09 07:52:59 +0000610 // 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
Chris Lattner7ebcf032008-12-07 02:15:47 +0000614 while (!Worklist.empty()) {
Chris Lattner9a193fd2008-12-07 02:56:57 +0000615 BasicBlock *BB = Worklist.pop_back_val();
Chris Lattner7ebcf032008-12-07 02:15:47 +0000616
Chris Lattner65633712008-12-09 07:52:59 +0000617 // 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;
Chris Lattner6290f5c2008-12-07 08:50:20 +0000625
Chris Lattner65633712008-12-09 07:52:59 +0000626 // 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 }
Chris Lattner7ebcf032008-12-07 02:15:47 +0000636 }
637
638 // Otherwise, we have to process all the predecessors of this block to scan
639 // them as well.
Chris Lattner4012fdd2008-12-09 06:28:49 +0000640 for (BasicBlock **PI = PredCache->GetPreds(BB); *PI; ++PI) {
Chris Lattner7ebcf032008-12-07 02:15:47 +0000641 // TODO: PHI TRANSLATE.
Chris Lattner9a193fd2008-12-07 02:56:57 +0000642 Worklist.push_back(*PI);
643 }
Chris Lattner7ebcf032008-12-07 02:15:47 +0000644 }
Chris Lattner6290f5c2008-12-07 08:50:20 +0000645
Chris Lattner9863c3f2008-12-09 07:47:11 +0000646 // Okay, we're done now. If we added new values to the cache, re-sort it.
Chris Lattnerba4dacc2008-12-09 07:05:45 +0000647 switch (Cache->size()-NumSortedEntries) {
648 case 0:
Chris Lattner1aeadac2008-12-09 06:58:04 +0000649 // done, no new entries.
Chris Lattnerba4dacc2008-12-09 07:05:45 +0000650 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: {
Chris Lattner1aeadac2008-12-09 06:58:04 +0000661 // 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);
Chris Lattnerba4dacc2008-12-09 07:05:45 +0000667 break;
668 }
669 default:
Chris Lattner1aeadac2008-12-09 06:58:04 +0000670 // Added many values, do a full scale sort.
Chris Lattner6290f5c2008-12-07 08:50:20 +0000671 std::sort(Cache->begin(), Cache->end());
Chris Lattner1aeadac2008-12-09 06:58:04 +0000672 }
Chris Lattner6290f5c2008-12-07 08:50:20 +0000673}
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.
Chris Lattner11dcd8d2008-12-08 07:31:50 +0000685 NonLocalDepInfo &PInfo = It->second.second;
Chris Lattner6290f5c2008-12-07 08:50:20 +0000686
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.
Chris Lattnerd44745d2008-12-07 18:39:13 +0000693 RemoveFromReverseMap(ReverseNonLocalPtrDeps, Target, P.getOpaqueValue());
Chris Lattner6290f5c2008-12-07 08:50:20 +0000694 }
695
696 // Remove P from NonLocalPointerDeps (which deletes NonLocalDepInfo).
697 NonLocalPointerDeps.erase(It);
Chris Lattner7ebcf032008-12-07 02:15:47 +0000698}
699
700
Chris Lattnerbc99be12008-12-09 22:06:23 +0000701/// 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
Owen Anderson78e02f72007-07-06 23:14:35 +0000716/// removeInstruction - Remove an instruction from the dependence analysis,
717/// updating the dependence of instructions that previously depended on it.
Owen Anderson642a9e32007-08-08 22:26:03 +0000718/// This method attempts to keep the cache coherent using the reverse map.
Chris Lattner5f589dc2008-11-28 22:04:47 +0000719void MemoryDependenceAnalysis::removeInstruction(Instruction *RemInst) {
Chris Lattner5f589dc2008-11-28 22:04:47 +0000720 // Walk through the Non-local dependencies, removing this one as the value
721 // for any cached queries.
Chris Lattnerf68f3102008-11-30 02:28:25 +0000722 NonLocalDepMapType::iterator NLDI = NonLocalDeps.find(RemInst);
723 if (NLDI != NonLocalDeps.end()) {
Chris Lattnerbf145d62008-12-01 01:15:42 +0000724 NonLocalDepInfo &BlockMap = NLDI->second.first;
Chris Lattner25f4b2b2008-11-30 02:30:50 +0000725 for (NonLocalDepInfo::iterator DI = BlockMap.begin(), DE = BlockMap.end();
726 DI != DE; ++DI)
Chris Lattnerfd3dcbe2008-11-30 23:17:19 +0000727 if (Instruction *Inst = DI->second.getInst())
Chris Lattnerd44745d2008-12-07 18:39:13 +0000728 RemoveFromReverseMap(ReverseNonLocalDeps, Inst, RemInst);
Chris Lattnerf68f3102008-11-30 02:28:25 +0000729 NonLocalDeps.erase(NLDI);
730 }
Owen Anderson5fc4aba2007-12-08 01:37:09 +0000731
Chris Lattner5f589dc2008-11-28 22:04:47 +0000732 // If we have a cached local dependence query for this instruction, remove it.
Chris Lattnerbaad8882008-11-28 22:28:27 +0000733 //
Chris Lattner39f372e2008-11-29 01:43:36 +0000734 LocalDepMapType::iterator LocalDepEntry = LocalDeps.find(RemInst);
735 if (LocalDepEntry != LocalDeps.end()) {
Chris Lattner125ce362008-11-30 01:09:30 +0000736 // Remove us from DepInst's reverse set now that the local dep info is gone.
Chris Lattnerd44745d2008-12-07 18:39:13 +0000737 if (Instruction *Inst = LocalDepEntry->second.getInst())
738 RemoveFromReverseMap(ReverseLocalDeps, Inst, RemInst);
Chris Lattner125ce362008-11-30 01:09:30 +0000739
Chris Lattnerbaad8882008-11-28 22:28:27 +0000740 // Remove this local dependency info.
Chris Lattner39f372e2008-11-29 01:43:36 +0000741 LocalDeps.erase(LocalDepEntry);
Chris Lattner6290f5c2008-12-07 08:50:20 +0000742 }
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 }
Chris Lattnerbaad8882008-11-28 22:28:27 +0000754
Chris Lattnerd3d12ec2008-11-28 22:51:08 +0000755 // Loop over all of the things that depend on the instruction we're removing.
756 //
Chris Lattner4f8c18c2008-11-29 23:30:39 +0000757 SmallVector<std::pair<Instruction*, Instruction*>, 8> ReverseDepsToAdd;
Chris Lattner0655f732008-12-07 18:42:51 +0000758
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));
Chris Lattner4f8c18c2008-11-29 23:30:39 +0000768
Chris Lattner8c465272008-11-29 09:20:15 +0000769 ReverseDepMapType::iterator ReverseDepIt = ReverseLocalDeps.find(RemInst);
770 if (ReverseDepIt != ReverseLocalDeps.end()) {
Chris Lattnerd3d12ec2008-11-28 22:51:08 +0000771 SmallPtrSet<Instruction*, 4> &ReverseDeps = ReverseDepIt->second;
Chris Lattner6290f5c2008-12-07 08:50:20 +0000772 // RemInst can't be the terminator if it has local stuff depending on it.
Chris Lattner125ce362008-11-30 01:09:30 +0000773 assert(!ReverseDeps.empty() && !isa<TerminatorInst>(RemInst) &&
774 "Nothing can locally depend on a terminator");
775
Chris Lattnerd3d12ec2008-11-28 22:51:08 +0000776 for (SmallPtrSet<Instruction*, 4>::iterator I = ReverseDeps.begin(),
777 E = ReverseDeps.end(); I != E; ++I) {
778 Instruction *InstDependingOnRemInst = *I;
Chris Lattnerf68f3102008-11-30 02:28:25 +0000779 assert(InstDependingOnRemInst != RemInst &&
780 "Already removed our local dep info");
Chris Lattner125ce362008-11-30 01:09:30 +0000781
Chris Lattner0655f732008-12-07 18:42:51 +0000782 LocalDeps[InstDependingOnRemInst] = NewDirtyVal;
Chris Lattnerd3d12ec2008-11-28 22:51:08 +0000783
Chris Lattner125ce362008-11-30 01:09:30 +0000784 // Make sure to remember that new things depend on NewDepInst.
Chris Lattner0655f732008-12-07 18:42:51 +0000785 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(),
Chris Lattner125ce362008-11-30 01:09:30 +0000788 InstDependingOnRemInst));
Chris Lattnerd3d12ec2008-11-28 22:51:08 +0000789 }
Chris Lattner4f8c18c2008-11-29 23:30:39 +0000790
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 }
Owen Anderson78e02f72007-07-06 23:14:35 +0000800 }
Owen Anderson4d13de42007-08-16 21:27:05 +0000801
Chris Lattner8c465272008-11-29 09:20:15 +0000802 ReverseDepIt = ReverseNonLocalDeps.find(RemInst);
803 if (ReverseDepIt != ReverseNonLocalDeps.end()) {
Chris Lattner6290f5c2008-12-07 08:50:20 +0000804 SmallPtrSet<Instruction*, 4> &Set = ReverseDepIt->second;
805 for (SmallPtrSet<Instruction*, 4>::iterator I = Set.begin(), E = Set.end();
Chris Lattnerf68f3102008-11-30 02:28:25 +0000806 I != E; ++I) {
807 assert(*I != RemInst && "Already removed NonLocalDep info for RemInst");
808
Chris Lattner4a69bad2008-11-30 02:52:26 +0000809 PerInstNLInfo &INLD = NonLocalDeps[*I];
Chris Lattner4a69bad2008-11-30 02:52:26 +0000810 // The information is now dirty!
Chris Lattnerbf145d62008-12-01 01:15:42 +0000811 INLD.second = true;
Chris Lattnerf68f3102008-11-30 02:28:25 +0000812
Chris Lattnerbf145d62008-12-01 01:15:42 +0000813 for (NonLocalDepInfo::iterator DI = INLD.first.begin(),
814 DE = INLD.first.end(); DI != DE; ++DI) {
Chris Lattnerfd3dcbe2008-11-30 23:17:19 +0000815 if (DI->second.getInst() != RemInst) continue;
Chris Lattnerf68f3102008-11-30 02:28:25 +0000816
817 // Convert to a dirty entry for the subsequent instruction.
Chris Lattner0655f732008-12-07 18:42:51 +0000818 DI->second = NewDirtyVal;
819
820 if (Instruction *NextI = NewDirtyVal.getInst())
Chris Lattnerf68f3102008-11-30 02:28:25 +0000821 ReverseDepsToAdd.push_back(std::make_pair(NextI, *I));
Chris Lattnerf68f3102008-11-30 02:28:25 +0000822 }
823 }
Chris Lattner4f8c18c2008-11-29 23:30:39 +0000824
825 ReverseNonLocalDeps.erase(ReverseDepIt);
826
Chris Lattner0ec48dd2008-11-29 22:02:15 +0000827 // 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 }
Owen Anderson4d13de42007-08-16 21:27:05 +0000833 }
Owen Anderson5fc4aba2007-12-08 01:37:09 +0000834
Chris Lattner6290f5c2008-12-07 08:50:20 +0000835 // 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
Chris Lattner11dcd8d2008-12-08 07:31:50 +0000850 NonLocalDepInfo &NLPDI = NonLocalPointerDeps[P].second;
851
852 // The cache is not valid for any specific block anymore.
853 NonLocalPointerDeps[P].first = 0;
Chris Lattner6290f5c2008-12-07 08:50:20 +0000854
Chris Lattner6290f5c2008-12-07 08:50:20 +0000855 // 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
Chris Lattnerf68f3102008-11-30 02:28:25 +0000878 assert(!NonLocalDeps.count(RemInst) && "RemInst got reinserted?");
Chris Lattnerd777d402008-11-30 19:24:31 +0000879 AA->deleteValue(RemInst);
Chris Lattner5f589dc2008-11-28 22:04:47 +0000880 DEBUG(verifyRemoved(RemInst));
Owen Anderson78e02f72007-07-06 23:14:35 +0000881}
Chris Lattner729b2372008-11-29 21:25:10 +0000882/// 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");
Chris Lattnerfd3dcbe2008-11-30 23:17:19 +0000888 assert(I->second.getInst() != D &&
Chris Lattner729b2372008-11-29 21:25:10 +0000889 "Inst occurs in data structures");
890 }
891
Chris Lattner6290f5c2008-12-07 08:50:20 +0000892 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");
Chris Lattner11dcd8d2008-12-08 07:31:50 +0000895 const NonLocalDepInfo &Val = I->second.second;
Chris Lattner6290f5c2008-12-07 08:50:20 +0000896 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
Chris Lattner729b2372008-11-29 21:25:10 +0000901 for (NonLocalDepMapType::const_iterator I = NonLocalDeps.begin(),
902 E = NonLocalDeps.end(); I != E; ++I) {
903 assert(I->first != D && "Inst occurs in data structures");
Chris Lattner4a69bad2008-11-30 02:52:26 +0000904 const PerInstNLInfo &INLD = I->second;
Chris Lattnerbf145d62008-12-01 01:15:42 +0000905 for (NonLocalDepInfo::const_iterator II = INLD.first.begin(),
906 EE = INLD.first.end(); II != EE; ++II)
Chris Lattnerfd3dcbe2008-11-30 23:17:19 +0000907 assert(II->second.getInst() != D && "Inst occurs in data structures");
Chris Lattner729b2372008-11-29 21:25:10 +0000908 }
909
910 for (ReverseDepMapType::const_iterator I = ReverseLocalDeps.begin(),
Chris Lattnerf68f3102008-11-30 02:28:25 +0000911 E = ReverseLocalDeps.end(); I != E; ++I) {
912 assert(I->first != D && "Inst occurs in data structures");
Chris Lattner729b2372008-11-29 21:25:10 +0000913 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");
Chris Lattnerf68f3102008-11-30 02:28:25 +0000916 }
Chris Lattner729b2372008-11-29 21:25:10 +0000917
918 for (ReverseDepMapType::const_iterator I = ReverseNonLocalDeps.begin(),
919 E = ReverseNonLocalDeps.end();
Chris Lattnerf68f3102008-11-30 02:28:25 +0000920 I != E; ++I) {
921 assert(I->first != D && "Inst occurs in data structures");
Chris Lattner729b2372008-11-29 21:25:10 +0000922 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");
Chris Lattnerf68f3102008-11-30 02:28:25 +0000925 }
Chris Lattner6290f5c2008-12-07 08:50:20 +0000926
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
Chris Lattner729b2372008-11-29 21:25:10 +0000939}