Hi all,
I wonder what the best way is to achieve compile-time
specialization of code in C. GCC can specialize
functions, and one could try something such as the
following.
static int bar(int x)
{
return x * x * x;
}
int foo(int x)
{
if (x == 3) return bar(3);
return bar(x);
}
This works in this example, but not always, requires writing
pointless code, and it is also errorprone. F
(For clang, I need __builtin_expect, which for GCC produces this
interesting result:
"foo":
mov edx, edi
mov eax, 27
imul edx, edi
imul edx, edi
cmp edi, 3
cmovne eax, edx
ret
)
But I am not so much interested in these small examples, more
on cases where the benefit of specialization materializes
on a larger high-level scales in possibly non-obvious way,
and where I want to have explicit control over it.
One could use templates in C++ or macros, but then this is
rather heavy weight and also rigid as one has to structure the
code around it. I am rather looking for some lightweight
solution such as annotation I could put on the argument or variable
that says: If this is value is known to be a compile-time
constant, please create a specialized code path when optimizing.
(maybe with some limit on recursion), maybe only for specified
parameter ranges.
Or are there other better ways to do this already?
Martin