[Clang] Inconsistent optimization around constant 1.0f
Given a simple switch which uses the constant 1.0f in case 0, the optimization is different than with any another constant, e.g. 0.0f.
#include <utility>
auto Switch(long i, float f)
{
switch(i)
{
case 0:
return CASE_O * f;
case 1:
return 2.0f * f;
case 2:
return 3.0f * f;
case 3:
return 5.0f * f;
case 4:
return 7.0f * f;
case 5:
return 11.0f * f;
case 6:
return 13.0f * f;
case 7:
return 17.0f * f;
}
std::unreachable();
}
Compiled with -std=c++23 -O3 -DCASE_O=1.0f and -std=c++23 -O3 -DCASE_O=0.0f respectively. The former leads to a jump for each of the 8 cases, while the latter is able to optimize to a single multiplication with a constant defined in a table. The latter appears to be more efficient, especially if it wasn't 8 different cases but 256 or more.
It seems to me that the 1.0f * f is optimized to f before the switch could optimized to table[i] * f. This also happens with -1.0f.
See https://godbolt.org/z/K4EdfzW4q
Side note: The example above is a simplified reproducer of what I observed in a more complex scenario, so optimizing it myself to table[i] * f is not a solution I can use.
I think the 1.0f part is a red herring; it will just fold that case to f. If you write the equivalent case with integers, do you see the same optimization?
Changing the example to use ints instead of floats does indeed not yield the same optimization. https://godbolt.org/z/PhzaGvajf The function remains with has 8 different jump labels. Each different case has different instructions, not just a multiplication with a constant. Though I would assume that all these jumps and different instructions would be better with a single multiplication to a constant defined in an array.
I made a quick-bench to test this: https://quick-bench.com/q/qNIt4_rLmZQ_roAoQvvCRvUBIuw For integers, an array is 2.2 times faster than the switch. For floats, using 0.0f as case 0, switch and array are the same. For floats, using 1.0f as case 0, the array is 2 times faster than the switch.
I think the problem is a premature folding of 1.0f * f to f or an int constant multiplication to a differen instruction, which prevents the switch being optimized to an array lookup.