1 //! Provides functionality for compiling and running CLIF IR for `run` tests.
2 use anyhow::{anyhow, Result};
3 use core::mem;
4 use cranelift_codegen::data_value::DataValue;
5 use cranelift_codegen::ir::{
6     ExternalName, Function, InstBuilder, Signature, UserExternalName, UserFuncName,
7 };
8 use cranelift_codegen::isa::{OwnedTargetIsa, TargetIsa};
9 use cranelift_codegen::{ir, settings, CodegenError, Context};
10 use cranelift_control::ControlPlane;
11 use cranelift_frontend::{FunctionBuilder, FunctionBuilderContext};
12 use cranelift_jit::{JITBuilder, JITModule};
13 use cranelift_module::{FuncId, Linkage, Module, ModuleError};
14 use cranelift_native::builder_with_options;
15 use cranelift_reader::TestFile;
16 use pulley_interpreter::interp as pulley;
17 use std::cmp::max;
18 use std::collections::hash_map::Entry;
19 use std::collections::HashMap;
20 use std::ptr::NonNull;
21 use target_lexicon::Architecture;
22 use thiserror::Error;
23 
24 const TESTFILE_NAMESPACE: u32 = 0;
25 
26 /// Holds information about a previously defined function.
27 #[derive(Debug)]
28 struct DefinedFunction {
29     /// This is the name that the function is internally known as.
30     ///
31     /// The JIT module does not support linking / calling [TestcaseName]'s, so
32     /// we rename every function into a [UserExternalName].
33     ///
34     /// By doing this we also have to rename functions that previously were using a
35     /// [UserFuncName], since they may now be in conflict after the renaming that
36     /// occurred.
37     new_name: UserExternalName,
38 
39     /// The function signature
40     signature: ir::Signature,
41 
42     /// JIT [FuncId]
43     func_id: FuncId,
44 }
45 
46 /// Compile a test case.
47 ///
48 /// Several Cranelift functions need the ability to run Cranelift IR (e.g. `test_run`); this
49 /// [TestFileCompiler] provides a way for compiling Cranelift [Function]s to
50 /// `CompiledFunction`s and subsequently calling them through the use of a `Trampoline`. As its
51 /// name indicates, this compiler is limited: any functionality that requires knowledge of things
52 /// outside the [Function] will likely not work (e.g. global values, calls). For an example of this
53 /// "outside-of-function" functionality, see `cranelift_jit::backend::JITBackend`.
54 ///
55 /// ```
56 /// # let ctrl_plane = &mut Default::default();
57 /// use cranelift_filetests::TestFileCompiler;
58 /// use cranelift_reader::parse_functions;
59 /// use cranelift_codegen::data_value::DataValue;
60 ///
61 /// let code = "test run \n function %add(i32, i32) -> i32 {  block0(v0:i32, v1:i32):  v2 = iadd v0, v1  return v2 }".into();
62 /// let func = parse_functions(code).unwrap().into_iter().nth(0).unwrap();
63 /// let mut compiler = TestFileCompiler::with_default_host_isa().unwrap();
64 /// compiler.declare_function(&func).unwrap();
65 /// compiler.define_function(func.clone(), ctrl_plane).unwrap();
66 /// compiler.create_trampoline_for_function(&func, ctrl_plane).unwrap();
67 /// let compiled = compiler.compile().unwrap();
68 /// let trampoline = compiled.get_trampoline(&func).unwrap();
69 ///
70 /// let returned = trampoline.call(&vec![DataValue::I32(2), DataValue::I32(40)]);
71 /// assert_eq!(vec![DataValue::I32(42)], returned);
72 /// ```
73 pub struct TestFileCompiler {
74     module: JITModule,
75     ctx: Context,
76 
77     /// Holds info about the functions that have already been defined.
78     /// Use look them up by their original [UserFuncName] since that's how the caller
79     /// passes them to us.
80     defined_functions: HashMap<UserFuncName, DefinedFunction>,
81 
82     /// We deduplicate trampolines by the signature of the function that they target.
83     /// This map holds as a key the [Signature] of the target function, and as a value
84     /// the [UserFuncName] of the trampoline for that [Signature].
85     ///
86     /// The trampoline is defined in `defined_functions` as any other regular function.
87     trampolines: HashMap<Signature, UserFuncName>,
88 }
89 
90 impl TestFileCompiler {
91     /// Build a [TestFileCompiler] from a [TargetIsa]. For functions to be runnable on the
92     /// host machine, this [TargetIsa] must match the host machine's ISA (see
93     /// [TestFileCompiler::with_host_isa]).
94     pub fn new(isa: OwnedTargetIsa) -> Self {
95         let mut builder = JITBuilder::with_isa(isa, cranelift_module::default_libcall_names());
96         let _ = &mut builder; // require mutability on all architectures
97         #[cfg(target_arch = "x86_64")]
98         {
99             builder.symbol_lookup_fn(Box::new(|name| {
100                 if name == "__cranelift_x86_pshufb" {
101                     Some(__cranelift_x86_pshufb as *const u8)
102                 } else {
103                     None
104                 }
105             }));
106         }
107 
108         // On Unix platforms force `libm` to get linked into this executable
109         // because tests that use libcalls rely on this library being present.
110         // Without this it's been seen that when cross-compiled to riscv64 the
111         // final binary doesn't link in `libm`.
112         #[cfg(unix)]
113         {
114             unsafe extern "C" {
115                 safe fn cosf(f: f32) -> f32;
116             }
117             let f = std::hint::black_box(1.2_f32);
118             assert_eq!(f.cos(), cosf(f));
119         }
120 
121         let module = JITModule::new(builder);
122         let ctx = module.make_context();
123 
124         Self {
125             module,
126             ctx,
127             defined_functions: HashMap::new(),
128             trampolines: HashMap::new(),
129         }
130     }
131 
132     /// Build a [TestFileCompiler] using the host machine's ISA and the passed flags.
133     pub fn with_host_isa(flags: settings::Flags) -> Result<Self> {
134         let builder =
135             builder_with_options(true).expect("Unable to build a TargetIsa for the current host");
136         let isa = builder.finish(flags)?;
137         Ok(Self::new(isa))
138     }
139 
140     /// Build a [TestFileCompiler] using the host machine's ISA and the default flags for this
141     /// ISA.
142     pub fn with_default_host_isa() -> Result<Self> {
143         let flags = settings::Flags::new(settings::builder());
144         Self::with_host_isa(flags)
145     }
146 
147     /// Declares and compiles all functions in `functions`. Additionally creates a trampoline for
148     /// each one of them.
149     pub fn add_functions(
150         &mut self,
151         functions: &[Function],
152         ctrl_planes: Vec<ControlPlane>,
153     ) -> Result<()> {
154         // Declare all functions in the file, so that they may refer to each other.
155         for func in functions {
156             self.declare_function(func)?;
157         }
158 
159         let ctrl_planes = ctrl_planes
160             .into_iter()
161             .chain(std::iter::repeat(ControlPlane::default()));
162 
163         // Define all functions and trampolines
164         for (func, ref mut ctrl_plane) in functions.iter().zip(ctrl_planes) {
165             self.define_function(func.clone(), ctrl_plane)?;
166             self.create_trampoline_for_function(func, ctrl_plane)?;
167         }
168 
169         Ok(())
170     }
171 
172     /// Registers all functions in a [TestFile]. Additionally creates a trampoline for each one
173     /// of them.
174     pub fn add_testfile(&mut self, testfile: &TestFile) -> Result<()> {
175         let functions = testfile
176             .functions
177             .iter()
178             .map(|(f, _)| f)
179             .cloned()
180             .collect::<Vec<_>>();
181 
182         self.add_functions(&functions[..], Vec::new())?;
183         Ok(())
184     }
185 
186     /// Declares a function an registers it as a linkable and callable target internally
187     pub fn declare_function(&mut self, func: &Function) -> Result<()> {
188         let next_id = self.defined_functions.len() as u32;
189         match self.defined_functions.entry(func.name.clone()) {
190             Entry::Occupied(_) => {
191                 anyhow::bail!("Duplicate function with name {} found!", &func.name)
192             }
193             Entry::Vacant(v) => {
194                 let name = func.name.to_string();
195                 let func_id =
196                     self.module
197                         .declare_function(&name, Linkage::Local, &func.signature)?;
198 
199                 v.insert(DefinedFunction {
200                     new_name: UserExternalName::new(TESTFILE_NAMESPACE, next_id),
201                     signature: func.signature.clone(),
202                     func_id,
203                 });
204             }
205         };
206 
207         Ok(())
208     }
209 
210     /// Renames the function to its new [UserExternalName], as well as any other function that
211     /// it may reference.
212     ///
213     /// We have to do this since the JIT cannot link Testcase functions.
214     fn apply_func_rename(
215         &self,
216         mut func: Function,
217         defined_func: &DefinedFunction,
218     ) -> Result<Function> {
219         // First, rename the function
220         let func_original_name = func.name;
221         func.name = UserFuncName::User(defined_func.new_name.clone());
222 
223         // Rename any functions that it references
224         // Do this in stages to appease the borrow checker
225         let mut redefines = Vec::with_capacity(func.dfg.ext_funcs.len());
226         for (ext_ref, ext_func) in &func.dfg.ext_funcs {
227             let old_name = match &ext_func.name {
228                 ExternalName::TestCase(tc) => UserFuncName::Testcase(tc.clone()),
229                 ExternalName::User(username) => {
230                     UserFuncName::User(func.params.user_named_funcs()[*username].clone())
231                 }
232                 // The other cases don't need renaming, so lets just continue...
233                 _ => continue,
234             };
235 
236             let target_df = self.defined_functions.get(&old_name).ok_or(anyhow!(
237                 "Undeclared function {} is referenced by {}!",
238                 &old_name,
239                 &func_original_name
240             ))?;
241 
242             redefines.push((ext_ref, target_df.new_name.clone()));
243         }
244 
245         // Now register the redefines
246         for (ext_ref, new_name) in redefines.into_iter() {
247             // Register the new name in the func, so that we can get a reference to it.
248             let new_name_ref = func.params.ensure_user_func_name(new_name);
249 
250             // Finally rename the ExtFunc
251             func.dfg.ext_funcs[ext_ref].name = ExternalName::User(new_name_ref);
252         }
253 
254         Ok(func)
255     }
256 
257     /// Defines the body of a function
258     pub fn define_function(&mut self, func: Function, ctrl_plane: &mut ControlPlane) -> Result<()> {
259         let defined_func = self
260             .defined_functions
261             .get(&func.name)
262             .ok_or(anyhow!("Undeclared function {} found!", &func.name))?;
263 
264         self.ctx.func = self.apply_func_rename(func, defined_func)?;
265         self.module.define_function_with_control_plane(
266             defined_func.func_id,
267             &mut self.ctx,
268             ctrl_plane,
269         )?;
270         self.module.clear_context(&mut self.ctx);
271         Ok(())
272     }
273 
274     /// Creates and registers a trampoline for a function if none exists.
275     pub fn create_trampoline_for_function(
276         &mut self,
277         func: &Function,
278         ctrl_plane: &mut ControlPlane,
279     ) -> Result<()> {
280         if !self.defined_functions.contains_key(&func.name) {
281             anyhow::bail!("Undeclared function {} found!", &func.name);
282         }
283 
284         // Check if a trampoline for this function signature already exists
285         if self.trampolines.contains_key(&func.signature) {
286             return Ok(());
287         }
288 
289         // Create a trampoline and register it
290         let name = UserFuncName::user(TESTFILE_NAMESPACE, self.defined_functions.len() as u32);
291         let trampoline = make_trampoline(name.clone(), &func.signature, self.module.isa());
292 
293         self.declare_function(&trampoline)?;
294         self.define_function(trampoline, ctrl_plane)?;
295 
296         self.trampolines.insert(func.signature.clone(), name);
297 
298         Ok(())
299     }
300 
301     /// Finalize this TestFile and link all functions.
302     pub fn compile(mut self) -> Result<CompiledTestFile, CompilationError> {
303         // Finalize the functions which we just defined, which resolves any
304         // outstanding relocations (patching in addresses, now that they're
305         // available).
306         self.module.finalize_definitions()?;
307 
308         Ok(CompiledTestFile {
309             module: Some(self.module),
310             defined_functions: self.defined_functions,
311             trampolines: self.trampolines,
312         })
313     }
314 }
315 
316 /// A finalized Test File
317 pub struct CompiledTestFile {
318     /// We need to store [JITModule] since it contains the underlying memory for the functions.
319     /// Store it in an [Option] so that we can later drop it.
320     module: Option<JITModule>,
321 
322     /// Holds info about the functions that have been registered in `module`.
323     /// See [TestFileCompiler] for more info.
324     defined_functions: HashMap<UserFuncName, DefinedFunction>,
325 
326     /// Trampolines available in this [JITModule].
327     /// See [TestFileCompiler] for more info.
328     trampolines: HashMap<Signature, UserFuncName>,
329 }
330 
331 impl CompiledTestFile {
332     /// Return a trampoline for calling.
333     ///
334     /// Returns None if [TestFileCompiler::create_trampoline_for_function] wasn't called for this function.
335     pub fn get_trampoline(&self, func: &Function) -> Option<Trampoline> {
336         let defined_func = self.defined_functions.get(&func.name)?;
337         let trampoline_id = self
338             .trampolines
339             .get(&func.signature)
340             .and_then(|name| self.defined_functions.get(name))
341             .map(|df| df.func_id)?;
342         Some(Trampoline {
343             module: self.module.as_ref()?,
344             func_id: defined_func.func_id,
345             func_signature: &defined_func.signature,
346             trampoline_id,
347         })
348     }
349 }
350 
351 impl Drop for CompiledTestFile {
352     fn drop(&mut self) {
353         // Freeing the module's memory erases the compiled functions.
354         // This should be safe since their pointers never leave this struct.
355         unsafe { self.module.take().unwrap().free_memory() }
356     }
357 }
358 
359 /// A callable trampoline
360 pub struct Trampoline<'a> {
361     module: &'a JITModule,
362     func_id: FuncId,
363     func_signature: &'a Signature,
364     trampoline_id: FuncId,
365 }
366 
367 impl<'a> Trampoline<'a> {
368     /// Call the target function of this trampoline, passing in [DataValue]s using a compiled trampoline.
369     pub fn call(&self, arguments: &[DataValue]) -> Vec<DataValue> {
370         let mut values = UnboxedValues::make_arguments(arguments, &self.func_signature);
371         let arguments_address = values.as_mut_ptr();
372 
373         let function_ptr = self.module.get_finalized_function(self.func_id);
374         let trampoline_ptr = self.module.get_finalized_function(self.trampoline_id);
375 
376         unsafe {
377             self.call_raw(trampoline_ptr, function_ptr, arguments_address);
378         }
379 
380         values.collect_returns(&self.func_signature)
381     }
382 
383     unsafe fn call_raw(
384         &self,
385         trampoline_ptr: *const u8,
386         function_ptr: *const u8,
387         arguments_address: *mut u128,
388     ) {
389         match self.module.isa().triple().architecture {
390             // For the pulley target this is pulley bytecode, not machine code,
391             // so run the interpreter.
392             Architecture::Pulley32
393             | Architecture::Pulley64
394             | Architecture::Pulley32be
395             | Architecture::Pulley64be => {
396                 let mut state = pulley::Vm::new();
397                 unsafe {
398                     state.call(
399                         NonNull::new(trampoline_ptr.cast_mut()).unwrap(),
400                         &[
401                             pulley::XRegVal::new_ptr(function_ptr.cast_mut()).into(),
402                             pulley::XRegVal::new_ptr(arguments_address).into(),
403                         ],
404                         [],
405                     );
406                 }
407             }
408 
409             // Other targets natively execute this machine code.
410             _ => {
411                 let callable_trampoline: fn(*const u8, *mut u128) -> () =
412                     unsafe { mem::transmute(trampoline_ptr) };
413                 callable_trampoline(function_ptr, arguments_address);
414             }
415         }
416     }
417 }
418 
419 /// Compilation Error when compiling a function.
420 #[derive(Error, Debug)]
421 pub enum CompilationError {
422     /// Cranelift codegen error.
423     #[error("Cranelift codegen error")]
424     CodegenError(#[from] CodegenError),
425     /// Module Error
426     #[error("Module error")]
427     ModuleError(#[from] ModuleError),
428     /// Memory mapping error.
429     #[error("Memory mapping error")]
430     IoError(#[from] std::io::Error),
431 }
432 
433 /// A container for laying out the [ValueData]s in memory in a way that the [Trampoline] can
434 /// understand.
435 struct UnboxedValues(Vec<u128>);
436 
437 impl UnboxedValues {
438     /// The size in bytes of each slot location in the allocated [DataValue]s. Though [DataValue]s
439     /// could be smaller than 16 bytes (e.g. `I16`), this simplifies the creation of the [DataValue]
440     /// array and could be used to align the slots to the largest used [DataValue] (i.e. 128-bit
441     /// vectors).
442     const SLOT_SIZE: usize = 16;
443 
444     /// Build the arguments vector for passing the [DataValue]s into the [Trampoline]. The size of
445     /// `u128` used here must match [Trampoline::SLOT_SIZE].
446     pub fn make_arguments(arguments: &[DataValue], signature: &ir::Signature) -> Self {
447         assert_eq!(arguments.len(), signature.params.len());
448         let mut values_vec = vec![0; max(signature.params.len(), signature.returns.len())];
449 
450         // Store the argument values into `values_vec`.
451         for ((arg, slot), param) in arguments.iter().zip(&mut values_vec).zip(&signature.params) {
452             assert!(
453                 arg.ty() == param.value_type || arg.is_vector(),
454                 "argument type mismatch: {} != {}",
455                 arg.ty(),
456                 param.value_type
457             );
458             unsafe {
459                 arg.write_value_to(slot);
460             }
461         }
462 
463         Self(values_vec)
464     }
465 
466     /// Return a pointer to the underlying memory for passing to the trampoline.
467     pub fn as_mut_ptr(&mut self) -> *mut u128 {
468         self.0.as_mut_ptr()
469     }
470 
471     /// Collect the returned [DataValue]s into a [Vec]. The size of `u128` used here must match
472     /// [Trampoline::SLOT_SIZE].
473     pub fn collect_returns(&self, signature: &ir::Signature) -> Vec<DataValue> {
474         assert!(self.0.len() >= signature.returns.len());
475         let mut returns = Vec::with_capacity(signature.returns.len());
476 
477         // Extract the returned values from this vector.
478         for (slot, param) in self.0.iter().zip(&signature.returns) {
479             let value = unsafe { DataValue::read_value_from(slot, param.value_type) };
480             returns.push(value);
481         }
482 
483         returns
484     }
485 }
486 
487 /// Build the Cranelift IR for moving the memory-allocated [DataValue]s to their correct location
488 /// (e.g. register, stack) prior to calling a [CompiledFunction]. The [Function] returned by
489 /// [make_trampoline] is compiled to a [Trampoline]. Note that this uses the [TargetIsa]'s default
490 /// calling convention so we must also check that the [CompiledFunction] has the same calling
491 /// convention (see [TestFileCompiler::compile]).
492 fn make_trampoline(name: UserFuncName, signature: &ir::Signature, isa: &dyn TargetIsa) -> Function {
493     // Create the trampoline signature: (callee_address: pointer, values_vec: pointer) -> ()
494     let pointer_type = isa.pointer_type();
495     let mut wrapper_sig = ir::Signature::new(isa.frontend_config().default_call_conv);
496     wrapper_sig.params.push(ir::AbiParam::new(pointer_type)); // Add the `callee_address` parameter.
497     wrapper_sig.params.push(ir::AbiParam::new(pointer_type)); // Add the `values_vec` parameter.
498 
499     let mut func = ir::Function::with_name_signature(name, wrapper_sig);
500 
501     // The trampoline has a single block filled with loads, one call to callee_address, and some loads.
502     let mut builder_context = FunctionBuilderContext::new();
503     let mut builder = FunctionBuilder::new(&mut func, &mut builder_context);
504     let block0 = builder.create_block();
505     builder.append_block_params_for_function_params(block0);
506     builder.switch_to_block(block0);
507     builder.seal_block(block0);
508 
509     // Extract the incoming SSA values.
510     let (callee_value, values_vec_ptr_val) = {
511         let params = builder.func.dfg.block_params(block0);
512         (params[0], params[1])
513     };
514 
515     // Load the argument values out of `values_vec`.
516     let callee_args = signature
517         .params
518         .iter()
519         .enumerate()
520         .map(|(i, param)| {
521             // We always store vector types in little-endian byte order as DataValue.
522             let mut flags = ir::MemFlags::trusted();
523             if param.value_type.is_vector() {
524                 flags.set_endianness(ir::Endianness::Little);
525             }
526 
527             // Load the value.
528             builder.ins().load(
529                 param.value_type,
530                 flags,
531                 values_vec_ptr_val,
532                 (i * UnboxedValues::SLOT_SIZE) as i32,
533             )
534         })
535         .collect::<Vec<_>>();
536 
537     // Call the passed function.
538     let new_sig = builder.import_signature(signature.clone());
539     let call = builder
540         .ins()
541         .call_indirect(new_sig, callee_value, &callee_args);
542 
543     // Store the return values into `values_vec`.
544     let results = builder.func.dfg.inst_results(call).to_vec();
545     for ((i, value), param) in results.iter().enumerate().zip(&signature.returns) {
546         // We always store vector types in little-endian byte order as DataValue.
547         let mut flags = ir::MemFlags::trusted();
548         if param.value_type.is_vector() {
549             flags.set_endianness(ir::Endianness::Little);
550         }
551         // Store the value.
552         builder.ins().store(
553             flags,
554             *value,
555             values_vec_ptr_val,
556             (i * UnboxedValues::SLOT_SIZE) as i32,
557         );
558     }
559 
560     builder.ins().return_(&[]);
561     builder.finalize();
562 
563     func
564 }
565 
566 #[cfg(target_arch = "x86_64")]
567 use std::arch::x86_64::__m128i;
568 #[cfg(target_arch = "x86_64")]
569 #[expect(
570     improper_ctypes_definitions,
571     reason = "manually verified to work for now"
572 )]
573 extern "C" fn __cranelift_x86_pshufb(a: __m128i, b: __m128i) -> __m128i {
574     union U {
575         reg: __m128i,
576         mem: [u8; 16],
577     }
578 
579     unsafe {
580         let a = U { reg: a }.mem;
581         let b = U { reg: b }.mem;
582 
583         let select = |arr: &[u8; 16], byte: u8| {
584             if byte & 0x80 != 0 {
585                 0x00
586             } else {
587                 arr[(byte & 0xf) as usize]
588             }
589         };
590 
591         U {
592             mem: [
593                 select(&a, b[0]),
594                 select(&a, b[1]),
595                 select(&a, b[2]),
596                 select(&a, b[3]),
597                 select(&a, b[4]),
598                 select(&a, b[5]),
599                 select(&a, b[6]),
600                 select(&a, b[7]),
601                 select(&a, b[8]),
602                 select(&a, b[9]),
603                 select(&a, b[10]),
604                 select(&a, b[11]),
605                 select(&a, b[12]),
606                 select(&a, b[13]),
607                 select(&a, b[14]),
608                 select(&a, b[15]),
609             ],
610         }
611         .reg
612     }
613 }
614 
615 #[cfg(test)]
616 mod test {
617     use super::*;
618     use cranelift_reader::{parse_functions, parse_test, ParseOptions};
619 
620     fn parse(code: &str) -> Function {
621         parse_functions(code).unwrap().into_iter().nth(0).unwrap()
622     }
623 
624     #[test]
625     fn nop() {
626         // Skip this test when cranelift doesn't support the native platform.
627         if cranelift_native::builder().is_err() {
628             return;
629         }
630         let code = String::from(
631             "
632             test run
633             function %test() -> i8 {
634             block0:
635                 nop
636                 v1 = iconst.i8 -1
637                 return v1
638             }",
639         );
640         let ctrl_plane = &mut ControlPlane::default();
641 
642         // extract function
643         let test_file = parse_test(code.as_str(), ParseOptions::default()).unwrap();
644         assert_eq!(1, test_file.functions.len());
645         let function = test_file.functions[0].0.clone();
646 
647         // execute function
648         let mut compiler = TestFileCompiler::with_default_host_isa().unwrap();
649         compiler.declare_function(&function).unwrap();
650         compiler
651             .define_function(function.clone(), ctrl_plane)
652             .unwrap();
653         compiler
654             .create_trampoline_for_function(&function, ctrl_plane)
655             .unwrap();
656         let compiled = compiler.compile().unwrap();
657         let trampoline = compiled.get_trampoline(&function).unwrap();
658         let returned = trampoline.call(&[]);
659         assert_eq!(returned, vec![DataValue::I8(-1)])
660     }
661 
662     #[test]
663     fn trampolines() {
664         // Skip this test when cranelift doesn't support the native platform.
665         if cranelift_native::builder().is_err() {
666             return;
667         }
668         let function = parse(
669             "
670             function %test(f32, i8, i64x2, i8) -> f32x4, i64 {
671             block0(v0: f32, v1: i8, v2: i64x2, v3: i8):
672                 v4 = vconst.f32x4 [0x0.1 0x0.2 0x0.3 0x0.4]
673                 v5 = iconst.i64 -1
674                 return v4, v5
675             }",
676         );
677 
678         let compiler = TestFileCompiler::with_default_host_isa().unwrap();
679         let trampoline = make_trampoline(
680             UserFuncName::user(0, 0),
681             &function.signature,
682             compiler.module.isa(),
683         );
684         println!("{trampoline}");
685         assert!(format!("{trampoline}").ends_with(
686             "sig0 = (f32, i8, i64x2, i8) -> f32x4, i64 fast
687 
688 block0(v0: i64, v1: i64):
689     v2 = load.f32 notrap aligned v1
690     v3 = load.i8 notrap aligned v1+16
691     v4 = load.i64x2 notrap aligned little v1+32
692     v5 = load.i8 notrap aligned v1+48
693     v6, v7 = call_indirect sig0, v0(v2, v3, v4, v5)
694     store notrap aligned little v6, v1
695     store notrap aligned v7, v1+16
696     return
697 }
698 "
699         ));
700     }
701 }
702