Passing structs to C functions

Strictly it would be the size of a general purpose register but yes you are correct. Though not all ABI will allow this, some might insist on it being passed in memory regardless.

In this specific example I think you’re looking for the architecture/platform ABIs. I recreated what I think is the C for your example and you can see that it varies by target: Compiler Explorer

So I think the one you are wondering about is for x86. I don’t know their ABI’s details but I think it’s packing the struct into 2 64 bit words and passing it in 2 64 bit registers.

Whether code can do this is detailed in a document like this. We (Arm) call this the “Procedure Call Standard”, and there is one for 32 bit as well, and you can find ones for other architectures like RISC-V.

(if you are building the entire stack of code, you can do almost anything, but if you want to link to anything else you have to play by the rules)

Sometimes these are modified by the operating system that runs on the architecture, for example Apple has differences from the standard Arm ABI.

I am not sure where to find the x86 documents though.

Is there a guide that explains what this is

Yes, these documents.

how to conform

This is more tricky. ABI enforcement in Clang is, if I recall correctly, split between Clang and LLVM, so if you’re generating LLVM IR yourself, you might miss some things.

There are test cases within LLVM you could reference, or as you’ve already done, “do what clang does” (an often used phrase around here :slight_smile: ).

Another thing you can do is limit what sort of things you pass across this ABI so that you only have a few cases to get right. If, for example, you just need to call some basic Posix APIs, this limits what you have to handle.

You could write you own “implementation” of those C functions which just verifies the input arguments are correct, and build a test suite from that.

Someone else may know if there is a way to tell LLVM to automatically apply these rules, depending on how you’re generating your IR.

1 Like