Skip to main content

offlineasm_ir/
lib.rs

1//! Defines the target-independent IR for offlineasm mnemonics, shared by
2//! the `offlineasm` and `onlineasm` assemblers.
3//!
4//! This crate is the single place where mnemonic *algorithms* live. Both
5//! assemblers run the same front half:
6//!
7//! ```text
8//! spelling -`Mnemonic`-> `expand()` + `Op`s -> Vec<`Inst`> -backend-> machine code | asm text
9//! ```
10//!
11//! * [`Mnemonic`] names the *operation*, one variant per operation rather than
12//!   one per spelling: `addp`/`addq` are the same value, and `mnem` holds one
13//!   constant per accepted spelling. [`Mnemonic::from_str`] is the crate's
14//!   only string comparison, and each frontend calls it once per instruction.
15//! * [`expand()`] turns one [`Mnemonic`] plus its `Op`s into core [`Inst`]
16//!   nodes.
17//!   Multi-instruction sequences (`truncatef2q`'s bias path,
18//!   `cq2f`'s halving path, `bcd2i`, ...) are expanded here once, using only
19//!   core nodes plus internal labels, so every backend inherits them.
20//! * Backends implement the core [`Inst`] variants with their ISA. Adding a
21//!   new backend means implementing `Inst`, never re-deriving 400+
22//!   mnemonics. `onlineasm`'s backends (`x86`/`aarch64`/`riscv64`) emit
23//!   machine code; `offlineasm`'s backends emit assembly text.
24//!
25//! # Operand order
26//!
27//! Mnemonics read destination first: `move dst, src`, and `addq dst, lhs,
28//! rhs` means `dst = lhs + rhs`. Branches and tests have no destination, so
29//! they keep `lhs, rhs, lbl` / `value, lbl`. Sources keep their relative
30//! order after the destination.
31//!
32//! # Registers
33//!
34//! [`Gpr`]/[`Fpr`] hold architecture physical numbers (x86 `rax = 0`,
35//! aarch64 `x0 = 0`, riscv `x10 = 10`, ...). Name resolution (offlineasm vreg
36//! to number, including the per-arch default maps) lives in [`regs`], so both
37//! frontends share one vocabulary.
38//!
39//! # Labels and symbols
40//!
41//! [`Label`] and [`SymId`] are opaque handles: each frontend owns a table
42//! and interprets the index its own way (`onlineasm` holds asmkit label
43//! handles and `offlineasm` holds symbol text). The IR never names either.
44//!
45//! # Implicit pairs
46//!
47//! A few nodes name no explicit register for ISA-implicit operands and use
48//! the *accumulator convention* instead: the dividend/quotient lives in the
49//! `t0` role, the high half / CAS expected value in the `t2` role
50//! (x86 `rax`/`rdx`, aarch64 `x0`/`x2`, riscv `x10`/`x12`). Each backend maps
51//! the roles to its own registers. User code keeps `t0`/`t2` mapped at their
52//! ABI homes (as the default maps do).
53//!
54//! # Pending flags
55//!
56//! `*S` ALU nodes ([`Inst::AluS`]) and every compare/test leave *pending
57//! flags*. [`Inst::FlagBranch`] and [`Inst::Adc`]/[`Inst::Sbb`] consume
58//! them. Nodes from one mnemonic expansion run back-to-back, so the
59//! state is always well-defined there. Across mnemonics it matches existing
60//! usage (`bo`/`bs`/`bz`/`bnz` directly after a flag-setting op). RISC-V has
61//! no flags: its backend materializes the predicate into a reserved scratch
62//! register, which nothing else clobbers.
63
64/// Names a general-purpose register by its architecture physical number.
65#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
66pub struct Gpr(pub u8);
67
68/// Names a floating-point or vector register by its architecture physical number.
69#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
70pub struct Fpr(pub u8);
71
72/// Identifies a code label with a frontend-owned handle.
73///
74/// The frontend owns the meaning: `onlineasm` maps the index to an asmkit
75/// label handle, `offlineasm` to a symbol name. The same handle appears in
76/// operands ([`Op::Label`]) and at [`Inst::Bind`].
77#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
78pub struct Label(pub u32);
79
80/// Identifies a symbolic operand with a frontend-owned handle.
81///
82/// Only `offlineasm` produces these, for offsets it cannot fold to an
83/// integer at compile time: the frontend renders the index as the assembler
84/// template's `{IDENT}` placeholder. `onlineasm` has no symbolic operands
85/// and rejects them.
86#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
87pub struct SymId(pub u32);
88
89/// Identifies an external symbol with a frontend-owned handle.
90///
91/// `onlineasm` maps the index to an asmkit symbol (an `ExternalName`),
92/// `offlineasm` to the symbol's assembler text.
93#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
94pub struct ExternId(pub u32);
95
96/// Says how generated code reaches an external symbol.
97#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
98pub enum Reach {
99    /// A direct PC-relative reference. The symbol must be within the
100    /// instruction's range of the code.
101    Near,
102    /// Through a pointer-sized slot in an address table next to the code,
103    /// so the symbol can be anywhere.
104    Far,
105}
106
107/// Refers to an external symbol.
108#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
109pub struct Extern {
110    pub id: ExternId,
111    pub reach: Reach,
112}
113
114/// Refers to a code label. `Bound` comes from the frontend (a concrete
115/// handle). `Fresh` labels are created by [`expand()`] for internal
116/// sequences and are scoped to one expansion. Backends must resolve them
117/// per mnemonic lowering.
118#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
119pub enum Lbl {
120    Bound(Label),
121    Fresh(u32),
122}
123
124/// Holds a memory displacement: a folded constant or a frontend-owned symbol.
125#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
126pub enum Disp {
127    Const(i32),
128    /// Holds `{IDENT}` in the `offlineasm` text template. `onlineasm` and
129    /// RISC-style backends that must fold it reject this variant.
130    Sym(SymId),
131}
132
133impl Disp {
134    /// Returns the constant value, or `None` when symbolic.
135    pub const fn constant(self) -> Option<i32> {
136        match self {
137            Disp::Const(v) => Some(v),
138            Disp::Sym(_) => None,
139        }
140    }
141
142    /// Returns the constant value, treating a symbolic displacement as `0`.
143    ///
144    /// Machine-code backends call this only after rejecting `Disp::Sym`.
145    pub const fn const_or_zero(self) -> i32 {
146        match self {
147            Disp::Const(v) => v,
148            Disp::Sym(_) => 0,
149        }
150    }
151}
152
153/// Holds a resolved machine address: `disp(base, index, scale)`.
154/// Every backend lowers this. RISC backends synthesize the index/scale part
155/// with the expansion scratch registers.
156#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
157pub struct Mem {
158    /// Holds the base register. `None` selects the absolute (`[disp]`) form:
159    /// x86-64 encodes it directly, AArch64 and RISC-V 64 materialize the
160    /// address into a scratch register.
161    pub base: Option<Gpr>,
162    /// Holds the index register and scale, when present.
163    pub index: Option<(Gpr, u8)>,
164    /// Holds the displacement.
165    pub disp: Disp,
166}
167
168impl Mem {
169    /// Builds `[base + disp]`.
170    pub fn base(base: Gpr, disp: i32) -> Self {
171        Self {
172            base: Some(base),
173            index: None,
174            disp: Disp::Const(disp),
175        }
176    }
177
178    /// Builds `[disp]`, with no base register.
179    pub fn absolute(disp: Disp) -> Self {
180        Self {
181            base: None,
182            index: None,
183            disp,
184        }
185    }
186
187    /// Returns the base register, or register 0 for the absolute form.
188    ///
189    /// Backends check [`Mem::base`] for the absolute form first and only
190    /// call this on a based address.
191    pub fn base_reg(&self) -> Gpr {
192        self.base.unwrap_or(Gpr(0))
193    }
194}
195
196/// Holds one operand of a mnemonic invocation.
197#[derive(Clone, Copy, PartialEq, Eq, Debug)]
198pub enum Op {
199    Imm(i64),
200    Gpr(Gpr),
201    Fpr(Fpr),
202    Mem(Mem),
203    Label(Lbl),
204    Sym(SymId),
205    /// Only `call`, `jmp`, `move`, and the `lea` family accept it.
206    Extern(Extern),
207}
208
209impl Op {
210    /// Reports whether `self` is the immediate `0`.
211    pub fn is_zero_imm(&self) -> bool {
212        matches!(self, Op::Imm(0))
213    }
214}
215
216/// Names an integer operand width.
217#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
218pub enum Width {
219    B8,
220    B16,
221    B32,
222    B64,
223}
224
225impl Width {
226    /// Returns the width in bytes.
227    pub fn bytes(self) -> u32 {
228        match self {
229            Width::B8 => 1,
230            Width::B16 => 2,
231            Width::B32 => 4,
232            Width::B64 => 8,
233        }
234    }
235
236    /// Reports whether `v` fits in `self` as a signed value.
237    pub fn fits(self, v: i64) -> bool {
238        match self {
239            Width::B8 => v == (v as i8) as i64,
240            Width::B16 => v == (v as i16) as i64,
241            Width::B32 => v == (v as i32) as i64,
242            Width::B64 => true,
243        }
244    }
245}
246
247/// Names a scalar float kind.
248#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
249pub enum FKind {
250    F32,
251    F64,
252}
253
254/// Names an integer comparison condition.
255#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
256pub enum IntCc {
257    /// Equal.
258    Eq,
259    /// Not equal.
260    Ne,
261    /// Unsigned above (`>`, x86 `a`).
262    Hi,
263    /// Unsigned above-or-equal (`>=`, x86 `ae`).
264    Hs,
265    /// Unsigned below (`<`, x86 `b`).
266    Lo,
267    /// Unsigned below-or-equal (`<=`, x86 `be`).
268    Ls,
269    /// Signed greater-than.
270    Gt,
271    /// Signed greater-or-equal.
272    Ge,
273    /// Signed less-than.
274    Lt,
275    /// Signed less-or-equal.
276    Le,
277}
278
279/// Names a float comparison condition.
280#[allow(dead_code)]
281#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
282pub enum FCc {
283    /// Equal.
284    Eq,
285    /// Not equal.
286    Ne,
287    /// Greater than.
288    Gt,
289    /// Greater than or equal.
290    Ge,
291    /// Less than.
292    Lt,
293    /// Less than or equal.
294    Le,
295    /// Unordered-or-equal (x86 `je` after `ucomi*`).
296    EqUn,
297    /// Unordered-or-not-equal.
298    NeUn,
299    /// Unordered-or-greater.
300    GtUn,
301    /// Unordered-or-greater-or-equal.
302    GeUn,
303    /// Unordered-or-less.
304    LtUn,
305    /// Unordered-or-less-or-equal.
306    LeUn,
307}
308
309/// Names a pending-flag predicate.
310#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
311pub enum PredFlag {
312    /// Overflow (x86 `o`, ARM `vs`).
313    O,
314    /// Sign / minus (x86 `s`, ARM `mi`).
315    S,
316    /// Zero / equal (x86 `z`, ARM `eq`).
317    Z,
318    /// Not-zero (x86 `nz`, ARM `ne`).
319    Nz,
320}
321
322/// Names a value test.
323#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
324pub enum TestKind {
325    /// Sign bit set (`bts*`, `t*s`).
326    Sign,
327    /// Whole value zero (`bt*z`, `t*z`).
328    Zero,
329    /// Whole value nonzero (`bt*nz`, `t*nz`).
330    NonZero,
331}
332
333/// Names a shift or rotate operation.
334#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
335pub enum ShiftOp {
336    /// Shift left.
337    Shl,
338    /// Shift right, sign-extending.
339    ShrSar,
340    /// Shift right, zero-filling.
341    Shr,
342    /// Rotate left.
343    Rotl,
344    /// Rotate right.
345    Rotr,
346}
347
348/// Names a float rounding mode.
349#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
350pub enum RoundMode {
351    /// To nearest.
352    Nearest,
353    /// Toward negative infinity.
354    Down,
355    /// Toward positive infinity.
356    Up,
357    /// Toward zero.
358    Trunc,
359}
360
361/// Names a jump or call target.
362#[derive(Clone, PartialEq, Eq, Debug)]
363pub enum Target {
364    Label(Lbl),
365    Reg(Gpr),
366    Mem(Mem),
367    Abs(i64),
368    Extern(Extern),
369}
370
371/// Supplies the scratch registers an expansion may use.
372#[derive(Clone, Copy, Debug)]
373pub struct Scratch {
374    /// First scratch GPR.
375    pub gpr: Gpr,
376    /// Second scratch GPR.
377    pub gpr2: Gpr,
378    /// Scratch FPR.
379    pub fpr: Fpr,
380}
381
382/// Reports a mnemonic expansion failure.
383#[derive(Clone, Debug, PartialEq, Eq)]
384pub enum ExpandError {
385    /// Unknown mnemonic spelling.
386    UnknownMnemonic(String),
387    /// Wrong operand count or kind.
388    BadOperand { mnemonic: String, msg: String },
389    /// Patch requested on a non-patchable mnemonic.
390    NotPatchable(String),
391}
392
393impl ExpandError {
394    /// Replaces the mnemonic spelling carried by `self`.
395    pub fn renamed(self, spelling: &str) -> Self {
396        match self {
397            ExpandError::UnknownMnemonic(_) => ExpandError::UnknownMnemonic(spelling.to_string()),
398            ExpandError::BadOperand { msg, .. } => ExpandError::BadOperand {
399                mnemonic: spelling.to_string(),
400                msg,
401            },
402            ExpandError::NotPatchable(_) => ExpandError::NotPatchable(spelling.to_string()),
403        }
404    }
405}
406
407impl std::fmt::Display for ExpandError {
408    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
409        match self {
410            ExpandError::UnknownMnemonic(m) => write!(f, "unknown mnemonic `{}`", m),
411            ExpandError::BadOperand { mnemonic, msg } => {
412                write!(f, "`{}`: bad operand: {}", mnemonic, msg)
413            }
414            ExpandError::NotPatchable(m) => {
415                write!(
416                    f,
417                    "`{}` cannot be a patch site (use jmp/call/branch/move-imm)",
418                    m
419                )
420            }
421        }
422    }
423}
424
425impl std::error::Error for ExpandError {}
426
427pub mod expand;
428pub mod inst;
429pub mod mnemonic;
430pub mod regs;
431pub mod riscv;
432
433pub use expand::{
434    aligned_push_bytes, aligned_push_offset, check_callee_saved, expand, patch_kind, PatchKind,
435};
436pub use inst::*;
437pub use mnemonic::{mnem, LeaForm, Mnemonic, SUPPORTED_MNEMONICS};
438pub use regs::{RegInfo, RegKind, TargetRegs, VReg, TARGETS};