rename "ping" to "verifyRemoved". I don't know why 'ping' what chosen,
[oota-llvm.git] / lib / Analysis / MemoryDependenceAnalysis.cpp
1 //===- MemoryDependenceAnalysis.cpp - Mem Deps Implementation  --*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements an analysis that determines, for a given memory
11 // operation, what preceding memory operations it depends on.  It builds on 
12 // alias analysis information, and tries to provide a lazy, caching interface to
13 // a common kind of alias information query.
14 //
15 //===----------------------------------------------------------------------===//
16
17 #include "llvm/Analysis/MemoryDependenceAnalysis.h"
18 #include "llvm/Constants.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/Function.h"
21 #include "llvm/Analysis/AliasAnalysis.h"
22 #include "llvm/Support/CFG.h"
23 #include "llvm/Support/CommandLine.h"
24 #include "llvm/Target/TargetData.h"
25 #include "llvm/ADT/Statistic.h"
26
27 #define DEBUG_TYPE "memdep"
28
29 using namespace llvm;
30
31 // Control the calculation of non-local dependencies by only examining the
32 // predecessors if the basic block has less than X amount (50 by default).
33 static cl::opt<int> 
34 PredLimit("nonlocaldep-threshold", cl::Hidden, cl::init(50),
35           cl::desc("Control the calculation of non-local"
36                    "dependencies (default = 50)"));           
37
38 STATISTIC(NumCacheNonlocal, "Number of cached non-local responses");
39 STATISTIC(NumUncacheNonlocal, "Number of uncached non-local responses");
40
41 char MemoryDependenceAnalysis::ID = 0;
42   
43 Instruction* const MemoryDependenceAnalysis::NonLocal = (Instruction*)-3;
44 Instruction* const MemoryDependenceAnalysis::None = (Instruction*)-4;
45 Instruction* const MemoryDependenceAnalysis::Dirty = (Instruction*)-5;
46   
47 // Register this pass...
48 static RegisterPass<MemoryDependenceAnalysis> X("memdep",
49                                                 "Memory Dependence Analysis", false, true);
50
51 void MemoryDependenceAnalysis::verifyRemoved(Instruction *D) const {
52   for (depMapType::const_iterator I = depGraphLocal.begin(),
53        E = depGraphLocal.end(); I != E; ++I) {
54     assert(I->first != D);
55     assert(I->second.first != D);
56   }
57
58   for (nonLocalDepMapType::const_iterator I = depGraphNonLocal.begin(),
59        E = depGraphNonLocal.end(); I != E; ++I) {
60     assert(I->first != D);
61     for (DenseMap<BasicBlock*, Value*>::iterator II = I->second.begin(),
62          EE = I->second.end(); II  != EE; ++II)
63       assert(II->second != D);
64   }
65
66   for (reverseDepMapType::const_iterator I = reverseDep.begin(),
67        E = reverseDep.end(); I != E; ++I)
68     for (SmallPtrSet<Instruction*, 4>::const_iterator II = I->second.begin(),
69          EE = I->second.end(); II != EE; ++II)
70       assert(*II != D);
71
72   for (reverseDepMapType::const_iterator I = reverseDepNonLocal.begin(),
73        E = reverseDepNonLocal.end();
74        I != E; ++I)
75     for (SmallPtrSet<Instruction*, 4>::const_iterator II = I->second.begin(),
76          EE = I->second.end(); II != EE; ++II)
77       assert(*II != D);
78 }
79
80 /// getAnalysisUsage - Does not modify anything.  It uses Alias Analysis.
81 ///
82 void MemoryDependenceAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
83   AU.setPreservesAll();
84   AU.addRequiredTransitive<AliasAnalysis>();
85   AU.addRequiredTransitive<TargetData>();
86 }
87
88 /// getCallSiteDependency - Private helper for finding the local dependencies
89 /// of a call site.
90 Instruction* MemoryDependenceAnalysis::getCallSiteDependency(CallSite C,
91                                                            Instruction* start,
92                                                             BasicBlock* block) {
93   
94   std::pair<Instruction*, bool>& cachedResult =
95                                               depGraphLocal[C.getInstruction()];
96   AliasAnalysis& AA = getAnalysis<AliasAnalysis>();
97   TargetData& TD = getAnalysis<TargetData>();
98   BasicBlock::iterator blockBegin = C.getInstruction()->getParent()->begin();
99   BasicBlock::iterator QI = C.getInstruction();
100   
101   // If the starting point was specified, use it
102   if (start) {
103     QI = start;
104     blockBegin = start->getParent()->begin();
105   // If the starting point wasn't specified, but the block was, use it
106   } else if (!start && block) {
107     QI = block->end();
108     blockBegin = block->begin();
109   }
110   
111   // Walk backwards through the block, looking for dependencies
112   while (QI != blockBegin) {
113     --QI;
114     
115     // If this inst is a memory op, get the pointer it accessed
116     Value* pointer = 0;
117     uint64_t pointerSize = 0;
118     if (StoreInst* S = dyn_cast<StoreInst>(QI)) {
119       pointer = S->getPointerOperand();
120       pointerSize = TD.getTypeStoreSize(S->getOperand(0)->getType());
121     } else if (AllocationInst* AI = dyn_cast<AllocationInst>(QI)) {
122       pointer = AI;
123       if (ConstantInt* C = dyn_cast<ConstantInt>(AI->getArraySize()))
124         pointerSize = C->getZExtValue() *
125                       TD.getABITypeSize(AI->getAllocatedType());
126       else
127         pointerSize = ~0UL;
128     } else if (VAArgInst* V = dyn_cast<VAArgInst>(QI)) {
129       pointer = V->getOperand(0);
130       pointerSize = TD.getTypeStoreSize(V->getType());
131     } else if (FreeInst* F = dyn_cast<FreeInst>(QI)) {
132       pointer = F->getPointerOperand();
133       
134       // FreeInsts erase the entire structure
135       pointerSize = ~0UL;
136     } else if (CallSite::get(QI).getInstruction() != 0) {
137       AliasAnalysis::ModRefBehavior result =
138                    AA.getModRefBehavior(CallSite::get(QI));
139       if (result != AliasAnalysis::DoesNotAccessMemory) {
140         if (!start && !block) {
141           cachedResult.first = QI;
142           cachedResult.second = true;
143           reverseDep[QI].insert(C.getInstruction());
144         }
145         return QI;
146       } else {
147         continue;
148       }
149     } else
150       continue;
151     
152     if (AA.getModRefInfo(C, pointer, pointerSize) != AliasAnalysis::NoModRef) {
153       if (!start && !block) {
154         cachedResult.first = QI;
155         cachedResult.second = true;
156         reverseDep[QI].insert(C.getInstruction());
157       }
158       return QI;
159     }
160   }
161   
162   // No dependence found
163   cachedResult.first = NonLocal;
164   cachedResult.second = true;
165   reverseDep[NonLocal].insert(C.getInstruction());
166   return NonLocal;
167 }
168
169 /// nonLocalHelper - Private helper used to calculate non-local dependencies
170 /// by doing DFS on the predecessors of a block to find its dependencies
171 void MemoryDependenceAnalysis::nonLocalHelper(Instruction* query,
172                                               BasicBlock* block,
173                                          DenseMap<BasicBlock*, Value*>& resp) {
174   // Set of blocks that we've already visited in our DFS
175   SmallPtrSet<BasicBlock*, 4> visited;
176   // If we're updating a dirtied cache entry, we don't need to reprocess
177   // already computed entries.
178   for (DenseMap<BasicBlock*, Value*>::iterator I = resp.begin(), 
179        E = resp.end(); I != E; ++I)
180     if (I->second != Dirty)
181       visited.insert(I->first);
182   
183   // Current stack of the DFS
184   SmallVector<BasicBlock*, 4> stack;
185   for (pred_iterator PI = pred_begin(block), PE = pred_end(block);
186        PI != PE; ++PI)
187     stack.push_back(*PI);
188   
189   // Do a basic DFS
190   while (!stack.empty()) {
191     BasicBlock* BB = stack.back();
192     
193     // If we've already visited this block, no need to revist
194     if (visited.count(BB)) {
195       stack.pop_back();
196       continue;
197     }
198     
199     // If we find a new block with a local dependency for query,
200     // then we insert the new dependency and backtrack.
201     if (BB != block) {
202       visited.insert(BB);
203       
204       Instruction* localDep = getDependency(query, 0, BB);
205       if (localDep != NonLocal) {
206         resp.insert(std::make_pair(BB, localDep));
207         stack.pop_back();
208         
209         continue;
210       }
211     // If we re-encounter the starting block, we still need to search it
212     // because there might be a dependency in the starting block AFTER
213     // the position of the query.  This is necessary to get loops right.
214     } else if (BB == block) {
215       visited.insert(BB);
216       
217       Instruction* localDep = getDependency(query, 0, BB);
218       if (localDep != query)
219         resp.insert(std::make_pair(BB, localDep));
220       
221       stack.pop_back();
222       
223       continue;
224     }
225     
226     // If we didn't find anything, recurse on the precessors of this block
227     // Only do this for blocks with a small number of predecessors.
228     bool predOnStack = false;
229     bool inserted = false;
230     if (std::distance(pred_begin(BB), pred_end(BB)) <= PredLimit) { 
231       for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
232            PI != PE; ++PI)
233         if (!visited.count(*PI)) {
234           stack.push_back(*PI);
235           inserted = true;
236         } else
237           predOnStack = true;
238     }
239     
240     // If we inserted a new predecessor, then we'll come back to this block
241     if (inserted)
242       continue;
243     // If we didn't insert because we have no predecessors, then this
244     // query has no dependency at all.
245     else if (!inserted && !predOnStack) {
246       resp.insert(std::make_pair(BB, None));
247     // If we didn't insert because our predecessors are already on the stack,
248     // then we might still have a dependency, but it will be discovered during
249     // backtracking.
250     } else if (!inserted && predOnStack){
251       resp.insert(std::make_pair(BB, NonLocal));
252     }
253     
254     stack.pop_back();
255   }
256 }
257
258 /// getNonLocalDependency - Fills the passed-in map with the non-local 
259 /// dependencies of the queries.  The map will contain NonLocal for
260 /// blocks between the query and its dependencies.
261 void MemoryDependenceAnalysis::getNonLocalDependency(Instruction* query,
262                                          DenseMap<BasicBlock*, Value*>& resp) {
263   if (depGraphNonLocal.count(query)) {
264     DenseMap<BasicBlock*, Value*>& cached = depGraphNonLocal[query];
265     NumCacheNonlocal++;
266     
267     SmallVector<BasicBlock*, 4> dirtied;
268     for (DenseMap<BasicBlock*, Value*>::iterator I = cached.begin(),
269          E = cached.end(); I != E; ++I)
270       if (I->second == Dirty)
271         dirtied.push_back(I->first);
272     
273     for (SmallVector<BasicBlock*, 4>::iterator I = dirtied.begin(),
274          E = dirtied.end(); I != E; ++I) {
275       Instruction* localDep = getDependency(query, 0, *I);
276       if (localDep != NonLocal)
277         cached[*I] = localDep;
278       else {
279         cached.erase(*I);
280         nonLocalHelper(query, *I, cached);
281       }
282     }
283     
284     resp = cached;
285     
286     // Update the reverse non-local dependency cache
287     for (DenseMap<BasicBlock*, Value*>::iterator I = resp.begin(), E = resp.end();
288          I != E; ++I)
289       reverseDepNonLocal[I->second].insert(query);
290     
291     return;
292   } else
293     NumUncacheNonlocal++;
294   
295   // If not, go ahead and search for non-local deps.
296   nonLocalHelper(query, query->getParent(), resp);
297   
298   // Update the non-local dependency cache
299   for (DenseMap<BasicBlock*, Value*>::iterator I = resp.begin(), E = resp.end();
300        I != E; ++I) {
301     depGraphNonLocal[query].insert(*I);
302     reverseDepNonLocal[I->second].insert(query);
303   }
304 }
305
306 /// getDependency - Return the instruction on which a memory operation
307 /// depends.  The local parameter indicates if the query should only
308 /// evaluate dependencies within the same basic block.
309 Instruction* MemoryDependenceAnalysis::getDependency(Instruction* query,
310                                                      Instruction* start,
311                                                      BasicBlock* block) {
312   // Start looking for dependencies with the queried inst
313   BasicBlock::iterator QI = query;
314   
315   // Check for a cached result
316   std::pair<Instruction*, bool>& cachedResult = depGraphLocal[query];
317   // If we have a _confirmed_ cached entry, return it
318   if (!block && !start) {
319     if (cachedResult.second)
320       return cachedResult.first;
321     else if (cachedResult.first && cachedResult.first != NonLocal)
322       // If we have an unconfirmed cached entry, we can start our search from there
323       QI = cachedResult.first;
324   }
325   
326   if (start)
327     QI = start;
328   else if (!start && block)
329     QI = block->end();
330   
331   AliasAnalysis& AA = getAnalysis<AliasAnalysis>();
332   TargetData& TD = getAnalysis<TargetData>();
333   
334   // Get the pointer value for which dependence will be determined
335   Value* dependee = 0;
336   uint64_t dependeeSize = 0;
337   bool queryIsVolatile = false;
338   if (StoreInst* S = dyn_cast<StoreInst>(query)) {
339     dependee = S->getPointerOperand();
340     dependeeSize = TD.getTypeStoreSize(S->getOperand(0)->getType());
341     queryIsVolatile = S->isVolatile();
342   } else if (LoadInst* L = dyn_cast<LoadInst>(query)) {
343     dependee = L->getPointerOperand();
344     dependeeSize = TD.getTypeStoreSize(L->getType());
345     queryIsVolatile = L->isVolatile();
346   } else if (VAArgInst* V = dyn_cast<VAArgInst>(query)) {
347     dependee = V->getOperand(0);
348     dependeeSize = TD.getTypeStoreSize(V->getType());
349   } else if (FreeInst* F = dyn_cast<FreeInst>(query)) {
350     dependee = F->getPointerOperand();
351     
352     // FreeInsts erase the entire structure, not just a field
353     dependeeSize = ~0UL;
354   } else if (CallSite::get(query).getInstruction() != 0)
355     return getCallSiteDependency(CallSite::get(query), start, block);
356   else if (isa<AllocationInst>(query))
357     return None;
358   else
359     return None;
360   
361   BasicBlock::iterator blockBegin = block ? block->begin()
362                                           : query->getParent()->begin();
363   
364   // Walk backwards through the basic block, looking for dependencies
365   while (QI != blockBegin) {
366     --QI;
367     
368     // If this inst is a memory op, get the pointer it accessed
369     Value* pointer = 0;
370     uint64_t pointerSize = 0;
371     if (StoreInst* S = dyn_cast<StoreInst>(QI)) {
372       // All volatile loads/stores depend on each other
373       if (queryIsVolatile && S->isVolatile()) {
374         if (!start && !block) {
375           cachedResult.first = S;
376           cachedResult.second = true;
377           reverseDep[S].insert(query);
378         }
379         
380         return S;
381       }
382       
383       pointer = S->getPointerOperand();
384       pointerSize = TD.getTypeStoreSize(S->getOperand(0)->getType());
385     } else if (LoadInst* L = dyn_cast<LoadInst>(QI)) {
386       // All volatile loads/stores depend on each other
387       if (queryIsVolatile && L->isVolatile()) {
388         if (!start && !block) {
389           cachedResult.first = L;
390           cachedResult.second = true;
391           reverseDep[L].insert(query);
392         }
393         
394         return L;
395       }
396       
397       pointer = L->getPointerOperand();
398       pointerSize = TD.getTypeStoreSize(L->getType());
399     } else if (AllocationInst* AI = dyn_cast<AllocationInst>(QI)) {
400       pointer = AI;
401       if (ConstantInt* C = dyn_cast<ConstantInt>(AI->getArraySize()))
402         pointerSize = C->getZExtValue() * 
403                       TD.getABITypeSize(AI->getAllocatedType());
404       else
405         pointerSize = ~0UL;
406     } else if (VAArgInst* V = dyn_cast<VAArgInst>(QI)) {
407       pointer = V->getOperand(0);
408       pointerSize = TD.getTypeStoreSize(V->getType());
409     } else if (FreeInst* F = dyn_cast<FreeInst>(QI)) {
410       pointer = F->getPointerOperand();
411       
412       // FreeInsts erase the entire structure
413       pointerSize = ~0UL;
414     } else if (CallSite::get(QI).getInstruction() != 0) {
415       // Call insts need special handling. Check if they can modify our pointer
416       AliasAnalysis::ModRefResult MR = AA.getModRefInfo(CallSite::get(QI),
417                                                       dependee, dependeeSize);
418       
419       if (MR != AliasAnalysis::NoModRef) {
420         // Loads don't depend on read-only calls
421         if (isa<LoadInst>(query) && MR == AliasAnalysis::Ref)
422           continue;
423         
424         if (!start && !block) {
425           cachedResult.first = QI;
426           cachedResult.second = true;
427           reverseDep[QI].insert(query);
428         }
429         
430         return QI;
431       } else {
432         continue;
433       }
434     }
435     
436     // If we found a pointer, check if it could be the same as our pointer
437     if (pointer) {
438       AliasAnalysis::AliasResult R = AA.alias(pointer, pointerSize,
439                                               dependee, dependeeSize);
440       
441       if (R != AliasAnalysis::NoAlias) {
442         // May-alias loads don't depend on each other
443         if (isa<LoadInst>(query) && isa<LoadInst>(QI) &&
444             R == AliasAnalysis::MayAlias)
445           continue;
446         
447         if (!start && !block) {
448           cachedResult.first = QI;
449           cachedResult.second = true;
450           reverseDep[QI].insert(query);
451         }
452         
453         return QI;
454       }
455     }
456   }
457   
458   // If we found nothing, return the non-local flag
459   if (!start && !block) {
460     cachedResult.first = NonLocal;
461     cachedResult.second = true;
462     reverseDep[NonLocal].insert(query);
463   }
464   
465   return NonLocal;
466 }
467
468 /// dropInstruction - Remove an instruction from the analysis, making 
469 /// absolutely conservative assumptions when updating the cache.  This is
470 /// useful, for example when an instruction is changed rather than removed.
471 void MemoryDependenceAnalysis::dropInstruction(Instruction* drop) {
472   depMapType::iterator depGraphEntry = depGraphLocal.find(drop);
473   if (depGraphEntry != depGraphLocal.end())
474     reverseDep[depGraphEntry->second.first].erase(drop);
475   
476   // Drop dependency information for things that depended on this instr
477   SmallPtrSet<Instruction*, 4>& set = reverseDep[drop];
478   for (SmallPtrSet<Instruction*, 4>::iterator I = set.begin(), E = set.end();
479        I != E; ++I)
480     depGraphLocal.erase(*I);
481   
482   depGraphLocal.erase(drop);
483   reverseDep.erase(drop);
484   
485   for (DenseMap<BasicBlock*, Value*>::iterator DI =
486        depGraphNonLocal[drop].begin(), DE = depGraphNonLocal[drop].end();
487        DI != DE; ++DI)
488     if (DI->second != None)
489       reverseDepNonLocal[DI->second].erase(drop);
490   
491   if (reverseDepNonLocal.count(drop)) {
492     SmallPtrSet<Instruction*, 4>& set = reverseDepNonLocal[drop];
493     for (SmallPtrSet<Instruction*, 4>::iterator I = set.begin(), E = set.end();
494          I != E; ++I)
495       for (DenseMap<BasicBlock*, Value*>::iterator DI =
496            depGraphNonLocal[*I].begin(), DE = depGraphNonLocal[*I].end();
497            DI != DE; ++DI)
498         if (DI->second == drop)
499           DI->second = Dirty;
500   }
501   
502   reverseDepNonLocal.erase(drop);
503   nonLocalDepMapType::iterator I = depGraphNonLocal.find(drop);
504   if (I != depGraphNonLocal.end())
505     depGraphNonLocal.erase(I);
506 }
507
508 /// removeInstruction - Remove an instruction from the dependence analysis,
509 /// updating the dependence of instructions that previously depended on it.
510 /// This method attempts to keep the cache coherent using the reverse map.
511 void MemoryDependenceAnalysis::removeInstruction(Instruction* rem) {
512   // Figure out the new dep for things that currently depend on rem
513   Instruction* newDep = NonLocal;
514
515   for (DenseMap<BasicBlock*, Value*>::iterator DI =
516        depGraphNonLocal[rem].begin(), DE = depGraphNonLocal[rem].end();
517        DI != DE; ++DI)
518     if (DI->second != None)
519       reverseDepNonLocal[DI->second].erase(rem);
520
521   depMapType::iterator depGraphEntry = depGraphLocal.find(rem);
522
523   if (depGraphEntry != depGraphLocal.end()) {
524     reverseDep[depGraphEntry->second.first].erase(rem);
525     
526     if (depGraphEntry->second.first != NonLocal &&
527         depGraphEntry->second.first != None &&
528         depGraphEntry->second.second) {
529       // If we have dep info for rem, set them to it
530       BasicBlock::iterator RI = depGraphEntry->second.first;
531       RI++;
532       
533       // If RI is rem, then we use rem's immediate successor.
534       if (RI == (BasicBlock::iterator)rem) RI++;
535       
536       newDep = RI;
537     } else if ((depGraphEntry->second.first == NonLocal ||
538                 depGraphEntry->second.first == None) &&
539                depGraphEntry->second.second) {
540       // If we have a confirmed non-local flag, use it
541       newDep = depGraphEntry->second.first;
542     } else {
543       // Otherwise, use the immediate successor of rem
544       // NOTE: This is because, when getDependence is called, it will first
545       // check the immediate predecessor of what is in the cache.
546       BasicBlock::iterator RI = rem;
547       RI++;
548       newDep = RI;
549     }
550   } else {
551     // Otherwise, use the immediate successor of rem
552     // NOTE: This is because, when getDependence is called, it will first
553     // check the immediate predecessor of what is in the cache.
554     BasicBlock::iterator RI = rem;
555     RI++;
556     newDep = RI;
557   }
558   
559   SmallPtrSet<Instruction*, 4>& set = reverseDep[rem];
560   for (SmallPtrSet<Instruction*, 4>::iterator I = set.begin(), E = set.end();
561        I != E; ++I) {
562     // Insert the new dependencies
563     // Mark it as unconfirmed as long as it is not the non-local flag
564     depGraphLocal[*I] = std::make_pair(newDep, (newDep == NonLocal ||
565                                                 newDep == None));
566   }
567   
568   depGraphLocal.erase(rem);
569   reverseDep.erase(rem);
570   
571   if (reverseDepNonLocal.count(rem)) {
572     SmallPtrSet<Instruction*, 4>& set = reverseDepNonLocal[rem];
573     for (SmallPtrSet<Instruction*, 4>::iterator I = set.begin(), E = set.end();
574          I != E; ++I)
575       for (DenseMap<BasicBlock*, Value*>::iterator DI =
576            depGraphNonLocal[*I].begin(), DE = depGraphNonLocal[*I].end();
577            DI != DE; ++DI)
578         if (DI->second == rem)
579           DI->second = Dirty;
580     
581   }
582   
583   reverseDepNonLocal.erase(rem);
584   nonLocalDepMapType::iterator I = depGraphNonLocal.find(rem);
585   if (I != depGraphNonLocal.end())
586     depGraphNonLocal.erase(I);
587
588   getAnalysis<AliasAnalysis>().deleteValue(rem);
589 }