assembly - 如何强制 NASM 将 [1 + rax*2] 编码为 disp32 + index*2 而不是 disp8 + base + index?

标签 assembly x86 nasm micro-optimization machine-code

高效地做 x = x*10 + 1 ,这可能是最佳使用

lea   eax, [rax + rax*4]   ; x*=5
lea   eax, [1 + rax*2]     ; x = x*2 + 1

3-component LEA has higher latency在现代 Intel CPU 上,例如Sandybridge 系列上有 3 个周期与 1 个周期,所以 disp32 + index*2disp8 + base + index*1 快SnB 系列,即我们关心优化的大多数主流 x86 CPU。 (这主要仅适用于 LEA,不适用于加载/存储,因为 LEA 在 ALU 执行单元上运行,而不是在大多数现代 x86 CPU 中的 AGU 上运行。)AMD CPU 的 LEA 较慢,具有 3 个组件或 scale > 1 (http://agner.org/optimize/)

但是 NASM 和 YASM 将通过使用 [1 + rax + rax*1] 来优化代码大小对于第二个 LEA,它只需要 disp8 而不是 disp32。 (寻址模式始终有基址寄存器或 disp32)。

即他们总是 split reg*2进入base+index ,因为这对于代码大小来说是最糟糕的。

我可以强制使用 lea eax, [dword 1 + rax*2] 的 disp32 ,但这并不能阻止 NASM 或 YASM 拆分寻址模式。 NASM手册似乎没有记录使用the strict keyword的方法在比例因子上,和 [1 + strict rax*2]不组装。 有没有办法使用strict或其他一些语法来强制寻址模式所需的编码

<小时/>

nasm -O0禁用优化不起作用。显然,这仅控制多 channel 分支位移优化,而不是 NASM 所做的所有优化。当然,您不想首先对整个源文件执行此操作,即使它确实有效。我仍然明白

8d 84 00 01 00 00 00    lea    eax,[rax+rax*1+0x1]
<小时/>

我能想到的唯一解决方法是使用 db 手动对其进行编码。这是相当不方便的。根据记录,手动编码为:

db 0x8d, 0x04, 0x45  ; opcode, modrm, SIB  for lea eax, [disp32 + rax*2]
dd 1                 ; disp32

比例因子编码在 SIB 字节的高 2 位中。我组装lea eax, [dword 1 + rax*4]获取正确寄存器的机器代码,因为 NASM 的优化仅适用于 *2 。 SIB 为 0x85 ,并将字节顶部的 2 位字段递减,将比例因子从 4 减少到 2。

<小时/>

但问题是:如何以一种易于阅读的方式编写它,以便轻松更改寄存器,并让 NASM 为您编码寻址模式?(我想一个巨大的宏可以使用文本处理和手动 db 编码来做到这一点,但这并不是我正在寻找的答案。我现在实际上不需要这个,我主要想知道 NASM 或 YASM 是否有语法来强制执行此操作.)

我知道的其他优化,例如mov rax, 1汇编为 5 字节 mov eax,1在所有 CPU 上都是纯粹的胜利,除非您想要更长的指令在没有 NOP 的情况下进行填充,and can be disabledmov rax, strict dword 1获取 7 字节符号扩展编码,或 strict qword对于 10 字节 imm64。

<小时/>

gas 不会执行此操作或大多数其他优化(仅立即数和分支位移的大小):lea 1(,%rax,2), %eax组装成
8d 04 45 01 00 00 00 lea eax,[rax*2+0x1] ,对于 .intel_syntax noprefix 也是如此版本。

不过,MASM 或其他汇编器的答案也很有趣。

最佳答案

NOSPLIT :

Similarly, NASM will split [eax*2] into [eax+eax] because that allows the offset field to be absent and space to be saved; in fact, it will also split [eax*2+offset] into [eax+eax+offset].
You can combat this behaviour by the use of the NOSPLIT keyword: [nosplit eax*2] will force [eax*2+0] to be generated literally.
[nosplit eax*1] also has the same effect. In another way, a split EA form [0, eax*2] can be used, too. However, NOSPLIT in [nosplit eax+eax] will be ignored because user's intention here is considered as [eax+eax].

lea eax, [NOSPLIT 1+rax*2]
lea eax, [1+rax*2]

00000000  8D044501000000    lea eax,[rax*2+0x1]
00000007  8D440001          lea eax,[rax+rax+0x1]

关于assembly - 如何强制 NASM 将 [1 + rax*2] 编码为 disp32 + index*2 而不是 disp8 + base + index?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48848230/

相关文章:

gcc - 为什么空函数不只是返回

c - 如何基于Linux GCC用汇编语言实现__sync_fetch_and_sub原子操作

c - 内联汇编后指针取消引用 (SIGSEGV) 失败

linux - 系统调用在调用_exit时返回07

在没有编译器生成序言/结尾和 RET 指令的情况下创建 C 函数?

c - NASM 程序集 while 循环计数器

c - 这是 ARM 编译器代码生成错误吗?

gcc - x86 asm - 从 esp 中减去 12 个字节。只需要8个

assembly - x86-64 和远程调用/跳转

assembly - 在 x86 汇编中,有效地址中的寄存器算术如何编译为字节码?