Search code examples
c++clang

How to tell which functions are evaluated at compilation time?


I'm developing a physics simulation program doing a lot of maths. I'd like to know exactly which functions (or code parts) are evaluated at compilation time.

It there a way to tell? I'm using clang, usually with c++14.


Solution

  • The language has precise rules about which expressions are evaluated at compile-time, and which are not. The technical term for that is constant-evaluated, and there is in fact a utility called std::is_constant_evaluated that can be used to programmatically query whether a particular evaluation of an expression must happen at compile-time or not.

    However, the language is still subject to the as-if rule, which allows the implementation to actually produce a program that evaluates expressions whenever it wants, so long as the program behaves as-if the expressions are evaluated when they are supposed to. In other words, std::is_constant_evaluated() is required to give the right results regardless.

    In practice, an implementation is allowed to produce a program that includes the entire compiler, and evaluates everything at run-time. Or the implementation can calculate all the results that it possibly can, even if it doesn't have to, and store them directly into the program it produces. Again, so long as the resulting program obeys the as-if rule, everything's ok.

    If you want to know which expressions were actually evaluated at compile-time, you'll need to look at the assembly of the particular program generated by the implementation you're using.