q/src/build/asm/Assembler.go

113 lines
2.5 KiB
Go

package asm
import (
"encoding/binary"
"git.akyoto.dev/cli/q/src/build/arch/x64"
)
// Assembler contains a list of instructions.
type Assembler struct {
Instructions []Instruction
}
// New creates a new assembler.
func New() *Assembler {
return &Assembler{
Instructions: make([]Instruction, 0, 8),
}
}
// Finalize generates the final machine code.
func (a *Assembler) Finalize() ([]byte, []byte) {
code := make([]byte, 0, len(a.Instructions)*8)
data := make([]byte, 0, 16)
labels := map[string]Address{}
pointers := []Pointer{}
for _, x := range a.Instructions {
switch x.Mnemonic {
case MOVE:
switch operands := x.Data.(type) {
case *RegisterNumber:
code = x64.MoveRegNum32(code, operands.Register, uint32(operands.Number))
case *RegisterRegister:
code = x64.MoveRegReg64(code, operands.Destination, operands.Source)
}
case RETURN:
code = x64.Return(code)
case SYSCALL:
code = x64.Syscall(code)
case CALL:
code = x64.Call(code, 0x00_00_00_00)
size := 4
label := x.Data.(*Label)
nextInstructionAddress := Address(len(code))
pointers = append(pointers, Pointer{
Position: Address(len(code) - size),
Size: uint8(size),
Resolve: func() Address {
destination := labels[label.Name]
distance := destination - nextInstructionAddress
return Address(distance)
},
})
case JUMP:
code = x64.Jump8(code, 0x00)
size := 1
label := x.Data.(*Label)
nextInstructionAddress := Address(len(code))
pointers = append(pointers, Pointer{
Position: Address(len(code) - size),
Size: uint8(size),
Resolve: func() Address {
destination := labels[label.Name]
distance := destination - nextInstructionAddress
return Address(distance)
},
})
case LABEL:
labels[x.Data.(*Label).Name] = Address(len(code))
default:
panic("Unknown mnemonic: " + x.Mnemonic.String())
}
}
// dataStart := config.BaseAddress + config.CodeOffset + Address(len(code))
for _, pointer := range pointers {
slice := code[pointer.Position : pointer.Position+Address(pointer.Size)]
address := pointer.Resolve()
switch pointer.Size {
case 1:
slice[0] = uint8(address)
case 2:
binary.LittleEndian.PutUint16(slice, uint16(address))
case 4:
binary.LittleEndian.PutUint32(slice, uint32(address))
case 8:
binary.LittleEndian.PutUint64(slice, uint64(address))
}
}
return code, data
}
// Merge combines the contents of this assembler with another one.
func (a *Assembler) Merge(b *Assembler) {
a.Instructions = append(a.Instructions, b.Instructions...)
}