Why is the lower test loop preferred?

I heard someone say that compilers often move loop conditions to the bottom of the loop. That is, loops like these:

while (condition) {
    ...
}

changes to:

if (condition) {
     do {
         ...
     } while (condition);
}

relatively machine-independent optimization, why is the latter preferable?

+5
source share
3 answers

Without compiler optimization, the first loop goes to assembler as follows:

  @@:
cmp ... ; or test ...
jz @f

...
jmp @b

While the second cycle goes on to the following:

jmp bottom

  @@:
...

  bottom:
cmp ... ; or test ...
jz @b

Conditional branching is usually predicted, so the first method could potentially lead to an increase in pipeline / instruction cache flows.

, , (2N), , jump (N+1).

. . 88 .

+7

. :

    jmp $test;
$loop:
    ; loop statements
$test:
    test <condition>;
    branch-true $loop;

:

$loop:
    test <condition>;
    branch-false $end;
    ; loop statements
    branch loop;
$end:

. , , do/while.

0

- , . .

Many command sets, such as x86, ARM, MIPS, provide conditional jump / jump commands. Will the transition take place depending on the condition specified in the instructions.

Therefore, compilers prefer such instructions and move the condition to the end of the loop to use the instruction.

0
source

All Articles