Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Small amount of escape analysis to allow more @nogc functions #18832

Open
dlangBugzillaToGithub opened this issue May 26, 2014 · 1 comment
Open

Comments

@dlangBugzillaToGithub
Copy link

bearophile_hugs reported this on 2014-05-26T21:53:34Z

Transferred from https://issues.dlang.org/show_bug.cgi?id=12808

CC List

  • Stanislav Blinov

Description

DMD 2.066alpha accepts this code:

// Program#1
void main() @nogc {
    int[2] tmp = [1, 2];
    foreach (x; tmp) {}
}


While it refuses this code:

// Program#2
void main() @nogc {
    foreach (x; [1, 2]) {}
}


With:

test.d(3,17): Error: array literal in @nogc function main may cause GC allocation

I suggest to start introducing a small amount of Escape Analysis in D, to support the @nogc attribute for the Program#2.


Eventually even this program could be supported:

// Program#3
void main() @nogc {
    import std.algorithm: filter;
    foreach (x; [1, 2].filter!(x => true)) {}
}



Note that with the []s suffix syntax for fixed-size arrays there is no ambiguity:


// Program#4
void main() @nogc {
    foreach (x; [1, 2]s) {}
}



And this can generate a clean error message (escape of pointer to stack frame fixed-size array):


// Program#5
int[] foo() @nogc {
    return [1, 2]s;
}
void main() {}


See also Issue 10242
@dlangBugzillaToGithub
Copy link
Author

stanislav.blinov commented on 2021-12-08T16:23:42Z

Rewritten relevant parts into contemprary D. With dmd 2.098:

void program2() @nogc {
    foreach (x; [1, 2]) {}
}

import std.array : staticArray;

void program3() @nogc {
    import std.algorithm: filter;
    foreach (x; [1, 2].filter!(x => true)) {} // fails to infer @nogc
    // workaround:
    foreach (x; [1, 2].staticArray[].filter!(x => true)) {}
}

int[] program5() @nogc {
    return [1, 2].staticArray; // detects the escape correctly
}
void main() {}

So I guess the only outstanding enhancement here is to make this infer @nogc:

foreach (x; [1, 2].filter!(x => true)) {}

...if at all possible. If not, I guess this could be closed?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant