Search code examples
c#assemblyx86micro-optimization.net-native

Why does .NET Native compile loop in reverse order?


I'm working on optimization techniques performed by the .NET Native compiler. I've created a sample loop:

        for (int i = 0; i < 100; i++)
        {
            Function();
        }

And I've compiled it with Native. Then I disassembled the result .dll file with machine code inside in IDA. As the result, I have:

IDA output

(I've removed a few unnecessary lines, so don't worry that address lines are inconsistent)

I understand that add esi, 0FFFFFFFFh means really subtract one from esi and alter Zero Flag if needed, so we can jump to the beginning if zero hasn't been reached yet.

What I don't understand is why did the compiler reverse the loop?

I came to the conclusion that

LOOP:
add esi, 0FFFFFFFFh
jnz LOOP

is just faster than for example

LOOP:
inc esi
cmp esi, 064h
jl LOOP

But is it really because of that and is the speed difference really significant?


Solution

  • inc might be slower than add because of the partial flag update. Moreover add affects the zero flag so you don't need to use another cmp instruction. Just jump directly.

    This is one famous type of loop optimization

    reversal: Loop reversal reverses the order in which values are assigned to the index variable. This is a subtle optimization which can help eliminate dependencies and thus enable other optimizations. Also, certain architectures utilize looping constructs at Assembly language level that count in a single direction only (e.g. decrement-jump-if-not-zero (DJNZ)).

    You can see the result for other compilers here.