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/Support/AlignOf.h"
19 #include "llvm/Support/Compiler.h"
20 #include "llvm/Support/MathExtras.h"
21 #include "llvm/Support/PointerLikeTypeTraits.h"
22 #include "llvm/Support/type_traits.h"
34 template<typename KeyT, typename ValueT,
35 typename KeyInfoT = DenseMapInfo<KeyT>,
37 class DenseMapIterator;
39 template<typename DerivedT,
40 typename KeyT, typename ValueT, typename KeyInfoT>
43 typedef std::pair<KeyT, ValueT> BucketT;
46 typedef unsigned size_type;
47 typedef KeyT key_type;
48 typedef ValueT mapped_type;
49 typedef BucketT value_type;
51 typedef DenseMapIterator<KeyT, ValueT, KeyInfoT> iterator;
52 typedef DenseMapIterator<KeyT, ValueT,
53 KeyInfoT, true> const_iterator;
54 inline iterator begin() {
55 // When the map is empty, avoid the overhead of AdvancePastEmptyBuckets().
56 return empty() ? end() : iterator(getBuckets(), getBucketsEnd());
58 inline iterator end() {
59 return iterator(getBucketsEnd(), getBucketsEnd(), true);
61 inline const_iterator begin() const {
62 return empty() ? end() : const_iterator(getBuckets(), getBucketsEnd());
64 inline const_iterator end() const {
65 return const_iterator(getBucketsEnd(), getBucketsEnd(), true);
68 bool LLVM_ATTRIBUTE_UNUSED_RESULT empty() const {
69 return getNumEntries() == 0;
71 unsigned size() const { return getNumEntries(); }
73 /// Grow the densemap so that it has at least Size buckets. Does not shrink
74 void resize(size_type Size) {
75 if (Size > getNumBuckets())
80 if (getNumEntries() == 0 && getNumTombstones() == 0) return;
82 // If the capacity of the array is huge, and the # elements used is small,
84 if (getNumEntries() * 4 < getNumBuckets() && getNumBuckets() > 64) {
89 const KeyT EmptyKey = getEmptyKey(), TombstoneKey = getTombstoneKey();
90 for (BucketT *P = getBuckets(), *E = getBucketsEnd(); P != E; ++P) {
91 if (!KeyInfoT::isEqual(P->first, EmptyKey)) {
92 if (!KeyInfoT::isEqual(P->first, TombstoneKey)) {
94 decrementNumEntries();
99 assert(getNumEntries() == 0 && "Node count imbalance!");
103 /// Return 1 if the specified key is in the map, 0 otherwise.
104 size_type count(const KeyT &Val) const {
105 const BucketT *TheBucket;
106 return LookupBucketFor(Val, TheBucket) ? 1 : 0;
109 iterator find(const KeyT &Val) {
111 if (LookupBucketFor(Val, TheBucket))
112 return iterator(TheBucket, getBucketsEnd(), true);
115 const_iterator find(const KeyT &Val) const {
116 const BucketT *TheBucket;
117 if (LookupBucketFor(Val, TheBucket))
118 return const_iterator(TheBucket, getBucketsEnd(), true);
122 /// Alternate version of find() which allows a different, and possibly
123 /// less expensive, key type.
124 /// The DenseMapInfo is responsible for supplying methods
125 /// getHashValue(LookupKeyT) and isEqual(LookupKeyT, KeyT) for each key
127 template<class LookupKeyT>
128 iterator find_as(const LookupKeyT &Val) {
130 if (LookupBucketFor(Val, TheBucket))
131 return iterator(TheBucket, getBucketsEnd(), true);
134 template<class LookupKeyT>
135 const_iterator find_as(const LookupKeyT &Val) const {
136 const BucketT *TheBucket;
137 if (LookupBucketFor(Val, TheBucket))
138 return const_iterator(TheBucket, getBucketsEnd(), true);
142 /// lookup - Return the entry for the specified key, or a default
143 /// constructed value if no such entry exists.
144 ValueT lookup(const KeyT &Val) const {
145 const BucketT *TheBucket;
146 if (LookupBucketFor(Val, TheBucket))
147 return TheBucket->second;
151 // Inserts key,value pair into the map if the key isn't already in the map.
152 // If the key is already in the map, it returns false and doesn't update the
154 std::pair<iterator, bool> insert(const std::pair<KeyT, ValueT> &KV) {
156 if (LookupBucketFor(KV.first, TheBucket))
157 return std::make_pair(iterator(TheBucket, getBucketsEnd(), true),
158 false); // Already in map.
160 // Otherwise, insert the new element.
161 TheBucket = InsertIntoBucket(KV.first, KV.second, TheBucket);
162 return std::make_pair(iterator(TheBucket, getBucketsEnd(), true), true);
165 // Inserts key,value pair into the map if the key isn't already in the map.
166 // If the key is already in the map, it returns false and doesn't update the
168 std::pair<iterator, bool> insert(std::pair<KeyT, ValueT> &&KV) {
170 if (LookupBucketFor(KV.first, TheBucket))
171 return std::make_pair(iterator(TheBucket, getBucketsEnd(), true),
172 false); // Already in map.
174 // Otherwise, insert the new element.
175 TheBucket = InsertIntoBucket(std::move(KV.first),
176 std::move(KV.second),
178 return std::make_pair(iterator(TheBucket, getBucketsEnd(), true), true);
181 /// insert - Range insertion of pairs.
182 template<typename InputIt>
183 void insert(InputIt I, InputIt E) {
189 bool erase(const KeyT &Val) {
191 if (!LookupBucketFor(Val, TheBucket))
192 return false; // not in map.
194 TheBucket->second.~ValueT();
195 TheBucket->first = getTombstoneKey();
196 decrementNumEntries();
197 incrementNumTombstones();
200 void erase(iterator I) {
201 BucketT *TheBucket = &*I;
202 TheBucket->second.~ValueT();
203 TheBucket->first = getTombstoneKey();
204 decrementNumEntries();
205 incrementNumTombstones();
208 value_type& FindAndConstruct(const KeyT &Key) {
210 if (LookupBucketFor(Key, TheBucket))
213 return *InsertIntoBucket(Key, ValueT(), TheBucket);
216 ValueT &operator[](const KeyT &Key) {
217 return FindAndConstruct(Key).second;
220 value_type& FindAndConstruct(KeyT &&Key) {
222 if (LookupBucketFor(Key, TheBucket))
225 return *InsertIntoBucket(std::move(Key), ValueT(), TheBucket);
228 ValueT &operator[](KeyT &&Key) {
229 return FindAndConstruct(std::move(Key)).second;
232 /// isPointerIntoBucketsArray - Return true if the specified pointer points
233 /// somewhere into the DenseMap's array of buckets (i.e. either to a key or
234 /// value in the DenseMap).
235 bool isPointerIntoBucketsArray(const void *Ptr) const {
236 return Ptr >= getBuckets() && Ptr < getBucketsEnd();
239 /// getPointerIntoBucketsArray() - Return an opaque pointer into the buckets
240 /// array. In conjunction with the previous method, this can be used to
241 /// determine whether an insertion caused the DenseMap to reallocate.
242 const void *getPointerIntoBucketsArray() const { return getBuckets(); }
248 if (getNumBuckets() == 0) // Nothing to do.
251 const KeyT EmptyKey = getEmptyKey(), TombstoneKey = getTombstoneKey();
252 for (BucketT *P = getBuckets(), *E = getBucketsEnd(); P != E; ++P) {
253 if (!KeyInfoT::isEqual(P->first, EmptyKey) &&
254 !KeyInfoT::isEqual(P->first, TombstoneKey))
260 memset((void*)getBuckets(), 0x5a, sizeof(BucketT)*getNumBuckets());
268 assert((getNumBuckets() & (getNumBuckets()-1)) == 0 &&
269 "# initial buckets must be a power of two!");
270 const KeyT EmptyKey = getEmptyKey();
271 for (BucketT *B = getBuckets(), *E = getBucketsEnd(); B != E; ++B)
272 new (&B->first) KeyT(EmptyKey);
275 void moveFromOldBuckets(BucketT *OldBucketsBegin, BucketT *OldBucketsEnd) {
278 // Insert all the old elements.
279 const KeyT EmptyKey = getEmptyKey();
280 const KeyT TombstoneKey = getTombstoneKey();
281 for (BucketT *B = OldBucketsBegin, *E = OldBucketsEnd; B != E; ++B) {
282 if (!KeyInfoT::isEqual(B->first, EmptyKey) &&
283 !KeyInfoT::isEqual(B->first, TombstoneKey)) {
284 // Insert the key/value into the new table.
286 bool FoundVal = LookupBucketFor(B->first, DestBucket);
287 (void)FoundVal; // silence warning.
288 assert(!FoundVal && "Key already in new map?");
289 DestBucket->first = std::move(B->first);
290 new (&DestBucket->second) ValueT(std::move(B->second));
291 incrementNumEntries();
300 if (OldBucketsBegin != OldBucketsEnd)
301 memset((void*)OldBucketsBegin, 0x5a,
302 sizeof(BucketT) * (OldBucketsEnd - OldBucketsBegin));
306 template <typename OtherBaseT>
307 void copyFrom(const DenseMapBase<OtherBaseT, KeyT, ValueT, KeyInfoT>& other) {
308 assert(&other != this);
309 assert(getNumBuckets() == other.getNumBuckets());
311 setNumEntries(other.getNumEntries());
312 setNumTombstones(other.getNumTombstones());
314 if (isPodLike<KeyT>::value && isPodLike<ValueT>::value)
315 memcpy(getBuckets(), other.getBuckets(),
316 getNumBuckets() * sizeof(BucketT));
318 for (size_t i = 0; i < getNumBuckets(); ++i) {
319 new (&getBuckets()[i].first) KeyT(other.getBuckets()[i].first);
320 if (!KeyInfoT::isEqual(getBuckets()[i].first, getEmptyKey()) &&
321 !KeyInfoT::isEqual(getBuckets()[i].first, getTombstoneKey()))
322 new (&getBuckets()[i].second) ValueT(other.getBuckets()[i].second);
326 void swap(DenseMapBase& RHS) {
327 std::swap(getNumEntries(), RHS.getNumEntries());
328 std::swap(getNumTombstones(), RHS.getNumTombstones());
331 static unsigned getHashValue(const KeyT &Val) {
332 return KeyInfoT::getHashValue(Val);
334 template<typename LookupKeyT>
335 static unsigned getHashValue(const LookupKeyT &Val) {
336 return KeyInfoT::getHashValue(Val);
338 static const KeyT getEmptyKey() {
339 return KeyInfoT::getEmptyKey();
341 static const KeyT getTombstoneKey() {
342 return KeyInfoT::getTombstoneKey();
346 unsigned getNumEntries() const {
347 return static_cast<const DerivedT *>(this)->getNumEntries();
349 void setNumEntries(unsigned Num) {
350 static_cast<DerivedT *>(this)->setNumEntries(Num);
352 void incrementNumEntries() {
353 setNumEntries(getNumEntries() + 1);
355 void decrementNumEntries() {
356 setNumEntries(getNumEntries() - 1);
358 unsigned getNumTombstones() const {
359 return static_cast<const DerivedT *>(this)->getNumTombstones();
361 void setNumTombstones(unsigned Num) {
362 static_cast<DerivedT *>(this)->setNumTombstones(Num);
364 void incrementNumTombstones() {
365 setNumTombstones(getNumTombstones() + 1);
367 void decrementNumTombstones() {
368 setNumTombstones(getNumTombstones() - 1);
370 const BucketT *getBuckets() const {
371 return static_cast<const DerivedT *>(this)->getBuckets();
373 BucketT *getBuckets() {
374 return static_cast<DerivedT *>(this)->getBuckets();
376 unsigned getNumBuckets() const {
377 return static_cast<const DerivedT *>(this)->getNumBuckets();
379 BucketT *getBucketsEnd() {
380 return getBuckets() + getNumBuckets();
382 const BucketT *getBucketsEnd() const {
383 return getBuckets() + getNumBuckets();
386 void grow(unsigned AtLeast) {
387 static_cast<DerivedT *>(this)->grow(AtLeast);
390 void shrink_and_clear() {
391 static_cast<DerivedT *>(this)->shrink_and_clear();
395 BucketT *InsertIntoBucket(const KeyT &Key, const ValueT &Value,
396 BucketT *TheBucket) {
397 TheBucket = InsertIntoBucketImpl(Key, TheBucket);
399 TheBucket->first = Key;
400 new (&TheBucket->second) ValueT(Value);
404 BucketT *InsertIntoBucket(const KeyT &Key, ValueT &&Value,
405 BucketT *TheBucket) {
406 TheBucket = InsertIntoBucketImpl(Key, TheBucket);
408 TheBucket->first = Key;
409 new (&TheBucket->second) ValueT(std::move(Value));
413 BucketT *InsertIntoBucket(KeyT &&Key, ValueT &&Value, BucketT *TheBucket) {
414 TheBucket = InsertIntoBucketImpl(Key, TheBucket);
416 TheBucket->first = std::move(Key);
417 new (&TheBucket->second) ValueT(std::move(Value));
421 BucketT *InsertIntoBucketImpl(const KeyT &Key, BucketT *TheBucket) {
422 // If the load of the hash table is more than 3/4, or if fewer than 1/8 of
423 // the buckets are empty (meaning that many are filled with tombstones),
426 // The later case is tricky. For example, if we had one empty bucket with
427 // tons of tombstones, failing lookups (e.g. for insertion) would have to
428 // probe almost the entire table until it found the empty bucket. If the
429 // table completely filled with tombstones, no lookup would ever succeed,
430 // causing infinite loops in lookup.
431 unsigned NewNumEntries = getNumEntries() + 1;
432 unsigned NumBuckets = getNumBuckets();
433 if (NewNumEntries*4 >= NumBuckets*3) {
434 this->grow(NumBuckets * 2);
435 LookupBucketFor(Key, TheBucket);
436 NumBuckets = getNumBuckets();
437 } else if (NumBuckets-(NewNumEntries+getNumTombstones()) <= NumBuckets/8) {
438 this->grow(NumBuckets);
439 LookupBucketFor(Key, TheBucket);
443 // Only update the state after we've grown our bucket space appropriately
444 // so that when growing buckets we have self-consistent entry count.
445 incrementNumEntries();
447 // If we are writing over a tombstone, remember this.
448 const KeyT EmptyKey = getEmptyKey();
449 if (!KeyInfoT::isEqual(TheBucket->first, EmptyKey))
450 decrementNumTombstones();
455 /// LookupBucketFor - Lookup the appropriate bucket for Val, returning it in
456 /// FoundBucket. If the bucket contains the key and a value, this returns
457 /// true, otherwise it returns a bucket with an empty marker or tombstone and
459 template<typename LookupKeyT>
460 bool LookupBucketFor(const LookupKeyT &Val,
461 const BucketT *&FoundBucket) const {
462 const BucketT *BucketsPtr = getBuckets();
463 const unsigned NumBuckets = getNumBuckets();
465 if (NumBuckets == 0) {
466 FoundBucket = nullptr;
470 // FoundTombstone - Keep track of whether we find a tombstone while probing.
471 const BucketT *FoundTombstone = nullptr;
472 const KeyT EmptyKey = getEmptyKey();
473 const KeyT TombstoneKey = getTombstoneKey();
474 assert(!KeyInfoT::isEqual(Val, EmptyKey) &&
475 !KeyInfoT::isEqual(Val, TombstoneKey) &&
476 "Empty/Tombstone value shouldn't be inserted into map!");
478 unsigned BucketNo = getHashValue(Val) & (NumBuckets-1);
479 unsigned ProbeAmt = 1;
481 const BucketT *ThisBucket = BucketsPtr + BucketNo;
482 // Found Val's bucket? If so, return it.
483 if (KeyInfoT::isEqual(Val, ThisBucket->first)) {
484 FoundBucket = ThisBucket;
488 // If we found an empty bucket, the key doesn't exist in the set.
489 // Insert it and return the default value.
490 if (KeyInfoT::isEqual(ThisBucket->first, EmptyKey)) {
491 // If we've already seen a tombstone while probing, fill it in instead
492 // of the empty bucket we eventually probed to.
493 FoundBucket = FoundTombstone ? FoundTombstone : ThisBucket;
497 // If this is a tombstone, remember it. If Val ends up not in the map, we
498 // prefer to return it than something that would require more probing.
499 if (KeyInfoT::isEqual(ThisBucket->first, TombstoneKey) && !FoundTombstone)
500 FoundTombstone = ThisBucket; // Remember the first tombstone found.
502 // Otherwise, it's a hash collision or a tombstone, continue quadratic
504 BucketNo += ProbeAmt++;
505 BucketNo &= (NumBuckets-1);
509 template <typename LookupKeyT>
510 bool LookupBucketFor(const LookupKeyT &Val, BucketT *&FoundBucket) {
511 const BucketT *ConstFoundBucket;
512 bool Result = const_cast<const DenseMapBase *>(this)
513 ->LookupBucketFor(Val, ConstFoundBucket);
514 FoundBucket = const_cast<BucketT *>(ConstFoundBucket);
519 /// Return the approximate size (in bytes) of the actual map.
520 /// This is just the raw memory used by DenseMap.
521 /// If entries are pointers to objects, the size of the referenced objects
522 /// are not included.
523 size_t getMemorySize() const {
524 return getNumBuckets() * sizeof(BucketT);
528 template<typename KeyT, typename ValueT,
529 typename KeyInfoT = DenseMapInfo<KeyT> >
531 : public DenseMapBase<DenseMap<KeyT, ValueT, KeyInfoT>,
532 KeyT, ValueT, KeyInfoT> {
533 // Lift some types from the dependent base class into this class for
534 // simplicity of referring to them.
535 typedef DenseMapBase<DenseMap, KeyT, ValueT, KeyInfoT> BaseT;
536 typedef typename BaseT::BucketT BucketT;
537 friend class DenseMapBase<DenseMap, KeyT, ValueT, KeyInfoT>;
541 unsigned NumTombstones;
545 explicit DenseMap(unsigned NumInitBuckets = 0) {
546 init(NumInitBuckets);
549 DenseMap(const DenseMap &other) : BaseT() {
554 DenseMap(DenseMap &&other) : BaseT() {
559 template<typename InputIt>
560 DenseMap(const InputIt &I, const InputIt &E) {
561 init(NextPowerOf2(std::distance(I, E)));
567 operator delete(Buckets);
570 void swap(DenseMap& RHS) {
571 std::swap(Buckets, RHS.Buckets);
572 std::swap(NumEntries, RHS.NumEntries);
573 std::swap(NumTombstones, RHS.NumTombstones);
574 std::swap(NumBuckets, RHS.NumBuckets);
577 DenseMap& operator=(const DenseMap& other) {
583 DenseMap& operator=(DenseMap &&other) {
585 operator delete(Buckets);
591 void copyFrom(const DenseMap& other) {
593 operator delete(Buckets);
594 if (allocateBuckets(other.NumBuckets)) {
595 this->BaseT::copyFrom(other);
602 void init(unsigned InitBuckets) {
603 if (allocateBuckets(InitBuckets)) {
604 this->BaseT::initEmpty();
611 void grow(unsigned AtLeast) {
612 unsigned OldNumBuckets = NumBuckets;
613 BucketT *OldBuckets = Buckets;
615 allocateBuckets(std::max<unsigned>(64, static_cast<unsigned>(NextPowerOf2(AtLeast-1))));
618 this->BaseT::initEmpty();
622 this->moveFromOldBuckets(OldBuckets, OldBuckets+OldNumBuckets);
624 // Free the old table.
625 operator delete(OldBuckets);
628 void shrink_and_clear() {
629 unsigned OldNumEntries = NumEntries;
632 // Reduce the number of buckets.
633 unsigned NewNumBuckets = 0;
635 NewNumBuckets = std::max(64, 1 << (Log2_32_Ceil(OldNumEntries) + 1));
636 if (NewNumBuckets == NumBuckets) {
637 this->BaseT::initEmpty();
641 operator delete(Buckets);
646 unsigned getNumEntries() const {
649 void setNumEntries(unsigned Num) {
653 unsigned getNumTombstones() const {
654 return NumTombstones;
656 void setNumTombstones(unsigned Num) {
660 BucketT *getBuckets() const {
664 unsigned getNumBuckets() const {
668 bool allocateBuckets(unsigned Num) {
670 if (NumBuckets == 0) {
675 Buckets = static_cast<BucketT*>(operator new(sizeof(BucketT) * NumBuckets));
680 template<typename KeyT, typename ValueT,
681 unsigned InlineBuckets = 4,
682 typename KeyInfoT = DenseMapInfo<KeyT> >
684 : public DenseMapBase<SmallDenseMap<KeyT, ValueT, InlineBuckets, KeyInfoT>,
685 KeyT, ValueT, KeyInfoT> {
686 // Lift some types from the dependent base class into this class for
687 // simplicity of referring to them.
688 typedef DenseMapBase<SmallDenseMap, KeyT, ValueT, KeyInfoT> BaseT;
689 typedef typename BaseT::BucketT BucketT;
690 friend class DenseMapBase<SmallDenseMap, KeyT, ValueT, KeyInfoT>;
693 unsigned NumEntries : 31;
694 unsigned NumTombstones;
701 /// A "union" of an inline bucket array and the struct representing
702 /// a large bucket. This union will be discriminated by the 'Small' bit.
703 AlignedCharArrayUnion<BucketT[InlineBuckets], LargeRep> storage;
706 explicit SmallDenseMap(unsigned NumInitBuckets = 0) {
707 init(NumInitBuckets);
710 SmallDenseMap(const SmallDenseMap &other) : BaseT() {
715 SmallDenseMap(SmallDenseMap &&other) : BaseT() {
720 template<typename InputIt>
721 SmallDenseMap(const InputIt &I, const InputIt &E) {
722 init(NextPowerOf2(std::distance(I, E)));
731 void swap(SmallDenseMap& RHS) {
732 unsigned TmpNumEntries = RHS.NumEntries;
733 RHS.NumEntries = NumEntries;
734 NumEntries = TmpNumEntries;
735 std::swap(NumTombstones, RHS.NumTombstones);
737 const KeyT EmptyKey = this->getEmptyKey();
738 const KeyT TombstoneKey = this->getTombstoneKey();
739 if (Small && RHS.Small) {
740 // If we're swapping inline bucket arrays, we have to cope with some of
741 // the tricky bits of DenseMap's storage system: the buckets are not
742 // fully initialized. Thus we swap every key, but we may have
743 // a one-directional move of the value.
744 for (unsigned i = 0, e = InlineBuckets; i != e; ++i) {
745 BucketT *LHSB = &getInlineBuckets()[i],
746 *RHSB = &RHS.getInlineBuckets()[i];
747 bool hasLHSValue = (!KeyInfoT::isEqual(LHSB->first, EmptyKey) &&
748 !KeyInfoT::isEqual(LHSB->first, TombstoneKey));
749 bool hasRHSValue = (!KeyInfoT::isEqual(RHSB->first, EmptyKey) &&
750 !KeyInfoT::isEqual(RHSB->first, TombstoneKey));
751 if (hasLHSValue && hasRHSValue) {
752 // Swap together if we can...
753 std::swap(*LHSB, *RHSB);
756 // Swap separately and handle any assymetry.
757 std::swap(LHSB->first, RHSB->first);
759 new (&RHSB->second) ValueT(std::move(LHSB->second));
760 LHSB->second.~ValueT();
761 } else if (hasRHSValue) {
762 new (&LHSB->second) ValueT(std::move(RHSB->second));
763 RHSB->second.~ValueT();
768 if (!Small && !RHS.Small) {
769 std::swap(getLargeRep()->Buckets, RHS.getLargeRep()->Buckets);
770 std::swap(getLargeRep()->NumBuckets, RHS.getLargeRep()->NumBuckets);
774 SmallDenseMap &SmallSide = Small ? *this : RHS;
775 SmallDenseMap &LargeSide = Small ? RHS : *this;
777 // First stash the large side's rep and move the small side across.
778 LargeRep TmpRep = std::move(*LargeSide.getLargeRep());
779 LargeSide.getLargeRep()->~LargeRep();
780 LargeSide.Small = true;
781 // This is similar to the standard move-from-old-buckets, but the bucket
782 // count hasn't actually rotated in this case. So we have to carefully
783 // move construct the keys and values into their new locations, but there
784 // is no need to re-hash things.
785 for (unsigned i = 0, e = InlineBuckets; i != e; ++i) {
786 BucketT *NewB = &LargeSide.getInlineBuckets()[i],
787 *OldB = &SmallSide.getInlineBuckets()[i];
788 new (&NewB->first) KeyT(std::move(OldB->first));
790 if (!KeyInfoT::isEqual(NewB->first, EmptyKey) &&
791 !KeyInfoT::isEqual(NewB->first, TombstoneKey)) {
792 new (&NewB->second) ValueT(std::move(OldB->second));
793 OldB->second.~ValueT();
797 // The hard part of moving the small buckets across is done, just move
798 // the TmpRep into its new home.
799 SmallSide.Small = false;
800 new (SmallSide.getLargeRep()) LargeRep(std::move(TmpRep));
803 SmallDenseMap& operator=(const SmallDenseMap& other) {
809 SmallDenseMap& operator=(SmallDenseMap &&other) {
817 void copyFrom(const SmallDenseMap& other) {
821 if (other.getNumBuckets() > InlineBuckets) {
823 new (getLargeRep()) LargeRep(allocateBuckets(other.getNumBuckets()));
825 this->BaseT::copyFrom(other);
828 void init(unsigned InitBuckets) {
830 if (InitBuckets > InlineBuckets) {
832 new (getLargeRep()) LargeRep(allocateBuckets(InitBuckets));
834 this->BaseT::initEmpty();
837 void grow(unsigned AtLeast) {
838 if (AtLeast >= InlineBuckets)
839 AtLeast = std::max<unsigned>(64, NextPowerOf2(AtLeast-1));
842 if (AtLeast < InlineBuckets)
843 return; // Nothing to do.
845 // First move the inline buckets into a temporary storage.
846 AlignedCharArrayUnion<BucketT[InlineBuckets]> TmpStorage;
847 BucketT *TmpBegin = reinterpret_cast<BucketT *>(TmpStorage.buffer);
848 BucketT *TmpEnd = TmpBegin;
850 // Loop over the buckets, moving non-empty, non-tombstones into the
851 // temporary storage. Have the loop move the TmpEnd forward as it goes.
852 const KeyT EmptyKey = this->getEmptyKey();
853 const KeyT TombstoneKey = this->getTombstoneKey();
854 for (BucketT *P = getBuckets(), *E = P + InlineBuckets; P != E; ++P) {
855 if (!KeyInfoT::isEqual(P->first, EmptyKey) &&
856 !KeyInfoT::isEqual(P->first, TombstoneKey)) {
857 assert(size_t(TmpEnd - TmpBegin) < InlineBuckets &&
858 "Too many inline buckets!");
859 new (&TmpEnd->first) KeyT(std::move(P->first));
860 new (&TmpEnd->second) ValueT(std::move(P->second));
867 // Now make this map use the large rep, and move all the entries back
870 new (getLargeRep()) LargeRep(allocateBuckets(AtLeast));
871 this->moveFromOldBuckets(TmpBegin, TmpEnd);
875 LargeRep OldRep = std::move(*getLargeRep());
876 getLargeRep()->~LargeRep();
877 if (AtLeast <= InlineBuckets) {
880 new (getLargeRep()) LargeRep(allocateBuckets(AtLeast));
883 this->moveFromOldBuckets(OldRep.Buckets, OldRep.Buckets+OldRep.NumBuckets);
885 // Free the old table.
886 operator delete(OldRep.Buckets);
889 void shrink_and_clear() {
890 unsigned OldSize = this->size();
893 // Reduce the number of buckets.
894 unsigned NewNumBuckets = 0;
896 NewNumBuckets = 1 << (Log2_32_Ceil(OldSize) + 1);
897 if (NewNumBuckets > InlineBuckets && NewNumBuckets < 64u)
900 if ((Small && NewNumBuckets <= InlineBuckets) ||
901 (!Small && NewNumBuckets == getLargeRep()->NumBuckets)) {
902 this->BaseT::initEmpty();
911 unsigned getNumEntries() const {
914 void setNumEntries(unsigned Num) {
915 assert(Num < INT_MAX && "Cannot support more than INT_MAX entries");
919 unsigned getNumTombstones() const {
920 return NumTombstones;
922 void setNumTombstones(unsigned Num) {
926 const BucketT *getInlineBuckets() const {
928 // Note that this cast does not violate aliasing rules as we assert that
929 // the memory's dynamic type is the small, inline bucket buffer, and the
930 // 'storage.buffer' static type is 'char *'.
931 return reinterpret_cast<const BucketT *>(storage.buffer);
933 BucketT *getInlineBuckets() {
934 return const_cast<BucketT *>(
935 const_cast<const SmallDenseMap *>(this)->getInlineBuckets());
937 const LargeRep *getLargeRep() const {
939 // Note, same rule about aliasing as with getInlineBuckets.
940 return reinterpret_cast<const LargeRep *>(storage.buffer);
942 LargeRep *getLargeRep() {
943 return const_cast<LargeRep *>(
944 const_cast<const SmallDenseMap *>(this)->getLargeRep());
947 const BucketT *getBuckets() const {
948 return Small ? getInlineBuckets() : getLargeRep()->Buckets;
950 BucketT *getBuckets() {
951 return const_cast<BucketT *>(
952 const_cast<const SmallDenseMap *>(this)->getBuckets());
954 unsigned getNumBuckets() const {
955 return Small ? InlineBuckets : getLargeRep()->NumBuckets;
958 void deallocateBuckets() {
962 operator delete(getLargeRep()->Buckets);
963 getLargeRep()->~LargeRep();
966 LargeRep allocateBuckets(unsigned Num) {
967 assert(Num > InlineBuckets && "Must allocate more buckets than are inline");
969 static_cast<BucketT*>(operator new(sizeof(BucketT) * Num)), Num
975 template<typename KeyT, typename ValueT,
976 typename KeyInfoT, bool IsConst>
977 class DenseMapIterator {
978 typedef std::pair<KeyT, ValueT> Bucket;
979 typedef DenseMapIterator<KeyT, ValueT,
980 KeyInfoT, true> ConstIterator;
981 friend class DenseMapIterator<KeyT, ValueT, KeyInfoT, true>;
983 typedef ptrdiff_t difference_type;
984 typedef typename std::conditional<IsConst, const Bucket, Bucket>::type
986 typedef value_type *pointer;
987 typedef value_type &reference;
988 typedef std::forward_iterator_tag iterator_category;
992 DenseMapIterator() : Ptr(nullptr), End(nullptr) {}
994 DenseMapIterator(pointer Pos, pointer E, bool NoAdvance = false)
996 if (!NoAdvance) AdvancePastEmptyBuckets();
999 // If IsConst is true this is a converting constructor from iterator to
1000 // const_iterator and the default copy constructor is used.
1001 // Otherwise this is a copy constructor for iterator.
1002 DenseMapIterator(const DenseMapIterator<KeyT, ValueT,
1003 KeyInfoT, false>& I)
1004 : Ptr(I.Ptr), End(I.End) {}
1006 reference operator*() const {
1009 pointer operator->() const {
1013 bool operator==(const ConstIterator &RHS) const {
1014 return Ptr == RHS.operator->();
1016 bool operator!=(const ConstIterator &RHS) const {
1017 return Ptr != RHS.operator->();
1020 inline DenseMapIterator& operator++() { // Preincrement
1022 AdvancePastEmptyBuckets();
1025 DenseMapIterator operator++(int) { // Postincrement
1026 DenseMapIterator tmp = *this; ++*this; return tmp;
1030 void AdvancePastEmptyBuckets() {
1031 const KeyT Empty = KeyInfoT::getEmptyKey();
1032 const KeyT Tombstone = KeyInfoT::getTombstoneKey();
1034 while (Ptr != End &&
1035 (KeyInfoT::isEqual(Ptr->first, Empty) ||
1036 KeyInfoT::isEqual(Ptr->first, Tombstone)))
1041 template<typename KeyT, typename ValueT, typename KeyInfoT>
1042 static inline size_t
1043 capacity_in_bytes(const DenseMap<KeyT, ValueT, KeyInfoT> &X) {
1044 return X.getMemorySize();
1047 } // end namespace llvm