LLVM  4.0.0
SmallPtrSet.h
Go to the documentation of this file.
1 //===- llvm/ADT/SmallPtrSet.h - 'Normally small' pointer set ----*- C++ -*-===//
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 defines the SmallPtrSet class. See the doxygen comment for
11 // SmallPtrSetImplBase for more details on the algorithm used.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #ifndef LLVM_ADT_SMALLPTRSET_H
16 #define LLVM_ADT_SMALLPTRSET_H
17 
18 #include "llvm/Config/abi-breaking.h"
19 #include "llvm/Support/Compiler.h"
21 #include <cassert>
22 #include <cstddef>
23 #include <cstring>
24 #include <cstdlib>
25 #include <initializer_list>
26 #include <iterator>
27 #include <utility>
28 
29 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
30 namespace llvm {
31 template <class T = void> struct ReverseIterate { static bool value; };
32 template <class T> bool ReverseIterate<T>::value = false;
33 }
34 #endif
35 
36 namespace llvm {
37 
38 /// SmallPtrSetImplBase - This is the common code shared among all the
39 /// SmallPtrSet<>'s, which is almost everything. SmallPtrSet has two modes, one
40 /// for small and one for large sets.
41 ///
42 /// Small sets use an array of pointers allocated in the SmallPtrSet object,
43 /// which is treated as a simple array of pointers. When a pointer is added to
44 /// the set, the array is scanned to see if the element already exists, if not
45 /// the element is 'pushed back' onto the array. If we run out of space in the
46 /// array, we grow into the 'large set' case. SmallSet should be used when the
47 /// sets are often small. In this case, no memory allocation is used, and only
48 /// light-weight and cache-efficient scanning is used.
49 ///
50 /// Large sets use a classic exponentially-probed hash table. Empty buckets are
51 /// represented with an illegal pointer value (-1) to allow null pointers to be
52 /// inserted. Tombstones are represented with another illegal pointer value
53 /// (-2), to allow deletion. The hash table is resized when the table is 3/4 or
54 /// more. When this happens, the table is doubled in size.
55 ///
58 
59 protected:
60  /// SmallArray - Points to a fixed size set of buckets, used in 'small mode'.
61  const void **SmallArray;
62  /// CurArray - This is the current set of buckets. If equal to SmallArray,
63  /// then the set is in 'small mode'.
64  const void **CurArray;
65  /// CurArraySize - The allocated size of CurArray, always a power of two.
66  unsigned CurArraySize;
67 
68  /// Number of elements in CurArray that contain a value or are a tombstone.
69  /// If small, all these elements are at the beginning of CurArray and the rest
70  /// is uninitialized.
71  unsigned NumNonEmpty;
72  /// Number of tombstones in CurArray.
73  unsigned NumTombstones;
74 
75  // Helpers to copy and move construct a SmallPtrSet.
76  SmallPtrSetImplBase(const void **SmallStorage,
77  const SmallPtrSetImplBase &that);
78  SmallPtrSetImplBase(const void **SmallStorage, unsigned SmallSize,
79  SmallPtrSetImplBase &&that);
80 
81  explicit SmallPtrSetImplBase(const void **SmallStorage, unsigned SmallSize)
82  : SmallArray(SmallStorage), CurArray(SmallStorage),
83  CurArraySize(SmallSize), NumNonEmpty(0), NumTombstones(0) {
84  assert(SmallSize && (SmallSize & (SmallSize-1)) == 0 &&
85  "Initial size must be a power of two!");
86  }
87 
89  if (!isSmall())
90  free(CurArray);
91  }
92 
93 public:
94  typedef unsigned size_type;
95 
97 
98  LLVM_NODISCARD bool empty() const { return size() == 0; }
99  size_type size() const { return NumNonEmpty - NumTombstones; }
100 
101  void clear() {
102  // If the capacity of the array is huge, and the # elements used is small,
103  // shrink the array.
104  if (!isSmall()) {
105  if (size() * 4 < CurArraySize && CurArraySize > 32)
106  return shrink_and_clear();
107  // Fill the array with empty markers.
108  memset(CurArray, -1, CurArraySize * sizeof(void *));
109  }
110 
111  NumNonEmpty = 0;
112  NumTombstones = 0;
113  }
114 
115 protected:
116  static void *getTombstoneMarker() { return reinterpret_cast<void*>(-2); }
117 
118  static void *getEmptyMarker() {
119  // Note that -1 is chosen to make clear() efficiently implementable with
120  // memset and because it's not a valid pointer value.
121  return reinterpret_cast<void*>(-1);
122  }
123 
124  const void **EndPointer() const {
125  return isSmall() ? CurArray + NumNonEmpty : CurArray + CurArraySize;
126  }
127 
128  /// insert_imp - This returns true if the pointer was new to the set, false if
129  /// it was already in the set. This is hidden from the client so that the
130  /// derived class can check that the right type of pointer is passed in.
131  std::pair<const void *const *, bool> insert_imp(const void *Ptr) {
132  if (isSmall()) {
133  // Check to see if it is already in the set.
134  const void **LastTombstone = nullptr;
135  for (const void **APtr = SmallArray, **E = SmallArray + NumNonEmpty;
136  APtr != E; ++APtr) {
137  const void *Value = *APtr;
138  if (Value == Ptr)
139  return std::make_pair(APtr, false);
140  if (Value == getTombstoneMarker())
141  LastTombstone = APtr;
142  }
143 
144  // Did we find any tombstone marker?
145  if (LastTombstone != nullptr) {
146  *LastTombstone = Ptr;
147  --NumTombstones;
148  return std::make_pair(LastTombstone, true);
149  }
150 
151  // Nope, there isn't. If we stay small, just 'pushback' now.
152  if (NumNonEmpty < CurArraySize) {
154  return std::make_pair(SmallArray + (NumNonEmpty - 1), true);
155  }
156  // Otherwise, hit the big set case, which will call grow.
157  }
158  return insert_imp_big(Ptr);
159  }
160 
161  /// erase_imp - If the set contains the specified pointer, remove it and
162  /// return true, otherwise return false. This is hidden from the client so
163  /// that the derived class can check that the right type of pointer is passed
164  /// in.
165  bool erase_imp(const void * Ptr) {
166  const void *const *P = find_imp(Ptr);
167  if (P == EndPointer())
168  return false;
169 
170  const void ** Loc = const_cast<const void **>(P);
171  assert(*Loc == Ptr && "broken find!");
172  *Loc = getTombstoneMarker();
173  NumTombstones++;
174  return true;
175  }
176 
177  /// Returns the raw pointer needed to construct an iterator. If element not
178  /// found, this will be EndPointer. Otherwise, it will be a pointer to the
179  /// slot which stores Ptr;
180  const void *const * find_imp(const void * Ptr) const {
181  if (isSmall()) {
182  // Linear search for the item.
183  for (const void *const *APtr = SmallArray,
184  *const *E = SmallArray + NumNonEmpty; APtr != E; ++APtr)
185  if (*APtr == Ptr)
186  return APtr;
187  return EndPointer();
188  }
189 
190  // Big set case.
191  auto *Bucket = FindBucketFor(Ptr);
192  if (*Bucket == Ptr)
193  return Bucket;
194  return EndPointer();
195  }
196 
197 private:
198  bool isSmall() const { return CurArray == SmallArray; }
199 
200  std::pair<const void *const *, bool> insert_imp_big(const void *Ptr);
201 
202  const void * const *FindBucketFor(const void *Ptr) const;
203  void shrink_and_clear();
204 
205  /// Grow - Allocate a larger backing store for the buckets and move it over.
206  void Grow(unsigned NewSize);
207 
208 protected:
209  /// swap - Swaps the elements of two sets.
210  /// Note: This method assumes that both sets have the same small size.
211  void swap(SmallPtrSetImplBase &RHS);
212 
213  void CopyFrom(const SmallPtrSetImplBase &RHS);
214  void MoveFrom(unsigned SmallSize, SmallPtrSetImplBase &&RHS);
215 
216 private:
217  /// Code shared by MoveFrom() and move constructor.
218  void MoveHelper(unsigned SmallSize, SmallPtrSetImplBase &&RHS);
219  /// Code shared by CopyFrom() and copy constructor.
220  void CopyHelper(const SmallPtrSetImplBase &RHS);
221 };
222 
223 /// SmallPtrSetIteratorImpl - This is the common base class shared between all
224 /// instances of SmallPtrSetIterator.
226 protected:
227  const void *const *Bucket;
228  const void *const *End;
229 
230 public:
231  explicit SmallPtrSetIteratorImpl(const void *const *BP, const void*const *E)
232  : Bucket(BP), End(E) {
233 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
236  return;
237  }
238 #endif
240  }
241 
242  bool operator==(const SmallPtrSetIteratorImpl &RHS) const {
243  return Bucket == RHS.Bucket;
244  }
245  bool operator!=(const SmallPtrSetIteratorImpl &RHS) const {
246  return Bucket != RHS.Bucket;
247  }
248 
249 protected:
250  /// AdvanceIfNotValid - If the current bucket isn't valid, advance to a bucket
251  /// that is. This is guaranteed to stop because the end() bucket is marked
252  /// valid.
254  assert(Bucket <= End);
255  while (Bucket != End &&
258  ++Bucket;
259  }
260 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
262  --Bucket;
263  assert(Bucket <= End);
264  while (Bucket != End &&
267  --Bucket;
268  }
269  }
270 #endif
271 };
272 
273 /// SmallPtrSetIterator - This implements a const_iterator for SmallPtrSet.
274 template<typename PtrTy>
277 
278 public:
279  typedef PtrTy value_type;
280  typedef PtrTy reference;
281  typedef PtrTy pointer;
282  typedef std::ptrdiff_t difference_type;
283  typedef std::forward_iterator_tag iterator_category;
284 
285  explicit SmallPtrSetIterator(const void *const *BP, const void *const *E)
286  : SmallPtrSetIteratorImpl(BP, E) {}
287 
288  // Most methods provided by baseclass.
289 
290  const PtrTy operator*() const {
291  assert(Bucket < End);
292  return PtrTraits::getFromVoidPointer(const_cast<void*>(*Bucket));
293  }
294 
295  inline SmallPtrSetIterator& operator++() { // Preincrement
296 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
299  return *this;
300  }
301 #endif
302  ++Bucket;
304  return *this;
305  }
306 
307  SmallPtrSetIterator operator++(int) { // Postincrement
308  SmallPtrSetIterator tmp = *this;
309  ++*this;
310  return tmp;
311  }
312 };
313 
314 /// RoundUpToPowerOfTwo - This is a helper template that rounds N up to the next
315 /// power of two (which means N itself if N is already a power of two).
316 template<unsigned N>
318 
319 /// RoundUpToPowerOfTwoH - If N is not a power of two, increase it. This is a
320 /// helper template used to implement RoundUpToPowerOfTwo.
321 template<unsigned N, bool isPowerTwo>
323  enum { Val = N };
324 };
325 template<unsigned N>
327  enum {
328  // We could just use NextVal = N+1, but this converges faster. N|(N-1) sets
329  // the right-most zero bits to one all at once, e.g. 0b0011000 -> 0b0011111.
331  };
332 };
333 
334 template<unsigned N>
335 struct RoundUpToPowerOfTwo {
336  enum { Val = RoundUpToPowerOfTwoH<N, (N&(N-1)) == 0>::Val };
337 };
338 
339 /// \brief A templated base class for \c SmallPtrSet which provides the
340 /// typesafe interface that is common across all small sizes.
341 ///
342 /// This is particularly useful for passing around between interface boundaries
343 /// to avoid encoding a particular small size in the interface boundary.
344 template <typename PtrType>
347 
348 protected:
349  // Constructors that forward to the base.
350  SmallPtrSetImpl(const void **SmallStorage, const SmallPtrSetImpl &that)
351  : SmallPtrSetImplBase(SmallStorage, that) {}
352  SmallPtrSetImpl(const void **SmallStorage, unsigned SmallSize,
353  SmallPtrSetImpl &&that)
354  : SmallPtrSetImplBase(SmallStorage, SmallSize, std::move(that)) {}
355  explicit SmallPtrSetImpl(const void **SmallStorage, unsigned SmallSize)
356  : SmallPtrSetImplBase(SmallStorage, SmallSize) {}
357 
358 public:
361 
362  SmallPtrSetImpl(const SmallPtrSetImpl &) = delete;
363 
364  /// Inserts Ptr if and only if there is no element in the container equal to
365  /// Ptr. The bool component of the returned pair is true if and only if the
366  /// insertion takes place, and the iterator component of the pair points to
367  /// the element equal to Ptr.
368  std::pair<iterator, bool> insert(PtrType Ptr) {
369  auto p = insert_imp(PtrTraits::getAsVoidPointer(Ptr));
370  return std::make_pair(iterator(p.first, EndPointer()), p.second);
371  }
372 
373  /// erase - If the set contains the specified pointer, remove it and return
374  /// true, otherwise return false.
375  bool erase(PtrType Ptr) {
376  return erase_imp(PtrTraits::getAsVoidPointer(Ptr));
377  }
378 
379  /// count - Return 1 if the specified pointer is in the set, 0 otherwise.
380  size_type count(PtrType Ptr) const {
381  return find(Ptr) != endPtr() ? 1 : 0;
382  }
383  iterator find(PtrType Ptr) const {
384  auto *P = find_imp(PtrTraits::getAsVoidPointer(Ptr));
385  return iterator(P, EndPointer());
386  }
387 
388  template <typename IterT>
389  void insert(IterT I, IterT E) {
390  for (; I != E; ++I)
391  insert(*I);
392  }
393 
394  void insert(std::initializer_list<PtrType> IL) {
395  insert(IL.begin(), IL.end());
396  }
397 
398  inline iterator begin() const {
399 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
401  return endPtr();
402 #endif
403  return iterator(CurArray, EndPointer());
404  }
405  inline iterator end() const {
406 #if LLVM_ENABLE_ABI_BREAKING_CHECKS
408  return iterator(CurArray, CurArray);
409 #endif
410  return endPtr();
411  }
412 
413 private:
414  inline iterator endPtr() const {
415  const void *const *End = EndPointer();
416  return iterator(End, End);
417  }
418 };
419 
420 /// SmallPtrSet - This class implements a set which is optimized for holding
421 /// SmallSize or less elements. This internally rounds up SmallSize to the next
422 /// power of two if it is not already a power of two. See the comments above
423 /// SmallPtrSetImplBase for details of the algorithm.
424 template<class PtrType, unsigned SmallSize>
425 class SmallPtrSet : public SmallPtrSetImpl<PtrType> {
426  // In small mode SmallPtrSet uses linear search for the elements, so it is
427  // not a good idea to choose this value too high. You may consider using a
428  // DenseSet<> instead if you expect many elements in the set.
429  static_assert(SmallSize <= 32, "SmallSize should be small");
430 
432 
433  // Make sure that SmallSize is a power of two, round up if not.
434  enum { SmallSizePowTwo = RoundUpToPowerOfTwo<SmallSize>::Val };
435  /// SmallStorage - Fixed size storage used in 'small mode'.
436  const void *SmallStorage[SmallSizePowTwo];
437 
438 public:
439  SmallPtrSet() : BaseT(SmallStorage, SmallSizePowTwo) {}
440  SmallPtrSet(const SmallPtrSet &that) : BaseT(SmallStorage, that) {}
442  : BaseT(SmallStorage, SmallSizePowTwo, std::move(that)) {}
443 
444  template<typename It>
445  SmallPtrSet(It I, It E) : BaseT(SmallStorage, SmallSizePowTwo) {
446  this->insert(I, E);
447  }
448 
449  SmallPtrSet(std::initializer_list<PtrType> IL)
450  : BaseT(SmallStorage, SmallSizePowTwo) {
451  this->insert(IL.begin(), IL.end());
452  }
453 
456  if (&RHS != this)
457  this->CopyFrom(RHS);
458  return *this;
459  }
460 
463  if (&RHS != this)
464  this->MoveFrom(SmallSizePowTwo, std::move(RHS));
465  return *this;
466  }
467 
469  operator=(std::initializer_list<PtrType> IL) {
470  this->clear();
471  this->insert(IL.begin(), IL.end());
472  return *this;
473  }
474 
475  /// swap - Swaps the elements of two sets.
478  }
479 };
480 
481 } // end namespace llvm
482 
483 namespace std {
484 
485  /// Implement std::swap in terms of SmallPtrSet swap.
486  template<class T, unsigned N>
488  LHS.swap(RHS);
489  }
490 
491 } // end namespace std
492 
493 #endif // LLVM_ADT_SMALLPTRSET_H
static void * getTombstoneMarker()
Definition: SmallPtrSet.h:116
SmallPtrSetImpl(const void **SmallStorage, unsigned SmallSize, SmallPtrSetImpl &&that)
Definition: SmallPtrSet.h:352
SmallPtrSet(const SmallPtrSet &that)
Definition: SmallPtrSet.h:440
SmallPtrSet(It I, It E)
Definition: SmallPtrSet.h:445
SmallPtrSetImpl(const void **SmallStorage, const SmallPtrSetImpl &that)
Definition: SmallPtrSet.h:350
SmallPtrSetIterator< PtrType > const_iterator
Definition: SmallPtrSet.h:360
std::ptrdiff_t difference_type
Definition: SmallPtrSet.h:282
size_type count(PtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
Definition: SmallPtrSet.h:380
const void *const * find_imp(const void *Ptr) const
Returns the raw pointer needed to construct an iterator.
Definition: SmallPtrSet.h:180
void MoveFrom(unsigned SmallSize, SmallPtrSetImplBase &&RHS)
unsigned NumNonEmpty
Number of elements in CurArray that contain a value or are a tombstone.
Definition: SmallPtrSet.h:71
A traits type that is used to handle pointer types and things that are just wrappers for pointers as ...
static bool value
Definition: SmallPtrSet.h:31
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
Definition: SmallPtrSet.h:345
SmallPtrSetIterator & operator++()
Definition: SmallPtrSet.h:295
SmallPtrSetIteratorImpl - This is the common base class shared between all instances of SmallPtrSetIt...
Definition: SmallPtrSet.h:225
void swap(SmallPtrSetImplBase &RHS)
swap - Swaps the elements of two sets.
SmallPtrSet(std::initializer_list< PtrType > IL)
Definition: SmallPtrSet.h:449
SmallPtrSet(SmallPtrSet &&that)
Definition: SmallPtrSet.h:441
unsigned CurArraySize
CurArraySize - The allocated size of CurArray, always a power of two.
Definition: SmallPtrSet.h:66
SmallPtrSetIterator(const void *const *BP, const void *const *E)
Definition: SmallPtrSet.h:285
const void ** CurArray
CurArray - This is the current set of buckets.
Definition: SmallPtrSet.h:64
RoundUpToPowerOfTwo - This is a helper template that rounds N up to the next power of two (which mean...
Definition: SmallPtrSet.h:317
bool erase_imp(const void *Ptr)
erase_imp - If the set contains the specified pointer, remove it and return true, otherwise return fa...
Definition: SmallPtrSet.h:165
bool operator!=(const SmallPtrSetIteratorImpl &RHS) const
Definition: SmallPtrSet.h:245
SmallPtrSet< PtrType, SmallSize > & operator=(const SmallPtrSet< PtrType, SmallSize > &RHS)
Definition: SmallPtrSet.h:455
static void * getEmptyMarker()
Definition: SmallPtrSet.h:118
void AdvanceIfNotValid()
AdvanceIfNotValid - If the current bucket isn't valid, advance to a bucket that is.
Definition: SmallPtrSet.h:253
Function Alias Analysis false
const void ** EndPointer() const
Definition: SmallPtrSet.h:124
void CopyFrom(const SmallPtrSetImplBase &RHS)
static GCRegistry::Add< CoreCLRGC > E("coreclr","CoreCLR-compatible GC")
#define P(N)
void insert(IterT I, IterT E)
Definition: SmallPtrSet.h:389
SmallPtrSet< PtrType, SmallSize > & operator=(SmallPtrSet< PtrType, SmallSize > &&RHS)
Definition: SmallPtrSet.h:462
size_type size() const
Definition: SmallPtrSet.h:99
const PtrTy operator*() const
Definition: SmallPtrSet.h:290
SmallPtrSetIterator operator++(int)
Definition: SmallPtrSet.h:307
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:368
SmallPtrSetImpl(const void **SmallStorage, unsigned SmallSize)
Definition: SmallPtrSet.h:355
static const unsigned End
const void *const * Bucket
Definition: SmallPtrSet.h:227
iterator find(PtrType Ptr) const
Definition: SmallPtrSet.h:383
iterator begin() const
Definition: SmallPtrSet.h:398
LLVM_NODISCARD bool empty() const
Definition: SmallPtrSet.h:98
bool operator==(const SmallPtrSetIteratorImpl &RHS) const
Definition: SmallPtrSet.h:242
const void *const * End
Definition: SmallPtrSet.h:228
SmallPtrSetIterator - This implements a const_iterator for SmallPtrSet.
Definition: SmallPtrSet.h:275
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
Definition: SmallPtrSet.h:425
bool erase(PtrType Ptr)
erase - If the set contains the specified pointer, remove it and return true, otherwise return false...
Definition: SmallPtrSet.h:375
const void ** SmallArray
SmallArray - Points to a fixed size set of buckets, used in 'small mode'.
Definition: SmallPtrSet.h:61
SmallPtrSetImplBase(const void **SmallStorage, unsigned SmallSize)
Definition: SmallPtrSet.h:81
SmallPtrSetIterator< PtrType > iterator
Definition: SmallPtrSet.h:359
SmallPtrSetImplBase(const void **SmallStorage, const SmallPtrSetImplBase &that)
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition: BitVector.h:586
RoundUpToPowerOfTwoH - If N is not a power of two, increase it.
Definition: SmallPtrSet.h:322
SmallPtrSetImplBase - This is the common code shared among all the SmallPtrSet<>'s, which is almost everything.
Definition: SmallPtrSet.h:56
iterator end() const
Definition: SmallPtrSet.h:405
unsigned NumTombstones
Number of tombstones in CurArray.
Definition: SmallPtrSet.h:73
SmallPtrSet< PtrType, SmallSize > & operator=(std::initializer_list< PtrType > IL)
Definition: SmallPtrSet.h:469
#define I(x, y, z)
Definition: MD5.cpp:54
#define N
#define LLVM_NODISCARD
LLVM_NODISCARD - Warn if a type or return value is discarded.
Definition: Compiler.h:132
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
LLVM Value Representation.
Definition: Value.h:71
SmallPtrSetIteratorImpl(const void *const *BP, const void *const *E)
Definition: SmallPtrSet.h:231
int * Ptr
SmallPtrSetImplBase & operator=(const SmallPtrSetImplBase &)=delete
void insert(std::initializer_list< PtrType > IL)
Definition: SmallPtrSet.h:394
void swap(SmallPtrSet< PtrType, SmallSize > &RHS)
swap - Swaps the elements of two sets.
Definition: SmallPtrSet.h:476
std::pair< const void *const *, bool > insert_imp(const void *Ptr)
insert_imp - This returns true if the pointer was new to the set, false if it was already in the set...
Definition: SmallPtrSet.h:131
std::forward_iterator_tag iterator_category
Definition: SmallPtrSet.h:283