Skip to content

cmd/compile: incorrect code generation bug when taking slice[:0] #29502

@ncw

Description

@ncw

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

go version devel +204a8f55dc Tue Jan 1 20:15:48 2019 +0000 linux/amd64

Also reproduces on go1.11.4

Does this issue reproduce with the latest release?

Yes

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

go env Output
GOARCH="amd64"
GOBIN=""
GOCACHE="/home/ncw/.cache/go-build"
GOEXE=""
GOFLAGS=""
GOHOSTARCH="amd64"
GOHOSTOS="linux"
GOOS="linux"
GOPATH="/home/ncw/go"
GOPROXY=""
GORACE=""
GOROOT="/opt/go/go-tip"
GOTMPDIR=""
GOTOOLDIR="/opt/go/go-tip/pkg/tool/linux_amd64"
GCCGO="gccgo"
CC="gcc"
CXX="g++"
CGO_ENABLED="1"
GOMOD=""
CGO_CFLAGS="-g -O2"
CGO_CPPFLAGS=""
CGO_CXXFLAGS="-g -O2"
CGO_FFLAGS="-g -O2"
CGO_LDFLAGS="-g -O2"
PKG_CONFIG="pkg-config"
GOGCCFLAGS="-fPIC -m64 -pthread -fmessage-length=0 -fdebug-prefix-map=/tmp/go-build968399806=/tmp/go-build -gno-record-gcc-switches"

What did you do?

I compile and ran this program (simplified from a larger project)

package main

func Bug() (e int64, err error) {
	var stack []int64
	stack = append(stack, 123)
	// Commenting the next 3 lines causes the function to work
	if len(stack) > 1 {
		panic("too many elements")
	}
	last := len(stack) - 1
	e = stack[last]
	stack = stack[:last]
	return e, nil
}

func main() {
	Bug()
}

What did you expect to see?

I expected it to run without error

What did you see instead?

$ go run bug2-inline.go
panic: runtime error: slice bounds out of range

goroutine 1 [running]:
main.Bug(...)
	/home/ncw/Go/bug2-inline.go:12
main.main()
	/home/ncw/Go/bug2-inline.go:17 +0x70
exit status 2

Compilation exited abnormally with code 1 at Wed Jan  2 12:32:47

This is incorrectly complaining that stack[:last] is out of range where last == 0 and len(stack) == cap(stack) == 1.

A tip-off that this is a compiler bug is that commenting out the if statement causes the program to work.

The > 1 is important in the if statement, > 2 does not provoke the bug - I conjecture the compiler is learning something about the length of the slice from that if statement but what it learnt is incorrect in some way - off by one maybe.

I note that this example does not fail on the playground.

Metadata

Metadata

Assignees

No one assigned

    Labels

    FrozenDueToAgeNeedsInvestigationSomeone must examine and confirm this is a valid issue and not a duplicate of an existing one.release-blocker

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions