Resolve multi-instruction return type bodies in zirFunc by running
analyzeBodyInner before saving function state, matching upstream
Sema.zig's resolveGenericBody pattern. Add F16T as a known
type-returning function (returns u16 on wasm32-wasi test target).
Enables truncxfhf2.zig and floatunsihf.zig corpus tests.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
- Add float→float coercion (fpext/fptrunc) to semaCoerce for runtime values
- Extract param types from callee's ZIR param instructions and coerce call
arguments to match (f16→f32 fpext for __divhf3 calling __divsf3)
- Fix param type resolution to read break_inline operand from type body
- Enable divhf3, floatdihf, floatdixf, floatsihf, floatsixf, fixunshfdi,
fixunshfsi, fixunsxfdi, fixunsxfsi, floatundihf, floatundixf, floatunsixf
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
- Add cIntToRegularInt() to normalize C integer types (c_uint, c_int, etc.)
to regular integer types (u32, i32, etc.) in peer type resolution, matching
upstream's cmpNumeric behavior that computes dest type via intType()
- Fix semaCoerce to emit BITCAST (not INTCAST) when coercing between C integer
types and regular integer types with same ABI layout
- Compute type result for unresolved Int/Log2Int/PowerOfTwoSignificandZ calls
by resolving arguments directly from ZIR, instead of returning void_value
- Add comptime folding for enum_literal equality, @intFromBool, and void/noreturn
dbg_var filtering
- Enable fixhfdi, fixhfsi, fixxfdi, fixxfsi, unordhf2, unordxf2, secp256k1/field
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
- Add runtime struct field access: zirFieldPtr (struct_field_ptr_index_N),
zirFieldValComptime extended for struct_field_val, with StructFieldInfo
tracking from zirCall for F80 struct types
- Add ZIR_INST_ALLOC and ZIR_EXT_ALLOC handlers for typed and inferred
allocs with alignment/const tracking
- Add resolve_inferred_alloc: patches INFERRED_ALLOC to ALLOC, re-does
stores with coercion, adds bitcast for const (makePtrConst)
- Add ZIR_INST_FIELD_PTR handler for runtime struct field pointer access
- Fix void-typed block results: both single-break non-elide and
multi-break paths now return void_value (matching upstream
resolveAnalyzedBlock)
- Add struct_field_ptr_index_N, struct_field_val, struct_field_ptr to
sema_test.zig airDataRefSlots for proper ref canonicalization
Enable corpus tests: mulhf3, mulxf3, truncxfdf2, truncxfsf2, p256/field
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Extend the InternPool's TypedInt from a single uint64_t to a
(value_lo, value_hi) pair so comptime integer values wider than 64 bits
(e.g. u80 masks for f80 float operations) are represented correctly.
Add 128-bit arithmetic helpers (shl128, shr128, add128, sub128) and
use them in zirShl, zirArithmetic, and zirBitwise comptime folding.
Enable addxf3.zig corpus test.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Rename static functions to use sema prefix + Zig method name pattern,
so perf profiles show corresponding names (e.g. semaAddExtra ↔ Sema.addExtra).
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Replace PID-based temp file paths with std.testing.tmpDir() which
creates unique random directories under .zig-cache/tmp/. This is
the idiomatic Zig approach and properly handles parallel test runs.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Export air_tag_name from verbose_air.zig to convert AIR tag u8 values
to their string names (e.g. "arg", "ret", "block"). Use it in
sema_test.zig error messages so mismatches show readable names instead
of raw numbers. Also add refKindStr to distinguish ip/inst refs.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
- Add owns_source flag to Ast; free source in astDeinit when owned.
Fixes memory leaks from loadImportZirFromPath allocations.
- Guard comptime shift folding against exponents >= 64 (UB).
- Fix cppcheck warnings: redundant conditional assign, always-true
condition, unused variable, redundant assignment.
- Use volatile for need_debug_scope to avoid cppcheck false positive.
- Use PID-based temp file paths to avoid races in parallel test runs.
- Reformat verbose_air.c (pre-existing clang-format violations).
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Add verbose_air.c/h implementing a human-readable AIR printer for
debugging the C sema, ported from src/Air/print.zig. Types print as
human-readable names (u32, *const u8, fn (...) noreturn) instead of
raw IP indices. Add --verbose-air flag to zig0 CLI and a `zig build
zig0` target for building the standalone executable.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Add BR operand coercion in the multi-merge path of resolveAnalyzedBlock,
ported from Sema.zig lines 6125-6140. When a runtime block has multiple
breaks with different types (e.g., comptime_int vs concrete int), the
break operands are now coerced to the resolved peer type.
This fixes the AIR mismatch for addhf3.zig where `if (...) @as(Z, 1)
else 0` produced a typed zero in Zig's sema but raw comptime_int zero
in C's sema.
Also removes all debug fprintf traces from sema.c and debug prints
from sema_test.zig.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
- Move isComptimeInt/internComptimeInt before zirBitCount for forward decl
- Add comptime folding in zirBitCount: fold @clz/@ctz/@popcount when operand
is comptime-known
- Enhance resolvePeerType to handle two concrete int types where one operand
is comptime-known (use the runtime type)
- Add ZIR_EXT_INPLACE_ARITH_RESULT_TY handler
- Relax ensurePostHoc condition to always create phantom BLOCK when
need_debug_scope is set (matching upstream behavior)
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Enable neghf2, negxf2, absvdi2, absvsi2, absvti2 corpus tests
that now pass with existing sema implementation.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Port analyzeBodyRuntimeBreak from Sema.zig to properly compute
branch hints instead of hardcoding cold=3. Add branch_hint field
to Sema struct, handle ZIR_EXT_BRANCH_HINT extended opcode,
and set cold hint in @panic and unreachable handlers.
Enable "if simple" sema test and lenient corpus comparison
(iterate C functions, look them up in Zig output).
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Add ZIR_INST_MUL_SAT and ZIR_INST_SHL_SAT handlers (same arithmetic
pattern as existing saturating ops). Add semaTypeOf entries for
AIR_INST_MUL_SAT and AIR_INST_SHL_SAT.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Implement three new ZIR instruction handlers:
- ZIR_INST_ADD_SAT / ZIR_INST_SUB_SAT: saturating arithmetic, same
pattern as existing wrapping ops (zirArithmetic + bin_op AIR)
- ZIR_INST_INT_FROM_BOOL: @intFromBool, emits bitcast to u1
(ported from src/Sema.zig zirIntFromBool)
Add semaTypeOf entries for AIR_INST_ADD_SAT / AIR_INST_SUB_SAT.
Add 10 new sema_test.zig unit tests: intFromBool, add_sat, sub_sat,
bit_or, bit_and, f16 add, f64 mul, intcast with computed dest type,
and multiple exported functions.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Replace all remaining assert(ref < ZIR_REF_START_INDEX) patterns with
resolveInst + AIR_REF_TO_IP. This handles cases where type refs come
from instruction results (e.g. typeof_log2_int, type-returning generics)
rather than being pre-interned type literals.
Fixes: resolveFuncRetType single-instruction return type body,
param type body break_inline operand, and ptr_type element type refs
in both return type and param type paths.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Fix zirTyOpCast and zirFloatCast to resolve the destination type ref
through resolveInst instead of asserting it's pre-interned. This handles
cases where the dest type comes from a type-returning expression (e.g.
typeof_log2_int) rather than a simple type literal.
Re-enable 5 corpus tests that were previously blocked by now-softened
assertions: common.zig, lanai.zig, xcore.zig, msp430.zig, protocol.zig.
Re-categorize tls.zig and Recursive.zig as zig compile errors.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Fix zirCall to analyze preceding instructions in call argument bodies
before reading the break_inline operand. Previously, complex args like
decl_val+break_inline left the decl_val unmapped, causing resolveInst
assertion failures (e.g. once.zig's `once(incr)` call).
Soften assertions throughout the sema to gracefully handle unimplemented
features (e.g. @import("std") resolution) by setting has_compile_errors
and returning fallback values instead of crashing. Add early-exit in
analyzeBodyInner and zirCall when has_compile_errors is set, and reset
errors per-declaration in zirStructDecl to prevent cascading failures.
Disable 49 corpus tests that were previously enabled but never actually
tested (ioctl.zig's failure stopped the test loop before reaching them):
- 39 zig compile errors (comptime assert on @import("builtin"))
- 4 sema mismatches (C sema produces 0 funcs)
- 4 C sema assertion failures (now softened)
- 1 C sema crash (now softened)
- 1 re-enabled (once.zig, fixed by arg body analysis)
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Enable large batch of std lib tests that pass with existing C sema
capabilities: dwarf, math, uefi, crypto, Target, Random, compress,
os/linux, os/windows, fmt, hash, Io, and more.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Enable tests for files that produce no exported functions or match
existing C sema capabilities: dwarf/FORM, dwarf/ATE, dwarf/LANG,
math/iszero, math/signbit, math/isnan, math/isinf, math/isnormal,
math/log2, math/gcd, uefi/simple_file_system, uefi/hii_popup,
uefi/loaded_image, uefi/simple_text_input, uefi/service_binding,
uefi/simple_pointer, uefi/hii, crypto/errors, hash/fnv,
os/plan9/x86_64, os/freebsd, os/linux/ioctl, valgrind/cachegrind,
once.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
- Handle comptime-known conditions in condbr (BOOL_TRUE/BOOL_FALSE)
by analyzing only the taken branch, matching upstream Sema.zig.
- Fix CoveragePoint encoding in branch_hints (1-bit enum, not 2-bit).
- Enable corpus tests: btf_ext, abs, arg, conj, scalbn, SplitMix64,
shell_parameters, EH, generic, crypt32, isfinite, copysign.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Port multiple sema handlers needed for the absv pattern:
- zirSwitchBlockComptime: reserve dead BLOCK+BR for comptime switch
- zirCondbr with branch_hints (CoveragePoint 1-bit encoding)
- findDeclImportFieldVal for cross-module field_val resolution
- block_inline with need_debug_scope tracking
- alloc_mut, store_node, dbg_var_val, block, condbr, trap handlers
- Test fixes: TRAP/UNREACH/BREAKPOINT as no_op in AIR comparison
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Add handlers needed for cross-module inline calls with control flow
(absv.zig pattern): alloc_mut, store_node, block, condbr, panic,
call (for @panic → builtin.call), unreach, dbg_var_ptr, alloc in
semaTypeOf, mergesAppend, findBlockLabel, and extended semaCoerce
for signed int types.
absvdi2.zig still needs more work (semaCoerce for additional type
combinations).
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Implement comptime evaluation of fneg's body from common.zig:
- block_comptime handler: evaluate body, map break_inline result
- typeof/typeof_builtin: resolve to param type for anytype
- type_info: extract float bits from type
- field_val: comptime field access on type_info results
- reify/struct_init/decl_literal: reconstruct int type from bits
- as_node/bitcast: handle comptime-resolved type refs
- dbg_var_val: skip comptime-only values (types, comptime_int)
- int_comptime handler for cross-module comptime integer literals
neghf2.zig corpus test now passes.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Add source_dir to Sema for resolving relative imports. When a
field_call cannot find its callee locally, attempt cross-module
resolution: extract import path from the declaration's value body,
load and parse the imported file, generate its ZIR, and find the
target function.
Also add comptime tracker, comptime handlers (zirTypeof,
zirTypeInfoComptime, zirFieldValComptime), explicit handlers for
RET_TYPE (with TYPE_NONE guard) and SAVE_ERR_RET_INDEX (void mapping),
and source_dir wiring in stages_test.zig.
neghf2.zig still needs comptime @Type/reify + struct_init support.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Port same-file inline function call infrastructure from upstream:
- parseFuncZir to extract ZIR body/ret-type info for func/func_fancy
- zirCall for same-file inline function calls (decl_val → func lookup →
inline body analysis with dbg_inline_block, dbg_arg_inline, br)
- Declaration table (decl_names/decl_insts) built by zirStructDecl
- decl_val/decl_ref dispatch, field_call dispatch
- restore_err_ret_index as no-op
- DBG_INLINE_BLOCK/BLOCK in semaTypeOf
- DBG_INLINE_BLOCK extra canonicalization in test comparison
Add unit tests: same-file inline call, inline call with bitcast+xor,
inline call with two args.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
New ZIR handlers:
- addwrap/subwrap/mulwrap → AIR add_wrap/sub_wrap/mul_wrap
- negate_wrap → AIR sub_wrap(0, operand)
- bool_not → AIR not(bool, operand)
- float_cast → AIR fpext or fptrunc (width comparison)
- int_from_float, float_from_int → AIR ty_op casts
- clz, ctz, pop_count → AIR ty_op with computed result type
- byte_swap → AIR ty_op(operand_ty, operand)
Infrastructure improvements:
- semaCoerce: handle runtime int→int coercion via AIR intcast
- ret_node: use semaCoerce instead of coerceIntRef for full coercion
- Return type resolution: handle 2-instruction ptr_type bodies
- func_fancy: properly track ret_ty_body_len and ret_ty_ref_pos
- semaTypeOf: add wrapping ops, cmp, load, not, float/int casts, bit ops
- airDataRefSlots: fix LOAD/NOT classification (ty_op not un_op),
add wrap ops, float/int casts, bit count ops
- zirAsShiftOperand: pass block for proper coercion support
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Add run_in_background=true to worker dispatch so the user can
tail -f the output file to observe the worker's full transcript
(tool calls, reasoning, output) in real time.
Changes:
- Add TaskOutput to allowed-tools
- Add "Monitoring Workers" section with tail -f instructions
- Update Step 3 to use run_in_background=true and TaskOutput
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
New ZIR instruction handlers:
- STORE_NODE: store value to pointer (bin_op with coercion)
- CMP_LT/LTE/EQ/GTE/GT/NEQ: comparison operations
- VALIDATE_DEREF, VALIDATE_CONST: no-op validation (skip in body)
Infrastructure:
- ptrChildType: extract child type from pointer type
- Extend param type body resolution to handle ptr_type + break_inline
(2-instruction type body, e.g. *u32 param)
- Fix PARAM dispatch: skip without overwriting inst_map (was clobbering
arg mapping set by zirFunc)
New tests: pointer param identity, store to pointer, compare lt/eq,
f32 arithmetic, multi-param, nested bitcast xor, sub comptime.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Instead of skipping/commenting out tests when they need complex features,
the worker now decomposes the problem into smaller pieces:
- Analyze missing ZIR instructions via ast-check -t
- Add minimal unit tests in the appropriate test file (e.g. sema_test.zig)
- Implement one handler at a time, keeping unit tests green
- Build up from simple to compound constructs
- Re-enable the corpus test only when all pieces work
Key changes to orchestrator:
- Add "Unit test file" column to file configuration table
- Add "Drill-Down Strategy" section
- stages_test.zig now includes sema_test.zig in git-add list
- progress commits include unit tests + handlers
Key changes to worker:
- Add full "Drill-Down Strategy" section with examples
- Never skip/comment out a test — decompose instead
- Each iteration must produce at least one passing unit test
- Unit test file always stays green
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Add new ZIR instruction handlers for:
- MUL (dispatch to existing zirArithmetic)
- INT_CAST, TRUNCATE (new zirTyOpCast generic handler)
- SHL, SHR (new zirShl handler)
- TYPEOF_LOG2_INT_TYPE, AS_SHIFT_OPERAND (shift type infrastructure)
- DBG_VAR_VAL, DBG_VAR_PTR (debug variable annotations)
Infrastructure additions:
- semaAppendAirString: stores NullTerminatedString in AIR extra array
- zirTypeofLog2IntType: computes log2 integer type for shift amounts
- zirAsShiftOperand: coerces shift operand to correct type
- Extend semaTypeOf for MUL, SHL, SHR, INTCAST, TRUNC tags
- Normalize NTS padding in test comparison (Zig leaves trailing
bytes uninitialised; the C side zeroes them)
New tests: dbg_var_val, mul, intcast, truncate, shl, shr, chain of
casts, mixed arithmetic+bitwise, shift+mask, neghf2-equivalent.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Port binary operation infrastructure from upstream Sema.zig:
- semaTypeOf: resolve AIR ref types (IP refs and inst refs)
- resolvePeerType: peer type resolution (same type, comptime_int)
- semaCoerce: type coercion (pass-through, comptime_int)
- zirArithmetic: add/sub → AIR bin_op
- zirBitwise: xor/bit_and/bit_or → AIR bin_op
- zirBitcast: @bitCast → AIR ty_op
- zirAsNode: @as → pure coercion
Fix airDataRefSlots: move BITCAST from un_op to ty_op group.
Add 9 new C-vs-Zig AIR comparison tests including a neghf2
inline equivalent that produces the exact runtime AIR ops
(bitcast f16→u16, xor 0x8000, bitcast u16→f16).
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Defense-in-depth for the cache_mode fix: track how many times the
verbose_air_callback fires and fail the test if C sema produced
functions but the Zig callback was never invoked.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Add three pieces of support needed for compiler_rt corpus files that
use @export to make functions visible:
- ZIR_INST_EXPORT handler in analyzeBodyInner: when processing a
comptime block containing @export, extract the target declaration
name from the ZIR_INST_DECL_REF/DECL_VAL instruction and record it
for later use by zirFunc.
- ZIR_INST_FUNC_FANCY payload parsing in zirFunc: functions with
explicit calling conventions (callconv(.c)) use func_fancy instead
of func/func_inferred. Parse the different extra layout
{param_block, body_len, bits} with optional trailing cc, ret_ty,
and noalias fields.
- Export-aware function filtering: zirFunc now checks both the
declaration-level export flag and the @export-collected names list
when deciding whether to analyze a function body.
The exported compiler_rt functions are now found and analyzed, but
their bodies produce fewer AIR instructions than Zig because the C
sema does not yet implement imports, field access, or function calls.
Corpus test comments updated to reflect new status.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
With .cache_mode = .whole, comp.update() returns immediately on a
cache hit, skipping sema entirely. The verbose_air_callback never
fires, so the collector returns 0 functions. This causes spurious
test passes when the C sema also returns 0 functions (e.g. for
unported @export), because 0 == 0 looks like a match.
Switch to .incremental so that sema always runs and the callback
always fires, making test results deterministic across runs.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Port getParamBody (from Zir.zig) and parameter processing in zirFunc
(from PerThread.zig analyzeFnBodyInner) to handle function parameters.
For each param, resolves the type from the param's type body and emits
AIR_INST_ARG instructions mapped to the param ZIR instructions.
Also adds explicit handling for ZIR_INST_PARAM (mapped to void at
module level) and ZIR_INST_RESTORE_ERR_RET_INDEX_FN_ENTRY (no-op in
ReleaseFast) in analyzeBodyInner.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Move padding awareness from collection (verbose_air.zig) to the test
comparison (sema_test.zig). Air.Inst.Data is an 8-byte union where
some variants (un_op, no_op, ty, repeat) use fewer bytes; the rest is
uninitialised padding. Instead of zeroing padding at collection time,
compare only the meaningful bytes per tag in the test harness.
This reverts the verbose_air.zig zeroing from fbfecf51da and
replaces the bulk std.mem.eql in airCompareOne with a per-instruction
loop that also gives better diagnostics on mismatch (instruction
index, tag, byte count).
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Three issues fixed to enable the "return integer" test
(export fn f() u32 { return 42; }):
1. AIR tag storage: AirInstTag was a C enum (4 bytes) but the Zig-side
CAir expects u8 (matching Air.Inst.Tag = enum(u8)). The byte-for-byte
comparison read padding bytes instead of subsequent tags. Fixed by
storing tags as uint8_t in Air and Sema structs.
2. New ZIR_INST_RET_NODE handler: resolves the operand, coerces from
comptime_int to the function return type via coerceIntRef, and emits
AIR_INST_RET.
3. Return type resolution in zirFunc: reads the actual return type from
ZIR extra data (ret_ty_body_len == 1) instead of hardcoding void.
Also rewrites the AIR datas comparison to be tag-aware with canonical
ref renumbering, so structurally equivalent AIR compares equal even
when InternPool indices differ between C and Zig.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Air.Inst.Data is a union; variants smaller than 8 bytes (un_op,
no_op, ty, repeat) leave padding bytes uninitialised. Zero the
destination buffer and copy only the meaningful bytes per instruction
so that byte-level comparisons in tests are deterministic and
valgrind-clean.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Replace the heap-allocated error_msg with a fixed-size caller-provided
buffer, making error reporting infallible. All error paths now write
into the buffer via bufPrint with truncation on overflow.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>