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