xref: /third_party/node/deps/v8/src/utils/address-map.h (revision 1cb0ef41)
1// Copyright 2015 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#ifndef V8_UTILS_ADDRESS_MAP_H_
6#define V8_UTILS_ADDRESS_MAP_H_
7
8#include "src/base/hashmap.h"
9#include "src/common/assert-scope.h"
10#include "src/objects/heap-object.h"
11#include "src/roots/roots.h"
12
13namespace v8 {
14namespace internal {
15
16template <typename Type>
17class PointerToIndexHashMap
18    : public base::TemplateHashMapImpl<uintptr_t, uint32_t,
19                                       base::KeyEqualityMatcher<intptr_t>,
20                                       base::DefaultAllocationPolicy> {
21 public:
22  using Entry = base::TemplateHashMapEntry<uintptr_t, uint32_t>;
23
24  inline void Set(Type value, uint32_t index) {
25    uintptr_t key = Key(value);
26    LookupOrInsert(key, Hash(key))->value = index;
27  }
28
29  inline Maybe<uint32_t> Get(Type value) const {
30    uintptr_t key = Key(value);
31    Entry* entry = Lookup(key, Hash(key));
32    if (entry == nullptr) return Nothing<uint32_t>();
33    return Just(entry->value);
34  }
35
36 private:
37  static inline uintptr_t Key(Type value);
38
39  static uint32_t Hash(uintptr_t key) { return static_cast<uint32_t>(key); }
40};
41
42template <>
43inline uintptr_t PointerToIndexHashMap<Address>::Key(Address value) {
44  return static_cast<uintptr_t>(value);
45}
46
47template <>
48inline uintptr_t PointerToIndexHashMap<HeapObject>::Key(HeapObject value) {
49  return value.ptr();
50}
51
52class AddressToIndexHashMap : public PointerToIndexHashMap<Address> {};
53class HeapObjectToIndexHashMap : public PointerToIndexHashMap<HeapObject> {};
54
55class RootIndexMap {
56 public:
57  explicit RootIndexMap(Isolate* isolate);
58  RootIndexMap(const RootIndexMap&) = delete;
59  RootIndexMap& operator=(const RootIndexMap&) = delete;
60
61  // Returns true on successful lookup and sets *|out_root_list|.
62  bool Lookup(HeapObject obj, RootIndex* out_root_list) const {
63    Maybe<uint32_t> maybe_index = map_->Get(obj);
64    if (maybe_index.IsJust()) {
65      *out_root_list = static_cast<RootIndex>(maybe_index.FromJust());
66      return true;
67    }
68    return false;
69  }
70  bool Lookup(Address obj, RootIndex* out_root_list) const;
71
72 private:
73  HeapObjectToIndexHashMap* map_;
74};
75
76}  // namespace internal
77}  // namespace v8
78
79#endif  // V8_UTILS_ADDRESS_MAP_H_
80