Optimize away immediately-called delegate literals?

Nick Sabalausky a at a.a
Mon Mar 12 20:08:00 PDT 2012


"Peter Alexander" <peter.alexander.au at gmail.com> wrote in message 
news:thetmhnnbeepmxgusntr at forum.dlang.org...
> On Sunday, 11 March 2012 at 06:49:27 UTC, H. S. Teoh wrote:
>> On Sun, Mar 11, 2012 at 01:29:01AM -0500, Nick Sabalausky wrote:
>>> Suppose you have a delegate literal and immediately call it:
>>>
>>> auto a = x + (){ doStuff(); return y; }() + z;
>>>
>>> Does DMD ever (or always?) optimize away a delegate if it's executed
>>> immediately and never stored into a variable? If not, can it, and
>>> would it be a simple change? Is something like this already on the
>>> table?
>> [...]
>>
>> I've always wondered about whether delegates passed to opApply ever get
>> inlined.
>
> Don't wonder. Find out!
>
> import std.stdio;
> void doStuff() { writeln("Howdy!"); }
> void main() {
>     int x = 1, y = 2, z = 3;
>     auto a = x + (){ doStuff(); return y; }() + z;
>     writeln(a);
> }
>
> $ dmd test.d -O -release -inline
>
> __Dmain:
> 000000010000106c pushq %rbp
[...]

I keep forgetting I can do that. ;)

>
> In short. No! It doesn't currently inline in this case.
>
> Even if the lambda just returns a constant, it doesn't get inlined.

Darn.

The reason this came up is I've gotten back into some more work on HaxeD 
(Haxe -> D converter). Haxe allows statements to be used as expressions. For 
example:

x = 5 + if(cond) { foo(); 1; } else 2;

At the moment, I'm converting those by just tossing them into an 
immediately-called anonymous delegate:

x = 5 + (){ ...blah... }();

But as I was afraid of, there's a performance hit with that. So eventually, 
I'll have to either do some fancier reworking:

// Something like
typeof(1) __tmp1;
if(cond) { foo(); __tmp1 = 1; } else __tmp1 = 2;
x = 5 + __tmp1;

...which might even run into some problems with order-of-execution. Or 
delegate inlining would have to get added to DMD.

Now that I actually look (heh :) ), it looks like there's an old Buzilla 
issue for it with an apperently overly-limited patch:

http://d.puremagic.com/issues/show_bug.cgi?id=4440

Unfortunately, according to Brad Roberts in the last comment: "Getting 
delegate inlining in dmd is going to take serious work." (Ugh, I wish 
Windows had an easy way to copy/paste text *without* the styling.)




More information about the Digitalmars-d mailing list