While we're on the subject of escape analysis...
Michel Fortin
michel.fortin at michelf.com
Fri Oct 31 04:20:30 PDT 2008
On 2008-10-30 22:20:33 -0400, Benji Smith <dlanguage at benjismith.net> said:
> Consider this code:
>
> class MyObject {
>
> public int x() {
> return obj.a().b().c().d();
> }
>
> public MyObject a() { ... }
> public MyObject b() { ... }
> public MyObject c() { ... }
> public int d() { ... }
>
> }
>
> This code creates three temporary objects that cannot possibly escape
> the scope of the "x" function. Although the user might be content with
> those object being allocated on the heap, the compiler could decide to
> allocate them on the stack instead, and the programmer would be
> blissfully unaware of the switcharoo.
>
> [...]
> Thoughts?
I made a proposal in the other thread that functions could specify the
requested scope of any parameter used so that the compiler could decide
if variables need to be allocated on the stack or on the heap. This
could apply to return values too, but probably only when returning a
reference to one of the arguments.
In this case MyObject isn't final, and thus the object returned may be
of a derivative class, which could be of any size, which you can't
really return on the stack (especially since you're supposed to return
a reference, not copy the object itself). It should still be possible
to declare the return value as scope (so that you can put a reference
to a scope argument in the object), but optimization by placing the
class on the stack doesn't seem likely to be possible since the object
is created in a higher scope that will disappear when returning the
value.
That said, if the object return a pointer to itself, no allocation is
necessary. Or if the compiler can inline the functions, it may be
possible for it to optimize away any dynamimc allocation.
--
Michel Fortin
michel.fortin at michelf.com
http://michelf.com/
More information about the Digitalmars-d
mailing list