Skip to content

[codegen] repeat-init [v; N>64] initializes only N/sizeof(T) elements; tail left uninitialized #1049

Closed

Description

@eas4ai

Summary

Repeat initialization [v; N] with N > 64 and a non-u8 element type initializes only the first N / sizeof(T) elements. The tail keeps uninitialized stack contents, producing silent wrong runtime values.

Repro

use std.builtins.print_i32
fn main -> i32:
    var a: [u32; 100] = [5u32; 100]
    var i = 0
    var first = -1
    var bad = 0
    while i < 100:
        if a[i] != 5u32:
            if first == -1:
                first = i
            bad = bad + 1
        i = i + 1
    print_i32(first)  // 25, expect -1
    print_i32(bad)    // 75, expect 0
    0

Observed initialized prefix (first / bad) at 450733e, all stable across runs:

case good bad
[u32; 80] 20 60
[u32; 100] 25 75
[u16; 80] 40 40
[u64; 72] 9 63
[u64; 80] 10 70
[u64; 65] 8 + elem 8 reads back 7 by luck of stack garbage (9/56 printed) —

Rule: exactly floor(N / sizeof(T)) elements are initialized. N <= 64 (aggregate lowering) and u8 (memset path, where elem count == byte count) are unaffected. Raw-pointer reads agree with index reads, and two consecutively initialized arrays show no cross-corruption, so this is an under-write, not a read-path disagreement.

Localization (all verified by execution)

  • MIR is correct: --dump-mir shows array_fill(const 5ty8, count=100) (d1 = N).
  • C backend is correct: --emit-c produces for (__with_i = 0; __with_i < 100; ...).
  • LLVM emission is correct: with WITH_DUMP_MIR_CLEANUP_FN='main', pre-cleanup IR for [u32; 80] contains all 80 store i32 5 with GEPs [80 x i32], 0, 0..79 (valid IR: in-bounds, aligned; module verifier is silent).
  • A gdb trace on LLVMBuildGEP2/LLVMBuildStore during compilation shows 80 consecutive (GEP, store) pairs with one shared base/type and second indices 0..79, so the for i in 0..fill_count loop in codegen executes the full trip.
  • After the mandatory per-function sroa,mem2reg MIR cleanup (run_mir_cleanup_passes, src/CodegenDispatch.w:15607), only 20 stores remain — in -O1 IR, -O0 objects, and every stage binary (stage1, stage2, release, and seed-archive v0.15.1.6/1.7, so this is old, not a recent regression).
  • Both LLVM fill sites emit the same GEP loop: temp path (src/CodegenDispatch.w:3851) and direct-to-local path (:5263).

So the defect is the interaction between the fully-unrolled N-store sequence and the always-on sroa,mem2reg cleanup, which reduces it to the first N / sizeof(T) stores. That quotient smells like a Mystery Division, but all contributor-side values are exact (d1 = N, loop trips = N); the division appears inside the LLVM step, not in With source.

Notes for the fix (not applied; audit is read-only)

  • The u8 memset path passes af_arr_len (element count) as the byte length — accidentally correct for u8. Any scalar-width memset (len = N * sizeof(T)) or a byte-count loop bound would sidestep the SROA interaction entirely.
  • The sibling array-copy path has the same elem-count-as-bytes shape and is live-broken (separate issue).

Activity

  1. ehartford commented on Sep 16, 2026

    @ehartford
    Contributor

    Review: reproduced

    Verdict. The central defect is reproduced exactly: a repeat-init [v; N] with N > 64 and a non-u8 element type leaves the tail uninitialized, and exactly floor(N / sizeof(T)) elements are set. The observed table matches on both compilers. The localization is where I diverge from the report: the root cause is not SROA dropping valid stores. The fill store loop is correct and emits all N stores; the truncation is a single wrong length on the array-copy that carries the fill result into the local — a memcpy whose byte length is the element count instead of the byte size. The report's own footnote ("the sibling array-copy path has the same elem-count-as-bytes shape and is live-broken") names the real cause but files it as a separate issue; it is this issue.

    Tested.

    Source main @ 5809ac1 (2026-09-14)
    Compilers with v0.15.2.1 built from 5809ac1 (staging worktree); a compiler built from the reported revision 450733e with the nightly-20260903 seed. Same results
    Platform macOS Darwin 25.6.0 arm64

    Reproduction (first = first wrong index, bad = count wrong):

    case first bad initialized elems = floor(N/sizeof(T))
    [u32; 64] -1 0 64 not truncated (see boundary)
    [u32; 65] 16 49 16 65/4
    [u32; 80] 20 60 20 80/4
    [u32; 100] 25 75 25 100/4
    [u16; 80] 40 40 40 80/2
    [u64; 72] 9 63 9 72/8
    [u64; 80] 10 70 10 80/8
    [u8; 100] -1 0 100 100/1 (accidentally whole)
    [u8; 200] -1 0 200 200/1

    Root-cause evidence (observed, not inferred). For var a: [u32; 80] = [5u32; 80], the pre-run_mir_cleanup_passes IR (WITH_DUMP_MIR_CLEANUP_FN=main) is correct: two [80 x i32] allocas, 80 element-indexed stores store i32 5, ptr %11..%90, align 4 into the temp %9 with GEPs getelementptr [80 x i32], ptr %9, i32 0, i32 0..79. Then the fill result is copied into the local %8 by:

    call void @llvm.memcpy.p0.p0.i64(ptr %8, ptr %9, i64 80, i1 false)
    

    The length is 80 — the element count — but [80 x i32] is 320 bytes. So the copy moves 80 bytes = 20 u32 elements. After sroa,mem2reg this correctly reduces to 20 stores covering bytes 0..79 (store i32 5, ..., align 1 at byte offsets 0,4,…,76). SROA is behaving correctly; it is faithfully propagating an 80-byte copy. The reduction to floor(N/sizeof(T)) is arithmetic on the wrong memcpy length, not a lost-store bug in SROA.

    Exact site. src/CodegenDispatch.w:5227:

    let mc_len = wl_const_int(wl_i64_type(self.context), wl_get_array_length(use_arr_ty), 0)
    

    wl_get_array_length is LLVMGetArrayLength2 (src/compiler/LlvmBridge.w:644) — the element count, passed straight to llvm.memcpy as a byte length. This is the array-copy path for RK_USE/OK_COPY, and it is gated on wl_get_array_length(use_arr_ty) > 64 at :5218. That gate — not "aggregate lowering" — is why N <= 64 is unaffected: arrays of 64 or fewer elements never take the memcpy path. And u8 is accidentally correct because element count equals byte count. Both facts the report attributes to other mechanisms are explained by this one gate + this one length.

    Why the fill itself is exonerated. The non-u8 fill uses the element-store loop (:5200-5208) which the pre-cleanup IR confirms emits all 80 correct stores; the u8 fill uses llvm.memset with af_arr_len (:5188), correct because that branch is width-8-only. wl_lower_aggregate_copies(...,64) in run_mir_cleanup_passes (:15477) only rewrites whole-aggregate stores and does not touch these scalar stores; it is not implicated.

    Severity. High. This is a silent miscompile of a common construct ([v; N] into a local for any N > 64 of a multi-byte element type), producing stack garbage with no diagnostic and passing with check. It is old, not a recent regression (reproduces on 450733e and, per the report, in seed archives back to v0.15.1.6).

    Validator gap. The LLVM module verifier is silent because the truncated memcpy is well-formed IR; there is no invariant that a value-array copy covers the whole aggregate. with build :drop-audit / codegen audits do not cover repeat-init tails. A codegen invariant that an array-to-array OK_COPY memcpy length equals ABISizeOf(array_ty) would have caught this.

    Related PRs. #1129 (936c1a0, aggregate-copy store merging) added wl_lower_aggregate_copies; it is adjacent but not the cause. No open PR fixes :5227.

    Recommendation — I would champion this. One-line fix: mc_len = wl_const_int(i64, wl_abi_size_of(wl_get_module_data_layout(self.llmod), use_arr_ty), 0) (the helper exists at LlvmBridge.w:1220). Acceptance criteria:

    • Every row of the table above reports first = -1, bad = 0.
    • The pre-cleanup memcpy length for [u32; 80] is 320, not 80.
    • A test/behavior case initializes [u32; 100], [u16; 80], [u64; 80], and a struct array > 64, and asserts every element; plus a value-array copy let b = a for the same sizes.
    • A codegen audit asserts array OK_COPY memcpy length equals ABISizeOf(array_ty), so no other wl_get_array_length-as-bytes site can regress.

    Untested. Struct-element arrays > 64 (same copy path, should truncate identically but I only exercised integer elements); -O0 object output (I used with run and IR dumps); Linux/Windows.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions