D issues are now tracked on GitHub. This Bugzilla instance remains as a read-only archive.
Issue 20688 - Wrong code when linking to C complex number functions
Summary: Wrong code when linking to C complex number functions
Status: RESOLVED WORKSFORME
Alias: None
Product: D
Classification: Unclassified
Component: dmd (show other issues)
Version: D2
Hardware: x86_64 Linux
: P2 major
Assignee: No Owner
URL:
Keywords: backend, wrong-code
Depends on:
Blocks:
 
Reported: 2020-03-20 02:36 UTC by Vladimir Panteleev
Modified: 2020-09-07 22:58 UTC (History)
1 user (show)

See Also:


Attachments

Note You need to log in before you can comment on or make changes to this issue.
Description Vladimir Panteleev 2020-03-20 02:36:31 UTC
C program:

/////////////////// test.c ///////////////////
#include <stdio.h>
#include <complex.h>

int main()
{
    double complex r = cpow(2 + 0*I, 2 + 0*I);
    printf("%f+%fi\n", creal(r), cimag(r));
    return 0;
}
//////////////////////////////////////////////

As expected, this prints 4.000000+0.000000i.

Equivalent D program:

////////////////// test.d /////////////////
import std.stdio;

import core.stdc.complex;

void main()
{
    cdouble r = cpowf(2. + 0i, 2. + 0i);
    printf("%f+%fi\n", creal(r), cimag(r));
}
///////////////////////////////////////////

This prints garbage (for me, randomly -0.000000+-0.000000i or nan+nani).
Comment 1 Walter Bright 2020-09-07 05:32:11 UTC
The %f format is for doubles, and creal/cimag return reals. To fix:

  printf("%f+%fi\n", cast(double)creal(r), cast(double)cimag(r));

which prints:

  4.000000+0.000000i
Comment 2 Vladimir Panteleev 2020-09-07 12:05:12 UTC
(In reply to Walter Bright from comment #1)
> The %f format is for doubles, and creal/cimag return reals.

So: https://github.com/dlang/druntime/blob/master/src/core/stdc/complex.d#L153

creal is weirdly an alias to "complex" instead of a function.

> To fix:

No, still a problem on Linux/x86_64.
Comment 3 Vladimir Panteleev 2020-09-07 12:10:12 UTC
Demonstration: https://run.dlang.io/is/haL0K3
Comment 4 Walter Bright 2020-09-07 22:49:01 UTC
It works correctly when I try it with master. Perhaps this is because I have fixed other bugs regarding structs in the meantime.
Comment 5 Vladimir Panteleev 2020-09-07 22:51:46 UTC
Confirmed, fixed in master. Thanks!
Comment 6 Walter Bright 2020-09-07 22:57:51 UTC
I added a test case to ensure it.
Comment 7 Walter Bright 2020-09-07 22:58:34 UTC
https://github.com/dlang/dmd/pull/11710