Force Clang not to unroll a loop
08:15 30 Jul 2024

I have a loop of the form

for (int i = 0; i < SOME_CONSTANT; ++i) {
    // Do some stuff involving `i`.
}

which Clang is partially unrolling to do two passes at a time. I need it to not be unrolled at all.

One option is to add an inline assembly barrier to prevent Clang/LLVM from seeing how i is modified:

for (int i = 0; i < SOME_CONSTANT; ++i) {
    asm volatile("" : "=r"(i) : "0"(i));
    // Do some stuff involving `i`.
}

But I'm wondering if there is a clearer way without resorting to such hacks.

c optimization clang llvm