Skip to content

Commit 4c7fbe1

Browse files
committed
fix: fixes -O3 optimization
ld sp, nn | inc sp | dec sp pop NN cannot be replaced with: pop NN ld sp, nn | inc sp | dec sp
1 parent 7d24127 commit 4c7fbe1

File tree

4 files changed

+27
-3
lines changed

4 files changed

+27
-3
lines changed

src/arch/z80/optimizer/memcell.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -323,7 +323,7 @@ def affects(self, reglist: list[str] | str) -> bool:
323323
reglist = [reglist]
324324

325325
reglist = helpers.single_registers(reglist)
326-
return bool([x for x in self.destroys if x in reglist])
326+
return any(x for x in self.destroys if x in reglist)
327327

328328
def needs(self, reglist: list[str] | str) -> bool:
329329
"""Returns if this instruction need any of the registers
@@ -333,7 +333,7 @@ def needs(self, reglist: list[str] | str) -> bool:
333333
reglist = [reglist]
334334

335335
reglist = helpers.single_registers(reglist)
336-
return bool([x for x in self.requires if x in reglist])
336+
return any(x for x in self.requires if x in reglist)
337337

338338
@property
339339
def used_labels(self) -> list[str]:

src/arch/z80/peephole/opts/028_o3_pop_up.opt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ REPLACE {{
1818

1919
IF {{
2020
!(INSTR($2) IN (jp, jr, ret, call, djnz, rst)) && !NEEDS($2, (sp, $1)) && !IS_LABEL($2)
21+
&& OP1($2) <> "sp"
2122
}}
2223

2324
WITH {{

tests/arch/zx48k/optimizer/test_optimizer.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,3 +41,26 @@ def test_unrequired_or_a(self):
4141
with mock_options_level(4):
4242
optimized_code = optimizer.Optimizer().optimize(code)
4343
assert optimized_code.split("\n")[:2] == ["call .core.__LTI8", "ld bc, 0"]
44+
45+
def test_ld_sp_requires_sp(self):
46+
code_src = """
47+
ld sp, hl
48+
pop iy
49+
"""
50+
code = [x.strip() for x in code_src.split("\n") if x.strip()]
51+
52+
with mock_options_level(4):
53+
optimized_code = optimizer.Optimizer().optimize(code)
54+
assert optimized_code.split("\n")[:2] == ["ld sp, hl", "pop iy"]
55+
56+
def test_hd_sp_requires_sp(self):
57+
code_src = """
58+
add hl, sp
59+
pop iy
60+
jp (hl)
61+
"""
62+
code = [x.strip() for x in code_src.split("\n") if x.strip()]
63+
64+
with mock_options_level(3):
65+
optimized_code = optimizer.Optimizer().optimize(code)
66+
assert optimized_code.split("\n") == ["add hl, sp", "pop iy", "jp (hl)"]

tests/functional/zxnext/opt4_mul8.asm

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,10 +33,10 @@ _y:
3333
push hl
3434
call _printTest
3535
.core.__END_PROGRAM:
36-
pop iy
3736
di
3837
ld hl, (.core.__CALL_BACK__)
3938
ld sp, hl
39+
pop iy
4040
ei
4141
ret
4242
_printTest:

0 commit comments

Comments
 (0)