No CTFE of function

Cecil Ward via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Aug 26 16:53:36 PDT 2017


On Saturday, 26 August 2017 at 23:49:30 UTC, Cecil Ward wrote:
> On Saturday, 26 August 2017 at 18:16:07 UTC, ag0aep6g wrote:
>> On Saturday, 26 August 2017 at 16:52:36 UTC, Cecil Ward wrote:
>>> Any ideas as to why GDC might just refuse to do CTFE on 
>>> compile-time-known inputs in a truly pure situation?
>>
>> That's not how CTFE works. CTFE only kicks in when the 
>> *result* is required at compile time. For example, when you 
>> assign it to an enum. The inputs must be known at compile 
>> time, and the interpreter will refuse to go on when you try 
>> something impure. But those things don't trigger CTFE.
>>
>> The compiler may choose to precompute any constant expression, 
>> but that's an optimization (constant folding), not CTFE.
>
> I think I understand, but I'm not sure. I should have explained 
> properly. I suspect what I should have said was that I was 
> expecting an _optimisation_ and I didn't see it. I thought that 
> a specific instance of a call to my pure function that has all 
> compile-time-known arguments would just produce generated code 
> that returned an explicit constant that is worked out by CTFE 
> calculation, replacing the actual code for the general function 
> entirely. So for example
>
>     auto foo() { return bar( 2, 3 ); }
>
> (where bar is strongly pure and completely CTFE-able) should 
> have been replaced by generated x64 code looking exactly 
> literally like
>     auto foo() { return 5; }
> expect that the returned result would be a fixed-length literal 
> array of 32-but numbers in my case (no dynamic arrays anywhere, 
> these I believe potentially involve RTL calls and the allocator 
> internally).

I was expecting this optimisation to 'return literal constant 
only' because I have seen it before in other cases with GDC. 
Obviously generating a call that involves running the algorithm 
at runtime is a performance disaster when it certainly could have 
all been thrown away in the particular case in point and been 
replaced by a return of a precomputed value with zero runtime 
cost. So this is actually an issue with specific compilers, but I 
was wondering if I have missed anything about any D general rules 
that make CTFE evaluation practically impossible?


More information about the Digitalmars-d-learn mailing list