|Posted by bearophile||PermalinkReply|
Days ago I have shown the idea for a possible feature (that may be seen as a better version of __builtin_constant_p() of GCC): a traits that at compile time inside a function allows to know if each of the argument values is known at compile-time (every time such information isn't available, it defaults to "false", that means such argument is not known at compile time). Such information can be used inside the function with static ifs, to avoid some run-time computations.
A function with N arguments that uses such feature may be seen as a template that generates up to 2^N instantiations in the binary (but usually arguments are few and often you don't need to test if each of them is a compile time constant, so usually if you use this feature you don't have more than 2 or 4 different instantiations). I'd like to know if such feature can be implemented.
This feature in practice allows for a manual form of partial compilation. It moves the burden of partial compilation from the compiler to the programmer. Generally moving work to the programmer isn't a good idea, but in this case I think it's acceptable because implementing partial compilation in compilers is hard, while I think this feature is much simpler to implement, and the programmer is able to manually optimize critical functions.
Now I've thought about another related possible feature. Inside a function (maybe with another trait) it may be interesting to know, at compile time, if the result of the function itself is being used (this feature is useful only for functions with side effects, so it's disallowed inside pure functions). If you know the result isn't used, then you don't need to compute it; so this trait may be used with a static if to avoid some useless computations.
Generally given a function, different parts of the code may use its return value or not use it, so this feature may produce two compiled versions of the function inside the binary. This is acceptable (so this feature can also be seen as a limited form of return overload, but you define a single function).
(The function attribute warn_unused_result of GCC is something quite different).