xref: /llvm-project/llvm/lib/Support/SmallPtrSet.cpp (revision f67e5c79d70cd5e314d1567b6596bb62f06785d8)
1 //===- llvm/ADT/SmallPtrSet.cpp - 'Normally small' pointer set ------------===//
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 implements the SmallPtrSet class.  See SmallPtrSet.h for an
11 // overview of the algorithm.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "llvm/ADT/SmallPtrSet.h"
16 #include "llvm/ADT/DenseMapInfo.h"
17 #include "llvm/Support/MathExtras.h"
18 #include <algorithm>
19 #include <cstdlib>
20 
21 using namespace llvm;
22 
23 void SmallPtrSetImplBase::shrink_and_clear() {
24   assert(!isSmall() && "Can't shrink a small set!");
25   free(CurArray);
26 
27   // Reduce the number of buckets.
28   CurArraySize = NumElements > 16 ? 1 << (Log2_32_Ceil(NumElements) + 1) : 32;
29   NumElements = NumTombstones = 0;
30 
31   // Install the new array.  Clear all the buckets to empty.
32   CurArray = (const void**)malloc(sizeof(void*) * CurArraySize);
33   assert(CurArray && "Failed to allocate memory?");
34   memset(CurArray, -1, CurArraySize*sizeof(void*));
35 }
36 
37 std::pair<const void *const *, bool>
38 SmallPtrSetImplBase::insert_imp_big(const void *Ptr) {
39   if (LLVM_UNLIKELY(NumElements * 4 >= CurArraySize * 3)) {
40     // If more than 3/4 of the array is full, grow.
41     Grow(CurArraySize < 64 ? 128 : CurArraySize*2);
42   } else if (LLVM_UNLIKELY(CurArraySize - (NumElements + NumTombstones) <
43                            CurArraySize / 8)) {
44     // If fewer of 1/8 of the array is empty (meaning that many are filled with
45     // tombstones), rehash.
46     Grow(CurArraySize);
47   }
48 
49   // Okay, we know we have space.  Find a hash bucket.
50   const void **Bucket = const_cast<const void**>(FindBucketFor(Ptr));
51   if (*Bucket == Ptr)
52     return std::make_pair(Bucket, false); // Already inserted, good.
53 
54   // Otherwise, insert it!
55   if (*Bucket == getTombstoneMarker())
56     --NumTombstones;
57   *Bucket = Ptr;
58   ++NumElements;  // Track density.
59   return std::make_pair(Bucket, true);
60 }
61 
62 bool SmallPtrSetImplBase::erase_imp(const void * Ptr) {
63   if (isSmall()) {
64     // Check to see if it is in the set.
65     for (const void **APtr = SmallArray, **E = SmallArray+NumElements;
66          APtr != E; ++APtr)
67       if (*APtr == Ptr) {
68         // If it is in the set, replace this element.
69         *APtr = E[-1];
70         E[-1] = getEmptyMarker();
71         --NumElements;
72         return true;
73       }
74 
75     return false;
76   }
77 
78   // Okay, we know we have space.  Find a hash bucket.
79   void **Bucket = const_cast<void**>(FindBucketFor(Ptr));
80   if (*Bucket != Ptr) return false;  // Not in the set?
81 
82   // Set this as a tombstone.
83   *Bucket = getTombstoneMarker();
84   --NumElements;
85   ++NumTombstones;
86   return true;
87 }
88 
89 const void * const *SmallPtrSetImplBase::FindBucketFor(const void *Ptr) const {
90   unsigned Bucket = DenseMapInfo<void *>::getHashValue(Ptr) & (CurArraySize-1);
91   unsigned ArraySize = CurArraySize;
92   unsigned ProbeAmt = 1;
93   const void *const *Array = CurArray;
94   const void *const *Tombstone = nullptr;
95   while (1) {
96     // If we found an empty bucket, the pointer doesn't exist in the set.
97     // Return a tombstone if we've seen one so far, or the empty bucket if
98     // not.
99     if (LLVM_LIKELY(Array[Bucket] == getEmptyMarker()))
100       return Tombstone ? Tombstone : Array+Bucket;
101 
102     // Found Ptr's bucket?
103     if (LLVM_LIKELY(Array[Bucket] == Ptr))
104       return Array+Bucket;
105 
106     // If this is a tombstone, remember it.  If Ptr ends up not in the set, we
107     // prefer to return it than something that would require more probing.
108     if (Array[Bucket] == getTombstoneMarker() && !Tombstone)
109       Tombstone = Array+Bucket;  // Remember the first tombstone found.
110 
111     // It's a hash collision or a tombstone. Reprobe.
112     Bucket = (Bucket + ProbeAmt++) & (ArraySize-1);
113   }
114 }
115 
116 /// Grow - Allocate a larger backing store for the buckets and move it over.
117 ///
118 void SmallPtrSetImplBase::Grow(unsigned NewSize) {
119   // Allocate at twice as many buckets, but at least 128.
120   unsigned OldSize = CurArraySize;
121 
122   const void **OldBuckets = CurArray;
123   bool WasSmall = isSmall();
124 
125   // Install the new array.  Clear all the buckets to empty.
126   CurArray = (const void**)malloc(sizeof(void*) * NewSize);
127   assert(CurArray && "Failed to allocate memory?");
128   CurArraySize = NewSize;
129   memset(CurArray, -1, NewSize*sizeof(void*));
130 
131   // Copy over all the elements.
132   if (WasSmall) {
133     // Small sets store their elements in order.
134     for (const void **BucketPtr = OldBuckets, **E = OldBuckets+NumElements;
135          BucketPtr != E; ++BucketPtr) {
136       const void *Elt = *BucketPtr;
137       *const_cast<void**>(FindBucketFor(Elt)) = const_cast<void*>(Elt);
138     }
139   } else {
140     // Copy over all valid entries.
141     for (const void **BucketPtr = OldBuckets, **E = OldBuckets+OldSize;
142          BucketPtr != E; ++BucketPtr) {
143       // Copy over the element if it is valid.
144       const void *Elt = *BucketPtr;
145       if (Elt != getTombstoneMarker() && Elt != getEmptyMarker())
146         *const_cast<void**>(FindBucketFor(Elt)) = const_cast<void*>(Elt);
147     }
148 
149     free(OldBuckets);
150     NumTombstones = 0;
151   }
152 }
153 
154 SmallPtrSetImplBase::SmallPtrSetImplBase(const void **SmallStorage,
155                                          const SmallPtrSetImplBase &that) {
156   SmallArray = SmallStorage;
157 
158   // If we're becoming small, prepare to insert into our stack space
159   if (that.isSmall()) {
160     CurArray = SmallArray;
161   // Otherwise, allocate new heap space (unless we were the same size)
162   } else {
163     CurArray = (const void**)malloc(sizeof(void*) * that.CurArraySize);
164     assert(CurArray && "Failed to allocate memory?");
165   }
166 
167   // Copy over the new array size
168   CurArraySize = that.CurArraySize;
169 
170   // Copy over the contents from the other set
171   memcpy(CurArray, that.CurArray, sizeof(void*)*CurArraySize);
172 
173   NumElements = that.NumElements;
174   NumTombstones = that.NumTombstones;
175 }
176 
177 SmallPtrSetImplBase::SmallPtrSetImplBase(const void **SmallStorage,
178                                          unsigned SmallSize,
179                                          SmallPtrSetImplBase &&that) {
180   SmallArray = SmallStorage;
181 
182   // Copy over the basic members.
183   CurArraySize = that.CurArraySize;
184   NumElements = that.NumElements;
185   NumTombstones = that.NumTombstones;
186 
187   // When small, just copy into our small buffer.
188   if (that.isSmall()) {
189     CurArray = SmallArray;
190     memcpy(CurArray, that.CurArray, sizeof(void *) * CurArraySize);
191   } else {
192     // Otherwise, we steal the large memory allocation and no copy is needed.
193     CurArray = that.CurArray;
194     that.CurArray = that.SmallArray;
195   }
196 
197   // Make the "that" object small and empty.
198   that.CurArraySize = SmallSize;
199   assert(that.CurArray == that.SmallArray);
200   that.NumElements = 0;
201   that.NumTombstones = 0;
202 }
203 
204 /// CopyFrom - implement operator= from a smallptrset that has the same pointer
205 /// type, but may have a different small size.
206 void SmallPtrSetImplBase::CopyFrom(const SmallPtrSetImplBase &RHS) {
207   assert(&RHS != this && "Self-copy should be handled by the caller.");
208 
209   if (isSmall() && RHS.isSmall())
210     assert(CurArraySize == RHS.CurArraySize &&
211            "Cannot assign sets with different small sizes");
212 
213   // If we're becoming small, prepare to insert into our stack space
214   if (RHS.isSmall()) {
215     if (!isSmall())
216       free(CurArray);
217     CurArray = SmallArray;
218   // Otherwise, allocate new heap space (unless we were the same size)
219   } else if (CurArraySize != RHS.CurArraySize) {
220     if (isSmall())
221       CurArray = (const void**)malloc(sizeof(void*) * RHS.CurArraySize);
222     else {
223       const void **T = (const void**)realloc(CurArray,
224                                              sizeof(void*) * RHS.CurArraySize);
225       if (!T)
226         free(CurArray);
227       CurArray = T;
228     }
229     assert(CurArray && "Failed to allocate memory?");
230   }
231 
232   // Copy over the new array size
233   CurArraySize = RHS.CurArraySize;
234 
235   // Copy over the contents from the other set
236   memcpy(CurArray, RHS.CurArray, sizeof(void*)*CurArraySize);
237 
238   NumElements = RHS.NumElements;
239   NumTombstones = RHS.NumTombstones;
240 }
241 
242 void SmallPtrSetImplBase::MoveFrom(unsigned SmallSize,
243                                    SmallPtrSetImplBase &&RHS) {
244   assert(&RHS != this && "Self-move should be handled by the caller.");
245 
246   if (!isSmall())
247     free(CurArray);
248 
249   if (RHS.isSmall()) {
250     // Copy a small RHS rather than moving.
251     CurArray = SmallArray;
252     memcpy(CurArray, RHS.CurArray, sizeof(void*)*RHS.CurArraySize);
253   } else {
254     CurArray = RHS.CurArray;
255     RHS.CurArray = RHS.SmallArray;
256   }
257 
258   // Copy the rest of the trivial members.
259   CurArraySize = RHS.CurArraySize;
260   NumElements = RHS.NumElements;
261   NumTombstones = RHS.NumTombstones;
262 
263   // Make the RHS small and empty.
264   RHS.CurArraySize = SmallSize;
265   assert(RHS.CurArray == RHS.SmallArray);
266   RHS.NumElements = 0;
267   RHS.NumTombstones = 0;
268 }
269 
270 void SmallPtrSetImplBase::swap(SmallPtrSetImplBase &RHS) {
271   if (this == &RHS) return;
272 
273   // We can only avoid copying elements if neither set is small.
274   if (!this->isSmall() && !RHS.isSmall()) {
275     std::swap(this->CurArray, RHS.CurArray);
276     std::swap(this->CurArraySize, RHS.CurArraySize);
277     std::swap(this->NumElements, RHS.NumElements);
278     std::swap(this->NumTombstones, RHS.NumTombstones);
279     return;
280   }
281 
282   // FIXME: From here on we assume that both sets have the same small size.
283 
284   // If only RHS is small, copy the small elements into LHS and move the pointer
285   // from LHS to RHS.
286   if (!this->isSmall() && RHS.isSmall()) {
287     std::copy(RHS.SmallArray, RHS.SmallArray+RHS.CurArraySize,
288               this->SmallArray);
289     std::swap(this->NumElements, RHS.NumElements);
290     std::swap(this->CurArraySize, RHS.CurArraySize);
291     RHS.CurArray = this->CurArray;
292     RHS.NumTombstones = this->NumTombstones;
293     this->CurArray = this->SmallArray;
294     this->NumTombstones = 0;
295     return;
296   }
297 
298   // If only LHS is small, copy the small elements into RHS and move the pointer
299   // from RHS to LHS.
300   if (this->isSmall() && !RHS.isSmall()) {
301     std::copy(this->SmallArray, this->SmallArray+this->CurArraySize,
302               RHS.SmallArray);
303     std::swap(RHS.NumElements, this->NumElements);
304     std::swap(RHS.CurArraySize, this->CurArraySize);
305     this->CurArray = RHS.CurArray;
306     this->NumTombstones = RHS.NumTombstones;
307     RHS.CurArray = RHS.SmallArray;
308     RHS.NumTombstones = 0;
309     return;
310   }
311 
312   // Both a small, just swap the small elements.
313   assert(this->isSmall() && RHS.isSmall());
314   assert(this->CurArraySize == RHS.CurArraySize);
315   std::swap_ranges(this->SmallArray, this->SmallArray+this->CurArraySize,
316                    RHS.SmallArray);
317   std::swap(this->NumElements, RHS.NumElements);
318 }
319 
320 SmallPtrSetImplBase::~SmallPtrSetImplBase() {
321   if (!isSmall())
322     free(CurArray);
323 }
324