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