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