Skip to main content

asmkit/core/
inst.rs

1//! Generic instruction representation.
2//!
3//! [`Inst`] is the asmkit equivalent of AsmJit's `BaseInst` + trailing operand array: an
4//! architecture-namespaced instruction id, options, an optional extra register, and up to
5//! [`MAX_OP_COUNT`] operands stored inline. It is the node type recorded by a Builder
6//! (see `core::builder`) and consumed by `query_rw_info`-style APIs, while the per-mnemonic
7//! emitter methods remain the ergonomic way to construct one.
8
9use super::arch_traits::Arch;
10use super::globals::{InstOptions, MAX_OP_COUNT};
11use super::operand::Operand;
12use crate::AsmError;
13
14/// A generic instruction: id + options + extra register + inline operand array.
15///
16/// The id is architecture-namespaced (`x86::InstId`, `aarch64::InstId`, `riscv::Opcode`,
17/// all cast to `u32`); architectures may pack modifiers into high bits of the id (AArch64
18/// packs a [`super::globals::CondCode`]). `extra_reg` carries the REP register or AVX-512
19/// `{k}` selector where applicable and is [`Operand::new()`] (none) otherwise.
20#[derive(Clone, Copy, PartialEq, Eq, Debug)]
21pub struct Inst {
22    arch: Arch,
23    /// Instruction id with modifiers (architecture-namespaced).
24    pub(crate) id: u32,
25    /// Instruction options.
26    pub(crate) options: InstOptions,
27    /// Extra register used by the instruction (REP register or AVX-512 mask selector).
28    pub(crate) extra_reg: Operand,
29    /// Number of valid entries in `operands`.
30    op_count: u8,
31    /// Operands; only the first `op_count` entries are meaningful.
32    operands: [Operand; MAX_OP_COUNT],
33}
34
35impl Inst {
36    /// Creates a host-tagged instruction with the given `id` and no operands.
37    /// Creates an instruction for a supported assembler architecture.
38    pub(crate) const fn new_for(arch: Arch, id: u32) -> Self {
39        Self {
40            arch,
41            id,
42            options: InstOptions::NONE,
43            extra_reg: Operand::new(),
44            op_count: 0,
45            operands: [Operand::new(); MAX_OP_COUNT],
46        }
47    }
48
49    /// Creates a host-tagged instruction with the given `id` and operands.
50    /// Creates an architecture-tagged instruction without operands.
51    pub fn for_arch(arch: Arch, id: u32) -> Result<Self, AsmError> {
52        Self::with_arch_operands(arch, id, &[])
53    }
54
55    /// Creates an architecture-tagged instruction without dropping operands.
56    pub fn with_arch_operands(arch: Arch, id: u32, ops: &[Operand]) -> Result<Self, AsmError> {
57        if !matches!(
58            arch,
59            Arch::X86 | Arch::X64 | Arch::AArch64 | Arch::RISCV32 | Arch::RISCV64
60        ) {
61            return Err(AsmError::InvalidArch);
62        }
63        let mut inst = Self::new_for(arch, id);
64        inst.set_operands(ops)?;
65        Ok(inst)
66    }
67
68    /// Architecture this instruction belongs to.
69    pub const fn arch(&self) -> Arch {
70        self.arch
71    }
72
73    /// Instruction id with architecture-specific modifiers.
74    pub const fn id(&self) -> u32 {
75        self.id
76    }
77
78    /// Encoding options retained by deferred replay.
79    pub const fn options(&self) -> InstOptions {
80        self.options
81    }
82
83    /// Optional extra register retained by deferred replay.
84    pub const fn extra_reg(&self) -> Operand {
85        self.extra_reg
86    }
87
88    /// Sets encoding options retained by deferred replay.
89    pub fn set_options(&mut self, options: InstOptions) {
90        self.options = options;
91    }
92
93    /// Sets the optional extra register retained by deferred replay.
94    pub fn set_extra_reg(&mut self, extra_reg: Operand) {
95        self.extra_reg = extra_reg;
96    }
97
98    /// Returns the number of operands.
99    pub const fn op_count(&self) -> usize {
100        self.op_count as usize
101    }
102
103    /// Returns the operands as a slice.
104    pub fn operands(&self) -> &[Operand] {
105        self.operands.split_at(self.op_count as usize).0
106    }
107
108    /// Returns the operands as a mutable slice.
109    pub fn operands_mut(&mut self) -> &mut [Operand] {
110        self.operands.split_at_mut(self.op_count as usize).0
111    }
112
113    /// Returns the operand at `index`, or `None` if out of range.
114    pub fn operand(&self, index: usize) -> Option<&Operand> {
115        self.operands().get(index)
116    }
117
118    /// Sets the operand at `index`. `index` must be less than `op_count`.
119    pub fn set_operand(&mut self, index: usize, op: Operand) -> Result<(), AsmError> {
120        let Some(slot) = self.operands_mut().get_mut(index) else {
121            return Err(AsmError::InvalidArgument);
122        };
123        *slot = op;
124        Ok(())
125    }
126
127    /// Appends an operand, or returns [`AsmError::InvalidState`] if the operand array is full.
128    pub fn add_operand(&mut self, op: Operand) -> Result<(), AsmError> {
129        if self.op_count() >= MAX_OP_COUNT {
130            return Err(AsmError::InvalidState);
131        }
132        self.operands[self.op_count()] = op;
133        self.op_count += 1;
134        Ok(())
135    }
136
137    /// Sets all operands from `ops`, replacing the current operand list.
138    ///
139    /// Returns [`AsmError::InvalidState`] if `ops` doesn't fit into the operand array.
140    pub fn set_operands(&mut self, ops: &[Operand]) -> Result<(), AsmError> {
141        if ops.len() > MAX_OP_COUNT {
142            return Err(AsmError::InvalidState);
143        }
144        self.operands[..ops.len()].copy_from_slice(ops);
145        self.operands[ops.len()..].fill(Operand::new());
146        self.op_count = ops.len() as u8;
147        Ok(())
148    }
149}