Phase 0 · Module 2 of 4
The ARM programmer's model: registers and a first function
Registers and the programmer's model · 12 min read
To program a CPU at the lowest level, you need its programmer's model: the registers it gives you and the rules for using them. On an ARM Cortex-M (the M-profile used in most microcontrollers), the model is refreshingly small.
Sixteen core registers
- R0–R12: general-purpose registers for your data.
- R13, the stack pointer (SP): where the top of the stack is.
- R14, the link register (LR): the return address when a function is called.
- R15, the program counter (PC): the address of the instruction being executed.
- xPSR: status flags (negative, zero, carry, overflow) and the current exception number.
The AAPCS, ARM's procedure call standard, says how functions use them: the first four arguments arrive in R0–R3, the result goes back in R0, and a function must preserve R4–R11 if it uses them. Every compiler and every hand-written routine follows these rules, which is how C and assembly can call each other.
A first function in Thumb assembly
.syntax unified
.thumb
.global add3
.type add3, %function
add3: @ int add3(int a, int b, int c)
adds r0, r0, r1 @ r0 = a + b (a, b, c arrive in r0, r1, r2)
adds r0, r0, r2 @ r0 = r0 + c (the result goes back in r0)
bx lr @ return to the caller's address in lrThree instructions, and every one maps to the model above: arguments in R0–R2, the result in R0, and a branch back through LR. From C you would declare it as int add3(int a, int b, int c); and call it like any other function.
Why this matters
Crash dumps, startup code, context switches in an RTOS and performance-critical loops are all read and written at this level. When a Cortex-M faults, the hardware pushes R0–R3, R12, LR, PC and xPSR onto the stack, and being able to read that frame is what turns a mysterious reset into a one-line fix.
Try it
- Write mul_add(a, b, c) that returns a * b + c. Which single Cortex-M instruction does both? (Look up MLA.)
- Why does add3 not need to save any registers? When would it have to push R4 onto the stack?
In the full course you assemble, link and debug routines like this on real hardware, then move up to AArch64, exceptions, the MMU and caches, TrustZone and NEON.