import { expect } from "chai" import { edgeConnects } from "../lib/data/graph" import { Loc } from "../lib/ir/loc" import type { AbsInsn2 } from "../lib/ir/insn" import { allocateRegisters, interference, liveness } from "../lib/regalloc" import { R8 } from "../lib/sm83/cpu" describe("liveness", () => { it("computes liveness", () => { const x = [0, 1, 2].map(i => Loc.vari("x" + i)) const y = [0, 1].map(i => Loc.vari("y" + i)) const block: Array = [ { type: "copy", dest: x[0], source: 1 }, { type: "unary", dest: x[1], source: x[0], op: "add" }, { type: "unary", dest: x[2], source: x[1], op: "add" }, { type: "unary", dest: y[0], source: x[0], op: "add" }, { type: "unary", dest: y[1], source: y[0], op: "add" }, ] const info = liveness(block) expect(info[0]).to.deep.equal(new Set()) expect(info[1]).to.deep.equal(new Set([x[0]])) expect(info[2]).to.deep.equal(new Set([x[0], x[1]])) expect(info[3]).to.deep.equal(new Set([x[0], x[1], x[2]])) expect(info[4]).to.deep.equal(new Set([y[0], x[2]])) }) }) describe("interference", () => { it("computes interference", () => { const block: Array = [ { type: "copy", dest: Loc.vari("a"), source: 7 }, { type: "copy", dest: Loc.vari("b"), source: 3 }, { type: "copy", dest: Loc.vari("x"), source: Loc.vari("a") }, ] const info = liveness(block) const g = interference(block, info) expect(edgeConnects(g, "a", "b")).to.be.true }) }) describe("allocateRegisters", () => { it("allocates registers", () => { const block: Array = [ { type: "copy", dest: Loc.vari("a"), source: 7 }, { type: "copy", dest: Loc.vari("b"), source: 3 }, { type: "copy", dest: Loc.vari("x"), source: Loc.vari("a") } ] const alloc = allocateRegisters(block, Object.values(R8)) expect(alloc.a).to.equal("A") expect(alloc.b).to.equal("B") expect(alloc.x).to.equal("A") }) })