MIPS:堆栈指针($ sp)和堆栈的相关用法 [英] MIPS: relevant use for a stack pointer ($sp) and the stack

查看:2260
本文介绍了MIPS:堆栈指针($ sp)和堆栈的相关用法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当前,我正在为我的计算机组织中期学习,并且我正在尝试完全理解堆栈指针和堆栈.我知道围绕这个概念的以下事实:

Currently I'm studying for my computer organization midterm, and I'm trying to fully understand the stack pointer and the stack. I know these following facts that surround the concept:

  • 遵循先进先出的原则
  • 向堆栈中添加内容需要两个步骤:

  • It follows the first in last out principle
  • And adding something to the stack takes a two step process:

addi $sp, $sp, -4
sw $s0, 0($sp)

我认为让我无法完全理解的是,我无法提出需要和/或想要使用堆栈指针跟踪数据的相关,不言自明的情况.

What I think is stopping me from fully understanding is that I can't come up with a relevant, self apparent situation where I would need and/or want to keep track of data with a stack pointer.

有人可以详细介绍这个概念,并给我一些有用的代码示例吗?

Could someone elaborate on the concept as a whole and give me some useful code examples?

推荐答案

堆栈的一个重要用途是嵌套子例程调用.

An important use of stack is nesting subroutine calls.

每个子例程可能具有该子例程本地的一组变量.这些变量可以方便地存储在 stack frame 中的堆栈中.一些调用约定也会在堆栈上传递参数.

Each subroutine may have a set of variables local to that subroutine. These variables can be conveniently stored on a stack in a stack frame. Some calling conventions pass arguments on the stack as well.

使用子例程还意味着您必须跟踪调用者,即返回地址. 一些体系结构为此目的有专用的堆栈,而另一些体系结构隐式地使用普通"堆栈.默认情况下,MIPS仅使用寄存器,但是在非叶函数(即调用其他函数的函数)中,返回地址将被覆盖.因此,您必须保存原始值,通常将其保存在局部变量中的堆栈上.调用约定也可能声明某些寄存器值必须在函数调用之间保留,您可以类似地使用堆栈来保存和恢复它们.

Using subroutines also means you have to keep track of the caller, that is the return address. Some architectures have a dedicated stack for this purpose, while others implicitly use the "normal" stack. MIPS by default only uses a register, but in non-leaf functions (ie. functions that call other functions) that return address is overwritten. Hence you have to save the original value, typically on the stack among your local variables. The calling conventions may also declare that some register values must be preserved across function calls, you can similarly save and restore them using the stack.

假设您有这个C片段:

extern void foo();
extern int bar();
int baz()
{
    int x = bar();
    foo();
    return x;
}

MIPS程序集可能看起来像:

MIPS assembly may then look like:

addiu $sp, $sp, -8  # allocate 2 words on the stack
sw $ra, 4($sp)      # save $ra in the upper one
jal bar             # this overwrites $ra
sw $v0, ($sp)       # save returned value (x)
jal foo             # this overwrites $ra and possibly $v0
lw $v0, ($sp)       # reload x so we can return it
lw $ra, 4($sp)      # reload $ra so we can return to caller
addiu $sp, $sp, 8   # restore $sp, freeing the allocated space
jr $ra              # return

这篇关于MIPS:堆栈指针($ sp)和堆栈的相关用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆