我试图在x86-64程序集中创建一个函数,它可以将两个数字x和y相乘,并在不使用循环或mul操作符的情况下返回输出。这是我想出的代码,但我不知道它为什么总是返回y。任何帮助都是非常感谢的。X在edi中,y在esi中。
mul:
xorl %eax, %eax
testl %edi, %edi #if x == 0 return 0 //base case 1
je done1
testl %esi, %esi #if y == 0 return 0 //base case 1
je done1
cmpl $1, %edi #if x == 1, return y //base case 2
je done2
addl %esi, %eax #add eax by y (esi) x (edi) times
decl %edi #decrease x by 1 each run of the function. B stays the same
call mul
done1:
ret
done2: #if x == 1, return y
movl %esi, %eax
ret发布于 2020-03-02 00:13:23
它总是返回"y",因为您将%edi与
decl %edi直到它达到值"1“为止。然后执行以下指令序列:
call mul # CALL -->
...
xorl %eax, %eax # RESET accumulator value to 0
testl %edi, %edi
je done1 # NOT TAKEN
testl %esi, %esi
je done1 # NOT TAKEN
cmpl $1, %edi # if x == 1, return y //base case 2
je done2 # HERE - THIS JUMP IS TAKEN
...
movl %esi, %eax # MOVE y to return register %eax
ret # It always returns y in %eax要修复此情况,首先将行xorl %eax, %eax移到mul标签之前。然后删除行movl %esi, %eax以将%eax值保留为返回值。
因此,这可能是一个解决方案:
xorl %eax, %eax # Set result value to "0"
# check for 0 for "y" input
testl %esi, %esi # if y == 0 return 0 //base case 1
je done1 # immediately return on zero
mul:
test %edi, %edi # if x == 0, exit recursive calls
je done1
addl %esi, %eax # add y (esi) to eax
decl %edi # decrease x by 1 each run of the function. B stays the same
call mul
# PASS-THROUGH on stack unwinding
done1:
ret免责声明:我还没有测试过它,但是你应该知道这个想法。
https://stackoverflow.com/questions/60480919
复制相似问题