8b25a82e6ac69b5d6954a3d4ddd9e394decd4b25
[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 was developed by Chris Lattner and is distributed under
6 // the University of Illinois Open Source 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 DenseMapKeyInfo {
26   //static inline T getEmptyKey();
27   //static inline T getTombstoneKey();
28   //static unsigned getHashValue(const T &Val);
29   //static bool isPod()
30 };
31
32 // Provide DenseMapKeyInfo for all pointers.
33 template<typename T>
34 struct DenseMapKeyInfo<T*> {
35   static inline T* getEmptyKey() { return (T*)-1; }
36   static inline T* getTombstoneKey() { return (T*)-2; }
37   static unsigned getHashValue(const T *PtrVal) {
38     return (unsigned)((uintptr_t)PtrVal >> 4) ^
39            (unsigned)((uintptr_t)PtrVal >> 9);
40   }
41   static bool isPod() { return true; }
42 };
43
44 template<typename KeyT, typename ValueT, 
45          typename KeyInfoT = DenseMapKeyInfo<KeyT> >
46 class DenseMapIterator;
47 template<typename KeyT, typename ValueT,
48          typename KeyInfoT = DenseMapKeyInfo<KeyT> >
49 class DenseMapConstIterator;
50
51 template<typename KeyT, typename ValueT,
52          typename KeyInfoT = DenseMapKeyInfo<KeyT> >
53 class DenseMap {
54   typedef std::pair<KeyT, ValueT> BucketT;
55   unsigned NumBuckets;
56   BucketT *Buckets;
57   
58   unsigned NumEntries;
59   unsigned NumTombstones;
60   DenseMap(const DenseMap &); // not implemented.
61 public:
62   explicit DenseMap(unsigned NumInitBuckets = 64) {
63     init(NumInitBuckets);
64   }
65   ~DenseMap() {
66     const KeyT EmptyKey = getEmptyKey(), TombstoneKey = getTombstoneKey();
67     for (BucketT *P = Buckets, *E = Buckets+NumBuckets; P != E; ++P) {
68       if (P->first != EmptyKey && P->first != TombstoneKey)
69         P->second.~ValueT();
70       P->first.~KeyT();
71     }
72     delete[] (char*)Buckets;
73   }
74   
75   typedef DenseMapIterator<KeyT, ValueT, KeyInfoT> iterator;
76   typedef DenseMapConstIterator<KeyT, ValueT, KeyInfoT> const_iterator;
77   inline iterator begin() {
78      return iterator(Buckets, Buckets+NumBuckets);
79   }
80   inline iterator end() {
81     return iterator(Buckets+NumBuckets, Buckets+NumBuckets);
82   }
83   inline const_iterator begin() const {
84     return const_iterator(Buckets, Buckets+NumBuckets);
85   }
86   inline const_iterator end() const {
87     return const_iterator(Buckets+NumBuckets, Buckets+NumBuckets);
88   }
89   
90   bool empty() const { return NumEntries == 0; }
91   unsigned size() const { return NumEntries; }
92   
93   void clear() {
94     // If the capacity of the array is huge, and the # elements used is small,
95     // shrink the array.
96     if (NumEntries * 4 < NumBuckets && NumBuckets > 64) {
97       shrink_and_clear();
98       return;
99     }
100     
101     const KeyT EmptyKey = getEmptyKey(), TombstoneKey = getTombstoneKey();
102     for (BucketT *P = Buckets, *E = Buckets+NumBuckets; P != E; ++P) {
103       if (P->first != EmptyKey && P->first != TombstoneKey) {
104         P->first = EmptyKey;
105         P->second.~ValueT();
106         --NumEntries;
107       }
108     }
109     assert(NumEntries == 0 && "Node count imbalance!");
110     NumTombstones = 0;
111   }
112
113   /// count - Return true if the specified key is in the map.
114   bool count(const KeyT &Val) const {
115     BucketT *TheBucket;
116     return LookupBucketFor(Val, TheBucket);
117   }
118   
119   iterator find(const KeyT &Val) {
120     BucketT *TheBucket;
121     if (LookupBucketFor(Val, TheBucket))
122       return iterator(TheBucket, Buckets+NumBuckets);
123     return end();
124   }
125   const_iterator find(const KeyT &Val) const {
126     BucketT *TheBucket;
127     if (LookupBucketFor(Val, TheBucket))
128       return const_iterator(TheBucket, Buckets+NumBuckets);
129     return end();
130   }
131   
132   bool insert(const std::pair<KeyT, ValueT> &KV) {
133     BucketT *TheBucket;
134     if (LookupBucketFor(KV.first, TheBucket))
135       return false; // Already in map.
136     
137     // Otherwise, insert the new element.
138     InsertIntoBucket(KV.first, KV.second, TheBucket);
139     return true;
140   }
141   
142   bool erase(const KeyT &Val) {
143     BucketT *TheBucket;
144     if (!LookupBucketFor(Val, TheBucket))
145       return false; // not in map.
146
147     TheBucket->second.~ValueT();
148     TheBucket->first = getTombstoneKey();
149     --NumEntries;
150     ++NumTombstones;
151     return true;
152   }
153   bool erase(iterator I) {
154     BucketT *TheBucket = &*I;
155     TheBucket->second.~ValueT();
156     TheBucket->first = getTombstoneKey();
157     --NumEntries;
158     ++NumTombstones;
159     return true;
160   }
161   
162   ValueT &operator[](const KeyT &Key) {
163     BucketT *TheBucket;
164     if (LookupBucketFor(Key, TheBucket))
165       return TheBucket->second;
166
167     return InsertIntoBucket(Key, ValueT(), TheBucket)->second;
168   }
169   
170 private:
171   BucketT *InsertIntoBucket(const KeyT &Key, const ValueT &Value,
172                             BucketT *TheBucket) {
173     // If the load of the hash table is more than 3/4, or if fewer than 1/8 of
174     // the buckets are empty (meaning that many are filled with tombstones),
175     // grow the table.
176     //
177     // The later case is tricky.  For example, if we had one empty bucket with
178     // tons of tombstones, failing lookups (e.g. for insertion) would have to
179     // probe almost the entire table until it found the empty bucket.  If the
180     // table completely filled with tombstones, no lookup would ever succeed,
181     // causing infinite loops in lookup.
182     if (NumEntries*4 >= NumBuckets*3 ||
183         NumBuckets-(NumEntries+NumTombstones) < NumBuckets/8) {        
184       this->grow();
185       LookupBucketFor(Key, TheBucket);
186     }
187     ++NumEntries;
188     
189     // If we are writing over a tombstone, remember this.
190     if (TheBucket->first != getEmptyKey())
191       --NumTombstones;
192     
193     TheBucket->first = Key;
194     new (&TheBucket->second) ValueT(Value);
195     return TheBucket;
196   }
197
198   static unsigned getHashValue(const KeyT &Val) {
199     return KeyInfoT::getHashValue(Val);
200   }
201   static const KeyT getEmptyKey() {
202     return KeyInfoT::getEmptyKey();
203   }
204   static const KeyT getTombstoneKey() {
205     return KeyInfoT::getTombstoneKey();
206   }
207   
208   /// LookupBucketFor - Lookup the appropriate bucket for Val, returning it in
209   /// FoundBucket.  If the bucket contains the key and a value, this returns
210   /// true, otherwise it returns a bucket with an empty marker or tombstone and
211   /// returns false.
212   bool LookupBucketFor(const KeyT &Val, BucketT *&FoundBucket) const {
213     unsigned BucketNo = getHashValue(Val);
214     unsigned ProbeAmt = 1;
215     BucketT *BucketsPtr = Buckets;
216     
217     // FoundTombstone - Keep track of whether we find a tombstone while probing.
218     BucketT *FoundTombstone = 0;
219     const KeyT EmptyKey = getEmptyKey();
220     const KeyT TombstoneKey = getTombstoneKey();
221     assert(Val != EmptyKey && Val != TombstoneKey &&
222            "Empty/Tombstone value shouldn't be inserted into map!");
223       
224     while (1) {
225       BucketT *ThisBucket = BucketsPtr + (BucketNo & (NumBuckets-1));
226       // Found Val's bucket?  If so, return it.
227       if (ThisBucket->first == Val) {
228         FoundBucket = ThisBucket;
229         return true;
230       }
231       
232       // If we found an empty bucket, the key doesn't exist in the set.
233       // Insert it and return the default value.
234       if (ThisBucket->first == EmptyKey) {
235         // If we've already seen a tombstone while probing, fill it in instead
236         // of the empty bucket we eventually probed to.
237         if (FoundTombstone) ThisBucket = FoundTombstone;
238         FoundBucket = FoundTombstone ? FoundTombstone : ThisBucket;
239         return false;
240       }
241       
242       // If this is a tombstone, remember it.  If Val ends up not in the map, we
243       // prefer to return it than something that would require more probing.
244       if (ThisBucket->first == TombstoneKey && !FoundTombstone)
245         FoundTombstone = ThisBucket;  // Remember the first tombstone found.
246       
247       // Otherwise, it's a hash collision or a tombstone, continue quadratic
248       // probing.
249       BucketNo += ProbeAmt++;
250     }
251   }
252
253   void init(unsigned InitBuckets) {
254     NumEntries = 0;
255     NumTombstones = 0;
256     NumBuckets = InitBuckets;
257     assert(InitBuckets && (InitBuckets & InitBuckets-1) == 0 &&
258            "# initial buckets must be a power of two!");
259     Buckets = (BucketT*)new char[sizeof(BucketT)*InitBuckets];
260     // Initialize all the keys to EmptyKey.
261     const KeyT EmptyKey = getEmptyKey();
262     for (unsigned i = 0; i != InitBuckets; ++i)
263       new (&Buckets[i].first) KeyT(EmptyKey);
264   }
265   
266   void grow() {
267     unsigned OldNumBuckets = NumBuckets;
268     BucketT *OldBuckets = Buckets;
269     
270     // Double the number of buckets.
271     NumBuckets <<= 1;
272     NumTombstones = 0;
273     Buckets = (BucketT*)new char[sizeof(BucketT)*NumBuckets];
274
275     // Initialize all the keys to EmptyKey.
276     const KeyT EmptyKey = getEmptyKey();
277     for (unsigned i = 0, e = NumBuckets; i != e; ++i)
278       new (&Buckets[i].first) KeyT(EmptyKey);
279
280     // Insert all the old elements.
281     const KeyT TombstoneKey = getTombstoneKey();
282     for (BucketT *B = OldBuckets, *E = OldBuckets+OldNumBuckets; B != E; ++B) {
283       if (B->first != EmptyKey && B->first != TombstoneKey) {
284         // Insert the key/value into the new table.
285         BucketT *DestBucket;
286         bool FoundVal = LookupBucketFor(B->first, DestBucket);
287         FoundVal = FoundVal; // silence warning.
288         assert(!FoundVal && "Key already in new map?");
289         DestBucket->first = B->first;
290         new (&DestBucket->second) ValueT(B->second);
291         
292         // Free the value.
293         B->second.~ValueT();
294       }
295       B->first.~KeyT();
296     }
297     
298     // Free the old table.
299     delete[] (char*)OldBuckets;
300   }
301   
302   void shrink_and_clear() {
303     unsigned OldNumBuckets = NumBuckets;
304     BucketT *OldBuckets = Buckets;
305     
306     // Reduce the number of buckets.
307     NumBuckets = NumEntries > 32 ? 1 << (Log2_32_Ceil(NumEntries) + 1)
308                                  : 64;
309     NumTombstones = 0;
310     Buckets = (BucketT*)new char[sizeof(BucketT)*NumBuckets];
311
312     // Initialize all the keys to EmptyKey.
313     const KeyT EmptyKey = getEmptyKey();
314     for (unsigned i = 0, e = NumBuckets; i != e; ++i)
315       new (&Buckets[i].first) KeyT(EmptyKey);
316
317     // Free the old buckets.
318     const KeyT TombstoneKey = getTombstoneKey();
319     for (BucketT *B = OldBuckets, *E = OldBuckets+OldNumBuckets; B != E; ++B) {
320       if (B->first != EmptyKey && B->first != TombstoneKey) {
321         // Free the value.
322         B->second.~ValueT();
323       }
324       B->first.~KeyT();
325     }
326     
327     // Free the old table.
328     delete[] (char*)OldBuckets;
329     
330     NumEntries = 0;
331   }
332 };
333
334 template<typename KeyT, typename ValueT, typename KeyInfoT>
335 class DenseMapIterator {
336   typedef std::pair<KeyT, ValueT> BucketT;
337 protected:
338   const BucketT *Ptr, *End;
339 public:
340   DenseMapIterator(const BucketT *Pos, const BucketT *E) : Ptr(Pos), End(E) {
341     AdvancePastEmptyBuckets();
342   }
343   
344   std::pair<KeyT, ValueT> &operator*() const {
345     return *const_cast<BucketT*>(Ptr);
346   }
347   std::pair<KeyT, ValueT> *operator->() const {
348     return const_cast<BucketT*>(Ptr);
349   }
350   
351   bool operator==(const DenseMapIterator &RHS) const {
352     return Ptr == RHS.Ptr;
353   }
354   bool operator!=(const DenseMapIterator &RHS) const {
355     return Ptr != RHS.Ptr;
356   }
357   
358   inline DenseMapIterator& operator++() {          // Preincrement
359     ++Ptr;
360     AdvancePastEmptyBuckets();
361     return *this;
362   }
363   DenseMapIterator operator++(int) {        // Postincrement
364     DenseMapIterator tmp = *this; ++*this; return tmp;
365   }
366   
367 private:
368   void AdvancePastEmptyBuckets() {
369     const KeyT Empty = KeyInfoT::getEmptyKey();
370     const KeyT Tombstone = KeyInfoT::getTombstoneKey();
371
372     while (Ptr != End && (Ptr->first == Empty || Ptr->first == Tombstone))
373       ++Ptr;
374   }
375 };
376
377 template<typename KeyT, typename ValueT, typename KeyInfoT>
378 class DenseMapConstIterator : public DenseMapIterator<KeyT, ValueT, KeyInfoT> {
379 public:
380   DenseMapConstIterator(const std::pair<KeyT, ValueT> *Pos,
381                         const std::pair<KeyT, ValueT> *E)
382     : DenseMapIterator<KeyT, ValueT, KeyInfoT>(Pos, E) {
383   }
384   const std::pair<KeyT, ValueT> &operator*() const {
385     return *this->Ptr;
386   }
387   const std::pair<KeyT, ValueT> *operator->() const {
388     return this->Ptr;
389   }
390 };
391
392 } // end namespace llvm
393
394 #endif