1 //! Provides functionality for compiling and running CLIF IR for `run` tests.
2 use core::{mem, ptr};
3 use cranelift_codegen::binemit::{NullRelocSink, NullStackMapSink, NullTrapSink};
4 use cranelift_codegen::data_value::DataValue;
5 use cranelift_codegen::ir::immediates::{Ieee32, Ieee64};
6 use cranelift_codegen::ir::{condcodes::IntCC, Function, InstBuilder, Signature, Type};
7 use cranelift_codegen::isa::TargetIsa;
8 use cranelift_codegen::{ir, settings, CodegenError, Context};
9 use cranelift_frontend::{FunctionBuilder, FunctionBuilderContext};
10 use cranelift_native::builder as host_isa_builder;
11 use log::trace;
12 use memmap2::{Mmap, MmapMut};
13 use std::cmp::max;
14 use std::collections::HashMap;
15 use thiserror::Error;
16 
17 /// Compile a single function.
18 ///
19 /// Several Cranelift functions need the ability to run Cranelift IR (e.g. `test_run`); this
20 /// [SingleFunctionCompiler] provides a way for compiling Cranelift [Function]s to
21 /// `CompiledFunction`s and subsequently calling them through the use of a `Trampoline`. As its
22 /// name indicates, this compiler is limited: any functionality that requires knowledge of things
23 /// outside the [Function] will likely not work (e.g. global values, calls). For an example of this
24 /// "outside-of-function" functionality, see `cranelift_jit::backend::JITBackend`.
25 ///
26 /// ```
27 /// use cranelift_filetests::SingleFunctionCompiler;
28 /// use cranelift_reader::parse_functions;
29 ///
30 /// let code = "test run \n function %add(i32, i32) -> i32 {  block0(v0:i32, v1:i32):  v2 = iadd v0, v1  return v2 }".into();
31 /// let func = parse_functions(code).unwrap().into_iter().nth(0).unwrap();
32 /// let mut compiler = SingleFunctionCompiler::with_default_host_isa();
33 /// let compiled_func = compiler.compile(func).unwrap();
34 /// println!("Address of compiled function: {:p}", compiled_func.as_ptr());
35 /// ```
36 pub struct SingleFunctionCompiler {
37     isa: Box<dyn TargetIsa>,
38     trampolines: HashMap<Signature, Trampoline>,
39 }
40 
41 impl SingleFunctionCompiler {
42     /// Build a [SingleFunctionCompiler] from a [TargetIsa]. For functions to be runnable on the
43     /// host machine, this [TargetIsa] must match the host machine's ISA (see
44     /// [SingleFunctionCompiler::with_host_isa]).
45     pub fn new(isa: Box<dyn TargetIsa>) -> Self {
46         let trampolines = HashMap::new();
47         Self { isa, trampolines }
48     }
49 
50     /// Build a [SingleFunctionCompiler] using the host machine's ISA and the passed flags.
51     pub fn with_host_isa(flags: settings::Flags) -> Self {
52         let builder = host_isa_builder().expect("Unable to build a TargetIsa for the current host");
53         let isa = builder.finish(flags);
54         Self::new(isa)
55     }
56 
57     /// Build a [SingleFunctionCompiler] using the host machine's ISA and the default flags for this
58     /// ISA.
59     pub fn with_default_host_isa() -> Self {
60         let flags = settings::Flags::new(settings::builder());
61         Self::with_host_isa(flags)
62     }
63 
64     /// Compile the passed [Function] to a `CompiledFunction`. This function will:
65     ///  - check that the default ISA calling convention is used (to ensure it can be called)
66     ///  - compile the [Function]
67     ///  - compile a `Trampoline` for the [Function]'s signature (or used a cached `Trampoline`;
68     ///    this makes it possible to call functions when the signature is not known until runtime.
69     pub fn compile(&mut self, function: Function) -> Result<CompiledFunction, CompilationError> {
70         let signature = function.signature.clone();
71         if signature.call_conv != self.isa.default_call_conv() {
72             return Err(CompilationError::InvalidTargetIsa);
73         }
74 
75         // Compile the function itself.
76         let code_page = compile(function, self.isa.as_ref())?;
77 
78         // Compile the trampoline to call it, if necessary (it may be cached).
79         let isa = self.isa.as_ref();
80         let trampoline = self
81             .trampolines
82             .entry(signature.clone())
83             .or_insert_with(|| {
84                 let ir = make_trampoline(&signature, isa);
85                 let code = compile(ir, isa).expect("failed to compile trampoline");
86                 Trampoline::new(code)
87             });
88 
89         Ok(CompiledFunction::new(code_page, signature, trampoline))
90     }
91 }
92 
93 #[derive(Error, Debug)]
94 pub enum CompilationError {
95     #[error("Cross-compilation not currently supported; use the host's default calling convention \
96     or remove the specified calling convention in the function signature to use the host's default.")]
97     InvalidTargetIsa,
98     #[error("Cranelift codegen error")]
99     CodegenError(#[from] CodegenError),
100     #[error("Memory mapping error")]
101     IoError(#[from] std::io::Error),
102 }
103 
104 /// Contains the compiled code to move memory-allocated [DataValue]s to the correct location (e.g.
105 /// register, stack) dictated by the calling convention before calling a [CompiledFunction]. Without
106 /// this, it would be quite difficult to correctly place [DataValue]s since both the calling
107 /// convention and function signature are not known until runtime. See [make_trampoline] for the
108 /// Cranelift IR used to build this.
109 pub struct Trampoline {
110     page: Mmap,
111 }
112 
113 impl Trampoline {
114     /// Build a new [Trampoline].
115     pub fn new(page: Mmap) -> Self {
116         Self { page }
117     }
118 
119     /// Return a pointer to the compiled code.
120     fn as_ptr(&self) -> *const u8 {
121         self.page.as_ptr()
122     }
123 }
124 
125 /// Container for the compiled code of a [Function]. This wrapper allows users to call the compiled
126 /// function through the use of a [Trampoline].
127 ///
128 /// ```
129 /// use cranelift_filetests::SingleFunctionCompiler;
130 /// use cranelift_reader::parse_functions;
131 /// use cranelift_codegen::data_value::DataValue;
132 ///
133 /// let code = "test run \n function %add(i32, i32) -> i32 {  block0(v0:i32, v1:i32):  v2 = iadd v0, v1  return v2 }".into();
134 /// let func = parse_functions(code).unwrap().into_iter().nth(0).unwrap();
135 /// let mut compiler = SingleFunctionCompiler::with_default_host_isa();
136 /// let compiled_func = compiler.compile(func).unwrap();
137 ///
138 /// let returned = compiled_func.call(&vec![DataValue::I32(2), DataValue::I32(40)]);
139 /// assert_eq!(vec![DataValue::I32(42)], returned);
140 /// ```
141 pub struct CompiledFunction<'a> {
142     page: Mmap,
143     signature: Signature,
144     trampoline: &'a Trampoline,
145 }
146 
147 impl<'a> CompiledFunction<'a> {
148     /// Build a new [CompiledFunction].
149     pub fn new(page: Mmap, signature: Signature, trampoline: &'a Trampoline) -> Self {
150         Self {
151             page,
152             signature,
153             trampoline,
154         }
155     }
156 
157     /// Return a pointer to the compiled code.
158     pub fn as_ptr(&self) -> *const u8 {
159         self.page.as_ptr()
160     }
161 
162     /// Call the [CompiledFunction], passing in [DataValue]s using a compiled [Trampoline].
163     pub fn call(&self, arguments: &[DataValue]) -> Vec<DataValue> {
164         let mut values = UnboxedValues::make_arguments(arguments, &self.signature);
165         let arguments_address = values.as_mut_ptr();
166         let function_address = self.as_ptr();
167 
168         let callable_trampoline: fn(*const u8, *mut u128) -> () =
169             unsafe { mem::transmute(self.trampoline.as_ptr()) };
170         callable_trampoline(function_address, arguments_address);
171 
172         values.collect_returns(&self.signature)
173     }
174 }
175 
176 /// A container for laying out the [ValueData]s in memory in a way that the [Trampoline] can
177 /// understand.
178 struct UnboxedValues(Vec<u128>);
179 
180 impl UnboxedValues {
181     /// The size in bytes of each slot location in the allocated [DataValue]s. Though [DataValue]s
182     /// could be smaller than 16 bytes (e.g. `I16`), this simplifies the creation of the [DataValue]
183     /// array and could be used to align the slots to the largest used [DataValue] (i.e. 128-bit
184     /// vectors).
185     const SLOT_SIZE: usize = 16;
186 
187     /// Build the arguments vector for passing the [DataValue]s into the [Trampoline]. The size of
188     /// `u128` used here must match [Trampoline::SLOT_SIZE].
189     pub fn make_arguments(arguments: &[DataValue], signature: &ir::Signature) -> Self {
190         assert_eq!(arguments.len(), signature.params.len());
191         let mut values_vec = vec![0; max(signature.params.len(), signature.returns.len())];
192 
193         // Store the argument values into `values_vec`.
194         for ((arg, slot), param) in arguments.iter().zip(&mut values_vec).zip(&signature.params) {
195             assert!(
196                 arg.ty() == param.value_type || arg.is_vector(),
197                 "argument type mismatch: {} != {}",
198                 arg.ty(),
199                 param.value_type
200             );
201             unsafe {
202                 Self::write_value_to(arg, slot);
203             }
204         }
205 
206         Self(values_vec)
207     }
208 
209     /// Return a pointer to the underlying memory for passing to the trampoline.
210     pub fn as_mut_ptr(&mut self) -> *mut u128 {
211         self.0.as_mut_ptr()
212     }
213 
214     /// Collect the returned [DataValue]s into a [Vec]. The size of `u128` used here must match
215     /// [Trampoline::SLOT_SIZE].
216     pub fn collect_returns(&self, signature: &ir::Signature) -> Vec<DataValue> {
217         assert!(self.0.len() >= signature.returns.len());
218         let mut returns = Vec::with_capacity(signature.returns.len());
219 
220         // Extract the returned values from this vector.
221         for (slot, param) in self.0.iter().zip(&signature.returns) {
222             let value = unsafe { Self::read_value_from(slot, param.value_type) };
223             returns.push(value);
224         }
225 
226         returns
227     }
228 
229     /// Write a [DataValue] to a memory location.
230     unsafe fn write_value_to(v: &DataValue, p: *mut u128) {
231         match v {
232             DataValue::B(b) => ptr::write(p as *mut bool, *b),
233             DataValue::I8(i) => ptr::write(p as *mut i8, *i),
234             DataValue::I16(i) => ptr::write(p as *mut i16, *i),
235             DataValue::I32(i) => ptr::write(p as *mut i32, *i),
236             DataValue::I64(i) => ptr::write(p as *mut i64, *i),
237             DataValue::F32(f) => ptr::write(p as *mut Ieee32, *f),
238             DataValue::F64(f) => ptr::write(p as *mut Ieee64, *f),
239             DataValue::V128(b) => ptr::write(p as *mut [u8; 16], *b),
240             _ => unimplemented!(),
241         }
242     }
243 
244     /// Read a [DataValue] from a memory location using a given [Type].
245     unsafe fn read_value_from(p: *const u128, ty: Type) -> DataValue {
246         match ty {
247             ir::types::I8 => DataValue::I8(ptr::read(p as *const i8)),
248             ir::types::I16 => DataValue::I16(ptr::read(p as *const i16)),
249             ir::types::I32 => DataValue::I32(ptr::read(p as *const i32)),
250             ir::types::I64 => DataValue::I64(ptr::read(p as *const i64)),
251             ir::types::F32 => DataValue::F32(ptr::read(p as *const Ieee32)),
252             ir::types::F64 => DataValue::F64(ptr::read(p as *const Ieee64)),
253             _ if ty.is_bool() => DataValue::B(ptr::read(p as *const bool)),
254             _ if ty.is_vector() && ty.bytes() == 16 => {
255                 DataValue::V128(ptr::read(p as *const [u8; 16]))
256             }
257             _ => unimplemented!(),
258         }
259     }
260 }
261 
262 /// Compile a [Function] to its executable bytes in memory.
263 ///
264 /// This currently returns a [Mmap], a type from an external crate, so we wrap this up before
265 /// exposing it in public APIs.
266 fn compile(function: Function, isa: &dyn TargetIsa) -> Result<Mmap, CompilationError> {
267     // Set up the context.
268     let mut context = Context::new();
269     context.func = function;
270 
271     // Compile and encode the result to machine code.
272     let relocs = &mut NullRelocSink {};
273     let traps = &mut NullTrapSink {};
274     let stack_maps = &mut NullStackMapSink {};
275     let code_info = context.compile(isa)?;
276     let mut code_page = MmapMut::map_anon(code_info.total_size as usize)?;
277 
278     unsafe {
279         context.emit_to_memory(isa, code_page.as_mut_ptr(), relocs, traps, stack_maps);
280     };
281 
282     let code_page = code_page.make_exec()?;
283     trace!(
284         "Compiled function {} with signature {} at: {:p}",
285         context.func.name,
286         context.func.signature,
287         code_page.as_ptr()
288     );
289 
290     Ok(code_page)
291 }
292 
293 /// Build the Cranelift IR for moving the memory-allocated [DataValue]s to their correct location
294 /// (e.g. register, stack) prior to calling a [CompiledFunction]. The [Function] returned by
295 /// [make_trampoline] is compiled to a [Trampoline]. Note that this uses the [TargetIsa]'s default
296 /// calling convention so we must also check that the [CompiledFunction] has the same calling
297 /// convention (see [SingleFunctionCompiler::compile]).
298 fn make_trampoline(signature: &ir::Signature, isa: &dyn TargetIsa) -> Function {
299     // Create the trampoline signature: (callee_address: pointer, values_vec: pointer) -> ()
300     let pointer_type = isa.pointer_type();
301     let mut wrapper_sig = ir::Signature::new(isa.frontend_config().default_call_conv);
302     wrapper_sig.params.push(ir::AbiParam::new(pointer_type)); // Add the `callee_address` parameter.
303     wrapper_sig.params.push(ir::AbiParam::new(pointer_type)); // Add the `values_vec` parameter.
304 
305     let mut func = ir::Function::with_name_signature(ir::ExternalName::user(0, 0), wrapper_sig);
306 
307     // The trampoline has a single block filled with loads, one call to callee_address, and some loads.
308     let mut builder_context = FunctionBuilderContext::new();
309     let mut builder = FunctionBuilder::new(&mut func, &mut builder_context);
310     let block0 = builder.create_block();
311     builder.append_block_params_for_function_params(block0);
312     builder.switch_to_block(block0);
313     builder.seal_block(block0);
314 
315     // Extract the incoming SSA values.
316     let (callee_value, values_vec_ptr_val) = {
317         let params = builder.func.dfg.block_params(block0);
318         (params[0], params[1])
319     };
320 
321     // Load the argument values out of `values_vec`.
322     let callee_args = signature
323         .params
324         .iter()
325         .enumerate()
326         .map(|(i, param)| {
327             // Calculate the type to load from memory, using integers for booleans (no encodings).
328             let ty = if param.value_type.is_bool() {
329                 Type::int(max(param.value_type.bits(), 8)).expect(
330                     "to be able to convert any boolean type to its equal-width integer type",
331                 )
332             } else {
333                 param.value_type
334             };
335             // Load the value.
336             let loaded = builder.ins().load(
337                 ty,
338                 ir::MemFlags::trusted(),
339                 values_vec_ptr_val,
340                 (i * UnboxedValues::SLOT_SIZE) as i32,
341             );
342             // For booleans, we want to type-convert the loaded integer into a boolean and ensure
343             // that we are using the architecture's canonical boolean representation (presumably
344             // comparison will emit this).
345             if param.value_type.is_bool() {
346                 builder.ins().icmp_imm(IntCC::NotEqual, loaded, 0)
347             } else {
348                 loaded
349             }
350         })
351         .collect::<Vec<_>>();
352 
353     // Call the passed function.
354     let new_sig = builder.import_signature(signature.clone());
355     let call = builder
356         .ins()
357         .call_indirect(new_sig, callee_value, &callee_args);
358 
359     // Store the return values into `values_vec`.
360     let results = builder.func.dfg.inst_results(call).to_vec();
361     for ((i, value), param) in results.iter().enumerate().zip(&signature.returns) {
362         // Before storing return values, we convert booleans to their integer representation.
363         let value = if param.value_type.is_bool() {
364             let ty = Type::int(max(param.value_type.bits(), 8))
365                 .expect("to be able to convert any boolean type to its equal-width integer type");
366             builder.ins().bint(ty, *value)
367         } else {
368             *value
369         };
370         // Store the value.
371         builder.ins().store(
372             ir::MemFlags::trusted(),
373             value,
374             values_vec_ptr_val,
375             (i * UnboxedValues::SLOT_SIZE) as i32,
376         );
377     }
378 
379     builder.ins().return_(&[]);
380     builder.finalize();
381 
382     func
383 }
384 
385 #[cfg(test)]
386 mod test {
387     use super::*;
388     use cranelift_reader::{parse_functions, parse_test, ParseOptions};
389 
390     fn parse(code: &str) -> Function {
391         parse_functions(code).unwrap().into_iter().nth(0).unwrap()
392     }
393 
394     #[test]
395     fn nop() {
396         let code = String::from(
397             "
398             test run
399             function %test() -> b8 {
400             block0:
401                 nop
402                 v1 = bconst.b8 true
403                 return v1
404             }",
405         );
406 
407         // extract function
408         let test_file = parse_test(code.as_str(), ParseOptions::default()).unwrap();
409         assert_eq!(1, test_file.functions.len());
410         let function = test_file.functions[0].0.clone();
411 
412         // execute function
413         let mut compiler = SingleFunctionCompiler::with_default_host_isa();
414         let compiled_function = compiler.compile(function).unwrap();
415         let returned = compiled_function.call(&[]);
416         assert_eq!(returned, vec![DataValue::B(true)])
417     }
418 
419     #[test]
420     fn trampolines() {
421         let function = parse(
422             "
423             function %test(f32, i8, i64x2, b1) -> f32x4, b64 {
424             block0(v0: f32, v1: i8, v2: i64x2, v3: b1):
425                 v4 = vconst.f32x4 [0x0.1 0x0.2 0x0.3 0x0.4]
426                 v5 = bconst.b64 true
427                 return v4, v5
428             }",
429         );
430 
431         let compiler = SingleFunctionCompiler::with_default_host_isa();
432         let trampoline = make_trampoline(&function.signature, compiler.isa.as_ref());
433         assert!(format!("{}", trampoline).ends_with(
434             "sig0 = (f32, i8, i64x2, b1) -> f32x4, b64 fast
435 
436 block0(v0: i64, v1: i64):
437     v2 = load.f32 notrap aligned v1
438     v3 = load.i8 notrap aligned v1+16
439     v4 = load.i64x2 notrap aligned v1+32
440     v5 = load.i8 notrap aligned v1+48
441     v6 = icmp_imm ne v5, 0
442     v7, v8 = call_indirect sig0, v0(v2, v3, v4, v6)
443     store notrap aligned v7, v1
444     v9 = bint.i64 v8
445     store notrap aligned v9, v1+16
446     return
447 }
448 "
449         ));
450     }
451 }
452