cranelift_codegen/machinst/mod.rs
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
47use crate::binemit::{Addend, CodeInfo, CodeOffset, Reloc};
48use crate::ir::{
49 self, DynamicStackSlot, Endianness, RelSourceLoc, StackSlot, TrapCode, Type,
50 function::FunctionParameters,
51};
52use crate::isa::FunctionAlignment;
53use crate::result::CodegenResult;
54use crate::settings;
55use crate::value_label::ValueLabelsRanges;
56use alloc::string::String;
57use alloc::vec::Vec;
58use core::fmt;
59use core::fmt::Debug;
60use core::num::NonZeroU8;
61use cranelift_control::ControlPlane;
62use cranelift_entity::PrimaryMap;
63use regalloc2::VReg;
64use smallvec::{SmallVec, smallvec};
65
66#[cfg(feature = "enable-serde")]
67use serde_derive::{Deserialize, Serialize};
68
69/// Guaranteed to use "natural alignment" for the given type.
70const BIT_ALIGNED: u16 = 1 << 0;
71
72/// A load that reads data in memory that does not change for the
73/// duration of the function's execution.
74const BIT_READONLY: u16 = 1 << 1;
75
76/// Load multi-byte values from memory in a little-endian format.
77const BIT_LITTLE_ENDIAN: u16 = 1 << 2;
78
79/// Load multi-byte values from memory in a big-endian format.
80const BIT_BIG_ENDIAN: u16 = 1 << 3;
81
82/// Trap code, if any, for this memory operation.
83const MASK_TRAP_CODE: u16 = ((1 << TRAP_CODE_BITS) - 1) << TRAP_CODE_OFFSET;
84const TRAP_CODE_BITS: u16 = 8;
85const TRAP_CODE_OFFSET: u16 = 7;
86
87/// Whether this memory operation may be freely moved by the optimizer.
88const BIT_CAN_MOVE: u16 = 1 << 15;
89
90/// Backend memory-operation flags.
91///
92/// These are the bit-packed flags that backends operate on directly.
93///
94/// Unlike [`ir::MemFlagsData`], this does not carry alias-region metadata.
95#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)]
96#[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))]
97pub struct MachMemFlags {
98 // Bit layout:
99 //
100 // - Bit 0: aligned
101 // - Bit 1: readonly
102 // - Bit 2: little-endian
103 // - Bit 3: big-endian
104 // - Bits 4..6: unused
105 // - Bits 7..14: trap code
106 // - Bit 15: can_move
107 bits: u16,
108}
109
110impl MachMemFlags {
111 /// Create a new empty set of flags.
112 pub const fn new() -> Self {
113 Self { bits: 0 }.with_trap_code(Some(TrapCode::HEAP_OUT_OF_BOUNDS))
114 }
115
116 /// Create a set of flags representing an access from a "trusted" address.
117 pub const fn trusted() -> Self {
118 Self::new().with_notrap().with_aligned()
119 }
120
121 const fn read_bit(self, bit: u16) -> bool {
122 self.bits & bit != 0
123 }
124
125 const fn with_bit(mut self, bit: u16) -> Self {
126 self.bits |= bit;
127 self
128 }
129
130 /// Return endianness of the memory access.
131 pub const fn endianness(self, native_endianness: Endianness) -> Endianness {
132 if self.read_bit(BIT_LITTLE_ENDIAN) {
133 Endianness::Little
134 } else if self.read_bit(BIT_BIG_ENDIAN) {
135 Endianness::Big
136 } else {
137 native_endianness
138 }
139 }
140
141 /// Return endianness of the memory access, if explicitly specified.
142 pub const fn explicit_endianness(self) -> Option<Endianness> {
143 if self.read_bit(BIT_LITTLE_ENDIAN) {
144 Some(Endianness::Little)
145 } else if self.read_bit(BIT_BIG_ENDIAN) {
146 Some(Endianness::Big)
147 } else {
148 None
149 }
150 }
151
152 /// Set endianness of the memory access, returning new flags.
153 pub const fn with_endianness(self, endianness: Endianness) -> Self {
154 let res = match endianness {
155 Endianness::Little => self.with_bit(BIT_LITTLE_ENDIAN),
156 Endianness::Big => self.with_bit(BIT_BIG_ENDIAN),
157 };
158 assert!(!(res.read_bit(BIT_LITTLE_ENDIAN) && res.read_bit(BIT_BIG_ENDIAN)));
159 res
160 }
161
162 /// Test if this memory access cannot trap.
163 pub const fn notrap(self) -> bool {
164 self.trap_code().is_none()
165 }
166
167 /// Set these flags to indicate this access does not trap.
168 pub const fn with_notrap(self) -> Self {
169 self.with_trap_code(None)
170 }
171
172 /// Test if the `can_move` flag is set.
173 pub const fn can_move(self) -> bool {
174 self.read_bit(BIT_CAN_MOVE)
175 }
176
177 /// Set the `can_move` flag, returning new flags.
178 pub const fn with_can_move(self) -> Self {
179 self.with_bit(BIT_CAN_MOVE)
180 }
181
182 /// Test if the `aligned` flag is set.
183 pub const fn aligned(self) -> bool {
184 self.read_bit(BIT_ALIGNED)
185 }
186
187 /// Set the `aligned` flag, returning new flags.
188 pub const fn with_aligned(self) -> Self {
189 self.with_bit(BIT_ALIGNED)
190 }
191
192 /// Test if the `readonly` flag is set.
193 pub const fn readonly(self) -> bool {
194 self.read_bit(BIT_READONLY)
195 }
196
197 /// Set the `readonly` flag, returning new flags.
198 pub const fn with_readonly(self) -> Self {
199 self.with_bit(BIT_READONLY)
200 }
201
202 /// Get the trap code to report if this memory access traps.
203 pub const fn trap_code(self) -> Option<TrapCode> {
204 let byte = ((self.bits & MASK_TRAP_CODE) >> TRAP_CODE_OFFSET) as u8;
205 match NonZeroU8::new(byte) {
206 Some(code) => Some(TrapCode::from_raw(code)),
207 None => None,
208 }
209 }
210
211 /// Configures these flags with the specified trap code `code`.
212 pub const fn with_trap_code(mut self, code: Option<TrapCode>) -> Self {
213 let bits = match code {
214 Some(code) => code.as_raw().get() as u16,
215 None => 0,
216 };
217 self.bits &= !MASK_TRAP_CODE;
218 self.bits |= bits << TRAP_CODE_OFFSET;
219 self
220 }
221}
222
223impl fmt::Display for MachMemFlags {
224 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
225 match self.trap_code() {
226 None => write!(f, " notrap")?,
227 Some(TrapCode::HEAP_OUT_OF_BOUNDS) => {}
228 Some(t) => write!(f, " {t}")?,
229 }
230 if self.aligned() {
231 write!(f, " aligned")?;
232 }
233 if self.readonly() {
234 write!(f, " readonly")?;
235 }
236 if self.can_move() {
237 write!(f, " can_move")?;
238 }
239 if self.read_bit(BIT_BIG_ENDIAN) {
240 write!(f, " big")?;
241 }
242 if self.read_bit(BIT_LITTLE_ENDIAN) {
243 write!(f, " little")?;
244 }
245 Ok(())
246 }
247}
248
249#[macro_use]
250pub mod isle;
251
252pub mod lower;
253pub use lower::*;
254pub mod vcode;
255pub use vcode::*;
256pub mod compile;
257pub use compile::*;
258pub mod blockorder;
259pub use blockorder::*;
260pub mod abi;
261pub use abi::*;
262pub mod buffer;
263pub use buffer::*;
264pub mod helpers;
265pub use helpers::*;
266pub mod valueregs;
267pub use reg::*;
268pub use valueregs::*;
269pub mod reg;
270
271/// A machine instruction.
272pub trait MachInst: Clone + Debug {
273 /// The ABI machine spec for this `MachInst`.
274 type ABIMachineSpec: ABIMachineSpec<I = Self>;
275
276 /// Return the registers referenced by this machine instruction along with
277 /// the modes of reference (use, def, modify).
278 fn get_operands(&mut self, collector: &mut impl OperandVisitor);
279
280 /// If this is a simple move, return the (source, destination) tuple of registers.
281 fn is_move(&self) -> Option<(Writable<Reg>, Reg)>;
282
283 /// Is this a terminator (branch or ret)? If so, return its type
284 /// (ret/uncond/cond) and target if applicable.
285 fn is_term(&self) -> MachTerminator;
286
287 /// Is this an unconditional trap?
288 fn is_trap(&self) -> bool;
289
290 /// Is this an "args" pseudoinst?
291 fn is_args(&self) -> bool;
292
293 /// Classify the type of call instruction this is.
294 ///
295 /// This enables more granular function type analysis and optimization.
296 /// Returns `CallType::None` for non-call instructions, `CallType::Regular`
297 /// for normal calls that return to the caller, and `CallType::TailCall`
298 /// for tail calls that don't return to the caller.
299 fn call_type(&self) -> CallType;
300
301 /// Should this instruction's clobber-list be included in the
302 /// clobber-set?
303 fn is_included_in_clobbers(&self) -> bool;
304
305 /// Does this instruction access memory?
306 fn is_mem_access(&self) -> bool;
307
308 /// Generate a move.
309 fn gen_move(to_reg: Writable<Reg>, from_reg: Reg, ty: Type) -> Self;
310
311 /// Generate a dummy instruction that will keep a value alive but
312 /// has no other purpose.
313 fn gen_dummy_use(reg: Reg) -> Self;
314
315 /// Determine register class(es) to store the given Cranelift type, and the
316 /// Cranelift type actually stored in the underlying register(s). May return
317 /// an error if the type isn't supported by this backend.
318 ///
319 /// If the type requires multiple registers, then the list of registers is
320 /// returned in little-endian order.
321 ///
322 /// Note that the type actually stored in the register(s) may differ in the
323 /// case that a value is split across registers: for example, on a 32-bit
324 /// target, an I64 may be stored in two registers, each of which holds an
325 /// I32. The actually-stored types are used only to inform the backend when
326 /// generating spills and reloads for individual registers.
327 fn rc_for_type(ty: Type) -> CodegenResult<(&'static [RegClass], &'static [Type])>;
328
329 /// Get an appropriate type that can fully hold a value in a given
330 /// register class. This may not be the only type that maps to
331 /// that class, but when used with `gen_move()` or the ABI trait's
332 /// load/spill constructors, it should produce instruction(s) that
333 /// move the entire register contents.
334 fn canonical_type_for_rc(rc: RegClass) -> Type;
335
336 /// Generate a jump to another target. Used during lowering of
337 /// control flow.
338 fn gen_jump(target: MachLabel) -> Self;
339
340 /// Generate a store of an immediate 64-bit integer to a register. Used by
341 /// the control plane to generate random instructions.
342 fn gen_imm_u64(_value: u64, _dst: Writable<Reg>) -> Option<Self> {
343 None
344 }
345
346 /// Generate a store of an immediate 64-bit integer to a register. Used by
347 /// the control plane to generate random instructions. The tmp register may
348 /// be used by architectures which don't support writing immediate values to
349 /// floating point registers directly.
350 fn gen_imm_f64(_value: f64, _tmp: Writable<Reg>, _dst: Writable<Reg>) -> SmallVec<[Self; 2]> {
351 SmallVec::new()
352 }
353
354 /// Generate a NOP. The `preferred_size` parameter allows the caller to
355 /// request a NOP of that size, or as close to it as possible. The machine
356 /// backend may return a NOP whose binary encoding is smaller than the
357 /// preferred size, but must not return a NOP that is larger. However,
358 /// the instruction must have a nonzero size if preferred_size is nonzero.
359 fn gen_nop(preferred_size: usize) -> Self;
360
361 /// The various kinds of NOP, with size, sorted in ascending-size
362 /// order.
363 fn gen_nop_units() -> Vec<Vec<u8>>;
364
365 /// Align a basic block offset (from start of function). By default, no
366 /// alignment occurs.
367 fn align_basic_block(offset: CodeOffset) -> CodeOffset {
368 offset
369 }
370
371 /// What is the worst-case instruction size emitted by this instruction type?
372 fn worst_case_size() -> CodeOffset;
373
374 /// Worst-case growth, in bytes, that emitting a single `MachInst`
375 /// instruction may add to the `MachBuffer`'s pending-island state
376 /// (constants, deferred traps, and worst-case veneers for new
377 /// fixups).
378 ///
379 /// `MachBuffer` treats one instruction emission as the atomic
380 /// "commit unit" and uses `worst_case_size() +
381 /// worst_case_island_growth()` as the per-instruction lookahead
382 /// bound when deciding whether to flush an island. Backends whose
383 /// label-use kinds always have wide enough range that islands are
384 /// never required may leave this at zero.
385 fn worst_case_island_growth() -> CodeOffset;
386
387 /// Is this a safepoint?
388 fn is_safepoint(&self) -> bool;
389
390 /// Generate an instruction that must appear at the beginning of a basic
391 /// block, if any. Note that the return value must not be subject to
392 /// register allocation.
393 fn gen_block_start(
394 _is_indirect_branch_target: bool,
395 _is_forward_edge_cfi_enabled: bool,
396 ) -> Option<Self> {
397 None
398 }
399
400 /// Returns a description of the alignment required for functions for this
401 /// architecture.
402 fn function_alignment() -> FunctionAlignment;
403
404 /// Is this a low-level, one-way branch, not meant for use in a
405 /// VCode body? These instructions are meant to be used only when
406 /// directly emitted, i.e. when `MachInst` is used as an assembler
407 /// library.
408 fn is_low_level_branch(&self) -> bool {
409 false
410 }
411
412 /// A label-use kind: a type that describes the types of label references that
413 /// can occur in an instruction.
414 type LabelUse: MachInstLabelUse;
415
416 /// Byte representation of a trap opcode which is inserted by `MachBuffer`
417 /// during its `defer_trap` method.
418 const TRAP_OPCODE: &'static [u8];
419}
420
421/// A descriptor of a label reference (use) in an instruction set.
422pub trait MachInstLabelUse: Clone + Copy + Debug + Eq {
423 /// Required alignment for any veneer. Usually the required instruction
424 /// alignment (e.g., 4 for a RISC with 32-bit instructions, or 1 for x86).
425 const ALIGN: CodeOffset;
426
427 /// What is the maximum PC-relative range (positive)? E.g., if `1024`, a
428 /// label-reference fixup at offset `x` is valid if the label resolves to `x
429 /// + 1024`.
430 fn max_pos_range(self) -> CodeOffset;
431 /// What is the maximum PC-relative range (negative)? This is the absolute
432 /// value; i.e., if `1024`, then a label-reference fixup at offset `x` is
433 /// valid if the label resolves to `x - 1024`.
434 fn max_neg_range(self) -> CodeOffset;
435 /// What is the size of code-buffer slice this label-use needs to patch in
436 /// the label's value?
437 fn patch_size(self) -> CodeOffset;
438 /// Perform a code-patch, given the offset into the buffer of this label use
439 /// and the offset into the buffer of the label's definition.
440 /// It is guaranteed that, given `delta = offset - label_offset`, we will
441 /// have `offset >= -self.max_neg_range()` and `offset <=
442 /// self.max_pos_range()`.
443 fn patch(self, buffer: &mut [u8], use_offset: CodeOffset, label_offset: CodeOffset);
444 /// Can the label-use be patched to a veneer that supports a longer range?
445 /// Usually valid for jumps (a short-range jump can jump to a longer-range
446 /// jump), but not for e.g. constant pool references, because the constant
447 /// load would require different code (one more level of indirection).
448 fn supports_veneer(self) -> bool;
449 /// How many bytes are needed for a veneer?
450 fn veneer_size(self) -> CodeOffset;
451 /// What's the largest possible veneer that may be generated?
452 fn worst_case_veneer_size() -> CodeOffset;
453 /// Generate a veneer. The given code-buffer slice is `self.veneer_size()`
454 /// bytes long at offset `veneer_offset` in the buffer. The original
455 /// label-use will be patched to refer to this veneer's offset. A new
456 /// (offset, LabelUse) is returned that allows the veneer to use the actual
457 /// label. For veneers to work properly, it is expected that the new veneer
458 /// has a larger range; on most platforms this probably means either a
459 /// "long-range jump" (e.g., on ARM, the 26-bit form), or if already at that
460 /// stage, a jump that supports a full 32-bit range, for example.
461 fn generate_veneer(self, buffer: &mut [u8], veneer_offset: CodeOffset) -> (CodeOffset, Self);
462
463 /// Returns the corresponding label-use for the relocation specified.
464 ///
465 /// This returns `None` if the relocation doesn't have a corresponding
466 /// representation for the target architecture.
467 fn from_reloc(reloc: Reloc, addend: Addend) -> Option<Self>;
468}
469
470/// Classification of call instruction types for granular analysis.
471#[derive(Clone, Copy, Debug, PartialEq, Eq)]
472pub enum CallType {
473 /// Not a call instruction.
474 None,
475 /// Regular call that returns to the caller.
476 Regular,
477 /// Tail call that doesn't return to the caller.
478 TailCall,
479}
480
481/// Function classification based on call patterns.
482///
483/// This enum classifies functions based on their calling behavior to enable
484/// targeted optimizations. Functions are categorized as:
485/// - `None`: No calls at all (can use simplified calling conventions)
486/// - `TailOnly`: Only tail calls (may skip frame setup in some cases)
487/// - `Regular`: Has regular calls (requires full calling convention support)
488#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
489pub enum FunctionCalls {
490 /// Function makes no calls at all.
491 #[default]
492 None,
493 /// Function only makes tail calls (no regular calls).
494 TailOnly,
495 /// Function makes at least one regular call (may also have tail calls).
496 Regular,
497}
498
499impl FunctionCalls {
500 /// Update the function classification based on a new call instruction.
501 ///
502 /// This method implements the merge logic for accumulating call patterns:
503 /// - Any regular call makes the function Regular
504 /// - Tail calls upgrade None to TailOnly
505 /// - Regular always stays Regular
506 pub fn update(&mut self, call_type: CallType) {
507 *self = match (*self, call_type) {
508 // No call instruction - state unchanged
509 (current, CallType::None) => current,
510 // Regular call always results in Regular classification
511 (_, CallType::Regular) => FunctionCalls::Regular,
512 // Tail call: None becomes TailOnly, others unchanged
513 (FunctionCalls::None, CallType::TailCall) => FunctionCalls::TailOnly,
514 (current, CallType::TailCall) => current,
515 };
516 }
517}
518
519/// Describes a block terminator (not call) in the VCode.
520///
521/// Actual targets are not included: the single-source-of-truth for
522/// those is the VCode itself, which holds, for each block, successors
523/// and outgoing branch args per successor.
524#[derive(Clone, Debug, PartialEq, Eq)]
525pub enum MachTerminator {
526 /// Not a terminator.
527 None,
528 /// A return instruction.
529 Ret,
530 /// A tail call.
531 RetCall,
532 /// A branch.
533 Branch,
534}
535
536/// A trait describing the ability to encode a MachInst into binary machine code.
537pub trait MachInstEmit: MachInst {
538 /// Persistent state carried across `emit` invocations.
539 type State: MachInstEmitState<Self>;
540
541 /// Constant information used in `emit` invocations.
542 type Info;
543
544 /// Emit the instruction.
545 fn emit(&self, code: &mut MachBuffer<Self>, info: &Self::Info, state: &mut Self::State);
546
547 /// Pretty-print the instruction.
548 fn pretty_print_inst(&self, state: &mut Self::State) -> String;
549}
550
551/// A trait describing the emission state carried between MachInsts when
552/// emitting a function body.
553pub trait MachInstEmitState<I: VCodeInst>: Default + Clone + Debug {
554 /// Create a new emission state given the ABI object.
555 fn new(abi: &Callee<I::ABIMachineSpec>, ctrl_plane: ControlPlane) -> Self;
556
557 /// Update the emission state before emitting an instruction that is a
558 /// safepoint.
559 fn pre_safepoint(&mut self, user_stack_map: Option<ir::UserStackMap>);
560
561 /// The emission state holds ownership of a control plane, so it doesn't
562 /// have to be passed around explicitly too much. `ctrl_plane_mut` may
563 /// be used if temporary access to the control plane is needed by some
564 /// other function that doesn't have access to the emission state.
565 fn ctrl_plane_mut(&mut self) -> &mut ControlPlane;
566
567 /// Used to continue using a control plane after the emission state is
568 /// not needed anymore.
569 fn take_ctrl_plane(self) -> ControlPlane;
570
571 /// A hook that triggers when first emitting a new block.
572 /// It is guaranteed to be called before any instructions are emitted.
573 fn on_new_block(&mut self) {}
574
575 /// The [`FrameLayout`] for the function currently being compiled.
576 fn frame_layout(&self) -> &FrameLayout;
577}
578
579/// The result of a `MachBackend::compile_function()` call. Contains machine
580/// code (as bytes) and a disassembly, if requested.
581#[derive(PartialEq, Debug, Clone)]
582#[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))]
583pub struct CompiledCodeBase<T: CompilePhase> {
584 /// Machine code.
585 pub buffer: MachBufferFinalized<T>,
586 /// Disassembly, if requested.
587 pub vcode: Option<String>,
588 /// Debug info: value labels to registers/stackslots at code offsets.
589 pub value_labels_ranges: ValueLabelsRanges,
590 /// Basic-block layout info: block start offsets.
591 ///
592 /// This info is generated only if the `machine_code_cfg_info`
593 /// flag is set.
594 pub bb_starts: Vec<CodeOffset>,
595 /// Basic-block layout info: block edges. Each edge is `(from,
596 /// to)`, where `from` and `to` are basic-block start offsets of
597 /// the respective blocks.
598 ///
599 /// This info is generated only if the `machine_code_cfg_info`
600 /// flag is set.
601 pub bb_edges: Vec<(CodeOffset, CodeOffset)>,
602}
603
604impl CompiledCodeStencil {
605 /// Apply function parameters to finalize a stencil into its final form.
606 pub fn apply_params(self, params: &FunctionParameters) -> CompiledCode {
607 CompiledCode {
608 buffer: self.buffer.apply_base_srcloc(params.base_srcloc()),
609 vcode: self.vcode,
610 value_labels_ranges: self.value_labels_ranges,
611 bb_starts: self.bb_starts,
612 bb_edges: self.bb_edges,
613 }
614 }
615}
616
617impl<T: CompilePhase> CompiledCodeBase<T> {
618 /// Get a `CodeInfo` describing section sizes from this compilation result.
619 pub fn code_info(&self) -> CodeInfo {
620 CodeInfo {
621 total_size: self.buffer.total_size(),
622 }
623 }
624
625 /// Returns a reference to the machine code generated for this function compilation.
626 pub fn code_buffer(&self) -> &[u8] {
627 self.buffer.data()
628 }
629
630 /// Get the disassembly of the buffer, using the given capstone context.
631 #[cfg(feature = "disas")]
632 pub fn disassemble(
633 &self,
634 params: Option<&crate::ir::function::FunctionParameters>,
635 cs: &capstone::Capstone,
636 ) -> Result<String, anyhow::Error> {
637 use core::fmt::Write;
638
639 let mut buf = String::new();
640
641 let relocs = self.buffer.relocs();
642 let traps = self.buffer.traps();
643 let mut patchables = self.buffer.patchable_call_sites().peekable();
644
645 // Normalize the block starts to include an initial block of offset 0.
646 let mut block_starts = Vec::new();
647 if self.bb_starts.first().copied() != Some(0) {
648 block_starts.push(0);
649 }
650 block_starts.extend_from_slice(&self.bb_starts);
651 block_starts.push(self.buffer.data().len() as u32);
652
653 // Iterate over block regions, to ensure that we always produce block labels
654 for (n, (&start, &end)) in block_starts
655 .iter()
656 .zip(block_starts.iter().skip(1))
657 .enumerate()
658 {
659 writeln!(buf, "block{n}: ; offset 0x{start:x}")?;
660
661 let buffer = &self.buffer.data()[start as usize..end as usize];
662 let insns = cs.disasm_all(buffer, start as u64).map_err(map_caperr)?;
663 for i in insns.iter() {
664 write!(buf, " ")?;
665
666 let op_str = i.op_str().unwrap_or("");
667 if let Some(s) = i.mnemonic() {
668 write!(buf, "{s}")?;
669 if !op_str.is_empty() {
670 write!(buf, " ")?;
671 }
672 }
673
674 write!(buf, "{op_str}")?;
675
676 let end = i.address() + i.bytes().len() as u64;
677 let contains = |off| i.address() <= off && off < end;
678
679 for reloc in relocs.iter().filter(|reloc| contains(reloc.offset as u64)) {
680 write!(
681 buf,
682 " ; reloc_external {} {} {}",
683 reloc.kind,
684 reloc.target.display(params),
685 reloc.addend,
686 )?;
687 }
688
689 if let Some(trap) = traps.iter().find(|trap| contains(trap.offset as u64)) {
690 write!(buf, " ; trap: {}", trap.code)?;
691 }
692
693 if let Some(patchable) = patchables.peek()
694 && patchable.ret_addr == end as u32
695 {
696 write!(
697 buf,
698 " ; patchable call: NOP out last {} bytes",
699 patchable.len
700 )?;
701 patchables.next();
702 }
703
704 writeln!(buf)?;
705 }
706 }
707
708 return Ok(buf);
709
710 fn map_caperr(err: capstone::Error) -> anyhow::Error {
711 anyhow::format_err!("{err}")
712 }
713 }
714}
715
716/// Result of compiling a `FunctionStencil`, before applying `FunctionParameters` onto it.
717///
718/// Only used internally, in a transient manner, for the incremental compilation cache.
719pub type CompiledCodeStencil = CompiledCodeBase<Stencil>;
720
721/// `CompiledCode` in its final form (i.e. after `FunctionParameters` have been applied), ready for
722/// consumption.
723pub type CompiledCode = CompiledCodeBase<Final>;
724
725impl CompiledCode {
726 /// If available, return information about the code layout in the
727 /// final machine code: the offsets (in bytes) of each basic-block
728 /// start, and all basic-block edges.
729 pub fn get_code_bb_layout(&self) -> (Vec<usize>, Vec<(usize, usize)>) {
730 (
731 self.bb_starts.iter().map(|&off| off as usize).collect(),
732 self.bb_edges
733 .iter()
734 .map(|&(from, to)| (from as usize, to as usize))
735 .collect(),
736 )
737 }
738
739 /// Creates unwind information for the function.
740 ///
741 /// Returns `None` if the function has no unwind information.
742 #[cfg(feature = "unwind")]
743 pub fn create_unwind_info(
744 &self,
745 isa: &dyn crate::isa::TargetIsa,
746 ) -> CodegenResult<Option<crate::isa::unwind::UnwindInfo>> {
747 use crate::isa::unwind::UnwindInfoKind;
748 let unwind_info_kind = match isa.triple().operating_system {
749 target_lexicon::OperatingSystem::Windows => UnwindInfoKind::Windows,
750 _ => UnwindInfoKind::SystemV,
751 };
752 self.create_unwind_info_of_kind(isa, unwind_info_kind)
753 }
754
755 /// Creates unwind information for the function using the supplied
756 /// "kind". Supports cross-OS (but not cross-arch) generation.
757 ///
758 /// Returns `None` if the function has no unwind information.
759 #[cfg(feature = "unwind")]
760 pub fn create_unwind_info_of_kind(
761 &self,
762 isa: &dyn crate::isa::TargetIsa,
763 unwind_info_kind: crate::isa::unwind::UnwindInfoKind,
764 ) -> CodegenResult<Option<crate::isa::unwind::UnwindInfo>> {
765 isa.emit_unwind_info(self, unwind_info_kind)
766 }
767}
768
769/// An object that can be used to create the text section of an executable.
770///
771/// This primarily handles resolving relative relocations at
772/// text-section-assembly time rather than at load/link time. This
773/// architecture-specific logic is sort of like a linker, but only for one
774/// object file at a time.
775pub trait TextSectionBuilder {
776 /// Appends `data` to the text section with the `align` specified.
777 ///
778 /// If `labeled` is `true` then this also binds the appended data to the
779 /// `n`th label for how many times this has been called with `labeled:
780 /// true`. The label target can be passed as the `target` argument to
781 /// `resolve_reloc`.
782 ///
783 /// This function returns the offset at which the data was placed in the
784 /// text section.
785 fn append(
786 &mut self,
787 labeled: bool,
788 data: &[u8],
789 align: u32,
790 ctrl_plane: &mut ControlPlane,
791 ) -> u64;
792
793 /// Attempts to resolve a relocation for this function.
794 ///
795 /// The `offset` is the offset of the relocation, within the text section.
796 /// The `reloc` is the kind of relocation.
797 /// The `addend` is the value to add to the relocation.
798 /// The `target` is the labeled function that is the target of this
799 /// relocation.
800 ///
801 /// Labeled functions are created with the `append` function above by
802 /// setting the `labeled` parameter to `true`.
803 ///
804 /// If this builder does not know how to handle `reloc` then this function
805 /// will return `false`. Otherwise this function will return `true` and this
806 /// relocation will be resolved in the final bytes returned by `finish`.
807 fn resolve_reloc(&mut self, offset: u64, reloc: Reloc, addend: Addend, target: usize) -> bool;
808
809 /// A debug-only option which is used to for
810 fn force_veneers(&mut self);
811
812 /// Write the `data` provided at `offset`, for example when resolving a
813 /// relocation.
814 fn write(&mut self, offset: u64, data: &[u8]);
815
816 /// Completes this text section, filling out any final details, and returns
817 /// the bytes of the text section.
818 fn finish(&mut self, ctrl_plane: &mut ControlPlane) -> Vec<u8>;
819}