cmd/compile: incorporate inlined function names into closure naming

In Go 1.17, cmd/compile gained the ability to inline calls to
functions that contain function literals (aka "closures"). This was
implemented by duplicating the function literal body and emitting a
second LSym, because in general it might be optimized better than the
original function literal.

However, the second LSym was named simply as any other function
literal appearing literally in the enclosing function would be named.
E.g., if f has a closure "f.funcX", and f is inlined into g, we would
create "g.funcY" (N.B., X and Y need not be the same.). Users then
have no idea this function originally came from f.

With this CL, the inlined call stack is incorporated into the clone
LSym's name: instead of "g.funcY", it's named "g.f.funcY".

In the future, it seems desirable to arrange for the clone's name to
appear exactly as the original name, so stack traces remain the same
as when -l or -d=inlfuncswithclosures are used. But it's unclear
whether the linker supports that today, or whether any downstream
tooling would be confused by this.

Updates #60324.

Change-Id: Ifad0ccef7e959e72005beeecdfffd872f63982f8
Reviewed-on: https://go-review.googlesource.com/c/go/+/497137
Reviewed-by: Michael Pratt <mpratt@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
Run-TryBot: Matthew Dempsky <mdempsky@google.com>
This commit is contained in:
Matthew Dempsky 2023-05-22 13:25:15 -07:00
parent 2ed6a54a39
commit 7f1467ff4d
6 changed files with 89 additions and 31 deletions

View file

@ -11,6 +11,7 @@ import (
"cmd/internal/objabi"
"cmd/internal/src"
"fmt"
"strings"
)
// A Func corresponds to a single function in a Go program
@ -359,8 +360,8 @@ func IsTrivialClosure(clo *ClosureExpr) bool {
// globClosgen is like Func.Closgen, but for the global scope.
var globClosgen int32
// closureName generates a new unique name for a closure within outerfn.
func closureName(outerfn *Func) *types.Sym {
// closureName generates a new unique name for a closure within outerfn at pos.
func closureName(outerfn *Func, pos src.XPos) *types.Sym {
pkg := types.LocalPkg
outer := "glob."
prefix := "func"
@ -382,6 +383,17 @@ func closureName(outerfn *Func) *types.Sym {
}
}
// If this closure was created due to inlining, then incorporate any
// inlined functions' names into the closure's linker symbol name
// too (#60324).
if inlIndex := base.Ctxt.InnermostPos(pos).Base().InliningIndex(); inlIndex >= 0 {
names := []string{outer}
base.Ctxt.InlTree.AllParents(inlIndex, func(call obj.InlinedCall) {
names = append(names, call.Name)
})
outer = strings.Join(names, ".")
}
*gen++
return pkg.Lookup(fmt.Sprintf("%s.%s%d", outer, prefix, *gen))
}
@ -418,7 +430,7 @@ func NameClosure(clo *ClosureExpr, outerfn *Func) {
base.FatalfAt(clo.Pos(), "closure already named: %v", name)
}
name.SetSym(closureName(outerfn))
name.SetSym(closureName(outerfn, clo.Pos()))
MarkFunc(name)
}