eliminate RegisterOpt. It does the same thing as RegisterPass.
[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/Type.h"
19 #include "llvm/Target/TargetData.h"
20 #include "llvm/Assembly/Writer.h"
21 #include "llvm/Support/InstIterator.h"
22 #include <iostream>
23 using namespace llvm;
24
25 /// mergeSetIn - Merge the specified alias set into this alias set.
26 ///
27 void AliasSet::mergeSetIn(AliasSet &AS, AliasSetTracker &AST) {
28   assert(!AS.Forward && "Alias set is already forwarding!");
29   assert(!Forward && "This set is a forwarding set!!");
30
31   // Update the alias and access types of this set...
32   AccessTy |= AS.AccessTy;
33   AliasTy  |= AS.AliasTy;
34
35   if (AliasTy == MustAlias) {
36     // Check that these two merged sets really are must aliases.  Since both
37     // used to be must-alias sets, we can just check any pointer from each set
38     // for aliasing.
39     AliasAnalysis &AA = AST.getAliasAnalysis();
40     HashNodePair *L = getSomePointer();
41     HashNodePair *R = AS.getSomePointer();
42
43     // If the pointers are not a must-alias pair, this set becomes a may alias.
44     if (AA.alias(L->first, L->second.getSize(), R->first, R->second.getSize())
45         != AliasAnalysis::MustAlias)
46       AliasTy = MayAlias;
47   }
48
49   if (CallSites.empty()) {            // Merge call sites...
50     if (!AS.CallSites.empty())
51       std::swap(CallSites, AS.CallSites);
52   } else if (!AS.CallSites.empty()) {
53     CallSites.insert(CallSites.end(), AS.CallSites.begin(), AS.CallSites.end());
54     AS.CallSites.clear();
55   }
56
57   AS.Forward = this;  // Forward across AS now...
58   addRef();           // AS is now pointing to us...
59
60   // Merge the list of constituent pointers...
61   if (AS.PtrList) {
62     *PtrListEnd = AS.PtrList;
63     AS.PtrList->second.setPrevInList(PtrListEnd);
64     PtrListEnd = AS.PtrListEnd;
65
66     AS.PtrList = 0;
67     AS.PtrListEnd = &AS.PtrList;
68     assert(*AS.PtrListEnd == 0 && "End of list is not null?");
69   }
70 }
71
72 void AliasSetTracker::removeAliasSet(AliasSet *AS) {
73   if (AliasSet *Fwd = AS->Forward) {
74     Fwd->dropRef(*this);
75     AS->Forward = 0;
76   }
77   AliasSets.erase(AS);
78 }
79
80 void AliasSet::removeFromTracker(AliasSetTracker &AST) {
81   assert(RefCount == 0 && "Cannot remove non-dead alias set from tracker!");
82   AST.removeAliasSet(this);
83 }
84
85 void AliasSet::addPointer(AliasSetTracker &AST, HashNodePair &Entry,
86                           unsigned Size, bool KnownMustAlias) {
87   assert(!Entry.second.hasAliasSet() && "Entry already in set!");
88
89   // Check to see if we have to downgrade to _may_ alias.
90   if (isMustAlias() && !KnownMustAlias)
91     if (HashNodePair *P = getSomePointer()) {
92       AliasAnalysis &AA = AST.getAliasAnalysis();
93       AliasAnalysis::AliasResult Result =
94         AA.alias(P->first, P->second.getSize(), Entry.first, Size);
95       if (Result == AliasAnalysis::MayAlias)
96         AliasTy = MayAlias;
97       else                  // First entry of must alias must have maximum size!
98         P->second.updateSize(Size);
99       assert(Result != AliasAnalysis::NoAlias && "Cannot be part of must set!");
100     }
101
102   Entry.second.setAliasSet(this);
103   Entry.second.updateSize(Size);
104
105   // Add it to the end of the list...
106   assert(*PtrListEnd == 0 && "End of list is not null?");
107   *PtrListEnd = &Entry;
108   PtrListEnd = Entry.second.setPrevInList(PtrListEnd);
109   assert(*PtrListEnd == 0 && "End of list is not null?");
110   addRef();               // Entry points to alias set...
111 }
112
113 void AliasSet::addCallSite(CallSite CS, AliasAnalysis &AA) {
114   CallSites.push_back(CS);
115
116   if (Function *F = CS.getCalledFunction()) {
117     AliasAnalysis::ModRefBehavior Behavior = AA.getModRefBehavior(F, CS);
118     if (Behavior == AliasAnalysis::DoesNotAccessMemory)
119       return;
120     else if (Behavior == AliasAnalysis::OnlyReadsMemory) {
121       AliasTy = MayAlias;
122       AccessTy |= Refs;
123       return;
124     }
125   }
126
127   // FIXME: This should use mod/ref information to make this not suck so bad
128   AliasTy = MayAlias;
129   AccessTy = ModRef;
130 }
131
132 /// aliasesPointer - Return true if the specified pointer "may" (or must)
133 /// alias one of the members in the set.
134 ///
135 bool AliasSet::aliasesPointer(const Value *Ptr, unsigned Size,
136                               AliasAnalysis &AA) const {
137   if (AliasTy == MustAlias) {
138     assert(CallSites.empty() && "Illegal must alias set!");
139
140     // If this is a set of MustAliases, only check to see if the pointer aliases
141     // SOME value in the set...
142     HashNodePair *SomePtr = getSomePointer();
143     assert(SomePtr && "Empty must-alias set??");
144     return AA.alias(SomePtr->first, SomePtr->second.getSize(), Ptr, Size);
145   }
146
147   // If this is a may-alias set, we have to check all of the pointers in the set
148   // to be sure it doesn't alias the set...
149   for (iterator I = begin(), E = end(); I != E; ++I)
150     if (AA.alias(Ptr, Size, I.getPointer(), I.getSize()))
151       return true;
152
153   // Check the call sites list and invoke list...
154   if (!CallSites.empty()) {
155     if (AA.hasNoModRefInfoForCalls())
156       return true;
157
158     for (unsigned i = 0, e = CallSites.size(); i != e; ++i)
159       if (AA.getModRefInfo(CallSites[i], const_cast<Value*>(Ptr), Size)
160                    != AliasAnalysis::NoModRef)
161         return true;
162   }
163
164   return false;
165 }
166
167 bool AliasSet::aliasesCallSite(CallSite CS, AliasAnalysis &AA) const {
168   if (Function *F = CS.getCalledFunction())
169     if (AA.doesNotAccessMemory(F))
170       return false;
171
172   if (AA.hasNoModRefInfoForCalls())
173     return true;
174
175   for (unsigned i = 0, e = CallSites.size(); i != e; ++i)
176     if (AA.getModRefInfo(CallSites[i], CS) != AliasAnalysis::NoModRef ||
177         AA.getModRefInfo(CS, CallSites[i]) != AliasAnalysis::NoModRef)
178       return true;
179
180   for (iterator I = begin(), E = end(); I != E; ++I)
181     if (AA.getModRefInfo(CS, I.getPointer(), I.getSize()) !=
182            AliasAnalysis::NoModRef)
183       return true;
184
185   return false;
186 }
187
188
189 /// findAliasSetForPointer - Given a pointer, find the one alias set to put the
190 /// instruction referring to the pointer into.  If there are multiple alias sets
191 /// that may alias the pointer, merge them together and return the unified set.
192 ///
193 AliasSet *AliasSetTracker::findAliasSetForPointer(const Value *Ptr,
194                                                   unsigned Size) {
195   AliasSet *FoundSet = 0;
196   for (iterator I = begin(), E = end(); I != E; ++I)
197     if (!I->Forward && I->aliasesPointer(Ptr, Size, AA)) {
198       if (FoundSet == 0) {  // If this is the first alias set ptr can go into.
199         FoundSet = I;       // Remember it.
200       } else {              // Otherwise, we must merge the sets.
201         FoundSet->mergeSetIn(*I, *this);     // Merge in contents.
202       }
203     }
204
205   return FoundSet;
206 }
207
208 /// containsPointer - Return true if the specified location is represented by
209 /// this alias set, false otherwise.  This does not modify the AST object or
210 /// alias sets.
211 bool AliasSetTracker::containsPointer(Value *Ptr, unsigned Size) const {
212   for (const_iterator I = begin(), E = end(); I != E; ++I)
213     if (!I->Forward && I->aliasesPointer(Ptr, Size, AA))
214       return true;
215   return false;
216 }
217
218
219
220 AliasSet *AliasSetTracker::findAliasSetForCallSite(CallSite CS) {
221   AliasSet *FoundSet = 0;
222   for (iterator I = begin(), E = end(); I != E; ++I)
223     if (!I->Forward && I->aliasesCallSite(CS, AA)) {
224       if (FoundSet == 0) {  // If this is the first alias set ptr can go into.
225         FoundSet = I;       // Remember it.
226       } else if (!I->Forward) {     // Otherwise, we must merge the sets.
227         FoundSet->mergeSetIn(*I, *this);     // Merge in contents.
228       }
229     }
230
231   return FoundSet;
232 }
233
234
235
236
237 /// getAliasSetForPointer - Return the alias set that the specified pointer
238 /// lives in...
239 AliasSet &AliasSetTracker::getAliasSetForPointer(Value *Pointer, unsigned Size,
240                                                  bool *New) {
241   AliasSet::HashNodePair &Entry = getEntryFor(Pointer);
242
243   // Check to see if the pointer is already known...
244   if (Entry.second.hasAliasSet()) {
245     Entry.second.updateSize(Size);
246     // Return the set!
247     return *Entry.second.getAliasSet(*this)->getForwardedTarget(*this);
248   } else if (AliasSet *AS = findAliasSetForPointer(Pointer, Size)) {
249     // Add it to the alias set it aliases...
250     AS->addPointer(*this, Entry, Size);
251     return *AS;
252   } else {
253     if (New) *New = true;
254     // Otherwise create a new alias set to hold the loaded pointer...
255     AliasSets.push_back(new AliasSet());
256     AliasSets.back().addPointer(*this, Entry, Size);
257     return AliasSets.back();
258   }
259 }
260
261 bool AliasSetTracker::add(Value *Ptr, unsigned Size) {
262   bool NewPtr;
263   addPointer(Ptr, Size, AliasSet::NoModRef, NewPtr);
264   return NewPtr;
265 }
266
267
268 bool AliasSetTracker::add(LoadInst *LI) {
269   bool NewPtr;
270   AliasSet &AS = addPointer(LI->getOperand(0),
271                             AA.getTargetData().getTypeSize(LI->getType()),
272                             AliasSet::Refs, NewPtr);
273   if (LI->isVolatile()) AS.setVolatile();
274   return NewPtr;
275 }
276
277 bool AliasSetTracker::add(StoreInst *SI) {
278   bool NewPtr;
279   Value *Val = SI->getOperand(0);
280   AliasSet &AS = addPointer(SI->getOperand(1),
281                             AA.getTargetData().getTypeSize(Val->getType()),
282                             AliasSet::Mods, NewPtr);
283   if (SI->isVolatile()) AS.setVolatile();
284   return NewPtr;
285 }
286
287 bool AliasSetTracker::add(FreeInst *FI) {
288   bool NewPtr;
289   AliasSet &AS = addPointer(FI->getOperand(0), ~0,
290                             AliasSet::Mods, NewPtr);
291
292   // Free operations are volatile ops (cannot be moved).
293   AS.setVolatile();
294   return NewPtr;
295 }
296
297
298 bool AliasSetTracker::add(CallSite CS) {
299   if (Function *F = CS.getCalledFunction())
300     if (AA.doesNotAccessMemory(F))
301       return true; // doesn't alias anything
302
303   AliasSet *AS = findAliasSetForCallSite(CS);
304   if (!AS) {
305     AliasSets.push_back(new AliasSet());
306     AS = &AliasSets.back();
307     AS->addCallSite(CS, AA);
308     return true;
309   } else {
310     AS->addCallSite(CS, AA);
311     return false;
312   }
313 }
314
315 bool AliasSetTracker::add(Instruction *I) {
316   // Dispatch to one of the other add methods...
317   if (LoadInst *LI = dyn_cast<LoadInst>(I))
318     return add(LI);
319   else if (StoreInst *SI = dyn_cast<StoreInst>(I))
320     return add(SI);
321   else if (CallInst *CI = dyn_cast<CallInst>(I))
322     return add(CI);
323   else if (InvokeInst *II = dyn_cast<InvokeInst>(I))
324     return add(II);
325   else if (FreeInst *FI = dyn_cast<FreeInst>(I))
326     return add(FI);
327   return true;
328 }
329
330 void AliasSetTracker::add(BasicBlock &BB) {
331   for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
332     add(I);
333 }
334
335 void AliasSetTracker::add(const AliasSetTracker &AST) {
336   assert(&AA == &AST.AA &&
337          "Merging AliasSetTracker objects with different Alias Analyses!");
338
339   // Loop over all of the alias sets in AST, adding the pointers contained
340   // therein into the current alias sets.  This can cause alias sets to be
341   // merged together in the current AST.
342   for (const_iterator I = AST.begin(), E = AST.end(); I != E; ++I)
343     if (!I->Forward) {   // Ignore forwarding alias sets
344       AliasSet &AS = const_cast<AliasSet&>(*I);
345
346       // If there are any call sites in the alias set, add them to this AST.
347       for (unsigned i = 0, e = AS.CallSites.size(); i != e; ++i)
348         add(AS.CallSites[i]);
349
350       // Loop over all of the pointers in this alias set...
351       AliasSet::iterator I = AS.begin(), E = AS.end();
352       bool X;
353       for (; I != E; ++I)
354         addPointer(I.getPointer(), I.getSize(),
355                    (AliasSet::AccessType)AS.AccessTy, X);
356     }
357 }
358
359 /// remove - Remove the specified (potentially non-empty) alias set from the
360 /// tracker.
361 void AliasSetTracker::remove(AliasSet &AS) {
362   // Drop all call sites.
363   AS.CallSites.clear();
364   
365   // Clear the alias set.
366   unsigned NumRefs = 0;
367   while (!AS.empty()) {
368     AliasSet::HashNodePair *P = AS.PtrList;
369     
370     // Unlink from the list of values.
371     P->second.removeFromList();
372     
373     // Remember how many references need to be dropped.
374     ++NumRefs;
375
376     // Finally, remove the entry.
377     PointerMap.erase(P->first);
378   }
379   
380   // Stop using the alias set, removing it.
381   AS.RefCount -= NumRefs;
382   if (AS.RefCount == 0)
383     AS.removeFromTracker(*this);
384 }
385
386 bool AliasSetTracker::remove(Value *Ptr, unsigned Size) {
387   AliasSet *AS = findAliasSetForPointer(Ptr, Size);
388   if (!AS) return false;
389   remove(*AS);
390   return true;
391 }
392
393 bool AliasSetTracker::remove(LoadInst *LI) {
394   unsigned Size = AA.getTargetData().getTypeSize(LI->getType());
395   AliasSet *AS = findAliasSetForPointer(LI->getOperand(0), Size);
396   if (!AS) return false;
397   remove(*AS);
398   return true;
399 }
400
401 bool AliasSetTracker::remove(StoreInst *SI) {
402   unsigned Size = AA.getTargetData().getTypeSize(SI->getOperand(0)->getType());
403   AliasSet *AS = findAliasSetForPointer(SI->getOperand(1), Size);
404   if (!AS) return false;
405   remove(*AS);
406   return true;
407 }
408
409 bool AliasSetTracker::remove(FreeInst *FI) {
410   AliasSet *AS = findAliasSetForPointer(FI->getOperand(0), ~0);
411   if (!AS) return false;
412   remove(*AS);
413   return true;
414 }
415
416 bool AliasSetTracker::remove(CallSite CS) {
417   if (Function *F = CS.getCalledFunction())
418     if (AA.doesNotAccessMemory(F))
419       return false; // doesn't alias anything
420
421   AliasSet *AS = findAliasSetForCallSite(CS);
422   if (!AS) return false;
423   remove(*AS);
424   return true;
425 }
426
427 bool AliasSetTracker::remove(Instruction *I) {
428   // Dispatch to one of the other remove methods...
429   if (LoadInst *LI = dyn_cast<LoadInst>(I))
430     return remove(LI);
431   else if (StoreInst *SI = dyn_cast<StoreInst>(I))
432     return remove(SI);
433   else if (CallInst *CI = dyn_cast<CallInst>(I))
434     return remove(CI);
435   else if (FreeInst *FI = dyn_cast<FreeInst>(I))
436     return remove(FI);
437   return true;
438 }
439
440
441 // deleteValue method - This method is used to remove a pointer value from the
442 // AliasSetTracker entirely.  It should be used when an instruction is deleted
443 // from the program to update the AST.  If you don't use this, you would have
444 // dangling pointers to deleted instructions.
445 //
446 void AliasSetTracker::deleteValue(Value *PtrVal) {
447   // Notify the alias analysis implementation that this value is gone.
448   AA.deleteValue(PtrVal);
449
450   // If this is a call instruction, remove the callsite from the appropriate
451   // AliasSet.
452   CallSite CS = CallSite::get(PtrVal);
453   if (CS.getInstruction()) {
454     Function *F = CS.getCalledFunction();
455     if (!F || !AA.doesNotAccessMemory(F)) {
456       if (AliasSet *AS = findAliasSetForCallSite(CS))
457         AS->removeCallSite(CS);
458     }
459   }
460
461   // First, look up the PointerRec for this pointer.
462   hash_map<Value*, AliasSet::PointerRec>::iterator I = PointerMap.find(PtrVal);
463   if (I == PointerMap.end()) return;  // Noop
464
465   // If we found one, remove the pointer from the alias set it is in.
466   AliasSet::HashNodePair &PtrValEnt = *I;
467   AliasSet *AS = PtrValEnt.second.getAliasSet(*this);
468
469   // Unlink from the list of values...
470   PtrValEnt.second.removeFromList();
471   // Stop using the alias set
472   AS->dropRef(*this);
473   PointerMap.erase(I);
474 }
475
476 // copyValue - This method should be used whenever a preexisting value in the
477 // program is copied or cloned, introducing a new value.  Note that it is ok for
478 // clients that use this method to introduce the same value multiple times: if
479 // the tracker already knows about a value, it will ignore the request.
480 //
481 void AliasSetTracker::copyValue(Value *From, Value *To) {
482   // Notify the alias analysis implementation that this value is copied.
483   AA.copyValue(From, To);
484
485   // First, look up the PointerRec for this pointer.
486   hash_map<Value*, AliasSet::PointerRec>::iterator I = PointerMap.find(From);
487   if (I == PointerMap.end() || !I->second.hasAliasSet())
488     return;  // Noop
489
490   AliasSet::HashNodePair &Entry = getEntryFor(To);
491   if (Entry.second.hasAliasSet()) return;    // Already in the tracker!
492
493   // Add it to the alias set it aliases...
494   AliasSet *AS = I->second.getAliasSet(*this);
495   AS->addPointer(*this, Entry, I->second.getSize(), true);
496 }
497
498
499
500 //===----------------------------------------------------------------------===//
501 //               AliasSet/AliasSetTracker Printing Support
502 //===----------------------------------------------------------------------===//
503
504 void AliasSet::print(std::ostream &OS) const {
505   OS << "  AliasSet[" << (void*)this << "," << RefCount << "] ";
506   OS << (AliasTy == MustAlias ? "must" : "may ") << " alias, ";
507   switch (AccessTy) {
508   case NoModRef: OS << "No access "; break;
509   case Refs    : OS << "Ref       "; break;
510   case Mods    : OS << "Mod       "; break;
511   case ModRef  : OS << "Mod/Ref   "; break;
512   default: assert(0 && "Bad value for AccessTy!");
513   }
514   if (isVolatile()) OS << "[volatile] ";
515   if (Forward)
516     OS << " forwarding to " << (void*)Forward;
517
518
519   if (begin() != end()) {
520     OS << "Pointers: ";
521     for (iterator I = begin(), E = end(); I != E; ++I) {
522       if (I != begin()) OS << ", ";
523       WriteAsOperand(OS << "(", I.getPointer());
524       OS << ", " << I.getSize() << ")";
525     }
526   }
527   if (!CallSites.empty()) {
528     OS << "\n    " << CallSites.size() << " Call Sites: ";
529     for (unsigned i = 0, e = CallSites.size(); i != e; ++i) {
530       if (i) OS << ", ";
531       WriteAsOperand(OS, CallSites[i].getCalledValue());
532     }
533   }
534   OS << "\n";
535 }
536
537 void AliasSetTracker::print(std::ostream &OS) const {
538   OS << "Alias Set Tracker: " << AliasSets.size() << " alias sets for "
539      << PointerMap.size() << " pointer values.\n";
540   for (const_iterator I = begin(), E = end(); I != E; ++I)
541     I->print(OS);
542   OS << "\n";
543 }
544
545 void AliasSet::dump() const { print (std::cerr); }
546 void AliasSetTracker::dump() const { print(std::cerr); }
547
548 //===----------------------------------------------------------------------===//
549 //                            AliasSetPrinter Pass
550 //===----------------------------------------------------------------------===//
551
552 namespace {
553   class AliasSetPrinter : public FunctionPass {
554     AliasSetTracker *Tracker;
555   public:
556     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
557       AU.setPreservesAll();
558       AU.addRequired<AliasAnalysis>();
559     }
560
561     virtual bool runOnFunction(Function &F) {
562       Tracker = new AliasSetTracker(getAnalysis<AliasAnalysis>());
563
564       for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
565         Tracker->add(&*I);
566       Tracker->print(std::cerr);
567       delete Tracker;
568       return false;
569     }
570   };
571   RegisterPass<AliasSetPrinter> X("print-alias-sets", "Alias Set Printer");
572 }