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 //!         |                        - nominal-SP-relative offsets resolved
43 //!         |                          by tracking EmitState.)
44 //!
45 //! ```
46 
47 use crate::binemit::{Addend, CodeInfo, CodeOffset, Reloc, StackMap};
48 use crate::ir::{SourceLoc, StackSlot, Type};
49 use crate::result::CodegenResult;
50 use crate::settings::Flags;
51 use crate::value_label::ValueLabelsRanges;
52 use alloc::boxed::Box;
53 use alloc::vec::Vec;
54 use core::fmt::Debug;
55 use cranelift_entity::PrimaryMap;
56 use regalloc2::{Allocation, VReg};
57 use smallvec::{smallvec, SmallVec};
58 use std::string::String;
59 
60 #[macro_use]
61 pub mod isle;
62 
63 pub mod lower;
64 pub use lower::*;
65 pub mod vcode;
66 pub use vcode::*;
67 pub mod compile;
68 pub use compile::*;
69 pub mod blockorder;
70 pub use blockorder::*;
71 pub mod abi;
72 pub use abi::*;
73 pub mod abi_impl;
74 pub use abi_impl::*;
75 pub mod buffer;
76 pub use buffer::*;
77 pub mod helpers;
78 pub use helpers::*;
79 pub mod inst_common;
80 pub use inst_common::*;
81 pub mod valueregs;
82 pub use reg::*;
83 pub use valueregs::*;
84 pub mod reg;
85 
86 /// A machine instruction.
87 pub trait MachInst: Clone + Debug {
88     /// Return the registers referenced by this machine instruction along with
89     /// the modes of reference (use, def, modify).
90     fn get_operands<F: Fn(VReg) -> VReg>(&self, collector: &mut OperandCollector<'_, F>);
91 
92     /// If this is a simple move, return the (source, destination) tuple of registers.
93     fn is_move(&self) -> Option<(Writable<Reg>, Reg)>;
94 
95     /// Is this a terminator (branch or ret)? If so, return its type
96     /// (ret/uncond/cond) and target if applicable.
97     fn is_term(&self) -> MachTerminator;
98 
99     /// Returns true if the instruction is an epilogue placeholder.
100     fn is_epilogue_placeholder(&self) -> bool;
101 
102     /// Should this instruction be included in the clobber-set?
103     fn is_included_in_clobbers(&self) -> bool {
104         true
105     }
106 
107     /// Generate a move.
108     fn gen_move(to_reg: Writable<Reg>, from_reg: Reg, ty: Type) -> Self;
109 
110     /// Generate a constant into a reg.
111     fn gen_constant<F: FnMut(Type) -> Writable<Reg>>(
112         to_regs: ValueRegs<Writable<Reg>>,
113         value: u128,
114         ty: Type,
115         alloc_tmp: F,
116     ) -> SmallVec<[Self; 4]>;
117 
118     /// Generate a dummy instruction that will keep a value alive but
119     /// has no other purpose.
120     fn gen_dummy_use(reg: Reg) -> Self;
121 
122     /// Determine register class(es) to store the given Cranelift type, and the
123     /// Cranelift type actually stored in the underlying register(s).  May return
124     /// an error if the type isn't supported by this backend.
125     ///
126     /// If the type requires multiple registers, then the list of registers is
127     /// returned in little-endian order.
128     ///
129     /// Note that the type actually stored in the register(s) may differ in the
130     /// case that a value is split across registers: for example, on a 32-bit
131     /// target, an I64 may be stored in two registers, each of which holds an
132     /// I32. The actually-stored types are used only to inform the backend when
133     /// generating spills and reloads for individual registers.
134     fn rc_for_type(ty: Type) -> CodegenResult<(&'static [RegClass], &'static [Type])>;
135 
136     /// Get an appropriate type that can fully hold a value in a given
137     /// register class. This may not be the only type that maps to
138     /// that class, but when used with `gen_move()` or the ABI trait's
139     /// load/spill constructors, it should produce instruction(s) that
140     /// move the entire register contents.
141     fn canonical_type_for_rc(rc: RegClass) -> Type;
142 
143     /// Generate a jump to another target. Used during lowering of
144     /// control flow.
145     fn gen_jump(target: MachLabel) -> Self;
146 
147     /// Generate a NOP. The `preferred_size` parameter allows the caller to
148     /// request a NOP of that size, or as close to it as possible. The machine
149     /// backend may return a NOP whose binary encoding is smaller than the
150     /// preferred size, but must not return a NOP that is larger. However,
151     /// the instruction must have a nonzero size if preferred_size is nonzero.
152     fn gen_nop(preferred_size: usize) -> Self;
153 
154     /// Align a basic block offset (from start of function).  By default, no
155     /// alignment occurs.
156     fn align_basic_block(offset: CodeOffset) -> CodeOffset {
157         offset
158     }
159 
160     /// What is the worst-case instruction size emitted by this instruction type?
161     fn worst_case_size() -> CodeOffset;
162 
163     /// What is the register class used for reference types (GC-observable pointers)? Can
164     /// be dependent on compilation flags.
165     fn ref_type_regclass(_flags: &Flags) -> RegClass;
166 
167     /// Is this a safepoint?
168     fn is_safepoint(&self) -> bool;
169 
170     /// A label-use kind: a type that describes the types of label references that
171     /// can occur in an instruction.
172     type LabelUse: MachInstLabelUse;
173 }
174 
175 /// A descriptor of a label reference (use) in an instruction set.
176 pub trait MachInstLabelUse: Clone + Copy + Debug + Eq {
177     /// Required alignment for any veneer. Usually the required instruction
178     /// alignment (e.g., 4 for a RISC with 32-bit instructions, or 1 for x86).
179     const ALIGN: CodeOffset;
180 
181     /// What is the maximum PC-relative range (positive)? E.g., if `1024`, a
182     /// label-reference fixup at offset `x` is valid if the label resolves to `x
183     /// + 1024`.
184     fn max_pos_range(self) -> CodeOffset;
185     /// What is the maximum PC-relative range (negative)? This is the absolute
186     /// value; i.e., if `1024`, then a label-reference fixup at offset `x` is
187     /// valid if the label resolves to `x - 1024`.
188     fn max_neg_range(self) -> CodeOffset;
189     /// What is the size of code-buffer slice this label-use needs to patch in
190     /// the label's value?
191     fn patch_size(self) -> CodeOffset;
192     /// Perform a code-patch, given the offset into the buffer of this label use
193     /// and the offset into the buffer of the label's definition.
194     /// It is guaranteed that, given `delta = offset - label_offset`, we will
195     /// have `offset >= -self.max_neg_range()` and `offset <=
196     /// self.max_pos_range()`.
197     fn patch(self, buffer: &mut [u8], use_offset: CodeOffset, label_offset: CodeOffset);
198     /// Can the label-use be patched to a veneer that supports a longer range?
199     /// Usually valid for jumps (a short-range jump can jump to a longer-range
200     /// jump), but not for e.g. constant pool references, because the constant
201     /// load would require different code (one more level of indirection).
202     fn supports_veneer(self) -> bool;
203     /// How many bytes are needed for a veneer?
204     fn veneer_size(self) -> CodeOffset;
205     /// Generate a veneer. The given code-buffer slice is `self.veneer_size()`
206     /// bytes long at offset `veneer_offset` in the buffer. The original
207     /// label-use will be patched to refer to this veneer's offset.  A new
208     /// (offset, LabelUse) is returned that allows the veneer to use the actual
209     /// label. For veneers to work properly, it is expected that the new veneer
210     /// has a larger range; on most platforms this probably means either a
211     /// "long-range jump" (e.g., on ARM, the 26-bit form), or if already at that
212     /// stage, a jump that supports a full 32-bit range, for example.
213     fn generate_veneer(self, buffer: &mut [u8], veneer_offset: CodeOffset) -> (CodeOffset, Self);
214 
215     /// Returns the corresponding label-use for the relocation specified.
216     ///
217     /// This returns `None` if the relocation doesn't have a corresponding
218     /// representation for the target architecture.
219     fn from_reloc(reloc: Reloc, addend: Addend) -> Option<Self>;
220 }
221 
222 /// Describes a block terminator (not call) in the vcode, when its branches
223 /// have not yet been finalized (so a branch may have two targets).
224 ///
225 /// Actual targets are not included: the single-source-of-truth for
226 /// those is the VCode itself, which holds, for each block, successors
227 /// and outgoing branch args per successor.
228 #[derive(Clone, Debug, PartialEq, Eq)]
229 pub enum MachTerminator {
230     /// Not a terminator.
231     None,
232     /// A return instruction.
233     Ret,
234     /// An unconditional branch to another block.
235     Uncond,
236     /// A conditional branch to one of two other blocks.
237     Cond,
238     /// An indirect branch with known possible targets.
239     Indirect,
240 }
241 
242 /// A trait describing the ability to encode a MachInst into binary machine code.
243 pub trait MachInstEmit: MachInst {
244     /// Persistent state carried across `emit` invocations.
245     type State: MachInstEmitState<Self>;
246     /// Constant information used in `emit` invocations.
247     type Info;
248     /// Emit the instruction.
249     fn emit(
250         &self,
251         allocs: &[Allocation],
252         code: &mut MachBuffer<Self>,
253         info: &Self::Info,
254         state: &mut Self::State,
255     );
256     /// Pretty-print the instruction.
257     fn pretty_print_inst(&self, allocs: &[Allocation], state: &mut Self::State) -> String;
258 }
259 
260 /// A trait describing the emission state carried between MachInsts when
261 /// emitting a function body.
262 pub trait MachInstEmitState<I: MachInst>: Default + Clone + Debug {
263     /// Create a new emission state given the ABI object.
264     fn new(abi: &dyn ABICallee<I = I>) -> Self;
265     /// Update the emission state before emitting an instruction that is a
266     /// safepoint.
267     fn pre_safepoint(&mut self, _stack_map: StackMap) {}
268     /// Update the emission state to indicate instructions are associated with a
269     /// particular SourceLoc.
270     fn pre_sourceloc(&mut self, _srcloc: SourceLoc) {}
271 }
272 
273 /// The result of a `MachBackend::compile_function()` call. Contains machine
274 /// code (as bytes) and a disassembly, if requested.
275 pub struct MachCompileResult {
276     /// Machine code.
277     pub buffer: MachBufferFinalized,
278     /// Size of stack frame, in bytes.
279     pub frame_size: u32,
280     /// Disassembly, if requested.
281     pub disasm: Option<String>,
282     /// Debug info: value labels to registers/stackslots at code offsets.
283     pub value_labels_ranges: ValueLabelsRanges,
284     /// Debug info: stackslots to stack pointer offsets.
285     pub stackslot_offsets: PrimaryMap<StackSlot, u32>,
286     /// Basic-block layout info: block start offsets.
287     ///
288     /// This info is generated only if the `machine_code_cfg_info`
289     /// flag is set.
290     pub bb_starts: Vec<CodeOffset>,
291     /// Basic-block layout info: block edges. Each edge is `(from,
292     /// to)`, where `from` and `to` are basic-block start offsets of
293     /// the respective blocks.
294     ///
295     /// This info is generated only if the `machine_code_cfg_info`
296     /// flag is set.
297     pub bb_edges: Vec<(CodeOffset, CodeOffset)>,
298 }
299 
300 impl MachCompileResult {
301     /// Get a `CodeInfo` describing section sizes from this compilation result.
302     pub fn code_info(&self) -> CodeInfo {
303         CodeInfo {
304             total_size: self.buffer.total_size(),
305         }
306     }
307 }
308 
309 /// An object that can be used to create the text section of an executable.
310 ///
311 /// This primarily handles resolving relative relocations at
312 /// text-section-assembly time rather than at load/link time. This
313 /// architecture-specific logic is sort of like a linker, but only for one
314 /// object file at a time.
315 pub trait TextSectionBuilder {
316     /// Appends `data` to the text section with the `align` specified.
317     ///
318     /// If `labeled` is `true` then the offset of the final data is used to
319     /// resolve relocations in `resolve_reloc` in the future.
320     ///
321     /// This function returns the offset at which the data was placed in the
322     /// text section.
323     fn append(&mut self, labeled: bool, data: &[u8], align: Option<u32>) -> u64;
324 
325     /// Attempts to resolve a relocation for this function.
326     ///
327     /// The `offset` is the offset of the relocation, within the text section.
328     /// The `reloc` is the kind of relocation.
329     /// The `addend` is the value to add to the relocation.
330     /// The `target` is the labeled function that is the target of this
331     /// relocation.
332     ///
333     /// Labeled functions are created with the `append` function above by
334     /// setting the `labeled` parameter to `true`.
335     ///
336     /// If this builder does not know how to handle `reloc` then this function
337     /// will return `false`. Otherwise this function will return `true` and this
338     /// relocation will be resolved in the final bytes returned by `finish`.
339     fn resolve_reloc(&mut self, offset: u64, reloc: Reloc, addend: Addend, target: u32) -> bool;
340 
341     /// A debug-only option which is used to for
342     fn force_veneers(&mut self);
343 
344     /// Completes this text section, filling out any final details, and returns
345     /// the bytes of the text section.
346     fn finish(&mut self) -> Vec<u8>;
347 }
348 
349 /// Expected unwind info type.
350 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
351 #[non_exhaustive]
352 pub enum UnwindInfoKind {
353     /// No unwind info.
354     None,
355     /// SystemV CIE/FDE unwind info.
356     #[cfg(feature = "unwind")]
357     SystemV,
358     /// Windows X64 Unwind info
359     #[cfg(feature = "unwind")]
360     Windows,
361 }
362