import { R8 } from "./cpu"
|
|
import { Loc, LocType } from "../ir/loc"
|
|
import { Operand, AbsInsn2, insnReduce2 } from "../ir/insn"
|
|
import { BinaryOp, UnaryOp } from "../ast"
|
|
import type { SM83Insn } from "./insn"
|
|
|
|
export const realizeBlock = (block: Array<AbsInsn2>): Array<SM83Insn> => block.flatMap(realizeInsn)
|
|
|
|
export const realizeInsn = (insn: AbsInsn2): Array<SM83Insn> => insnReduce2(realizeCopy, realizeUnary, insn)
|
|
|
|
const getSourceName = (source: Operand): string => typeof source === "number"
|
|
? source.toString()
|
|
: source.asmName()
|
|
|
|
export const realizeCopy = (dest: Loc, source: Operand): Array<SM83Insn> => [
|
|
`LD ${dest.asmName()}, ${getSourceName(source)}`
|
|
]
|
|
|
|
export const realizeUnary = (dest: Loc, op: UnaryOp | BinaryOp, source: Operand): Array<SM83Insn> => {
|
|
if (!isA(dest)) {
|
|
throw new Error("unexpected form for unary operation")
|
|
}
|
|
|
|
switch (op) {
|
|
case "add":
|
|
return [`ADD ${getSourceName(source)}`]
|
|
|
|
case "arith_negate":
|
|
return ["CPL", "INC A"]
|
|
|
|
case "bit_negate":
|
|
return ["CPL"]
|
|
|
|
default:
|
|
throw new Error(`unsupported unary op \`${op}'`)
|
|
}
|
|
}
|
|
|
|
const isA = (loc: Operand): boolean =>
|
|
typeof loc === "object" && loc.type === LocType.REGISTER && loc.name === R8.A
|