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/PointerLikeTypeTraits.h"
18 #include "llvm/Support/MathExtras.h"
19 #include "llvm/ADT/DenseMapInfo.h"
27 template<typename KeyT, typename ValueT,
28 typename KeyInfoT = DenseMapInfo<KeyT>,
29 typename ValueInfoT = DenseMapInfo<ValueT> >
30 class DenseMapIterator;
31 template<typename KeyT, typename ValueT,
32 typename KeyInfoT = DenseMapInfo<KeyT>,
33 typename ValueInfoT = DenseMapInfo<ValueT> >
34 class DenseMapConstIterator;
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 = 64) {
61 const KeyT EmptyKey = getEmptyKey(), TombstoneKey = getTombstoneKey();
62 for (BucketT *P = Buckets, *E = Buckets+NumBuckets; P != E; ++P) {
63 if (!KeyInfoT::isEqual(P->first, EmptyKey) &&
64 !KeyInfoT::isEqual(P->first, TombstoneKey))
69 memset(Buckets, 0x5a, sizeof(BucketT)*NumBuckets);
71 operator delete(Buckets);
74 typedef DenseMapIterator<KeyT, ValueT, KeyInfoT> iterator;
75 typedef DenseMapConstIterator<KeyT, ValueT, KeyInfoT> const_iterator;
76 inline iterator begin() {
77 return iterator(Buckets, Buckets+NumBuckets);
79 inline iterator end() {
80 return iterator(Buckets+NumBuckets, Buckets+NumBuckets);
82 inline const_iterator begin() const {
83 return const_iterator(Buckets, Buckets+NumBuckets);
85 inline const_iterator end() const {
86 return const_iterator(Buckets+NumBuckets, Buckets+NumBuckets);
89 bool empty() const { return NumEntries == 0; }
90 unsigned size() const { return NumEntries; }
92 /// Grow the densemap so that it has at least Size buckets. Does not shrink
93 void resize(size_t Size) { grow(Size); }
96 if (NumEntries == 0 && NumTombstones == 0) return;
98 // If the capacity of the array is huge, and the # elements used is small,
100 if (NumEntries * 4 < NumBuckets && NumBuckets > 64) {
105 const KeyT EmptyKey = getEmptyKey(), TombstoneKey = getTombstoneKey();
106 for (BucketT *P = Buckets, *E = Buckets+NumBuckets; P != E; ++P) {
107 if (!KeyInfoT::isEqual(P->first, EmptyKey)) {
108 if (!KeyInfoT::isEqual(P->first, TombstoneKey)) {
115 assert(NumEntries == 0 && "Node count imbalance!");
119 /// count - Return true if the specified key is in the map.
120 bool count(const KeyT &Val) const {
122 return LookupBucketFor(Val, TheBucket);
125 iterator find(const KeyT &Val) {
127 if (LookupBucketFor(Val, TheBucket))
128 return iterator(TheBucket, Buckets+NumBuckets);
131 const_iterator find(const KeyT &Val) const {
133 if (LookupBucketFor(Val, TheBucket))
134 return const_iterator(TheBucket, Buckets+NumBuckets);
138 /// lookup - Return the entry for the specified key, or a default
139 /// constructed value if no such entry exists.
140 ValueT lookup(const KeyT &Val) const {
142 if (LookupBucketFor(Val, TheBucket))
143 return TheBucket->second;
147 std::pair<iterator, bool> insert(const std::pair<KeyT, ValueT> &KV) {
149 if (LookupBucketFor(KV.first, TheBucket))
150 return std::make_pair(iterator(TheBucket, Buckets+NumBuckets),
151 false); // Already in map.
153 // Otherwise, insert the new element.
154 TheBucket = InsertIntoBucket(KV.first, KV.second, TheBucket);
155 return std::make_pair(iterator(TheBucket, Buckets+NumBuckets),
159 /// insert - Range insertion of pairs.
160 template<typename InputIt>
161 void insert(InputIt I, InputIt E) {
167 bool erase(const KeyT &Val) {
169 if (!LookupBucketFor(Val, TheBucket))
170 return false; // not in map.
172 TheBucket->second.~ValueT();
173 TheBucket->first = getTombstoneKey();
178 bool erase(iterator I) {
179 BucketT *TheBucket = &*I;
180 TheBucket->second.~ValueT();
181 TheBucket->first = getTombstoneKey();
187 value_type& FindAndConstruct(const KeyT &Key) {
189 if (LookupBucketFor(Key, TheBucket))
192 return *InsertIntoBucket(Key, ValueT(), TheBucket);
195 ValueT &operator[](const KeyT &Key) {
196 return FindAndConstruct(Key).second;
199 DenseMap& operator=(const DenseMap& other) {
204 /// isPointerIntoBucketsArray - Return true if the specified pointer points
205 /// somewhere into the DenseMap's array of buckets (i.e. either to a key or
206 /// value in the DenseMap).
207 bool isPointerIntoBucketsArray(const void *Ptr) const {
208 return Ptr >= Buckets && Ptr < Buckets+NumBuckets;
211 /// getPointerIntoBucketsArray() - Return an opaque pointer into the buckets
212 /// array. In conjunction with the previous method, this can be used to
213 /// determine whether an insertion caused the DenseMap to reallocate.
214 const void *getPointerIntoBucketsArray() const { return Buckets; }
217 void CopyFrom(const DenseMap& other) {
218 if (NumBuckets != 0 && (!KeyInfoT::isPod() || !ValueInfoT::isPod())) {
219 const KeyT EmptyKey = getEmptyKey(), TombstoneKey = getTombstoneKey();
220 for (BucketT *P = Buckets, *E = Buckets+NumBuckets; P != E; ++P) {
221 if (!KeyInfoT::isEqual(P->first, EmptyKey) &&
222 !KeyInfoT::isEqual(P->first, TombstoneKey))
228 NumEntries = other.NumEntries;
229 NumTombstones = other.NumTombstones;
233 memset(Buckets, 0x5a, sizeof(BucketT)*NumBuckets);
235 operator delete(Buckets);
237 Buckets = static_cast<BucketT*>(operator new(sizeof(BucketT) *
240 if (KeyInfoT::isPod() && ValueInfoT::isPod())
241 memcpy(Buckets, other.Buckets, other.NumBuckets * sizeof(BucketT));
243 for (size_t i = 0; i < other.NumBuckets; ++i) {
244 new (&Buckets[i].first) KeyT(other.Buckets[i].first);
245 if (!KeyInfoT::isEqual(Buckets[i].first, getEmptyKey()) &&
246 !KeyInfoT::isEqual(Buckets[i].first, getTombstoneKey()))
247 new (&Buckets[i].second) ValueT(other.Buckets[i].second);
249 NumBuckets = other.NumBuckets;
252 BucketT *InsertIntoBucket(const KeyT &Key, const ValueT &Value,
253 BucketT *TheBucket) {
254 // If the load of the hash table is more than 3/4, or if fewer than 1/8 of
255 // the buckets are empty (meaning that many are filled with tombstones),
258 // The later case is tricky. For example, if we had one empty bucket with
259 // tons of tombstones, failing lookups (e.g. for insertion) would have to
260 // probe almost the entire table until it found the empty bucket. If the
261 // table completely filled with tombstones, no lookup would ever succeed,
262 // causing infinite loops in lookup.
264 if (NumEntries*4 >= NumBuckets*3 ||
265 NumBuckets-(NumEntries+NumTombstones) < NumBuckets/8) {
266 this->grow(NumBuckets * 2);
267 LookupBucketFor(Key, TheBucket);
270 // If we are writing over a tombstone, remember this.
271 if (!KeyInfoT::isEqual(TheBucket->first, getEmptyKey()))
274 TheBucket->first = Key;
275 new (&TheBucket->second) ValueT(Value);
279 static unsigned getHashValue(const KeyT &Val) {
280 return KeyInfoT::getHashValue(Val);
282 static const KeyT getEmptyKey() {
283 return KeyInfoT::getEmptyKey();
285 static const KeyT getTombstoneKey() {
286 return KeyInfoT::getTombstoneKey();
289 /// LookupBucketFor - Lookup the appropriate bucket for Val, returning it in
290 /// FoundBucket. If the bucket contains the key and a value, this returns
291 /// true, otherwise it returns a bucket with an empty marker or tombstone and
293 bool LookupBucketFor(const KeyT &Val, BucketT *&FoundBucket) const {
294 unsigned BucketNo = getHashValue(Val);
295 unsigned ProbeAmt = 1;
296 BucketT *BucketsPtr = Buckets;
298 // FoundTombstone - Keep track of whether we find a tombstone while probing.
299 BucketT *FoundTombstone = 0;
300 const KeyT EmptyKey = getEmptyKey();
301 const KeyT TombstoneKey = getTombstoneKey();
302 assert(!KeyInfoT::isEqual(Val, EmptyKey) &&
303 !KeyInfoT::isEqual(Val, TombstoneKey) &&
304 "Empty/Tombstone value shouldn't be inserted into map!");
307 BucketT *ThisBucket = BucketsPtr + (BucketNo & (NumBuckets-1));
308 // Found Val's bucket? If so, return it.
309 if (KeyInfoT::isEqual(ThisBucket->first, Val)) {
310 FoundBucket = ThisBucket;
314 // If we found an empty bucket, the key doesn't exist in the set.
315 // Insert it and return the default value.
316 if (KeyInfoT::isEqual(ThisBucket->first, EmptyKey)) {
317 // If we've already seen a tombstone while probing, fill it in instead
318 // of the empty bucket we eventually probed to.
319 if (FoundTombstone) ThisBucket = FoundTombstone;
320 FoundBucket = FoundTombstone ? FoundTombstone : ThisBucket;
324 // If this is a tombstone, remember it. If Val ends up not in the map, we
325 // prefer to return it than something that would require more probing.
326 if (KeyInfoT::isEqual(ThisBucket->first, TombstoneKey) && !FoundTombstone)
327 FoundTombstone = ThisBucket; // Remember the first tombstone found.
329 // Otherwise, it's a hash collision or a tombstone, continue quadratic
331 BucketNo += ProbeAmt++;
335 void init(unsigned InitBuckets) {
338 NumBuckets = InitBuckets;
339 assert(InitBuckets && (InitBuckets & (InitBuckets-1)) == 0 &&
340 "# initial buckets must be a power of two!");
341 Buckets = static_cast<BucketT*>(operator new(sizeof(BucketT)*InitBuckets));
342 // Initialize all the keys to EmptyKey.
343 const KeyT EmptyKey = getEmptyKey();
344 for (unsigned i = 0; i != InitBuckets; ++i)
345 new (&Buckets[i].first) KeyT(EmptyKey);
348 void grow(unsigned AtLeast) {
349 unsigned OldNumBuckets = NumBuckets;
350 BucketT *OldBuckets = Buckets;
352 // Double the number of buckets.
353 while (NumBuckets <= AtLeast)
356 Buckets = static_cast<BucketT*>(operator new(sizeof(BucketT)*NumBuckets));
358 // Initialize all the keys to EmptyKey.
359 const KeyT EmptyKey = getEmptyKey();
360 for (unsigned i = 0, e = NumBuckets; i != e; ++i)
361 new (&Buckets[i].first) KeyT(EmptyKey);
363 // Insert all the old elements.
364 const KeyT TombstoneKey = getTombstoneKey();
365 for (BucketT *B = OldBuckets, *E = OldBuckets+OldNumBuckets; B != E; ++B) {
366 if (!KeyInfoT::isEqual(B->first, EmptyKey) &&
367 !KeyInfoT::isEqual(B->first, TombstoneKey)) {
368 // Insert the key/value into the new table.
370 bool FoundVal = LookupBucketFor(B->first, DestBucket);
371 FoundVal = FoundVal; // silence warning.
372 assert(!FoundVal && "Key already in new map?");
373 DestBucket->first = B->first;
374 new (&DestBucket->second) ValueT(B->second);
383 memset(OldBuckets, 0x5a, sizeof(BucketT)*OldNumBuckets);
385 // Free the old table.
386 operator delete(OldBuckets);
389 void shrink_and_clear() {
390 unsigned OldNumBuckets = NumBuckets;
391 BucketT *OldBuckets = Buckets;
393 // Reduce the number of buckets.
394 NumBuckets = NumEntries > 32 ? 1 << (Log2_32_Ceil(NumEntries) + 1)
397 Buckets = static_cast<BucketT*>(operator new(sizeof(BucketT)*NumBuckets));
399 // Initialize all the keys to EmptyKey.
400 const KeyT EmptyKey = getEmptyKey();
401 for (unsigned i = 0, e = NumBuckets; i != e; ++i)
402 new (&Buckets[i].first) KeyT(EmptyKey);
404 // Free the old buckets.
405 const KeyT TombstoneKey = getTombstoneKey();
406 for (BucketT *B = OldBuckets, *E = OldBuckets+OldNumBuckets; B != E; ++B) {
407 if (!KeyInfoT::isEqual(B->first, EmptyKey) &&
408 !KeyInfoT::isEqual(B->first, TombstoneKey)) {
416 memset(OldBuckets, 0x5a, sizeof(BucketT)*OldNumBuckets);
418 // Free the old table.
419 operator delete(OldBuckets);
425 template<typename KeyT, typename ValueT, typename KeyInfoT, typename ValueInfoT>
426 class DenseMapIterator {
427 typedef std::pair<KeyT, ValueT> BucketT;
429 const BucketT *Ptr, *End;
431 DenseMapIterator() : Ptr(0), End(0) {}
433 DenseMapIterator(const BucketT *Pos, const BucketT *E) : Ptr(Pos), End(E) {
434 AdvancePastEmptyBuckets();
437 std::pair<KeyT, ValueT> &operator*() const {
438 return *const_cast<BucketT*>(Ptr);
440 std::pair<KeyT, ValueT> *operator->() const {
441 return const_cast<BucketT*>(Ptr);
444 bool operator==(const DenseMapIterator &RHS) const {
445 return Ptr == RHS.Ptr;
447 bool operator!=(const DenseMapIterator &RHS) const {
448 return Ptr != RHS.Ptr;
451 inline DenseMapIterator& operator++() { // Preincrement
453 AdvancePastEmptyBuckets();
456 DenseMapIterator operator++(int) { // Postincrement
457 DenseMapIterator tmp = *this; ++*this; return tmp;
461 void AdvancePastEmptyBuckets() {
462 const KeyT Empty = KeyInfoT::getEmptyKey();
463 const KeyT Tombstone = KeyInfoT::getTombstoneKey();
466 (KeyInfoT::isEqual(Ptr->first, Empty) ||
467 KeyInfoT::isEqual(Ptr->first, Tombstone)))
472 template<typename KeyT, typename ValueT, typename KeyInfoT, typename ValueInfoT>
473 class DenseMapConstIterator : public DenseMapIterator<KeyT, ValueT, KeyInfoT> {
475 DenseMapConstIterator() : DenseMapIterator<KeyT, ValueT, KeyInfoT>() {}
476 DenseMapConstIterator(const std::pair<KeyT, ValueT> *Pos,
477 const std::pair<KeyT, ValueT> *E)
478 : DenseMapIterator<KeyT, ValueT, KeyInfoT>(Pos, E) {
480 const std::pair<KeyT, ValueT> &operator*() const {
483 const std::pair<KeyT, ValueT> *operator->() const {
488 } // end namespace llvm