Course: Computer Architectures
Source lesson: ARM Branches and Control Flow (PDF pages 9-15)
1. Compare, then branch
CMP performs a subtraction for the purpose of setting flags but does not save the subtraction result.
CMP r0, #18
BEQ equal_caseBEQ checks Z=1; it does not compare the registers itself.
2. Conditions
| Condition | Meaning | Main flag rule |
|---|---|---|
EQ / NE | equal / not equal | Z=1 / Z=0 |
BLO / BHS | unsigned lower / higher-or-same | C=0 / C=1 |
BHI / BLS | unsigned higher / lower-or-same | C=1 and Z=0 / C=0 or Z=1 |
BLT / BGE | signed lower / greater-or-equal | N != V / N = V |
BGT / BLE | signed greater / lower-or-equal | signed relation plus Z |
Use unsigned conditions for sizes, addresses and counters. Use signed conditions for mathematical values that can be negative.
3. SUB versus SUBS
SUBS r1, r0, #0xFF
BLO lowerThe S suffix updates the flags. A plain SUB normally does not, so a later conditional branch could inspect stale flags. CMP is useful when only the flags are needed.
4. Unsigned versus signed example
For 8-bit values 0xFF and 1:
- unsigned:
255 < 1is false, soBLOis not taken; - signed:
-1 < 1is true, soBLTis taken.
The signed result requires sign extension when stored in a 32-bit ARM register; raw 0x000000FF is still 255.
5. CBZ and CBNZ
CBZ r0, exit
CBNZ r0, loopThese branch directly on whether a register is zero. They do not modify flags, use only r0-r7, and support short forward branches. They are therefore not a general replacement for CMP plus a conditional branch.
Retrieval checks
Q: Which instruction checks r0 == 0 without changing flags?
A: CBZ r0, label.
Q: Why is BLO wrong for a signed comparison?
A: It uses the unsigned carry relationship rather than the signed N/V relationship.
Q: What must be true before BNE can reliably follow SUBS?
A: SUBS must be the instruction whose zero flag the branch is meant to test, and no intervening instruction may overwrite the flags.