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