Skip to content

cmd/compile: optimize recursive closure calls #59708

Open
@adonovan

Description

@adonovan

It is often convenient to define recursive functions local to some outer function, either because you don't want to pollute the package namespace with helper functions, or because the recursive function wants to close over locals of the outer function. Of course Go doesn't have recursive function literals so you have to fake it by using the var trick. The escape analysis is smart enough to avoid heap-allocating the closure in such cases, but unfortunately the actual recursive call is still dynamic.

type Cell struct {
	Next *Cell
}

func f(c *Cell) {
	var visit func(c *Cell)
	visit = func(c *Cell) {
		if c.Next != nil {
			visit(c.Next) // generates CALL (R1) on ARM
		}
	}
	visit(c)
}

Could the compiler be made smart enough to notice that the visit variable is assigned exactly once to a func literal, and thus it is safe to turn the whole thing into a letrec so that the call to visit becomes static?

Metadata

Metadata

Assignees

Labels

FeatureRequestIssues asking for a new feature that does not need a proposal.NeedsDecisionFeedback is required from experts, contributors, and/or the community before a change can be made.Performancecompiler/runtimeIssues related to the Go compiler and/or runtime.

Type

No type

Projects

Status

Todo

Relationships

None yet

Development

No branches or pull requests

Issue actions