Stream: cranelift

Topic: C compatible structs


view this post on Zulip ibrahim (Jan 25 2025 at 21:37):

Hello people,

Using cranelift, I have been able to generate some code to call c functions with primitive arguments, but I can't quite figure out how to approach structs.

what would I need to generate for the f and g? one or the other could be defined from c.

#include <stdio.h>

typedef struct MyStruct
{
  int a;
  char b;
  float c;
} MyStruct;

void f(MyStruct s)
{
  printf("a=%d, b=%c, c=%f\n", s.a, s.b, s.c);
}

MyStruct g()
{
  MyStruct x;
  x.a = 5;
  x.b = 'b';
  x.c = 5.;
  return x;
}

int main()
{
  f(g());
  return 0;
}

Appreciate any direction.

view this post on Zulip ibrahim (Jan 25 2025 at 21:41):

I have tried looking at the --debug-ir output of saltwater, but it is crashing on this file.

view this post on Zulip ibrahim (Jan 25 2025 at 21:41):

https://github.com/afonso360/saltwater

A C compiler written in Rust, with a focus on good error messages. - afonso360/saltwater

view this post on Zulip ibrahim (Jan 25 2025 at 22:28):

#cranelift > returning values to rust this topic helped a bit.

view this post on Zulip Chris Fallin (Jan 26 2025 at 01:05):

The short answer is that Cranelift's IR doesn't have any notion of structs, so you will need to lower to loads and stores directly, and follow the platform's ABI. You found one thread that answers your question re: return values already. In general if you compile the code natively using clang or gcc and look at the disassembly, you'll see that structs are handled as loads and stores at offsets from a base pointer.

view this post on Zulip bjorn3 (Jan 26 2025 at 07:43):

And when you dump LLVM IR you will see that returns of large structs use an sret return pointer argument (small structs may directly return the fields depending on the abi or pack multiple fields in a single register) And for large struct arguments byval pointers are passed (again small structs may directly pass the fields or pack multiple fields in a single register) These correspond to ArgumentPurpose::StructReturn and ArgumentPurpose::StructArgument respectively in clif ir.


Last updated: Feb 27 2025 at 22:03 UTC