This is the implementation of https://github.com/bytecodealliance/wasmtime/issues/4155, using the "inverted API" approach suggested by @cfallin (thanks!) in Cranelift, and trait object to provide a backend for an all-included experience in Wasmtime. After the suggestion of Chris, `Function` has been split into mostly two parts: - on the one hand, `FunctionStencil` contains all the fields required during compilation, and that act as a compilation cache key: if two function stencils are the same, then the result of their compilation (`CompiledCodeBase<Stencil>`) will be the same. This makes caching trivial, as the only thing to cache is the `FunctionStencil`. - on the other hand, `FunctionParameters` contain the... function parameters that are required to finalize the result of compilation into a `CompiledCode` (aka `CompiledCodeBase<Final>`) with proper final relocations etc., by applying fixups and so on. Most changes are here to accomodate those requirements, in particular that `FunctionStencil` should be `Hash`able to be used as a key in the cache: - most source locations are now relative to a base source location in the function, and as such they're encoded as `RelSourceLoc` in the `FunctionStencil`. This required changes so that there's no need to explicitly mark a `SourceLoc` as the base source location, it's automatically detected instead the first time a non-default `SourceLoc` is set. - user-defined external names in the `FunctionStencil` (aka before this patch `ExternalName::User { namespace, index }`) are now references into an external table of `UserExternalNameRef -> UserExternalName`, present in the `FunctionParameters`, and must be explicitly declared using `Function::declare_imported_user_function`. - some refactorings have been made for function names: - `ExternalName` was used as the type for a `Function`'s name; while it thus allowed `ExternalName::Libcall` in this place, this would have been quite confusing to use it there. Instead, a new enum `UserFuncName` is introduced for this name, that's either a user-defined function name (the above `UserExternalName`) or a test case name. - The future of `ExternalName` is likely to become a full reference into the `FunctionParameters`'s mapping, instead of being "either a handle for user-defined external names, or the thing itself for other variants". I'm running out of time to do this, and this is not trivial as it implies touching ISLE which I'm less familiar with. The cache computes a sha256 hash of the `FunctionStencil`, and uses this as the cache key. No equality check (using `PartialEq`) is performed in addition to the hash being the same, as we hope that this is sufficient data to avoid collisions. A basic fuzz target has been introduced that tries to do the bare minimum: - check that a function successfully compiled and cached will be also successfully reloaded from the cache, and returns the exact same function. - check that a trivial modification in the external mapping of `UserExternalNameRef -> UserExternalName` hits the cache, and that other modifications don't hit the cache. - This last check is less efficient and less likely to happen, so probably should be rethought a bit. Thanks to both @alexcrichton and @cfallin for your very useful feedback on Zulip. Some numbers show that for a large wasm module we're using internally, this is a 20% compile-time speedup, because so many `FunctionStencil`s are the same, even within a single module. For a group of modules that have a lot of code in common, we get hit rates up to 70% when they're used together. When a single function changes in a wasm module, every other function is reloaded; that's still slower than I expect (between 10% and 50% of the overall compile time), so there's likely room for improvement. Fixes #4155.
107 lines
3.5 KiB
Rust
107 lines
3.5 KiB
Rust
//! Implements the function environment (e.g. a name-to-function mapping) for interpretation.
|
|
use cranelift_codegen::ir::{FuncRef, Function};
|
|
use cranelift_entity::{entity_impl, PrimaryMap};
|
|
use std::collections::HashMap;
|
|
|
|
/// A function store contains all of the functions that are accessible to an interpreter.
|
|
#[derive(Default, Clone)]
|
|
pub struct FunctionStore<'a> {
|
|
functions: PrimaryMap<FuncIndex, &'a Function>,
|
|
function_names: HashMap<String, FuncIndex>,
|
|
}
|
|
|
|
/// An opaque reference to a [`Function`](Function) stored in the [FunctionStore].
|
|
#[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
|
pub struct FuncIndex(u32);
|
|
entity_impl!(FuncIndex, "fn");
|
|
|
|
/// This is a helpful conversion for instantiating a store from a single [Function].
|
|
impl<'a> From<&'a Function> for FunctionStore<'a> {
|
|
fn from(function: &'a Function) -> Self {
|
|
let mut store = FunctionStore::default();
|
|
store.add(function.name.to_string(), function);
|
|
store
|
|
}
|
|
}
|
|
|
|
impl<'a> FunctionStore<'a> {
|
|
/// Add a function by name.
|
|
pub fn add(&mut self, name: String, function: &'a Function) {
|
|
assert!(!self.function_names.contains_key(&name));
|
|
let index = self.functions.push(function);
|
|
self.function_names.insert(name, index);
|
|
}
|
|
|
|
/// Retrieve the index of a function in the function store by its `name`.
|
|
pub fn index_of(&self, name: &str) -> Option<FuncIndex> {
|
|
self.function_names.get(name).cloned()
|
|
}
|
|
|
|
/// Retrieve a function by its index in the function store.
|
|
pub fn get_by_index(&self, index: FuncIndex) -> Option<&'a Function> {
|
|
self.functions.get(index).cloned()
|
|
}
|
|
|
|
/// Retrieve a function by its name.
|
|
pub fn get_by_name(&self, name: &str) -> Option<&'a Function> {
|
|
let index = self.index_of(name)?;
|
|
self.get_by_index(index)
|
|
}
|
|
|
|
/// Retrieve a function from a [FuncRef] within a [Function]. TODO this should be optimized, if possible, as
|
|
/// currently it retrieves the function name as a string and performs string matching.
|
|
pub fn get_from_func_ref(
|
|
&self,
|
|
func_ref: FuncRef,
|
|
function: &Function,
|
|
) -> Option<&'a Function> {
|
|
self.get_by_name(&get_function_name(func_ref, function))
|
|
}
|
|
}
|
|
|
|
/// Retrieve a function name from a [FuncRef] within a [Function]. TODO this should be optimized, if possible, as
|
|
/// currently it retrieves the function name as a string and performs string matching.
|
|
fn get_function_name(func_ref: FuncRef, function: &Function) -> String {
|
|
function
|
|
.stencil
|
|
.dfg
|
|
.ext_funcs
|
|
.get(func_ref)
|
|
.expect("function to exist")
|
|
.name
|
|
.display(Some(&function.params))
|
|
.to_string()
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
use cranelift_codegen::ir::{Signature, UserFuncName};
|
|
use cranelift_codegen::isa::CallConv;
|
|
|
|
#[test]
|
|
fn addition() {
|
|
let mut env = FunctionStore::default();
|
|
let a = "a";
|
|
let f = Function::new();
|
|
|
|
env.add(a.to_string(), &f);
|
|
assert!(env.get_by_name(a).is_some());
|
|
}
|
|
|
|
#[test]
|
|
fn nonexistence() {
|
|
let env = FunctionStore::default();
|
|
assert!(env.get_by_name("a").is_none());
|
|
}
|
|
|
|
#[test]
|
|
fn from() {
|
|
let name = UserFuncName::testcase("test");
|
|
let signature = Signature::new(CallConv::Fast);
|
|
let func = &Function::with_name_signature(name, signature);
|
|
let env: FunctionStore = func.into();
|
|
assert_eq!(env.index_of("%test"), Some(FuncIndex::from_u32(0)));
|
|
}
|
|
}
|