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 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(&mut self, user_stack_map: Option<ir::UserStackMap>);
308 
309     /// The emission state holds ownership of a control plane, so it doesn't
310     /// have to be passed around explicitly too much. `ctrl_plane_mut` may
311     /// be used if temporary access to the control plane is needed by some
312     /// other function that doesn't have access to the emission state.
313     fn ctrl_plane_mut(&mut self) -> &mut ControlPlane;
314 
315     /// Used to continue using a control plane after the emission state is
316     /// not needed anymore.
317     fn take_ctrl_plane(self) -> ControlPlane;
318 
319     /// A hook that triggers when first emitting a new block.
320     /// It is guaranteed to be called before any instructions are emitted.
321     fn on_new_block(&mut self) {}
322 
323     /// The [`FrameLayout`] for the function currently being compiled.
324     fn frame_layout(&self) -> &FrameLayout;
325 }
326 
327 /// The result of a `MachBackend::compile_function()` call. Contains machine
328 /// code (as bytes) and a disassembly, if requested.
329 #[derive(PartialEq, Debug, Clone)]
330 #[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))]
331 pub struct CompiledCodeBase<T: CompilePhase> {
332     /// Machine code.
333     pub buffer: MachBufferFinalized<T>,
334     /// Size of stack frame, in bytes.
335     pub frame_size: u32,
336     /// Disassembly, if requested.
337     pub vcode: Option<String>,
338     /// Debug info: value labels to registers/stackslots at code offsets.
339     pub value_labels_ranges: ValueLabelsRanges,
340     /// Debug info: stackslots to stack pointer offsets.
341     pub sized_stackslot_offsets: PrimaryMap<StackSlot, u32>,
342     /// Debug info: stackslots to stack pointer offsets.
343     pub dynamic_stackslot_offsets: PrimaryMap<DynamicStackSlot, u32>,
344     /// Basic-block layout info: block start offsets.
345     ///
346     /// This info is generated only if the `machine_code_cfg_info`
347     /// flag is set.
348     pub bb_starts: Vec<CodeOffset>,
349     /// Basic-block layout info: block edges. Each edge is `(from,
350     /// to)`, where `from` and `to` are basic-block start offsets of
351     /// the respective blocks.
352     ///
353     /// This info is generated only if the `machine_code_cfg_info`
354     /// flag is set.
355     pub bb_edges: Vec<(CodeOffset, CodeOffset)>,
356 }
357 
358 impl CompiledCodeStencil {
359     /// Apply function parameters to finalize a stencil into its final form.
360     pub fn apply_params(self, params: &FunctionParameters) -> CompiledCode {
361         CompiledCode {
362             buffer: self.buffer.apply_base_srcloc(params.base_srcloc()),
363             frame_size: self.frame_size,
364             vcode: self.vcode,
365             value_labels_ranges: self.value_labels_ranges,
366             sized_stackslot_offsets: self.sized_stackslot_offsets,
367             dynamic_stackslot_offsets: self.dynamic_stackslot_offsets,
368             bb_starts: self.bb_starts,
369             bb_edges: self.bb_edges,
370         }
371     }
372 }
373 
374 impl<T: CompilePhase> CompiledCodeBase<T> {
375     /// Get a `CodeInfo` describing section sizes from this compilation result.
376     pub fn code_info(&self) -> CodeInfo {
377         CodeInfo {
378             total_size: self.buffer.total_size(),
379         }
380     }
381 
382     /// Returns a reference to the machine code generated for this function compilation.
383     pub fn code_buffer(&self) -> &[u8] {
384         self.buffer.data()
385     }
386 
387     /// Get the disassembly of the buffer, using the given capstone context.
388     #[cfg(feature = "disas")]
389     pub fn disassemble(
390         &self,
391         params: Option<&crate::ir::function::FunctionParameters>,
392         cs: &capstone::Capstone,
393     ) -> Result<String, anyhow::Error> {
394         use std::fmt::Write;
395 
396         let mut buf = String::new();
397 
398         let relocs = self.buffer.relocs();
399         let traps = self.buffer.traps();
400 
401         // Normalize the block starts to include an initial block of offset 0.
402         let mut block_starts = Vec::new();
403         if self.bb_starts.first().copied() != Some(0) {
404             block_starts.push(0);
405         }
406         block_starts.extend_from_slice(&self.bb_starts);
407         block_starts.push(self.buffer.data().len() as u32);
408 
409         // Iterate over block regions, to ensure that we always produce block labels
410         for (n, (&start, &end)) in block_starts
411             .iter()
412             .zip(block_starts.iter().skip(1))
413             .enumerate()
414         {
415             writeln!(buf, "block{n}: ; offset 0x{start:x}")?;
416 
417             let buffer = &self.buffer.data()[start as usize..end as usize];
418             let insns = cs.disasm_all(buffer, start as u64).map_err(map_caperr)?;
419             for i in insns.iter() {
420                 write!(buf, "  ")?;
421 
422                 let op_str = i.op_str().unwrap_or("");
423                 if let Some(s) = i.mnemonic() {
424                     write!(buf, "{s}")?;
425                     if !op_str.is_empty() {
426                         write!(buf, " ")?;
427                     }
428                 }
429 
430                 write!(buf, "{op_str}")?;
431 
432                 let end = i.address() + i.bytes().len() as u64;
433                 let contains = |off| i.address() <= off && off < end;
434 
435                 for reloc in relocs.iter().filter(|reloc| contains(reloc.offset as u64)) {
436                     write!(
437                         buf,
438                         " ; reloc_external {} {} {}",
439                         reloc.kind,
440                         reloc.target.display(params),
441                         reloc.addend,
442                     )?;
443                 }
444 
445                 if let Some(trap) = traps.iter().find(|trap| contains(trap.offset as u64)) {
446                     write!(buf, " ; trap: {}", trap.code)?;
447                 }
448 
449                 writeln!(buf)?;
450             }
451         }
452 
453         return Ok(buf);
454 
455         fn map_caperr(err: capstone::Error) -> anyhow::Error {
456             anyhow::format_err!("{}", err)
457         }
458     }
459 }
460 
461 /// Result of compiling a `FunctionStencil`, before applying `FunctionParameters` onto it.
462 ///
463 /// Only used internally, in a transient manner, for the incremental compilation cache.
464 pub type CompiledCodeStencil = CompiledCodeBase<Stencil>;
465 
466 /// `CompiledCode` in its final form (i.e. after `FunctionParameters` have been applied), ready for
467 /// consumption.
468 pub type CompiledCode = CompiledCodeBase<Final>;
469 
470 impl CompiledCode {
471     /// If available, return information about the code layout in the
472     /// final machine code: the offsets (in bytes) of each basic-block
473     /// start, and all basic-block edges.
474     pub fn get_code_bb_layout(&self) -> (Vec<usize>, Vec<(usize, usize)>) {
475         (
476             self.bb_starts.iter().map(|&off| off as usize).collect(),
477             self.bb_edges
478                 .iter()
479                 .map(|&(from, to)| (from as usize, to as usize))
480                 .collect(),
481         )
482     }
483 
484     /// Creates unwind information for the function.
485     ///
486     /// Returns `None` if the function has no unwind information.
487     #[cfg(feature = "unwind")]
488     pub fn create_unwind_info(
489         &self,
490         isa: &dyn crate::isa::TargetIsa,
491     ) -> CodegenResult<Option<crate::isa::unwind::UnwindInfo>> {
492         use crate::isa::unwind::UnwindInfoKind;
493         let unwind_info_kind = match isa.triple().operating_system {
494             target_lexicon::OperatingSystem::Windows => UnwindInfoKind::Windows,
495             _ => UnwindInfoKind::SystemV,
496         };
497         self.create_unwind_info_of_kind(isa, unwind_info_kind)
498     }
499 
500     /// Creates unwind information for the function using the supplied
501     /// "kind". Supports cross-OS (but not cross-arch) generation.
502     ///
503     /// Returns `None` if the function has no unwind information.
504     #[cfg(feature = "unwind")]
505     pub fn create_unwind_info_of_kind(
506         &self,
507         isa: &dyn crate::isa::TargetIsa,
508         unwind_info_kind: crate::isa::unwind::UnwindInfoKind,
509     ) -> CodegenResult<Option<crate::isa::unwind::UnwindInfo>> {
510         isa.emit_unwind_info(self, unwind_info_kind)
511     }
512 }
513 
514 /// An object that can be used to create the text section of an executable.
515 ///
516 /// This primarily handles resolving relative relocations at
517 /// text-section-assembly time rather than at load/link time. This
518 /// architecture-specific logic is sort of like a linker, but only for one
519 /// object file at a time.
520 pub trait TextSectionBuilder {
521     /// Appends `data` to the text section with the `align` specified.
522     ///
523     /// If `labeled` is `true` then this also binds the appended data to the
524     /// `n`th label for how many times this has been called with `labeled:
525     /// true`. The label target can be passed as the `target` argument to
526     /// `resolve_reloc`.
527     ///
528     /// This function returns the offset at which the data was placed in the
529     /// text section.
530     fn append(
531         &mut self,
532         labeled: bool,
533         data: &[u8],
534         align: u32,
535         ctrl_plane: &mut ControlPlane,
536     ) -> u64;
537 
538     /// Attempts to resolve a relocation for this function.
539     ///
540     /// The `offset` is the offset of the relocation, within the text section.
541     /// The `reloc` is the kind of relocation.
542     /// The `addend` is the value to add to the relocation.
543     /// The `target` is the labeled function that is the target of this
544     /// relocation.
545     ///
546     /// Labeled functions are created with the `append` function above by
547     /// setting the `labeled` parameter to `true`.
548     ///
549     /// If this builder does not know how to handle `reloc` then this function
550     /// will return `false`. Otherwise this function will return `true` and this
551     /// relocation will be resolved in the final bytes returned by `finish`.
552     fn resolve_reloc(&mut self, offset: u64, reloc: Reloc, addend: Addend, target: usize) -> bool;
553 
554     /// A debug-only option which is used to for
555     fn force_veneers(&mut self);
556 
557     /// Completes this text section, filling out any final details, and returns
558     /// the bytes of the text section.
559     fn finish(&mut self, ctrl_plane: &mut ControlPlane) -> Vec<u8>;
560 }
561