Skip to content

Commit a5999be

Browse files
jakobkummerowV8 LUCI CQ
authored andcommitted
[wasm] Share import wrappers per WasmEngine
IOW, share them per process, instead of duplicating them for each NativeModule. Detailed changes: - The WasmImportWrapperCache is promoted from having an instance per NativeModule to having an instance per WasmEngine. It also gets its own code space for storing wrappers. - Wrapper compilation functions now return a WasmCompilationResult instead of an already-published WasmCode, so that callers can decide where to put the WasmCode. That is done, specifically, by the WasmImportWrapperCache. - WasmCode objects used for wrappers now don't have a NativeModule, i.e. their native_module_ == nullptr. - Whereas wrappers previously had their lifetime implicitly tied to the NativeModule that owned them, we must now accurately track their refcount. - To this end, WasmDispatchTables get an off-heap WasmDispatchTableData, which keeps track of all wrappers referenced by the table. Storing this information off-heap is necessary so that it's still available when the table's finalizer is invoked (at which time the table itself can no longer be accessed). Using shared wrappers for WasmJSFunctions is left for a future patch. Bug: 42204526 Change-Id: I59d044b5d461a0e7ae8937e7965bd7e44f58b402 Reviewed-on: https://chromium-review.googlesource.com/c/v8/v8/+/5783527 Reviewed-by: Matthias Liedtke <[email protected]> Reviewed-by: Michael Lippautz <[email protected]> Commit-Queue: Jakob Kummerow <[email protected]> Cr-Commit-Position: refs/heads/main@{#95828}
1 parent 1a2b08e commit a5999be

24 files changed

Lines changed: 727 additions & 386 deletions

‎src/codegen/x64/macro-assembler-x64.cc‎

Lines changed: 2 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -776,28 +776,7 @@ void MacroAssembler::CallTSANStoreStub(Register address, Register value,
776776
// Prepare argument registers for calling GetTSANStoreStub.
777777
MovePair(address_parameter, address, value_parameter, value);
778778

779-
if (isolate()) {
780-
CallBuiltin(CodeFactory::GetTSANStoreStub(fp_mode, size, order));
781-
}
782-
#if V8_ENABLE_WEBASSEMBLY
783-
// There are two different kinds of wasm-to-js functions: one lives in the
784-
// wasm code space, and another one lives on the heap. Both of them have the
785-
// same CodeKind (WASM_TO_JS_FUNCTION), but depending on where they are they
786-
// have to either use the wasm stub calls, or call the builtin using the
787-
// isolate like JS does. In order to know which wasm-to-js function we are
788-
// compiling right now, we check if the isolate is null.
789-
// TODO(solanes, v8:11600): Split CodeKind::WASM_TO_JS_FUNCTION into two
790-
// different CodeKinds and pass the CodeKind as a parameter so that we can use
791-
// that instead of a nullptr check.
792-
// NOLINTNEXTLINE(readability/braces)
793-
else {
794-
DCHECK_EQ(mode, StubCallMode::kCallWasmRuntimeStub);
795-
// Use {near_call} for direct Wasm call within a module.
796-
auto wasm_target = static_cast<intptr_t>(
797-
wasm::WasmCode::GetTSANStoreBuiltin(fp_mode, size, order));
798-
near_call(wasm_target, RelocInfo::WASM_STUB_CALL);
799-
}
800-
#endif // V8_ENABLE_WEBASSEMBLY
779+
CallBuiltin(CodeFactory::GetTSANStoreStub(fp_mode, size, order));
801780

802781
PopAll(registers);
803782
}
@@ -816,28 +795,7 @@ void MacroAssembler::CallTSANRelaxedLoadStub(Register address,
816795
// Prepare argument registers for calling TSANRelaxedLoad.
817796
Move(address_parameter, address);
818797

819-
if (isolate()) {
820-
CallBuiltin(CodeFactory::GetTSANRelaxedLoadStub(fp_mode, size));
821-
}
822-
#if V8_ENABLE_WEBASSEMBLY
823-
// There are two different kinds of wasm-to-js functions: one lives in the
824-
// wasm code space, and another one lives on the heap. Both of them have the
825-
// same CodeKind (WASM_TO_JS_FUNCTION), but depending on where they are they
826-
// have to either use the wasm stub calls, or call the builtin using the
827-
// isolate like JS does. In order to know which wasm-to-js function we are
828-
// compiling right now, we check if the isolate is null.
829-
// TODO(solanes, v8:11600): Split CodeKind::WASM_TO_JS_FUNCTION into two
830-
// different CodeKinds and pass the CodeKind as a parameter so that we can use
831-
// that instead of a nullptr check.
832-
// NOLINTNEXTLINE(readability/braces)
833-
else {
834-
DCHECK_EQ(mode, StubCallMode::kCallWasmRuntimeStub);
835-
// Use {near_call} for direct Wasm call within a module.
836-
auto wasm_target = static_cast<intptr_t>(
837-
wasm::WasmCode::GetTSANRelaxedLoadBuiltin(fp_mode, size));
838-
near_call(wasm_target, RelocInfo::WASM_STUB_CALL);
839-
}
840-
#endif // V8_ENABLE_WEBASSEMBLY
798+
CallBuiltin(CodeFactory::GetTSANRelaxedLoadStub(fp_mode, size));
841799

842800
PopAll(registers);
843801
}

‎src/compiler/backend/code-generator.cc‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -942,11 +942,13 @@ bool CodeGenerator::GetSlotAboveSPBeforeTailCall(Instruction* instr,
942942
StubCallMode CodeGenerator::DetermineStubCallMode() const {
943943
#if V8_ENABLE_WEBASSEMBLY
944944
CodeKind code_kind = info()->code_kind();
945-
if (code_kind == CodeKind::WASM_FUNCTION ||
946-
code_kind == CodeKind::WASM_TO_CAPI_FUNCTION ||
947-
code_kind == CodeKind::WASM_TO_JS_FUNCTION) {
945+
if (code_kind == CodeKind::WASM_FUNCTION) {
948946
return StubCallMode::kCallWasmRuntimeStub;
949947
}
948+
if (code_kind == CodeKind::WASM_TO_CAPI_FUNCTION ||
949+
code_kind == CodeKind::WASM_TO_JS_FUNCTION) {
950+
return StubCallMode::kCallBuiltinPointer;
951+
}
950952
#endif // V8_ENABLE_WEBASSEMBLY
951953
return StubCallMode::kCallCodeObject;
952954
}

‎src/compiler/wasm-compiler.cc‎

Lines changed: 7 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -8708,8 +8708,8 @@ wasm::WasmCompilationResult CompileWasmImportCallWrapper(
87088708
return result;
87098709
}
87108710

8711-
wasm::WasmCode* CompileWasmCapiCallWrapper(wasm::NativeModule* native_module,
8712-
const wasm::FunctionSig* sig) {
8711+
wasm::WasmCompilationResult CompileWasmCapiCallWrapper(
8712+
wasm::NativeModule* native_module, const wasm::FunctionSig* sig) {
87138713
TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("v8.wasm.detailed"),
87148714
"wasm.CompileWasmCapiFunction");
87158715
const char* debug_name = "WasmCapiCall";
@@ -8747,31 +8747,17 @@ wasm::WasmCode* CompileWasmCapiCallWrapper(wasm::NativeModule* native_module,
87478747
call_descriptor, mcgraph, CodeKind::WASM_TO_CAPI_FUNCTION, debug_name,
87488748
WasmStubAssemblerOptions(), source_positions);
87498749
};
8750-
wasm::WasmCompilationResult result = v8_flags.turboshaft_wasm_wrappers
8751-
? compile_with_turboshaft()
8750+
return v8_flags.turboshaft_wasm_wrappers ? compile_with_turboshaft()
87528751
: compile_with_turbofan();
8753-
wasm::WasmCode* published_code;
8754-
{
8755-
std::unique_ptr<wasm::WasmCode> wasm_code = native_module->AddCode(
8756-
wasm::kAnonymousFuncIndex, result.code_desc, result.frame_slot_count,
8757-
result.ool_spill_count, result.tagged_parameter_slots,
8758-
result.protected_instructions_data.as_vector(),
8759-
result.source_positions.as_vector(),
8760-
result.inlining_positions.as_vector(), result.deopt_data.as_vector(),
8761-
wasm::WasmCode::kWasmToCapiWrapper, wasm::ExecutionTier::kNone,
8762-
wasm::kNotForDebugging);
8763-
published_code = native_module->PublishCode(std::move(wasm_code));
8764-
}
8765-
return published_code;
87668752
}
87678753

87688754
bool IsFastCallSupportedSignature(const v8::CFunctionInfo* sig) {
87698755
return fast_api_call::CanOptimizeFastSignature(sig);
87708756
}
87718757

8772-
wasm::WasmCode* CompileWasmJSFastCallWrapper(wasm::NativeModule* native_module,
8773-
const wasm::FunctionSig* sig,
8774-
Handle<JSReceiver> callable) {
8758+
wasm::WasmCompilationResult CompileWasmJSFastCallWrapper(
8759+
wasm::NativeModule* native_module, const wasm::FunctionSig* sig,
8760+
Handle<JSReceiver> callable) {
87758761
TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("v8.wasm.detailed"),
87768762
"wasm.CompileWasmJSFastCallWrapper");
87778763

@@ -8802,17 +8788,7 @@ wasm::WasmCode* CompileWasmJSFastCallWrapper(wasm::NativeModule* native_module,
88028788
wasm::WasmCompilationResult result = Pipeline::GenerateCodeForWasmNativeStub(
88038789
call_descriptor, mcgraph, CodeKind::WASM_TO_JS_FUNCTION, debug_name,
88048790
WasmStubAssemblerOptions(), source_positions);
8805-
{
8806-
std::unique_ptr<wasm::WasmCode> wasm_code = native_module->AddCode(
8807-
wasm::kAnonymousFuncIndex, result.code_desc, result.frame_slot_count,
8808-
result.ool_spill_count, result.tagged_parameter_slots,
8809-
result.protected_instructions_data.as_vector(),
8810-
result.source_positions.as_vector(),
8811-
result.inlining_positions.as_vector(), result.deopt_data.as_vector(),
8812-
wasm::WasmCode::kWasmToJsWrapper, wasm::ExecutionTier::kNone,
8813-
wasm::kNotForDebugging);
8814-
return native_module->PublishCode(std::move(wasm_code));
8815-
}
8791+
return result;
88168792
}
88178793

88188794
MaybeHandle<Code> CompileWasmToJSWrapper(Isolate* isolate,

‎src/compiler/wasm-compiler.h‎

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -77,14 +77,13 @@ V8_EXPORT_PRIVATE wasm::WasmCompilationResult CompileWasmImportCallWrapper(
7777
bool source_positions, int expected_arity, wasm::Suspend);
7878

7979
// Compiles a host call wrapper, which allows Wasm to call host functions.
80-
wasm::WasmCode* CompileWasmCapiCallWrapper(wasm::NativeModule*,
81-
const wasm::FunctionSig*);
80+
wasm::WasmCompilationResult CompileWasmCapiCallWrapper(
81+
wasm::NativeModule*, const wasm::FunctionSig*);
8282

8383
bool IsFastCallSupportedSignature(const v8::CFunctionInfo*);
8484
// Compiles a wrapper to call a Fast API function from Wasm.
85-
wasm::WasmCode* CompileWasmJSFastCallWrapper(wasm::NativeModule*,
86-
const wasm::FunctionSig*,
87-
Handle<JSReceiver> callable);
85+
wasm::WasmCompilationResult CompileWasmJSFastCallWrapper(
86+
wasm::NativeModule*, const wasm::FunctionSig*, Handle<JSReceiver> callable);
8887

8988
// Returns an TurbofanCompilationJob or TurboshaftCompilationJob object
9089
// (depending on the --turboshaft-wasm-wrappers flag) for a JS to Wasm wrapper.

‎src/heap/factory.cc‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,7 @@
6666
#include "src/objects/js-struct-inl.h"
6767
#include "src/objects/js-weak-refs-inl.h"
6868
#include "src/objects/literal-objects-inl.h"
69+
#include "src/objects/managed-inl.h"
6970
#include "src/objects/megadom-handler-inl.h"
7071
#include "src/objects/microtask-inl.h"
7172
#include "src/objects/module-inl.h"
@@ -1626,12 +1627,21 @@ Handle<WasmTrustedInstanceData> Factory::NewWasmTrustedInstanceData() {
16261627

16271628
Handle<WasmDispatchTable> Factory::NewWasmDispatchTable(int length) {
16281629
CHECK_LE(length, WasmDispatchTable::kMaxLength);
1630+
1631+
// TODO(jkummerow): Any chance to get a better estimate?
1632+
size_t estimated_offheap_size = 0;
1633+
Handle<TrustedManaged<WasmDispatchTableData>> offheap_data =
1634+
TrustedManaged<WasmDispatchTableData>::From(
1635+
isolate(), estimated_offheap_size,
1636+
std::make_shared<WasmDispatchTableData>());
1637+
16291638
int bytes = WasmDispatchTable::SizeFor(length);
16301639
Tagged<WasmDispatchTable> result = UncheckedCast<WasmDispatchTable>(
16311640
AllocateRawWithImmortalMap(bytes, AllocationType::kTrusted,
16321641
read_only_roots().wasm_dispatch_table_map()));
16331642
result->WriteField<int>(WasmDispatchTable::kLengthOffset, length);
16341643
result->WriteField<int>(WasmDispatchTable::kCapacityOffset, length);
1644+
result->set_protected_offheap_data(*offheap_data);
16351645
for (int i = 0; i < length; ++i) {
16361646
result->Clear(i);
16371647
result->clear_entry_padding(i);

‎src/heap/memory-measurement.cc‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,12 +14,12 @@
1414
#include "src/logging/counters.h"
1515
#include "src/objects/js-array-buffer-inl.h"
1616
#include "src/objects/js-promise-inl.h"
17-
#include "src/objects/smi.h"
1817
#include "src/tasks/task-utils.h"
1918

2019
#if V8_ENABLE_WEBASSEMBLY
2120
#include "src/wasm/wasm-code-manager.h"
2221
#include "src/wasm/wasm-engine.h"
22+
#include "src/wasm/wasm-import-wrapper-cache.h"
2323
#endif
2424

2525
namespace v8 {
@@ -238,7 +238,8 @@ void MemoryMeasurement::FinishProcessing(const NativeContextStats& stats) {
238238
#if V8_ENABLE_WEBASSEMBLY
239239
size_t wasm_code = wasm::GetWasmCodeManager()->committed_code_space();
240240
size_t wasm_metadata =
241-
wasm::GetWasmEngine()->EstimateCurrentMemoryConsumption();
241+
wasm::GetWasmEngine()->EstimateCurrentMemoryConsumption() +
242+
wasm::GetWasmImportWrapperCache()->EstimateCurrentMemoryConsumption();
242243
#endif
243244

244245
while (!processing_.empty()) {

‎src/logging/log.cc‎

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,7 @@
5656
#if V8_ENABLE_WEBASSEMBLY
5757
#include "src/wasm/wasm-code-manager.h"
5858
#include "src/wasm/wasm-engine.h"
59+
#include "src/wasm/wasm-import-wrapper-cache.h"
5960
#include "src/wasm/wasm-objects-inl.h"
6061
#endif // V8_ENABLE_WEBASSEMBLY
6162

@@ -1601,10 +1602,14 @@ void V8FileLogger::CodeCreateEvent(CodeTag tag, const wasm::WasmCode* code,
16011602
// We have to add two extra fields that allow the tick processor to group
16021603
// events for the same wasm function, even if it gets compiled again. For
16031604
// normal JS functions, we use the shared function info. For wasm, the pointer
1604-
// to the native module + function index works well enough.
1605+
// to the native module + function index works well enough. For Wasm wrappers,
1606+
// just use the address of the WasmCode.
16051607
// TODO(herhut) Clean up the tick processor code instead.
1606-
void* tag_ptr =
1607-
reinterpret_cast<uint8_t*>(code->native_module()) + code->index();
1608+
const void* tag_ptr =
1609+
code->native_module() != nullptr
1610+
? reinterpret_cast<uint8_t*>(code->native_module()) + code->index()
1611+
: reinterpret_cast<const uint8_t*>(code);
1612+
16081613
msg << kNext << tag_ptr << kNext << ComputeMarker(code);
16091614
msg.WriteToLogFile();
16101615
}
@@ -2614,6 +2619,7 @@ void ExistingCodeLogger::LogCompiledFunctions(
26142619
module_object->native_module()->LogWasmCodes(isolate_,
26152620
module_object->script());
26162621
}
2622+
wasm::GetWasmImportWrapperCache()->LogForIsolate(isolate_);
26172623
#endif // V8_ENABLE_WEBASSEMBLY
26182624
}
26192625

‎src/objects/objects-body-descriptors-inl.h‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1118,6 +1118,7 @@ class WasmDispatchTable::BodyDescriptor final : public BodyDescriptorBase {
11181118
template <typename ObjectVisitor>
11191119
static inline void IterateBody(Tagged<Map> map, Tagged<HeapObject> obj,
11201120
int object_size, ObjectVisitor* v) {
1121+
IterateProtectedPointer(obj, kProtectedOffheapDataOffset, v);
11211122
int length = Cast<WasmDispatchTable>(obj)->length(kAcquireLoad);
11221123
for (int i = 0; i < length; ++i) {
11231124
IterateProtectedPointer(obj, OffsetOf(i) + kImplicitArgBias, v);

‎src/runtime/runtime-wasm.cc‎

Lines changed: 13 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -625,6 +625,7 @@ RUNTIME_FUNCTION(Runtime_TierUpWasmToJSWrapper) {
625625
if (IsWasmFuncRef(*origin)) {
626626
// The tierup for `WasmInternalFunction is special, as there may not be an
627627
// instance.
628+
// TODO(jkummerow): Use the WasmImportWrapperCache here.
628629
size_t expected_arity = sig.parameter_count();
629630
wasm::ImportCallKind kind = wasm::kDefaultImportCallKind;
630631
if (IsJSFunction(import_data->callable())) {
@@ -710,7 +711,6 @@ RUNTIME_FUNCTION(Runtime_TierUpWasmToJSWrapper) {
710711
wasm::ImportCallKind kind = resolved.kind();
711712
callable = resolved.callable(); // Update to ultimate target.
712713
DCHECK_NE(wasm::ImportCallKind::kLinkError, kind);
713-
wasm::CompilationEnv env = wasm::CompilationEnv::ForModule(native_module);
714714
// {expected_arity} should only be used if kind != kJSFunctionArityMismatch.
715715
int expected_arity = static_cast<int>(sig.parameter_count());
716716
if (kind == wasm::ImportCallKind ::kJSFunctionArityMismatch) {
@@ -719,36 +719,31 @@ RUNTIME_FUNCTION(Runtime_TierUpWasmToJSWrapper) {
719719
->internal_formal_parameter_count_without_receiver();
720720
}
721721

722-
wasm::WasmImportWrapperCache* cache = native_module->import_wrapper_cache();
722+
wasm::WasmImportWrapperCache* cache = wasm::GetWasmImportWrapperCache();
723723
wasm::WasmCode* wasm_code =
724724
cache->MaybeGet(kind, canonical_sig_index, expected_arity, suspend);
725725
if (!wasm_code) {
726+
wasm::CompilationEnv env = wasm::CompilationEnv::ForModule(native_module);
726727
wasm::WasmCompilationResult result = compiler::CompileWasmImportCallWrapper(
727728
&env, kind, &sig, false, expected_arity, suspend);
728-
std::unique_ptr<wasm::WasmCode> compiled_code = native_module->AddCode(
729-
result.func_index, result.code_desc, result.frame_slot_count,
730-
result.ool_spill_count, result.tagged_parameter_slots,
731-
result.protected_instructions_data.as_vector(),
732-
result.source_positions.as_vector(),
733-
result.inlining_positions.as_vector(), result.deopt_data.as_vector(),
734-
GetCodeKind(result), wasm::ExecutionTier::kNone,
735-
wasm::kNotForDebugging);
736-
wasm_code = native_module->PublishCode(std::move(compiled_code));
729+
wasm::WasmImportWrapperCache::ModificationScope cache_scope(cache);
730+
wasm::WasmImportWrapperCache::CacheKey key(kind, canonical_sig_index,
731+
expected_arity, suspend);
732+
wasm_code = cache_scope.AddWrapper(key, std::move(result),
733+
wasm::WasmCode::Kind::kWasmToJsWrapper);
737734
isolate->counters()->wasm_generated_code_size()->Increment(
738735
wasm_code->instructions().length());
739736
isolate->counters()->wasm_reloc_size()->Increment(
740737
wasm_code->reloc_info().length());
741738
if (V8_UNLIKELY(native_module->log_code())) {
742-
wasm::GetWasmEngine()->LogCode(base::VectorOf(&wasm_code, 1));
739+
wasm::GetWasmEngine()->LogWrapperCode(base::VectorOf(&wasm_code, 1));
743740
// Log the code immediately in the current isolate.
744741
wasm::GetWasmEngine()->LogOutstandingCodesForIsolate(isolate);
745742
}
746-
747-
wasm::WasmImportWrapperCache::ModificationScope cache_scope(cache);
748-
wasm::WasmImportWrapperCache::CacheKey key(kind, canonical_sig_index,
749-
expected_arity, suspend);
750-
cache_scope[key] = wasm_code;
751743
}
744+
// Note: we don't need to decrement any refcounts here, because tier-up
745+
// doesn't overwrite an existing compiled wrapper, and the generic wrapper
746+
// isn't refcounted.
752747

753748
if (WasmImportData::CallOriginIsImportIndex(origin)) {
754749
int func_index = WasmImportData::CallOriginAsIndex(origin);
@@ -765,6 +760,7 @@ RUNTIME_FUNCTION(Runtime_TierUpWasmToJSWrapper) {
765760
trusted_data->dispatch_table(table_index);
766761
if (entry_index < table->length() &&
767762
table->implicit_arg(entry_index) == *import_data) {
763+
table->offheap_data()->Add(wasm_code->instruction_start());
768764
table->SetTarget(entry_index, wasm_code->instruction_start());
769765
// {ref} is used in at most one table.
770766
break;

0 commit comments

Comments
 (0)