fix(asm): match go tool asm encodings and strictness

This commit is contained in:
2026-08-28 19:55:25 +02:00
parent 19a26e049b
commit 78b12dd427
4 changed files with 106 additions and 6 deletions
+51 -1
View File
@@ -78,13 +78,63 @@ func TestALU(t *testing.T) {
checkSyntax(t, "cmp rsi, r10", "CMPQ", SI, Reg{idx: 10, size: 8})
checkSyntax(t, "add rbx, qword ptr [rax]", "ADDQ", Ptr(AX, 0, 8), BX)
checkSyntax(t, "add qword ptr [rax], rbx", "ADDQ", BX, Ptr(AX, 0, 8))
checkSyntax(t, "cmp rbx, -0x20", "CMPQ", Imm(-32), BX)
// The Go assembler rejects the immediate-first CMP spelling outright,
// so Encode errors instead of silently emitting the swapped form.
if _, err := Encode("CMPQ", Imm(-32), BX); err == nil {
t.Errorf("Encode(CMPQ imm-first) should error, got success")
}
// The Go assembler's own spelling: immediate second.
checkSyntax(t, "cmp ecx, 0x1f", "CMPL", CX, Imm(31))
checkSyntax(t, "cmp ecx, -0x80000000", "CMPL", CX, Imm(-2147483648))
checkSyntax(t, "cmp r9, -0x80000000", "CMPQ", Reg{idx: 9, size: 8}, Imm(-2147483648))
}
// TestScalarXmmRegMoves pins the Go-assembler byte forms of scalar
// MOVQ/MOVL between GPRs and XMM registers (66 REX.W 0F 6E/0F 7E) and the
// memory forms (F3 0F 7E load, 66 0F D6 store), all byte-for-byte.
func TestScalarXmmRegMoves(t *testing.T) {
cases := []struct {
name string
mnem string
ops []Operand
want string
}{
{"MOVQ AX,X1", "MOVQ", []Operand{AX, vreg(t, "X1")}, "66480f6ec8"},
{"MOVQ DX,X2", "MOVQ", []Operand{DX, vreg(t, "X2")}, "66480f6ed2"},
{"MOVQ X1,AX", "MOVQ", []Operand{vreg(t, "X1"), AX}, "66480f7ec8"},
{"MOVQ X0,DX", "MOVQ", []Operand{vreg(t, "X0"), DX}, "66480f7ec2"},
{"MOVL AX,X1", "MOVL", []Operand{AX, vreg(t, "X1")}, "660f6ec8"},
{"MOVL X1,AX", "MOVL", []Operand{vreg(t, "X1"), AX}, "660f7ec8"},
{"MOVQ (SI),X1", "MOVQ", []Operand{Ptr(SI, 0, 8), vreg(t, "X1")}, "f30f7e0e"},
{"MOVQ X3,(DI)", "MOVQ", []Operand{vreg(t, "X3"), Ptr(DI, 0, 8)}, "660fd61f"},
}
for _, c := range cases {
code, err := Encode(c.mnem, c.ops...)
if err != nil {
t.Errorf("%s: %v", c.name, err)
continue
}
if got := fmt.Sprintf("%x", code); got != c.want {
t.Errorf("%s: got %s, want %s", c.name, got, c.want)
}
}
}
// TestBadScale pins the go-tool-asm parity of rejecting SIB scales the
// hardware cannot encode.
func TestBadScale(t *testing.T) {
for _, sc := range []int{3, 5, 16, 32} {
if _, err := Encode("LEAQ", Idx(SI, BX, sc, 0, 8), AX); err == nil {
t.Errorf("LEAQ scale %d: expected error, got success", sc)
}
}
for _, sc := range []int{1, 2, 4, 8} {
if _, err := Encode("LEAQ", Idx(SI, BX, sc, 0, 8), AX); err != nil {
t.Errorf("LEAQ scale %d: %v", sc, err)
}
}
}
func TestLea(t *testing.T) {
checkSyntax(t, "lea r9, ptr [rsi+4*rbx]", "LEAQ", Idx(SI, BX, 4, 0, 8), Reg{idx: 9, size: 8})
checkSyntax(t, "lea rax, ptr [rbx+0x8]", "LEAQ", Ptr(BX, 0x8, 8), AX)