Reading Arm assembly
Enough Thumb-2 to read compiler output, check volatile and find a fault.
Why read assembly at all
You will rarely write assembly, but reading it is a core embedded skill. The disassembly is the only ground truth for questions like: did volatile keep this read inside the loop? Did this function get inlined? Why is this ISR 40 cycles longer than expected? Where exactly did the HardFault happen? Interviewers often show a few lines of Arm assembly and ask what they do.
This lesson covers enough Thumb-2 (the instruction set of every Cortex-M) to follow compiler output.
Registers
| Register | Role |
|---|---|
r0–r3 | Arguments and return value; scratch (caller-saved) |
r4–r11 | General purpose; preserved across calls (callee-saved) |
r12 (ip) | Scratch, used by the linker for veneers |
r13 (sp) | Stack pointer (MSP or PSP) |
r14 (lr) | Link register: return address after bl |
r15 (pc) | Program counter |
xPSR | Flags (N, Z, C, V), exception number, Thumb bit |
The flags: N negative result, Z zero result, C carry (or "no borrow" after a subtraction), V signed overflow.
The instructions you will see most
Arm is a load-store architecture: arithmetic works only on registers, and memory is reached only by loads and stores.
| Instruction | Meaning |
|---|---|
movs r0, #5 | r0 = 5 (s suffix: also set flags) |
mov r1, r0 | r1 = r0 |
ldr r0, [r1] | r0 = 32-bit word at address r1 |
ldr r0, [r1, #8] | r0 = word at r1 + 8 (a struct member) |
ldrb / ldrh / ldrsb | Load byte / halfword / signed byte |
str r0, [r1, #4] | Store word r0 at r1 + 4 |
ldr r0, =0x40020014 | Pseudo-instruction: load a constant (assembled as a PC-relative load from a nearby "literal pool") |
adds r0, r1, r2 | r0 = r1 + r2, setting flags |
subs, muls, sdiv, udiv | Subtract, multiply, divide (M3 and up) |
ands, orrs, eors, bics | AND, OR, XOR, AND NOT (bit clear) |
lsls, lsrs, asrs | Logical shift left/right, arithmetic shift right |
cmp r0, #10 | Compute r0 − 10 and set flags, discard result |
tst r0, #4 | Compute r0 AND 4 and set flags |
b label | Branch |
beq bne blt bge bhi bls | Branch if equal, not equal, signed less, signed ≥, unsigned higher, unsigned lower-or-same |
bl func | Branch with link: call (return address in lr) |
bx lr | Return |
push {r4, lr} / pop {r4, pc} | Save and restore registers; popping into pc returns |
cbz r0, label | Branch if r0 is zero |
it / ite blocks | Make the next one to four instructions conditional (moveq, movne) |
Condition codes on signed versus unsigned comparisons are a common source of bugs: blt/bgt are signed, blo/bhi are unsigned. The compiler chooses based on the C types, which is why mixing signed and unsigned variables changes the generated branch.
Reading compiler output
C source:
uint32_t sum(const uint32_t *p, uint32_t n) {
uint32_t total = 0;
for (uint32_t i = 0; i < n; i++) total += p[i];
return total;
}
Typical -O2 output for a Cortex-M4 (annotated):
sum:
cbz r1, .Lzero @ if n == 0, return 0
add r1, r0, r1, lsl #2 @ r1 = p + n*4: the end pointer
movs r3, #0 @ total = 0
.Lloop:
ldr r2, [r0], #4 @ r2 = *p; p += 4 (post-increment addressing)
cmp r0, r1 @ reached the end?
add r3, r3, r2 @ total += r2
bne .Lloop
mov r0, r3 @ return value goes in r0
bx lr
.Lzero:
movs r0, #0
bx lr
Notice what the optimiser did: it turned the index into a moving pointer and compares against an end pointer, so the loop body is four instructions.
Spotting the effect of volatile
extern volatile uint32_t STATUS;
while ((STATUS & 1u) == 0) { }
With volatile, the load is inside the loop:
ldr r2, =STATUS
.Lwait:
ldr r3, [r2] @ re-read every iteration
lsls r3, r3, #31 @ move bit 0 into the sign bit / test it
beq .Lwait
Without volatile, a compiler may load once and spin on a register forever:
ldr r3, [r2]
lsls r3, r3, #31
.Lstuck:
beq .Lstuck @ nothing in the loop reloads STATUS
Function prologues and the stack
process:
push {r4, r5, r6, lr} @ save callee-saved registers and the return address
sub sp, sp, #16 @ 16 bytes of locals
...
add sp, sp, #16
pop {r4, r5, r6, pc} @ restore and return in one instruction
The size of the push and the sub sp tell you the function's stack usage, which -fstack-usage also reports per function. The calling-conventions lesson explains which registers must be saved and why.
Getting the disassembly
arm-none-eabi-objdump -d -S --no-show-raw-insn build/fw.elf | less # interleaved with C
arm-none-eabi-gcc -O2 -S -fverbose-asm uart.c -o uart.s # one file
The Compiler Explorer website (godbolt.org) shows the assembly for any snippet and compiler, with lines colour-matched to the source; it is the fastest way to answer "what does this compile to?".
Counting instructions without hardware
The program below "executes" a tiny made-up instruction list the way a CPU would, keeping registers and flags, to make the fetch-decode-execute loop concrete:
#include <stdio.h>
#include <stdint.h>
typedef enum { MOVI, ADD, SUBI, BNE, HALT } op_t;
typedef struct { op_t op; int rd, rn; int32_t imm; } insn_t;
int main(void) {
/* r0 = 5; r1 = 0; loop: r1 += r0; r0 -= 1 (sets Z); bne loop */
const insn_t prog[] = {
{ MOVI, 0, 0, 5 }, { MOVI, 1, 0, 0 },
{ ADD, 1, 0, 0 }, { SUBI, 0, 0, 1 }, { BNE, 0, 0, 2 }, { HALT, 0, 0, 0 },
};
int32_t r[4] = { 0 };
int z = 0, pc = 0, executed = 0;
for (;;) {
insn_t in = prog[pc++];
executed++;
if (in.op == MOVI) r[in.rd] = in.imm;
else if (in.op == ADD) r[in.rd] += r[in.rn];
else if (in.op == SUBI) { r[in.rd] -= in.imm; z = (r[in.rd] == 0); }
else if (in.op == BNE) { if (!z) pc = in.imm; }
else break;
}
printf("r1 = %d after %d instructions\n", r[1], executed);
return 0;
}
Pitfall: Debugging optimised code at the source level can look nonsensical (lines out of order, variables "optimised out"). Switching to the disassembly view shows what the CPU is really doing.
Interview question: Why is Arm called a load-store architecture, and what does that mean for C code that updates memory?
Answer: Arithmetic and logic instructions only operate on registers; memory is accessed only by explicit load and store instructions. So counter++ on a variable in RAM becomes a load into a register, an add, and a store back: three instructions, which is why it is not atomic and an interrupt between the load and the store can lose an update.
Interview question: How would you find out whether a function was inlined, and how much stack it uses?
Answer: Look at the disassembly with objdump -d -S or the compiler's -S output: if there is no bl to the function at the call site and its body appears inline, it was inlined (or check whether the symbol exists at all with nm). For stack usage, compile with -fstack-usage to get a .su file per source file, or read the prologue: the registers pushed plus any sub sp, sp, #n.
Build it: a tiny Thumb disassembler for the crash log
This is step 2 of the module project. When an ESC in the field faults, it saves the 16-bit instruction found at the crash address. The ground-station tool should show it as assembly, not a hex number. Write a disassembler for the five Thumb instructions that turn up most in its control loop.
Lab: Decode 16-bit Thumb instructions
| Instruction | Bits 15 to 0 | Print as |
|---|---|---|
MOVS Rd, #imm | 00100 ddd iiiiiiii | MOVS r3, #200 |
CMP Rn, #imm | 00101 nnn iiiiiiii | CMP r1, #50 |
ADDS Rd, Rn, Rm | 0001100 mmm nnn ddd | ADDS r0, r1, r2 |
B<cond> label | 1101 cccc oooooooo | BNE .+12 |
BX Rm | 010001110 mmmm 000 | BX lr |
- Registers are numbered 0 to 7 (
r0tor7) in the 3-bit fields; inBXthe 4-bit field can also be 13, 14 or 15, printedsp,lr,pc(8 to 12 arer8tor12). - The condition codes
cccc: 0EQ, 1NE, 10GE, 11LT, 12GT, 13LE; others print asB??. The offsetoooooooois a signed 8-bit count of halfwords, and the target is 4 bytes past the instruction plus twice the offset, printed as.+Nor.-N(N in bytes from the instruction itself). - Anything else prints
.hword 0xXXXX(four upper-case hex digits).
Write disasm(op, out) which writes the text into out (at least 32 bytes). snprintf is available.
Going deeper
Interview question: A motor controller's loop is 2 % too slow. How would you use the assembly to fix it?
Answer: Profile to find the hot function, then read its generated assembly for surprises: a division in the loop, floating point done in software, a volatile forcing repeated loads, a missed inline, or 64-bit arithmetic on a 32-bit core. Change the C (or the compiler options) to remove them, and confirm with cycle counts on the target.
Interview question: What is a literal pool?
Answer: Thumb instructions cannot hold an arbitrary 32-bit constant, so the assembler places such constants (addresses, large numbers) in small data areas near the code, called literal pools, and loads them with PC-relative LDR instructions. That is what the ldr r0, =0x40020014 pseudo-instruction becomes. Alternatives are a MOVW/MOVT pair, which builds the constant from two 16-bit halves without a memory load.
Interview question: Why do signed and unsigned comparisons compile to different branches?
Answer: The compare instruction sets the same flags either way, but signed and unsigned orderings interpret them differently: signed conditions (LT, GE, GT, LE) use the N and V flags, unsigned ones (LO, HS, HI, LS) use the carry flag. The compiler picks the condition from the C types after the usual arithmetic conversions, which is why comparing a negative int with an unsigned value can make -1 compare greater than 1.
Explain it: In your own words, explain how you would use the disassembly to check that a register-polling loop really re-reads the register.
Answer: Disassemble the function (objdump -d -S or the compiler's -S output) and find the loop: the label it branches back to. A correct loop has the load from the register's address (an LDR from the address held in a register, often set up with a literal-pool load before the loop) inside the loop, between the label and the backward branch, followed by the test and the conditional branch. If the load is only before the label and the branch jumps back to itself or to a test on a register that never changes, the read was hoisted out of the loop, which means the register access is missing volatile.