乐闻世界logo
搜索文章和话题

ARM : link register and frame pointer

1个答案

1

In the ARM architecture, the Link Register (LR) and Frame Pointer (FP) are two critical registers that play a key role in function calls and stack frame management.

Role of the Link Register (LR, R14): The Link Register (LR) is primarily used to store the return address during function calls. In the ARM architecture, when a function (the caller) invokes another function (the callee), the return address (the address of the instruction following the call instruction in the caller) is automatically stored in the LR register. This enables the callee function to return to the correct location in the caller after execution.

For example, suppose function A calls function B:

assembly
// In function A BL functionB // BL instruction calls function B and stores the return address in LR

In function B, the following instruction is typically used to return to caller A before completion:

assembly
MOV PC, LR // Moves the value of LR to the program counter PC to return to the caller

Role of the Frame Pointer (FP, R11): The Frame Pointer (FP) is used to locate the current function's stack frame. In complex function calls, particularly when the function has local variables and registers that need to be preserved, the stack frame provides a structure for storing this information. The FP register points to the base address of the stack frame, enabling efficient access to all local variables and saved registers during function execution.

For example, when entering a new function, the following operations are typically performed:

assembly
PUSH {FP, LR} // Saves the old frame pointer and link register ADD FP, SP, #4 // Sets the new frame pointer

Before the function exits, FP and LR are restored, and the stack pointer (SP) is adjusted as needed:

assembly
MOV SP, FP // Restores the stack pointer POP {FP, LR} // Restores the frame pointer and link register, preparing to return

Through these operations, even with multiple nested function calls and complex call stacks, each function can accurately access its local variables and return correctly to the calling function.

This mechanism simplifies debugging and maintenance, as each function's execution environment is well-defined and clear.

2024年6月29日 12:07 回复

你的答案