Compile-time vs. compile-time

ag0aep6g anonymous at example.com
Fri Jan 5 15:38:45 UTC 2018


On 01/04/2018 11:59 PM, H. S. Teoh wrote:
> I wouldn't say that CTFE means that it is forced/guaranteed. But you're
> right that it could be confusing the way I described it.  I added a
> section to clarify that usually the compiler would not use CTFE to
> constant-fold complex expressions, unless the value is required at
> compile-time.
[...]
> Are you sure that's non-CTFE?  Isn't standard constant folding a part of
> CTFE?
Myself, I use "CTFE" only for the forced kind of compile-time evaluation.

This is my train of thought: CTFE is when `__ctfe` is set. Anything else 
would be too confusing. During forced compile-time evaluation, `__ctfe` 
is obviously set. But an optional optimization cannot set `__ctfe`, 
because that might change the value of the optimized expression. And 
that's something an optimization must not do.

Example:
----
int foo() { return __ctfe ? 10 : 20; }
int main() { return foo(); }
----

The program must return 20, no matter how aggressively the compiler 
optimizes.

As far as I can tell, the compilers share this view. For the example, 
they optimize `main` to `return 20;` [1]. So they evaluate `foo()` 
during compilation and use `__ctfe = false`.

The spec's wording isn't as clear as it could be, but can be interpreted 
this way, I think. The relevant statements are [2]:

1) "The __ctfe boolean pseudo-variable [...] evaluates to true at 
compile time, but false at run time".
2) "In order to be executed at compile time, the function must appear in 
a context where it must be so executed".

Unfortunately, the first one says "at compile time" which can very well 
be understood to mean that `__ctfe` should be true during constant 
folding as done by the optimizer.  But then the second statement would 
forbid this optional constant folding, because it doesn't allow 
execution "at compile time" unless the context forces it.

So I'm interpreting "at compile time" to be a synonym for the feature 
called "CTFE". And then it makes perfect sense (to me):

1) "The __ctfe boolean pseudo-variable [...] evaluates to true [during 
CTFE], but false [elsewhere]". -- Makes sense.
2) "In order to be executed [via CTFE], the function must appear in a 
context where [its result must be available during compilation]". -- 
Meaning that anything else isn't CTFE.


[1] https://godbolt.org/g/6xrDF7
[2] https://dlang.org/spec/function.html#interpretation


More information about the Digitalmars-d mailing list