优化的 c++ 编译器如何重用函数的堆栈槽?
优化的 c++ 编译器如何确定函数的堆栈槽(函数堆栈帧的一部分)何时不再需要该函数,以便它可以重用其内存?.
堆栈槽是指函数堆栈框架的一部分,不一定是函数的整个堆栈框架,一个澄清问题的例子是,假设我们有一个函数,它的范围内定义了六个整数变量,时间到了在函数中使用第六个变量,第五个变量变得无用,因此编译器可以为第五个和第六个变量使用相同的内存块.
感谢您提供有关此主题的任何信息.
How does an optimizing c++ compiler determine when a stack slot of a function(part of stack frame of a function) is no longer needed by that function, so it can reuse its memory? .
By stack slot I mean a part of stack frame of a function, not necessarily a whole stack frame of a function and an example to clarify the matter is, suppose we have a function that has six integer variables defined in its scope, when it's time to use sixth variable in the function, fifth variable's become useless so compiler can use same memory block for fifth and sixth variables.
any information on this subject is appreciated.
推荐答案
简单的部分是:当一个函数退出时,该函数的所有局部变量都被释放.因此,函数退出表示可以释放整个堆栈帧.不过,这很简单,如果您追求的是优化编译器",您就不会提到.
The easy part is: When a function exits, all local variables of that function are released. Thus, function exit indicates that the whole stack frame can be freed. That's a no-brainer, though, and you wouldn't have mentioned "optimizing compiler" if that's what you were after.
理论上,编译器可以对函数进行流分析,找出在什么时间使用了哪些内存块,甚至可能根据变量可用的顺序重新排序堆栈分配.然后,如果在函数中间的某处或嵌套在函数内的其他作用域(而不是在函数开头)引入了新的自动变量,则可以重新使用那些最近释放的槽.
In theory, a compiler can do flow analysis on a function, find out which chunks of memory are used at what time, and perhaps even re-order stack allocation based on the order in which variables become available. Then, if new automatic variables are introduced somewhere in the middle of the function or other scope nested within the function (rather than at its beginning), those recently freed slots could be re-used.
在实践中,这听起来像是很多旋转的齿轮,我怀疑只要变量进入作用域,堆栈就会被简单地分配,并在作用域结束时通过递减堆栈指针来弹出整个块.但我承认我不是这个话题的专家.有比较权威的知识的可以过来指正一下.
In practice, this sounds like a lot of spinning gears, and I suspect that stack is simply allocated whenever variables come in scope and popped off en block by decrementing the stack pointer when the scope finishes. But I admit I'm no expert on this topic. Someone with more authoritative knowledge may come along and correct me.
相关文章