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