Bug 13093 – D ABI change for guaranteed efficient return of fixed size array
Status
RESOLVED
Resolution
FIXED
Severity
normal
Priority
P1
Component
dlang.org
Product
D
Version
D2
Platform
All
OS
All
Creation time
2014-07-11T08:16:00Z
Last change time
2015-02-18T03:40:19Z
Keywords
pull
Assigned to
nobody
Creator
bearophile_hugs
Comments
Comment #0 by bearophile_hugs — 2014-07-11T08:16:51Z
I suggest to change the D ABI to make code like this avoid an array copy in 100% of the cases (without inlining, and regardless the optimization levels, and in all D compilers):
ubyte[10000] foo() nothrow @safe {
typeof(return) data;
// Some code here.
return data;
}
void main() nothrow {
immutable data = foo();
}
That means that code is equivalent to (note the need for the explicit cast):
void foo(ref ubyte[10000] __data) nothrow @safe {
__data[] = 0;
// Some code here.
}
void main() nothrow {
ubyte[10000] __data = void;
foo(__data);
immutable data = cast(immutable ubyte[10000])__data;
}
If the returned fixed-size array is very small (like one or two CPU words, or perhaps even three), the new ABI can specify it's returned by value in registers.
In my @nogc code I'd like to use fixed-size arrays, so it's nice to be sure they are _always_ returned efficiently, and at the same time keep a nice syntax that allows me to tag the result as immutable (and more DRY code that avoids to repeat ubyte[10000] more than once as it happens in the second program).
Dmitry Olshansky has commented:
http://forum.dlang.org/thread/[email protected]
> IMO this is a good idea and it pretty much NRVO/RVO for structs extended
> to fixed-size arrays (which more or less a special kind of struct).
> Since C/C++ do not have fixed-size arrays passed by value I see no
> damage to ABI compatibility.
Comment #1 by k.hara.pg — 2014-07-11T09:36:04Z
It's already supported, but not explicitly described in ABI page.
From http://dlang.org/abi
Return Value
...
* 1, 2 and 4 byte structs are returned in EAX.
* 8 byte structs are returned in EDX,EAX, where EDX gets the most significant half.
* For other struct sizes, the return value is stored through a hidden pointer passed as an argument to the function.
...
Normally static arrays are treated as the same size structs, so ubyte[1000] is always returned through hidden pointer.
https://github.com/D-Programming-Language/dlang.org/pull/611
Comment #2 by k.hara.pg — 2014-07-11T09:39:01Z
You can test it by the code.
void* p;
ubyte[10000] foo() nothrow {
typeof(return) data;
p = &data;
return data;
}
void main() nothrow {
immutable data = foo();
assert(p == &data);
}
Comment #3 by github-bugzilla — 2014-11-27T12:50:32Z