Fix #includes of i*.h => Instructions.h as per PR403.
[oota-llvm.git] / lib / Analysis / AliasSetTracker.cpp
1 //===- AliasSetTracker.cpp - Alias Sets Tracker implementation-------------===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 // 
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the AliasSetTracker and AliasSet classes.
11 // 
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Analysis/AliasSetTracker.h"
15 #include "llvm/Analysis/AliasAnalysis.h"
16 #include "llvm/Instructions.h"
17 #include "llvm/Pass.h"
18 #include "llvm/Target/TargetData.h"
19 #include "llvm/Assembly/Writer.h"
20 #include "llvm/Support/InstIterator.h"
21 #include <iostream>
22 using namespace llvm;
23
24 /// mergeSetIn - Merge the specified alias set into this alias set...
25 ///
26 void AliasSet::mergeSetIn(AliasSet &AS) {
27   assert(!AS.Forward && "Alias set is already forwarding!");
28   assert(!Forward && "This set is a forwarding set!!");
29
30   // Update the alias and access types of this set...
31   AccessTy |= AS.AccessTy;
32   AliasTy  |= AS.AliasTy;
33
34   if (CallSites.empty()) {            // Merge call sites...
35     if (!AS.CallSites.empty())
36       std::swap(CallSites, AS.CallSites);
37   } else if (!AS.CallSites.empty()) {
38     CallSites.insert(CallSites.end(), AS.CallSites.begin(), AS.CallSites.end());
39     AS.CallSites.clear();
40   }
41   
42   AS.Forward = this;  // Forward across AS now...
43   addRef();           // AS is now pointing to us...
44
45   // Merge the list of constituent pointers...
46   if (AS.PtrList) {
47     *PtrListEnd = AS.PtrList;
48     AS.PtrList->second.setPrevInList(PtrListEnd);
49     PtrListEnd = AS.PtrListEnd;
50
51     AS.PtrList = 0;
52     AS.PtrListEnd = &AS.PtrList;
53   }
54 }
55
56 void AliasSetTracker::removeAliasSet(AliasSet *AS) {
57   if (AliasSet *Fwd = AS->Forward) {
58     Fwd->dropRef(*this);
59     AS->Forward = 0;
60   }
61   AliasSets.erase(AS);
62 }
63
64 void AliasSet::removeFromTracker(AliasSetTracker &AST) {
65   assert(RefCount == 0 && "Cannot remove non-dead alias set from tracker!");
66   AST.removeAliasSet(this);
67 }
68
69 void AliasSet::addPointer(AliasSetTracker &AST, HashNodePair &Entry,
70                           unsigned Size) {
71   assert(!Entry.second.hasAliasSet() && "Entry already in set!");
72
73   AliasAnalysis &AA = AST.getAliasAnalysis();
74
75   if (isMustAlias())    // Check to see if we have to downgrade to _may_ alias
76     if (HashNodePair *P = getSomePointer()) {
77       AliasAnalysis::AliasResult Result =
78         AA.alias(P->first, P->second.getSize(), Entry.first, Size);
79       if (Result == AliasAnalysis::MayAlias)
80         AliasTy = MayAlias;
81       else                  // First entry of must alias must have maximum size!
82         P->second.updateSize(Size);
83       assert(Result != AliasAnalysis::NoAlias && "Cannot be part of must set!");
84     }
85
86   Entry.second.setAliasSet(this);
87   Entry.second.updateSize(Size);
88
89   // Add it to the end of the list...
90   assert(*PtrListEnd == 0 && "End of list is not null?");
91   *PtrListEnd = &Entry;
92   PtrListEnd = Entry.second.setPrevInList(PtrListEnd);
93   addRef();               // Entry points to alias set...
94 }
95
96 void AliasSet::addCallSite(CallSite CS, AliasAnalysis &AA) {
97   CallSites.push_back(CS);
98
99   if (Function *F = CS.getCalledFunction()) {
100     if (AA.doesNotAccessMemory(F))
101       return;
102     else if (AA.onlyReadsMemory(F)) {
103       AliasTy = MayAlias;
104       AccessTy |= Refs;
105       return;
106     }
107   }
108
109   // FIXME: This should use mod/ref information to make this not suck so bad
110   AliasTy = MayAlias;
111   AccessTy = ModRef;
112 }
113
114 /// aliasesPointer - Return true if the specified pointer "may" (or must)
115 /// alias one of the members in the set.
116 ///
117 bool AliasSet::aliasesPointer(const Value *Ptr, unsigned Size,
118                               AliasAnalysis &AA) const {
119   if (AliasTy == MustAlias) {
120     assert(CallSites.empty() && "Illegal must alias set!");
121
122     // If this is a set of MustAliases, only check to see if the pointer aliases
123     // SOME value in the set...
124     HashNodePair *SomePtr = getSomePointer();
125     assert(SomePtr && "Empty must-alias set??");
126     return AA.alias(SomePtr->first, SomePtr->second.getSize(), Ptr, Size);
127   }
128
129   // If this is a may-alias set, we have to check all of the pointers in the set
130   // to be sure it doesn't alias the set...
131   for (iterator I = begin(), E = end(); I != E; ++I)
132     if (AA.alias(Ptr, Size, I.getPointer(), I.getSize()))
133       return true;
134
135   // Check the call sites list and invoke list...
136   if (!CallSites.empty()) {
137     if (AA.hasNoModRefInfoForCalls())
138       return true;
139
140     for (unsigned i = 0, e = CallSites.size(); i != e; ++i)
141       if (AA.getModRefInfo(CallSites[i], const_cast<Value*>(Ptr), Size)
142                    != AliasAnalysis::NoModRef)
143         return true;
144   }
145
146   return false;
147 }
148
149 bool AliasSet::aliasesCallSite(CallSite CS, AliasAnalysis &AA) const {
150   if (Function *F = CS.getCalledFunction())
151     if (AA.doesNotAccessMemory(F))
152       return false;
153
154   if (AA.hasNoModRefInfoForCalls())
155     return true;
156
157   for (unsigned i = 0, e = CallSites.size(); i != e; ++i)
158     if (AA.getModRefInfo(CallSites[i], CS) != AliasAnalysis::NoModRef ||
159         AA.getModRefInfo(CS, CallSites[i]) != AliasAnalysis::NoModRef)
160       return true;
161
162   for (iterator I = begin(), E = end(); I != E; ++I)
163     if (AA.getModRefInfo(CS, I.getPointer(), I.getSize()) !=
164            AliasAnalysis::NoModRef)
165       return true;
166
167   return false;
168 }
169
170
171 /// findAliasSetForPointer - Given a pointer, find the one alias set to put the
172 /// instruction referring to the pointer into.  If there are multiple alias sets
173 /// that may alias the pointer, merge them together and return the unified set.
174 ///
175 AliasSet *AliasSetTracker::findAliasSetForPointer(const Value *Ptr,
176                                                   unsigned Size) {
177   AliasSet *FoundSet = 0;
178   for (iterator I = begin(), E = end(); I != E; ++I)
179     if (!I->Forward && I->aliasesPointer(Ptr, Size, AA)) {
180       if (FoundSet == 0) {  // If this is the first alias set ptr can go into...
181         FoundSet = I;       // Remember it.
182       } else {              // Otherwise, we must merge the sets...
183         FoundSet->mergeSetIn(*I);     // Merge in contents...
184       }
185     }
186
187   return FoundSet;
188 }
189
190 AliasSet *AliasSetTracker::findAliasSetForCallSite(CallSite CS) {
191   AliasSet *FoundSet = 0;
192   for (iterator I = begin(), E = end(); I != E; ++I)
193     if (!I->Forward && I->aliasesCallSite(CS, AA)) {
194       if (FoundSet == 0) {  // If this is the first alias set ptr can go into...
195         FoundSet = I;       // Remember it.
196       } else if (!I->Forward) {     // Otherwise, we must merge the sets...
197         FoundSet->mergeSetIn(*I);     // Merge in contents...
198       }
199     }
200
201   return FoundSet;
202 }
203
204
205
206
207 /// getAliasSetForPointer - Return the alias set that the specified pointer
208 /// lives in...
209 AliasSet &AliasSetTracker::getAliasSetForPointer(Value *Pointer, unsigned Size,
210                                                  bool *New) {
211   AliasSet::HashNodePair &Entry = getEntryFor(Pointer);
212
213   // Check to see if the pointer is already known...
214   if (Entry.second.hasAliasSet()) {
215     Entry.second.updateSize(Size);
216     // Return the set!
217     return *Entry.second.getAliasSet(*this)->getForwardedTarget(*this);
218   } else if (AliasSet *AS = findAliasSetForPointer(Pointer, Size)) {
219     // Add it to the alias set it aliases...
220     AS->addPointer(*this, Entry, Size);
221     return *AS;
222   } else {
223     if (New) *New = true;
224     // Otherwise create a new alias set to hold the loaded pointer...
225     AliasSets.push_back(new AliasSet());
226     AliasSets.back().addPointer(*this, Entry, Size);
227     return AliasSets.back();
228   }
229 }
230
231 bool AliasSetTracker::add(Value *Ptr, unsigned Size) {
232   bool NewPtr;
233   addPointer(Ptr, Size, AliasSet::NoModRef, NewPtr);
234   return NewPtr;
235 }
236
237
238 bool AliasSetTracker::add(LoadInst *LI) {
239   bool NewPtr;
240   AliasSet &AS = addPointer(LI->getOperand(0),
241                             AA.getTargetData().getTypeSize(LI->getType()),
242                             AliasSet::Refs, NewPtr);
243   if (LI->isVolatile()) AS.setVolatile();
244   return NewPtr;
245 }
246
247 bool AliasSetTracker::add(StoreInst *SI) {
248   bool NewPtr;
249   Value *Val = SI->getOperand(0);
250   AliasSet &AS = addPointer(SI->getOperand(1),
251                             AA.getTargetData().getTypeSize(Val->getType()),
252                             AliasSet::Mods, NewPtr);
253   if (SI->isVolatile()) AS.setVolatile();
254   return NewPtr;
255 }
256
257 bool AliasSetTracker::add(FreeInst *FI) {
258   bool NewPtr;
259   AliasSet &AS = addPointer(FI->getOperand(0), ~0,
260                             AliasSet::Mods, NewPtr);
261   return NewPtr;
262 }
263
264
265 bool AliasSetTracker::add(CallSite CS) {
266   bool NewPtr;
267   if (Function *F = CS.getCalledFunction())
268     if (AA.doesNotAccessMemory(F))
269       return true; // doesn't alias anything
270
271   AliasSet *AS = findAliasSetForCallSite(CS);
272   if (!AS) {
273     AliasSets.push_back(new AliasSet());
274     AS = &AliasSets.back();
275     AS->addCallSite(CS, AA);
276     return true;
277   } else {
278     AS->addCallSite(CS, AA);
279     return false;
280   }
281 }
282
283 bool AliasSetTracker::add(Instruction *I) {
284   // Dispatch to one of the other add methods...
285   if (LoadInst *LI = dyn_cast<LoadInst>(I))
286     return add(LI);
287   else if (StoreInst *SI = dyn_cast<StoreInst>(I))
288     return add(SI);
289   else if (CallInst *CI = dyn_cast<CallInst>(I))
290     return add(CI);
291   else if (InvokeInst *II = dyn_cast<InvokeInst>(I))
292     return add(II);
293   else if (FreeInst *FI = dyn_cast<FreeInst>(I))
294     return add(FI);
295   return true;
296 }
297
298 void AliasSetTracker::add(BasicBlock &BB) {
299   for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
300     add(I);
301 }
302
303 void AliasSetTracker::add(const AliasSetTracker &AST) {
304   assert(&AA == &AST.AA &&
305          "Merging AliasSetTracker objects with different Alias Analyses!");
306
307   // Loop over all of the alias sets in AST, adding the pointers contained
308   // therein into the current alias sets.  This can cause alias sets to be
309   // merged together in the current AST.
310   for (const_iterator I = AST.begin(), E = AST.end(); I != E; ++I)
311     if (!I->Forward) {   // Ignore forwarding alias sets
312       AliasSet &AS = const_cast<AliasSet&>(*I);
313
314       // If there are any call sites in the alias set, add them to this AST.
315       for (unsigned i = 0, e = AS.CallSites.size(); i != e; ++i)
316         add(AS.CallSites[i]);
317
318       // Loop over all of the pointers in this alias set...
319       AliasSet::iterator I = AS.begin(), E = AS.end();
320       bool X;
321       for (; I != E; ++I)
322         addPointer(I.getPointer(), I.getSize(),
323                    (AliasSet::AccessType)AS.AccessTy, X);
324     }
325 }
326
327 /// remove - Remove the specified (potentially non-empty) alias set from the
328 /// tracker.
329 void AliasSetTracker::remove(AliasSet &AS) {
330   bool SetDead;
331   do {
332     AliasSet::iterator I = AS.begin();
333     Value *Ptr = I.getPointer(); ++I;
334
335     // deleteValue will delete the set automatically when the last pointer
336     // reference is destroyed.  "Predict" when this will happen.
337     SetDead = I == AS.end();
338     deleteValue(Ptr);  // Delete all of the pointers from the set
339   } while (!SetDead);
340 }
341
342 bool AliasSetTracker::remove(Value *Ptr, unsigned Size) {
343   AliasSet *AS = findAliasSetForPointer(Ptr, Size);
344   if (!AS) return false;
345   remove(*AS);
346   return true;
347 }
348
349 bool AliasSetTracker::remove(LoadInst *LI) {
350   unsigned Size = AA.getTargetData().getTypeSize(LI->getType());
351   AliasSet *AS = findAliasSetForPointer(LI->getOperand(0), Size);
352   if (!AS) return false;
353   remove(*AS);
354   return true;
355 }
356
357 bool AliasSetTracker::remove(StoreInst *SI) {
358   unsigned Size = AA.getTargetData().getTypeSize(SI->getOperand(0)->getType());
359   AliasSet *AS = findAliasSetForPointer(SI->getOperand(1), Size);
360   if (!AS) return false;
361   remove(*AS);
362   return true;
363 }
364
365 bool AliasSetTracker::remove(FreeInst *FI) {
366   AliasSet *AS = findAliasSetForPointer(FI->getOperand(0), ~0);
367   if (!AS) return false;
368   remove(*AS);
369   return true;
370 }
371
372 bool AliasSetTracker::remove(CallSite CS) {
373   if (Function *F = CS.getCalledFunction())
374     if (AA.doesNotAccessMemory(F))
375       return false; // doesn't alias anything
376
377   AliasSet *AS = findAliasSetForCallSite(CS);
378   if (!AS) return false;
379   remove(*AS);
380   return true;
381 }
382
383 bool AliasSetTracker::remove(Instruction *I) {
384   // Dispatch to one of the other remove methods...
385   if (LoadInst *LI = dyn_cast<LoadInst>(I))
386     return remove(LI);
387   else if (StoreInst *SI = dyn_cast<StoreInst>(I))
388     return remove(SI);
389   else if (CallInst *CI = dyn_cast<CallInst>(I))
390     return remove(CI);
391   else if (FreeInst *FI = dyn_cast<FreeInst>(I))
392     return remove(FI);
393   return true;
394 }
395
396
397 // deleteValue method - This method is used to remove a pointer value from the
398 // AliasSetTracker entirely.  It should be used when an instruction is deleted
399 // from the program to update the AST.  If you don't use this, you would have
400 // dangling pointers to deleted instructions.
401 //
402 void AliasSetTracker::deleteValue(Value *PtrVal) {
403   // First, look up the PointerRec for this pointer...
404   hash_map<Value*, AliasSet::PointerRec>::iterator I = PointerMap.find(PtrVal);
405   if (I == PointerMap.end()) return;  // Noop
406
407   // If we found one, remove the pointer from the alias set it is in.
408   AliasSet::HashNodePair &PtrValEnt = *I;
409   AliasSet *AS = PtrValEnt.second.getAliasSet(*this);
410
411   // Unlink from the list of values...
412   PtrValEnt.second.removeFromList();
413   // Stop using the alias set
414   AS->dropRef(*this);
415   PointerMap.erase(I);
416 }
417
418
419 //===----------------------------------------------------------------------===//
420 //               AliasSet/AliasSetTracker Printing Support
421 //===----------------------------------------------------------------------===//
422
423 void AliasSet::print(std::ostream &OS) const {
424   OS << "  AliasSet[" << (void*)this << "," << RefCount << "] ";
425   OS << (AliasTy == MustAlias ? "must" : "may ") << " alias, ";
426   switch (AccessTy) {
427   case NoModRef: OS << "No access "; break;
428   case Refs    : OS << "Ref       "; break;
429   case Mods    : OS << "Mod       "; break;
430   case ModRef  : OS << "Mod/Ref   "; break;
431   default: assert(0 && "Bad value for AccessTy!");
432   }
433   if (isVolatile()) OS << "[volatile] ";
434   if (Forward)
435     OS << " forwarding to " << (void*)Forward;
436
437
438   if (begin() != end()) {
439     OS << "Pointers: ";
440     for (iterator I = begin(), E = end(); I != E; ++I) {
441       if (I != begin()) OS << ", ";
442       WriteAsOperand(OS << "(", I.getPointer());
443       OS << ", " << I.getSize() << ")";
444     }
445   }
446   if (!CallSites.empty()) {
447     OS << "\n    " << CallSites.size() << " Call Sites: ";
448     for (unsigned i = 0, e = CallSites.size(); i != e; ++i) {
449       if (i) OS << ", ";
450       WriteAsOperand(OS, CallSites[i].getCalledValue());
451     }      
452   }
453   OS << "\n";
454 }
455
456 void AliasSetTracker::print(std::ostream &OS) const {
457   OS << "Alias Set Tracker: " << AliasSets.size() << " alias sets for "
458      << PointerMap.size() << " pointer values.\n";
459   for (const_iterator I = begin(), E = end(); I != E; ++I)
460     I->print(OS);
461   OS << "\n";
462 }
463
464 void AliasSet::dump() const { print (std::cerr); }
465 void AliasSetTracker::dump() const { print(std::cerr); }
466
467 //===----------------------------------------------------------------------===//
468 //                            AliasSetPrinter Pass
469 //===----------------------------------------------------------------------===//
470
471 namespace {
472   class AliasSetPrinter : public FunctionPass {
473     AliasSetTracker *Tracker;
474   public:
475     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
476       AU.setPreservesAll();
477       AU.addRequired<AliasAnalysis>();
478     }
479
480     virtual bool runOnFunction(Function &F) {
481       Tracker = new AliasSetTracker(getAnalysis<AliasAnalysis>());
482
483       for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
484         Tracker->add(&*I);
485       return false;
486     }
487
488     /// print - Convert to human readable form
489     virtual void print(std::ostream &OS) const {
490       Tracker->print(OS);
491     }
492
493     virtual void releaseMemory() {
494       delete Tracker;
495     }
496   };
497   RegisterPass<AliasSetPrinter> X("print-alias-sets", "Alias Set Printer",
498                                   PassInfo::Analysis | PassInfo::Optimization);
499 }