LLVM API Documentation

AliasSetTracker.h
Go to the documentation of this file.
00001 //===- llvm/Analysis/AliasSetTracker.h - Build Alias Sets -------*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file defines two classes: AliasSetTracker and AliasSet.  These interface
00011 // are used to classify a collection of pointer references into a maximal number
00012 // of disjoint sets.  Each AliasSet object constructed by the AliasSetTracker
00013 // object refers to memory disjoint from the other sets.
00014 //
00015 //===----------------------------------------------------------------------===//
00016 
00017 #ifndef LLVM_ANALYSIS_ALIASSETTRACKER_H
00018 #define LLVM_ANALYSIS_ALIASSETTRACKER_H
00019 
00020 #include "llvm/ADT/DenseMap.h"
00021 #include "llvm/ADT/ilist.h"
00022 #include "llvm/ADT/ilist_node.h"
00023 #include "llvm/Support/ValueHandle.h"
00024 #include <vector>
00025 
00026 namespace llvm {
00027 
00028 class AliasAnalysis;
00029 class LoadInst;
00030 class StoreInst;
00031 class VAArgInst;
00032 class AliasSetTracker;
00033 class AliasSet;
00034 
00035 class AliasSet : public ilist_node<AliasSet> {
00036   friend class AliasSetTracker;
00037 
00038   class PointerRec {
00039     Value *Val;  // The pointer this record corresponds to.
00040     PointerRec **PrevInList, *NextInList;
00041     AliasSet *AS;
00042     uint64_t Size;
00043     const MDNode *TBAAInfo;
00044   public:
00045     PointerRec(Value *V)
00046       : Val(V), PrevInList(0), NextInList(0), AS(0), Size(0),
00047         TBAAInfo(DenseMapInfo<const MDNode *>::getEmptyKey()) {}
00048 
00049     Value *getValue() const { return Val; }
00050     
00051     PointerRec *getNext() const { return NextInList; }
00052     bool hasAliasSet() const { return AS != 0; }
00053 
00054     PointerRec** setPrevInList(PointerRec **PIL) {
00055       PrevInList = PIL;
00056       return &NextInList;
00057     }
00058 
00059     void updateSizeAndTBAAInfo(uint64_t NewSize, const MDNode *NewTBAAInfo) {
00060       if (NewSize > Size) Size = NewSize;
00061 
00062       if (TBAAInfo == DenseMapInfo<const MDNode *>::getEmptyKey())
00063         // We don't have a TBAAInfo yet. Set it to NewTBAAInfo.
00064         TBAAInfo = NewTBAAInfo;
00065       else if (TBAAInfo != NewTBAAInfo)
00066         // NewTBAAInfo conflicts with TBAAInfo.
00067         TBAAInfo = DenseMapInfo<const MDNode *>::getTombstoneKey();
00068     }
00069 
00070     uint64_t getSize() const { return Size; }
00071 
00072     /// getTBAAInfo - Return the TBAAInfo, or null if there is no
00073     /// information or conflicting information.
00074     const MDNode *getTBAAInfo() const {
00075       // If we have missing or conflicting TBAAInfo, return null.
00076       if (TBAAInfo == DenseMapInfo<const MDNode *>::getEmptyKey() ||
00077           TBAAInfo == DenseMapInfo<const MDNode *>::getTombstoneKey())
00078         return 0;
00079       return TBAAInfo;
00080     }
00081 
00082     AliasSet *getAliasSet(AliasSetTracker &AST) {
00083       assert(AS && "No AliasSet yet!");
00084       if (AS->Forward) {
00085         AliasSet *OldAS = AS;
00086         AS = OldAS->getForwardedTarget(AST);
00087         AS->addRef();
00088         OldAS->dropRef(AST);
00089       }
00090       return AS;
00091     }
00092 
00093     void setAliasSet(AliasSet *as) {
00094       assert(AS == 0 && "Already have an alias set!");
00095       AS = as;
00096     }
00097 
00098     void eraseFromList() {
00099       if (NextInList) NextInList->PrevInList = PrevInList;
00100       *PrevInList = NextInList;
00101       if (AS->PtrListEnd == &NextInList) {
00102         AS->PtrListEnd = PrevInList;
00103         assert(*AS->PtrListEnd == 0 && "List not terminated right!");
00104       }
00105       delete this;
00106     }
00107   };
00108 
00109   PointerRec *PtrList, **PtrListEnd;  // Doubly linked list of nodes.
00110   AliasSet *Forward;             // Forwarding pointer.
00111 
00112   // All instructions without a specific address in this alias set.
00113   std::vector<AssertingVH<Instruction> > UnknownInsts;
00114 
00115   // RefCount - Number of nodes pointing to this AliasSet plus the number of
00116   // AliasSets forwarding to it.
00117   unsigned RefCount : 28;
00118 
00119   /// AccessType - Keep track of whether this alias set merely refers to the
00120   /// locations of memory, whether it modifies the memory, or whether it does
00121   /// both.  The lattice goes from "NoModRef" to either Refs or Mods, then to
00122   /// ModRef as necessary.
00123   ///
00124   enum AccessType {
00125     NoModRef = 0, Refs = 1,         // Ref = bit 1
00126     Mods     = 2, ModRef = 3        // Mod = bit 2
00127   };
00128   unsigned AccessTy : 2;
00129 
00130   /// AliasType - Keep track the relationships between the pointers in the set.
00131   /// Lattice goes from MustAlias to MayAlias.
00132   ///
00133   enum AliasType {
00134     MustAlias = 0, MayAlias = 1
00135   };
00136   unsigned AliasTy : 1;
00137 
00138   // Volatile - True if this alias set contains volatile loads or stores.
00139   bool Volatile : 1;
00140 
00141   void addRef() { ++RefCount; }
00142   void dropRef(AliasSetTracker &AST) {
00143     assert(RefCount >= 1 && "Invalid reference count detected!");
00144     if (--RefCount == 0)
00145       removeFromTracker(AST);
00146   }
00147 
00148   Instruction *getUnknownInst(unsigned i) const {
00149     assert(i < UnknownInsts.size());
00150     return UnknownInsts[i];
00151   }
00152   
00153 public:
00154   /// Accessors...
00155   bool isRef() const { return AccessTy & Refs; }
00156   bool isMod() const { return AccessTy & Mods; }
00157   bool isMustAlias() const { return AliasTy == MustAlias; }
00158   bool isMayAlias()  const { return AliasTy == MayAlias; }
00159 
00160   // isVolatile - Return true if this alias set contains volatile loads or
00161   // stores.
00162   bool isVolatile() const { return Volatile; }
00163 
00164   /// isForwardingAliasSet - Return true if this alias set should be ignored as
00165   /// part of the AliasSetTracker object.
00166   bool isForwardingAliasSet() const { return Forward; }
00167 
00168   /// mergeSetIn - Merge the specified alias set into this alias set...
00169   ///
00170   void mergeSetIn(AliasSet &AS, AliasSetTracker &AST);
00171 
00172   // Alias Set iteration - Allow access to all of the pointer which are part of
00173   // this alias set...
00174   class iterator;
00175   iterator begin() const { return iterator(PtrList); }
00176   iterator end()   const { return iterator(); }
00177   bool empty() const { return PtrList == 0; }
00178 
00179   void print(raw_ostream &OS) const;
00180   void dump() const;
00181 
00182   /// Define an iterator for alias sets... this is just a forward iterator.
00183   class iterator : public std::iterator<std::forward_iterator_tag,
00184                                         PointerRec, ptrdiff_t> {
00185     PointerRec *CurNode;
00186   public:
00187     explicit iterator(PointerRec *CN = 0) : CurNode(CN) {}
00188 
00189     bool operator==(const iterator& x) const {
00190       return CurNode == x.CurNode;
00191     }
00192     bool operator!=(const iterator& x) const { return !operator==(x); }
00193 
00194     const iterator &operator=(const iterator &I) {
00195       CurNode = I.CurNode;
00196       return *this;
00197     }
00198 
00199     value_type &operator*() const {
00200       assert(CurNode && "Dereferencing AliasSet.end()!");
00201       return *CurNode;
00202     }
00203     value_type *operator->() const { return &operator*(); }
00204 
00205     Value *getPointer() const { return CurNode->getValue(); }
00206     uint64_t getSize() const { return CurNode->getSize(); }
00207     const MDNode *getTBAAInfo() const { return CurNode->getTBAAInfo(); }
00208 
00209     iterator& operator++() {                // Preincrement
00210       assert(CurNode && "Advancing past AliasSet.end()!");
00211       CurNode = CurNode->getNext();
00212       return *this;
00213     }
00214     iterator operator++(int) { // Postincrement
00215       iterator tmp = *this; ++*this; return tmp;
00216     }
00217   };
00218 
00219 private:
00220   // Can only be created by AliasSetTracker. Also, ilist creates one
00221   // to serve as a sentinel.
00222   friend struct ilist_sentinel_traits<AliasSet>;
00223   AliasSet() : PtrList(0), PtrListEnd(&PtrList), Forward(0), RefCount(0),
00224                AccessTy(NoModRef), AliasTy(MustAlias), Volatile(false) {
00225   }
00226 
00227   AliasSet(const AliasSet &AS) LLVM_DELETED_FUNCTION;
00228   void operator=(const AliasSet &AS) LLVM_DELETED_FUNCTION;
00229 
00230   PointerRec *getSomePointer() const {
00231     return PtrList;
00232   }
00233 
00234   /// getForwardedTarget - Return the real alias set this represents.  If this
00235   /// has been merged with another set and is forwarding, return the ultimate
00236   /// destination set.  This also implements the union-find collapsing as well.
00237   AliasSet *getForwardedTarget(AliasSetTracker &AST) {
00238     if (!Forward) return this;
00239 
00240     AliasSet *Dest = Forward->getForwardedTarget(AST);
00241     if (Dest != Forward) {
00242       Dest->addRef();
00243       Forward->dropRef(AST);
00244       Forward = Dest;
00245     }
00246     return Dest;
00247   }
00248 
00249   void removeFromTracker(AliasSetTracker &AST);
00250 
00251   void addPointer(AliasSetTracker &AST, PointerRec &Entry, uint64_t Size,
00252                   const MDNode *TBAAInfo,
00253                   bool KnownMustAlias = false);
00254   void addUnknownInst(Instruction *I, AliasAnalysis &AA);
00255   void removeUnknownInst(Instruction *I) {
00256     for (size_t i = 0, e = UnknownInsts.size(); i != e; ++i)
00257       if (UnknownInsts[i] == I) {
00258         UnknownInsts[i] = UnknownInsts.back();
00259         UnknownInsts.pop_back();
00260         --i; --e;  // Revisit the moved entry.
00261       }
00262   }
00263   void setVolatile() { Volatile = true; }
00264 
00265 public:
00266   /// aliasesPointer - Return true if the specified pointer "may" (or must)
00267   /// alias one of the members in the set.
00268   ///
00269   bool aliasesPointer(const Value *Ptr, uint64_t Size, const MDNode *TBAAInfo,
00270                       AliasAnalysis &AA) const;
00271   bool aliasesUnknownInst(Instruction *Inst, AliasAnalysis &AA) const;
00272 };
00273 
00274 inline raw_ostream& operator<<(raw_ostream &OS, const AliasSet &AS) {
00275   AS.print(OS);
00276   return OS;
00277 }
00278 
00279 
00280 class AliasSetTracker {
00281   /// CallbackVH - A CallbackVH to arrange for AliasSetTracker to be
00282   /// notified whenever a Value is deleted.
00283   class ASTCallbackVH : public CallbackVH {
00284     AliasSetTracker *AST;
00285     virtual void deleted();
00286     virtual void allUsesReplacedWith(Value *);
00287   public:
00288     ASTCallbackVH(Value *V, AliasSetTracker *AST = 0);
00289     ASTCallbackVH &operator=(Value *V);
00290   };
00291   /// ASTCallbackVHDenseMapInfo - Traits to tell DenseMap that tell us how to
00292   /// compare and hash the value handle.
00293   struct ASTCallbackVHDenseMapInfo : public DenseMapInfo<Value *> {};
00294 
00295   AliasAnalysis &AA;
00296   ilist<AliasSet> AliasSets;
00297 
00298   typedef DenseMap<ASTCallbackVH, AliasSet::PointerRec*,
00299                    ASTCallbackVHDenseMapInfo>
00300     PointerMapType;
00301 
00302   // Map from pointers to their node
00303   PointerMapType PointerMap;
00304 
00305 public:
00306   /// AliasSetTracker ctor - Create an empty collection of AliasSets, and use
00307   /// the specified alias analysis object to disambiguate load and store
00308   /// addresses.
00309   explicit AliasSetTracker(AliasAnalysis &aa) : AA(aa) {}
00310   ~AliasSetTracker() { clear(); }
00311 
00312   /// add methods - These methods are used to add different types of
00313   /// instructions to the alias sets.  Adding a new instruction can result in
00314   /// one of three actions happening:
00315   ///
00316   ///   1. If the instruction doesn't alias any other sets, create a new set.
00317   ///   2. If the instruction aliases exactly one set, add it to the set
00318   ///   3. If the instruction aliases multiple sets, merge the sets, and add
00319   ///      the instruction to the result.
00320   ///
00321   /// These methods return true if inserting the instruction resulted in the
00322   /// addition of a new alias set (i.e., the pointer did not alias anything).
00323   ///
00324   bool add(Value *Ptr, uint64_t Size, const MDNode *TBAAInfo); // Add a location
00325   bool add(LoadInst *LI);
00326   bool add(StoreInst *SI);
00327   bool add(VAArgInst *VAAI);
00328   bool add(Instruction *I);       // Dispatch to one of the other add methods...
00329   void add(BasicBlock &BB);       // Add all instructions in basic block
00330   void add(const AliasSetTracker &AST); // Add alias relations from another AST
00331   bool addUnknown(Instruction *I);
00332 
00333   /// remove methods - These methods are used to remove all entries that might
00334   /// be aliased by the specified instruction.  These methods return true if any
00335   /// alias sets were eliminated.
00336   // Remove a location
00337   bool remove(Value *Ptr, uint64_t Size, const MDNode *TBAAInfo);
00338   bool remove(LoadInst *LI);
00339   bool remove(StoreInst *SI);
00340   bool remove(VAArgInst *VAAI);
00341   bool remove(Instruction *I);
00342   void remove(AliasSet &AS);
00343   bool removeUnknown(Instruction *I);
00344   
00345   void clear();
00346 
00347   /// getAliasSets - Return the alias sets that are active.
00348   ///
00349   const ilist<AliasSet> &getAliasSets() const { return AliasSets; }
00350 
00351   /// getAliasSetForPointer - Return the alias set that the specified pointer
00352   /// lives in.  If the New argument is non-null, this method sets the value to
00353   /// true if a new alias set is created to contain the pointer (because the
00354   /// pointer didn't alias anything).
00355   AliasSet &getAliasSetForPointer(Value *P, uint64_t Size,
00356                                   const MDNode *TBAAInfo,
00357                                   bool *New = 0);
00358 
00359   /// getAliasSetForPointerIfExists - Return the alias set containing the
00360   /// location specified if one exists, otherwise return null.
00361   AliasSet *getAliasSetForPointerIfExists(Value *P, uint64_t Size,
00362                                           const MDNode *TBAAInfo) {
00363     return findAliasSetForPointer(P, Size, TBAAInfo);
00364   }
00365 
00366   /// containsPointer - Return true if the specified location is represented by
00367   /// this alias set, false otherwise.  This does not modify the AST object or
00368   /// alias sets.
00369   bool containsPointer(Value *P, uint64_t Size, const MDNode *TBAAInfo) const;
00370 
00371   /// getAliasAnalysis - Return the underlying alias analysis object used by
00372   /// this tracker.
00373   AliasAnalysis &getAliasAnalysis() const { return AA; }
00374 
00375   /// deleteValue method - This method is used to remove a pointer value from
00376   /// the AliasSetTracker entirely.  It should be used when an instruction is
00377   /// deleted from the program to update the AST.  If you don't use this, you
00378   /// would have dangling pointers to deleted instructions.
00379   ///
00380   void deleteValue(Value *PtrVal);
00381 
00382   /// copyValue - This method should be used whenever a preexisting value in the
00383   /// program is copied or cloned, introducing a new value.  Note that it is ok
00384   /// for clients that use this method to introduce the same value multiple
00385   /// times: if the tracker already knows about a value, it will ignore the
00386   /// request.
00387   ///
00388   void copyValue(Value *From, Value *To);
00389 
00390 
00391   typedef ilist<AliasSet>::iterator iterator;
00392   typedef ilist<AliasSet>::const_iterator const_iterator;
00393 
00394   const_iterator begin() const { return AliasSets.begin(); }
00395   const_iterator end()   const { return AliasSets.end(); }
00396 
00397   iterator begin() { return AliasSets.begin(); }
00398   iterator end()   { return AliasSets.end(); }
00399 
00400   void print(raw_ostream &OS) const;
00401   void dump() const;
00402 
00403 private:
00404   friend class AliasSet;
00405   void removeAliasSet(AliasSet *AS);
00406 
00407   // getEntryFor - Just like operator[] on the map, except that it creates an
00408   // entry for the pointer if it doesn't already exist.
00409   AliasSet::PointerRec &getEntryFor(Value *V) {
00410     AliasSet::PointerRec *&Entry = PointerMap[ASTCallbackVH(V, this)];
00411     if (Entry == 0)
00412       Entry = new AliasSet::PointerRec(V);
00413     return *Entry;
00414   }
00415 
00416   AliasSet &addPointer(Value *P, uint64_t Size, const MDNode *TBAAInfo,
00417                        AliasSet::AccessType E,
00418                        bool &NewSet) {
00419     NewSet = false;
00420     AliasSet &AS = getAliasSetForPointer(P, Size, TBAAInfo, &NewSet);
00421     AS.AccessTy |= E;
00422     return AS;
00423   }
00424   AliasSet *findAliasSetForPointer(const Value *Ptr, uint64_t Size,
00425                                    const MDNode *TBAAInfo);
00426 
00427   AliasSet *findAliasSetForUnknownInst(Instruction *Inst);
00428 };
00429 
00430 inline raw_ostream& operator<<(raw_ostream &OS, const AliasSetTracker &AST) {
00431   AST.print(OS);
00432   return OS;
00433 }
00434 
00435 } // End llvm namespace
00436 
00437 #endif