Optimizing Immutable and Purity

Jason House jason.james.house at gmail.com
Sun Dec 28 10:06:24 PST 2008

Andrei Alexandrescu wrote:

> Jason House wrote:
>> Andrei Alexandrescu Wrote:
>>> There are two issues here. One is that the const guarantees that foo
>>> does not legally change a, so it is useful for an optimization (e.g.
>>> assume that a == 5 after the call to foo). The second issue is that
>>> compilers often assume that a function call may change the stack of the
>>> caller in an arbitrary way. I think it is safe to lift that assumption
>>> for D programs and consider a functions' automatic variables as private
>>> to the function.
>>> Andrei
>> You have to be extremely careful with this kind of thing.  If any calls
>> are made with a mutable &a before the call to foo, that optimization can
>> no longer be performed. Also, if a's type changes and used a custom
>> constructor, then that optimization is unreliable for anything other than
>> taking the object's address. If a mutable reference is leaked, all
>> function calls become suspect...
> Care goes without saying.
> Andrei

The underlying question the optimizer must answer when doing this kind of optimization is "are there any other mutable references"?  My whole set of caveats above is all about answering that question.  Once upon a time, I had convinced myself that a complete const system would address that.  Maybe when it's time to come back and do a complete solution to scope delegates and escape analysis, this kind of thing could be explored further.

More information about the Digitalmars-d mailing list