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 238 .define_function(defined_func.func_id, &mut self.ctx, ctrl_plane)?; 239 self.module.clear_context(&mut self.ctx); 240 Ok(()) 241 } 242 243 /// Creates and registers a trampoline for a function if none exists. 244 pub fn create_trampoline_for_function( 245 &mut self, 246 func: &Function, 247 ctrl_plane: &mut ControlPlane, 248 ) -> Result<()> { 249 if !self.defined_functions.contains_key(&func.name) { 250 anyhow::bail!("Undeclared function {} found!", &func.name); 251 } 252 253 // Check if a trampoline for this function signature already exists 254 if self.trampolines.contains_key(&func.signature) { 255 return Ok(()); 256 } 257 258 // Create a trampoline and register it 259 let name = UserFuncName::user(TESTFILE_NAMESPACE, self.defined_functions.len() as u32); 260 let trampoline = make_trampoline(name.clone(), &func.signature, self.module.isa()); 261 262 self.declare_function(&trampoline)?; 263 self.define_function(trampoline, ctrl_plane)?; 264 265 self.trampolines.insert(func.signature.clone(), name); 266 267 Ok(()) 268 } 269 270 /// Finalize this TestFile and link all functions. 271 pub fn compile(mut self) -> Result<CompiledTestFile, CompilationError> { 272 // Finalize the functions which we just defined, which resolves any 273 // outstanding relocations (patching in addresses, now that they're 274 // available). 275 self.module.finalize_definitions()?; 276 277 Ok(CompiledTestFile { 278 module: Some(self.module), 279 defined_functions: self.defined_functions, 280 trampolines: self.trampolines, 281 }) 282 } 283 } 284 285 /// A finalized Test File 286 pub struct CompiledTestFile { 287 /// We need to store [JITModule] since it contains the underlying memory for the functions. 288 /// Store it in an [Option] so that we can later drop it. 289 module: Option<JITModule>, 290 291 /// Holds info about the functions that have been registered in `module`. 292 /// See [TestFileCompiler] for more info. 293 defined_functions: HashMap<UserFuncName, DefinedFunction>, 294 295 /// Trampolines available in this [JITModule]. 296 /// See [TestFileCompiler] for more info. 297 trampolines: HashMap<Signature, UserFuncName>, 298 } 299 300 impl CompiledTestFile { 301 /// Return a trampoline for calling. 302 /// 303 /// Returns None if [TestFileCompiler::create_trampoline_for_function] wasn't called for this function. 304 pub fn get_trampoline(&self, func: &Function) -> Option<Trampoline> { 305 let defined_func = self.defined_functions.get(&func.name)?; 306 let trampoline_id = self 307 .trampolines 308 .get(&func.signature) 309 .and_then(|name| self.defined_functions.get(name)) 310 .map(|df| df.func_id)?; 311 Some(Trampoline { 312 module: self.module.as_ref()?, 313 func_id: defined_func.func_id, 314 func_signature: &defined_func.signature, 315 trampoline_id, 316 }) 317 } 318 } 319 320 impl Drop for CompiledTestFile { 321 fn drop(&mut self) { 322 // Freeing the module's memory erases the compiled functions. 323 // This should be safe since their pointers never leave this struct. 324 unsafe { self.module.take().unwrap().free_memory() } 325 } 326 } 327 328 /// A callable trampoline 329 pub struct Trampoline<'a> { 330 module: &'a JITModule, 331 func_id: FuncId, 332 func_signature: &'a Signature, 333 trampoline_id: FuncId, 334 } 335 336 impl<'a> Trampoline<'a> { 337 /// Call the target function of this trampoline, passing in [DataValue]s using a compiled trampoline. 338 pub fn call(&self, arguments: &[DataValue]) -> Vec<DataValue> { 339 let mut values = UnboxedValues::make_arguments(arguments, &self.func_signature); 340 let arguments_address = values.as_mut_ptr(); 341 342 let function_ptr = self.module.get_finalized_function(self.func_id); 343 let trampoline_ptr = self.module.get_finalized_function(self.trampoline_id); 344 345 let callable_trampoline: fn(*const u8, *mut u128) -> () = 346 unsafe { mem::transmute(trampoline_ptr) }; 347 callable_trampoline(function_ptr, arguments_address); 348 349 values.collect_returns(&self.func_signature) 350 } 351 } 352 353 /// Compilation Error when compiling a function. 354 #[derive(Error, Debug)] 355 pub enum CompilationError { 356 /// Cranelift codegen error. 357 #[error("Cranelift codegen error")] 358 CodegenError(#[from] CodegenError), 359 /// Module Error 360 #[error("Module error")] 361 ModuleError(#[from] ModuleError), 362 /// Memory mapping error. 363 #[error("Memory mapping error")] 364 IoError(#[from] std::io::Error), 365 } 366 367 /// A container for laying out the [ValueData]s in memory in a way that the [Trampoline] can 368 /// understand. 369 struct UnboxedValues(Vec<u128>); 370 371 impl UnboxedValues { 372 /// The size in bytes of each slot location in the allocated [DataValue]s. Though [DataValue]s 373 /// could be smaller than 16 bytes (e.g. `I16`), this simplifies the creation of the [DataValue] 374 /// array and could be used to align the slots to the largest used [DataValue] (i.e. 128-bit 375 /// vectors). 376 const SLOT_SIZE: usize = 16; 377 378 /// Build the arguments vector for passing the [DataValue]s into the [Trampoline]. The size of 379 /// `u128` used here must match [Trampoline::SLOT_SIZE]. 380 pub fn make_arguments(arguments: &[DataValue], signature: &ir::Signature) -> Self { 381 assert_eq!(arguments.len(), signature.params.len()); 382 let mut values_vec = vec![0; max(signature.params.len(), signature.returns.len())]; 383 384 // Store the argument values into `values_vec`. 385 for ((arg, slot), param) in arguments.iter().zip(&mut values_vec).zip(&signature.params) { 386 assert!( 387 arg.ty() == param.value_type || arg.is_vector(), 388 "argument type mismatch: {} != {}", 389 arg.ty(), 390 param.value_type 391 ); 392 unsafe { 393 arg.write_value_to(slot); 394 } 395 } 396 397 Self(values_vec) 398 } 399 400 /// Return a pointer to the underlying memory for passing to the trampoline. 401 pub fn as_mut_ptr(&mut self) -> *mut u128 { 402 self.0.as_mut_ptr() 403 } 404 405 /// Collect the returned [DataValue]s into a [Vec]. The size of `u128` used here must match 406 /// [Trampoline::SLOT_SIZE]. 407 pub fn collect_returns(&self, signature: &ir::Signature) -> Vec<DataValue> { 408 assert!(self.0.len() >= signature.returns.len()); 409 let mut returns = Vec::with_capacity(signature.returns.len()); 410 411 // Extract the returned values from this vector. 412 for (slot, param) in self.0.iter().zip(&signature.returns) { 413 let value = unsafe { DataValue::read_value_from(slot, param.value_type) }; 414 returns.push(value); 415 } 416 417 returns 418 } 419 } 420 421 /// Build the Cranelift IR for moving the memory-allocated [DataValue]s to their correct location 422 /// (e.g. register, stack) prior to calling a [CompiledFunction]. The [Function] returned by 423 /// [make_trampoline] is compiled to a [Trampoline]. Note that this uses the [TargetIsa]'s default 424 /// calling convention so we must also check that the [CompiledFunction] has the same calling 425 /// convention (see [TestFileCompiler::compile]). 426 fn make_trampoline(name: UserFuncName, signature: &ir::Signature, isa: &dyn TargetIsa) -> Function { 427 // Create the trampoline signature: (callee_address: pointer, values_vec: pointer) -> () 428 let pointer_type = isa.pointer_type(); 429 let mut wrapper_sig = ir::Signature::new(isa.frontend_config().default_call_conv); 430 wrapper_sig.params.push(ir::AbiParam::new(pointer_type)); // Add the `callee_address` parameter. 431 wrapper_sig.params.push(ir::AbiParam::new(pointer_type)); // Add the `values_vec` parameter. 432 433 let mut func = ir::Function::with_name_signature(name, wrapper_sig); 434 435 // The trampoline has a single block filled with loads, one call to callee_address, and some loads. 436 let mut builder_context = FunctionBuilderContext::new(); 437 let mut builder = FunctionBuilder::new(&mut func, &mut builder_context); 438 let block0 = builder.create_block(); 439 builder.append_block_params_for_function_params(block0); 440 builder.switch_to_block(block0); 441 builder.seal_block(block0); 442 443 // Extract the incoming SSA values. 444 let (callee_value, values_vec_ptr_val) = { 445 let params = builder.func.dfg.block_params(block0); 446 (params[0], params[1]) 447 }; 448 449 // Load the argument values out of `values_vec`. 450 let callee_args = signature 451 .params 452 .iter() 453 .enumerate() 454 .map(|(i, param)| { 455 // We always store vector types in little-endian byte order as DataValue. 456 let mut flags = ir::MemFlags::trusted(); 457 if param.value_type.is_vector() { 458 flags.set_endianness(ir::Endianness::Little); 459 } 460 461 // Load the value. 462 builder.ins().load( 463 param.value_type, 464 flags, 465 values_vec_ptr_val, 466 (i * UnboxedValues::SLOT_SIZE) as i32, 467 ) 468 }) 469 .collect::<Vec<_>>(); 470 471 // Call the passed function. 472 let new_sig = builder.import_signature(signature.clone()); 473 let call = builder 474 .ins() 475 .call_indirect(new_sig, callee_value, &callee_args); 476 477 // Store the return values into `values_vec`. 478 let results = builder.func.dfg.inst_results(call).to_vec(); 479 for ((i, value), param) in results.iter().enumerate().zip(&signature.returns) { 480 // We always store vector types in little-endian byte order as DataValue. 481 let mut flags = ir::MemFlags::trusted(); 482 if param.value_type.is_vector() { 483 flags.set_endianness(ir::Endianness::Little); 484 } 485 // Store the value. 486 builder.ins().store( 487 flags, 488 *value, 489 values_vec_ptr_val, 490 (i * UnboxedValues::SLOT_SIZE) as i32, 491 ); 492 } 493 494 builder.ins().return_(&[]); 495 builder.finalize(); 496 497 func 498 } 499 500 #[cfg(test)] 501 mod test { 502 use super::*; 503 use cranelift_reader::{parse_functions, parse_test, ParseOptions}; 504 505 fn parse(code: &str) -> Function { 506 parse_functions(code).unwrap().into_iter().nth(0).unwrap() 507 } 508 509 #[test] 510 fn nop() { 511 let code = String::from( 512 " 513 test run 514 function %test() -> i8 { 515 block0: 516 nop 517 v1 = iconst.i8 -1 518 return v1 519 }", 520 ); 521 let ctrl_plane = &mut ControlPlane::default(); 522 523 // extract function 524 let test_file = parse_test(code.as_str(), ParseOptions::default()).unwrap(); 525 assert_eq!(1, test_file.functions.len()); 526 let function = test_file.functions[0].0.clone(); 527 528 // execute function 529 let mut compiler = TestFileCompiler::with_default_host_isa().unwrap(); 530 compiler.declare_function(&function).unwrap(); 531 compiler 532 .define_function(function.clone(), ctrl_plane) 533 .unwrap(); 534 compiler 535 .create_trampoline_for_function(&function, ctrl_plane) 536 .unwrap(); 537 let compiled = compiler.compile().unwrap(); 538 let trampoline = compiled.get_trampoline(&function).unwrap(); 539 let returned = trampoline.call(&[]); 540 assert_eq!(returned, vec![DataValue::I8(-1)]) 541 } 542 543 #[test] 544 fn trampolines() { 545 let function = parse( 546 " 547 function %test(f32, i8, i64x2, i8) -> f32x4, i64 { 548 block0(v0: f32, v1: i8, v2: i64x2, v3: i8): 549 v4 = vconst.f32x4 [0x0.1 0x0.2 0x0.3 0x0.4] 550 v5 = iconst.i64 -1 551 return v4, v5 552 }", 553 ); 554 555 let compiler = TestFileCompiler::with_default_host_isa().unwrap(); 556 let trampoline = make_trampoline( 557 UserFuncName::user(0, 0), 558 &function.signature, 559 compiler.module.isa(), 560 ); 561 println!("{}", trampoline); 562 assert!(format!("{}", trampoline).ends_with( 563 "sig0 = (f32, i8, i64x2, i8) -> f32x4, i64 fast 564 565 block0(v0: i64, v1: i64): 566 v2 = load.f32 notrap aligned v1 567 v3 = load.i8 notrap aligned v1+16 568 v4 = load.i64x2 notrap aligned little v1+32 569 v5 = load.i8 notrap aligned v1+48 570 v6, v7 = call_indirect sig0, v0(v2, v3, v4, v5) 571 store notrap aligned little v6, v1 572 store notrap aligned v7, v1+16 573 return 574 } 575 " 576 )); 577 } 578 } 579