by comex · 11y ago · 0 comments
Other readers, check it out for yourself with
gcc -g sum.c ; echo 'disas main' | gdb ./a.out
gcc -g -O2 sum.c ; echo 'disas main' | gdb ./a.out
gcc -fverbose-asm -g -Wa,-adhln=sum.lst sum.cAs a human, I can see that the loop has no effects except to increase s by 1 each of NUMBER times, and that the result of doing so would increase s by 1 * NUMBER, and that s started as 0, so s ends up as NUMBER. (Also the loop variable i is incremented NUMBER times so it ends up as NUMBER too, but its value is never referred to again.)
I'm wondering how the optimizer observed and represented these facts, and how much more general its attempts at optimizing this loop were.
LLVM also has a pass dedicated to detecting loop idioms: http://llvm.org/docs/doxygen/html/LoopIdiomRecognize_8cpp_so...
(I'm not at all familiar with how GCC is architected, sorry)