Commit 82b26e2d
82b26e2d41b5Merged
Ryan Seys <[email protected]> · 6 months ago · 4 files · +3 added · ~1 modified
Description
perf(codegen): fuse Range#each over literal numeric range to C for-loop
GAPS.md "Range#each over numeric range compiles to tight C for".
(1..100_000).each { |i| ... } previously copied the receiver into a
local sp_Range struct and looped against tmp.first / tmp.last. The
struct copy is essentially free, but the looping form blocks the C
compiler from seeing the bounds as constants — no unrolling, no
strength reduction, no bound-check elision against an obviously-finite
range.
The new fusion applies in compile_each_block's range arm when the
receiver is a literal RangeNode (or a parens-wrapped one). It mirrors
the to_a / count literal-range pattern: pull @nd_left and
@nd_right directly from the AST and emit:
for (lv_<bp> = <lo>; lv_<bp> <= <hi>; lv_<bp>++) { ... }
<= becomes < for exclusive ranges (...) — the existing
range_excl_end helper already exposes the parser bit. Non-literal
range receivers (r = 1..10; r.each { ... }) keep the existing
sp_Range-copy form since the bounds aren't visible at codegen.
Verified the generated C for test/range_each_fusion.rb contains
zero references to sp_Range or sp_range_new — the entire test runs
through inlined for loops.
Test exercises:
- accumulator over an inclusive range
(1..10).each=> 55 - accumulator over an exclusive range
(1...10).each=> 45 - negative bounds
(-3..3).each=> 0 - single-element inclusive range
(7..7).eachticks once - empty exclusive range
(5...5).eachticks zero times - 100_000-element loop counter (simulated GAPS.md repro)
- nested ranges
(1..3).each { |i| (1..3).each { |j| ... } }=> the inner loop doesn't shadow the outer block param
Out of scope: Float ranges (sp_Range is mrb_int-only), endless /
beginless ranges (1.., ..10), descending ranges with negative
step (Range#each is always ascending in Ruby).
Bootstrap: gen2.c == gen3.c. Tests: 217 pass.
Co-Authored-By: Claude Opus 4.7 (1M context) [email protected]
Details
- Commit
- 82b26e2d41b5
- Parent
- 1d5291554707
benchmark/bm_range_each.rbaddedView file
# bm_range_each - Range#each over a literal numeric range## Hot loop iterates `(1..500_000_000).each` accumulating# `sum + (i % 7)` per iteration. The `% 7` introduces a# sequential data dependency on the loop body so the C# compiler cannot collapse the loop to a closed form.## Tests Spinel's Range#each lowering: a literal numeric range# should fuse to a tight C `for` loop with bounds inlined,# avoiding the `sp_Range` struct allocation+access of the# generic `each` path.sum = 0(1..500_000_000).each { |i| sum = sum + (i % 7) }puts sumspinel_codegen.rbmodifiedView file
Loading diff…
test/range_each_fusion.rbaddedView file
Loading diff…
test/range_each_fusion.rb.expectedaddedView file
Loading diff…