gpt4 book ai didi

c - 为递归函数绘制堆栈框架

转载 作者:太空宇宙 更新时间:2023-11-03 23:45:23 27 4
gpt4 key购买 nike

给定以下递归函数:

int silly(int n, int *p)
{
int val, val2;

if (n > 0) {
val2 = silly(n << 1, &val);
} else {
val = val2 = 0;
}

*p = val + val2 + n;

return val + val2;
}

在没有启用优化器的情况下,这会产生以下汇编代码:

silly:
pushq %rbp
movq %rsp, %rbp
subq $32, %rsp
movl %edi, -20(%rbp)
movq %rsi, -32(%rbp)
cmpl $0, -20(%rbp)
jle .L2
movl -20(%rbp), %eax
leal (%rax,%rax), %edx
leaq -8(%rbp), %rax
movq %rax, %rsi
movl %edx, %edi
call silly
movl %eax, -4(%rbp)
jmp .L3
.L2:
movl $0, -4(%rbp)
movl -4(%rbp), %eax
movl %eax, -8(%rbp)
.L3:
movl -8(%rbp), %edx
movl -4(%rbp), %eax
addl %eax, %edx
movl -20(%rbp), %eax
addl %eax, %edx
movq -32(%rbp), %rax
movl %edx, (%rax)
movl -8(%rbp), %edx
movl -4(%rbp), %eax
addl %edx, %eax
movq %rbp, %rsp
popq %rbp
ret

谁能帮我画一下这个函数中用到的栈帧,说明程序值存放在什么地方%rsp%rbp 寄存器指向递归调用之前愚蠢()?

最佳答案

所以这是最终答案:

    |                                |  
+--------------------------------+
| |
+--------------------------------+
| ... |
+--------------------------------+
| return address | 12
+--------------------------------+
| return address | 8
+--------------------------------+
| %rbp | 4
+--------------------------------+
| %rbp | 0
+--------------------------------+
| val2 | -4
+--------------------------------+
| val | -8
+--------------------------------+
| | -12
+--------------------------------+
| | -16
+--------------------------------+
| n | -20
+--------------------------------+
| | -24
+--------------------------------+
| p | -28
+--------------------------------+
| p | -32
+--------------------------------+

关于c - 为递归函数绘制堆栈框架,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34700700/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com