blob: acd4a299da1ad5d0cad0231c55ffbe5a6debb14c [file] [log] [blame]
Rubin Xu7bc1b612021-02-16 09:38:50 +00001// 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
11namespace v8 {
12namespace internal {
13
14class Counters;
15
16namespace wasm {
17
18class WasmCode;
19class WasmEngine;
20
21using FunctionSig = Signature<ValueType>;
22
23// Implements a cache for import wrappers.
24class WasmImportWrapperCache {
25 public:
26 struct CacheKey {
27 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:
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:
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_