1 //! Intermediate representation of a function. 2 //! 3 //! The `Function` struct defined in this module owns all of its basic blocks and 4 //! instructions. 5 6 use crate::entity::{PrimaryMap, SecondaryMap}; 7 use crate::ir::{ 8 self, Block, DataFlowGraph, DynamicStackSlot, DynamicStackSlotData, DynamicStackSlots, 9 DynamicType, ExtFuncData, FuncRef, GlobalValue, GlobalValueData, Inst, JumpTable, 10 JumpTableData, Layout, Opcode, SigRef, Signature, SourceLocs, StackSlot, StackSlotData, 11 StackSlots, Table, TableData, Type, 12 }; 13 use crate::isa::CallConv; 14 use crate::write::write_function; 15 use crate::HashMap; 16 #[cfg(feature = "enable-serde")] 17 use alloc::string::String; 18 use core::fmt; 19 20 #[cfg(feature = "enable-serde")] 21 use serde::de::{Deserializer, Error}; 22 #[cfg(feature = "enable-serde")] 23 use serde::ser::Serializer; 24 #[cfg(feature = "enable-serde")] 25 use serde::{Deserialize, Serialize}; 26 27 use super::entities::UserExternalNameRef; 28 use super::extname::UserFuncName; 29 use super::{RelSourceLoc, SourceLoc, UserExternalName}; 30 31 /// A version marker used to ensure that serialized clif ir is never deserialized with a 32 /// different version of Cranelift. 33 #[derive(Default, Copy, Clone, Debug, PartialEq, Hash)] 34 pub struct VersionMarker; 35 36 #[cfg(feature = "enable-serde")] 37 impl Serialize for VersionMarker { 38 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> 39 where 40 S: Serializer, 41 { 42 crate::VERSION.serialize(serializer) 43 } 44 } 45 46 #[cfg(feature = "enable-serde")] 47 impl<'de> Deserialize<'de> for VersionMarker { 48 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> 49 where 50 D: Deserializer<'de>, 51 { 52 let version = String::deserialize(deserializer)?; 53 if version != crate::VERSION { 54 return Err(D::Error::custom(&format!( 55 "Expected a clif ir function for version {}, found one for version {}", 56 crate::VERSION, 57 version, 58 ))); 59 } 60 Ok(VersionMarker) 61 } 62 } 63 64 /// Function parameters used when creating this function, and that will become applied after 65 /// compilation to materialize the final `CompiledCode`. 66 #[derive(Clone, PartialEq)] 67 #[cfg_attr( 68 feature = "enable-serde", 69 derive(serde_derive::Serialize, serde_derive::Deserialize) 70 )] 71 pub struct FunctionParameters { 72 /// The first `SourceLoc` appearing in the function, serving as a base for every relative 73 /// source loc in the function. 74 base_srcloc: Option<SourceLoc>, 75 76 /// External user-defined function references. 77 user_named_funcs: PrimaryMap<UserExternalNameRef, UserExternalName>, 78 79 /// Inverted mapping of `user_named_funcs`, to deduplicate internally. 80 user_ext_name_to_ref: HashMap<UserExternalName, UserExternalNameRef>, 81 } 82 83 impl FunctionParameters { 84 /// Creates a new `FunctionParameters` with the given name. 85 pub fn new() -> Self { 86 Self { 87 base_srcloc: None, 88 user_named_funcs: Default::default(), 89 user_ext_name_to_ref: Default::default(), 90 } 91 } 92 93 /// Returns the base `SourceLoc`. 94 /// 95 /// If it was never explicitly set with `ensure_base_srcloc`, will return an invalid 96 /// `SourceLoc`. 97 pub fn base_srcloc(&self) -> SourceLoc { 98 self.base_srcloc.unwrap_or_default() 99 } 100 101 /// Sets the base `SourceLoc`, if not set yet, and returns the base value. 102 pub fn ensure_base_srcloc(&mut self, srcloc: SourceLoc) -> SourceLoc { 103 match self.base_srcloc { 104 Some(val) => val, 105 None => { 106 self.base_srcloc = Some(srcloc); 107 srcloc 108 } 109 } 110 } 111 112 /// Retrieve a `UserExternalNameRef` for the given name, or add a new one. 113 /// 114 /// This method internally deduplicates same `UserExternalName` so they map to the same 115 /// reference. 116 pub fn ensure_user_func_name(&mut self, name: UserExternalName) -> UserExternalNameRef { 117 if let Some(reff) = self.user_ext_name_to_ref.get(&name) { 118 *reff 119 } else { 120 let reff = self.user_named_funcs.push(name.clone()); 121 self.user_ext_name_to_ref.insert(name, reff); 122 reff 123 } 124 } 125 126 /// Resets an already existing user function name to a new value. 127 pub fn reset_user_func_name(&mut self, index: UserExternalNameRef, name: UserExternalName) { 128 if let Some(prev_name) = self.user_named_funcs.get_mut(index) { 129 self.user_ext_name_to_ref.remove(prev_name); 130 *prev_name = name.clone(); 131 self.user_ext_name_to_ref.insert(name, index); 132 } 133 } 134 135 /// Returns the internal mapping of `UserExternalNameRef` to `UserExternalName`. 136 pub fn user_named_funcs(&self) -> &PrimaryMap<UserExternalNameRef, UserExternalName> { 137 &self.user_named_funcs 138 } 139 140 fn clear(&mut self) { 141 self.base_srcloc = None; 142 self.user_named_funcs.clear(); 143 self.user_ext_name_to_ref.clear(); 144 } 145 } 146 147 /// Function fields needed when compiling a function. 148 /// 149 /// Additionally, these fields can be the same for two functions that would be compiled the same 150 /// way, and finalized by applying `FunctionParameters` onto their `CompiledCodeStencil`. 151 #[derive(Clone, PartialEq, Hash)] 152 #[cfg_attr( 153 feature = "enable-serde", 154 derive(serde_derive::Serialize, serde_derive::Deserialize) 155 )] 156 pub struct FunctionStencil { 157 /// A version marker used to ensure that serialized clif ir is never deserialized with a 158 /// different version of Cranelift. 159 // Note: This must be the first field to ensure that Serde will deserialize it before 160 // attempting to deserialize other fields that are potentially changed between versions. 161 pub version_marker: VersionMarker, 162 163 /// Signature of this function. 164 pub signature: Signature, 165 166 /// Sized stack slots allocated in this function. 167 pub sized_stack_slots: StackSlots, 168 169 /// Dynamic stack slots allocated in this function. 170 pub dynamic_stack_slots: DynamicStackSlots, 171 172 /// Global values referenced. 173 pub global_values: PrimaryMap<ir::GlobalValue, ir::GlobalValueData>, 174 175 /// Tables referenced. 176 pub tables: PrimaryMap<ir::Table, ir::TableData>, 177 178 /// Data flow graph containing the primary definition of all instructions, blocks and values. 179 pub dfg: DataFlowGraph, 180 181 /// Layout of blocks and instructions in the function body. 182 pub layout: Layout, 183 184 /// Source locations. 185 /// 186 /// Track the original source location for each instruction. The source locations are not 187 /// interpreted by Cranelift, only preserved. 188 pub srclocs: SourceLocs, 189 190 /// An optional global value which represents an expression evaluating to 191 /// the stack limit for this function. This `GlobalValue` will be 192 /// interpreted in the prologue, if necessary, to insert a stack check to 193 /// ensure that a trap happens if the stack pointer goes below the 194 /// threshold specified here. 195 pub stack_limit: Option<ir::GlobalValue>, 196 } 197 198 impl FunctionStencil { 199 fn clear(&mut self) { 200 self.signature.clear(CallConv::Fast); 201 self.sized_stack_slots.clear(); 202 self.dynamic_stack_slots.clear(); 203 self.global_values.clear(); 204 self.tables.clear(); 205 self.dfg.clear(); 206 self.layout.clear(); 207 self.srclocs.clear(); 208 self.stack_limit = None; 209 } 210 211 /// Creates a jump table in the function, to be used by `br_table` instructions. 212 pub fn create_jump_table(&mut self, data: JumpTableData) -> JumpTable { 213 self.dfg.jump_tables.push(data) 214 } 215 216 /// Creates a sized stack slot in the function, to be used by `stack_load`, `stack_store` 217 /// and `stack_addr` instructions. 218 pub fn create_sized_stack_slot(&mut self, data: StackSlotData) -> StackSlot { 219 self.sized_stack_slots.push(data) 220 } 221 222 /// Creates a dynamic stack slot in the function, to be used by `dynamic_stack_load`, 223 /// `dynamic_stack_store` and `dynamic_stack_addr` instructions. 224 pub fn create_dynamic_stack_slot(&mut self, data: DynamicStackSlotData) -> DynamicStackSlot { 225 self.dynamic_stack_slots.push(data) 226 } 227 228 /// Adds a signature which can later be used to declare an external function import. 229 pub fn import_signature(&mut self, signature: Signature) -> SigRef { 230 self.dfg.signatures.push(signature) 231 } 232 233 /// Declares a global value accessible to the function. 234 pub fn create_global_value(&mut self, data: GlobalValueData) -> GlobalValue { 235 self.global_values.push(data) 236 } 237 238 /// Find the global dyn_scale value associated with given DynamicType. 239 pub fn get_dyn_scale(&self, ty: DynamicType) -> GlobalValue { 240 self.dfg.dynamic_types.get(ty).unwrap().dynamic_scale 241 } 242 243 /// Find the global dyn_scale for the given stack slot. 244 pub fn get_dynamic_slot_scale(&self, dss: DynamicStackSlot) -> GlobalValue { 245 let dyn_ty = self.dynamic_stack_slots.get(dss).unwrap().dyn_ty; 246 self.get_dyn_scale(dyn_ty) 247 } 248 249 /// Get a concrete `Type` from a user defined `DynamicType`. 250 pub fn get_concrete_dynamic_ty(&self, ty: DynamicType) -> Option<Type> { 251 self.dfg 252 .dynamic_types 253 .get(ty) 254 .unwrap_or_else(|| panic!("Undeclared dynamic vector type: {}", ty)) 255 .concrete() 256 } 257 258 /// Declares a table accessible to the function. 259 pub fn create_table(&mut self, data: TableData) -> Table { 260 self.tables.push(data) 261 } 262 263 /// Find a presumed unique special-purpose function parameter value. 264 /// 265 /// Returns the value of the last `purpose` parameter, or `None` if no such parameter exists. 266 pub fn special_param(&self, purpose: ir::ArgumentPurpose) -> Option<ir::Value> { 267 let entry = self.layout.entry_block().expect("Function is empty"); 268 self.signature 269 .special_param_index(purpose) 270 .map(|i| self.dfg.block_params(entry)[i]) 271 } 272 273 /// Starts collection of debug information. 274 pub fn collect_debug_info(&mut self) { 275 self.dfg.collect_debug_info(); 276 } 277 278 /// Rewrite the branch destination to `new_dest` if the destination matches `old_dest`. 279 /// Does nothing if called with a non-jump or non-branch instruction. 280 pub fn rewrite_branch_destination(&mut self, inst: Inst, old_dest: Block, new_dest: Block) { 281 for dest in self.dfg.insts[inst].branch_destination_mut(&mut self.dfg.jump_tables) { 282 if dest.block(&self.dfg.value_lists) == old_dest { 283 dest.set_block(new_dest, &mut self.dfg.value_lists) 284 } 285 } 286 } 287 288 /// Checks that the specified block can be encoded as a basic block. 289 /// 290 /// On error, returns the first invalid instruction and an error message. 291 pub fn is_block_basic(&self, block: Block) -> Result<(), (Inst, &'static str)> { 292 let dfg = &self.dfg; 293 let inst_iter = self.layout.block_insts(block); 294 295 // Ignore all instructions prior to the first branch. 296 let mut inst_iter = inst_iter.skip_while(|&inst| !dfg.insts[inst].opcode().is_branch()); 297 298 // A conditional branch is permitted in a basic block only when followed 299 // by a terminal jump instruction. 300 if let Some(_branch) = inst_iter.next() { 301 if let Some(next) = inst_iter.next() { 302 match dfg.insts[next].opcode() { 303 Opcode::Jump => (), 304 _ => return Err((next, "post-branch instruction not jump")), 305 } 306 } 307 } 308 309 Ok(()) 310 } 311 312 /// Returns true if the function is function that doesn't call any other functions. This is not 313 /// to be confused with a "leaf function" in Windows terminology. 314 pub fn is_leaf(&self) -> bool { 315 // Conservative result: if there's at least one function signature referenced in this 316 // function, assume it is not a leaf. 317 self.dfg.signatures.is_empty() 318 } 319 320 /// Replace the `dst` instruction's data with the `src` instruction's data 321 /// and then remove `src`. 322 /// 323 /// `src` and its result values should not be used at all, as any uses would 324 /// be left dangling after calling this method. 325 /// 326 /// `src` and `dst` must have the same number of resulting values, and 327 /// `src`'s i^th value must have the same type as `dst`'s i^th value. 328 pub fn transplant_inst(&mut self, dst: Inst, src: Inst) { 329 debug_assert_eq!( 330 self.dfg.inst_results(dst).len(), 331 self.dfg.inst_results(src).len() 332 ); 333 debug_assert!(self 334 .dfg 335 .inst_results(dst) 336 .iter() 337 .zip(self.dfg.inst_results(src)) 338 .all(|(a, b)| self.dfg.value_type(*a) == self.dfg.value_type(*b))); 339 340 self.dfg.insts[dst] = self.dfg.insts[src]; 341 self.layout.remove_inst(src); 342 } 343 344 /// Size occupied by all stack slots associated with this function. 345 /// 346 /// Does not include any padding necessary due to offsets 347 pub fn fixed_stack_size(&self) -> u32 { 348 self.sized_stack_slots.values().map(|ss| ss.size).sum() 349 } 350 351 /// Returns the list of relative source locations for this function. 352 pub(crate) fn rel_srclocs(&self) -> &SecondaryMap<Inst, RelSourceLoc> { 353 &self.srclocs 354 } 355 } 356 357 /// Functions can be cloned, but it is not a very fast operation. 358 /// The clone will have all the same entity numbers as the original. 359 #[derive(Clone, PartialEq)] 360 #[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))] 361 pub struct Function { 362 /// Name of this function. 363 /// 364 /// Mostly used by `.clif` files, only there for debugging / naming purposes. 365 pub name: UserFuncName, 366 367 /// All the fields required for compiling a function, independently of details irrelevant to 368 /// compilation and that are stored in the `FunctionParameters` `params` field instead. 369 pub stencil: FunctionStencil, 370 371 /// All the parameters that can be applied onto the function stencil, that is, that don't 372 /// matter when caching compilation artifacts. 373 pub params: FunctionParameters, 374 } 375 376 impl core::ops::Deref for Function { 377 type Target = FunctionStencil; 378 379 fn deref(&self) -> &Self::Target { 380 &self.stencil 381 } 382 } 383 384 impl core::ops::DerefMut for Function { 385 fn deref_mut(&mut self) -> &mut Self::Target { 386 &mut self.stencil 387 } 388 } 389 390 impl Function { 391 /// Create a function with the given name and signature. 392 pub fn with_name_signature(name: UserFuncName, sig: Signature) -> Self { 393 Self { 394 name, 395 stencil: FunctionStencil { 396 version_marker: VersionMarker, 397 signature: sig, 398 sized_stack_slots: StackSlots::new(), 399 dynamic_stack_slots: DynamicStackSlots::new(), 400 global_values: PrimaryMap::new(), 401 tables: PrimaryMap::new(), 402 dfg: DataFlowGraph::new(), 403 layout: Layout::new(), 404 srclocs: SecondaryMap::new(), 405 stack_limit: None, 406 }, 407 params: FunctionParameters::new(), 408 } 409 } 410 411 /// Clear all data structures in this function. 412 pub fn clear(&mut self) { 413 self.stencil.clear(); 414 self.params.clear(); 415 self.name = UserFuncName::default(); 416 } 417 418 /// Create a new empty, anonymous function with a Fast calling convention. 419 pub fn new() -> Self { 420 Self::with_name_signature(Default::default(), Signature::new(CallConv::Fast)) 421 } 422 423 /// Return an object that can display this function with correct ISA-specific annotations. 424 pub fn display(&self) -> DisplayFunction<'_> { 425 DisplayFunction(self) 426 } 427 428 /// Sets an absolute source location for the given instruction. 429 /// 430 /// If no base source location has been set yet, records it at the same time. 431 pub fn set_srcloc(&mut self, inst: Inst, srcloc: SourceLoc) { 432 let base = self.params.ensure_base_srcloc(srcloc); 433 self.stencil.srclocs[inst] = RelSourceLoc::from_base_offset(base, srcloc); 434 } 435 436 /// Returns an absolute source location for the given instruction. 437 pub fn srcloc(&self, inst: Inst) -> SourceLoc { 438 let base = self.params.base_srcloc(); 439 self.stencil.srclocs[inst].expand(base) 440 } 441 442 /// Declare a user-defined external function import, to be referenced in `ExtFuncData::User` later. 443 pub fn declare_imported_user_function( 444 &mut self, 445 name: UserExternalName, 446 ) -> UserExternalNameRef { 447 self.params.ensure_user_func_name(name) 448 } 449 450 /// Declare an external function import. 451 pub fn import_function(&mut self, data: ExtFuncData) -> FuncRef { 452 self.stencil.dfg.ext_funcs.push(data) 453 } 454 } 455 456 /// Wrapper type capable of displaying a `Function`. 457 pub struct DisplayFunction<'a>(&'a Function); 458 459 impl<'a> fmt::Display for DisplayFunction<'a> { 460 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { 461 write_function(fmt, self.0) 462 } 463 } 464 465 impl fmt::Display for Function { 466 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { 467 write_function(fmt, self) 468 } 469 } 470 471 impl fmt::Debug for Function { 472 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { 473 write_function(fmt, self) 474 } 475 } 476