You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
cmd/compile: adding panic to a never taken branch of an if inside a loop significantly speeds it up by removing knots in the CFG and marking that branch cold #70030
Ran this benchmark:
( I think I can't post benchmarks on go.dev/play)
package bryan
import (
"testing"
)
func toLower(s string, a []byte) []byte {
var buf []byte
for i := 0; i < len(s); i++ {
c := s[i]
if 'A' <= c && c <= 'Z' {
if buf == nil {
if cap(a) > len(s) {
buf = a[:len(s)]
copy(buf, s)
//panic("copy") // Goes faster with this line uncommented.
} else {
buf = []byte(s)
}
}
buf[i] = c + 'a' - 'A'
}
}
return buf
}
func BenchmarkToLower(b *testing.B) {
inputs := make([]string, 10)
for i := range inputs {
chars := "abcdefghijklmnopqrstuvwxyz"
// Swap the alphabet to make alternatives.
inputs[i] = chars[i%len(chars):] + chars[:i%len(chars)]
}
b.ResetTimer()
for n := 0; n < b.N; n++ {
var a [256]byte
toLower(inputs[n%len(inputs)], a[:])
}
}
What did you see happen?
With the panic it takes 25ns per op, and without it takes 45ns. (Panic is never executed)
According to the profiler, it's calling copy, which it shouldn't do. Hence I added a panic to see how it was called, and then it went faster.
What did you expect to see?
It shouldn't call copy. It shouldn't go faster if I add a redundant panic.
It shouldn't call copy. It shouldn't go faster if I add a redundant panic.
It is easy to assume that code that is never ran does not affect performance, code exists create side effects which could be optimized at runtime but a purely static "naive" compiler like go's one can't see that.
As a caricature example if you have something like this:
varalwaysFalseboolvarleak*intfuncf(x*int) int {
ifalwaysFalse {
leak=x
}
return*x
}
the go compiler will heap allocate x when it is passed in, while it could stack allocate it if you did const alwaysFalse = false.
For your function, without the panic it needs to handle cases where calling copy destroyed the values in the registers and they need to be restored. With the panic, that branch of code never goes back to loop, breaking the control flow graph and simplifying the compiler's job.
Altho []byte() calls runtime.stringtoslicebyte which also have this effect so the different aint that drastic.
More importantly the compiler assumes panics are bad, and treat them as cold, the panic is placed after the loop in memory, while the first one interweave the two clauses of the if, experimentally this has the biggest effect, manually taking the assembly for without panic and moving the never taken branch at the bottom of the funtion make it go* from 25ns to 20ns (while the compiler's with panic is 17ns but is significantly shorter).
* on my computer with the winds blowing 10km/h South-SouthEast
Tl;Dr
Adding panic to a never taken branch of an if inside a loop improves the loop layout by moving the never taken branch away from the loop and significantly reducing codesize by removing the need to restore registers after a runtime.memmove call.
I have multiple ideas on how to improve this, like interprocedural register allocation or using PGO to annotate cold branches but neither is particularly easy nor fast to implement, and have downsides so I don't know how to make this issue actionable.
changed the title [-]Benchmark goes faster if I add a panic.[/-][+]cmd/compile: adding panic to a never taken branch of an `if` inside a loop significantly speeds it up by removing knots in the CFG and marking that branch cold[/+]on Oct 24, 2024
I'm not sure I understand the question or where the profiler is, when I run your benchmark the branch does not run otherwise it would call panic which would blow up loudly. The benchmark does not blow up loudly so the branch does not run.
The compiler knows that control flow never continues past a panic call. That avoids the compiler needing to do the merge of control flow at line 19.
I believe that accounts for the difference in time.
Note the code being jumped around (as @Jorropo says, in the panic case that code gets pushed to the end) and the additional mov instructions to get values back into the right registers for the merge. (Ideally regalloc should be better here, but nothing is perfect.)
According to my experiments 17ns vs 25ns, 5ns comes from improving the loop layout by marking the branch cold. And the remaining 3ns are unexplained but are likely the extra merge you pointed out as there isn't much other differences.
Activity
gabyhelp commentedon Oct 24, 2024
Related Issues and Documentation
(Emoji vote if this was helpful or unhelpful; more detailed feedback welcome in this discussion.)
Jorropo commentedon Oct 24, 2024
It is easy to assume that code that is never ran does not affect performance, code exists create side effects which could be optimized at runtime but a purely static "naive" compiler like go's one can't see that.
As a caricature example if you have something like this:
the go compiler will heap allocate
xwhen it is passed in, while it could stack allocate it if you didconst alwaysFalse = false.For your function, without the panic it needs to handle cases where calling
copydestroyed the values in the registers and they need to be restored. With the panic, that branch of code never goes back to loop, breaking the control flow graph and simplifying the compiler's job.Altho
[]byte()callsruntime.stringtoslicebytewhich also have this effect so the different aint that drastic.More importantly the compiler assumes
panics are bad, and treat them as cold, the panic is placed after the loop in memory, while the first one interweave the two clauses of the if, experimentally this has the biggest effect, manually taking the assembly for without panic and moving the never taken branch at the bottom of the funtion make it go* from 25ns to 20ns (while the compiler's with panic is 17ns but is significantly shorter).* on my computer with the winds blowing 10km/h South-SouthEast
Tl;Dr
Adding panic to a never taken branch of an
ifinside a loop improves the loop layout by moving the never taken branch away from the loop and significantly reducing codesize by removing the need to restore registers after aruntime.memmovecall.I have multiple ideas on how to improve this, like interprocedural register allocation or using PGO to annotate cold branches but neither is particularly easy nor fast to implement, and have downsides so I don't know how to make this issue actionable.
cc @golang/compiler
[-]Benchmark goes faster if I add a panic.[/-][+]cmd/compile: adding panic to a never taken branch of an `if` inside a loop significantly speeds it up by removing knots in the CFG and marking that branch cold[/+]bboreham commentedon Oct 24, 2024
But it did run, according to the profiler.
bboreham commentedon Oct 24, 2024
Maybe I misunderstood. Are you saying the time is attributed to that line, which is still not running?
Jorropo commentedon Oct 24, 2024
I'm not sure I understand the question or where the profiler is, when I run your benchmark the branch does not run otherwise it would call panic which would blow up loudly. The benchmark does not blow up loudly so the branch does not run.
randall77 commentedon Oct 24, 2024
The compiler knows that control flow never continues past a
paniccall. That avoids the compiler needing to do the merge of control flow at line 19.I believe that accounts for the difference in time.
Inner loop with
panic:inner loop without
panic:Note the code being jumped around (as @Jorropo says, in the
paniccase that code gets pushed to the end) and the additionalmovinstructions to get values back into the right registers for the merge. (Ideally regalloc should be better here, but nothing is perfect.)Jorropo commentedon Oct 24, 2024
According to my experiments 17ns vs 25ns, 5ns comes from improving the loop layout by marking the branch cold. And the remaining 3ns are unexplained but are likely the extra merge you pointed out as there isn't much other differences.