Skip to content

cmd/compile: backing a local slice with an array in a loop causes the array to escape #24730

Closed

Description

@mundaym

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

go version devel +68c7cb25a7 Wed Apr 4 12:18:29 2018 +0100 darwin/amd64

Does this issue reproduce with the latest release?

Yes (go version go1.10.1 darwin/amd64)

What did you do?

Compile the following code with '-m -m' to print escape information:

package main

type T struct {
	x [64]byte
}

func (t *T) f() {
	y := t.x[:]
	for i := range t.x[:] {
		y[i] = 1
	}
}

func (t *T) g() {
	y := t.x[:]
	for i := range t.x[:] {
		y = t.x[:] // <--- causes t.x to escape 
		y[i] = 1
	}
}

func main() { }

What did you expect to see?

t.x not to escape in f() or g() (it is only referenced by local variables).

What did you see instead?

t.x escapes in g() due to the second assignment.

./esc.go:7:10: (*T).f t does not escape
./esc.go:8:10: (*T).f t.x does not escape
./esc.go:17:10: t.x escapes to heap
./esc.go:17:10: 	from y (assigned) at ./esc.go:17:5
./esc.go:14:10: (*T).g t does not escape
./esc.go:15:10: (*T).g t.x does not escape
./esc.go:16:20: (*T).g t.x does not escape

Activity

  1. mvdan commented on Apr 6, 2018

    @mvdan
    Member

    Smaller repro:

    $ cat f.go
    package p
    
    var arr [64]byte
    
    func f() {
            var y []byte
            for i := 0; i < 2; i++ {
                    y = arr[:]
                    y[i] = 1
            }
    }
    $ go build -gcflags=-m f.go
    # command-line-arguments
    ./f.go:8:10: arr escapes to heap
    
  2. josharian commented on Apr 6, 2018

    @josharian
    Contributor
  3. cherrymui commented on Apr 6, 2018

    @cherrymui
    Member

    This is not specific to slice and array.

    package p
    
    type T struct { x int }
    
    func f(t *T) {
            var y *int
            for i := 0; i < 2; i++ {
                    y = &t.x
                    *y = 1
            }
    }
    
    e2.go:8:21: &t.x escapes to heap
    

    The escape analysis models "loop depth". If the address of t.x to is passed to something defined at a lower (outer) loop depth, the escape analysis decides it escape. The problem is that it uses the loop depth of the address operator (or [:] which is implicitly address operator) instead of where the RHS is defined.

  4. gopherbot commented on Apr 9, 2018

    @gopherbot
    Contributor

    Change https://golang.org/cl/105257 mentions this issue: cmd/compile: in escape analysis, propagate loop depth to field

  5. locked and limited conversation to collaborators on Apr 13, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions