xref: /freebsd/contrib/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_dense_map.h (revision 5e801ac66d24704442eba426ed13c3effb8a34e7)
1 //===- sanitizer_dense_map.h - Dense probed hash table ----------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This is fork of llvm/ADT/DenseMap.h class with the following changes:
10 //  * Use mmap to allocate.
11 //  * No iterators.
12 //  * Does not shrink.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #ifndef SANITIZER_DENSE_MAP_H
17 #define SANITIZER_DENSE_MAP_H
18 
19 #include "sanitizer_common.h"
20 #include "sanitizer_dense_map_info.h"
21 #include "sanitizer_internal_defs.h"
22 #include "sanitizer_type_traits.h"
23 
24 namespace __sanitizer {
25 
26 template <typename DerivedT, typename KeyT, typename ValueT, typename KeyInfoT,
27           typename BucketT>
28 class DenseMapBase {
29  public:
30   using size_type = unsigned;
31   using key_type = KeyT;
32   using mapped_type = ValueT;
33   using value_type = BucketT;
34 
35   WARN_UNUSED_RESULT bool empty() const { return getNumEntries() == 0; }
36   unsigned size() const { return getNumEntries(); }
37 
38   /// Grow the densemap so that it can contain at least \p NumEntries items
39   /// before resizing again.
40   void reserve(size_type NumEntries) {
41     auto NumBuckets = getMinBucketToReserveForEntries(NumEntries);
42     if (NumBuckets > getNumBuckets())
43       grow(NumBuckets);
44   }
45 
46   void clear() {
47     if (getNumEntries() == 0 && getNumTombstones() == 0)
48       return;
49 
50     const KeyT EmptyKey = getEmptyKey(), TombstoneKey = getTombstoneKey();
51     if (__sanitizer::is_trivially_destructible<ValueT>::value) {
52       // Use a simpler loop when values don't need destruction.
53       for (BucketT *P = getBuckets(), *E = getBucketsEnd(); P != E; ++P)
54         P->getFirst() = EmptyKey;
55     } else {
56       unsigned NumEntries = getNumEntries();
57       for (BucketT *P = getBuckets(), *E = getBucketsEnd(); P != E; ++P) {
58         if (!KeyInfoT::isEqual(P->getFirst(), EmptyKey)) {
59           if (!KeyInfoT::isEqual(P->getFirst(), TombstoneKey)) {
60             P->getSecond().~ValueT();
61             --NumEntries;
62           }
63           P->getFirst() = EmptyKey;
64         }
65       }
66       CHECK_EQ(NumEntries, 0);
67     }
68     setNumEntries(0);
69     setNumTombstones(0);
70   }
71 
72   /// Return 1 if the specified key is in the map, 0 otherwise.
73   size_type count(const KeyT &Key) const {
74     const BucketT *TheBucket;
75     return LookupBucketFor(Key, TheBucket) ? 1 : 0;
76   }
77 
78   value_type *find(const KeyT &Key) {
79     BucketT *TheBucket;
80     if (LookupBucketFor(Key, TheBucket))
81       return TheBucket;
82     return nullptr;
83   }
84   const value_type *find(const KeyT &Key) const {
85     const BucketT *TheBucket;
86     if (LookupBucketFor(Key, TheBucket))
87       return TheBucket;
88     return nullptr;
89   }
90 
91   /// Alternate version of find() which allows a different, and possibly
92   /// less expensive, key type.
93   /// The DenseMapInfo is responsible for supplying methods
94   /// getHashValue(LookupKeyT) and isEqual(LookupKeyT, KeyT) for each key
95   /// type used.
96   template <class LookupKeyT>
97   value_type *find_as(const LookupKeyT &Key) {
98     BucketT *TheBucket;
99     if (LookupBucketFor(Key, TheBucket))
100       return TheBucket;
101     return nullptr;
102   }
103   template <class LookupKeyT>
104   const value_type *find_as(const LookupKeyT &Key) const {
105     const BucketT *TheBucket;
106     if (LookupBucketFor(Key, TheBucket))
107       return TheBucket;
108     return nullptr;
109   }
110 
111   /// lookup - Return the entry for the specified key, or a default
112   /// constructed value if no such entry exists.
113   ValueT lookup(const KeyT &Key) const {
114     const BucketT *TheBucket;
115     if (LookupBucketFor(Key, TheBucket))
116       return TheBucket->getSecond();
117     return ValueT();
118   }
119 
120   // Inserts key,value pair into the map if the key isn't already in the map.
121   // If the key is already in the map, it returns false and doesn't update the
122   // value.
123   detail::DenseMapPair<value_type *, bool> insert(const value_type &KV) {
124     return try_emplace(KV.first, KV.second);
125   }
126 
127   // Inserts key,value pair into the map if the key isn't already in the map.
128   // If the key is already in the map, it returns false and doesn't update the
129   // value.
130   detail::DenseMapPair<value_type *, bool> insert(value_type &&KV) {
131     return try_emplace(__sanitizer::move(KV.first),
132                        __sanitizer::move(KV.second));
133   }
134 
135   // Inserts key,value pair into the map if the key isn't already in the map.
136   // The value is constructed in-place if the key is not in the map, otherwise
137   // it is not moved.
138   template <typename... Ts>
139   detail::DenseMapPair<value_type *, bool> try_emplace(KeyT &&Key,
140                                                        Ts &&...Args) {
141     BucketT *TheBucket;
142     if (LookupBucketFor(Key, TheBucket))
143       return {TheBucket, false};  // Already in map.
144 
145     // Otherwise, insert the new element.
146     TheBucket = InsertIntoBucket(TheBucket, __sanitizer::move(Key),
147                                  __sanitizer::forward<Ts>(Args)...);
148     return {TheBucket, true};
149   }
150 
151   // Inserts key,value pair into the map if the key isn't already in the map.
152   // The value is constructed in-place if the key is not in the map, otherwise
153   // it is not moved.
154   template <typename... Ts>
155   detail::DenseMapPair<value_type *, bool> try_emplace(const KeyT &Key,
156                                                        Ts &&...Args) {
157     BucketT *TheBucket;
158     if (LookupBucketFor(Key, TheBucket))
159       return {TheBucket, false};  // Already in map.
160 
161     // Otherwise, insert the new element.
162     TheBucket =
163         InsertIntoBucket(TheBucket, Key, __sanitizer::forward<Ts>(Args)...);
164     return {TheBucket, true};
165   }
166 
167   /// Alternate version of insert() which allows a different, and possibly
168   /// less expensive, key type.
169   /// The DenseMapInfo is responsible for supplying methods
170   /// getHashValue(LookupKeyT) and isEqual(LookupKeyT, KeyT) for each key
171   /// type used.
172   template <typename LookupKeyT>
173   detail::DenseMapPair<value_type *, bool> insert_as(value_type &&KV,
174                                                      const LookupKeyT &Val) {
175     BucketT *TheBucket;
176     if (LookupBucketFor(Val, TheBucket))
177       return {TheBucket, false};  // Already in map.
178 
179     // Otherwise, insert the new element.
180     TheBucket =
181         InsertIntoBucketWithLookup(TheBucket, __sanitizer::move(KV.first),
182                                    __sanitizer::move(KV.second), Val);
183     return {TheBucket, true};
184   }
185 
186   bool erase(const KeyT &Val) {
187     BucketT *TheBucket;
188     if (!LookupBucketFor(Val, TheBucket))
189       return false;  // not in map.
190 
191     TheBucket->getSecond().~ValueT();
192     TheBucket->getFirst() = getTombstoneKey();
193     decrementNumEntries();
194     incrementNumTombstones();
195     return true;
196   }
197 
198   void erase(value_type *I) {
199     CHECK_NE(I, nullptr);
200     BucketT *TheBucket = &*I;
201     TheBucket->getSecond().~ValueT();
202     TheBucket->getFirst() = getTombstoneKey();
203     decrementNumEntries();
204     incrementNumTombstones();
205   }
206 
207   value_type &FindAndConstruct(const KeyT &Key) {
208     BucketT *TheBucket;
209     if (LookupBucketFor(Key, TheBucket))
210       return *TheBucket;
211 
212     return *InsertIntoBucket(TheBucket, Key);
213   }
214 
215   ValueT &operator[](const KeyT &Key) { return FindAndConstruct(Key).second; }
216 
217   value_type &FindAndConstruct(KeyT &&Key) {
218     BucketT *TheBucket;
219     if (LookupBucketFor(Key, TheBucket))
220       return *TheBucket;
221 
222     return *InsertIntoBucket(TheBucket, __sanitizer::move(Key));
223   }
224 
225   ValueT &operator[](KeyT &&Key) {
226     return FindAndConstruct(__sanitizer::move(Key)).second;
227   }
228 
229   /// Equality comparison for DenseMap.
230   ///
231   /// Iterates over elements of LHS confirming that each (key, value) pair in
232   /// LHS is also in RHS, and that no additional pairs are in RHS. Equivalent to
233   /// N calls to RHS.find and N value comparisons. Amortized complexity is
234   /// linear, worst case is O(N^2) (if every hash collides).
235   bool operator==(const DenseMapBase &RHS) const {
236     if (size() != RHS.size())
237       return false;
238 
239     const KeyT EmptyKey = getEmptyKey(), TombstoneKey = getTombstoneKey();
240     for (auto *P = getBuckets(), *E = getBucketsEnd(); P != E; ++P) {
241       const KeyT K = P->getFirst();
242       if (!KeyInfoT::isEqual(K, EmptyKey) &&
243           !KeyInfoT::isEqual(K, TombstoneKey)) {
244         const auto *I = RHS.find(K);
245         if (!I || P->getSecond() != I->getSecond())
246           return false;
247       }
248     }
249 
250     return true;
251   }
252 
253  protected:
254   DenseMapBase() = default;
255 
256   void destroyAll() {
257     if (getNumBuckets() == 0)  // Nothing to do.
258       return;
259 
260     const KeyT EmptyKey = getEmptyKey(), TombstoneKey = getTombstoneKey();
261     for (BucketT *P = getBuckets(), *E = getBucketsEnd(); P != E; ++P) {
262       if (!KeyInfoT::isEqual(P->getFirst(), EmptyKey) &&
263           !KeyInfoT::isEqual(P->getFirst(), TombstoneKey))
264         P->getSecond().~ValueT();
265       P->getFirst().~KeyT();
266     }
267   }
268 
269   void initEmpty() {
270     setNumEntries(0);
271     setNumTombstones(0);
272 
273     CHECK_EQ((getNumBuckets() & (getNumBuckets() - 1)), 0);
274     const KeyT EmptyKey = getEmptyKey();
275     for (BucketT *B = getBuckets(), *E = getBucketsEnd(); B != E; ++B)
276       ::new (&B->getFirst()) KeyT(EmptyKey);
277   }
278 
279   /// Returns the number of buckets to allocate to ensure that the DenseMap can
280   /// accommodate \p NumEntries without need to grow().
281   unsigned getMinBucketToReserveForEntries(unsigned NumEntries) {
282     // Ensure that "NumEntries * 4 < NumBuckets * 3"
283     if (NumEntries == 0)
284       return 0;
285     // +1 is required because of the strict equality.
286     // For example if NumEntries is 48, we need to return 401.
287     return RoundUpToPowerOfTwo((NumEntries * 4 / 3 + 1) + /* NextPowerOf2 */ 1);
288   }
289 
290   void moveFromOldBuckets(BucketT *OldBucketsBegin, BucketT *OldBucketsEnd) {
291     initEmpty();
292 
293     // Insert all the old elements.
294     const KeyT EmptyKey = getEmptyKey();
295     const KeyT TombstoneKey = getTombstoneKey();
296     for (BucketT *B = OldBucketsBegin, *E = OldBucketsEnd; B != E; ++B) {
297       if (!KeyInfoT::isEqual(B->getFirst(), EmptyKey) &&
298           !KeyInfoT::isEqual(B->getFirst(), TombstoneKey)) {
299         // Insert the key/value into the new table.
300         BucketT *DestBucket;
301         bool FoundVal = LookupBucketFor(B->getFirst(), DestBucket);
302         (void)FoundVal;  // silence warning.
303         CHECK(!FoundVal);
304         DestBucket->getFirst() = __sanitizer::move(B->getFirst());
305         ::new (&DestBucket->getSecond())
306             ValueT(__sanitizer::move(B->getSecond()));
307         incrementNumEntries();
308 
309         // Free the value.
310         B->getSecond().~ValueT();
311       }
312       B->getFirst().~KeyT();
313     }
314   }
315 
316   template <typename OtherBaseT>
317   void copyFrom(
318       const DenseMapBase<OtherBaseT, KeyT, ValueT, KeyInfoT, BucketT> &other) {
319     CHECK_NE(&other, this);
320     CHECK_EQ(getNumBuckets(), other.getNumBuckets());
321 
322     setNumEntries(other.getNumEntries());
323     setNumTombstones(other.getNumTombstones());
324 
325     if (__sanitizer::is_trivially_copyable<KeyT>::value &&
326         __sanitizer::is_trivially_copyable<ValueT>::value)
327       internal_memcpy(reinterpret_cast<void *>(getBuckets()),
328                       other.getBuckets(), getNumBuckets() * sizeof(BucketT));
329     else
330       for (uptr i = 0; i < getNumBuckets(); ++i) {
331         ::new (&getBuckets()[i].getFirst())
332             KeyT(other.getBuckets()[i].getFirst());
333         if (!KeyInfoT::isEqual(getBuckets()[i].getFirst(), getEmptyKey()) &&
334             !KeyInfoT::isEqual(getBuckets()[i].getFirst(), getTombstoneKey()))
335           ::new (&getBuckets()[i].getSecond())
336               ValueT(other.getBuckets()[i].getSecond());
337       }
338   }
339 
340   static unsigned getHashValue(const KeyT &Val) {
341     return KeyInfoT::getHashValue(Val);
342   }
343 
344   template <typename LookupKeyT>
345   static unsigned getHashValue(const LookupKeyT &Val) {
346     return KeyInfoT::getHashValue(Val);
347   }
348 
349   static const KeyT getEmptyKey() { return KeyInfoT::getEmptyKey(); }
350 
351   static const KeyT getTombstoneKey() { return KeyInfoT::getTombstoneKey(); }
352 
353  private:
354   unsigned getNumEntries() const {
355     return static_cast<const DerivedT *>(this)->getNumEntries();
356   }
357 
358   void setNumEntries(unsigned Num) {
359     static_cast<DerivedT *>(this)->setNumEntries(Num);
360   }
361 
362   void incrementNumEntries() { setNumEntries(getNumEntries() + 1); }
363 
364   void decrementNumEntries() { setNumEntries(getNumEntries() - 1); }
365 
366   unsigned getNumTombstones() const {
367     return static_cast<const DerivedT *>(this)->getNumTombstones();
368   }
369 
370   void setNumTombstones(unsigned Num) {
371     static_cast<DerivedT *>(this)->setNumTombstones(Num);
372   }
373 
374   void incrementNumTombstones() { setNumTombstones(getNumTombstones() + 1); }
375 
376   void decrementNumTombstones() { setNumTombstones(getNumTombstones() - 1); }
377 
378   const BucketT *getBuckets() const {
379     return static_cast<const DerivedT *>(this)->getBuckets();
380   }
381 
382   BucketT *getBuckets() { return static_cast<DerivedT *>(this)->getBuckets(); }
383 
384   unsigned getNumBuckets() const {
385     return static_cast<const DerivedT *>(this)->getNumBuckets();
386   }
387 
388   BucketT *getBucketsEnd() { return getBuckets() + getNumBuckets(); }
389 
390   const BucketT *getBucketsEnd() const {
391     return getBuckets() + getNumBuckets();
392   }
393 
394   void grow(unsigned AtLeast) { static_cast<DerivedT *>(this)->grow(AtLeast); }
395 
396   template <typename KeyArg, typename... ValueArgs>
397   BucketT *InsertIntoBucket(BucketT *TheBucket, KeyArg &&Key,
398                             ValueArgs &&...Values) {
399     TheBucket = InsertIntoBucketImpl(Key, Key, TheBucket);
400 
401     TheBucket->getFirst() = __sanitizer::forward<KeyArg>(Key);
402     ::new (&TheBucket->getSecond())
403         ValueT(__sanitizer::forward<ValueArgs>(Values)...);
404     return TheBucket;
405   }
406 
407   template <typename LookupKeyT>
408   BucketT *InsertIntoBucketWithLookup(BucketT *TheBucket, KeyT &&Key,
409                                       ValueT &&Value, LookupKeyT &Lookup) {
410     TheBucket = InsertIntoBucketImpl(Key, Lookup, TheBucket);
411 
412     TheBucket->getFirst() = __sanitizer::move(Key);
413     ::new (&TheBucket->getSecond()) ValueT(__sanitizer::move(Value));
414     return TheBucket;
415   }
416 
417   template <typename LookupKeyT>
418   BucketT *InsertIntoBucketImpl(const KeyT &Key, const LookupKeyT &Lookup,
419                                 BucketT *TheBucket) {
420     // If the load of the hash table is more than 3/4, or if fewer than 1/8 of
421     // the buckets are empty (meaning that many are filled with tombstones),
422     // grow the table.
423     //
424     // The later case is tricky.  For example, if we had one empty bucket with
425     // tons of tombstones, failing lookups (e.g. for insertion) would have to
426     // probe almost the entire table until it found the empty bucket.  If the
427     // table completely filled with tombstones, no lookup would ever succeed,
428     // causing infinite loops in lookup.
429     unsigned NewNumEntries = getNumEntries() + 1;
430     unsigned NumBuckets = getNumBuckets();
431     if (UNLIKELY(NewNumEntries * 4 >= NumBuckets * 3)) {
432       this->grow(NumBuckets * 2);
433       LookupBucketFor(Lookup, TheBucket);
434       NumBuckets = getNumBuckets();
435     } else if (UNLIKELY(NumBuckets - (NewNumEntries + getNumTombstones()) <=
436                         NumBuckets / 8)) {
437       this->grow(NumBuckets);
438       LookupBucketFor(Lookup, TheBucket);
439     }
440     CHECK(TheBucket);
441 
442     // Only update the state after we've grown our bucket space appropriately
443     // so that when growing buckets we have self-consistent entry count.
444     incrementNumEntries();
445 
446     // If we are writing over a tombstone, remember this.
447     const KeyT EmptyKey = getEmptyKey();
448     if (!KeyInfoT::isEqual(TheBucket->getFirst(), EmptyKey))
449       decrementNumTombstones();
450 
451     return TheBucket;
452   }
453 
454   /// LookupBucketFor - Lookup the appropriate bucket for Val, returning it in
455   /// FoundBucket.  If the bucket contains the key and a value, this returns
456   /// true, otherwise it returns a bucket with an empty marker or tombstone and
457   /// returns false.
458   template <typename LookupKeyT>
459   bool LookupBucketFor(const LookupKeyT &Val,
460                        const BucketT *&FoundBucket) const {
461     const BucketT *BucketsPtr = getBuckets();
462     const unsigned NumBuckets = getNumBuckets();
463 
464     if (NumBuckets == 0) {
465       FoundBucket = nullptr;
466       return false;
467     }
468 
469     // FoundTombstone - Keep track of whether we find a tombstone while probing.
470     const BucketT *FoundTombstone = nullptr;
471     const KeyT EmptyKey = getEmptyKey();
472     const KeyT TombstoneKey = getTombstoneKey();
473     CHECK(!KeyInfoT::isEqual(Val, EmptyKey));
474     CHECK(!KeyInfoT::isEqual(Val, TombstoneKey));
475 
476     unsigned BucketNo = getHashValue(Val) & (NumBuckets - 1);
477     unsigned ProbeAmt = 1;
478     while (true) {
479       const BucketT *ThisBucket = BucketsPtr + BucketNo;
480       // Found Val's bucket?  If so, return it.
481       if (LIKELY(KeyInfoT::isEqual(Val, ThisBucket->getFirst()))) {
482         FoundBucket = ThisBucket;
483         return true;
484       }
485 
486       // If we found an empty bucket, the key doesn't exist in the set.
487       // Insert it and return the default value.
488       if (LIKELY(KeyInfoT::isEqual(ThisBucket->getFirst(), EmptyKey))) {
489         // If we've already seen a tombstone while probing, fill it in instead
490         // of the empty bucket we eventually probed to.
491         FoundBucket = FoundTombstone ? FoundTombstone : ThisBucket;
492         return false;
493       }
494 
495       // If this is a tombstone, remember it.  If Val ends up not in the map, we
496       // prefer to return it than something that would require more probing.
497       if (KeyInfoT::isEqual(ThisBucket->getFirst(), TombstoneKey) &&
498           !FoundTombstone)
499         FoundTombstone = ThisBucket;  // Remember the first tombstone found.
500 
501       // Otherwise, it's a hash collision or a tombstone, continue quadratic
502       // probing.
503       BucketNo += ProbeAmt++;
504       BucketNo &= (NumBuckets - 1);
505     }
506   }
507 
508   template <typename LookupKeyT>
509   bool LookupBucketFor(const LookupKeyT &Val, BucketT *&FoundBucket) {
510     const BucketT *ConstFoundBucket;
511     bool Result = const_cast<const DenseMapBase *>(this)->LookupBucketFor(
512         Val, ConstFoundBucket);
513     FoundBucket = const_cast<BucketT *>(ConstFoundBucket);
514     return Result;
515   }
516 
517  public:
518   /// Return the approximate size (in bytes) of the actual map.
519   /// This is just the raw memory used by DenseMap.
520   /// If entries are pointers to objects, the size of the referenced objects
521   /// are not included.
522   uptr getMemorySize() const {
523     return RoundUpTo(getNumBuckets() * sizeof(BucketT), GetPageSizeCached());
524   }
525 };
526 
527 /// Inequality comparison for DenseMap.
528 ///
529 /// Equivalent to !(LHS == RHS). See operator== for performance notes.
530 template <typename DerivedT, typename KeyT, typename ValueT, typename KeyInfoT,
531           typename BucketT>
532 bool operator!=(
533     const DenseMapBase<DerivedT, KeyT, ValueT, KeyInfoT, BucketT> &LHS,
534     const DenseMapBase<DerivedT, KeyT, ValueT, KeyInfoT, BucketT> &RHS) {
535   return !(LHS == RHS);
536 }
537 
538 template <typename KeyT, typename ValueT,
539           typename KeyInfoT = DenseMapInfo<KeyT>,
540           typename BucketT = detail::DenseMapPair<KeyT, ValueT>>
541 class DenseMap : public DenseMapBase<DenseMap<KeyT, ValueT, KeyInfoT, BucketT>,
542                                      KeyT, ValueT, KeyInfoT, BucketT> {
543   friend class DenseMapBase<DenseMap, KeyT, ValueT, KeyInfoT, BucketT>;
544 
545   // Lift some types from the dependent base class into this class for
546   // simplicity of referring to them.
547   using BaseT = DenseMapBase<DenseMap, KeyT, ValueT, KeyInfoT, BucketT>;
548 
549   BucketT *Buckets = nullptr;
550   unsigned NumEntries = 0;
551   unsigned NumTombstones = 0;
552   unsigned NumBuckets = 0;
553 
554  public:
555   /// Create a DenseMap with an optional \p InitialReserve that guarantee that
556   /// this number of elements can be inserted in the map without grow()
557   explicit DenseMap(unsigned InitialReserve) { init(InitialReserve); }
558   constexpr DenseMap() = default;
559 
560   DenseMap(const DenseMap &other) : BaseT() {
561     init(0);
562     copyFrom(other);
563   }
564 
565   DenseMap(DenseMap &&other) : BaseT() {
566     init(0);
567     swap(other);
568   }
569 
570   ~DenseMap() {
571     this->destroyAll();
572     deallocate_buffer(Buckets, sizeof(BucketT) * NumBuckets);
573   }
574 
575   void swap(DenseMap &RHS) {
576     Swap(Buckets, RHS.Buckets);
577     Swap(NumEntries, RHS.NumEntries);
578     Swap(NumTombstones, RHS.NumTombstones);
579     Swap(NumBuckets, RHS.NumBuckets);
580   }
581 
582   DenseMap &operator=(const DenseMap &other) {
583     if (&other != this)
584       copyFrom(other);
585     return *this;
586   }
587 
588   DenseMap &operator=(DenseMap &&other) {
589     this->destroyAll();
590     deallocate_buffer(Buckets, sizeof(BucketT) * NumBuckets, alignof(BucketT));
591     init(0);
592     swap(other);
593     return *this;
594   }
595 
596   void copyFrom(const DenseMap &other) {
597     this->destroyAll();
598     deallocate_buffer(Buckets, sizeof(BucketT) * NumBuckets);
599     if (allocateBuckets(other.NumBuckets)) {
600       this->BaseT::copyFrom(other);
601     } else {
602       NumEntries = 0;
603       NumTombstones = 0;
604     }
605   }
606 
607   void init(unsigned InitNumEntries) {
608     auto InitBuckets = BaseT::getMinBucketToReserveForEntries(InitNumEntries);
609     if (allocateBuckets(InitBuckets)) {
610       this->BaseT::initEmpty();
611     } else {
612       NumEntries = 0;
613       NumTombstones = 0;
614     }
615   }
616 
617   void grow(unsigned AtLeast) {
618     unsigned OldNumBuckets = NumBuckets;
619     BucketT *OldBuckets = Buckets;
620 
621     allocateBuckets(RoundUpToPowerOfTwo(Max<unsigned>(64, AtLeast)));
622     CHECK(Buckets);
623     if (!OldBuckets) {
624       this->BaseT::initEmpty();
625       return;
626     }
627 
628     this->moveFromOldBuckets(OldBuckets, OldBuckets + OldNumBuckets);
629 
630     // Free the old table.
631     deallocate_buffer(OldBuckets, sizeof(BucketT) * OldNumBuckets);
632   }
633 
634  private:
635   unsigned getNumEntries() const { return NumEntries; }
636 
637   void setNumEntries(unsigned Num) { NumEntries = Num; }
638 
639   unsigned getNumTombstones() const { return NumTombstones; }
640 
641   void setNumTombstones(unsigned Num) { NumTombstones = Num; }
642 
643   BucketT *getBuckets() const { return Buckets; }
644 
645   unsigned getNumBuckets() const { return NumBuckets; }
646 
647   bool allocateBuckets(unsigned Num) {
648     NumBuckets = Num;
649     if (NumBuckets == 0) {
650       Buckets = nullptr;
651       return false;
652     }
653 
654     uptr Size = sizeof(BucketT) * NumBuckets;
655     if (Size * 2 <= GetPageSizeCached()) {
656       // We always allocate at least a page, so use entire space.
657       unsigned Log2 = MostSignificantSetBitIndex(GetPageSizeCached() / Size);
658       Size <<= Log2;
659       NumBuckets <<= Log2;
660       CHECK_EQ(Size, sizeof(BucketT) * NumBuckets);
661       CHECK_GT(Size * 2, GetPageSizeCached());
662     }
663     Buckets = static_cast<BucketT *>(allocate_buffer(Size));
664     return true;
665   }
666 
667   static void *allocate_buffer(uptr Size) {
668     return MmapOrDie(RoundUpTo(Size, GetPageSizeCached()), "DenseMap");
669   }
670 
671   static void deallocate_buffer(void *Ptr, uptr Size) {
672     UnmapOrDie(Ptr, RoundUpTo(Size, GetPageSizeCached()));
673   }
674 };
675 
676 }  // namespace __sanitizer
677 
678 #endif  // SANITIZER_DENSE_MAP_H
679