CHAPTER 16. REPLACING ARITHMETIC INSTRUCTIONS TO OTHER ONES CHAPTER 16. REPLACING ARITHMETIC INSTRUCTIONS TO OTHER ONES
f3:
add x0, x0, x0, lsl 4
; X0=X0+X0<<4=a+a16=a17
ret
16.2 Division
16.2.1 Division using shifts.
Example of division by 4:
unsigned int f(unsigned int a)
{
return a/4;
};
We get (MSVC 2010):
Listing 16.11: MSVC 2010
_a$ = 8 ; size = 4
_f PROC
mov eax, DWORD PTR _a$[esp-4]
shr eax, 2
ret 0
_f ENDP
TheSHR(SHift Right) instruction in this example is shifting a number by 2 bits to the right. The two freed bits at left (e.g.,
two most significant bits) are set to zero. The two least significant bits are dropped. In fact, these two dropped bits are the
division operation remainder.
TheSHRinstruction works just likeSHL, but in the other direction.
7 6 5 4 3 2 1 0
0 7 6 5 4 3 2 1 0 CF
It is easy to understand if you imagine the number 23 in the decimal numeral system. 23 can be easily divided by 10 just by
dropping last digit (3—division remainder). 2 is left after the operation as aquotient.
So the remainder is dropped, but that’s OK, we work on integer values anyway, these are not areal numbers!
Division by 4 in ARM:
Listing 16.12: Non-optimizing Keil 6/2013 (ARM mode)
f PROC
LSR r0,r0,#2
BX lr
ENDP
Division by 4 in MIPS:
Listing 16.13: Optimizing GCC 4.4.5 (IDA)
jr $ra
srl $v0, $a0, 2 ; branch delay slot
The SRL instruction is “Shift Right Logical”.