November 19, 2023
https://issues.dlang.org/show_bug.cgi?id=24250

          Issue ID: 24250
           Summary: Recognize immediate indexing of array literal to
                    prevent GC allocation
           Product: D
           Version: D2
          Hardware: All
                OS: All
            Status: NEW
          Severity: enhancement
          Priority: P1
         Component: dmd
          Assignee: nobody@puremagic.com
          Reporter: johanengelen@weka.io

Testcase:
```
enum int[3] masks = [1, 2, 3];
int foo(int a) @nogc {
    return masks[a];
}

int foo2(int a) @nogc {
    int[3] m = [1, 2, 3];
    return m[a];
}

int foo3(int a) @nogc {
    return (cast(int[3])[1, 2, 3])[a];
}

int foo4(int a) @nogc {
    return [1, 2, 3][a];  // <-- Error
}
```

Compilation error:
`Error: array literal in `@nogc` function `example.foo4` may cause a GC
allocation`

I think this is correct, because the spec says that an array literal is a dynamic array (https://dlang.org/spec/expression.html#array_literals).

However, it would be nice if the pattern in foo4 is recognized and turned into
foo3 (immediate indexing of array, thus the array does not have to be dynamic),
and no GC allocation is used in foo4.
This does lead to more stack usage in foo4, so there should be an array size
limit for this pattern. But note that foo (with enum) suffers from the same
problem, without clear visibility. (in foo2 and foo3 the potentially large
stack usage is more obvious to the programmer)

--