xref: /third_party/node/deps/v8/src/base/hashmap.h (revision 1cb0ef41)
1// Copyright 2012 the V8 project authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5// The reason we write our own hash map instead of using unordered_map in STL,
6// is that STL containers use a mutex pool on debug build, which will lead to
7// deadlock when we are using async signal handler.
8
9#ifndef V8_BASE_HASHMAP_H_
10#define V8_BASE_HASHMAP_H_
11
12#include <stdlib.h>
13
14#include "src/base/bits.h"
15#include "src/base/hashmap-entry.h"
16#include "src/base/logging.h"
17#include "src/base/platform/wrappers.h"
18
19namespace v8 {
20namespace base {
21
22class DefaultAllocationPolicy {
23 public:
24  template <typename T, typename TypeTag = T[]>
25  V8_INLINE T* NewArray(size_t length) {
26    return static_cast<T*>(base::Malloc(length * sizeof(T)));
27  }
28  template <typename T, typename TypeTag = T[]>
29  V8_INLINE void DeleteArray(T* p, size_t length) {
30    base::Free(p);
31  }
32};
33
34template <typename Key, typename Value, class MatchFun, class AllocationPolicy>
35class TemplateHashMapImpl {
36 public:
37  using Entry = TemplateHashMapEntry<Key, Value>;
38
39  // The default capacity.  This is used by the call sites which want
40  // to pass in a non-default AllocationPolicy but want to use the
41  // default value of capacity specified by the implementation.
42  static const uint32_t kDefaultHashMapCapacity = 8;
43
44  // initial_capacity is the size of the initial hash map;
45  // it must be a power of 2 (and thus must not be 0).
46  explicit TemplateHashMapImpl(uint32_t capacity = kDefaultHashMapCapacity,
47                               MatchFun match = MatchFun(),
48                               AllocationPolicy allocator = AllocationPolicy());
49
50  TemplateHashMapImpl(const TemplateHashMapImpl&) = delete;
51  TemplateHashMapImpl& operator=(const TemplateHashMapImpl&) = delete;
52
53  // Clones the given hashmap and creates a copy with the same entries.
54  explicit TemplateHashMapImpl(const TemplateHashMapImpl* original,
55                               AllocationPolicy allocator = AllocationPolicy());
56
57  TemplateHashMapImpl(TemplateHashMapImpl&& other) V8_NOEXCEPT = default;
58
59  ~TemplateHashMapImpl();
60
61  TemplateHashMapImpl& operator=(TemplateHashMapImpl&& other)
62      V8_NOEXCEPT = default;
63
64  // If an entry with matching key is found, returns that entry.
65  // Otherwise, nullptr is returned.
66  Entry* Lookup(const Key& key, uint32_t hash) const;
67
68  // If an entry with matching key is found, returns that entry.
69  // If no matching entry is found, a new entry is inserted with
70  // corresponding key, key hash, and default initialized value.
71  Entry* LookupOrInsert(const Key& key, uint32_t hash);
72
73  // If an entry with matching key is found, returns that entry.
74  // If no matching entry is found, a new entry is inserted with
75  // corresponding key, key hash, and value created by func.
76  template <typename Func>
77  Entry* LookupOrInsert(const Key& key, uint32_t hash, const Func& value_func);
78
79  // Heterogeneous version of LookupOrInsert, which allows a
80  // different lookup key type than the hashmap's key type.
81  // The requirement is that MatchFun has an overload:
82  //
83  //   operator()(const LookupKey& lookup_key, const Key& entry_key)
84  //
85  // If an entry with matching key is found, returns that entry.
86  // If no matching entry is found, a new entry is inserted with
87  // a key created by key_func, key hash, and value created by
88  // value_func.
89  template <typename LookupKey, typename KeyFunc, typename ValueFunc>
90  Entry* LookupOrInsert(const LookupKey& lookup_key, uint32_t hash,
91                        const KeyFunc& key_func, const ValueFunc& value_func);
92
93  Entry* InsertNew(const Key& key, uint32_t hash);
94
95  // Removes the entry with matching key.
96  // It returns the value of the deleted entry
97  // or null if there is no value for such key.
98  Value Remove(const Key& key, uint32_t hash);
99
100  // Empties the hash map (occupancy() == 0).
101  void Clear();
102
103  // Empties the map and makes it unusable for allocation.
104  void Invalidate() {
105    DCHECK_NOT_NULL(impl_.map_);
106    impl_.allocator().DeleteArray(impl_.map_, capacity());
107    impl_ = Impl(impl_.match(), AllocationPolicy());
108  }
109
110  // The number of (non-empty) entries in the table.
111  uint32_t occupancy() const { return impl_.occupancy_; }
112
113  // The capacity of the table. The implementation
114  // makes sure that occupancy is at most 80% of
115  // the table capacity.
116  uint32_t capacity() const { return impl_.capacity_; }
117
118  // Iteration
119  //
120  // for (Entry* p = map.Start(); p != nullptr; p = map.Next(p)) {
121  //   ...
122  // }
123  //
124  // If entries are inserted during iteration, the effect of
125  // calling Next() is undefined.
126  Entry* Start() const;
127  Entry* Next(Entry* entry) const;
128
129  AllocationPolicy allocator() const { return impl_.allocator(); }
130
131 protected:
132  void Initialize(uint32_t capacity);
133
134 private:
135  Entry* map_end() const { return impl_.map_ + impl_.capacity_; }
136  template <typename LookupKey>
137  Entry* Probe(const LookupKey& key, uint32_t hash) const;
138  Entry* FillEmptyEntry(Entry* entry, const Key& key, const Value& value,
139                        uint32_t hash);
140  void Resize();
141
142  // To support matcher and allocator that may not be possible to
143  // default-construct, we have to store their instances. Using this to store
144  // all internal state of the hash map and using private inheritance to store
145  // matcher and allocator lets us take advantage of an empty base class
146  // optimization to avoid extra space in the common case when MatchFun and
147  // AllocationPolicy have no state.
148  // TODO(ishell): Once we reach C++20, consider removing the Impl struct and
149  // adding match and allocator as [[no_unique_address]] fields.
150  struct Impl : private MatchFun, private AllocationPolicy {
151    Impl(MatchFun match, AllocationPolicy allocator)
152        : MatchFun(std::move(match)), AllocationPolicy(std::move(allocator)) {}
153
154    Impl() = default;
155    Impl(const Impl&) V8_NOEXCEPT = default;
156    Impl(Impl&& other) V8_NOEXCEPT { *this = std::move(other); }
157
158    Impl& operator=(const Impl& other) V8_NOEXCEPT = default;
159    Impl& operator=(Impl&& other) V8_NOEXCEPT {
160      MatchFun::operator=(std::move(other));
161      AllocationPolicy::operator=(std::move(other));
162      map_ = other.map_;
163      capacity_ = other.capacity_;
164      occupancy_ = other.occupancy_;
165
166      other.map_ = nullptr;
167      other.capacity_ = 0;
168      other.occupancy_ = 0;
169      return *this;
170    }
171
172    const MatchFun& match() const { return *this; }
173    MatchFun& match() { return *this; }
174
175    const AllocationPolicy& allocator() const { return *this; }
176    AllocationPolicy& allocator() { return *this; }
177
178    Entry* map_ = nullptr;
179    uint32_t capacity_ = 0;
180    uint32_t occupancy_ = 0;
181  } impl_;
182};
183template <typename Key, typename Value, typename MatchFun,
184          class AllocationPolicy>
185TemplateHashMapImpl<Key, Value, MatchFun, AllocationPolicy>::
186    TemplateHashMapImpl(uint32_t initial_capacity, MatchFun match,
187                        AllocationPolicy allocator)
188    : impl_(std::move(match), std::move(allocator)) {
189  Initialize(initial_capacity);
190}
191
192template <typename Key, typename Value, typename MatchFun,
193          class AllocationPolicy>
194TemplateHashMapImpl<Key, Value, MatchFun, AllocationPolicy>::
195    TemplateHashMapImpl(const TemplateHashMapImpl* original,
196                        AllocationPolicy allocator)
197    : impl_(original->impl_.match(), std::move(allocator)) {
198  impl_.capacity_ = original->capacity();
199  impl_.occupancy_ = original->occupancy();
200  impl_.map_ = impl_.allocator().template NewArray<Entry>(capacity());
201  memcpy(impl_.map_, original->impl_.map_, capacity() * sizeof(Entry));
202}
203
204template <typename Key, typename Value, typename MatchFun,
205          class AllocationPolicy>
206TemplateHashMapImpl<Key, Value, MatchFun,
207                    AllocationPolicy>::~TemplateHashMapImpl() {
208  if (impl_.map_) impl_.allocator().DeleteArray(impl_.map_, capacity());
209}
210
211template <typename Key, typename Value, typename MatchFun,
212          class AllocationPolicy>
213typename TemplateHashMapImpl<Key, Value, MatchFun, AllocationPolicy>::Entry*
214TemplateHashMapImpl<Key, Value, MatchFun, AllocationPolicy>::Lookup(
215    const Key& key, uint32_t hash) const {
216  Entry* entry = Probe(key, hash);
217  return entry->exists() ? entry : nullptr;
218}
219
220template <typename Key, typename Value, typename MatchFun,
221          class AllocationPolicy>
222typename TemplateHashMapImpl<Key, Value, MatchFun, AllocationPolicy>::Entry*
223TemplateHashMapImpl<Key, Value, MatchFun, AllocationPolicy>::LookupOrInsert(
224    const Key& key, uint32_t hash) {
225  return LookupOrInsert(key, hash, []() { return Value(); });
226}
227
228template <typename Key, typename Value, typename MatchFun,
229          class AllocationPolicy>
230template <typename Func>
231typename TemplateHashMapImpl<Key, Value, MatchFun, AllocationPolicy>::Entry*
232TemplateHashMapImpl<Key, Value, MatchFun, AllocationPolicy>::LookupOrInsert(
233    const Key& key, uint32_t hash, const Func& value_func) {
234  return LookupOrInsert(
235      key, hash, [&key]() { return key; }, value_func);
236}
237
238template <typename Key, typename Value, typename MatchFun,
239          class AllocationPolicy>
240template <typename LookupKey, typename KeyFunc, typename ValueFunc>
241typename TemplateHashMapImpl<Key, Value, MatchFun, AllocationPolicy>::Entry*
242TemplateHashMapImpl<Key, Value, MatchFun, AllocationPolicy>::LookupOrInsert(
243    const LookupKey& lookup_key, uint32_t hash, const KeyFunc& key_func,
244    const ValueFunc& value_func) {
245  // Find a matching entry.
246  Entry* entry = Probe(lookup_key, hash);
247  if (entry->exists()) {
248    return entry;
249  }
250
251  return FillEmptyEntry(entry, key_func(), value_func(), hash);
252}
253
254template <typename Key, typename Value, typename MatchFun,
255          class AllocationPolicy>
256typename TemplateHashMapImpl<Key, Value, MatchFun, AllocationPolicy>::Entry*
257TemplateHashMapImpl<Key, Value, MatchFun, AllocationPolicy>::InsertNew(
258    const Key& key, uint32_t hash) {
259  Entry* entry = Probe(key, hash);
260  return FillEmptyEntry(entry, key, Value(), hash);
261}
262
263template <typename Key, typename Value, typename MatchFun,
264          class AllocationPolicy>
265Value TemplateHashMapImpl<Key, Value, MatchFun, AllocationPolicy>::Remove(
266    const Key& key, uint32_t hash) {
267  // Lookup the entry for the key to remove.
268  Entry* p = Probe(key, hash);
269  if (!p->exists()) {
270    // Key not found nothing to remove.
271    return nullptr;
272  }
273
274  Value value = p->value;
275  // To remove an entry we need to ensure that it does not create an empty
276  // entry that will cause the search for another entry to stop too soon. If all
277  // the entries between the entry to remove and the next empty slot have their
278  // initial position inside this interval, clearing the entry to remove will
279  // not break the search. If, while searching for the next empty entry, an
280  // entry is encountered which does not have its initial position between the
281  // entry to remove and the position looked at, then this entry can be moved to
282  // the place of the entry to remove without breaking the search for it. The
283  // entry made vacant by this move is now the entry to remove and the process
284  // starts over.
285  // Algorithm from http://en.wikipedia.org/wiki/Open_addressing.
286
287  // This guarantees loop termination as there is at least one empty entry so
288  // eventually the removed entry will have an empty entry after it.
289  DCHECK(occupancy() < capacity());
290
291  // p is the candidate entry to clear. q is used to scan forwards.
292  Entry* q = p;  // Start at the entry to remove.
293  while (true) {
294    // Move q to the next entry.
295    q = q + 1;
296    if (q == map_end()) {
297      q = impl_.map_;
298    }
299
300    // All entries between p and q have their initial position between p and q
301    // and the entry p can be cleared without breaking the search for these
302    // entries.
303    if (!q->exists()) {
304      break;
305    }
306
307    // Find the initial position for the entry at position q.
308    Entry* r = impl_.map_ + (q->hash & (capacity() - 1));
309
310    // If the entry at position q has its initial position outside the range
311    // between p and q it can be moved forward to position p and will still be
312    // found. There is now a new candidate entry for clearing.
313    if ((q > p && (r <= p || r > q)) || (q < p && (r <= p && r > q))) {
314      *p = *q;
315      p = q;
316    }
317  }
318
319  // Clear the entry which is allowed to en emptied.
320  p->clear();
321  impl_.occupancy_--;
322  return value;
323}
324
325template <typename Key, typename Value, typename MatchFun,
326          class AllocationPolicy>
327void TemplateHashMapImpl<Key, Value, MatchFun, AllocationPolicy>::Clear() {
328  // Mark all entries as empty.
329  for (size_t i = 0; i < capacity(); ++i) {
330    impl_.map_[i].clear();
331  }
332  impl_.occupancy_ = 0;
333}
334
335template <typename Key, typename Value, typename MatchFun,
336          class AllocationPolicy>
337typename TemplateHashMapImpl<Key, Value, MatchFun, AllocationPolicy>::Entry*
338TemplateHashMapImpl<Key, Value, MatchFun, AllocationPolicy>::Start() const {
339  return Next(impl_.map_ - 1);
340}
341
342template <typename Key, typename Value, typename MatchFun,
343          class AllocationPolicy>
344typename TemplateHashMapImpl<Key, Value, MatchFun, AllocationPolicy>::Entry*
345TemplateHashMapImpl<Key, Value, MatchFun, AllocationPolicy>::Next(
346    Entry* entry) const {
347  const Entry* end = map_end();
348  DCHECK(impl_.map_ - 1 <= entry && entry < end);
349  for (entry++; entry < end; entry++) {
350    if (entry->exists()) {
351      return entry;
352    }
353  }
354  return nullptr;
355}
356
357template <typename Key, typename Value, typename MatchFun,
358          class AllocationPolicy>
359template <typename LookupKey>
360typename TemplateHashMapImpl<Key, Value, MatchFun, AllocationPolicy>::Entry*
361TemplateHashMapImpl<Key, Value, MatchFun, AllocationPolicy>::Probe(
362    const LookupKey& key, uint32_t hash) const {
363  DCHECK(base::bits::IsPowerOfTwo(capacity()));
364  size_t i = hash & (capacity() - 1);
365  DCHECK(i < capacity());
366
367  DCHECK(occupancy() < capacity());  // Guarantees loop termination.
368  Entry* map = impl_.map_;
369  while (map[i].exists() &&
370         !impl_.match()(hash, map[i].hash, key, map[i].key)) {
371    i = (i + 1) & (capacity() - 1);
372  }
373
374  return &map[i];
375}
376
377template <typename Key, typename Value, typename MatchFun,
378          class AllocationPolicy>
379typename TemplateHashMapImpl<Key, Value, MatchFun, AllocationPolicy>::Entry*
380TemplateHashMapImpl<Key, Value, MatchFun, AllocationPolicy>::FillEmptyEntry(
381    Entry* entry, const Key& key, const Value& value, uint32_t hash) {
382  DCHECK(!entry->exists());
383
384  new (entry) Entry(key, value, hash);
385  impl_.occupancy_++;
386
387  // Grow the map if we reached >= 80% occupancy.
388  if (occupancy() + occupancy() / 4 >= capacity()) {
389    Resize();
390    entry = Probe(key, hash);
391  }
392
393  return entry;
394}
395
396template <typename Key, typename Value, typename MatchFun,
397          class AllocationPolicy>
398void TemplateHashMapImpl<Key, Value, MatchFun, AllocationPolicy>::Initialize(
399    uint32_t capacity) {
400  DCHECK(base::bits::IsPowerOfTwo(capacity));
401  impl_.map_ = impl_.allocator().template NewArray<Entry>(capacity);
402  if (impl_.map_ == nullptr) {
403    FATAL("Out of memory: HashMap::Initialize");
404    return;
405  }
406  impl_.capacity_ = capacity;
407  Clear();
408}
409
410template <typename Key, typename Value, typename MatchFun,
411          class AllocationPolicy>
412void TemplateHashMapImpl<Key, Value, MatchFun, AllocationPolicy>::Resize() {
413  Entry* old_map = impl_.map_;
414  uint32_t old_capacity = capacity();
415  uint32_t n = occupancy();
416
417  // Allocate larger map.
418  Initialize(capacity() * 2);
419
420  // Rehash all current entries.
421  for (Entry* entry = old_map; n > 0; entry++) {
422    if (entry->exists()) {
423      Entry* new_entry = Probe(entry->key, entry->hash);
424      new_entry =
425          FillEmptyEntry(new_entry, entry->key, entry->value, entry->hash);
426      n--;
427    }
428  }
429
430  // Delete old map.
431  impl_.allocator().DeleteArray(old_map, old_capacity);
432}
433
434// Match function which compares hashes before executing a (potentially
435// expensive) key comparison.
436template <typename Key, typename MatchFun>
437struct HashEqualityThenKeyMatcher {
438  explicit HashEqualityThenKeyMatcher(MatchFun match) : match_(match) {}
439
440  bool operator()(uint32_t hash1, uint32_t hash2, const Key& key1,
441                  const Key& key2) const {
442    return hash1 == hash2 && match_(key1, key2);
443  }
444
445 private:
446  MatchFun match_;
447};
448
449// Hashmap<void*, void*> which takes a custom key comparison function pointer.
450template <typename AllocationPolicy>
451class CustomMatcherTemplateHashMapImpl
452    : public TemplateHashMapImpl<
453          void*, void*,
454          HashEqualityThenKeyMatcher<void*, bool (*)(void*, void*)>,
455          AllocationPolicy> {
456  using Base = TemplateHashMapImpl<
457      void*, void*, HashEqualityThenKeyMatcher<void*, bool (*)(void*, void*)>,
458      AllocationPolicy>;
459
460 public:
461  using MatchFun = bool (*)(void*, void*);
462
463  explicit CustomMatcherTemplateHashMapImpl(
464      MatchFun match, uint32_t capacity = Base::kDefaultHashMapCapacity,
465      AllocationPolicy allocator = AllocationPolicy())
466      : Base(capacity, HashEqualityThenKeyMatcher<void*, MatchFun>(match),
467             allocator) {}
468
469  explicit CustomMatcherTemplateHashMapImpl(
470      const CustomMatcherTemplateHashMapImpl* original,
471      AllocationPolicy allocator = AllocationPolicy())
472      : Base(original, allocator) {}
473
474  CustomMatcherTemplateHashMapImpl(const CustomMatcherTemplateHashMapImpl&) =
475      delete;
476  CustomMatcherTemplateHashMapImpl& operator=(
477      const CustomMatcherTemplateHashMapImpl&) = delete;
478};
479
480using CustomMatcherHashMap =
481    CustomMatcherTemplateHashMapImpl<DefaultAllocationPolicy>;
482
483// Match function which compares keys directly by equality.
484template <typename Key>
485struct KeyEqualityMatcher {
486  bool operator()(uint32_t hash1, uint32_t hash2, const Key& key1,
487                  const Key& key2) const {
488    return key1 == key2;
489  }
490};
491
492// Hashmap<void*, void*> which compares the key pointers directly.
493template <typename AllocationPolicy>
494class PointerTemplateHashMapImpl
495    : public TemplateHashMapImpl<void*, void*, KeyEqualityMatcher<void*>,
496                                 AllocationPolicy> {
497  using Base = TemplateHashMapImpl<void*, void*, KeyEqualityMatcher<void*>,
498                                   AllocationPolicy>;
499
500 public:
501  explicit PointerTemplateHashMapImpl(
502      uint32_t capacity = Base::kDefaultHashMapCapacity,
503      AllocationPolicy allocator = AllocationPolicy())
504      : Base(capacity, KeyEqualityMatcher<void*>(), allocator) {}
505
506  PointerTemplateHashMapImpl(const PointerTemplateHashMapImpl& other,
507                             AllocationPolicy allocator = AllocationPolicy())
508      : Base(&other, allocator) {}
509
510  PointerTemplateHashMapImpl(PointerTemplateHashMapImpl&& other) V8_NOEXCEPT
511      : Base(std::move(other)) {}
512
513  PointerTemplateHashMapImpl& operator=(PointerTemplateHashMapImpl&& other)
514      V8_NOEXCEPT {
515    static_cast<Base&>(*this) = std::move(other);
516    return *this;
517  }
518};
519
520using HashMap = PointerTemplateHashMapImpl<DefaultAllocationPolicy>;
521
522// A hash map for pointer keys and values with an STL-like interface.
523template <class Key, class Value, class MatchFun, class AllocationPolicy>
524class TemplateHashMap
525    : private TemplateHashMapImpl<void*, void*,
526                                  HashEqualityThenKeyMatcher<void*, MatchFun>,
527                                  AllocationPolicy> {
528  using Base = TemplateHashMapImpl<void*, void*,
529                                   HashEqualityThenKeyMatcher<void*, MatchFun>,
530                                   AllocationPolicy>;
531
532 public:
533  STATIC_ASSERT(sizeof(Key*) == sizeof(void*));
534  STATIC_ASSERT(sizeof(Value*) == sizeof(void*));
535  struct value_type {
536    Key* first;
537    Value* second;
538  };
539
540  class Iterator {
541   public:
542    Iterator& operator++() {
543      entry_ = map_->Next(entry_);
544      return *this;
545    }
546
547    value_type* operator->() { return reinterpret_cast<value_type*>(entry_); }
548    bool operator!=(const Iterator& other) { return entry_ != other.entry_; }
549
550   private:
551    Iterator(const Base* map, typename Base::Entry* entry)
552        : map_(map), entry_(entry) {}
553
554    const Base* map_;
555    typename Base::Entry* entry_;
556
557    friend class TemplateHashMap;
558  };
559
560  explicit TemplateHashMap(MatchFun match,
561                           AllocationPolicy allocator = AllocationPolicy())
562      : Base(Base::kDefaultHashMapCapacity,
563             HashEqualityThenKeyMatcher<void*, MatchFun>(match), allocator) {}
564
565  Iterator begin() const { return Iterator(this, this->Start()); }
566  Iterator end() const { return Iterator(this, nullptr); }
567  Iterator find(Key* key, bool insert = false) {
568    if (insert) {
569      return Iterator(this, this->LookupOrInsert(key, key->Hash()));
570    }
571    return Iterator(this, this->Lookup(key, key->Hash()));
572  }
573};
574
575}  // namespace base
576}  // namespace v8
577
578#endif  // V8_BASE_HASHMAP_H_
579