Course: Computer Architectures
Source lesson: ARM Branches and Control Flow (PDF pages 16-28)

1. Loop translations

A while loop tests before each iteration:

    B test
loop:
    ; body
test:
    CMP r0, #N
    BNE loop

A do-while tests after the body:

loop:
    ; body
    CMP r0, #N
    BNE loop

A direct for (i=0; i<N; i++) translation is:

MOV r0, #0
loop:
    CMP r0, #N
    BHS exit
    ; body
    ADD r0, r0, #1
    B loop
exit:

When only the count matters, counting down combines decrement and test:

MOV r0, N
loop:
    ; body
    SUBS r0, r0, #1
    BNE loop

CBNZ cannot replace the final BNE here because its target is backward.

2. Branch penalty

A pipeline may fetch instructions after a branch before the branch condition is resolved. If the branch is taken, those wrong-path instructions must be discarded. The resulting lost work is the branch penalty, a form of control hazard connected to control hazards.

The penalty is not a universal constant: it depends on pipeline depth, when the branch resolves and whether prediction is used.

3. IT conditional execution

An IT block conditionally executes up to four following instructions without changing the PC:

CMP   r0, r1
ITE   GE
SUBGE r2, r0, r1
SUBLT r2, r1, r0

This computes abs(r0-r1). The T and E pattern describes the true and inverse-condition instructions. The first instruction is the true case, the false condition is the inverse, and a branch may appear only as the final instruction in the block.

Conditional execution can avoid a taken-branch penalty for a short choice, but it is not automatically faster: executing a longer block conditionally can have its own cost, and modern ARM instruction-set rules restrict IT usage in some contexts.

Retrieval checks

Q: Why does a do-while body execute at least once?
A: Its condition is tested after the body.

Q: Why does the countdown loop need SUBS rather than SUB?
A: SUBS updates Z, allowing BNE to test whether the counter reached zero.

Q: What is the difference between a branch penalty and a loop iteration?
A: An iteration is program work; a branch penalty is pipeline work discarded because control-flow resolution arrived late.