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