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/DataTypes.h"
18 #include "llvm/Support/MathExtras.h"
26 //static inline T getEmptyKey();
27 //static inline T getTombstoneKey();
28 //static unsigned getHashValue(const T &Val);
29 //static bool isEqual(const T &LHS, const T &RHS);
33 // Provide DenseMapInfo for all pointers.
35 struct DenseMapInfo<T*> {
36 static inline T* getEmptyKey() { return reinterpret_cast<T*>(-1); }
37 static inline T* getTombstoneKey() { return reinterpret_cast<T*>(-2); }
38 static unsigned getHashValue(const T *PtrVal) {
39 return (unsigned((uintptr_t)PtrVal) >> 4) ^
40 (unsigned((uintptr_t)PtrVal) >> 9);
42 static bool isEqual(const T *LHS, const T *RHS) { return LHS == RHS; }
43 static bool isPod() { return true; }
46 // Provide DenseMapInfo for unsigned ints.
47 template<> struct DenseMapInfo<uint32_t> {
48 static inline uint32_t getEmptyKey() { return ~0; }
49 static inline uint32_t getTombstoneKey() { return ~0 - 1; }
50 static unsigned getHashValue(const uint32_t& Val) { return Val * 37; }
51 static bool isPod() { return true; }
52 static bool isEqual(const uint32_t& LHS, const uint32_t& RHS) {
57 // Provide DenseMapInfo for all pairs whose members have info.
58 template<typename T, typename U>
59 struct DenseMapInfo<std::pair<T, U> > {
60 typedef std::pair<T, U> Pair;
61 typedef DenseMapInfo<T> FirstInfo;
62 typedef DenseMapInfo<U> SecondInfo;
64 static inline Pair getEmptyKey() {
65 return std::make_pair(FirstInfo::getEmptyKey(),
66 SecondInfo::getEmptyKey());
68 static inline Pair getTombstoneKey() {
69 return std::make_pair(FirstInfo::getTombstoneKey(),
70 SecondInfo::getEmptyKey()); }
71 static unsigned getHashValue(const Pair& PairVal) {
72 uint64_t key = (uint64_t)FirstInfo::getHashValue(PairVal.first) << 32
73 | (uint64_t)SecondInfo::getHashValue(PairVal.second);
84 static bool isEqual(const Pair& LHS, const Pair& RHS) { return LHS == RHS; }
85 static bool isPod() { return false; }
88 template<typename KeyT, typename ValueT,
89 typename KeyInfoT = DenseMapInfo<KeyT>,
90 typename ValueInfoT = DenseMapInfo<ValueT> >
91 class DenseMapIterator;
92 template<typename KeyT, typename ValueT,
93 typename KeyInfoT = DenseMapInfo<KeyT>,
94 typename ValueInfoT = DenseMapInfo<ValueT> >
95 class DenseMapConstIterator;
97 template<typename KeyT, typename ValueT,
98 typename KeyInfoT = DenseMapInfo<KeyT>,
99 typename ValueInfoT = DenseMapInfo<ValueT> >
101 typedef std::pair<KeyT, ValueT> BucketT;
106 unsigned NumTombstones;
108 typedef BucketT value_type;
110 DenseMap(const DenseMap& other) {
115 explicit DenseMap(unsigned NumInitBuckets = 64) {
116 init(NumInitBuckets);
120 const KeyT EmptyKey = getEmptyKey(), TombstoneKey = getTombstoneKey();
121 for (BucketT *P = Buckets, *E = Buckets+NumBuckets; P != E; ++P) {
122 if (!KeyInfoT::isEqual(P->first, EmptyKey) &&
123 !KeyInfoT::isEqual(P->first, TombstoneKey))
127 operator delete(Buckets);
130 typedef DenseMapIterator<KeyT, ValueT, KeyInfoT> iterator;
131 typedef DenseMapConstIterator<KeyT, ValueT, KeyInfoT> const_iterator;
132 inline iterator begin() {
133 return iterator(Buckets, Buckets+NumBuckets);
135 inline iterator end() {
136 return iterator(Buckets+NumBuckets, Buckets+NumBuckets);
138 inline const_iterator begin() const {
139 return const_iterator(Buckets, Buckets+NumBuckets);
141 inline const_iterator end() const {
142 return const_iterator(Buckets+NumBuckets, Buckets+NumBuckets);
145 bool empty() const { return NumEntries == 0; }
146 unsigned size() const { return NumEntries; }
148 /// Grow the densemap so that it has at least Size buckets. Does not shrink
149 void resize(size_t Size) { grow(Size); }
152 // If the capacity of the array is huge, and the # elements used is small,
154 if (NumEntries * 4 < NumBuckets && NumBuckets > 64) {
159 const KeyT EmptyKey = getEmptyKey(), TombstoneKey = getTombstoneKey();
160 for (BucketT *P = Buckets, *E = Buckets+NumBuckets; P != E; ++P) {
161 if (!KeyInfoT::isEqual(P->first, EmptyKey)) {
162 if (!KeyInfoT::isEqual(P->first, TombstoneKey)) {
169 assert(NumEntries == 0 && "Node count imbalance!");
173 /// count - Return true if the specified key is in the map.
174 bool count(const KeyT &Val) const {
176 return LookupBucketFor(Val, TheBucket);
179 iterator find(const KeyT &Val) {
181 if (LookupBucketFor(Val, TheBucket))
182 return iterator(TheBucket, Buckets+NumBuckets);
185 const_iterator find(const KeyT &Val) const {
187 if (LookupBucketFor(Val, TheBucket))
188 return const_iterator(TheBucket, Buckets+NumBuckets);
192 std::pair<iterator, bool> insert(const std::pair<KeyT, ValueT> &KV) {
194 if (LookupBucketFor(KV.first, TheBucket))
195 return std::make_pair(iterator(TheBucket, Buckets+NumBuckets),
196 false); // Already in map.
198 // Otherwise, insert the new element.
199 TheBucket = InsertIntoBucket(KV.first, KV.second, TheBucket);
200 return std::make_pair(iterator(TheBucket, Buckets+NumBuckets),
204 bool erase(const KeyT &Val) {
206 if (!LookupBucketFor(Val, TheBucket))
207 return false; // not in map.
209 TheBucket->second.~ValueT();
210 TheBucket->first = getTombstoneKey();
215 bool erase(iterator I) {
216 BucketT *TheBucket = &*I;
217 TheBucket->second.~ValueT();
218 TheBucket->first = getTombstoneKey();
224 value_type& FindAndConstruct(const KeyT &Key) {
226 if (LookupBucketFor(Key, TheBucket))
229 return *InsertIntoBucket(Key, ValueT(), TheBucket);
232 ValueT &operator[](const KeyT &Key) {
233 return FindAndConstruct(Key).second;
236 DenseMap& operator=(const DenseMap& other) {
242 void CopyFrom(const DenseMap& other) {
243 if (NumBuckets != 0 && (!KeyInfoT::isPod() || !ValueInfoT::isPod())) {
244 const KeyT EmptyKey = getEmptyKey(), TombstoneKey = getTombstoneKey();
245 for (BucketT *P = Buckets, *E = Buckets+NumBuckets; P != E; ++P) {
246 if (!KeyInfoT::isEqual(P->first, EmptyKey) &&
247 !KeyInfoT::isEqual(P->first, TombstoneKey))
253 NumEntries = other.NumEntries;
254 NumTombstones = other.NumTombstones;
257 operator delete(Buckets);
258 Buckets = static_cast<BucketT*>(operator new(sizeof(BucketT) *
261 if (KeyInfoT::isPod() && ValueInfoT::isPod())
262 memcpy(Buckets, other.Buckets, other.NumBuckets * sizeof(BucketT));
264 for (size_t i = 0; i < other.NumBuckets; ++i) {
265 new (&Buckets[i].first) KeyT(other.Buckets[i].first);
266 if (!KeyInfoT::isEqual(Buckets[i].first, getEmptyKey()) &&
267 !KeyInfoT::isEqual(Buckets[i].first, getTombstoneKey()))
268 new (&Buckets[i].second) ValueT(other.Buckets[i].second);
270 NumBuckets = other.NumBuckets;
273 BucketT *InsertIntoBucket(const KeyT &Key, const ValueT &Value,
274 BucketT *TheBucket) {
275 // If the load of the hash table is more than 3/4, or if fewer than 1/8 of
276 // the buckets are empty (meaning that many are filled with tombstones),
279 // The later case is tricky. For example, if we had one empty bucket with
280 // tons of tombstones, failing lookups (e.g. for insertion) would have to
281 // probe almost the entire table until it found the empty bucket. If the
282 // table completely filled with tombstones, no lookup would ever succeed,
283 // causing infinite loops in lookup.
284 if (NumEntries*4 >= NumBuckets*3 ||
285 NumBuckets-(NumEntries+NumTombstones) < NumBuckets/8) {
286 this->grow(NumBuckets * 2);
287 LookupBucketFor(Key, TheBucket);
291 // If we are writing over a tombstone, remember this.
292 if (!KeyInfoT::isEqual(TheBucket->first, getEmptyKey()))
295 TheBucket->first = Key;
296 new (&TheBucket->second) ValueT(Value);
300 static unsigned getHashValue(const KeyT &Val) {
301 return KeyInfoT::getHashValue(Val);
303 static const KeyT getEmptyKey() {
304 return KeyInfoT::getEmptyKey();
306 static const KeyT getTombstoneKey() {
307 return KeyInfoT::getTombstoneKey();
310 /// LookupBucketFor - Lookup the appropriate bucket for Val, returning it in
311 /// FoundBucket. If the bucket contains the key and a value, this returns
312 /// true, otherwise it returns a bucket with an empty marker or tombstone and
314 bool LookupBucketFor(const KeyT &Val, BucketT *&FoundBucket) const {
315 unsigned BucketNo = getHashValue(Val);
316 unsigned ProbeAmt = 1;
317 BucketT *BucketsPtr = Buckets;
319 // FoundTombstone - Keep track of whether we find a tombstone while probing.
320 BucketT *FoundTombstone = 0;
321 const KeyT EmptyKey = getEmptyKey();
322 const KeyT TombstoneKey = getTombstoneKey();
323 assert(!KeyInfoT::isEqual(Val, EmptyKey) &&
324 !KeyInfoT::isEqual(Val, TombstoneKey) &&
325 "Empty/Tombstone value shouldn't be inserted into map!");
328 BucketT *ThisBucket = BucketsPtr + (BucketNo & (NumBuckets-1));
329 // Found Val's bucket? If so, return it.
330 if (KeyInfoT::isEqual(ThisBucket->first, Val)) {
331 FoundBucket = ThisBucket;
335 // If we found an empty bucket, the key doesn't exist in the set.
336 // Insert it and return the default value.
337 if (KeyInfoT::isEqual(ThisBucket->first, EmptyKey)) {
338 // If we've already seen a tombstone while probing, fill it in instead
339 // of the empty bucket we eventually probed to.
340 if (FoundTombstone) ThisBucket = FoundTombstone;
341 FoundBucket = FoundTombstone ? FoundTombstone : ThisBucket;
345 // If this is a tombstone, remember it. If Val ends up not in the map, we
346 // prefer to return it than something that would require more probing.
347 if (KeyInfoT::isEqual(ThisBucket->first, TombstoneKey) && !FoundTombstone)
348 FoundTombstone = ThisBucket; // Remember the first tombstone found.
350 // Otherwise, it's a hash collision or a tombstone, continue quadratic
352 BucketNo += ProbeAmt++;
356 void init(unsigned InitBuckets) {
359 NumBuckets = InitBuckets;
360 assert(InitBuckets && (InitBuckets & (InitBuckets-1)) == 0 &&
361 "# initial buckets must be a power of two!");
362 Buckets = static_cast<BucketT*>(operator new(sizeof(BucketT)*InitBuckets));
363 // Initialize all the keys to EmptyKey.
364 const KeyT EmptyKey = getEmptyKey();
365 for (unsigned i = 0; i != InitBuckets; ++i)
366 new (&Buckets[i].first) KeyT(EmptyKey);
369 void grow(unsigned AtLeast) {
370 unsigned OldNumBuckets = NumBuckets;
371 BucketT *OldBuckets = Buckets;
373 // Double the number of buckets.
374 while (NumBuckets <= AtLeast)
377 Buckets = static_cast<BucketT*>(operator new(sizeof(BucketT)*NumBuckets));
379 // Initialize all the keys to EmptyKey.
380 const KeyT EmptyKey = getEmptyKey();
381 for (unsigned i = 0, e = NumBuckets; i != e; ++i)
382 new (&Buckets[i].first) KeyT(EmptyKey);
384 // Insert all the old elements.
385 const KeyT TombstoneKey = getTombstoneKey();
386 for (BucketT *B = OldBuckets, *E = OldBuckets+OldNumBuckets; B != E; ++B) {
387 if (!KeyInfoT::isEqual(B->first, EmptyKey) &&
388 !KeyInfoT::isEqual(B->first, TombstoneKey)) {
389 // Insert the key/value into the new table.
391 bool FoundVal = LookupBucketFor(B->first, DestBucket);
392 FoundVal = FoundVal; // silence warning.
393 assert(!FoundVal && "Key already in new map?");
394 DestBucket->first = B->first;
395 new (&DestBucket->second) ValueT(B->second);
403 // Free the old table.
404 operator delete(OldBuckets);
407 void shrink_and_clear() {
408 unsigned OldNumBuckets = NumBuckets;
409 BucketT *OldBuckets = Buckets;
411 // Reduce the number of buckets.
412 NumBuckets = NumEntries > 32 ? 1 << (Log2_32_Ceil(NumEntries) + 1)
415 Buckets = static_cast<BucketT*>(operator new(sizeof(BucketT)*NumBuckets));
417 // Initialize all the keys to EmptyKey.
418 const KeyT EmptyKey = getEmptyKey();
419 for (unsigned i = 0, e = NumBuckets; i != e; ++i)
420 new (&Buckets[i].first) KeyT(EmptyKey);
422 // Free the old buckets.
423 const KeyT TombstoneKey = getTombstoneKey();
424 for (BucketT *B = OldBuckets, *E = OldBuckets+OldNumBuckets; B != E; ++B) {
425 if (!KeyInfoT::isEqual(B->first, EmptyKey) &&
426 !KeyInfoT::isEqual(B->first, TombstoneKey)) {
433 // Free the old table.
434 operator delete(OldBuckets);
440 template<typename KeyT, typename ValueT, typename KeyInfoT, typename ValueInfoT>
441 class DenseMapIterator {
442 typedef std::pair<KeyT, ValueT> BucketT;
444 const BucketT *Ptr, *End;
446 DenseMapIterator(const BucketT *Pos, const BucketT *E) : Ptr(Pos), End(E) {
447 AdvancePastEmptyBuckets();
450 std::pair<KeyT, ValueT> &operator*() const {
451 return *const_cast<BucketT*>(Ptr);
453 std::pair<KeyT, ValueT> *operator->() const {
454 return const_cast<BucketT*>(Ptr);
457 bool operator==(const DenseMapIterator &RHS) const {
458 return Ptr == RHS.Ptr;
460 bool operator!=(const DenseMapIterator &RHS) const {
461 return Ptr != RHS.Ptr;
464 inline DenseMapIterator& operator++() { // Preincrement
466 AdvancePastEmptyBuckets();
469 DenseMapIterator operator++(int) { // Postincrement
470 DenseMapIterator tmp = *this; ++*this; return tmp;
474 void AdvancePastEmptyBuckets() {
475 const KeyT Empty = KeyInfoT::getEmptyKey();
476 const KeyT Tombstone = KeyInfoT::getTombstoneKey();
479 (KeyInfoT::isEqual(Ptr->first, Empty) ||
480 KeyInfoT::isEqual(Ptr->first, Tombstone)))
485 template<typename KeyT, typename ValueT, typename KeyInfoT, typename ValueInfoT>
486 class DenseMapConstIterator : public DenseMapIterator<KeyT, ValueT, KeyInfoT> {
488 DenseMapConstIterator(const std::pair<KeyT, ValueT> *Pos,
489 const std::pair<KeyT, ValueT> *E)
490 : DenseMapIterator<KeyT, ValueT, KeyInfoT>(Pos, E) {
492 const std::pair<KeyT, ValueT> &operator*() const {
495 const std::pair<KeyT, ValueT> *operator->() const {
500 } // end namespace llvm