</>EmbeddedInterview

What is the Arm calling convention (AAPCS), and why does it matter in embedded work?

MediumEmbedded C

Short answer: The AAPCS (Procedure Call Standard for the Arm Architecture) defines how functions pass arguments and return values and which registers they must preserve. On 32-bit Arm: the first four arguments go in r0–r3, the rest on the stack; results come back in r0 (and r1 for 64-bit values); r0–r3 and r12 are caller-saved (scratch); r4–r11 are callee-saved; r13 is SP, r14 is LR (return address), r15 is PC; and the stack must be 8-byte aligned at public function boundaries.

Register Role Preserved across calls?
r0–r3 arguments, return value, scratch no (caller-saved)
r4–r11 local variables yes (callee-saved)
r12 (IP) intra-procedure scratch no
r13 (SP) stack pointer yes
r14 (LR) return address saved by callee if it makes calls
r15 (PC) program counter –
s0–s15 / d0–d7 (FPU) FP arguments/results (hard-float), scratch no
s16–s31 FP callee-saved yes

AArch64 is similar with more registers: x0–x7 for arguments and results, x19–x28 callee-saved, x29 frame pointer, x30 link register, 16-byte stack alignment.

Why it matters

  • Cortex-M interrupts are plain C functions because the hardware automatically stacks exactly the caller-saved registers (r0–r3, r12, lr, pc, xPSR). The compiler-generated code saves r4–r11 only if the ISR uses them. That is a deliberate fit with the AAPCS.
  • Writing assembly that is called from C (or calls C): you must preserve r4–r11 and keep SP aligned, or C code breaks in subtle ways.
  • Performance: functions with four or fewer integer arguments pass everything in registers; a fifth argument goes on the stack. Passing a pointer to a struct instead of many arguments is cheaper.
  • Struct returns: small structs (≤ 4 bytes on AArch32) come back in r0; larger ones through memory the caller provides.
  • Float ABI: -mfloat-abi=hard passes floats in FPU registers; softfp uses FPU instructions but passes floats in integer registers; mixing objects built with hard and soft/softfp fails to link.
  • Context switches: an RTOS on Cortex-M saves r4–r11 (and s16–s31 if the FPU is used) in software in PendSV, because the hardware already saved the rest.
  • Debugging: in a crash dump, lr and the stacked frame let you reconstruct the call chain.