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 // SmallPtrSetImplBase 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 /// SmallPtrSetImplBase - 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 SmallPtrSetImplBase {
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   // Helpers to copy and move construct a SmallPtrSet.
00064   SmallPtrSetImplBase(const void **SmallStorage, const SmallPtrSetImplBase &that);
00065   SmallPtrSetImplBase(const void **SmallStorage, unsigned SmallSize,
00066                   SmallPtrSetImplBase &&that);
00067   explicit SmallPtrSetImplBase(const void **SmallStorage, unsigned SmallSize) :
00068     SmallArray(SmallStorage), CurArray(SmallStorage), CurArraySize(SmallSize) {
00069     assert(SmallSize && (SmallSize & (SmallSize-1)) == 0 &&
00070            "Initial size must be a power of two!");
00071     clear();
00072   }
00073   ~SmallPtrSetImplBase();
00074 
00075 public:
00076   typedef unsigned size_type;
00077   bool LLVM_ATTRIBUTE_UNUSED_RESULT empty() const { return size() == 0; }
00078   size_type size() const { return NumElements; }
00079 
00080   void clear() {
00081     // If the capacity of the array is huge, and the # elements used is small,
00082     // shrink the array.
00083     if (!isSmall() && NumElements*4 < CurArraySize && CurArraySize > 32)
00084       return shrink_and_clear();
00085 
00086     // Fill the array with empty markers.
00087     memset(CurArray, -1, CurArraySize*sizeof(void*));
00088     NumElements = 0;
00089     NumTombstones = 0;
00090   }
00091 
00092 protected:
00093   static void *getTombstoneMarker() { return reinterpret_cast<void*>(-2); }
00094   static void *getEmptyMarker() {
00095     // Note that -1 is chosen to make clear() efficiently implementable with
00096     // memset and because it's not a valid pointer value.
00097     return reinterpret_cast<void*>(-1);
00098   }
00099 
00100   /// insert_imp - This returns true if the pointer was new to the set, false if
00101   /// it was already in the set.  This is hidden from the client so that the
00102   /// derived class can check that the right type of pointer is passed in.
00103   bool insert_imp(const void * Ptr);
00104 
00105   /// erase_imp - If the set contains the specified pointer, remove it and
00106   /// return true, otherwise return false.  This is hidden from the client so
00107   /// that the derived class can check that the right type of pointer is passed
00108   /// in.
00109   bool erase_imp(const void * Ptr);
00110 
00111   bool count_imp(const void * Ptr) const {
00112     if (isSmall()) {
00113       // Linear search for the item.
00114       for (const void *const *APtr = SmallArray,
00115                       *const *E = SmallArray+NumElements; APtr != E; ++APtr)
00116         if (*APtr == Ptr)
00117           return true;
00118       return false;
00119     }
00120 
00121     // Big set case.
00122     return *FindBucketFor(Ptr) == Ptr;
00123   }
00124 
00125 private:
00126   bool isSmall() const { return CurArray == SmallArray; }
00127 
00128   const void * const *FindBucketFor(const void *Ptr) const;
00129   void shrink_and_clear();
00130 
00131   /// Grow - Allocate a larger backing store for the buckets and move it over.
00132   void Grow(unsigned NewSize);
00133 
00134   void operator=(const SmallPtrSetImplBase &RHS) LLVM_DELETED_FUNCTION;
00135 protected:
00136   /// swap - Swaps the elements of two sets.
00137   /// Note: This method assumes that both sets have the same small size.
00138   void swap(SmallPtrSetImplBase &RHS);
00139 
00140   void CopyFrom(const SmallPtrSetImplBase &RHS);
00141   void MoveFrom(unsigned SmallSize, SmallPtrSetImplBase &&RHS);
00142 };
00143 
00144 /// SmallPtrSetIteratorImpl - This is the common base class shared between all
00145 /// instances of SmallPtrSetIterator.
00146 class SmallPtrSetIteratorImpl {
00147 protected:
00148   const void *const *Bucket;
00149   const void *const *End;
00150 public:
00151   explicit SmallPtrSetIteratorImpl(const void *const *BP, const void*const *E)
00152     : Bucket(BP), End(E) {
00153       AdvanceIfNotValid();
00154   }
00155 
00156   bool operator==(const SmallPtrSetIteratorImpl &RHS) const {
00157     return Bucket == RHS.Bucket;
00158   }
00159   bool operator!=(const SmallPtrSetIteratorImpl &RHS) const {
00160     return Bucket != RHS.Bucket;
00161   }
00162 
00163 protected:
00164   /// AdvanceIfNotValid - If the current bucket isn't valid, advance to a bucket
00165   /// that is.   This is guaranteed to stop because the end() bucket is marked
00166   /// valid.
00167   void AdvanceIfNotValid() {
00168     assert(Bucket <= End);
00169     while (Bucket != End &&
00170            (*Bucket == SmallPtrSetImplBase::getEmptyMarker() ||
00171             *Bucket == SmallPtrSetImplBase::getTombstoneMarker()))
00172       ++Bucket;
00173   }
00174 };
00175 
00176 /// SmallPtrSetIterator - This implements a const_iterator for SmallPtrSet.
00177 template<typename PtrTy>
00178 class SmallPtrSetIterator : public SmallPtrSetIteratorImpl {
00179   typedef PointerLikeTypeTraits<PtrTy> PtrTraits;
00180   
00181 public:
00182   typedef PtrTy                     value_type;
00183   typedef PtrTy                     reference;
00184   typedef PtrTy                     pointer;
00185   typedef std::ptrdiff_t            difference_type;
00186   typedef std::forward_iterator_tag iterator_category;
00187   
00188   explicit SmallPtrSetIterator(const void *const *BP, const void *const *E)
00189     : SmallPtrSetIteratorImpl(BP, E) {}
00190 
00191   // Most methods provided by baseclass.
00192 
00193   const PtrTy operator*() const {
00194     assert(Bucket < End);
00195     return PtrTraits::getFromVoidPointer(const_cast<void*>(*Bucket));
00196   }
00197 
00198   inline SmallPtrSetIterator& operator++() {          // Preincrement
00199     ++Bucket;
00200     AdvanceIfNotValid();
00201     return *this;
00202   }
00203 
00204   SmallPtrSetIterator operator++(int) {        // Postincrement
00205     SmallPtrSetIterator tmp = *this; ++*this; return tmp;
00206   }
00207 };
00208 
00209 /// RoundUpToPowerOfTwo - This is a helper template that rounds N up to the next
00210 /// power of two (which means N itself if N is already a power of two).
00211 template<unsigned N>
00212 struct RoundUpToPowerOfTwo;
00213 
00214 /// RoundUpToPowerOfTwoH - If N is not a power of two, increase it.  This is a
00215 /// helper template used to implement RoundUpToPowerOfTwo.
00216 template<unsigned N, bool isPowerTwo>
00217 struct RoundUpToPowerOfTwoH {
00218   enum { Val = N };
00219 };
00220 template<unsigned N>
00221 struct RoundUpToPowerOfTwoH<N, false> {
00222   enum {
00223     // We could just use NextVal = N+1, but this converges faster.  N|(N-1) sets
00224     // the right-most zero bits to one all at once, e.g. 0b0011000 -> 0b0011111.
00225     Val = RoundUpToPowerOfTwo<(N|(N-1)) + 1>::Val
00226   };
00227 };
00228 
00229 template<unsigned N>
00230 struct RoundUpToPowerOfTwo {
00231   enum { Val = RoundUpToPowerOfTwoH<N, (N&(N-1)) == 0>::Val };
00232 };
00233   
00234 
00235 /// \brief A templated base class for \c SmallPtrSet which provides the
00236 /// typesafe interface that is common across all small sizes.
00237 ///
00238 /// This is particularly useful for passing around between interface boundaries
00239 /// to avoid encoding a particular small size in the interface boundary.
00240 template <typename PtrType>
00241 class SmallPtrSetImpl : public SmallPtrSetImplBase {
00242   typedef PointerLikeTypeTraits<PtrType> PtrTraits;
00243 
00244   SmallPtrSetImpl(const SmallPtrSetImpl&) LLVM_DELETED_FUNCTION;
00245 protected:
00246   // Constructors that forward to the base.
00247   SmallPtrSetImpl(const void **SmallStorage, const SmallPtrSetImpl &that)
00248       : SmallPtrSetImplBase(SmallStorage, that) {}
00249   SmallPtrSetImpl(const void **SmallStorage, unsigned SmallSize,
00250                   SmallPtrSetImpl &&that)
00251       : SmallPtrSetImplBase(SmallStorage, SmallSize, std::move(that)) {}
00252   explicit SmallPtrSetImpl(const void **SmallStorage, unsigned SmallSize)
00253       : SmallPtrSetImplBase(SmallStorage, SmallSize) {}
00254 
00255 public:
00256   /// insert - This returns true if the pointer was new to the set, false if it
00257   /// was already in the set.
00258   bool insert(PtrType Ptr) {
00259     return insert_imp(PtrTraits::getAsVoidPointer(Ptr));
00260   }
00261 
00262   /// erase - If the set contains the specified pointer, remove it and return
00263   /// true, otherwise return false.
00264   bool erase(PtrType Ptr) {
00265     return erase_imp(PtrTraits::getAsVoidPointer(Ptr));
00266   }
00267 
00268   /// count - Return 1 if the specified pointer is in the set, 0 otherwise.
00269   size_type count(PtrType Ptr) const {
00270     return count_imp(PtrTraits::getAsVoidPointer(Ptr)) ? 1 : 0;
00271   }
00272 
00273   template <typename IterT>
00274   void insert(IterT I, IterT E) {
00275     for (; I != E; ++I)
00276       insert(*I);
00277   }
00278 
00279   typedef SmallPtrSetIterator<PtrType> iterator;
00280   typedef SmallPtrSetIterator<PtrType> const_iterator;
00281   inline iterator begin() const {
00282     return iterator(CurArray, CurArray+CurArraySize);
00283   }
00284   inline iterator end() const {
00285     return iterator(CurArray+CurArraySize, CurArray+CurArraySize);
00286   }
00287 };
00288 
00289 /// SmallPtrSet - This class implements a set which is optimized for holding
00290 /// SmallSize or less elements.  This internally rounds up SmallSize to the next
00291 /// power of two if it is not already a power of two.  See the comments above
00292 /// SmallPtrSetImplBase for details of the algorithm.
00293 template<class PtrType, unsigned SmallSize>
00294 class SmallPtrSet : public SmallPtrSetImpl<PtrType> {
00295   typedef SmallPtrSetImpl<PtrType> BaseT;
00296 
00297   // Make sure that SmallSize is a power of two, round up if not.
00298   enum { SmallSizePowTwo = RoundUpToPowerOfTwo<SmallSize>::Val };
00299   /// SmallStorage - Fixed size storage used in 'small mode'.
00300   const void *SmallStorage[SmallSizePowTwo];
00301 public:
00302   SmallPtrSet() : BaseT(SmallStorage, SmallSizePowTwo) {}
00303   SmallPtrSet(const SmallPtrSet &that) : BaseT(SmallStorage, that) {}
00304   SmallPtrSet(SmallPtrSet &&that)
00305       : BaseT(SmallStorage, SmallSizePowTwo, std::move(that)) {}
00306 
00307   template<typename It>
00308   SmallPtrSet(It I, It E) : BaseT(SmallStorage, SmallSizePowTwo) {
00309     this->insert(I, E);
00310   }
00311 
00312   SmallPtrSet<PtrType, SmallSize> &
00313   operator=(const SmallPtrSet<PtrType, SmallSize> &RHS) {
00314     if (&RHS != this)
00315       this->CopyFrom(RHS);
00316     return *this;
00317   }
00318 
00319   SmallPtrSet<PtrType, SmallSize>&
00320   operator=(SmallPtrSet<PtrType, SmallSize> &&RHS) {
00321     if (&RHS != this)
00322       this->MoveFrom(SmallSizePowTwo, std::move(RHS));
00323     return *this;
00324   }
00325 
00326   /// swap - Swaps the elements of two sets.
00327   void swap(SmallPtrSet<PtrType, SmallSize> &RHS) {
00328     SmallPtrSetImplBase::swap(RHS);
00329   }
00330 };
00331 
00332 }
00333 
00334 namespace std {
00335   /// Implement std::swap in terms of SmallPtrSet swap.
00336   template<class T, unsigned N>
00337   inline void swap(llvm::SmallPtrSet<T, N> &LHS, llvm::SmallPtrSet<T, N> &RHS) {
00338     LHS.swap(RHS);
00339   }
00340 }
00341 
00342 #endif