[LLVMdev] Problem returning structures by value from C

Dale Johannesen dalej at apple.com
Fri Jan 7 13:38:24 PST 2011


On Jan 7, 2011, at 1:31 PMPST, Lockal wrote:

> I have a simple structure in my program:
> 
> struct pair { double value; int32_t type; };
> 
> Also I have 2 functions, which are called from LLVM code:
> 
> extern "C" void dump(pair s) {
>    unsigned char *p = reinterpret_cast<unsigned char *>(&s);
>    printf("#dump, %02x%02x%02x%02x %02x%02x%02x%02x %02x%02x%02x%02x\n",
>      p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7], p[8], p[9], p[10], p[11]);
> }
> 
> extern "C" pair set() {
>    pair ret = { 0, 3 };
> 
>    unsigned char *p = reinterpret_cast<unsigned char *>(&ret);
>    printf("#set, %02x%02x%02x%02x %02x%02x%02x%02x %02x%02x%02x%02x\n",
>      p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7], p[8], p[9], p[10], p[11]);
> 
>    return ret;
> }
> 
> LLVM code contains the same structure definition and prototypes for functions:
> 
> %0 = type { double, i32 }
> declare %0 @set()
> declare void @dump(%0)
> 
> 
> So the question is: why the structure data is smashed after this code?
> 
> %a = call %0 @set()
> call void @dump(%0 %a)
> 
> Output:
> #set, 00000000 00000000 03000000
> #dump, 00000000 0000f8ff 88b93709
> 
> Is there any way to return structure from C to LLVM by value?

Yes, but what you're doing won't usually work.  You need to use IR that reflects the calling convention on your target.  sret is often the right thing to use; some targets are more complicated.  The best way to find out what you need is run llvm-gcc -S -emit-llvm on a testcase and look at the output file.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/llvm-dev/attachments/20110107/93caaf91/attachment.html>


More information about the llvm-dev mailing list