cstage+selfhost+test: principled identity-cast skip (#33)

Generalizes b5632b1's single-site dst_is_enum gate. Skip the narrow-
clamp MOVL when src.width == dst.width && src.signed == dst.signed.
Closes #25's followup.

Both stages need symmetric source-type derivation for byte-id. cstage
deliberately throws away the checker's richer typed-AST and uses a
structural walker (castsrcprim) that mirrors wwstage's exprprimresolved
case-for-case. Otherwise cstage's `.len: i32` resolves to i32 (skip)
while wwstage's misses the pseudo-field (clamp) — bootstrap diverges.
Pseudo-fields, N_BIN, N_INDEX, N_CALL, match-bindings all yield sz=0
→ clamp emits defensively on both.

The N_TENUM walker now follows enum aliases in wwstage's
typenodeprimresolved (was the original lacuna behind #25), and bool
is excluded early in the same helper (mirrors cstage's
type_isint(TY_BOOL)=false). bool→bool keeps its dedicated is_bool
ANDQ $255 emit; bool→i8 / bool→u8 etc. fall through to the clamp on
both stages.

Walker shape (cstage castsrcprim / wwstage exprprimresolved):
  N_INTLIT     → tsuffix gated, untyped excluded
  N_IDENT      → trust local's resolved tnode
  N_CAST       → recurse on declared dst
  N_UN         → recurse on operand
  N_DOT        → real-struct only (TY_STRUCT or TY_PTR→TY_STRUCT)
  others       → sz=0 → identity false → clamp emits

Test 710 grew from 5 → 16 rows: 6 identity-width pins (u32/i32/u8/
i8/u16/i16 self), 1 sign-change pin (u32→i32 clamp MUST fire), 2
silent-miscompile exit-validating rows (truncate via divide), 1
pseudo-field defensive pin (`s.len: i32`), 1 bool-source pin
(`b: i8`). Asm byte-id asserted on every row.

Out of scope: redundant clamps remain for patterns wwstage can't
structurally derive (N_BIN, N_CALL, N_INDEX, pseudo-fields). A
sibling task extending wwstage's type inference closes those.
This commit is contained in:
2026-05-16 12:20:56 +09:00
parent 993da52333
commit 2fb594748c
6 changed files with 860 additions and 217 deletions

View File

@@ -1,60 +1,109 @@
/*
* 710_cast_enum_movl — cstage and wwstage agree byte-for-byte on the
* N_CAST narrow-clamp when the dst is an enum (task #25).
* N_CAST narrow-clamp under the principled identity-width identity-
* sign predicate (task #33). Extended from the original #25 fixture
* which mirrored wwstage's N_TENUM lacuna as a single-site `tu->kind
* == TY_ENUM` gate in cstage.
*
* Pre-fix: cstage's N_CAST handler in cmd/w6c/cgen.c walked
* `type_isint`/`type_isunsigned` which recurse through TY_ENUM into
* `t->sub`; for a u32→enum-u32 cast that landed on the size==4 unsigned
* branch and emitted a redundant `MOVL AX, AX`. Wwstage's cgcast walker
* (selfhost/cmd/wcc/cgenexpr.ww) only steps through N_TBANG / N_TNAME;
* `aliaslookup` on an enum returns the N_TENUM body, which breaks the
* loop and skips the clamp.
* Predicate (both stages):
* skip the narrow-clamp on an int→int cast iff
* src.width == dst.width && src.signed == dst.signed
* where (width, signedness) resolve through TY_NAMED / TY_ENUM
* alias chains in cstage and N_TBANG / N_TENUM / N_TNAME-alias
* chains in wwstage. Bool keeps its dedicated ANDQ $255 contract.
*
* Surfaced by worker-stat during #10: when kstat.mode was first typed
* as raw `u32`, `out.mode = k.mode` parsed as a u32→enum-u32 cast via
* `fs.mode`, and the cstage→wwstage asm divergence broke 993_ww_ww +
* 995_self_rebuild on the first selfhost pass. Workaround in tree
* (lib/os/os.ww:498, kstat.mode: mode) sidesteps until this fix lands;
* reverting it is a sibling cleanup, out of scope here.
* History: #25 (b5632b1) shipped a single-site gate in cstage —
* `dst_is_enum → skip` — that made cstage byte-for-byte identical
* to wwstage on a u32→enum-u32 cast. It also inadvertently kept a
* silent miscompile alive: u32→enum-u8 and i64→enum-i32 also took
* the dst-is-enum exit, so the narrow-clamp didn't fire on a
* genuinely-width-narrowing cast and the upper bits of the source
* value leaked into any register-chained downstream use (the slot
* store happens to mask via MOVB/MOVL of the dst width, so program
* semantics looked right unless the result was consumed by a
* register-chained outer cast / arithmetic).
*
* Fix shape: cstage's N_CAST clamp gate adds an explicit
* `tu->kind == TY_ENUM` skip, mirroring wwstage's lacuna. The predicate
* recursion through TY_ENUM in `type_isint`/`type_isunsigned` is
* preserved — other call sites depend on it; only this site gates
* explicitly. Skip is on dst kind only, so `enum-u32 → u32` still emits
* the clamp, matching wwstage's asymmetry. A principled
* identity-width identity-sign skip across both stages is filed as
* a separate followup.
* Surfaced by worker-stat during #10: when kstat.mode was first
* typed as raw `u32`, `out.mode = k.mode` parsed as a u32→enum-u32
* cast via `fs.mode`, and the cstage→wwstage asm divergence broke
* 993_ww_ww + 995_self_rebuild on the first selfhost pass. The
* workaround that was in tree (lib/os/os.ww kstat.mode: mode) has
* already been retired by #25's single-site fix; #33 generalises
* the gate.
*
* row | shape | gate
* -----------------+----------------------------------------+----------
* u32_to_enum_u32 | `let y: m = x: m;` with m=enum u32. | exit=7
* | Headline. Both stages emit ONE MOVL | + byte-id
* | (the slot load); no clamp. |
* enum_u32_to_u32 | reverse direction: `let z: u32 = y;`. | exit=7
* | Both stages emit clamp MOVL AX, AX | + byte-id
* | (post-load) — pins the asymmetry. |
* u32_to_enum_u8 | dst is enum u8. Pre-fix cstage emits | exit=7
* | ANDQ $0xFF; wwstage skips. Post-fix | + byte-id
* | both skip — matches wwstage. (Width |
* | narrowing through the enum-u8 is a |
* | known shared gap; principled followup. |
* | The u8-typed local's slot load uses |
* | MOVZBQ which masks anyway, so program |
* | semantics stays right at this width.) |
* i64_to_enum_i32 | signed-narrow: dst is enum i32. | exit=7
* | Pre-fix cstage emits MOVSXD; post-fix | + byte-id
* | skips. The slot is read with MOVSXD |
* | downstream so sign-ext survives. |
* struct_field_rt | mirror of lib/os fillfilestat: a u32 | exit=7
* | struct field copied into an enum-typed | + byte-id
* | field by chained N_DOT. Pins the field-|
* | store path through the cast. |
* row | shape | gate
* --------------------+--------------------------------------+----------
* u32_to_enum_u32 | `let y: m = x: m;` with m=enum u32. | exit=7
* | Identity (4B/unsigned). Both stages | + byte-id
* | skip — no clamp. |
* enum_u32_to_u32 | reverse: `let z: u32 = y: u32;`. | exit=7
* | Also identity (4B/unsigned, walker | + byte-id
* | now resolves `mymode` through |
* | aliaslookup to u32). Both skip — |
* | flips from #25's clamp-emit. |
* u32_to_enum_u8 | dst is enum u8. Width narrows 4→1, | exit=7
* | so identity is false. Both stages | + byte-id
* | now emit ANDQ $0xFF — flips from |
* | #25's skip. Fixes the silent leak |
* | (see u32_to_enum_u8_truncate below). |
* i64_to_enum_i32 | signed-narrow: dst is enum i32. | exit=7
* | Width narrows 8→4 → identity false. | + byte-id
* | Both stages emit MOVSXD AX, AX — |
* | flips from #25's skip. Fixes the |
* | silent leak (see |
* | i64_to_enum_i32_truncate below). |
* struct_field_rt | mirror of lib/os fillfilestat: a u32 | exit=7
* | struct field copied into an enum-u32 | + byte-id
* | field by chained N_DOT. Identity |
* | (4B/unsigned). Both skip. |
* u32_u32_identity | `let y: u32 = x: u32;` with src=u32. | exit=7
* | Trivial identity. Both stages skip; | + byte-id
* | pre-#33 they emitted a redundant |
* | MOVL AX, AX. |
* i32_i32_identity | same shape, src/dst i32. Pre-#33 | exit=7
* | both emitted MOVSXD AX, AX. Now | + byte-id
* | skip. |
* u8_u8_identity | u8 → u8. Pre-#33 ANDQ $0xFF. Now | exit=7
* | skip. | + byte-id
* i8_i8_identity | i8 → i8. Pre-#33 MOVSBQ AX, AX. | exit=7
* | Now skip. | + byte-id
* u16_u16_identity | u16 → u16. Pre-#33 ANDQ $0xFFFF. | exit=7
* | Now skip. | + byte-id
* i16_i16_identity | i16 → i16. Pre-#33 MOVSWQ AX, AX. | exit=7
* | Now skip. | + byte-id
* u32_to_i32_signchg | width equal, signedness differs. | exit=7
* | Identity is FALSE → narrow-clamp | + byte-id
* | MUST fire. Both stages emit MOVSXD |
* | (dst is signed-narrow). Pin against |
* | future refactors that mis-broaden |
* | the skip. |
* u32_to_enum_u8_trnc | exit-code-validating silent- | exit=0
* | miscompile fix. x=0xFFFFu32 cast to | + byte-id
* | enum-u8, then to u32, then divided |
* | by 0x100. Post-#33 the inner cast |
* | clamps to 0xFF, divide yields 0; |
* | pre-#33 the upper bits leaked |
* | (AX=0xFFFF), divide yielded 0xFF. |
* i64_to_enum_i32_trnc| same shape on i64 → enum-i32. | exit=0
* | x=0x100000000i64 cast to enum-i32, | + byte-id
* | then to i64, divided by 0x100000000. |
* | Post-#33 MOVSXD takes low 32 bits |
* | (0), divide yields 0; pre-#33 the |
* | high 32 bits leaked, divide |
* | yielded 1. |
*
* Cstage exit-code rows confirm the binary still runs correctly
* post-fix; the asm-byte-id rows are the regression-pinning rows for
* the symmetric-emit contract. ww2!=ww3 byte-id (995_self_rebuild)
* covers a broader surface but doesn't isolate this corner.
* post-#33. The asm-byte-id rows pin the symmetric-emit contract.
* The `*_trnc` rows are the regression-pinning ones for the
* silent-miscompile fix that #25's dst-kind-only skip left in
* place. ww3!=ww4 byte-id (995_self_rebuild) covers a broader
* surface but doesn't isolate this corner.
*
* Note: removing the defensive MOVL exposes any upstream cgen path
* that leaves garbage in upper RAX when producing a sub-word value.
* If a future test goes red post-#33, the contract is violated
* somewhere — fix the upstream producer, do NOT reinstate the
* defensive clamp.
*/
#include <stdio.h>
#include <stdlib.h>
@@ -89,11 +138,11 @@ static const struct row rows[] = {
"};\n",
7 },
/* 2. Reverse direction: enum-u32 → u32. Both stages still emit
* the clamp `MOVL AX, AX` here (wwstage's walker steps through
* the N_TNAME("u32") rhs and primsize=4 fires). The byte-id
* row pins that the fix didn't accidentally widen the skip to
* include this case. */
/* 2. Reverse direction: enum-u32 → u32. Post-#33 both stages
* walk `mymode` through aliaslookup to u32, see (src u32, dst
* u32, both unsigned), and skip the narrow-clamp under the
* identity-width identity-sign predicate. Flips from #25's
* clamp-emit. Exit code unchanged at 7. */
{ "enum_u32_to_u32",
"type mymode = enum u32 { A = 1u32 };\n"
"fn main() i32 = {\n"
@@ -103,14 +152,13 @@ static const struct row rows[] = {
"};\n",
7 },
/* 3. Different enum width: u32 → enum-u8. Wwstage skips clamp
* because dst is an enum (lacuna); cstage now also skips
* (mirror). The local's u8 slot reads with MOVZBQ later, so
* the value 7 still reads back as 7. Pinning byte-id here
* documents that the skip is by dst-kind, not by dst-size —
* the principled identity-width fix would behave differently
* here, so this row is the canary that flips when the
* followup lands. */
/* 3. Different enum width: u32 → enum-u8. Post-#33 both stages
* emit ANDQ $0xFF because identity is false (src 4B, dst 1B).
* Flips from #25's dst-is-enum skip. The slot write masks via
* MOVB so program semantics with `7` reads back as 7 either
* way; the silent-miscompile case (upper bits leaking into
* register-chained downstream use) is pinned by
* u32_to_enum_u8_trnc below. */
{ "u32_to_enum_u8",
"type small = enum u8 { A = 1u8 };\n"
"fn main() i32 = {\n"
@@ -120,10 +168,12 @@ static const struct row rows[] = {
"};\n",
7 },
/* 4. Signed-narrow path: i64 → enum-i32. Pre-fix cstage emitted
* `MOVSXD AX, AX`; wwstage skipped. Post-fix both skip. The
* enum-i32 local's slot read uses MOVSXD downstream so the
* sign-extension is recovered on use. */
/* 4. Signed-narrow path: i64 → enum-i32. Post-#33 both stages
* emit MOVSXD AX, AX (identity false: src 8B, dst 4B). Flips
* from #25's skip. Slot is read with MOVSXD downstream so the
* sign-extension is recovered on use; silent leak through a
* register-chained outer cast is pinned by
* i64_to_enum_i32_trnc below. */
{ "i64_to_enum_i32",
"type sflag = enum i32 { A = 1i32 };\n"
"fn main() i32 = {\n"
@@ -135,9 +185,9 @@ static const struct row rows[] = {
/* 5. Mirror of lib/os fillfilestat: struct field of one type
* copied into an enum-typed field of another struct via
* chained N_DOT. The `out.mode = k.mode` shape is exactly
* what blew up worker-stat's first kstat.mode: u32 attempt
* pre-fix (993_ww_ww + 995_self_rebuild went red). */
* chained N_DOT. Identity (4B/unsigned on both sides) → both
* stages skip the clamp. Pre-#25 this blew up 993_ww_ww +
* 995_self_rebuild on the first selfhost pass. */
{ "struct_field_rt",
"type mymode = enum u32 { A = 1u32 };\n"
"type src = struct { mode: u32 };\n"
@@ -149,6 +199,141 @@ static const struct row rows[] = {
"\treturn (b.mode: u32): i32;\n"
"};\n",
7 },
/* 6-11. Identity-width identity-sign rows. Pre-#33 the cast
* always emitted a clamp for sub-8B dst (MOVL/ANDQ/MOVSBQ/
* MOVSWQ/MOVSXD depending on width and signedness); post-#33
* all six skip because src and dst share the underlying
* primitive. Asm byte-id pins the contract. */
{ "u32_u32_identity",
"fn main() i32 = {\n"
"\tlet x: u32 = 7u32;\n"
"\tlet y: u32 = x: u32;\n"
"\treturn y: i32;\n"
"};\n",
7 },
{ "i32_i32_identity",
"fn main() i32 = {\n"
"\tlet x: i32 = 7i32;\n"
"\tlet y: i32 = x: i32;\n"
"\treturn y;\n"
"};\n",
7 },
{ "u8_u8_identity",
"fn main() i32 = {\n"
"\tlet x: u8 = 7u8;\n"
"\tlet y: u8 = x: u8;\n"
"\treturn (y: u32): i32;\n"
"};\n",
7 },
{ "i8_i8_identity",
"fn main() i32 = {\n"
"\tlet x: i8 = 7i8;\n"
"\tlet y: i8 = x: i8;\n"
"\treturn (y: i32);\n"
"};\n",
7 },
{ "u16_u16_identity",
"fn main() i32 = {\n"
"\tlet x: u16 = 7u16;\n"
"\tlet y: u16 = x: u16;\n"
"\treturn (y: u32): i32;\n"
"};\n",
7 },
{ "i16_i16_identity",
"fn main() i32 = {\n"
"\tlet x: i16 = 7i16;\n"
"\tlet y: i16 = x: i16;\n"
"\treturn (y: i32);\n"
"};\n",
7 },
/* 12. Width-equal sign-change: u32 → i32. Identity is FALSE
* (signedness differs) so the clamp MUST still emit (MOVSXD
* because dst is signed-narrow). Asm byte-id pins this
* against future refactors that mis-broaden the identity
* skip. Exit code 7 is just the value round-tripping. */
{ "u32_to_i32_signchg",
"fn main() i32 = {\n"
"\tlet x: u32 = 7u32;\n"
"\tlet y: i32 = x: i32;\n"
"\treturn y;\n"
"};\n",
7 },
/* 13. Silent-miscompile fix, u32 → enum-u8. Pre-#33 the
* b5632b1 dst-is-enum skip left the upper bits of the u32
* source in AX. With register-chained downstream use (no slot
* spill between the inner cast and the outer expression), the
* leak survives. Probe: start with x=0xFFFFu32, cast to
* enum-u8 (should clamp to 0xFF), cast to u32, divide by
* 0x100. Post-#33 the inner clamp leaves AX=0xFF and the
* divide yields 0; pre-#33 AX stayed 0xFFFF and the divide
* yielded 0xFF. Exit code distinguishes (0 vs 255). */
{ "u32_to_enum_u8_trnc",
"type small = enum u8 { A = 1u8 };\n"
"fn main() i32 = {\n"
"\tlet x: u32 = 0xFFFFu32;\n"
"\tlet r: u32 = ((x: small): u32) / 0x100u32;\n"
"\treturn r: i32;\n"
"};\n",
0 },
/* 14. Silent-miscompile fix, i64 → enum-i32. Same shape on
* the signed-narrow path. x=0x100000000i64 (bit 32 set, low
* 32 bits zero). Post-#33 the MOVSXD takes the low 32 bits
* (0), AX=0, divide by 0x100000000 yields 0. Pre-#33 the
* clamp was skipped, AX stayed 0x100000000, divide yielded
* 1. Exit code distinguishes (0 vs 1). */
{ "i64_to_enum_i32_trnc",
"type sflag = enum i32 { A = 1i32 };\n"
"fn main() i32 = {\n"
"\tlet x: i64 = 0x100000000i64;\n"
"\tlet r: i64 = ((x: sflag): i64) / 0x100000000i64;\n"
"\treturn r: i32;\n"
"};\n",
0 },
/* 15. Pseudo-field defensive-clamp pin. Source is `s.len`, a
* str header pseudo-field — neither stage's source-type
* resolver recognises it (cstage's `castsrcprim` gates the
* N_DOT branch on `bu->kind == TY_STRUCT`; wwstage's
* `exprprimresolved` routes through `dotfieldtnode` which
* returns nil for non-struct base). Both fall back to sz=0,
* identity is false, the narrow-clamp emits (MOVSXD here
* because dst is signed-narrow i32). Pinning byte-id on this
* row catches a future refactor that wires pseudo-field
* inference asymmetrically into one stage — the kind of drift
* that would silently break 995_self_rebuild without naming
* the corner. Exit code 7 = round-trip of the literal len. */
{ "pseudo_field_clamp",
"fn main() i32 = {\n"
"\tlet s: str = \"abcdefg\";\n"
"\tlet n: i32 = s.len: i32;\n"
"\treturn n;\n"
"};\n",
7 },
/* 16. Bool source clamp pin. Source is a bool local, dst is i8.
* Width matches (1B) but bool is excluded from the int-prim
* contract on both stages (cstage's `type_isint(TY_BOOL)` is
* false; wwstage's `typenodeprimresolved` has an explicit
* `streq(nm, "bool") → return` early-out). So identity is
* never true on a bool source: the narrow-clamp emits
* (MOVSBQ AX, AX because dst is i8, signed-narrow). Without
* the bool early-out in wwstage, `primsize("bool")=1` and
* `typenameisunsigned("bool")=false` made wwstage see
* (sz=1, unsigned=false) and fire identity on bool→i8 while
* cstage emitted MOVSBQ — silent asm asymmetry that no other
* row exercises. Mirrors the `*_trnc` rows' pattern: the row
* pins the clamp emit, not just the exit code. */
{ "bool_to_i8_clamp",
"fn main() i32 = {\n"
"\tlet b: bool = true;\n"
"\tlet y: i8 = b: i8;\n"
"\treturn (y: i32);\n"
"};\n",
1 },
};
static int