stage2 修复全局变量未完成的问题 提供错误处理解析

This commit is contained in:
zzy committed 2026-09-25 13:46:07 +08:00
1 parent c0a86ea552
commit 0b8f649818
11 files changed
+317 -18

No files matched your search

+37 -1
View File
@@ -16,7 +16,7 @@ type .{ .Layout } = @import("./layout.spl");
type AttrM = @import("./attr.spl");
type .{ .Attr, .AttrArg } = @import("./attr.spl");
type IrM = @import("./ir.spl");
type .{ .Ir, .IrFunc, .IrEntry } = @import("./ir.spl");
type .{ .Ir, .IrFunc, .IrEntry, .Global } = @import("./ir.spl");
type Mcode = @import("./mcode.spl");
type .{ .Prog, .Op, .VmKind, .VmIns, .VmFunc } = @import("./mcode.spl");
type Mem = @import("sys/mem.spl");
@@ -28,6 +28,7 @@ ty: *TypeTable,
attr: *Attr,
layout: *Layout,
extern_native: Vec, // isize
global_gaddr: Vec, // usize:每个全局变量在 prog.gdata 的下标
prog: Prog,
// ---- 类型/布局查询 ----
@@ -589,6 +590,23 @@ fn cg_const(cg: *Cgen, ref: usize, n: *IrEntry) {
var te = TypeTable.node(ctx.ty, tid);
if te == null { ret; }
// 全局变量引用:Const{ lit = Global(gidx) } → GADDR(该全局的运行时地址)。
match n.body {
.Const(c) => {
match c.lit {
.Global(g) => {
var di: usize = 0;
if g < ctx.global_gaddr.len { di = (ctx.global_gaddr.data as *usize)[g]; }
emit(cg, .Gaddr, .Void, di);
cg_store_slot(cg, ref, .Ptr);
ret;
},
_ => {},
}
},
_ => {},
}
match te.node {
.Fn(f) => {
var cref = const_fn(n);
@@ -1213,6 +1231,7 @@ fn init(ctx: *Ir2Vm, ir: *Ir, ty: *TypeTable, layout: *Layout, attr: *Attr) {
ctx.attr = attr;
ctx.layout = layout;
ctx.extern_native = Vec.blank(@sizeof(isize), @alignof(isize));
ctx.global_gaddr = Vec.blank(@sizeof(usize), @alignof(usize));
match Mcode.new() {
.Ok(v) => { ctx.prog = v; },
@@ -1223,6 +1242,7 @@ fn init(ctx: *Ir2Vm, ir: *Ir, ty: *TypeTable, layout: *Layout, attr: *Attr) {
fn drop(ctx: *Ir2Vm) {
Mcode.drop(&ctx.prog);
Vec.drop(&ctx.extern_native);
Vec.drop(&ctx.global_gaddr);
}
fn run_func(ctx: *Ir2Vm, ref: usize): i32 {
@@ -1253,6 +1273,22 @@ fn run(ctx: *Ir2Vm): i32 {
i = i + 1;
}
// 登记全局变量到 prog.gdata(Zero→零填/BSS,Bytes→拷贝),记下运行时下标。
var gi: usize = 0;
while gi < ctx.ir.globals.len {
var g = (ctx.ir.globals.data as *Global) + gi;
var gsize = ir_type_size(ctx, g.tid);
var didx: usize = 0;
if g.zero {
didx = Mcode.add_zero_data(&ctx.prog, gsize);
} else {
didx = Mcode.add_data(&ctx.prog, g.data.data as usize, gsize);
}
var dv = didx;
match Vec.push(&ctx.global_gaddr, &dv as *u8) { .Ok => {}, .Err(error) => {} }
gi = gi + 1;
}
// 哨兵:保证真实函数入口地址非零。
ignore_usize(Mcode.add_instr(&ctx.prog, .Halt, .Void, 0));