rucc_mir/inst.rs
1//! What one machine instruction is, and what an operand is.
2//!
3//! Design: `spec/10-backend.md` section 10.1.
4//!
5//! An instruction is an opcode, a run of operands, and the three things an opcode may carry
6//! besides its operands: an immediate, a memory addressing mode, and a symbol. Twenty-four
7//! bytes, all of it either a small number or an index into a table the function owns, so
8//! walking a function is walking one dense array and nothing in it is separately freed.
9//!
10//! An operand is a register, the class it is drawn from, whether the instruction reads or
11//! writes it, and any constraint on where it may live. That is what the allocator reads and it
12//! is all the allocator reads, which is the point: the opcode is a name to everything except
13//! the encoder, and the allocator never has to know what any particular target's instructions
14//! mean.
15//!
16//! # Where the other pieces are
17//!
18//! [`Role`] and [`Constraint`] are in `rucc-target`, and this crate re-exports them. A target
19//! says what its instructions do to their operands before there is any machine IR to say it in,
20//! and both the selector that builds the IR and the encoder that reads it need the answer, so
21//! the two of them live below both.
22//!
23//! Successors are on the block rather than on the terminator, in the order the terminator's own
24//! arms run. That is regalloc2's arrangement, which `spec/10-backend.md` section 10.4 says the
25//! allocator interface follows, and it keeps a branch's arguments out of the operand vector
26//! where they would otherwise be uses the allocator has to be told to treat differently.
27//!
28//! The source location is a parallel array in the function, reached by [`crate::Func::span`],
29//! for the same reason `rucc-ir` puts it there: it is read when a diagnostic is being made and
30//! at no other time, so it does not belong on the row that every pass walks.
31
32use rucc_base::{Idx, IdxRange, Symbol};
33use rucc_target::{Constraint, PhysReg, RegClass, Role};
34
35/// One instruction, in the function that owns it.
36pub type Inst = Idx<InstData>;
37/// One basic block, in the function that owns it.
38pub type Block = Idx<BlockData>;
39/// A run of operands, which is what an instruction's operand vector is.
40pub type OperandList = IdxRange<Operand>;
41/// One immediate, in the function's immediate table.
42pub type ImmRef = Idx<Imm>;
43/// One addressing mode, in the function's table of them.
44pub type MemRef = Idx<Amode>;
45
46/// Which instruction this is.
47///
48/// A name rather than a variant of an enum. `spec/10-backend.md` section 10.8 says no pipeline
49/// crate holds target-specific code, and an enum of every x86-64 opcode in the crate every
50/// target's MIR passes through is exactly that. The opcodes a target has are data: they come out
51/// of its rule set, which is what the selector was compiled from, and this crate never asks what
52/// one of them means. The encoder does, against the same description the rules were written
53/// against.
54#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
55pub struct Opcode(Symbol);
56
57impl Opcode {
58 /// The opcode of that name.
59 #[must_use]
60 pub const fn new(name: Symbol) -> Self {
61 Self(name)
62 }
63
64 /// Its name, which needs the interner it was made with to read.
65 #[must_use]
66 pub const fn name(self) -> Symbol {
67 self.0
68 }
69}
70
71/// A register, either one the allocator has still to place or one it has placed.
72///
73/// The two are one type and four bytes because every operand holds one and because a pass that
74/// runs both before and after allocation should not be two passes. Which of the two it is, is
75/// the top bit, so a virtual register is its own number and nothing has to be masked to compare
76/// two of them.
77#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
78pub struct Reg(u32);
79
80impl Reg {
81 /// The bit that says the rest is a physical register rather than a virtual one.
82 const PHYSICAL: u32 = 1 << 31;
83
84 /// The virtual register with that number.
85 ///
86 /// # Panics
87 ///
88 /// Panics if the number is two billion or more, which no function reaches.
89 #[must_use]
90 pub const fn virtual_reg(number: u32) -> Self {
91 assert!(number < Self::PHYSICAL, "a function with two billion virtual registers");
92 Self(number)
93 }
94
95 /// The physical register, once one has been chosen.
96 #[must_use]
97 pub const fn physical(reg: PhysReg) -> Self {
98 Self(Self::PHYSICAL | reg.number() as u32)
99 }
100
101 /// Whether the allocator has still to place it.
102 #[must_use]
103 pub const fn is_virtual(self) -> bool {
104 self.0 & Self::PHYSICAL == 0
105 }
106
107 /// Its number as a virtual register, or `None` once it is a physical one.
108 #[must_use]
109 pub const fn number(self) -> Option<u32> {
110 if self.is_virtual() { Some(self.0) } else { None }
111 }
112
113 /// The physical register it is, or `None` while it is still virtual.
114 ///
115 /// Which class the register is in is on the operand rather than here, because an operand
116 /// carries its class already and a second copy of it is a thing that can disagree.
117 #[must_use]
118 pub const fn phys(self) -> Option<PhysReg> {
119 if self.is_virtual() { None } else { Some(PhysReg::new((self.0 & 0xff) as u8)) }
120 }
121}
122
123/// One operand of one instruction.
124#[derive(Debug, Clone, Copy, PartialEq, Eq)]
125pub struct Operand {
126 /// The register, virtual until the allocator has run.
127 pub reg: Reg,
128 /// The class it is drawn from.
129 pub class: RegClass,
130 /// Whether the instruction reads it or writes it.
131 pub role: Role,
132 /// Where it is allowed to live.
133 pub constraint: Constraint,
134}
135
136impl Operand {
137 /// An operand the instruction reads.
138 #[must_use]
139 pub const fn read(reg: Reg, class: RegClass) -> Self {
140 Self { reg, class, role: Role::Use, constraint: Constraint::Reg }
141 }
142
143 /// An operand the instruction writes as it finishes.
144 #[must_use]
145 pub const fn write(reg: Reg, class: RegClass) -> Self {
146 Self { reg, class, role: Role::Def, constraint: Constraint::Reg }
147 }
148
149 /// An operand the instruction writes before it has finished reading.
150 #[must_use]
151 pub const fn write_early(reg: Reg, class: RegClass) -> Self {
152 Self { reg, class, role: Role::EarlyDef, constraint: Constraint::Reg }
153 }
154
155 /// The same operand, constrained.
156 #[must_use]
157 pub const fn with(mut self, constraint: Constraint) -> Self {
158 self.constraint = constraint;
159 self
160 }
161}
162
163/// One immediate.
164///
165/// Signed and sixty-four bits, which every immediate field of every target we have is narrower
166/// than. What fits in the field the encoder is about to write is the encoder's question, and it
167/// is one it can only answer per opcode, so nothing here tries to.
168#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
169pub struct Imm(pub i64);
170
171/// A memory addressing mode, as the instruction holds it.
172///
173/// The registers are the indices of the operands holding them rather than the registers
174/// themselves, because an address register is a register the allocator has to see and rewrite,
175/// and the only thing it looks at is the operand vector. [`Mem`] is the same thing written the
176/// way a caller writes it, and [`crate::InstBuilder::mem`] turns one into the other.
177#[derive(Debug, Clone, Copy, PartialEq, Eq)]
178pub struct Amode {
179 /// The operand holding the base register.
180 pub base: Option<u8>,
181 /// The operand holding the index register.
182 pub index: Option<u8>,
183 /// What the index is multiplied by, which is 1 when there is no index.
184 pub scale: u8,
185 /// The constant added to the address.
186 pub disp: i32,
187 /// The symbol the address is relative to, for an access to a global.
188 pub symbol: Option<Symbol>,
189}
190
191impl Amode {
192 /// The addressing mode naming no register and no symbol, at offset zero.
193 pub const NOTHING: Self = Self { base: None, index: None, scale: 1, disp: 0, symbol: None };
194}
195
196/// A memory addressing mode as a caller writes one down.
197///
198/// The difference from [`Amode`] is that the registers are here rather than in the operand
199/// vector, which is what [`crate::InstBuilder::mem`] fixes. Keeping the two apart is what lets
200/// the operand indices in an [`Amode`] be an invariant of the builder rather than something
201/// every caller has to get right.
202#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
203pub struct Mem {
204 /// The base register, which the instruction reads.
205 pub base: Option<Operand>,
206 /// The index register, which the instruction reads.
207 pub index: Option<Operand>,
208 /// What the index is multiplied by.
209 pub scale: u8,
210 /// The constant added to the address.
211 pub disp: i32,
212 /// The symbol the address is relative to.
213 pub symbol: Option<Symbol>,
214}
215
216impl Mem {
217 /// The address in that register.
218 #[must_use]
219 pub const fn at(base: Operand) -> Self {
220 Self { base: Some(base), index: None, scale: 1, disp: 0, symbol: None }
221 }
222
223 /// The address of that symbol.
224 #[must_use]
225 pub const fn of(symbol: Symbol) -> Self {
226 Self { base: None, index: None, scale: 1, disp: 0, symbol: Some(symbol) }
227 }
228
229 /// The same address with an index register scaled by that much.
230 #[must_use]
231 pub const fn indexed(mut self, index: Operand, scale: u8) -> Self {
232 self.index = Some(index);
233 self.scale = scale;
234 self
235 }
236
237 /// The same address, that many bytes along.
238 #[must_use]
239 pub const fn plus(mut self, disp: i32) -> Self {
240 self.disp = disp;
241 self
242 }
243}
244
245/// One arm of a terminator: where it goes, and what it takes with it.
246///
247/// The arguments are the values the target block's parameters arrive as, so this is the edge on
248/// which a phi would otherwise sit. After allocation the parameters are physical registers and
249/// these arguments have become the moves that write them, which is the point at which MIR stops
250/// being in SSA form.
251#[derive(Debug, Clone, PartialEq, Eq)]
252pub struct BlockCall {
253 /// The block it goes to.
254 pub block: Block,
255 /// What its parameters arrive as, one for one.
256 pub args: Vec<Reg>,
257}
258
259impl BlockCall {
260 /// A jump to that block carrying nothing.
261 #[must_use]
262 pub const fn to(block: Block) -> Self {
263 Self { block, args: Vec::new() }
264 }
265
266 /// A jump to that block carrying those registers.
267 #[must_use]
268 pub fn with(block: Block, args: Vec<Reg>) -> Self {
269 Self { block, args }
270 }
271}
272
273/// One parameter of a block: the register the value arrives in, and its class.
274#[derive(Debug, Clone, Copy, PartialEq, Eq)]
275pub struct Param {
276 /// What the value arrives as, virtual until the allocator has run.
277 pub reg: Reg,
278 /// The class it is drawn from.
279 pub class: RegClass,
280}
281
282/// One instruction.
283#[derive(Debug, Clone, Copy, PartialEq, Eq)]
284pub struct InstData {
285 /// Which instruction this is.
286 pub opcode: Opcode,
287 /// Its operands, defs first and then uses, with the registers a memory operand names last.
288 /// The order is what the printer and the parser agree on, and [`crate::InstBuilder`] is
289 /// what keeps it.
290 pub operands: OperandList,
291 /// Its immediate, if it has one.
292 pub imm: Option<ImmRef>,
293 /// Its memory operand, if it has one.
294 pub mem: Option<MemRef>,
295 /// The symbol it names, which is the callee of a direct call and the target of a direct
296 /// jump to another function.
297 pub symbol: Option<Symbol>,
298}
299
300impl InstData {
301 /// An instruction with that opcode and nothing else.
302 #[must_use]
303 pub const fn new(opcode: Opcode) -> Self {
304 Self { opcode, operands: OperandList::EMPTY, imm: None, mem: None, symbol: None }
305 }
306}
307
308/// Where an instruction sits: which block it is in, and what is either side of it.
309#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
310pub(crate) struct InstLayout {
311 pub(crate) block: Option<Block>,
312 pub(crate) prev: Option<Inst>,
313 pub(crate) next: Option<Inst>,
314}
315
316/// One block: what arrives in it, what is in it, and where it goes.
317#[derive(Debug, Clone, Default, PartialEq, Eq)]
318pub struct BlockData {
319 /// The values that arrive in it, which are the function's arguments in the entry block.
320 pub params: Vec<Param>,
321 /// Where its terminator goes, in the order the terminator's arms run.
322 pub succs: Vec<BlockCall>,
323 pub(crate) first_inst: Option<Inst>,
324 pub(crate) last_inst: Option<Inst>,
325 pub(crate) prev: Option<Block>,
326 pub(crate) next: Option<Block>,
327}
328
329#[cfg(test)]
330mod tests {
331 use super::*;
332
333 #[test]
334 fn an_instruction_is_the_size_the_design_says() {
335 assert_eq!(size_of::<InstData>(), 24);
336 assert_eq!(size_of::<Operand>(), 8);
337 }
338
339 #[test]
340 fn a_virtual_register_is_its_own_number() {
341 let reg = Reg::virtual_reg(7);
342 assert!(reg.is_virtual());
343 assert_eq!(reg.number(), Some(7));
344 assert_eq!(reg.phys(), None);
345 }
346
347 #[test]
348 fn a_physical_register_is_not_a_virtual_one_of_the_same_number() {
349 let reg = Reg::physical(PhysReg::new(7));
350 assert!(!reg.is_virtual());
351 assert_eq!(reg.number(), None);
352 assert_eq!(reg.phys(), Some(PhysReg::new(7)));
353 assert_ne!(reg, Reg::virtual_reg(7));
354 }
355
356 #[test]
357 fn an_operand_keeps_what_it_was_constrained_to() {
358 let class = RegClass::new(0);
359 let plain = Operand::write(Reg::virtual_reg(1), class);
360 assert_eq!(plain.role, Role::Def);
361 assert_eq!(plain.constraint, Constraint::Reg);
362 let tied = plain.with(Constraint::Reuse(1));
363 assert_eq!(tied.constraint, Constraint::Reuse(1));
364 assert_eq!(tied.reg, plain.reg);
365 assert!(tied.role.is_def());
366 assert!(!Operand::read(Reg::virtual_reg(1), class).role.is_def());
367 }
368}