import type { AssignStmt, Expr, Stmt } from "../ast"
|
|
import { Loc } from "./loc"
|
|
import type { Operand, SSA } from "./ssa"
|
|
|
|
type IRState = {
|
|
nextID: number
|
|
ssa_stmts: Array<SSA>
|
|
}
|
|
|
|
export const convertIR = (stmts: Array<Stmt>): Array<SSA> => {
|
|
const state: IRState = {
|
|
nextID: 0,
|
|
ssa_stmts: [],
|
|
}
|
|
|
|
stmts.forEach(stmt => {
|
|
const ssa_stmts = convertAssignStmt(state, stmt)
|
|
state.ssa_stmts.push(...ssa_stmts)
|
|
})
|
|
|
|
return state.ssa_stmts
|
|
}
|
|
|
|
export const convertAssignStmt = (state: IRState, stmt: AssignStmt): Array<SSA> => {
|
|
return convertExpr(state, Loc.vari(stmt.args.name), stmt.args.expr)
|
|
}
|
|
|
|
export const convertExpr = (state: IRState, dest: Loc, expr: Expr): Array<SSA> => {
|
|
let expr_stmts: Array<SSA> = []
|
|
|
|
if (typeof expr === "number") {
|
|
expr_stmts = [{ dest, source: expr }]
|
|
} else if (typeof expr === "string") {
|
|
expr_stmts = [{ dest, source: Loc.vari(expr) }]
|
|
} else if (expr.type === "unary") {
|
|
const [source, stmts] = getSource(state, expr.arg)
|
|
stmts.push({
|
|
dest,
|
|
op: expr.op,
|
|
source,
|
|
})
|
|
|
|
expr_stmts = stmts
|
|
} else {
|
|
const [left_source, left_stmts] = getSource(state, expr.left)
|
|
const [right_source, right_stmts] = getSource(state, expr.right)
|
|
|
|
const stmts = [...left_stmts, ...right_stmts]
|
|
stmts.push({
|
|
dest,
|
|
op: expr.op,
|
|
source: left_source,
|
|
source1: right_source,
|
|
})
|
|
|
|
expr_stmts = stmts
|
|
}
|
|
|
|
return expr_stmts
|
|
}
|
|
|
|
const getSource = (state: IRState, expr: Expr): [Operand, Array<SSA>] => {
|
|
if (typeof expr === "number") {
|
|
return [expr, []]
|
|
} else if (typeof expr === "string") {
|
|
return [Loc.vari(expr), []]
|
|
}
|
|
|
|
const source = Loc.temp(`t${state.nextID++}`)
|
|
const stmts = convertExpr(state, source, expr)
|
|
return [source, stmts]
|
|
}
|