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