From ba8da1fccbf3f4f1a96f1f779566b04c94fc6bf0 Mon Sep 17 00:00:00 2001 From: sfja Date: Fri, 28 Mar 2025 00:05:59 +0100 Subject: [PATCH] compiler: use cqo, short ty --- sbc/asm_gen.ts | 8 ++++---- sbc/mir.ts | 4 +++- sbc/ty.ts | 29 ++++++++++++++++++++++------- 3 files changed, 29 insertions(+), 12 deletions(-) diff --git a/sbc/asm_gen.ts b/sbc/asm_gen.ts index b386893..669484b 100644 --- a/sbc/asm_gen.ts +++ b/sbc/asm_gen.ts @@ -33,16 +33,16 @@ export class AsmGen { } this.writeln(`sbc__div:`); - this.writeIns(`mov rdx, 0`); this.writeIns(`mov rax, [rsp+16]`); this.writeIns(`mov rdi, [rsp+8]`); - this.writeIns(`div rdi`); + this.writeIns(`cqo`); + this.writeIns(`idiv rdi`); this.writeIns(`ret`); this.writeln(`sbc__mod:`); - this.writeIns(`mov rdx, 0`); this.writeIns(`mov rax, [rsp+16]`); this.writeIns(`mov rdi, [rsp+8]`); - this.writeIns(`div rdi`); + this.writeIns(`cqo`); + this.writeIns(`idiv rdi`); this.writeIns(`mov rax, rdx`); this.writeIns(`ret`); diff --git a/sbc/mir.ts b/sbc/mir.ts index 93bcbdb..4d5c42b 100644 --- a/sbc/mir.ts +++ b/sbc/mir.ts @@ -111,7 +111,9 @@ export class FnStringifyer { case "error": return ""; case "push": - return `push (${tyToString(k.ty)}) ${this.val(k.val)}`; + return `push (${tyToString(k.ty, { short: true })}) ${ + this.val(k.val) + }`; case "pop": return "pop"; case "load": diff --git a/sbc/ty.ts b/sbc/ty.ts index 7ce56c2..10c6396 100644 --- a/sbc/ty.ts +++ b/sbc/ty.ts @@ -9,7 +9,11 @@ export type Ty = | { tag: "ptr"; ty: Ty } | { tag: "fn"; stmt: ast.Stmt; params: Ty[]; returnTy: Ty }; -export function tyToString(ty: Ty): string { +type TyToStringOpts = { + short?: boolean; +}; + +export function tyToString(ty: Ty, opts: TyToStringOpts = {}): string { switch (ty.tag) { case "error": return ``; @@ -24,12 +28,23 @@ export function tyToString(ty: Ty): string { case "ptr": return `*${tyToString(ty.ty)}`; case "fn": { - const k = ty.stmt.kind as ast.StmtKind & { tag: "fn" }; - const params = ty.params - .map((param, i) => `${k.params[i].ident}: ${tyToString(param)}`) - .join(", "); - const returnTy = tyToString(ty.returnTy); - return `fn ${k.ident}(${params}) -> ${returnTy}`; + if (!opts.short) { + const k = ty.stmt.kind as ast.StmtKind & { tag: "fn" }; + const params = ty.params + .map((param, i) => + `${k.params[i].ident}: ${tyToString(param)}` + ) + .join(", "); + const returnTy = tyToString(ty.returnTy); + return `fn ${k.ident}(${params}) -> ${returnTy}`; + } else { + const k = ty.stmt.kind as ast.StmtKind & { tag: "fn" }; + const params = ty.params + .map((param) => tyToString(param)) + .join(", "); + const returnTy = tyToString(ty.returnTy); + return `fn(${params}) -> ${returnTy}`; + } } } }