如果迭代次数在编译时未知,GCC如何展开循环?

当我发现选项-funroll-all-loops时,我正在读取optimization options for GCC.

其描述如下:

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’

如果迭代次数在编译时未知,编译器如何展开循环?编译器是否需要这些信息来展开?它生成哪些相应的C代码,如果通常使程序运行得更慢,在什么情况下可能会有用?

最佳答案

in what contexts could this be useful if it usually makes the programs run more slowly?

那么他们假设如果你选择这个选项,你知道你在做什么,如果你不这样做不应该使用这个选项.

什么是gcc要做,我使用这个示例程序:

#include <stdio.h>

void f(int j )
{
  for( int k = 0; k < j; ++k )
  {
    printf( "%d\n", k ) ;
  }
}

并使用godbolt进行测试,并根据剩余的迭代次数生成跳转表(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

转载注明原文:如果迭代次数在编译时未知,GCC如何展开循环? - 代码日志