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