// selfhost/cmd/wwc/cgen.ww — port of cmd/6c/cgen.c. // // Status: GROWING. Each subsystem we add is verified by `wwdump_ww -c` // producing byte-identical output to C-side `6c` for the same source, // then by assembling + linking + running the result. // // Current coverage: // - decls: N_FILE, N_FNDECL (params, frame for locals, prologue // + dual-epilogue suppression; FFI body-less fn skipped) // - stmts: N_BLOCK, N_RETURN, N_EXPRSTMT, N_LET (no init), // N_LET (int-literal / ident / call / N_BIN init), // N_IF (with optional else), N_FOR (cond-only and full // init/cond/post), N_BREAK, N_CONTINUE // - exprs: N_INTLIT, N_IDENT (local/param), N_BIN with full op // coverage (+/-/*/// %, &/|/^, <>, comparisons with // signed-vs-unsigned dispatch, &&/||), N_UN (- ! ~ & *), // N_CALL (recursive R-to-L push, pop into argregs L-to-R), // N_ASSIGN to local idents (plain and compound +=/-=) // // Type info is shallow — frame slots are 8 bytes per local, all loads // /stores are MOVQ. Programs that mix i8/i32/i64 locals work but spill // 8 bytes per local. Float, str, slice, struct, match, defer, alloc, // tagged-union return — none of those are wired yet. use os; use mem; use ast; use tok; use typ; use sym; use strconv; // ---- typedef alias registry ----------------------------------------- // // `type error = str;` makes `error` a struct-shape alias. We track // alias→target so is_str_type / is_slice_type / struct_lookup can // resolve through the chain. Only direct N_TNAME aliases are mapped; // `type p = struct {...}` is handled by collect_structs. type alias_ent = struct { aname: str, target: *node, // the rhs type expr aanext: *alias_ent, }; fn collect_aliases(c: *cgen, file: *node) void = { c.aliases = nil; let d: *node = file.list; for (d != nil) { if (d.kind == N_TYPEDECL) { let body: *node = d.lhs; if (body != nil) { if (body.kind != N_TSTRUCT) { let a: *alias_ent = amalloc(c.a, 32u64): *alias_ent; a.aname = d.str; a.target = body; a.aanext = c.aliases; c.aliases = a; }; }; }; d = d.next; }; }; fn alias_lookup(c: *cgen, name: str) *node = { let a: *alias_ent = c.aliases; for (a != nil) { let an: str = a.aname; if (streq(an, name)) { return a.target; }; a = a.aanext; }; return nil; }; // resolve_type — follow typedef alias chains to a "canonical" type // expr (str/slice/array/struct/...). Stops on cycles via depth limit. fn resolve_type(c: *cgen, t: *node) *node = { let cur: *node = t; let depth: i32 = 0; for (depth < 16) { if (cur == nil) { return nil; }; if (cur.kind != N_TNAME) { return cur; }; let nm: str = cur.str; let next: *node = alias_lookup(c, nm); if (next == nil) { return cur; }; cur = next; depth += 1; }; return cur; }; // ---- struct registry ------------------------------------------------ // // Per-file map from struct name → list of fields with computed offsets // and sizes. Built when cg_file walks N_TYPEDECL with N_TSTRUCT lhs. // N_DOT and N_ASSIGN consult this to resolve `s.field` for struct or // *struct bases. type field_info = struct { fname: str, foff: i32, fsz: i32, tnode: *node, // the field type expr, for nested struct lookups finext: *field_info, }; type struct_info = struct { sname: str, fields: *field_info, tot_size: i32, sinext: *struct_info, }; // ---- locals / frame -------------------------------------------------- type local = struct { name: str, off: i32, tnode: *node, // declared type expr (N_TNAME / N_TPTR / ...) or nil lnext: *local, }; // strlit — interned string literal record. Emitted as a DATA directive // after all functions; cgexpr N_STRLIT loads (LEAQ ptr, MOVQ len). type strlit = struct { label: str, // "_S_" bytes: str, slnext: *strlit, }; // ffi — `@symbol("name")` mapping. Body-less fn `foo` with this attr // gets its CALL target rewritten to `name`. type ffi = struct { ident: str, symbol: str, fnext: *ffi, }; def LOOP_MAX: i32 = 16; type cgen = struct { a: *arena, locals: *local, frame: i32, last_was_return: i32, labelseq: i32, strlit_seq: i32, strlits: *strlit, ffis: *ffi, defs: *def_ent, fnrets: *fnret, aliases: *alias_ent, structs: *struct_info, fn_name: str, fn_ret: *node, // declared return type of current fn (or nil) loop_top: i32, loop_end_buf: *str, // stack of end labels for break loop_cont_buf: *str, // stack of cont labels for continue }; fn cgen_init(c: *cgen, a: *arena) void = { c.a = a; c.locals = nil; c.frame = 0; c.last_was_return = 0; c.labelseq = 0; // Note: strlit_seq, strlits, ffis are *not* reset here; they // persist across cgfn calls within one file. cg_file resets them // at the start of each compilation unit. c.loop_top = 0; c.loop_end_buf = amalloc(a, (LOOP_MAX: u64) * 16u64): *str; c.loop_cont_buf = amalloc(a, (LOOP_MAX: u64) * 16u64): *str; }; // local_alloc — append a slot for `name` without dedup. Used for // match-arm bindings, which C cgen allocates via cgexpr's by-value // `locals` list — so two separate matches each get fresh slots even // when their bind names collide. scan_locals follows the same rule // for N_MCASE. fn local_alloc(c: *cgen, name: str, sz: i32, tnode: *node) i32 = { let asz: i32 = sz; if (asz < 8) { asz = 8; }; if ((asz & 7) != 0) { asz = (asz + 7) & ~7; }; c.frame += asz; let off: i32 = 0 - c.frame; let l: *local = amalloc(c.a, 48u64): *local; l.name = name; l.off = off; l.tnode = tnode; l.lnext = c.locals; c.locals = l; return off; }; fn local_add(c: *cgen, name: str, sz: i32, tnode: *node) i32 = { // Name-based slot reuse for N_LETs and params: if `name` is // already declared in this function, return its existing // offset. Mirrors C cgen (cmd/6c/cgen.c:localoff). Two // disjoint scopes that declare the same name share one slot — // so `escape` in wwdump (three `let cp: pos;` across separate // branches) reserves one slot, not three. scan_locals does // the matching dedup at prologue time so the SUBQ stays in // sync. // // On a dedup hit we also overwrite the stored tnode to match // the new declaration's type. C reads `n->lhs->type` (filled // by the checker) at every N_DOT/N_CAST site; we read // `lc.tnode`, so it must follow source order. Without this, // a later `let m: *node` inside a branch keeps an earlier // `let m: i32`'s tnode and `m.next` falls into the SB fallback. let cur: *local = c.locals; for (cur != nil) { let cn: str = cur.name; if (streq(cn, name)) { cur.tnode = tnode; return cur.off; }; cur = cur.lnext; }; return local_alloc(c, name, sz, tnode); }; // scan_seen_mark — called by scan_locals on every let / match-bind // site. Returns true if `name` is already tracked in c.locals (so // the slot will be shared at emission time — no new frame bump). // Otherwise appends a name-only stub and returns false. Stubs are // thrown away when cgfn resets c.locals before emission. fn scan_seen_mark(c: *cgen, name: str) bool = { if (local_find_node(c, name) != nil) { return true; }; let l: *local = amalloc(c.a, 48u64): *local; l.name = name; l.off = 0; l.tnode = nil; l.lnext = c.locals; c.locals = l; return false; }; fn local_find_node(c: *cgen, name: str) *local = { let l: *local = c.locals; for (l != nil) { let ln: str = l.name; if (streq(ln, name)) { return l; }; l = l.lnext; }; return nil; }; fn local_find(c: *cgen, name: str) i32 = { let l: *local = c.locals; for (l != nil) { let ln: str = l.name; if (ln.len == name.len) { let i: i32 = 0; let eq: bool = true; for (i < name.len) { if (ln[i] != name[i]) { eq = false; i = name.len; } else { i += 1; }; }; if (eq) { return l.off; }; }; l = l.lnext; }; return 0; }; // ---- emit helpers --------------------------------------------------- fn emit_line(s: str) void = { os.write(1, s.ptr, s.len: u64); }; fn emit_int(v: i64) void = { let buf: [32]u8; let n: i32 = strconv.i64toa(buf[0:32], v); os.write(1, buf.ptr, n: u64); }; fn emit_uint(v: u64) void = { let buf: [32]u8; let n: i32 = strconv.u64toa(buf[0:32], v); os.write(1, buf.ptr, n: u64); }; // emit_disp_reg — print "disp(reg)" or "(reg)" when disp == 0, the // way Plan 9 6c/6a do. fn emit_disp_reg(off: i64, reg: str) void = { if (off != 0i64) { emit_int(off); }; emit_line("("); emit_line(reg); emit_line(")"); }; // emit_off — print an integer offset, suppressing it entirely when 0. // Use before any emit_line("(BP)...") or emit_line("(SB)...") sequence. // Plan 9 cc convention: "(BP)" not "0(BP)". fn emit_off(v: i64) void = { if (v != 0i64) { emit_int(v); }; }; // mklabel — fresh label "__". Returns an // arena-owned str. Mirrors C cgen's mklabel so diffs match. fn mklabel(c: *cgen, base: str) str = { let buf: [128]u8; let i: i32 = 0; let fname: str = c.fn_name; let j: i32 = 0; for (j < fname.len) { buf[i] = fname[j]; i += 1; j += 1; }; buf[i] = 95u8; i += 1; // '_' j = 0; for (j < base.len) { buf[i] = base[j]; i += 1; j += 1; }; buf[i] = 95u8; i += 1; // '_' let n: i32 = strconv.i64toa(buf[i:128], c.labelseq: i64); c.labelseq += 1; let total: i32 = i + n; let p: *u8 = amalloc(c.a, (total: u64) + 1u64): *u8; let k: i32 = 0; for (k < total) { p[k] = buf[k]; k += 1; }; p[total] = 0u8; let r: str; r.ptr = p; r.len = total; return r; }; fn emit_label(s: str) void = { os.write(1, s.ptr, s.len: u64); emit_line(":\n"); }; // ---- string interning ------------------------------------------------ // // streq is provided by sym.ww and reused here. // intern_strlit — return a stable label for `bytes`. Dedups by content // so identical literals share storage. fn intern_strlit(c: *cgen, bytes: str) str = { let s: *strlit = c.strlits; for (s != nil) { let bs: str = s.bytes; if (streq(bs, bytes)) { return s.label; }; s = s.slnext; }; // New label "_S_". let buf: [32]u8; buf[0] = 95u8; buf[1] = 83u8; buf[2] = 95u8; // "_S_" let n: i32 = strconv.i64toa(buf[3:32], c.strlit_seq: i64); c.strlit_seq += 1; let total: i32 = 3 + n; let p: *u8 = amalloc(c.a, (total: u64) + 1u64): *u8; let i: i32 = 0; for (i < total) { p[i] = buf[i]; i += 1; }; p[total] = 0u8; let lab: str; lab.ptr = p; lab.len = total; let nw: *strlit = amalloc(c.a, 48u64): *strlit; nw.label = lab; nw.bytes = bytes; nw.slnext = c.strlits; c.strlits = nw; return lab; }; // emit_def_constants — DATA directive per top-level int-literal `def`. // 8 bytes little-endian to match what the C cgen emits. fn emit_def_constants(c: *cgen, file: *node) void = { let d: *node = file.list; for (d != nil) { if (d.kind == N_DEF) { let r: *node = d.rhs; let v: u64 = 0u64; let ok: bool = false; if (r != nil) { if (r.kind == N_INTLIT) { v = r.uval; ok = true; }; if (r.kind == N_RUNELIT) { v = r.uval; ok = true; }; if (r.kind == N_TRUE) { v = 1u64; ok = true; }; if (r.kind == N_FALSE) { v = 0u64; ok = true; }; if (r.kind == N_NIL) { v = 0u64; ok = true; }; }; if (ok) { emit_line("DATA "); let nm: str = d.str; os.write(1, nm.ptr, nm.len: u64); emit_line("(SB),\""); let i: i32 = 0; let n: u64 = v; for (i < 8) { let b: u8 = (n & 255u64): u8; n = n >> 8u64; // C emit_defs only special-cases " and \; // every other non-printable goes as \xHH. if (b == 34u8) { emit_line("\\\""); } else { if (b == 92u8) { emit_line("\\\\"); } else { if (b < 32u8) { emit_line("\\x"); let hi: u8 = b >> 4u8; let lo: u8 = b & 15u8; let bb: [2]u8; if (hi < 10u8) { bb[0] = hi + 48u8; } else { bb[0] = (hi - 10u8) + 97u8; }; if (lo < 10u8) { bb[1] = lo + 48u8; } else { bb[1] = (lo - 10u8) + 97u8; }; os.write(1, bb.ptr, 2u64); } else { if (b >= 127u8) { emit_line("\\x"); let hi: u8 = b >> 4u8; let lo: u8 = b & 15u8; let bb: [2]u8; if (hi < 10u8) { bb[0] = hi + 48u8; } else { bb[0] = (hi - 10u8) + 97u8; }; if (lo < 10u8) { bb[1] = lo + 48u8; } else { bb[1] = (lo - 10u8) + 97u8; }; os.write(1, bb.ptr, 2u64); } else { let bb: [1]u8; bb[0] = b; os.write(1, bb.ptr, 1u64); }; }; };}; i += 1; }; emit_line("\"\n"); }; }; d = d.next; }; }; // emit_data_section — DATA directives for every interned strlit. // Trailing NUL appended so .ptr can be used as a C string by syscalls. fn emit_data_section(c: *cgen) void = { let s: *strlit = c.strlits; for (s != nil) { emit_line("DATA "); let lab: str = s.label; os.write(1, lab.ptr, lab.len: u64); emit_line("(SB),\""); let bs: str = s.bytes; let i: i32 = 0; for (i < bs.len) { let b: u8 = bs[i]; if (b == 34u8) { emit_line("\\\""); } // " else { if (b == 92u8) { emit_line("\\\\"); } // \ else { if (b == 10u8) { emit_line("\\n"); } else { if (b == 9u8) { emit_line("\\t"); } else { if (b == 13u8) { emit_line("\\r"); } else { if (b < 32u8) { emit_line("\\x"); let hi: u8 = b >> 4u8; let lo: u8 = b & 15u8; let bb: [2]u8; if (hi < 10u8) { bb[0] = hi + 48u8; } else { bb[0] = (hi - 10u8) + 97u8; }; if (lo < 10u8) { bb[1] = lo + 48u8; } else { bb[1] = (lo - 10u8) + 97u8; }; os.write(1, bb.ptr, 2u64); } else { if (b >= 127u8) { emit_line("\\x"); let hi: u8 = b >> 4u8; let lo: u8 = b & 15u8; let bb: [2]u8; if (hi < 10u8) { bb[0] = hi + 48u8; } else { bb[0] = (hi - 10u8) + 97u8; }; if (lo < 10u8) { bb[1] = lo + 48u8; } else { bb[1] = (lo - 10u8) + 97u8; }; os.write(1, bb.ptr, 2u64); } else { let bb: [1]u8; bb[0] = b; os.write(1, bb.ptr, 1u64); }; }; };};};};}; i += 1; }; emit_line("\\x00\"\n"); s = s.slnext; }; }; // ---- fn return-type map --------------------------------------------- // // Per-file: ident → ret-type-node. Used to decide whether to shuffle // (AX, DX) → (AX, BX) after a CALL — needed for str-returning fns so // the value flows through cgen as the canonical (AX, BX) str pair. type fnret = struct { fname: str, rtype: *node, frnext: *fnret, }; fn collect_fnrets(c: *cgen, file: *node) void = { c.fnrets = nil; let d: *node = file.list; for (d != nil) { if (d.kind == N_FNDECL) { let f: *fnret = amalloc(c.a, 32u64): *fnret; f.fname = d.str; f.rtype = d.lhs; f.frnext = c.fnrets; c.fnrets = f; }; d = d.next; }; }; fn fnret_lookup(c: *cgen, name: str) *node = { let f: *fnret = c.fnrets; for (f != nil) { let fn_: str = f.fname; if (streq(fn_, name)) { return f.rtype; }; f = f.frnext; }; return nil; }; // ---- def-constant registry ------------------------------------------ // // `def NAME: T = LIT;` becomes a DATA symbol the C-side 6c emits; an // ident reference loads it via `MOVQ NAME(SB), AX`. We collect them at // file load and consult on N_IDENT lookup. type def_ent = struct { dname: str, dnext: *def_ent, }; fn collect_defs(c: *cgen, file: *node) void = { c.defs = nil; let d: *node = file.list; for (d != nil) { if (d.kind == N_DEF) { let e: *def_ent = amalloc(c.a, 32u64): *def_ent; e.dname = d.str; e.dnext = c.defs; c.defs = e; }; d = d.next; }; }; fn def_lookup(c: *cgen, name: str) bool = { let e: *def_ent = c.defs; for (e != nil) { let dn: str = e.dname; if (streq(dn, name)) { return true; }; e = e.dnext; }; return false; }; // ---- FFI map --------------------------------------------------------- fn ffi_collect(c: *cgen, file: *node) void = { c.ffis = nil; if (file == nil) { return; }; let d: *node = file.list; for (d != nil) { if (d.kind == N_FNDECL) { let a: *node = d.attr; for (a != nil) { if (a.kind == N_ATTR) { let aname: str = a.str; if (streq(aname, "symbol")) { let sym_node: *node = a.list; if (sym_node != nil) { if (sym_node.kind == N_STRLIT) { let f: *ffi = amalloc(c.a, 48u64): *ffi; f.ident = d.str; f.symbol = sym_node.str; f.fnext = c.ffis; c.ffis = f; }; }; }; }; a = a.next; }; }; d = d.next; }; }; fn ffi_resolve(c: *cgen, ident: str) str = { let f: *ffi = c.ffis; for (f != nil) { let id: str = f.ident; if (streq(id, ident)) { return f.symbol; }; f = f.fnext; }; return ident; }; // ---- ABI argreg helpers --------------------------------------------- fn argreg_name(i: i32) str = { if (i == 0) { return "DI"; }; if (i == 1) { return "SI"; }; if (i == 2) { return "DX"; }; if (i == 3) { return "CX"; }; if (i == 4) { return "R8"; }; if (i == 5) { return "R9"; }; return "?"; }; // ---- expression cgen ------------------------------------------------- // push_args_rev — recursively walks the arg list, evaluates rightmost // first, and pushes. str args take two slots (ptr in AX, len in BX); // the order on the stack so a left-to-right pop into argregs lands // (ptr, len) correctly is: PUSHQ BX (top), PUSHQ AX (above) — the // pop sequence then yields AX, then BX. fn push_args_rev(c: *cgen, arg: *node) i32 = { if (arg == nil) { return 0; }; let rest: i32 = push_args_rev(c, arg.next); // N_SLICE expression as arg: `buf[lo:hi]` builds a slice header // on the stack matching C cgen's sequence — push base, push hi, // compute lo, pop into BX/CX, derive len/ptr, push (cap, len, ptr). if (arg.kind == N_SLICE) { let base: *node = arg.lhs; let lo: *node = arg.rhs; let hi: *node = arg.cond; let base_local: *local = nil; if (base != nil) { if (base.kind == N_IDENT) { let bn: str = base.str; base_local = local_find_node(c, bn); }; }; // base address → push if (base_local != nil) { let tn: *node = base_local.tnode; if (tn != nil) { if (tn.kind == N_TARRAY) { emit_line("\tLEAQ\t"); emit_off(base_local.off: i64); emit_line("(BP), AX\n"); } else { emit_line("\tMOVQ\t"); emit_off(base_local.off: i64); emit_line("(BP), AX\n"); }; } else { emit_line("\tMOVQ\t"); emit_off(base_local.off: i64); emit_line("(BP), AX\n"); }; } else { cgexpr(c, base); }; emit_line("\tPUSHQ\tAX\n"); // hi (default base length) → push if (hi != nil) { cgexpr(c, hi); } else { if (base_local != nil) { let tn: *node = base_local.tnode; if (tn != nil) { if (tn.kind == N_TARRAY) { let len_n: *node = tn.rhs; if (len_n != nil) { if (len_n.kind == N_INTLIT) { emit_line("\tMOVQ\t$"); emit_uint(len_n.uval); emit_line(", AX\n"); }; }; } else { if (tn.kind == N_TSLICE) { emit_line("\tMOVQ\t"); emit_off((base_local.off + 8): i64); emit_line("(BP), AX\n"); } else { if (tn.kind == N_TNAME) { if (streq(tn.str, "str")) { emit_line("\tMOVQ\t"); emit_off((base_local.off + 8): i64); emit_line("(BP), AX\n"); }; };};}; }; } else { emit_line("\tMOVQ\t$0, AX\n"); };}; emit_line("\tPUSHQ\tAX\n"); // lo (default 0) → AX if (lo != nil) { cgexpr(c, lo); } else { emit_line("\tMOVQ\t$0, AX\n"); }; emit_line("\tPOPQ\tBX\n"); // hi emit_line("\tPOPQ\tCX\n"); // base emit_line("\tMOVQ\tBX, DX\n"); // DX = hi emit_line("\tSUBQ\tAX, DX\n"); // DX = hi - lo = len emit_line("\tADDQ\tAX, CX\n"); // CX = base + lo = ptr emit_line("\tPUSHQ\tDX\n"); // cap emit_line("\tPUSHQ\tDX\n"); // len emit_line("\tPUSHQ\tCX\n"); // ptr (top) return rest + 3; }; // Slice/tagged ident args: emit per-register MOVQ+PUSHQ pairs in // reverse order (cap/v1, len/v0, ptr/tag) so a left-to-right pop // into argregs lands the canonical (ptr/tag, len/v0, cap/v1). if (arg.kind == N_IDENT) { let nm: str = arg.str; let lc: *local = local_find_node(c, nm); if (lc != nil) { let off: i32 = lc.off; if (is_slice_type(c, lc.tnode) || is_tagged_type(lc.tnode)) { emit_line("\tMOVQ\t"); emit_off((off + 16): i64); emit_line("(BP), AX\n"); emit_line("\tPUSHQ\tAX\n"); emit_line("\tMOVQ\t"); emit_off((off + 8): i64); emit_line("(BP), AX\n"); emit_line("\tPUSHQ\tAX\n"); emit_line("\tMOVQ\t"); emit_off(off: i64); emit_line("(BP), AX\n"); emit_line("\tPUSHQ\tAX\n"); return rest + 3; }; }; }; cgexpr(c, arg); if (node_isslice(c, arg)) { emit_line("\tPUSHQ\tCX\n"); emit_line("\tPUSHQ\tBX\n"); emit_line("\tPUSHQ\tAX\n"); return rest + 3; }; if (node_isstr(c, arg)) { emit_line("\tPUSHQ\tBX\n"); emit_line("\tPUSHQ\tAX\n"); return rest + 2; }; emit_line("\tPUSHQ\tAX\n"); return rest + 1; }; fn node_isslice(c: *cgen, n: *node) bool = { if (n == nil) { return false; }; let k: i32 = n.kind; if (k == N_IDENT) { let nm: str = n.str; let lc: *local = local_find_node(c, nm); if (lc != nil) { return is_slice_type(c, lc.tnode); }; return false; }; if (k == N_SLICE) { return true; }; return false; }; // node_isstr — best-effort surface check: does this expression // evaluate to a str value? Used to drive the call-arg push convention // (str args take two slots: ptr + len). fn node_isstr(c: *cgen, n: *node) bool = { if (n == nil) { return false; }; let k: i32 = n.kind; if (k == N_STRLIT) { return true; }; if (k == N_IDENT) { let nm: str = n.str; let lc: *local = local_find_node(c, nm); if (lc != nil) { let tn: *node = lc.tnode; if (tn != nil) { if (tn.kind == N_TNAME) { let tnm: str = tn.str; if (streq(tnm, "str")) { return true; }; }; }; }; return false; }; if (k == N_CALL) { let callee: *node = n.lhs; if (callee != nil) { if (callee.kind == N_IDENT) { let cnm: str = callee.str; let rt: *node = fnret_lookup(c, cnm); return is_str_type(c, rt); }; }; return false; }; if (k == N_DOT) { let base: *node = n.lhs; let fld: str = n.str; // `.ptr` is *u8 not str; `.len` is i32 not str. if (streq(fld, "ptr")) { return false; }; if (streq(fld, "len")) { return false; }; if (streq(fld, "cap")) { return false; }; if (base != nil) { let sname: str; sname.ptr = nil; sname.len = 0; if (base.kind == N_IDENT) { let lc: *local = local_find_node(c, base.str); if (lc != nil) { let tn: *node = lc.tnode; let lkind: i32 = -1; if (tn != nil) { lkind = tn.kind; }; if (lkind == N_TNAME) { sname = tn.str; }; if (lkind == N_TPTR) { let inner: *node = tn.lhs; if (inner != nil) { if (inner.kind == N_TNAME) { sname = inner.str; }; }; }; }; }; // Chained dot (`p.foo.bar`): use dot_inner_struct_ptr // to resolve the inner chain to the *struct it lands // on, then look up `fld` in that struct. if (base.kind == N_DOT) { let inner_t: *node = dot_inner_struct_ptr(c, base); if (inner_t != nil) { if (inner_t.kind == N_TNAME) { sname = inner_t.str; }; }; }; if (sname.len > 0) { let si: *struct_info = struct_lookup(c, sname); if (si != nil) { let fi: *field_info = si.fields; for (fi != nil) { let fn_: str = fi.fname; if (streq(fn_, fld)) { return is_str_type(c, fi.tnode); }; fi = fi.finext; }; }; }; }; return false; }; if (k == N_CAST) { return is_str_type(c, n.rhs); }; return false; }; // type_name_isunsigned — true for u8/u16/u32/u64/uint/uintptr. fn type_name_isunsigned(nm: str) bool = { if (streq(nm, "u8")) { return true; }; if (streq(nm, "u16")) { return true; }; if (streq(nm, "u32")) { return true; }; if (streq(nm, "u64")) { return true; }; if (streq(nm, "uint")) { return true; }; if (streq(nm, "uintptr")) { return true; }; return false; }; // type_node_isunsigned — recurse through TNAME / TPTR / TSLICE etc. fn type_node_isunsigned(t: *node) bool = { if (t == nil) { return false; }; if (t.kind == N_TNAME) { return type_name_isunsigned(t.str); }; return false; }; // type_is_8byte_primitive — does this type take exactly one 8-byte // slot (pointer / fn-ptr / 64-bit int / chan / scalar primitive // padded up to 8) rather than a wider aggregate? Used by N_LET // zero-init to mirror C cgen's "only zero if sz == 8 at the type // level" rule. Strings (16), slices (24), tagged unions (>=16), // tuples (16), structs (varies), arrays — all fall through to // false here even when their *slot* rounds up to 8. fn type_is_8byte_primitive(c: *cgen, t: *node) bool = { if (t == nil) { return false; }; let k: i32 = t.kind; if (k == N_TPTR) { return true; }; if (k == N_TFN) { return true; }; if (k == N_TCHAN) { return true; }; if (k == N_TSLICE) { return false; }; if (k == N_TARRAY) { return false; }; if (k == N_TTUPLE) { return false; }; if (k == N_TTAGGED){ return false; }; if (k == N_TNAME) { let nm: str = t.str; if (streq(nm, "str")) { return false; }; // Struct alias: not a primitive even if the slot is 8B. if (struct_lookup(c, nm) != nil) { return false; }; // Primitive (i8/u8/.../i64/u64/bool/rune/f32/f64/int/...). // All of these get slot-padded to 8 and zero-init in C. if (prim_size(nm) > 0) { return true; }; return false; }; return false; }; // type_name_issigned — true for i8/i16/i32/i64/int/rune. fn type_name_issigned(nm: str) bool = { if (streq(nm, "i8")) { return true; }; if (streq(nm, "i16")) { return true; }; if (streq(nm, "i32")) { return true; }; if (streq(nm, "i64")) { return true; }; if (streq(nm, "int")) { return true; }; if (streq(nm, "rune")) { return true; }; return false; }; // field_load_op — pick the load instruction for a non-str struct // field by its declared size + signedness. Mirrors the C cgen op // dispatch (MOVZBQ for u8/bool/i8, MOVSXD for i32, MOVL for u32, MOVQ // for 8-byte). f might be nil for fields outside our struct registry. fn field_load_op(f: *field_info) str = { if (f == nil) { return "MOVQ"; }; let sz: i32 = f.fsz; if (sz == 1) { return "MOVZBQ"; }; if (sz == 4) { let t: *node = f.tnode; if (t != nil) { if (t.kind == N_TNAME) { if (type_name_issigned(t.str)) { return "MOVSXD"; }; }; }; return "MOVL"; }; return "MOVQ"; }; // field_store_op — pick the store instruction for a non-str struct // field by its declared size. MOVB for 1, MOVL for 4, MOVQ for 8. fn field_store_op(f: *field_info) str = { if (f == nil) { return "MOVQ"; }; let sz: i32 = f.fsz; if (sz == 1) { return "MOVB"; }; if (sz == 4) { return "MOVL"; }; return "MOVQ"; }; // index_base_esz — element size for `arr[i]` where the base is a // chained-dot pseudo-field `s.ptr` (s being str/*str/slice/*slice). // For str the element is one byte; for `[]T` / `*[]T` we drill into // the slice element type. fn index_base_esz(c: *cgen, base: *node) i32 = { if (base == nil) { return 8; }; if (base.kind != N_DOT) { return 8; }; let fld: str = base.str; let inner: *node = base.lhs; if (inner == nil) { return 8; }; if (inner.kind != N_IDENT) { return 8; }; let nm: str = inner.str; let lc: *local = local_find_node(c, nm); if (lc == nil) { return 8; }; let tn: *node = lc.tnode; if (tn == nil) { return 8; }; // `.ptr` pseudo-field on str/slice → element of the str/slice. if (streq(fld, "ptr")) { let inner_t: *node = tn; if (tn.kind == N_TPTR) { inner_t = tn.lhs; }; if (inner_t == nil) { return 8; }; if (inner_t.kind == N_TNAME) { if (streq(inner_t.str, "str")) { return 1; }; }; if (inner_t.kind == N_TSLICE) { return elem_size_of(inner_t); }; return 8; }; // Generic struct field: if it's *T, element size is T's size. let lkind: i32 = tn.kind; let sname: str; sname.ptr = nil; sname.len = 0; if (lkind == N_TNAME) { sname = tn.str; }; if (lkind == N_TPTR) { let pinner: *node = tn.lhs; if (pinner != nil) { if (pinner.kind == N_TNAME) { sname = pinner.str; }; }; }; if (sname.len == 0) { return 8; }; let si: *struct_info = struct_lookup(c, sname); if (si == nil) { return 8; }; let fi: *field_info = si.fields; for (fi != nil) { let fn_: str = fi.fname; if (streq(fn_, fld)) { let ft: *node = fi.tnode; if (ft == nil) { return 8; }; if (ft.kind == N_TPTR) { let elem: *node = ft.lhs; if (elem != nil) { if (elem.kind == N_TNAME) { if (streq(elem.str, "str")) { return 16; }; let ps: i32 = prim_size(elem.str); if (ps > 0) { return ps; }; }; }; return 8; }; if (ft.kind == N_TSLICE) { return elem_size_of(ft); }; // str-typed field: indexing yields one byte // (`n.s[i]` where .s is str — matches C cgen's // MOVZBQ for byte indexing). if (ft.kind == N_TNAME) { if (streq(ft.str, "str")) { return 1; }; }; return 8; }; fi = fi.finext; }; return 8; }; // dot_inner_struct_ptr — for an N_DOT whose lhs is a chain of dots // or an N_IDENT, walk the chain and return the N_TNAME tnode of the // struct that the chain dereferences to (i.e., for `r.sym` where // .sym is *lsym, return N_TNAME("lsym")). Returns nil if the chain // doesn't resolve to a *struct. // // Used by the chained-DOT cgen path so `r.sym.val` knows the outer // is a field of `lsym`. fn dot_inner_struct_ptr(c: *cgen, n: *node) *node = { if (n == nil) { return nil; }; if (n.kind != N_DOT) { return nil; }; let base: *node = n.lhs; let fld: str = n.str; if (base == nil) { return nil; }; // Resolve base's struct tnode. let base_t: *node = nil; if (base.kind == N_IDENT) { let lc: *local = local_find_node(c, base.str); if (lc == nil) { return nil; }; let tn: *node = lc.tnode; if (tn == nil) { return nil; }; // base could be either struct-by-value (N_TNAME) or *struct (N_TPTR). if (tn.kind == N_TNAME) { base_t = tn; }; if (tn.kind == N_TPTR) { base_t = tn.lhs; }; } else { if (base.kind == N_DOT) { base_t = dot_inner_struct_ptr(c, base); };}; if (base_t == nil) { return nil; }; if (base_t.kind != N_TNAME) { return nil; }; // Look up the struct, find the field, return the field's *struct. let si: *struct_info = struct_lookup(c, base_t.str); if (si == nil) { return nil; }; let fi: *field_info = si.fields; for (fi != nil) { if (streq(fi.fname, fld)) { let ft: *node = fi.tnode; if (ft == nil) { return nil; }; if (ft.kind != N_TPTR) { return nil; }; let inner: *node = ft.lhs; if (inner == nil) { return nil; }; if (inner.kind != N_TNAME) { return nil; }; return inner; }; fi = fi.finext; }; return nil; }; // elem_size_of — given the type node of an indexable (`*T`, `[]T`, // `[N]T`, `str`), return the byte size of one element (1 for u8/i8/ // bool/str-byte, 8 otherwise — same shape as C cgen's esz fallback). fn elem_size_of(t: *node) i32 = { if (t == nil) { return 1; }; let k: i32 = t.kind; let elem: *node = nil; if (k == N_TPTR) { elem = t.lhs; }; if (k == N_TSLICE) { elem = t.lhs; }; if (k == N_TARRAY) { elem = t.lhs; }; if (k == N_TNAME) { let nm: str = t.str; if (streq(nm, "str")) { return 1; }; // Indexing a primitive name (rare): element size = the prim. let ps: i32 = prim_size(nm); if (ps > 0) { return ps; }; return 1; }; if (elem == nil) { return 1; }; if (elem.kind == N_TNAME) { let nm: str = elem.str; // str element is 16B (ptr+len). prim_size returns 0 for it. if (streq(nm, "str")) { return 16; }; let ps: i32 = prim_size(nm); if (ps > 0) { return ps; }; }; return 8; }; // node_isunsigned — best-effort cgen-time inference from the AST. We // don't have a typed AST yet, so we walk surface nodes: // N_INTLIT — never marked unsigned (no tsuffix plumbing yet) // N_IDENT — look up the local's declared type // N_DOT — look up the field's declared type via struct reg // N_BIN / N_UN — recurse: unsigned if either operand is unsigned // N_CAST — use the cast target type // // Conservative: if we can't tell, return false (signed). The cost of // being wrong here is byte-different asm vs C, not bad runtime. fn node_isunsigned(c: *cgen, n: *node) bool = { if (n == nil) { return false; }; let k: i32 = n.kind; if (k == N_IDENT) { let nm: str = n.str; let lc: *local = local_find_node(c, nm); if (lc != nil) { return type_node_isunsigned(lc.tnode); }; return false; }; if (k == N_DOT) { let base: *node = n.lhs; let fld: str = n.str; if (base != nil) { if (base.kind == N_IDENT) { let bn: str = base.str; let lc: *local = local_find_node(c, bn); if (lc != nil) { let tn: *node = lc.tnode; let lkind: i32 = -1; if (tn != nil) { lkind = tn.kind; }; let sname: str; sname.ptr = nil; sname.len = 0; if (lkind == N_TPTR) { let inner: *node = tn.lhs; if (inner != nil) { if (inner.kind == N_TNAME) { sname = inner.str; }; }; }; if (lkind == N_TNAME) { sname = tn.str; }; if (sname.len > 0) { let si: *struct_info = struct_lookup(c, sname); if (si != nil) { let fi: *field_info = si.fields; for (fi != nil) { let fn_: str = fi.fname; if (streq(fn_, fld)) { return type_node_isunsigned(fi.tnode); }; fi = fi.finext; }; }; }; }; }; }; return false; }; if (k == N_CAST) { return type_node_isunsigned(n.rhs); }; if (k == N_BIN) { if (node_isunsigned(c, n.lhs)) { return true; }; return node_isunsigned(c, n.rhs); }; if (k == N_UN) { return node_isunsigned(c, n.lhs); }; // N_INDEX: `p[i]` is unsigned iff p's element type is unsigned. // Walks the base local's declared type and pulls the element // out — *u8 → u8, [N]u32 → u32, []u64 → u64. Without this the // compare-codegen for `p[i] >= 48u8` falls back to signed JGE // instead of JAE, diverging from C 6c on byte indexing. if (k == N_INDEX) { let base: *node = n.lhs; if (base != nil) { if (base.kind == N_IDENT) { let lc: *local = local_find_node(c, base.str); if (lc != nil) { let tn: *node = lc.tnode; if (tn != nil) { let elem: *node = nil; if (tn.kind == N_TPTR) { elem = tn.lhs; }; if (tn.kind == N_TARRAY) { elem = tn.lhs; }; if (tn.kind == N_TSLICE) { elem = tn.lhs; }; if (elem != nil) { return type_node_isunsigned(elem); }; }; }; }; }; return false; }; return false; }; fn cgexpr(c: *cgen, n: *node) void = { if (n == nil) { return; }; let k: i32 = n.kind; if (k == N_INTLIT) { // Print signed (i64), not unsigned (u64). C cgen uses // `$%lld` so 64-bit constants with bit 63 set show up as // negative — e.g. FNV-1a's offset basis prints as // $-3750763034362895579, not $14695981039346656037. emit_line("\tMOVQ\t$"); emit_int(n.uval: i64); emit_line(", AX\n"); return; }; if (k == N_RUNELIT) { emit_line("\tMOVQ\t$"); emit_int(n.uval: i64); emit_line(", AX\n"); return; }; if (k == N_STRLIT) { // Result is the (ptr, len) pair: ptr in AX, len in BX. Call // sites that expect a str arg pick these up directly. let nstr: str = n.str; let lab: str = intern_strlit(c, nstr); emit_line("\tLEAQ\t"); os.write(1, lab.ptr, lab.len: u64); emit_line("(SB), AX\n"); emit_line("\tMOVQ\t$"); emit_int(nstr.len: i64); emit_line(", BX\n"); return; }; if (k == N_TRUE) { emit_line("\tMOVQ\t$1, AX\n"); return; }; if (k == N_FALSE) { emit_line("\tMOVQ\t$0, AX\n"); return; }; if (k == N_NIL) { emit_line("\tMOVQ\t$0, AX\n"); return; }; if (k == N_IDENT) { let nm: str = n.str; let lc: *local = local_find_node(c, nm); if (lc != nil) { let off: i32 = lc.off; emit_line("\tMOVQ\t"); emit_off(off: i64); emit_line("(BP), AX\n"); // str local: also load the len half into BX. if (is_str_type(c, lc.tnode)) { emit_line("\tMOVQ\t"); emit_off((off + 8): i64); emit_line("(BP), BX\n"); }; // slice local: load (ptr, len, cap) into (AX, BX, CX). if (is_slice_type(c, lc.tnode)) { emit_line("\tMOVQ\t"); emit_off((off + 8): i64); emit_line("(BP), BX\n"); emit_line("\tMOVQ\t"); emit_off((off + 16): i64); emit_line("(BP), CX\n"); }; return; }; // Top-level `def` constant — load from its DATA symbol. if (def_lookup(c, nm)) { emit_line("\tMOVQ\t"); os.write(1, nm.ptr, nm.len: u64); emit_line("(SB), AX\n"); return; }; // Fn-name used as a value (e.g. `let f = some_fn;` or // `... = some_fn;`). LEAQ the symbol address into AX — // resolved through ffi_resolve so a body-less FFI binding // emits the C symbol it was declared with via @symbol(), // not the ww-side ident. let rt: *node = fnret_lookup(c, nm); if (rt != nil) { let resolved: str = ffi_resolve(c, nm); emit_line("\tLEAQ\t"); os.write(1, resolved.ptr, resolved.len: u64); emit_line("(SB), AX\n"); return; }; return; }; if (k == N_INDEX) { // Element-size-aware load: u8-element bases use MOVZBQ, // everything else MOVQ. Fast path when the base is a bare // ident (mem.ww shape). let base: *node = n.lhs; let idx: *node = n.rhs; let esz: i32 = 8; let base_local: *local = nil; if (base != nil) { if (base.kind == N_IDENT) { let bn: str = base.str; base_local = local_find_node(c, bn); if (base_local != nil) { esz = elem_size_of(base_local.tnode); }; } else { if (base.kind == N_DOT) { esz = index_base_esz(c, base); };}; }; cgexpr(c, idx); if (esz > 1) { emit_line("\tMOVQ\t$"); emit_int(esz: i64); emit_line(", CX\n"); emit_line("\tIMULQ\tCX, AX\n"); }; if (base_local != nil) { let tn: *node = base_local.tnode; let is_array: bool = false; if (tn != nil) { if (tn.kind == N_TARRAY) { is_array = true; }; }; if (is_array) { emit_line("\tLEAQ\t"); emit_off(base_local.off: i64); emit_line("(BP), BX\n"); } else { emit_line("\tMOVQ\t"); emit_off(base_local.off: i64); emit_line("(BP), BX\n"); }; emit_line("\tADDQ\tAX, BX\n"); // str element (16B): load (ptr, len) into (AX, BX) so // the value flows through the str-rhs convention. if (esz == 16) { emit_line("\tMOVQ\t8(BX), CX\n"); emit_line("\tMOVQ\t(BX), AX\n"); emit_line("\tMOVQ\tCX, BX\n"); return; }; if (esz == 1) { emit_line("\tMOVZBQ\t(BX), AX\n"); } else { emit_line("\tMOVQ\t(BX), AX\n"); }; return; }; // Generic fallback when base isn't a plain ident. emit_line("\tPUSHQ\tAX\n"); cgexpr(c, base); emit_line("\tPOPQ\tBX\n"); emit_line("\tADDQ\tBX, AX\n"); if (esz == 16) { emit_line("\tMOVQ\t8(AX), BX\n"); emit_line("\tMOVQ\t(AX), AX\n"); return; }; if (esz == 1) { emit_line("\tMOVZBQ\t(AX), AX\n"); } else { emit_line("\tMOVQ\t(AX), AX\n"); }; return; }; if (k == N_MATCH) { // match (e) { case let v: T => stmt; ... } // // Read the tagged-union slot and dispatch by tag. Slot // layout: [+0]=tag, [+8]=value0, [+16]=value1. Bindings // (`case let v: T =>`) get a fresh local slot loaded from // slot+8 (and slot+16 for str-typed payload). let scrut: *node = n.lhs; let scrut_off: i32 = 0; let scrut_t: *node = nil; if (scrut != nil) { if (scrut.kind == N_IDENT) { let lc: *local = local_find_node(c, scrut.str); if (lc != nil) { scrut_off = lc.off; scrut_t = resolve_type(c, lc.tnode); }; }; }; let endl: str = mklabel(c, "match_end"); let cs: *node = n.list; for (cs != nil) { let nxt: str = mklabel(c, "match_next"); let pat: *node = cs.lhs; // Compute the variant tag for this arm. Default arm // (no pattern) skips the tag check. if (pat != nil) { let want: i32 = 0; if (scrut_t != nil) { if (scrut_t.kind == N_TTAGGED) { let pat_name: str; pat_name.ptr = nil; pat_name.len = 0; if (pat.kind == N_TNAME) { pat_name = pat.str; }; let v: *node = scrut_t.list; let idx: i32 = 0; let found: bool = false; for (v != nil) { if (v.kind == N_TNAME) { if (streq(v.str, pat_name)) { want = idx; found = true; v = nil; }; }; if (v != nil) { v = v.next; idx += 1; }; }; if (!found) { want = 0; }; }; }; emit_line("\tMOVQ\t"); emit_off(scrut_off: i64); emit_line("(BP), AX\n"); emit_line("\tCMPQ\t$"); emit_int(want: i64); emit_line(", AX\n"); emit_line("\tJNE\t"); emit_line(nxt); emit_line("\n"); }; // Bind `let v: T` from the slot, if requested. let bn: str = cs.str; if (bn.len > 0) { if (pat != nil) { let bsz: i32 = 8; if (is_str_type(c, pat)) { bsz = 16; }; // local_alloc (not local_add): match-arm // binds don't dedup with same-named binds // in *other* matches, since C's cgexpr // allocates a fresh slot per match expr. let voff: i32 = local_alloc(c, bn, bsz, pat); emit_line("\tMOVQ\t"); emit_off((scrut_off + 8): i64); emit_line("(BP), AX\n"); emit_line("\tMOVQ\tAX, "); emit_off(voff: i64); emit_line("(BP)\n"); if (bsz == 16) { emit_line("\tMOVQ\t"); emit_off((scrut_off + 16): i64); emit_line("(BP), AX\n"); emit_line("\tMOVQ\tAX, "); emit_off((voff + 8): i64); emit_line("(BP)\n"); }; }; }; // Body. Match arms are statements; we cgstmt them. if (cs.body != nil) { cgstmt(c, cs.body); }; emit_line("\tJMP\t"); emit_line(endl); emit_line("\n"); emit_label(nxt); cs = cs.next; }; emit_label(endl); return; }; if (k == N_CAST) { // Type casts are mostly no-ops at the asm level for our // integer-shaped operands. Evaluate the source; AX holds // the bits unchanged. (Sign- or zero-extending narrow loads // to wider types is the loader's job, not cast's, in this // minimal cgen.) cgexpr(c, n.lhs); return; }; if (k == N_DOT) { let lhs: *node = n.lhs; let fld: str = n.str; if (lhs != nil) { if (lhs.kind == N_IDENT) { let nm: str = lhs.str; let lc: *local = local_find_node(c, nm); if (lc != nil) { let tn: *node = lc.tnode; let lkind: i32 = -1; if (tn != nil) { lkind = tn.kind; }; // Pointer-to-struct: deref then field load. if (lkind == N_TPTR) { let inner: *node = tn.lhs; let sname: str; sname.ptr = nil; sname.len = 0; if (inner != nil) { if (inner.kind == N_TNAME) { sname = inner.str; }; }; if (sname.len > 0) { let si: *struct_info = struct_lookup(c, sname); if (si != nil) { let fi: *field_info = si.fields; for (fi != nil) { let fn_: str = fi.fname; if (streq(fn_, fld)) { // str field via *struct: load len into a // scratch first (so loading ptr into AX // last leaves (AX=ptr, BX=len)). emit_line("\tMOVQ\t"); emit_off(lc.off: i64); emit_line("(BP), BX\n"); if (is_str_type(c, fi.tnode)) { emit_line("\tMOVQ\t"); emit_disp_reg((fi.foff + 8): i64, "BX"); emit_line(", CX\n"); emit_line("\tMOVQ\t"); emit_disp_reg(fi.foff: i64, "BX"); emit_line(", AX\n"); emit_line("\tMOVQ\tCX, BX\n"); } else { let op: str = field_load_op(fi); emit_line("\t"); emit_line(op); emit_line("\t"); emit_disp_reg(fi.foff: i64, "BX"); emit_line(", AX\n"); }; return; }; fi = fi.finext; }; }; }; }; // Direct struct local: field load at off+foff. if (lkind == N_TNAME) { let sname: str = tn.str; let si: *struct_info = struct_lookup(c, sname); if (si != nil) { let fi: *field_info = si.fields; for (fi != nil) { let fn_: str = fi.fname; if (streq(fn_, fld)) { // str field: load both halves so chained // `.ptr` / `.len` see (AX=ptr, BX=len). if (is_str_type(c, fi.tnode)) { emit_line("\tMOVQ\t"); emit_off((lc.off + fi.foff): i64); emit_line("(BP), AX\n"); emit_line("\tMOVQ\t"); emit_off((lc.off + fi.foff + 8): i64); emit_line("(BP), BX\n"); } else { let op: str = field_load_op(fi); emit_line("\t"); emit_line(op); emit_line("\t"); emit_off((lc.off + fi.foff): i64); emit_line("(BP), AX\n"); }; return; }; fi = fi.finext; }; }; }; // Array pseudo-fields: `.ptr` is the array's // address (LEAQ); `.len` is the static element // count (immediate). if (lkind == N_TARRAY) { if (streq(fld, "ptr")) { emit_line("\tLEAQ\t"); emit_off(lc.off: i64); emit_line("(BP), AX\n"); return; }; if (streq(fld, "len")) { let len_n: *node = tn.rhs; let alen: i64 = 0i64; if (len_n != nil) { if (len_n.kind == N_INTLIT) { alen = len_n.uval: i64; }; }; emit_line("\tMOVQ\t$"); emit_int(alen); emit_line(", AX\n"); return; }; }; // str/slice pseudo-fields .ptr/.len/.cap on a // direct local: load at slot+delta. let delta: i32 = -1; if (streq(fld, "ptr")) { delta = 0; }; if (streq(fld, "len")) { delta = 8; }; if (streq(fld, "cap")) { delta = 16; }; if (delta >= 0) { // Pointer to str/slice (`*[]u8`, `*str`): // deref, then load at delta within the // pointed-to header. C cgen does the same. if (lkind == N_TPTR) { let inner: *node = tn.lhs; let inner_kind: i32 = -1; if (inner != nil) { inner_kind = inner.kind; }; let inner_str: bool = false; if (inner_kind == N_TNAME) { if (streq(inner.str, "str")) { inner_str = true; }; }; if (inner_kind == N_TSLICE) { inner_str = true; }; if (inner_str) { emit_line("\tMOVQ\t"); emit_off(lc.off: i64); emit_line("(BP), BX\n"); emit_line("\tMOVQ\t"); emit_disp_reg(delta: i64, "BX"); emit_line(", AX\n"); return; }; }; emit_line("\tMOVQ\t"); emit_off((lc.off + delta): i64); emit_line("(BP), AX\n"); return; }; }; }; }; // Module-qualified value reference: `mod.name` where `mod` // is N_IDENT bound as SK_USE and the leaf isn't a local. // Treat as a SB symbol — `MOVQ leaf(SB), AX`. Same fallback // the C cgen takes when bt is NULL/ty_err. if (lhs != nil) { if (lhs.kind == N_IDENT) { emit_line("\tMOVQ\t"); emit_line(fld); emit_line("(SB), AX\n"); return; }; }; // Non-ident base pseudo-field: e.g. `"abc".ptr` / `"abc".len`. // Evaluate the str-producing expression — that leaves // (AX=ptr, BX=len). Then `.ptr` returns AX as is; `.len` // shuffles BX→AX. Mirrors what C cgen does (it just evaluates // the literal and picks the half it wants). if (streq(fld, "ptr")) { cgexpr(c, lhs); return; }; if (streq(fld, "len")) { cgexpr(c, lhs); emit_line("\tMOVQ\tBX, AX\n"); return; }; // Chained struct-field-via-ptr-via-ptr access: // r.sym.val where r: *lrel, .sym: *lsym, .val: u64 // Inner DOT (`r.sym`) returns a *struct (a pointer-to-struct // field). Outer DOT dereferences and reads `val`. Without this // path the cgen falls through and AX retains whatever the // inner expression left there — typically the *struct pointer // itself, so reads silently get the pointer value instead of // the field. (Showed up porting 6l/pass.ww.) if (lhs != nil) { if (lhs.kind == N_DOT) { let inner_t: *node = dot_inner_struct_ptr(c, lhs); if (inner_t != nil) { let sname: str = inner_t.str; let si: *struct_info = struct_lookup(c, sname); if (si != nil) { let fi: *field_info = si.fields; for (fi != nil) { if (streq(fi.fname, fld)) { cgexpr(c, lhs); // AX = ptr to inner struct let lop: str = field_load_op(fi); // str field: load both halves. if (is_str_type(c, fi.tnode)) { emit_line("\tMOVQ\t"); emit_disp_reg((fi.foff + 8): i64, "AX"); emit_line(", BX\n"); emit_line("\tMOVQ\t"); emit_disp_reg(fi.foff: i64, "AX"); emit_line(", AX\n"); return; }; emit_line("\t"); emit_line(lop); emit_line("\t"); emit_disp_reg(fi.foff: i64, "AX"); emit_line(", AX\n"); return; }; fi = fi.finext; }; }; }; }; }; return; }; if (k == N_UN) { // Match C cgen ordering: evaluate operand first (load into AX), // then apply the unary op. AMP / STAR override AX with the // address / deref. The wasted load before AMP keeps our asm // byte-identical to the C version. cgexpr(c, n.lhs); if (n.op == TK_MINUS) { emit_line("\tNEGQ\tAX\n"); return; }; if (n.op == TK_TILDE) { emit_line("\tNOTQ\tAX\n"); return; }; if (n.op == TK_STAR) { emit_line("\tMOVQ\t(AX), AX\n"); return; }; if (n.op == TK_AMP) { let opnd: *node = n.lhs; if (opnd != nil) { if (opnd.kind == N_IDENT) { let nm: str = opnd.str; let off: i32 = local_find(c, nm); if (off != 0) { emit_line("\tLEAQ\t"); emit_off(off: i64); emit_line("(BP), AX\n"); return; }; }; }; return; }; if (n.op == TK_NOT) { let t: str = mklabel(c, "tt"); let e: str = mklabel(c, "te"); emit_line("\tCMPQ\t$0, AX\n"); emit_line("\tJE\t"); emit_line(t); emit_line("\n"); emit_line("\tMOVQ\t$0, AX\n"); emit_line("\tJMP\t"); emit_line(e); emit_line("\n"); emit_label(t); emit_line("\tMOVQ\t$1, AX\n"); emit_label(e); return; }; return; }; if (k == N_BIN) { let unsignd: bool = node_isunsigned(c, n.lhs); if (!unsignd) { unsignd = node_isunsigned(c, n.rhs); }; cgexpr(c, n.rhs); emit_line("\tPUSHQ\tAX\n"); cgexpr(c, n.lhs); emit_line("\tPOPQ\tBX\n"); if (n.op == TK_PLUS) { emit_line("\tADDQ\tBX, AX\n"); return; }; if (n.op == TK_MINUS) { emit_line("\tSUBQ\tBX, AX\n"); return; }; if (n.op == TK_STAR) { emit_line("\tIMULQ\tBX, AX\n"); return; }; if (n.op == TK_SLASH) { emit_line("\tMOVQ\t$0, DX\n"); if (unsignd) { emit_line("\tDIVQ\tBX\n"); } else { emit_line("\tIDIVQ\tBX\n"); }; return; }; if (n.op == TK_PERCENT) { emit_line("\tMOVQ\t$0, DX\n"); if (unsignd) { emit_line("\tDIVQ\tBX\n"); } else { emit_line("\tIDIVQ\tBX\n"); }; emit_line("\tMOVQ\tDX, AX\n"); return; }; if (n.op == TK_AMP) { emit_line("\tANDQ\tBX, AX\n"); return; }; if (n.op == TK_PIPE) { emit_line("\tORQ\tBX, AX\n"); return; }; if (n.op == TK_CARET) { emit_line("\tXORQ\tBX, AX\n"); return; }; if (n.op == TK_LSHIFT) { emit_line("\tMOVQ\tBX, CX\n"); emit_line("\tSHLQ\tCX, AX\n"); return; }; if (n.op == TK_RSHIFT) { emit_line("\tMOVQ\tBX, CX\n"); emit_line("\tSHRQ\tCX, AX\n"); return; }; if (n.op == TK_AND) { emit_line("\tANDQ\tBX, AX\n"); return; }; if (n.op == TK_OR) { emit_line("\tORQ\tBX, AX\n"); return; }; // Comparison: emit CMPQ, jump on signed/unsigned variant, // materialise 0/1 in AX. Same shape as the C cgen. let is_cmp: bool = false; let jcc: str = ""; if (n.op == TK_EQ) { is_cmp = true; jcc = "JE"; }; if (n.op == TK_NEQ) { is_cmp = true; jcc = "JNE"; }; if (n.op == TK_LT) { is_cmp = true; if (unsignd) { jcc = "JB"; } else { jcc = "JL"; }; }; if (n.op == TK_LE) { is_cmp = true; if (unsignd) { jcc = "JBE"; } else { jcc = "JLE"; }; }; if (n.op == TK_GT) { is_cmp = true; if (unsignd) { jcc = "JA"; } else { jcc = "JG"; }; }; if (n.op == TK_GE) { is_cmp = true; if (unsignd) { jcc = "JAE"; } else { jcc = "JGE"; }; }; if (is_cmp) { let t: str = mklabel(c, "ct"); let e: str = mklabel(c, "ce"); emit_line("\tCMPQ\tBX, AX\n"); emit_line("\t"); emit_line(jcc); emit_line("\t"); emit_line(t); emit_line("\n"); emit_line("\tMOVQ\t$0, AX\n"); emit_line("\tJMP\t"); emit_line(e); emit_line("\n"); emit_label(t); emit_line("\tMOVQ\t$1, AX\n"); emit_label(e); return; }; return; }; if (k == N_CALL) { let nargs: i32 = push_args_rev(c, n.list); let i: i32 = 0; for (i < nargs) { emit_line("\tPOPQ\t"); emit_line(argreg_name(i)); emit_line("\n"); i += 1; }; let callee: *node = n.lhs; let callee_name: str; callee_name.ptr = nil; callee_name.len = 0; // Detect fn-pointer field call: `w.emit(args)` where `w` is // a struct local and `emit` is an N_TFN field. Load the // field value into AX and CALL through it. Also detect a // bare `fp(args)` where `fp` is a local holding a function // pointer — mirror C cgen's localfind dispatch (commit // 635818e). Without this the call emits `CALL fp(SB)` and // the linker rightly fails. let is_fnptr_call: bool = false; if (callee != nil) { if (callee.kind == N_IDENT) { let cn: str = callee.str; if (local_find_node(c, cn) != nil) { is_fnptr_call = true; }; }; if (callee.kind == N_DOT) { let base: *node = callee.lhs; let fld: str = callee.str; if (base != nil) { if (base.kind == N_IDENT) { let bn: str = base.str; let lc: *local = local_find_node(c, bn); if (lc != nil) { let tn: *node = lc.tnode; if (tn != nil) { let lkind: i32 = tn.kind; let sname: str; sname.ptr = nil; sname.len = 0; if (lkind == N_TNAME) { sname = tn.str; }; if (lkind == N_TPTR) { let inner: *node = tn.lhs; if (inner != nil) { if (inner.kind == N_TNAME) { sname = inner.str; }; }; }; if (sname.len > 0) { let si: *struct_info = struct_lookup(c, sname); if (si != nil) { let fi: *field_info = si.fields; for (fi != nil) { let fn_: str = fi.fname; if (streq(fn_, fld)) { let ft: *node = fi.tnode; if (ft != nil) { if (ft.kind == N_TFN) { is_fnptr_call = true; }; }; fi = nil; } else { fi = fi.finext; }; }; }; }; }; }; }; }; }; }; if (is_fnptr_call) { // Load fn-ptr field value into AX; CALL AX. We emit the // load AFTER the args have been popped (so AX/BX/etc // don't get clobbered by the field load before the pops). // `popped args` left DI/SI/etc set; AX is free. cgexpr(c, callee); emit_line("\tCALL\tAX\n"); } else { emit_line("\tCALL\t"); if (callee != nil) { if (callee.kind == N_IDENT) { callee_name = callee.str; let resolved: str = ffi_resolve(c, callee_name); os.write(1, resolved.ptr, resolved.len: u64); } else { if (callee.kind == N_DOT) { callee_name = callee.str; let resolved: str = ffi_resolve(c, callee_name); os.write(1, resolved.ptr, resolved.len: u64); };}; }; emit_line("(SB)\n"); }; // SysV returns 16-byte aggregates in (AX, DX). Our str // convention is (AX, BX), so shuffle for str-returning calls. if (callee_name.len > 0) { let rt: *node = fnret_lookup(c, callee_name); if (is_str_type(c, rt)) { emit_line("\tMOVQ\tDX, BX\n"); }; }; return; }; if (k == N_ASSIGN) { let lhs: *node = n.lhs; // `*p = v` — deref-assign. Element width comes from the // pointer's declared type. Mirrors C cgen: eval rhs (AX, // and BX if str), push, eval pointer, pop value, store. // We default to MOVQ (8B) since most fixtures use it; for // `*bool` / `*u8` / `*i32` we narrow via the local's tnode. if (lhs != nil) { if (lhs.kind == N_UN) { if (lhs.op == TK_STAR) { if (n.op == TK_ASSIGN) { let inner: *node = lhs.lhs; let elem_str: bool = false; let store_op: str = "MOVQ"; if (inner != nil) { if (inner.kind == N_IDENT) { let lc: *local = local_find_node(c, inner.str); if (lc != nil) { let tn: *node = lc.tnode; if (tn != nil) { if (tn.kind == N_TPTR) { let pe: *node = tn.lhs; if (pe != nil) { if (pe.kind == N_TNAME) { if (streq(pe.str, "str")) { elem_str = true; } else { let ps: i32 = prim_size(pe.str); if (ps == 1) { store_op = "MOVB"; } else { if (ps == 4) { store_op = "MOVL"; }; }; }; }; }; }; }; }; }; }; cgexpr(c, n.rhs); // Push order matches C cgen // (cmd/6c/cgen.c:1033-1041): PUSHQ AX // (ptr) first, then PUSHQ BX (len) if // str, so the pop sequence is POP CX // (len) → POP AX (ptr) → MOVQ AX, // (BX) → MOVQ CX, 8(BX). emit_line("\tPUSHQ\tAX\n"); if (elem_str) { emit_line("\tPUSHQ\tBX\n"); }; cgexpr(c, inner); emit_line("\tMOVQ\tAX, BX\n"); if (elem_str) { emit_line("\tPOPQ\tCX\n"); emit_line("\tPOPQ\tAX\n"); emit_line("\tMOVQ\tAX, (BX)\n"); emit_line("\tMOVQ\tCX, 8(BX)\n"); return; }; emit_line("\tPOPQ\tAX\n"); emit_line("\t"); emit_line(store_op); emit_line("\tAX, (BX)\n"); return; }; }; }; }; // Array/slice/ptr index store: `arr[i] = v;`. Element size // from base.tnode picks MOVB vs MOVQ. if (lhs != nil) { if (lhs.kind == N_INDEX) { if (n.op == TK_ASSIGN) { let base: *node = lhs.lhs; let idx: *node = lhs.rhs; let esz: i32 = 8; let base_local: *local = nil; if (base != nil) { if (base.kind == N_IDENT) { let bn: str = base.str; base_local = local_find_node(c, bn); if (base_local != nil) { esz = elem_size_of(base_local.tnode); }; } else { if (base.kind == N_DOT) { esz = index_base_esz(c, base); };}; }; cgexpr(c, n.rhs); // value → AX if (esz == 16) { emit_line("\tPUSHQ\tBX\n"); }; emit_line("\tPUSHQ\tAX\n"); cgexpr(c, idx); // idx → AX if (esz > 1) { emit_line("\tMOVQ\t$"); emit_int(esz: i64); emit_line(", CX\n"); emit_line("\tIMULQ\tCX, AX\n"); }; emit_line("\tPUSHQ\tAX\n"); // scaled idx if (base_local != nil) { let tn: *node = base_local.tnode; let is_array: bool = false; if (tn != nil) { if (tn.kind == N_TARRAY) { is_array = true; }; }; if (is_array) { emit_line("\tLEAQ\t"); emit_off(base_local.off: i64); emit_line("(BP), BX\n"); } else { emit_line("\tMOVQ\t"); emit_off(base_local.off: i64); emit_line("(BP), BX\n"); }; } else { cgexpr(c, base); emit_line("\tMOVQ\tAX, BX\n"); }; emit_line("\tPOPQ\tAX\n"); // scaled idx emit_line("\tADDQ\tAX, BX\n"); emit_line("\tPOPQ\tAX\n"); // value if (esz == 16) { emit_line("\tMOVQ\tAX, (BX)\n"); emit_line("\tPOPQ\tCX\n"); emit_line("\tMOVQ\tCX, 8(BX)\n"); return; }; if (esz == 1) { emit_line("\tMOVB\tAX, (BX)\n"); } else { emit_line("\tMOVQ\tAX, (BX)\n"); }; return; }; }; }; // Struct/ptr-to-struct field assignment: `s.f = expr;` or // `p.f = expr;`. Only plain `=` is wired (compound on field // is rare and not yet needed by our fixtures). if (lhs != nil) { if (lhs.kind == N_DOT) { let base: *node = lhs.lhs; let fld: str = lhs.str; if (base != nil) { if (base.kind == N_IDENT) { let bn: str = base.str; let lc: *local = local_find_node(c, bn); if (lc != nil) { let tn: *node = lc.tnode; let lkind: i32 = -1; if (tn != nil) { lkind = tn.kind; }; // Pointer-to-struct: deref then store. if (lkind == N_TPTR) { let inner: *node = tn.lhs; let sname: str; sname.ptr = nil; sname.len = 0; if (inner != nil) { if (inner.kind == N_TNAME) { sname = inner.str; }; }; if (sname.len > 0) { let si: *struct_info = struct_lookup(c, sname); if (si != nil) { let fi: *field_info = si.fields; for (fi != nil) { let fn_: str = fi.fname; if (streq(fn_, fld)) { if (n.op != TK_ASSIGN) { // compound: load current value emit_line("\tMOVQ\t"); emit_off(lc.off: i64); emit_line("(BP), BX\n"); let lop: str = field_load_op(fi); emit_line("\t"); emit_line(lop); emit_line("\t"); emit_disp_reg(fi.foff: i64, "BX"); emit_line(", BX\n"); emit_line("\tPUSHQ\tBX\n"); }; cgexpr(c, n.rhs); if (n.op != TK_ASSIGN) { emit_line("\tPOPQ\tBX\n"); // PLUSEQ is commutative; MINUSEQ // needs lhs - rhs (BX is old lhs, // AX is rhs). if (n.op == TK_PLUSEQ) { emit_line("\tADDQ\tBX, AX\n"); }; if (n.op == TK_MINUSEQ) { emit_line("\tSUBQ\tAX, BX\n"); emit_line("\tMOVQ\tBX, AX\n"); }; }; // str field via *struct: rhs left // (AX=ptr, BX=len). Use CX as the // address scratch so we don't clobber // the len half before storing it. if (n.op == TK_ASSIGN) { if (is_str_type(c, fi.tnode)) { emit_line("\tMOVQ\t"); emit_off(lc.off: i64); emit_line("(BP), CX\n"); emit_line("\tMOVQ\tAX, "); emit_disp_reg(fi.foff: i64, "CX"); emit_line("\n"); emit_line("\tMOVQ\tBX, "); emit_disp_reg((fi.foff + 8): i64, "CX"); emit_line("\n"); return; }; }; emit_line("\tMOVQ\t"); emit_off(lc.off: i64); emit_line("(BP), BX\n"); let sop: str = field_store_op(fi); emit_line("\t"); emit_line(sop); emit_line("\tAX, "); emit_disp_reg(fi.foff: i64, "BX"); emit_line("\n"); return; }; fi = fi.finext; }; }; }; }; // Direct struct local: store at off+foff. if (lkind == N_TNAME) { let sname: str = tn.str; let si: *struct_info = struct_lookup(c, sname); if (si != nil) { let fi: *field_info = si.fields; for (fi != nil) { let fn_: str = fi.fname; if (streq(fn_, fld)) { cgexpr(c, n.rhs); let sop: str = field_store_op(fi); emit_line("\t"); emit_line(sop); emit_line("\tAX, "); emit_off((lc.off + fi.foff): i64); emit_line("(BP)\n"); return; }; fi = fi.finext; }; }; }; // str/slice pseudo-field assignment. let delta: i32 = -1; if (streq(fld, "ptr")) { delta = 0; }; if (streq(fld, "len")) { delta = 8; }; if (streq(fld, "cap")) { delta = 16; }; if (delta >= 0) { if (lkind == N_TPTR) { let inner: *node = tn.lhs; let inner_kind: i32 = -1; if (inner != nil) { inner_kind = inner.kind; }; let inner_str: bool = false; if (inner_kind == N_TNAME) { if (streq(inner.str, "str")) { inner_str = true; }; }; if (inner_kind == N_TSLICE) { inner_str = true; }; if (inner_str) { if (n.op != TK_ASSIGN) { // Compound on `(*str|*slice).field`: load // current → push → eval rhs → combine → store. emit_line("\tMOVQ\t"); emit_off(lc.off: i64); emit_line("(BP), BX\n"); emit_line("\tMOVQ\t"); emit_disp_reg(delta: i64, "BX"); emit_line(", BX\n"); emit_line("\tPUSHQ\tBX\n"); cgexpr(c, n.rhs); emit_line("\tPOPQ\tBX\n"); // PLUSEQ is commutative; MINUSEQ // needs lhs - rhs. if (n.op == TK_PLUSEQ) { emit_line("\tADDQ\tBX, AX\n"); }; if (n.op == TK_MINUSEQ) { emit_line("\tSUBQ\tAX, BX\n"); emit_line("\tMOVQ\tBX, AX\n"); }; emit_line("\tMOVQ\t"); emit_off(lc.off: i64); emit_line("(BP), BX\n"); emit_line("\tMOVQ\tAX, "); emit_disp_reg(delta: i64, "BX"); emit_line("\n"); return; }; cgexpr(c, n.rhs); emit_line("\tMOVQ\t"); emit_off(lc.off: i64); emit_line("(BP), BX\n"); emit_line("\tMOVQ\tAX, "); emit_disp_reg(delta: i64, "BX"); emit_line("\n"); return; }; }; cgexpr(c, n.rhs); emit_line("\tMOVQ\tAX, "); emit_off((lc.off + delta): i64); emit_line("(BP)\n"); return; }; }; }; }; }; }; // Local-ident target — plain `=` and the simple compound // forms (+= -= *= /=); other compounds fall back to // "evaluate rhs, replace". Mirrors C cgen's IDENT-assign path. if (lhs != nil) { if (lhs.kind == N_IDENT) { let nm: str = lhs.str; let off: i32 = local_find(c, nm); if (off == 0) { return; }; // Detect str-typed local — assignment must store both // halves (AX=ptr at +0, BX=len at +8). let lc_str: bool = false; let lcn: *local = local_find_node(c, nm); if (lcn != nil) { lc_str = is_str_type(c, lcn.tnode); }; cgexpr(c, n.rhs); if (n.op == TK_ASSIGN) { emit_line("\tMOVQ\tAX, "); emit_off(off: i64); emit_line("(BP)\n"); if (lc_str) { emit_line("\tMOVQ\tBX, "); emit_off((off + 8): i64); emit_line("(BP)\n"); }; return; }; if (n.op == TK_PLUSEQ) { emit_line("\tADDQ\tAX, "); emit_off(off: i64); emit_line("(BP)\n"); return; }; if (n.op == TK_MINUSEQ) { emit_line("\tSUBQ\tAX, "); emit_off(off: i64); emit_line("(BP)\n"); return; }; // Generic compound: load → combine in BX → store. emit_line("\tMOVQ\t"); emit_off(off: i64); emit_line("(BP), BX\n"); if (n.op == TK_STAREQ) { emit_line("\tIMULQ\tAX, BX\n"); }; if (n.op == TK_AMPEQ) { emit_line("\tANDQ\tAX, BX\n"); }; if (n.op == TK_PIPEEQ) { emit_line("\tORQ\tAX, BX\n"); }; if (n.op == TK_CARETEQ) { emit_line("\tXORQ\tAX, BX\n"); }; if (n.op == TK_LSHIFTEQ) { emit_line("\tMOVQ\tAX, CX\n"); emit_line("\tSHLQ\tCX, BX\n"); }; if (n.op == TK_RSHIFTEQ) { emit_line("\tMOVQ\tAX, CX\n"); emit_line("\tSHRQ\tCX, BX\n"); }; emit_line("\tMOVQ\tBX, "); emit_off(off: i64); emit_line("(BP)\n"); return; }; }; return; }; }; // ---- type-driven slot sizing ---------------------------------------- fn struct_lookup(c: *cgen, name: str) *struct_info = { let s: *struct_info = c.structs; for (s != nil) { let sn: str = s.sname; if (streq(sn, name)) { return s; }; s = s.sinext; }; return nil; }; // prim_size — size in bytes of a primitive type name (or 0 if not // recognised as a primitive — the caller falls back to other paths). fn prim_size(name: str) i32 = { if (streq(name, "u8")) { return 1; }; if (streq(name, "i8")) { return 1; }; if (streq(name, "bool")) { return 1; }; if (streq(name, "u16")) { return 2; }; if (streq(name, "i16")) { return 2; }; if (streq(name, "u32")) { return 4; }; if (streq(name, "i32")) { return 4; }; if (streq(name, "f32")) { return 4; }; if (streq(name, "u64")) { return 8; }; if (streq(name, "i64")) { return 8; }; if (streq(name, "uint")) { return 8; }; if (streq(name, "int")) { return 8; }; if (streq(name, "uintptr")) { return 8; }; if (streq(name, "f64")) { return 8; }; if (streq(name, "rune")) { return 4; }; if (streq(name, "void")) { return 0; }; return 0; }; fn slot_size(c: *cgen, typ_n: *node) i32 = { if (typ_n == nil) { return 8; }; let k: i32 = typ_n.kind; if (k == N_TPTR) { return 8; }; if (k == N_TFN) { return 8; }; if (k == N_TCHAN) { return 8; }; if (k == N_TSLICE) { return 24; }; if (k == N_TTUPLE) { return 16; }; if (k == N_TTAGGED){ return 24; }; if (k == N_TNAME) { let nm: str = typ_n.str; if (streq(nm, "str")) { return 16; }; let ps: i32 = prim_size(nm); if (ps > 0) { // Pad to 8 for stack slots — matches C cgen which spills // every primitive into an 8-byte slot. return 8; }; // Named struct lookup. let si: *struct_info = struct_lookup(c, nm); if (si != nil) { return si.tot_size; }; return 8; }; if (k == N_TARRAY) { let len_n: *node = typ_n.rhs; let elem_n: *node = typ_n.lhs; let elen: i64 = 1i64; if (len_n != nil) { if (len_n.kind == N_INTLIT) { elen = len_n.uval: i64; }; }; let esz: i32 = 8; if (elem_n != nil) { if (elem_n.kind == N_TNAME) { let en: str = elem_n.str; let ps: i32 = prim_size(en); if (ps > 0) { esz = ps; }; }; }; return (esz: i64 * elen): i32; }; if (k == N_TSTRUCT) { // Inline anonymous struct — sum of field sizes. let f: *node = typ_n.list; let total: i32 = 0; for (f != nil) { if (f.kind == N_TFIELD) { total += slot_size(c, f.lhs); }; f = f.next; }; return total; }; return 8; }; // register_struct — compute field offsets + total size for a struct // type-decl, store in c.structs. Field type sizes use the same // slot_size logic (with primitives kept at their natural width — we // only round to 8 for stack slots, not struct interiors). fn field_size(c: *cgen, tnode: *node) i32 = { if (tnode == nil) { return 8; }; let k: i32 = tnode.kind; if (k == N_TNAME) { let nm: str = tnode.str; if (streq(nm, "str")) { return 16; }; let ps: i32 = prim_size(nm); if (ps > 0) { return ps; }; let si: *struct_info = struct_lookup(c, nm); if (si != nil) { return si.tot_size; }; return 8; }; if (k == N_TPTR) { return 8; }; if (k == N_TSLICE) { return 24; }; if (k == N_TARRAY) { // Same shape as slot_size's TARRAY branch. let len_n: *node = tnode.rhs; let elem_n: *node = tnode.lhs; let elen: i64 = 1i64; if (len_n != nil) { if (len_n.kind == N_INTLIT) { elen = len_n.uval: i64; }; }; let esz: i32 = field_size(c, elem_n); return (esz: i64 * elen): i32; }; return 8; }; fn register_struct(c: *cgen, name: str, tstruct: *node) void = { let si: *struct_info = amalloc(c.a, 64u64): *struct_info; si.sname = name; si.fields = nil; si.tot_size = 0; let head: *field_info = nil; let tail: *field_info = nil; let off: i32 = 0; let f: *node = tstruct.list; for (f != nil) { if (f.kind == N_TFIELD) { let sz: i32 = field_size(c, f.lhs); // Align to 8 for any field >= 4 bytes (matches our other // cgen choices). i8/u8/bool may sit on odd byte offsets; // the C cgen does similar best-effort packing. let aln: i32 = 1; if (sz >= 8) { aln = 8; } else { if (sz >= 4) { aln = 4; } else { if (sz >= 2) { aln = 2; }; }; }; if ((off & (aln - 1)) != 0) { off = (off + aln - 1) & ~(aln - 1); }; let fi: *field_info = amalloc(c.a, 48u64): *field_info; fi.fname = f.str; fi.foff = off; fi.fsz = sz; fi.tnode = f.lhs; if (head == nil) { head = fi; tail = fi; } else { tail.finext = fi; tail = fi; }; off += sz; }; f = f.next; }; // Round total to 8 for stack-slot use. if ((off & 7) != 0) { off = (off + 7) & ~7; }; si.fields = head; si.tot_size = off; si.sinext = c.structs; c.structs = si; }; fn collect_structs(c: *cgen, file: *node) void = { c.structs = nil; if (file == nil) { return; }; let d: *node = file.list; for (d != nil) { if (d.kind == N_TYPEDECL) { let body: *node = d.lhs; if (body != nil) { if (body.kind == N_TSTRUCT) { register_struct(c, d.str, body); }; }; }; d = d.next; }; }; // ---- frame pre-scan -------------------------------------------------- // // Recursively walks the body to count every local `let`. Each gets a // slot sized by slot_size(typ); 8-byte default. Match-bindings + for- // init lets count too. Params are added by the cgfn driver. fn scan_locals(c: *cgen, n: *node) i32 = { if (n == nil) { return 0; }; let total: i32 = 0; if (n.kind == N_LET) { // Match local_add's rounding: < 8 bumps to 8, then 8-align. // scan_locals must agree with local_add or the prologue // SUBQ undersizes the frame and lets overflow into the // caller's stack — corrupting whatever's at -frameSize..-1 // of the caller. Same-name re-declarations share the first // slot (see scan_seen_mark / local_add). if (!scan_seen_mark(c, n.str)) { let sz: i32 = slot_size(c, n.lhs); if (sz < 8) { sz = 8; }; if ((sz & 7) != 0) { sz = (sz + 7) & ~7; }; total += sz; }; }; // Match-arm binding (`case let v: T => ...`) gets a slot too. // Crucially we do NOT dedup these against c.locals: C cgen // handles a match as an expression with a by-value locals copy, // so two separate matches in the same function each allocate // their `v`/`e` slots fresh. Treating these as deduped would // shrink the frame below what local_add then bumps it to. if (n.kind == N_MCASE) { let bn: str = n.str; if (bn.len > 0) { let pat: *node = n.lhs; if (pat != nil) { if (is_str_type(c, pat)) { total += 16; } else { total += 8; }; }; }; }; if (n.lhs != nil) { total += scan_locals(c, n.lhs); }; if (n.rhs != nil) { total += scan_locals(c, n.rhs); }; if (n.cond != nil) { total += scan_locals(c, n.cond); }; if (n.body != nil) { total += scan_locals(c, n.body); }; if (n.els != nil) { total += scan_locals(c, n.els); }; if (n.list != nil) { let m: *node = n.list; for (m != nil) { total += scan_locals(c, m); m = m.next; }; }; return total; }; // ---- statement cgen -------------------------------------------------- fn cgstmt(c: *cgen, n: *node) void = { if (n == nil) { return; }; let k: i32 = n.kind; if (k == N_BLOCK) { let s: *node = n.list; for (s != nil) { cgstmt(c, s); s = s.next; }; return; }; if (k == N_RETURN) { let rhs: *node = n.lhs; if (rhs != nil) { // Tuple return `return a, b;` — pack as (AX=v0, DX=v1). // Matches C cgen: evaluate v1 first (PUSHQ), then v0 // into AX, then POPQ DX. End state: AX = v0, DX = v1. if (rhs.kind == N_TUPLE) { let v: *node = rhs.list; if (v != nil) { let v2: *node = v.next; if (v2 != nil) { cgexpr(c, v2); emit_line("\tPUSHQ\tAX\n"); cgexpr(c, v); emit_line("\tPOPQ\tDX\n"); } else { cgexpr(c, v); }; }; emit_line("\tMOVQ\tBP, SP\n"); emit_line("\tPOPQ\tBP\n"); emit_line("\tRET\n"); c.last_was_return = 1; return; }; // Tagged-union return: pack as (AX=tag, DX=value0, CX=value1). // For str variant, cgexpr leaves (AX=ptr, BX=len), so we // shuffle DX←AX (ptr) and CX←BX (len), then load tag. // For other variants, cgexpr leaves AX, shuffle DX←AX. if (is_tagged_type(c.fn_ret)) { cgexpr(c, rhs); let idx: i32 = tagged_variant_index(c, c.fn_ret, rhs); if (node_isstr(c, rhs)) { emit_line("\tMOVQ\tBX, CX\n"); emit_line("\tMOVQ\tAX, DX\n"); } else { emit_line("\tMOVQ\tAX, DX\n"); }; emit_line("\tMOVQ\t$"); if (idx < 0) { idx = 0; }; emit_int(idx: i64); emit_line(", AX\n"); emit_line("\tMOVQ\tBP, SP\n"); emit_line("\tPOPQ\tBP\n"); emit_line("\tRET\n"); c.last_was_return = 1; return; }; cgexpr(c, rhs); } else { // Bare `return;` in a void fn — zero AX so the caller // sees a deterministic value (matches C cgen, which // always falls through to `cgexpr_int(c, 0)`). emit_line("\tMOVQ\t$0, AX\n"); }; // SysV: 16-byte aggregates (str, 2-tuple) return in (AX, DX). // cgexpr leaves str in (AX, BX); shuffle BX→DX. if (is_str_type(c, c.fn_ret)) { emit_line("\tMOVQ\tBX, DX\n"); }; emit_line("\tMOVQ\tBP, SP\n"); emit_line("\tPOPQ\tBP\n"); emit_line("\tRET\n"); c.last_was_return = 1; return; }; if (k == N_EXPRSTMT) { if (n.lhs != nil) { cgexpr(c, n.lhs); }; c.last_was_return = 0; return; }; if (k == N_LET) { let nm: str = n.str; let sz: i32 = slot_size(c, n.lhs); let off: i32 = local_add(c, nm, sz, n.lhs); if (n.rhs != nil) { let rhs: *node = n.rhs; // Tagged-union init: `let r: (T | E) = expr;`. // - If rhs is a CALL to a fn returning tagged-union, // the result is already in (AX=tag, DX=v0, CX=v1); // just spill all three. // - Otherwise rhs is a bare variant value: pack tag + // value(s). if (is_tagged_type(n.lhs)) { let rhs_returns_tagged: bool = false; if (rhs.kind == N_CALL) { let callee: *node = rhs.lhs; if (callee != nil) { let callee_name: str; callee_name.ptr = nil; callee_name.len = 0; if (callee.kind == N_IDENT) { callee_name = callee.str; }; if (callee.kind == N_DOT) { callee_name = callee.str; }; if (callee_name.len > 0) { let rt: *node = fnret_lookup(c, callee_name); if (is_tagged_type(rt)) { rhs_returns_tagged = true; }; }; }; }; cgexpr(c, rhs); if (rhs_returns_tagged) { emit_line("\tMOVQ\tAX, "); emit_off(off: i64); emit_line("(BP)\n"); emit_line("\tMOVQ\tDX, "); emit_off((off + 8): i64); emit_line("(BP)\n"); emit_line("\tMOVQ\tCX, "); emit_off((off + 16): i64); emit_line("(BP)\n"); c.last_was_return = 0; return; }; let tag_idx: i32 = tagged_variant_index(c, n.lhs, rhs); if (tag_idx < 0) { tag_idx = 0; }; if (node_isstr(c, rhs)) { emit_line("\tMOVQ\tAX, "); emit_off((off + 8): i64); emit_line("(BP)\n"); emit_line("\tMOVQ\tBX, "); emit_off((off + 16): i64); emit_line("(BP)\n"); } else { emit_line("\tMOVQ\tAX, "); emit_off((off + 8): i64); emit_line("(BP)\n"); }; emit_line("\tMOVQ\t$"); emit_int(tag_idx: i64); emit_line(", "); emit_off(off: i64); emit_line("(BP)\n"); c.last_was_return = 0; return; }; // Struct literal init: `let p: point = point{x=..., y=...};`. // For each field in the lit, evaluate its value and store at // the field's offset within the slot. Field-name → offset // from the struct registry. if (rhs.kind == N_STRUCTLIT) { let trefn: *node = rhs.lhs; let sname: str; sname.ptr = nil; sname.len = 0; if (trefn != nil) { if (trefn.kind == N_IDENT) { sname = trefn.str; } else { if (trefn.kind == N_TNAME) { sname = trefn.str; }; }; }; let si: *struct_info = struct_lookup(c, sname); if (si != nil) { let field_node: *node = rhs.list; for (field_node != nil) { if (field_node.kind == N_FIELD) { let fname: str = field_node.str; let fi: *field_info = si.fields; for (fi != nil) { let fn_: str = fi.fname; if (streq(fn_, fname)) { cgexpr(c, field_node.lhs); let sop: str = field_store_op(fi); emit_line("\t"); emit_line(sop); emit_line("\tAX, "); emit_off((off + fi.foff): i64); emit_line("(BP)\n"); fi = nil; } else { fi = fi.finext; }; }; }; field_node = field_node.next; }; c.last_was_return = 0; return; }; }; cgexpr(c, rhs); emit_line("\tMOVQ\tAX, "); emit_off(off: i64); emit_line("(BP)\n"); // str init: cgexpr also leaves len in BX; store both. if (sz == 16) { emit_line("\tMOVQ\tBX, "); emit_off((off + 8): i64); emit_line("(BP)\n"); }; // slice init: ptr/len/cap in AX/BX/CX. if (sz == 24) { emit_line("\tMOVQ\tBX, "); emit_off((off + 8): i64); emit_line("(BP)\n"); emit_line("\tMOVQ\tCX, "); emit_off((off + 16): i64); emit_line("(BP)\n"); }; } else { // Bare `let x: T;` with no initializer. C cgen // (cmd/6c/cgen.c:2181-2183) zero-inits only when // the underlying type's natural size is 8 — pointers, // i64/u64, function pointers, ints. Structs/arrays/ // slices/strings/tagged/tuples are left for per-field // writes. ww's slot_size pads struct slots up to 8, // so we can't just check sz == 8: walk the type AST // directly to make the same call. if (type_is_8byte_primitive(c, n.lhs)) { emit_line("\tMOVQ\t$0, "); emit_off(off: i64); emit_line("(BP)\n"); }; }; c.last_was_return = 0; return; }; if (k == N_IF) { let els: str = mklabel(c, "else"); let endl: str = mklabel(c, "end"); cgexpr(c, n.cond); emit_line("\tCMPQ\t$0, AX\n"); emit_line("\tJE\t"); if (n.els != nil) { emit_line(els); } else { emit_line(endl); }; emit_line("\n"); if (n.body != nil) { cgstmt(c, n.body); }; if (n.els != nil) { emit_line("\tJMP\t"); emit_line(endl); emit_line("\n"); emit_label(els); cgstmt(c, n.els); }; emit_label(endl); c.last_was_return = 0; return; }; if (k == N_FOR) { // Match C cgen's label scheme: _loop_N for the top, // _endloop_N for the post-body merge. No separate cont // label when there's no post-expression. let topl: str = mklabel(c, "loop"); let endl: str = mklabel(c, "endloop"); if (n.lhs != nil) { cgstmt(c, n.lhs); }; emit_label(topl); if (n.cond != nil) { cgexpr(c, n.cond); emit_line("\tCMPQ\t$0, AX\n"); emit_line("\tJE\t"); emit_line(endl); emit_line("\n"); }; c.loop_end_buf[c.loop_top] = endl; c.loop_cont_buf[c.loop_top] = topl; c.loop_top += 1; if (n.body != nil) { cgstmt(c, n.body); }; c.loop_top -= 1; if (n.rhs != nil) { cgexpr(c, n.rhs); }; emit_line("\tJMP\t"); emit_line(topl); emit_line("\n"); emit_label(endl); c.last_was_return = 0; return; }; // Tuple-destructure assign: `a, b = call();`. The call's tuple // return lands in (AX, DX); push DX to free it, store AX into // the first lvalue, then pop DX into the second. Mirrors // cmd/6c/cgen.c:2424-2440. Lvalues beyond two are dropped (same // as C — no fixture uses >2 today). if (k == N_MASSIGN) { if (n.rhs != nil) { cgexpr(c, n.rhs); }; emit_line("\tPUSHQ\tDX\n"); let l0: *node = n.list; let l1: *node = nil; if (l0 != nil) { l1 = l0.next; }; if (l0 != nil) { if (l0.kind == N_IDENT) { let off: i32 = local_find(c, l0.str); if (off != 0) { emit_line("\tMOVQ\tAX, "); emit_off(off: i64); emit_line("(BP)\n"); }; }; }; emit_line("\tPOPQ\tDX\n"); if (l1 != nil) { if (l1.kind == N_IDENT) { let off: i32 = local_find(c, l1.str); if (off != 0) { emit_line("\tMOVQ\tDX, "); emit_off(off: i64); emit_line("(BP)\n"); }; }; }; c.last_was_return = 0; return; }; if (k == N_BREAK) { if (c.loop_top > 0) { let lbl: str = c.loop_end_buf[c.loop_top - 1]; emit_line("\tJMP\t"); emit_line(lbl); emit_line("\n"); }; c.last_was_return = 0; return; }; if (k == N_CONTINUE) { if (c.loop_top > 0) { let lbl: str = c.loop_cont_buf[c.loop_top - 1]; emit_line("\tJMP\t"); emit_line(lbl); emit_line("\n"); }; c.last_was_return = 0; return; }; c.last_was_return = 0; }; // ---- function-level cgen --------------------------------------------- // is_str_type — true when the type expr resolves (through any // `type X = str;` aliases) to `str`. Takes *cgen so it can walk the // alias chain registered at file load. fn is_str_type_raw(t: *node) bool = { if (t == nil) { return false; }; if (t.kind == N_TNAME) { let nm: str = t.str; if (streq(nm, "str")) { return true; }; }; return false; }; fn is_str_type(c: *cgen, t: *node) bool = { if (is_str_type_raw(t)) { return true; }; if (c == nil) { return false; }; let r: *node = resolve_type(c, t); return is_str_type_raw(r); }; fn is_slice_type_raw(t: *node) bool = { if (t == nil) { return false; }; if (t.kind == N_TSLICE) { return true; }; return false; }; fn is_slice_type(c: *cgen, t: *node) bool = { if (is_slice_type_raw(t)) { return true; }; if (c == nil) { return false; }; let r: *node = resolve_type(c, t); return is_slice_type_raw(r); }; fn is_tagged_type(t: *node) bool = { if (t == nil) { return false; }; if (t.kind == N_TTAGGED) { return true; }; return false; }; // rhs_target_name — for a returned value, what's its declared (or // surface-inferred) type name? `expr: T` casts dictate T directly; // bare strlit/intlit fall back to a primitive name. fn rhs_target_name(c: *cgen, rhs: *node) str = { let nm: str; nm.ptr = nil; nm.len = 0; if (rhs == nil) { return nm; }; if (rhs.kind == N_CAST) { let t: *node = rhs.rhs; if (t != nil) { if (t.kind == N_TNAME) { return t.str; }; }; return nm; }; if (rhs.kind == N_STRLIT) { return "str"; }; if (rhs.kind == N_IDENT) { let lc: *local = local_find_node(c, rhs.str); if (lc != nil) { let tn: *node = lc.tnode; if (tn != nil) { if (tn.kind == N_TNAME) { return tn.str; }; }; }; }; return nm; }; // tagged_variant_index — given the tagged-union type expr and the // returned value's surface type, find the matching variant's 0-based // index. Compare by exact type name first; if no match, fall back to // "any str-shape variant matches an str-typed value". fn tagged_variant_index(c: *cgen, tagged: *node, rhs: *node) i32 = { if (tagged == nil) { return -1; }; if (rhs == nil) { return -1; }; let want_name: str = rhs_target_name(c, rhs); if (want_name.len > 0) { let v: *node = tagged.list; let idx: i32 = 0; for (v != nil) { if (v.kind == N_TNAME) { if (streq(v.str, want_name)) { return idx; }; }; v = v.next; idx += 1; }; }; // Fallback: by str-shape (resolves aliases). let want_str: bool = node_isstr(c, rhs); let v: *node = tagged.list; let idx: i32 = 0; for (v != nil) { let v_is_str: bool = false; if (v.kind == N_TNAME) { if (is_str_type(c, v)) { v_is_str = true; }; }; if (v_is_str == want_str) { return idx; }; v = v.next; idx += 1; }; return -1; }; fn cgfn_params(c: *cgen, params: *node) void = { let p: *node = params; let idx: i32 = 0; for (p != nil) { if (p.kind == N_PARAM) { let nm: str = p.str; if (is_tagged_type(p.lhs)) { // tagged-union param: passed in 3 regs (tag, v0, v1), // 24-byte slot. let off: i32 = local_add(c, nm, 24, p.lhs); emit_line("\tMOVQ\t"); emit_line(argreg_name(idx)); emit_line(", "); emit_off(off: i64); emit_line("(BP)\n"); idx += 1; emit_line("\tMOVQ\t"); emit_line(argreg_name(idx)); emit_line(", "); emit_off((off + 8): i64); emit_line("(BP)\n"); idx += 1; emit_line("\tMOVQ\t"); emit_line(argreg_name(idx)); emit_line(", "); emit_off((off + 16): i64); emit_line("(BP)\n"); idx += 1; } else { if (is_slice_type(c, p.lhs)) { // slice param: 3 regs (ptr, len, cap), 24-byte slot. let off: i32 = local_add(c, nm, 24, p.lhs); emit_line("\tMOVQ\t"); emit_line(argreg_name(idx)); emit_line(", "); emit_off(off: i64); emit_line("(BP)\n"); idx += 1; emit_line("\tMOVQ\t"); emit_line(argreg_name(idx)); emit_line(", "); emit_off((off + 8): i64); emit_line("(BP)\n"); idx += 1; emit_line("\tMOVQ\t"); emit_line(argreg_name(idx)); emit_line(", "); emit_off((off + 16): i64); emit_line("(BP)\n"); idx += 1; } else { if (is_str_type(c, p.lhs)) { // str param: passed in two regs (ptr, len). // Slot is 16 bytes; ptr at off+0, len at off+8. let off: i32 = local_add(c, nm, 16, p.lhs); emit_line("\tMOVQ\t"); emit_line(argreg_name(idx)); emit_line(", "); emit_off(off: i64); emit_line("(BP)\n"); idx += 1; emit_line("\tMOVQ\t"); emit_line(argreg_name(idx)); emit_line(", "); emit_off((off + 8): i64); emit_line("(BP)\n"); idx += 1; } else { let off: i32 = local_add(c, nm, 8, p.lhs); emit_line("\tMOVQ\t"); emit_line(argreg_name(idx)); emit_line(", "); emit_off(off: i64); emit_line("(BP)\n"); idx += 1; };};}; }; p = p.next; }; }; fn cgfn(c: *cgen, fn_: *node) void = { cgen_init(c, c.a); c.fn_name = fn_.str; c.fn_ret = fn_.lhs; emit_line("TEXT "); let nm: str = fn_.str; os.write(1, nm.ptr, nm.len: u64); emit_line(",$"); // Pre-scan total frame: 24 bytes per slice param, 16 per str // param, 8 per other param, plus per-let from scan_locals. // Seed c.locals with param-name stubs so scan_locals dedups a // re-declared `let ` in the body against the param's // slot (matches C cgen). Stubs get cleared before emission. let scan_p: *node = fn_.list; let frame: i32 = 0; for (scan_p != nil) { if (scan_p.kind == N_PARAM) { if (is_tagged_type(scan_p.lhs)) { frame += 24; } else { if (is_slice_type(c, scan_p.lhs)) { frame += 24; } else { if (is_str_type(c, scan_p.lhs)) { frame += 16; } else { frame += 8; }; }; }; scan_seen_mark(c, scan_p.str); }; scan_p = scan_p.next; }; if (fn_.body != nil) { frame += scan_locals(c, fn_.body); }; // Drop the stubs so emission rebuilds c.locals with real offsets. c.locals = nil; if ((frame & 15) != 0) { frame = (frame + 15) & ~15; }; emit_int(frame: i64); emit_line("\n"); emit_line("\tPUSHQ\tBP\n"); emit_line("\tMOVQ\tSP, BP\n"); emit_line("\tSUBQ\t$"); emit_int(frame: i64); emit_line(", SP\n"); cgfn_params(c, fn_.list); c.last_was_return = 0; if (fn_.body != nil) { cgstmt(c, fn_.body); }; if (c.last_was_return == 0) { // Zero AX before the fall-through return — matches C cgen, // which always emits this so void-returning fns don't leak // a stale callee value to their caller. emit_line("\tMOVQ\t$0, AX\n"); emit_line("\tMOVQ\tBP, SP\n"); emit_line("\tPOPQ\tBP\n"); emit_line("\tRET\n"); }; }; // ---- file-level entry ------------------------------------------------ export fn cg_file(c: *cgen, file: *node) void = { if (file == nil) { return; }; c.strlits = nil; c.strlit_seq = 0; collect_aliases(c, file); collect_structs(c, file); collect_defs(c, file); collect_fnrets(c, file); ffi_collect(c, file); let d: *node = file.list; for (d != nil) { if (d.kind == N_FNDECL) { if (d.body != nil) { cgfn(c, d); }; }; d = d.next; }; emit_data_section(c); emit_def_constants(c, file); };