Heap allocation found in function prolog

171 views
Skip to first unread message

ju...@sqreen.com

unread,
Sep 23, 2020, 9:34:30 AM9/23/20
to golang-nuts
Hello,

I was surprised to find a heap allocation in the following function prolog:

Under what circumstances is this happening and it is possible to avoid it?

Thanks,
Julio

Jan Mercl

unread,
Sep 23, 2020, 9:48:44 AM9/23/20
to ju...@sqreen.com, golang-nuts
On Wed, Sep 23, 2020 at 3:36 PM 'ju...@sqreen.com' via golang-nuts
<golan...@googlegroups.com> wrote:

> I was surprised to find a heap allocation in the following function prolog:
> https://gist.github.com/Julio-Guerra/a3a2088832cd927669c08e1127e4c25a

I think the function prolog consists of the first three assembler
instructions, with the possible additional prolog at 4fedf0 when stack
must be enlarged.

Keith Randall

unread,
Sep 23, 2020, 8:32:18 PM9/23/20
to golang-nuts
That looks like something escaped to the heap.
If you pass the -S option to the compiler, the assembly output will have the symbolic name of the type being allocated (at the LEAQ 2 instructions before the call to newobject).
If you pass the -m option to the compiler, it will tell you what escaped and why.

ju...@sqreen.com

unread,
Nov 17, 2020, 11:00:28 AM11/17/20
to golang-nuts
Thanks for the hints, I could finally have a look at it and found that a uint64 value was escaping regardless of the actual function code path. I can reproduce it with this dummy function example: 

func foo(cond bool, v int) *int {
    if cond {
        return &v
    }
    return nil
}

The compiled function prolog allocates the int value regardless of the fact it's not always needed.
I fixed it for now by declaring a new value in the condition block:

func foo(cond bool, v int) *int {
    if cond {
        v := v // new declaration in this scope to avoid using function scope
        return &v
    }
    return nil
}

Is it something expected?

Best
-- 
Julio Guerra
Reply all
Reply to author
Forward
0 new messages