有没有办法优化这个 x86 汇编代码?

Is there a way to optimize this x86 assembly code?

假设在 eax,ecx 中给定了值。写一段代码 计算 5*eax + 3*ecx + 1,并将结果存储在 eax 中。 (* 这里表示乘法)。

我的代码:

;Initialize the values in eax and ecx
mov eax,3
mov ecx,4
;Compute 3*ecx
mov ebx,eax
mov eax,ecx
mov edx,3
mul edx
; Compute 5*eax
mov ecx,eax
mov eax,ebx
mov edx,5
mul edx
; Compute 5*eax + 3*ecx + 1
lea eax,[ecx + eax]
inc eax

如果 "optimize" 你的意思是优化指令数,那么当然,使用 lea 甚至更多:

;Initialize the values in eax and ecx
mov eax,3
mov ecx,4

;Compute 3*ecx
lea ecx,[ecx*2 + ecx]

; Compute 5*eax
lea eax,[eax*4 + eax]

; Compute 5*eax + 3*ecx + 1
lea eax,[ecx + eax + 1]

如果我没看错的话,机器代码大小也减少了 16 个字节。

管理您可以使用 lea 计算的内容的规则列在 Intel's manuals 中的 指定偏移量 部分。

Michael 的(最优秀的)解决方案还可以针对大小(缩短 1 个字节)进行稍微优化,但这需要先进行一些代数运算。

  5*eax + 3*ecx + 1
= 2*eax + 3*eax + 3*ecx + 1
= 2*eax + 3*(eax + ecx) + 1

这可以通过...解决

(Excluding initialization of EAX and ECX)
add ecx, eax                  ; 2 bytes
lea ecx,[ecx*2 + ecx]         ; 3 bytes
lea eax,[eax*2 + ecx + 1]     ; 4 bytes