0
0
ARM Architectureknowledge~5 mins

Preserving callee-saved registers in ARM Architecture

Choose your learning style9 modes available
Introduction

When a function uses certain registers, it must save their values before changing them. This keeps the program running correctly by restoring those values when the function ends.

When writing a function that uses registers meant to keep their values across calls.
When you want to call another function but keep your current register values safe.
When debugging to understand how functions save and restore important data.
When optimizing code to avoid unnecessary saving and restoring of registers.
Core Concept
ARM Architecture
push {registers}
... function code ...
pop {registers}

push saves registers on the stack.

pop restores registers from the stack.

Key Points
This saves registers r4 and r5 before use and restores them after.
ARM Architecture
push {r4, r5}
... use r4 and r5 ...
pop {r4, r5}
Saves and restores a range of registers from r4 to r7.
ARM Architecture
push {r4-r7}
... function code ...
pop {r4-r7}
Detailed Explanation

This function saves the callee-saved register r4 and the link register (lr) at the start. It uses r4 to hold and modify the input value. Before returning, it restores r4 and lr to keep the program state safe.

ARM Architecture
my_function:
    push {r4, lr}      @ Save r4 and link register
    mov r4, r0         @ Use r4 to store input
    add r4, r4, #1     @ Increment value
    mov r0, r4         @ Move result to r0 for return
    pop {r4, lr}       @ Restore r4 and link register
    bx lr              @ Return from function
OutputSuccess
Important Notes

Callee-saved registers are usually r4 to r11 and lr in ARM.

Always save and restore the same registers to avoid bugs.

Not saving callee-saved registers can cause unexpected program errors.

Summary

Functions must save callee-saved registers if they use them.

Use push to save and pop to restore registers.

This keeps the program stable and prevents data loss.