Re: C aggregate passing (Rust kernel policy)

Linus Torvalds
2025-02-20T16:47:17Z

On Thu, 20 Feb 2025 at 07:17, Jan Engelhardt <ej@inai.de> wrote:
>
>
> On Thursday 2025-02-20 14:23, H. Peter Anvin wrote:
> >
> >People writing C seem to have a real aversion for using structures
> >as values (arguments, return values or assignments) even though that
> >has been valid since at least C90 and can genuinely produce better
> >code in some cases.
>
> The aversion stems from compilers producing "worse" ASM to this
> date, as in this case for example:

We actually use structures for arguments and return values in the
kernel, and it really does generate better code - but only for
specific situations.

In particular, it really only works well for structures that fit in
two registers. That's the magic cut-off point, partly due calling
convention rules, but also due to compiler implementation issues (ie
gcc has lots of special code for two registers, I am pretty sure clang
does too).

So in the kernel, we use this whole "pass structures around by value"
(either as arguments or return values) mainly in very specific areas.
The main - and historical: we've been doing it for decades - case is
the page table entries. But there are other cases where it happens.

The other problem with aggregate data particularly for return values
is that it gets quite syntactically ugly in C. You can't do ad-hoc
things like

{ a, b } = function_with_two_return_values();

like you can in some other languages (eg python), so it only tends to
work cleanly only with things that really are "one" thing, and it gets
pretty ugly if you want to return something like an error value in
addition to some other thing.

Again, page table entries are a perfect example of where passing
aggregate values around works really well, and we have done it for a
long long time because of that.

Linus