why the opendefer optimization will close when my function's named return value escape

90 views
Skip to first unread message

ワタナベハルキ

unread,
Apr 7, 2022, 2:04:02 PM4/7/22
to golang-nuts
GOARCH="amd64"
GOHOSTOS="linux"
GOVERSION="go1.17.2"

Here is my test code

var sink *int

func main(){
    escape()
}

// named return value r
func escape() (r int) {
    defer func(){
        recover()
    }()
    sink = &r // escape r
    panic("qOeOp")
    return
}

jokoi@ubuntu:~/GoProJ/test$ go build -gcflags "-d defer" main.go
./main.go:11:2: stack-allocated defer

and i find something comment may be useful in package cmd/compile/internel/ssagen

if s.hasOpenDefers {
    ......
                // Similarly, skip if there are any heap-allocated result
                // parameters that need to be copied back to their stack slots.
                for _, f := range s.curfn.Type().Results().FieldSlice() {
                        if !f.Nname.(*ir.Name).OnStack() {
                                s.hasOpenDefers = false
                                break
                        }
                }
        }
    ......
}

but i cannot understand why ? As far as i know , coping heap-allocated result parameter back just need a small piece of code like mov rax [rax] at the exit point of one function , why compiler cannot generate  it .

Ian Lance Taylor

unread,
Apr 11, 2022, 8:20:55 PM4/11/22
to ワタナベハルキ, golang-nuts
It was probably just never implemented. An escaping result parameter
is not a common case.

I expect the compiler developers would be happy to review a patch that
makes it work. See https://go.dev/doc/contribute.

Ian
Reply all
Reply to author
Forward
0 new messages