AMD 250 Computer Hardware User Manual


 
Chapter 8 Integer Optimizations 163
Software Optimization Guide for AMD64 Processors
25112 Rev. 3.06 September 2005
Signed Division by 2
n
; In: EAX = dividend
; Out: EAX = quotient
cdq ; Sign extend into EDX.
and edx, (2^n - 1) ; Mask correction (use divisor - 1)
add eax, edx ; Apply correction if necessary.
sar eax, (n) ; Perform right shift by log2(divisor).
Signed Division by –2
; In: EAX = dividend
; Out: EAX = quotient
cmp eax, 80000000h ; CF = 1 if dividend >= 0.
sbb eax, -1 ; Increment dividend if it is < 0.
sar eax, 1 ; Perform right shift.
neg eax ; Use (x / -2) == -(x / 2).
Signed Division by –(2
n
)
; In: EAX = dividend
; Out: EAX = quotient
cdq ; Sign extend into EDX.
and edx, (2^n - 1) ; Mask correction (-divisor - 1).
add eax, edx ; Apply correction if necessary.
sar eax, (n) ; Right shift by log2(-divisor).
neg eax ; Use (x / -(2^n)) == (-(x / 2^n)).
Remainder of Signed Division by 2 or –2
; In: EAX = dividend
; Out: EAX = remainder
cdq ; Sign extend into EDX.
and eax, 1 ; Compute remainder.
xor eax, edx ; Negate remainder if
sub eax, edx ; dividend was < 0.
Remainder of Signed Division by 2
n
or –(2
n
)
; In: EAX = dividend
; Out: EAX = remainder
cdq ; Sign extend into EDX.
and edx, (2^n - 1) ; Mask correction (abs(divisor) - 1)
add eax, edx ; Apply pre-correction.
and eax, (2^n - 1) ; Mask out remainder (abs(divisor) - 1)
sub eax, edx ; Apply pre-correction if necessary.