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