Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions crates/cranelift/src/compiler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -364,9 +364,9 @@ impl Compiler {

let (builtin_func_index, wasm_sig) = match key {
FuncKey::WasmToBuiltinTrampoline(builtin) => (builtin, sigs.wasm_signature(builtin)),
FuncKey::PatchableToBuiltinTrampoline(builtin) => {
FuncKey::PreserveAllToBuiltinTrampoline(builtin) => {
let mut sig = sigs.wasm_signature(builtin);
// Patchable functions cannot return anything. We
// `preserve_all` functions cannot return anything. We
// raise any errors that occur below so this is fine.
sig.returns.clear();
sig.call_conv = CallConv::PreserveAll;
Expand Down Expand Up @@ -703,7 +703,7 @@ impl wasmtime_environ::Compiler for Compiler {
panic!("use `compile_function` instead")
}

FuncKey::WasmToBuiltinTrampoline(..) | FuncKey::PatchableToBuiltinTrampoline(_) => {
FuncKey::WasmToBuiltinTrampoline(..) | FuncKey::PreserveAllToBuiltinTrampoline(_) => {
self.compile_wasm_to_builtin(key, symbol)
}

Expand Down Expand Up @@ -744,7 +744,7 @@ impl wasmtime_environ::Compiler for Compiler {
),
// Delegate to a helper to finish compiling this.
Abi::Wasm => self.compile_module_startup(translation, types, key, ty),
Abi::Patchable => unreachable!(),
Abi::PreserveAll => unreachable!(),
}
}
}
Expand Down Expand Up @@ -1176,7 +1176,7 @@ impl InliningCompiler for Compiler {
None => Cow::Borrowed(symbol),
Some(Abi::Wasm) => Cow::Owned(format!("{symbol}_wasm_call")),
Some(Abi::Array) => Cow::Owned(format!("{symbol}_array_call")),
Some(Abi::Patchable) => Cow::Owned(format!("{symbol}_patchable_call")),
Some(Abi::PreserveAll) => Cow::Owned(format!("{symbol}_preserve_all_call")),
};

let compiled_func = if let Some(input) = input {
Expand Down
8 changes: 4 additions & 4 deletions crates/cranelift/src/compiler/component.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1662,8 +1662,8 @@ impl ComponentCompiler for Compiler {
)?);
}

Abi::Patchable => unreachable!(
"We should not be compiling a patchable-ABI trampoline for a component function"
Abi::PreserveAll => unreachable!(
"We should not be compiling a preserve_all-ABI trampoline for a component function"
Comment on lines -1665 to +1666

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Refactorings like this FWIW are generally fine to include in PRs, but where possible we prefer them to be separated out commit-wise to make review easier. No problem this time, but if you're interested in making future PRs we'd appreciate that.

),
}

Expand Down Expand Up @@ -1742,9 +1742,9 @@ impl ComponentCompiler for Compiler {
)?);
}

Abi::Patchable => {
Abi::PreserveAll => {
unreachable!(
"We should not be compiling a patchable trampoline for a component intrinsic"
"We should not be compiling a preserve_all trampoline for a component intrinsic"
)
}
}
Expand Down
94 changes: 72 additions & 22 deletions crates/cranelift/src/func_environ.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,8 @@ pub(crate) struct BuiltinFunctions {

builtins: [Option<ir::FuncRef>; BuiltinFunctionIndex::len() as usize],
breakpoint_trampoline: Option<ir::FuncRef>,
out_of_gas_preserve_all: Option<ir::FuncRef>,
new_epoch_preserve_all: Option<ir::FuncRef>,
}

impl BuiltinFunctions {
Expand All @@ -99,6 +101,8 @@ impl BuiltinFunctions {
types: BuiltinFunctionSignatures::new(compiler),
builtins: [None; BuiltinFunctionIndex::len() as usize],
breakpoint_trampoline: None,
out_of_gas_preserve_all: None,
new_epoch_preserve_all: None,
}
}

Expand Down Expand Up @@ -127,24 +131,63 @@ impl BuiltinFunctions {
f
}

/// A call to the `out_of_gas` builtin through its `PreserveAll`
/// trampoline.
///
/// Fuel checks sit at function entries and in every loop header. A call
/// with the normal Wasm ABI there clobbers all caller-saved registers on a
/// path that is almost never taken, which forces every value that is live
/// across the check into a callee-saved register or a stack slot. The
/// `PreserveAll` trampoline clobbers nothing, so values stay in whatever
/// registers they are in. The trampoline returns nothing and raises the
/// builtin's trap itself.
pub(crate) fn out_of_gas_preserve_all(&mut self, func: &mut Function) -> ir::FuncRef {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@cfallin question for you, did you have a particular reason for doing this style of getting the breakpoint intrisnic vs an alternative approach along the lines of https://github.com/bytecodealliance/wasmtime/pull/14975/changes#diff-f4e65f6eab2ed0d2568b98f7090476dab5cf37bbf7e7d5ef10a6a2ca9e97c33e where internally libcalls are special-cased?

Personally I'm partial to the latter approach as it makes so all usage of the libcall is guaranteed to have a single ABI as opposed to accidentally using the wrong helper to get the wrong ABI. Even more ideally I'd love like a #[abi_preserve_all] on the builtins macro itself so we can just annotate some libcalls over others, but that might be a bit overkill to parse when it's only needed in one location here.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is there any reason that we add new libcalls with _preserve_all suffixes, rather than just changing the ABI for the libcall (as we do for breakpoint)?

let ptr = self.types.pointer_type;
*self.out_of_gas_preserve_all.get_or_insert_with(|| {
Self::preserve_all(func, ptr, BuiltinFunctionIndex::out_of_gas(), false)
})
}

/// Like `out_of_gas_preserve_all`, for the `new_epoch` builtin. The new
/// deadline is not returned and has to be reloaded from the store.
pub(crate) fn new_epoch_preserve_all(&mut self, func: &mut Function) -> ir::FuncRef {
let ptr = self.types.pointer_type;
*self.new_epoch_preserve_all.get_or_insert_with(|| {
Self::preserve_all(func, ptr, BuiltinFunctionIndex::new_epoch(), false)
})
}

/// Imports `builtin` through its `PreserveAll` trampoline, which takes
/// only the vmctx, returns nothing and raises the builtin's trap itself.
fn preserve_all(
func: &mut Function,
pointer_type: ir::Type,
builtin: BuiltinFunctionIndex,
patchable: bool,
) -> ir::FuncRef {
let mut signature = ir::Signature::new(CallConv::PreserveAll);
signature.params.push(ir::AbiParam::special(
pointer_type,
ir::ArgumentPurpose::VMContext,
));
let signature = func.import_signature(signature);
let key = FuncKey::PreserveAllToBuiltinTrampoline(builtin);
let (namespace, index) = key.into_raw_parts();
let name = ir::ExternalName::User(
func.declare_imported_user_function(ir::UserExternalName { namespace, index }),
);
func.import_function(ir::ExtFuncData {
name,
signature,
colocated: true,
patchable,
})
}

pub(crate) fn patchable_breakpoint(&mut self, func: &mut Function) -> ir::FuncRef {
let ptr = self.types.pointer_type;
*self.breakpoint_trampoline.get_or_insert_with(|| {
let mut signature = ir::Signature::new(CallConv::PreserveAll);
signature
.params
.push(ir::AbiParam::new(self.types.pointer_type));
let signature = func.import_signature(signature);
let key = FuncKey::PatchableToBuiltinTrampoline(BuiltinFunctionIndex::breakpoint());
let (namespace, index) = key.into_raw_parts();
let name = ir::ExternalName::User(
func.declare_imported_user_function(ir::UserExternalName { namespace, index }),
);
func.import_function(ir::ExtFuncData {
name,
signature,
colocated: true,
patchable: true,
})
Self::preserve_all(func, ptr, BuiltinFunctionIndex::breakpoint(), true)
})
}
}
Expand Down Expand Up @@ -785,6 +828,7 @@ impl<'module_environment> FuncEnvironment<'module_environment> {
fn fuel_check(&mut self, builder: &mut FunctionBuilder) {
self.fuel_increment_var(builder);
let out_of_gas_block = builder.create_block();
builder.set_cold_block(out_of_gas_block);
let continuation_block = builder.create_block();

// Note that our fuel is encoded as adding positive values to a
Expand Down Expand Up @@ -812,7 +856,7 @@ impl<'module_environment> FuncEnvironment<'module_environment> {
// intrinsic may alter how much fuel is in the system.
builder.switch_to_block(out_of_gas_block);
self.fuel_save_from_var(builder);
let out_of_gas = self.builtin_functions.out_of_gas(builder.func);
let out_of_gas = self.builtin_functions.out_of_gas_preserve_all(builder.func);
let vmctx = self.vmctx_val(&mut builder.cursor());
self.call_builtin(builder, out_of_gas, &[vmctx]);
self.fuel_load_into_var(builder);
Expand Down Expand Up @@ -964,12 +1008,18 @@ impl<'module_environment> FuncEnvironment<'module_environment> {
builder.def_var(self.epoch_deadline_var, deadline);
self.epoch_check_cached(builder, cur_epoch_value, continuation_block);

let new_epoch = self.builtin_functions.new_epoch(builder.func);
// Like the fuel check, call through a `PreserveAll` trampoline so the
// (cold) call does not clobber registers in loop headers. It does not
// return the new deadline, so reload it.
let new_epoch = self.builtin_functions.new_epoch_preserve_all(builder.func);
let vmctx = self.vmctx_val(&mut builder.cursor());
// new_epoch() returns the new deadline, so we don't have to
// reload it.
let call = self.call_builtin(builder, new_epoch, &[vmctx]);
let new_deadline = *builder.func.dfg.inst_results(call).first().unwrap();
self.call_builtin(builder, new_epoch, &[vmctx]);
let vmstore_ctx = self.get_vmstore_context_ptr(builder);
let new_deadline = self
.alias_regions
.vm_store_context()
.epoch_deadline()
.load(&mut builder.cursor(), vmstore_ctx);
builder.def_var(self.epoch_deadline_var, new_deadline);
builder.ins().jump(continuation_block, &[]);
builder.seal_block(continuation_block);
Expand Down
35 changes: 19 additions & 16 deletions crates/environ/src/key.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,8 @@ pub enum FuncKeyKind {
/// A trampoline from a Wasm-caller to the given builtin.
WasmToBuiltinTrampoline = FuncKey::new_kind(0b0011),

/// A trampoline from the patchable ABI to the given builtin.
PatchableToBuiltinTrampoline = FuncKey::new_kind(0b0100),
/// A trampoline from the `preserve_all` ABI to the given builtin.
PreserveAllToBuiltinTrampoline = FuncKey::new_kind(0b0100),

/// A Pulley-specific host call.
PulleyHostCall = FuncKey::new_kind(0b0101),
Expand Down Expand Up @@ -73,8 +73,8 @@ impl FuncKeyKind {
x if x == Self::ArrayToWasmTrampoline.into() => Self::ArrayToWasmTrampoline,
x if x == Self::WasmToArrayTrampoline.into() => Self::WasmToArrayTrampoline,
x if x == Self::WasmToBuiltinTrampoline.into() => Self::WasmToBuiltinTrampoline,
x if x == Self::PatchableToBuiltinTrampoline.into() => {
Self::PatchableToBuiltinTrampoline
x if x == Self::PreserveAllToBuiltinTrampoline.into() => {
Self::PreserveAllToBuiltinTrampoline
}
x if x == Self::PulleyHostCall.into() => Self::PulleyHostCall,
x if x == Self::ModuleStartup.into() => Self::ModuleStartup,
Expand Down Expand Up @@ -135,7 +135,7 @@ impl FuncKeyNamespace {
| FuncKeyKind::ModuleStartup => Self(raw),
FuncKeyKind::WasmToArrayTrampoline
| FuncKeyKind::WasmToBuiltinTrampoline
| FuncKeyKind::PatchableToBuiltinTrampoline
| FuncKeyKind::PreserveAllToBuiltinTrampoline
| FuncKeyKind::PulleyHostCall => {
assert_eq!(raw & FuncKey::MODULE_MASK, 0);
Self(raw)
Expand Down Expand Up @@ -206,18 +206,18 @@ pub enum Abi {
Wasm = 0,
/// The "array" ABI, or suitable to be an `array_call` field.
Array = 1,
/// The "patchable" ABI. Signature same as Wasm ABI, but
/// The `preserve_all` ABI. Signature same as Wasm ABI, but
/// Cranelift-level (machine-level) ABI is different (no
/// clobbers).
Patchable = 2,
PreserveAll = 2,
}

impl Abi {
fn from_raw(raw: u32) -> Self {
match raw {
x if x == Self::Wasm.into_raw() => Self::Wasm,
x if x == Self::Array.into_raw() => Self::Array,
x if x == Self::Patchable.into_raw() => Self::Patchable,
x if x == Self::PreserveAll.into_raw() => Self::PreserveAll,
_ => panic!("invalid raw representation passed to `Abi::from_raw`: {raw}"),
}
}
Expand Down Expand Up @@ -246,8 +246,11 @@ pub enum FuncKey {
/// A Pulley-specific host call.
PulleyHostCall(HostCall),

/// A trampoline from the patchable ABI to the given builtin.
PatchableToBuiltinTrampoline(BuiltinFunctionIndex),
/// A trampoline from the `preserve_all` ABI to the given builtin.
///
/// Debugger breakpoints call it from patchable call sites, and fuel and
/// epoch checks from ordinary ones.
PreserveAllToBuiltinTrampoline(BuiltinFunctionIndex),

/// A Wasm-caller to component builtin trampoline.
#[cfg(feature = "component-model")]
Expand Down Expand Up @@ -322,8 +325,8 @@ impl FuncKey {
let index = builtin.index();
(namespace, index)
}
FuncKey::PatchableToBuiltinTrampoline(builtin) => {
let namespace = FuncKeyKind::PatchableToBuiltinTrampoline.into_raw();
FuncKey::PreserveAllToBuiltinTrampoline(builtin) => {
let namespace = FuncKeyKind::PreserveAllToBuiltinTrampoline.into_raw();
let index = builtin.index();
(namespace, index)
}
Expand Down Expand Up @@ -388,7 +391,7 @@ impl FuncKey {
FuncKey::ArrayToWasmTrampoline(_, _) => Abi::Array,
FuncKey::WasmToArrayTrampoline(_) => Abi::Wasm,
FuncKey::WasmToBuiltinTrampoline(_) => Abi::Wasm,
FuncKey::PatchableToBuiltinTrampoline(_) => Abi::Patchable,
FuncKey::PreserveAllToBuiltinTrampoline(_) => Abi::PreserveAll,
FuncKey::PulleyHostCall(_) => Abi::Wasm,
#[cfg(feature = "component-model")]
FuncKey::ComponentTrampoline(abi, _) => abi,
Expand Down Expand Up @@ -454,10 +457,10 @@ impl FuncKey {
let builtin = BuiltinFunctionIndex::from_u32(b);
Self::WasmToBuiltinTrampoline(builtin)
}
FuncKeyKind::PatchableToBuiltinTrampoline => {
FuncKeyKind::PreserveAllToBuiltinTrampoline => {
assert_eq!(a & Self::MODULE_MASK, 0);
let builtin = BuiltinFunctionIndex::from_u32(b);
Self::PatchableToBuiltinTrampoline(builtin)
Self::PreserveAllToBuiltinTrampoline(builtin)
}
FuncKeyKind::PulleyHostCall => {
assert_eq!(a & Self::MODULE_MASK, 0);
Expand Down Expand Up @@ -588,7 +591,7 @@ impl FuncKey {
| Self::ModuleStartup(..) => false,
Self::WasmToArrayTrampoline(..)
| Self::WasmToBuiltinTrampoline(..)
| Self::PatchableToBuiltinTrampoline(..)
| Self::PreserveAllToBuiltinTrampoline(..)
| Self::PulleyHostCall(..) => true,
#[cfg(feature = "component-model")]
Self::ComponentTrampoline(..)
Expand Down
4 changes: 2 additions & 2 deletions crates/environ/src/module_artifacts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -552,7 +552,7 @@ impl CompiledFunctionsTable {

FuncKeyKind::ArrayToWasmTrampoline
| FuncKeyKind::WasmToBuiltinTrampoline
| FuncKeyKind::PatchableToBuiltinTrampoline
| FuncKeyKind::PreserveAllToBuiltinTrampoline
| FuncKeyKind::ModuleStartup => false,

// `FactInlineIntrinsic` never names a compiled function, so it is
Expand All @@ -571,7 +571,7 @@ impl CompiledFunctionsTable {
FuncKeyKind::ArrayToWasmTrampoline
| FuncKeyKind::WasmToArrayTrampoline
| FuncKeyKind::WasmToBuiltinTrampoline
| FuncKeyKind::PatchableToBuiltinTrampoline
| FuncKeyKind::PreserveAllToBuiltinTrampoline
| FuncKeyKind::PulleyHostCall
| FuncKeyKind::ModuleStartup => false,
#[cfg(feature = "component-model")]
Expand Down
18 changes: 10 additions & 8 deletions crates/wasmtime/src/compile.rs
Original file line number Diff line number Diff line change
Expand Up @@ -361,7 +361,7 @@ impl<'a> CompileInputs<'a> {
match abi {
Abi::Wasm => "wasm-call",
Abi::Array => "array-call",
Abi::Patchable => "patchable-call",
Abi::PreserveAll => "preserve-all-call",
},
intrinsic.name(),
);
Expand Down Expand Up @@ -390,7 +390,7 @@ impl<'a> CompileInputs<'a> {
match abi {
Abi::Wasm => "wasm-call",
Abi::Array => "array-call",
Abi::Patchable => "patchable-call",
Abi::PreserveAll => "preserve-all-call",
},
trampoline.symbol_name(),
);
Expand Down Expand Up @@ -994,7 +994,7 @@ fn is_inlining_function(key: FuncKey) -> bool {
FuncKey::ArrayToWasmTrampoline(..)
| FuncKey::WasmToArrayTrampoline(..)
| FuncKey::WasmToBuiltinTrampoline(..)
| FuncKey::PatchableToBuiltinTrampoline(..)
| FuncKey::PreserveAllToBuiltinTrampoline(..)
| FuncKey::ModuleStartup(..) => false,
FuncKey::ComponentTrampoline(..) | FuncKey::ResourceDropTrampoline => false,

Expand Down Expand Up @@ -1024,6 +1024,8 @@ fn compile_required_builtins<'a>(
raw_outputs: &mut Vec<CompileOutput<'a>>,
) -> Result<()> {
let compiler = engine.try_compiler()?;
// Keyed by `FuncKey`, since each trampoline kind of a builtin is a
// separate function.
let mut builtins = HashSet::new();
let mut new_inputs: Vec<CompileInput<'_>> = Vec::new();

Expand All @@ -1033,8 +1035,8 @@ fn compile_required_builtins<'a>(
FuncKey::WasmToBuiltinTrampoline(builtin) => {
format!("wasmtime_builtin_{}", builtin.name())
}
FuncKey::PatchableToBuiltinTrampoline(builtin) => {
format!("wasmtime_patchable_builtin_{}", builtin.name())
FuncKey::PreserveAllToBuiltinTrampoline(builtin) => {
format!("wasmtime_preserve_all_builtin_{}", builtin.name())
}
_ => unreachable!(),
};
Expand All @@ -1058,9 +1060,9 @@ fn compile_required_builtins<'a>(
for output in raw_outputs.iter() {
for reloc in compiler.compiled_function_relocation_targets(&*output.function.code) {
match reloc {
FuncKey::WasmToBuiltinTrampoline(builtin)
| FuncKey::PatchableToBuiltinTrampoline(builtin) => {
if builtins.insert(builtin) {
FuncKey::WasmToBuiltinTrampoline(_)
| FuncKey::PreserveAllToBuiltinTrampoline(_) => {
if builtins.insert(reloc) {
new_inputs.push(compile_builtin(reloc));
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/commands/objdump.rs
Original file line number Diff line number Diff line change
Expand Up @@ -215,7 +215,7 @@ impl ObjdumpCommand {
let bytes = &text[sym.address() as usize..][..sym.size() as usize];

let kind = if name.starts_with("wasmtime_builtin")
|| name.starts_with("wasmtime_patchable_builtin")
|| name.starts_with("wasmtime_preserve_all_builtin")
{
Func::Builtin
} else if name.contains("]::function[") {
Expand Down
Loading
Loading