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/Support/Compiler.h"
18 #include "llvm/Support/MathExtras.h"
19 #include "llvm/Support/PointerLikeTypeTraits.h"
20 #include "llvm/Support/type_traits.h"
21 #include "llvm/ADT/DenseMapInfo.h"
32 template<typename KeyT, typename ValueT,
33 typename KeyInfoT = DenseMapInfo<KeyT>,
35 class DenseMapIterator;
37 template<typename KeyT, typename ValueT,
38 typename KeyInfoT = DenseMapInfo<KeyT> >
40 typedef std::pair<KeyT, ValueT> BucketT;
45 unsigned NumTombstones;
47 typedef KeyT key_type;
48 typedef ValueT mapped_type;
49 typedef BucketT value_type;
51 DenseMap(const DenseMap &other) {
56 explicit DenseMap(unsigned NumInitBuckets = 0) {
60 template<typename InputIt>
61 DenseMap(const InputIt &I, const InputIt &E) {
62 init(NextPowerOf2(std::distance(I, E)));
70 typedef DenseMapIterator<KeyT, ValueT, KeyInfoT> iterator;
71 typedef DenseMapIterator<KeyT, ValueT,
72 KeyInfoT, true> const_iterator;
73 inline iterator begin() {
74 // When the map is empty, avoid the overhead of AdvancePastEmptyBuckets().
75 return empty() ? end() : iterator(Buckets, Buckets+NumBuckets);
77 inline iterator end() {
78 return iterator(Buckets+NumBuckets, Buckets+NumBuckets, true);
80 inline const_iterator begin() const {
81 return empty() ? end() : const_iterator(Buckets, Buckets+NumBuckets);
83 inline const_iterator end() const {
84 return const_iterator(Buckets+NumBuckets, Buckets+NumBuckets, true);
87 bool empty() const { return NumEntries == 0; }
88 unsigned size() const { return NumEntries; }
90 /// Grow the densemap so that it has at least Size buckets. Does not shrink
91 void resize(size_t Size) {
92 if (Size > NumBuckets)
97 if (NumEntries == 0 && NumTombstones == 0) return;
99 // If the capacity of the array is huge, and the # elements used is small,
101 if (NumEntries * 4 < NumBuckets && NumBuckets > 64) {
106 const KeyT EmptyKey = getEmptyKey(), TombstoneKey = getTombstoneKey();
107 for (BucketT *P = Buckets, *E = Buckets+NumBuckets; P != E; ++P) {
108 if (!KeyInfoT::isEqual(P->first, EmptyKey)) {
109 if (!KeyInfoT::isEqual(P->first, TombstoneKey)) {
116 assert(NumEntries == 0 && "Node count imbalance!");
120 /// count - Return true if the specified key is in the map.
121 bool count(const KeyT &Val) const {
123 return LookupBucketFor(Val, TheBucket);
126 iterator find(const KeyT &Val) {
128 if (LookupBucketFor(Val, TheBucket))
129 return iterator(TheBucket, Buckets+NumBuckets, true);
132 const_iterator find(const KeyT &Val) const {
134 if (LookupBucketFor(Val, TheBucket))
135 return const_iterator(TheBucket, Buckets+NumBuckets, true);
139 /// Alternate version of find() which allows a different, and possibly
140 /// less expensive, key type.
141 /// The DenseMapInfo is responsible for supplying methods
142 /// getHashValue(LookupKeyT) and isEqual(LookupKeyT, KeyT) for each key
144 template<class LookupKeyT>
145 iterator find_as(const LookupKeyT &Val) {
147 if (LookupBucketFor(Val, TheBucket))
148 return iterator(TheBucket, Buckets+NumBuckets, true);
151 template<class LookupKeyT>
152 const_iterator find_as(const LookupKeyT &Val) const {
154 if (LookupBucketFor(Val, TheBucket))
155 return const_iterator(TheBucket, Buckets+NumBuckets, true);
159 /// lookup - Return the entry for the specified key, or a default
160 /// constructed value if no such entry exists.
161 ValueT lookup(const KeyT &Val) const {
163 if (LookupBucketFor(Val, TheBucket))
164 return TheBucket->second;
168 // Inserts key,value pair into the map if the key isn't already in the map.
169 // If the key is already in the map, it returns false and doesn't update the
171 std::pair<iterator, bool> insert(const std::pair<KeyT, ValueT> &KV) {
173 if (LookupBucketFor(KV.first, TheBucket))
174 return std::make_pair(iterator(TheBucket, Buckets+NumBuckets, true),
175 false); // Already in map.
177 // Otherwise, insert the new element.
178 TheBucket = InsertIntoBucket(KV.first, KV.second, TheBucket);
179 return std::make_pair(iterator(TheBucket, Buckets+NumBuckets, 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();
201 void erase(iterator I) {
202 BucketT *TheBucket = &*I;
203 TheBucket->second.~ValueT();
204 TheBucket->first = getTombstoneKey();
209 void swap(DenseMap& RHS) {
210 std::swap(NumBuckets, RHS.NumBuckets);
211 std::swap(Buckets, RHS.Buckets);
212 std::swap(NumEntries, RHS.NumEntries);
213 std::swap(NumTombstones, RHS.NumTombstones);
216 value_type& FindAndConstruct(const KeyT &Key) {
218 if (LookupBucketFor(Key, TheBucket))
221 return *InsertIntoBucket(Key, ValueT(), TheBucket);
224 ValueT &operator[](const KeyT &Key) {
225 return FindAndConstruct(Key).second;
228 DenseMap& operator=(const DenseMap& other) {
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 >= Buckets && Ptr < Buckets+NumBuckets;
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 Buckets; }
247 const KeyT EmptyKey = getEmptyKey(), TombstoneKey = getTombstoneKey();
248 for (BucketT *P = Buckets, *E = Buckets+NumBuckets; P != E; ++P) {
249 if (!KeyInfoT::isEqual(P->first, EmptyKey) &&
250 !KeyInfoT::isEqual(P->first, TombstoneKey))
257 memset((void*)Buckets, 0x5a, sizeof(BucketT)*NumBuckets);
259 operator delete(Buckets);
263 void CopyFrom(const DenseMap& other) {
266 NumEntries = other.NumEntries;
267 NumTombstones = other.NumTombstones;
268 NumBuckets = other.NumBuckets;
270 if (NumBuckets == 0) {
275 Buckets = static_cast<BucketT*>(operator new(sizeof(BucketT) * NumBuckets));
277 if (isPodLike<KeyT>::value && isPodLike<ValueT>::value)
278 memcpy(Buckets, other.Buckets, NumBuckets * sizeof(BucketT));
280 for (size_t i = 0; i < NumBuckets; ++i) {
281 new (&Buckets[i].first) KeyT(other.Buckets[i].first);
282 if (!KeyInfoT::isEqual(Buckets[i].first, getEmptyKey()) &&
283 !KeyInfoT::isEqual(Buckets[i].first, getTombstoneKey()))
284 new (&Buckets[i].second) ValueT(other.Buckets[i].second);
288 BucketT *InsertIntoBucket(const KeyT &Key, const ValueT &Value,
289 BucketT *TheBucket) {
290 // If the load of the hash table is more than 3/4, or if fewer than 1/8 of
291 // the buckets are empty (meaning that many are filled with tombstones),
294 // The later case is tricky. For example, if we had one empty bucket with
295 // tons of tombstones, failing lookups (e.g. for insertion) would have to
296 // probe almost the entire table until it found the empty bucket. If the
297 // table completely filled with tombstones, no lookup would ever succeed,
298 // causing infinite loops in lookup.
300 if (NumEntries*4 >= NumBuckets*3) {
301 this->grow(NumBuckets * 2);
302 LookupBucketFor(Key, TheBucket);
304 if (NumBuckets-(NumEntries+NumTombstones) < NumBuckets/8) {
305 this->grow(NumBuckets);
306 LookupBucketFor(Key, TheBucket);
309 // If we are writing over a tombstone, remember this.
310 if (!KeyInfoT::isEqual(TheBucket->first, getEmptyKey()))
313 TheBucket->first = Key;
314 new (&TheBucket->second) ValueT(Value);
318 static unsigned getHashValue(const KeyT &Val) {
319 return KeyInfoT::getHashValue(Val);
321 template<typename LookupKeyT>
322 static unsigned getHashValue(const LookupKeyT &Val) {
323 return KeyInfoT::getHashValue(Val);
325 static const KeyT getEmptyKey() {
326 return KeyInfoT::getEmptyKey();
328 static const KeyT getTombstoneKey() {
329 return KeyInfoT::getTombstoneKey();
332 /// LookupBucketFor - Lookup the appropriate bucket for Val, returning it in
333 /// FoundBucket. If the bucket contains the key and a value, this returns
334 /// true, otherwise it returns a bucket with an empty marker or tombstone and
336 template<typename LookupKeyT>
337 bool LookupBucketFor(const LookupKeyT &Val, BucketT *&FoundBucket) const {
338 unsigned BucketNo = getHashValue(Val);
339 unsigned ProbeAmt = 1;
340 BucketT *BucketsPtr = Buckets;
342 if (NumBuckets == 0) {
347 // FoundTombstone - Keep track of whether we find a tombstone while probing.
348 BucketT *FoundTombstone = 0;
349 const KeyT EmptyKey = getEmptyKey();
350 const KeyT TombstoneKey = getTombstoneKey();
351 assert(!KeyInfoT::isEqual(Val, EmptyKey) &&
352 !KeyInfoT::isEqual(Val, TombstoneKey) &&
353 "Empty/Tombstone value shouldn't be inserted into map!");
356 BucketT *ThisBucket = BucketsPtr + (BucketNo & (NumBuckets-1));
357 // Found Val's bucket? If so, return it.
358 if (KeyInfoT::isEqual(Val, ThisBucket->first)) {
359 FoundBucket = ThisBucket;
363 // If we found an empty bucket, the key doesn't exist in the set.
364 // Insert it and return the default value.
365 if (KeyInfoT::isEqual(ThisBucket->first, EmptyKey)) {
366 // If we've already seen a tombstone while probing, fill it in instead
367 // of the empty bucket we eventually probed to.
368 if (FoundTombstone) ThisBucket = FoundTombstone;
369 FoundBucket = FoundTombstone ? FoundTombstone : ThisBucket;
373 // If this is a tombstone, remember it. If Val ends up not in the map, we
374 // prefer to return it than something that would require more probing.
375 if (KeyInfoT::isEqual(ThisBucket->first, TombstoneKey) && !FoundTombstone)
376 FoundTombstone = ThisBucket; // Remember the first tombstone found.
378 // Otherwise, it's a hash collision or a tombstone, continue quadratic
380 BucketNo += ProbeAmt++;
384 void init(unsigned InitBuckets) {
387 NumBuckets = InitBuckets;
389 if (InitBuckets == 0) {
394 assert(InitBuckets && (InitBuckets & (InitBuckets-1)) == 0 &&
395 "# initial buckets must be a power of two!");
396 Buckets = static_cast<BucketT*>(operator new(sizeof(BucketT)*InitBuckets));
397 // Initialize all the keys to EmptyKey.
398 const KeyT EmptyKey = getEmptyKey();
399 for (unsigned i = 0; i != InitBuckets; ++i)
400 new (&Buckets[i].first) KeyT(EmptyKey);
403 void grow(unsigned AtLeast) {
404 unsigned OldNumBuckets = NumBuckets;
405 BucketT *OldBuckets = Buckets;
410 // Double the number of buckets.
411 while (NumBuckets < AtLeast)
414 Buckets = static_cast<BucketT*>(operator new(sizeof(BucketT)*NumBuckets));
416 // Initialize all the keys to EmptyKey.
417 const KeyT EmptyKey = getEmptyKey();
418 for (unsigned i = 0, e = NumBuckets; i != e; ++i)
419 new (&Buckets[i].first) KeyT(EmptyKey);
421 // Insert all the old elements.
422 const KeyT TombstoneKey = getTombstoneKey();
423 for (BucketT *B = OldBuckets, *E = OldBuckets+OldNumBuckets; B != E; ++B) {
424 if (!KeyInfoT::isEqual(B->first, EmptyKey) &&
425 !KeyInfoT::isEqual(B->first, TombstoneKey)) {
426 // Insert the key/value into the new table.
428 bool FoundVal = LookupBucketFor(B->first, DestBucket);
429 (void)FoundVal; // silence warning.
430 assert(!FoundVal && "Key already in new map?");
431 DestBucket->first = llvm_move(B->first);
432 new (&DestBucket->second) ValueT(llvm_move(B->second));
442 memset((void*)OldBuckets, 0x5a, sizeof(BucketT)*OldNumBuckets);
444 // Free the old table.
445 operator delete(OldBuckets);
448 void shrink_and_clear() {
449 unsigned OldNumBuckets = NumBuckets;
450 BucketT *OldBuckets = Buckets;
452 // Reduce the number of buckets.
453 NumBuckets = NumEntries > 32 ? 1 << (Log2_32_Ceil(NumEntries) + 1)
456 Buckets = static_cast<BucketT*>(operator new(sizeof(BucketT)*NumBuckets));
458 // Initialize all the keys to EmptyKey.
459 const KeyT EmptyKey = getEmptyKey();
460 for (unsigned i = 0, e = NumBuckets; i != e; ++i)
461 new (&Buckets[i].first) KeyT(EmptyKey);
463 // Free the old buckets.
464 const KeyT TombstoneKey = getTombstoneKey();
465 for (BucketT *B = OldBuckets, *E = OldBuckets+OldNumBuckets; B != E; ++B) {
466 if (!KeyInfoT::isEqual(B->first, EmptyKey) &&
467 !KeyInfoT::isEqual(B->first, TombstoneKey)) {
475 memset((void*)OldBuckets, 0x5a, sizeof(BucketT)*OldNumBuckets);
477 // Free the old table.
478 operator delete(OldBuckets);
484 /// Return the approximate size (in bytes) of the actual map.
485 /// This is just the raw memory used by DenseMap.
486 /// If entries are pointers to objects, the size of the referenced objects
487 /// are not included.
488 size_t getMemorySize() const {
489 return NumBuckets * sizeof(BucketT);
493 template<typename KeyT, typename ValueT,
494 typename KeyInfoT, bool IsConst>
495 class DenseMapIterator {
496 typedef std::pair<KeyT, ValueT> Bucket;
497 typedef DenseMapIterator<KeyT, ValueT,
498 KeyInfoT, true> ConstIterator;
499 friend class DenseMapIterator<KeyT, ValueT, KeyInfoT, true>;
501 typedef ptrdiff_t difference_type;
502 typedef typename conditional<IsConst, const Bucket, Bucket>::type value_type;
503 typedef value_type *pointer;
504 typedef value_type &reference;
505 typedef std::forward_iterator_tag iterator_category;
509 DenseMapIterator() : Ptr(0), End(0) {}
511 DenseMapIterator(pointer Pos, pointer E, bool NoAdvance = false)
513 if (!NoAdvance) AdvancePastEmptyBuckets();
516 // If IsConst is true this is a converting constructor from iterator to
517 // const_iterator and the default copy constructor is used.
518 // Otherwise this is a copy constructor for iterator.
519 DenseMapIterator(const DenseMapIterator<KeyT, ValueT,
521 : Ptr(I.Ptr), End(I.End) {}
523 reference operator*() const {
526 pointer operator->() const {
530 bool operator==(const ConstIterator &RHS) const {
531 return Ptr == RHS.operator->();
533 bool operator!=(const ConstIterator &RHS) const {
534 return Ptr != RHS.operator->();
537 inline DenseMapIterator& operator++() { // Preincrement
539 AdvancePastEmptyBuckets();
542 DenseMapIterator operator++(int) { // Postincrement
543 DenseMapIterator tmp = *this; ++*this; return tmp;
547 void AdvancePastEmptyBuckets() {
548 const KeyT Empty = KeyInfoT::getEmptyKey();
549 const KeyT Tombstone = KeyInfoT::getTombstoneKey();
552 (KeyInfoT::isEqual(Ptr->first, Empty) ||
553 KeyInfoT::isEqual(Ptr->first, Tombstone)))
558 template<typename KeyT, typename ValueT, typename KeyInfoT>
560 capacity_in_bytes(const DenseMap<KeyT, ValueT, KeyInfoT> &X) {
561 return X.getMemorySize();
564 } // end namespace llvm