Skip to content

comptime integer arithmetic evaluates at 32 bits — 3000000001i64 + 0i64 silently yields -1294967295 #943

Closed

Description

@migueldecimal128

Summary

The comptime evaluator performs integer arithmetic at 32 bits regardless of
the declared type. Values wider than i32 are truncated on the way into the
arithmetic helper, before the overflow check runs — so an out-of-range operand is
silently normalized rather than diagnosed.

The clearest demonstration is adding zero:

comptime fn ident -> i64: 3000000001i64 + 0i64
const I: i64 = comptime ident()
fn main: print(f"{I}")
-1294967295        // expected 3000000001

Both operands carry explicit i64 suffixes, the function returns i64, and the
const is annotated i64. -1294967295 is exactly 3000000001 - 2^32.

This is not a 128-bit issue — plain i64 comptime arithmetic is affected today.

Reproduction

comptime fn lit    -> i64: 3000000001i64                    // no arithmetic
comptime fn ident  -> i64: 3000000001i64 + 0i64             // add zero
comptime fn divbig -> i64: 3000000000i64 / 1000000000i64    // division
comptime fn edge   -> i64: 2147483647i64 + 1i64             // i32 MAX + 1

const L: i64 = comptime lit()
const I: i64 = comptime ident()
const D: i64 = comptime divbig()

fn main:
    print(f"lit    = {L}")
    print(f"ident  = {I}")
    print(f"divbig = {D}")
Expression Expected Actual
3000000001i64 (no arithmetic) 3000000001 3000000001 — correct
3000000001i64 + 0i64 3000000001 -1294967295 — silent
0i64 - 3000000000i64 -3000000000 1294967296 — silent
3000000000i64 / 1000000000i64 3 3 — correct
2147483647i64 + 1i64 2147483648 error: integer overflow in comptime

The same wrap occurs through a typed local (var x: i64 = 2147483647; x + 1),
so annotating the binding does not avoid it. The identical expression evaluated
at runtime rather than comptime is correct, and lit above shows the value
survives comptime → const materialization intact when no arithmetic is applied.

2147483647i64 + 1i64 raising an overflow error is itself the proof that the
arithmetic is being done at 32 bits.

Root cause

Three links, all at 22e534c6:

1. src/ComptimeEval.w:7862 — integer literals default to i32

return comptime_control_value(comptime_value_int(
    self.node_type_or(node, self.sema.ty_i32 as i32), fast.value))

A literal that fits in i64 takes this fast path. When typed_expr_types has
no entry for the node, node_type_or falls back to ty_i32. The exact path
one line above (:7861) — for literals too large for i64 — falls back to
ty_i64, so the two paths disagree on their default.

Sema itself has the correct type. with analyze on the ident case reports the
binary node as i64:

sema expression node:6657  node-kind=25  type-name=i64  start=26 end=46

So the type information exists; the evaluator's lookup misses it and takes the
i32 fallback.

2. src/ComptimeEval.w:6742 — the fallback propagates

let result_ty = self.node_type_or(node, if lhs.type_id != 0: lhs.type_id else: rhs.type_id)

lhs.type_id is now i32, so comptime_int_width(result_ty) returns 32.

3. src/Overflow.w:154-155 — operands are truncated before the check

fn int_signed_add(lhs: i64, rhs: i64, width_raw: i32, mode: i32) -> IntArithmeticResult:
    let width = int_width_clamp(width_raw)
    let lv = int_truncate_to_width(lhs, width, false)   // 3000000001 -> -1294967295
    let rv = int_truncate_to_width(rhs, width, false)
    let min = int_signed_min(width)
    let max = int_signed_max(width)
    let over_hi = rv > 0 and lv > max - rv               // rv == 0 -> false
    let over_lo = rv < 0 and lv < min - rv               // rv == 0 -> false
    let wrapped = int_truncate_to_width(lv +% rv, width, false)
    if not over_hi and not over_lo:
        return int_arith_ok(wrapped)                     // returns the corrupted value

The overflow check asks whether the operation overflows, but by then the
operands have already been silently truncated. Adding 0 cannot overflow, so
the corruption is never flagged. int_signed_sub (:171-172) and
int_signed_mul (:203-204) have the same ordering.

This is the link that makes the bug silent. Link 1 alone would produce loud
errors on any out-of-range literal.

Division is unaffected because the OP_DIV arm in ComptimeEval.w computes
lv / rv directly and only consults the width for int_div_overflows — it never
truncates its operands.

Relationship to #914

This corrects the D4 characterization in the i128/u128 plan, which describes
comptime evaluation as "i64-only" and silently narrowing for 128-bit values. The
measured boundary is 32 bits, and the corruption reaches i64 code that has
nothing to do with 128-bit integers.

It also affects the plan's proposed D4 mitigation. Refusing 128-bit operands with
a diagnostic would be keyed on the evaluator's own notion of width — which is 32
here, not 128 — so the refusal would not fire and these expressions would still
be silently corrupted. Fixing the operand-truncation ordering in Overflow.w
converts silent corruption into a loud error across all widths at once, which
matches the plan's stated principle that a loud gap is shippable and a silent
truncation is not.

Filing separately because the i64 corruption is independent of the 128-bit
campaign and is probably worth landing first.

Test coverage

There are no comptime integer overflow tests in test/behavior/, and the only
128-bit test is the 12-line smoke test behav_i128_u128.w (1 + 1, 40 + 2).
Nothing in the suite would catch this.

Provenance

Runtime measurements and the with analyze output were produced with the
released v0.15.1.7 binary (tagged at 04ca1a74). Root cause was read at
22e534c6.

The two are equivalent for this bug. Between 04ca1a74 and 22e534c6:

So every code path exercised by the reproduction is identical in the two
revisions, and the behavior above is the behavior at 22e534c6.

I was not able to confirm this by building 22e534c6 directly — with build
on a clean checkout does not produce out/stage/bin/with-stage2 with a
v0.15.1.7 seed, so the bootstrap never reaches a usable stage compiler.
That may well be a seeding mistake on my part rather than a repo issue; I have
not filed anything about it.


Investigated and drafted jointly by @migueldecimal128 and Claude (Claude Code).

Activity

  1. migueldecimal128 commented on Sep 2, 2026

    @migueldecimal128
    ContributorAuthor

    Correction: u64 is affected too, and more quietly

    The report above uses only signed examples, which makes it read as an i64
    issue. It isn't — u64 is affected by the same root cause, and the unsigned
    manifestation is harder to notice.

    All three identity operations corrupt their operand:

    comptime fn a -> u64: 4294967301u64 + 0u64    // 2^32 + 5
    comptime fn b -> u64: 4294967296u64 + 0u64    // 2^32
    comptime fn c -> u64: 8589934592u64 + 7u64    // 2^33 + 7
    comptime fn s -> u64: 4294967301u64 - 1u64
    comptime fn m -> u64: 4294967301u64 * 1u64
    
    Expression Expected Actual
    4294967301u64 + 0u64 4294967301 5
    4294967296u64 + 0u64 4294967296 0
    8589934592u64 + 7u64 8589934599 7
    4294967301u64 - 1u64 4294967300 4
    4294967301u64 * 1u64 4294967301 5

    2^32 silently evaluating to 0 is the case I would most want to avoid
    shipping. Unlike the signed examples, these results are small positive integers
    — they look like ordinary data rather than obvious garbage, so they are unlikely
    to be spotted by inspection.

    Same root cause

    int_unsigned_add (src/Overflow.w:109-110), int_unsigned_sub (:125-126),
    and int_unsigned_mul (:138-139) each truncate both operands to width before
    the overflow check, exactly as the signed helpers do:

    fn int_unsigned_add(lhs: i64, rhs: i64, width_raw: i32, mode: i32) -> IntArithmeticResult:
        let width = int_width_clamp(width_raw)
        let lv = int_truncate_to_width(lhs, width, true)   // 4294967301 -> 5
        let rv = int_truncate_to_width(rhs, width, true)
        let exact = exact_int_add_values(exact_int_value(lv, 0), exact_int_value(rv, 0))
        ...
        if exact.overflow == 0 and exact_int_fits_unsigned_bits(exact, width):
            return int_arith_ok(wrapped)                    // 5 + 0 does not overflow
    

    5 + 0 cannot overflow at any width, so nothing is flagged. The unsigned add
    and mul helpers do use the exact_int_* machinery for the operation itself,
    which is more careful than the signed path — but that care is spent on operands
    that were already corrupted one line earlier.

    One accidental guard, and a misleading message

    When the truncated value happens to land negative, the unsigned fit check
    catches it at materialization:

    comptime fn uident -> u64: 3000000001u64 + 0u64
    const UI: u64 = comptime uident()
    
    error: integer literal does not fit expected type
           (digits='' raw=-1294967295 expected=9 resolved_kind=1 d0=64 d1=0)
    

    Note raw=-1294967295 — the identical corruption from the signed report,
    surfaced only because the result went negative. Two things worth noting:

    1. Whether u64 fails loudly or silently depends on which side of zero the
      truncated value lands on. That is not a guard anyone should rely on.
    2. The message blames a literal, but there is no ill-fitting literal here —
      3000000001u64 fits u64 fine. The diagnostic points away from the actual
      fault. Worth fixing alongside, since anyone hitting it will start debugging
      in the wrong place.

    Scope note

    Signed and unsigned share the single root cause described in the issue body, so
    a fix to the operand-truncation ordering should cover both. Flagging it
    explicitly because the issue title and examples name only i64, and a fix
    scoped from those alone would leave 2^32 -> 0 live.

    Provenance is as stated in the issue body: measured on v0.15.1.7
    (04ca1a74), and src/Overflow.w is byte-identical at 22e534c6, so these
    results hold at main.

  2. migueldecimal128 commented on Sep 4, 2026

    @migueldecimal128
    ContributorAuthor

    Provenance update: reproduced directly on 22e534c6

    The Provenance section above argues from unchanged diffs that measurements taken
    with the released v0.15.1.7 binary hold at main. That inference is no longer
    needed — I built the compiler from 22e534c6 and reproduced all three symptom
    classes on it directly.

    $ out/release/bin/with --version
    with v0.15.1.7-g22e534c6c
    
    comptime fn ident -> i64: 3000000001i64 + 0i64
    comptime fn uadd  -> u64: 4294967296u64 + 0u64
    const I: i64 = comptime ident()
    const U: u64 = comptime uadd()
    const S: i64 = comptime (1i64 << 40)
    
    3000000001i64 + 0i64 = -1294967295      (expect 3000000001)
    4294967296u64 + 0u64 = 0                (expect 4294967296)
    1i64 << 40           = 0                (expect 1099511627776)
    

    The tree is healthy while this is live

    Worth recording, because it sharpens the "Test coverage" section: this was
    reproduced on a checkout where every gate passes.

    with build            → all targets green
    with build :fixpoint  → FIXPOINT (stage2 byte-identical to stage3)
    with build :test      → all targets green, 35 targets, 618s, 0 failures
    otool -L out/release/bin/with | grep -iE 'clang|LLVM'  → no dynamic dependency
    

    The full battery is green with 2^32 + 0 folding to 0. Nothing in the suite
    observes comptime integer arithmetic past 2^31, so the bug is invisible to it.

    Reproducing this needs a :deps workaround

    with build :deps fails on a clean checkout:

    error: deps: could not find a release containing asset
           'with-llvm-sdk-22.1.6-darwin-aarch64.tar.gz'
    

    The asset exists — it is published on v0.15.1.7 and on every nightly, so the
    message names the wrong thing whatever the cause. Root cause not established.
    I originally wrote here that seed_release_from_api (build/seed.w:137) was at
    fault; that was a guess and it does not hold up. Replaying that function's
    algorithm against the live releases?per_page=10 response finds the asset and
    returns a tag, and seed_fetch_to_file emits its own diagnostic on a fetch
    failure, which did not appear. The failure was observed once and I could not
    reproduce it afterwards, since the marker short-circuits the target once the SDK
    is in place. Treat the lookup as unproven rather than as the culprit.

    The documented escape hatch works regardless:

    WITH_LLVM_SDK_VERSION=v0.15.1.7 with build :deps

    Failing that, fetching the asset and extracting it into .deps/ works, since
    the tarball's top-level directory is already llvm-22.1.6-darwin-arm64 as
    BuildGraphTools.w:58 expects. Note the asset name says aarch64 while the
    directory says arm64.

    Noting it here only so the next person to reproduce this does not lose an hour
    to it. Not filed separately — without a reproduction there is nothing actionable
    to file.

    Edited to withdraw the seed_release_from_api attribution, which I could not
    substantiate.

  3. eas4ai commented on Sep 4, 2026

    @eas4ai
    Contributor

    Still reproduces at 450733e (seed stage1): 3000000001i64 + 0i64 in comptime yields -1294967295, re-verified during read-only audit (probe .audit/probes/comptime/t23_i64_silent.w). Sibling checks all loud: comptime division-by-zero errors, I/O rejected, infinite loop/recursion hit step limits (rc=1 each). So the 32-bit truncation is isolated to value narrowing, not a general limit failure.

  4. migueldecimal128 commented on Sep 4, 2026

    @migueldecimal128
    ContributorAuthor

    Thanks for confirmation. I'm still working on getting it fixed.

  5. added 4 commits that reference this issue on Sep 4, 2026
  6. migueldecimal128 commented on Sep 5, 2026

    @migueldecimal128
    ContributorAuthor

    The :deps workaround note above is now root-caused and filed as #1079

    My earlier comment described with build :deps failing on a clean checkout with

    error: deps: could not find a release containing asset
           'with-llvm-sdk-22.1.6-darwin-aarch64.tar.gz'
    

    and then withdrew the attribution to seed_release_from_api
    (build/seed.w) as unproven, on the grounds that replaying that function's
    algorithm against the live releases?per_page=10 response finds the asset and
    returns a tag.

    That withdrawal was wrong. The original attribution was correct, and the
    failure is deterministic rather than intermittent. Filed as #1079.

    The replay succeeds only against a pretty-printed copy of the response — what
    gh api or a browser renders. The GitHub REST API returns compact JSON, and
    seed_release_from_api parses it line by line, so the whole 239,931-byte body
    is a single "line", the scan loop runs exactly once, and seed_json_line_value
    returns the first "name" in the entire document — the release's own display
    name — instead of ever reaching assets[].

    Running the two functions transcribed verbatim from build/seed.w against the
    raw bytes the fetch helper writes:

    body bytes     = 239931
    lines produced = 1
      line 0: tag_name -> 'v0.15.1.12'   name -> 'With v0.15.1.12'
    RESULT = ''  (empty => 'could not find a release containing asset')
    

    It looked intermittent because the :deps marker file short-circuits the target
    once the SDK is on disk, so it only surfaces on a checkout that actually needs
    to download.

    with build :seed has the identical defect through the same helper, which is
    the more damaging half: a checkout whose installed compiler has fallen behind
    main cannot bootstrap back, because the command that repairs a stale seed is
    itself the broken one. The stale seed then fails somewhere else entirely — on
    main at 5a21c2e0 a v0.15.1.7 seed dies with comptime index requires an array, tuple, or vec, and on this branch's base it dies with expression kind 26 is not comptime-evaluable yet during pcre2-wo-build — neither of which
    points at the seed.

    Workaround unchanged, and it applies to both targets:

    SEED_VERSION=v0.15.1.12 with build :seed
    WITH_LLVM_SDK_VERSION=v0.15.1.12 with build :deps

    Nothing here bears on the comptime width defect this issue tracks; it only
    retires the "root cause not established" note above.

  7. added 5 commits that reference this issue on Sep 5, 2026
  8. added a commit that references this issue on Sep 5, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions