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 KeyT key_type;
47 typedef ValueT mapped_type;
48 typedef BucketT value_type;
50 typedef DenseMapIterator<KeyT, ValueT, KeyInfoT> iterator;
51 typedef DenseMapIterator<KeyT, ValueT,
52 KeyInfoT, true> const_iterator;
53 inline iterator begin() {
54 // When the map is empty, avoid the overhead of AdvancePastEmptyBuckets().
55 return empty() ? end() : iterator(getBuckets(), getBucketsEnd());
57 inline iterator end() {
58 return iterator(getBucketsEnd(), getBucketsEnd(), true);
60 inline const_iterator begin() const {
61 return empty() ? end() : const_iterator(getBuckets(), getBucketsEnd());
63 inline const_iterator end() const {
64 return const_iterator(getBucketsEnd(), getBucketsEnd(), true);
67 bool empty() const { return getNumEntries() == 0; }
68 unsigned size() const { return getNumEntries(); }
70 /// Grow the densemap so that it has at least Size buckets. Does not shrink
71 void resize(size_t Size) {
72 if (Size > getNumBuckets())
77 if (getNumEntries() == 0 && getNumTombstones() == 0) return;
79 // If the capacity of the array is huge, and the # elements used is small,
81 if (getNumEntries() * 4 < getNumBuckets() && getNumBuckets() > 64) {
86 const KeyT EmptyKey = getEmptyKey(), TombstoneKey = getTombstoneKey();
87 for (BucketT *P = getBuckets(), *E = getBucketsEnd(); P != E; ++P) {
88 if (!KeyInfoT::isEqual(P->first, EmptyKey)) {
89 if (!KeyInfoT::isEqual(P->first, TombstoneKey)) {
91 decrementNumEntries();
96 assert(getNumEntries() == 0 && "Node count imbalance!");
100 /// count - Return true if the specified key is in the map.
101 bool count(const KeyT &Val) const {
102 const BucketT *TheBucket;
103 return LookupBucketFor(Val, TheBucket);
106 iterator find(const KeyT &Val) {
108 if (LookupBucketFor(Val, TheBucket))
109 return iterator(TheBucket, getBucketsEnd(), true);
112 const_iterator find(const KeyT &Val) const {
113 const BucketT *TheBucket;
114 if (LookupBucketFor(Val, TheBucket))
115 return const_iterator(TheBucket, getBucketsEnd(), true);
119 /// Alternate version of find() which allows a different, and possibly
120 /// less expensive, key type.
121 /// The DenseMapInfo is responsible for supplying methods
122 /// getHashValue(LookupKeyT) and isEqual(LookupKeyT, KeyT) for each key
124 template<class LookupKeyT>
125 iterator find_as(const LookupKeyT &Val) {
127 if (LookupBucketFor(Val, TheBucket))
128 return iterator(TheBucket, getBucketsEnd(), true);
131 template<class LookupKeyT>
132 const_iterator find_as(const LookupKeyT &Val) const {
133 const BucketT *TheBucket;
134 if (LookupBucketFor(Val, TheBucket))
135 return const_iterator(TheBucket, getBucketsEnd(), true);
139 /// lookup - Return the entry for the specified key, or a default
140 /// constructed value if no such entry exists.
141 ValueT lookup(const KeyT &Val) const {
142 const BucketT *TheBucket;
143 if (LookupBucketFor(Val, TheBucket))
144 return TheBucket->second;
148 // Inserts key,value pair into the map if the key isn't already in the map.
149 // If the key is already in the map, it returns false and doesn't update the
151 std::pair<iterator, bool> insert(const std::pair<KeyT, ValueT> &KV) {
153 if (LookupBucketFor(KV.first, TheBucket))
154 return std::make_pair(iterator(TheBucket, getBucketsEnd(), true),
155 false); // Already in map.
157 // Otherwise, insert the new element.
158 TheBucket = InsertIntoBucket(KV.first, KV.second, TheBucket);
159 return std::make_pair(iterator(TheBucket, getBucketsEnd(), true), true);
162 #if LLVM_HAS_RVALUE_REFERENCES
163 // Inserts key,value pair into the map if the key isn't already in the map.
164 // If the key is already in the map, it returns false and doesn't update the
166 std::pair<iterator, bool> insert(std::pair<KeyT, ValueT> &&KV) {
168 if (LookupBucketFor(KV.first, TheBucket))
169 return std::make_pair(iterator(TheBucket, getBucketsEnd(), true),
170 false); // Already in map.
172 // Otherwise, insert the new element.
173 TheBucket = InsertIntoBucket(std::move(KV.first),
174 std::move(KV.second),
176 return std::make_pair(iterator(TheBucket, getBucketsEnd(), true), true);
180 /// insert - Range insertion of pairs.
181 template<typename InputIt>
182 void insert(InputIt I, InputIt E) {
188 bool erase(const KeyT &Val) {
190 if (!LookupBucketFor(Val, TheBucket))
191 return false; // not in map.
193 TheBucket->second.~ValueT();
194 TheBucket->first = getTombstoneKey();
195 decrementNumEntries();
196 incrementNumTombstones();
199 void erase(iterator I) {
200 BucketT *TheBucket = &*I;
201 TheBucket->second.~ValueT();
202 TheBucket->first = getTombstoneKey();
203 decrementNumEntries();
204 incrementNumTombstones();
207 value_type& FindAndConstruct(const KeyT &Key) {
209 if (LookupBucketFor(Key, TheBucket))
212 return *InsertIntoBucket(Key, ValueT(), TheBucket);
215 ValueT &operator[](const KeyT &Key) {
216 return FindAndConstruct(Key).second;
219 #if LLVM_HAS_RVALUE_REFERENCES
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;
233 /// isPointerIntoBucketsArray - Return true if the specified pointer points
234 /// somewhere into the DenseMap's array of buckets (i.e. either to a key or
235 /// value in the DenseMap).
236 bool isPointerIntoBucketsArray(const void *Ptr) const {
237 return Ptr >= getBuckets() && Ptr < getBucketsEnd();
240 /// getPointerIntoBucketsArray() - Return an opaque pointer into the buckets
241 /// array. In conjunction with the previous method, this can be used to
242 /// determine whether an insertion caused the DenseMap to reallocate.
243 const void *getPointerIntoBucketsArray() const { return getBuckets(); }
249 if (getNumBuckets() == 0) // Nothing to do.
252 const KeyT EmptyKey = getEmptyKey(), TombstoneKey = getTombstoneKey();
253 for (BucketT *P = getBuckets(), *E = getBucketsEnd(); P != E; ++P) {
254 if (!KeyInfoT::isEqual(P->first, EmptyKey) &&
255 !KeyInfoT::isEqual(P->first, TombstoneKey))
261 memset((void*)getBuckets(), 0x5a, sizeof(BucketT)*getNumBuckets());
269 assert((getNumBuckets() & (getNumBuckets()-1)) == 0 &&
270 "# initial buckets must be a power of two!");
271 const KeyT EmptyKey = getEmptyKey();
272 for (BucketT *B = getBuckets(), *E = getBucketsEnd(); B != E; ++B)
273 new (&B->first) KeyT(EmptyKey);
276 void moveFromOldBuckets(BucketT *OldBucketsBegin, BucketT *OldBucketsEnd) {
279 // Insert all the old elements.
280 const KeyT EmptyKey = getEmptyKey();
281 const KeyT TombstoneKey = getTombstoneKey();
282 for (BucketT *B = OldBucketsBegin, *E = OldBucketsEnd; B != E; ++B) {
283 if (!KeyInfoT::isEqual(B->first, EmptyKey) &&
284 !KeyInfoT::isEqual(B->first, TombstoneKey)) {
285 // Insert the key/value into the new table.
287 bool FoundVal = LookupBucketFor(B->first, DestBucket);
288 (void)FoundVal; // silence warning.
289 assert(!FoundVal && "Key already in new map?");
290 DestBucket->first = llvm_move(B->first);
291 new (&DestBucket->second) ValueT(llvm_move(B->second));
292 incrementNumEntries();
301 if (OldBucketsBegin != OldBucketsEnd)
302 memset((void*)OldBucketsBegin, 0x5a,
303 sizeof(BucketT) * (OldBucketsEnd - OldBucketsBegin));
307 template <typename OtherBaseT>
308 void copyFrom(const DenseMapBase<OtherBaseT, KeyT, ValueT, KeyInfoT>& other) {
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 #if LLVM_HAS_RVALUE_REFERENCES
405 BucketT *InsertIntoBucket(const KeyT &Key, ValueT &&Value,
406 BucketT *TheBucket) {
407 TheBucket = InsertIntoBucketImpl(Key, TheBucket);
409 TheBucket->first = Key;
410 new (&TheBucket->second) ValueT(std::move(Value));
414 BucketT *InsertIntoBucket(KeyT &&Key, ValueT &&Value, BucketT *TheBucket) {
415 TheBucket = InsertIntoBucketImpl(Key, TheBucket);
417 TheBucket->first = std::move(Key);
418 new (&TheBucket->second) ValueT(std::move(Value));
423 BucketT *InsertIntoBucketImpl(const KeyT &Key, BucketT *TheBucket) {
424 // If the load of the hash table is more than 3/4, or if fewer than 1/8 of
425 // the buckets are empty (meaning that many are filled with tombstones),
428 // The later case is tricky. For example, if we had one empty bucket with
429 // tons of tombstones, failing lookups (e.g. for insertion) would have to
430 // probe almost the entire table until it found the empty bucket. If the
431 // table completely filled with tombstones, no lookup would ever succeed,
432 // causing infinite loops in lookup.
433 unsigned NewNumEntries = getNumEntries() + 1;
434 unsigned NumBuckets = getNumBuckets();
435 if (NewNumEntries*4 >= NumBuckets*3) {
436 this->grow(NumBuckets * 2);
437 LookupBucketFor(Key, TheBucket);
438 NumBuckets = getNumBuckets();
440 if (NumBuckets-(NewNumEntries+getNumTombstones()) <= NumBuckets/8) {
441 this->grow(NumBuckets * 2);
442 LookupBucketFor(Key, TheBucket);
446 // Only update the state after we've grown our bucket space appropriately
447 // so that when growing buckets we have self-consistent entry count.
448 incrementNumEntries();
450 // If we are writing over a tombstone, remember this.
451 const KeyT EmptyKey = getEmptyKey();
452 if (!KeyInfoT::isEqual(TheBucket->first, EmptyKey))
453 decrementNumTombstones();
458 /// LookupBucketFor - Lookup the appropriate bucket for Val, returning it in
459 /// FoundBucket. If the bucket contains the key and a value, this returns
460 /// true, otherwise it returns a bucket with an empty marker or tombstone and
462 template<typename LookupKeyT>
463 bool LookupBucketFor(const LookupKeyT &Val,
464 const BucketT *&FoundBucket) const {
465 const BucketT *BucketsPtr = getBuckets();
466 const unsigned NumBuckets = getNumBuckets();
468 if (NumBuckets == 0) {
473 // FoundTombstone - Keep track of whether we find a tombstone while probing.
474 const BucketT *FoundTombstone = 0;
475 const KeyT EmptyKey = getEmptyKey();
476 const KeyT TombstoneKey = getTombstoneKey();
477 assert(!KeyInfoT::isEqual(Val, EmptyKey) &&
478 !KeyInfoT::isEqual(Val, TombstoneKey) &&
479 "Empty/Tombstone value shouldn't be inserted into map!");
481 unsigned BucketNo = getHashValue(Val) & (NumBuckets-1);
482 unsigned ProbeAmt = 1;
484 const BucketT *ThisBucket = BucketsPtr + BucketNo;
485 // Found Val's bucket? If so, return it.
486 if (KeyInfoT::isEqual(Val, ThisBucket->first)) {
487 FoundBucket = ThisBucket;
491 // If we found an empty bucket, the key doesn't exist in the set.
492 // Insert it and return the default value.
493 if (KeyInfoT::isEqual(ThisBucket->first, EmptyKey)) {
494 // If we've already seen a tombstone while probing, fill it in instead
495 // of the empty bucket we eventually probed to.
496 FoundBucket = FoundTombstone ? FoundTombstone : ThisBucket;
500 // If this is a tombstone, remember it. If Val ends up not in the map, we
501 // prefer to return it than something that would require more probing.
502 if (KeyInfoT::isEqual(ThisBucket->first, TombstoneKey) && !FoundTombstone)
503 FoundTombstone = ThisBucket; // Remember the first tombstone found.
505 // Otherwise, it's a hash collision or a tombstone, continue quadratic
507 BucketNo += ProbeAmt++;
508 BucketNo &= (NumBuckets-1);
512 template <typename LookupKeyT>
513 bool LookupBucketFor(const LookupKeyT &Val, BucketT *&FoundBucket) {
514 const BucketT *ConstFoundBucket;
515 bool Result = const_cast<const DenseMapBase *>(this)
516 ->LookupBucketFor(Val, ConstFoundBucket);
517 FoundBucket = const_cast<BucketT *>(ConstFoundBucket);
522 /// Return the approximate size (in bytes) of the actual map.
523 /// This is just the raw memory used by DenseMap.
524 /// If entries are pointers to objects, the size of the referenced objects
525 /// are not included.
526 size_t getMemorySize() const {
527 return getNumBuckets() * sizeof(BucketT);
531 template<typename KeyT, typename ValueT,
532 typename KeyInfoT = DenseMapInfo<KeyT> >
534 : public DenseMapBase<DenseMap<KeyT, ValueT, KeyInfoT>,
535 KeyT, ValueT, KeyInfoT> {
536 // Lift some types from the dependent base class into this class for
537 // simplicity of referring to them.
538 typedef DenseMapBase<DenseMap, KeyT, ValueT, KeyInfoT> BaseT;
539 typedef typename BaseT::BucketT BucketT;
540 friend class DenseMapBase<DenseMap, KeyT, ValueT, KeyInfoT>;
544 unsigned NumTombstones;
548 explicit DenseMap(unsigned NumInitBuckets = 0) {
549 init(NumInitBuckets);
552 DenseMap(const DenseMap &other) : BaseT() {
557 #if LLVM_HAS_RVALUE_REFERENCES
558 DenseMap(DenseMap &&other) : BaseT() {
564 template<typename InputIt>
565 DenseMap(const InputIt &I, const InputIt &E) {
566 init(NextPowerOf2(std::distance(I, E)));
572 operator delete(Buckets);
575 void swap(DenseMap& RHS) {
576 std::swap(Buckets, RHS.Buckets);
577 std::swap(NumEntries, RHS.NumEntries);
578 std::swap(NumTombstones, RHS.NumTombstones);
579 std::swap(NumBuckets, RHS.NumBuckets);
582 DenseMap& operator=(const DenseMap& other) {
587 #if LLVM_HAS_RVALUE_REFERENCES
588 DenseMap& operator=(DenseMap &&other) {
590 operator delete(Buckets);
597 void copyFrom(const DenseMap& other) {
599 operator delete(Buckets);
600 if (allocateBuckets(other.NumBuckets)) {
601 this->BaseT::copyFrom(other);
608 void init(unsigned InitBuckets) {
609 assert(!KeyInfoT::isEqual(this->getEmptyKey(), this->getTombstoneKey()) &&
610 "Bad implementation of KeyInfoT: empty key and tombstone key "
611 "should be different");
612 if (allocateBuckets(InitBuckets)) {
613 this->BaseT::initEmpty();
620 void grow(unsigned AtLeast) {
621 unsigned OldNumBuckets = NumBuckets;
622 BucketT *OldBuckets = Buckets;
624 allocateBuckets(std::max<unsigned>(64, static_cast<unsigned>(NextPowerOf2(AtLeast-1))));
627 this->BaseT::initEmpty();
631 this->moveFromOldBuckets(OldBuckets, OldBuckets+OldNumBuckets);
633 // Free the old table.
634 operator delete(OldBuckets);
637 void shrink_and_clear() {
638 unsigned OldNumEntries = NumEntries;
641 // Reduce the number of buckets.
642 unsigned NewNumBuckets = 0;
644 NewNumBuckets = std::max(64, 1 << (Log2_32_Ceil(OldNumEntries) + 1));
645 if (NewNumBuckets == NumBuckets) {
646 this->BaseT::initEmpty();
650 operator delete(Buckets);
655 unsigned getNumEntries() const {
658 void setNumEntries(unsigned Num) {
662 unsigned getNumTombstones() const {
663 return NumTombstones;
665 void setNumTombstones(unsigned Num) {
669 BucketT *getBuckets() const {
673 unsigned getNumBuckets() const {
677 bool allocateBuckets(unsigned Num) {
679 if (NumBuckets == 0) {
684 Buckets = static_cast<BucketT*>(operator new(sizeof(BucketT) * NumBuckets));
689 template<typename KeyT, typename ValueT,
690 unsigned InlineBuckets = 4,
691 typename KeyInfoT = DenseMapInfo<KeyT> >
693 : public DenseMapBase<SmallDenseMap<KeyT, ValueT, InlineBuckets, KeyInfoT>,
694 KeyT, ValueT, KeyInfoT> {
695 // Lift some types from the dependent base class into this class for
696 // simplicity of referring to them.
697 typedef DenseMapBase<SmallDenseMap, KeyT, ValueT, KeyInfoT> BaseT;
698 typedef typename BaseT::BucketT BucketT;
699 friend class DenseMapBase<SmallDenseMap, KeyT, ValueT, KeyInfoT>;
702 unsigned NumEntries : 31;
703 unsigned NumTombstones;
710 /// A "union" of an inline bucket array and the struct representing
711 /// a large bucket. This union will be discriminated by the 'Small' bit.
712 AlignedCharArrayUnion<BucketT[InlineBuckets], LargeRep> storage;
715 explicit SmallDenseMap(unsigned NumInitBuckets = 0) {
716 init(NumInitBuckets);
719 SmallDenseMap(const SmallDenseMap &other) {
724 #if LLVM_HAS_RVALUE_REFERENCES
725 SmallDenseMap(SmallDenseMap &&other) {
731 template<typename InputIt>
732 SmallDenseMap(const InputIt &I, const InputIt &E) {
733 init(NextPowerOf2(std::distance(I, E)));
742 void swap(SmallDenseMap& RHS) {
743 unsigned TmpNumEntries = RHS.NumEntries;
744 RHS.NumEntries = NumEntries;
745 NumEntries = TmpNumEntries;
746 std::swap(NumTombstones, RHS.NumTombstones);
748 const KeyT EmptyKey = this->getEmptyKey();
749 const KeyT TombstoneKey = this->getTombstoneKey();
750 if (Small && RHS.Small) {
751 // If we're swapping inline bucket arrays, we have to cope with some of
752 // the tricky bits of DenseMap's storage system: the buckets are not
753 // fully initialized. Thus we swap every key, but we may have
754 // a one-directional move of the value.
755 for (unsigned i = 0, e = InlineBuckets; i != e; ++i) {
756 BucketT *LHSB = &getInlineBuckets()[i],
757 *RHSB = &RHS.getInlineBuckets()[i];
758 bool hasLHSValue = (!KeyInfoT::isEqual(LHSB->first, EmptyKey) &&
759 !KeyInfoT::isEqual(LHSB->first, TombstoneKey));
760 bool hasRHSValue = (!KeyInfoT::isEqual(RHSB->first, EmptyKey) &&
761 !KeyInfoT::isEqual(RHSB->first, TombstoneKey));
762 if (hasLHSValue && hasRHSValue) {
763 // Swap together if we can...
764 std::swap(*LHSB, *RHSB);
767 // Swap separately and handle any assymetry.
768 std::swap(LHSB->first, RHSB->first);
770 new (&RHSB->second) ValueT(llvm_move(LHSB->second));
771 LHSB->second.~ValueT();
772 } else if (hasRHSValue) {
773 new (&LHSB->second) ValueT(llvm_move(RHSB->second));
774 RHSB->second.~ValueT();
779 if (!Small && !RHS.Small) {
780 std::swap(getLargeRep()->Buckets, RHS.getLargeRep()->Buckets);
781 std::swap(getLargeRep()->NumBuckets, RHS.getLargeRep()->NumBuckets);
785 SmallDenseMap &SmallSide = Small ? *this : RHS;
786 SmallDenseMap &LargeSide = Small ? RHS : *this;
788 // First stash the large side's rep and move the small side across.
789 LargeRep TmpRep = llvm_move(*LargeSide.getLargeRep());
790 LargeSide.getLargeRep()->~LargeRep();
791 LargeSide.Small = true;
792 // This is similar to the standard move-from-old-buckets, but the bucket
793 // count hasn't actually rotated in this case. So we have to carefully
794 // move construct the keys and values into their new locations, but there
795 // is no need to re-hash things.
796 for (unsigned i = 0, e = InlineBuckets; i != e; ++i) {
797 BucketT *NewB = &LargeSide.getInlineBuckets()[i],
798 *OldB = &SmallSide.getInlineBuckets()[i];
799 new (&NewB->first) KeyT(llvm_move(OldB->first));
801 if (!KeyInfoT::isEqual(NewB->first, EmptyKey) &&
802 !KeyInfoT::isEqual(NewB->first, TombstoneKey)) {
803 new (&NewB->second) ValueT(llvm_move(OldB->second));
804 OldB->second.~ValueT();
808 // The hard part of moving the small buckets across is done, just move
809 // the TmpRep into its new home.
810 SmallSide.Small = false;
811 new (SmallSide.getLargeRep()) LargeRep(llvm_move(TmpRep));
814 SmallDenseMap& operator=(const SmallDenseMap& other) {
819 #if LLVM_HAS_RVALUE_REFERENCES
820 SmallDenseMap& operator=(SmallDenseMap &&other) {
829 void copyFrom(const SmallDenseMap& other) {
833 if (other.getNumBuckets() > InlineBuckets) {
835 allocateBuckets(other.getNumBuckets());
837 this->BaseT::copyFrom(other);
840 void init(unsigned InitBuckets) {
842 if (InitBuckets > InlineBuckets) {
844 new (getLargeRep()) LargeRep(allocateBuckets(InitBuckets));
846 this->BaseT::initEmpty();
849 void grow(unsigned AtLeast) {
850 if (AtLeast >= InlineBuckets)
851 AtLeast = std::max<unsigned>(64, NextPowerOf2(AtLeast-1));
854 if (AtLeast < InlineBuckets)
855 return; // Nothing to do.
857 // First move the inline buckets into a temporary storage.
858 AlignedCharArrayUnion<BucketT[InlineBuckets]> TmpStorage;
859 BucketT *TmpBegin = reinterpret_cast<BucketT *>(TmpStorage.buffer);
860 BucketT *TmpEnd = TmpBegin;
862 // Loop over the buckets, moving non-empty, non-tombstones into the
863 // temporary storage. Have the loop move the TmpEnd forward as it goes.
864 const KeyT EmptyKey = this->getEmptyKey();
865 const KeyT TombstoneKey = this->getTombstoneKey();
866 for (BucketT *P = getBuckets(), *E = P + InlineBuckets; P != E; ++P) {
867 if (!KeyInfoT::isEqual(P->first, EmptyKey) &&
868 !KeyInfoT::isEqual(P->first, TombstoneKey)) {
869 assert(size_t(TmpEnd - TmpBegin) < InlineBuckets &&
870 "Too many inline buckets!");
871 new (&TmpEnd->first) KeyT(llvm_move(P->first));
872 new (&TmpEnd->second) ValueT(llvm_move(P->second));
879 // Now make this map use the large rep, and move all the entries back
882 new (getLargeRep()) LargeRep(allocateBuckets(AtLeast));
883 this->moveFromOldBuckets(TmpBegin, TmpEnd);
887 LargeRep OldRep = llvm_move(*getLargeRep());
888 getLargeRep()->~LargeRep();
889 if (AtLeast <= InlineBuckets) {
892 new (getLargeRep()) LargeRep(allocateBuckets(AtLeast));
895 this->moveFromOldBuckets(OldRep.Buckets, OldRep.Buckets+OldRep.NumBuckets);
897 // Free the old table.
898 operator delete(OldRep.Buckets);
901 void shrink_and_clear() {
902 unsigned OldSize = this->size();
905 // Reduce the number of buckets.
906 unsigned NewNumBuckets = 0;
908 NewNumBuckets = 1 << (Log2_32_Ceil(OldSize) + 1);
909 if (NewNumBuckets > InlineBuckets && NewNumBuckets < 64u)
912 if ((Small && NewNumBuckets <= InlineBuckets) ||
913 (!Small && NewNumBuckets == getLargeRep()->NumBuckets)) {
914 this->BaseT::initEmpty();
923 unsigned getNumEntries() const {
926 void setNumEntries(unsigned Num) {
927 assert(Num < INT_MAX && "Cannot support more than INT_MAX entries");
931 unsigned getNumTombstones() const {
932 return NumTombstones;
934 void setNumTombstones(unsigned Num) {
938 const BucketT *getInlineBuckets() const {
940 // Note that this cast does not violate aliasing rules as we assert that
941 // the memory's dynamic type is the small, inline bucket buffer, and the
942 // 'storage.buffer' static type is 'char *'.
943 return reinterpret_cast<const BucketT *>(storage.buffer);
945 BucketT *getInlineBuckets() {
946 return const_cast<BucketT *>(
947 const_cast<const SmallDenseMap *>(this)->getInlineBuckets());
949 const LargeRep *getLargeRep() const {
951 // Note, same rule about aliasing as with getInlineBuckets.
952 return reinterpret_cast<const LargeRep *>(storage.buffer);
954 LargeRep *getLargeRep() {
955 return const_cast<LargeRep *>(
956 const_cast<const SmallDenseMap *>(this)->getLargeRep());
959 const BucketT *getBuckets() const {
960 return Small ? getInlineBuckets() : getLargeRep()->Buckets;
962 BucketT *getBuckets() {
963 return const_cast<BucketT *>(
964 const_cast<const SmallDenseMap *>(this)->getBuckets());
966 unsigned getNumBuckets() const {
967 return Small ? InlineBuckets : getLargeRep()->NumBuckets;
970 void deallocateBuckets() {
974 operator delete(getLargeRep()->Buckets);
975 getLargeRep()->~LargeRep();
978 LargeRep allocateBuckets(unsigned Num) {
979 assert(Num > InlineBuckets && "Must allocate more buckets than are inline");
981 static_cast<BucketT*>(operator new(sizeof(BucketT) * Num)), Num
987 template<typename KeyT, typename ValueT,
988 typename KeyInfoT, bool IsConst>
989 class DenseMapIterator {
990 typedef std::pair<KeyT, ValueT> Bucket;
991 typedef DenseMapIterator<KeyT, ValueT,
992 KeyInfoT, true> ConstIterator;
993 friend class DenseMapIterator<KeyT, ValueT, KeyInfoT, true>;
995 typedef ptrdiff_t difference_type;
996 typedef typename conditional<IsConst, const Bucket, Bucket>::type value_type;
997 typedef value_type *pointer;
998 typedef value_type &reference;
999 typedef std::forward_iterator_tag iterator_category;
1003 DenseMapIterator() : Ptr(0), End(0) {}
1005 DenseMapIterator(pointer Pos, pointer E, bool NoAdvance = false)
1006 : Ptr(Pos), End(E) {
1007 if (!NoAdvance) AdvancePastEmptyBuckets();
1010 // If IsConst is true this is a converting constructor from iterator to
1011 // const_iterator and the default copy constructor is used.
1012 // Otherwise this is a copy constructor for iterator.
1013 DenseMapIterator(const DenseMapIterator<KeyT, ValueT,
1014 KeyInfoT, false>& I)
1015 : Ptr(I.Ptr), End(I.End) {}
1017 reference operator*() const {
1020 pointer operator->() const {
1024 bool operator==(const ConstIterator &RHS) const {
1025 return Ptr == RHS.operator->();
1027 bool operator!=(const ConstIterator &RHS) const {
1028 return Ptr != RHS.operator->();
1031 inline DenseMapIterator& operator++() { // Preincrement
1033 AdvancePastEmptyBuckets();
1036 DenseMapIterator operator++(int) { // Postincrement
1037 DenseMapIterator tmp = *this; ++*this; return tmp;
1041 void AdvancePastEmptyBuckets() {
1042 const KeyT Empty = KeyInfoT::getEmptyKey();
1043 const KeyT Tombstone = KeyInfoT::getTombstoneKey();
1045 while (Ptr != End &&
1046 (KeyInfoT::isEqual(Ptr->first, Empty) ||
1047 KeyInfoT::isEqual(Ptr->first, Tombstone)))
1052 template<typename KeyT, typename ValueT, typename KeyInfoT>
1053 static inline size_t
1054 capacity_in_bytes(const DenseMap<KeyT, ValueT, KeyInfoT> &X) {
1055 return X.getMemorySize();
1058 } // end namespace llvm