Is this a compilation optimization bug ?

209 views
Skip to first unread message

iori yamada

unread,
Jun 28, 2022, 8:24:28 AM6/28/22
to golang-nuts
Running the code in the link below times out, is this a bug?
Looking at the assembly, it seems that the instructions corresponding to the if statement have been removed due to optimization.

https://go.dev/play/p/CZX4mbyrp37

The following is a description of how I thought it was a bug.

In the first loop, the value of i is 9223372036854775807 (the maximum value of type int), which is incremented and overflows. Then it becomes -9223372036854775808 (minimum value of type int) and I thought the condition in the if statement exits from the true neighbor loop.

I couldn't figure out where the bug was happening, so I decided to look at an assembly of the same code as above, built it locally, and checked it with objdump.
Perhaps, the CMP instruction that compares the conditions of the if statement has been removed due to optimization.

```
...
TEXT main.main(SB) Path/main.go
  main.go:3 0x100051550 92f00000 MOVD $9223372036854775807, R0
  main.go:4 0x100051554 14000002 JMP 2(PC)
  main.go:4 0x100051558 91000400 ADD $1, R0, R0
  main.go:4 0x10005155c 92f0001b MOVD $9223372036854775807, R27
  main.go:4 0x100051560 eb1b001f CMP R27, R0
  main.go:4 0x100051564 54ffffad BLE -3(PC)
  main.go:9 0x100051568 d65f03c0 RET
  main.go:9 0x10005156c 00000000 ?
```

So I compiled it without optimization (go build -gcflags '-N -l') and the program terminated immediately as intended.

I may have misunderstood something, may I ask anyone to check once?

Dan Kortschak

unread,
Jun 28, 2022, 8:47:53 AM6/28/22
to golan...@googlegroups.com
Yes, I see the same behaviour when I run this locally (also tried with
an old version go1.14.9).

Also, the assembly generated at godbolt shows that no code is generated
for the terminating branch  https://godbolt.org/z/9jW1GaKfv unless
optimisation is turned off https://godbolt.org/z/o7o6x3bzd.

Dan

Ian Lance Taylor

unread,
Jun 28, 2022, 12:40:56 PM6/28/22
to Dan Kortschak, golan...@googlegroups.com
Interesting. Looks like Go 1.10 got this right, but 1.11 and higher
go into an endless loop. gccgo gets it right.

Please open an issue. Thanks.

Ian

Dan Kortschak

unread,
Jun 29, 2022, 6:09:28 AM6/29/22
to golan...@googlegroups.com
On Tue, 2022-06-28 at 09:40 -0700, Ian Lance Taylor wrote:
> Please open an issue.  Thanks.

Filed https://go.dev/issue/53600.

Dan

Reply all
Reply to author
Forward
0 new messages