5d1ad7546e21272ebf7d2a82121b31c4d848347c
[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 <cassert>
19 #include <utility>
20
21 namespace llvm {
22   
23 template<typename T>
24 struct DenseMapKeyInfo {
25   //static inline T getEmptyKey();
26   //static inline T getTombstoneKey();
27   //static unsigned getHashValue(const T &Val);
28   //static bool isPod()
29 };
30
31 template<typename T>
32 struct DenseMapKeyInfo<T*> {
33   static inline T* getEmptyKey() { return (T*)-1; }
34   static inline T* getTombstoneKey() { return (T*)-2; }
35   static unsigned getHashValue(const T *PtrVal) {
36     return (unsigned)((uintptr_t)PtrVal >> 4) ^
37            (unsigned)((uintptr_t)PtrVal >> 9);
38   }
39   static bool isPod() { return true; }
40 };
41
42 template<typename KeyT, typename ValueT>
43 class DenseMapIterator;
44 template<typename KeyT, typename ValueT>
45 class DenseMapConstIterator;
46
47 template<typename KeyT, typename ValueT>
48 class DenseMap {
49   typedef std::pair<KeyT, ValueT> BucketT;
50   unsigned NumBuckets;
51   BucketT *Buckets;
52   
53   unsigned NumEntries;
54   DenseMap(const DenseMap &); // not implemented.
55 public:
56   explicit DenseMap(unsigned NumInitBuckets = 64) {
57     init(NumInitBuckets);
58   }
59   ~DenseMap() {
60     const KeyT EmptyKey = getEmptyKey(), TombstoneKey = getTombstoneKey();
61     for (BucketT *P = Buckets, *E = Buckets+NumBuckets; P != E; ++P) {
62       if (P->first != EmptyKey && P->first != TombstoneKey)
63         P->second.~ValueT();
64       P->first.~KeyT();
65     }
66     delete[] (char*)Buckets;
67   }
68   
69   typedef DenseMapIterator<KeyT, ValueT> iterator;
70   typedef DenseMapConstIterator<KeyT, ValueT> const_iterator;
71   inline iterator begin() {
72      return DenseMapIterator<KeyT, ValueT>(Buckets, Buckets+NumBuckets);
73   }
74   inline iterator end() {
75     return DenseMapIterator<KeyT, ValueT>(Buckets+NumBuckets, 
76                                           Buckets+NumBuckets);
77   }
78   inline const_iterator begin() const {
79     return DenseMapConstIterator<KeyT, ValueT>(Buckets, Buckets+NumBuckets);
80   }
81   inline const_iterator end() const {
82     return DenseMapConstIterator<KeyT, ValueT>(Buckets+NumBuckets, 
83                                                Buckets+NumBuckets);
84   }
85   
86   bool empty() const { return NumEntries == 0; }
87   unsigned size() const { return NumEntries; }
88   
89   void clear() {
90     const KeyT EmptyKey = getEmptyKey(), TombstoneKey = getTombstoneKey();
91     for (BucketT *P = Buckets, *E = Buckets+NumBuckets; P != E; ++P) {
92       if (P->first != EmptyKey && P->first != TombstoneKey) {
93         P->first = EmptyKey;
94         P->second.~ValueT();
95         --NumEntries;
96       }
97     }
98     assert(NumEntries == 0 && "Node count imbalance!");
99   }
100   
101   /// count - Return true if the specified key is in the map.
102   bool count(const KeyT &Val) const {
103     BucketT *TheBucket;
104     return LookupBucketFor(Val, TheBucket);
105   }
106   
107   iterator find(const KeyT &Val) const {
108     BucketT *TheBucket;
109     if (LookupBucketFor(Val, TheBucket))
110       return iterator(TheBucket, Buckets+NumBuckets);
111     return end();
112   }
113   
114   bool insert(const std::pair<KeyT, ValueT> &KV) {
115     BucketT *TheBucket;
116     if (LookupBucketFor(KV.first, TheBucket))
117       return false; // Already in map.
118     
119     // Otherwise, insert the new element.
120     InsertIntoBucket(KV.first, KV.second, TheBucket);
121     return true;
122   }
123   
124   bool erase(const KeyT &Val) {
125     BucketT *TheBucket;
126     if (!LookupBucketFor(Val, TheBucket))
127       return false; // not in map.
128
129     TheBucket->second.~ValueT();
130     TheBucket->first = getTombstoneKey();
131     --NumEntries;
132     return true;
133   }
134   bool erase(iterator I) {
135     BucketT *TheBucket = &*I;
136     TheBucket->second.~ValueT();
137     TheBucket->first = getTombstoneKey();
138     --NumEntries;
139     return true;
140   }
141   
142   ValueT &operator[](const KeyT &Key) {
143     BucketT *TheBucket;
144     if (LookupBucketFor(Key, TheBucket))
145       return TheBucket->second;
146
147     return InsertIntoBucket(Key, ValueT(), TheBucket)->second;
148   }
149   
150 private:
151   BucketT *InsertIntoBucket(const KeyT &Key, const ValueT &Value,
152                             BucketT *TheBucket) {
153     // If the load of the hash table is more than 3/4, grow it.
154     if (NumEntries*4 >= NumBuckets*3) {
155       this->grow();
156       LookupBucketFor(Key, TheBucket);
157     }
158     ++NumEntries;
159     TheBucket->first = Key;
160     new (&TheBucket->second) ValueT(Value);
161     return TheBucket;
162   }
163
164   static unsigned getHashValue(const KeyT &Val) {
165     return DenseMapKeyInfo<KeyT>::getHashValue(Val);
166   }
167   static const KeyT getEmptyKey() {
168     return DenseMapKeyInfo<KeyT>::getEmptyKey();
169   }
170   static const KeyT getTombstoneKey() {
171     return DenseMapKeyInfo<KeyT>::getTombstoneKey();
172   }
173   
174   /// LookupBucketFor - Lookup the appropriate bucket for Val, returning it in
175   /// FoundBucket.  If the bucket contains the key and a value, this returns
176   /// true, otherwise it returns a bucket with an empty marker or tombstone and
177   /// returns false.
178   bool LookupBucketFor(const KeyT &Val, BucketT *&FoundBucket) const {
179     unsigned BucketNo = getHashValue(Val);
180     unsigned ProbeAmt = 1;
181     BucketT *BucketsPtr = Buckets;
182     
183     // FoundTombstone - Keep track of whether we find a tombstone while probing.
184     BucketT *FoundTombstone = 0;
185     const KeyT EmptyKey = getEmptyKey();
186     const KeyT TombstoneKey = getTombstoneKey();
187     assert(Val != EmptyKey && Val != TombstoneKey &&
188            "Empty/Tombstone value shouldn't be inserted into map!");
189       
190     while (1) {
191       BucketT *ThisBucket = BucketsPtr + (BucketNo & (NumBuckets-1));
192       // Found Val's bucket?  If so, return it.
193       if (ThisBucket->first == Val) {
194         FoundBucket = ThisBucket;
195         return true;
196       }
197       
198       // If we found an empty bucket, the key doesn't exist in the set.
199       // Insert it and return the default value.
200       if (ThisBucket->first == EmptyKey) {
201         // If we've already seen a tombstone while probing, fill it in instead
202         // of the empty bucket we eventually probed to.
203         if (FoundTombstone) ThisBucket = FoundTombstone;
204         FoundBucket = FoundTombstone ? FoundTombstone : ThisBucket;
205         return false;
206       }
207       
208       // If this is a tombstone, remember it.  If Val ends up not in the map, we
209       // prefer to return it than something that would require more probing.
210       if (ThisBucket->first == TombstoneKey && !FoundTombstone)
211         FoundTombstone = ThisBucket;  // Remember the first tombstone found.
212       
213       // Otherwise, it's a hash collision or a tombstone, continue quadratic
214       // probing.
215       BucketNo += ProbeAmt++;
216     }
217   }
218
219   void init(unsigned InitBuckets) {
220     NumEntries = 0;
221     NumBuckets = InitBuckets;
222     assert(InitBuckets && (InitBuckets & InitBuckets-1) == 0 &&
223            "# initial buckets must be a power of two!");
224     Buckets = (BucketT*)new char[sizeof(BucketT)*InitBuckets];
225     // Initialize all the keys to EmptyKey.
226     const KeyT EmptyKey = getEmptyKey();
227     for (unsigned i = 0; i != InitBuckets; ++i)
228       new (&Buckets[i].first) KeyT(EmptyKey);
229   }
230   
231   void grow() {
232     unsigned OldNumBuckets = NumBuckets;
233     BucketT *OldBuckets = Buckets;
234     
235     // Double the number of buckets.
236     NumBuckets <<= 1;
237     Buckets = (BucketT*)new char[sizeof(BucketT)*NumBuckets];
238
239     // Initialize all the keys to EmptyKey.
240     const KeyT EmptyKey = getEmptyKey();
241     for (unsigned i = 0, e = NumBuckets; i != e; ++i)
242       new (&Buckets[i].first) KeyT(EmptyKey);
243
244     // Insert all the old elements.
245     const KeyT TombstoneKey = getTombstoneKey();
246     for (BucketT *B = OldBuckets, *E = OldBuckets+OldNumBuckets; B != E; ++B) {
247       if (B->first != EmptyKey && B->first != TombstoneKey) {
248         // Insert the key/value into the new table.
249         BucketT *DestBucket;
250         bool FoundVal = LookupBucketFor(B->first, DestBucket);
251         FoundVal = FoundVal; // silence warning.
252         assert(!FoundVal && "Key already in new map?");
253         DestBucket->first = B->first;
254         new (&DestBucket->second) ValueT(B->second);
255         
256         // Free the value.
257         B->second.~ValueT();
258       }
259       B->first.~KeyT();
260     }
261     
262     // Free the old table.
263     delete[] (char*)OldBuckets;
264   }
265 };
266
267 template<typename KeyT, typename ValueT>
268 class DenseMapIterator {
269   typedef std::pair<KeyT, ValueT> BucketT;
270 protected:
271   const BucketT *Ptr, *End;
272 public:
273   DenseMapIterator(const BucketT *Pos, const BucketT *E) : Ptr(Pos), End(E) {
274     AdvancePastEmptyBuckets();
275   }
276   
277   std::pair<KeyT, ValueT> &operator*() const {
278     return *const_cast<BucketT*>(Ptr);
279   }
280   std::pair<KeyT, ValueT> *operator->() const {
281     return const_cast<BucketT*>(Ptr);
282   }
283   
284   bool operator==(const DenseMapIterator &RHS) const {
285     return Ptr == RHS.Ptr;
286   }
287   bool operator!=(const DenseMapIterator &RHS) const {
288     return Ptr != RHS.Ptr;
289   }
290   
291   inline DenseMapIterator& operator++() {          // Preincrement
292     ++Ptr;
293     AdvancePastEmptyBuckets();
294     return *this;
295   }
296   DenseMapIterator operator++(int) {        // Postincrement
297     DenseMapIterator tmp = *this; ++*this; return tmp;
298   }
299   
300 private:
301   void AdvancePastEmptyBuckets() {
302     const KeyT Empty = DenseMapKeyInfo<KeyT>::getEmptyKey();
303     const KeyT Tombstone = DenseMapKeyInfo<KeyT>::getTombstoneKey();
304
305     while (Ptr != End && (Ptr->first == Empty || Ptr->first == Tombstone))
306       ++Ptr;
307   }
308 };
309
310 template<typename KeyT, typename ValueT>
311 class DenseMapConstIterator : public DenseMapIterator<KeyT, ValueT> {
312 public:
313   DenseMapConstIterator(const std::pair<KeyT, ValueT> *Pos,
314                         const std::pair<KeyT, ValueT> *E)
315     : DenseMapIterator<KeyT, ValueT>(Pos, E) {
316   }
317   const std::pair<KeyT, ValueT> &operator*() const {
318     return *this->Ptr;
319   }
320   const std::pair<KeyT, ValueT> *operator->() const {
321     return this->Ptr;
322   }
323 };
324
325 } // end namespace llvm
326
327 #endif