[LLVMdev] Strange loop unrolling problem (partially solved)

Pertti Kellomäki pertti.kellomaki at tut.fi
Mon Apr 27 05:26:02 PDT 2009

A short while ago I wrote about the strange loop unrolling
behavior we encountered. The problem was that with -O3,
the following loop does not get unrolled if the ifdef'ed
dead code is not present.

extern volatile int v1;

int unroll() {
   int i;
   int v2 = 0;

   for(i = 0; i < 3; i++) {
     if (i == v2) { v1 = 1000;
     } else { v1 = 1001;
#ifdef MODIFY_V2
     // Dead code
     if (i == 3) { v2 = v2 + 1; }
   return v2;

It turns out that the reason unrolling does not work
in the simpler case is that some optimization pass figures
out that the `then' branch of the if is always executed, and
lifts it above the loop header. This confuses the loop trip
count code, and unrolling does not take place. The dead code
simply makes the optimization pass give up on the loop so
the structure is preserved.

Any ideas which pass does the lifting of the `then' branch?
I have my eyes no jump threading, but I don't understand the
loop transformations well enough yet to know if it simply
makes the problem manifest itself rather than creating it.

Unrolling is absolutely crucial for the application we have.
The loops that do not get unrolled are inner loops in a DSP
application, and unless we get big fat basic blocks, we don't
get much speedup from the VLIW-like machine we are targeting.

More information about the llvm-dev mailing list