1 //! This module exposes the machine-specific backend definition pieces. 2 //! 3 //! The MachInst infrastructure is the compiler backend, from CLIF 4 //! (ir::Function) to machine code. The purpose of this infrastructure is, at a 5 //! high level, to do instruction selection/lowering (to machine instructions), 6 //! register allocation, and then perform all the fixups to branches, constant 7 //! data references, etc., needed to actually generate machine code. 8 //! 9 //! The container for machine instructions, at various stages of construction, 10 //! is the `VCode` struct. We refer to a sequence of machine instructions organized 11 //! into basic blocks as "vcode". This is short for "virtual-register code". 12 //! 13 //! The compilation pipeline, from an `ir::Function` (already optimized as much as 14 //! you like by machine-independent optimization passes) onward, is as follows. 15 //! 16 //! ```plain 17 //! 18 //! ir::Function (SSA IR, machine-independent opcodes) 19 //! | 20 //! | [lower] 21 //! | 22 //! VCode<arch_backend::Inst> (machine instructions: 23 //! | - mostly virtual registers. 24 //! | - cond branches in two-target form. 25 //! | - branch targets are block indices. 26 //! | - in-memory constants held by insns, 27 //! | with unknown offsets. 28 //! | - critical edges (actually all edges) 29 //! | are split.) 30 //! | 31 //! | [regalloc --> `regalloc2::Output`; VCode is unchanged] 32 //! | 33 //! | [binary emission via MachBuffer] 34 //! | 35 //! Vec<u8> (machine code: 36 //! | - two-dest branches resolved via 37 //! | streaming branch resolution/simplification. 38 //! | - regalloc `Allocation` results used directly 39 //! | by instruction emission code. 40 //! | - prologue and epilogue(s) built and emitted 41 //! | directly during emission. 42 //! | - SP-relative offsets resolved by tracking 43 //! | EmitState.) 44 //! 45 //! ``` 46 47 use crate::binemit::{Addend, CodeInfo, CodeOffset, Reloc, StackMap}; 48 use crate::ir::{ 49 self, function::FunctionParameters, DynamicStackSlot, RelSourceLoc, StackSlot, Type, 50 }; 51 use crate::isa::FunctionAlignment; 52 use crate::result::CodegenResult; 53 use crate::settings; 54 use crate::settings::Flags; 55 use crate::value_label::ValueLabelsRanges; 56 use alloc::vec::Vec; 57 use core::fmt::Debug; 58 use cranelift_control::ControlPlane; 59 use cranelift_entity::PrimaryMap; 60 use regalloc2::VReg; 61 use smallvec::{smallvec, SmallVec}; 62 use std::string::String; 63 64 #[cfg(feature = "enable-serde")] 65 use serde_derive::{Deserialize, Serialize}; 66 67 #[macro_use] 68 pub mod isle; 69 70 pub mod lower; 71 pub use lower::*; 72 pub mod vcode; 73 pub use vcode::*; 74 pub mod compile; 75 pub use compile::*; 76 pub mod blockorder; 77 pub use blockorder::*; 78 pub mod abi; 79 pub use abi::*; 80 pub mod buffer; 81 pub use buffer::*; 82 pub mod helpers; 83 pub use helpers::*; 84 pub mod inst_common; 85 #[allow(unused_imports)] // not used in all backends right now 86 pub use inst_common::*; 87 pub mod valueregs; 88 pub use reg::*; 89 pub use valueregs::*; 90 pub mod pcc; 91 pub mod reg; 92 93 /// A machine instruction. 94 pub trait MachInst: Clone + Debug { 95 /// The ABI machine spec for this `MachInst`. 96 type ABIMachineSpec: ABIMachineSpec<I = Self>; 97 98 /// Return the registers referenced by this machine instruction along with 99 /// the modes of reference (use, def, modify). 100 fn get_operands(&mut self, collector: &mut impl OperandVisitor); 101 102 /// If this is a simple move, return the (source, destination) tuple of registers. 103 fn is_move(&self) -> Option<(Writable<Reg>, Reg)>; 104 105 /// Is this a terminator (branch or ret)? If so, return its type 106 /// (ret/uncond/cond) and target if applicable. 107 fn is_term(&self) -> MachTerminator; 108 109 /// Is this an unconditional trap? 110 fn is_trap(&self) -> bool; 111 112 /// Is this an "args" pseudoinst? 113 fn is_args(&self) -> bool; 114 115 /// Should this instruction be included in the clobber-set? 116 fn is_included_in_clobbers(&self) -> bool; 117 118 /// Does this instruction access memory? 119 fn is_mem_access(&self) -> bool; 120 121 /// Generate a move. 122 fn gen_move(to_reg: Writable<Reg>, from_reg: Reg, ty: Type) -> Self; 123 124 /// Generate a dummy instruction that will keep a value alive but 125 /// has no other purpose. 126 fn gen_dummy_use(reg: Reg) -> Self; 127 128 /// Determine register class(es) to store the given Cranelift type, and the 129 /// Cranelift type actually stored in the underlying register(s). May return 130 /// an error if the type isn't supported by this backend. 131 /// 132 /// If the type requires multiple registers, then the list of registers is 133 /// returned in little-endian order. 134 /// 135 /// Note that the type actually stored in the register(s) may differ in the 136 /// case that a value is split across registers: for example, on a 32-bit 137 /// target, an I64 may be stored in two registers, each of which holds an 138 /// I32. The actually-stored types are used only to inform the backend when 139 /// generating spills and reloads for individual registers. 140 fn rc_for_type(ty: Type) -> CodegenResult<(&'static [RegClass], &'static [Type])>; 141 142 /// Get an appropriate type that can fully hold a value in a given 143 /// register class. This may not be the only type that maps to 144 /// that class, but when used with `gen_move()` or the ABI trait's 145 /// load/spill constructors, it should produce instruction(s) that 146 /// move the entire register contents. 147 fn canonical_type_for_rc(rc: RegClass) -> Type; 148 149 /// Generate a jump to another target. Used during lowering of 150 /// control flow. 151 fn gen_jump(target: MachLabel) -> Self; 152 153 /// Generate a store of an immediate 64-bit integer to a register. Used by 154 /// the control plane to generate random instructions. 155 fn gen_imm_u64(_value: u64, _dst: Writable<Reg>) -> Option<Self> { 156 None 157 } 158 159 /// Generate a store of an immediate 64-bit integer to a register. Used by 160 /// the control plane to generate random instructions. The tmp register may 161 /// be used by architectures which don't support writing immediate values to 162 /// floating point registers directly. 163 fn gen_imm_f64(_value: f64, _tmp: Writable<Reg>, _dst: Writable<Reg>) -> SmallVec<[Self; 2]> { 164 SmallVec::new() 165 } 166 167 /// Generate a NOP. The `preferred_size` parameter allows the caller to 168 /// request a NOP of that size, or as close to it as possible. The machine 169 /// backend may return a NOP whose binary encoding is smaller than the 170 /// preferred size, but must not return a NOP that is larger. However, 171 /// the instruction must have a nonzero size if preferred_size is nonzero. 172 fn gen_nop(preferred_size: usize) -> Self; 173 174 /// Align a basic block offset (from start of function). By default, no 175 /// alignment occurs. 176 fn align_basic_block(offset: CodeOffset) -> CodeOffset { 177 offset 178 } 179 180 /// What is the worst-case instruction size emitted by this instruction type? 181 fn worst_case_size() -> CodeOffset; 182 183 /// What is the register class used for reference types (GC-observable pointers)? Can 184 /// be dependent on compilation flags. 185 fn ref_type_regclass(_flags: &Flags) -> RegClass; 186 187 /// Is this a safepoint? 188 fn is_safepoint(&self) -> bool; 189 190 /// Generate an instruction that must appear at the beginning of a basic 191 /// block, if any. Note that the return value must not be subject to 192 /// register allocation. 193 fn gen_block_start( 194 _is_indirect_branch_target: bool, 195 _is_forward_edge_cfi_enabled: bool, 196 ) -> Option<Self> { 197 None 198 } 199 200 /// Returns a description of the alignment required for functions for this 201 /// architecture. 202 fn function_alignment() -> FunctionAlignment; 203 204 /// A label-use kind: a type that describes the types of label references that 205 /// can occur in an instruction. 206 type LabelUse: MachInstLabelUse; 207 208 /// Byte representation of a trap opcode which is inserted by `MachBuffer` 209 /// during its `defer_trap` method. 210 const TRAP_OPCODE: &'static [u8]; 211 } 212 213 /// A descriptor of a label reference (use) in an instruction set. 214 pub trait MachInstLabelUse: Clone + Copy + Debug + Eq { 215 /// Required alignment for any veneer. Usually the required instruction 216 /// alignment (e.g., 4 for a RISC with 32-bit instructions, or 1 for x86). 217 const ALIGN: CodeOffset; 218 219 /// What is the maximum PC-relative range (positive)? E.g., if `1024`, a 220 /// label-reference fixup at offset `x` is valid if the label resolves to `x 221 /// + 1024`. 222 fn max_pos_range(self) -> CodeOffset; 223 /// What is the maximum PC-relative range (negative)? This is the absolute 224 /// value; i.e., if `1024`, then a label-reference fixup at offset `x` is 225 /// valid if the label resolves to `x - 1024`. 226 fn max_neg_range(self) -> CodeOffset; 227 /// What is the size of code-buffer slice this label-use needs to patch in 228 /// the label's value? 229 fn patch_size(self) -> CodeOffset; 230 /// Perform a code-patch, given the offset into the buffer of this label use 231 /// and the offset into the buffer of the label's definition. 232 /// It is guaranteed that, given `delta = offset - label_offset`, we will 233 /// have `offset >= -self.max_neg_range()` and `offset <= 234 /// self.max_pos_range()`. 235 fn patch(self, buffer: &mut [u8], use_offset: CodeOffset, label_offset: CodeOffset); 236 /// Can the label-use be patched to a veneer that supports a longer range? 237 /// Usually valid for jumps (a short-range jump can jump to a longer-range 238 /// jump), but not for e.g. constant pool references, because the constant 239 /// load would require different code (one more level of indirection). 240 fn supports_veneer(self) -> bool; 241 /// How many bytes are needed for a veneer? 242 fn veneer_size(self) -> CodeOffset; 243 /// What's the largest possible veneer that may be generated? 244 fn worst_case_veneer_size() -> CodeOffset; 245 /// Generate a veneer. The given code-buffer slice is `self.veneer_size()` 246 /// bytes long at offset `veneer_offset` in the buffer. The original 247 /// label-use will be patched to refer to this veneer's offset. A new 248 /// (offset, LabelUse) is returned that allows the veneer to use the actual 249 /// label. For veneers to work properly, it is expected that the new veneer 250 /// has a larger range; on most platforms this probably means either a 251 /// "long-range jump" (e.g., on ARM, the 26-bit form), or if already at that 252 /// stage, a jump that supports a full 32-bit range, for example. 253 fn generate_veneer(self, buffer: &mut [u8], veneer_offset: CodeOffset) -> (CodeOffset, Self); 254 255 /// Returns the corresponding label-use for the relocation specified. 256 /// 257 /// This returns `None` if the relocation doesn't have a corresponding 258 /// representation for the target architecture. 259 fn from_reloc(reloc: Reloc, addend: Addend) -> Option<Self>; 260 } 261 262 /// Describes a block terminator (not call) in the vcode, when its branches 263 /// have not yet been finalized (so a branch may have two targets). 264 /// 265 /// Actual targets are not included: the single-source-of-truth for 266 /// those is the VCode itself, which holds, for each block, successors 267 /// and outgoing branch args per successor. 268 #[derive(Clone, Debug, PartialEq, Eq)] 269 pub enum MachTerminator { 270 /// Not a terminator. 271 None, 272 /// A return instruction. 273 Ret, 274 /// A tail call. 275 RetCall, 276 /// An unconditional branch to another block. 277 Uncond, 278 /// A conditional branch to one of two other blocks. 279 Cond, 280 /// An indirect branch with known possible targets. 281 Indirect, 282 } 283 284 /// A trait describing the ability to encode a MachInst into binary machine code. 285 pub trait MachInstEmit: MachInst { 286 /// Persistent state carried across `emit` invocations. 287 type State: MachInstEmitState<Self>; 288 289 /// Constant information used in `emit` invocations. 290 type Info; 291 292 /// Emit the instruction. 293 fn emit(&self, code: &mut MachBuffer<Self>, info: &Self::Info, state: &mut Self::State); 294 295 /// Pretty-print the instruction. 296 fn pretty_print_inst(&self, state: &mut Self::State) -> String; 297 } 298 299 /// A trait describing the emission state carried between MachInsts when 300 /// emitting a function body. 301 pub trait MachInstEmitState<I: VCodeInst>: Default + Clone + Debug { 302 /// Create a new emission state given the ABI object. 303 fn new(abi: &Callee<I::ABIMachineSpec>, ctrl_plane: ControlPlane) -> Self; 304 305 /// Update the emission state before emitting an instruction that is a 306 /// safepoint. 307 fn pre_safepoint( 308 &mut self, 309 stack_map: Option<StackMap>, 310 user_stack_map: Option<ir::UserStackMap>, 311 ); 312 313 /// The emission state holds ownership of a control plane, so it doesn't 314 /// have to be passed around explicitly too much. `ctrl_plane_mut` may 315 /// be used if temporary access to the control plane is needed by some 316 /// other function that doesn't have access to the emission state. 317 fn ctrl_plane_mut(&mut self) -> &mut ControlPlane; 318 319 /// Used to continue using a control plane after the emission state is 320 /// not needed anymore. 321 fn take_ctrl_plane(self) -> ControlPlane; 322 323 /// A hook that triggers when first emitting a new block. 324 /// It is guaranteed to be called before any instructions are emitted. 325 fn on_new_block(&mut self) {} 326 327 /// The [`FrameLayout`] for the function currently being compiled. 328 fn frame_layout(&self) -> &FrameLayout; 329 } 330 331 /// The result of a `MachBackend::compile_function()` call. Contains machine 332 /// code (as bytes) and a disassembly, if requested. 333 #[derive(PartialEq, Debug, Clone)] 334 #[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))] 335 pub struct CompiledCodeBase<T: CompilePhase> { 336 /// Machine code. 337 pub buffer: MachBufferFinalized<T>, 338 /// Size of stack frame, in bytes. 339 pub frame_size: u32, 340 /// Disassembly, if requested. 341 pub vcode: Option<String>, 342 /// Debug info: value labels to registers/stackslots at code offsets. 343 pub value_labels_ranges: ValueLabelsRanges, 344 /// Debug info: stackslots to stack pointer offsets. 345 pub sized_stackslot_offsets: PrimaryMap<StackSlot, u32>, 346 /// Debug info: stackslots to stack pointer offsets. 347 pub dynamic_stackslot_offsets: PrimaryMap<DynamicStackSlot, u32>, 348 /// Basic-block layout info: block start offsets. 349 /// 350 /// This info is generated only if the `machine_code_cfg_info` 351 /// flag is set. 352 pub bb_starts: Vec<CodeOffset>, 353 /// Basic-block layout info: block edges. Each edge is `(from, 354 /// to)`, where `from` and `to` are basic-block start offsets of 355 /// the respective blocks. 356 /// 357 /// This info is generated only if the `machine_code_cfg_info` 358 /// flag is set. 359 pub bb_edges: Vec<(CodeOffset, CodeOffset)>, 360 } 361 362 impl CompiledCodeStencil { 363 /// Apply function parameters to finalize a stencil into its final form. 364 pub fn apply_params(self, params: &FunctionParameters) -> CompiledCode { 365 CompiledCode { 366 buffer: self.buffer.apply_base_srcloc(params.base_srcloc()), 367 frame_size: self.frame_size, 368 vcode: self.vcode, 369 value_labels_ranges: self.value_labels_ranges, 370 sized_stackslot_offsets: self.sized_stackslot_offsets, 371 dynamic_stackslot_offsets: self.dynamic_stackslot_offsets, 372 bb_starts: self.bb_starts, 373 bb_edges: self.bb_edges, 374 } 375 } 376 } 377 378 impl<T: CompilePhase> CompiledCodeBase<T> { 379 /// Get a `CodeInfo` describing section sizes from this compilation result. 380 pub fn code_info(&self) -> CodeInfo { 381 CodeInfo { 382 total_size: self.buffer.total_size(), 383 } 384 } 385 386 /// Returns a reference to the machine code generated for this function compilation. 387 pub fn code_buffer(&self) -> &[u8] { 388 self.buffer.data() 389 } 390 391 /// Get the disassembly of the buffer, using the given capstone context. 392 #[cfg(feature = "disas")] 393 pub fn disassemble( 394 &self, 395 params: Option<&crate::ir::function::FunctionParameters>, 396 cs: &capstone::Capstone, 397 ) -> Result<String, anyhow::Error> { 398 use std::fmt::Write; 399 400 let mut buf = String::new(); 401 402 let relocs = self.buffer.relocs(); 403 let traps = self.buffer.traps(); 404 405 // Normalize the block starts to include an initial block of offset 0. 406 let mut block_starts = Vec::new(); 407 if self.bb_starts.first().copied() != Some(0) { 408 block_starts.push(0); 409 } 410 block_starts.extend_from_slice(&self.bb_starts); 411 block_starts.push(self.buffer.data().len() as u32); 412 413 // Iterate over block regions, to ensure that we always produce block labels 414 for (n, (&start, &end)) in block_starts 415 .iter() 416 .zip(block_starts.iter().skip(1)) 417 .enumerate() 418 { 419 writeln!(buf, "block{}: ; offset 0x{:x}", n, start)?; 420 421 let buffer = &self.buffer.data()[start as usize..end as usize]; 422 let insns = cs.disasm_all(buffer, start as u64).map_err(map_caperr)?; 423 for i in insns.iter() { 424 write!(buf, " ")?; 425 426 let op_str = i.op_str().unwrap_or(""); 427 if let Some(s) = i.mnemonic() { 428 write!(buf, "{}", s)?; 429 if !op_str.is_empty() { 430 write!(buf, " ")?; 431 } 432 } 433 434 write!(buf, "{}", op_str)?; 435 436 let end = i.address() + i.bytes().len() as u64; 437 let contains = |off| i.address() <= off && off < end; 438 439 for reloc in relocs.iter().filter(|reloc| contains(reloc.offset as u64)) { 440 write!( 441 buf, 442 " ; reloc_external {} {} {}", 443 reloc.kind, 444 reloc.target.display(params), 445 reloc.addend, 446 )?; 447 } 448 449 if let Some(trap) = traps.iter().find(|trap| contains(trap.offset as u64)) { 450 write!(buf, " ; trap: {}", trap.code)?; 451 } 452 453 writeln!(buf)?; 454 } 455 } 456 457 return Ok(buf); 458 459 fn map_caperr(err: capstone::Error) -> anyhow::Error { 460 anyhow::format_err!("{}", err) 461 } 462 } 463 } 464 465 /// Result of compiling a `FunctionStencil`, before applying `FunctionParameters` onto it. 466 /// 467 /// Only used internally, in a transient manner, for the incremental compilation cache. 468 pub type CompiledCodeStencil = CompiledCodeBase<Stencil>; 469 470 /// `CompiledCode` in its final form (i.e. after `FunctionParameters` have been applied), ready for 471 /// consumption. 472 pub type CompiledCode = CompiledCodeBase<Final>; 473 474 impl CompiledCode { 475 /// If available, return information about the code layout in the 476 /// final machine code: the offsets (in bytes) of each basic-block 477 /// start, and all basic-block edges. 478 pub fn get_code_bb_layout(&self) -> (Vec<usize>, Vec<(usize, usize)>) { 479 ( 480 self.bb_starts.iter().map(|&off| off as usize).collect(), 481 self.bb_edges 482 .iter() 483 .map(|&(from, to)| (from as usize, to as usize)) 484 .collect(), 485 ) 486 } 487 488 /// Creates unwind information for the function. 489 /// 490 /// Returns `None` if the function has no unwind information. 491 #[cfg(feature = "unwind")] 492 pub fn create_unwind_info( 493 &self, 494 isa: &dyn crate::isa::TargetIsa, 495 ) -> CodegenResult<Option<crate::isa::unwind::UnwindInfo>> { 496 use crate::isa::unwind::UnwindInfoKind; 497 let unwind_info_kind = match isa.triple().operating_system { 498 target_lexicon::OperatingSystem::Windows => UnwindInfoKind::Windows, 499 _ => UnwindInfoKind::SystemV, 500 }; 501 self.create_unwind_info_of_kind(isa, unwind_info_kind) 502 } 503 504 /// Creates unwind information for the function using the supplied 505 /// "kind". Supports cross-OS (but not cross-arch) generation. 506 /// 507 /// Returns `None` if the function has no unwind information. 508 #[cfg(feature = "unwind")] 509 pub fn create_unwind_info_of_kind( 510 &self, 511 isa: &dyn crate::isa::TargetIsa, 512 unwind_info_kind: crate::isa::unwind::UnwindInfoKind, 513 ) -> CodegenResult<Option<crate::isa::unwind::UnwindInfo>> { 514 isa.emit_unwind_info(self, unwind_info_kind) 515 } 516 } 517 518 /// An object that can be used to create the text section of an executable. 519 /// 520 /// This primarily handles resolving relative relocations at 521 /// text-section-assembly time rather than at load/link time. This 522 /// architecture-specific logic is sort of like a linker, but only for one 523 /// object file at a time. 524 pub trait TextSectionBuilder { 525 /// Appends `data` to the text section with the `align` specified. 526 /// 527 /// If `labeled` is `true` then this also binds the appended data to the 528 /// `n`th label for how many times this has been called with `labeled: 529 /// true`. The label target can be passed as the `target` argument to 530 /// `resolve_reloc`. 531 /// 532 /// This function returns the offset at which the data was placed in the 533 /// text section. 534 fn append( 535 &mut self, 536 labeled: bool, 537 data: &[u8], 538 align: u32, 539 ctrl_plane: &mut ControlPlane, 540 ) -> u64; 541 542 /// Attempts to resolve a relocation for this function. 543 /// 544 /// The `offset` is the offset of the relocation, within the text section. 545 /// The `reloc` is the kind of relocation. 546 /// The `addend` is the value to add to the relocation. 547 /// The `target` is the labeled function that is the target of this 548 /// relocation. 549 /// 550 /// Labeled functions are created with the `append` function above by 551 /// setting the `labeled` parameter to `true`. 552 /// 553 /// If this builder does not know how to handle `reloc` then this function 554 /// will return `false`. Otherwise this function will return `true` and this 555 /// relocation will be resolved in the final bytes returned by `finish`. 556 fn resolve_reloc(&mut self, offset: u64, reloc: Reloc, addend: Addend, target: usize) -> bool; 557 558 /// A debug-only option which is used to for 559 fn force_veneers(&mut self); 560 561 /// Completes this text section, filling out any final details, and returns 562 /// the bytes of the text section. 563 fn finish(&mut self, ctrl_plane: &mut ControlPlane) -> Vec<u8>; 564 } 565