Implement an incremental compilation cache for Cranelift (#4551)
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.
This commit is contained in:
@@ -3,12 +3,14 @@
|
||||
use cranelift_codegen::binemit::{Addend, CodeOffset, Reloc};
|
||||
use cranelift_codegen::entity::PrimaryMap;
|
||||
use cranelift_codegen::ir;
|
||||
use cranelift_codegen::MachReloc;
|
||||
use std::borrow::ToOwned;
|
||||
use std::boxed::Box;
|
||||
use std::string::String;
|
||||
use std::vec::Vec;
|
||||
|
||||
use crate::module::ModuleReloc;
|
||||
use crate::ModuleExtName;
|
||||
|
||||
/// This specifies how data is to be initialized.
|
||||
#[derive(Clone, PartialEq, Eq, Debug)]
|
||||
pub enum Init {
|
||||
@@ -43,9 +45,9 @@ pub struct DataDescription {
|
||||
/// How the data should be initialized.
|
||||
pub init: Init,
|
||||
/// External function declarations.
|
||||
pub function_decls: PrimaryMap<ir::FuncRef, ir::ExternalName>,
|
||||
pub function_decls: PrimaryMap<ir::FuncRef, ModuleExtName>,
|
||||
/// External data object declarations.
|
||||
pub data_decls: PrimaryMap<ir::GlobalValue, ir::ExternalName>,
|
||||
pub data_decls: PrimaryMap<ir::GlobalValue, ModuleExtName>,
|
||||
/// Function addresses to write at specified offsets.
|
||||
pub function_relocs: Vec<(CodeOffset, ir::FuncRef)>,
|
||||
/// Data addresses to write at specified offsets.
|
||||
@@ -59,11 +61,14 @@ pub struct DataDescription {
|
||||
|
||||
impl DataDescription {
|
||||
/// An iterator over all relocations of the data object.
|
||||
pub fn all_relocs<'a>(&'a self, pointer_reloc: Reloc) -> impl Iterator<Item = MachReloc> + 'a {
|
||||
pub fn all_relocs<'a>(
|
||||
&'a self,
|
||||
pointer_reloc: Reloc,
|
||||
) -> impl Iterator<Item = ModuleReloc> + 'a {
|
||||
let func_relocs = self
|
||||
.function_relocs
|
||||
.iter()
|
||||
.map(move |&(offset, id)| MachReloc {
|
||||
.map(move |&(offset, id)| ModuleReloc {
|
||||
kind: pointer_reloc,
|
||||
offset,
|
||||
name: self.function_decls[id].clone(),
|
||||
@@ -72,7 +77,7 @@ impl DataDescription {
|
||||
let data_relocs = self
|
||||
.data_relocs
|
||||
.iter()
|
||||
.map(move |&(offset, id, addend)| MachReloc {
|
||||
.map(move |&(offset, id, addend)| ModuleReloc {
|
||||
kind: pointer_reloc,
|
||||
offset,
|
||||
name: self.data_decls[id].clone(),
|
||||
@@ -144,7 +149,7 @@ impl DataContext {
|
||||
/// Users of the `Module` API generally should call
|
||||
/// `Module::declare_func_in_data` instead, as it takes care of generating
|
||||
/// the appropriate `ExternalName`.
|
||||
pub fn import_function(&mut self, name: ir::ExternalName) -> ir::FuncRef {
|
||||
pub fn import_function(&mut self, name: ModuleExtName) -> ir::FuncRef {
|
||||
self.description.function_decls.push(name)
|
||||
}
|
||||
|
||||
@@ -155,7 +160,7 @@ impl DataContext {
|
||||
/// Users of the `Module` API generally should call
|
||||
/// `Module::declare_data_in_data` instead, as it takes care of generating
|
||||
/// the appropriate `ExternalName`.
|
||||
pub fn import_global_value(&mut self, name: ir::ExternalName) -> ir::GlobalValue {
|
||||
pub fn import_global_value(&mut self, name: ModuleExtName) -> ir::GlobalValue {
|
||||
self.description.data_decls.push(name)
|
||||
}
|
||||
|
||||
@@ -181,8 +186,9 @@ impl DataContext {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::ModuleExtName;
|
||||
|
||||
use super::{DataContext, Init};
|
||||
use cranelift_codegen::ir;
|
||||
|
||||
#[test]
|
||||
fn basic_data_context() {
|
||||
@@ -198,11 +204,11 @@ mod tests {
|
||||
|
||||
data_ctx.define_zeroinit(256);
|
||||
|
||||
let _func_a = data_ctx.import_function(ir::ExternalName::user(0, 0));
|
||||
let func_b = data_ctx.import_function(ir::ExternalName::user(0, 1));
|
||||
let func_c = data_ctx.import_function(ir::ExternalName::user(1, 0));
|
||||
let _data_a = data_ctx.import_global_value(ir::ExternalName::user(2, 2));
|
||||
let data_b = data_ctx.import_global_value(ir::ExternalName::user(2, 3));
|
||||
let _func_a = data_ctx.import_function(ModuleExtName::user(0, 0));
|
||||
let func_b = data_ctx.import_function(ModuleExtName::user(0, 1));
|
||||
let func_c = data_ctx.import_function(ModuleExtName::user(0, 2));
|
||||
let _data_a = data_ctx.import_global_value(ModuleExtName::user(0, 3));
|
||||
let data_b = data_ctx.import_global_value(ModuleExtName::user(0, 4));
|
||||
|
||||
data_ctx.write_function_addr(8, func_b);
|
||||
data_ctx.write_function_addr(16, func_c);
|
||||
|
||||
@@ -43,7 +43,7 @@ mod traps;
|
||||
pub use crate::data_context::{DataContext, DataDescription, Init};
|
||||
pub use crate::module::{
|
||||
DataId, FuncId, FuncOrDataId, Linkage, Module, ModuleCompiledFunction, ModuleDeclarations,
|
||||
ModuleError, ModuleResult,
|
||||
ModuleError, ModuleExtName, ModuleReloc, ModuleResult,
|
||||
};
|
||||
pub use crate::traps::TrapSite;
|
||||
|
||||
|
||||
@@ -7,19 +7,57 @@
|
||||
|
||||
use super::HashMap;
|
||||
use crate::data_context::DataContext;
|
||||
use core::fmt::Display;
|
||||
use cranelift_codegen::binemit::{CodeOffset, Reloc};
|
||||
use cranelift_codegen::entity::{entity_impl, PrimaryMap};
|
||||
use cranelift_codegen::ir::Function;
|
||||
use cranelift_codegen::{binemit, MachReloc};
|
||||
use cranelift_codegen::{ir, isa, CodegenError, CompileError, Context};
|
||||
use std::borrow::ToOwned;
|
||||
use std::string::String;
|
||||
|
||||
/// A module relocation.
|
||||
#[derive(Clone)]
|
||||
pub struct ModuleReloc {
|
||||
/// The offset at which the relocation applies, *relative to the
|
||||
/// containing section*.
|
||||
pub offset: CodeOffset,
|
||||
/// The kind of relocation.
|
||||
pub kind: Reloc,
|
||||
/// The external symbol / name to which this relocation refers.
|
||||
pub name: ModuleExtName,
|
||||
/// The addend to add to the symbol value.
|
||||
pub addend: i64,
|
||||
}
|
||||
|
||||
impl ModuleReloc {
|
||||
/// Converts a `MachReloc` produced from a `Function` into a `ModuleReloc`.
|
||||
pub fn from_mach_reloc(mach_reloc: &MachReloc, func: &Function) -> Self {
|
||||
let name = match mach_reloc.name {
|
||||
ir::ExternalName::User(reff) => {
|
||||
let name = &func.params.user_named_funcs()[reff];
|
||||
ModuleExtName::user(name.namespace, name.index)
|
||||
}
|
||||
ir::ExternalName::TestCase(_) => unimplemented!(),
|
||||
ir::ExternalName::LibCall(libcall) => ModuleExtName::LibCall(libcall),
|
||||
ir::ExternalName::KnownSymbol(ks) => ModuleExtName::KnownSymbol(ks),
|
||||
};
|
||||
Self {
|
||||
offset: mach_reloc.offset,
|
||||
kind: mach_reloc.kind,
|
||||
name,
|
||||
addend: mach_reloc.addend,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A function identifier for use in the `Module` interface.
|
||||
#[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
||||
pub struct FuncId(u32);
|
||||
entity_impl!(FuncId, "funcid");
|
||||
|
||||
/// Function identifiers are namespace 0 in `ir::ExternalName`
|
||||
impl From<FuncId> for ir::ExternalName {
|
||||
impl From<FuncId> for ModuleExtName {
|
||||
fn from(id: FuncId) -> Self {
|
||||
Self::User {
|
||||
namespace: 0,
|
||||
@@ -30,12 +68,12 @@ impl From<FuncId> for ir::ExternalName {
|
||||
|
||||
impl FuncId {
|
||||
/// Get the `FuncId` for the function named by `name`.
|
||||
pub fn from_name(name: &ir::ExternalName) -> FuncId {
|
||||
if let ir::ExternalName::User { namespace, index } = *name {
|
||||
debug_assert_eq!(namespace, 0);
|
||||
FuncId::from_u32(index)
|
||||
pub fn from_name(name: &ModuleExtName) -> FuncId {
|
||||
if let ModuleExtName::User { namespace, index } = name {
|
||||
debug_assert_eq!(*namespace, 0);
|
||||
FuncId::from_u32(*index)
|
||||
} else {
|
||||
panic!("unexpected ExternalName kind {}", name)
|
||||
panic!("unexpected name in DataId::from_name")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -46,7 +84,7 @@ pub struct DataId(u32);
|
||||
entity_impl!(DataId, "dataid");
|
||||
|
||||
/// Data identifiers are namespace 1 in `ir::ExternalName`
|
||||
impl From<DataId> for ir::ExternalName {
|
||||
impl From<DataId> for ModuleExtName {
|
||||
fn from(id: DataId) -> Self {
|
||||
Self::User {
|
||||
namespace: 1,
|
||||
@@ -57,12 +95,12 @@ impl From<DataId> for ir::ExternalName {
|
||||
|
||||
impl DataId {
|
||||
/// Get the `DataId` for the data object named by `name`.
|
||||
pub fn from_name(name: &ir::ExternalName) -> DataId {
|
||||
if let ir::ExternalName::User { namespace, index } = *name {
|
||||
debug_assert_eq!(namespace, 1);
|
||||
DataId::from_u32(index)
|
||||
pub fn from_name(name: &ModuleExtName) -> DataId {
|
||||
if let ModuleExtName::User { namespace, index } = name {
|
||||
debug_assert_eq!(*namespace, 1);
|
||||
DataId::from_u32(*index)
|
||||
} else {
|
||||
panic!("unexpected ExternalName kind {}", name)
|
||||
panic!("unexpected name in DataId::from_name")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -134,8 +172,8 @@ pub enum FuncOrDataId {
|
||||
Data(DataId),
|
||||
}
|
||||
|
||||
/// Mapping to `ir::ExternalName` is trivial based on the `FuncId` and `DataId` mapping.
|
||||
impl From<FuncOrDataId> for ir::ExternalName {
|
||||
/// Mapping to `ModuleExtName` is trivial based on the `FuncId` and `DataId` mapping.
|
||||
impl From<FuncOrDataId> for ModuleExtName {
|
||||
fn from(id: FuncOrDataId) -> Self {
|
||||
match id {
|
||||
FuncOrDataId::Func(funcid) => Self::from(funcid),
|
||||
@@ -277,6 +315,39 @@ impl DataDeclaration {
|
||||
}
|
||||
}
|
||||
|
||||
/// A translated `ExternalName` into something global we can handle.
|
||||
#[derive(Clone)]
|
||||
pub enum ModuleExtName {
|
||||
/// User defined function, converted from `ExternalName::User`.
|
||||
User {
|
||||
/// Arbitrary.
|
||||
namespace: u32,
|
||||
/// Arbitrary.
|
||||
index: u32,
|
||||
},
|
||||
/// Call into a library function.
|
||||
LibCall(ir::LibCall),
|
||||
/// Symbols known to the linker.
|
||||
KnownSymbol(ir::KnownSymbol),
|
||||
}
|
||||
|
||||
impl ModuleExtName {
|
||||
/// Creates a user-defined external name.
|
||||
pub fn user(namespace: u32, index: u32) -> Self {
|
||||
Self::User { namespace, index }
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for ModuleExtName {
|
||||
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
|
||||
match self {
|
||||
Self::User { namespace, index } => write!(f, "u{}:{}", namespace, index),
|
||||
Self::LibCall(lc) => write!(f, "%{}", lc),
|
||||
Self::KnownSymbol(ks) => write!(f, "{}", ks),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// This provides a view to the state of a module which allows `ir::ExternalName`s to be translated
|
||||
/// into `FunctionDeclaration`s and `DataDeclaration`s.
|
||||
#[derive(Debug, Default)]
|
||||
@@ -299,11 +370,12 @@ impl ModuleDeclarations {
|
||||
}
|
||||
|
||||
/// Return whether `name` names a function, rather than a data object.
|
||||
pub fn is_function(name: &ir::ExternalName) -> bool {
|
||||
if let ir::ExternalName::User { namespace, .. } = *name {
|
||||
namespace == 0
|
||||
} else {
|
||||
panic!("unexpected ExternalName kind {}", name)
|
||||
pub fn is_function(name: &ModuleExtName) -> bool {
|
||||
match name {
|
||||
ModuleExtName::User { namespace, .. } => *namespace == 0,
|
||||
ModuleExtName::LibCall(_) | ModuleExtName::KnownSymbol(_) => {
|
||||
panic!("unexpected module ext name")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -503,12 +575,16 @@ pub trait Module {
|
||||
///
|
||||
/// TODO: Coalesce redundant decls and signatures.
|
||||
/// TODO: Look into ways to reduce the risk of using a FuncRef in the wrong function.
|
||||
fn declare_func_in_func(&self, func: FuncId, in_func: &mut ir::Function) -> ir::FuncRef {
|
||||
let decl = &self.declarations().functions[func];
|
||||
let signature = in_func.import_signature(decl.signature.clone());
|
||||
fn declare_func_in_func(&mut self, func_id: FuncId, func: &mut ir::Function) -> ir::FuncRef {
|
||||
let decl = &self.declarations().functions[func_id];
|
||||
let signature = func.import_signature(decl.signature.clone());
|
||||
let user_name_ref = func.declare_imported_user_function(ir::UserExternalName {
|
||||
namespace: 0,
|
||||
index: func_id.as_u32(),
|
||||
});
|
||||
let colocated = decl.linkage.is_final();
|
||||
in_func.import_function(ir::ExtFuncData {
|
||||
name: ir::ExternalName::user(0, func.as_u32()),
|
||||
func.import_function(ir::ExtFuncData {
|
||||
name: ir::ExternalName::user(user_name_ref),
|
||||
signature,
|
||||
colocated,
|
||||
})
|
||||
@@ -520,8 +596,12 @@ pub trait Module {
|
||||
fn declare_data_in_func(&self, data: DataId, func: &mut ir::Function) -> ir::GlobalValue {
|
||||
let decl = &self.declarations().data_objects[data];
|
||||
let colocated = decl.linkage.is_final();
|
||||
let user_name_ref = func.declare_imported_user_function(ir::UserExternalName {
|
||||
namespace: 1,
|
||||
index: data.as_u32(),
|
||||
});
|
||||
func.create_global_value(ir::GlobalValueData::Symbol {
|
||||
name: ir::ExternalName::user(1, data.as_u32()),
|
||||
name: ir::ExternalName::user(user_name_ref),
|
||||
offset: ir::immediates::Imm64::new(0),
|
||||
colocated,
|
||||
tls: decl.tls,
|
||||
@@ -530,12 +610,12 @@ pub trait Module {
|
||||
|
||||
/// TODO: Same as above.
|
||||
fn declare_func_in_data(&self, func: FuncId, ctx: &mut DataContext) -> ir::FuncRef {
|
||||
ctx.import_function(ir::ExternalName::user(0, func.as_u32()))
|
||||
ctx.import_function(ModuleExtName::user(0, func.as_u32()))
|
||||
}
|
||||
|
||||
/// TODO: Same as above.
|
||||
fn declare_data_in_data(&self, data: DataId, ctx: &mut DataContext) -> ir::GlobalValue {
|
||||
ctx.import_global_value(ir::ExternalName::user(1, data.as_u32()))
|
||||
ctx.import_global_value(ModuleExtName::user(1, data.as_u32()))
|
||||
}
|
||||
|
||||
/// Define a function, producing the function body from the given `Context`.
|
||||
@@ -558,7 +638,8 @@ pub trait Module {
|
||||
/// Returns the size of the function's code.
|
||||
fn define_function_bytes(
|
||||
&mut self,
|
||||
func: FuncId,
|
||||
func_id: FuncId,
|
||||
func: &ir::Function,
|
||||
bytes: &[u8],
|
||||
relocs: &[MachReloc],
|
||||
) -> ModuleResult<ModuleCompiledFunction>;
|
||||
@@ -627,7 +708,7 @@ impl<M: Module> Module for &mut M {
|
||||
(**self).declare_anonymous_data(writable, tls)
|
||||
}
|
||||
|
||||
fn declare_func_in_func(&self, func: FuncId, in_func: &mut ir::Function) -> ir::FuncRef {
|
||||
fn declare_func_in_func(&mut self, func: FuncId, in_func: &mut ir::Function) -> ir::FuncRef {
|
||||
(**self).declare_func_in_func(func, in_func)
|
||||
}
|
||||
|
||||
@@ -635,14 +716,6 @@ impl<M: Module> Module for &mut M {
|
||||
(**self).declare_data_in_func(data, func)
|
||||
}
|
||||
|
||||
fn declare_func_in_data(&self, func: FuncId, ctx: &mut DataContext) -> ir::FuncRef {
|
||||
(**self).declare_func_in_data(func, ctx)
|
||||
}
|
||||
|
||||
fn declare_data_in_data(&self, data: DataId, ctx: &mut DataContext) -> ir::GlobalValue {
|
||||
(**self).declare_data_in_data(data, ctx)
|
||||
}
|
||||
|
||||
fn define_function(
|
||||
&mut self,
|
||||
func: FuncId,
|
||||
@@ -653,11 +726,12 @@ impl<M: Module> Module for &mut M {
|
||||
|
||||
fn define_function_bytes(
|
||||
&mut self,
|
||||
func: FuncId,
|
||||
func_id: FuncId,
|
||||
func: &ir::Function,
|
||||
bytes: &[u8],
|
||||
relocs: &[MachReloc],
|
||||
) -> ModuleResult<ModuleCompiledFunction> {
|
||||
(**self).define_function_bytes(func, bytes, relocs)
|
||||
(**self).define_function_bytes(func_id, func, bytes, relocs)
|
||||
}
|
||||
|
||||
fn define_data(&mut self, data: DataId, data_ctx: &DataContext) -> ModuleResult<()> {
|
||||
|
||||
Reference in New Issue
Block a user