AMD Athlon™ Processor x86 Code Optimization

22007E/0 — November 1999

;algorithm

1

 

MOV

EAX,

m

 

MOV

EDX,

dividend

 

MOV

ECX,

EDX

 

IMUL

EDX

 

 

ADD

EDX,

ECX

 

SHR

ECX,

31

 

SAR

EDX,

s

 

ADD

EDX,

ECX

;quotient in EDX

Derivation for a, m, s The derivation for the algorithm (a), multiplier (m), and shift count (s), is found in the section “Signed Derivation for Algorithm, Multiplier, and Shift Factor” on page 95.

Signed Division By 2

;IN: EAX =

dividend

 

 

;OUT:EAX =

quotient

 

 

CMP

EAX,

800000000h

;CY = 1, if dividend >=0

 

SBB

EAX,

–1

;Increment dividend if it is < 0

 

SAR

EAX,

1

;Perform a right shift

Signed Division By 2n

;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,

800000000h

;CY = 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

;IN:EAX = dividend

 

–(2n)

;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

;IN:EAX = dividend

 

Integer 2 or –2

;OUT:EAX =

remainder

 

 

CDQ

 

 

;Sign extend into EDX

 

AND

EDX,

1

;Compute remainder

 

XOR

EAX,

EDX

;Negate remainder if

 

SUB

EAX,

EDX

;Dividend was < 0

 

MOV

[remainder], EAX

 

80

Replace Divides with Multiplies

Page 96
Image 96
AMD x86 manual Signed Division By 2n, Remainder of Signed, Integer 2 or