package gen
import (
"fmt"
"io"
"math"
"strconv"
"strings"
"github.com/mmcloughlin/avo/internal/inst"
)
type LoaderTest struct {
sym string // reference to the test function symbol
rel8 string // label to be used for near jumps
rel32 string // label for far jumps
}
func (l *LoaderTest) Generate(w io.Writer, is []*inst.Instruction) error {
p := &printer{w: w}
l.sym = "\u00b7loadertest(SB)"
p.printf("TEXT %s, 0, $0\n", l.sym)
// Define a label for far jumps.
p.printf("rel32:\n")
l.rel32 = "rel32"
counts := map[string]int{}
for _, i := range is {
p.printf("\t// %s %s\n", i.Opcode, i.Summary)
if skip, msg := l.skip(i.Opcode); skip {
p.printf("\t// SKIP: %s\n", msg)
counts["skip"]++
continue
}
if i.Opcode[0] == 'J' {
label := fmt.Sprintf("rel8_%s", strings.ToLower(i.Opcode))
p.printf("%s:\n", label)
l.rel8 = label
}
for _, f := range i.Forms {
as := l.args(i.Opcode, f.Operands)
p.printf("\t// %#v\n", f.Operands)
if as == nil {
p.printf("\t// TODO\n")
counts["todo"]++
continue
}
p.printf("\t%s\t%s\n", i.Opcode, strings.Join(as, ", "))
counts["total"]++
}
p.printf("\n")
}
p.printf("\tRET\n")
for m, c := range counts {
p.printf("// %s: %d\n", m, c)
}
return p.Err()
}
func (l LoaderTest) skip(opcode string) (bool, string) {
prefixes := map[string]string{
"PUSH": "PUSH can produce 'unbalanced PUSH/POP' assembler error",
"POP": "POP can produce 'unbalanced PUSH/POP' assembler error",
}
for p, m := range prefixes {
if strings.HasPrefix(opcode, p) {
return true, m
}
}
return false, ""
}
func (l LoaderTest) args(opcode string, ops []inst.Operand) []string {
// Special case for CALL, since it needs a different type of rel32 argument than others.
if opcode == "CALL" {
return []string{l.sym}
}
as := make([]string, len(ops))
for i, op := range ops {
a := l.arg(op.Type, i)
if a == "" {
return nil
}
as[i] = a
}
return as
}
// arg generates an argument for an operand of the given type.
func (l LoaderTest) arg(t string, i int) string {
m := map[string]string{
"1": "$1", //
"3": "$3", //
"imm2u": "$3",
//
"imm8": fmt.Sprintf("$%d", math.MaxInt8), //
"imm16": fmt.Sprintf("$%d", math.MaxInt16), //
"imm32": fmt.Sprintf("$%d", math.MaxInt32), //
"imm64": fmt.Sprintf("$%d", math.MaxInt64), //
"al": "AL", //
"cl": "CL", //
"r8": "CH", //
"ax": "AX", //
"r16": "SI", //
"eax": "AX", //
"r32": "DX", //
"rax": "AX", //
"r64": "R15", //
"mm": "M5", //
"xmm0": "X0", //
"xmm": "X" + strconv.Itoa(7+i), //
//
//
"ymm": "Y" + strconv.Itoa(3+i), //
//
//
//
//
//
//
//
//
//
"m": "0(AX)(CX*2)", //
"m8": "8(AX)(CX*2)", //
"m16": "16(AX)(CX*2)", //
//
"m32": "32(AX)(CX*2)", //
//
//
"m64": "64(AX)(CX*2)", //
//
//
"m128": "128(AX)(CX*2)", //
//
"m256": "256(AX)(CX*2)", //
//
//
//
//
//
//
//
//
//
//
"vm32x": "32(X14*8)", //
//
//
//
//
//
//
//
//
//
//
//
"rel8": l.rel8, //
"rel32": l.rel32, //
//
//
// Appear unused:
"r8l": "????", //
"r16l": "????", //
"r32l": "????", //
}
return m[t]
}