Keep float constants in registers through call-free loops; x*2.0 is x+x

LICM leaves standalone constants at their uses, which suits integers: x86
takes them as immediates. A float constant has none: each use rebuilt it
with movabs and movq inside the loop. In a loop with no call, which would
clobber every XMM register, a float constant now moves to the preheader
and stays in a register. Mandelbrot's inner loop no longer rebuilds 4.0
and 2.0 on every iteration.

Constant folding rewrites a float multiply by 2.0 as an add of the other
operand to itself. x+x is exactly x*2.0 for every input, signed zeros,
infinities and NaNs included, and needs no constant; GCC emits the same
addsd for mandelbrot's 2.0*zr*zi.

Retained cases: a call-free float loop whose 1.5 moves to the preheader
while its integer constants stay (compiler_opt_licm_cases), and x*2.0
becoming x+x with the same results for 1.5, -0.0, infinity, a NaN and the
smallest subnormal (compiler_opt_float_cases).
This commit is contained in:
waozi committed 2026-11-17 21:39:48 -03:00
1 parent 45b74b4e31
commit 96ce8d50d6
6 files changed
+194 -7

No files matched your search

+1
View File
@@ -2,6 +2,7 @@
## [Unreleased]
- In a loop without calls, a float constant moves out of the loop and stays in a register instead of being rebuilt from a general register on every use, and `x * 2.0` becomes `x + x` (exact for every value). Mandelbrot's inner loop no longer rebuilds 4.0 and 2.0 per iteration.
- 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.
+26
View File
@@ -583,6 +583,20 @@ FoldInstruction :: (program: LirProgram, function: LirFunction,
return .{known = true, type = result_type_id, bits = bits & Mask(result_type.bits)}
}
// Which operand of a float multiply is the constant 2.0, or -1.
DoubledOperand :: (program: LirProgram, function: LirFunction, instruction: LirInstruction,
facts: []ConstantFact) -> s64 {
if instruction.op != .Multiply || instruction.operands.count != 2 || instruction.result < 0 { return -1 }
type := program.types[function.values[instruction.result]]
if type.kind != .Float || type.bits != 64 && type.bits != 32 { return -1 }
two: u64 = ifx type.bits == 64 then 0x4000000000000000 else 0x40000000
for at: 0..1 {
fact := facts[instruction.operands[at]]
if fact.known && fact.bits == two && !facts[instruction.operands[1 - at]].known { return at }
}
return -1
}
FoldPass :: (state: *OptState, owner: *LirOptOwner, limits: LirLimits,
options: LirOptOptions) -> bool {
program := LirReadProgram(*owner.storage)
@@ -712,6 +726,18 @@ FoldPass :: (state: *OptState, owner: *LirOptOwner, limits: LirLimits,
}
continue
}
doubled := DoubledOperand(program, function, instruction, facts[:function.values.count])
if doubled >= 0 {
// x*2.0 is exactly x+x, NaN, infinities and signed
// zeros included, and needs no constant.
instruction.operands[doubled] = instruction.operands[1 - doubled]
instruction.op = .Add
block.instructions[instruction_index] = instruction
changed += 1
function_changed += 1
total += 1
continue
}
folded := FoldInstruction(program, function, instruction, facts[:function.values.count])
if !folded.known { continue }
if constant_count >= constants.count { return Fail(state, .Limit) }
+25
View File
@@ -13,6 +13,19 @@ Integer :: (program: LirProgram, type: s32) -> bool {
return kind == .Integer || kind == .Bool
}
// Whether a loop member block calls anything, which clobbers every
// caller-saved register a hoisted value could stay in.
LoopCalls :: (function: LirFunction, plan: *LirLoopPlan) -> bool {
for block, b: function.blocks {
if plan.members[b] == 0 { continue }
for instruction: block.instructions {
op := instruction.op
if op == .Call || op == .CallIndirect || op == .HostCall { return true }
}
}
return false
}
// These operations are total: executing one on a zero-trip path cannot
// introduce a trap, memory access, allocation or observable effect. In
// particular, division, shifts, float conversions and addresses derived
@@ -65,6 +78,18 @@ Select :: (program: LirProgram, function: LirFunction, plan: *LirLoopPlan,
if !LirSsaSpend(budget, 1) { return -1 }
if hoisted[at].operands.count > 0 { selected[hoisted[at].result] = 2 }
}
// A float constant has no immediate form on x86-64: each use rebuilds
// it from a general register. In a loop without calls it stays in a
// register across iterations instead.
if !LoopCalls(function, plan) {
if !LirSsaSpend(budget, count) { return -1 }
for at: 0..count - 1 {
instruction := hoisted[at]
if instruction.op == .Constant && program.types[function.values[instruction.result]].kind == .Float {
selected[instruction.result] = 2
}
}
}
reverse := count
while reverse > 0 {
reverse -= 1
+16 -5
View File
@@ -1128,9 +1128,20 @@ Redundancies C skips, ranked:
5. In-process: the step check per iteration (`sub $1,%r15 ; jb`) and, with
fuel on, no loop vectorization anywhere.
### Order of work
### Order of work and status
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.
1. Fib 1, done: `compiler_opt_accumulate.zi` turns `F(a) + F(b)` into an
accumulator loop (functions with a base case only, so runaway recursion
keeps its stack trap). Alpha standard-ab, 5 shuffled rounds, C / before /
after µs: fib 18,779 / 54,539 / 44,612 (-18%); the other ten workloads
within noise. Calls halve, but the loop still has a back-edge copy
(`mov %rax,%r12` in its own block, two jumps), the base case now always
builds a frame, and GCC also unrolls the remaining recursion.
2. Mandelbrot 2 and 4, in review: float constants stay in registers through
call-free loops, and `x*2.0` is `x+x`. The inner loop has no constant
rebuilds left.
3. Next: back-edge copies (mandelbrot's five `movsd` with a swap, fib's
accumulator copy): coalesce a loop-carried value's new definition with
its block parameter's register when the old value dies there.
4. Then layout (one taken branch per iteration), the in-process step checks
for unbounded runs, and the fib frame items.
+58 -1
View File
@@ -1,5 +1,6 @@
using IR :: #import "compiler_lowered_ir"
using Opt :: #import "compiler_opt"
using Exec :: #import "compiler_exec"
#scope_file
@@ -33,6 +34,60 @@ Table :: () -> [28]Vector {
.{3, 0x3f800000, 0xbf800000, true}]
}
// double(x) = x * 2.0 at INPUT, run by the portable engine.
Doubled :: (program: LirProgram, input: 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(), 813, *instance)
if opened.problem != .None { return opened }
arguments := LirExecArgument.[.{type = 0, bits = input}]
return LirExecCall(*instance, 0, arguments[:])
}
// x * 2.0 becomes x + x: the same value for every input, signed zeros,
// infinities and NaNs included, without the constant.
DoublingCase :: () -> s32 {
types := LirType.[.{kind = .Float, bits = 64}]
constants := LirConstant.[.{type = 0, bits = 0x4000000000000000}]
modules := string.["optimizer"]
parameter := s32.[0]
values := s32.[0, 0, 0]
product := s32.[0, 1]
result := s32.[2]
body := LirInstruction.[.{op = .Constant, result = 1, symbol = 0, origin = -1},
.{op = .Multiply, result = 2, operands = product[:], symbol = -1, origin = -1},
.{op = .Return, result = -1, operands = result[:], symbol = -1, origin = -1}]
blocks := LirBlock.[.{parameters = parameter[:], instructions = body[:]}]
functions := LirFunction.[.{module = 0, name = "double", parameters = parameter[:], result = 0,
values = values[:], blocks = 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 11 }
owner: LirOptOwner
defer LirOptFree(*owner)
built := LirOptBuild(*owner, program, LirDefaultLimits(), LirOptDefaultOptions())
if built.problem != .None || !owner.valid { return 12 }
optimized := LirOptProgram(*owner)
if LirVerify(optimized, LirDefaultLimits()).problem != .None { return 13 }
added := false
for instruction: optimized.functions[0].blocks[0].instructions {
if instruction.op == .Multiply || instruction.op == .Constant { return 14 }
if instruction.op == .Add && instruction.operands[0] == instruction.operands[1] { added = true }
}
if !added { return 15 }
inputs := u64.[0x3ff8000000000000, 0x8000000000000000, 0x7ff0000000000000, 0x7ff8000000000001, 0x0000000000000001]
for input: inputs {
x := Doubled(program, input)
y := Doubled(optimized, input)
if x.problem != .None || y.problem != .None || x.value.bits != y.value.bits { return 16 }
}
return 0
}
#scope_export
// One function per vector: a constant, the operation and a return.
@@ -95,6 +150,8 @@ OptFloatCases :: () -> s32 {
}
}
LirOptFree(*owner)
print("compiler optimizer: float conversions and negations fold to the hardware's patterns, NaNs stay\n")
doubling := DoublingCase()
if doubling != 0 { print("float doubling case % failed\n", doubling); return doubling }
print("compiler optimizer: float conversions and negations fold to the hardware's patterns, NaNs stay, x*2.0 is x+x\n")
return 0
}
+68 -1
View File
@@ -107,14 +107,81 @@ Fixture :: (iterations: s64, trapping: bool) -> s32 {
return 0
}
// A loop with no call adds the float constant 1.5 each iteration: the
// constant moves to the preheader, where it stays in a register, while the
// integer constants stay at their uses. The sum is unchanged.
FloatConstantCase :: () -> s32 {
types := LirType.[.{kind = .Void}, .{kind = .Integer, bits = 64, is_signed = true}, .{kind = .Bool, bits = 1},
.{kind = .Float, bits = 64}]
constants := LirConstant.[.{type = 1, bits = 0}, .{type = 1, bits = 1}, .{type = 1, bits = 5},
.{type = 3, bits = 0x3ff8000000000000}, .{type = 3, bits = 0}]
modules := string.["licm"]
values := s32.[1, 3, 1, 3, 1, 2, 3, 3, 1, 1]
start := s32.[0, 1]
parameters := s32.[2, 3]
less := s32.[2, 4]
flag := s32.[5]
grow := s32.[3, 6]
step := s32.[2, 8]
next := s32.[9, 7]
sum := s32.[3]
to_header := LirEdge.[.{block = 1, arguments = start[:]}]
split := LirEdge.[.{block = 2}, .{block = 3}]
back := LirEdge.[.{block = 1, arguments = next[:]}]
entry := LirInstruction.[.{op = .Constant, result = 0, symbol = 0, origin = -1}, .{op = .Constant, result = 1, symbol = 4, origin = -1},
.{op = .Jump, result = -1, symbol = -1, edges = to_header[:], origin = -1}]
header := LirInstruction.[.{op = .Fuel, result = -1, symbol = -1, immediate = 1, effect = 1, origin = -1},
.{op = .Constant, result = 4, symbol = 2, origin = -1}, .{op = .Less, result = 5, symbol = -1, operands = less[:], origin = -1},
.{op = .Branch, result = -1, symbol = -1, operands = flag[:], edges = split[:], origin = -1}]
body := LirInstruction.[.{op = .Constant, result = 6, symbol = 3, origin = -1},
.{op = .Add, result = 7, symbol = -1, operands = grow[:], origin = -1}, .{op = .Constant, result = 8, symbol = 1, origin = -1},
.{op = .Add, result = 9, symbol = -1, operands = step[:], origin = -1},
.{op = .Jump, result = -1, symbol = -1, edges = back[:], origin = -1}]
exit := LirInstruction.[.{op = .Return, result = -1, symbol = -1, operands = sum[:], origin = -1}]
blocks := LirBlock.[.{instructions = entry[:]}, .{parameters = parameters[:], instructions = header[:]},
.{instructions = body[:]}, .{instructions = exit[:]}]
functions := LirFunction.[.{module = 0, name = "float_sum", result = 3, values = values[:], blocks = blocks[:],
entry = 0, origin = -1}]
program := LirProgram.{version = LirVersion, modules = modules[:], types = types[:],
constants = constants[:], functions = functions[:], entry = 0}
if LirVerify(program, LirDefaultLimits()).problem != .None { return 21 }
before := Execute(program)
if before.problem != .None || before.value.bits != 0x401e000000000000 { return 22 }
empty: []u8
measured := LirWrite(program, empty)
encoded: Vec(u8)
defer VecFree(encoded)
if measured.problem != .None || !VecResize(encoded, measured.size) || LirWrite(program, encoded[:]).problem != .None { return 23 }
owner: LirReadOwner
defer LirReadFree(*owner)
if LirRead(*owner, TextView(encoded[:]), LirDefaultLimits()).problem != .None { return 24 }
moved := LirLicm(*owner, LirDefaultLimits(), 100000)
if moved.problem != .None || moved.codec.problem != .None || moved.instructions != 1 { return 25 }
output := LirReadProgram(*owner)
if LirVerify(output, LirDefaultLimits()).problem != .None { return 26 }
hoisted := false
for instruction: output.functions[0].blocks[0].instructions { if instruction.result == 6 { hoisted = true } }
kept := false
for instruction: output.functions[0].blocks[2].instructions {
if instruction.result == 6 { return 27 }
if instruction.result == 8 { kept = true }
}
if !hoisted || !kept { return 28 }
after := Execute(output)
if after.problem != .None || after.value.bits != before.value.bits { return 29 }
return 0
}
#scope_export
OptLicmCases :: () -> s32 {
float_constant := FloatConstantCase()
if float_constant != 0 { print("LICM float constant case % failed\n", float_constant); return float_constant }
for iterations: cast(s64)0..7 {
for mode: 0..1 {
result := Fixture(iterations, mode == 1)
if result != 0 { print("LICM case % iterations % trap % failed\n", result, iterations, mode); return result }
}
}
print("compiler optimizer: invariant chains, zero/many iterations, traps, fuel and budgets passed\n")
print("compiler optimizer: invariant chains, float constants, zero/many iterations, traps, fuel and budgets passed\n")
return 0
}