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