-
Notifications
You must be signed in to change notification settings - Fork 17.9k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
cmd/compile: some closures can be optimized to be allocated on stack rather heap #43210
Comments
The problem is that Inlining may fix this particular example, that's #28727 (and #10292). Did you run into this in real code? Is the body of |
@randall77 Yes, I run into this in real code, which is very similar to |
@randall77 Currently, the compiler will rewrite a closure like that to an anonymous struct, which has two fields. I think the reason why we need to allocate that struct on heap is when the compiler meets a function call like |
I don't think this really has to do with the call to If we inline
The compiler does know that it is a closure call.
So should we close this as a dup of #28727 ? |
I mean we cannot return a copy of closures (those two field anonymous structs) rather than a pointer, is because the compiler cannot figure out whether it's a normal function pointer or a copied closure struct and handle it specially. But I fully understand your meaning. I'll close this issue. |
Indeed. Furthermore, we can't return closures by value because they aren't constant sized. The caller has no way to know how big the closure allocated by the callee was, so it can't allocate space in its stack frame for it.
If The former closure is 2 words in size (function entry point, the value of x), the latter is 3 words in size (function entry point, the values of x and y). (I guess we could do interprocedural analysis to figure out when it is constant sized, and pass by value in that case. But even then it is tricky because the caller needs to know the pointerness of each entry.) |
What version of Go are you using (
go version
)?Does this issue reproduce with the latest release?
Yes.
What operating system and processor architecture are you using (
go env
)?go env
OutputWhat did you do?
https://play.golang.org/p/cbvFc7e9MbI
What did you expect to see?
functions Test1 and Test2 do totally the same thing, one with "functor" and the other with closure. They can be both zero-allocated.
What did you see instead?
Test2 will always allocate the closure on heap.
The text was updated successfully, but these errors were encountered: