Skip to main content

logicaffeine_forge/
x64asm.rs

1//! A minimal x86-64 instruction encoder for the contiguous register-allocated
2//! region backend (`compile_region_regalloc`).
3//!
4//! This is deliberately tiny: it covers exactly the instruction shapes the
5//! linear-scan int backend emits — register/immediate moves, the three-operand
6//! arithmetic the allocator lowers (via a two-address `dst = lhs; dst OP rhs`
7//! discipline), compares + `setcc`, conditional and unconditional jumps with
8//! late-bound labels, frame loads/stores (`base + disp`), prologue/epilogue
9//! register save/restore, and `ret`. It is NOT a general assembler.
10//!
11//! Register numbering follows the hardware encoding (`rax=0 … r15=15`); the REX
12//! prefix and ModRM/SIB bytes are emitted directly. All emitted code is
13//! position-independent except the `jcc`/`jmp` displacements, which are resolved
14//! against final offsets by [`Asm::resolve`] before the bytes leave this module.
15
16#![cfg(target_arch = "x86_64")]
17
18/// A hardware general-purpose register, by its 4-bit encoding.
19#[derive(Clone, Copy, Debug, PartialEq, Eq)]
20#[repr(u8)]
21#[allow(missing_docs)]
22pub enum Reg {
23    Rax = 0,
24    Rcx = 1,
25    Rdx = 2,
26    Rbx = 3,
27    Rsp = 4,
28    Rbp = 5,
29    Rsi = 6,
30    Rdi = 7,
31    R8 = 8,
32    R9 = 9,
33    R10 = 10,
34    R11 = 11,
35    R12 = 12,
36    R13 = 13,
37    R14 = 14,
38    R15 = 15,
39}
40
41impl Reg {
42    /// The low 3 bits (the ModRM/opcode field).
43    #[inline]
44    fn lo3(self) -> u8 {
45        (self as u8) & 0b111
46    }
47    /// The high bit (the REX extension bit).
48    #[inline]
49    fn hi(self) -> u8 {
50        ((self as u8) >> 3) & 1
51    }
52}
53
54/// A hardware XMM register (SSE2), by its 4-bit encoding. f64 slots that win a
55/// physical register live here for the whole function (a SECOND register class
56/// alongside the GP [`Reg`] one); the rest spill to the frame. All XMM registers
57/// are caller-saved under SysV, so none need save/restore in the prologue.
58#[derive(Clone, Copy, Debug, PartialEq, Eq)]
59#[repr(u8)]
60#[allow(missing_docs)]
61pub enum Xmm {
62    Xmm0 = 0,
63    Xmm1 = 1,
64    Xmm2 = 2,
65    Xmm3 = 3,
66    Xmm4 = 4,
67    Xmm5 = 5,
68    Xmm6 = 6,
69    Xmm7 = 7,
70    Xmm8 = 8,
71    Xmm9 = 9,
72    Xmm10 = 10,
73    Xmm11 = 11,
74    Xmm12 = 12,
75    Xmm13 = 13,
76    Xmm14 = 14,
77    Xmm15 = 15,
78}
79
80impl Xmm {
81    /// The low 3 bits (the ModRM/opcode field).
82    #[inline]
83    fn lo3(self) -> u8 {
84        (self as u8) & 0b111
85    }
86    /// The high bit (the REX extension bit).
87    #[inline]
88    fn hi(self) -> u8 {
89        ((self as u8) >> 3) & 1
90    }
91}
92
93/// An integer condition, mapping to an x86 condition code. The first six are
94/// SIGNED; [`Cond::AeU`] is the one UNSIGNED code the array bounds check needs
95/// (`jae` — "above or equal", unsigned `>=`), used so a 1-based index whose
96/// `idx - 1` wraps negative (e.g. index 0) trips the OOB exit, matching the
97/// stencil's `(im1 as u64) >= (len as u64)` guard.
98#[derive(Clone, Copy, Debug, PartialEq, Eq)]
99pub enum Cond {
100    /// `<` (signed less): `cc=0xC`.
101    Lt,
102    /// `>` (signed greater): `cc=0xF`.
103    Gt,
104    /// `<=` (signed less-or-equal): `cc=0xE`.
105    Le,
106    /// `>=` (signed greater-or-equal): `cc=0xD`.
107    Ge,
108    /// `==`: `cc=0x4`.
109    Eq,
110    /// `!=`: `cc=0x5`.
111    Ne,
112    /// `>=` UNSIGNED (above or equal): `cc=0x3` (`jae`/`jnc`). The array
113    /// bounds-check uses this to fold the lower (`im1 < 0`) and upper
114    /// (`im1 >= len`) out-of-bounds cases into ONE unsigned comparison.
115    AeU,
116    /// `>` UNSIGNED (above): `cc=0x7` (`ja`). After `ucomisd`, `seta` is the
117    /// strict ordered-greater test (CF=0 && ZF=0) — NaN (ZF=1) folds to FALSE,
118    /// the float `>`/`<` (with swapped operands) primitive.
119    AU,
120    /// UNSIGNED below-or-equal: `cc=0x6` (`jbe`). The NEGATION of `AU` (CF=1 ||
121    /// ZF=1) — the "comparison FALSE" branch for a float `>`/`<` BranchF, where
122    /// NaN (ZF=1) must TAKE the false branch.
123    BeU,
124    /// UNSIGNED below: `cc=0x2` (`jb`). After `ucomisd`, the strict
125    /// ordered-less primitive (CF=1); NaN folds to FALSE.
126    BU,
127    /// PARITY EVEN (`jp`/`jpe`): `cc=0xA`. After `ucomisd`, PF=1 ⟺ the operands
128    /// were UNORDERED (a NaN). The `DivF` zero-divisor guard uses this to skip
129    /// the side-exit on a NaN divisor (NaN is not `0.0`).
130    ParityEven,
131    /// PARITY ODD (`jnp`/`jpo`): `cc=0xB`. After `ucomisd`, PF=0 ⟺ ORDERED —
132    /// the second half of the IEEE `==` test (`sete && setnp`), so a NaN
133    /// compare yields false exactly like the reference `a == b`.
134    ParityOdd,
135    /// OVERFLOW (`jo`): `cc=0x0`. OF=1 after a signed `add`/`sub`/`imul` — the
136    /// integer-overflow side-exit (`jo deopt`) for exact arithmetic: on overflow
137    /// the native tier deopts so the exact VM recomputes (and promotes to BigInt).
138    Overflow,
139}
140
141impl Cond {
142    /// The 4-bit x86 condition-code tetrad (`jcc` low nibble = `0x80 | cc`,
143    /// `setcc` = `0x90 | cc`).
144    fn cc(self) -> u8 {
145        match self {
146            Cond::Eq => 0x4,
147            Cond::Ne => 0x5,
148            Cond::Ge => 0xD,         // GE (signed): NL
149            Cond::Lt => 0xC,         // L  (signed)
150            Cond::Le => 0xE,         // LE (signed)
151            Cond::Gt => 0xF,         // G  (signed): NLE
152            Cond::AeU => 0x3,        // AE (unsigned): NB/NC
153            Cond::AU => 0x7,         // A  (unsigned): NBE
154            Cond::BeU => 0x6,        // BE (unsigned): NA
155            Cond::BU => 0x2,         // B  (unsigned): C
156            Cond::ParityEven => 0xA, // P/PE (parity even): unordered after ucomisd
157            Cond::ParityOdd => 0xB,  // NP/PO (parity odd): ordered after ucomisd
158            Cond::Overflow => 0x0,   // O (overflow): OF=1 after signed add/sub/imul
159        }
160    }
161}
162
163/// A label in the instruction stream. Created with [`Asm::new_label`], its
164/// position fixed with [`Asm::bind`], and referenced by jumps; all references
165/// are patched in [`Asm::resolve`].
166#[derive(Clone, Copy, Debug, PartialEq, Eq)]
167pub struct LabelId(pub usize);
168
169enum Fixup {
170    /// A rel32 jump site: 4 LE bytes at `site` are filled with
171    /// `target_off - (site + 4)`.
172    Rel32 { site: usize, label: LabelId },
173}
174
175/// The x86-64 byte emitter with late-bound labels.
176pub struct Asm {
177    buf: Vec<u8>,
178    /// `label_pos[i]` = byte offset of label `i`, or `usize::MAX` until bound.
179    label_pos: Vec<usize>,
180    fixups: Vec<Fixup>,
181}
182
183impl Default for Asm {
184    fn default() -> Self {
185        Asm::new()
186    }
187}
188
189impl Asm {
190    /// An empty assembler.
191    pub fn new() -> Self {
192        Asm {
193            buf: Vec::with_capacity(256),
194            label_pos: Vec::new(),
195            fixups: Vec::new(),
196        }
197    }
198
199    /// The current byte length (a position label).
200    pub fn pos(&self) -> usize {
201        self.buf.len()
202    }
203
204    /// Reserve a new (unbound) label.
205    pub fn new_label(&mut self) -> LabelId {
206        let id = LabelId(self.label_pos.len());
207        self.label_pos.push(usize::MAX);
208        id
209    }
210
211    /// Fix label `l` at the current position.
212    pub fn bind(&mut self, l: LabelId) {
213        self.label_pos[l.0] = self.buf.len();
214    }
215
216    /// REX prefix. `w` = 64-bit operand; `r` = ModRM.reg high bit; `x` = SIB
217    /// index high bit; `b` = ModRM.rm / opcode-reg high bit.
218    fn rex(&mut self, w: bool, r: u8, x: u8, b: u8) {
219        let byte = 0x40 | ((w as u8) << 3) | (r << 2) | (x << 1) | b;
220        self.buf.push(byte);
221    }
222
223    /// `mov dst, imm64` (REX.W + B8+rd io). Always 10 bytes; simple and exact.
224    pub fn mov_ri(&mut self, dst: Reg, imm: i64) {
225        self.rex(true, 0, 0, dst.hi());
226        self.buf.push(0xB8 + dst.lo3());
227        self.buf.extend_from_slice(&imm.to_le_bytes());
228    }
229
230    /// `mov dst, src` (REX.W 89 /r, src in reg field).
231    pub fn mov_rr(&mut self, dst: Reg, src: Reg) {
232        if dst == src {
233            return;
234        }
235        self.rex(true, src.hi(), 0, dst.hi());
236        self.buf.push(0x89);
237        self.modrm_reg(src, dst);
238    }
239
240    /// ModRM for register-direct (`mod=11`): reg field = `r`, rm field = `m`.
241    fn modrm_reg(&mut self, r: Reg, m: Reg) {
242        self.buf.push(0b1100_0000 | (r.lo3() << 3) | m.lo3());
243    }
244
245    /// ModRM + (optional) SIB + disp for a `[base + disp32]` memory operand,
246    /// with `r` as the reg field. Always emits a disp32 for simplicity.
247    fn modrm_mem(&mut self, r: Reg, base: Reg, disp: i32) {
248        // mod=10 (disp32). rm=base.lo3(); rm==100 (rsp/r12) needs a SIB byte.
249        let rm = base.lo3();
250        self.buf.push(0b1000_0000 | (r.lo3() << 3) | rm);
251        if rm == 0b100 {
252            // SIB: scale=0, index=100 (none), base=rm.
253            self.buf.push(0b0000_0000 | (0b100 << 3) | rm);
254        }
255        self.buf.extend_from_slice(&disp.to_le_bytes());
256    }
257
258    /// `mov dst, [base + disp]` (REX.W 8B /r).
259    pub fn mov_rm(&mut self, dst: Reg, base: Reg, disp: i32) {
260        self.rex(true, dst.hi(), 0, base.hi());
261        self.buf.push(0x8B);
262        self.modrm_mem(dst, base, disp);
263    }
264
265    /// `mov [base + disp], src` (REX.W 89 /r).
266    pub fn mov_mr(&mut self, base: Reg, disp: i32, src: Reg) {
267        self.rex(true, src.hi(), 0, base.hi());
268        self.buf.push(0x89);
269        self.modrm_mem(src, base, disp);
270    }
271
272    /// `add dst, src` (REX.W 01 /r).
273    pub fn add_rr(&mut self, dst: Reg, src: Reg) {
274        self.rex(true, src.hi(), 0, dst.hi());
275        self.buf.push(0x01);
276        self.modrm_reg(src, dst);
277    }
278
279    /// `sub dst, src` (REX.W 29 /r).
280    pub fn sub_rr(&mut self, dst: Reg, src: Reg) {
281        self.rex(true, src.hi(), 0, dst.hi());
282        self.buf.push(0x29);
283        self.modrm_reg(src, dst);
284    }
285
286    /// `imul dst, src` (REX.W 0F AF /r — dst is the reg field).
287    pub fn imul_rr(&mut self, dst: Reg, src: Reg) {
288        self.rex(true, dst.hi(), 0, src.hi());
289        self.buf.push(0x0F);
290        self.buf.push(0xAF);
291        self.modrm_reg(dst, src);
292    }
293
294    /// `popcnt dst, src` (F3 REX.W 0F B8 /r) — `dst = src.count_ones()`. The F3 prefix precedes REX.
295    pub fn popcnt_rr(&mut self, dst: Reg, src: Reg) {
296        self.buf.push(0xF3);
297        self.rex(true, dst.hi(), 0, src.hi());
298        self.buf.push(0x0F);
299        self.buf.push(0xB8);
300        self.modrm_reg(dst, src);
301    }
302
303    /// `lzcnt dst, src` (F3 REX.W 0F BD /r) — `dst = src.leading_zeros()` (64 for 0). The F3 prefix (which
304    /// precedes REX) is what distinguishes it from `bsr` (0F BD, undefined for 0); requires the ABM feature.
305    pub fn lzcnt_rr(&mut self, dst: Reg, src: Reg) {
306        self.buf.push(0xF3);
307        self.rex(true, dst.hi(), 0, src.hi());
308        self.buf.push(0x0F);
309        self.buf.push(0xBD);
310        self.modrm_reg(dst, src);
311    }
312
313    /// `tzcnt dst, src` (F3 REX.W 0F BC /r) — `dst = src.trailing_zeros()` (64 for 0). The F3 prefix (which
314    /// precedes REX) is what distinguishes it from `bsf` (0F BC, undefined for 0); requires the BMI1 feature.
315    pub fn tzcnt_rr(&mut self, dst: Reg, src: Reg) {
316        self.buf.push(0xF3);
317        self.rex(true, dst.hi(), 0, src.hi());
318        self.buf.push(0x0F);
319        self.buf.push(0xBC);
320        self.modrm_reg(dst, src);
321    }
322
323    /// `sub dst, imm32` (REX.W 81 /5 id) — sign-extended 32-bit immediate.
324    pub fn sub_ri(&mut self, dst: Reg, imm: i32) {
325        self.rex(true, 0, 0, dst.hi());
326        self.buf.push(0x81);
327        self.buf.push(0b1100_0000 | (5 << 3) | dst.lo3());
328        self.buf.extend_from_slice(&imm.to_le_bytes());
329    }
330
331    /// `add dst, imm32` (REX.W 81 /0 id) — sign-extended 32-bit immediate.
332    pub fn add_ri(&mut self, dst: Reg, imm: i32) {
333        self.rex(true, 0, 0, dst.hi());
334        self.buf.push(0x81);
335        self.buf.push(0b1100_0000 | dst.lo3());
336        self.buf.extend_from_slice(&imm.to_le_bytes());
337    }
338
339    /// `cmp dst, imm32` (REX.W 81 /7 id) — `dst - imm`, sets flags.
340    pub fn cmp_ri(&mut self, dst: Reg, imm: i32) {
341        self.rex(true, 0, 0, dst.hi());
342        self.buf.push(0x81);
343        self.buf.push(0b1100_0000 | (7 << 3) | dst.lo3());
344        self.buf.extend_from_slice(&imm.to_le_bytes());
345    }
346
347    /// `call reg` (FF /2) — an indirect near call through a register.
348    pub fn call_r(&mut self, target: Reg) {
349        if target.hi() == 1 {
350            self.buf.push(0x41);
351        }
352        self.buf.push(0xFF);
353        self.buf.push(0b1100_0000 | (2 << 3) | target.lo3());
354    }
355
356    /// `shl dst, imm8` (REX.W C1 /4 ib) — shift left by a constant count.
357    pub fn shl_ri(&mut self, dst: Reg, imm: u8) {
358        self.rex(true, 0, 0, dst.hi());
359        self.buf.push(0xC1);
360        self.buf.push(0b1100_0000 | (4 << 3) | dst.lo3());
361        self.buf.push(imm);
362    }
363
364    /// `and dst, src` (REX.W 21 /r).
365    pub fn and_rr(&mut self, dst: Reg, src: Reg) {
366        self.rex(true, src.hi(), 0, dst.hi());
367        self.buf.push(0x21);
368        self.modrm_reg(src, dst);
369    }
370
371    /// `or dst, src` (REX.W 09 /r).
372    pub fn or_rr(&mut self, dst: Reg, src: Reg) {
373        self.rex(true, src.hi(), 0, dst.hi());
374        self.buf.push(0x09);
375        self.modrm_reg(src, dst);
376    }
377
378    /// `xor dst, src` (REX.W 31 /r).
379    pub fn xor_rr(&mut self, dst: Reg, src: Reg) {
380        self.rex(true, src.hi(), 0, dst.hi());
381        self.buf.push(0x31);
382        self.modrm_reg(src, dst);
383    }
384
385    /// `not dst` (REX.W F7 /2).
386    pub fn not_r(&mut self, dst: Reg) {
387        self.rex(true, 0, 0, dst.hi());
388        self.buf.push(0xF7);
389        self.buf.push(0b1100_0000 | (2 << 3) | dst.lo3());
390    }
391
392    /// `neg dst` (REX.W F7 /3).
393    pub fn neg_r(&mut self, dst: Reg) {
394        self.rex(true, 0, 0, dst.hi());
395        self.buf.push(0xF7);
396        self.buf.push(0b1100_0000 | (3 << 3) | dst.lo3());
397    }
398
399    /// `shl dst, cl` (REX.W D3 /4).
400    pub fn shl_cl(&mut self, dst: Reg) {
401        self.rex(true, 0, 0, dst.hi());
402        self.buf.push(0xD3);
403        self.buf.push(0b1100_0000 | (4 << 3) | dst.lo3());
404    }
405
406    /// `sar dst, cl` (REX.W D3 /7) — arithmetic shift right.
407    pub fn sar_cl(&mut self, dst: Reg) {
408        self.rex(true, 0, 0, dst.hi());
409        self.buf.push(0xD3);
410        self.buf.push(0b1100_0000 | (7 << 3) | dst.lo3());
411    }
412
413    /// `shr dst, cl` (REX.W D3 /5) — LOGICAL (unsigned) shift right (zero-fill).
414    pub fn shr_cl(&mut self, dst: Reg) {
415        self.rex(true, 0, 0, dst.hi());
416        self.buf.push(0xD3);
417        self.buf.push(0b1100_0000 | (5 << 3) | dst.lo3());
418    }
419
420    /// `rol dst, cl` (`D3 /0`). A 32-bit destination write zero-extends.
421    pub fn rol_cl(&mut self, dst: Reg, width32: bool) {
422        self.rex(!width32, 0, 0, dst.hi());
423        self.buf.push(0xD3);
424        self.buf.push(0b1100_0000 | dst.lo3());
425    }
426
427    /// `ror dst, cl` (`D3 /1`). A 32-bit destination write zero-extends.
428    pub fn ror_cl(&mut self, dst: Reg, width32: bool) {
429        self.rex(!width32, 0, 0, dst.hi());
430        self.buf.push(0xD3);
431        self.buf.push(0b1100_0000 | (1 << 3) | dst.lo3());
432    }
433
434    /// `cmp a, b` (REX.W 39 /r — `a - b`, sets flags).
435    pub fn cmp_rr(&mut self, a: Reg, b: Reg) {
436        self.rex(true, b.hi(), 0, a.hi());
437        self.buf.push(0x39);
438        self.modrm_reg(b, a);
439    }
440
441    /// `cqo` (REX.W 99): sign-extend rax into rdx:rax (for idiv).
442    pub fn cqo(&mut self) {
443        self.buf.push(0x48);
444        self.buf.push(0x99);
445    }
446
447    /// `idiv src` (REX.W F7 /7): rdx:rax / src → quotient rax, remainder rdx.
448    pub fn idiv_r(&mut self, src: Reg) {
449        self.rex(true, 0, 0, src.hi());
450        self.buf.push(0xF7);
451        self.buf.push(0b1100_0000 | (7 << 3) | src.lo3());
452    }
453
454    /// `mul src` (REX.W F7 /4): UNSIGNED rdx:rax = rax * src — the high 64 bits
455    /// of the 128-bit product land in rdx, the low in rax. The magic-reciprocal
456    /// high-multiply primitive.
457    pub fn mul_r(&mut self, src: Reg) {
458        self.rex(true, 0, 0, src.hi());
459        self.buf.push(0xF7);
460        self.buf.push(0b1100_0000 | (4 << 3) | src.lo3());
461    }
462
463    /// `shr dst, imm` (REX.W C1 /5 ib) — LOGICAL (zero-filling) shift right by a
464    /// constant. Distinct from `sar` (`/7`, arithmetic/sign-filling): the
465    /// unsigned magic reciprocal shifts unsigned high-product bits, so it must
466    /// zero-fill.
467    pub fn shr_ri(&mut self, dst: Reg, imm: u8) {
468        self.rex(true, 0, 0, dst.hi());
469        self.buf.push(0xC1);
470        self.buf.push(0b1100_0000 | (5 << 3) | dst.lo3());
471        self.buf.push(imm);
472    }
473
474    /// `test a, a` (REX.W 85 /r) — sets ZF when `a == 0`.
475    pub fn test_rr(&mut self, a: Reg, b: Reg) {
476        self.rex(true, b.hi(), 0, a.hi());
477        self.buf.push(0x85);
478        self.modrm_reg(b, a);
479    }
480
481    // ---------------------------------------------------------------
482    // SSE2 scalar-double (f64) encodings for the XMM register class.
483    //
484    // Every scalar-double op is `<prefix> 0F <op> /r` where the prefix is F2
485    // for the SD (scalar-double) arithmetic forms, 66 for the abs-mask/move
486    // bit ops, F3 for sqrt's reciprocal sibling (we only need F2 0F 51 for
487    // sqrtsd). The REX bits route the high registers (xmm8..xmm15). Memory
488    // operands reuse the GP `modrm_mem` (base + disp32, SIB for rsp/r12) — the
489    // ModRM `reg` field there is taken from a GP `Reg`, so for XMM memory ops
490    // we hand-emit the ModRM with the XMM reg in the reg field.
491    // ---------------------------------------------------------------
492
493    /// REX for an SSE2 reg-reg op `xmm_r OP xmm_m` (reg field = `r`, rm = `m`).
494    /// Emitted only when any high bit is set (the SSE2 forms have no mandatory
495    /// REX.W); a spurious zero REX would be harmless but we keep bytes minimal.
496    fn sse_rex_rr(&mut self, r: Xmm, m: Xmm) {
497        if r.hi() != 0 || m.hi() != 0 {
498            self.buf.push(0x40 | (r.hi() << 2) | m.hi());
499        }
500    }
501
502    /// ModRM for register-direct between two XMM regs.
503    fn modrm_xmm_rr(&mut self, r: Xmm, m: Xmm) {
504        self.buf.push(0b1100_0000 | (r.lo3() << 3) | m.lo3());
505    }
506
507    /// A scalar-double reg-reg op: `<prefix> [REX] 0F <op> /r`, dst is the reg
508    /// field (read-modify-write: `dst = dst OP src`).
509    fn sse_sd_rr(&mut self, prefix: u8, op: u8, dst: Xmm, src: Xmm) {
510        self.buf.push(prefix);
511        self.sse_rex_rr(dst, src);
512        self.buf.push(0x0F);
513        self.buf.push(op);
514        self.modrm_xmm_rr(dst, src);
515    }
516
517    /// A scalar-double reg-MEM op: `<prefix> [REX] 0F <op> /r` with a
518    /// `[base+disp32]` memory operand and the XMM reg in the reg field.
519    fn sse_sd_rm(&mut self, prefix: u8, op: u8, dst: Xmm, base: Reg, disp: i32) {
520        self.buf.push(prefix);
521        // REX: R = dst.hi(), B = base.hi().
522        if dst.hi() != 0 || base.hi() != 0 {
523            self.buf.push(0x40 | (dst.hi() << 2) | base.hi());
524        }
525        self.buf.push(0x0F);
526        self.buf.push(op);
527        let rm = base.lo3();
528        self.buf.push(0b1000_0000 | (dst.lo3() << 3) | rm);
529        if rm == 0b100 {
530            self.buf.push(0b0000_0000 | (0b100 << 3) | rm);
531        }
532        self.buf.extend_from_slice(&disp.to_le_bytes());
533    }
534
535    /// `movsd xmm, [base+disp]` (F2 0F 10 /r) — load an f64 from the frame.
536    pub fn movsd_rm(&mut self, dst: Xmm, base: Reg, disp: i32) {
537        self.sse_sd_rm(0xF2, 0x10, dst, base, disp);
538    }
539    /// `movsd [base+disp], xmm` (F2 0F 11 /r) — store an f64 to the frame.
540    pub fn movsd_mr(&mut self, base: Reg, disp: i32, src: Xmm) {
541        self.sse_sd_rm(0xF2, 0x11, src, base, disp);
542    }
543    /// `movsd dst, src` (F2 0F 10 /r) — XMM→XMM scalar-double copy.
544    pub fn movsd_rr(&mut self, dst: Xmm, src: Xmm) {
545        if dst == src {
546            return;
547        }
548        self.sse_sd_rr(0xF2, 0x10, dst, src);
549    }
550    /// `addsd dst, src` (F2 0F 58 /r) — `dst += src`.
551    pub fn addsd_rr(&mut self, dst: Xmm, src: Xmm) {
552        self.sse_sd_rr(0xF2, 0x58, dst, src);
553    }
554    /// `subsd dst, src` (F2 0F 5C /r) — `dst -= src`.
555    pub fn subsd_rr(&mut self, dst: Xmm, src: Xmm) {
556        self.sse_sd_rr(0xF2, 0x5C, dst, src);
557    }
558    /// `mulsd dst, src` (F2 0F 59 /r) — `dst *= src`.
559    pub fn mulsd_rr(&mut self, dst: Xmm, src: Xmm) {
560        self.sse_sd_rr(0xF2, 0x59, dst, src);
561    }
562    /// `divsd dst, src` (F2 0F 5E /r) — `dst /= src`.
563    pub fn divsd_rr(&mut self, dst: Xmm, src: Xmm) {
564        self.sse_sd_rr(0xF2, 0x5E, dst, src);
565    }
566    /// `sqrtsd dst, src` (F2 0F 51 /r) — `dst = sqrt(src)`.
567    pub fn sqrtsd_rr(&mut self, dst: Xmm, src: Xmm) {
568        self.sse_sd_rr(0xF2, 0x51, dst, src);
569    }
570
571    // ---- Packed double (SIMD, 2-wide) ----------------------------------------
572    // Each instruction below shares the scalar-double encoder helpers but swaps
573    // the `F2` (scalar) prefix for `66` (packed). A packed op computes BOTH f64
574    // lanes with the SAME IEEE-754 rounding as the scalar form, so each lane is
575    // bit-identical to the corresponding scalar op — the soundness invariant that
576    // makes auto-vectorization a LEGAL bit-exact lever (unlike FMA, which fuses
577    // two roundings into one and is therefore NOT bit-exact).
578
579    /// `movupd xmm, [base+disp]` (66 0F 10 /r) — load an UNALIGNED 128-bit pair.
580    /// Unaligned (not `movapd`) because frame/array slots carry no 16-byte
581    /// alignment guarantee; the unaligned form is penalty-free on modern cores
582    /// when the access happens to be aligned.
583    pub fn movupd_rm(&mut self, dst: Xmm, base: Reg, disp: i32) {
584        self.sse_sd_rm(0x66, 0x10, dst, base, disp);
585    }
586    /// `movupd [base+disp], xmm` (66 0F 11 /r) — store an unaligned 128-bit pair.
587    pub fn movupd_mr(&mut self, base: Reg, disp: i32, src: Xmm) {
588        self.sse_sd_rm(0x66, 0x11, src, base, disp);
589    }
590    /// `movupd dst, src` (66 0F 10 /r) — XMM→XMM 128-bit copy (both lanes).
591    pub fn movupd_rr(&mut self, dst: Xmm, src: Xmm) {
592        if dst == src {
593            return;
594        }
595        self.sse_sd_rr(0x66, 0x10, dst, src);
596    }
597    /// `addpd dst, src` (66 0F 58 /r) — `dst[lane] += src[lane]` for both lanes.
598    pub fn addpd_rr(&mut self, dst: Xmm, src: Xmm) {
599        self.sse_sd_rr(0x66, 0x58, dst, src);
600    }
601    /// `subpd dst, src` (66 0F 5C /r) — `dst[lane] -= src[lane]` for both lanes.
602    pub fn subpd_rr(&mut self, dst: Xmm, src: Xmm) {
603        self.sse_sd_rr(0x66, 0x5C, dst, src);
604    }
605    /// `mulpd dst, src` (66 0F 59 /r) — `dst[lane] *= src[lane]` for both lanes.
606    pub fn mulpd_rr(&mut self, dst: Xmm, src: Xmm) {
607        self.sse_sd_rr(0x66, 0x59, dst, src);
608    }
609    /// `cmppd dst, src, pred` (66 0F C2 /r ib) — per-lane compare; each lane is
610    /// set to all-ones (true) or all-zero (false). `pred`: 0=EQ 1=LT 2=LE 3=UNORD
611    /// 4=NEQ 5=NLT 6=NLE 7=ORD. The mandelbrot escape test uses LE (2).
612    pub fn cmppd_rr(&mut self, dst: Xmm, src: Xmm, pred: u8) {
613        self.buf.push(0x66);
614        self.sse_rex_rr(dst, src);
615        self.buf.push(0x0F);
616        self.buf.push(0xC2);
617        self.modrm_xmm_rr(dst, src);
618        self.buf.push(pred);
619    }
620    /// `movmskpd r32/64, xmm` (66 0F 50 /r) — extract the two lane SIGN bits into
621    /// a GP register (bit0=lane0, bit1=lane1). After a cmppd, a true lane's sign
622    /// bit is 1, so this yields the active-lane bitmask the loop-exit test reads.
623    /// The GP dst is the reg field, the XMM src the rm field.
624    pub fn movmskpd(&mut self, dst: Reg, src: Xmm) {
625        self.buf.push(0x66);
626        let rex = 0x40 | (dst.hi() << 2) | src.hi();
627        if rex != 0x40 {
628            self.buf.push(rex);
629        }
630        self.buf.push(0x0F);
631        self.buf.push(0x50);
632        self.buf.push(0b1100_0000 | (dst.lo3() << 3) | src.lo3());
633    }
634    /// `andpd dst, src` (66 0F 54 /r) — bitwise AND of both 128-bit lanes. The
635    /// branchless counter masks a packed 1.0 by the escape mask.
636    pub fn andpd_rr(&mut self, dst: Xmm, src: Xmm) {
637        self.sse_sd_rr(0x66, 0x54, dst, src);
638    }
639    /// `andnpd dst, src` (66 0F 55 /r) — `dst = (NOT dst) AND src` (128-bit).
640    pub fn andnpd_rr(&mut self, dst: Xmm, src: Xmm) {
641        self.sse_sd_rr(0x66, 0x55, dst, src);
642    }
643    /// `orpd dst, src` (66 0F 56 /r) — bitwise OR of both 128-bit lanes.
644    pub fn orpd_rr(&mut self, dst: Xmm, src: Xmm) {
645        self.sse_sd_rr(0x66, 0x56, dst, src);
646    }
647    /// `xorpd dst, src` (66 0F 57 /r) — bitwise XOR of both 128-bit lanes.
648    pub fn xorpd_rr(&mut self, dst: Xmm, src: Xmm) {
649        self.sse_sd_rr(0x66, 0x57, dst, src);
650    }
651    /// `divpd dst, src` (66 0F 5E /r) — `dst[lane] /= src[lane]` for both lanes.
652    pub fn divpd_rr(&mut self, dst: Xmm, src: Xmm) {
653        self.sse_sd_rr(0x66, 0x5E, dst, src);
654    }
655    /// `sqrtpd dst, src` (66 0F 51 /r) — `dst[lane] = sqrt(src[lane])` both lanes.
656    pub fn sqrtpd_rr(&mut self, dst: Xmm, src: Xmm) {
657        self.sse_sd_rr(0x66, 0x51, dst, src);
658    }
659    /// `ucomisd a, b` (66 0F 2E /r) — unordered f64 compare setting CF/ZF/PF.
660    /// NaN (unordered) sets ZF=CF=PF=1, so the seta/setae/jbe family used by the
661    /// backend folds the unordered case to FALSE, matching the kernel's IEEE
662    /// relations (NaN compares false).
663    pub fn ucomisd_rr(&mut self, a: Xmm, b: Xmm) {
664        self.buf.push(0x66);
665        self.sse_rex_rr(a, b);
666        self.buf.push(0x0F);
667        self.buf.push(0x2E);
668        self.modrm_xmm_rr(a, b);
669    }
670    /// `cvtsi2sd xmm, r64` (F2 REX.W 0F 2A /r) — signed i64 → f64 (the kernel's
671    /// IntToFloat). The GP source is the rm field, the XMM dst the reg field.
672    pub fn cvtsi2sd(&mut self, dst: Xmm, src: Reg) {
673        self.buf.push(0xF2);
674        // REX.W=1, R = dst.hi(), B = src.hi().
675        self.buf.push(0x48 | (dst.hi() << 2) | src.hi());
676        self.buf.push(0x0F);
677        self.buf.push(0x2A);
678        self.buf.push(0b1100_0000 | (dst.lo3() << 3) | src.lo3());
679    }
680    /// `roundsd dst, src, imm8` (66 0F 3A 0B /r ib) — round `src` to an integral f64 by `imm8` mode
681    /// (bit0-1: 0=nearest-even, 1=floor/−∞, 2=ceil/+∞, 3=trunc/toward-0; bit3 set = suppress inexact).
682    /// SSE4.1; both operands XMM (dst = reg field, src = rm field). Guard the lowering on the CPU feature.
683    pub fn roundsd_rri(&mut self, dst: Xmm, src: Xmm, imm: u8) {
684        self.buf.push(0x66);
685        self.sse_rex_rr(dst, src);
686        self.buf.push(0x0F);
687        self.buf.push(0x3A);
688        self.buf.push(0x0B);
689        self.modrm_xmm_rr(dst, src);
690        self.buf.push(imm);
691    }
692    /// `cvttsd2si r64, xmm` (F2 REX.W 0F 2C /r) — convert f64 → i64 by TRUNCATION toward zero (the `as
693    /// i64` cast; saturating/out-of-range gives i64::MIN). GP dst = reg field, XMM src = rm field.
694    pub fn cvttsd2si_rr(&mut self, dst: Reg, src: Xmm) {
695        self.buf.push(0xF2);
696        // REX.W=1, R = dst.hi() (GP reg field), B = src.hi() (XMM rm field).
697        self.buf.push(0x48 | (dst.hi() << 2) | src.hi());
698        self.buf.push(0x0F);
699        self.buf.push(0x2C);
700        self.buf.push(0b1100_0000 | (dst.lo3() << 3) | src.lo3());
701    }
702    /// `movq xmm, r64` (66 REX.W 0F 6E /r) — bit-copy a GP register into an XMM
703    /// (no conversion). The GP src is the rm field, the XMM dst the reg field.
704    pub fn movq_xr(&mut self, dst: Xmm, src: Reg) {
705        self.buf.push(0x66);
706        self.buf.push(0x48 | (dst.hi() << 2) | src.hi());
707        self.buf.push(0x0F);
708        self.buf.push(0x6E);
709        self.buf.push(0b1100_0000 | (dst.lo3() << 3) | src.lo3());
710    }
711    /// `movq r64, xmm` (66 REX.W 0F 7E /r) — bit-copy an XMM into a GP register.
712    /// The XMM src is the reg field, the GP dst the rm field.
713    pub fn movq_rx(&mut self, dst: Reg, src: Xmm) {
714        self.buf.push(0x66);
715        self.buf.push(0x48 | (src.hi() << 2) | dst.hi());
716        self.buf.push(0x0F);
717        self.buf.push(0x7E);
718        self.buf.push(0b1100_0000 | (src.lo3() << 3) | dst.lo3());
719    }
720
721    /// `movzx dst, byte [base + disp]` (REX.W 0F B6 /r) — load ONE byte from
722    /// memory and zero-extend it into the 64-bit `dst`. The byte-array
723    /// (`Seq of Bool`) element load: `frame[D] = buf[i-1] as i64` over 1-byte
724    /// elements, where the loaded `u8` widens to a non-negative i64 (0..=255) —
725    /// bit-identical to the `logos_stencil_arrldb` `*ptr as i64`.
726    pub fn movzx_rm8(&mut self, dst: Reg, base: Reg, disp: i32) {
727        self.rex(true, dst.hi(), 0, base.hi());
728        self.buf.push(0x0F);
729        self.buf.push(0xB6);
730        self.modrm_mem(dst, base, disp);
731    }
732
733    /// `mov byte [base + disp], src8` (88 /r) — store the LOW byte of `src` to
734    /// memory. The byte-array element store; the value is pre-normalized to 0/1
735    /// by the caller (matching `logos_stencil_arrstb`'s `(v != 0) as u8`), so
736    /// only the low byte is written. A REX prefix is emitted whenever any high
737    /// register bit is set OR `src` is one of `spl/bpl/sil/dil` (rsp..rdi,
738    /// encodings 4..7) — those low-byte registers are addressable ONLY with a
739    /// REX prefix present (without REX the encoding means `ah/ch/dh/bh`).
740    pub fn mov_mr8(&mut self, base: Reg, disp: i32, src: Reg) {
741        let need_rex = src.hi() != 0 || base.hi() != 0 || ((src as u8) & 0b100) != 0;
742        if need_rex {
743            self.buf.push(0x40 | (src.hi() << 2) | base.hi());
744        }
745        self.buf.push(0x88);
746        self.modrm_mem(src, base, disp);
747    }
748
749    /// `movsxd dst, dword [base + disp]` (REX.W 63 /r) — load FOUR bytes from
750    /// memory and SIGN-extend them into the 64-bit `dst`. The half-width
751    /// (`IntsI32`) array element load: `frame[D] = buf[i-1] as i64` over 4-byte
752    /// `i32` elements — bit-identical to `logos_stencil_arrld_i32`'s
753    /// `*(i32*)ptr as i64`.
754    pub fn movsxd_rm(&mut self, dst: Reg, base: Reg, disp: i32) {
755        self.rex(true, dst.hi(), 0, base.hi());
756        self.buf.push(0x63);
757        self.modrm_mem(dst, base, disp);
758    }
759
760    /// `mov dword [base + disp], src32` (89 /r, NO REX.W) — store the LOW 4 bytes
761    /// of `src` to memory. The half-width (`IntsI32`) element store: the value is
762    /// truncated to `i32` (lossless under the narrowing proof) — bit-identical to
763    /// `logos_stencil_arrst_i32`'s `*(i32*)ptr = v as i32`. A REX prefix (without
764    /// the W bit) is emitted only for the high-register extension bits.
765    pub fn mov_mr32(&mut self, base: Reg, disp: i32, src: Reg) {
766        if src.hi() != 0 || base.hi() != 0 {
767            self.buf.push(0x40 | (src.hi() << 2) | base.hi());
768        }
769        self.buf.push(0x89);
770        self.modrm_mem(src, base, disp);
771    }
772
773    /// `setcc dst8` — set the LOW byte of `dst` to 0/1 from the flags (no
774    /// zero-extension of the upper bits). A REX prefix (even empty) makes
775    /// `spl/bpl/sil/dil` and `r8b..r15b` addressable; emit REX with B = dst.hi().
776    /// Used to normalize a byte-array store value to 0/1 in the same register
777    /// whose low byte is then stored by [`Asm::mov_mr8`].
778    pub fn setcc8(&mut self, cond: Cond, dst: Reg) {
779        self.buf.push(0x40 | dst.hi());
780        self.buf.push(0x0F);
781        self.buf.push(0x90 | cond.cc());
782        self.buf.push(0b1100_0000 | dst.lo3());
783    }
784
785    /// `setcc dst8` then `movzx dst, dst8` — materialize a 0/1 from flags.
786    /// `dst` must be a register whose low byte is addressable under REX
787    /// (all of rax..r15 are with a REX prefix).
788    pub fn setcc_movzx(&mut self, cond: Cond, dst: Reg) {
789        // setcc r/m8: 0F (90+cc) /0. A REX prefix (even empty) makes spl/bpl/
790        // sil/dil and r8b..r15b addressable; emit REX with B = dst.hi().
791        self.buf.push(0x40 | dst.hi());
792        self.buf.push(0x0F);
793        self.buf.push(0x90 | cond.cc());
794        self.buf.push(0b1100_0000 | dst.lo3());
795        // movzx dst, dst8 (REX.W 0F B6 /r).
796        self.rex(true, dst.hi(), 0, dst.hi());
797        self.buf.push(0x0F);
798        self.buf.push(0xB6);
799        self.modrm_reg(dst, dst);
800    }
801
802    /// `jmp label` (E9 cd, rel32 patched in `resolve`).
803    pub fn jmp(&mut self, label: LabelId) {
804        self.buf.push(0xE9);
805        let site = self.buf.len();
806        self.buf.extend_from_slice(&[0, 0, 0, 0]);
807        self.fixups.push(Fixup::Rel32 { site, label });
808    }
809
810    /// `jcc label` (0F 80+cc cd, rel32 patched in `resolve`).
811    pub fn jcc(&mut self, cond: Cond, label: LabelId) {
812        self.buf.push(0x0F);
813        self.buf.push(0x80 | cond.cc());
814        let site = self.buf.len();
815        self.buf.extend_from_slice(&[0, 0, 0, 0]);
816        self.fixups.push(Fixup::Rel32 { site, label });
817    }
818
819    /// `push reg` (50+rd, with REX.B for r8..r15).
820    pub fn push(&mut self, r: Reg) {
821        if r.hi() == 1 {
822            self.buf.push(0x41);
823        }
824        self.buf.push(0x50 + r.lo3());
825    }
826
827    /// `pop reg` (58+rd, with REX.B for r8..r15).
828    pub fn pop(&mut self, r: Reg) {
829        if r.hi() == 1 {
830            self.buf.push(0x41);
831        }
832        self.buf.push(0x58 + r.lo3());
833    }
834
835    /// `ret` (C3).
836    pub fn ret(&mut self) {
837        self.buf.push(0xC3);
838    }
839
840    /// Resolve all label fixups against bound positions and return the final
841    /// machine code. Panics if a referenced label was never bound (a backend
842    /// bug — every label this module creates is bound before `resolve`).
843    pub fn resolve(mut self) -> Vec<u8> {
844        for f in &self.fixups {
845            match *f {
846                Fixup::Rel32 { site, label } => {
847                    let target = self.label_pos[label.0];
848                    assert_ne!(target, usize::MAX, "unbound label {label:?}");
849                    let rel = (target as i64) - (site as i64 + 4);
850                    let rel32 = rel as i32;
851                    self.buf[site..site + 4].copy_from_slice(&rel32.to_le_bytes());
852                }
853            }
854        }
855        self.buf
856    }
857}
858
859#[cfg(test)]
860#[path = "../../logicaffeine_tests/unit/logicaffeine_forge/x64asm/tests.rs"]
861mod tests;