443a620d1af0a44396ce0fd3744bb56758bfc0bd
[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/ADT/DenseMapInfo.h"
18 #include "llvm/ADT/EpochTracker.h"
19 #include "llvm/Support/AlignOf.h"
20 #include "llvm/Support/Compiler.h"
21 #include "llvm/Support/MathExtras.h"
22 #include "llvm/Support/PointerLikeTypeTraits.h"
23 #include "llvm/Support/type_traits.h"
24 #include <algorithm>
25 #include <cassert>
26 #include <climits>
27 #include <cstddef>
28 #include <cstring>
29 #include <iterator>
30 #include <new>
31 #include <utility>
32
33 namespace llvm {
34
35 namespace detail {
36 // We extend a pair to allow users to override the bucket type with their own
37 // implementation without requiring two members.
38 template <typename KeyT, typename ValueT>
39 struct DenseMapPair : public std::pair<KeyT, ValueT> {
40   KeyT &getFirst() { return std::pair<KeyT, ValueT>::first; }
41   const KeyT &getFirst() const { return std::pair<KeyT, ValueT>::first; }
42   ValueT &getSecond() { return std::pair<KeyT, ValueT>::second; }
43   const ValueT &getSecond() const { return std::pair<KeyT, ValueT>::second; }
44 };
45 }
46
47 template <
48     typename KeyT, typename ValueT, typename KeyInfoT = DenseMapInfo<KeyT>,
49     typename Bucket = detail::DenseMapPair<KeyT, ValueT>, bool IsConst = false>
50 class DenseMapIterator;
51
52 template <typename DerivedT, typename KeyT, typename ValueT, typename KeyInfoT,
53           typename BucketT>
54 class DenseMapBase : public DebugEpochBase {
55 public:
56   typedef unsigned size_type;
57   typedef KeyT key_type;
58   typedef ValueT mapped_type;
59   typedef BucketT value_type;
60
61   typedef DenseMapIterator<KeyT, ValueT, KeyInfoT, BucketT> iterator;
62   typedef DenseMapIterator<KeyT, ValueT, KeyInfoT, BucketT, true>
63       const_iterator;
64   inline iterator begin() {
65     // When the map is empty, avoid the overhead of AdvancePastEmptyBuckets().
66     return empty() ? end() : iterator(getBuckets(), getBucketsEnd(), *this);
67   }
68   inline iterator end() {
69     return iterator(getBucketsEnd(), getBucketsEnd(), *this, true);
70   }
71   inline const_iterator begin() const {
72     return empty() ? end()
73                    : const_iterator(getBuckets(), getBucketsEnd(), *this);
74   }
75   inline const_iterator end() const {
76     return const_iterator(getBucketsEnd(), getBucketsEnd(), *this, true);
77   }
78
79   bool LLVM_ATTRIBUTE_UNUSED_RESULT empty() const {
80     return getNumEntries() == 0;
81   }
82   unsigned size() const { return getNumEntries(); }
83
84   /// Grow the densemap so that it has at least Size buckets. Does not shrink
85   void resize(size_type Size) {
86     incrementEpoch();
87     if (Size > getNumBuckets())
88       grow(Size);
89   }
90
91   void clear() {
92     incrementEpoch();
93     if (getNumEntries() == 0 && getNumTombstones() == 0) return;
94
95     // If the capacity of the array is huge, and the # elements used is small,
96     // shrink the array.
97     if (getNumEntries() * 4 < getNumBuckets() && getNumBuckets() > 64) {
98       shrink_and_clear();
99       return;
100     }
101
102     const KeyT EmptyKey = getEmptyKey(), TombstoneKey = getTombstoneKey();
103     for (BucketT *P = getBuckets(), *E = getBucketsEnd(); P != E; ++P) {
104       if (!KeyInfoT::isEqual(P->getFirst(), EmptyKey)) {
105         if (!KeyInfoT::isEqual(P->getFirst(), TombstoneKey)) {
106           P->getSecond().~ValueT();
107           decrementNumEntries();
108         }
109         P->getFirst() = EmptyKey;
110       }
111     }
112     assert(getNumEntries() == 0 && "Node count imbalance!");
113     setNumTombstones(0);
114   }
115
116   /// Return 1 if the specified key is in the map, 0 otherwise.
117   size_type count(const KeyT &Val) const {
118     const BucketT *TheBucket;
119     return LookupBucketFor(Val, TheBucket) ? 1 : 0;
120   }
121
122   iterator find(const KeyT &Val) {
123     BucketT *TheBucket;
124     if (LookupBucketFor(Val, TheBucket))
125       return iterator(TheBucket, getBucketsEnd(), *this, true);
126     return end();
127   }
128   const_iterator find(const KeyT &Val) const {
129     const BucketT *TheBucket;
130     if (LookupBucketFor(Val, TheBucket))
131       return const_iterator(TheBucket, getBucketsEnd(), *this, true);
132     return end();
133   }
134
135   /// Alternate version of find() which allows a different, and possibly
136   /// less expensive, key type.
137   /// The DenseMapInfo is responsible for supplying methods
138   /// getHashValue(LookupKeyT) and isEqual(LookupKeyT, KeyT) for each key
139   /// type used.
140   template<class LookupKeyT>
141   iterator find_as(const LookupKeyT &Val) {
142     BucketT *TheBucket;
143     if (LookupBucketFor(Val, TheBucket))
144       return iterator(TheBucket, getBucketsEnd(), *this, true);
145     return end();
146   }
147   template<class LookupKeyT>
148   const_iterator find_as(const LookupKeyT &Val) const {
149     const BucketT *TheBucket;
150     if (LookupBucketFor(Val, TheBucket))
151       return const_iterator(TheBucket, getBucketsEnd(), *this, true);
152     return end();
153   }
154
155   /// lookup - Return the entry for the specified key, or a default
156   /// constructed value if no such entry exists.
157   ValueT lookup(const KeyT &Val) const {
158     const BucketT *TheBucket;
159     if (LookupBucketFor(Val, TheBucket))
160       return TheBucket->getSecond();
161     return ValueT();
162   }
163
164   // Inserts key,value pair into the map if the key isn't already in the map.
165   // If the key is already in the map, it returns false and doesn't update the
166   // value.
167   std::pair<iterator, bool> insert(const std::pair<KeyT, ValueT> &KV) {
168     BucketT *TheBucket;
169     if (LookupBucketFor(KV.first, TheBucket))
170       return std::make_pair(iterator(TheBucket, getBucketsEnd(), *this, true),
171                             false); // Already in map.
172
173     // Otherwise, insert the new element.
174     TheBucket = InsertIntoBucket(KV.first, KV.second, TheBucket);
175     return std::make_pair(iterator(TheBucket, getBucketsEnd(), *this, true),
176                           true);
177   }
178
179   // Inserts key,value pair into the map if the key isn't already in the map.
180   // If the key is already in the map, it returns false and doesn't update the
181   // value.
182   std::pair<iterator, bool> insert(std::pair<KeyT, ValueT> &&KV) {
183     BucketT *TheBucket;
184     if (LookupBucketFor(KV.first, TheBucket))
185       return std::make_pair(iterator(TheBucket, getBucketsEnd(), *this, true),
186                             false); // Already in map.
187
188     // Otherwise, insert the new element.
189     TheBucket = InsertIntoBucket(std::move(KV.first),
190                                  std::move(KV.second),
191                                  TheBucket);
192     return std::make_pair(iterator(TheBucket, getBucketsEnd(), *this, true),
193                           true);
194   }
195
196   /// insert - Range insertion of pairs.
197   template<typename InputIt>
198   void insert(InputIt I, InputIt E) {
199     for (; I != E; ++I)
200       insert(*I);
201   }
202
203
204   bool erase(const KeyT &Val) {
205     BucketT *TheBucket;
206     if (!LookupBucketFor(Val, TheBucket))
207       return false; // not in map.
208
209     TheBucket->getSecond().~ValueT();
210     TheBucket->getFirst() = getTombstoneKey();
211     decrementNumEntries();
212     incrementNumTombstones();
213     return true;
214   }
215   void erase(iterator I) {
216     BucketT *TheBucket = &*I;
217     TheBucket->getSecond().~ValueT();
218     TheBucket->getFirst() = getTombstoneKey();
219     decrementNumEntries();
220     incrementNumTombstones();
221   }
222
223   value_type& FindAndConstruct(const KeyT &Key) {
224     BucketT *TheBucket;
225     if (LookupBucketFor(Key, TheBucket))
226       return *TheBucket;
227
228     return *InsertIntoBucket(Key, ValueT(), TheBucket);
229   }
230
231   ValueT &operator[](const KeyT &Key) {
232     return FindAndConstruct(Key).second;
233   }
234
235   value_type& FindAndConstruct(KeyT &&Key) {
236     BucketT *TheBucket;
237     if (LookupBucketFor(Key, TheBucket))
238       return *TheBucket;
239
240     return *InsertIntoBucket(std::move(Key), ValueT(), TheBucket);
241   }
242
243   ValueT &operator[](KeyT &&Key) {
244     return FindAndConstruct(std::move(Key)).second;
245   }
246
247   /// isPointerIntoBucketsArray - Return true if the specified pointer points
248   /// somewhere into the DenseMap's array of buckets (i.e. either to a key or
249   /// value in the DenseMap).
250   bool isPointerIntoBucketsArray(const void *Ptr) const {
251     return Ptr >= getBuckets() && Ptr < getBucketsEnd();
252   }
253
254   /// getPointerIntoBucketsArray() - Return an opaque pointer into the buckets
255   /// array.  In conjunction with the previous method, this can be used to
256   /// determine whether an insertion caused the DenseMap to reallocate.
257   const void *getPointerIntoBucketsArray() const { return getBuckets(); }
258
259 protected:
260   DenseMapBase() {}
261
262   void destroyAll() {
263     if (getNumBuckets() == 0) // Nothing to do.
264       return;
265
266     const KeyT EmptyKey = getEmptyKey(), TombstoneKey = getTombstoneKey();
267     for (BucketT *P = getBuckets(), *E = getBucketsEnd(); P != E; ++P) {
268       if (!KeyInfoT::isEqual(P->getFirst(), EmptyKey) &&
269           !KeyInfoT::isEqual(P->getFirst(), TombstoneKey))
270         P->getSecond().~ValueT();
271       P->getFirst().~KeyT();
272     }
273
274 #ifndef NDEBUG
275     memset((void*)getBuckets(), 0x5a, sizeof(BucketT)*getNumBuckets());
276 #endif
277   }
278
279   void initEmpty() {
280     setNumEntries(0);
281     setNumTombstones(0);
282
283     assert((getNumBuckets() & (getNumBuckets()-1)) == 0 &&
284            "# initial buckets must be a power of two!");
285     const KeyT EmptyKey = getEmptyKey();
286     for (BucketT *B = getBuckets(), *E = getBucketsEnd(); B != E; ++B)
287       new (&B->getFirst()) KeyT(EmptyKey);
288   }
289
290   void moveFromOldBuckets(BucketT *OldBucketsBegin, BucketT *OldBucketsEnd) {
291     initEmpty();
292
293     // Insert all the old elements.
294     const KeyT EmptyKey = getEmptyKey();
295     const KeyT TombstoneKey = getTombstoneKey();
296     for (BucketT *B = OldBucketsBegin, *E = OldBucketsEnd; B != E; ++B) {
297       if (!KeyInfoT::isEqual(B->getFirst(), EmptyKey) &&
298           !KeyInfoT::isEqual(B->getFirst(), TombstoneKey)) {
299         // Insert the key/value into the new table.
300         BucketT *DestBucket;
301         bool FoundVal = LookupBucketFor(B->getFirst(), DestBucket);
302         (void)FoundVal; // silence warning.
303         assert(!FoundVal && "Key already in new map?");
304         DestBucket->getFirst() = std::move(B->getFirst());
305         new (&DestBucket->getSecond()) ValueT(std::move(B->getSecond()));
306         incrementNumEntries();
307
308         // Free the value.
309         B->getSecond().~ValueT();
310       }
311       B->getFirst().~KeyT();
312     }
313
314 #ifndef NDEBUG
315     if (OldBucketsBegin != OldBucketsEnd)
316       memset((void*)OldBucketsBegin, 0x5a,
317              sizeof(BucketT) * (OldBucketsEnd - OldBucketsBegin));
318 #endif
319   }
320
321   template <typename OtherBaseT>
322   void copyFrom(
323       const DenseMapBase<OtherBaseT, KeyT, ValueT, KeyInfoT, BucketT> &other) {
324     assert(&other != this);
325     assert(getNumBuckets() == other.getNumBuckets());
326
327     setNumEntries(other.getNumEntries());
328     setNumTombstones(other.getNumTombstones());
329
330     if (isPodLike<KeyT>::value && isPodLike<ValueT>::value)
331       memcpy(getBuckets(), other.getBuckets(),
332              getNumBuckets() * sizeof(BucketT));
333     else
334       for (size_t i = 0; i < getNumBuckets(); ++i) {
335         new (&getBuckets()[i].getFirst())
336             KeyT(other.getBuckets()[i].getFirst());
337         if (!KeyInfoT::isEqual(getBuckets()[i].getFirst(), getEmptyKey()) &&
338             !KeyInfoT::isEqual(getBuckets()[i].getFirst(), getTombstoneKey()))
339           new (&getBuckets()[i].getSecond())
340               ValueT(other.getBuckets()[i].getSecond());
341       }
342   }
343
344   static unsigned getHashValue(const KeyT &Val) {
345     return KeyInfoT::getHashValue(Val);
346   }
347   template<typename LookupKeyT>
348   static unsigned getHashValue(const LookupKeyT &Val) {
349     return KeyInfoT::getHashValue(Val);
350   }
351   static const KeyT getEmptyKey() {
352     return KeyInfoT::getEmptyKey();
353   }
354   static const KeyT getTombstoneKey() {
355     return KeyInfoT::getTombstoneKey();
356   }
357
358 private:
359   unsigned getNumEntries() const {
360     return static_cast<const DerivedT *>(this)->getNumEntries();
361   }
362   void setNumEntries(unsigned Num) {
363     static_cast<DerivedT *>(this)->setNumEntries(Num);
364   }
365   void incrementNumEntries() {
366     setNumEntries(getNumEntries() + 1);
367   }
368   void decrementNumEntries() {
369     setNumEntries(getNumEntries() - 1);
370   }
371   unsigned getNumTombstones() const {
372     return static_cast<const DerivedT *>(this)->getNumTombstones();
373   }
374   void setNumTombstones(unsigned Num) {
375     static_cast<DerivedT *>(this)->setNumTombstones(Num);
376   }
377   void incrementNumTombstones() {
378     setNumTombstones(getNumTombstones() + 1);
379   }
380   void decrementNumTombstones() {
381     setNumTombstones(getNumTombstones() - 1);
382   }
383   const BucketT *getBuckets() const {
384     return static_cast<const DerivedT *>(this)->getBuckets();
385   }
386   BucketT *getBuckets() {
387     return static_cast<DerivedT *>(this)->getBuckets();
388   }
389   unsigned getNumBuckets() const {
390     return static_cast<const DerivedT *>(this)->getNumBuckets();
391   }
392   BucketT *getBucketsEnd() {
393     return getBuckets() + getNumBuckets();
394   }
395   const BucketT *getBucketsEnd() const {
396     return getBuckets() + getNumBuckets();
397   }
398
399   void grow(unsigned AtLeast) {
400     static_cast<DerivedT *>(this)->grow(AtLeast);
401   }
402
403   void shrink_and_clear() {
404     static_cast<DerivedT *>(this)->shrink_and_clear();
405   }
406
407
408   BucketT *InsertIntoBucket(const KeyT &Key, const ValueT &Value,
409                             BucketT *TheBucket) {
410     TheBucket = InsertIntoBucketImpl(Key, TheBucket);
411
412     TheBucket->getFirst() = Key;
413     new (&TheBucket->getSecond()) ValueT(Value);
414     return TheBucket;
415   }
416
417   BucketT *InsertIntoBucket(const KeyT &Key, ValueT &&Value,
418                             BucketT *TheBucket) {
419     TheBucket = InsertIntoBucketImpl(Key, TheBucket);
420
421     TheBucket->getFirst() = Key;
422     new (&TheBucket->getSecond()) ValueT(std::move(Value));
423     return TheBucket;
424   }
425
426   BucketT *InsertIntoBucket(KeyT &&Key, ValueT &&Value, BucketT *TheBucket) {
427     TheBucket = InsertIntoBucketImpl(Key, TheBucket);
428
429     TheBucket->getFirst() = std::move(Key);
430     new (&TheBucket->getSecond()) ValueT(std::move(Value));
431     return TheBucket;
432   }
433
434   BucketT *InsertIntoBucketImpl(const KeyT &Key, BucketT *TheBucket) {
435     incrementEpoch();
436
437     // If the load of the hash table is more than 3/4, or if fewer than 1/8 of
438     // the buckets are empty (meaning that many are filled with tombstones),
439     // grow the table.
440     //
441     // The later case is tricky.  For example, if we had one empty bucket with
442     // tons of tombstones, failing lookups (e.g. for insertion) would have to
443     // probe almost the entire table until it found the empty bucket.  If the
444     // table completely filled with tombstones, no lookup would ever succeed,
445     // causing infinite loops in lookup.
446     unsigned NewNumEntries = getNumEntries() + 1;
447     unsigned NumBuckets = getNumBuckets();
448     if (LLVM_UNLIKELY(NewNumEntries * 4 >= NumBuckets * 3)) {
449       this->grow(NumBuckets * 2);
450       LookupBucketFor(Key, TheBucket);
451       NumBuckets = getNumBuckets();
452     } else if (LLVM_UNLIKELY(NumBuckets-(NewNumEntries+getNumTombstones()) <=
453                              NumBuckets/8)) {
454       this->grow(NumBuckets);
455       LookupBucketFor(Key, TheBucket);
456     }
457     assert(TheBucket);
458
459     // Only update the state after we've grown our bucket space appropriately
460     // so that when growing buckets we have self-consistent entry count.
461     incrementNumEntries();
462
463     // If we are writing over a tombstone, remember this.
464     const KeyT EmptyKey = getEmptyKey();
465     if (!KeyInfoT::isEqual(TheBucket->getFirst(), EmptyKey))
466       decrementNumTombstones();
467
468     return TheBucket;
469   }
470
471   /// LookupBucketFor - Lookup the appropriate bucket for Val, returning it in
472   /// FoundBucket.  If the bucket contains the key and a value, this returns
473   /// true, otherwise it returns a bucket with an empty marker or tombstone and
474   /// returns false.
475   template<typename LookupKeyT>
476   bool LookupBucketFor(const LookupKeyT &Val,
477                        const BucketT *&FoundBucket) const {
478     const BucketT *BucketsPtr = getBuckets();
479     const unsigned NumBuckets = getNumBuckets();
480
481     if (NumBuckets == 0) {
482       FoundBucket = nullptr;
483       return false;
484     }
485
486     // FoundTombstone - Keep track of whether we find a tombstone while probing.
487     const BucketT *FoundTombstone = nullptr;
488     const KeyT EmptyKey = getEmptyKey();
489     const KeyT TombstoneKey = getTombstoneKey();
490     assert(!KeyInfoT::isEqual(Val, EmptyKey) &&
491            !KeyInfoT::isEqual(Val, TombstoneKey) &&
492            "Empty/Tombstone value shouldn't be inserted into map!");
493
494     unsigned BucketNo = getHashValue(Val) & (NumBuckets-1);
495     unsigned ProbeAmt = 1;
496     while (1) {
497       const BucketT *ThisBucket = BucketsPtr + BucketNo;
498       // Found Val's bucket?  If so, return it.
499       if (LLVM_LIKELY(KeyInfoT::isEqual(Val, ThisBucket->getFirst()))) {
500         FoundBucket = ThisBucket;
501         return true;
502       }
503
504       // If we found an empty bucket, the key doesn't exist in the set.
505       // Insert it and return the default value.
506       if (LLVM_LIKELY(KeyInfoT::isEqual(ThisBucket->getFirst(), EmptyKey))) {
507         // If we've already seen a tombstone while probing, fill it in instead
508         // of the empty bucket we eventually probed to.
509         FoundBucket = FoundTombstone ? FoundTombstone : ThisBucket;
510         return false;
511       }
512
513       // If this is a tombstone, remember it.  If Val ends up not in the map, we
514       // prefer to return it than something that would require more probing.
515       if (KeyInfoT::isEqual(ThisBucket->getFirst(), TombstoneKey) &&
516           !FoundTombstone)
517         FoundTombstone = ThisBucket;  // Remember the first tombstone found.
518
519       // Otherwise, it's a hash collision or a tombstone, continue quadratic
520       // probing.
521       BucketNo += ProbeAmt++;
522       BucketNo &= (NumBuckets-1);
523     }
524   }
525
526   template <typename LookupKeyT>
527   bool LookupBucketFor(const LookupKeyT &Val, BucketT *&FoundBucket) {
528     const BucketT *ConstFoundBucket;
529     bool Result = const_cast<const DenseMapBase *>(this)
530       ->LookupBucketFor(Val, ConstFoundBucket);
531     FoundBucket = const_cast<BucketT *>(ConstFoundBucket);
532     return Result;
533   }
534
535 public:
536   /// Return the approximate size (in bytes) of the actual map.
537   /// This is just the raw memory used by DenseMap.
538   /// If entries are pointers to objects, the size of the referenced objects
539   /// are not included.
540   size_t getMemorySize() const {
541     return getNumBuckets() * sizeof(BucketT);
542   }
543 };
544
545 template <typename KeyT, typename ValueT,
546           typename KeyInfoT = DenseMapInfo<KeyT>,
547           typename BucketT = detail::DenseMapPair<KeyT, ValueT>>
548 class DenseMap : public DenseMapBase<DenseMap<KeyT, ValueT, KeyInfoT, BucketT>,
549                                      KeyT, ValueT, KeyInfoT, BucketT> {
550   // Lift some types from the dependent base class into this class for
551   // simplicity of referring to them.
552   typedef DenseMapBase<DenseMap, KeyT, ValueT, KeyInfoT, BucketT> BaseT;
553   friend class DenseMapBase<DenseMap, KeyT, ValueT, KeyInfoT, BucketT>;
554
555   BucketT *Buckets;
556   unsigned NumEntries;
557   unsigned NumTombstones;
558   unsigned NumBuckets;
559
560 public:
561   explicit DenseMap(unsigned NumInitBuckets = 0) {
562     init(NumInitBuckets);
563   }
564
565   DenseMap(const DenseMap &other) : BaseT() {
566     init(0);
567     copyFrom(other);
568   }
569
570   DenseMap(DenseMap &&other) : BaseT() {
571     init(0);
572     swap(other);
573   }
574
575   template<typename InputIt>
576   DenseMap(const InputIt &I, const InputIt &E) {
577     init(NextPowerOf2(std::distance(I, E)));
578     this->insert(I, E);
579   }
580
581   ~DenseMap() {
582     this->destroyAll();
583     operator delete(Buckets);
584   }
585
586   void swap(DenseMap& RHS) {
587     std::swap(Buckets, RHS.Buckets);
588     std::swap(NumEntries, RHS.NumEntries);
589     std::swap(NumTombstones, RHS.NumTombstones);
590     std::swap(NumBuckets, RHS.NumBuckets);
591   }
592
593   DenseMap& operator=(const DenseMap& other) {
594     if (&other != this)
595       copyFrom(other);
596     return *this;
597   }
598
599   DenseMap& operator=(DenseMap &&other) {
600     this->destroyAll();
601     operator delete(Buckets);
602     init(0);
603     swap(other);
604     return *this;
605   }
606
607   void copyFrom(const DenseMap& other) {
608     this->destroyAll();
609     operator delete(Buckets);
610     if (allocateBuckets(other.NumBuckets)) {
611       this->BaseT::copyFrom(other);
612     } else {
613       NumEntries = 0;
614       NumTombstones = 0;
615     }
616   }
617
618   void init(unsigned InitBuckets) {
619     if (allocateBuckets(InitBuckets)) {
620       this->BaseT::initEmpty();
621     } else {
622       NumEntries = 0;
623       NumTombstones = 0;
624     }
625   }
626
627   void grow(unsigned AtLeast) {
628     unsigned OldNumBuckets = NumBuckets;
629     BucketT *OldBuckets = Buckets;
630
631     allocateBuckets(std::max<unsigned>(64, static_cast<unsigned>(NextPowerOf2(AtLeast-1))));
632     assert(Buckets);
633     if (!OldBuckets) {
634       this->BaseT::initEmpty();
635       return;
636     }
637
638     this->moveFromOldBuckets(OldBuckets, OldBuckets+OldNumBuckets);
639
640     // Free the old table.
641     operator delete(OldBuckets);
642   }
643
644   void shrink_and_clear() {
645     unsigned OldNumEntries = NumEntries;
646     this->destroyAll();
647
648     // Reduce the number of buckets.
649     unsigned NewNumBuckets = 0;
650     if (OldNumEntries)
651       NewNumBuckets = std::max(64, 1 << (Log2_32_Ceil(OldNumEntries) + 1));
652     if (NewNumBuckets == NumBuckets) {
653       this->BaseT::initEmpty();
654       return;
655     }
656
657     operator delete(Buckets);
658     init(NewNumBuckets);
659   }
660
661 private:
662   unsigned getNumEntries() const {
663     return NumEntries;
664   }
665   void setNumEntries(unsigned Num) {
666     NumEntries = Num;
667   }
668
669   unsigned getNumTombstones() const {
670     return NumTombstones;
671   }
672   void setNumTombstones(unsigned Num) {
673     NumTombstones = Num;
674   }
675
676   BucketT *getBuckets() const {
677     return Buckets;
678   }
679
680   unsigned getNumBuckets() const {
681     return NumBuckets;
682   }
683
684   bool allocateBuckets(unsigned Num) {
685     NumBuckets = Num;
686     if (NumBuckets == 0) {
687       Buckets = nullptr;
688       return false;
689     }
690
691     Buckets = static_cast<BucketT*>(operator new(sizeof(BucketT) * NumBuckets));
692     return true;
693   }
694 };
695
696 template <typename KeyT, typename ValueT, unsigned InlineBuckets = 4,
697           typename KeyInfoT = DenseMapInfo<KeyT>,
698           typename BucketT = detail::DenseMapPair<KeyT, ValueT>>
699 class SmallDenseMap
700     : public DenseMapBase<
701           SmallDenseMap<KeyT, ValueT, InlineBuckets, KeyInfoT, BucketT>, KeyT,
702           ValueT, KeyInfoT, BucketT> {
703   // Lift some types from the dependent base class into this class for
704   // simplicity of referring to them.
705   typedef DenseMapBase<SmallDenseMap, KeyT, ValueT, KeyInfoT, BucketT> BaseT;
706   friend class DenseMapBase<SmallDenseMap, KeyT, ValueT, KeyInfoT, BucketT>;
707
708   unsigned Small : 1;
709   unsigned NumEntries : 31;
710   unsigned NumTombstones;
711
712   struct LargeRep {
713     BucketT *Buckets;
714     unsigned NumBuckets;
715   };
716
717   /// A "union" of an inline bucket array and the struct representing
718   /// a large bucket. This union will be discriminated by the 'Small' bit.
719   AlignedCharArrayUnion<BucketT[InlineBuckets], LargeRep> storage;
720
721 public:
722   explicit SmallDenseMap(unsigned NumInitBuckets = 0) {
723     init(NumInitBuckets);
724   }
725
726   SmallDenseMap(const SmallDenseMap &other) : BaseT() {
727     init(0);
728     copyFrom(other);
729   }
730
731   SmallDenseMap(SmallDenseMap &&other) : BaseT() {
732     init(0);
733     swap(other);
734   }
735
736   template<typename InputIt>
737   SmallDenseMap(const InputIt &I, const InputIt &E) {
738     init(NextPowerOf2(std::distance(I, E)));
739     this->insert(I, E);
740   }
741
742   ~SmallDenseMap() {
743     this->destroyAll();
744     deallocateBuckets();
745   }
746
747   void swap(SmallDenseMap& RHS) {
748     unsigned TmpNumEntries = RHS.NumEntries;
749     RHS.NumEntries = NumEntries;
750     NumEntries = TmpNumEntries;
751     std::swap(NumTombstones, RHS.NumTombstones);
752
753     const KeyT EmptyKey = this->getEmptyKey();
754     const KeyT TombstoneKey = this->getTombstoneKey();
755     if (Small && RHS.Small) {
756       // If we're swapping inline bucket arrays, we have to cope with some of
757       // the tricky bits of DenseMap's storage system: the buckets are not
758       // fully initialized. Thus we swap every key, but we may have
759       // a one-directional move of the value.
760       for (unsigned i = 0, e = InlineBuckets; i != e; ++i) {
761         BucketT *LHSB = &getInlineBuckets()[i],
762                 *RHSB = &RHS.getInlineBuckets()[i];
763         bool hasLHSValue = (!KeyInfoT::isEqual(LHSB->getFirst(), EmptyKey) &&
764                             !KeyInfoT::isEqual(LHSB->getFirst(), TombstoneKey));
765         bool hasRHSValue = (!KeyInfoT::isEqual(RHSB->getFirst(), EmptyKey) &&
766                             !KeyInfoT::isEqual(RHSB->getFirst(), TombstoneKey));
767         if (hasLHSValue && hasRHSValue) {
768           // Swap together if we can...
769           std::swap(*LHSB, *RHSB);
770           continue;
771         }
772         // Swap separately and handle any assymetry.
773         std::swap(LHSB->getFirst(), RHSB->getFirst());
774         if (hasLHSValue) {
775           new (&RHSB->getSecond()) ValueT(std::move(LHSB->getSecond()));
776           LHSB->getSecond().~ValueT();
777         } else if (hasRHSValue) {
778           new (&LHSB->getSecond()) ValueT(std::move(RHSB->getSecond()));
779           RHSB->getSecond().~ValueT();
780         }
781       }
782       return;
783     }
784     if (!Small && !RHS.Small) {
785       std::swap(getLargeRep()->Buckets, RHS.getLargeRep()->Buckets);
786       std::swap(getLargeRep()->NumBuckets, RHS.getLargeRep()->NumBuckets);
787       return;
788     }
789
790     SmallDenseMap &SmallSide = Small ? *this : RHS;
791     SmallDenseMap &LargeSide = Small ? RHS : *this;
792
793     // First stash the large side's rep and move the small side across.
794     LargeRep TmpRep = std::move(*LargeSide.getLargeRep());
795     LargeSide.getLargeRep()->~LargeRep();
796     LargeSide.Small = true;
797     // This is similar to the standard move-from-old-buckets, but the bucket
798     // count hasn't actually rotated in this case. So we have to carefully
799     // move construct the keys and values into their new locations, but there
800     // is no need to re-hash things.
801     for (unsigned i = 0, e = InlineBuckets; i != e; ++i) {
802       BucketT *NewB = &LargeSide.getInlineBuckets()[i],
803               *OldB = &SmallSide.getInlineBuckets()[i];
804       new (&NewB->getFirst()) KeyT(std::move(OldB->getFirst()));
805       OldB->getFirst().~KeyT();
806       if (!KeyInfoT::isEqual(NewB->getFirst(), EmptyKey) &&
807           !KeyInfoT::isEqual(NewB->getFirst(), TombstoneKey)) {
808         new (&NewB->getSecond()) ValueT(std::move(OldB->getSecond()));
809         OldB->getSecond().~ValueT();
810       }
811     }
812
813     // The hard part of moving the small buckets across is done, just move
814     // the TmpRep into its new home.
815     SmallSide.Small = false;
816     new (SmallSide.getLargeRep()) LargeRep(std::move(TmpRep));
817   }
818
819   SmallDenseMap& operator=(const SmallDenseMap& other) {
820     if (&other != this)
821       copyFrom(other);
822     return *this;
823   }
824
825   SmallDenseMap& operator=(SmallDenseMap &&other) {
826     this->destroyAll();
827     deallocateBuckets();
828     init(0);
829     swap(other);
830     return *this;
831   }
832
833   void copyFrom(const SmallDenseMap& other) {
834     this->destroyAll();
835     deallocateBuckets();
836     Small = true;
837     if (other.getNumBuckets() > InlineBuckets) {
838       Small = false;
839       new (getLargeRep()) LargeRep(allocateBuckets(other.getNumBuckets()));
840     }
841     this->BaseT::copyFrom(other);
842   }
843
844   void init(unsigned InitBuckets) {
845     Small = true;
846     if (InitBuckets > InlineBuckets) {
847       Small = false;
848       new (getLargeRep()) LargeRep(allocateBuckets(InitBuckets));
849     }
850     this->BaseT::initEmpty();
851   }
852
853   void grow(unsigned AtLeast) {
854     if (AtLeast >= InlineBuckets)
855       AtLeast = std::max<unsigned>(64, NextPowerOf2(AtLeast-1));
856
857     if (Small) {
858       if (AtLeast < InlineBuckets)
859         return; // Nothing to do.
860
861       // First move the inline buckets into a temporary storage.
862       AlignedCharArrayUnion<BucketT[InlineBuckets]> TmpStorage;
863       BucketT *TmpBegin = reinterpret_cast<BucketT *>(TmpStorage.buffer);
864       BucketT *TmpEnd = TmpBegin;
865
866       // Loop over the buckets, moving non-empty, non-tombstones into the
867       // temporary storage. Have the loop move the TmpEnd forward as it goes.
868       const KeyT EmptyKey = this->getEmptyKey();
869       const KeyT TombstoneKey = this->getTombstoneKey();
870       for (BucketT *P = getBuckets(), *E = P + InlineBuckets; P != E; ++P) {
871         if (!KeyInfoT::isEqual(P->getFirst(), EmptyKey) &&
872             !KeyInfoT::isEqual(P->getFirst(), TombstoneKey)) {
873           assert(size_t(TmpEnd - TmpBegin) < InlineBuckets &&
874                  "Too many inline buckets!");
875           new (&TmpEnd->getFirst()) KeyT(std::move(P->getFirst()));
876           new (&TmpEnd->getSecond()) ValueT(std::move(P->getSecond()));
877           ++TmpEnd;
878           P->getSecond().~ValueT();
879         }
880         P->getFirst().~KeyT();
881       }
882
883       // Now make this map use the large rep, and move all the entries back
884       // into it.
885       Small = false;
886       new (getLargeRep()) LargeRep(allocateBuckets(AtLeast));
887       this->moveFromOldBuckets(TmpBegin, TmpEnd);
888       return;
889     }
890
891     LargeRep OldRep = std::move(*getLargeRep());
892     getLargeRep()->~LargeRep();
893     if (AtLeast <= InlineBuckets) {
894       Small = true;
895     } else {
896       new (getLargeRep()) LargeRep(allocateBuckets(AtLeast));
897     }
898
899     this->moveFromOldBuckets(OldRep.Buckets, OldRep.Buckets+OldRep.NumBuckets);
900
901     // Free the old table.
902     operator delete(OldRep.Buckets);
903   }
904
905   void shrink_and_clear() {
906     unsigned OldSize = this->size();
907     this->destroyAll();
908
909     // Reduce the number of buckets.
910     unsigned NewNumBuckets = 0;
911     if (OldSize) {
912       NewNumBuckets = 1 << (Log2_32_Ceil(OldSize) + 1);
913       if (NewNumBuckets > InlineBuckets && NewNumBuckets < 64u)
914         NewNumBuckets = 64;
915     }
916     if ((Small && NewNumBuckets <= InlineBuckets) ||
917         (!Small && NewNumBuckets == getLargeRep()->NumBuckets)) {
918       this->BaseT::initEmpty();
919       return;
920     }
921
922     deallocateBuckets();
923     init(NewNumBuckets);
924   }
925
926 private:
927   unsigned getNumEntries() const {
928     return NumEntries;
929   }
930   void setNumEntries(unsigned Num) {
931     assert(Num < INT_MAX && "Cannot support more than INT_MAX entries");
932     NumEntries = Num;
933   }
934
935   unsigned getNumTombstones() const {
936     return NumTombstones;
937   }
938   void setNumTombstones(unsigned Num) {
939     NumTombstones = Num;
940   }
941
942   const BucketT *getInlineBuckets() const {
943     assert(Small);
944     // Note that this cast does not violate aliasing rules as we assert that
945     // the memory's dynamic type is the small, inline bucket buffer, and the
946     // 'storage.buffer' static type is 'char *'.
947     return reinterpret_cast<const BucketT *>(storage.buffer);
948   }
949   BucketT *getInlineBuckets() {
950     return const_cast<BucketT *>(
951       const_cast<const SmallDenseMap *>(this)->getInlineBuckets());
952   }
953   const LargeRep *getLargeRep() const {
954     assert(!Small);
955     // Note, same rule about aliasing as with getInlineBuckets.
956     return reinterpret_cast<const LargeRep *>(storage.buffer);
957   }
958   LargeRep *getLargeRep() {
959     return const_cast<LargeRep *>(
960       const_cast<const SmallDenseMap *>(this)->getLargeRep());
961   }
962
963   const BucketT *getBuckets() const {
964     return Small ? getInlineBuckets() : getLargeRep()->Buckets;
965   }
966   BucketT *getBuckets() {
967     return const_cast<BucketT *>(
968       const_cast<const SmallDenseMap *>(this)->getBuckets());
969   }
970   unsigned getNumBuckets() const {
971     return Small ? InlineBuckets : getLargeRep()->NumBuckets;
972   }
973
974   void deallocateBuckets() {
975     if (Small)
976       return;
977
978     operator delete(getLargeRep()->Buckets);
979     getLargeRep()->~LargeRep();
980   }
981
982   LargeRep allocateBuckets(unsigned Num) {
983     assert(Num > InlineBuckets && "Must allocate more buckets than are inline");
984     LargeRep Rep = {
985       static_cast<BucketT*>(operator new(sizeof(BucketT) * Num)), Num
986     };
987     return Rep;
988   }
989 };
990
991 template <typename KeyT, typename ValueT, typename KeyInfoT, typename Bucket,
992           bool IsConst>
993 class DenseMapIterator : DebugEpochBase::HandleBase {
994   typedef DenseMapIterator<KeyT, ValueT, KeyInfoT, Bucket, true> ConstIterator;
995   friend class DenseMapIterator<KeyT, ValueT, KeyInfoT, Bucket, true>;
996   friend class DenseMapIterator<KeyT, ValueT, KeyInfoT, Bucket, false>;
997
998 public:
999   typedef ptrdiff_t difference_type;
1000   typedef typename std::conditional<IsConst, const Bucket, Bucket>::type
1001   value_type;
1002   typedef value_type *pointer;
1003   typedef value_type &reference;
1004   typedef std::forward_iterator_tag iterator_category;
1005 private:
1006   pointer Ptr, End;
1007 public:
1008   DenseMapIterator() : Ptr(nullptr), End(nullptr) {}
1009
1010   DenseMapIterator(pointer Pos, pointer E, const DebugEpochBase &Epoch,
1011                    bool NoAdvance = false)
1012       : DebugEpochBase::HandleBase(&Epoch), Ptr(Pos), End(E) {
1013     assert(isHandleInSync() && "invalid construction!");
1014     if (!NoAdvance) AdvancePastEmptyBuckets();
1015   }
1016
1017   // Converting ctor from non-const iterators to const iterators. SFINAE'd out
1018   // for const iterator destinations so it doesn't end up as a user defined copy
1019   // constructor.
1020   template <bool IsConstSrc,
1021             typename = typename std::enable_if<!IsConstSrc && IsConst>::type>
1022   DenseMapIterator(
1023       const DenseMapIterator<KeyT, ValueT, KeyInfoT, Bucket, IsConstSrc> &I)
1024       : DebugEpochBase::HandleBase(I), Ptr(I.Ptr), End(I.End) {}
1025
1026   reference operator*() const {
1027     assert(isHandleInSync() && "invalid iterator access!");
1028     return *Ptr;
1029   }
1030   pointer operator->() const {
1031     assert(isHandleInSync() && "invalid iterator access!");
1032     return Ptr;
1033   }
1034
1035   bool operator==(const ConstIterator &RHS) const {
1036     assert((!Ptr || isHandleInSync()) && "handle not in sync!");
1037     assert((!RHS.Ptr || RHS.isHandleInSync()) && "handle not in sync!");
1038     assert(getEpochAddress() == RHS.getEpochAddress() &&
1039            "comparing incomparable iterators!");
1040     return Ptr == RHS.Ptr;
1041   }
1042   bool operator!=(const ConstIterator &RHS) const {
1043     assert((!Ptr || isHandleInSync()) && "handle not in sync!");
1044     assert((!RHS.Ptr || RHS.isHandleInSync()) && "handle not in sync!");
1045     assert(getEpochAddress() == RHS.getEpochAddress() &&
1046            "comparing incomparable iterators!");
1047     return Ptr != RHS.Ptr;
1048   }
1049
1050   inline DenseMapIterator& operator++() {  // Preincrement
1051     assert(isHandleInSync() && "invalid iterator access!");
1052     ++Ptr;
1053     AdvancePastEmptyBuckets();
1054     return *this;
1055   }
1056   DenseMapIterator operator++(int) {  // Postincrement
1057     assert(isHandleInSync() && "invalid iterator access!");
1058     DenseMapIterator tmp = *this; ++*this; return tmp;
1059   }
1060
1061 private:
1062   void AdvancePastEmptyBuckets() {
1063     const KeyT Empty = KeyInfoT::getEmptyKey();
1064     const KeyT Tombstone = KeyInfoT::getTombstoneKey();
1065
1066     while (Ptr != End && (KeyInfoT::isEqual(Ptr->getFirst(), Empty) ||
1067                           KeyInfoT::isEqual(Ptr->getFirst(), Tombstone)))
1068       ++Ptr;
1069   }
1070 };
1071
1072 template<typename KeyT, typename ValueT, typename KeyInfoT>
1073 static inline size_t
1074 capacity_in_bytes(const DenseMap<KeyT, ValueT, KeyInfoT> &X) {
1075   return X.getMemorySize();
1076 }
1077
1078 } // end namespace llvm
1079
1080 #endif