Thread overview
The reason for not compiling safeD code on the gdc compiler
Aug 21, 2021
Heikuw
Aug 21, 2021
jfondren
Aug 22, 2021
Mathias LANG
August 21, 2021

What causes this example of safeD code to be compiled in dmd and ldc but not compiled in gcc?

code :

immutable(int)* f(int* p) @trusted
{
    version (none) p[2] = 13;
    // Invalid. p[2] is out of bounds. This line would exhibit undefined
    // behavior.

    version (none) p[1] = 13;
    // Invalid. In this program, p[1] happens to be in-bounds, so the
    // line would not exhibit undefined behavior, but a trusted function
    // is not allowed to rely on this.

    version (none) return cast(immutable) p;
    // Invalid. @safe code still has mutable access and could trigger
    // undefined behavior by overwriting the value later on.

    int* p2 = new int;
    *p2 = 42;
    return cast(immutable) p2;
    // Valid. After f returns, no mutable aliases of p2 can exist.
}

void main() @safe
{
    int[2] a = [10, 20];
    int* mp = &a[0];
    immutable(int)* ip = f(mp);
    assert(a[1] == 20); // Guaranteed. f cannot access a[1].
    assert(ip !is mp); // Guaranteed. f cannot introduce unsafe aliasing.
}


result code in gdc compiler :
main.d:25:15: error: cannot take address of local a in @safe function main
   25 |     int* mp = &a[0];
      |               ^
August 21, 2021

On Saturday, 21 August 2021 at 07:16:46 UTC, Heikuw wrote:

>

What causes this example of safeD code to be compiled in dmd and ldc but not compiled in gcc?

The default behavior varies, but the dip1000 behavior is the same:

$ gdc -ftransition=dip1000 bug.d
bug.d:26:28: error: scope variable mp assigned to non-scope parameter p calling bug.f
   26 |     immutable(int)* ip = f(mp);
      |                            ^
$ dmd -preview=dip1000 bug.d
bug.d(26): Error: scope variable `mp` assigned to non-scope parameter `p` calling bug.f
$ ldc2 -preview=dip1000 bug.d
bug.d(26): Error: scope variable `mp` assigned to non-scope parameter `p` calling bug.f
August 22, 2021

On Saturday, 21 August 2021 at 07:16:46 UTC, Heikuw wrote:

>

What causes this example of safeD code to be compiled in dmd and ldc but not compiled in gcc?

Most likely frontend differences. Check pragma(msg, __VERSION__);.