Path: blob/main/cranelift/filetests/src/function_runner.rs
3056 views
//! Provides functionality for compiling and running CLIF IR for `run` tests.1use anyhow::{Context as _, Result, anyhow};2use core::mem;3use cranelift::prelude::Imm64;4use cranelift_codegen::cursor::{Cursor, FuncCursor};5use cranelift_codegen::data_value::DataValue;6use cranelift_codegen::ir::{7ExternalName, Function, InstBuilder, InstructionData, LibCall, Opcode, Signature,8UserExternalName, UserFuncName,9};10use cranelift_codegen::isa::{OwnedTargetIsa, TargetIsa};11use cranelift_codegen::{CodegenError, Context, ir, settings};12use cranelift_control::ControlPlane;13use cranelift_frontend::{FunctionBuilder, FunctionBuilderContext};14use cranelift_jit::{JITBuilder, JITModule};15use cranelift_module::{FuncId, Linkage, Module, ModuleError};16use cranelift_native::builder_with_options;17use cranelift_reader::TestFile;18use pulley_interpreter::interp as pulley;19use std::cell::Cell;20use std::cmp::max;21use std::collections::hash_map::Entry;22use std::collections::{HashMap, HashSet};23use std::ptr::NonNull;24use target_lexicon::Architecture;25use thiserror::Error;2627const TESTFILE_NAMESPACE: u32 = 0;2829/// Holds information about a previously defined function.30#[derive(Debug)]31struct DefinedFunction {32/// This is the name that the function is internally known as.33///34/// The JIT module does not support linking / calling [TestcaseName]'s, so35/// we rename every function into a [UserExternalName].36///37/// By doing this we also have to rename functions that previously were using a38/// [UserFuncName], since they may now be in conflict after the renaming that39/// occurred.40new_name: UserExternalName,4142/// The function signature43signature: ir::Signature,4445/// JIT [FuncId]46func_id: FuncId,47}4849/// Compile a test case.50///51/// Several Cranelift functions need the ability to run Cranelift IR (e.g. `test_run`); this52/// [TestFileCompiler] provides a way for compiling Cranelift [Function]s to53/// `CompiledFunction`s and subsequently calling them through the use of a `Trampoline`. As its54/// name indicates, this compiler is limited: any functionality that requires knowledge of things55/// outside the [Function] will likely not work (e.g. global values, calls). For an example of this56/// "outside-of-function" functionality, see `cranelift_jit::backend::JITBackend`.57///58/// ```59/// # let ctrl_plane = &mut Default::default();60/// use cranelift_filetests::TestFileCompiler;61/// use cranelift_reader::parse_functions;62/// use cranelift_codegen::data_value::DataValue;63///64/// let code = "test run \n function %add(i32, i32) -> i32 { block0(v0:i32, v1:i32): v2 = iadd v0, v1 return v2 }".into();65/// let func = parse_functions(code).unwrap().into_iter().nth(0).unwrap();66/// let Ok(mut compiler) = TestFileCompiler::with_default_host_isa() else {67/// return;68/// };69/// compiler.declare_function(&func).unwrap();70/// compiler.define_function(func.clone(), ctrl_plane).unwrap();71/// compiler.create_trampoline_for_function(&func, ctrl_plane).unwrap();72/// let compiled = compiler.compile().unwrap();73/// let trampoline = compiled.get_trampoline(&func).unwrap();74///75/// let returned = trampoline.call(&compiled, &vec![DataValue::I32(2), DataValue::I32(40)]);76/// assert_eq!(vec![DataValue::I32(42)], returned);77/// ```78pub struct TestFileCompiler {79module: JITModule,80ctx: Context,8182/// Holds info about the functions that have already been defined.83/// Use look them up by their original [UserFuncName] since that's how the caller84/// passes them to us.85defined_functions: HashMap<UserFuncName, DefinedFunction>,8687/// We deduplicate trampolines by the signature of the function that they target.88/// This map holds as a key the [Signature] of the target function, and as a value89/// the [UserFuncName] of the trampoline for that [Signature].90///91/// The trampoline is defined in `defined_functions` as any other regular function.92trampolines: HashMap<Signature, UserFuncName>,93}9495impl TestFileCompiler {96/// Build a [TestFileCompiler] from a [TargetIsa]. For functions to be runnable on the97/// host machine, this [TargetIsa] must match the host machine's ISA (see98/// [TestFileCompiler::with_host_isa]).99pub fn new(isa: OwnedTargetIsa) -> Self {100let mut builder = JITBuilder::with_isa(isa, cranelift_module::default_libcall_names());101builder.symbol_lookup_fn(Box::new(lookup_libcall));102103// On Unix platforms force `libm` to get linked into this executable104// because tests that use libcalls rely on this library being present.105// Without this it's been seen that when cross-compiled to riscv64 the106// final binary doesn't link in `libm`.107#[cfg(unix)]108{109unsafe extern "C" {110safe fn cosf(f: f32) -> f32;111}112let f = std::hint::black_box(1.2_f32);113assert_eq!(f.cos(), cosf(f));114}115116let module = JITModule::new(builder);117let ctx = module.make_context();118119Self {120module,121ctx,122defined_functions: HashMap::new(),123trampolines: HashMap::new(),124}125}126127/// Build a [TestFileCompiler] using the host machine's ISA and the passed flags.128pub fn with_host_isa(flags: settings::Flags) -> Result<Self> {129let builder = builder_with_options(true)130.map_err(anyhow::Error::msg)131.context("Unable to build a TargetIsa for the current host")?;132let isa = builder.finish(flags)?;133Ok(Self::new(isa))134}135136/// Build a [TestFileCompiler] using the host machine's ISA and the default flags for this137/// ISA.138pub fn with_default_host_isa() -> Result<Self> {139let flags = settings::Flags::new(settings::builder());140Self::with_host_isa(flags)141}142143/// Declares and compiles all functions in `functions`. Additionally creates a trampoline for144/// each one of them.145pub fn add_functions(146&mut self,147functions: &[Function],148ctrl_planes: Vec<ControlPlane>,149) -> Result<()> {150// Declare all functions in the file, so that they may refer to each other.151for func in functions {152self.declare_function(func)?;153}154155let ctrl_planes = ctrl_planes156.into_iter()157.chain(std::iter::repeat(ControlPlane::default()));158159// Define all functions and trampolines160for (func, ref mut ctrl_plane) in functions.iter().zip(ctrl_planes) {161self.define_function(func.clone(), ctrl_plane)?;162self.create_trampoline_for_function(func, ctrl_plane)?;163}164165Ok(())166}167168/// Registers all functions in a [TestFile]. Additionally creates a trampoline for each one169/// of them.170pub fn add_testfile(&mut self, testfile: &TestFile) -> Result<()> {171let functions = testfile172.functions173.iter()174.map(|(f, _)| f)175.cloned()176.collect::<Vec<_>>();177178self.add_functions(&functions[..], Vec::new())?;179Ok(())180}181182/// Declares a function an registers it as a linkable and callable target internally183pub fn declare_function(&mut self, func: &Function) -> Result<()> {184let next_id = self.defined_functions.len() as u32;185match self.defined_functions.entry(func.name.clone()) {186Entry::Occupied(_) => {187anyhow::bail!("Duplicate function with name {} found!", &func.name)188}189Entry::Vacant(v) => {190let name = func.name.to_string();191let func_id =192self.module193.declare_function(&name, Linkage::Local, &func.signature)?;194195v.insert(DefinedFunction {196new_name: UserExternalName::new(TESTFILE_NAMESPACE, next_id),197signature: func.signature.clone(),198func_id,199});200}201};202203Ok(())204}205206/// Renames the function to its new [UserExternalName], as well as any other function that207/// it may reference.208///209/// We have to do this since the JIT cannot link Testcase functions.210fn apply_func_rename(211&self,212mut func: Function,213defined_func: &DefinedFunction,214) -> Result<Function> {215// First, rename the function216let func_original_name = func.name;217func.name = UserFuncName::User(defined_func.new_name.clone());218219// Rename any functions that it references220// Do this in stages to appease the borrow checker221let mut redefines = Vec::with_capacity(func.dfg.ext_funcs.len());222for (ext_ref, ext_func) in &func.dfg.ext_funcs {223let old_name = match &ext_func.name {224ExternalName::TestCase(tc) => UserFuncName::Testcase(tc.clone()),225ExternalName::User(username) => {226UserFuncName::User(func.params.user_named_funcs()[*username].clone())227}228// The other cases don't need renaming, so lets just continue...229_ => continue,230};231232let target_df = self.defined_functions.get(&old_name).ok_or(anyhow!(233"Undeclared function {} is referenced by {}!",234&old_name,235&func_original_name236))?;237238redefines.push((ext_ref, target_df.new_name.clone()));239}240241// Now register the redefines242for (ext_ref, new_name) in redefines.into_iter() {243// Register the new name in the func, so that we can get a reference to it.244let new_name_ref = func.params.ensure_user_func_name(new_name);245246// Finally rename the ExtFunc247func.dfg.ext_funcs[ext_ref].name = ExternalName::User(new_name_ref);248}249250Ok(func)251}252253/// Defines the body of a function254pub fn define_function(255&mut self,256mut func: Function,257ctrl_plane: &mut ControlPlane,258) -> Result<()> {259Self::replace_hostcall_references(&mut func);260261let defined_func = self262.defined_functions263.get(&func.name)264.ok_or(anyhow!("Undeclared function {} found!", &func.name))?;265266self.ctx.func = self.apply_func_rename(func, defined_func)?;267self.module.define_function_with_control_plane(268defined_func.func_id,269&mut self.ctx,270ctrl_plane,271)?;272self.module.clear_context(&mut self.ctx);273Ok(())274}275276fn replace_hostcall_references(func: &mut Function) {277// For every `func_addr` referring to a hostcall that we278// define, replace with an `iconst` with the actual279// address. Then modify the external func references to280// harmless libcall references (that will be unused so281// ignored).282let mut funcrefs_to_remove = HashSet::new();283let mut cursor = FuncCursor::new(func);284while let Some(_block) = cursor.next_block() {285while let Some(inst) = cursor.next_inst() {286match &cursor.func.dfg.insts[inst] {287InstructionData::FuncAddr {288opcode: Opcode::FuncAddr,289func_ref,290} => {291let ext_func = &cursor.func.dfg.ext_funcs[*func_ref];292let hostcall_addr = match &ext_func.name {293ExternalName::TestCase(tc) if tc.raw() == b"__cranelift_throw" => {294Some((__cranelift_throw as *const ()).addr())295}296_ => None,297};298299if let Some(addr) = hostcall_addr {300funcrefs_to_remove.insert(*func_ref);301cursor.func.dfg.insts[inst] = InstructionData::UnaryImm {302opcode: Opcode::Iconst,303imm: Imm64::new(addr as i64),304};305}306}307_ => {}308}309}310}311312for to_remove in funcrefs_to_remove {313func.dfg.ext_funcs[to_remove].name = ExternalName::LibCall(LibCall::Probestack);314}315}316317/// Creates and registers a trampoline for a function if none exists.318pub fn create_trampoline_for_function(319&mut self,320func: &Function,321ctrl_plane: &mut ControlPlane,322) -> Result<()> {323if !self.defined_functions.contains_key(&func.name) {324anyhow::bail!("Undeclared function {} found!", &func.name);325}326327// Check if a trampoline for this function signature already exists328if self.trampolines.contains_key(&func.signature) {329return Ok(());330}331332// Create a trampoline and register it333let name = UserFuncName::user(TESTFILE_NAMESPACE, self.defined_functions.len() as u32);334let trampoline = make_trampoline(name.clone(), &func.signature, self.module.isa());335336self.declare_function(&trampoline)?;337self.define_function(trampoline, ctrl_plane)?;338339self.trampolines.insert(func.signature.clone(), name);340341Ok(())342}343344/// Finalize this TestFile and link all functions.345pub fn compile(mut self) -> Result<CompiledTestFile, CompilationError> {346// Finalize the functions which we just defined, which resolves any347// outstanding relocations (patching in addresses, now that they're348// available).349self.module.finalize_definitions()?;350351Ok(CompiledTestFile {352module: Some(self.module),353defined_functions: self.defined_functions,354trampolines: self.trampolines,355})356}357}358359/// A finalized Test File360pub struct CompiledTestFile {361/// We need to store [JITModule] since it contains the underlying memory for the functions.362/// Store it in an [Option] so that we can later drop it.363module: Option<JITModule>,364365/// Holds info about the functions that have been registered in `module`.366/// See [TestFileCompiler] for more info.367defined_functions: HashMap<UserFuncName, DefinedFunction>,368369/// Trampolines available in this [JITModule].370/// See [TestFileCompiler] for more info.371trampolines: HashMap<Signature, UserFuncName>,372}373374impl CompiledTestFile {375/// Return a trampoline for calling.376///377/// Returns None if [TestFileCompiler::create_trampoline_for_function] wasn't called for this function.378pub fn get_trampoline(&self, func: &Function) -> Option<Trampoline<'_>> {379let defined_func = self.defined_functions.get(&func.name)?;380let trampoline_id = self381.trampolines382.get(&func.signature)383.and_then(|name| self.defined_functions.get(name))384.map(|df| df.func_id)?;385Some(Trampoline {386module: self.module.as_ref()?,387func_id: defined_func.func_id,388func_signature: &defined_func.signature,389trampoline_id,390})391}392}393394impl Drop for CompiledTestFile {395fn drop(&mut self) {396// Freeing the module's memory erases the compiled functions.397// This should be safe since their pointers never leave this struct.398unsafe { self.module.take().unwrap().free_memory() }399}400}401402std::thread_local! {403/// TLS slot used to store a CompiledTestFile reference so that it404/// can be recovered when a hostcall (such as the exception-throw405/// handler) is invoked.406pub static COMPILED_TEST_FILE: Cell<*const CompiledTestFile> = Cell::new(std::ptr::null());407}408409/// A callable trampoline410pub struct Trampoline<'a> {411module: &'a JITModule,412func_id: FuncId,413func_signature: &'a Signature,414trampoline_id: FuncId,415}416417impl<'a> Trampoline<'a> {418/// Call the target function of this trampoline, passing in [DataValue]s using a compiled trampoline.419pub fn call(&self, compiled: &CompiledTestFile, arguments: &[DataValue]) -> Vec<DataValue> {420let mut values = UnboxedValues::make_arguments(arguments, &self.func_signature);421let arguments_address = values.as_mut_ptr();422423let function_ptr = self.module.get_finalized_function(self.func_id);424let trampoline_ptr = self.module.get_finalized_function(self.trampoline_id);425426COMPILED_TEST_FILE.set(compiled as *const _);427unsafe {428self.call_raw(trampoline_ptr, function_ptr, arguments_address);429}430COMPILED_TEST_FILE.set(std::ptr::null());431432values.collect_returns(&self.func_signature)433}434435unsafe fn call_raw(436&self,437trampoline_ptr: *const u8,438function_ptr: *const u8,439arguments_address: *mut u128,440) {441match self.module.isa().triple().architecture {442// For the pulley target this is pulley bytecode, not machine code,443// so run the interpreter.444Architecture::Pulley32445| Architecture::Pulley64446| Architecture::Pulley32be447| Architecture::Pulley64be => {448let mut state = pulley::Vm::new();449unsafe {450state.call(451NonNull::new(trampoline_ptr.cast_mut()).unwrap(),452&[453pulley::XRegVal::new_ptr(function_ptr.cast_mut()).into(),454pulley::XRegVal::new_ptr(arguments_address).into(),455],456[],457);458}459}460461// Other targets natively execute this machine code.462_ => {463let callable_trampoline: fn(*const u8, *mut u128) -> () =464unsafe { mem::transmute(trampoline_ptr) };465callable_trampoline(function_ptr, arguments_address);466}467}468}469}470471/// Compilation Error when compiling a function.472#[derive(Error, Debug)]473pub enum CompilationError {474/// Cranelift codegen error.475#[error("Cranelift codegen error")]476CodegenError(#[from] CodegenError),477/// Module Error478#[error("Module error")]479ModuleError(#[from] ModuleError),480/// Memory mapping error.481#[error("Memory mapping error")]482IoError(#[from] std::io::Error),483}484485/// A container for laying out the [ValueData]s in memory in a way that the [Trampoline] can486/// understand.487struct UnboxedValues(Vec<u128>);488489impl UnboxedValues {490/// The size in bytes of each slot location in the allocated [DataValue]s. Though [DataValue]s491/// could be smaller than 16 bytes (e.g. `I16`), this simplifies the creation of the [DataValue]492/// array and could be used to align the slots to the largest used [DataValue] (i.e. 128-bit493/// vectors).494const SLOT_SIZE: usize = 16;495496/// Build the arguments vector for passing the [DataValue]s into the [Trampoline]. The size of497/// `u128` used here must match [Trampoline::SLOT_SIZE].498pub fn make_arguments(arguments: &[DataValue], signature: &ir::Signature) -> Self {499assert_eq!(arguments.len(), signature.params.len());500let mut values_vec = vec![0; max(signature.params.len(), signature.returns.len())];501502// Store the argument values into `values_vec`.503for ((arg, slot), param) in arguments.iter().zip(&mut values_vec).zip(&signature.params) {504assert!(505arg.ty() == param.value_type || arg.is_vector(),506"argument type mismatch: {} != {}",507arg.ty(),508param.value_type509);510unsafe {511arg.write_value_to(slot);512}513}514515Self(values_vec)516}517518/// Return a pointer to the underlying memory for passing to the trampoline.519pub fn as_mut_ptr(&mut self) -> *mut u128 {520self.0.as_mut_ptr()521}522523/// Collect the returned [DataValue]s into a [Vec]. The size of `u128` used here must match524/// [Trampoline::SLOT_SIZE].525pub fn collect_returns(&self, signature: &ir::Signature) -> Vec<DataValue> {526assert!(self.0.len() >= signature.returns.len());527let mut returns = Vec::with_capacity(signature.returns.len());528529// Extract the returned values from this vector.530for (slot, param) in self.0.iter().zip(&signature.returns) {531let value = unsafe { DataValue::read_value_from(slot, param.value_type) };532returns.push(value);533}534535returns536}537}538539/// Build the Cranelift IR for moving the memory-allocated [DataValue]s to their correct location540/// (e.g. register, stack) prior to calling a [CompiledFunction]. The [Function] returned by541/// [make_trampoline] is compiled to a [Trampoline]. Note that this uses the [TargetIsa]'s default542/// calling convention so we must also check that the [CompiledFunction] has the same calling543/// convention (see [TestFileCompiler::compile]).544fn make_trampoline(name: UserFuncName, signature: &ir::Signature, isa: &dyn TargetIsa) -> Function {545// Create the trampoline signature: (callee_address: pointer, values_vec: pointer) -> ()546let pointer_type = isa.pointer_type();547let mut wrapper_sig = ir::Signature::new(isa.frontend_config().default_call_conv);548wrapper_sig.params.push(ir::AbiParam::new(pointer_type)); // Add the `callee_address` parameter.549wrapper_sig.params.push(ir::AbiParam::new(pointer_type)); // Add the `values_vec` parameter.550551let mut func = ir::Function::with_name_signature(name, wrapper_sig);552553// The trampoline has a single block filled with loads, one call to callee_address, and some loads.554let mut builder_context = FunctionBuilderContext::new();555let mut builder = FunctionBuilder::new(&mut func, &mut builder_context);556let block0 = builder.create_block();557builder.append_block_params_for_function_params(block0);558builder.switch_to_block(block0);559builder.seal_block(block0);560561// Extract the incoming SSA values.562let (callee_value, values_vec_ptr_val) = {563let params = builder.func.dfg.block_params(block0);564(params[0], params[1])565};566567// Load the argument values out of `values_vec`.568let callee_args = signature569.params570.iter()571.enumerate()572.map(|(i, param)| {573// We always store vector types in little-endian byte order as DataValue.574let mut flags = ir::MemFlags::trusted();575if param.value_type.is_vector() {576flags.set_endianness(ir::Endianness::Little);577}578579// Load the value.580builder.ins().load(581param.value_type,582flags,583values_vec_ptr_val,584(i * UnboxedValues::SLOT_SIZE) as i32,585)586})587.collect::<Vec<_>>();588589// Call the passed function.590let new_sig = builder.import_signature(signature.clone());591let call = builder592.ins()593.call_indirect(new_sig, callee_value, &callee_args);594595// Store the return values into `values_vec`.596let results = builder.func.dfg.inst_results(call).to_vec();597for ((i, value), param) in results.iter().enumerate().zip(&signature.returns) {598// We always store vector types in little-endian byte order as DataValue.599let mut flags = ir::MemFlags::trusted();600if param.value_type.is_vector() {601flags.set_endianness(ir::Endianness::Little);602}603// Store the value.604builder.ins().store(605flags,606*value,607values_vec_ptr_val,608(i * UnboxedValues::SLOT_SIZE) as i32,609);610}611612builder.ins().return_(&[]);613builder.finalize();614615func616}617618/// Hostcall invoked directly from a compiled function body to test619/// exception throws.620///621/// This function does not return normally: it either uses the622/// unwinder to jump directly to a Cranelift frame further up the623/// stack, if a handler is found; or it panics, if not.624#[cfg(any(625target_arch = "x86_64",626target_arch = "aarch64",627target_arch = "s390x",628target_arch = "riscv64"629))]630extern "C-unwind" fn __cranelift_throw(631entry_fp: usize,632exit_fp: usize,633exit_pc: usize,634tag: u32,635payload1: usize,636payload2: usize,637) -> ! {638let compiled_test_file = unsafe { &*COMPILED_TEST_FILE.get() };639let unwind_host = wasmtime_unwinder::UnwindHost;640let frame_handler = |frame: &wasmtime_unwinder::Frame| -> Option<(usize, usize)> {641let (base, table) = compiled_test_file642.module643.as_ref()644.unwrap()645.lookup_wasmtime_exception_data(frame.pc())?;646let relative_pc = u32::try_from(647frame648.pc()649.checked_sub(base)650.expect("module lookup did not return a module base below the PC"),651)652.expect("module larger than 4GiB");653654table655.lookup_pc_tag(relative_pc, tag)656.map(|(frame_offset, handler)| {657let handler_sp = frame658.fp()659.wrapping_sub(usize::try_from(frame_offset).unwrap());660let handler_pc = base661.checked_add(usize::try_from(handler).unwrap())662.expect("Handler address computation overflowed");663(handler_pc, handler_sp)664})665};666unsafe {667match wasmtime_unwinder::Handler::find(668&unwind_host,669frame_handler,670exit_pc,671exit_fp,672entry_fp,673) {674Some(handler) => handler.resume_tailcc(payload1, payload2),675None => {676panic!("Expected a handler to exit for throw of tag {tag} at pc {exit_pc:x}");677}678}679}680}681682#[cfg(not(any(683target_arch = "x86_64",684target_arch = "aarch64",685target_arch = "s390x",686target_arch = "riscv64"687)))]688extern "C-unwind" fn __cranelift_throw(689_entry_fp: usize,690_exit_fp: usize,691_exit_pc: usize,692_tag: u32,693_payload1: usize,694_payload2: usize,695) -> ! {696panic!("Throw not implemented on platforms without native backends.");697}698699// Manually define all libcalls here to avoid relying on `libm` or diverging700// behavior across platforms from libm-like functionality. Note that this also701// serves as insurance that the libcall implementation in the Cranelift702// interpreter is the same as the libcall implementation used by compiled code.703// This is important for differential fuzzing where manual invocations of704// libcalls are expected to return the same result, so here they get identical705// implementations.706fn lookup_libcall(name: &str) -> Option<*const u8> {707match name {708"ceil" => {709extern "C" fn ceil(a: f64) -> f64 {710a.ceil()711}712Some(ceil as *const u8)713}714"ceilf" => {715extern "C" fn ceilf(a: f32) -> f32 {716a.ceil()717}718Some(ceilf as *const u8)719}720"trunc" => {721extern "C" fn trunc(a: f64) -> f64 {722a.trunc()723}724Some(trunc as *const u8)725}726"truncf" => {727extern "C" fn truncf(a: f32) -> f32 {728a.trunc()729}730Some(truncf as *const u8)731}732"floor" => {733extern "C" fn floor(a: f64) -> f64 {734a.floor()735}736Some(floor as *const u8)737}738"floorf" => {739extern "C" fn floorf(a: f32) -> f32 {740a.floor()741}742Some(floorf as *const u8)743}744"nearbyint" => {745extern "C" fn nearbyint(a: f64) -> f64 {746a.round_ties_even()747}748Some(nearbyint as *const u8)749}750"nearbyintf" => {751extern "C" fn nearbyintf(a: f32) -> f32 {752a.round_ties_even()753}754Some(nearbyintf as *const u8)755}756"fma" => {757// The `fma` function for `x86_64-pc-windows-gnu` is incorrect. Use758// `libm`'s instead. See:759// https://github.com/bytecodealliance/wasmtime/issues/4512760extern "C" fn fma(a: f64, b: f64, c: f64) -> f64 {761#[cfg(all(target_os = "windows", target_env = "gnu"))]762return libm::fma(a, b, c);763#[cfg(not(all(target_os = "windows", target_env = "gnu")))]764return a.mul_add(b, c);765}766Some(fma as *const u8)767}768"fmaf" => {769extern "C" fn fmaf(a: f32, b: f32, c: f32) -> f32 {770#[cfg(all(target_os = "windows", target_env = "gnu"))]771return libm::fmaf(a, b, c);772#[cfg(not(all(target_os = "windows", target_env = "gnu")))]773return a.mul_add(b, c);774}775Some(fmaf as *const u8)776}777778#[cfg(target_arch = "x86_64")]779"__cranelift_x86_pshufb" => Some(__cranelift_x86_pshufb as *const u8),780781_ => panic!("unknown libcall {name}"),782}783}784785#[cfg(target_arch = "x86_64")]786use std::arch::x86_64::__m128i;787#[cfg(target_arch = "x86_64")]788#[expect(789improper_ctypes_definitions,790reason = "manually verified to work for now"791)]792extern "C" fn __cranelift_x86_pshufb(a: __m128i, b: __m128i) -> __m128i {793union U {794reg: __m128i,795mem: [u8; 16],796}797798unsafe {799let a = U { reg: a }.mem;800let b = U { reg: b }.mem;801802let select = |arr: &[u8; 16], byte: u8| {803if byte & 0x80 != 0 {8040x00805} else {806arr[(byte & 0xf) as usize]807}808};809810U {811mem: [812select(&a, b[0]),813select(&a, b[1]),814select(&a, b[2]),815select(&a, b[3]),816select(&a, b[4]),817select(&a, b[5]),818select(&a, b[6]),819select(&a, b[7]),820select(&a, b[8]),821select(&a, b[9]),822select(&a, b[10]),823select(&a, b[11]),824select(&a, b[12]),825select(&a, b[13]),826select(&a, b[14]),827select(&a, b[15]),828],829}830.reg831}832}833834#[cfg(test)]835mod test {836use super::*;837use cranelift_reader::{ParseOptions, parse_functions, parse_test};838839fn parse(code: &str) -> Function {840parse_functions(code).unwrap().into_iter().nth(0).unwrap()841}842843#[test]844fn nop() {845// Skip this test when cranelift doesn't support the native platform.846if cranelift_native::builder().is_err() {847return;848}849let code = String::from(850"851test run852function %test() -> i8 {853block0:854nop855v1 = iconst.i8 -1856return v1857}",858);859let ctrl_plane = &mut ControlPlane::default();860861// extract function862let test_file = parse_test(code.as_str(), ParseOptions::default()).unwrap();863assert_eq!(1, test_file.functions.len());864let function = test_file.functions[0].0.clone();865866// execute function867let mut compiler = TestFileCompiler::with_default_host_isa().unwrap();868compiler.declare_function(&function).unwrap();869compiler870.define_function(function.clone(), ctrl_plane)871.unwrap();872compiler873.create_trampoline_for_function(&function, ctrl_plane)874.unwrap();875let compiled = compiler.compile().unwrap();876let trampoline = compiled.get_trampoline(&function).unwrap();877let returned = trampoline.call(&compiled, &[]);878assert_eq!(returned, vec![DataValue::I8(-1)])879}880881#[test]882fn trampolines() {883// Skip this test when cranelift doesn't support the native platform.884if cranelift_native::builder().is_err() {885return;886}887let function = parse(888"889function %test(f32, i8, i64x2, i8) -> f32x4, i64 {890block0(v0: f32, v1: i8, v2: i64x2, v3: i8):891v4 = vconst.f32x4 [0x0.1 0x0.2 0x0.3 0x0.4]892v5 = iconst.i64 -1893return v4, v5894}",895);896897let compiler = TestFileCompiler::with_default_host_isa().unwrap();898let trampoline = make_trampoline(899UserFuncName::user(0, 0),900&function.signature,901compiler.module.isa(),902);903println!("{trampoline}");904assert!(format!("{trampoline}").ends_with(905"sig0 = (f32, i8, i64x2, i8) -> f32x4, i64 fast906907block0(v0: i64, v1: i64):908v2 = load.f32 notrap aligned v1909v3 = load.i8 notrap aligned v1+16910v4 = load.i64x2 notrap aligned little v1+32911v5 = load.i8 notrap aligned v1+48912v6, v7 = call_indirect sig0, v0(v2, v3, v4, v5)913store notrap aligned little v6, v1914store notrap aligned v7, v1+16915return916}917"918));919}920}921922923