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"
29 template<typename KeyT, typename ValueT,
30 typename KeyInfoT = DenseMapInfo<KeyT>,
31 typename ValueInfoT = DenseMapInfo<ValueT>, bool IsConst = false>
32 class DenseMapIterator;
34 template<typename KeyT, typename ValueT,
35 typename KeyInfoT = DenseMapInfo<KeyT>,
36 typename ValueInfoT = DenseMapInfo<ValueT> >
38 typedef std::pair<KeyT, ValueT> BucketT;
43 unsigned NumTombstones;
45 typedef KeyT key_type;
46 typedef ValueT mapped_type;
47 typedef BucketT value_type;
49 DenseMap(const DenseMap &other) {
54 explicit DenseMap(unsigned NumInitBuckets = 64) {
58 template<typename InputIt>
59 DenseMap(const InputIt &I, const InputIt &E) {
65 const KeyT EmptyKey = getEmptyKey(), TombstoneKey = getTombstoneKey();
66 for (BucketT *P = Buckets, *E = Buckets+NumBuckets; P != E; ++P) {
67 if (!KeyInfoT::isEqual(P->first, EmptyKey) &&
68 !KeyInfoT::isEqual(P->first, TombstoneKey))
73 memset(Buckets, 0x5a, sizeof(BucketT)*NumBuckets);
75 operator delete(Buckets);
78 typedef DenseMapIterator<KeyT, ValueT, KeyInfoT> iterator;
79 typedef DenseMapIterator<KeyT, ValueT,
80 KeyInfoT, ValueInfoT, true> const_iterator;
81 inline iterator begin() {
82 return iterator(Buckets, Buckets+NumBuckets);
84 inline iterator end() {
85 return iterator(Buckets+NumBuckets, Buckets+NumBuckets);
87 inline const_iterator begin() const {
88 return const_iterator(Buckets, Buckets+NumBuckets);
90 inline const_iterator end() const {
91 return const_iterator(Buckets+NumBuckets, Buckets+NumBuckets);
94 bool empty() const { return NumEntries == 0; }
95 unsigned size() const { return NumEntries; }
97 /// Grow the densemap so that it has at least Size buckets. Does not shrink
98 void resize(size_t Size) { grow(Size); }
101 if (NumEntries == 0 && NumTombstones == 0) return;
103 // If the capacity of the array is huge, and the # elements used is small,
105 if (NumEntries * 4 < NumBuckets && NumBuckets > 64) {
110 const KeyT EmptyKey = getEmptyKey(), TombstoneKey = getTombstoneKey();
111 for (BucketT *P = Buckets, *E = Buckets+NumBuckets; P != E; ++P) {
112 if (!KeyInfoT::isEqual(P->first, EmptyKey)) {
113 if (!KeyInfoT::isEqual(P->first, TombstoneKey)) {
120 assert(NumEntries == 0 && "Node count imbalance!");
124 /// count - Return true if the specified key is in the map.
125 bool count(const KeyT &Val) const {
127 return LookupBucketFor(Val, TheBucket);
130 iterator find(const KeyT &Val) {
132 if (LookupBucketFor(Val, TheBucket))
133 return iterator(TheBucket, Buckets+NumBuckets);
136 const_iterator find(const KeyT &Val) const {
138 if (LookupBucketFor(Val, TheBucket))
139 return const_iterator(TheBucket, Buckets+NumBuckets);
143 /// lookup - Return the entry for the specified key, or a default
144 /// constructed value if no such entry exists.
145 ValueT lookup(const KeyT &Val) const {
147 if (LookupBucketFor(Val, TheBucket))
148 return TheBucket->second;
152 // Inserts key,value pair into the map if the key isn't already in the map.
153 // If the key is already in the map, it returns false and doesn't update the
155 std::pair<iterator, bool> insert(const std::pair<KeyT, ValueT> &KV) {
157 if (LookupBucketFor(KV.first, TheBucket))
158 return std::make_pair(iterator(TheBucket, Buckets+NumBuckets),
159 false); // Already in map.
161 // Otherwise, insert the new element.
162 TheBucket = InsertIntoBucket(KV.first, KV.second, TheBucket);
163 return std::make_pair(iterator(TheBucket, Buckets+NumBuckets),
167 /// insert - Range insertion of pairs.
168 template<typename InputIt>
169 void insert(InputIt I, InputIt E) {
175 bool erase(const KeyT &Val) {
177 if (!LookupBucketFor(Val, TheBucket))
178 return false; // not in map.
180 TheBucket->second.~ValueT();
181 TheBucket->first = getTombstoneKey();
186 bool erase(iterator I) {
187 BucketT *TheBucket = &*I;
188 TheBucket->second.~ValueT();
189 TheBucket->first = getTombstoneKey();
195 value_type& FindAndConstruct(const KeyT &Key) {
197 if (LookupBucketFor(Key, TheBucket))
200 return *InsertIntoBucket(Key, ValueT(), TheBucket);
203 ValueT &operator[](const KeyT &Key) {
204 return FindAndConstruct(Key).second;
207 DenseMap& operator=(const DenseMap& other) {
212 /// isPointerIntoBucketsArray - Return true if the specified pointer points
213 /// somewhere into the DenseMap's array of buckets (i.e. either to a key or
214 /// value in the DenseMap).
215 bool isPointerIntoBucketsArray(const void *Ptr) const {
216 return Ptr >= Buckets && Ptr < Buckets+NumBuckets;
219 /// getPointerIntoBucketsArray() - Return an opaque pointer into the buckets
220 /// array. In conjunction with the previous method, this can be used to
221 /// determine whether an insertion caused the DenseMap to reallocate.
222 const void *getPointerIntoBucketsArray() const { return Buckets; }
225 void CopyFrom(const DenseMap& other) {
226 if (NumBuckets != 0 &&
227 (!isPodLike<KeyInfoT>::value || !isPodLike<ValueInfoT>::value)) {
228 const KeyT EmptyKey = getEmptyKey(), TombstoneKey = getTombstoneKey();
229 for (BucketT *P = Buckets, *E = Buckets+NumBuckets; P != E; ++P) {
230 if (!KeyInfoT::isEqual(P->first, EmptyKey) &&
231 !KeyInfoT::isEqual(P->first, TombstoneKey))
237 NumEntries = other.NumEntries;
238 NumTombstones = other.NumTombstones;
242 memset(Buckets, 0x5a, sizeof(BucketT)*NumBuckets);
244 operator delete(Buckets);
246 Buckets = static_cast<BucketT*>(operator new(sizeof(BucketT) *
249 if (isPodLike<KeyInfoT>::value && isPodLike<ValueInfoT>::value)
250 memcpy(Buckets, other.Buckets, other.NumBuckets * sizeof(BucketT));
252 for (size_t i = 0; i < other.NumBuckets; ++i) {
253 new (&Buckets[i].first) KeyT(other.Buckets[i].first);
254 if (!KeyInfoT::isEqual(Buckets[i].first, getEmptyKey()) &&
255 !KeyInfoT::isEqual(Buckets[i].first, getTombstoneKey()))
256 new (&Buckets[i].second) ValueT(other.Buckets[i].second);
258 NumBuckets = other.NumBuckets;
261 BucketT *InsertIntoBucket(const KeyT &Key, const ValueT &Value,
262 BucketT *TheBucket) {
263 // If the load of the hash table is more than 3/4, or if fewer than 1/8 of
264 // the buckets are empty (meaning that many are filled with tombstones),
267 // The later case is tricky. For example, if we had one empty bucket with
268 // tons of tombstones, failing lookups (e.g. for insertion) would have to
269 // probe almost the entire table until it found the empty bucket. If the
270 // table completely filled with tombstones, no lookup would ever succeed,
271 // causing infinite loops in lookup.
273 if (NumEntries*4 >= NumBuckets*3 ||
274 NumBuckets-(NumEntries+NumTombstones) < NumBuckets/8) {
275 this->grow(NumBuckets * 2);
276 LookupBucketFor(Key, TheBucket);
279 // If we are writing over a tombstone, remember this.
280 if (!KeyInfoT::isEqual(TheBucket->first, getEmptyKey()))
283 TheBucket->first = Key;
284 new (&TheBucket->second) ValueT(Value);
288 static unsigned getHashValue(const KeyT &Val) {
289 return KeyInfoT::getHashValue(Val);
291 static const KeyT getEmptyKey() {
292 return KeyInfoT::getEmptyKey();
294 static const KeyT getTombstoneKey() {
295 return KeyInfoT::getTombstoneKey();
298 /// LookupBucketFor - Lookup the appropriate bucket for Val, returning it in
299 /// FoundBucket. If the bucket contains the key and a value, this returns
300 /// true, otherwise it returns a bucket with an empty marker or tombstone and
302 bool LookupBucketFor(const KeyT &Val, BucketT *&FoundBucket) const {
303 unsigned BucketNo = getHashValue(Val);
304 unsigned ProbeAmt = 1;
305 BucketT *BucketsPtr = Buckets;
307 // FoundTombstone - Keep track of whether we find a tombstone while probing.
308 BucketT *FoundTombstone = 0;
309 const KeyT EmptyKey = getEmptyKey();
310 const KeyT TombstoneKey = getTombstoneKey();
311 assert(!KeyInfoT::isEqual(Val, EmptyKey) &&
312 !KeyInfoT::isEqual(Val, TombstoneKey) &&
313 "Empty/Tombstone value shouldn't be inserted into map!");
316 BucketT *ThisBucket = BucketsPtr + (BucketNo & (NumBuckets-1));
317 // Found Val's bucket? If so, return it.
318 if (KeyInfoT::isEqual(ThisBucket->first, Val)) {
319 FoundBucket = ThisBucket;
323 // If we found an empty bucket, the key doesn't exist in the set.
324 // Insert it and return the default value.
325 if (KeyInfoT::isEqual(ThisBucket->first, EmptyKey)) {
326 // If we've already seen a tombstone while probing, fill it in instead
327 // of the empty bucket we eventually probed to.
328 if (FoundTombstone) ThisBucket = FoundTombstone;
329 FoundBucket = FoundTombstone ? FoundTombstone : ThisBucket;
333 // If this is a tombstone, remember it. If Val ends up not in the map, we
334 // prefer to return it than something that would require more probing.
335 if (KeyInfoT::isEqual(ThisBucket->first, TombstoneKey) && !FoundTombstone)
336 FoundTombstone = ThisBucket; // Remember the first tombstone found.
338 // Otherwise, it's a hash collision or a tombstone, continue quadratic
340 BucketNo += ProbeAmt++;
344 void init(unsigned InitBuckets) {
347 NumBuckets = InitBuckets;
348 assert(InitBuckets && (InitBuckets & (InitBuckets-1)) == 0 &&
349 "# initial buckets must be a power of two!");
350 Buckets = static_cast<BucketT*>(operator new(sizeof(BucketT)*InitBuckets));
351 // Initialize all the keys to EmptyKey.
352 const KeyT EmptyKey = getEmptyKey();
353 for (unsigned i = 0; i != InitBuckets; ++i)
354 new (&Buckets[i].first) KeyT(EmptyKey);
357 void grow(unsigned AtLeast) {
358 unsigned OldNumBuckets = NumBuckets;
359 BucketT *OldBuckets = Buckets;
361 // Double the number of buckets.
362 while (NumBuckets <= AtLeast)
365 Buckets = static_cast<BucketT*>(operator new(sizeof(BucketT)*NumBuckets));
367 // Initialize all the keys to EmptyKey.
368 const KeyT EmptyKey = getEmptyKey();
369 for (unsigned i = 0, e = NumBuckets; i != e; ++i)
370 new (&Buckets[i].first) KeyT(EmptyKey);
372 // Insert all the old elements.
373 const KeyT TombstoneKey = getTombstoneKey();
374 for (BucketT *B = OldBuckets, *E = OldBuckets+OldNumBuckets; B != E; ++B) {
375 if (!KeyInfoT::isEqual(B->first, EmptyKey) &&
376 !KeyInfoT::isEqual(B->first, TombstoneKey)) {
377 // Insert the key/value into the new table.
379 bool FoundVal = LookupBucketFor(B->first, DestBucket);
380 FoundVal = FoundVal; // silence warning.
381 assert(!FoundVal && "Key already in new map?");
382 DestBucket->first = B->first;
383 new (&DestBucket->second) ValueT(B->second);
392 memset(OldBuckets, 0x5a, sizeof(BucketT)*OldNumBuckets);
394 // Free the old table.
395 operator delete(OldBuckets);
398 void shrink_and_clear() {
399 unsigned OldNumBuckets = NumBuckets;
400 BucketT *OldBuckets = Buckets;
402 // Reduce the number of buckets.
403 NumBuckets = NumEntries > 32 ? 1 << (Log2_32_Ceil(NumEntries) + 1)
406 Buckets = static_cast<BucketT*>(operator new(sizeof(BucketT)*NumBuckets));
408 // Initialize all the keys to EmptyKey.
409 const KeyT EmptyKey = getEmptyKey();
410 for (unsigned i = 0, e = NumBuckets; i != e; ++i)
411 new (&Buckets[i].first) KeyT(EmptyKey);
413 // Free the old buckets.
414 const KeyT TombstoneKey = getTombstoneKey();
415 for (BucketT *B = OldBuckets, *E = OldBuckets+OldNumBuckets; B != E; ++B) {
416 if (!KeyInfoT::isEqual(B->first, EmptyKey) &&
417 !KeyInfoT::isEqual(B->first, TombstoneKey)) {
425 memset(OldBuckets, 0x5a, sizeof(BucketT)*OldNumBuckets);
427 // Free the old table.
428 operator delete(OldBuckets);
434 template<typename KeyT, typename ValueT,
435 typename KeyInfoT, typename ValueInfoT, bool IsConst>
436 class DenseMapIterator {
437 typedef std::pair<KeyT, ValueT> Bucket;
438 typedef DenseMapIterator<KeyT, ValueT,
439 KeyInfoT, ValueInfoT, true> ConstIterator;
440 friend class DenseMapIterator<KeyT, ValueT, KeyInfoT, ValueInfoT, true>;
442 typedef ptrdiff_t difference_type;
443 typedef typename conditional<IsConst, const Bucket, Bucket>::type value_type;
444 typedef value_type *pointer;
445 typedef value_type &reference;
446 typedef std::forward_iterator_tag iterator_category;
450 DenseMapIterator() : Ptr(0), End(0) {}
452 DenseMapIterator(pointer Pos, pointer E) : Ptr(Pos), End(E) {
453 AdvancePastEmptyBuckets();
456 // If IsConst is true this is a converting constructor from iterator to
457 // const_iterator and the default copy constructor is used.
458 // Otherwise this is a copy constructor for iterator.
459 DenseMapIterator(const DenseMapIterator<KeyT, ValueT,
460 KeyInfoT, ValueInfoT, false>& I)
461 : Ptr(I.Ptr), End(I.End) {}
463 reference operator*() const {
466 pointer operator->() const {
470 bool operator==(const ConstIterator &RHS) const {
471 return Ptr == RHS.operator->();
473 bool operator!=(const ConstIterator &RHS) const {
474 return Ptr != RHS.operator->();
477 inline DenseMapIterator& operator++() { // Preincrement
479 AdvancePastEmptyBuckets();
482 DenseMapIterator operator++(int) { // Postincrement
483 DenseMapIterator tmp = *this; ++*this; return tmp;
487 void AdvancePastEmptyBuckets() {
488 const KeyT Empty = KeyInfoT::getEmptyKey();
489 const KeyT Tombstone = KeyInfoT::getTombstoneKey();
492 (KeyInfoT::isEqual(Ptr->first, Empty) ||
493 KeyInfoT::isEqual(Ptr->first, Tombstone)))
498 } // end namespace llvm