Author Topic: Can somebody explain me this code?  (Read 16006 times)

nobody

  • Guest
Can somebody explain me this code?
« on: April 11, 2009, 03:51:09 PM »
Hello

I wrote this C function:

int F(int a, int b) {
 return a+b*25;
}

Borland C and GCC outputs for the code above the following assembly code:

push      ebp
   mov       ebp,esp

mov       eax,dword ptr [ebp+12]
   lea       eax,dword ptr [eax+4*eax]
   lea       eax,dword ptr [eax+4*eax]
   add       eax,dword ptr [ebp+8]

pop       ebp
   ret

the function works perfectly, but how does the compiler manages to multiply B by 25 using LEA??

thanks

Offline Frank Kotler

  • NASM Developer
  • Hero Member
  • *****
  • Posts: 2667
  • Country: us
Re: Can somebody explain me this code?
« Reply #1 on: April 11, 2009, 04:42:19 PM »
As you see! Pretty clever. these compilers. eh?

Here's another one (also stolen from a compiler). You know how to convert ascii text to integer, right? Multiply "result so far" by ten, and add in the digit (after converting ascii character to number)...

atoi:
    mov edx, [esp + 4]  ; pointer to string
    xor eax, eax        ; clear "result"
.top:
    movzx ecx, byte [edx]
    inc edx
    cmp ecx, byte '0'
    jb .done
    cmp ecx, byte '9'
    ja .done

; we have a valid character - multiply
    ; result-so-far by 10, subtract '0'
    ; from the character to convert it to
    ; a number, and add it to result.

lea eax, [eax + eax * 4]
    lea eax, [eax * 2 + ecx - 48]

jmp short .top
.done
    ret
;--------

(gawd, I hope that's more readable when it unwraps!)

lea "looks" like a "memory function", but it doesn't touch memory at all - it's really an "arithmetic function". Can't do arbitrary arithmetic with it, of course, but anything that has the form of a valid effective address can be calculated with lea.

Might be interesting to experiment and see just *how* clever the compiler is at this!

Best,
Frank