digitalmars.D - Did Walter's pure optimization ever make it into dmd?
In this nice article Walter described how immutable and pure
allow for optimizations:
http://www.drdobbs.com/architecture-and-design/optimizing-immutable-and-purity/228700592
```For these examples, I'll use the D programming language
compiler that is currently under development. (...)
But what if bar is pure?
pure int bar(int);
int foo(int i)
{
return bar(i) + bar(i);
}
Now the assembler output is:
push EAX ; save argument i on stack
call bar ; call bar(i)
add EAX,EAX ; double result
pop ECX ; clean stack
ret ; return to caller
bar(i) is called only once```
I've checked whether multiple calls to pure functions get
optimized, and it seems like they *never* do. I've tried
different versions of dmd with optimizaiton flags on/off, and
also LDC/GDC.
In the case of lazy parameters (which get lowered to delegates
that can be inferred to be pure), this can lead to doing the same
string concatenation multiple times every time you use it.
```
import std.stdio: writeln;
void log(lazy string str)
{
if (str.length > 0) writeln(str.ptr); //the lazy 'str' gets
evaluated twice here
}
void main(string[] args) {
log("first arg: "~args[0]);
}
```
So were these optimizations never finished and put into dmd? Or
is there a bug that prevents these optimizations from happening?
Apr 02 2018
On 04/02/2018 10:52 AM, Dennis wrote:
```For these examples, I'll use the D programming language compiler that
is currently under development. (...)
But what if bar is pure?
pure int bar(int);
int foo(int i)
{
return bar(i) + bar(i);
}
Now the assembler output is:
push EAX ; save argument i on stack
call bar ; call bar(i)
add EAX,EAX ; double result
pop ECX ; clean stack
ret ; return to caller
bar(i) is called only once```
I've checked whether multiple calls to pure functions get optimized, and
it seems like they *never* do. I've tried different versions of dmd with
optimizaiton flags on/off, and also LDC/GDC.
The function also needs the `nothrow` attribute. And you have to compile
with `-O -release`.
https://run.dlang.io/is/GWnUPH
Apr 02 2018
On Monday, 2 April 2018 at 11:33:29 UTC, ag0aep6g wrote:On 04/02/2018 10:52 AM, Dennis wrote: The function also needs the `nothrow` attribute. And you have to compile with `-O -release`.Aha, I presume the release flag is necessary in case there is a `debug {writeln("...");}` in the function. Is there a list of things the -release flag changes? There's only a brief description here: https://dlang.org/dmd-windows.html And it seems like there are a lot more subtle differences. Also, I wonder why it has to be nothrow. In which cases does it make a difference? I think these two are identical for example: try {int x = sqrt(-1) + sqrt(-1)} catch (ArithmeticException e) {} try {int x = 2*sqrt(-1)} catch (ArithmeticException e) {}
Apr 03 2018








Dennis <dkorpel gmail.com>