Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In assembler, why does the use of registers differ between addition and subtraction?

Tags:

c

x86

assembly

I have a very basic doubt here. I have two very simple C codes and their assembly codes:

program 1:

main()

{

    int temp1, temp2, temp3;
    char temp5, temp6, temp7, temp8, temp9;
    temp1 = 5;
    temp1 = 9 - temp1;
}

Assembly:

   0x080483b4 <+0>: push   ebp    
   0x080483b5 <+1>: mov    ebp,esp    
   0x080483b7 <+3>: sub    esp,0x20    
   0x080483ba <+6>: mov    DWORD PTR [ebp-0xc],0x5    
   0x080483c1 <+13>:    mov    eax,0x9    
   0x080483c6 <+18>:    sub    eax,DWORD PTR [ebp-0xc]    
   0x080483c9 <+21>:    mov    DWORD PTR [ebp-0xc],eax    
   0x080483cc <+24>:    leave      
   0x080483cd <+25>:    ret  

Program 2:

main()    
{    
    int temp1, temp2, temp3;
    char temp5, temp6, temp7, temp8, temp9;
    temp1 = 5;
    temp1 = 9 + temp1;    
}

Assembly:

   0x080483b4 <+0>: push   ebp    
   0x080483b5 <+1>: mov    ebp,esp    
   0x080483b7 <+3>: sub    esp,0x20    
   0x080483ba <+6>: mov    DWORD PTR [ebp-0xc],0x5    
   0x080483c1 <+13>:    add    DWORD PTR [ebp-0xc],0x9    
   0x080483c5 <+17>:    leave      
   0x080483c6 <+18>:    ret

Why in the case of subtraction, eax register need to be used and not in the case of addition. Can't it be like:

0x080483c1 <+13>:   sub    DWORD PTR [ebp-0xc],0x9

instead of -

0x080483c1 <+13>:   mov    eax,0x9

0x080483c6 <+18>:   sub    eax,DWORD PTR [ebp-0xc]
like image 675
pkumar Avatar asked Nov 13 '11 11:11

pkumar


2 Answers

I'm guessing because addition is commutative (A + B == B + A), whereas subtraction is not (A - B != B - A). Because of this the addition of 9 + temp1 is the same as temp1 + 9, hence the simpler assembler sequence. 9 - temp1 involves creating a temporary variable.

like image 157
SmacL Avatar answered Sep 20 '22 10:09

SmacL


temp1 = 9 - temp1; is the same as temp1 = - temp1 + 9;. This carries out 2 operations:

  1. Negate temp1
  2. Do the addition

eax is used as the temporary location to save the middle value.

In the addition case, there's no "middle value", the operation can be done directly.

like image 42
tomnotcat Avatar answered Sep 20 '22 10:09

tomnotcat