Optimize Func::call and its C API (#3319)

* Optimize `Func::call` and its C API

This commit is an alternative to #3298 which achieves effectively the
same goal of optimizing the `Func::call` API as well as its C API
sibling of `wasmtime_func_call`. The strategy taken here is different
than #3298 though where a new API isn't created, rather a small tweak to
an existing API is done. Specifically this commit handles the major
sources of slowness with `Func::call` with:

* Looking up the type of a function, to typecheck the arguments with and
  use to guide how the results should be loaded, no longer hits the
  rwlock in the `Engine` but instead each `Func` contains its own
  `FuncType`. This can be an unnecessary allocation for funcs not used
  with `Func::call`, so this is a downside of this implementation
  relative to #3298. A mitigating factor, though, is that instance
  exports are loaded lazily into the `Store` and in theory not too many
  funcs are active in the store as `Func` objects.

* Temporary storage is amortized with a long-lived `Vec` in the `Store`
  rather than allocating a new vector on each call. This is basically
  the same strategy as #3294 only applied to different types in
  different places. Specifically `wasmtime::Store` now retains a
  `Vec<u128>` for `Func::call`, and the C API retains a `Vec<Val>` for
  calling `Func::call`.

* Finally, an API breaking change is made to `Func::call` and its type
  signature (as well as `Func::call_async`). Instead of returning
  `Box<[Val]>` as it did before this function now takes a
  `results: &mut [Val]` parameter. This allows the caller to manage the
  allocation and we can amortize-remove it in `wasmtime_func_call` by
  using space after the parameters in the `Vec<Val>` we're passing in.
  This change is naturally a breaking change and we'll want to consider
  it carefully, but mitigating factors are that most embeddings are
  likely using `TypedFunc::call` instead and this signature taking a
  mutable slice better aligns with `Func::new` which receives a mutable
  slice for the results.

Overall this change, in the benchmark of "call a nop function from the C
API" is not quite as good as #3298. It's still a bit slower, on the
order of 15ns, because there's lots of capacity checks around vectors
and the type checks are slightly less optimized than before. Overall
though this is still significantly better than today because allocations
and the rwlock to acquire the type information are both avoided. I
personally feel that this change is the best to do because it has less
of an API impact than #3298.

* Rebase issues
This commit is contained in:
Alex Crichton
2021-09-21 14:07:05 -05:00
committed by GitHub
parent 38463d11ed
commit bcf3544924
26 changed files with 399 additions and 253 deletions

View File

@@ -297,8 +297,10 @@ pub fn differential_execution(
let ty = f.ty(&store);
let params = dummy::dummy_values(ty.params());
let mut results = vec![Val::I32(0); ty.results().len()];
let this_result = f
.call(&mut store, &params)
.call(&mut store, &params, &mut results)
.map(|()| results.into())
.map_err(|e| e.downcast::<Trap>().unwrap());
let existing_result = export_func_results
@@ -312,7 +314,7 @@ pub fn differential_execution(
match instance.get_export(&mut *store, "hangLimitInitializer") {
None => return,
Some(Extern::Func(f)) => {
f.call(store, &[])
f.call(store, &[], &mut [])
.expect("initializing the hang limit should not fail");
}
Some(_) => panic!("unexpected hangLimitInitializer export"),
@@ -478,7 +480,8 @@ pub fn make_api_calls(api: crate::generators::api::ApiCalls) {
let f = &funcs[nth];
let ty = f.ty(&store);
let params = dummy::dummy_values(ty.params());
let _ = f.call(store, &params);
let mut results = vec![Val::I32(0); ty.results().len()];
let _ = f.call(store, &params, &mut results);
}
}
}
@@ -636,7 +639,7 @@ pub fn table_ops(
let args: Vec<_> = (0..ops.num_params())
.map(|_| Val::ExternRef(Some(ExternRef::new(CountDrops(num_dropped.clone())))))
.collect();
let _ = run.call(&mut store, &args);
let _ = run.call(&mut store, &args, &mut []);
}
assert_eq!(num_dropped.load(SeqCst), expected_drops.load(SeqCst));
@@ -740,7 +743,7 @@ pub fn differential_wasmi_execution(wasm: &[u8], config: &crate::generators::Con
// Introspect wasmtime module to find name of an exported function and of an
// exported memory.
let (func_name, _ty) = first_exported_function(&wasmtime_module)?;
let (func_name, ty) = first_exported_function(&wasmtime_module)?;
let memory_name = first_exported_memory(&wasmtime_module)?;
let wasmi_mem_export = wasmi_instance.export_by_name(memory_name).unwrap();
@@ -755,8 +758,10 @@ pub fn differential_wasmi_execution(wasm: &[u8], config: &crate::generators::Con
let wasmtime_main = wasmtime_instance
.get_func(&mut wasmtime_store, func_name)
.expect("function export is present");
let wasmtime_vals = wasmtime_main.call(&mut wasmtime_store, &[]);
let wasmtime_val = wasmtime_vals.map(|v| v.iter().next().cloned());
let mut wasmtime_results = vec![Val::I32(0); ty.results().len()];
let wasmtime_val = wasmtime_main
.call(&mut wasmtime_store, &[], &mut wasmtime_results)
.map(|()| wasmtime_results.get(0).cloned());
debug!(
"Successful execution: wasmi returned {:?}, wasmtime returned {:?}",
@@ -918,15 +923,17 @@ fn run_in_wasmtime(
.context("Wasmtime cannot instantiate module")?;
// Find the first exported function.
let (func_name, _ty) =
let (func_name, ty) =
first_exported_function(&wasmtime_module).context("Cannot find exported function")?;
let wasmtime_main = wasmtime_instance
.get_func(&mut wasmtime_store, &func_name[..])
.expect("function export is present");
// Execute the function and return the values.
let wasmtime_vals = wasmtime_main.call(&mut wasmtime_store, params);
wasmtime_vals.map(|v| v.to_vec())
let mut results = vec![Val::I32(0); ty.results().len()];
wasmtime_main
.call(&mut wasmtime_store, params, &mut results)
.map(|()| results)
}
// Introspect wasmtime module to find the name of the first exported function.

View File

@@ -93,7 +93,9 @@ pub fn differential_v8_execution(wasm: &[u8], config: &crate::generators::Config
let wasmtime_main = wasmtime_instance
.get_func(&mut wasmtime_store, func)
.expect("function export is present");
let wasmtime_vals = wasmtime_main.call(&mut wasmtime_store, &wasmtime_params);
let mut wasmtime_vals = vec![Val::I32(0); ty.results().len()];
let wasmtime_result =
wasmtime_main.call(&mut wasmtime_store, &wasmtime_params, &mut wasmtime_vals);
log::trace!("finished wasmtime invocation");
// V8: call the first exported func
@@ -112,15 +114,15 @@ pub fn differential_v8_execution(wasm: &[u8], config: &crate::generators::Config
log::trace!("finished v8 invocation");
// Verify V8 and wasmtime match
match (wasmtime_vals, v8_vals) {
(Ok(wasmtime), Ok(v8)) => {
match (wasmtime_result, v8_vals) {
(Ok(()), Ok(v8)) => {
log::trace!("both executed successfully");
match wasmtime.len() {
match wasmtime_vals.len() {
0 => assert!(v8.is_undefined()),
1 => assert_val_match(&wasmtime[0], &v8, &mut scope),
1 => assert_val_match(&wasmtime_vals[0], &v8, &mut scope),
_ => {
let array = v8::Local::<'_, v8::Array>::try_from(v8).unwrap();
for (i, wasmtime) in wasmtime.iter().enumerate() {
for (i, wasmtime) in wasmtime_vals.iter().enumerate() {
let v8 = array.get_index(&mut scope, i as u32).unwrap();
assert_val_match(wasmtime, &v8, &mut scope);
// ..
@@ -128,7 +130,7 @@ pub fn differential_v8_execution(wasm: &[u8], config: &crate::generators::Config
}
}
}
(Ok(_), Err(msg)) => {
(Ok(()), Err(msg)) => {
panic!("wasmtime succeeded at invocation, v8 failed: {}", msg)
}
(Err(err), Ok(_)) => {