gaoryrt
2019-10-16 12:06:51 +08:00
同事给了段代码对比尾递归优化:
```
int f(int n, long long t){
if (n == 1) {
return t;
}
return f(n-1, n * t);
}
(gdb) disassemble f
Dump of assembler code for function f(int, long long):
0x0000000000400abd <+0>: push %rbp
0x0000000000400abe <+1>: mov %rsp,%rbp
0x0000000000400ac1 <+4>: sub $0x10,%rsp
0x0000000000400ac5 <+8>: mov %edi,-0x4(%rbp)
0x0000000000400ac8 <+11>: mov %rsi,-0x10(%rbp)
0x0000000000400acc <+15>: cmpl $0x1,-0x4(%rbp)
0x0000000000400ad0 <+19>: jne 0x400ad8 <f(int, long long)+27>
0x0000000000400ad2 <+21>: mov -0x10(%rbp),%rax
0x0000000000400ad6 <+25>: jmp 0x400af2 <f(int, long long)+53>
0x0000000000400ad8 <+27>: mov -0x4(%rbp),%eax
0x0000000000400adb <+30>: cltq
0x0000000000400add <+32>: imul -0x10(%rbp),%rax
0x0000000000400ae2 <+37>: mov -0x4(%rbp),%edx
0x0000000000400ae5 <+40>: sub $0x1,%edx
0x0000000000400ae8 <+43>: mov %rax,%rsi
0x0000000000400aeb <+46>: mov %edx,%edi
0x0000000000400aed <+48>: callq 0x400abd <f(int, long long)>
0x0000000000400af2 <+53>: leaveq
0x0000000000400af3 <+54>: retq
End of assembler dump.
(gdb) disassemble f
Dump of assembler code for function f(int, long long):
0x0000000000400b70 <+0>: cmp $0x1,%edi
0x0000000000400b73 <+3>: mov %rsi,%rax
0x0000000000400b76 <+6>: je 0x400b9b <f(int, long long)+43>
0x0000000000400b78 <+8>: lea -0x2(%rdi),%esi
0x0000000000400b7b <+11>: xor %edx,%edx
0x0000000000400b7d <+13>: movslq %edi,%rdi
0x0000000000400b80 <+16>: add $0x1,%rsi
0x0000000000400b84 <+20>: nopl 0x0(%rax)
0x0000000000400b88 <+24>: mov %rdi,%rcx
0x0000000000400b8b <+27>: sub %rdx,%rcx
0x0000000000400b8e <+30>: add $0x1,%rdx
0x0000000000400b92 <+34>: imul %rcx,%rax
0x0000000000400b96 <+38>: cmp %rsi,%rdx
0x0000000000400b99 <+41>: jne 0x400b88 <f(int, long long)+24>
0x0000000000400b9b <+43>: repz retq
End of assembler dump.
```
上面一段没有优化,push callq leave 就一直进栈到最后再一个个出栈
下面的优化过,就是 jne 循环
优化的是栈吧