D issues are now tracked on GitHub. This Bugzilla instance remains as a read-only archive.
Issue 12808 - Small amount of escape analysis to allow more @nogc functions
Summary: Small amount of escape analysis to allow more @nogc functions
Status: NEW
Alias: None
Product: D
Classification: Unclassified
Component: dmd (show other issues)
Version: D2
Hardware: All All
: P4 enhancement
Assignee: No Owner
URL:
Keywords:
Depends on:
Blocks:
 
Reported: 2014-05-26 21:53 UTC by bearophile_hugs
Modified: 2024-12-13 18:21 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 bearophile_hugs 2014-05-26 21:53:34 UTC
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
Comment 1 Stanislav Blinov 2021-12-08 16:23:42 UTC
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?
Comment 2 dlangBugzillaToGithub 2024-12-13 18:21:04 UTC
THIS ISSUE HAS BEEN MOVED TO GITHUB

https://github.com/dlang/dmd/issues/18832

DO NOT COMMENT HERE ANYMORE, NOBODY WILL SEE IT, THIS ISSUE HAS BEEN MOVED TO GITHUB