<p>In languages with well defined object lifetimes the destructors of by-value parameters have to be called at some point. This can be the responsibility of the caller or of the callee.</p>
<p>GCC and Clang compiling C++ for example decide to have the caller destroy the arguments. This can can lead to slightly inefficient code if the callee will always move the value out of the argument. <a href="https://godbolt.org/z/xob46x5e6" rel="nofollow noreferrer">For example</a> after passing a <code>std::unique_ptr</code> by value, the caller must always check if the value was moved out of the argument and if not call <code>operator delete</code> on the pointer. Taking <code>unique_ptr</code> by value and moving out unconditionally is a common idiom and the check in the caller is always unnecessary in this case.</p>
<p>Here</p>
<pre class="lang-cpp prettyprint-override"><code>#include &lt;memory&gt;

// Will always move out of p
void foo(std::unique_ptr&lt;int&gt; p);

void bar() {
    foo(std::make_unique&lt;int&gt;());
}
</code></pre>
<p>is lowered to</p>
<pre><code>bar():
        push    rbx
        mov     edi, 4
        sub     rsp, 16
        call    operator new(unsigned long)
        lea     rdi, [rsp+8]
        mov     DWORD PTR [rax], 0
        mov     QWORD PTR [rsp+8], rax
        call    foo(std::unique_ptr&lt;int, std::default_delete&lt;int&gt; &gt;)
        mov     rdi, QWORD PTR [rsp+8]
        test    rdi, rdi                  ; Null pointer check here!
        je      .L1
        mov     esi, 4
        call    operator delete(void*, unsigned long)
.L1:
        add     rsp, 16
        pop     rbx
        ret
        mov     rbx, rax
        jmp     .L3
bar() [clone .cold]:
</code></pre>
<p>Rustc on the other hand generates code where the callee destroys the arguments. So the <code>unique_ptr</code> (or rather <code>Box</code>) <a href="https://godbolt.org/z/axTj9PMGd" rel="nofollow noreferrer">example</a> does not require an extra null pointer check.</p>
<p>Here</p>
<pre class="lang-rust prettyprint-override"><code>#[inline(never)]
pub fn foo(p: Box&lt;i32&gt;) {/*...*/}

pub fn bar() {
    foo(Box::new(0));
}
</code></pre>
<p>is lowered to</p>
<pre><code>example::bar:
        push    rax
        mov     rax, qword ptr [rip + __rust_no_alloc_shim_is_unstable@GOTPCREL]
        movzx   eax, byte ptr [rax]
        mov     edi, 4
        mov     esi, 4
        call    qword ptr [rip + __rust_alloc@GOTPCREL]
        test    rax, rax
        je      .LBB1_1
        mov     dword ptr [rax], 0
        mov     rdi, rax
        pop     rax
        jmp     qword ptr [rip + example::foo@GOTPCREL] ; Tail call to foo, no cleanup afterwards
.LBB1_1:
        mov     edi, 4
        mov     esi, 4
        call    qword ptr [rip + alloc::alloc::handle_alloc_error@GOTPCREL]
        ud2
</code></pre>
<p>So what are the advantages of the &quot;caller destroys arguments&quot; approach?</p>
<p>And, if there are others beside the one mentioned above, what are the advantages of Rustc's &quot;callee destroys arguments&quot; approach?</p>

<calling-conventions>
What are the advantages if caller is responsible for argument destruction vs callee is responsible?
CC BY-SA 4.0
2024-01-17T11:35:00.593Z
Why must the caller check whether a value was moved from?  The moved-from object is in a valid state and so can simply be destructed in the normal way when it goes out of scope.
Toby Speight
CC BY-SA 4.0
2024-01-17T11:37:35.757Z
@TobySpeight Yes, but in the case of `std::unique_ptr` and many other types the destruction involves a null pointer check. But if the compiler saw that the value was moved out it would statically know that the pointer is null and could elide the entire destructor.
chrysante
CC BY-SA 4.0
2024-01-17T21:19:29.397Z
You write that “C++ for instance requires the caller to destroy the arguments,” but this seems unlikely to be true to me. I could be wrong, but I don’t think anything in the C++ specification requires this choice, and in fact I don’t think C++ is specified at a low enough level that would permit requiring this choice. Rather, it seems like C++ *compilers* choose to implement things this way. Is it accurate to say that your question is then why C++ compilers choose to use this calling convention?
Alexis King
CC BY-SA 4.0
2024-01-17T21:33:33.070Z
@AlexisKing [_The initialization and destruction of each parameter occurs within the context of the full-expression (\[intro.execution\]) where the function call appears._](http://eel.is/c++draft/expr.call#6) If I understand this correctly the standard requires it as phrased in my question. But it doesn't really matter to the question if it is the standard or the compiler that made the decision.
chrysante
CC BY-SA 4.0
2024-01-17T21:42:30.030Z
@chrysante That sentence just means that each parameter must be destructed before the end of the enclosing full-expression. It doesn’t specify where the code to do the destruction must be generated because that decision is not observable under the semantics of the C++ abstract machine. Indeed, the immediately preceding sentence, “It is implementation-defined whether the lifetime of a parameter ends when the function in which it is defined returns or at the end of the enclosing full-expression,” explicitly leaves open both possibilities.
Alexis King
CC BY-SA 4.0
2024-01-17T22:11:05.700Z
@AlexisKing Thank you, yes it makes sense that the standard would not specify this. I edited the question.
chrysante
<p>I think the main reason is for backwards compatibility with C varargs (<code>&lt;cstdarg&gt;</code> header).</p>
<p>When C stadrgs are used, the callee does not necessarily know the types of the arguments -- it is legal to pass extra arguments that the callee does not use, and they still need to be cleaned up properly.  By having the caller always clean up all arguments, this becomes much less of an issue.</p>

CC BY-SA 4.0
2024-01-17T22:41:58.363Z
2024-01-17T22:41:58.363Z
Chris Dodd
CC BY-SA 4.0
2024-01-18T12:09:12.650Z
I have to say I'm not convinced. The question is not about who resets the stack pointer but who invokes destructors. And since you cannot pass objects with non-trivial lifetime to C style varargs functions, this should not be related unless I misunderstand your answer.
chrysante
<p><strong>TL;DR: It may well be historical.</strong></p>
<h1>Trip down memory lane</h1>
<p>C++ was first standardized in 1998, though it had started its existed 15 years prior already. And only in C++11 were move semantics introduced.</p>
<p>This means that from 13 years (to 28 years) of its existence, moves <em>were not</em>. Instead, passing by value entailed copying the value -- possibly invoking a copy constructor.</p>
<p>In such a scheme, the caller is naturally responsible for cleaning up the value being copied -- if necessary -- and therefore well-suited to cleaning up the argument.</p>
<h3>References &amp; Pointers</h3>
<p>Another possible justification for having the caller clean-up, is that whenever an argument is passed by reference or pointer, the caller will perform the clean-up already.</p>
<p>Thus, it seems in keeping to also have the caller be responsible for the one case where arguments are passed by value.</p>
<h3>ABI Consideration</h3>
<p>At the assembly level, arguments are passed either by register, or via the stack.</p>
<p>An arbitrarily large value cannot be passed by register -- today, I believe at most 2 registers are used to pass by value on x64 for example -- and therefore at the assembly level the caller reserves some stack space, initialize it, then passes a pointer to it.</p>
<p>This is symmetrical with the caller reserving some stack space and passing a pointer to it when returning large values, by the way.</p>
<p>It seems consistent to have the caller handle destruction, when it is already handling memory allocation.</p>
<h3>ABI Optimization</h3>
<p>One clever little trick used by many implementations is the so-called <a href="https://en.wikipedia.org/wiki/Red_zone_(computing)" rel="nofollow noreferrer">Red Zone</a>.</p>
<p>Whenever a function is invoked which is:</p>
<ol>
<li>A leaf function: a function invoking no other function.</li>
<li>A frugal function: a function using no more than 128 bytes on the stack.</li>
</ol>
<p>Then this function <em>skips</em> setting up (and tearing down) a stack frame of its own.</p>
<p>This is a clever trick, as it both minimizes the size of those functions, and minimizes their execution time, even if they are not inlined.</p>
<p>Having the caller take care of the clean-up, rather than the callee, has the advantage of making more callees frugal, and thus eligible for Red Zone optimization. Whether this was foreseen or not, I know not.</p>
<h3>Summary so far</h3>
<p>Up until C++11, it is therefore &quot;logical&quot; for the caller to be the one cleaning up arguments passed by value.</p>
<p>There's a slight advantage (Red Zone) and it's otherwise in line with cleaning up <em>all</em> other arguments.</p>
<h1>Moves enter the scene</h1>
<p>When C++11 introduced moves, <em>how</em> to design moves was up in the air.</p>
<p>In the end, the design selected was user-provided move operators -- which automatically gated their introduction on existing types, to avoid introducing bugs -- and for the moved-out object to be left in an unspecified but valid state. In particular, the moved-out object has its destructor invoked.</p>
<p>This all very conservative, essentially mimicking the design of existing copy constructors -- including the &quot;fake&quot; copy-constructor that <code>auto_ptr</code> had at the time which transferred its pointee.</p>
<p>It also has the distinct advantage of being compatible with the existing ABI so far!</p>
<p>I know not whether anyone realized, then, that it was sub-optimal in a number of cases. Even if they did, compatibility may have trumped any such concern.</p>
<h1>Conclusion</h1>
<p>In the end, I am afraid that the not so satisfying answer is just &quot;it is what it is&quot;, and that C++11 simply inherited the mechanics from C++98 (and prior). The migration to C++11 (libstdc++ <code>std::string</code> fiasco) was complicated enough as it is.</p>
<p>The Red Zone argument <em>may</em> still hold, and make the choice a trade-off, but with compilers nowadays inlining more, I'm not too convinced it's worth it.</p>

CC BY-SA 4.0
2024-01-19T15:39:37.260Z
2024-01-19T15:39:37.260Z
Matthieu M.
CC BY-SA 4.0
2024-01-19T16:23:28.370Z
Thank you, this is a great answer! I was mostly asking this to make sure I'm not getting myself into trouble if I implement argument destruction by the callee in my compiler, and this is making me not worried anymore. I do have a follow up question though: how does the compiler know if a function is a leaf or frugal? Or does the red zone optimization only work with functions whose bodies are visible to the compiler, i.e. `static` functions?
chrysante
CC BY-SA 4.0
2024-01-19T17:25:56.847Z
@chrysante: the Red Zone optimization is entirely self-contained, as it only modifies the function prologue/epilogue _within the function itself_. So the compiler knows it because it's compiling the very function it applies the optimization to :)
Matthieu M.
# What are the advantages if caller is responsible for argument destruction vs callee is responsible?
Posted by: username_0 on 2024-01-17
In languages with well defined object lifetimes the destructors of by-value parameters have to be called at some point. This can be the responsibility of the caller or of the callee.
GCC and Clang compiling C++ for example decide to have the caller destroy the arguments. This can can lead to slightly inefficient code if the callee will always move the value out of the argument. For example after passing a std::unique_ptr by value, the caller must always check if the value was moved out of the argument and if not call operator delete on the pointer. Taking unique_ptr by value and moving out unconditionally is a common idiom and the check in the caller is always unnecessary in this case.
Here
#include 

// Will always move out of p
void foo(std::unique_ptr p);

void bar() {
    foo(std::make_unique());
}

is lowered to
bar():
        push    rbx
        mov     edi, 4
        sub     rsp, 16
        call    operator new(unsigned long)
        lea     rdi, [rsp+8]
        mov     DWORD PTR [rax], 0
        mov     QWORD PTR [rsp+8], rax
        call    foo(std::unique_ptr >)
        mov     rdi, QWORD PTR [rsp+8]
        test    rdi, rdi                  ; Null pointer check here!
        je      .L1
        mov     esi, 4
        call    operator delete(void*, unsigned long)
.L1:
        add     rsp, 16
        pop     rbx
        ret
        mov     rbx, rax
        jmp     .L3
bar() [clone .cold]:

Rustc on the other hand generates code where the callee destroys the arguments. So the unique_ptr (or rather Box) example does not require an extra null pointer check.
Here
#[inline(never)]
pub fn foo(p: Box) {/*...*/}

pub fn bar() {
    foo(Box::new(0));
}

is lowered to
example::bar:
        push    rax
        mov     rax, qword ptr [rip + __rust_no_alloc_shim_is_unstable@GOTPCREL]
        movzx   eax, byte ptr [rax]
        mov     edi, 4
        mov     esi, 4
        call    qword ptr [rip + __rust_alloc@GOTPCREL]
        test    rax, rax
        je      .LBB1_1
        mov     dword ptr [rax], 0
        mov     rdi, rax
        pop     rax
        jmp     qword ptr [rip + example::foo@GOTPCREL] ; Tail call to foo, no cleanup afterwards
.LBB1_1:
        mov     edi, 4
        mov     esi, 4
        call    qword ptr [rip + alloc::alloc::handle_alloc_error@GOTPCREL]
        ud2

So what are the advantages of the "caller destroys arguments" approach?
And, if there are others beside the one mentioned above, what are the advantages of Rustc's "callee destroys arguments" approach?
**Tags:** calling-conventions
> **Comments:**
> **username_1**: Why must the caller check whether a value was moved from?  The moved-from object is in a valid state and so can simply be destructed in the normal way when it goes out of scope.  
> **username_0**: @TobySpeight Yes, but in the case of `std::unique_ptr` and many other types the destruction involves a null pointer check. But if the compiler saw that the value was moved out it would statically know that the pointer is null and could elide the entire destructor.  
> **username_2**: You write that “C++ for instance requires the caller to destroy the arguments,” but this seems unlikely to be true to me. I could be wrong, but I don’t think anything in the C++ specification requires this choice, and in fact I don’t think C++ is specified at a low enough level that would permit requiring this choice. Rather, it seems like C++ *compilers* choose to implement things this way. Is it accurate to say that your question is then why C++ compilers choose to use this calling convention?  
> **username_0**: @AlexisKing [_The initialization and destruction of each parameter occurs within the context of the full-expression (\[intro.execution\]) where the function call appears._](http://eel.is/c++draft/expr.call#6) If I understand this correctly the standard requires it as phrased in my question. But it doesn't really matter to the question if it is the standard or the compiler that made the decision.  
> **username_2**: @chrysante That sentence just means that each parameter must be destructed before the end of the enclosing full-expression. It doesn’t specify where the code to do the destruction must be generated because that decision is not observable under the semantics of the C++ abstract machine. Indeed, the immediately preceding sentence, “It is implementation-defined whether the lifetime of a parameter ends when the function in which it is defined returns or at the end of the enclosing full-expression,” explicitly leaves open both possibilities.  
> **username_0**: @AlexisKing Thank you, yes it makes sense that the standard would not specify this. I edited the question.  
---
## 2 answers
### Answer by username_4 on 2024-01-19. Score: 4 | Accepted answer
**TL;DR: It may well be historical.**

# Trip down memory lane

C++ was first standardized in 1998, though it had started its existed 15 years prior already. And only in C++11 were move semantics introduced.

This means that from 13 years (to 28 years) of its existence, moves *were not*. Instead, passing by value entailed copying the value -- possibly invoking a copy constructor.

In such a scheme, the caller is naturally responsible for cleaning up the value being copied -- if necessary -- and therefore well-suited to cleaning up the argument.

### References & Pointers

Another possible justification for having the caller clean-up, is that whenever an argument is passed by reference or pointer, the caller will perform the clean-up already.

Thus, it seems in keeping to also have the caller be responsible for the one case where arguments are passed by value.

### ABI Consideration

At the assembly level, arguments are passed either by register, or via the stack.

An arbitrarily large value cannot be passed by register -- today, I believe at most 2 registers are used to pass by value on x64 for example -- and therefore at the assembly level the caller reserves some stack space, initialize it, then passes a pointer to it.

This is symmetrical with the caller reserving some stack space and passing a pointer to it when returning large values, by the way.

It seems consistent to have the caller handle destruction, when it is already handling memory allocation.

### ABI Optimization

One clever little trick used by many implementations is the so-called [Red Zone](https://en.wikipedia.org/wiki/Red_zone_(computing)).

Whenever a function is invoked which is:

1. A leaf function: a function invoking no other function.
2. A frugal function: a function using no more than 128 bytes on the stack.

Then this function *skips* setting up (and tearing down) a stack frame of its own.

This is a clever trick, as it both minimizes the size of those functions, and minimizes their execution time, even if they are not inlined.

Having the caller take care of the clean-up, rather than the callee, has the advantage of making more callees frugal, and thus eligible for Red Zone optimization. Whether this was foreseen or not, I know not.

### Summary so far

Up until C++11, it is therefore "logical" for the caller to be the one cleaning up arguments passed by value.

There's a slight advantage (Red Zone) and it's otherwise in line with cleaning up *all* other arguments.

# Moves enter the scene

When C++11 introduced moves, *how* to design moves was up in the air.

In the end, the design selected was user-provided move operators -- which automatically gated their introduction on existing types, to avoid introducing bugs -- and for the moved-out object to be left in an unspecified but valid state. In particular, the moved-out object has its destructor invoked.

This all very conservative, essentially mimicking the design of existing copy constructors -- including the "fake" copy-constructor that `auto_ptr` had at the time which transferred its pointee.

It also has the distinct advantage of being compatible with the existing ABI so far!

I know not whether anyone realized, then, that it was sub-optimal in a number of cases. Even if they did, compatibility may have trumped any such concern.

# Conclusion

In the end, I am afraid that the not so satisfying answer is just "it is what it is", and that C++11 simply inherited the mechanics from C++98 (and prior). The migration to C++11 (libstdc++ `std::string` fiasco) was complicated enough as it is.

The Red Zone argument *may* still hold, and make the choice a trade-off, but with compilers nowadays inlining more, I'm not too convinced it's worth it.
> **Comments:**
> **username_0** (2024-01-19): Thank you, this is a great answer! I was mostly asking this to make sure I'm not getting myself into trouble if I implement argument destruction by the callee in my compiler, and this is making me not worried anymore. I do have a follow up question though: how does the compiler know if a function is a leaf or frugal? Or does the red zone optimization only work with functions whose bodies are visible to the compiler, i.e. `static` functions?  
> **username_4** (2024-01-19): @chrysante: the Red Zone optimization is entirely self-contained, as it only modifies the function prologue/epilogue _within the function itself_. So the compiler knows it because it's compiling the very function it applies the optimization to :)  
---
### Answer by username_3 on 2024-01-17. Score: 1
I think the main reason is for backwards compatibility with C varargs ( header).

When C stadrgs are used, the callee does not necessarily know the types of the arguments -- it is legal to pass extra arguments that the callee does not use, and they still need to be cleaned up properly. By having the caller always clean up all arguments, this becomes much less of an issue.
> **Comments:**
> **username_0** (2024-01-18): I have to say I'm not convinced. The question is not about who resets the stack pointer but who invokes destructors. And since you cannot pass objects with non-trivial lifetime to C style varargs functions, this should not be related unless I misunderstand your answer.  
---
