I was reading the optimization options for GCC when I found the option -funroll-all-loops
.
Its description reads:
Unroll all loops, even if their number of iterations is uncertain when the loop is entered. This usually makes programs run more slowly. '-funroll-all-loops' implies the same options as '-funroll-loops'
How can the compiler unroll a loop if its number of iterations is unknown at compile time? Doesn't the compiler need this information to unroll it? What corresponding C code does it generate, and in what contexts could this be useful if it usually makes the programs run more slowly?
in what contexts could this be useful if it usually makes the programs run more slowly?
Well they are assuming if you choose this option you know what you are doing, if you don't you should not use this option.
what is gcc going to do, well I used this sample program:
#include <stdio.h>
void f(int j )
{
for( int k = 0; k < j; ++k )
{
printf( "%d\n", k ) ;
}
}
and tested it with godbolt and it generates a jump table based on the number of iterations left (see it live):
cmpl $1, %ebp
movl $1, %ebx
je .L1
testl %r12d, %r12d
je .L27
cmpl $1, %r12d
je .L28
cmpl $2, %r12d
je .L29
cmpl $3, %r12d
je .L30
cmpl $4, %r12d
je .L31
cmpl $5, %r12d
je .L32
cmpl $6, %r12d
je .L33