Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C compiler optimize loop by running it

Can a C compiler ever optimize a loop by running it?

For example:

int num[] = {1, 2, 3, 4, 5}, i;
for(i = 0; i < sizeof(num)/sizeof(num[0]); i++) {
  if(num[i] > 6) {
    printf("Error in data\n");
    exit(1);
  }
}

Instead of running this each time the program is executed, can the compiler simply run this and optimize it away?

like image 401
Ariel Avatar asked Mar 06 '26 16:03

Ariel


1 Answers

Let's have a look… (This really is the only way to tell.)

Fist, I've converted your snippet into something we can actually try to compile and run and saved it in a file named main.c.

#include <stdio.h>

static int
f()
{
  const int num[] = {1, 2, 3, 4, 5};
  int i;
  for (i = 0; i < sizeof(num) / sizeof(num[0]); i++)
    {
      if (num[i] > 6)
        {
          printf("Error in data\n");
          return 1;
        }
    }
  return 0;
}

int
main()
{
  return f();
}

Running gcc -S -O3 main.c produces the following assembly file (in main.s).

        .file   "main.c"
        .section        .text.unlikely,"ax",@progbits
.LCOLDB0:
        .section        .text.startup,"ax",@progbits
.LHOTB0:
        .p2align 4,,15
        .globl  main
        .type   main, @function
main:
.LFB22:
        .cfi_startproc
        xorl    %eax, %eax
        ret
        .cfi_endproc
.LFE22:
        .size   main, .-main
        .section        .text.unlikely
.LCOLDE0:
        .section        .text.startup
.LHOTE0:
        .ident  "GCC: (GNU) 5.1.0"
        .section        .note.GNU-stack,"",@progbits

Even if you don't know assembly, you'll notice that the string "Error in data\n" is not present in the file so, apparently, some kind of optimization must have taken place.

If we look closer at the machine instructions generated for the main function,

xorl    %eax, %eax
ret

We can see that all it does is XOR'ing the EAX register with itself (which always results in zero) and writing that value into EAX. Then it returns again. The EAX register is used to hold the return value. As we can see, the f function was completely optimized away.

like image 169
5gon12eder Avatar answered Mar 08 '26 07:03

5gon12eder