Skip to content

cmd/compile: Loop not being optimized even though it can be evaluated at compile time #53952

@boriskrisanov

Description

@boriskrisanov

What version of Go are you using (go version)?

$ go version
go version go1.18.4 windows/amd64

Does this issue reproduce with the latest release?

Yes

What operating system and processor architecture are you using (go env)?

go env Output
$ go env
set GO111MODULE=auto
set GOARCH=amd64
set GOBIN=
set GOCACHE=C:\Users\boris\AppData\Local\go-build
set GOENV=C:\Users\boris\AppData\Roaming\go\env
set GOEXE=.exe
set GOEXPERIMENT=
set GOFLAGS=
set GOHOSTARCH=amd64
set GOHOSTOS=windows
set GOINSECURE=
set GOMODCACHE=C:\Users\boris\go\pkg\mod
set GONOPROXY=
set GONOSUMDB=
set GOOS=windows
set GOPATH=C:\Users\boris\go
set GOPRIVATE=
set GOPROXY=https://proxy.golang.org,direct
set GOROOT=C:\Program Files\Go
set GOSUMDB=sum.golang.org
set GOTMPDIR=
set GOTOOLDIR=C:\Program Files\Go\pkg\tool\windows_amd64
set GOVCS=
set GOVERSION=go1.18.4
set GCCGO=gccgo
set GOAMD64=v1
set AR=ar
set CC=gcc
set CXX=g++
set CGO_ENABLED=1
set GOMOD=
set GOWORK=
set CGO_CFLAGS=-g -O2
set CGO_CPPFLAGS=
set CGO_CXXFLAGS=-g -O2
set CGO_FFLAGS=-g -O2
set CGO_LDFLAGS=-g -O2
set PKG_CONFIG=pkg-config
set GOGCCFLAGS=-m64 -mthreads -fno-caret-diagnostics -Qunused-arguments -fmessage-length=0 -fdebug-prefix-map=C:\Users\boris\AppData\Local\Temp\go-build1984047059=/tmp/go-build -gno-record-gcc-switches
package sum

func Sum() int {
	sum := 0
	for i := 0; i < 64; i++ {
		sum += i
	}
	return sum
}

Compiling the code above outputs the following assembly code for the Sum function:

0x0000 00000 (main.go:3)	XORL	AX, AX
0x0002 00002 (main.go:3)	XORL	CX, CX
0x0004 00004 (main.go:5)	JMP	16
0x0006 00006 (main.go:5)	LEAQ	1(AX), DX
0x000a 00010 (main.go:6)	ADDQ	AX, CX
0x000d 00013 (main.go:5)	MOVQ	DX, AX
0x0010 00016 (main.go:5)	CMPQ	AX, $64
0x0014 00020 (main.go:5)	JLT	6
0x0016 00022 (main.go:8)	MOVQ	CX, AX
0x0019 00025 (main.go:8)	RET

Because this loop can be evaluated at compile time, the value of sum can be computed (2016). Therefore, the following assembly code should be generated instead:

0x0000 00000 (main.go:4)	MOVL	$2016, AX
0x0005 00005 (main.go:4)	RET

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions