From 96fb55ad3033887bfda93c465f4e1cf39e69a1be Mon Sep 17 00:00:00 2001 From: Tyler Smith <74526874+tylertms@users.noreply.github.com> Date: Thu, 19 Nov 2026 11:47:22 -0500 Subject: [PATCH] perf(compiler): a legacy instruction is encoded on the stack and appended once, the encoder asks the vector cache only where an instruction writes XMM or marks a fault site, and a block's code and relocations take their room at once, where every instruction built an encoder with the pool's state and the buffers grew through seven sizes: emit 20% less per guest instruction over the dsc sample, same bytes --- crates/stela-compiler/src/x86_64/asm.rs | 50 ++++-- crates/stela-compiler/src/x86_64/asm/code.rs | 14 +- .../stela-compiler/src/x86_64/asm/prefixes.rs | 144 ++++++++++++------ .../stela-compiler/src/x86_64/vector_cache.rs | 9 ++ 4 files changed, 152 insertions(+), 65 deletions(-) diff --git a/crates/stela-compiler/src/x86_64/asm.rs b/crates/stela-compiler/src/x86_64/asm.rs index 81013befef..77700c3211 100644 --- a/crates/stela-compiler/src/x86_64/asm.rs +++ b/crates/stela-compiler/src/x86_64/asm.rs @@ -40,12 +40,13 @@ pub(crate) struct Asm<'a> { /// The locals a fault recovers from their hosts ([`super::pinned::Span`]). dirty: super::pinned::Dirty, linked_block: Option, - /// Host XMM registers that hold guest vectors - /// ([`super::vector_cache`]): no instruction emitted here writes one. - guarded: u32, - /// The guest vectors whose only current value is a home: a fault site - /// here records them for recovery. - homes: super::vector_cache::DirtyHomes, + /// The [`Code`]'s guest vectors in host XMM registers + /// ([`super::vector_cache`]), which no instruction emitted here writes + /// unless `unguarded`, and whose homes holding the only current value + /// a fault site here records for recovery. Asked only where an + /// instruction needs them: every instruction builds an encoder. + vectors: Option<&'a super::vector_cache::VectorCache>, + unguarded: bool, } impl<'a> Asm<'a> { @@ -76,10 +77,24 @@ impl<'a> Asm<'a> { locals: None, dirty: Default::default(), linked_block: None, - guarded: 0, - homes: Default::default(), + vectors: None, + unguarded: false, } } + /// Host XMM registers that hold guest vectors, which no instruction + /// emitted here writes. + fn guarded(&self) -> u32 { + match self.vectors { + Some(vectors) if !self.unguarded => vectors.occupied(), + _ => 0, + } + } + /// The guest vectors whose only current value is a home. + fn homes(&self) -> super::vector_cache::DirtyHomes { + self.vectors + .map(super::vector_cache::VectorCache::dirty_homes) + .unwrap_or_default() + } /// [`Self::new`] for code that keeps guest registers in host registers /// ([`super::pinned`]). pub(crate) fn pinned(code: &'a mut Vec) -> Self { @@ -133,6 +148,7 @@ impl<'a> Asm<'a> { self.refuse_dirty_homes("a helper call"); let start = self.len(); self.data(&[bytes, flags]); + let homes = self.homes(); if let Some(sites) = self.sites.as_deref_mut() { assert!( sites.last().is_none_or(|previous| previous.end <= start), @@ -145,7 +161,7 @@ impl<'a> Asm<'a> { stack: None, source: None, locals: self.dirty, - homes: self.homes, + homes, }); } } @@ -153,7 +169,7 @@ impl<'a> Asm<'a> { /// a home ([`super::vector_cache`]). pub(crate) fn refuse_dirty_homes(&self, what: &str) { assert!( - self.homes.iter().all(Option::is_none), + self.homes().iter().all(Option::is_none), "{what} with V registers only in XMM" ); } @@ -161,7 +177,7 @@ impl<'a> Asm<'a> { /// ([`super::vector_cache`]): a recipe names it only as a source. pub(crate) fn guard_vector(&self, xmm: u8) { assert!( - self.guarded & 1 << xmm == 0, + self.guarded() & 1 << xmm == 0, "xmm{xmm} holds a guest vector of the block" ); } @@ -180,6 +196,7 @@ impl<'a> Asm<'a> { "one exact faulting instruction" ); let end = self.len(); + let homes = self.homes(); if let Some(sites) = self.sites.as_deref_mut() { assert!( sites.last().is_none_or(|previous| previous.end <= start), @@ -192,7 +209,7 @@ impl<'a> Asm<'a> { stack, source: None, locals: self.dirty, - homes: self.homes, + homes, }); } } @@ -243,9 +260,9 @@ impl<'a> Asm<'a> { xmm: u8, rm: impl Into, ) { - let guarded = core::mem::replace(&mut self.guarded, 0); + let unguarded = core::mem::replace(&mut self.unguarded, true); self.sse(prefix, opcode, xmm, rm); - self.guarded = guarded; + self.unguarded = unguarded; } /// [`Self::sse`] with an 8-bit immediate. pub(crate) fn sse_imm( @@ -375,6 +392,11 @@ impl<'a> Asm<'a> { let at = self.code.len(); self.data(&address.0.to_le_bytes()); if let Some(relocations) = self.relocations.as_deref_mut() { + // Room for a block's exits and constants at once, where the + // list grew through three sizes. + if relocations.capacity() == 0 { + relocations.reserve(16); + } relocations.push(u32::try_from(at).expect("code under 4 GiB")); } } diff --git a/crates/stela-compiler/src/x86_64/asm/code.rs b/crates/stela-compiler/src/x86_64/asm/code.rs index b80d5ecf56..1048cce92d 100644 --- a/crates/stela-compiler/src/x86_64/asm/code.rs +++ b/crates/stela-compiler/src/x86_64/asm/code.rs @@ -242,8 +242,12 @@ impl Code { } /// An encoder that appends here and adds to this count. pub(crate) fn asm(&mut self) -> Asm<'_> { - let guarded = self.vectors.occupied(); - let homes = self.vectors.dirty_homes(); + // A buffer made empty (`Default`, as a block's own is) takes room + // for most blocks at its first instruction, where it grew through + // seven sizes to that. + if self.bytes.capacity() == 0 { + self.bytes.reserve(INITIAL_BYTES); + } Asm { code: &mut self.bytes, instructions: 0, @@ -254,15 +258,15 @@ impl Code { locals: self.locals, dirty: self.dirty, linked_block: self.linked_block, - guarded, - homes, + vectors: Some(&self.vectors), + unguarded: false, } } /// [`Self::asm`] for the vector cache's own moves, which may write the /// pool registers that hold guest vectors. pub(in crate::x86_64) fn asm_unguarded(&mut self) -> Asm<'_> { let mut asm = self.asm(); - asm.guarded = 0; + asm.unguarded = true; asm } /// A typed recipe that emits exactly one guest memory instruction. diff --git a/crates/stela-compiler/src/x86_64/asm/prefixes.rs b/crates/stela-compiler/src/x86_64/asm/prefixes.rs index b77efde640..ba499d20de 100644 --- a/crates/stela-compiler/src/x86_64/asm/prefixes.rs +++ b/crates/stela-compiler/src/x86_64/asm/prefixes.rs @@ -1,6 +1,34 @@ //! Operand-derived legacy, REX2, VEX and vector EVEX prefixes. use super::{Asm, Disp, Evex, Gpr, Map, Mem, Rm, Size, Vex}; +/// The bytes of one instruction, built on the stack and appended to the +/// code at once: each push to the code checks its room, and an +/// instruction's prefixes, opcode and operand bytes were a dozen pushes. +struct Encoding { + bytes: [u8; 15], + len: usize, +} + +impl Encoding { + const fn new() -> Self { + Self { + bytes: [0; 15], + len: 0, + } + } + fn push(&mut self, byte: u8) { + self.bytes[self.len] = byte; + self.len += 1; + } + fn extend(&mut self, bytes: &[u8]) { + self.bytes[self.len..self.len + bytes.len()].copy_from_slice(bytes); + self.len += bytes.len(); + } + fn as_slice(&self) -> &[u8] { + &self.bytes[..self.len] + } +} + impl Asm<'_> { pub(super) fn modrm(&mut self, reg: u8, rm: Rm) { self.modrm_scaled(reg, rm, 1); @@ -9,10 +37,17 @@ impl Asm<'_> { /// ModRM, SIB and displacement, with an 8-bit displacement counted in /// units of `scale` bytes (EVEX disp8*N; 1 elsewhere). fn modrm_scaled(&mut self, reg: u8, rm: Rm, scale: u8) { + let mut encoding = Encoding::new(); + self.modrm_into(&mut encoding, reg, rm, scale); + self.code.extend_from_slice(encoding.as_slice()); + } + + /// [`Self::modrm_scaled`] into `out`. + fn modrm_into(&self, out: &mut Encoding, reg: u8, rm: Rm, scale: u8) { let reg = (reg & 7) << 3; match rm { - Rm::Reg(register) => self.code.push(0xc0 | reg | register.low()), - Rm::Xmm(register) => self.code.push(0xc0 | reg | (register & 7)), + Rm::Reg(register) => out.push(0xc0 | reg | register.low()), + Rm::Xmm(register) => out.push(0xc0 | reg | (register & 7)), Rm::Mem(Mem { base: None, index, @@ -20,8 +55,8 @@ impl Asm<'_> { .. }) => { debug_assert!(index.is_none(), "RIP-relative addressing has no index"); - self.code.push(reg | 5); - self.code.extend(displacement.to_le_bytes()); + out.push(reg | 5); + out.extend(&displacement.to_le_bytes()); } Rm::Mem(Mem { base: Some(base), @@ -51,8 +86,8 @@ impl Asm<'_> { Disp::Auto => 2, }; match index { - None if base.low() != 4 => self.code.push(mode << 6 | reg | base.low()), - None => self.code.extend([mode << 6 | reg | 4, 0x24]), + None if base.low() != 4 => out.push(mode << 6 | reg | base.low()), + None => out.extend(&[mode << 6 | reg | 4, 0x24]), Some((index, scale)) => { debug_assert!(index != Gpr::Rsp, "RSP cannot be an index"); let scale = match scale { @@ -62,15 +97,15 @@ impl Asm<'_> { 8 => 3, _ => unreachable!("scale of 1, 2, 4 or 8"), }; - self.code.extend([ + out.extend(&[ mode << 6 | reg | 4, scale << 6 | index.low() << 3 | base.low(), ]); } } match mode { - 1 => self.code.push((displacement / scale) as u8), - 2 => self.code.extend(displacement.to_le_bytes()), + 1 => out.push((displacement / scale) as u8), + 2 => out.extend(&displacement.to_le_bytes()), _ => {} } } @@ -102,15 +137,17 @@ impl Asm<'_> { byte_rex: bool, rm: Rm, ) { + let mut encoding = Encoding::new(); if size == Size::Word { - self.code.push(0x66); + encoding.push(0x66); } if let Some(prefix) = prefix { - self.code.push(prefix); + encoding.push(prefix); } - let skip = self.opcode_prefix(size, byte_rex, opcode, reg, rm); - self.code.extend(&opcode[skip..]); - self.modrm(reg, rm); + let skip = opcode_prefix_into(&mut encoding, size, byte_rex, opcode, reg, rm); + encoding.extend(&opcode[skip..]); + self.modrm_into(&mut encoding, reg, rm, 1); + self.code.extend_from_slice(encoding.as_slice()); self.count(); } @@ -123,40 +160,55 @@ impl Asm<'_> { reg: u8, rm: Rm, ) -> usize { - assert!(reg < 32, "integer register encoding is at most five bits"); - let (x, b) = rm.extensions(); - let (x4, b4) = rm.extended_extensions(); - let w = size == Size::Qword; - let r = reg & 8 != 0; - let r4 = reg & 16 != 0; - if r4 || x4 || b4 { - let map1 = opcode.first() == Some(&0x0f); - assert!( - (!map1 && opcode.len() == 1) || (map1 && opcode.len() == 2), - "REX2 supports only legacy maps zero and one" - ); - self.code.extend([ - 0xd5, - u8::from(map1) << 7 - | u8::from(r4) << 6 - | u8::from(x4) << 5 - | u8::from(b4) << 4 - | u8::from(w) << 3 - | u8::from(r) << 2 - | u8::from(x) << 1 - | u8::from(b), - ]); - usize::from(map1) - } else { - if w || r || x || b || force { - self.code.push( - 0x40 | u8::from(w) << 3 | u8::from(r) << 2 | u8::from(x) << 1 | u8::from(b), - ); - } - 0 - } + let mut encoding = Encoding::new(); + let skip = opcode_prefix_into(&mut encoding, size, force, opcode, reg, rm); + self.code.extend_from_slice(encoding.as_slice()); + skip } +} +/// [`Asm::opcode_prefix`] into `out`. +fn opcode_prefix_into( + out: &mut Encoding, + size: Size, + force: bool, + opcode: &[u8], + reg: u8, + rm: Rm, +) -> usize { + assert!(reg < 32, "integer register encoding is at most five bits"); + let (x, b) = rm.extensions(); + let (x4, b4) = rm.extended_extensions(); + let w = size == Size::Qword; + let r = reg & 8 != 0; + let r4 = reg & 16 != 0; + if r4 || x4 || b4 { + let map1 = opcode.first() == Some(&0x0f); + assert!( + (!map1 && opcode.len() == 1) || (map1 && opcode.len() == 2), + "REX2 supports only legacy maps zero and one" + ); + out.extend(&[ + 0xd5, + u8::from(map1) << 7 + | u8::from(r4) << 6 + | u8::from(x4) << 5 + | u8::from(b4) << 4 + | u8::from(w) << 3 + | u8::from(r) << 2 + | u8::from(x) << 1 + | u8::from(b), + ]); + usize::from(map1) + } else { + if w || r || x || b || force { + out.push(0x40 | u8::from(w) << 3 | u8::from(r) << 2 | u8::from(x) << 1 | u8::from(b)); + } + 0 + } +} + +impl Asm<'_> { /// A VEX-encoded instruction: two-byte C5 when the fields allow it, /// otherwise three-byte C4. pub(crate) fn vex(&mut self, prefix: Vex, opcode: u8, reg: u8, vvvv: u8, rm: Rm) { diff --git a/crates/stela-compiler/src/x86_64/vector_cache.rs b/crates/stela-compiler/src/x86_64/vector_cache.rs index 3fa9312cca..c5f5051ba5 100644 --- a/crates/stela-compiler/src/x86_64/vector_cache.rs +++ b/crates/stela-compiler/src/x86_64/vector_cache.rs @@ -130,6 +130,10 @@ impl VectorCache { /// The dirty homes, for a fault site here. pub(crate) fn dirty_homes(&self) -> DirtyHomes { let mut homes = [None; HOSTS]; + // Most code holds no dirty vector: every instruction it emits asks. + if self.dirty == 0 { + return homes; + } for (index, owner) in self.owner.iter().enumerate() { if *owner != NONE && self.is_dirty(*owner) { homes[index] = Some((*owner, FIRST_HOST + index as u8)); @@ -140,6 +144,11 @@ impl VectorCache { /// The pool registers that hold a guest vector: no recipe may write one, /// except the destination home it is writing. pub(crate) fn occupied(&self) -> u32 { + // Most code keeps no vector in the pool: every instruction it emits + // asks. + if self.owner == [NONE; HOSTS] && self.derived == [None; DERIVED_HOSTS] { + return 0; + } let occupied = self .owner .iter()