Determine if CTFE or RT
ag0aep6g
anonymous at example.com
Mon Jun 25 10:40:47 UTC 2018
On 06/25/2018 07:47 AM, Mr.Bingo wrote:
> The docs say that CTFE is used only when explicit, I was under the
> impression that it would attempt to optimize functions if they could be
> computed at compile time. The halting problem has nothing to do with
> this. The ctfe engine already complains when one recurses to deep, it is
> not difficult to have a time out function that cancels the computation
> within some user definable time limit... and since fail can simply fall
> through and use the rtfe, it is not a big deal.
>
> The problem then, if D can't arbitrarily use ctfe, means that there
> should be a way to force ctfe optionally!
A D compiler is free to precompute whatever it sees fit, as an
optimization. It's just not called "CTFE" then, and `__ctfe` will be
false during that kind of precomputation.
For example, let's try compiling this code based on an earlier example
of yours:
----
int main()
{
return foo(3) + foo(8);
}
int foo(int i)
{
return __ctfe && i == 3 ? 1 : 2;
}
----
`dmd -O -inline` compiles that to:
----
0000000000000000 <_Dmain>:
0: 55 push rbp
1: 48 8b ec mov rbp,rsp
4: b8 04 00 00 00 mov eax,0x4
9: 5d pop rbp
a: c3 ret
----
As expected, `ldc2 -O` is even smarter:
----
0000000000000000 <_Dmain>:
0: b8 04 00 00 00 mov eax,0x4
5: c3 ret
----
Both compilers manage to eliminate the calls to `foo`. They have been
precomputed. `__ctfe` was false, though, because the term "CTFE" only
covers the forced/guaranteed kind of precomputation, not the optimization.
More information about the Digitalmars-d-learn
mailing list