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_ADDRESS_MAP_H_ 6 #define V8_ADDRESS_MAP_H_ 7 8 #include "include/v8.h" 9 #include "src/assert-scope.h" 10 #include "src/base/hashmap.h" 11 #include "src/objects.h" 12 13 namespace v8 { 14 namespace internal { 15 16 template <typename Type> 17 class PointerToIndexHashMap 18 : public base::TemplateHashMapImpl<uintptr_t, uint32_t, 19 base::KeyEqualityMatcher<intptr_t>, 20 base::DefaultAllocationPolicy> { 21 public: 22 typedef base::TemplateHashMapEntry<uintptr_t, uint32_t> Entry; 23 Set(Type value,uint32_t index)24 inline void Set(Type value, uint32_t index) { 25 uintptr_t key = Key(value); 26 LookupOrInsert(key, Hash(key))->value = index; 27 } 28 Get(Type value)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 Hash(uintptr_t key)39 static uint32_t Hash(uintptr_t key) { return static_cast<uint32_t>(key); } 40 }; 41 42 template <> Key(Address value)43inline uintptr_t PointerToIndexHashMap<Address>::Key(Address value) { 44 return static_cast<uintptr_t>(value); 45 } 46 47 template <typename Type> Key(Type value)48inline uintptr_t PointerToIndexHashMap<Type>::Key(Type value) { 49 return reinterpret_cast<uintptr_t>(value); 50 } 51 52 class AddressToIndexHashMap : public PointerToIndexHashMap<Address> {}; 53 class HeapObjectToIndexHashMap : public PointerToIndexHashMap<HeapObject*> {}; 54 55 class RootIndexMap { 56 public: 57 explicit RootIndexMap(Isolate* isolate); 58 59 static const int kInvalidRootIndex = -1; 60 Lookup(HeapObject * obj)61 int Lookup(HeapObject* obj) { 62 Maybe<uint32_t> maybe_index = map_->Get(obj); 63 return maybe_index.IsJust() ? maybe_index.FromJust() : kInvalidRootIndex; 64 } 65 66 private: 67 HeapObjectToIndexHashMap* map_; 68 69 DISALLOW_COPY_AND_ASSIGN(RootIndexMap); 70 }; 71 72 } // namespace internal 73 } // namespace v8 74 75 #endif // V8_ADDRESS_MAP_H_ 76