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 LLVM_ATTRIBUTE_UNUSED_RESULT empty() const {
68 return getNumEntries() == 0;
70 unsigned size() const { return getNumEntries(); }
72 /// Grow the densemap so that it has at least Size buckets. Does not shrink
73 void resize(size_t Size) {
74 if (Size > getNumBuckets())
79 if (getNumEntries() == 0 && getNumTombstones() == 0) return;
81 // If the capacity of the array is huge, and the # elements used is small,
83 if (getNumEntries() * 4 < getNumBuckets() && getNumBuckets() > 64) {
88 const KeyT EmptyKey = getEmptyKey(), TombstoneKey = getTombstoneKey();
89 for (BucketT *P = getBuckets(), *E = getBucketsEnd(); P != E; ++P) {
90 if (!KeyInfoT::isEqual(P->first, EmptyKey)) {
91 if (!KeyInfoT::isEqual(P->first, TombstoneKey)) {
93 decrementNumEntries();
98 assert(getNumEntries() == 0 && "Node count imbalance!");
102 /// count - Return true if the specified key is in the map.
103 bool count(const KeyT &Val) const {
104 const BucketT *TheBucket;
105 return LookupBucketFor(Val, TheBucket);
108 iterator find(const KeyT &Val) {
110 if (LookupBucketFor(Val, TheBucket))
111 return iterator(TheBucket, getBucketsEnd(), true);
114 const_iterator find(const KeyT &Val) const {
115 const BucketT *TheBucket;
116 if (LookupBucketFor(Val, TheBucket))
117 return const_iterator(TheBucket, getBucketsEnd(), true);
121 /// Alternate version of find() which allows a different, and possibly
122 /// less expensive, key type.
123 /// The DenseMapInfo is responsible for supplying methods
124 /// getHashValue(LookupKeyT) and isEqual(LookupKeyT, KeyT) for each key
126 template<class LookupKeyT>
127 iterator find_as(const LookupKeyT &Val) {
129 if (LookupBucketFor(Val, TheBucket))
130 return iterator(TheBucket, getBucketsEnd(), true);
133 template<class LookupKeyT>
134 const_iterator find_as(const LookupKeyT &Val) const {
135 const BucketT *TheBucket;
136 if (LookupBucketFor(Val, TheBucket))
137 return const_iterator(TheBucket, getBucketsEnd(), true);
141 /// lookup - Return the entry for the specified key, or a default
142 /// constructed value if no such entry exists.
143 ValueT lookup(const KeyT &Val) const {
144 const BucketT *TheBucket;
145 if (LookupBucketFor(Val, TheBucket))
146 return TheBucket->second;
150 // Inserts key,value pair into the map if the key isn't already in the map.
151 // If the key is already in the map, it returns false and doesn't update the
153 std::pair<iterator, bool> insert(const std::pair<KeyT, ValueT> &KV) {
155 if (LookupBucketFor(KV.first, TheBucket))
156 return std::make_pair(iterator(TheBucket, getBucketsEnd(), true),
157 false); // Already in map.
159 // Otherwise, insert the new element.
160 TheBucket = InsertIntoBucket(KV.first, KV.second, TheBucket);
161 return std::make_pair(iterator(TheBucket, getBucketsEnd(), true), true);
164 #if LLVM_HAS_RVALUE_REFERENCES
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);
182 /// insert - Range insertion of pairs.
183 template<typename InputIt>
184 void insert(InputIt I, InputIt E) {
190 bool erase(const KeyT &Val) {
192 if (!LookupBucketFor(Val, TheBucket))
193 return false; // not in map.
195 TheBucket->second.~ValueT();
196 TheBucket->first = getTombstoneKey();
197 decrementNumEntries();
198 incrementNumTombstones();
201 void erase(iterator I) {
202 BucketT *TheBucket = &*I;
203 TheBucket->second.~ValueT();
204 TheBucket->first = getTombstoneKey();
205 decrementNumEntries();
206 incrementNumTombstones();
209 value_type& FindAndConstruct(const KeyT &Key) {
211 if (LookupBucketFor(Key, TheBucket))
214 return *InsertIntoBucket(Key, ValueT(), TheBucket);
217 ValueT &operator[](const KeyT &Key) {
218 return FindAndConstruct(Key).second;
221 #if LLVM_HAS_RVALUE_REFERENCES
222 value_type& FindAndConstruct(KeyT &&Key) {
224 if (LookupBucketFor(Key, TheBucket))
227 return *InsertIntoBucket(std::move(Key), ValueT(), TheBucket);
230 ValueT &operator[](KeyT &&Key) {
231 return FindAndConstruct(std::move(Key)).second;
235 /// isPointerIntoBucketsArray - Return true if the specified pointer points
236 /// somewhere into the DenseMap's array of buckets (i.e. either to a key or
237 /// value in the DenseMap).
238 bool isPointerIntoBucketsArray(const void *Ptr) const {
239 return Ptr >= getBuckets() && Ptr < getBucketsEnd();
242 /// getPointerIntoBucketsArray() - Return an opaque pointer into the buckets
243 /// array. In conjunction with the previous method, this can be used to
244 /// determine whether an insertion caused the DenseMap to reallocate.
245 const void *getPointerIntoBucketsArray() const { return getBuckets(); }
251 if (getNumBuckets() == 0) // Nothing to do.
254 const KeyT EmptyKey = getEmptyKey(), TombstoneKey = getTombstoneKey();
255 for (BucketT *P = getBuckets(), *E = getBucketsEnd(); P != E; ++P) {
256 if (!KeyInfoT::isEqual(P->first, EmptyKey) &&
257 !KeyInfoT::isEqual(P->first, TombstoneKey))
263 memset((void*)getBuckets(), 0x5a, sizeof(BucketT)*getNumBuckets());
271 assert((getNumBuckets() & (getNumBuckets()-1)) == 0 &&
272 "# initial buckets must be a power of two!");
273 const KeyT EmptyKey = getEmptyKey();
274 for (BucketT *B = getBuckets(), *E = getBucketsEnd(); B != E; ++B)
275 new (&B->first) KeyT(EmptyKey);
278 void moveFromOldBuckets(BucketT *OldBucketsBegin, BucketT *OldBucketsEnd) {
281 // Insert all the old elements.
282 const KeyT EmptyKey = getEmptyKey();
283 const KeyT TombstoneKey = getTombstoneKey();
284 for (BucketT *B = OldBucketsBegin, *E = OldBucketsEnd; B != E; ++B) {
285 if (!KeyInfoT::isEqual(B->first, EmptyKey) &&
286 !KeyInfoT::isEqual(B->first, TombstoneKey)) {
287 // Insert the key/value into the new table.
289 bool FoundVal = LookupBucketFor(B->first, DestBucket);
290 (void)FoundVal; // silence warning.
291 assert(!FoundVal && "Key already in new map?");
292 DestBucket->first = llvm_move(B->first);
293 new (&DestBucket->second) ValueT(llvm_move(B->second));
294 incrementNumEntries();
303 if (OldBucketsBegin != OldBucketsEnd)
304 memset((void*)OldBucketsBegin, 0x5a,
305 sizeof(BucketT) * (OldBucketsEnd - OldBucketsBegin));
309 template <typename OtherBaseT>
310 void copyFrom(const DenseMapBase<OtherBaseT, KeyT, ValueT, KeyInfoT>& other) {
311 assert(getNumBuckets() == other.getNumBuckets());
313 setNumEntries(other.getNumEntries());
314 setNumTombstones(other.getNumTombstones());
316 if (isPodLike<KeyT>::value && isPodLike<ValueT>::value)
317 memcpy(getBuckets(), other.getBuckets(),
318 getNumBuckets() * sizeof(BucketT));
320 for (size_t i = 0; i < getNumBuckets(); ++i) {
321 new (&getBuckets()[i].first) KeyT(other.getBuckets()[i].first);
322 if (!KeyInfoT::isEqual(getBuckets()[i].first, getEmptyKey()) &&
323 !KeyInfoT::isEqual(getBuckets()[i].first, getTombstoneKey()))
324 new (&getBuckets()[i].second) ValueT(other.getBuckets()[i].second);
328 void swap(DenseMapBase& RHS) {
329 std::swap(getNumEntries(), RHS.getNumEntries());
330 std::swap(getNumTombstones(), RHS.getNumTombstones());
333 static unsigned getHashValue(const KeyT &Val) {
334 return KeyInfoT::getHashValue(Val);
336 template<typename LookupKeyT>
337 static unsigned getHashValue(const LookupKeyT &Val) {
338 return KeyInfoT::getHashValue(Val);
340 static const KeyT getEmptyKey() {
341 return KeyInfoT::getEmptyKey();
343 static const KeyT getTombstoneKey() {
344 return KeyInfoT::getTombstoneKey();
348 unsigned getNumEntries() const {
349 return static_cast<const DerivedT *>(this)->getNumEntries();
351 void setNumEntries(unsigned Num) {
352 static_cast<DerivedT *>(this)->setNumEntries(Num);
354 void incrementNumEntries() {
355 setNumEntries(getNumEntries() + 1);
357 void decrementNumEntries() {
358 setNumEntries(getNumEntries() - 1);
360 unsigned getNumTombstones() const {
361 return static_cast<const DerivedT *>(this)->getNumTombstones();
363 void setNumTombstones(unsigned Num) {
364 static_cast<DerivedT *>(this)->setNumTombstones(Num);
366 void incrementNumTombstones() {
367 setNumTombstones(getNumTombstones() + 1);
369 void decrementNumTombstones() {
370 setNumTombstones(getNumTombstones() - 1);
372 const BucketT *getBuckets() const {
373 return static_cast<const DerivedT *>(this)->getBuckets();
375 BucketT *getBuckets() {
376 return static_cast<DerivedT *>(this)->getBuckets();
378 unsigned getNumBuckets() const {
379 return static_cast<const DerivedT *>(this)->getNumBuckets();
381 BucketT *getBucketsEnd() {
382 return getBuckets() + getNumBuckets();
384 const BucketT *getBucketsEnd() const {
385 return getBuckets() + getNumBuckets();
388 void grow(unsigned AtLeast) {
389 static_cast<DerivedT *>(this)->grow(AtLeast);
392 void shrink_and_clear() {
393 static_cast<DerivedT *>(this)->shrink_and_clear();
397 BucketT *InsertIntoBucket(const KeyT &Key, const ValueT &Value,
398 BucketT *TheBucket) {
399 TheBucket = InsertIntoBucketImpl(Key, TheBucket);
401 TheBucket->first = Key;
402 new (&TheBucket->second) ValueT(Value);
406 #if LLVM_HAS_RVALUE_REFERENCES
407 BucketT *InsertIntoBucket(const KeyT &Key, ValueT &&Value,
408 BucketT *TheBucket) {
409 TheBucket = InsertIntoBucketImpl(Key, TheBucket);
411 TheBucket->first = Key;
412 new (&TheBucket->second) ValueT(std::move(Value));
416 BucketT *InsertIntoBucket(KeyT &&Key, ValueT &&Value, BucketT *TheBucket) {
417 TheBucket = InsertIntoBucketImpl(Key, TheBucket);
419 TheBucket->first = std::move(Key);
420 new (&TheBucket->second) ValueT(std::move(Value));
425 BucketT *InsertIntoBucketImpl(const KeyT &Key, BucketT *TheBucket) {
426 // If the load of the hash table is more than 3/4, or if fewer than 1/8 of
427 // the buckets are empty (meaning that many are filled with tombstones),
430 // The later case is tricky. For example, if we had one empty bucket with
431 // tons of tombstones, failing lookups (e.g. for insertion) would have to
432 // probe almost the entire table until it found the empty bucket. If the
433 // table completely filled with tombstones, no lookup would ever succeed,
434 // causing infinite loops in lookup.
435 unsigned NewNumEntries = getNumEntries() + 1;
436 unsigned NumBuckets = getNumBuckets();
437 if (NewNumEntries*4 >= NumBuckets*3) {
438 this->grow(NumBuckets * 2);
439 LookupBucketFor(Key, TheBucket);
440 NumBuckets = getNumBuckets();
441 } else if (NumBuckets-(NewNumEntries+getNumTombstones()) <= NumBuckets/8) {
442 this->grow(NumBuckets);
443 LookupBucketFor(Key, TheBucket);
447 // Only update the state after we've grown our bucket space appropriately
448 // so that when growing buckets we have self-consistent entry count.
449 incrementNumEntries();
451 // If we are writing over a tombstone, remember this.
452 const KeyT EmptyKey = getEmptyKey();
453 if (!KeyInfoT::isEqual(TheBucket->first, EmptyKey))
454 decrementNumTombstones();
459 /// LookupBucketFor - Lookup the appropriate bucket for Val, returning it in
460 /// FoundBucket. If the bucket contains the key and a value, this returns
461 /// true, otherwise it returns a bucket with an empty marker or tombstone and
463 template<typename LookupKeyT>
464 bool LookupBucketFor(const LookupKeyT &Val,
465 const BucketT *&FoundBucket) const {
466 const BucketT *BucketsPtr = getBuckets();
467 const unsigned NumBuckets = getNumBuckets();
469 if (NumBuckets == 0) {
474 // FoundTombstone - Keep track of whether we find a tombstone while probing.
475 const BucketT *FoundTombstone = 0;
476 const KeyT EmptyKey = getEmptyKey();
477 const KeyT TombstoneKey = getTombstoneKey();
478 assert(!KeyInfoT::isEqual(Val, EmptyKey) &&
479 !KeyInfoT::isEqual(Val, TombstoneKey) &&
480 "Empty/Tombstone value shouldn't be inserted into map!");
482 unsigned BucketNo = getHashValue(Val) & (NumBuckets-1);
483 unsigned ProbeAmt = 1;
485 const BucketT *ThisBucket = BucketsPtr + BucketNo;
486 // Found Val's bucket? If so, return it.
487 if (KeyInfoT::isEqual(Val, ThisBucket->first)) {
488 FoundBucket = ThisBucket;
492 // If we found an empty bucket, the key doesn't exist in the set.
493 // Insert it and return the default value.
494 if (KeyInfoT::isEqual(ThisBucket->first, EmptyKey)) {
495 // If we've already seen a tombstone while probing, fill it in instead
496 // of the empty bucket we eventually probed to.
497 FoundBucket = FoundTombstone ? FoundTombstone : ThisBucket;
501 // If this is a tombstone, remember it. If Val ends up not in the map, we
502 // prefer to return it than something that would require more probing.
503 if (KeyInfoT::isEqual(ThisBucket->first, TombstoneKey) && !FoundTombstone)
504 FoundTombstone = ThisBucket; // Remember the first tombstone found.
506 // Otherwise, it's a hash collision or a tombstone, continue quadratic
508 BucketNo += ProbeAmt++;
509 BucketNo &= (NumBuckets-1);
513 template <typename LookupKeyT>
514 bool LookupBucketFor(const LookupKeyT &Val, BucketT *&FoundBucket) {
515 const BucketT *ConstFoundBucket;
516 bool Result = const_cast<const DenseMapBase *>(this)
517 ->LookupBucketFor(Val, ConstFoundBucket);
518 FoundBucket = const_cast<BucketT *>(ConstFoundBucket);
523 /// Return the approximate size (in bytes) of the actual map.
524 /// This is just the raw memory used by DenseMap.
525 /// If entries are pointers to objects, the size of the referenced objects
526 /// are not included.
527 size_t getMemorySize() const {
528 return getNumBuckets() * sizeof(BucketT);
532 template<typename KeyT, typename ValueT,
533 typename KeyInfoT = DenseMapInfo<KeyT> >
535 : public DenseMapBase<DenseMap<KeyT, ValueT, KeyInfoT>,
536 KeyT, ValueT, KeyInfoT> {
537 // Lift some types from the dependent base class into this class for
538 // simplicity of referring to them.
539 typedef DenseMapBase<DenseMap, KeyT, ValueT, KeyInfoT> BaseT;
540 typedef typename BaseT::BucketT BucketT;
541 friend class DenseMapBase<DenseMap, KeyT, ValueT, KeyInfoT>;
545 unsigned NumTombstones;
549 explicit DenseMap(unsigned NumInitBuckets = 0) {
550 init(NumInitBuckets);
553 DenseMap(const DenseMap &other) : BaseT() {
558 #if LLVM_HAS_RVALUE_REFERENCES
559 DenseMap(DenseMap &&other) : BaseT() {
565 template<typename InputIt>
566 DenseMap(const InputIt &I, const InputIt &E) {
567 init(NextPowerOf2(std::distance(I, E)));
573 operator delete(Buckets);
576 void swap(DenseMap& RHS) {
577 std::swap(Buckets, RHS.Buckets);
578 std::swap(NumEntries, RHS.NumEntries);
579 std::swap(NumTombstones, RHS.NumTombstones);
580 std::swap(NumBuckets, RHS.NumBuckets);
583 DenseMap& operator=(const DenseMap& other) {
588 #if LLVM_HAS_RVALUE_REFERENCES
589 DenseMap& operator=(DenseMap &&other) {
591 operator delete(Buckets);
598 void copyFrom(const DenseMap& other) {
600 operator delete(Buckets);
601 if (allocateBuckets(other.NumBuckets)) {
602 this->BaseT::copyFrom(other);
609 void init(unsigned InitBuckets) {
610 if (allocateBuckets(InitBuckets)) {
611 this->BaseT::initEmpty();
618 void grow(unsigned AtLeast) {
619 unsigned OldNumBuckets = NumBuckets;
620 BucketT *OldBuckets = Buckets;
622 allocateBuckets(std::max<unsigned>(64, static_cast<unsigned>(NextPowerOf2(AtLeast-1))));
625 this->BaseT::initEmpty();
629 this->moveFromOldBuckets(OldBuckets, OldBuckets+OldNumBuckets);
631 // Free the old table.
632 operator delete(OldBuckets);
635 void shrink_and_clear() {
636 unsigned OldNumEntries = NumEntries;
639 // Reduce the number of buckets.
640 unsigned NewNumBuckets = 0;
642 NewNumBuckets = std::max(64, 1 << (Log2_32_Ceil(OldNumEntries) + 1));
643 if (NewNumBuckets == NumBuckets) {
644 this->BaseT::initEmpty();
648 operator delete(Buckets);
653 unsigned getNumEntries() const {
656 void setNumEntries(unsigned Num) {
660 unsigned getNumTombstones() const {
661 return NumTombstones;
663 void setNumTombstones(unsigned Num) {
667 BucketT *getBuckets() const {
671 unsigned getNumBuckets() const {
675 bool allocateBuckets(unsigned Num) {
677 if (NumBuckets == 0) {
682 Buckets = static_cast<BucketT*>(operator new(sizeof(BucketT) * NumBuckets));
687 template<typename KeyT, typename ValueT,
688 unsigned InlineBuckets = 4,
689 typename KeyInfoT = DenseMapInfo<KeyT> >
691 : public DenseMapBase<SmallDenseMap<KeyT, ValueT, InlineBuckets, KeyInfoT>,
692 KeyT, ValueT, KeyInfoT> {
693 // Lift some types from the dependent base class into this class for
694 // simplicity of referring to them.
695 typedef DenseMapBase<SmallDenseMap, KeyT, ValueT, KeyInfoT> BaseT;
696 typedef typename BaseT::BucketT BucketT;
697 friend class DenseMapBase<SmallDenseMap, KeyT, ValueT, KeyInfoT>;
700 unsigned NumEntries : 31;
701 unsigned NumTombstones;
708 /// A "union" of an inline bucket array and the struct representing
709 /// a large bucket. This union will be discriminated by the 'Small' bit.
710 AlignedCharArrayUnion<BucketT[InlineBuckets], LargeRep> storage;
713 explicit SmallDenseMap(unsigned NumInitBuckets = 0) {
714 init(NumInitBuckets);
717 SmallDenseMap(const SmallDenseMap &other) : BaseT() {
722 #if LLVM_HAS_RVALUE_REFERENCES
723 SmallDenseMap(SmallDenseMap &&other) : BaseT() {
729 template<typename InputIt>
730 SmallDenseMap(const InputIt &I, const InputIt &E) {
731 init(NextPowerOf2(std::distance(I, E)));
740 void swap(SmallDenseMap& RHS) {
741 unsigned TmpNumEntries = RHS.NumEntries;
742 RHS.NumEntries = NumEntries;
743 NumEntries = TmpNumEntries;
744 std::swap(NumTombstones, RHS.NumTombstones);
746 const KeyT EmptyKey = this->getEmptyKey();
747 const KeyT TombstoneKey = this->getTombstoneKey();
748 if (Small && RHS.Small) {
749 // If we're swapping inline bucket arrays, we have to cope with some of
750 // the tricky bits of DenseMap's storage system: the buckets are not
751 // fully initialized. Thus we swap every key, but we may have
752 // a one-directional move of the value.
753 for (unsigned i = 0, e = InlineBuckets; i != e; ++i) {
754 BucketT *LHSB = &getInlineBuckets()[i],
755 *RHSB = &RHS.getInlineBuckets()[i];
756 bool hasLHSValue = (!KeyInfoT::isEqual(LHSB->first, EmptyKey) &&
757 !KeyInfoT::isEqual(LHSB->first, TombstoneKey));
758 bool hasRHSValue = (!KeyInfoT::isEqual(RHSB->first, EmptyKey) &&
759 !KeyInfoT::isEqual(RHSB->first, TombstoneKey));
760 if (hasLHSValue && hasRHSValue) {
761 // Swap together if we can...
762 std::swap(*LHSB, *RHSB);
765 // Swap separately and handle any assymetry.
766 std::swap(LHSB->first, RHSB->first);
768 new (&RHSB->second) ValueT(llvm_move(LHSB->second));
769 LHSB->second.~ValueT();
770 } else if (hasRHSValue) {
771 new (&LHSB->second) ValueT(llvm_move(RHSB->second));
772 RHSB->second.~ValueT();
777 if (!Small && !RHS.Small) {
778 std::swap(getLargeRep()->Buckets, RHS.getLargeRep()->Buckets);
779 std::swap(getLargeRep()->NumBuckets, RHS.getLargeRep()->NumBuckets);
783 SmallDenseMap &SmallSide = Small ? *this : RHS;
784 SmallDenseMap &LargeSide = Small ? RHS : *this;
786 // First stash the large side's rep and move the small side across.
787 LargeRep TmpRep = llvm_move(*LargeSide.getLargeRep());
788 LargeSide.getLargeRep()->~LargeRep();
789 LargeSide.Small = true;
790 // This is similar to the standard move-from-old-buckets, but the bucket
791 // count hasn't actually rotated in this case. So we have to carefully
792 // move construct the keys and values into their new locations, but there
793 // is no need to re-hash things.
794 for (unsigned i = 0, e = InlineBuckets; i != e; ++i) {
795 BucketT *NewB = &LargeSide.getInlineBuckets()[i],
796 *OldB = &SmallSide.getInlineBuckets()[i];
797 new (&NewB->first) KeyT(llvm_move(OldB->first));
799 if (!KeyInfoT::isEqual(NewB->first, EmptyKey) &&
800 !KeyInfoT::isEqual(NewB->first, TombstoneKey)) {
801 new (&NewB->second) ValueT(llvm_move(OldB->second));
802 OldB->second.~ValueT();
806 // The hard part of moving the small buckets across is done, just move
807 // the TmpRep into its new home.
808 SmallSide.Small = false;
809 new (SmallSide.getLargeRep()) LargeRep(llvm_move(TmpRep));
812 SmallDenseMap& operator=(const SmallDenseMap& other) {
817 #if LLVM_HAS_RVALUE_REFERENCES
818 SmallDenseMap& operator=(SmallDenseMap &&other) {
827 void copyFrom(const SmallDenseMap& other) {
831 if (other.getNumBuckets() > InlineBuckets) {
833 new (getLargeRep()) LargeRep(allocateBuckets(other.getNumBuckets()));
835 this->BaseT::copyFrom(other);
838 void init(unsigned InitBuckets) {
840 if (InitBuckets > InlineBuckets) {
842 new (getLargeRep()) LargeRep(allocateBuckets(InitBuckets));
844 this->BaseT::initEmpty();
847 void grow(unsigned AtLeast) {
848 if (AtLeast >= InlineBuckets)
849 AtLeast = std::max<unsigned>(64, NextPowerOf2(AtLeast-1));
852 if (AtLeast < InlineBuckets)
853 return; // Nothing to do.
855 // First move the inline buckets into a temporary storage.
856 AlignedCharArrayUnion<BucketT[InlineBuckets]> TmpStorage;
857 BucketT *TmpBegin = reinterpret_cast<BucketT *>(TmpStorage.buffer);
858 BucketT *TmpEnd = TmpBegin;
860 // Loop over the buckets, moving non-empty, non-tombstones into the
861 // temporary storage. Have the loop move the TmpEnd forward as it goes.
862 const KeyT EmptyKey = this->getEmptyKey();
863 const KeyT TombstoneKey = this->getTombstoneKey();
864 for (BucketT *P = getBuckets(), *E = P + InlineBuckets; P != E; ++P) {
865 if (!KeyInfoT::isEqual(P->first, EmptyKey) &&
866 !KeyInfoT::isEqual(P->first, TombstoneKey)) {
867 assert(size_t(TmpEnd - TmpBegin) < InlineBuckets &&
868 "Too many inline buckets!");
869 new (&TmpEnd->first) KeyT(llvm_move(P->first));
870 new (&TmpEnd->second) ValueT(llvm_move(P->second));
877 // Now make this map use the large rep, and move all the entries back
880 new (getLargeRep()) LargeRep(allocateBuckets(AtLeast));
881 this->moveFromOldBuckets(TmpBegin, TmpEnd);
885 LargeRep OldRep = llvm_move(*getLargeRep());
886 getLargeRep()->~LargeRep();
887 if (AtLeast <= InlineBuckets) {
890 new (getLargeRep()) LargeRep(allocateBuckets(AtLeast));
893 this->moveFromOldBuckets(OldRep.Buckets, OldRep.Buckets+OldRep.NumBuckets);
895 // Free the old table.
896 operator delete(OldRep.Buckets);
899 void shrink_and_clear() {
900 unsigned OldSize = this->size();
903 // Reduce the number of buckets.
904 unsigned NewNumBuckets = 0;
906 NewNumBuckets = 1 << (Log2_32_Ceil(OldSize) + 1);
907 if (NewNumBuckets > InlineBuckets && NewNumBuckets < 64u)
910 if ((Small && NewNumBuckets <= InlineBuckets) ||
911 (!Small && NewNumBuckets == getLargeRep()->NumBuckets)) {
912 this->BaseT::initEmpty();
921 unsigned getNumEntries() const {
924 void setNumEntries(unsigned Num) {
925 assert(Num < INT_MAX && "Cannot support more than INT_MAX entries");
929 unsigned getNumTombstones() const {
930 return NumTombstones;
932 void setNumTombstones(unsigned Num) {
936 const BucketT *getInlineBuckets() const {
938 // Note that this cast does not violate aliasing rules as we assert that
939 // the memory's dynamic type is the small, inline bucket buffer, and the
940 // 'storage.buffer' static type is 'char *'.
941 return reinterpret_cast<const BucketT *>(storage.buffer);
943 BucketT *getInlineBuckets() {
944 return const_cast<BucketT *>(
945 const_cast<const SmallDenseMap *>(this)->getInlineBuckets());
947 const LargeRep *getLargeRep() const {
949 // Note, same rule about aliasing as with getInlineBuckets.
950 return reinterpret_cast<const LargeRep *>(storage.buffer);
952 LargeRep *getLargeRep() {
953 return const_cast<LargeRep *>(
954 const_cast<const SmallDenseMap *>(this)->getLargeRep());
957 const BucketT *getBuckets() const {
958 return Small ? getInlineBuckets() : getLargeRep()->Buckets;
960 BucketT *getBuckets() {
961 return const_cast<BucketT *>(
962 const_cast<const SmallDenseMap *>(this)->getBuckets());
964 unsigned getNumBuckets() const {
965 return Small ? InlineBuckets : getLargeRep()->NumBuckets;
968 void deallocateBuckets() {
972 operator delete(getLargeRep()->Buckets);
973 getLargeRep()->~LargeRep();
976 LargeRep allocateBuckets(unsigned Num) {
977 assert(Num > InlineBuckets && "Must allocate more buckets than are inline");
979 static_cast<BucketT*>(operator new(sizeof(BucketT) * Num)), Num
985 template<typename KeyT, typename ValueT,
986 typename KeyInfoT, bool IsConst>
987 class DenseMapIterator {
988 typedef std::pair<KeyT, ValueT> Bucket;
989 typedef DenseMapIterator<KeyT, ValueT,
990 KeyInfoT, true> ConstIterator;
991 friend class DenseMapIterator<KeyT, ValueT, KeyInfoT, true>;
993 typedef ptrdiff_t difference_type;
994 typedef typename conditional<IsConst, const Bucket, Bucket>::type value_type;
995 typedef value_type *pointer;
996 typedef value_type &reference;
997 typedef std::forward_iterator_tag iterator_category;
1001 DenseMapIterator() : Ptr(0), End(0) {}
1003 DenseMapIterator(pointer Pos, pointer E, bool NoAdvance = false)
1004 : Ptr(Pos), End(E) {
1005 if (!NoAdvance) AdvancePastEmptyBuckets();
1008 // If IsConst is true this is a converting constructor from iterator to
1009 // const_iterator and the default copy constructor is used.
1010 // Otherwise this is a copy constructor for iterator.
1011 DenseMapIterator(const DenseMapIterator<KeyT, ValueT,
1012 KeyInfoT, false>& I)
1013 : Ptr(I.Ptr), End(I.End) {}
1015 reference operator*() const {
1018 pointer operator->() const {
1022 bool operator==(const ConstIterator &RHS) const {
1023 return Ptr == RHS.operator->();
1025 bool operator!=(const ConstIterator &RHS) const {
1026 return Ptr != RHS.operator->();
1029 inline DenseMapIterator& operator++() { // Preincrement
1031 AdvancePastEmptyBuckets();
1034 DenseMapIterator operator++(int) { // Postincrement
1035 DenseMapIterator tmp = *this; ++*this; return tmp;
1039 void AdvancePastEmptyBuckets() {
1040 const KeyT Empty = KeyInfoT::getEmptyKey();
1041 const KeyT Tombstone = KeyInfoT::getTombstoneKey();
1043 while (Ptr != End &&
1044 (KeyInfoT::isEqual(Ptr->first, Empty) ||
1045 KeyInfoT::isEqual(Ptr->first, Tombstone)))
1050 template<typename KeyT, typename ValueT, typename KeyInfoT>
1051 static inline size_t
1052 capacity_in_bytes(const DenseMap<KeyT, ValueT, KeyInfoT> &X) {
1053 return X.getMemorySize();
1056 } // end namespace llvm