Consider this program:
package p
func f(x []int, j int) int {
if x[j] != 0 {
return 1
}
if j > 0 && x[j-1] != 0 {
return 1
}
return 0
}
The bounds check for x[j-1] can be eliminated: at that point, x[j] did not panic, so j < len(x), and the if statement has also tested j > 0, so 0 <= j-1 < len(x).
The compiler does eliminate this check:
$ go tool compile -S x.go |grep panicindex
0x006e 00110 (x.go:4) CALL runtime.panicindex(SB)
rel 111+4 t=8 runtime.panicindex+0
$
But if I change j to be int32 then the check is not eliminated:
package p
func f(x []int, j int32) int {
if x[j] != 0 {
return 1
}
if j > 0 && x[j-1] != 0 {
return 1
}
return 0
}
$ go tool compile -S x.go |grep panicindex
0x0078 00120 (x.go:7) CALL runtime.panicindex(SB)
0x007f 00127 (x.go:4) CALL runtime.panicindex(SB)
rel 121+4 t=8 runtime.panicindex+0
rel 128+4 t=8 runtime.panicindex+0
$
Is this necessary? /cc @aclements
Consider this program:
The bounds check for x[j-1] can be eliminated: at that point, x[j] did not panic, so j < len(x), and the if statement has also tested j > 0, so 0 <= j-1 < len(x).
The compiler does eliminate this check:
But if I change j to be int32 then the check is not eliminated:
Is this necessary? /cc @aclements