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