########### ########
# Registers # # Stack #
########### ########
################################### ####################################
#### Stack Pointer (sp) ### ### local variable n ###
################################### ####################################
#### Fame Counter (fc) ### ### ......................... ###
################################### ####################################
#### Link Register (lr) ### ### local variable 1 ###
################################### ####################################
#### Program Counter (pc) ### ### Passed Parameter n ###
################################### ####################################
### ............................... ###
####################################
### Passed Parameter 1 ###
####################################
### caller function lr (return address) ###
####################################
### caller function fp (frame pointer) ###
####################################
### same block repeats ###
### for caller functions ###
### ................................ ###
- Stack pointer (sp) register:
- Is a HW register, which points to the top of the stack
- As local variables are defined, they are added to the stack, and the stack pointer value changes.
- Since the stack pointer is changing, we can not reference the function parameters and local variables as offset from the sp value
- Instead, we reference the function parameters and variables by adding offset to the frame pointer (fp)
- Frame Pointer (fp) register
- Frame pointer register, points to the bottom of the stack part that is related to the current function
- By other words, fp = sp, before adding the function parameters or local variables.
- fp value is constant for a function, hence it is used to reference the function parameters and local variable.
- Program Counter (pc) register:
- A register that points to the next instruction to be executed.
- Link Register (lr):
- When calling a function, a branch happens from the normal sequence to the address of this function.
- The return address is saved in the link register.
- After the function finishes, pc = lr
- When a function call happens:
- Current lr is saved to stack --> Update sp
- lr = pc + 1 (return address is saved to lr)
- Current fp is saved to stack --> Update sp
- Current sp is saved to fp
- Parameters are moved to stack --> Update sp
- Local variables are created on stack --> Update sp
- Parameters and local variables are refered to as [fp + offset]
- After the function is finished:
- It returns the return value in a special register
- sp = fp
- pc = lr
- fp = saved fp
- lr = saved lr
No comments:
Post a Comment