Home >Backend Development >C++ >Why is RAX Pushed onto the Stack Before a Tail Call with a `std::function`?

Why is RAX Pushed onto the Stack Before a Tail Call with a `std::function`?

Susan Sarandon
Susan SarandonOriginal
2024-12-13 01:11:16176browse

Why is RAX Pushed onto the Stack Before a Tail Call with a `std::function`?

Why is RAX Pushed to the Stack Before Tail Call?

The assembly output for the function f taking a std::function argument reveals an intriguing operation: immediately before the tail call, RAX is pushed to the stack. This behavior is not observed in a simple tail call without the std::function wrapper.

Alignment Considerations

The reason for pushing RAX is rooted in the 64-bit ABI, which requires that the stack be aligned to 16 bytes before a call instruction. The call instruction pushes an 8-byte return address onto the stack, violating the alignment. To rectify this, the compiler must realign the stack to a multiple of 16 bytes before the tail call.

Efficient Stack Alignment

Pushing a don't-care value like RAX is an efficient way to achieve stack alignment because:

  • Stack engines on some CPUs can optimize the operation compared to sub rsp, 8.
  • The value pushed to the stack is irrelevant as it is not used within the function.

By pushing RAX, the compiler satisfies the alignment requirement without disrupting the function's behavior.

The above is the detailed content of Why is RAX Pushed onto the Stack Before a Tail Call with a `std::function`?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn