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