Loop unrolling behaviour in GCC
<p>This question is in part a follow up question to <a href="https://stackoverflow.com/questions/37967425/gcc-5-1-loop-unrolling">GCC 5.1 Loop unrolling</a>.</p>

<p>According to the <a href="https://gcc.gnu.org/onlinedocs/gcc-6.1.0/gcc/Optimize-Options.html">GCC documentation</a>, and as stated in my answer to the above question, flags such as <code>-funroll-loops</code> turn on <em>"complete loop peeling (i.e. complete removal of loops with a small constant number of iterations)"</em>. Therefore, when such a flag is enabled, the compiler can choose to unroll a loop if it determines that this would optimise the execution of a given piece of code. </p>

<p>Nevertheless, I noticed in one of my projects that GCC would sometimes unroll loops <strong>even though the relevant flags were not enabled</strong>. For instance, consider the following simple piece of code:</p>

<pre><code>int main(int argc, char **argv)
{
  int k = 0;
  for( k = 0; k &lt; 5; ++k )
  {
    volatile int temp = k;
  }
}
</code></pre>

<p>When compiling with <code>-O1</code>, the loop is unrolled and the following assembly code is generated with any modern version of GCC:</p>

<pre><code>main:
        movl    $0, -4(%rsp)
        movl    $1, -4(%rsp)
        movl    $2, -4(%rsp)
        movl    $3, -4(%rsp)
        movl    $4, -4(%rsp)
        movl    $0, %eax
        ret
</code></pre>

<p>Even when compiling with the additional <code>-fno-unroll-loops -fno-peel-loops</code> to make sure the flags are <strong>disabled</strong>, GCC unexpectedly still performs loop unrolling on the example described above.</p>

<p>This observation leads me to the following closely related questions. Why does GCC perform loop unrolling even though the flags corresponding to this behaviour are disabled? Is unrolling also controlled by other flags which can make the compiler unroll a loop in some cases even though <code>-funroll-loops</code> is disabled? Is there a way to completely disable loop unrolling in GCC (a part from compiling with <code>-O0</code>)?</p>

<p>Interestingly the <strong>Clang</strong> compiler has the expected behaviour here, and seems to only perform unrolling when <code>-funroll-loops</code> is enabled, and not in other cases.</p>

<p>Thanks in advance, any additional insights on this matter would be greatly appreciated!</p>