1 //===- llvm/ADT/DenseMap.h - Dense probed hash table ------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the DenseMap class.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_ADT_DENSEMAP_H
15 #define LLVM_ADT_DENSEMAP_H
17 #include "llvm/ADT/DenseMapInfo.h"
18 #include "llvm/ADT/EpochTracker.h"
19 #include "llvm/Support/AlignOf.h"
20 #include "llvm/Support/Compiler.h"
21 #include "llvm/Support/MathExtras.h"
22 #include "llvm/Support/ReverseIteration.h"
23 #include "llvm/Support/type_traits.h"
28 #include <initializer_list>
31 #include <type_traits>
38 // We extend a pair to allow users to override the bucket type with their own
39 // implementation without requiring two members.
40 template <typename KeyT, typename ValueT>
41 struct DenseMapPair : public std::pair<KeyT, ValueT> {
43 // FIXME: Switch to inheriting constructors when we drop support for older
45 // NOTE: This default constructor is declared with '{}' rather than
46 // '= default' to work around a separate bug in clang-3.8. This can
47 // also go when we switch to inheriting constructors.
50 DenseMapPair(const KeyT &Key, const ValueT &Value)
51 : std::pair<KeyT, ValueT>(Key, Value) {}
53 DenseMapPair(KeyT &&Key, ValueT &&Value)
54 : std::pair<KeyT, ValueT>(std::move(Key), std::move(Value)) {}
56 template <typename AltKeyT, typename AltValueT>
57 DenseMapPair(AltKeyT &&AltKey, AltValueT &&AltValue,
58 typename std::enable_if<
59 std::is_convertible<AltKeyT, KeyT>::value &&
60 std::is_convertible<AltValueT, ValueT>::value>::type * = 0)
61 : std::pair<KeyT, ValueT>(std::forward<AltKeyT>(AltKey),
62 std::forward<AltValueT>(AltValue)) {}
64 template <typename AltPairT>
65 DenseMapPair(AltPairT &&AltPair,
66 typename std::enable_if<std::is_convertible<
67 AltPairT, std::pair<KeyT, ValueT>>::value>::type * = 0)
68 : std::pair<KeyT, ValueT>(std::forward<AltPairT>(AltPair)) {}
70 KeyT &getFirst() { return std::pair<KeyT, ValueT>::first; }
71 const KeyT &getFirst() const { return std::pair<KeyT, ValueT>::first; }
72 ValueT &getSecond() { return std::pair<KeyT, ValueT>::second; }
73 const ValueT &getSecond() const { return std::pair<KeyT, ValueT>::second; }
76 } // end namespace detail
78 template <typename KeyT, typename ValueT,
79 typename KeyInfoT = DenseMapInfo<KeyT>,
80 typename Bucket = llvm::detail::DenseMapPair<KeyT, ValueT>,
82 class DenseMapIterator;
84 template <typename DerivedT, typename KeyT, typename ValueT, typename KeyInfoT,
86 class DenseMapBase : public DebugEpochBase {
88 using const_arg_type_t = typename const_pointer_or_const_ref<T>::type;
91 using size_type = unsigned;
92 using key_type = KeyT;
93 using mapped_type = ValueT;
94 using value_type = BucketT;
96 using iterator = DenseMapIterator<KeyT, ValueT, KeyInfoT, BucketT>;
97 using const_iterator =
98 DenseMapIterator<KeyT, ValueT, KeyInfoT, BucketT, true>;
100 inline iterator begin() {
101 // When the map is empty, avoid the overhead of advancing/retreating past
105 if (shouldReverseIterate<KeyT>())
106 return makeIterator(getBucketsEnd() - 1, getBuckets(), *this);
107 return makeIterator(getBuckets(), getBucketsEnd(), *this);
109 inline iterator end() {
110 return makeIterator(getBucketsEnd(), getBucketsEnd(), *this, true);
112 inline const_iterator begin() const {
115 if (shouldReverseIterate<KeyT>())
116 return makeConstIterator(getBucketsEnd() - 1, getBuckets(), *this);
117 return makeConstIterator(getBuckets(), getBucketsEnd(), *this);
119 inline const_iterator end() const {
120 return makeConstIterator(getBucketsEnd(), getBucketsEnd(), *this, true);
123 LLVM_NODISCARD bool empty() const {
124 return getNumEntries() == 0;
126 unsigned size() const { return getNumEntries(); }
128 /// Grow the densemap so that it can contain at least \p NumEntries items
129 /// before resizing again.
130 void reserve(size_type NumEntries) {
131 auto NumBuckets = getMinBucketToReserveForEntries(NumEntries);
133 if (NumBuckets > getNumBuckets())
139 if (getNumEntries() == 0 && getNumTombstones() == 0) return;
141 // If the capacity of the array is huge, and the # elements used is small,
143 if (getNumEntries() * 4 < getNumBuckets() && getNumBuckets() > 64) {
148 const KeyT EmptyKey = getEmptyKey(), TombstoneKey = getTombstoneKey();
149 if (isPodLike<KeyT>::value && isPodLike<ValueT>::value) {
150 // Use a simpler loop when these are trivial types.
151 for (BucketT *P = getBuckets(), *E = getBucketsEnd(); P != E; ++P)
152 P->getFirst() = EmptyKey;
154 unsigned NumEntries = getNumEntries();
155 for (BucketT *P = getBuckets(), *E = getBucketsEnd(); P != E; ++P) {
156 if (!KeyInfoT::isEqual(P->getFirst(), EmptyKey)) {
157 if (!KeyInfoT::isEqual(P->getFirst(), TombstoneKey)) {
158 P->getSecond().~ValueT();
161 P->getFirst() = EmptyKey;
164 assert(NumEntries == 0 && "Node count imbalance!");
170 /// Return 1 if the specified key is in the map, 0 otherwise.
171 size_type count(const_arg_type_t<KeyT> Val) const {
172 const BucketT *TheBucket;
173 return LookupBucketFor(Val, TheBucket) ? 1 : 0;
176 iterator find(const_arg_type_t<KeyT> Val) {
178 if (LookupBucketFor(Val, TheBucket))
179 return makeIterator(TheBucket, getBucketsEnd(), *this, true);
182 const_iterator find(const_arg_type_t<KeyT> Val) const {
183 const BucketT *TheBucket;
184 if (LookupBucketFor(Val, TheBucket))
185 return makeConstIterator(TheBucket, getBucketsEnd(), *this, true);
189 /// Alternate version of find() which allows a different, and possibly
190 /// less expensive, key type.
191 /// The DenseMapInfo is responsible for supplying methods
192 /// getHashValue(LookupKeyT) and isEqual(LookupKeyT, KeyT) for each key
194 template<class LookupKeyT>
195 iterator find_as(const LookupKeyT &Val) {
197 if (LookupBucketFor(Val, TheBucket))
198 return makeIterator(TheBucket, getBucketsEnd(), *this, true);
201 template<class LookupKeyT>
202 const_iterator find_as(const LookupKeyT &Val) const {
203 const BucketT *TheBucket;
204 if (LookupBucketFor(Val, TheBucket))
205 return makeConstIterator(TheBucket, getBucketsEnd(), *this, true);
209 /// lookup - Return the entry for the specified key, or a default
210 /// constructed value if no such entry exists.
211 ValueT lookup(const_arg_type_t<KeyT> Val) const {
212 const BucketT *TheBucket;
213 if (LookupBucketFor(Val, TheBucket))
214 return TheBucket->getSecond();
218 // Inserts key,value pair into the map if the key isn't already in the map.
219 // If the key is already in the map, it returns false and doesn't update the
221 std::pair<iterator, bool> insert(const std::pair<KeyT, ValueT> &KV) {
222 return try_emplace(KV.first, KV.second);
225 // Inserts key,value pair into the map if the key isn't already in the map.
226 // If the key is already in the map, it returns false and doesn't update the
228 std::pair<iterator, bool> insert(std::pair<KeyT, ValueT> &&KV) {
229 return try_emplace(std::move(KV.first), std::move(KV.second));
232 // Inserts key,value pair into the map if the key isn't already in the map.
233 // The value is constructed in-place if the key is not in the map, otherwise
235 template <typename... Ts>
236 std::pair<iterator, bool> try_emplace(KeyT &&Key, Ts &&... Args) {
238 if (LookupBucketFor(Key, TheBucket))
239 return std::make_pair(
240 makeIterator(TheBucket, getBucketsEnd(), *this, true),
241 false); // Already in map.
243 // Otherwise, insert the new element.
245 InsertIntoBucket(TheBucket, std::move(Key), std::forward<Ts>(Args)...);
246 return std::make_pair(
247 makeIterator(TheBucket, getBucketsEnd(), *this, true),
251 // Inserts key,value pair into the map if the key isn't already in the map.
252 // The value is constructed in-place if the key is not in the map, otherwise
254 template <typename... Ts>
255 std::pair<iterator, bool> try_emplace(const KeyT &Key, Ts &&... Args) {
257 if (LookupBucketFor(Key, TheBucket))
258 return std::make_pair(
259 makeIterator(TheBucket, getBucketsEnd(), *this, true),
260 false); // Already in map.
262 // Otherwise, insert the new element.
263 TheBucket = InsertIntoBucket(TheBucket, Key, std::forward<Ts>(Args)...);
264 return std::make_pair(
265 makeIterator(TheBucket, getBucketsEnd(), *this, true),
269 /// Alternate version of insert() which allows a different, and possibly
270 /// less expensive, key type.
271 /// The DenseMapInfo is responsible for supplying methods
272 /// getHashValue(LookupKeyT) and isEqual(LookupKeyT, KeyT) for each key
274 template <typename LookupKeyT>
275 std::pair<iterator, bool> insert_as(std::pair<KeyT, ValueT> &&KV,
276 const LookupKeyT &Val) {
278 if (LookupBucketFor(Val, TheBucket))
279 return std::make_pair(
280 makeIterator(TheBucket, getBucketsEnd(), *this, true),
281 false); // Already in map.
283 // Otherwise, insert the new element.
284 TheBucket = InsertIntoBucketWithLookup(TheBucket, std::move(KV.first),
285 std::move(KV.second), Val);
286 return std::make_pair(
287 makeIterator(TheBucket, getBucketsEnd(), *this, true),
291 /// insert - Range insertion of pairs.
292 template<typename InputIt>
293 void insert(InputIt I, InputIt E) {
298 bool erase(const KeyT &Val) {
300 if (!LookupBucketFor(Val, TheBucket))
301 return false; // not in map.
303 TheBucket->getSecond().~ValueT();
304 TheBucket->getFirst() = getTombstoneKey();
305 decrementNumEntries();
306 incrementNumTombstones();
309 void erase(iterator I) {
310 BucketT *TheBucket = &*I;
311 TheBucket->getSecond().~ValueT();
312 TheBucket->getFirst() = getTombstoneKey();
313 decrementNumEntries();
314 incrementNumTombstones();
317 value_type& FindAndConstruct(const KeyT &Key) {
319 if (LookupBucketFor(Key, TheBucket))
322 return *InsertIntoBucket(TheBucket, Key);
325 ValueT &operator[](const KeyT &Key) {
326 return FindAndConstruct(Key).second;
329 value_type& FindAndConstruct(KeyT &&Key) {
331 if (LookupBucketFor(Key, TheBucket))
334 return *InsertIntoBucket(TheBucket, std::move(Key));
337 ValueT &operator[](KeyT &&Key) {
338 return FindAndConstruct(std::move(Key)).second;
341 /// isPointerIntoBucketsArray - Return true if the specified pointer points
342 /// somewhere into the DenseMap's array of buckets (i.e. either to a key or
343 /// value in the DenseMap).
344 bool isPointerIntoBucketsArray(const void *Ptr) const {
345 return Ptr >= getBuckets() && Ptr < getBucketsEnd();
348 /// getPointerIntoBucketsArray() - Return an opaque pointer into the buckets
349 /// array. In conjunction with the previous method, this can be used to
350 /// determine whether an insertion caused the DenseMap to reallocate.
351 const void *getPointerIntoBucketsArray() const { return getBuckets(); }
354 DenseMapBase() = default;
357 if (getNumBuckets() == 0) // Nothing to do.
360 const KeyT EmptyKey = getEmptyKey(), TombstoneKey = getTombstoneKey();
361 for (BucketT *P = getBuckets(), *E = getBucketsEnd(); P != E; ++P) {
362 if (!KeyInfoT::isEqual(P->getFirst(), EmptyKey) &&
363 !KeyInfoT::isEqual(P->getFirst(), TombstoneKey))
364 P->getSecond().~ValueT();
365 P->getFirst().~KeyT();
373 assert((getNumBuckets() & (getNumBuckets()-1)) == 0 &&
374 "# initial buckets must be a power of two!");
375 const KeyT EmptyKey = getEmptyKey();
376 for (BucketT *B = getBuckets(), *E = getBucketsEnd(); B != E; ++B)
377 ::new (&B->getFirst()) KeyT(EmptyKey);
380 /// Returns the number of buckets to allocate to ensure that the DenseMap can
381 /// accommodate \p NumEntries without need to grow().
382 unsigned getMinBucketToReserveForEntries(unsigned NumEntries) {
383 // Ensure that "NumEntries * 4 < NumBuckets * 3"
386 // +1 is required because of the strict equality.
387 // For example if NumEntries is 48, we need to return 401.
388 return NextPowerOf2(NumEntries * 4 / 3 + 1);
391 void moveFromOldBuckets(BucketT *OldBucketsBegin, BucketT *OldBucketsEnd) {
394 // Insert all the old elements.
395 const KeyT EmptyKey = getEmptyKey();
396 const KeyT TombstoneKey = getTombstoneKey();
397 for (BucketT *B = OldBucketsBegin, *E = OldBucketsEnd; B != E; ++B) {
398 if (!KeyInfoT::isEqual(B->getFirst(), EmptyKey) &&
399 !KeyInfoT::isEqual(B->getFirst(), TombstoneKey)) {
400 // Insert the key/value into the new table.
402 bool FoundVal = LookupBucketFor(B->getFirst(), DestBucket);
403 (void)FoundVal; // silence warning.
404 assert(!FoundVal && "Key already in new map?");
405 DestBucket->getFirst() = std::move(B->getFirst());
406 ::new (&DestBucket->getSecond()) ValueT(std::move(B->getSecond()));
407 incrementNumEntries();
410 B->getSecond().~ValueT();
412 B->getFirst().~KeyT();
416 template <typename OtherBaseT>
418 const DenseMapBase<OtherBaseT, KeyT, ValueT, KeyInfoT, BucketT> &other) {
419 assert(&other != this);
420 assert(getNumBuckets() == other.getNumBuckets());
422 setNumEntries(other.getNumEntries());
423 setNumTombstones(other.getNumTombstones());
425 if (isPodLike<KeyT>::value && isPodLike<ValueT>::value)
426 memcpy(reinterpret_cast<void *>(getBuckets()), other.getBuckets(),
427 getNumBuckets() * sizeof(BucketT));
429 for (size_t i = 0; i < getNumBuckets(); ++i) {
430 ::new (&getBuckets()[i].getFirst())
431 KeyT(other.getBuckets()[i].getFirst());
432 if (!KeyInfoT::isEqual(getBuckets()[i].getFirst(), getEmptyKey()) &&
433 !KeyInfoT::isEqual(getBuckets()[i].getFirst(), getTombstoneKey()))
434 ::new (&getBuckets()[i].getSecond())
435 ValueT(other.getBuckets()[i].getSecond());
439 static unsigned getHashValue(const KeyT &Val) {
440 return KeyInfoT::getHashValue(Val);
443 template<typename LookupKeyT>
444 static unsigned getHashValue(const LookupKeyT &Val) {
445 return KeyInfoT::getHashValue(Val);
448 static const KeyT getEmptyKey() {
449 static_assert(std::is_base_of<DenseMapBase, DerivedT>::value,
450 "Must pass the derived type to this template!");
451 return KeyInfoT::getEmptyKey();
454 static const KeyT getTombstoneKey() {
455 return KeyInfoT::getTombstoneKey();
459 iterator makeIterator(BucketT *P, BucketT *E,
460 DebugEpochBase &Epoch,
461 bool NoAdvance=false) {
462 if (shouldReverseIterate<KeyT>()) {
463 BucketT *B = P == getBucketsEnd() ? getBuckets() : P + 1;
464 return iterator(B, E, Epoch, NoAdvance);
466 return iterator(P, E, Epoch, NoAdvance);
469 const_iterator makeConstIterator(const BucketT *P, const BucketT *E,
470 const DebugEpochBase &Epoch,
471 const bool NoAdvance=false) const {
472 if (shouldReverseIterate<KeyT>()) {
473 const BucketT *B = P == getBucketsEnd() ? getBuckets() : P + 1;
474 return const_iterator(B, E, Epoch, NoAdvance);
476 return const_iterator(P, E, Epoch, NoAdvance);
479 unsigned getNumEntries() const {
480 return static_cast<const DerivedT *>(this)->getNumEntries();
483 void setNumEntries(unsigned Num) {
484 static_cast<DerivedT *>(this)->setNumEntries(Num);
487 void incrementNumEntries() {
488 setNumEntries(getNumEntries() + 1);
491 void decrementNumEntries() {
492 setNumEntries(getNumEntries() - 1);
495 unsigned getNumTombstones() const {
496 return static_cast<const DerivedT *>(this)->getNumTombstones();
499 void setNumTombstones(unsigned Num) {
500 static_cast<DerivedT *>(this)->setNumTombstones(Num);
503 void incrementNumTombstones() {
504 setNumTombstones(getNumTombstones() + 1);
507 void decrementNumTombstones() {
508 setNumTombstones(getNumTombstones() - 1);
511 const BucketT *getBuckets() const {
512 return static_cast<const DerivedT *>(this)->getBuckets();
515 BucketT *getBuckets() {
516 return static_cast<DerivedT *>(this)->getBuckets();
519 unsigned getNumBuckets() const {
520 return static_cast<const DerivedT *>(this)->getNumBuckets();
523 BucketT *getBucketsEnd() {
524 return getBuckets() + getNumBuckets();
527 const BucketT *getBucketsEnd() const {
528 return getBuckets() + getNumBuckets();
531 void grow(unsigned AtLeast) {
532 static_cast<DerivedT *>(this)->grow(AtLeast);
535 void shrink_and_clear() {
536 static_cast<DerivedT *>(this)->shrink_and_clear();
539 template <typename KeyArg, typename... ValueArgs>
540 BucketT *InsertIntoBucket(BucketT *TheBucket, KeyArg &&Key,
541 ValueArgs &&... Values) {
542 TheBucket = InsertIntoBucketImpl(Key, Key, TheBucket);
544 TheBucket->getFirst() = std::forward<KeyArg>(Key);
545 ::new (&TheBucket->getSecond()) ValueT(std::forward<ValueArgs>(Values)...);
549 template <typename LookupKeyT>
550 BucketT *InsertIntoBucketWithLookup(BucketT *TheBucket, KeyT &&Key,
551 ValueT &&Value, LookupKeyT &Lookup) {
552 TheBucket = InsertIntoBucketImpl(Key, Lookup, TheBucket);
554 TheBucket->getFirst() = std::move(Key);
555 ::new (&TheBucket->getSecond()) ValueT(std::move(Value));
559 template <typename LookupKeyT>
560 BucketT *InsertIntoBucketImpl(const KeyT &Key, const LookupKeyT &Lookup,
561 BucketT *TheBucket) {
564 // If the load of the hash table is more than 3/4, or if fewer than 1/8 of
565 // the buckets are empty (meaning that many are filled with tombstones),
568 // The later case is tricky. For example, if we had one empty bucket with
569 // tons of tombstones, failing lookups (e.g. for insertion) would have to
570 // probe almost the entire table until it found the empty bucket. If the
571 // table completely filled with tombstones, no lookup would ever succeed,
572 // causing infinite loops in lookup.
573 unsigned NewNumEntries = getNumEntries() + 1;
574 unsigned NumBuckets = getNumBuckets();
575 if (LLVM_UNLIKELY(NewNumEntries * 4 >= NumBuckets * 3)) {
576 this->grow(NumBuckets * 2);
577 LookupBucketFor(Lookup, TheBucket);
578 NumBuckets = getNumBuckets();
579 } else if (LLVM_UNLIKELY(NumBuckets-(NewNumEntries+getNumTombstones()) <=
581 this->grow(NumBuckets);
582 LookupBucketFor(Lookup, TheBucket);
586 // Only update the state after we've grown our bucket space appropriately
587 // so that when growing buckets we have self-consistent entry count.
588 incrementNumEntries();
590 // If we are writing over a tombstone, remember this.
591 const KeyT EmptyKey = getEmptyKey();
592 if (!KeyInfoT::isEqual(TheBucket->getFirst(), EmptyKey))
593 decrementNumTombstones();
598 /// LookupBucketFor - Lookup the appropriate bucket for Val, returning it in
599 /// FoundBucket. If the bucket contains the key and a value, this returns
600 /// true, otherwise it returns a bucket with an empty marker or tombstone and
602 template<typename LookupKeyT>
603 bool LookupBucketFor(const LookupKeyT &Val,
604 const BucketT *&FoundBucket) const {
605 const BucketT *BucketsPtr = getBuckets();
606 const unsigned NumBuckets = getNumBuckets();
608 if (NumBuckets == 0) {
609 FoundBucket = nullptr;
613 // FoundTombstone - Keep track of whether we find a tombstone while probing.
614 const BucketT *FoundTombstone = nullptr;
615 const KeyT EmptyKey = getEmptyKey();
616 const KeyT TombstoneKey = getTombstoneKey();
617 assert(!KeyInfoT::isEqual(Val, EmptyKey) &&
618 !KeyInfoT::isEqual(Val, TombstoneKey) &&
619 "Empty/Tombstone value shouldn't be inserted into map!");
621 unsigned BucketNo = getHashValue(Val) & (NumBuckets-1);
622 unsigned ProbeAmt = 1;
624 const BucketT *ThisBucket = BucketsPtr + BucketNo;
625 // Found Val's bucket? If so, return it.
626 if (LLVM_LIKELY(KeyInfoT::isEqual(Val, ThisBucket->getFirst()))) {
627 FoundBucket = ThisBucket;
631 // If we found an empty bucket, the key doesn't exist in the set.
632 // Insert it and return the default value.
633 if (LLVM_LIKELY(KeyInfoT::isEqual(ThisBucket->getFirst(), EmptyKey))) {
634 // If we've already seen a tombstone while probing, fill it in instead
635 // of the empty bucket we eventually probed to.
636 FoundBucket = FoundTombstone ? FoundTombstone : ThisBucket;
640 // If this is a tombstone, remember it. If Val ends up not in the map, we
641 // prefer to return it than something that would require more probing.
642 if (KeyInfoT::isEqual(ThisBucket->getFirst(), TombstoneKey) &&
644 FoundTombstone = ThisBucket; // Remember the first tombstone found.
646 // Otherwise, it's a hash collision or a tombstone, continue quadratic
648 BucketNo += ProbeAmt++;
649 BucketNo &= (NumBuckets-1);
653 template <typename LookupKeyT>
654 bool LookupBucketFor(const LookupKeyT &Val, BucketT *&FoundBucket) {
655 const BucketT *ConstFoundBucket;
656 bool Result = const_cast<const DenseMapBase *>(this)
657 ->LookupBucketFor(Val, ConstFoundBucket);
658 FoundBucket = const_cast<BucketT *>(ConstFoundBucket);
663 /// Return the approximate size (in bytes) of the actual map.
664 /// This is just the raw memory used by DenseMap.
665 /// If entries are pointers to objects, the size of the referenced objects
666 /// are not included.
667 size_t getMemorySize() const {
668 return getNumBuckets() * sizeof(BucketT);
672 /// Equality comparison for DenseMap.
674 /// Iterates over elements of LHS confirming that each (key, value) pair in LHS
675 /// is also in RHS, and that no additional pairs are in RHS.
676 /// Equivalent to N calls to RHS.find and N value comparisons. Amortized
677 /// complexity is linear, worst case is O(N^2) (if every hash collides).
678 template <typename DerivedT, typename KeyT, typename ValueT, typename KeyInfoT,
681 const DenseMapBase<DerivedT, KeyT, ValueT, KeyInfoT, BucketT> &LHS,
682 const DenseMapBase<DerivedT, KeyT, ValueT, KeyInfoT, BucketT> &RHS) {
683 if (LHS.size() != RHS.size())
686 for (auto &KV : LHS) {
687 auto I = RHS.find(KV.first);
688 if (I == RHS.end() || I->second != KV.second)
695 /// Inequality comparison for DenseMap.
697 /// Equivalent to !(LHS == RHS). See operator== for performance notes.
698 template <typename DerivedT, typename KeyT, typename ValueT, typename KeyInfoT,
701 const DenseMapBase<DerivedT, KeyT, ValueT, KeyInfoT, BucketT> &LHS,
702 const DenseMapBase<DerivedT, KeyT, ValueT, KeyInfoT, BucketT> &RHS) {
703 return !(LHS == RHS);
706 template <typename KeyT, typename ValueT,
707 typename KeyInfoT = DenseMapInfo<KeyT>,
708 typename BucketT = llvm::detail::DenseMapPair<KeyT, ValueT>>
709 class DenseMap : public DenseMapBase<DenseMap<KeyT, ValueT, KeyInfoT, BucketT>,
710 KeyT, ValueT, KeyInfoT, BucketT> {
711 friend class DenseMapBase<DenseMap, KeyT, ValueT, KeyInfoT, BucketT>;
713 // Lift some types from the dependent base class into this class for
714 // simplicity of referring to them.
715 using BaseT = DenseMapBase<DenseMap, KeyT, ValueT, KeyInfoT, BucketT>;
719 unsigned NumTombstones;
723 /// Create a DenseMap wth an optional \p InitialReserve that guarantee that
724 /// this number of elements can be inserted in the map without grow()
725 explicit DenseMap(unsigned InitialReserve = 0) { init(InitialReserve); }
727 DenseMap(const DenseMap &other) : BaseT() {
732 DenseMap(DenseMap &&other) : BaseT() {
737 template<typename InputIt>
738 DenseMap(const InputIt &I, const InputIt &E) {
739 init(std::distance(I, E));
743 DenseMap(std::initializer_list<typename BaseT::value_type> Vals) {
745 this->insert(Vals.begin(), Vals.end());
750 operator delete(Buckets);
753 void swap(DenseMap& RHS) {
754 this->incrementEpoch();
755 RHS.incrementEpoch();
756 std::swap(Buckets, RHS.Buckets);
757 std::swap(NumEntries, RHS.NumEntries);
758 std::swap(NumTombstones, RHS.NumTombstones);
759 std::swap(NumBuckets, RHS.NumBuckets);
762 DenseMap& operator=(const DenseMap& other) {
768 DenseMap& operator=(DenseMap &&other) {
770 operator delete(Buckets);
776 void copyFrom(const DenseMap& other) {
778 operator delete(Buckets);
779 if (allocateBuckets(other.NumBuckets)) {
780 this->BaseT::copyFrom(other);
787 void init(unsigned InitNumEntries) {
788 auto InitBuckets = BaseT::getMinBucketToReserveForEntries(InitNumEntries);
789 if (allocateBuckets(InitBuckets)) {
790 this->BaseT::initEmpty();
797 void grow(unsigned AtLeast) {
798 unsigned OldNumBuckets = NumBuckets;
799 BucketT *OldBuckets = Buckets;
801 allocateBuckets(std::max<unsigned>(64, static_cast<unsigned>(NextPowerOf2(AtLeast-1))));
804 this->BaseT::initEmpty();
808 this->moveFromOldBuckets(OldBuckets, OldBuckets+OldNumBuckets);
810 // Free the old table.
811 operator delete(OldBuckets);
814 void shrink_and_clear() {
815 unsigned OldNumEntries = NumEntries;
818 // Reduce the number of buckets.
819 unsigned NewNumBuckets = 0;
821 NewNumBuckets = std::max(64, 1 << (Log2_32_Ceil(OldNumEntries) + 1));
822 if (NewNumBuckets == NumBuckets) {
823 this->BaseT::initEmpty();
827 operator delete(Buckets);
832 unsigned getNumEntries() const {
836 void setNumEntries(unsigned Num) {
840 unsigned getNumTombstones() const {
841 return NumTombstones;
844 void setNumTombstones(unsigned Num) {
848 BucketT *getBuckets() const {
852 unsigned getNumBuckets() const {
856 bool allocateBuckets(unsigned Num) {
858 if (NumBuckets == 0) {
863 Buckets = static_cast<BucketT*>(operator new(sizeof(BucketT) * NumBuckets));
868 template <typename KeyT, typename ValueT, unsigned InlineBuckets = 4,
869 typename KeyInfoT = DenseMapInfo<KeyT>,
870 typename BucketT = llvm::detail::DenseMapPair<KeyT, ValueT>>
872 : public DenseMapBase<
873 SmallDenseMap<KeyT, ValueT, InlineBuckets, KeyInfoT, BucketT>, KeyT,
874 ValueT, KeyInfoT, BucketT> {
875 friend class DenseMapBase<SmallDenseMap, KeyT, ValueT, KeyInfoT, BucketT>;
877 // Lift some types from the dependent base class into this class for
878 // simplicity of referring to them.
879 using BaseT = DenseMapBase<SmallDenseMap, KeyT, ValueT, KeyInfoT, BucketT>;
881 static_assert(isPowerOf2_64(InlineBuckets),
882 "InlineBuckets must be a power of 2.");
885 unsigned NumEntries : 31;
886 unsigned NumTombstones;
893 /// A "union" of an inline bucket array and the struct representing
894 /// a large bucket. This union will be discriminated by the 'Small' bit.
895 AlignedCharArrayUnion<BucketT[InlineBuckets], LargeRep> storage;
898 explicit SmallDenseMap(unsigned NumInitBuckets = 0) {
899 init(NumInitBuckets);
902 SmallDenseMap(const SmallDenseMap &other) : BaseT() {
907 SmallDenseMap(SmallDenseMap &&other) : BaseT() {
912 template<typename InputIt>
913 SmallDenseMap(const InputIt &I, const InputIt &E) {
914 init(NextPowerOf2(std::distance(I, E)));
923 void swap(SmallDenseMap& RHS) {
924 unsigned TmpNumEntries = RHS.NumEntries;
925 RHS.NumEntries = NumEntries;
926 NumEntries = TmpNumEntries;
927 std::swap(NumTombstones, RHS.NumTombstones);
929 const KeyT EmptyKey = this->getEmptyKey();
930 const KeyT TombstoneKey = this->getTombstoneKey();
931 if (Small && RHS.Small) {
932 // If we're swapping inline bucket arrays, we have to cope with some of
933 // the tricky bits of DenseMap's storage system: the buckets are not
934 // fully initialized. Thus we swap every key, but we may have
935 // a one-directional move of the value.
936 for (unsigned i = 0, e = InlineBuckets; i != e; ++i) {
937 BucketT *LHSB = &getInlineBuckets()[i],
938 *RHSB = &RHS.getInlineBuckets()[i];
939 bool hasLHSValue = (!KeyInfoT::isEqual(LHSB->getFirst(), EmptyKey) &&
940 !KeyInfoT::isEqual(LHSB->getFirst(), TombstoneKey));
941 bool hasRHSValue = (!KeyInfoT::isEqual(RHSB->getFirst(), EmptyKey) &&
942 !KeyInfoT::isEqual(RHSB->getFirst(), TombstoneKey));
943 if (hasLHSValue && hasRHSValue) {
944 // Swap together if we can...
945 std::swap(*LHSB, *RHSB);
948 // Swap separately and handle any assymetry.
949 std::swap(LHSB->getFirst(), RHSB->getFirst());
951 ::new (&RHSB->getSecond()) ValueT(std::move(LHSB->getSecond()));
952 LHSB->getSecond().~ValueT();
953 } else if (hasRHSValue) {
954 ::new (&LHSB->getSecond()) ValueT(std::move(RHSB->getSecond()));
955 RHSB->getSecond().~ValueT();
960 if (!Small && !RHS.Small) {
961 std::swap(getLargeRep()->Buckets, RHS.getLargeRep()->Buckets);
962 std::swap(getLargeRep()->NumBuckets, RHS.getLargeRep()->NumBuckets);
966 SmallDenseMap &SmallSide = Small ? *this : RHS;
967 SmallDenseMap &LargeSide = Small ? RHS : *this;
969 // First stash the large side's rep and move the small side across.
970 LargeRep TmpRep = std::move(*LargeSide.getLargeRep());
971 LargeSide.getLargeRep()->~LargeRep();
972 LargeSide.Small = true;
973 // This is similar to the standard move-from-old-buckets, but the bucket
974 // count hasn't actually rotated in this case. So we have to carefully
975 // move construct the keys and values into their new locations, but there
976 // is no need to re-hash things.
977 for (unsigned i = 0, e = InlineBuckets; i != e; ++i) {
978 BucketT *NewB = &LargeSide.getInlineBuckets()[i],
979 *OldB = &SmallSide.getInlineBuckets()[i];
980 ::new (&NewB->getFirst()) KeyT(std::move(OldB->getFirst()));
981 OldB->getFirst().~KeyT();
982 if (!KeyInfoT::isEqual(NewB->getFirst(), EmptyKey) &&
983 !KeyInfoT::isEqual(NewB->getFirst(), TombstoneKey)) {
984 ::new (&NewB->getSecond()) ValueT(std::move(OldB->getSecond()));
985 OldB->getSecond().~ValueT();
989 // The hard part of moving the small buckets across is done, just move
990 // the TmpRep into its new home.
991 SmallSide.Small = false;
992 new (SmallSide.getLargeRep()) LargeRep(std::move(TmpRep));
995 SmallDenseMap& operator=(const SmallDenseMap& other) {
1001 SmallDenseMap& operator=(SmallDenseMap &&other) {
1003 deallocateBuckets();
1009 void copyFrom(const SmallDenseMap& other) {
1011 deallocateBuckets();
1013 if (other.getNumBuckets() > InlineBuckets) {
1015 new (getLargeRep()) LargeRep(allocateBuckets(other.getNumBuckets()));
1017 this->BaseT::copyFrom(other);
1020 void init(unsigned InitBuckets) {
1022 if (InitBuckets > InlineBuckets) {
1024 new (getLargeRep()) LargeRep(allocateBuckets(InitBuckets));
1026 this->BaseT::initEmpty();
1029 void grow(unsigned AtLeast) {
1030 if (AtLeast >= InlineBuckets)
1031 AtLeast = std::max<unsigned>(64, NextPowerOf2(AtLeast-1));
1034 if (AtLeast < InlineBuckets)
1035 return; // Nothing to do.
1037 // First move the inline buckets into a temporary storage.
1038 AlignedCharArrayUnion<BucketT[InlineBuckets]> TmpStorage;
1039 BucketT *TmpBegin = reinterpret_cast<BucketT *>(TmpStorage.buffer);
1040 BucketT *TmpEnd = TmpBegin;
1042 // Loop over the buckets, moving non-empty, non-tombstones into the
1043 // temporary storage. Have the loop move the TmpEnd forward as it goes.
1044 const KeyT EmptyKey = this->getEmptyKey();
1045 const KeyT TombstoneKey = this->getTombstoneKey();
1046 for (BucketT *P = getBuckets(), *E = P + InlineBuckets; P != E; ++P) {
1047 if (!KeyInfoT::isEqual(P->getFirst(), EmptyKey) &&
1048 !KeyInfoT::isEqual(P->getFirst(), TombstoneKey)) {
1049 assert(size_t(TmpEnd - TmpBegin) < InlineBuckets &&
1050 "Too many inline buckets!");
1051 ::new (&TmpEnd->getFirst()) KeyT(std::move(P->getFirst()));
1052 ::new (&TmpEnd->getSecond()) ValueT(std::move(P->getSecond()));
1054 P->getSecond().~ValueT();
1056 P->getFirst().~KeyT();
1059 // Now make this map use the large rep, and move all the entries back
1062 new (getLargeRep()) LargeRep(allocateBuckets(AtLeast));
1063 this->moveFromOldBuckets(TmpBegin, TmpEnd);
1067 LargeRep OldRep = std::move(*getLargeRep());
1068 getLargeRep()->~LargeRep();
1069 if (AtLeast <= InlineBuckets) {
1072 new (getLargeRep()) LargeRep(allocateBuckets(AtLeast));
1075 this->moveFromOldBuckets(OldRep.Buckets, OldRep.Buckets+OldRep.NumBuckets);
1077 // Free the old table.
1078 operator delete(OldRep.Buckets);
1081 void shrink_and_clear() {
1082 unsigned OldSize = this->size();
1085 // Reduce the number of buckets.
1086 unsigned NewNumBuckets = 0;
1088 NewNumBuckets = 1 << (Log2_32_Ceil(OldSize) + 1);
1089 if (NewNumBuckets > InlineBuckets && NewNumBuckets < 64u)
1092 if ((Small && NewNumBuckets <= InlineBuckets) ||
1093 (!Small && NewNumBuckets == getLargeRep()->NumBuckets)) {
1094 this->BaseT::initEmpty();
1098 deallocateBuckets();
1099 init(NewNumBuckets);
1103 unsigned getNumEntries() const {
1107 void setNumEntries(unsigned Num) {
1108 // NumEntries is hardcoded to be 31 bits wide.
1109 assert(Num < (1U << 31) && "Cannot support more than 1<<31 entries");
1113 unsigned getNumTombstones() const {
1114 return NumTombstones;
1117 void setNumTombstones(unsigned Num) {
1118 NumTombstones = Num;
1121 const BucketT *getInlineBuckets() const {
1123 // Note that this cast does not violate aliasing rules as we assert that
1124 // the memory's dynamic type is the small, inline bucket buffer, and the
1125 // 'storage.buffer' static type is 'char *'.
1126 return reinterpret_cast<const BucketT *>(storage.buffer);
1129 BucketT *getInlineBuckets() {
1130 return const_cast<BucketT *>(
1131 const_cast<const SmallDenseMap *>(this)->getInlineBuckets());
1134 const LargeRep *getLargeRep() const {
1136 // Note, same rule about aliasing as with getInlineBuckets.
1137 return reinterpret_cast<const LargeRep *>(storage.buffer);
1140 LargeRep *getLargeRep() {
1141 return const_cast<LargeRep *>(
1142 const_cast<const SmallDenseMap *>(this)->getLargeRep());
1145 const BucketT *getBuckets() const {
1146 return Small ? getInlineBuckets() : getLargeRep()->Buckets;
1149 BucketT *getBuckets() {
1150 return const_cast<BucketT *>(
1151 const_cast<const SmallDenseMap *>(this)->getBuckets());
1154 unsigned getNumBuckets() const {
1155 return Small ? InlineBuckets : getLargeRep()->NumBuckets;
1158 void deallocateBuckets() {
1162 operator delete(getLargeRep()->Buckets);
1163 getLargeRep()->~LargeRep();
1166 LargeRep allocateBuckets(unsigned Num) {
1167 assert(Num > InlineBuckets && "Must allocate more buckets than are inline");
1169 static_cast<BucketT*>(operator new(sizeof(BucketT) * Num)), Num
1175 template <typename KeyT, typename ValueT, typename KeyInfoT, typename Bucket,
1177 class DenseMapIterator : DebugEpochBase::HandleBase {
1178 friend class DenseMapIterator<KeyT, ValueT, KeyInfoT, Bucket, true>;
1179 friend class DenseMapIterator<KeyT, ValueT, KeyInfoT, Bucket, false>;
1181 using ConstIterator = DenseMapIterator<KeyT, ValueT, KeyInfoT, Bucket, true>;
1184 using difference_type = ptrdiff_t;
1186 typename std::conditional<IsConst, const Bucket, Bucket>::type;
1187 using pointer = value_type *;
1188 using reference = value_type &;
1189 using iterator_category = std::forward_iterator_tag;
1192 pointer Ptr = nullptr;
1193 pointer End = nullptr;
1196 DenseMapIterator() = default;
1198 DenseMapIterator(pointer Pos, pointer E, const DebugEpochBase &Epoch,
1199 bool NoAdvance = false)
1200 : DebugEpochBase::HandleBase(&Epoch), Ptr(Pos), End(E) {
1201 assert(isHandleInSync() && "invalid construction!");
1203 if (NoAdvance) return;
1204 if (shouldReverseIterate<KeyT>()) {
1205 RetreatPastEmptyBuckets();
1208 AdvancePastEmptyBuckets();
1211 // Converting ctor from non-const iterators to const iterators. SFINAE'd out
1212 // for const iterator destinations so it doesn't end up as a user defined copy
1214 template <bool IsConstSrc,
1215 typename = typename std::enable_if<!IsConstSrc && IsConst>::type>
1217 const DenseMapIterator<KeyT, ValueT, KeyInfoT, Bucket, IsConstSrc> &I)
1218 : DebugEpochBase::HandleBase(I), Ptr(I.Ptr), End(I.End) {}
1220 reference operator*() const {
1221 assert(isHandleInSync() && "invalid iterator access!");
1222 if (shouldReverseIterate<KeyT>())
1226 pointer operator->() const {
1227 assert(isHandleInSync() && "invalid iterator access!");
1228 if (shouldReverseIterate<KeyT>())
1233 bool operator==(const ConstIterator &RHS) const {
1234 assert((!Ptr || isHandleInSync()) && "handle not in sync!");
1235 assert((!RHS.Ptr || RHS.isHandleInSync()) && "handle not in sync!");
1236 assert(getEpochAddress() == RHS.getEpochAddress() &&
1237 "comparing incomparable iterators!");
1238 return Ptr == RHS.Ptr;
1240 bool operator!=(const ConstIterator &RHS) const {
1241 assert((!Ptr || isHandleInSync()) && "handle not in sync!");
1242 assert((!RHS.Ptr || RHS.isHandleInSync()) && "handle not in sync!");
1243 assert(getEpochAddress() == RHS.getEpochAddress() &&
1244 "comparing incomparable iterators!");
1245 return Ptr != RHS.Ptr;
1248 inline DenseMapIterator& operator++() { // Preincrement
1249 assert(isHandleInSync() && "invalid iterator access!");
1250 if (shouldReverseIterate<KeyT>()) {
1252 RetreatPastEmptyBuckets();
1256 AdvancePastEmptyBuckets();
1259 DenseMapIterator operator++(int) { // Postincrement
1260 assert(isHandleInSync() && "invalid iterator access!");
1261 DenseMapIterator tmp = *this; ++*this; return tmp;
1265 void AdvancePastEmptyBuckets() {
1267 const KeyT Empty = KeyInfoT::getEmptyKey();
1268 const KeyT Tombstone = KeyInfoT::getTombstoneKey();
1270 while (Ptr != End && (KeyInfoT::isEqual(Ptr->getFirst(), Empty) ||
1271 KeyInfoT::isEqual(Ptr->getFirst(), Tombstone)))
1275 void RetreatPastEmptyBuckets() {
1277 const KeyT Empty = KeyInfoT::getEmptyKey();
1278 const KeyT Tombstone = KeyInfoT::getTombstoneKey();
1280 while (Ptr != End && (KeyInfoT::isEqual(Ptr[-1].getFirst(), Empty) ||
1281 KeyInfoT::isEqual(Ptr[-1].getFirst(), Tombstone)))
1286 template <typename KeyT, typename ValueT, typename KeyInfoT>
1287 inline size_t capacity_in_bytes(const DenseMap<KeyT, ValueT, KeyInfoT> &X) {
1288 return X.getMemorySize();
1291 } // end namespace llvm
1293 #endif // LLVM_ADT_DENSEMAP_H