program-with-loop

Search IconIcon to open search

Source: samek-embedded
See also: General considerations for non-linear control flow

Code and instructions

Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
int main()
{
  int counter = 0;
  
  while (counter < 10) {
  ++counter;
  }
  
  return 0;
}

Disassembly

Comparison

Original structureOptimised structure
  • In the compiled code, the execution of the while loop is different than that given by the code.
  • However, the effect of the loop on the calculation remains the same.
  • The compiler proposes this order of instructions for increased efficiency, e.g. the BLT.Ninstruction steps back to ++counter instead of forwards, which allows the PC register to naturally increment without having to use another branch instruction.

Compare

Before
After

CMP modifies the APSR (Application Program Status Register)

N bit (negative) is set, because R0 - #10 is negative