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/MathExtras.h"
18 #include "llvm/Support/PointerLikeTypeTraits.h"
19 #include "llvm/Support/type_traits.h"
20 #include "llvm/ADT/DenseMapInfo.h"
31 template<typename KeyT, typename ValueT,
32 typename KeyInfoT = DenseMapInfo<KeyT>,
33 typename ValueInfoT = DenseMapInfo<ValueT>, bool IsConst = false>
34 class DenseMapIterator;
36 template<typename KeyT, typename ValueT,
37 typename KeyInfoT = DenseMapInfo<KeyT>,
38 typename ValueInfoT = DenseMapInfo<ValueT> >
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)));
67 const KeyT EmptyKey = getEmptyKey(), TombstoneKey = getTombstoneKey();
68 for (BucketT *P = Buckets, *E = Buckets+NumBuckets; P != E; ++P) {
69 if (!KeyInfoT::isEqual(P->first, EmptyKey) &&
70 !KeyInfoT::isEqual(P->first, TombstoneKey))
76 memset((void*)Buckets, 0x5a, sizeof(BucketT)*NumBuckets);
78 operator delete(Buckets);
81 typedef DenseMapIterator<KeyT, ValueT, KeyInfoT> iterator;
82 typedef DenseMapIterator<KeyT, ValueT,
83 KeyInfoT, ValueInfoT, true> const_iterator;
84 inline iterator begin() {
85 // When the map is empty, avoid the overhead of AdvancePastEmptyBuckets().
86 return empty() ? end() : iterator(Buckets, Buckets+NumBuckets);
88 inline iterator end() {
89 return iterator(Buckets+NumBuckets, Buckets+NumBuckets);
91 inline const_iterator begin() const {
92 return empty() ? end() : const_iterator(Buckets, Buckets+NumBuckets);
94 inline const_iterator end() const {
95 return const_iterator(Buckets+NumBuckets, Buckets+NumBuckets);
98 bool empty() const { return NumEntries == 0; }
99 unsigned size() const { return NumEntries; }
101 /// Grow the densemap so that it has at least Size buckets. Does not shrink
102 void resize(size_t Size) {
103 if (Size > NumBuckets)
108 if (NumEntries == 0 && NumTombstones == 0) return;
110 // If the capacity of the array is huge, and the # elements used is small,
112 if (NumEntries * 4 < NumBuckets && NumBuckets > 64) {
117 const KeyT EmptyKey = getEmptyKey(), TombstoneKey = getTombstoneKey();
118 for (BucketT *P = Buckets, *E = Buckets+NumBuckets; P != E; ++P) {
119 if (!KeyInfoT::isEqual(P->first, EmptyKey)) {
120 if (!KeyInfoT::isEqual(P->first, TombstoneKey)) {
127 assert(NumEntries == 0 && "Node count imbalance!");
131 /// count - Return true if the specified key is in the map.
132 bool count(const KeyT &Val) const {
134 return LookupBucketFor(Val, TheBucket);
137 iterator find(const KeyT &Val) {
139 if (LookupBucketFor(Val, TheBucket))
140 return iterator(TheBucket, Buckets+NumBuckets);
143 const_iterator find(const KeyT &Val) const {
145 if (LookupBucketFor(Val, TheBucket))
146 return const_iterator(TheBucket, Buckets+NumBuckets);
150 /// lookup - Return the entry for the specified key, or a default
151 /// constructed value if no such entry exists.
152 ValueT lookup(const KeyT &Val) const {
154 if (LookupBucketFor(Val, TheBucket))
155 return TheBucket->second;
159 // Inserts key,value pair into the map if the key isn't already in the map.
160 // If the key is already in the map, it returns false and doesn't update the
162 std::pair<iterator, bool> insert(const std::pair<KeyT, ValueT> &KV) {
164 if (LookupBucketFor(KV.first, TheBucket))
165 return std::make_pair(iterator(TheBucket, Buckets+NumBuckets),
166 false); // Already in map.
168 // Otherwise, insert the new element.
169 TheBucket = InsertIntoBucket(KV.first, KV.second, TheBucket);
170 return std::make_pair(iterator(TheBucket, Buckets+NumBuckets),
174 /// insert - Range insertion of pairs.
175 template<typename InputIt>
176 void insert(InputIt I, InputIt E) {
182 bool erase(const KeyT &Val) {
184 if (!LookupBucketFor(Val, TheBucket))
185 return false; // not in map.
187 TheBucket->second.~ValueT();
188 TheBucket->first = getTombstoneKey();
193 void erase(iterator I) {
194 BucketT *TheBucket = &*I;
195 TheBucket->second.~ValueT();
196 TheBucket->first = getTombstoneKey();
201 void swap(DenseMap& RHS) {
202 std::swap(NumBuckets, RHS.NumBuckets);
203 std::swap(Buckets, RHS.Buckets);
204 std::swap(NumEntries, RHS.NumEntries);
205 std::swap(NumTombstones, RHS.NumTombstones);
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 DenseMap& operator=(const DenseMap& other) {
225 /// isPointerIntoBucketsArray - Return true if the specified pointer points
226 /// somewhere into the DenseMap's array of buckets (i.e. either to a key or
227 /// value in the DenseMap).
228 bool isPointerIntoBucketsArray(const void *Ptr) const {
229 return Ptr >= Buckets && Ptr < Buckets+NumBuckets;
232 /// getPointerIntoBucketsArray() - Return an opaque pointer into the buckets
233 /// array. In conjunction with the previous method, this can be used to
234 /// determine whether an insertion caused the DenseMap to reallocate.
235 const void *getPointerIntoBucketsArray() const { return Buckets; }
238 void CopyFrom(const DenseMap& other) {
239 if (NumBuckets != 0 &&
240 (!isPodLike<KeyInfoT>::value || !isPodLike<ValueInfoT>::value)) {
241 const KeyT EmptyKey = getEmptyKey(), TombstoneKey = getTombstoneKey();
242 for (BucketT *P = Buckets, *E = Buckets+NumBuckets; P != E; ++P) {
243 if (!KeyInfoT::isEqual(P->first, EmptyKey) &&
244 !KeyInfoT::isEqual(P->first, TombstoneKey))
250 NumEntries = other.NumEntries;
251 NumTombstones = other.NumTombstones;
255 memset((void*)Buckets, 0x5a, sizeof(BucketT)*NumBuckets);
257 operator delete(Buckets);
260 NumBuckets = other.NumBuckets;
262 if (NumBuckets == 0) {
267 Buckets = static_cast<BucketT*>(operator new(sizeof(BucketT) * NumBuckets));
269 if (isPodLike<KeyInfoT>::value && isPodLike<ValueInfoT>::value)
270 memcpy(Buckets, other.Buckets, NumBuckets * sizeof(BucketT));
272 for (size_t i = 0; i < NumBuckets; ++i) {
273 new (&Buckets[i].first) KeyT(other.Buckets[i].first);
274 if (!KeyInfoT::isEqual(Buckets[i].first, getEmptyKey()) &&
275 !KeyInfoT::isEqual(Buckets[i].first, getTombstoneKey()))
276 new (&Buckets[i].second) ValueT(other.Buckets[i].second);
280 BucketT *InsertIntoBucket(const KeyT &Key, const ValueT &Value,
281 BucketT *TheBucket) {
282 // If the load of the hash table is more than 3/4, or if fewer than 1/8 of
283 // the buckets are empty (meaning that many are filled with tombstones),
286 // The later case is tricky. For example, if we had one empty bucket with
287 // tons of tombstones, failing lookups (e.g. for insertion) would have to
288 // probe almost the entire table until it found the empty bucket. If the
289 // table completely filled with tombstones, no lookup would ever succeed,
290 // causing infinite loops in lookup.
292 if (NumEntries*4 >= NumBuckets*3) {
293 this->grow(NumBuckets * 2);
294 LookupBucketFor(Key, TheBucket);
296 if (NumBuckets-(NumEntries+NumTombstones) < NumBuckets/8) {
297 this->grow(NumBuckets);
298 LookupBucketFor(Key, TheBucket);
301 // If we are writing over a tombstone, remember this.
302 if (!KeyInfoT::isEqual(TheBucket->first, getEmptyKey()))
305 TheBucket->first = Key;
306 new (&TheBucket->second) ValueT(Value);
310 static unsigned getHashValue(const KeyT &Val) {
311 return KeyInfoT::getHashValue(Val);
313 static const KeyT getEmptyKey() {
314 return KeyInfoT::getEmptyKey();
316 static const KeyT getTombstoneKey() {
317 return KeyInfoT::getTombstoneKey();
320 /// LookupBucketFor - Lookup the appropriate bucket for Val, returning it in
321 /// FoundBucket. If the bucket contains the key and a value, this returns
322 /// true, otherwise it returns a bucket with an empty marker or tombstone and
324 bool LookupBucketFor(const KeyT &Val, BucketT *&FoundBucket) const {
325 unsigned BucketNo = getHashValue(Val);
326 unsigned ProbeAmt = 1;
327 BucketT *BucketsPtr = Buckets;
329 if (NumBuckets == 0) {
334 // FoundTombstone - Keep track of whether we find a tombstone while probing.
335 BucketT *FoundTombstone = 0;
336 const KeyT EmptyKey = getEmptyKey();
337 const KeyT TombstoneKey = getTombstoneKey();
338 assert(!KeyInfoT::isEqual(Val, EmptyKey) &&
339 !KeyInfoT::isEqual(Val, TombstoneKey) &&
340 "Empty/Tombstone value shouldn't be inserted into map!");
343 BucketT *ThisBucket = BucketsPtr + (BucketNo & (NumBuckets-1));
344 // Found Val's bucket? If so, return it.
345 if (KeyInfoT::isEqual(ThisBucket->first, Val)) {
346 FoundBucket = ThisBucket;
350 // If we found an empty bucket, the key doesn't exist in the set.
351 // Insert it and return the default value.
352 if (KeyInfoT::isEqual(ThisBucket->first, EmptyKey)) {
353 // If we've already seen a tombstone while probing, fill it in instead
354 // of the empty bucket we eventually probed to.
355 if (FoundTombstone) ThisBucket = FoundTombstone;
356 FoundBucket = FoundTombstone ? FoundTombstone : ThisBucket;
360 // If this is a tombstone, remember it. If Val ends up not in the map, we
361 // prefer to return it than something that would require more probing.
362 if (KeyInfoT::isEqual(ThisBucket->first, TombstoneKey) && !FoundTombstone)
363 FoundTombstone = ThisBucket; // Remember the first tombstone found.
365 // Otherwise, it's a hash collision or a tombstone, continue quadratic
367 BucketNo += ProbeAmt++;
371 void init(unsigned InitBuckets) {
374 NumBuckets = InitBuckets;
376 if (InitBuckets == 0) {
381 assert(InitBuckets && (InitBuckets & (InitBuckets-1)) == 0 &&
382 "# initial buckets must be a power of two!");
383 Buckets = static_cast<BucketT*>(operator new(sizeof(BucketT)*InitBuckets));
384 // Initialize all the keys to EmptyKey.
385 const KeyT EmptyKey = getEmptyKey();
386 for (unsigned i = 0; i != InitBuckets; ++i)
387 new (&Buckets[i].first) KeyT(EmptyKey);
390 void grow(unsigned AtLeast) {
391 unsigned OldNumBuckets = NumBuckets;
392 BucketT *OldBuckets = Buckets;
397 // Double the number of buckets.
398 while (NumBuckets < AtLeast)
401 Buckets = static_cast<BucketT*>(operator new(sizeof(BucketT)*NumBuckets));
403 // Initialize all the keys to EmptyKey.
404 const KeyT EmptyKey = getEmptyKey();
405 for (unsigned i = 0, e = NumBuckets; i != e; ++i)
406 new (&Buckets[i].first) KeyT(EmptyKey);
408 // Insert all the old elements.
409 const KeyT TombstoneKey = getTombstoneKey();
410 for (BucketT *B = OldBuckets, *E = OldBuckets+OldNumBuckets; B != E; ++B) {
411 if (!KeyInfoT::isEqual(B->first, EmptyKey) &&
412 !KeyInfoT::isEqual(B->first, TombstoneKey)) {
413 // Insert the key/value into the new table.
415 bool FoundVal = LookupBucketFor(B->first, DestBucket);
416 (void)FoundVal; // silence warning.
417 assert(!FoundVal && "Key already in new map?");
418 DestBucket->first = B->first;
419 new (&DestBucket->second) ValueT(B->second);
429 memset((void*)OldBuckets, 0x5a, sizeof(BucketT)*OldNumBuckets);
431 // Free the old table.
432 operator delete(OldBuckets);
435 void shrink_and_clear() {
436 unsigned OldNumBuckets = NumBuckets;
437 BucketT *OldBuckets = Buckets;
439 // Reduce the number of buckets.
440 NumBuckets = NumEntries > 32 ? 1 << (Log2_32_Ceil(NumEntries) + 1)
443 Buckets = static_cast<BucketT*>(operator new(sizeof(BucketT)*NumBuckets));
445 // Initialize all the keys to EmptyKey.
446 const KeyT EmptyKey = getEmptyKey();
447 for (unsigned i = 0, e = NumBuckets; i != e; ++i)
448 new (&Buckets[i].first) KeyT(EmptyKey);
450 // Free the old buckets.
451 const KeyT TombstoneKey = getTombstoneKey();
452 for (BucketT *B = OldBuckets, *E = OldBuckets+OldNumBuckets; B != E; ++B) {
453 if (!KeyInfoT::isEqual(B->first, EmptyKey) &&
454 !KeyInfoT::isEqual(B->first, TombstoneKey)) {
462 memset((void*)OldBuckets, 0x5a, sizeof(BucketT)*OldNumBuckets);
464 // Free the old table.
465 operator delete(OldBuckets);
471 /// Return the approximate size (in bytes) of the actual map.
472 /// This is just the raw memory used by DenseMap.
473 /// If entries are pointers to objects, the size of the referenced objects
474 /// are not included.
475 size_t getMemorySize() const {
476 return NumBuckets * sizeof(BucketT);
480 template<typename KeyT, typename ValueT,
481 typename KeyInfoT, typename ValueInfoT, bool IsConst>
482 class DenseMapIterator {
483 typedef std::pair<KeyT, ValueT> Bucket;
484 typedef DenseMapIterator<KeyT, ValueT,
485 KeyInfoT, ValueInfoT, true> ConstIterator;
486 friend class DenseMapIterator<KeyT, ValueT, KeyInfoT, ValueInfoT, true>;
488 typedef ptrdiff_t difference_type;
489 typedef typename conditional<IsConst, const Bucket, Bucket>::type value_type;
490 typedef value_type *pointer;
491 typedef value_type &reference;
492 typedef std::forward_iterator_tag iterator_category;
496 DenseMapIterator() : Ptr(0), End(0) {}
498 DenseMapIterator(pointer Pos, pointer E) : Ptr(Pos), End(E) {
499 AdvancePastEmptyBuckets();
502 // If IsConst is true this is a converting constructor from iterator to
503 // const_iterator and the default copy constructor is used.
504 // Otherwise this is a copy constructor for iterator.
505 DenseMapIterator(const DenseMapIterator<KeyT, ValueT,
506 KeyInfoT, ValueInfoT, false>& I)
507 : Ptr(I.Ptr), End(I.End) {}
509 reference operator*() const {
512 pointer operator->() const {
516 bool operator==(const ConstIterator &RHS) const {
517 return Ptr == RHS.operator->();
519 bool operator!=(const ConstIterator &RHS) const {
520 return Ptr != RHS.operator->();
523 inline DenseMapIterator& operator++() { // Preincrement
525 AdvancePastEmptyBuckets();
528 DenseMapIterator operator++(int) { // Postincrement
529 DenseMapIterator tmp = *this; ++*this; return tmp;
533 void AdvancePastEmptyBuckets() {
534 const KeyT Empty = KeyInfoT::getEmptyKey();
535 const KeyT Tombstone = KeyInfoT::getTombstoneKey();
538 (KeyInfoT::isEqual(Ptr->first, Empty) ||
539 KeyInfoT::isEqual(Ptr->first, Tombstone)))
544 template<typename KeyT, typename ValueT, typename KeyInfoT, typename ValueInfoT>
546 capacity_in_bytes(const DenseMap<KeyT, ValueT, KeyInfoT, ValueInfoT> &X) {
547 return X.getMemorySize();
550 } // end namespace llvm