Skip to content

Truly independent web browser

LibWasm+LibWeb: Reduce allocations when calling imported functions

Timothy Flynn6e99b180b1b5
diff --git a/Libraries/LibWasm/Engine/src/runtime/mod.rs b/Libraries/LibWasm/Engine/src/runtime/mod.rs
index 83e5c3099d9..ce8ca5a8544 100644
--- a/Libraries/LibWasm/Engine/src/runtime/mod.rs
+++ b/Libraries/LibWasm/Engine/src/runtime/mod.rs
@@ -1232,13 +1232,22 @@ impl Store {
let function = unsafe { address.get() };
let parameter_slots = function.header.param_slots as usize;
let slots = unsafe { ak::slice_from_raw_parts(arguments, parameter_slots) };
- let mut values = Vec::with_capacity(function.ty.params.len());
+ // Host calls are frequent in code that uses JavaScript wrappers for exception handling. Most have only a
+ // few arguments, so keep those on the stack instead of allocating a vector for each call.
+ let mut small_values = [Value::I32(0); 8];
+ let mut large_values = Vec::new();
+ let values = if function.ty.params.len() <= small_values.len() {
+ &mut small_values[..function.ty.params.len()]
+ } else {
+ large_values.resize(function.ty.params.len(), Value::I32(0));
+ &mut large_values
+ };
let mut slot = parameter_slots;
- for &ty in &function.ty.params {
+ for (value, &ty) in values.iter_mut().zip(&function.ty.params) {
slot -= ty.slot_count() as usize;
- values.push(Value::from_slots(ty, &slots[slot..]));
+ *value = Value::from_slots(ty, &slots[slot..]);
}
- let values = self.call_host(address, &values)?;
+ let values = self.call_host(address, values)?;
let mut next = results;
for value in values.iter().rev() {
let (value, count) = value.to_slots();
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_assembly/exported_function.rs b/Libraries/LibWeb/Bindings/Rust/src/web_assembly/exported_function.rs
index 694b0d9f2b1..7e498652130 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/web_assembly/exported_function.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_assembly/exported_function.rs
@@ -218,6 +218,7 @@ struct HostFunctionSteps {
function: Gc<FunctionObject>,
ty: FuncType,
index: u32,
+ use_stack_arguments: bool,
}
impl HostFunction for HostFunctionSteps {
@@ -228,7 +229,7 @@ impl HostFunction for HostFunctionSteps {
let agent = Agent::current();
let vm = agent.vm();
// FIXME: The settings steps around the call.
- let result = run_a_host_function(vm, self.function, &self.ty, arguments);
+ let result = run_a_host_function(vm, self.function, &self.ty, arguments, self.use_stack_arguments);
let throw = match result {
Ok(results) => return Ok(results),
@@ -267,6 +268,7 @@ fn run_a_host_function(
function: Gc<FunctionObject>,
functype: &FuncType,
arguments: &[WasmValue],
+ use_stack_arguments: bool,
) -> ThrowCompletionOr<Vec<WasmValue>> {
// 1. Let func parameters → results be the expansion of functype.
let FuncType {
@@ -282,22 +284,34 @@ fn run_a_host_function(
);
}
- // 3. Let jsArguments be « ».
- let js_arguments = MarkedVec::with_capacity(vm, arguments.len());
+ let callee = Value::from_object(function.upcast::<Object>());
- // 4. For each arg of arguments,
- for (arg, &parameter) in arguments.iter().zip(parameters) {
- // 1. Append ToJSValue(arg) to jsArguments.
- js_arguments.push(to_js_value(vm, *arg, parameter)?);
- }
+ // OPTIMIZATION: These conversions produce only Numbers, so the arguments need no GC roots.
+ let ret = if use_stack_arguments {
+ // 3. Let jsArguments be « ».
+ let mut js_arguments = [Value::UNDEFINED; STACK_SLOT_CAPACITY];
- // 5. Let ret be ? Call(func, undefined, jsArguments).
- let ret = call(
- vm,
- Value::from_object(function.upcast::<Object>()),
- Value::UNDEFINED,
- &js_arguments.values(),
- )?;
+ // 4. For each arg of arguments,
+ for (i, (arg, &parameter)) in arguments.iter().zip(parameters).enumerate() {
+ // 1. Append ToJSValue(arg) to jsArguments.
+ js_arguments[i] = to_js_value(vm, *arg, parameter)?;
+ }
+
+ // 5. Let ret be ? Call(func, undefined, jsArguments).
+ call(vm, callee, Value::UNDEFINED, &js_arguments[..arguments.len()])?
+ } else {
+ // 3. Let jsArguments be « ».
+ let js_arguments = MarkedVec::with_capacity(vm, arguments.len());
+
+ // 4. For each arg of arguments,
+ for (arg, &parameter) in arguments.iter().zip(parameters) {
+ // 1. Append ToJSValue(arg) to jsArguments.
+ js_arguments.push(to_js_value(vm, *arg, parameter)?);
+ }
+
+ // 5. Let ret be ? Call(func, undefined, jsArguments).
+ call(vm, callee, Value::UNDEFINED, &js_arguments.values())?
+ };
// 6. Let resultsSize be results's size.
// 7. If resultsSize is 0, return « ».
@@ -305,17 +319,18 @@ fn run_a_host_function(
return Ok(Vec::new());
}
- // NB: The converted values may refer to new cells, which the cell of the values keeps alive until the engine has
- // them.
- let converted = WasmValues::allocate(vm);
-
// 8. Otherwise, if resultsSize is 1, return « ? ToWebAssemblyValue(ret, results[0]) ».
if results.len() == 1 {
let value = to_webassembly_value(vm, ret, results[0])?;
- converted.0.borrow_mut().push(value);
+ // OPTIMIZATION: No further conversion or GC allocation can occur before the engine receives this value.
+ return Ok(vec![value]);
}
+
+ // NB: Converting subsequent results can collect garbage, so keep earlier reference results in a traced cell.
+ let converted = WasmValues::allocate(vm);
+
// 9. Otherwise,
- else {
+ {
// 1. Let method be ? GetMethod(ret, %Symbol.iterator%).
let method = ret.get_method(vm, &PropertyKey::from(vm.well_known_symbols().iterator))?;
@@ -379,6 +394,11 @@ pub(crate) fn create_host_function(vm: &Vm, function: Gc<FunctionObject>, ty: Fu
)]
let steps: HostCallback = Rc::new(HostFunctionSteps {
function,
+ use_stack_arguments: ty.params.len() <= STACK_SLOT_CAPACITY
+ && ty
+ .params
+ .iter()
+ .all(|ty| matches!(ty, ValType::I32 | ValType::F32 | ValType::F64)),
ty: ty.clone(),
index,
});
diff --git a/Tests/LibWeb/Text/expected/Wasm/WebAssembly-host-call-arguments.txt b/Tests/LibWeb/Text/expected/Wasm/WebAssembly-host-call-arguments.txt
new file mode 100644
index 00000000000..1c9c3864c7a
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/Wasm/WebAssembly-host-call-arguments.txt
@@ -0,0 +1,6 @@
+numeric arguments across nested calls: true
+reexported import: true
+wide arguments: 1, 2, 3, 4, 5, 6, 7, 8, 9
+rooted arguments: true
+host exception: true
+call after exception and result coercion: 42
diff --git a/Tests/LibWeb/Text/input/Wasm/WebAssembly-host-call-arguments.html b/Tests/LibWeb/Text/input/Wasm/WebAssembly-host-call-arguments.html
new file mode 100644
index 00000000000..e665bcf4875
--- /dev/null
+++ b/Tests/LibWeb/Text/input/Wasm/WebAssembly-host-call-arguments.html
@@ -0,0 +1,65 @@
+<!doctype html>
+<script src="../include.js"></script>
+<script>
+ // (module (type (func (param T...) (result T...)))
+ // (import "m" "f" (func (type 0)))
+ // (export "imported" (func 0))
+ // (func (export "forward") (type 0) (call 0 (local.get 0) ...)))
+ function forwardingModule(types, callback) {
+ const section = (id, bytes) => [id, bytes.length, ...bytes];
+ const string = value => [value.length, ...Array.from(value, c => c.charCodeAt(0))];
+ const body = [0, ...types.flatMap((_, i) => [0x20, i]), 0x10, 0, 0x0b];
+ return new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([
+ 0, 97, 115, 109, 1, 0, 0, 0,
+ ...section(1, [1, 0x60, types.length, ...types, types.length, ...types]),
+ ...section(2, [1, ...string("m"), ...string("f"), 0, 0]),
+ ...section(3, [1, 0]),
+ ...section(7, [2, ...string("imported"), 0, 0, ...string("forward"), 0, 1]),
+ ...section(10, [1, body.length, ...body]),
+ ])), { m: { f: callback } }).exports;
+ }
+
+ test(() => {
+ const i32 = 0x7f, i64 = 0x7e, f32 = 0x7d, f64 = 0x7c, externref = 0x6f;
+ const nested = forwardingModule([i32], value => value + 1).forward;
+ const types = [i32, f32, f64, i32, f64, f32, i32, f64];
+ const values = [-2147483648, Math.fround(1 / 3), -0, 2147483647, Infinity, -Infinity, 42, NaN];
+ let calls = 0;
+ const functions = forwardingModule(types, (...args) => {
+ if (calls++ % 1024 === 0)
+ internals.gc();
+ if (nested(99) !== 100)
+ throw new Error("nested call failed");
+ return args;
+ });
+ let correct = true;
+ for (let i = 0; i < 2000; ++i) {
+ const result = functions.forward(...values);
+ correct &&= result.every((value, index) => Object.is(value, values[index]));
+ }
+ println(`numeric arguments across nested calls: ${correct}`);
+ println(`reexported import: ${functions.imported(...values).every((v, i) => Object.is(v, values[i]))}`);
+ println(`wide arguments: ${forwardingModule(Array(9).fill(i32), (...args) => args).forward(1, 2, 3, 4, 5, 6, 7, 8, 9).join(", ")}`);
+
+ const object = { marker: 42 };
+ const refs = forwardingModule([i64, externref], (integer, ref) => {
+ internals.gc();
+ nested(1);
+ return [integer, ref];
+ }).forward((1n << 63n) - 1n, object);
+ println(`rooted arguments: ${refs[0] === (1n << 63n) - 1n && refs[1] === object}`);
+
+ const sentinel = {};
+ const throwing = forwardingModule([i32], value => {
+ if (value === 0)
+ throw sentinel;
+ return { valueOf() { internals.gc(); return nested(value); } };
+ }).forward;
+ try {
+ throwing(0);
+ } catch (e) {
+ println(`host exception: ${e === sentinel}`);
+ }
+ println(`call after exception and result coercion: ${throwing(41)}`);
+ });
+</script>