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