Search code examples
c++compiler-constructionvariadic-templatesconstexprcompile-time

Possibility of Iteration For Compile-Time Computations


In my understanding compile-time computation is anything that can be computed by the compiler instead of that portion being computed during program execution to increase performance. Iterative computation is possible when a program executes but it is not allowed during compile-time computations. One troublesome and specific example is Variadic Templates where one naturally thinks of iteration to handle various types provided yet the standard and compilers force programmers to handle them recursively.

In general, all compile-time computations are handled via recursion rather than iteration. As far as I know constexpr functions expected to be computed at compile-time is supposed to be recursive as well. What makes iteration forbidden for anything that is compile-time?


Solution

  • When I implemented elimination of constant subexpressions as optimizations in Hammer, the issue turned out to be that recursion basically already happens during code generation. You do not really need to define variables, because they simply get replaced with constants.

    On the other hand, if you are trying to run a loop, not only do you need to have code that not just executes the operations on constants at runtime, but is a full-blown interpreter of your language. You need to be able to declare variables, set and receive their values (as loop counters), and even worse, you need to detect endless loops so your compiler won't hang (I mean, while(true); is a perfectly constant expression).

    So in short, due to the nature of parsers, ASTs and optimizers, it is simply easier to recursively evaluate parts at compile time than it is to implement full control flow and implement loops and variable manipulation.