by assbuttbuttass · 1y ago · 0 comments
But CPS isn't really the state of the art for functional compilers anymore. It's complex for a human to read and hard to optimize. Something like A-normal form is much easier to work with for a compiler intermediate representation
This isn’t identical to floating the call to E inside the “if”, obviously, but would have (within predictable boundaries) the same performance. If this code went through LLVM to produce machine code I suspect it would wind up identical as LLVM will likely rewrite the duplicated call to be outside the “if”.
Let's say E[h] is "if h == 1 then 2 else 3", a is 1, and b is 2. Then before:
if (if x then 1 else 2) == 1 then 2 else 3
After:
if x then (if 1 == 1 then 2 else 3) else (if 2 == 1 then 2 else 3)
which trivially simplifies to if x then 2 else 3
Your proposed rewrite is "let a0 = if x then 1 else 2 in if a0 == 1 then 2 else 3" which is not a simplification at all - it makes the expression longer and actually introduces a variable indirection, making the expression harder to analyze. The call will require some sort of non-local analysis to pierce through the variable and do the duplication and elimination.
if x then
let a0 = a in E a0
else
let a0 = b in E a0
If a and b are simple variables or constants the new “let”s will be eliminated by ANF.What happens to E isn’t so straightforward. In your example, though, it’s a small expression tree and would just be duplicated inline with the same obvious constant reductions available.
If it’s ‘large’ (heuristically) it might instead be assigned to a “let” binding outside the “if”, to avoid duplicating a large block of code.
CPS should be making that same determination on E.
edit: it looks like there's distinct Core join points now, never mind!