[Issue 18788] static arrays with a length specified at runtime should dynamically allocate on the stack

d-bugmail at puremagic.com d-bugmail at puremagic.com
Tue Aug 14 10:47:22 UTC 2018


https://issues.dlang.org/show_bug.cgi?id=18788

ZombineDev <petar.p.kirov at gmail.com> changed:

           What    |Removed                     |Added
----------------------------------------------------------------------------
                 CC|                            |petar.p.kirov at gmail.com

--- Comment #6 from ZombineDev <petar.p.kirov at gmail.com> ---
LDC has a pass[1] that does escape analysis for class instances and dynamic
arrays and stack allocates them when possible. Sadly they do this on the LLVM
IR level, so their solution can't be easily upstream-ed to dmd's frontend.

Static arrays can't have their length specified at run-time, as it's part of
their type. (Just like you can't specify template arguments at run-time. The
only thing resembling providing compile-time arguments at run-time is simply
instantiating various alternatives at compile-time and selecting one of them at
run-time.) What you can do is an array-like struct that wraps alloca.
Compile-time safety is out of the question, but it could try to check if it can
fit in the remaining stack space minus a several pages. Even so, it would be
quite brittle and heavily dependent on platform and run-time specifics (e.g.
querying the fiber stack size, when not running on the native thread stack).

AFAIK, `scope` is currently inferred only for value types (scalars and static
arrays) with -dip1000. Perhaps the inference can be extended to cover dynamic
arrays and classes as well.

One thing that we must be careful about is that the array memory management [2]
built on top of the GC has certain assumptions like looking for block metadata
(e.g. array capacity) on its heap. These assumptions may fail if the compiler
promotes the array on the stack. But if all of druntime's lifetime code is
template-ized, in theory the compiler should be able to see through it and
detect that the array .length getter property is trivially scope-friendly,
while the setter is not. Don't know how .capacity should be handled.

[1]:
https://github.com/ldc-developers/ldc/blob/16f37466fe918e0824a3b2db239ba5a7ce5a33cc/gen/passes/GarbageCollect2Stack.cpp

[2]:
https://github.com/dlang/druntime/blob/bb7e1c0991c0ae43520e67c91d0b7b0d8d315d2e/src/rt/lifetime.d#L1442

--


More information about the Digitalmars-d-bugs mailing list