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