From 09f53d0eb19d0fc7b5775a4c6ab99e407b6744d7 Mon Sep 17 00:00:00 2001 From: Samuel Dionne-Riel Date: Wed, 17 Jul 2024 19:25:02 -0400 Subject: [PATCH] Implement four out of five suggested optimizations (#37) Fix #27 The remaining suggestion requires understanding where a label point to so that it can be replaced by its literal equivalent. See #36. --- src/chibi.h | 1 + src/optimize.c | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 37 insertions(+) diff --git a/src/chibi.h b/src/chibi.h index 0621a4b1..b4b1c748 100644 --- a/src/chibi.h +++ b/src/chibi.h @@ -375,6 +375,7 @@ typedef enum { EOR2 = EOR | flag_2, SFT2 = SFT | flag_2, + ORAk = ORA | flag_k, STA2k = STA2 | flag_k, STH2kr = STH2 | flag_k | flag_r, POP2r = POP2 | flag_r, diff --git a/src/optimize.c b/src/optimize.c index 4b7ab335..6c51a121 100644 --- a/src/optimize.c +++ b/src/optimize.c @@ -393,6 +393,42 @@ static bool optimize_pass(Instruction *prog, int stage) { continue; } + // + // https://github.com/lynn/chibicc/issues/27 + // + + // instances of #00 ORA, [can] be removed. + if (IsLit(prog, 0) && prog->next->opcode == ORA) { + memcpy(prog, prog->next->next, sizeof(Instruction)); + changed = true; + continue; + } + + // [SWP] static arithmetic operation e.g. #abcd SWP, could be #cdab. + if (prog->opcode == LIT2 && prog->next->opcode == SWP) { + unsigned short tmp = prog->literal; + prog->literal = ((tmp & 0xFF) << 8) | ((tmp & 0xFF00) >> 8 ); + prog->next = prog->next->next; + changed = true; + continue; + } + + // DUP2 #0000 EQU2, [can] be turned into ORAk #00 EQU + if (prog->opcode == DUP2 && IsLit2(prog->next, 0) && prog->next->next->opcode == EQU2) { + prog ->opcode = ORAk; + prog->next ->opcode = LIT; + prog->next->next->opcode = EQU; + changed = true; + continue; + } + + // #0000 SWP, to #0000 + if (IsLit2(prog, 0) && prog->next->opcode == SWP) { + memcpy(prog->next, prog->next->next, sizeof(Instruction)); + changed = true; + continue; + } + prog = prog->next; } return changed;