Turn a self call added to a value into an accumulator loop

A function whose block ends `r = F(args); s = x + r; return s` (integer
result, either operand order) now adds x to an accumulator and jumps back
to its old entry with args instead of calling itself; every other
`return v` returns `acc + v`, and a new entry starts the accumulator at
zero. Integer addition wraps, so the regrouped sums are exact. The
replaced call ran last in its block, so effects keep their order. The old
entry's fuel moves to the new entry and each jump back charges one step,
so a run counts the same steps as before. GCC does the same at -O2.

Only a function that also has a base-case return is rewritten: one whose
only exit is the self call cannot return normally, so runaway recursion
such as `1 + Forever(depth + 1)` still takes the stack trap instead of
becoming an endless loop.

Fib(n-1) + Fib(n-2) keeps one call per loop iteration, half the calls.
The pass runs first in LirOptBuild, before inlining, as
compiler_opt_accumulate.zi. The new entry takes values 0.. as its
parameters, which native lowering expects of an entry block.

The three passes that each kept a private copy of the same encode/read
helper now share LirSsaSerialize in compiler_opt_ssa.zi.

compiler_opt_accumulate_cases covers fib (one self call left, values for
n = 0..20 with and without inlining), a call added to itself, a float sum
and a function with no base case (all three unchanged).
This commit is contained in:
waozi committed 2026-11-17 21:23:03 -03:00
1 parent e0f10da84b
commit 45b74b4e31
12 files changed
+645 -49

No files matched your search

+1
View File
@@ -2,6 +2,7 @@
## [Unreleased]
- The optimizer turns a self call whose integer result is added to another value and returned, as in `Fib(n-1) + Fib(n-2)`, into an accumulator loop, as GCC does at `-O2`: the remaining call runs once per iteration and the other becomes a jump back. Fib makes half as many calls. Effects keep their order, a run charges the same steps, and a function with no base case is left alone so runaway recursion still takes the stack trap.
- The native runtime builds on ARMv7 again. Only x86-64 checks the heap offsets used by its generated allocator.
- Native x86-64 code divides by a constant divisor folded into the instruction instead of first loading it into a register the division never reads, and starts every loop on a 32-byte boundary, so a change before a loop no longer moves its speed.
- Native x86-64 callers keep floating-point values in XMM registers across a direct call to a function whose allocated code, including its own calls, leaves those registers untouched, instead of spilling them around the call. The allocated-code verifier checks each reduced mask against the callee; indirect, recursive and not-yet-allocated callees keep the full ABI clobber set.
+2 -2
View File
@@ -253,7 +253,7 @@ obj = $(patsubst %.c,$(BUILD_DIR)/obj/%.o,$(1))
# bootstrap compiler opens no bundle and has none.
ENGINE_C := $(BUILD_DIR)/compiler-runtime
ENGINE_MODULES := binary math utf8 vec compiler_lowered_ir compiler_lowered_verify \
compiler_lowered_proven compiler_exec_serial compiler_exec_debug compiler_exec_link compiler_exec compiler_opt compiler_opt_ssa compiler_opt_rotate compiler_opt_loop compiler_opt_licm compiler_opt_induction compiler_opt_layout compiler_opt_inline compiler_opt_thread compiler_opt_dom compiler_learning compiler_learning_policy \
compiler_lowered_proven compiler_exec_serial compiler_exec_debug compiler_exec_link compiler_exec compiler_opt compiler_opt_ssa compiler_opt_rotate compiler_opt_loop compiler_opt_licm compiler_opt_induction compiler_opt_layout compiler_opt_inline compiler_opt_thread compiler_opt_accumulate compiler_opt_dom compiler_learning compiler_learning_policy \
text_buffer number_text compiler_zx_wasm_types compiler_zx_wasm_fn compiler_zx_wasm_plan compiler_zx_wasm_code \
compiler_zx_wasm_body compiler_zx_wasm_helpers compiler_zx_wasm
# The Wasm lowering of revision-28 ZX (cmd/compiler_zx_wasm*.zi) is part of
@@ -785,7 +785,7 @@ $(PROOF_C)/.generated: cmd/compiler_proof.zi cmd/compiler_ir.zi cmd/compiler_ser
-o $(PROOF_C) cmd/compiler_proof.zi
touch $@
$(ENGINE_C)/.generated: cmd/compiler_runtime.zi cmd/compiler_exec_link.zi cmd/compiler_exec_debug.zi cmd/compiler_exec.zi cmd/compiler_opt.zi cmd/compiler_opt_ssa.zi cmd/compiler_opt_rotate.zi cmd/compiler_opt_loop.zi cmd/compiler_opt_licm.zi cmd/compiler_opt_induction.zi cmd/compiler_opt_layout.zi cmd/compiler_opt_inline.zi cmd/compiler_opt_thread.zi cmd/compiler_opt_dom.zi cmd/compiler_learning.zi cmd/compiler_learning_policy.zi cmd/compiler_learning_table.zi \
$(ENGINE_C)/.generated: cmd/compiler_runtime.zi cmd/compiler_exec_link.zi cmd/compiler_exec_debug.zi cmd/compiler_exec.zi cmd/compiler_opt.zi cmd/compiler_opt_ssa.zi cmd/compiler_opt_rotate.zi cmd/compiler_opt_loop.zi cmd/compiler_opt_licm.zi cmd/compiler_opt_induction.zi cmd/compiler_opt_layout.zi cmd/compiler_opt_inline.zi cmd/compiler_opt_thread.zi cmd/compiler_opt_accumulate.zi cmd/compiler_opt_dom.zi cmd/compiler_learning.zi cmd/compiler_learning_policy.zi cmd/compiler_learning_table.zi \
cmd/compiler_exec_serial.zi cmd/compiler_lowered_verify.zi cmd/compiler_lowered_proven.zi cmd/compiler_lowered_ir.zi \
cmd/compiler_bundle.zi std/math.zi std/text_buffer.zi std/number_text.zi $(wildcard cmd/compiler_zx_wasm*.zi) $(BOOTSTRAP_BIN)
env -u DISPLAY -u WAYLAND_DISPLAY $(BOOTSTRAP_BIN) --no-main --root cmd \
+1 -1
View File
@@ -7,7 +7,7 @@ ASSEMBLY_MACHINE_SOURCES := cmd/compiler_vector_form.zi cmd/compiler_vectorize.z
cmd/compiler_encode.zi cmd/compiler_aarch64.zi cmd/compiler_armv7.zi \
cmd/compiler_arm_bytes.zi \
cmd/compiler_machine_elf.zi cmd/compiler_machine_pe.zi cmd/compiler_machine_pipeline.zi cmd/compiler_native_cache.zi
ASSEMBLY_SOURCES := std/math.zi cmd/compiler_bundle.zi cmd/compiler_lowered_ir.zi cmd/compiler_lowered_verify.zi cmd/compiler_lowered_proven.zi cmd/compiler_zir_lower.zi cmd/compiler_exec_serial.zi cmd/compiler_exec_debug.zi cmd/compiler_exec_link.zi cmd/compiler_exec.zi cmd/compiler_opt.zi cmd/compiler_opt_ssa.zi cmd/compiler_opt_rotate.zi cmd/compiler_opt_loop.zi cmd/compiler_opt_licm.zi cmd/compiler_opt_induction.zi cmd/compiler_opt_layout.zi cmd/compiler_opt_inline.zi cmd/compiler_opt_thread.zi cmd/compiler_opt_dom.zi cmd/compiler_learning.zi cmd/compiler_learning_policy.zi cmd/compiler_learning_table.zi $(ASSEMBLY_MACHINE_SOURCES)
ASSEMBLY_SOURCES := std/math.zi cmd/compiler_bundle.zi cmd/compiler_lowered_ir.zi cmd/compiler_lowered_verify.zi cmd/compiler_lowered_proven.zi cmd/compiler_zir_lower.zi cmd/compiler_exec_serial.zi cmd/compiler_exec_debug.zi cmd/compiler_exec_link.zi cmd/compiler_exec.zi cmd/compiler_opt.zi cmd/compiler_opt_ssa.zi cmd/compiler_opt_rotate.zi cmd/compiler_opt_loop.zi cmd/compiler_opt_licm.zi cmd/compiler_opt_induction.zi cmd/compiler_opt_layout.zi cmd/compiler_opt_inline.zi cmd/compiler_opt_thread.zi cmd/compiler_opt_accumulate.zi cmd/compiler_opt_dom.zi cmd/compiler_learning.zi cmd/compiler_learning_policy.zi cmd/compiler_learning_table.zi $(ASSEMBLY_MACHINE_SOURCES)
ifneq ($(BOOTSTRAP),1)
ifeq ($(NATIVE_HOST_ENABLED),1)
+10
View File
@@ -9,6 +9,7 @@ using Induction :: #import "compiler_opt_induction"
using Layout :: #import "compiler_opt_layout"
using Inline :: #import "compiler_opt_inline"
using Thread :: #import "compiler_opt_thread"
using Accumulate :: #import "compiler_opt_accumulate"
using Dominators :: #import "compiler_opt_dom"
#import "compiler_learning"
@@ -1963,6 +1964,13 @@ CfgRound :: (state: *OptState, owner: *LirOptOwner, limits: LirLimits) -> bool {
return CfgPass(state, LirReadProgram(*owner.storage), limits)
}
// Turns self calls added to a value into accumulator loops.
AccumulateRound :: (state: *OptState, owner: *LirOptOwner, limits: LirLimits) -> bool {
accumulated := LirAccumulate(*owner.storage, limits, state.remaining)
state.counters.cfg.instructions += accumulated.calls
return SharedPassResult(state, accumulated.problem, accumulated.codec, accumulated.work, accumulated.scratch_bytes)
}
Result :: (state: OptState) -> LirOptResult {
return .{problem = state.problem, diagnostic = state.diagnostic,
counters = state.counters, work = state.used,
@@ -2074,6 +2082,8 @@ LirOptBuild :: (owner: *LirOptOwner, program: LirProgram, limits: LirLimits,
}
owner.valid = false
owner.program = .{version = LirVersion, entry = LirNoId}
// Before inlining, so a self call that becomes a loop is not expanded.
if options.simplify_cfg && !AccumulateRound(*state, owner, limits) { LirOptFree(owner); return Result(state) }
if options.inline_leaf_operations > 0 {
inlined := LirInlineLeaves(LirReadProgram(*owner.storage), options.inline_leaf_operations, state.remaining)
if !Spend(*state, inlined.work) || inlined.limited {
+331
View File
@@ -0,0 +1,331 @@
using IR :: #import "compiler_lowered_ir"
using Codec :: #import "compiler_exec_serial"
using SSA :: #import "compiler_opt_ssa"
using Vectors :: #import "std/vec"
// Recursion modulo an integer accumulator. A function F whose block ends
// `r = F(args); s = x + r; return s` (either operand order) adds x to an
// accumulator and jumps back to its old entry with args instead of calling
// itself; every other `return v` returns `acc + v`. A new entry block
// starts the accumulator at zero. Integer addition wraps, so the sums
// regroup exactly. The recursive call ran last in its block, so effects
// keep their order. The old entry's leading fuel moves to the new entry and
// each jump back charges one step, so a run counts the same steps as
// before. Fib(n-1) + Fib(n-2) makes half as many calls. A function with no
// other return cannot return normally, so it is left alone and runaway
// recursion such as `1 + Forever(depth + 1)` still takes the stack trap.
LirAccumulateResult :: struct {
problem: LirSsaProblem
codec: LirCodecResult
calls: s64
work: s64
scratch_bytes: s64
}
#scope_file
// One rewritten function and the storage its slices borrow.
AddendRebuilt :: struct {
values: Vec(s32)
instructions: Vec(LirInstruction)
edges: Vec(LirEdge)
data: Vec(s32)
blocks: Vec(LirBlock)
function: LirFunction
}
AddendRebuiltFree :: (rebuilt: *AddendRebuilt) {
VecFree(rebuilt.values)
VecFree(rebuilt.instructions)
VecFree(rebuilt.edges)
VecFree(rebuilt.data)
VecFree(rebuilt.blocks)
}
// Whether BLOCK ends in a self call whose result is added to another value
// and returned; ADDEND receives the other value.
AddendCall :: (function: LirFunction, self: s32, block: LirBlock, addend: *s32) -> bool {
n := block.instructions.count
if n < 3 { return false }
ret := block.instructions[n - 1]
add := block.instructions[n - 2]
call := block.instructions[n - 3]
if ret.op != .Return || ret.operands.count != 1 || add.op != .Add || add.operands.count != 2 ||
add.result == LirNoId || add.result != ret.operands[0] || call.op != .Call || call.symbol != self ||
call.result == LirNoId || call.operands.count != function.parameters.count { return false }
left := add.operands[0] == call.result
right := add.operands[1] == call.result
if left == right { return false }
<<addend = ifx left then add.operands[1] else add.operands[0]
return function.values[add.result] == function.result && function.values[call.result] == function.result
}
// The candidate count, or 0 when FUNCTION does not qualify: an integer
// result, its own entry parameters, and a value on every return.
AddendCalls :: (program: LirProgram, function: LirFunction, self: s32, budget: *LirSsaBudget) -> s64 {
if function.external || function.variadic || function.calling != .Portable { return 0 }
if function.result < 0 || function.result >= program.types.count ||
program.types[function.result].kind != .Integer { return 0 }
if function.entry < 0 || function.entry >= function.blocks.count ||
function.blocks[function.entry].parameters.count != function.parameters.count { return 0 }
entry := function.blocks[function.entry]
if entry.instructions.count < 2 || entry.instructions[0].op != .Fuel { return 0 }
found: s64
plain: s64
for block: function.blocks {
if !LirSsaSpend(budget, 1) { return 0 }
if block.instructions.count == 0 { return 0 }
last := block.instructions[block.instructions.count - 1]
for edge: last.edges { if edge.block == function.entry { return 0 } }
addend: s32
if AddendCall(function, self, block, *addend) { found += 1 }
else if last.op == .Return {
if last.operands.count != 1 { return 0 }
plain += 1
}
}
return ifx plain > 0 then found else 0
}
// The zero constant of TYPE, or -1.
AddendZero :: (constants: []LirConstant, type: s32) -> s32 {
for at: 0..constants.count - 1 {
constant := constants[at]
if constant.type == type && constant.bits == 0 && constant.bytes.count == 0 { return cast(s32)at }
}
return -1
}
AddendVersionsFree :: (versions: []AddendRebuilt) {
for at: 0..versions.count - 1 { AddendRebuiltFree(*versions[at]) }
}
AddendRewrite :: (function: LirFunction, self: s32, zero: s32, out: *AddendRebuilt, budget: *LirSsaBudget) -> bool {
blocks := function.blocks.count
values := function.values.count
parameters := function.parameters.count
old_entry := function.entry
// Every existing word, plus the new entry's parameters and jump, the
// accumulator parameter and argument, and two operands per return.
word_total: s64 = 3 * parameters + 4
instruction_total: s64 = 3 + blocks
edge_total: s64 = 1
returns: s64
for block: function.blocks {
word_total += block.parameters.count + 1
for instruction: block.instructions {
word_total += instruction.operands.count + 2
instruction_total += 1
for edge: instruction.edges { word_total += edge.arguments.count + 1; edge_total += 1 }
if instruction.op == .Return { returns += 1 }
}
// A candidate's jump carries the call's arguments and the sum.
word_total += parameters + 1
edge_total += 1
}
value_total := values + 2 + parameters + returns
if !LirSsaSpend(budget, word_total) ||
!LirSsaReserve(budget, values + value_total + word_total, size_of(s32)) ||
!LirSsaReserve(budget, instruction_total + returns, size_of(LirInstruction)) ||
!LirSsaReserve(budget, edge_total, size_of(LirEdge)) ||
!LirSsaReserve(budget, blocks + 1, size_of(LirBlock)) { return false }
numbers: Vec(s32)
defer VecFree(numbers)
if !VecResizeBounded(numbers, values, values) ||
!VecResizeBounded(out.values, value_total, value_total) ||
!VecResizeBounded(out.instructions, instruction_total + returns, instruction_total + returns) ||
!VecResizeBounded(out.edges, edge_total, edge_total) ||
!VecResizeBounded(out.data, word_total, word_total) ||
!VecResizeBounded(out.blocks, blocks + 1, blocks + 1) {
budget.problem = .Allocation
return false
}
// The new entry's parameters are values 0.. as lowering expects; a
// replaced call's result is no longer defined, so it leaves the table.
for block: function.blocks {
addend: s32
if AddendCall(function, self, block, *addend) {
numbers[block.instructions[block.instructions.count - 3].result] = LirNoId - 1
}
}
types := out.values[:]
for p: 0..parameters - 1 { types[p] = function.parameters[p] }
kept := cast(s32)parameters
for v: 0..values - 1 {
if numbers[v] == LirNoId - 1 { continue }
numbers[v] = kept
types[kept] = function.values[v]
kept += 1
}
instructions := out.instructions[:]
edges := out.edges[:]
data := out.data[:]
built := out.blocks[:]
acc := kept
initial := kept + 1
types[acc] = function.result
types[initial] = function.result
next_value := cast(s64)kept + 2
ip: s64
ep: s64
wp: s64
// Block 0: the new entry starts the accumulator at zero.
entry_parameters := wp
for p: 0..parameters - 1 { data[wp] = cast(s32)p; wp += 1 }
entry_start := ip
instructions[ip] = function.blocks[old_entry].instructions[0]
ip += 1
instructions[ip] = .{op = .Constant, result = initial, symbol = zero, origin = function.origin}
ip += 1
arguments := wp
for p: 0..parameters - 1 { data[wp] = cast(s32)p; wp += 1 }
data[wp] = initial; wp += 1
edges[ep] = .{block = old_entry + 1, arguments = data[arguments:wp]}
ep += 1
instructions[ip] = .{op = .Jump, result = LirNoId, edges = edges[ep - 1:ep], symbol = LirNoId, origin = function.origin}
ip += 1
built[0] = .{parameters = data[entry_parameters:entry_parameters + parameters], instructions = instructions[entry_start:ip]}
for b: 0..blocks - 1 {
block := function.blocks[b]
parameter_start := wp
for value: block.parameters { data[wp] = numbers[value]; wp += 1 }
if b == old_entry { data[wp] = acc; wp += 1 }
parameter_count := wp - parameter_start
start := ip
addend: s32
candidate := AddendCall(function, self, block, *addend)
n := block.instructions.count
keep := ifx candidate then n - 3 else n - 1
// The old entry's fuel now runs in the new entry and on each jump back.
skip := ifx b == old_entry then 1 else 0
effect: s32
for i: skip..keep - 1 {
instruction := block.instructions[i]
first := wp
for value: instruction.operands { data[wp] = numbers[value]; wp += 1 }
instruction.operands = data[first:wp]
if instruction.result != LirNoId { instruction.result = numbers[instruction.result] }
if LirEffectful(instruction.op) { effect += 1; instruction.effect = effect }
instructions[ip] = instruction
ip += 1
}
last := block.instructions[n - 1]
if candidate {
// acc + x replaces x + F(args); the jump passes args and the sum.
add := block.instructions[n - 2]
call := block.instructions[n - 3]
first := wp
data[wp] = acc; data[wp + 1] = numbers[addend]; wp += 2
add.operands = data[first:wp]
add.result = numbers[add.result]
instructions[ip] = add
ip += 1
// The step the replaced call charged on entry.
fuel := function.blocks[old_entry].instructions[0]
effect += 1
fuel.effect = effect
fuel.origin = call.origin
instructions[ip] = fuel
ip += 1
arguments = wp
for value: call.operands { data[wp] = numbers[value]; wp += 1 }
data[wp] = add.result; wp += 1
edges[ep] = .{block = old_entry + 1, arguments = data[arguments:wp]}
ep += 1
instructions[ip] = .{op = .Jump, result = LirNoId, edges = edges[ep - 1:ep], symbol = LirNoId, origin = last.origin}
ip += 1
} else if last.op == .Return {
sum := cast(s32)next_value
types[sum] = function.result
next_value += 1
first := wp
data[wp] = acc; data[wp + 1] = numbers[last.operands[0]]; wp += 2
instructions[ip] = .{op = .Add, result = sum, operands = data[first:wp], symbol = LirNoId, origin = last.origin}
ip += 1
first = wp
data[wp] = sum; wp += 1
last.operands = data[first:wp]
instructions[ip] = last
ip += 1
} else {
first := wp
for value: last.operands { data[wp] = numbers[value]; wp += 1 }
last.operands = data[first:wp]
edge_start := ep
for edge: last.edges {
argument_start := wp
for value: edge.arguments { data[wp] = numbers[value]; wp += 1 }
// An edge back to the old entry keeps the current sum.
if edge.block == old_entry { data[wp] = acc; wp += 1 }
edges[ep] = .{block = edge.block + 1, arguments = data[argument_start:wp]}
ep += 1
}
last.edges = edges[edge_start:ep]
instructions[ip] = last
ip += 1
}
built[b + 1] = .{parameters = data[parameter_start:parameter_start + parameter_count],
instructions = instructions[start:ip]}
}
rewritten := function
rewritten.entry = 0
rewritten.values = types[0:next_value]
rewritten.blocks = built
out.function = rewritten
return true
}
#scope_export
LirAccumulate :: (storage: *LirReadOwner, limits: LirLimits, work: s64) -> LirAccumulateResult {
result: LirAccumulateResult
budget := LirSsaBudget.{work = work, bytes = limits.bytes}
held: s64
program := LirReadProgram(storage)
functions: Vec(LirFunction)
constants: Vec(LirConstant)
versions: Vec(AddendRebuilt)
defer VecFree(functions)
defer VecFree(constants)
defer VecFree(versions)
defer AddendVersionsFree(versions[:])
for fi: 0..program.functions.count - 1 {
function := program.functions[fi]
found := AddendCalls(program, function, cast(s32)fi, *budget)
if budget.problem != .None { break }
if found == 0 { continue }
if functions.count == 0 {
if !LirSsaReserve(*budget, program.functions.count + program.constants.count + 1, 112) ||
!VecResizeBounded(functions, program.functions.count, program.functions.count) {
if budget.problem == .None { budget.problem = .Allocation }
break
}
for at: 0..program.functions.count - 1 { functions[at] = program.functions[at] }
for constant: program.constants { VecPush(constants, constant) }
held = budget.reserved
}
budget.reserved = held
zero := AddendZero(constants[:], function.result)
if zero < 0 {
VecPush(constants, LirConstant.{type = function.result})
zero = cast(s32)(constants.count - 1)
}
rebuilt: AddendRebuilt
if !AddendRewrite(function, cast(s32)fi, zero, *rebuilt, *budget) { AddendRebuiltFree(*rebuilt); break }
if budget.reserved > result.scratch_bytes { result.scratch_bytes = budget.reserved }
functions[fi] = rebuilt.function
VecPush(versions, rebuilt)
result.calls += found
}
if budget.reserved > result.scratch_bytes { result.scratch_bytes = budget.reserved }
if budget.problem == .None && result.calls > 0 {
budget.reserved = 0
accumulated := program
accumulated.functions = functions[:]
accumulated.constants = constants[:]
result.codec = LirSsaSerialize(storage, accumulated, limits, *budget)
}
result.problem = budget.problem
result.work = budget.used
return result
}
+2 -16
View File
@@ -429,20 +429,6 @@ CalleesFirst :: (program: LirProgram, order: []s32, budget: *LirSsaBudget) -> bo
return true
}
Serialize :: (storage: *LirReadOwner, program: LirProgram, limits: LirLimits,
budget: *LirSsaBudget) -> LirCodecResult {
empty: []u8
measured := LirWrite(program, empty)
if measured.problem != .None { return measured }
if !LirSsaReserve(budget, measured.size, 1) { return .{} }
encoded: Vec(u8)
defer VecFree(encoded)
if !VecResizeBounded(encoded, measured.size, measured.size) { budget.problem = .Allocation; return .{} }
written := LirWrite(program, encoded[:])
if written.problem != .None { return written }
return LirRead(storage, TextView(encoded[:]), limits)
}
// Whether FUNCTION's blocks form no cycle: every block leaves the
// topological order Kahn's method builds from the entry.
Acyclic :: (function: LirFunction, budget: *LirSsaBudget) -> bool {
@@ -658,7 +644,7 @@ LirInlineCalls :: (storage: *LirReadOwner, limits: LirLimits, work: s64, maximum
budget.reserved = 0
inlined := program
inlined.functions = functions[:]
result.codec = Serialize(storage, inlined, limits, *budget)
result.codec = LirSsaSerialize(storage, inlined, limits, *budget)
if budget.reserved > result.scratch_bytes { result.scratch_bytes = budget.reserved }
}
result.problem = budget.problem
@@ -921,7 +907,7 @@ LirSinkFieldReads :: (storage: *LirReadOwner, limits: LirLimits, work: s64, roun
budget.reserved = 0
sunk_program := program
sunk_program.functions = functions[:]
result.codec = Serialize(storage, sunk_program, limits, *budget)
result.codec = LirSsaSerialize(storage, sunk_program, limits, *budget)
if budget.reserved > result.scratch_bytes { result.scratch_bytes = budget.reserved }
}
result.problem = budget.problem
+1 -15
View File
@@ -243,20 +243,6 @@ RebuildFunction :: (function: LirFunction, functions: s64, header: s32, latch: s
// Serialize once, while every rotated table and the borrowed input still
// exist; only LirRead may replace the owner's storage.
Serialize :: (storage: *LirReadOwner, program: LirProgram, limits: LirLimits,
budget: *LirSsaBudget) -> LirCodecResult {
empty: []u8
measured := LirWrite(program, empty)
if measured.problem != .None { return measured }
if !LirSsaReserve(budget, measured.size, 1) { return .{} }
encoded: Vec(u8)
defer VecFree(encoded)
if !VecResizeBounded(encoded, measured.size, measured.size) { budget.problem = .Allocation; return .{} }
written := LirWrite(program, encoded[:])
if written.problem != .None { return written }
return LirRead(storage, TextView(encoded[:]), limits)
}
#scope_export
// The shared optimizer owns storage and supplies its remaining work budget.
// Each successful rebuild is verified by the codec before replacing it.
@@ -328,7 +314,7 @@ LirRotate :: (storage: *LirReadOwner, limits: LirLimits, work: s64) -> LirRotate
budget.reserved = 0
rotated := program
rotated.functions = functions[:]
result.codec = Serialize(storage, rotated, limits, *budget)
result.codec = LirSsaSerialize(storage, rotated, limits, *budget)
if budget.reserved > result.scratch_bytes { result.scratch_bytes = budget.reserved }
}
result.problem = budget.problem
+17
View File
@@ -1,4 +1,5 @@
using IR :: #import "compiler_lowered_ir"
using Codec :: #import "compiler_exec_serial"
using Vectors :: #import "std/vec"
// A bounded, pruned block-argument repair plan. Definitions are available at
@@ -122,3 +123,19 @@ LirSsaPlanBuild :: (plan: *LirSsaPlan, function: LirFunction, source: s32,
}
return true
}
// Encodes PROGRAM and reads it back into STORAGE, which then owns every
// slice; a pass's rebuilt functions can be freed afterwards.
LirSsaSerialize :: (storage: *LirReadOwner, program: LirProgram, limits: LirLimits,
budget: *LirSsaBudget) -> LirCodecResult {
empty: []u8
measured := LirWrite(program, empty)
if measured.problem != .None { return measured }
if !LirSsaReserve(budget, measured.size, 1) { return .{} }
encoded: Vec(u8)
defer VecFree(encoded)
if !VecResizeBounded(encoded, measured.size, measured.size) { budget.problem = .Allocation; return .{} }
written := LirWrite(program, encoded[:])
if written.problem != .None { return written }
return LirRead(storage, TextView(encoded[:]), limits)
}
+1 -15
View File
@@ -452,20 +452,6 @@ Emit :: (function: LirFunction, work: *Work, threaded: s64, out: *Rebuilt, budge
return merged
}
Serialize :: (storage: *LirReadOwner, program: LirProgram, limits: LirLimits,
budget: *LirSsaBudget) -> LirCodecResult {
empty: []u8
measured := LirWrite(program, empty)
if measured.problem != .None { return measured }
if !LirSsaReserve(budget, measured.size, 1) { return .{} }
encoded: Vec(u8)
defer VecFree(encoded)
if !VecResizeBounded(encoded, measured.size, measured.size) { budget.problem = .Allocation; return .{} }
written := LirWrite(program, encoded[:])
if written.problem != .None { return written }
return LirRead(storage, TextView(encoded[:]), limits)
}
#scope_export
// Jump threading and straight-line merging. An edge into a block that only
// jumps goes to where it jumps; an edge into a block that only branches,
@@ -522,7 +508,7 @@ LirThread :: (storage: *LirReadOwner, limits: LirLimits, work: s64) -> LirThread
budget.reserved = 0
threaded := program
threaded.functions = functions[:]
result.codec = Serialize(storage, threaded, limits, *budget)
result.codec = LirSsaSerialize(storage, threaded, limits, *budget)
}
result.problem = budget.problem
result.work = budget.used
+95
View File
@@ -1039,3 +1039,98 @@ above is unchanged by this register-pressure fix.
AArch64 NEON is a follow-up: reuse the counted-loop plan and scalar epilogue,
add a NEON form/encoder, and run the same differential fixtures on AArch64.
It is outside this SSE2 change.
## Fib and mandelbrot against gcc -O2, instruction by instruction (2026-11-17)
Alpha, standard diagnostic at fa65a3fb, C / in-process ZX native: fib(35)
18.5 / 55.5 ms, mandelbrot(1000) 71.2 / 116.2 ms. Code read from a
`zx2native` ELF of `bench/standard/kernels.zi` (inputs from a global so
nothing folds) at e6f45f0d, against `gcc -O2` of `reference.c` (GCC 14 on
Omega; Alpha has GCC 15, same shape). The in-process runner compiles with
fuel on (`MachineBuild`: `options.fuel = !emit_executable || ...`), so its
code also carries the step checks listed below.
### Fib
GCC: no recursion on the second call at all. `Fib(n-1) + Fib(n-2)` becomes
an accumulator loop (`acc += Fib(n-1); n -= 2` until `n < 2`, then
`acc + n`), and the remaining call is unrolled about five levels deep, so
C makes a small fraction of Ziran's ~30 million calls. That is most of
the 3× gap.
Ziran, per call (unfueled ELF; in-process adds the fuel line):
```
cmp $2,%rdi ; jge L1 ; mov %rdi,%rax ; ret early base case, good
L1: push %rbp ; mov %rsp,%rbp ; sub $0x10,%rsp frame pointer + frame
mov %rbx,-8(%rbp) ; mov %r12,-0x10(%rbp) callee-saved by mov
[in-process: subq $1,fuel(%rip) ; jb trap] memory RMW step check
cmp $2,%rdi ; jge L3 base test again
...base return path...
L3: mov %rdi,%rbx ; jmp L2 second taken branch
L2: lea -1(%rbx),%rax ; mov %rax,%rdi lea straight to rdi
call Fib ; mov %rax,%r12
sub $2,%rbx ; mov %rbx,%rdi ; call Fib lea -2(%rbx),%rdi
add %r12,%rax
mov -8(%rbp),%rbx ; mov -0x10(%rbp),%r12 ; leave ; ret
```
Redundancies C skips, ranked:
1. The second recursive call (no accumulator/tail transformation): about
half of all calls.
2. In-process: a fuel decrement of a memory word per call, and fuel
disables the early base-case return, so every base case builds a frame.
3. The `n < 2` test runs twice on the recursive path after the early return
was cloned; the recursive block sits after the return block, so the path
takes `jge` and then `jmp` back.
4. Frame pointer setup and `leave` in a function with no stack objects;
callee-saved registers stored with `mov` into the frame.
5. Argument copies: `lea` into a temporary then `mov` to `%rdi`.
### Mandelbrot inner loop
GCC (14 instructions, one taken branch, all values in registers, 4.0 kept
in `%xmm7`, the 50-iteration bound counted down):
```
addsd %xmm0,%xmm0 ; subsd %xmm3,%xmm2 ; mulsd %xmm0,%xmm1 ; addsd %xmm5,%xmm2
movapd %xmm2,%xmm0 ; mulsd %xmm2,%xmm2 ; addsd %xmm6,%xmm1 ; movapd %xmm1,%xmm3
mulsd %xmm1,%xmm3 ; movapd %xmm2,%xmm4 ; addsd %xmm3,%xmm4
sub $1,%rax ; je out ; comisd %xmm4,%xmm7 ; jae top
```
Ziran (unfueled; 27 instructions, three taken branches per iteration):
```
H: movsd %xmm1,%xmm6 ; addsd %xmm0,%xmm6 tr+ti
movabs $4.0,%r11 ; movq %r11,%xmm7 constant rebuilt each time
ucomisd %xmm6,%xmm7 ; jae B taken into the body
B: movabs $2.0,%r11 ; movq %r11,%xmm6 constant rebuilt each time
mulsd %xmm2,%xmm6 ; mulsd %xmm3,%xmm6 2.0*zr*zi (GCC: zr+zr)
addsd %xmm5,%xmm6 ; subsd %xmm0,%xmm1 ; addsd %xmm4,%xmm1
movsd %xmm1,%xmm0 ; mulsd %xmm1,%xmm0 ; movsd %xmm6,%xmm2 ; mulsd %xmm6,%xmm2
add $1,%rbx ; cmp $0x32,%rbx ; jl E taken to the edge block
E: movsd %xmm6,%xmm3 ; movsd %xmm2,%xmm15 ; movsd %xmm1,%xmm2
movsd %xmm0,%xmm1 ; movsd %xmm15,%xmm0 ; jmp H five copies, one swap
```
Redundancies C skips, ranked:
1. Loop-carried values are not coalesced: five `movsd` at the back edge,
including a swap through `%xmm15`, in a separate block reached by a
taken branch.
2. Float constants 4.0 and 2.0 are rebuilt from a GPR inside the loop
(`movabs` + `movq`, four instructions per iteration) while eight XMM
registers are free.
3. Layout: the header test jumps forward into the body and the latch jumps
to the edge block, then back: three taken branches against one.
4. `x*2.0` is a multiply by a loaded constant; `x+x` is exact and needs
no constant.
5. In-process: the step check per iteration (`sub $1,%r15 ; jb`) and, with
fuel on, no loop vectorization anywhere.
### Order of work
Fib 1 (accumulator transformation in the optimizer), then mandelbrot 2 and 4
(constants), 1 and 3 (back-edge copies and layout), then the in-process step
checks for unbounded runs, then the fib frame items. Each lands with a
retained test and a matched Alpha A/B.
+181
View File
@@ -0,0 +1,181 @@
using IR :: #import "compiler_lowered_ir"
using Verify :: #import "compiler_lowered_verify"
using Opt :: #import "compiler_opt"
using Exec :: #import "compiler_exec"
#scope_file
// Calls FUNCTION with the one argument VALUE of its parameter type.
Call :: (program: LirProgram, function: s32, value: u64) -> LirExecResult {
plan: LirExecPlan
defer LirExecPlanFree(*plan)
built := LirExecPlanBuild(program, LirDefaultLimits(), *plan)
if built.problem != .None { return built }
instance: LirExecInstance
defer LirExecInstanceClose(*instance)
opened := LirExecInstanceOpen(*plan, LirExecDefaultLimits(), 812, *instance)
if opened.problem != .None { return opened }
arguments := LirExecArgument.[.{type = program.functions[function].parameters[0], bits = value}]
return LirExecCall(*instance, function, arguments[:])
}
FibReference :: (n: s64) -> s64 {
if n < 2 { return n }
a: s64 = 0
b: s64 = 1
for at: 2..n { c := a + b; a = b; b = c }
return b
}
// Self calls left in FUNCTION.
SelfCalls :: (program: LirProgram, function: s32) -> s64 {
count: s64
for block: program.functions[function].blocks {
for instruction: block.instructions {
if instruction.op == .Call && instruction.symbol == function { count += 1 }
}
}
return count
}
Optimize :: (owner: *LirOptOwner, program: LirProgram, inline: bool) -> bool {
options := LirOptDefaultOptions()
if !inline { options.inline_calls = 0; options.inline_leaf_operations = 0 }
optimized := LirOptBuild(owner, program, LirDefaultLimits(), options)
if optimized.problem != .None || !owner.valid {
print("accumulate: optimization problem % pass % function % block % instruction % value %\n",
cast(s32)optimized.problem, cast(s32)optimized.diagnostic.problem, optimized.diagnostic.function,
optimized.diagnostic.block, optimized.diagnostic.instruction, optimized.diagnostic.value)
return false
}
return LirVerify(LirOptProgram(owner), LirDefaultLimits()).problem == .None
}
#scope_export
// fib(n) = n < 2 ? n : fib(n-1) + fib(n-2) keeps one self call and returns
// the same values; double(n) adds its call's result to itself, fsum(x)
// adds floats and forever(d) has no base case, so none of them changes.
AccumulateCases :: () -> s32 {
types := LirType.[.{kind = .Void}, .{kind = .Integer, bits = 64, is_signed = true}, .{kind = .Bool, bits = 1},
.{kind = .Float, bits = 64}]
modules := string.["accumulate"]
constants := LirConstant.[.{type = 1, bits = 2}, .{type = 1, bits = 1}, .{type = 3, bits = 0x3ff0000000000000},
.{type = 3, bits = 0}]
integer := s32.[1]
float := s32.[3]
// fib: b0(v0) tests v0 < 2; b1 returns v0; b2 returns fib(v0-1) + fib(v0-2).
fib_values := s32.[1, 1, 2, 1, 1, 1, 1, 1, 1]
v0 := s32.[0]
less := s32.[0, 1]
flag := s32.[2]
minus_one := s32.[0, 3]
minus_two := s32.[0, 1]
first := s32.[4]
second := s32.[6]
sum := s32.[5, 7]
result := s32.[8]
split := LirEdge.[.{block = 1}, .{block = 2}]
f0 := LirInstruction.[
.{op = .Fuel, result = -1, immediate = 1, symbol = -1, effect = 1, origin = -1},
.{op = .Constant, result = 1, symbol = 0, origin = -1},
.{op = .Less, result = 2, operands = less[:], symbol = -1, origin = -1},
.{op = .Branch, result = -1, operands = flag[:], edges = split[:], symbol = -1, origin = -1}]
f1 := LirInstruction.[.{op = .Return, result = -1, operands = v0[:], symbol = -1, origin = -1}]
f2 := LirInstruction.[
.{op = .Constant, result = 3, symbol = 1, origin = -1},
.{op = .Subtract, result = 4, operands = minus_one[:], symbol = -1, origin = -1},
.{op = .Call, result = 5, operands = first[:], symbol = 0, effect = 1, origin = -1},
.{op = .Subtract, result = 6, operands = minus_two[:], symbol = -1, origin = -1},
.{op = .Call, result = 7, operands = second[:], symbol = 0, effect = 2, origin = -1},
.{op = .Add, result = 8, operands = sum[:], symbol = -1, origin = -1},
.{op = .Return, result = -1, operands = result[:], symbol = -1, origin = -1}]
fib_blocks := LirBlock.[.{parameters = v0[:], instructions = f0[:]}, .{instructions = f1[:]},
.{instructions = f2[:]}]
// double: b0(v0) returns 0 when v0 < 1, else double(v0-1) + double(v0-1) via one call.
double_values := s32.[1, 1, 2, 1, 1, 1, 1]
below := s32.[0, 1]
to_double := LirEdge.[.{block = 1}, .{block = 2}]
decrement := s32.[0, 1]
argument := s32.[3]
twice := s32.[4, 4]
doubled := s32.[5]
zero := s32.[6]
d0 := LirInstruction.[
.{op = .Fuel, result = -1, immediate = 1, symbol = -1, effect = 1, origin = -1},
.{op = .Constant, result = 1, symbol = 1, origin = -1},
.{op = .Less, result = 2, operands = below[:], symbol = -1, origin = -1},
.{op = .Branch, result = -1, operands = flag[:], edges = to_double[:], symbol = -1, origin = -1}]
itself := s32.[0, 0]
d1 := LirInstruction.[.{op = .Subtract, result = 6, operands = itself[:], symbol = -1, origin = -1},
.{op = .Return, result = -1, operands = zero[:], symbol = -1, origin = -1}]
d2 := LirInstruction.[
.{op = .Subtract, result = 3, operands = decrement[:], symbol = -1, origin = -1},
.{op = .Call, result = 4, operands = argument[:], symbol = 1, effect = 1, origin = -1},
.{op = .Add, result = 5, operands = twice[:], symbol = -1, origin = -1},
.{op = .Return, result = -1, operands = doubled[:], symbol = -1, origin = -1}]
double_blocks := LirBlock.[.{parameters = v0[:], instructions = d0[:]}, .{instructions = d1[:]},
.{instructions = d2[:]}]
// fsum: b0(v0) returns 0.0 when v0 < 1.0, else fsum(v0 - 1.0) + 1.0.
fsum_values := s32.[3, 3, 2, 3, 3, 3, 3]
s0 := LirInstruction.[
.{op = .Fuel, result = -1, immediate = 1, symbol = -1, effect = 1, origin = -1},
.{op = .Constant, result = 1, symbol = 2, origin = -1},
.{op = .Less, result = 2, operands = below[:], symbol = -1, origin = -1},
.{op = .Branch, result = -1, operands = flag[:], edges = to_double[:], symbol = -1, origin = -1}]
s1 := LirInstruction.[.{op = .Constant, result = 6, symbol = 3, origin = -1},
.{op = .Return, result = -1, operands = zero[:], symbol = -1, origin = -1}]
plus_one := s32.[4, 1]
s2 := LirInstruction.[
.{op = .Subtract, result = 3, operands = decrement[:], symbol = -1, origin = -1},
.{op = .Call, result = 4, operands = argument[:], symbol = 2, effect = 1, origin = -1},
.{op = .Add, result = 5, operands = plus_one[:], symbol = -1, origin = -1},
.{op = .Return, result = -1, operands = doubled[:], symbol = -1, origin = -1}]
fsum_blocks := LirBlock.[.{parameters = v0[:], instructions = s0[:]}, .{instructions = s1[:]},
.{instructions = s2[:]}]
// forever: b0(v0) returns 1 + forever(v0 + 1) and has no other return.
forever_values := s32.[1, 1, 1, 1, 1]
step := s32.[0, 1]
deeper := s32.[2]
plus := s32.[1, 3]
total := s32.[4]
r0 := LirInstruction.[
.{op = .Fuel, result = -1, immediate = 1, symbol = -1, effect = 1, origin = -1},
.{op = .Constant, result = 1, symbol = 1, origin = -1},
.{op = .Add, result = 2, operands = step[:], symbol = -1, origin = -1},
.{op = .Call, result = 3, operands = deeper[:], symbol = 3, effect = 2, origin = -1},
.{op = .Add, result = 4, operands = plus[:], symbol = -1, origin = -1},
.{op = .Return, result = -1, operands = total[:], symbol = -1, origin = -1}]
forever_blocks := LirBlock.[.{parameters = v0[:], instructions = r0[:]}]
functions := LirFunction.[
.{module = 0, name = "fib", parameters = integer[:], result = 1, values = fib_values[:],
blocks = fib_blocks[:], entry = 0, origin = -1},
.{module = 0, name = "double", parameters = integer[:], result = 1, values = double_values[:],
blocks = double_blocks[:], entry = 0, origin = -1},
.{module = 0, name = "fsum", parameters = float[:], result = 3, values = fsum_values[:],
blocks = fsum_blocks[:], entry = 0, origin = -1},
.{module = 0, name = "forever", parameters = integer[:], result = 1, values = forever_values[:],
blocks = forever_blocks[:], entry = 0, origin = -1}]
program := LirProgram.{version = LirVersion, modules = modules[:], types = types[:],
constants = constants[:], functions = functions[:], entry = LirNoId}
if LirVerify(program, LirDefaultLimits()).problem != .None { return 81 }
for inline: 0..1 {
owner: LirOptOwner
defer LirOptFree(*owner)
if !Optimize(*owner, program, inline == 1) { return cast(s32)(82 + inline) }
output := LirOptProgram(*owner)
if SelfCalls(output, 0) != 1 { return 84 }
if SelfCalls(output, 1) != 1 || SelfCalls(output, 2) != 1 { return 85 }
// With no base case it would only loop; runaway recursion keeps its stack trap.
if SelfCalls(output, 3) != 1 || output.functions[3].blocks.count != 1 { return 89 }
for n: cast(s64)0..20 {
called := Call(output, 0, cast(u64)n)
if called.problem != .None || called.value.bits != cast(u64)FibReference(n) { return 86 }
}
for n: cast(s64)0..5 {
called := Call(output, 1, cast(u64)n)
if called.problem != .None || called.value.bits != 0 { return 87 }
}
called := Call(output, 2, 0x4014000000000000)
if called.problem != .None || called.value.bits != 0x4014000000000000 { return 88 }
}
return 0
}
+3
View File
@@ -15,6 +15,7 @@ using FloatFolds :: #import "compiler_opt_float_cases"
using LoopLayout :: #import "compiler_opt_layout_cases"
using LicmCases :: #import "compiler_opt_licm_cases"
using InductionCases :: #import "compiler_opt_induction_cases"
using Accumulation :: #import "compiler_opt_accumulate_cases"
OptInstruction :: (op: LirOp, result: s32, operands: []s32,
symbol: s32 = -1, origin: s32 = 0) -> LirInstruction {
@@ -255,6 +256,8 @@ main :: (argc: s32, argv: **u8) -> s32 {
if themes != 0 { print("theme read case % failed\n", themes); return 1 }
threads := ThreadCases()
if threads != 0 { print("thread case % failed\n", threads); return 1 }
accumulated := AccumulateCases()
if accumulated != 0 { print("accumulate case % failed\n", accumulated); return 1 }
common := CseCases()
if common != 0 { print("cse case % failed\n", common); return 1 }
budget_work: s64