编译器存储本地变量的确切位置在哪里?

huangapple go评论59阅读模式
英文:

Where exactly compilers store local variables

问题

我正在编写一个针对较旧的8位处理器(C的一个小子集)的编译器,该编译器应该生成汇编代码(或直接生成机器代码,不重要)。

本地变量应存储在哪里?在(正常调用的)堆栈上还是在某个单独的数据堆栈上?所以,在函数的开头是否应该保留(可能初始化)空间,并在返回时进行清理?注意,中断可能随时修改(调用)堆栈指针下方的区域。

英文:

I'm in the process of writing a compiler for an older 8 bit processor (a tiny subset of C), that should generate assembler code (or machine code directly, doesn't matter).

Where should local variables be stored? On the (normal call) stack or some separate data stack? So should at the beginning of a function the space be reserved (maybe initialized) and on the return cleaned up? Note, that interrupts could modify the area below the (call) stack pointer at any time.

答案1

得分: 1

常见做法是将本地变量存储在处理器寄存器中,如果可能的话。(在8位机器上,有时这不是一个选项。)其余的本地变量通常存储在正常的数据栈上。

通常为函数生成的入口代码执行以下操作:

  • 通过调整堆栈指针在堆栈上保留一定数量的字节。
  • 存储被调用者保存的寄存器,如果需要的话。(即,按照调用约定,不应该在函数调用过程中更改的寄存器。)
  • 初始化本地变量。

退出代码通常执行以下操作:

  • 恢复被调用者保存的寄存器。
  • 通过在堆栈中的另一方向调整堆栈指针来取消保留的堆栈区域。

正如您自己注意到的,函数永远不能依赖于堆栈指针“错误”一侧的数据,因为这些数据可能会被中断函数修改。

英文:

Common practice is to store local variables in processor registers, if possible. (On an 8-bit machine this sometimes isn't an option.) The remaining local variables are typically stored on the normal data stack.

The entry code emitted for a function typically does the following:

  • Reserve a number of bytes on the stack, by adjusting the stack pointer.
  • Store callee-save registers, if needed. (I.e. registers that the calling-convention says should not be changes over the function call.)
  • Initializes local variables.

The exit code typically does the following:

  • Restore the callee-save registers.
  • Unreserve the area on the stack by adjusting the stack pointer in the other direction.

As you noted yourself, a function can never rely on data on the "wrong" side of the stack pointer, as that can be modified by interrupt functions.

huangapple
  • 本文由 发表于 2023年6月12日 00:14:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/76451370.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定