Skip to content

Commit e5f97c1

Browse files
committed
Optimized _DivideHLBC, fixed incorrect behavior for INT_MIN inputs
1 parent 2e07062 commit e5f97c1

File tree

1 file changed

+21
-24
lines changed

1 file changed

+21
-24
lines changed

src/graphx/graphx.asm

+21-24
Original file line numberDiff line numberDiff line change
@@ -6401,33 +6401,39 @@ _UCDivA:
64016401

64026402
;-------------------------------------------------------------------------------
64036403
_DivideHLBC:
6404-
; Performs signed integer division
6404+
; Performs signed integer division, rounding towards negative
64056405
; Inputs:
64066406
; HL : Operand 1
64076407
; BC : Operand 2
64086408
; Outputs:
6409-
; HL = HL/BC
6409+
; HL = floor(HL/BC)
6410+
ld a,23
64106411
ex de,hl
6411-
xor a,a
64126412
sbc hl,hl
6413+
ccf
64136414
sbc hl,bc
6414-
jp p,.next0
6415+
jp m,.positive
6416+
add hl,bc
6417+
inc hl
6418+
sbc hl,de
6419+
jp po,.signcheck
6420+
inc a
6421+
jr .overflowed
6422+
.positive:
6423+
inc hl
64156424
push hl
64166425
pop bc
6417-
inc a
6418-
.next0:
6419-
or a,a
6420-
sbc hl,hl
6421-
sbc hl,de
6422-
jp m,.next1
64236426
ex de,hl
6424-
inc a
6425-
.next1:
6426-
add hl,de
6427-
rra
6428-
ld a,24
6427+
.signcheck:
6428+
add hl,hl
6429+
ex de,hl
6430+
sbc hl,hl
6431+
jr nc,.loop
6432+
inc hl
6433+
sbc hl,bc
64296434
.loop:
64306435
ex de,hl
6436+
.overflowed:
64316437
adc hl,hl
64326438
ex de,hl
64336439
adc hl,hl
@@ -6437,17 +6443,8 @@ _DivideHLBC:
64376443
.spill:
64386444
dec a
64396445
jr nz,.loop
6440-
64416446
ex de,hl
64426447
adc hl,hl
6443-
ret c
6444-
dec de ; ude=UDE-1
6445-
add hl, de ; uhl=UHL+UDE-1
6446-
add hl, bc ; uhl=UHL+UDE+UBC-1
6447-
ex de, hl ; uhl=UDE-1, ude=UHL+UDE+UBC-1
6448-
add hl, bc ; uhl=UDE+UBC-1, carry set if UDE==0
6449-
ccf ; carry set if UDE!=0
6450-
sbc hl, de ; uhl=-UHL-(UDE!=0)
64516448
ret
64526449

64536450
;-------------------------------------------------------------------------------

0 commit comments

Comments
 (0)