]> git.saurik.com Git - apple/objc4.git/blob - runtime/llvm-DenseMap.h
objc4-493.11.tar.gz
[apple/objc4.git] / runtime / llvm-DenseMap.h
1 //===- llvm/ADT/DenseMap.h - Dense probed hash table ------------*- C++ -*-===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the DenseMap class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #ifndef LLVM_ADT_DENSEMAP_H
15 #define LLVM_ADT_DENSEMAP_H
16
17 #include "llvm-type_traits.h"
18 #include <algorithm>
19 #include <iterator>
20 #include <new>
21 #include <utility>
22 #include <cassert>
23 #include <cstddef>
24 #include <cstring>
25 #include <TargetConditionals.h>
26
27
28 namespace objc {
29
30 #if TARGET_OS_IPHONE
31
32 // lifted from <MathExtras.h>:
33
34 /// CountLeadingZeros_32 - this function performs the platform optimal form of
35 /// counting the number of zeros from the most significant bit to the first one
36 /// bit. Ex. CountLeadingZeros_32(0x00F000FF) == 8.
37 /// Returns 32 if the word is zero.
38 inline unsigned CountLeadingZeros_32(uint32_t Value) {
39 unsigned Count; // result
40 #if __GNUC__ >= 4
41 // PowerPC is defined for __builtin_clz(0)
42 #if !defined(__ppc__) && !defined(__ppc64__)
43 if (!Value) return 32;
44 #endif
45 Count = __builtin_clz(Value);
46 #else
47 if (!Value) return 32;
48 Count = 0;
49 // bisection method for count leading zeros
50 for (unsigned Shift = 32 >> 1; Shift; Shift >>= 1) {
51 uint32_t Tmp = Value >> Shift;
52 if (Tmp) {
53 Value = Tmp;
54 } else {
55 Count |= Shift;
56 }
57 }
58 #endif
59 return Count;
60 }
61 /// CountLeadingOnes_32 - this function performs the operation of
62 /// counting the number of ones from the most significant bit to the first zero
63 /// bit. Ex. CountLeadingOnes_32(0xFF0FFF00) == 8.
64 /// Returns 32 if the word is all ones.
65 inline unsigned CountLeadingOnes_32(uint32_t Value) {
66 return CountLeadingZeros_32(~Value);
67 }
68 /// CountLeadingZeros_64 - This function performs the platform optimal form
69 /// of counting the number of zeros from the most significant bit to the first
70 /// one bit (64 bit edition.)
71 /// Returns 64 if the word is zero.
72 inline unsigned CountLeadingZeros_64(uint64_t Value) {
73 unsigned Count; // result
74 #if __GNUC__ >= 4
75 // PowerPC is defined for __builtin_clzll(0)
76 #if !defined(__ppc__) && !defined(__ppc64__)
77 if (!Value) return 64;
78 #endif
79 Count = __builtin_clzll(Value);
80 #else
81 if (sizeof(long) == sizeof(int64_t)) {
82 if (!Value) return 64;
83 Count = 0;
84 // bisection method for count leading zeros
85 for (unsigned Shift = 64 >> 1; Shift; Shift >>= 1) {
86 uint64_t Tmp = Value >> Shift;
87 if (Tmp) {
88 Value = Tmp;
89 } else {
90 Count |= Shift;
91 }
92 }
93 } else {
94 // get hi portion
95 uint32_t Hi = Hi_32(Value);
96 // if some bits in hi portion
97 if (Hi) {
98 // leading zeros in hi portion plus all bits in lo portion
99 Count = CountLeadingZeros_32(Hi);
100 } else {
101 // get lo portion
102 uint32_t Lo = Lo_32(Value);
103 // same as 32 bit value
104 Count = CountLeadingZeros_32(Lo)+32;
105 }
106 }
107 #endif
108 return Count;
109 }
110 /// CountLeadingOnes_64 - This function performs the operation
111 /// of counting the number of ones from the most significant bit to the first
112 /// zero bit (64 bit edition.)
113 /// Returns 64 if the word is all ones.
114 inline unsigned CountLeadingOnes_64(uint64_t Value) {
115 return CountLeadingZeros_64(~Value);
116 }
117 /// CountTrailingZeros_32 - this function performs the platform optimal form of
118 /// counting the number of zeros from the least significant bit to the first one
119 /// bit. Ex. CountTrailingZeros_32(0xFF00FF00) == 8.
120 /// Returns 32 if the word is zero.
121 inline unsigned CountTrailingZeros_32(uint32_t Value) {
122 #if __GNUC__ >= 4
123 return Value ? __builtin_ctz(Value) : 32;
124 #else
125 static const unsigned Mod37BitPosition[] = {
126 32, 0, 1, 26, 2, 23, 27, 0, 3, 16, 24, 30, 28, 11, 0, 13,
127 4, 7, 17, 0, 25, 22, 31, 15, 29, 10, 12, 6, 0, 21, 14, 9,
128 5, 20, 8, 19, 18
129 };
130 return Mod37BitPosition[(-Value & Value) % 37];
131 #endif
132 }
133 /// CountTrailingOnes_32 - this function performs the operation of
134 /// counting the number of ones from the least significant bit to the first zero
135 /// bit. Ex. CountTrailingOnes_32(0x00FF00FF) == 8.
136 /// Returns 32 if the word is all ones.
137 inline unsigned CountTrailingOnes_32(uint32_t Value) {
138 return CountTrailingZeros_32(~Value);
139 }
140 /// CountTrailingZeros_64 - This function performs the platform optimal form
141 /// of counting the number of zeros from the least significant bit to the first
142 /// one bit (64 bit edition.)
143 /// Returns 64 if the word is zero.
144 inline unsigned CountTrailingZeros_64(uint64_t Value) {
145 #if __GNUC__ >= 4
146 return Value ? __builtin_ctzll(Value) : 64;
147 #else
148 static const unsigned Mod67Position[] = {
149 64, 0, 1, 39, 2, 15, 40, 23, 3, 12, 16, 59, 41, 19, 24, 54,
150 4, 64, 13, 10, 17, 62, 60, 28, 42, 30, 20, 51, 25, 44, 55,
151 47, 5, 32, 65, 38, 14, 22, 11, 58, 18, 53, 63, 9, 61, 27,
152 29, 50, 43, 46, 31, 37, 21, 57, 52, 8, 26, 49, 45, 36, 56,
153 7, 48, 35, 6, 34, 33, 0
154 };
155 return Mod67Position[(-Value & Value) % 67];
156 #endif
157 }
158
159 /// CountTrailingOnes_64 - This function performs the operation
160 /// of counting the number of ones from the least significant bit to the first
161 /// zero bit (64 bit edition.)
162 /// Returns 64 if the word is all ones.
163 inline unsigned CountTrailingOnes_64(uint64_t Value) {
164 return CountTrailingZeros_64(~Value);
165 }
166 /// CountPopulation_32 - this function counts the number of set bits in a value.
167 /// Ex. CountPopulation(0xF000F000) = 8
168 /// Returns 0 if the word is zero.
169 inline unsigned CountPopulation_32(uint32_t Value) {
170 #if __GNUC__ >= 4
171 return __builtin_popcount(Value);
172 #else
173 uint32_t v = Value - ((Value >> 1) & 0x55555555);
174 v = (v & 0x33333333) + ((v >> 2) & 0x33333333);
175 return ((v + (v >> 4) & 0xF0F0F0F) * 0x1010101) >> 24;
176 #endif
177 }
178 /// CountPopulation_64 - this function counts the number of set bits in a value,
179 /// (64 bit edition.)
180 inline unsigned CountPopulation_64(uint64_t Value) {
181 #if __GNUC__ >= 4
182 return __builtin_popcountll(Value);
183 #else
184 uint64_t v = Value - ((Value >> 1) & 0x5555555555555555ULL);
185 v = (v & 0x3333333333333333ULL) + ((v >> 2) & 0x3333333333333333ULL);
186 v = (v + (v >> 4)) & 0x0F0F0F0F0F0F0F0FULL;
187 return unsigned((uint64_t)(v * 0x0101010101010101ULL) >> 56);
188 #endif
189 }
190 /// Log2_32 - This function returns the floor log base 2 of the specified value,
191 /// -1 if the value is zero. (32 bit edition.)
192 /// Ex. Log2_32(32) == 5, Log2_32(1) == 0, Log2_32(0) == -1, Log2_32(6) == 2
193 inline unsigned Log2_32(uint32_t Value) {
194 return 31 - CountLeadingZeros_32(Value);
195 }
196 /// Log2_64 - This function returns the floor log base 2 of the specified value,
197 /// -1 if the value is zero. (64 bit edition.)
198 inline unsigned Log2_64(uint64_t Value) {
199 return 63 - CountLeadingZeros_64(Value);
200 }
201 /// Log2_32_Ceil - This function returns the ceil log base 2 of the specified
202 /// value, 32 if the value is zero. (32 bit edition).
203 /// Ex. Log2_32_Ceil(32) == 5, Log2_32_Ceil(1) == 0, Log2_32_Ceil(6) == 3
204 inline unsigned Log2_32_Ceil(uint32_t Value) {
205 return 32-CountLeadingZeros_32(Value-1);
206 }
207
208 #endif /* TARGET_OS_IPHONE */
209
210 template<typename T>
211 struct DenseMapInfo {
212 //static inline T getEmptyKey();
213 //static inline T getTombstoneKey();
214 //static unsigned getHashValue(const T &Val);
215 //static bool isEqual(const T &LHS, const T &RHS);
216 };
217
218 // Provide DenseMapInfo for all pointers.
219 template<typename T>
220 struct DenseMapInfo<T*> {
221 static inline T* getEmptyKey() {
222 intptr_t Val = -1;
223 return reinterpret_cast<T*>(Val);
224 }
225 static inline T* getTombstoneKey() {
226 intptr_t Val = -2;
227 return reinterpret_cast<T*>(Val);
228 }
229 static unsigned getHashValue(const T *PtrVal) {
230 return (unsigned((uintptr_t)PtrVal) >> 4) ^
231 (unsigned((uintptr_t)PtrVal) >> 9);
232 }
233 static bool isEqual(const T *LHS, const T *RHS) { return LHS == RHS; }
234 };
235
236 // Provide DenseMapInfo for chars.
237 template<> struct DenseMapInfo<char> {
238 static inline char getEmptyKey() { return ~0; }
239 static inline char getTombstoneKey() { return ~0 - 1; }
240 static unsigned getHashValue(const char& Val) { return Val * 37; }
241 static bool isEqual(const char &LHS, const char &RHS) {
242 return LHS == RHS;
243 }
244 };
245
246 // Provide DenseMapInfo for unsigned ints.
247 template<> struct DenseMapInfo<unsigned> {
248 static inline unsigned getEmptyKey() { return ~0; }
249 static inline unsigned getTombstoneKey() { return ~0U - 1; }
250 static unsigned getHashValue(const unsigned& Val) { return Val * 37; }
251 static bool isEqual(const unsigned& LHS, const unsigned& RHS) {
252 return LHS == RHS;
253 }
254 };
255
256 // Provide DenseMapInfo for unsigned longs.
257 template<> struct DenseMapInfo<unsigned long> {
258 static inline unsigned long getEmptyKey() { return ~0UL; }
259 static inline unsigned long getTombstoneKey() { return ~0UL - 1L; }
260 static unsigned getHashValue(const unsigned long& Val) {
261 return (unsigned)(Val * 37UL);
262 }
263 static bool isEqual(const unsigned long& LHS, const unsigned long& RHS) {
264 return LHS == RHS;
265 }
266 };
267
268 // Provide DenseMapInfo for unsigned long longs.
269 template<> struct DenseMapInfo<unsigned long long> {
270 static inline unsigned long long getEmptyKey() { return ~0ULL; }
271 static inline unsigned long long getTombstoneKey() { return ~0ULL - 1ULL; }
272 static unsigned getHashValue(const unsigned long long& Val) {
273 return (unsigned)(Val * 37ULL);
274 }
275 static bool isEqual(const unsigned long long& LHS,
276 const unsigned long long& RHS) {
277 return LHS == RHS;
278 }
279 };
280
281 // Provide DenseMapInfo for ints.
282 template<> struct DenseMapInfo<int> {
283 static inline int getEmptyKey() { return 0x7fffffff; }
284 static inline int getTombstoneKey() { return -0x7fffffff - 1; }
285 static unsigned getHashValue(const int& Val) { return (unsigned)(Val * 37); }
286 static bool isEqual(const int& LHS, const int& RHS) {
287 return LHS == RHS;
288 }
289 };
290
291 // Provide DenseMapInfo for longs.
292 template<> struct DenseMapInfo<long> {
293 static inline long getEmptyKey() {
294 return (1UL << (sizeof(long) * 8 - 1)) - 1L;
295 }
296 static inline long getTombstoneKey() { return getEmptyKey() - 1L; }
297 static unsigned getHashValue(const long& Val) {
298 return (unsigned)(Val * 37L);
299 }
300 static bool isEqual(const long& LHS, const long& RHS) {
301 return LHS == RHS;
302 }
303 };
304
305 // Provide DenseMapInfo for long longs.
306 template<> struct DenseMapInfo<long long> {
307 static inline long long getEmptyKey() { return 0x7fffffffffffffffLL; }
308 static inline long long getTombstoneKey() { return -0x7fffffffffffffffLL-1; }
309 static unsigned getHashValue(const long long& Val) {
310 return (unsigned)(Val * 37LL);
311 }
312 static bool isEqual(const long long& LHS,
313 const long long& RHS) {
314 return LHS == RHS;
315 }
316 };
317
318 // Provide DenseMapInfo for all pairs whose members have info.
319 template<typename T, typename U>
320 struct DenseMapInfo<std::pair<T, U> > {
321 typedef std::pair<T, U> Pair;
322 typedef DenseMapInfo<T> FirstInfo;
323 typedef DenseMapInfo<U> SecondInfo;
324
325 static inline Pair getEmptyKey() {
326 return std::make_pair(FirstInfo::getEmptyKey(),
327 SecondInfo::getEmptyKey());
328 }
329 static inline Pair getTombstoneKey() {
330 return std::make_pair(FirstInfo::getTombstoneKey(),
331 SecondInfo::getEmptyKey());
332 }
333 static unsigned getHashValue(const Pair& PairVal) {
334 uint64_t key = (uint64_t)FirstInfo::getHashValue(PairVal.first) << 32
335 | (uint64_t)SecondInfo::getHashValue(PairVal.second);
336 key += ~(key << 32);
337 key ^= (key >> 22);
338 key += ~(key << 13);
339 key ^= (key >> 8);
340 key += (key << 3);
341 key ^= (key >> 15);
342 key += ~(key << 27);
343 key ^= (key >> 31);
344 return (unsigned)key;
345 }
346 static bool isEqual(const Pair& LHS, const Pair& RHS) { return LHS == RHS; }
347 };
348
349 } // end namespace objc
350
351
352
353 namespace objc {
354
355 template<typename KeyT, typename ValueT,
356 typename KeyInfoT = DenseMapInfo<KeyT>,
357 typename ValueInfoT = DenseMapInfo<ValueT>, bool IsConst = false>
358 class DenseMapIterator;
359
360 // ZeroValuesArePurgeable=true is used by the refcount table.
361 // A key/value pair with value==0 is not required to be stored
362 // in the refcount table; it could correctly be erased instead.
363 // For performance, we do keep zero values in the table when the
364 // true refcount decreases to 1: this makes any future retain faster.
365 // For memory size, we allow rehashes and table insertions to
366 // remove a zero value as if it were a tombstone.
367
368 template<typename KeyT, typename ValueT,
369 bool ZeroValuesArePurgeable = false,
370 typename KeyInfoT = DenseMapInfo<KeyT>,
371 typename ValueInfoT = DenseMapInfo<ValueT> >
372 class DenseMap {
373 typedef std::pair<KeyT, ValueT> BucketT;
374 unsigned NumBuckets;
375 BucketT *Buckets;
376
377 unsigned NumEntries;
378 unsigned NumTombstones;
379 public:
380 typedef KeyT key_type;
381 typedef ValueT mapped_type;
382 typedef BucketT value_type;
383
384 DenseMap(const DenseMap &other) {
385 NumBuckets = 0;
386 CopyFrom(other);
387 }
388
389 explicit DenseMap(unsigned NumInitBuckets = 64) {
390 init(NumInitBuckets);
391 }
392
393 template<typename InputIt>
394 DenseMap(const InputIt &I, const InputIt &E) {
395 init(64);
396 insert(I, E);
397 }
398
399 ~DenseMap() {
400 const KeyT EmptyKey = getEmptyKey(), TombstoneKey = getTombstoneKey();
401 for (BucketT *P = Buckets, *E = Buckets+NumBuckets; P != E; ++P) {
402 if (!KeyInfoT::isEqual(P->first, EmptyKey) &&
403 !KeyInfoT::isEqual(P->first, TombstoneKey))
404 P->second.~ValueT();
405 P->first.~KeyT();
406 }
407 #ifndef NDEBUG
408 memset(Buckets, 0x5a, sizeof(BucketT)*NumBuckets);
409 #endif
410 operator delete(Buckets);
411 }
412
413 typedef DenseMapIterator<KeyT, ValueT, KeyInfoT> iterator;
414 typedef DenseMapIterator<KeyT, ValueT,
415 KeyInfoT, ValueInfoT, true> const_iterator;
416 inline iterator begin() {
417 // When the map is empty, avoid the overhead of AdvancePastEmptyBuckets().
418 return empty() ? end() : iterator(Buckets, Buckets+NumBuckets);
419 }
420 inline iterator end() {
421 return iterator(Buckets+NumBuckets, Buckets+NumBuckets);
422 }
423 inline const_iterator begin() const {
424 return empty() ? end() : const_iterator(Buckets, Buckets+NumBuckets);
425 }
426 inline const_iterator end() const {
427 return const_iterator(Buckets+NumBuckets, Buckets+NumBuckets);
428 }
429
430 bool empty() const { return NumEntries == 0; }
431 unsigned size() const { return NumEntries; }
432
433 /// Grow the densemap so that it has at least Size buckets. Does not shrink
434 void resize(size_t Size) { grow(Size); }
435
436 void clear() {
437 if (NumEntries == 0 && NumTombstones == 0) return;
438
439 // If the capacity of the array is huge, and the # elements used is small,
440 // shrink the array.
441 if (NumEntries * 4 < NumBuckets && NumBuckets > 64) {
442 shrink_and_clear();
443 return;
444 }
445
446 const KeyT EmptyKey = getEmptyKey(), TombstoneKey = getTombstoneKey();
447 for (BucketT *P = Buckets, *E = Buckets+NumBuckets; P != E; ++P) {
448 if (!KeyInfoT::isEqual(P->first, EmptyKey)) {
449 if (!KeyInfoT::isEqual(P->first, TombstoneKey)) {
450 P->second.~ValueT();
451 --NumEntries;
452 }
453 P->first = EmptyKey;
454 }
455 }
456 assert(NumEntries == 0 && "Node count imbalance!");
457 NumTombstones = 0;
458 }
459
460 /// count - Return true if the specified key is in the map.
461 bool count(const KeyT &Val) const {
462 BucketT *TheBucket;
463 return LookupBucketFor(Val, TheBucket);
464 }
465
466 iterator find(const KeyT &Val) {
467 BucketT *TheBucket;
468 if (LookupBucketFor(Val, TheBucket))
469 return iterator(TheBucket, Buckets+NumBuckets);
470 return end();
471 }
472 const_iterator find(const KeyT &Val) const {
473 BucketT *TheBucket;
474 if (LookupBucketFor(Val, TheBucket))
475 return const_iterator(TheBucket, Buckets+NumBuckets);
476 return end();
477 }
478
479 /// lookup - Return the entry for the specified key, or a default
480 /// constructed value if no such entry exists.
481 ValueT lookup(const KeyT &Val) const {
482 BucketT *TheBucket;
483 if (LookupBucketFor(Val, TheBucket))
484 return TheBucket->second;
485 return ValueT();
486 }
487
488 // Inserts key,value pair into the map if the key isn't already in the map.
489 // If the key is already in the map, it returns false and doesn't update the
490 // value.
491 std::pair<iterator, bool> insert(const std::pair<KeyT, ValueT> &KV) {
492 BucketT *TheBucket;
493 if (LookupBucketFor(KV.first, TheBucket))
494 return std::make_pair(iterator(TheBucket, Buckets+NumBuckets),
495 false); // Already in map.
496
497 // Otherwise, insert the new element.
498 TheBucket = InsertIntoBucket(KV.first, KV.second, TheBucket);
499 return std::make_pair(iterator(TheBucket, Buckets+NumBuckets),
500 true);
501 }
502
503 /// insert - Range insertion of pairs.
504 template<typename InputIt>
505 void insert(InputIt I, InputIt E) {
506 for (; I != E; ++I)
507 insert(*I);
508 }
509
510
511 bool erase(const KeyT &Val) {
512 BucketT *TheBucket;
513 if (!LookupBucketFor(Val, TheBucket))
514 return false; // not in map.
515
516 TheBucket->second.~ValueT();
517 TheBucket->first = getTombstoneKey();
518 --NumEntries;
519 ++NumTombstones;
520 return true;
521 }
522 void erase(iterator I) {
523 BucketT *TheBucket = &*I;
524 TheBucket->second.~ValueT();
525 TheBucket->first = getTombstoneKey();
526 --NumEntries;
527 ++NumTombstones;
528 }
529
530 void swap(DenseMap& RHS) {
531 std::swap(NumBuckets, RHS.NumBuckets);
532 std::swap(Buckets, RHS.Buckets);
533 std::swap(NumEntries, RHS.NumEntries);
534 std::swap(NumTombstones, RHS.NumTombstones);
535 }
536
537 value_type& FindAndConstruct(const KeyT &Key) {
538 BucketT *TheBucket;
539 if (LookupBucketFor(Key, TheBucket))
540 return *TheBucket;
541
542 return *InsertIntoBucket(Key, ValueT(), TheBucket);
543 }
544
545 ValueT &operator[](const KeyT &Key) {
546 return FindAndConstruct(Key).second;
547 }
548
549 DenseMap& operator=(const DenseMap& other) {
550 CopyFrom(other);
551 return *this;
552 }
553
554 /// isPointerIntoBucketsArray - Return true if the specified pointer points
555 /// somewhere into the DenseMap's array of buckets (i.e. either to a key or
556 /// value in the DenseMap).
557 bool isPointerIntoBucketsArray(const void *Ptr) const {
558 return Ptr >= Buckets && Ptr < Buckets+NumBuckets;
559 }
560
561 /// getPointerIntoBucketsArray() - Return an opaque pointer into the buckets
562 /// array. In conjunction with the previous method, this can be used to
563 /// determine whether an insertion caused the DenseMap to reallocate.
564 const void *getPointerIntoBucketsArray() const { return Buckets; }
565
566 private:
567 void CopyFrom(const DenseMap& other) {
568 if (NumBuckets != 0 &&
569 (!isPodLike<KeyInfoT>::value || !isPodLike<ValueInfoT>::value)) {
570 const KeyT EmptyKey = getEmptyKey(), TombstoneKey = getTombstoneKey();
571 for (BucketT *P = Buckets, *E = Buckets+NumBuckets; P != E; ++P) {
572 if (!KeyInfoT::isEqual(P->first, EmptyKey) &&
573 !KeyInfoT::isEqual(P->first, TombstoneKey))
574 P->second.~ValueT();
575 P->first.~KeyT();
576 }
577 }
578
579 NumEntries = other.NumEntries;
580 NumTombstones = other.NumTombstones;
581
582 if (NumBuckets) {
583 #ifndef NDEBUG
584 memset(Buckets, 0x5a, sizeof(BucketT)*NumBuckets);
585 #endif
586 operator delete(Buckets);
587 }
588 Buckets = static_cast<BucketT*>(operator new(sizeof(BucketT) *
589 other.NumBuckets));
590
591 if (isPodLike<KeyInfoT>::value && isPodLike<ValueInfoT>::value)
592 memcpy(Buckets, other.Buckets, other.NumBuckets * sizeof(BucketT));
593 else
594 for (size_t i = 0; i < other.NumBuckets; ++i) {
595 new (&Buckets[i].first) KeyT(other.Buckets[i].first);
596 if (!KeyInfoT::isEqual(Buckets[i].first, getEmptyKey()) &&
597 !KeyInfoT::isEqual(Buckets[i].first, getTombstoneKey()))
598 new (&Buckets[i].second) ValueT(other.Buckets[i].second);
599 }
600 NumBuckets = other.NumBuckets;
601 }
602
603 BucketT *InsertIntoBucket(const KeyT &Key, const ValueT &Value,
604 BucketT *TheBucket) {
605 // If the load of the hash table is more than 3/4, grow the table.
606 // If fewer than 1/8 of the buckets are empty (meaning that many are
607 // filled with tombstones), rehash the table without growing.
608 //
609 // The later case is tricky. For example, if we had one empty bucket with
610 // tons of tombstones, failing lookups (e.g. for insertion) would have to
611 // probe almost the entire table until it found the empty bucket. If the
612 // table completely filled with tombstones, no lookup would ever succeed,
613 // causing infinite loops in lookup.
614 ++NumEntries;
615 if (NumEntries*4 >= NumBuckets*3) {
616 this->grow(NumBuckets * 2);
617 LookupBucketFor(Key, TheBucket);
618 }
619 else if (NumBuckets-(NumEntries+NumTombstones) < NumBuckets/8) {
620 this->grow(NumBuckets);
621 LookupBucketFor(Key, TheBucket);
622 }
623
624 // If we are writing over a tombstone or zero value, remember this.
625 if (!KeyInfoT::isEqual(TheBucket->first, getEmptyKey())) {
626 if (KeyInfoT::isEqual(TheBucket->first, getTombstoneKey())) {
627 --NumTombstones;
628 } else {
629 assert(ZeroValuesArePurgeable && TheBucket->second == 0);
630 TheBucket->second.~ValueT();
631 --NumEntries;
632 }
633 }
634
635 TheBucket->first = Key;
636 new (&TheBucket->second) ValueT(Value);
637 return TheBucket;
638 }
639
640 static unsigned getHashValue(const KeyT &Val) {
641 return KeyInfoT::getHashValue(Val);
642 }
643 static const KeyT getEmptyKey() {
644 return KeyInfoT::getEmptyKey();
645 }
646 static const KeyT getTombstoneKey() {
647 return KeyInfoT::getTombstoneKey();
648 }
649
650 /// LookupBucketFor - Lookup the appropriate bucket for Val, returning it in
651 /// FoundBucket. If the bucket contains the key and a value, this returns
652 /// true, otherwise it returns a bucket with an empty marker or tombstone
653 /// or zero value and returns false.
654 bool LookupBucketFor(const KeyT &Val, BucketT *&FoundBucket) const {
655 unsigned BucketNo = getHashValue(Val);
656 unsigned ProbeAmt = 1;
657 BucketT *BucketsPtr = Buckets;
658
659 // FoundTombstone - Keep track of whether we find a tombstone or zero value while probing.
660 BucketT *FoundTombstone = 0;
661 const KeyT EmptyKey = getEmptyKey();
662 const KeyT TombstoneKey = getTombstoneKey();
663 assert(!KeyInfoT::isEqual(Val, EmptyKey) &&
664 !KeyInfoT::isEqual(Val, TombstoneKey) &&
665 "Empty/Tombstone value shouldn't be inserted into map!");
666
667 while (1) {
668 BucketT *ThisBucket = BucketsPtr + (BucketNo & (NumBuckets-1));
669 // Found Val's bucket? If so, return it.
670 if (KeyInfoT::isEqual(ThisBucket->first, Val)) {
671 FoundBucket = ThisBucket;
672 return true;
673 }
674
675 // If we found an empty bucket, the key doesn't exist in the set.
676 // Insert it and return the default value.
677 if (KeyInfoT::isEqual(ThisBucket->first, EmptyKey)) {
678 // If we've already seen a tombstone while probing, fill it in instead
679 // of the empty bucket we eventually probed to.
680 if (FoundTombstone) ThisBucket = FoundTombstone;
681 FoundBucket = FoundTombstone ? FoundTombstone : ThisBucket;
682 return false;
683 }
684
685 // If this is a tombstone, remember it. If Val ends up not in the map, we
686 // prefer to return it than something that would require more probing.
687 // Ditto for zero values.
688 if (KeyInfoT::isEqual(ThisBucket->first, TombstoneKey) && !FoundTombstone)
689 FoundTombstone = ThisBucket; // Remember the first tombstone found.
690 if (ZeroValuesArePurgeable &&
691 ThisBucket->second == 0 && !FoundTombstone)
692 FoundTombstone = ThisBucket;
693
694 // Otherwise, it's a hash collision or a tombstone, continue quadratic
695 // probing.
696 BucketNo += ProbeAmt++;
697 }
698 }
699
700 void init(unsigned InitBuckets) {
701 NumEntries = 0;
702 NumTombstones = 0;
703 NumBuckets = InitBuckets;
704 assert(InitBuckets && (InitBuckets & (InitBuckets-1)) == 0 &&
705 "# initial buckets must be a power of two!");
706 Buckets = static_cast<BucketT*>(operator new(sizeof(BucketT)*InitBuckets));
707 // Initialize all the keys to EmptyKey.
708 const KeyT EmptyKey = getEmptyKey();
709 for (unsigned i = 0; i != InitBuckets; ++i)
710 new (&Buckets[i].first) KeyT(EmptyKey);
711 }
712
713 void grow(unsigned AtLeast) {
714 unsigned OldNumBuckets = NumBuckets;
715 BucketT *OldBuckets = Buckets;
716
717 // Double the number of buckets.
718 while (NumBuckets < AtLeast)
719 NumBuckets <<= 1;
720 NumTombstones = 0;
721 Buckets = static_cast<BucketT*>(operator new(sizeof(BucketT)*NumBuckets));
722
723 // Initialize all the keys to EmptyKey.
724 const KeyT EmptyKey = getEmptyKey();
725 for (unsigned i = 0, e = NumBuckets; i != e; ++i)
726 new (&Buckets[i].first) KeyT(EmptyKey);
727
728 // Insert all the old elements.
729 const KeyT TombstoneKey = getTombstoneKey();
730 for (BucketT *B = OldBuckets, *E = OldBuckets+OldNumBuckets; B != E; ++B) {
731 if (!KeyInfoT::isEqual(B->first, EmptyKey) &&
732 !KeyInfoT::isEqual(B->first, TombstoneKey))
733 {
734 // Valid key/value, or zero value
735 if (!ZeroValuesArePurgeable || B->second != 0) {
736 // Insert the key/value into the new table.
737 BucketT *DestBucket;
738 bool FoundVal = LookupBucketFor(B->first, DestBucket);
739 (void)FoundVal; // silence warning.
740 assert(!FoundVal && "Key already in new map?");
741 DestBucket->first = B->first;
742 new (&DestBucket->second) ValueT(B->second);
743 } else {
744 NumEntries--;
745 }
746
747 // Free the value.
748 B->second.~ValueT();
749 }
750 B->first.~KeyT();
751 }
752
753 #ifndef NDEBUG
754 memset(OldBuckets, 0x5a, sizeof(BucketT)*OldNumBuckets);
755 #endif
756 // Free the old table.
757 operator delete(OldBuckets);
758 }
759
760 void shrink_and_clear() {
761 unsigned OldNumBuckets = NumBuckets;
762 BucketT *OldBuckets = Buckets;
763
764 // Reduce the number of buckets.
765 NumBuckets = NumEntries > 32 ? 1 << (Log2_32_Ceil(NumEntries) + 1)
766 : 64;
767 NumTombstones = 0;
768 Buckets = static_cast<BucketT*>(operator new(sizeof(BucketT)*NumBuckets));
769
770 // Initialize all the keys to EmptyKey.
771 const KeyT EmptyKey = getEmptyKey();
772 for (unsigned i = 0, e = NumBuckets; i != e; ++i)
773 new (&Buckets[i].first) KeyT(EmptyKey);
774
775 // Free the old buckets.
776 const KeyT TombstoneKey = getTombstoneKey();
777 for (BucketT *B = OldBuckets, *E = OldBuckets+OldNumBuckets; B != E; ++B) {
778 if (!KeyInfoT::isEqual(B->first, EmptyKey) &&
779 !KeyInfoT::isEqual(B->first, TombstoneKey)) {
780 // Free the value.
781 B->second.~ValueT();
782 }
783 B->first.~KeyT();
784 }
785
786 #ifndef NDEBUG
787 memset(OldBuckets, 0x5a, sizeof(BucketT)*OldNumBuckets);
788 #endif
789 // Free the old table.
790 operator delete(OldBuckets);
791
792 NumEntries = 0;
793 }
794 };
795
796 template<typename KeyT, typename ValueT,
797 typename KeyInfoT, typename ValueInfoT, bool IsConst>
798 class DenseMapIterator {
799 typedef std::pair<KeyT, ValueT> Bucket;
800 typedef DenseMapIterator<KeyT, ValueT,
801 KeyInfoT, ValueInfoT, true> ConstIterator;
802 friend class DenseMapIterator<KeyT, ValueT, KeyInfoT, ValueInfoT, true>;
803 public:
804 typedef ptrdiff_t difference_type;
805 typedef typename conditional<IsConst, const Bucket, Bucket>::type value_type;
806 typedef value_type *pointer;
807 typedef value_type &reference;
808 typedef std::forward_iterator_tag iterator_category;
809 private:
810 pointer Ptr, End;
811 public:
812 DenseMapIterator() : Ptr(0), End(0) {}
813
814 DenseMapIterator(pointer Pos, pointer E) : Ptr(Pos), End(E) {
815 AdvancePastEmptyBuckets();
816 }
817
818 // If IsConst is true this is a converting constructor from iterator to
819 // const_iterator and the default copy constructor is used.
820 // Otherwise this is a copy constructor for iterator.
821 DenseMapIterator(const DenseMapIterator<KeyT, ValueT,
822 KeyInfoT, ValueInfoT, false>& I)
823 : Ptr(I.Ptr), End(I.End) {}
824
825 reference operator*() const {
826 return *Ptr;
827 }
828 pointer operator->() const {
829 return Ptr;
830 }
831
832 bool operator==(const ConstIterator &RHS) const {
833 return Ptr == RHS.operator->();
834 }
835 bool operator!=(const ConstIterator &RHS) const {
836 return Ptr != RHS.operator->();
837 }
838
839 inline DenseMapIterator& operator++() { // Preincrement
840 ++Ptr;
841 AdvancePastEmptyBuckets();
842 return *this;
843 }
844 DenseMapIterator operator++(int) { // Postincrement
845 DenseMapIterator tmp = *this; ++*this; return tmp;
846 }
847
848 private:
849 void AdvancePastEmptyBuckets() {
850 const KeyT Empty = KeyInfoT::getEmptyKey();
851 const KeyT Tombstone = KeyInfoT::getTombstoneKey();
852
853 while (Ptr != End &&
854 (KeyInfoT::isEqual(Ptr->first, Empty) ||
855 KeyInfoT::isEqual(Ptr->first, Tombstone)))
856 ++Ptr;
857 }
858 };
859
860 } // end namespace objc
861
862 #endif