C function argument, memory alignment considerations
Asked Answered
A

2

13

When defining structs in C, there are considerations regarding padding, if struct size is a concern, its common to re-arrange the values to avoid padding. (see: Structure padding and packing)

My questions is:

Do the same (or similar) rules apply to function arguments? ... is there any advantage in arranging arguments to avoid argument padding bytes?


  • Assuming this isn't an inline (where it wont matter), or static function where the compiler could re-arrange arguments.

  • Accepting that the real world measurable improvement is likely to be small.

... in practice if function call overhead is a concern, it may be worth inlining the function. nevertheless, inlining isnt always an option (libraries or function pointers for eg).

Arroba answered 21/5, 2015 at 2:42 Comment(2)
Note that the standard mentions padding in structs because they form objects that can be copied by value, inspected as contiguous blocks of memory, etc. It won't mention anything similar for parameter lists because they don't form a single value, and there's no explicit requirement for them to be contiguous at all. Your answer will therefore be implementation-defined.Shot
I would imagine that the answer is no, it does not matter. The reason is that the arguments would be moved into offsets of %esp / %rsp and so their sizes do not matter when they are later referenced by offsets of %ebp / %rbp. I will leave a more complete answer to the assembly wizards thoughChunchung
B
4

If the argument is small enough to be passed in a register, then the size is immaterial.

Generally the answer is no because compilers often widen arguments when they are passed on the stack to a function. For example:

  • Windows Visual C++ widens to 32 bits on x86 platforms. (link)
  • On Mac OS X, the IA-32 calling convection is to widen to 4 bytes, and on x86-64 the calling convention is to widen to 8 bytes.
  • According to this the Linux x86-64 calling convention is the same as Mac OS X.
  • The ARM standard specifies widening to 4 bytes.

So it doesn't pay to group your one and two byte arguments together because either the argument will be passed in a register or the compiler will probably treat them as being four or eight bytes in length anyway.

Bowel answered 21/5, 2015 at 4:4 Comment(0)
M
3

How arguments are passed to a function varies from architecture to architecture, so it's not possible to provide any sort of definite answer. However, for most modern architectures, the first few parameters are passed in registers, not on the stack, and it matters little how the parameters are aligned, because narrow arguments are not multiplexed into a single register.

Michel answered 21/5, 2015 at 3:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.