LLVM API Documentation

SmallPtrSet.h
Go to the documentation of this file.
00001 //===- llvm/ADT/SmallPtrSet.h - 'Normally small' pointer set ----*- 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 the SmallPtrSet class.  See the doxygen comment for
00011 // SmallPtrSetImpl for more details on the algorithm used.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #ifndef LLVM_ADT_SMALLPTRSET_H
00016 #define LLVM_ADT_SMALLPTRSET_H
00017 
00018 #include "llvm/Support/Compiler.h"
00019 #include "llvm/Support/DataTypes.h"
00020 #include "llvm/Support/PointerLikeTypeTraits.h"
00021 #include <cassert>
00022 #include <cstddef>
00023 #include <cstring>
00024 #include <iterator>
00025 
00026 namespace llvm {
00027 
00028 class SmallPtrSetIteratorImpl;
00029 
00030 /// SmallPtrSetImpl - This is the common code shared among all the
00031 /// SmallPtrSet<>'s, which is almost everything.  SmallPtrSet has two modes, one
00032 /// for small and one for large sets.
00033 ///
00034 /// Small sets use an array of pointers allocated in the SmallPtrSet object,
00035 /// which is treated as a simple array of pointers.  When a pointer is added to
00036 /// the set, the array is scanned to see if the element already exists, if not
00037 /// the element is 'pushed back' onto the array.  If we run out of space in the
00038 /// array, we grow into the 'large set' case.  SmallSet should be used when the
00039 /// sets are often small.  In this case, no memory allocation is used, and only
00040 /// light-weight and cache-efficient scanning is used.
00041 ///
00042 /// Large sets use a classic exponentially-probed hash table.  Empty buckets are
00043 /// represented with an illegal pointer value (-1) to allow null pointers to be
00044 /// inserted.  Tombstones are represented with another illegal pointer value
00045 /// (-2), to allow deletion.  The hash table is resized when the table is 3/4 or
00046 /// more.  When this happens, the table is doubled in size.
00047 ///
00048 class SmallPtrSetImpl {
00049   friend class SmallPtrSetIteratorImpl;
00050 protected:
00051   /// SmallArray - Points to a fixed size set of buckets, used in 'small mode'.
00052   const void **SmallArray;
00053   /// CurArray - This is the current set of buckets.  If equal to SmallArray,
00054   /// then the set is in 'small mode'.
00055   const void **CurArray;
00056   /// CurArraySize - The allocated size of CurArray, always a power of two.
00057   unsigned CurArraySize;
00058 
00059   // If small, this is # elts allocated consecutively
00060   unsigned NumElements;
00061   unsigned NumTombstones;
00062 
00063   // Helper to copy construct a SmallPtrSet.
00064   SmallPtrSetImpl(const void **SmallStorage, const SmallPtrSetImpl& that);
00065   explicit SmallPtrSetImpl(const void **SmallStorage, unsigned SmallSize) :
00066     SmallArray(SmallStorage), CurArray(SmallStorage), CurArraySize(SmallSize) {
00067     assert(SmallSize && (SmallSize & (SmallSize-1)) == 0 &&
00068            "Initial size must be a power of two!");
00069     clear();
00070   }
00071   ~SmallPtrSetImpl();
00072 
00073 public:
00074   bool empty() const { return size() == 0; }
00075   unsigned size() const { return NumElements; }
00076 
00077   void clear() {
00078     // If the capacity of the array is huge, and the # elements used is small,
00079     // shrink the array.
00080     if (!isSmall() && NumElements*4 < CurArraySize && CurArraySize > 32)
00081       return shrink_and_clear();
00082 
00083     // Fill the array with empty markers.
00084     memset(CurArray, -1, CurArraySize*sizeof(void*));
00085     NumElements = 0;
00086     NumTombstones = 0;
00087   }
00088 
00089 protected:
00090   static void *getTombstoneMarker() { return reinterpret_cast<void*>(-2); }
00091   static void *getEmptyMarker() {
00092     // Note that -1 is chosen to make clear() efficiently implementable with
00093     // memset and because it's not a valid pointer value.
00094     return reinterpret_cast<void*>(-1);
00095   }
00096 
00097   /// insert_imp - This returns true if the pointer was new to the set, false if
00098   /// it was already in the set.  This is hidden from the client so that the
00099   /// derived class can check that the right type of pointer is passed in.
00100   bool insert_imp(const void * Ptr);
00101 
00102   /// erase_imp - If the set contains the specified pointer, remove it and
00103   /// return true, otherwise return false.  This is hidden from the client so
00104   /// that the derived class can check that the right type of pointer is passed
00105   /// in.
00106   bool erase_imp(const void * Ptr);
00107 
00108   bool count_imp(const void * Ptr) const {
00109     if (isSmall()) {
00110       // Linear search for the item.
00111       for (const void *const *APtr = SmallArray,
00112                       *const *E = SmallArray+NumElements; APtr != E; ++APtr)
00113         if (*APtr == Ptr)
00114           return true;
00115       return false;
00116     }
00117 
00118     // Big set case.
00119     return *FindBucketFor(Ptr) == Ptr;
00120   }
00121 
00122 private:
00123   bool isSmall() const { return CurArray == SmallArray; }
00124 
00125   const void * const *FindBucketFor(const void *Ptr) const;
00126   void shrink_and_clear();
00127 
00128   /// Grow - Allocate a larger backing store for the buckets and move it over.
00129   void Grow(unsigned NewSize);
00130 
00131   void operator=(const SmallPtrSetImpl &RHS) LLVM_DELETED_FUNCTION;
00132 protected:
00133   /// swap - Swaps the elements of two sets.
00134   /// Note: This method assumes that both sets have the same small size.
00135   void swap(SmallPtrSetImpl &RHS);
00136 
00137   void CopyFrom(const SmallPtrSetImpl &RHS);
00138 };
00139 
00140 /// SmallPtrSetIteratorImpl - This is the common base class shared between all
00141 /// instances of SmallPtrSetIterator.
00142 class SmallPtrSetIteratorImpl {
00143 protected:
00144   const void *const *Bucket;
00145   const void *const *End;
00146 public:
00147   explicit SmallPtrSetIteratorImpl(const void *const *BP, const void*const *E)
00148     : Bucket(BP), End(E) {
00149       AdvanceIfNotValid();
00150   }
00151 
00152   bool operator==(const SmallPtrSetIteratorImpl &RHS) const {
00153     return Bucket == RHS.Bucket;
00154   }
00155   bool operator!=(const SmallPtrSetIteratorImpl &RHS) const {
00156     return Bucket != RHS.Bucket;
00157   }
00158 
00159 protected:
00160   /// AdvanceIfNotValid - If the current bucket isn't valid, advance to a bucket
00161   /// that is.   This is guaranteed to stop because the end() bucket is marked
00162   /// valid.
00163   void AdvanceIfNotValid() {
00164     assert(Bucket <= End);
00165     while (Bucket != End &&
00166            (*Bucket == SmallPtrSetImpl::getEmptyMarker() ||
00167             *Bucket == SmallPtrSetImpl::getTombstoneMarker()))
00168       ++Bucket;
00169   }
00170 };
00171 
00172 /// SmallPtrSetIterator - This implements a const_iterator for SmallPtrSet.
00173 template<typename PtrTy>
00174 class SmallPtrSetIterator : public SmallPtrSetIteratorImpl {
00175   typedef PointerLikeTypeTraits<PtrTy> PtrTraits;
00176   
00177 public:
00178   typedef PtrTy                     value_type;
00179   typedef PtrTy                     reference;
00180   typedef PtrTy                     pointer;
00181   typedef std::ptrdiff_t            difference_type;
00182   typedef std::forward_iterator_tag iterator_category;
00183   
00184   explicit SmallPtrSetIterator(const void *const *BP, const void *const *E)
00185     : SmallPtrSetIteratorImpl(BP, E) {}
00186 
00187   // Most methods provided by baseclass.
00188 
00189   const PtrTy operator*() const {
00190     assert(Bucket < End);
00191     return PtrTraits::getFromVoidPointer(const_cast<void*>(*Bucket));
00192   }
00193 
00194   inline SmallPtrSetIterator& operator++() {          // Preincrement
00195     ++Bucket;
00196     AdvanceIfNotValid();
00197     return *this;
00198   }
00199 
00200   SmallPtrSetIterator operator++(int) {        // Postincrement
00201     SmallPtrSetIterator tmp = *this; ++*this; return tmp;
00202   }
00203 };
00204 
00205 /// RoundUpToPowerOfTwo - This is a helper template that rounds N up to the next
00206 /// power of two (which means N itself if N is already a power of two).
00207 template<unsigned N>
00208 struct RoundUpToPowerOfTwo;
00209 
00210 /// RoundUpToPowerOfTwoH - If N is not a power of two, increase it.  This is a
00211 /// helper template used to implement RoundUpToPowerOfTwo.
00212 template<unsigned N, bool isPowerTwo>
00213 struct RoundUpToPowerOfTwoH {
00214   enum { Val = N };
00215 };
00216 template<unsigned N>
00217 struct RoundUpToPowerOfTwoH<N, false> {
00218   enum {
00219     // We could just use NextVal = N+1, but this converges faster.  N|(N-1) sets
00220     // the right-most zero bits to one all at once, e.g. 0b0011000 -> 0b0011111.
00221     Val = RoundUpToPowerOfTwo<(N|(N-1)) + 1>::Val
00222   };
00223 };
00224 
00225 template<unsigned N>
00226 struct RoundUpToPowerOfTwo {
00227   enum { Val = RoundUpToPowerOfTwoH<N, (N&(N-1)) == 0>::Val };
00228 };
00229   
00230 
00231 /// SmallPtrSet - This class implements a set which is optimized for holding
00232 /// SmallSize or less elements.  This internally rounds up SmallSize to the next
00233 /// power of two if it is not already a power of two.  See the comments above
00234 /// SmallPtrSetImpl for details of the algorithm.
00235 template<class PtrType, unsigned SmallSize>
00236 class SmallPtrSet : public SmallPtrSetImpl {
00237   // Make sure that SmallSize is a power of two, round up if not.
00238   enum { SmallSizePowTwo = RoundUpToPowerOfTwo<SmallSize>::Val };
00239   /// SmallStorage - Fixed size storage used in 'small mode'.
00240   const void *SmallStorage[SmallSizePowTwo];
00241   typedef PointerLikeTypeTraits<PtrType> PtrTraits;
00242 public:
00243   SmallPtrSet() : SmallPtrSetImpl(SmallStorage, SmallSizePowTwo) {}
00244   SmallPtrSet(const SmallPtrSet &that) : SmallPtrSetImpl(SmallStorage, that) {}
00245 
00246   template<typename It>
00247   SmallPtrSet(It I, It E) : SmallPtrSetImpl(SmallStorage, SmallSizePowTwo) {
00248     insert(I, E);
00249   }
00250 
00251   /// insert - This returns true if the pointer was new to the set, false if it
00252   /// was already in the set.
00253   bool insert(PtrType Ptr) {
00254     return insert_imp(PtrTraits::getAsVoidPointer(Ptr));
00255   }
00256 
00257   /// erase - If the set contains the specified pointer, remove it and return
00258   /// true, otherwise return false.
00259   bool erase(PtrType Ptr) {
00260     return erase_imp(PtrTraits::getAsVoidPointer(Ptr));
00261   }
00262 
00263   /// count - Return true if the specified pointer is in the set.
00264   bool count(PtrType Ptr) const {
00265     return count_imp(PtrTraits::getAsVoidPointer(Ptr));
00266   }
00267 
00268   template <typename IterT>
00269   void insert(IterT I, IterT E) {
00270     for (; I != E; ++I)
00271       insert(*I);
00272   }
00273 
00274   typedef SmallPtrSetIterator<PtrType> iterator;
00275   typedef SmallPtrSetIterator<PtrType> const_iterator;
00276   inline iterator begin() const {
00277     return iterator(CurArray, CurArray+CurArraySize);
00278   }
00279   inline iterator end() const {
00280     return iterator(CurArray+CurArraySize, CurArray+CurArraySize);
00281   }
00282 
00283   // Allow assignment from any smallptrset with the same element type even if it
00284   // doesn't have the same smallsize.
00285   const SmallPtrSet<PtrType, SmallSize>&
00286   operator=(const SmallPtrSet<PtrType, SmallSize> &RHS) {
00287     CopyFrom(RHS);
00288     return *this;
00289   }
00290 
00291   /// swap - Swaps the elements of two sets.
00292   void swap(SmallPtrSet<PtrType, SmallSize> &RHS) {
00293     SmallPtrSetImpl::swap(RHS);
00294   }
00295 };
00296 
00297 }
00298 
00299 namespace std {
00300   /// Implement std::swap in terms of SmallPtrSet swap.
00301   template<class T, unsigned N>
00302   inline void swap(llvm::SmallPtrSet<T, N> &LHS, llvm::SmallPtrSet<T, N> &RHS) {
00303     LHS.swap(RHS);
00304   }
00305 }
00306 
00307 #endif