Typo fix.
[oota-llvm.git] / include / llvm / ADT / 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/Support/DataTypes.h"
18 #include "llvm/Support/MathExtras.h"
19 #include <cassert>
20 #include <utility>
21
22 namespace llvm {
23   
24 template<typename T>
25 struct DenseMapInfo {
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);
30   //static bool isPod()
31 };
32
33 // Provide DenseMapInfo for all pointers.
34 template<typename T>
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);
41   }
42   static bool isEqual(const T *LHS, const T *RHS) { return LHS == RHS; }
43   static bool isPod() { return true; }
44 };
45
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) {
53   return LHS == RHS;
54   }
55 };
56
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;
63
64   static inline Pair getEmptyKey() { 
65     return std::make_pair(FirstInfo::getEmptyKey(), 
66                           SecondInfo::getEmptyKey()); 
67   }
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);
74       key += ~(key << 32);
75       key ^= (key >> 22);
76       key += ~(key << 13);
77       key ^= (key >> 8);
78       key += (key << 3);
79       key ^= (key >> 15);
80       key += ~(key << 27);
81       key ^= (key >> 31);
82       return (unsigned)key;
83     }
84     static bool isEqual(const Pair& LHS, const Pair& RHS) { return LHS == RHS; }
85     static bool isPod() { return false; }
86 };
87
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;
96
97 template<typename KeyT, typename ValueT,
98          typename KeyInfoT = DenseMapInfo<KeyT>,
99          typename ValueInfoT = DenseMapInfo<ValueT> >
100 class DenseMap {
101   typedef std::pair<KeyT, ValueT> BucketT;
102   unsigned NumBuckets;
103   BucketT *Buckets;
104   
105   unsigned NumEntries;
106   unsigned NumTombstones;
107 public:
108   typedef KeyT key_type;
109   typedef ValueT mapped_type;
110   typedef BucketT value_type;
111   
112   DenseMap(const DenseMap& other) {
113     NumBuckets = 0;
114     CopyFrom(other);
115   }
116   
117   explicit DenseMap(unsigned NumInitBuckets = 64) {
118     init(NumInitBuckets);
119   }
120   
121   ~DenseMap() {
122     const KeyT EmptyKey = getEmptyKey(), TombstoneKey = getTombstoneKey();
123     for (BucketT *P = Buckets, *E = Buckets+NumBuckets; P != E; ++P) {
124       if (!KeyInfoT::isEqual(P->first, EmptyKey) &&
125           !KeyInfoT::isEqual(P->first, TombstoneKey))
126         P->second.~ValueT();
127       P->first.~KeyT();
128     }
129     operator delete(Buckets);
130   }
131   
132   typedef DenseMapIterator<KeyT, ValueT, KeyInfoT> iterator;
133   typedef DenseMapConstIterator<KeyT, ValueT, KeyInfoT> const_iterator;
134   inline iterator begin() {
135      return iterator(Buckets, Buckets+NumBuckets);
136   }
137   inline iterator end() {
138     return iterator(Buckets+NumBuckets, Buckets+NumBuckets);
139   }
140   inline const_iterator begin() const {
141     return const_iterator(Buckets, Buckets+NumBuckets);
142   }
143   inline const_iterator end() const {
144     return const_iterator(Buckets+NumBuckets, Buckets+NumBuckets);
145   }
146   
147   bool empty() const { return NumEntries == 0; }
148   unsigned size() const { return NumEntries; }
149
150   /// Grow the densemap so that it has at least Size buckets. Does not shrink
151   void resize(size_t Size) { grow(Size); }
152   
153   void clear() {
154     // If the capacity of the array is huge, and the # elements used is small,
155     // shrink the array.
156     if (NumEntries * 4 < NumBuckets && NumBuckets > 64) {
157       shrink_and_clear();
158       return;
159     }
160     
161     const KeyT EmptyKey = getEmptyKey(), TombstoneKey = getTombstoneKey();
162     for (BucketT *P = Buckets, *E = Buckets+NumBuckets; P != E; ++P) {
163       if (!KeyInfoT::isEqual(P->first, EmptyKey)) {
164         if (!KeyInfoT::isEqual(P->first, TombstoneKey)) {
165           P->second.~ValueT();
166           --NumEntries;
167         }
168         P->first = EmptyKey;
169       }
170     }
171     assert(NumEntries == 0 && "Node count imbalance!");
172     NumTombstones = 0;
173   }
174
175   /// count - Return true if the specified key is in the map.
176   bool count(const KeyT &Val) const {
177     BucketT *TheBucket;
178     return LookupBucketFor(Val, TheBucket);
179   }
180   
181   iterator find(const KeyT &Val) {
182     BucketT *TheBucket;
183     if (LookupBucketFor(Val, TheBucket))
184       return iterator(TheBucket, Buckets+NumBuckets);
185     return end();
186   }
187   const_iterator find(const KeyT &Val) const {
188     BucketT *TheBucket;
189     if (LookupBucketFor(Val, TheBucket))
190       return const_iterator(TheBucket, Buckets+NumBuckets);
191     return end();
192   }
193   
194   /// lookup - Return the entry for the specified key, or a default
195   /// constructed value if no such entry exists.
196   ValueT lookup(const KeyT &Val) const {
197     BucketT *TheBucket;
198     if (LookupBucketFor(Val, TheBucket))
199       return TheBucket->second;
200     return ValueT();
201   }
202
203   std::pair<iterator, bool> insert(const std::pair<KeyT, ValueT> &KV) {
204     BucketT *TheBucket;
205     if (LookupBucketFor(KV.first, TheBucket))
206       return std::make_pair(iterator(TheBucket, Buckets+NumBuckets),
207                             false); // Already in map.
208     
209     // Otherwise, insert the new element.
210     TheBucket = InsertIntoBucket(KV.first, KV.second, TheBucket);
211     return std::make_pair(iterator(TheBucket, Buckets+NumBuckets),
212                           true);
213   }
214   
215   bool erase(const KeyT &Val) {
216     BucketT *TheBucket;
217     if (!LookupBucketFor(Val, TheBucket))
218       return false; // not in map.
219
220     TheBucket->second.~ValueT();
221     TheBucket->first = getTombstoneKey();
222     --NumEntries;
223     ++NumTombstones;
224     return true;
225   }
226   bool erase(iterator I) {
227     BucketT *TheBucket = &*I;
228     TheBucket->second.~ValueT();
229     TheBucket->first = getTombstoneKey();
230     --NumEntries;
231     ++NumTombstones;
232     return true;
233   }
234
235   value_type& FindAndConstruct(const KeyT &Key) {
236     BucketT *TheBucket;
237     if (LookupBucketFor(Key, TheBucket))
238       return *TheBucket;
239     
240     return *InsertIntoBucket(Key, ValueT(), TheBucket);
241   }
242   
243   ValueT &operator[](const KeyT &Key) {
244     return FindAndConstruct(Key).second;
245   }
246   
247   DenseMap& operator=(const DenseMap& other) {
248     CopyFrom(other);
249     return *this;
250   }
251   
252 private:
253   void CopyFrom(const DenseMap& other) {
254     if (NumBuckets != 0 && (!KeyInfoT::isPod() || !ValueInfoT::isPod())) {
255       const KeyT EmptyKey = getEmptyKey(), TombstoneKey = getTombstoneKey();
256       for (BucketT *P = Buckets, *E = Buckets+NumBuckets; P != E; ++P) {
257         if (!KeyInfoT::isEqual(P->first, EmptyKey) &&
258             !KeyInfoT::isEqual(P->first, TombstoneKey))
259           P->second.~ValueT();
260         P->first.~KeyT();
261       }
262     }
263     
264     NumEntries = other.NumEntries;
265     NumTombstones = other.NumTombstones;
266     
267     if (NumBuckets)
268       operator delete(Buckets);
269     Buckets = static_cast<BucketT*>(operator new(sizeof(BucketT) *
270                                                  other.NumBuckets));
271     
272     if (KeyInfoT::isPod() && ValueInfoT::isPod())
273       memcpy(Buckets, other.Buckets, other.NumBuckets * sizeof(BucketT));
274     else
275       for (size_t i = 0; i < other.NumBuckets; ++i) {
276         new (&Buckets[i].first) KeyT(other.Buckets[i].first);
277         if (!KeyInfoT::isEqual(Buckets[i].first, getEmptyKey()) &&
278             !KeyInfoT::isEqual(Buckets[i].first, getTombstoneKey()))
279           new (&Buckets[i].second) ValueT(other.Buckets[i].second);
280       }
281     NumBuckets = other.NumBuckets;
282   }
283   
284   BucketT *InsertIntoBucket(const KeyT &Key, const ValueT &Value,
285                             BucketT *TheBucket) {
286     // If the load of the hash table is more than 3/4, or if fewer than 1/8 of
287     // the buckets are empty (meaning that many are filled with tombstones),
288     // grow the table.
289     //
290     // The later case is tricky.  For example, if we had one empty bucket with
291     // tons of tombstones, failing lookups (e.g. for insertion) would have to
292     // probe almost the entire table until it found the empty bucket.  If the
293     // table completely filled with tombstones, no lookup would ever succeed,
294     // causing infinite loops in lookup.
295     if (NumEntries*4 >= NumBuckets*3 ||
296         NumBuckets-(NumEntries+NumTombstones) < NumBuckets/8) {        
297       this->grow(NumBuckets * 2);
298       LookupBucketFor(Key, TheBucket);
299     }
300     ++NumEntries;
301     
302     // If we are writing over a tombstone, remember this.
303     if (!KeyInfoT::isEqual(TheBucket->first, getEmptyKey()))
304       --NumTombstones;
305     
306     TheBucket->first = Key;
307     new (&TheBucket->second) ValueT(Value);
308     return TheBucket;
309   }
310
311   static unsigned getHashValue(const KeyT &Val) {
312     return KeyInfoT::getHashValue(Val);
313   }
314   static const KeyT getEmptyKey() {
315     return KeyInfoT::getEmptyKey();
316   }
317   static const KeyT getTombstoneKey() {
318     return KeyInfoT::getTombstoneKey();
319   }
320   
321   /// LookupBucketFor - Lookup the appropriate bucket for Val, returning it in
322   /// FoundBucket.  If the bucket contains the key and a value, this returns
323   /// true, otherwise it returns a bucket with an empty marker or tombstone and
324   /// returns false.
325   bool LookupBucketFor(const KeyT &Val, BucketT *&FoundBucket) const {
326     unsigned BucketNo = getHashValue(Val);
327     unsigned ProbeAmt = 1;
328     BucketT *BucketsPtr = Buckets;
329     
330     // FoundTombstone - Keep track of whether we find a tombstone while probing.
331     BucketT *FoundTombstone = 0;
332     const KeyT EmptyKey = getEmptyKey();
333     const KeyT TombstoneKey = getTombstoneKey();
334     assert(!KeyInfoT::isEqual(Val, EmptyKey) &&
335            !KeyInfoT::isEqual(Val, TombstoneKey) &&
336            "Empty/Tombstone value shouldn't be inserted into map!");
337       
338     while (1) {
339       BucketT *ThisBucket = BucketsPtr + (BucketNo & (NumBuckets-1));
340       // Found Val's bucket?  If so, return it.
341       if (KeyInfoT::isEqual(ThisBucket->first, Val)) {
342         FoundBucket = ThisBucket;
343         return true;
344       }
345       
346       // If we found an empty bucket, the key doesn't exist in the set.
347       // Insert it and return the default value.
348       if (KeyInfoT::isEqual(ThisBucket->first, EmptyKey)) {
349         // If we've already seen a tombstone while probing, fill it in instead
350         // of the empty bucket we eventually probed to.
351         if (FoundTombstone) ThisBucket = FoundTombstone;
352         FoundBucket = FoundTombstone ? FoundTombstone : ThisBucket;
353         return false;
354       }
355       
356       // If this is a tombstone, remember it.  If Val ends up not in the map, we
357       // prefer to return it than something that would require more probing.
358       if (KeyInfoT::isEqual(ThisBucket->first, TombstoneKey) && !FoundTombstone)
359         FoundTombstone = ThisBucket;  // Remember the first tombstone found.
360       
361       // Otherwise, it's a hash collision or a tombstone, continue quadratic
362       // probing.
363       BucketNo += ProbeAmt++;
364     }
365   }
366
367   void init(unsigned InitBuckets) {
368     NumEntries = 0;
369     NumTombstones = 0;
370     NumBuckets = InitBuckets;
371     assert(InitBuckets && (InitBuckets & (InitBuckets-1)) == 0 &&
372            "# initial buckets must be a power of two!");
373     Buckets = static_cast<BucketT*>(operator new(sizeof(BucketT)*InitBuckets));
374     // Initialize all the keys to EmptyKey.
375     const KeyT EmptyKey = getEmptyKey();
376     for (unsigned i = 0; i != InitBuckets; ++i)
377       new (&Buckets[i].first) KeyT(EmptyKey);
378   }
379   
380   void grow(unsigned AtLeast) {
381     unsigned OldNumBuckets = NumBuckets;
382     BucketT *OldBuckets = Buckets;
383     
384     // Double the number of buckets.
385     while (NumBuckets <= AtLeast)
386       NumBuckets <<= 1;
387     NumTombstones = 0;
388     Buckets = static_cast<BucketT*>(operator new(sizeof(BucketT)*NumBuckets));
389
390     // Initialize all the keys to EmptyKey.
391     const KeyT EmptyKey = getEmptyKey();
392     for (unsigned i = 0, e = NumBuckets; i != e; ++i)
393       new (&Buckets[i].first) KeyT(EmptyKey);
394
395     // Insert all the old elements.
396     const KeyT TombstoneKey = getTombstoneKey();
397     for (BucketT *B = OldBuckets, *E = OldBuckets+OldNumBuckets; B != E; ++B) {
398       if (!KeyInfoT::isEqual(B->first, EmptyKey) &&
399           !KeyInfoT::isEqual(B->first, TombstoneKey)) {
400         // Insert the key/value into the new table.
401         BucketT *DestBucket;
402         bool FoundVal = LookupBucketFor(B->first, DestBucket);
403         FoundVal = FoundVal; // silence warning.
404         assert(!FoundVal && "Key already in new map?");
405         DestBucket->first = B->first;
406         new (&DestBucket->second) ValueT(B->second);
407         
408         // Free the value.
409         B->second.~ValueT();
410       }
411       B->first.~KeyT();
412     }
413     
414     // Free the old table.
415     operator delete(OldBuckets);
416   }
417   
418   void shrink_and_clear() {
419     unsigned OldNumBuckets = NumBuckets;
420     BucketT *OldBuckets = Buckets;
421     
422     // Reduce the number of buckets.
423     NumBuckets = NumEntries > 32 ? 1 << (Log2_32_Ceil(NumEntries) + 1)
424                                  : 64;
425     NumTombstones = 0;
426     Buckets = static_cast<BucketT*>(operator new(sizeof(BucketT)*NumBuckets));
427
428     // Initialize all the keys to EmptyKey.
429     const KeyT EmptyKey = getEmptyKey();
430     for (unsigned i = 0, e = NumBuckets; i != e; ++i)
431       new (&Buckets[i].first) KeyT(EmptyKey);
432
433     // Free the old buckets.
434     const KeyT TombstoneKey = getTombstoneKey();
435     for (BucketT *B = OldBuckets, *E = OldBuckets+OldNumBuckets; B != E; ++B) {
436       if (!KeyInfoT::isEqual(B->first, EmptyKey) &&
437           !KeyInfoT::isEqual(B->first, TombstoneKey)) {
438         // Free the value.
439         B->second.~ValueT();
440       }
441       B->first.~KeyT();
442     }
443     
444     // Free the old table.
445     operator delete(OldBuckets);
446     
447     NumEntries = 0;
448   }
449 };
450
451 template<typename KeyT, typename ValueT, typename KeyInfoT, typename ValueInfoT>
452 class DenseMapIterator {
453   typedef std::pair<KeyT, ValueT> BucketT;
454 protected:
455   const BucketT *Ptr, *End;
456 public:
457   DenseMapIterator(void) : Ptr(0), End(0) {}
458
459   DenseMapIterator(const BucketT *Pos, const BucketT *E) : Ptr(Pos), End(E) {
460     AdvancePastEmptyBuckets();
461   }
462   
463   std::pair<KeyT, ValueT> &operator*() const {
464     return *const_cast<BucketT*>(Ptr);
465   }
466   std::pair<KeyT, ValueT> *operator->() const {
467     return const_cast<BucketT*>(Ptr);
468   }
469   
470   bool operator==(const DenseMapIterator &RHS) const {
471     return Ptr == RHS.Ptr;
472   }
473   bool operator!=(const DenseMapIterator &RHS) const {
474     return Ptr != RHS.Ptr;
475   }
476   
477   inline DenseMapIterator& operator++() {          // Preincrement
478     ++Ptr;
479     AdvancePastEmptyBuckets();
480     return *this;
481   }
482   DenseMapIterator operator++(int) {        // Postincrement
483     DenseMapIterator tmp = *this; ++*this; return tmp;
484   }
485   
486 private:
487   void AdvancePastEmptyBuckets() {
488     const KeyT Empty = KeyInfoT::getEmptyKey();
489     const KeyT Tombstone = KeyInfoT::getTombstoneKey();
490
491     while (Ptr != End && 
492            (KeyInfoT::isEqual(Ptr->first, Empty) ||
493             KeyInfoT::isEqual(Ptr->first, Tombstone)))
494       ++Ptr;
495   }
496 };
497
498 template<typename KeyT, typename ValueT, typename KeyInfoT, typename ValueInfoT>
499 class DenseMapConstIterator : public DenseMapIterator<KeyT, ValueT, KeyInfoT> {
500 public:
501   DenseMapConstIterator(void) : DenseMapIterator<KeyT, ValueT, KeyInfoT>() {}
502   DenseMapConstIterator(const std::pair<KeyT, ValueT> *Pos,
503                         const std::pair<KeyT, ValueT> *E)
504     : DenseMapIterator<KeyT, ValueT, KeyInfoT>(Pos, E) {
505   }
506   const std::pair<KeyT, ValueT> &operator*() const {
507     return *this->Ptr;
508   }
509   const std::pair<KeyT, ValueT> *operator->() const {
510     return this->Ptr;
511   }
512 };
513
514 } // end namespace llvm
515
516 #endif