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