1 // Copyright 2018 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_WASM_WASM_IMPORT_WRAPPER_CACHE_H_ 6 #define V8_WASM_WASM_IMPORT_WRAPPER_CACHE_H_ 7 8 #include "src/base/platform/mutex.h" 9 #include "src/compiler/wasm-compiler.h" 10 11 namespace v8 { 12 namespace internal { 13 14 class Counters; 15 16 namespace wasm { 17 18 class WasmCode; 19 class WasmEngine; 20 21 using FunctionSig = Signature<ValueType>; 22 23 // Implements a cache for import wrappers. 24 class WasmImportWrapperCache { 25 public: 26 struct CacheKey { CacheKeyCacheKey27 CacheKey(const compiler::WasmImportCallKind& _kind, const FunctionSig* _sig, 28 int _expected_arity) 29 : kind(_kind), 30 signature(_sig), 31 expected_arity(_expected_arity == kDontAdaptArgumentsSentinel 32 ? 0 33 : _expected_arity) {} 34 35 bool operator==(const CacheKey& rhs) const { 36 return kind == rhs.kind && signature == rhs.signature && 37 expected_arity == rhs.expected_arity; 38 } 39 40 compiler::WasmImportCallKind kind; 41 const FunctionSig* signature; 42 int expected_arity; 43 }; 44 45 class CacheKeyHash { 46 public: operator()47 size_t operator()(const CacheKey& key) const { 48 return base::hash_combine(static_cast<uint8_t>(key.kind), key.signature, 49 key.expected_arity); 50 } 51 }; 52 53 // Helper class to modify the cache under a lock. 54 class ModificationScope { 55 public: ModificationScope(WasmImportWrapperCache * cache)56 explicit ModificationScope(WasmImportWrapperCache* cache) 57 : cache_(cache), guard_(&cache->mutex_) {} 58 59 V8_EXPORT_PRIVATE WasmCode*& operator[](const CacheKey& key); 60 61 private: 62 WasmImportWrapperCache* const cache_; 63 base::MutexGuard guard_; 64 }; 65 66 // Not thread-safe, use ModificationScope to get exclusive write access to the 67 // cache. 68 V8_EXPORT_PRIVATE WasmCode*& operator[](const CacheKey& key); 69 70 // Thread-safe. Assumes the key exists in the map. 71 V8_EXPORT_PRIVATE WasmCode* Get(compiler::WasmImportCallKind kind, 72 const FunctionSig* sig, 73 int expected_arity) const; 74 75 ~WasmImportWrapperCache(); 76 77 private: 78 mutable base::Mutex mutex_; 79 std::unordered_map<CacheKey, WasmCode*, CacheKeyHash> entry_map_; 80 }; 81 82 } // namespace wasm 83 } // namespace internal 84 } // namespace v8 85 86 #endif // V8_WASM_WASM_IMPORT_WRAPPER_CACHE_H_ 87