Commit 82d5cace

82d5cace65d9Merged

Yukihiro "Matz" Matsumoto <[email protected]> · 6 months ago · 3 files · +2 added · ~1 modified

Description

fix(codegen): emit LL suffix on integer literals to avoid int32 overflow

Plain integer literals in the generated C carried no type suffix, so an expression of pure int literals (24329 * 256 * 500) folded by the C compiler using int arithmetic — overflowing INT_MAX and producing a silently wrong constant value.

Most call sites assigned to mrb_int (= long long) slots, which implicitly promoted the result and hid the issue. Constant-init contexts (static mrb_int cst_<name> = (...)) are evaluated by the C compiler before any assignment, so the overflow was the final value stored.

Surfaced via optcarrot's APU::Mixer constants, e.g. TND_1 = 100 * 24329 * 256 / 500 whose intermediate product clears int32. -Woverflow flagged it; now the literals carry LL so C performs the arithmetic in long long throughout.

Co-Authored-By: Claude Opus 4.7 (1M context) [email protected]

Details

Commit
82d5cace65d9
Parent
4c0ef26e9d86

spinel_codegen.rbmodifiedView file

@@ -21308,7 +21308,16 @@
2130821308 exit(1)
2130921309 end
2131021310 if t == "IntegerNode"
21311- return @nd_value[nid].to_s
21311+ # Suffix with `LL` so the literal is `long long` rather than
21312+ # `int` in the emitted C. Without it, an expression of int
21313+ # literals whose product exceeds int32 (e.g. APU mixer
21314+ # constant `24329 * 256 * 500 = 3,114,112,000`) overflows
21315+ # at constant-folding time and the C compiler emits a wrong
21316+ # value. Plain literals at runtime sites get implicitly
21317+ # promoted to mrb_int (= long long) on assignment, but
21318+ # constant-init expressions are evaluated by the C compiler
21319+ # using the literals' declared type.
21320+ return @nd_value[nid].to_s + "LL"
2131221321 end
2131321322 if t == "FloatNode"
2131421323 return @nd_content[nid]