Baseline: tree as shared

This commit is contained in:
alexm committed 2026-10-05 03:03:38 +00:00
commit 659c03bbf8
1471 files changed
+990535

No files matched your search

+254
View File
@@ -0,0 +1,254 @@
// Scalar double arithmetic, the parity flag, shld/shrd, and the compiler's constant pool.
import test from 'node:test';
import assert from 'node:assert/strict';
import { parseAsm, runAsmProgram } from '../dist/services/asm.js';
import { rflagsValue } from '../dist/engines/asm86/interp.js';
import { intelLine, forSimulator, simulatorSetup } from '../dist/mojo/att.js';
import { listingFunctions } from '../dist/services/godbolt.js';
const dv = new DataView(new ArrayBuffer(8));
const M64 = 0xffffffffffffffffn;
const bits = (x) => { dv.setFloat64(0, x); return dv.getBigUint64(0); };
const dbl = (b) => { dv.setBigUint64(0, BigInt(b) & M64); return dv.getFloat64(0); };
const le = (v) => Array.from({ length: 8 }, (_, i) => Number((BigInt(v) >> BigInt(8 * i)) & 0xffn));
const lo = (v) => BigInt(v) & M64;
function run(src, setup = '') {
const p = parseAsm(src);
assert.ok(p.ok, p.diagnostics?.map((d) => d.message).join('; '));
const r = runAsmProgram(p, { setup, machine: 'teaching', maxSteps: 300 });
return { s: r.states[r.count], error: r.error?.message };
}
const load = (reg, x) => [`mov rax, 0x${bits(x).toString(16)}`, `movq ${reg}, rax`];
const two = (op, a, b) => run([...load('xmm0', a), ...load('xmm1', b), `${op} xmm0, xmm1`].join('\n')).s.regs.xmm0;
const three = (op, a, b) => run([...load('xmm1', a), ...load('xmm2', b), `${op} xmm0, xmm1, xmm2`].join('\n')).s.regs.xmm0;
test('arithmetic is IEEE binary64, rounded to nearest even', () => {
assert.equal(lo(two('addsd', 0.1, 0.2)), 0x3FD3333333333334n);
assert.equal(lo(two('addsd', 0.1, 0.2)), bits(0.1 + 0.2));
assert.equal(dbl(lo(two('divsd', 1, 3))), 1 / 3);
assert.equal(dbl(lo(two('mulsd', 1e200, 1e200))), Infinity, 'overflow gives infinity');
assert.equal(dbl(lo(three('vsubsd', 4, 3))), 1);
assert.equal(dbl(lo(three('vdivsd', 4, 3))), 4 / 3);
const r = run([...load('xmm1', 2), 'vsqrtsd xmm0, xmm1, xmm1'].join('\n')).s.regs.xmm0;
assert.equal(dbl(lo(r)), Math.SQRT2);
});
test('special values: division by zero, invalid operations, NaN propagation', () => {
assert.equal(dbl(lo(two('divsd', 1, 0))), Infinity);
assert.equal(dbl(lo(two('divsd', -1, 0))), -Infinity);
assert.equal(lo(two('divsd', 0, 0)), 0xFFF8000000000000n, '0/0 is the default NaN');
const sq = (x) => lo(run([...load('xmm1', x), 'vsqrtsd xmm0, xmm1, xmm1'].join('\n')).s.regs.xmm0);
assert.equal(sq(-1), 0xFFF8000000000000n);
assert.equal(sq(-0), bits(-0), 'sqrt(-0) is -0');
// a quiet NaN with a payload is kept; a signalling one is quieted; with two NaNs the first operand wins
const nan = (payload) => `mov rax, 0x${payload.toString(16)}\nmovq xmm0, rax`;
const q = run(`${nan(0x7FF8000000000123n)}\n${load('xmm1', 1).join('\n')}\naddsd xmm0, xmm1`).s.regs.xmm0;
assert.equal(lo(q), 0x7FF8000000000123n);
const sig = run(`${nan(0x7FF0000000000001n)}\n${load('xmm1', 1).join('\n')}\naddsd xmm0, xmm1`).s.regs.xmm0;
assert.equal(lo(sig), 0x7FF8000000000001n);
const both = run(`${nan(0x7FF8000000000001n)}\nmov rax, 0x7FF8000000000002\nmovq xmm1, rax\naddsd xmm0, xmm1`).s.regs.xmm0;
assert.equal(lo(both), 0x7FF8000000000001n);
});
test('cvtsi2sd rounds to nearest even and reads the integer width asked for', () => {
const cvt = (setup, line) => lo(run(`${setup}\n${line}`).s.regs.xmm0);
assert.equal(cvt('mov rax, 9007199254740993', 'cvtsi2sd xmm0, rax'), bits(9007199254740992), '2^53+1 ties to even');
assert.equal(cvt('mov rax, 0x8000000000000000', 'cvtsi2sd xmm0, rax'), bits(-9223372036854775808));
assert.equal(cvt('mov eax, 0xffffffff', 'cvtsi2sd xmm0, eax'), bits(-1), '32-bit source is signed');
});
test('upper halves: the VEX forms copy from the first source, the SSE forms keep the destination', () => {
// 16 bytes at 0x1000: low half 5.0's bits, high half 0x1111; at 0x1010: low 7.0's bits, high 0x2222
const mem = `memory 0x1000 bytes ${[...le(bits(5)), ...le(0x1111n), ...le(bits(7)), ...le(0x2222n)].map((b) => '0x' + b.toString(16)).join(' ')}`;
const prog = (body) => run(['movdqu xmm0, xmmword ptr [0x1000]', 'movdqu xmm1, xmmword ptr [0x1010]', body].join('\n'), mem).s.regs.xmm0;
const hi = (v) => v >> 64n;
assert.equal(hi(prog('vaddsd xmm0, xmm1, xmm1')), 0x2222n, 'vaddsd takes the upper half of its first source');
assert.equal(dbl(lo(prog('vaddsd xmm0, xmm1, xmm1'))), 14);
assert.equal(hi(prog('addsd xmm0, xmm1')), 0x1111n, 'addsd keeps the destination\u2019s');
assert.equal(hi(prog('movsd xmm0, xmm1')), 0x1111n, 'register movsd merges the low half');
assert.equal(dbl(lo(prog('movsd xmm0, xmm1'))), 7);
assert.equal(hi(prog('movsd xmm0, qword ptr [0x1010]')), 0n, 'a movsd load clears the upper half');
assert.equal(hi(prog('vmovsd xmm0, xmm0, xmm1')), 0x1111n, 'three-operand vmovsd keeps the first source\u2019s upper half');
assert.equal(dbl(lo(prog('vmovsd xmm0, xmm0, xmm1'))), 7);
});
const flagsAfter = (a, b, op = 'ucomisd') => run([...load('xmm0', a), ...load('xmm1', b), `${op} xmm0, xmm1`].join('\n')).s.flags;
const pick = (f) => ['ZF', 'PF', 'CF'].map((k) => (f[k] ? 1 : 0)).join('');
test('ucomisd and comisd: less sets CF, equal sets ZF, unordered sets all three', () => {
for (const op of ['ucomisd', 'comisd', 'vucomisd', 'vcomisd']) {
assert.equal(pick(flagsAfter(1, 2, op)), '001', `${op} less`);
assert.equal(pick(flagsAfter(2, 1, op)), '000', `${op} greater`);
assert.equal(pick(flagsAfter(2, 2, op)), '100', `${op} equal`);
assert.equal(pick(flagsAfter(NaN, 1, op)), '111', `${op} unordered`);
}
assert.equal(pick(flagsAfter(0, -0)), '100', '+0 equals -0');
const f = flagsAfter(NaN, 1);
assert.equal(f.OF, false);
assert.equal(f.SF, false);
});
test('conditions after a compare: ja, jb, je, jp and setp', () => {
const took = (a, b, j) => run([...load('xmm0', a), ...load('xmm1', b), 'ucomisd xmm0, xmm1', 'mov rcx, 0', `${j} yes`, 'jmp done', 'yes: mov rcx, 1', 'done: nop'].join('\n')).s.regs.rcx;
assert.equal(took(2, 1, 'ja'), 1n);
assert.equal(took(1, 2, 'ja'), 0n);
assert.equal(took(1, 2, 'jb'), 1n);
assert.equal(took(3, 3, 'je'), 1n);
assert.equal(took(NaN, 3, 'jp'), 1n);
assert.equal(took(3, 3, 'jp'), 0n);
assert.equal(took(NaN, 3, 'jnp'), 0n);
const set = run([...load('xmm0', NaN), ...load('xmm1', 1), 'ucomisd xmm0, xmm1', 'setp al', 'setnp bl'].join('\n')).s.regs;
assert.equal(set.rax & 0xffn, 1n);
assert.equal(set.rbx & 0xffn, 0n);
});
test('the parity flag: set by logic, arithmetic and shifts; left alone by rotates; cleared by popcnt', () => {
const pf = (src) => run(src).s.flags.PF;
assert.equal(pf('mov rax, 3\ntest rax, rax'), true, '0b11 has two set bits');
assert.equal(pf('mov rax, 1\ntest rax, rax'), false);
assert.equal(pf('mov rax, 5\nxor rax, rax'), true, 'zero has even parity');
assert.equal(pf('mov rax, 1\nshl rax, 1'), false);
assert.equal(pf('mov rax, 2\ninc rax'), true);
assert.equal(pf('mov rax, 0\ntest rax, rax\nrol rax, 1'), true, 'rol does not touch PF');
assert.equal(pf('mov rax, 0\ntest rax, rax\npopcnt rbx, rax'), false);
assert.equal((rflagsValue({ ZF: false, SF: false, CF: false, OF: false, PF: true }) >> 2n) & 1n, 1n, 'PF is bit 2 of RFLAGS');
assert.equal((rflagsValue({ ZF: false, SF: false, CF: false, OF: false, PF: false }) >> 2n) & 1n, 0n);
});
test('shld and shrd shift in bits from the second register', () => {
const r = (src) => run(src, 'memory 0x1000 zero 16').s;
assert.equal(r('mov rax, 0xff\nmov rsi, 0xf000000000000000\nshld rax, rsi, 4').regs.rax, 0xfffn);
assert.equal(r('mov rbx, 0xff\nmov rdi, 0xf\nshrd rbx, rdi, 4').regs.rbx, 0xf00000000000000fn);
assert.equal(r('mov rax, 1\nmov rcx, 4\nmov rsi, 0xf000000000000000\nshld rax, rsi, cl').regs.rax, 0x1fn, 'count in cl');
// count zero changes nothing, flags included
const z = r('mov rax, 3\ntest rax, rax\nmov rsi, 1\nshld rax, rsi, 0');
assert.equal(z.regs.rax, 3n);
assert.equal(z.flags.PF, true);
// 32-bit counts are masked to five bits: 33 acts as 1
assert.equal(r('mov eax, 1\nmov esi, 0x80000000\nshld eax, esi, 33').regs.rax, 3n);
// the same register on both sides is a rotate
assert.equal(r('mov rax, 0x8000000000000001\nshld rax, rax, 1').regs.rax, 3n);
// carry is the last bit shifted out of the destination
assert.equal(r('mov rax, 0x8000000000000000\nmov rsi, 0\nshld rax, rsi, 1').flags.CF, true);
// a memory destination
assert.equal(r('mov qword ptr [0x1000], 0xff\nmov rsi, 0xf000000000000000\nshld qword ptr [0x1000], rsi, 4\nmov rax, qword ptr [0x1000]').regs.rax, 0xfffn);
});
test('shld refuses a 16-bit operand and nonsense forms', () => {
for (const bad of ['shld ax, bx, 1', 'vaddsd xmm0, rax', 'cvtsi2sd rax, xmm0', 'ucomisd rax, rbx', 'sqrtsd xmm0']) {
const p = parseAsm(bad);
const failed = !p.ok || (() => { const r = runAsmProgram(p, { setup: '', machine: 'teaching', maxSteps: 10 }); return !!r.error; })();
assert.ok(failed, bad);
}
});
test('AT&T spellings of the new instructions become Intel', () => {
const t = (att) => intelLine(att, new Map());
assert.equal(t('vcvtsi2sd %rax, %xmm0, %xmm0'), 'vcvtsi2sd xmm0, xmm0, rax');
assert.equal(t('vcvtsi2sdl (%rax), %xmm0, %xmm0'), 'vcvtsi2sd xmm0, xmm0, dword ptr [rax]');
assert.equal(t('vcvtsi2sdq 8(%rsp), %xmm1, %xmm1'), 'vcvtsi2sd xmm1, xmm1, qword ptr [rsp + 8]');
assert.equal(t('vmovsd 8(%rsp), %xmm0'), 'vmovsd xmm0, [rsp + 8]');
assert.equal(t('shldq $3, %rsi, %rax'), 'shld rax, rsi, 3');
assert.equal(t('shldq %cl, %rsi, %rax'), 'shld rax, rsi, cl');
assert.equal(t('setp %al'), 'setp al');
assert.equal(t('vdivsd .LCPI0_0+8(%rip), %xmm0, %xmm0'), 'vdivsd xmm0, xmm0, [rip + .LCPI0_0 + 8]');
});
// LLVM's output for `fn scale(n: Int) -> Float64: return Float64(n) / 1_000_000.0`, trimmed to what matters.
const LISTING = [
'"example::scale(::Int)":',
' vcvtsi2sd %rdi, %xmm0, %xmm0',
' vdivsd .LCPI0_0(%rip), %xmm0, %xmm0',
' retq',
'.LCPI0_0:',
' .quad 0x412e848000000000 # double 1.0E+6',
'.LCPI0_1:',
' .quad 0x4000000000000000',
' .quad 0x4008000000000000',
].map((text, i) => ({ text, line: i === 1 ? 3 : null }));
test('a constant pool in the listing is placed in memory and the code points at it', () => {
const fns = listingFunctions(LISTING);
const fn = fns.find((f) => f.kind === 'user');
assert.ok(fn, 'the user function is found');
const sim = forSimulator(fns, fn);
assert.doesNotMatch(sim.source, /LCPI/, 'no constant-pool label is left in the code');
assert.equal(sim.data.length, 1, 'only the blocks the code uses are placed');
assert.match(sim.data[0], /^memory 0x6000 bytes 0x00 0x00 0x00 0x00 0x80 0x84 0x2e 0x41 /);
const setup = simulatorSetup(fn, sim.data).replace('rdi = 0', 'rdi = 5000000');
const p = parseAsm(sim.source);
assert.ok(p.ok, p.diagnostics?.[0]?.message);
const r = runAsmProgram(p, { setup, machine: 'teaching', maxSteps: 50 });
assert.ok(!r.error, String(r.error?.message));
assert.equal(dbl(lo(r.states[r.count].regs.xmm0)), 5);
});
test('a constant block with a symbol in it is not placed, so the instruction using it is refused as before', () => {
const fns = listingFunctions([
{ text: '"example::f(::Int)":' }, { text: ' vmovsd .LJT(%rip), %xmm0' }, { text: ' retq' },
{ text: '.LJT:' }, { text: ' .quad .LBB0_1' },
]);
const sim = forSimulator(fns, fns[0]);
assert.equal(sim.data.length, 0);
});
test('a call to the debugger raise hook (every -O0 loop over a range ends with one) returns instead of stopping the run', () => {
const fns = listingFunctions([
{ text: '"example::count(::Int)":' },
{ text: ' movq %rdi, %rax' },
{ text: ' callq "std::builtin::error::__mojo_debugger_raise_hook()"' },
{ text: ' callq "std::builtin::string::String::__init__()"' },
{ text: ' retq' },
]);
const sim = forSimulator(fns, fns[0]);
assert.deepEqual(sim.refusedCalls, ['std_builtin_string_String___init__'], 'only real library code is refused');
assert.match(sim.source, /std_builtin_error___mojo_debugger_raise_hook:\n\s+ret\b/);
// with the String call removed, the function runs to its ret
const fns2 = listingFunctions([{ text: '"example::count(::Int)":' }, { text: ' movq %rdi, %rax' }, { text: ' callq "std::builtin::error::__mojo_debugger_raise_hook()"' }, { text: ' retq' }]);
const p = parseAsm(forSimulator(fns2, fns2[0]).source);
assert.ok(p.ok, p.diagnostics?.[0]?.message);
const r = runAsmProgram(p, { setup: 'rdi = 285', machine: 'teaching', maxSteps: 50 });
assert.ok(!r.error, String(r.error?.message));
assert.equal(r.states[r.count].regs.rax, 285n);
});
test('read-only strings in every form the listing writes them are placed: .asciz, an empty string as .zero 1, pieces, and an alias', () => {
const lines = [
'"example::f()":',
' leaq static_string_e(%rip), %rax',
' leaq static_string_s(%rip), %rbx',
' leaq static_string_p(%rip), %rcx',
' leaq static_string_a(%rip), %rdx',
' retq',
'static_string_e:', ' .zero 1',
'static_string_s:', ' .asciz " "',
'static_string_p:', ' .ascii "ab"', ' .byte 99, 0',
'static_string_x:', ' .asciz "hello"',
' .set static_string_a, static_string_x+2',
].map((text) => ({ text }));
const fns = listingFunctions(lines);
const sim = forSimulator(fns, fns.find((f) => f.kind === 'user'));
assert.doesNotMatch(sim.source, /rip \+/, 'every address became a number');
assert.doesNotMatch(sim.source, /does not define/);
const p = parseAsm(sim.source);
assert.ok(p.ok, p.diagnostics?.[0]?.message);
const r = runAsmProgram(p, { setup: sim.data.join('\n'), machine: 'teaching', maxSteps: 20 });
assert.ok(!r.error, String(r.error?.message));
const regs = r.states[r.count].regs;
const mem = (addr, n) => sim.data.find((d) => d.startsWith(`memory 0x${addr.toString(16)} `));
assert.match(mem(regs.rax), /bytes 0x00/, 'the empty string is one zero byte');
assert.match(mem(regs.rbx), /" "/);
assert.match(mem(regs.rcx), /bytes 0x61 0x62 0x63 0x00/);
assert.equal(regs.rdx, regs.rdx, 'alias resolves');
const hello = sim.data.find((d) => /"hello"/.test(d));
assert.ok(hello, 'the aliased string is placed');
assert.equal(regs.rdx, BigInt(parseInt(/memory (0x[0-9a-f]+)/.exec(hello)[1], 16) + 2), 'the alias points two bytes in');
});
test('vpcmpgtb compares signed bytes', () => {
const r = run(['mov rax, 0x00000000000080ff', 'movq xmm1, rax', 'mov rax, 0x0000000000000102', 'movq xmm2, rax', 'vpcmpgtb xmm0, xmm2, xmm1'].join('\n')).s.regs.xmm0;
// lane 0: 2 > -1 yes; lane 1: 1 > -128 yes; lanes 2..15: 0 > 0 no
assert.equal(r & 0xffffn, 0xffffn);
assert.equal(r >> 16n, 0n);
});