问题描述
如何在Assembler中返回64位值?我试过了:
How do I return in Assembler a 64bit value ?I tried this:
C程序:
#include <stdio.h>
double result=0;
double a = 10;
extern double func(double a);
int main() {
result = func(a);
printf("result: %f\n", result);
return 0;
}
组装:
section .bss
x: resq 1
section .text
global func
func:
movq qword[x],xmm0
fld qword [x]
fld qword [x]
fadd
movq xmm0,qword[x]
ret
应返回20.0,但始终为10.0我怎么了
It should return 20.0 but instead it is always 10.0What did I wrong?
推荐答案
@ petch @ Michael Petch指出,使用以下代码可以使整个函数更高效:
@Michael Petch noted that the whole function could be much more efficient with the following code:
addsd xmm0, xmm0 ; Add input parameter to itself
ret ; Done! (return values go in xmm0)
x86-64在XMM寄存器(而不是内存或x87堆栈)中传递/返回double
.(适用于x86-64 System V ABI/调用约定和Windows x64.请参阅 x86标签wiki )
发布的代码没有评论.评论它会对OP有所帮助,所以...
The code posted didn't have comments. Commenting it would have helped the OP, so...
;; Buggy original version with comments
movq qword[x],xmm0 ; Store current value in memory [Why?]
fld qword [x] ; Load current value from memory [Why??]
fld qword [x] ; Load current value from memory again
fadd ; Add top two stack items
movq xmm0,qword[x] ; reload original value from memory, unmodified
@ElderBug指出,OP在执行最后的movq
之前忘记将fadd
的结果存储到内存中,因此该函数只是返回其输入,例如double foo(double x) { return x; }
,但在x87堆栈上留下了垃圾.
@ElderBug noted that the OP forgot to store the result of the fadd
into memory before doing the final movq
, so this function simply returns its input, likedouble foo(double x) { return x; }
but leaving garbage on the x87 stack.
@Michael Petch继续指出,原始代码在浮点堆栈上留下了大量碎片"-没有尝试使用各种pop
版本的指令(fstp
,或faddp
而不是fadd
).这样就为下一个浮点函数留出了更少的空间-直到最终导致浮点堆栈溢出,从而导致意外的NaN!
@Michael Petch went on to note that the original code left a large amount of 'debris' on the floating point stack - there was no attempt to clean it up with various pop
versions of the instructions (fstp
, or faddp
instead of fadd
). This leaves less room for the next floating point function - until finally a floating-point stack overflow is caused, resulting in an unexpected NaN!
这篇关于汇编64位:如何返回双精度值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!