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