我正在尝试在 64 位汇编中编写一个函数 (max),但我不知道我做错了什么,也许你们中的一些人可以确定我做错了什么:/
函数如下:
int max(int a, int b) {
/* Return the larger of the two integers `a' and `b'. */
if (a > b)
return a;
else
return b;
}
这是我的汇编代码(带注释):
push %rbp
mov %rsp, %rbp
mov %rdi, %rax
mov %rsi, %rcx
test %rax, %rax // Checking if first parameter is signed
js .signedRAX
test %rcx, %rcx // Checking if second parameter is signed
js .signedRCX
jmp .compare // If either one signed then jump to .compare
.signedRAX:
test %rcx, %rcx // Checking if both are signed
js .signedRAXandRCX
mov %rcx, %rax // If not then return the positive number
jmp .end // finish the function
.signedRCX:
jmp .end // If only the second parameter is signed then jump
.signedRAXandRCX: // straight to end of function and return %rax
cmp %rax, %rcx // If both are signed compare which one is the max
jl .end
mov %rcx, %rax
jmp .end
.compare:
cmp %rax, %rcx // If both are positive then compare which one is
jg .end // the max
mov %rcx, %rax
.end:
mov %rbp, %rsp
pop %rbp
ret
比较两个既有符号又有正数的参数时,我得到了错误的输出。
最佳答案
你的工作太复杂了。
如果我将你的程序输入gcc -S
,我得到
max:
.LFB0:
.cfi_startproc
pushl %ebp
.cfi_def_cfa_offset 8
.cfi_offset 5, -8
movl %esp, %ebp
.cfi_def_cfa_register 5
movl 8(%ebp), %eax
cmpl 12(%ebp), %eax
jle .L2
movl 8(%ebp), %eax
jmp .L3
.L2:
movl 12(%ebp), %eax
.L3:
popl %ebp
.cfi_restore 5
.cfi_def_cfa 4, 4
ret
.cfi_endproc
.LFE0:
如果我接管你的“ABI”和传递参数的方式,
我明白了
max:
push %rbp
mov %rsp, %rbp
mov %rdi, %rax
mov %rsi, %rcx
cmpl %rcx, %rax
jle .L2
movl %rcx, %rax
.L2:
mov %rbp, %rsp
pop %rbp
ret
关于c - 在 64 位汇编中编写函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26671870/