gpt4 book ai didi

c++ - "shld"指令产生奇怪的值

转载 作者:太空宇宙 更新时间:2023-11-04 00:57:11 27 4
gpt4 key购买 nike

我在内联汇编中使用“shld”指令,由 g++ (7.3.0) 编译。它会产生一些奇怪的结果。

在 Ubuntu 和 WSL 上试过。

   unsigned long long hi, lo;
//some code goes here
//...
asm volatile (
"shld $0x3, %1, %0;\n"
: "=r"(hi)
: "r"(lo)
:
);
//I expect the asm produces this:
//hi = (hi << 3) | (lo >> 61);
//but the actual result is:
//hi = (lo << 3) | (lo >> 61);
//you can see the real assembly produced by gcc below.

我希望“hi”中的结果值为

(hi << 3) | (lo >> 61)

但实际结果是

(lo << 3) | (lo >> 61)

参见 https://en.wikibooks.org/wiki/X86_Assembly/Shift_and_Rotate了解详情。

事实证明,g++ 将我的代码翻译成这样:

    6e6a:       48 8b 45 a0             mov    -0x60(%rbp),%rax
6e6e: 48 0f a4 c0 03 shld $0x3,%rax,%rax
6e73: 48 89 45 98 mov %rax,-0x68(%rbp)

其中 -0x60(%rbp) 是“lo”,-0x68(%rbp) 是“hi”。

最佳答案

您需要指定hi 既是输入又是输出。像这样:

asm volatile (
"shld $0x3, %1, %0;\n"
: "=r"(hi)
: "r"(lo)
, "0"(hi)
:
);

产生以下汇编代码:

mov    -0x10(%rbp),%rdx
mov -0x8(%rbp),%rax
shld $0x3,%rdx,%rax
mov %rax,-0x8(%rbp)

“0”表示这个操作数(2 号)必须与 0 号操作数相同,这看起来没什么用,除了它使这个寄存器既是输入又是输出。

关于c++ - "shld"指令产生奇怪的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55564747/

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