From e3e38e832c083ce49874462381a3ff29a9e3e285 Mon Sep 17 00:00:00 2001 From: Daniel Serpell Date: Tue, 20 Oct 2026 20:06:13 -0300 Subject: [PATCH 01/11] fix: Document PRINT function output restriction Functions called from within a PRINT expression must only compute and return a value; nested output or I/O-channel changes invalidate the statement-local print state. Aided by Opencode / DeepSeek V4.1 Flash 1017 --- manual.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/manual.md b/manual.md index c88ff39..afa9ea1 100644 --- a/manual.md +++ b/manual.md @@ -1132,6 +1132,16 @@ Console Print and Input Statements S = 1234 ? #6, "SCORE: "; COLOR(32) S + A function called from within a + `PRINT` statement must only compute + and return its value. It must not + perform its own output or change the + I/O channel: the channel and print + color are statement-local, so a + nested `PRINT` changes the state + expected by the rest of the outer + statement. + The `TAB` function advances the position to a column multiple of the argument, so that `TAB(10)` is the From 2fdaaf27f5f043346d91c17e9b564916b1447622 Mon Sep 17 00:00:00 2001 From: Daniel Serpell Date: Tue, 20 Oct 2026 23:51:53 -0300 Subject: [PATCH 02/11] compiler: Reset print color at labels A label may be reached by a jump, so the tracked print color from the previous linear block is no longer valid. Reset it together with the top-of-stack tracking when a label is seen. Aided by Opencode / DeepSeek V4.1 Flash 1017 --- src/compiler/peephole.cc | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/compiler/peephole.cc b/src/compiler/peephole.cc index 84c1659..6776599 100644 --- a/src/compiler/peephole.cc +++ b/src/compiler/peephole.cc @@ -595,9 +595,12 @@ class peephole // Only go through tokens if(!code[i].is_tok()) { - // Invalidate TOS after a label + // Invalidate TOS and print color after a label if(code[i].is_label()) + { last_TOS_value = -1; + print_color = 0; + } continue; } From e7b2766348505c30071ab9ed912e3e76840b113a Mon Sep 17 00:00:00 2001 From: Daniel Serpell Date: Tue, 20 Oct 2026 23:52:03 -0300 Subject: [PATCH 03/11] compiler: Add pattern-based peephole rule engine Add a reusable token-pattern matcher with typed captures and replacement templates. Rules are compiled once into tables and dispatched by their first token. FASTBASIC_PEEPHOLE_DEBUG=1 prints parsed rules, matches and captures. Aided by Opencode / DeepSeek V4.1 Flash 1017 --- src/compiler/peephole-patterns.h | 533 +++++++++++++++++++++++++++++++ 1 file changed, 533 insertions(+) create mode 100644 src/compiler/peephole-patterns.h diff --git a/src/compiler/peephole-patterns.h b/src/compiler/peephole-patterns.h new file mode 100644 index 0000000..38815b7 --- /dev/null +++ b/src/compiler/peephole-patterns.h @@ -0,0 +1,533 @@ +/* + * FastBasic - Fast basic interpreter for the Atari 8-bit computers + * Copyright (C) 2017-2025 Daniel Serpell + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + */ + +// Small compiled token-pattern matcher used by the peephole optimizer. + +#pragma once + +#include "codew.h" +#include +#include +#include +#include +#include +#include +#include +#include + +inline bool peep_debug_enabled() +{ + static int enabled = -1; + if(enabled < 0) + { + auto e = std::getenv("FASTBASIC_PEEPHOLE_DEBUG"); + enabled = e && *e && std::string(e) != "0"; + } + return enabled; +} + +struct peep_state +{ + int print_color = 0; + bool color_pending = false; + int ioch = 0; + bool ioch_pending = false; + std::map tgt; + + void on_label() + { + print_color = 0; + color_pending = false; + ioch = 0; + ioch_pending = false; + } +}; + +class peep_match +{ + public: + enum capture_kind + { + cap_word, + cap_byte, + cap_varn, + cap_label, + cap_label_marker, + cap_string, + cap_any, + cap_span + }; + struct capture + { + capture_kind type; + size_t index; + size_t end; + int value; + bool numeric; + std::string text; + }; + size_t start = 0; + size_t end = 0; + peep_state &state; + std::map caps; + + explicit peep_match(peep_state &s) : state(s) {} + + int word(std::string name) const { return caps.at(name).value; } + int varn(std::string name) const { return caps.at(name).value; } + bool numeric(std::string name) const { return caps.at(name).numeric; } + std::string text(std::string name) const { return caps.at(name).text; } + bool is_label(std::string name) const + { + return caps.at(name).type == cap_label_marker; + } + void debug_caps() const + { + for(auto &c : caps) + std::cerr << " " << c.first << "=" << c.second.value << "\n"; + } +}; + +class peep_pattern +{ + private: + struct item + { + enum type + { + token, + word, + word_any, + byte_range, + byte, + byte_any, + varn, + label, + label_marker, + string, + any, + span + } type; + std::string value; + std::string name; + }; + std::string source; + std::vector items; + + public: + explicit peep_pattern(std::string p) : source(std::move(p)) + { + std::istringstream in(source); + std::string part; + while(in >> part) + { + item i; + if(part.size() > 1 && part[0] == '%') + { + auto colon = part.find(':'); + if(colon == std::string::npos) + throw std::runtime_error("invalid peephole capture '" + part + "'"); + std::string type = part.substr(1, colon - 1); + std::string rest = part.substr(colon + 1); + auto second = rest.find(':'); + i.name = rest.substr(0, second); + if(type == "w") + i.type = item::word; + else if(type == "W") + i.type = item::word_any; + else if(type == "c") + i.type = item::byte_range; + else if(type == "b") + i.type = item::byte; + else if(type == "B") + i.type = item::byte_any; + else if(type == "v") + i.type = item::varn; + else if(type == "l") + i.type = item::label; + else if(type == "L") + i.type = item::label_marker; + else if(type == "s") + i.type = item::string; + else if(type == "a") + i.type = item::any; + else if(type == "e") + { + i.type = item::span; + if(second == std::string::npos) + throw std::runtime_error("missing span terminator in '" + source + "'"); + i.value = rest.substr(second + 1); + } + else + throw std::runtime_error("invalid peephole capture type in '" + part + "'"); + } + else + { + i.type = item::token; + i.value = part; + } + items.push_back(i); + } + } + + std::string first() const + { + if(items.empty() || items[0].type != item::token) + return std::string(); + return items[0].value; + } + + const std::string &source_text() const { return source; } + + bool match(std::vector &code, size_t current, peep_match &out) const + { + out.caps.clear(); + out.start = current; + size_t pos = current; + for(auto &i : items) + { + switch(i.type) + { + case item::token: + if(pos >= code.size() || !code[pos].is_tok(i.value)) + return false; + pos++; + break; + case item::word: + if(pos >= code.size() || !code[pos].is_word()) + return false; + out.caps[i.name] = {peep_match::cap_word, pos, pos + 1, + (int16_t)code[pos].get_val(), true, {}}; + pos++; + break; + case item::word_any: + if(pos >= code.size() || + !(code[pos].is_word() || code[pos].is_sword())) + return false; + out.caps[i.name] = { + peep_match::cap_word, pos, pos + 1, + code[pos].is_word() ? (int16_t)code[pos].get_val() : 0, + code[pos].is_word(), + code[pos].is_word() ? std::string() : code[pos].get_str()}; + pos++; + break; + case item::byte_range: + if(pos >= code.size() || !code[pos].is_word() || + code[pos].get_val() < 0 || code[pos].get_val() > 255) + return false; + out.caps[i.name] = {peep_match::cap_word, pos, pos + 1, + code[pos].get_val(), true, {}}; + pos++; + break; + case item::byte: + if(pos >= code.size() || !code[pos].is_byte()) + return false; + out.caps[i.name] = {peep_match::cap_byte, pos, pos + 1, + code[pos].get_val(), true, {}}; + pos++; + break; + case item::byte_any: + if(pos >= code.size() || + !(code[pos].is_byte() || code[pos].is_sbyte())) + return false; + out.caps[i.name] = { + peep_match::cap_byte, pos, pos + 1, + code[pos].is_byte() ? code[pos].get_val() : 0, + code[pos].is_byte(), + code[pos].is_byte() ? std::string() : code[pos].get_str()}; + pos++; + break; + case item::varn: + if(pos >= code.size() || !code[pos].is_varn()) + return false; + out.caps[i.name] = {peep_match::cap_varn, pos, pos + 1, + code[pos].get_varn(), true, {}}; + pos++; + break; + case item::label: + if(pos >= code.size() || !code[pos].is_sword()) + return false; + out.caps[i.name] = {peep_match::cap_label, pos, pos + 1, 0, false, + code[pos].get_str()}; + pos++; + break; + case item::label_marker: + if(pos >= code.size() || !code[pos].is_label()) + return false; + out.caps[i.name] = {peep_match::cap_label_marker, pos, pos + 1, 0, + false, code[pos].get_str()}; + pos++; + break; + case item::string: + if(pos >= code.size() || !code[pos].is_string()) + return false; + out.caps[i.name] = {peep_match::cap_string, pos, pos + 1, 0, false, + code[pos].get_str()}; + pos++; + break; + case item::any: + { + if(pos >= code.size()) + return false; + bool numeric = code[pos].is_byte() || code[pos].is_word(); + int value = numeric && code[pos].is_word() + ? (int16_t)code[pos].get_val() + : (numeric ? code[pos].get_val() : 0); + out.caps[i.name] = {code[pos].is_label() + ? peep_match::cap_label_marker + : peep_match::cap_any, + pos, pos + 1, value, numeric, {}}; + pos++; + break; + } + case item::span: + { + size_t begin = pos; + while(pos < code.size() && !code[pos].is_tok(i.value)) + pos++; + if(pos == begin || pos >= code.size()) + return false; + out.caps[i.name] = {peep_match::cap_span, begin, pos, 0, false, {}}; + break; + } + } + } + out.end = pos; + return true; + } +}; + +class peep_builder +{ + private: + const std::vector *code; + int line; + public: + std::vector out; + bool modified = true; + peep_builder(const std::vector &c, int l) : code(&c), line(l) {} + void keep() { modified = false; } + void tok(std::string t) { out.push_back(codew::ctok(t, line)); } + void word(int v) { out.push_back(codew::cword(v, line)); } + void symbol(std::string s) { out.push_back(codew::cword(s, line)); } + void byte(int v) { out.push_back(codew::cbyte(v, line)); } + void string(std::string s) { out.push_back(codew::cstring(s, line)); } + void emit_value(const std::string &part, int value) + { + if(part == "%w") + word(value & 0xFFFF); + else if(part == "%b") + byte(value & 0xFF); + else + throw std::runtime_error("invalid peephole format: " + part); + } + void emit_value(const std::string &part, const std::string &value) + { + if(part == "%s") + string(value); + else + throw std::runtime_error("invalid peephole format: " + part); + } + template + void write(const char *format, T value) + { + std::istringstream in(format); + std::string part; + bool used = false; + while(in >> part) + { + if(part.size() > 1 && part[0] == '%') + { + if(used) + throw std::runtime_error("multiple values in peephole format"); + emit_value(part, value); + used = true; + } + else + tok(part); + } + if(!used) + throw std::runtime_error("missing value in peephole format"); + } + void write(const char *format, const peep_match &m) + { + std::istringstream in(format); + std::string part; + while(in >> part) + { + if(part.size() > 1 && part[0] == '$') + raw(m, part.substr(1)); + else if(part.size() > 1 && part[0] == '%') + throw std::runtime_error("value required in peephole format"); + else + tok(part); + } + } + void raw(const peep_match &m, std::string name) + { + auto &c = m.caps.at(name); + if(c.type == peep_match::cap_span) + for(size_t i = c.index; i < c.end; ++i) + out.push_back((*code)[i]); + else + out.push_back((*code)[c.index]); + } + bool valid_span(const peep_match &m, const std::string &name) const + { + auto it = m.caps.find(name); + if(it == m.caps.end() || it->second.type != peep_match::cap_span || + it->second.index >= it->second.end) + return false; + int line = (*code)[it->second.index].linenum(); + for(size_t i = it->second.index; i < it->second.end; ++i) + { + auto &c = (*code)[i]; + if(c.linenum() != line || c.is_label()) + return false; + if(c.is_tok()) + { + auto t = c.get_tok(); + if(t == "TOK_POKE" || t == "TOK_DPOKE" || + t == "TOK_BYTE_POKE" || t == "TOK_NUM_POKE" || + t == "TOK_PUT" || t == "TOK_END") + return false; + } + } + return true; + } +}; + +class peep_rule +{ + public: + using cond_fn = std::function; + using action_fn = std::function; + struct rep_item + { + bool capture; + char mode; + std::string value; + }; + peep_pattern pattern; + std::vector replacement; + action_fn action; + cond_fn condition; + + peep_rule(std::string pat, std::string repl, cond_fn cond = {}) + : pattern(std::move(pat)), action(), condition(std::move(cond)) + { + std::istringstream in(repl); + std::string part; + while(in >> part) + { + if(part.size() > 1 && part[0] == '$') + { + auto colon = part.find(':'); + char mode = 0; + std::string name = part.substr(1, colon == std::string::npos + ? std::string::npos + : colon - 1); + if(colon != std::string::npos) + mode = part[colon + 1]; + replacement.push_back({true, mode, name}); + } + else + replacement.push_back({false, 0, part}); + } + } + peep_rule(std::string pat, action_fn act, cond_fn cond = {}) + : pattern(std::move(pat)), action(std::move(act)), condition(std::move(cond)) + { + } + + bool match(std::vector &code, size_t current, peep_match &m) const + { + return pattern.match(code, current, m) && + (!condition || condition(m)); + } + void build(const peep_match &m, peep_builder &b) const + { + if(action) + { + action(m, b); + return; + } + for(auto &r : replacement) + { + if(!r.capture) + b.tok(r.value); + else if(r.mode == 'b') + b.byte(m.word(r.value)); + else if(r.mode == 'w') + b.word(m.word(r.value)); + else + b.raw(m, r.value); + } + } +}; + +class peep_rules +{ + private: + std::string name; + std::vector rules; + std::map> by_first; + + public: + peep_rules(std::string n, std::vector r) + : name(std::move(n)), rules(std::move(r)) + { + for(size_t i = 0; i < rules.size(); i++) + by_first[rules[i].pattern.first()].push_back(i); + if(peep_debug_enabled()) + for(size_t i = 0; i < rules.size(); i++) + std::cerr << "peephole pattern [" << name << "] #" << i + << ": " << rules[i].pattern.source_text() << "\n"; + } + bool apply(std::vector &code, size_t current, peep_state &state, + std::vector &repl, size_t &begin, size_t &end, + bool &modified) const + { + if(current >= code.size() || !code[current].is_tok()) + return false; + auto it = by_first.find(code[current].get_tok()); + if(it == by_first.end()) + return false; + peep_match m(state); + for(size_t index : it->second) + { + auto &rule = rules[index]; + if(!rule.match(code, current, m)) + continue; + if(peep_debug_enabled()) + { + std::cerr << "peephole match [" << name << "] #" << index + << ": " << rule.pattern.source_text() << "\n"; + m.debug_caps(); + } + peep_builder b(code, code[current].linenum()); + rule.build(m, b); + if(peep_debug_enabled() && b.modified) + std::cerr << "peephole apply [" << name << "] #" << index + << ": " << rule.pattern.source_text() << "\n"; + repl = std::move(b.out); + begin = m.start; + end = m.end; + modified = b.modified; + return true; + } + return false; + } +}; From 69d8cf0f34a6be88277aaa150e8a2eb6c85a8143 Mon Sep 17 00:00:00 2001 From: Daniel Serpell Date: Tue, 20 Oct 2026 23:52:44 -0300 Subject: [PATCH 04/11] compiler: Convert local peephole rules to pattern tables Replace the arithmetic, memory, I/O, POKE, constant, variable, update, boolean, branch and print-join checks with entries in the compiled rule table. Structural passes that need to inspect whole ranges still run procedurally. Aided by Opencode / DeepSeek V4.1 Flash 1017 --- src/compiler/peephole.cc | 1440 ++++++++++---------------------------- 1 file changed, 363 insertions(+), 1077 deletions(-) diff --git a/src/compiler/peephole.cc b/src/compiler/peephole.cc index 6776599..d5cb6b2 100644 --- a/src/compiler/peephole.cc +++ b/src/compiler/peephole.cc @@ -19,15 +19,358 @@ // peephole.cc: Peephole optimizer #include "peephole.h" +#include "peephole-patterns.h" #include #include +static std::vector make_peephole_rules() +{ + return { + {"TOK_NUM %w:x TOK_NEG", + [](const peep_match &m, peep_builder &b) { + b.write("TOK_NUM %w", -m.word("x")); + }}, + {"TOK_NUM %w:x TOK_USHL", + [](const peep_match &m, peep_builder &b) { + b.write("TOK_NUM %w", 2 * m.word("x")); + }}, + {"TOK_NUM %w:x TOK_SHL8", + [](const peep_match &m, peep_builder &b) { + b.write("TOK_NUM %w", 256 * m.word("x")); + }}, + {"TOK_PUSH TOK_NUM %w:x TOK_MUL", "TOK_SHL8", + [](const peep_match &m) { return m.word("x") == 256; }}, + {"TOK_PUSH TOK_NUM %w:x TOK_MUL", "TOK_USHL TOK_USHL", + [](const peep_match &m) { return m.word("x") == 4; }}, + {"TOK_PUSH TOK_NUM %w:x TOK_MUL", "TOK_USHL", + [](const peep_match &m) { return m.word("x") == 2; }}, + {"TOK_PUSH TOK_NUM %w:x TOK_MUL", "", + [](const peep_match &m) { return m.word("x") == 1; }}, + {"TOK_PUSH TOK_NUM %w:x TOK_DIV", "", + [](const peep_match &m) { return m.word("x") == 1; }}, + {"TOK_PUSH TOK_NUM %w:x TOK_ADD", "", + [](const peep_match &m) { return m.word("x") == 0; }}, + {"TOK_PUSH TOK_NUM %w:x TOK_SUB", "", + [](const peep_match &m) { return m.word("x") == 0; }}, + {"TOK_PUSH TOK_NUM %w:x TOK_NEQ", "TOK_COMP_0", + [](const peep_match &m) { return m.word("x") == 0; }}, + {"TOK_PUSH TOK_NUM %w:x TOK_EQ", "TOK_COMP_0 TOK_L_NOT", + [](const peep_match &m) { return m.word("x") == 0; }}, + {"TOK_NUM %w:x TOK_ADD_VAR %v:v", + "TOK_VAR_LOAD $v", + [](const peep_match &m) { return m.word("x") == 0; }}, + {"TOK_NUM %w:x TOK_PUSH TOK_NUM %w:y TOK_ADD", + [](const peep_match &m, peep_builder &b) { + b.write("TOK_NUM %w", m.word("x") + m.word("y")); + }}, + {"TOK_NUM %w:x TOK_PUSH TOK_NUM %w:y TOK_SUB", + [](const peep_match &m, peep_builder &b) { + b.write("TOK_NUM %w", m.word("x") - m.word("y")); + }}, + // Memory and I/O. + {"TOK_NUM %w:x TOK_VAR_STORE %v:v", + "TOK_VAR_STORE_0 $v", + [](const peep_match &m) { return m.word("x") == 0; }}, + {"TOK_VAR_ADDR %v:v TOK_SADDR TOK_GET TOK_DPOKE", + "TOK_GET TOK_VAR_STORE $v"}, + {"TOK_VAR_ADDR %v:v TOK_SADDR TOK_GETKEY TOK_DPOKE", + "TOK_GETKEY TOK_VAR_STORE $v"}, + {"TOK_NUM %w:x TOK_PUT", + [](const peep_match &m, peep_builder &b) { + b.write("TOK_BYTE_PUT %b", m.word("x")); + }}, + {"TOK_BYTE %B:x TOK_PUT", "TOK_BYTE_PUT $x"}, + // Track PRINT_COLOR and remove redundant color changes. + {"TOK_NUM %w:x TOK_BYTE_POKE %B:color", + [](const peep_match &m, peep_builder &b) { + int x = m.word("x"); + if(x == m.state.print_color) + return; + m.state.print_color = x; + m.state.color_pending = true; + b.keep(); + }, + [](const peep_match &m) { + return m.text("color") == "PRINT_COLOR"; + }}, + // A color change from a non-constant expression is unknown. + {"TOK_BYTE_POKE %B:color", + [](const peep_match &m, peep_builder &b) { + if(m.state.color_pending) + m.state.color_pending = false; + else + m.state.print_color = -1; + b.keep(); + }, + [](const peep_match &m) { + return m.text("color") == "PRINT_COLOR"; + }}, + {"TOK_NUM %c:x TOK_PEEK", + [](const peep_match &m, peep_builder &b) { + b.write("TOK_BYTE_PEEK %b", m.word("x")); + }}, + {"TOK_BYTE %B:x TOK_PEEK", "TOK_BYTE_PEEK $x"}, + // Constant-address POKE variants. + {"TOK_NUM %c:a TOK_SADDR TOK_NUM %w:v TOK_POKE", + [](const peep_match &m, peep_builder &b) { + b.write("TOK_NUM %w", m.word("v") & 255); + b.write("TOK_BYTE_POKE %b", m.word("a")); + }}, + {"TOK_NUM %c:a TOK_SADDR TOK_VAR_LOAD %v:v TOK_POKE", + [](const peep_match &m, peep_builder &b) { + b.write("TOK_VAR_LOAD $v", m); + b.write("TOK_BYTE_POKE %b", m.word("a")); + }}, + {"TOK_BYTE %B:a TOK_SADDR TOK_NUM %w:v TOK_POKE", + [](const peep_match &m, peep_builder &b) { + b.write("TOK_NUM %w", m.word("v") & 255); + b.write("TOK_BYTE_POKE $a", m); + }}, + {"TOK_BYTE %B:a TOK_SADDR TOK_VAR_LOAD %v:v TOK_POKE", + [](const peep_match &m, peep_builder &b) { + b.write("TOK_VAR_LOAD $v TOK_BYTE_POKE $a", m); + }}, + {"TOK_NUM %W:a TOK_SADDR TOK_NUM %w:v TOK_POKE", + [](const peep_match &m, peep_builder &b) { + b.write("TOK_NUM %w", m.word("v") & 255); + b.write("TOK_NUM_POKE $a", m); + }}, + {"TOK_NUM %w:a TOK_SADDR TOK_VAR_LOAD %v:v TOK_POKE", + [](const peep_match &m, peep_builder &b) { + b.write("TOK_VAR_LOAD $v", m); + b.write("TOK_NUM_POKE %w", m.word("a")); + }}, + // Constant arithmetic operations. + {"TOK_NUM %w:x TOK_PUSH TOK_NUM %w:y TOK_MUL", + [](const peep_match &m, peep_builder &b) { + b.write("TOK_NUM %w", m.word("x") * m.word("y")); + }}, + {"TOK_NUM %w:x TOK_PUSH TOK_NUM %w:y TOK_DIV", + [](const peep_match &m, peep_builder &b) { + int y = m.word("y"); + int v = y ? m.word("x") / y : (m.word("x") < 0 ? 1 : -1); + b.write("TOK_NUM %w", v); + }}, + {"TOK_NUM %w:x TOK_PUSH TOK_NUM %w:y TOK_MOD", + [](const peep_match &m, peep_builder &b) { + int y = m.word("y"); + int v = y ? m.word("x") % y : m.word("x"); + b.write("TOK_NUM %w", v); + }}, + {"TOK_NUM %w:x TOK_PUSH TOK_NUM %w:y TOK_BIT_AND", + [](const peep_match &m, peep_builder &b) { + b.write("TOK_NUM %w", m.word("x") & m.word("y")); + }}, + {"TOK_NUM %w:x TOK_PUSH TOK_NUM %w:y TOK_BIT_OR", + [](const peep_match &m, peep_builder &b) { + b.write("TOK_NUM %w", m.word("x") | m.word("y")); + }}, + {"TOK_NUM %w:x TOK_PUSH TOK_NUM %w:y TOK_BIT_EXOR", + [](const peep_match &m, peep_builder &b) { + b.write("TOK_NUM %w", m.word("x") ^ m.word("y")); + }}, + // Variable updates. + {"TOK_PUSH TOK_VAR_LOAD %v:x TOK_ADD", + "TOK_ADD_VAR $x"}, + {"TOK_VAR_LOAD %v:x TOK_PUSH TOK_NUM %w:y TOK_ADD", + "TOK_NUM $y:w TOK_ADD_VAR $x"}, + {"TOK_VAR_LOAD %v:x TOK_PUSH TOK_VAR_LOAD %v:y TOK_ADD", + "TOK_VAR_LOAD $x TOK_USHL", + [](const peep_match &m) { return m.varn("x") == m.varn("y"); }}, + {"TOK_NUM %w:one TOK_ADD_VAR %v:x TOK_VAR_STORE %v:y", + "TOK_INCVAR $x", + [](const peep_match &m) { + return m.word("one") == 1 && m.varn("x") == m.varn("y"); + }}, + {"TOK_VAR_LOAD %v:x TOK_PUSH TOK_NUM %w:one TOK_ADD " + "TOK_VAR_STORE %v:y", + "TOK_INCVAR $x", + [](const peep_match &m) { + return m.word("one") == 1 && m.varn("x") == m.varn("y"); + }}, + {"TOK_VAR_LOAD %v:x TOK_PUSH TOK_NUM %w:one TOK_SUB " + "TOK_VAR_STORE %v:y", + "TOK_DECVAR $x", + [](const peep_match &m) { + return m.word("one") == 1 && m.varn("x") == m.varn("y"); + }}, + {"TOK_VAR_ADDR %v:x TOK_INC", "TOK_INCVAR $x"}, + {"TOK_SADDR TOK_INC", "TOK_INC"}, + {"TOK_VAR_ADDR %v:x TOK_DEC", "TOK_DECVAR $x"}, + {"TOK_SADDR TOK_DEC", "TOK_DEC"}, + // Boolean and branch simplifications. + {"TOK_L_NOT TOK_L_NOT", "TOK_COMP_0"}, + {"TOK_EQ TOK_L_NOT", "TOK_NEQ"}, + {"TOK_NEQ TOK_L_NOT", "TOK_EQ"}, + {"TOK_CALL %l:target TOK_RET", "TOK_JUMP $target"}, + {"TOK_L_NOT TOK_CJUMP", "TOK_CNJUMP"}, + {"TOK_L_NOT TOK_CNJUMP", "TOK_CJUMP"}, + {"TOK_CJUMP %l:from TOK_JUMP %l:to %L:end", + "TOK_CNJUMP $to $end", + [](const peep_match &m) { + return m.text("from") == m.text("end"); + }}, + {"TOK_CJUMP %l:from TOK_RET %L:end", + "TOK_CNRET $end", + [](const peep_match &m) { + return m.text("from") == m.text("end"); + }}, + {"TOK_CJUMP %l:from TOK_NUM %w:v TOK_RET %L:end", + "TOK_CNRET $end", + [](const peep_match &m) { + return m.word("v") == 0 && m.text("from") == m.text("end"); + }}, + {"TOK_CNJUMP %l:from TOK_JUMP %l:to %L:end", + "TOK_CJUMP $to $end", + [](const peep_match &m) { + return m.text("from") == m.text("end"); + }}, + {"TOK_CNJUMP %l:from TOK_RET %L:end", + "TOK_CRET $end", + [](const peep_match &m) { + return m.text("from") == m.text("end"); + }}, + {"TOK_CNJUMP %l:from TOK_NUM %w:v TOK_RET %L:end", + "TOK_CRET $end", + [](const peep_match &m) { + return m.word("v") == 0 && m.text("from") == m.text("end"); + }}, + {"TOK_L_NOT TOK_CRET", "TOK_CNRET"}, + {"TOK_L_NOT TOK_CNRET", "TOK_CRET"}, + {"TOK_NUM %w:x TOK_COMP_0", + [](const peep_match &m, peep_builder &b) { + b.write("TOK_NUM %w", m.word("x") ? 1 : 0); + }}, + {"TOK_NUM %w:x TOK_CNJUMP %l:target", + [](const peep_match &m, peep_builder &b) { + if(m.word("x")) + { + b.write("TOK_JUMP $target", m); + } + }}, + {"TOK_NUM %w:x TOK_CJUMP %l:target", + [](const peep_match &m, peep_builder &b) { + if(!m.word("x")) + { + b.write("TOK_JUMP $target", m); + } + }}, + // Transform multiple subtractions to addition: + // PUSH a SUB PUSH b SUB -> PUSH a PUSH b ADD SUB + {"TOK_PUSH TOK_VAR_LOAD %v:a TOK_SUB TOK_PUSH TOK_VAR_LOAD %v:b TOK_SUB", + "TOK_PUSH TOK_VAR_LOAD $a TOK_PUSH TOK_VAR_LOAD $b TOK_ADD TOK_SUB"}, + {"TOK_PUSH TOK_VAR_LOAD %v:a TOK_SUB TOK_PUSH TOK_NUM %w:b TOK_SUB", + "TOK_PUSH TOK_VAR_LOAD $a TOK_PUSH TOK_NUM $b TOK_ADD TOK_SUB"}, + {"TOK_PUSH TOK_NUM %w:a TOK_SUB TOK_PUSH TOK_VAR_LOAD %v:b TOK_SUB", + "TOK_PUSH TOK_NUM $a TOK_PUSH TOK_VAR_LOAD $b TOK_ADD TOK_SUB"}, + {"TOK_PUSH TOK_NUM %w:a TOK_SUB TOK_PUSH TOK_NUM %w:b TOK_SUB", + "TOK_PUSH TOK_NUM $a TOK_PUSH TOK_NUM $b TOK_ADD TOK_SUB"}, + // VAR + VAR * 2 -> VAR * 2 + VAR + {"TOK_VAR_LOAD %v:x TOK_PUSH TOK_VAR_LOAD %v:y TOK_USHL TOK_ADD", + "TOK_VAR_LOAD $y TOK_USHL TOK_ADD_VAR $x"}, + // Array indexing: ARR(VAR + X) with a word index. + {"TOK_VAR_LOAD %v:x TOK_PUSH TOK_NUM %w:n TOK_ADD_VAR %v:y TOK_USHL TOK_ADD", + "TOK_NUM $n TOK_ADD_VAR $y TOK_USHL TOK_ADD_VAR $x"}, + // VAR = VAR +/- 1 through the address/DPOKE sequence. + {"TOK_VAR_ADDR %v:x TOK_SADDR TOK_VAR_LOAD %v:y TOK_PUSH TOK_NUM %w:one " + "TOK_ADD TOK_DPOKE", + "TOK_INCVAR $x", + [](const peep_match &m) { + return m.word("one") == 1 && m.varn("x") == m.varn("y"); + }}, + {"TOK_VAR_ADDR %v:x TOK_SADDR TOK_VAR_LOAD %v:y TOK_PUSH TOK_NUM %w:one " + "TOK_SUB TOK_DPOKE", + "TOK_DECVAR $x", + [](const peep_match &m) { + return m.word("one") == 1 && m.varn("x") == m.varn("y"); + }}, + // Boolean results already normalized by COMP_0 need no second test. + {"TOK_NEQ TOK_COMP_0", "TOK_NEQ"}, + {"TOK_L_AND TOK_COMP_0", "TOK_L_AND"}, + {"TOK_L_OR TOK_COMP_0", "TOK_L_OR"}, + {"TOK_L_NOT TOK_COMP_0", "TOK_L_NOT"}, + {"TOK_COMP_0 TOK_COMP_0", "TOK_COMP_0"}, + {"TOK_EQ TOK_COMP_0", "TOK_EQ"}, + {"TOK_LT TOK_COMP_0", "TOK_LT"}, + {"TOK_GT TOK_COMP_0", "TOK_GT"}, + // NOT (A > x) == A <= x -> A < x+1 + {"TOK_NUM %w:x TOK_GT TOK_L_NOT", + [](const peep_match &m, peep_builder &b) { + int x = m.word("x"); + if(x == 32637) + b.write("TOK_NUM %w TOK_BIT_OR TOK_COMP_0", 1); + else + b.write("TOK_NUM %w TOK_LT", (x + 1) & 0xFFFF); + }}, + // STRING[i, n>255] -> STRING[i, 255] + {"TOK_NUM %w:x TOK_STR_IDX", + [](const peep_match &m, peep_builder &b) { + b.write("TOK_NUM %w TOK_STR_IDX", 255); + }, + [](const peep_match &m) { return m.word("x") > 255; }}, + // NOT (A < x) == A >= x -> A > x-1 + {"TOK_NUM %w:x TOK_LT TOK_L_NOT", + [](const peep_match &m, peep_builder &b) { + int x = m.word("x"); + if(x == -32768) + b.write("TOK_NUM %w TOK_BIT_OR TOK_COMP_0", 1); + else + b.write("TOK_NUM %w TOK_GT", (x - 1) & 0xFFFF); + }}, + // JUMP to the immediately following label. + {"TOK_JUMP %l:target %L:label", + "$label", + [](const peep_match &m) { + return m.text("target") == m.text("label"); + }}, + // Drop one dead item after an unconditional JUMP. + {"TOK_JUMP %l:target %a:dead", + "TOK_JUMP $target", + [](const peep_match &m) { return !m.is_label("dead"); }}, + // Drop dead code after RET or END. + {"TOK_RET %a:dead", "TOK_RET", + [](const peep_match &m) { return !m.is_label("dead"); }}, + {"TOK_END %a:dead", "TOK_END", + [](const peep_match &m) { return !m.is_label("dead"); }}, + // PRINT CHR$(X) is the same as PUT X. + {"TOK_CHR TOK_PRINT_STR", "TOK_PUT"}, + // Join a constant string with a known-color PUT. + {"TOK_CSTRING %s:s TOK_PRINT_STR TOK_NUM %w:x TOK_PUT", + [](const peep_match &m, peep_builder &b) { + b.write("TOK_CSTRING %s TOK_PRINT_STR", + m.text("s") + char(m.word("x") ^ m.state.print_color)); + }, + [](const peep_match &m) { + return m.text("s").size() < 255 && m.state.print_color >= 0; + }}, + {"TOK_CSTRING %s:s TOK_PRINT_STR TOK_BYTE_PUT %a:x", + [](const peep_match &m, peep_builder &b) { + b.write("TOK_CSTRING %s TOK_PRINT_STR", + m.text("s") + char(m.word("x") ^ m.state.print_color)); + }, + [](const peep_match &m) { + return m.numeric("x") && m.text("s").size() < 255 && + m.state.print_color >= 0; + }}, + // Join two adjacent constant strings. + {"TOK_CSTRING %s:s1 TOK_PRINT_STR TOK_CSTRING %s:s2 TOK_PRINT_STR", + [](const peep_match &m, peep_builder &b) { + b.write("TOK_CSTRING %s TOK_PRINT_STR", + m.text("s1") + m.text("s2")); + }, + [](const peep_match &m) { + return m.text("s1").size() + m.text("s2").size() < 256; + }}, + }; +} + // Implements a simple peephole optimizer class peephole { private: bool changed; std::vector &code; + peep_rules rules; size_t current; // Matching functions for the peephole opt bool mtok(size_t idx, std::string tok) @@ -146,25 +489,6 @@ class peephole lnum = code[idx + current].linenum(); code.insert(code.begin() + idx + current, codew::ctok(tok, lnum)); } - // Detect "X (op) Y" - bool const_op(std::string tok) - { - return mtok(0, "TOK_NUM") && mword(1) && mtok(2, "TOK_PUSH") && - mtok(3, "TOK_NUM") && mword(4) && mtok(5, tok); - } - void copy(size_t idx, size_t from, size_t num) - { - changed = true; - while(num) - { - code.insert(code.begin() + idx + current, code[from + current]); - num--; - idx++; - from++; - if(from >= idx) - from++; - } - } void set_ws(size_t idx, std::string str) { changed = true; @@ -190,6 +514,12 @@ class peephole changed = true; code[idx + current] = codew::cstring(str, code[idx + current].linenum()); } + void replace_range(size_t begin, size_t end, std::vector &&replacement) + { + changed = true; + code.erase(code.begin() + begin, code.begin() + end); + code.insert(code.begin() + begin, replacement.begin(), replacement.end()); + } // Transforms all "numeric" tokens to TOK_NUM, so that the next phases can // optimize void expand_numbers() @@ -575,7 +905,8 @@ class peephole } public: - peephole(std::vector &code) : code(code), current(0) + peephole(std::vector &code) + : code(code), rules("main", make_peephole_rules()), current(0) { expand_push(); expand_numbers(); @@ -585,1078 +916,33 @@ class peephole remove_unused_labels(); replace_label_targets(); trace_iochn(); - int print_color = 0; - // Tracks last top-of-stack value, if known - int last_TOS_value = -1; + peep_state state; for(size_t i = 0; i < code.size(); i++) { - // Only go through tokens if(!code[i].is_tok()) - { - // Invalidate TOS and print color after a label - if(code[i].is_label()) - { - last_TOS_value = -1; - print_color = 0; - } continue; - } current = i; - // Track current print color - if(mtok(0, "TOK_BYTE_POKE") && mcbyte(1, "PRINT_COLOR")) - { - print_color = last_TOS_value; - last_TOS_value = -1; - continue; - } - - // Track TOS value - if(mtok(0, "TOK_NUM") && mword(1)) - last_TOS_value = val(1); - else - last_TOS_value = -1; - - // Remove extra PRINT COLOR - if(mtok(0, "TOK_NUM") && mword(1) && mtok(2, "TOK_BYTE_POKE") && - mcbyte(3, "PRINT_COLOR")) + // Apply compiled token-rewrite rules. { - // Remove if we are setting the same color as already set: - if(val(1) == print_color) + std::vector replacement; + size_t begin, end; + bool modified; + if(rules.apply(code, i, state, replacement, begin, end, + modified)) { - del(3); - del(2); - del(1); - del(0); - i--; + if(modified) + { + replace_range(begin, end, std::move(replacement)); + i--; + } continue; } } - // Sequences: - // TOK_NUM / x / TOK_NEG -> TOK_NUM / -x - if(mtok(0, "TOK_NUM") && mword(1) && mtok(2, "TOK_NEG")) - { - del(2); - set_w(1, -val(1)); - i--; - continue; - } - // TOK_NUM / x / TOK_USHL -> TOK_NUM / 2*x - if(mtok(0, "TOK_NUM") && mword(1) && mtok(2, "TOK_USHL")) - { - del(2); - set_w(1, 2 * val(1)); - i--; - continue; - } - // TOK_NUM / x / TOK_SHL8 -> TOK_NUM / 256*x - if(mtok(0, "TOK_NUM") && mword(1) && mtok(2, "TOK_SHL8")) - { - - del(2); - set_w(1, 256 * val(1)); - i--; - continue; - } - // TOK_PUSH / TOK_NUM / 256 / TOK_MUL -> TOK_SHL8 - if(mtok(0, "TOK_PUSH") && mtok(1, "TOK_NUM") && mword(2) && - val(2) == 256 && mtok(3, "TOK_MUL")) - { - del(3); - del(2); - del(1); - set_tok(0, "TOK_SHL8"); - i--; - continue; - } - // TOK_PUSH / TOK_NUM / 4 / TOK_MUL -> TOK_USHL TOK_USHL - if(mtok(0, "TOK_PUSH") && mtok(1, "TOK_NUM") && mword(2) && val(2) == 4 && - mtok(3, "TOK_MUL")) - { - del(3); - del(2); - set_tok(1, "TOK_USHL"); - set_tok(0, "TOK_USHL"); - i--; - continue; - } - // TOK_PUSH / TOK_NUM / 2 / TOK_MUL -> TOK_USHL - if(mtok(0, "TOK_PUSH") && mtok(1, "TOK_NUM") && mword(2) && val(2) == 2 && - mtok(3, "TOK_MUL")) - { - del(3); - del(2); - del(1); - set_tok(0, "TOK_USHL"); - i--; - continue; - } - // TOK_PUSH / TOK_NUM / 1 / TOK_MUL -> - - if(mtok(0, "TOK_PUSH") && mtok(1, "TOK_NUM") && mword(2) && val(2) == 1 && - mtok(3, "TOK_MUL")) - { - del(3); - del(2); - del(1); - del(0); - i--; - continue; - } - // TOK_PUSH / TOK_NUM / 1 / TOK_DIV -> - - if(mtok(0, "TOK_PUSH") && mtok(1, "TOK_NUM") && mword(2) && val(2) == 1 && - mtok(3, "TOK_DIV")) - { - del(3); - del(2); - del(1); - del(0); - i--; - continue; - } - // TOK_PUSH / TOK_NUM / 0 / TOK_ADD -> - - if(mtok(0, "TOK_PUSH") && mtok(1, "TOK_NUM") && mword(2) && val(2) == 0 && - mtok(3, "TOK_ADD")) - { - del(3); - del(2); - del(1); - del(0); - i--; - continue; - } - // TOK_NUM / 0 / TOK_ADD_VAR -> TOK_VAR_LOAD - if(mtok(0, "TOK_NUM") && mword(1) && val(1) == 0 && - mtok(2, "TOK_ADD_VAR")) - { - del(1); - del(0); - set_tok(0, "TOK_VAR_LOAD"); - i--; - continue; - } - // TOK_PUSH / TOK_NUM / 0 / TOK_SUB -> - - if(mtok(0, "TOK_PUSH") && mtok(1, "TOK_NUM") && mword(2) && val(2) == 0 && - mtok(3, "TOK_SUB")) - { - del(3); - del(2); - del(1); - del(0); - i--; - continue; - } - // TOK_PUSH / TOK_NUM / 0 / TOK_NEQ -> TOK_COMP_0 - if(mtok(0, "TOK_PUSH") && mtok(1, "TOK_NUM") && mword(2) && val(2) == 0 && - mtok(3, "TOK_NEQ")) - { - del(3); - del(2); - del(1); - set_tok(0, "TOK_COMP_0"); - i--; - continue; - } - // TOK_PUSH / TOK_BYTE / 0 / TOK_EQ -> TOK_COMP_0 TOK_L_NOT - if(mtok(0, "TOK_PUSH") && mtok(1, "TOK_NUM") && mword(2) && val(2) == 0 && - mtok(3, "TOK_EQ")) - { - del(3); - del(2); - set_tok(0, "TOK_COMP_0"); - set_tok(1, "TOK_L_NOT"); - i--; - continue; - } - // TOK_NUM / x / TOK_PUSH / TOK_NUM / y / TOK_ADD -> TOK_NUM (x+y) - if(const_op("TOK_ADD")) - { - set_tok(0, "TOK_NUM"); - set_w(1, val(1) + val(4)); - del(5); - del(4); - del(3); - del(2); - i--; - continue; - } - // TOK_NUM / x / TOK_PUSH / TOK_NUM / y / TOK_SUB -> TOK_NUM (x-y) - if(const_op("TOK_SUB")) - { - set_tok(0, "TOK_NUM"); - set_w(1, val(1) - val(4)); - del(5); - del(4); - del(3); - del(2); - i--; - continue; - } - // TOK_NUM / 0 / TOK_VAR_STORE / x -> TOK_VAR_STORE_0 - if(mtok(0, "TOK_NUM") && mword(1) && val(1) == 0 && - mtok(2, "TOK_VAR_STORE")) - { - set_tok(2, "TOK_VAR_STORE_0"); - del(1); - del(0); - i--; - continue; - } - // TOK_VAR_ADDR / x / TOK_SADDR / TOK_GET / TOK_DPOKE - // -> TOK_GET / TOK_VAR_STORE / x - if(mtok(0, "TOK_VAR_ADDR") && mtok(2, "TOK_SADDR") && - mtok(3, "TOK_GET") && mtok(4, "TOK_DPOKE")) - { - ins_tok(0, "TOK_GET"); - set_tok(1, "TOK_VAR_STORE"); - del(5); - del(4); - del(3); - i--; - continue; - } - // TOK_VAR_ADDR / x / TOK_SADDR / TOK_GETKEY / TOK_DPOKE - // -> TOK_GET / TOK_VAR_STORE / x - if(mtok(0, "TOK_VAR_ADDR") && mtok(2, "TOK_SADDR") && - mtok(3, "TOK_GETKEY") && mtok(4, "TOK_DPOKE")) - { - ins_tok(0, "TOK_GETKEY"); - set_tok(1, "TOK_VAR_STORE"); - del(5); - del(4); - del(3); - i--; - continue; - } - // TOK_NUM / x / TOK_PUT - // -> TOK_BYTE_PUT / x - if(mtok(0, "TOK_NUM") && mword(1) && mtok(2, "TOK_PUT")) - { - set_tok(0, "TOK_BYTE_PUT"); - set_b(1, val(1) & 255); - del(2); - i--; - continue; - } - // TOK_BYTE / x / TOK_PUT - // -> TOK_BYTE_PUT / x - if(mtok(0, "TOK_BYTE") && mtok(2, "TOK_PUT")) - { - set_tok(0, "TOK_BYTE_PUT"); - del(2); - i--; - continue; - } - // TOK_NUM / x<256 / TOK_PEEK - // -> TOK_BYTE_PEEK / x - if(mtok(0, "TOK_NUM") && mword(1) && val(1) < 256 && val(1) >= 0 && - mtok(2, "TOK_PEEK")) - { - set_tok(0, "TOK_BYTE_PEEK"); - set_b(1, val(1)); - del(2); - i--; - continue; - } - // TOK_BYTE / x / TOK_PEEK - // -> TOK_BYTE_PEEK / x - if(mtok(0, "TOK_BYTE") && mtok(2, "TOK_PEEK")) - { - set_tok(0, "TOK_BYTE_PEEK"); - del(2); - i--; - continue; - } - // TODO: should support complex expressions on "y" - // TOK_NUM / x<256 / TOK_SADDR / TOK_NUM / y / TOK_POKE - // -> TOK_NUM / (y&255) / TOK_BYTE_POKE / x - if(mtok(0, "TOK_NUM") && mword(1) && mtok(2, "TOK_SADDR") && - mtok(3, "TOK_NUM") && mword(4) && mtok(5, "TOK_POKE") && val(1) >= 0 && - val(1) <= 255) - { - int x = val(1); - set_w(1, val(4) & 255); - set_b(4, x); - set_tok(3, "TOK_BYTE_POKE"); - del(5); - del(2); - i--; - continue; - } - // TOK_NUM / x<256 / TOK_SADDR / TOK_VAR_LOAD / y / TOK_POKE - // -> TOK_VAR_LOAD / y / TOK_BYTE_POKE / x - if(mtok(0, "TOK_NUM") && mword(1) && mtok(2, "TOK_SADDR") && - mtok(3, "TOK_VAR_LOAD") && mtok(5, "TOK_POKE") && val(1) >= 0 && - val(1) <= 255) - { - int x = val(1); - set_tok(0, "TOK_VAR_LOAD"); - copy(1, 4, 1); - del(2); - set_b(4, x); - set_tok(3, "TOK_BYTE_POKE"); - del(5); - del(2); - i--; - continue; - } - // TODO: should support complex expressions on "y" - // TOK_BYTE / x / TOK_SADDR / TOK_NUM / y / TOK_POKE - // -> TOK_NUM / (y&255) / TOK_BYTE_POKE / x - if(mtok(0, "TOK_BYTE") && mtok(2, "TOK_SADDR") && mtok(3, "TOK_NUM") && - mword(4) && mtok(5, "TOK_POKE")) - { - copy(4, 1, 1); - set_w(1, val(5) & 255); - set_tok(0, "TOK_NUM"); - set_tok(3, "TOK_BYTE_POKE"); - del(6); - del(5); - del(2); - i--; - continue; - } - // TOK_BYTE / x / TOK_SADDR / TOK_VAR_LOAD / y / TOK_POKE - // -> TOK_VAR_LOAD / y / TOK_BYTE_POKE / x - if(mtok(0, "TOK_BYTE") && mtok(2, "TOK_SADDR") && - mtok(3, "TOK_VAR_LOAD") && mtok(5, "TOK_POKE")) - { - copy(0, 3, 2); - set_tok(2, "TOK_BYTE_POKE"); - del(7); - del(6); - del(5); - del(4); - i--; - continue; - } - // TOK_NUM / x / TOK_SADDR / TOK_NUM / y / TOK_POKE - // -> TOK_NUM / (y&255) / TOK_NUM_POKE / x - if(mtok(0, "TOK_NUM") && mtok(2, "TOK_SADDR") && mtok(3, "TOK_NUM") && - mword(4) && mtok(5, "TOK_POKE")) - { - copy(4, 1, 1); - set_w(1, val(5) & 255); - set_tok(3, "TOK_NUM_POKE"); - del(6); - del(5); - del(2); - i--; - continue; - } - // TOK_NUM / x / TOK_SADDR / TOK_VAR_LOAD / y / TOK_POKE - // -> TOK_VAR_LOAD / y / TOK_NUM_POKE / x - if(mtok(0, "TOK_NUM") && mword(1) && mtok(2, "TOK_SADDR") && - mtok(3, "TOK_VAR_LOAD") && mtok(5, "TOK_POKE")) - { - int x = val(1); - set_tok(0, "TOK_VAR_LOAD"); - copy(1, 4, 1); - del(2); - set_w(4, x); - set_tok(3, "TOK_NUM_POKE"); - del(5); - del(2); - i--; - continue; - } -#if 0 - // TOK_ADD / TOK_NUM / x / TOK_ADD - // -> TOK_NUM x / TOK_ADD / TOK_ADD - if( mtok(0,"TOK_ADD") && mtok(1,"TOK_NUM") && mword(2) && mtok(3,"TOK_ADD") ) - { - set_tok(0, "TOK_NUM"); set_w(1,val(2)); set_tok(2, "TOK_ADD"); i--; - continue; - } - // TOK_ADD / TOK_NUM / x / TOK_SUB - // -> TOK_NUM x / TOK_SUB / TOK_ADD - if( mtok(0,"TOK_ADD") && mtok(1,"TOK_NUM") && mword(2) && mtok(3,"TOK_SUB") ) - { - set_tok(0, "TOK_NUM"); set_w(1,val(2)); set_tok(2, "TOK_SUB"); - set_tok(3, "TOK_ADD"); i--; - continue; - } - // TOK_SUB / TOK_NUM / x / TOK_ADD - // -> TOK_NUM x / TOK_SUB / TOK_SUB - if( mtok(0,"TOK_SUB") && mtok(1,"TOK_NUM") && mword(2) && mtok(3,"TOK_ADD") ) - { - set_tok(0, "TOK_NUM"); set_w(1,val(2)); set_tok(2, "TOK_SUB"); - set_tok(3, "TOK_SUB"); i--; - continue; - } - // TOK_SUB / TOK_NUM / x / TOK_SUB - // -> TOK_NUM x / TOK_ADD / TOK_SUB - if( mtok(0,"TOK_SUB") && mtok(1,"TOK_NUM") && mword(2) && mtok(3,"TOK_SUB") ) - { - set_tok(0, "TOK_NUM"); set_w(1,val(2)); set_tok(2, "TOK_ADD"); - set_tok(3, "TOK_SUB"); i--; - continue; - } -#endif - // TOK_NUM / x / TOK_PUSH / TOK_NUM / y / TOK_MUL -> TOK_NUM (x*y) - if(const_op("TOK_MUL")) - { - set_tok(0, "TOK_NUM"); - set_w(1, val(1) * val(4)); - del(5); - del(4); - del(3); - del(2); - i--; - continue; - } - // TOK_NUM / x / TOK_PUSH / TOK_NUM / y / TOK_DIV -> TOK_NUM (x/y) - if(const_op("TOK_DIV")) - { - int16_t div = val(4); - if(div) - div = val(1) / div; - else if(val(1) < 0) - div = 1; // Probably a bug in the division routine, but we emulate - // the result - else - div = -1; - set_tok(0, "TOK_NUM"); - set_w(1, div); - del(5); - del(4); - del(3); - del(2); - i--; - continue; - } - // TOK_NUM / x / TOK_PUSH / TOK_NUM / y / TOK_MOD -> TOK_NUM (x%y) - if(const_op("TOK_MOD")) - { - int16_t div = val(4); - if(div) - div = val(1) % div; - else - div = val(1); // Probably a bug in the division routine, but we - // emulate the result - set_tok(0, "TOK_NUM"); - set_w(1, div); - del(5); - del(4); - del(3); - del(2); - i--; - continue; - } - // TOK_NUM / x / TOK_PUSH / TOK_NUM / y / TOK_BIT_AND -> TOK_NUM (x&y) - if(const_op("TOK_BIT_AND")) - { - set_tok(0, "TOK_NUM"); - set_w(1, val(1) & val(4)); - del(5); - del(4); - del(3); - del(2); - i--; - continue; - } - // TOK_NUM / x / TOK_PUSH / TOK_NUM / y / TOK_BIT_OR -> TOK_NUM (x|y) - if(const_op("TOK_BIT_OR")) - { - set_tok(0, "TOK_NUM"); - set_w(1, val(1) | val(4)); - del(5); - del(4); - del(3); - del(2); - i--; - continue; - } - // TOK_NUM / x / TOK_PUSH / TOK_NUM / y / TOK_BIT_EXOR -> TOK_NUM - // (x^y) - if(const_op("TOK_BIT_EXOR")) - { - set_tok(0, "TOK_NUM"); - set_w(1, val(1) ^ val(4)); - del(5); - del(4); - del(3); - del(2); - i--; - continue; - } - // Transform multiple subtractions to addition - // TOK_PUSH / TOK_VAR / x / TOK_SUB / TOK_PUSH / TOK_VAR / y / TOK_SUB - // -> - // TOK_PUSH / TOK_VAR / x / TOK_PUSH / TOK_VAR / y / TOK_ADD / TOK_SUB - if(mtok(0, "TOK_PUSH") && - (mtok(1, "TOK_VAR_LOAD") || mtok(1, "TOK_NUM")) && - mtok(3, "TOK_SUB") && mtok(4, "TOK_PUSH") && - (mtok(5, "TOK_VAR_LOAD") || mtok(5, "TOK_NUM")) && mtok(7, "TOK_SUB")) - { - ins_tok(7, "TOK_ADD"); - del(3); - } - // TOK_PUSH / TOK_VAR / x / TOK_ADD -> TOK_ADD_VAR / x - if(mtok(0, "TOK_PUSH") && mtok(1, "TOK_VAR_LOAD") && mtok(3, "TOK_ADD")) - { - set_tok(1, "TOK_ADD_VAR"); - del(3); - del(0); - i--; - continue; - } - // TOK_VAR / x / TOK_PUSH / TOK_NUM / y / TOK_ADD -> TOK_NUM / y / - // TOK_ADD_VAR / x - if(mtok(0, "TOK_VAR_LOAD") && mtok(2, "TOK_PUSH") && mtok(3, "TOK_NUM") && - mword(4) && mtok(5, "TOK_ADD")) - { - set_tok(0, "TOK_NUM"); - set_tok(2, "TOK_ADD_VAR"); - copy(3, 1, 1); - del(4); - set_w(1, val(4)); - del(5); - del(4); - i--; - continue; - } - // TOK_VAR / x / TOK_PUSH / TOK_VAR / y / TOK_USHL / TOK_ADD -> - // TOK_VAR / y / TOK_USHL / TOK_ADD_VAR / x - if(mtok(0, "TOK_VAR_LOAD") && mtok(2, "TOK_PUSH") && - mtok(3, "TOK_VAR_LOAD") && mtok(5, "TOK_USHL") && mtok(6, "TOK_ADD")) - { - copy(1, 4, 1); - copy(5, 2, 1); - del(6); - del(2); - set_tok(2, "TOK_USHL"); - set_tok(3, "TOK_ADD_VAR"); - del(6); - del(5); - i--; - continue; - } - //////////////////////////////////7 - // This pattern is generated on array access: ARR(VAR + X) - // TOK_VAR / x / TOK_PUSH / - // TOK_NUM / n / TOK_ADD_VAR / y / - // TOK_USHL / TOK_ADD -> - // - // TOK_NUM / n / TOK_ADD_VAR / y / TOK_USHL / TOK_ADD:VAR / x - // - if(mtok(0, "TOK_VAR_LOAD") && mtok(2, "TOK_PUSH") && mtok(3, "TOK_NUM") && - mword(4) && mtok(5, "TOK_ADD_VAR") && mtok(7, "TOK_USHL") && - mtok(8, "TOK_ADD")) - { - ins_w(9, 1); - copy(9, 1, 1); - del(10); - set_tok(8, "TOK_ADD_VAR"); - del(2); - del(1); - del(0); - i--; - continue; - } - // VAR + VAR ==> 2 * VAR - // TOK_VAR / x / TOK_PUSH / TOK_VAR / x / TOK_ADD -> TOK_VAR / x / - // TOK_USHL - if(mtok(0, "TOK_VAR_LOAD") && mtok(2, "TOK_PUSH") && - mtok(3, "TOK_VAR_LOAD") && mtok(5, "TOK_ADD") && varn(1) == varn(4)) - { - set_tok(2, "TOK_USHL"); - del(5); - del(4); - del(3); - i--; - continue; - } - // VAR = VAR + 1 (or 1 + VAR), after the rules above ==> INC VAR - // TOK_NUM / 1 / TOK_ADD_VAR / x / TOK_VAR_STORE / x -> TOK_INCVAR / x - if(mtok(0, "TOK_NUM") && mword(1) && val(1) == 1 && - mtok(2, "TOK_ADD_VAR") && mtok(4, "TOK_VAR_STORE") && varn(3) == varn(5)) - { - set_tok(2, "TOK_INCVAR"); - del(5); - del(4); - del(1); - del(0); - i--; - continue; - } - // VAR = VAR + 1 ==> INC VAR - // TOK_VAR / x / TOK_PUSH / TOK_NUM / 1 / TOK_ADD / TOK_VAR_STORE / x - // -> TOK_INCVAR / x - if(mtok(0, "TOK_VAR_LOAD") && mtok(2, "TOK_PUSH") && mtok(3, "TOK_NUM") && - mword(4) && val(4) == 1 && mtok(5, "TOK_ADD") && - mtok(6, "TOK_VAR_STORE") && varn(1) == varn(7)) - { - set_tok(0, "TOK_INCVAR"); - del(7); - del(6); - del(5); - del(4); - del(3); - del(2); - i--; - continue; - } - // VAR = VAR + 1 ==> INC VAR - // TOK_VAR_A / x / TOK_SADDR / TOK_VAR / x / TOK_PUSH / TOK_NUM / 1 / - // TOK_ADD / TOK_DPOKE - // -> TOK_INCVAR / x - if(mtok(0, "TOK_VAR_ADDR") && mtok(2, "TOK_SADDR") && - mtok(3, "TOK_VAR_LOAD") && mtok(5, "TOK_PUSH") && mtok(6, "TOK_NUM") && - mword(7) && val(7) == 1 && mtok(8, "TOK_ADD") && - mtok(9, "TOK_DPOKE") && varn(1) == varn(4)) - { - set_tok(0, "TOK_INCVAR"); - del(9); - del(8); - del(7); - del(6); - del(5); - del(4); - del(3); - del(2); - i--; - continue; - } - // INC VAR ==> INC VAR (optimized) - // TOK_VAR_A / x / TOK_INC -> TOK_INCVAR / x - if(mtok(0, "TOK_VAR_ADDR") && mtok(2, "TOK_INC")) - { - set_tok(0, "TOK_INCVAR"); - del(2); - i--; - continue; - } - // INC ==> INC (optimized) - // TOK_SADDR / TOK_INC -> TOK_INC - if(mtok(0, "TOK_SADDR") && mtok(1, "TOK_INC")) - { - del(0); - i--; - continue; - } - // VAR = VAR - 1 ==> DEC VAR - // TOK_VAR / x / TOK_PUSH / TOK_NUM / 1 / TOK_SUB / TOK_VAR_STORE / x - // -> TOK_DECVAR / x - if(mtok(0, "TOK_VAR_LOAD") && mtok(2, "TOK_PUSH") && mtok(3, "TOK_NUM") && - mword(4) && val(4) == 1 && mtok(5, "TOK_SUB") && - mtok(6, "TOK_VAR_STORE") && varn(1) == varn(7)) - { - set_tok(0, "TOK_DECVAR"); - del(7); - del(6); - del(5); - del(4); - del(3); - del(2); - i--; - continue; - } - // VAR = VAR - 1 ==> DEC VAR - // TOK_VAR_A / x / TOK_SADDR / TOK_VAR / x / TOK_PUSH / TOK_NUM / 1 / - // TOK_SUB / TOK_DPOKE - // -> TOK_DECVAR / x - if(mtok(0, "TOK_VAR_ADDR") && mtok(2, "TOK_SADDR") && - mtok(3, "TOK_VAR_LOAD") && mtok(5, "TOK_PUSH") && mtok(6, "TOK_NUM") && - mword(7) && val(7) == 1 && mtok(8, "TOK_SUB") && - mtok(9, "TOK_DPOKE") && varn(1) == varn(4)) - { - set_tok(0, "TOK_DECVAR"); - del(9); - del(8); - del(7); - del(6); - del(5); - del(4); - del(3); - del(2); - i--; - continue; - } - // DEC VAR ==> DEC VAR (optimized) - // TOK_VAR_A / x / TOK_DEC -> TOK_DECVAR / x - if(mtok(0, "TOK_VAR_ADDR") && mtok(2, "TOK_DEC")) - { - set_tok(0, "TOK_DECVAR"); - del(2); - i--; - continue; - } - // DEC ==> DEC (optimized) - // TOK_SADDR / TOK_DEC -> TOK_DEC - if(mtok(0, "TOK_SADDR") && mtok(1, "TOK_DEC")) - { - del(0); - i--; - continue; - } - // NOT NOT A -> A - // TOK_L_NOT / TOK_L_NOT -> TOK_COMP_0 - if(mtok(0, "TOK_L_NOT") && mtok(1, "TOK_L_NOT")) - { - set_tok(0, "TOK_COMP_0"); - del(1); - continue; - } - // NOT A=B -> A<>B - // TOK_EQ / TOK_L_NOT -> TOK_NEQ - if(mtok(0, "TOK_EQ") && mtok(1, "TOK_L_NOT")) - { - set_tok(0, "TOK_NEQ"); - del(1); - continue; - } - // NOT A<>B -> A=B - // TOK_NEQ / TOK_L_NOT -> TOK_EQ - if(mtok(0, "TOK_NEQ") && mtok(1, "TOK_L_NOT")) - { - set_tok(0, "TOK_EQ"); - del(1); - continue; - } - // (bool) != 0 -> (bool) - // TOK_L_AND | TOK_L_OR | TOK_L_NOT | - // TOK_NEQ | TOK_COMP_0 | TOK_EQ | - // TOK_LT | TOK_GT - // / TOK_COMP_0 -> remove TOK_COMP_0 - if((mtok(0, "TOK_NEQ") || mtok(0, "TOK_L_AND") || mtok(0, "TOK_L_OR") || - mtok(0, "TOK_L_NOT") || mtok(0, "TOK_COMP_0") || mtok(0, "TOK_EQ") || - mtok(0, "TOK_LT") || mtok(0, "TOK_GT")) && - mtok(1, "TOK_COMP_0")) - { - del(1); - continue; - } - // NOT (A > x) == A <= x -> A < x+1 - // TOK_NUM / x / TOK_GT / TOK_L_NOT -> TOK_NUM / x+1 / TOK_LT - if(mtok(0, "TOK_NUM") && mword(1) && mtok(2, "TOK_GT") && - mtok(3, "TOK_L_NOT")) - { - if(val(1) == 32637) - { - // If x=32767, the expression is always true. - // We can't currently delete an expression, so - // simply replace it with "OR 1" - set_tok(0, "TOK_NUM"); - set_w(1, 1); - set_tok(2, "TOK_BIT_OR"); - set_tok(3, "TOK_COMP_0"); - } - else - { - set_tok(0, "TOK_NUM"); - set_w(1, val(1) + 1); - set_tok(2, "TOK_LT"); - del(3); - } - } - // STRING[i,n>255] -> STRING[i,255] - // TOK_NUM / > 255 / TOK_STR_IDX - // -> TOK_NUM / 255 / TOK_STR_IDX - if(mtok(0, "TOK_NUM") && mword(1) && mtok(2, "TOK_STR_IDX") && - val(1) > 255) - { - set_w(1, 255); - continue; - } -#if 0 - // STRING[i][j,n] -> STRING[i+j-1,n] - // TOK_NUM / 255 / TOK_STR_IDX / - // ( TOK_NUM / j ) || ( TOK_VAR_LOAD / k ) / - // ( TOK_NUM / n ) || ( TOK_VAR_LOAD / n ) / - // TOK_STR_IDX - // -> - // TOK_NUM / j / TOK_ADD / TOK_NUM / 1 / TOK_SUB / TOK_NUM / n / TOK_STR_IDX - if( mtok(0, "TOK_NUM") && mword(1) && (val(1) == 255) && - mtok(2, "TOK_STR_IDX") && - ( mtok(3, "TOK_NUM") || mtok(3, "TOK_VAR_LOAD") ) && - ( mtok(5, "TOK_NUM") || mtok(5, "TOK_VAR_LOAD") ) && - mtok(7, "TOK_STR_IDX") ) - { - ins_tok(5, "TOK_ADD"); - ins_tok(6, "TOK_NUM"); ins_w(7, 1); - ins_tok(8, "TOK_SUB"); - del(2); del(1); del(0); - continue; - } - // STRING[i,n][j] -> STRING[i+j-1,n-j+1] - // ( TOK_NUM / n ) || ( TOK_VAR_LOAD / n ) / TOK_STR_IDX - // ( TOK_NUM / j ) || ( TOK_VAR_LOAD / k ) / - // TOK_NUM / 255 / TOK_STR_IDX - // -> - // TOK_NUM / j / TOK_ADD / TOK_NUM / 1 / TOK_SUB / TOK_NUM / n / - // TOK_NUM / j / TOK_SUB / TOK_NUM / 1 / TOK_ADD / TOK_STR_IDX - if( ( mtok(0, "TOK_NUM") || mtok(0, "TOK_VAR_LOAD") ) && - mtok(2, "TOK_STR_IDX") && - ( mtok(3, "TOK_NUM") || mtok(3, "TOK_VAR_LOAD") ) && - mtok(5, "TOK_NUM") && mword(6) && (val(6) == 255) && - mtok(7, "TOK_STR_IDX") ) - { - del(6); del(5); - copy(0, 3, 2); - ins_tok(2, "TOK_ADD"); - ins_tok(3, "TOK_NUM"); ins_w(4, 1); - ins_tok(5, "TOK_SUB"); - del(8); - ins_tok(10, "TOK_SUB"); - ins_tok(11, "TOK_NUM"); ins_w(12, 1); - ins_tok(13, "TOK_ADD"); - continue; - } - // ASC( STRING[i,X (>=1) ] ) -> PEEK( ADR(STRING) + i ) - // - // TOK_NUM / X (>=1) / TOK_STR_IDX / - // TOK_NUM / Y (<=X) / TOK_ADD / TOK_PEEK - // -> - // TOK_ADD / TOK_NUM / Y - 1 / TOK_ADD / TOK_PEEK - if( mtok(0, "TOK_NUM") && mword(1) && (val(1)>0) && mtok(2, "TOK_STR_IDX") && - mtok(3, "TOK_NUM") && mword(4) && (val(4)<=val(1)) && - (val(4)>=1) && mtok(5, "TOK_ADD") && mtok(6, "TOK_PEEK") ) - { - set_tok(2, "TOK_ADD"); - set_w(4, val(4) - 1); - del(1); del(0); - continue; - } -#endif - // NOT (A < x) == A >= x -> A > x-1 - // TOK_NUM / x / TOK_LT / TOK_L_NOT -> TOK_NUM / x+1 / TOK_LT - if(mtok(0, "TOK_NUM") && mword(1) && mtok(2, "TOK_LT") && - mtok(3, "TOK_L_NOT")) - { - if(val(1) == -32768) - { - // If x=-32768, the expression is always true. - // We can't currently delete an expression, so - // simply replace it with "OR 1" - set_tok(0, "TOK_NUM"); - set_w(1, 1); - set_tok(2, "TOK_BIT_OR"); - set_tok(3, "TOK_COMP_0"); - } - else - { - set_tok(0, "TOK_NUM"); - set_w(1, val(1) - 1); - set_tok(2, "TOK_GT"); - del(3); - } - } - // x == 0 -> 1 / 0 - if(mtok(0, "TOK_NUM") && mword(1) && mtok(2, "TOK_COMP_0")) - { - set_w(1, val(1) ? 1 : 0); - del(2); - continue; - } - // x / TOK_CNJUMP -> remove or always jump - if(mtok(0, "TOK_NUM") && mword(1) && mtok(2, "TOK_CNJUMP")) - { - if(!val(1)) - { - del(3); - del(2); - del(1); - del(0); - } - else - { - set_tok(2, "TOK_JUMP"); - del(1); - del(0); - } - continue; - } - // x / TOK_CJUMP -> remove or always jump - if(mtok(0, "TOK_NUM") && mword(1) && mtok(2, "TOK_CJUMP")) - { - if(val(1)) - { - del(3); - del(2); - del(1); - del(0); - } - else - { - set_tok(2, "TOK_JUMP"); - del(1); - del(0); - } - continue; - } - // CALL xxxxx / RETURN -> JUMP xxxxx - // TOK_CALL / x / TOK_RET -> TOK_JUMP / x - if(mtok(0, "TOK_CALL") && mtok(2, "TOK_RET")) - { - set_tok(0, "TOK_JUMP"); - del(2); - continue; - } - // TOK_L_NOT / TOK_CJUMP - // -> TOK_CNJUMP - if(mtok(0, "TOK_L_NOT") && mtok(1, "TOK_CJUMP")) - { - set_tok(1, "TOK_CNJUMP"); - del(0); - continue; - } - // TOK_L_NOT / TOK_CNJUMP - // -> TOK_CJUMP - if(mtok(0, "TOK_L_NOT") && mtok(1, "TOK_CNJUMP")) - { - set_tok(1, "TOK_CJUMP"); - del(0); - continue; - } - // Bypass CJUMP/CNJUMP over a RETURN 0 - // TOK_CJUMP / x / TOK_NUM / 0 / TOK_RET / LABEL x - // -> TOK_CNRET / LABEL x - // TOK_CNJUMP / x / TOK_NUM / 0 / TOK_RET / LABEL x - // -> TOK_CRET / LABEL x - if((mtok(0, "TOK_CJUMP") || mtok(0, "TOK_CNJUMP")) && - mtok(2, "TOK_NUM") && mword(3) && val(3) == 0 && - mtok(4, "TOK_RET") && mlabel(5) && lbl(5) == wlbl(1)) - { - bool cjump = mtok(0, "TOK_CJUMP"); - set_tok(0, cjump ? "TOK_CNRET" : "TOK_CRET"); - del(4); - del(3); - del(2); - del(1); - continue; - } - // Bypass CJUMP over another JUMP - // TOK_CJUMP / x / TOK_JUMP / y / LABEL x - // -> TOK_CNJUMP / y / LABEL x - if(mtok(0, "TOK_CJUMP") && mtok(2, "TOK_JUMP") && mlabel(4) && - lbl(4) == wlbl(1)) - { - set_tok(2, "TOK_CNJUMP"); - del(1); - del(0); - continue; - } - // Bypass CJUMP over a RET - // TOK_CJUMP / x / TOK_RET / LABEL x - // -> TOK_CNRET / LABEL x - if(mtok(0, "TOK_CJUMP") && mtok(2, "TOK_RET") && mlabel(3) && - lbl(3) == wlbl(1)) - { - set_tok(2, "TOK_CNRET"); - del(1); - del(0); - continue; - } - // Bypass CNJUMP over another JUMP - // TOK_CNJUMP / x / TOK_JUMP / y / LABEL x - // -> TOK_CJUMP / y / LABEL x - if(mtok(0, "TOK_CNJUMP") && mtok(2, "TOK_JUMP") && mlabel(4) && - lbl(4) == wlbl(1)) - { - set_tok(2, "TOK_CJUMP"); - del(1); - del(0); - continue; - } - // Bypass CNJUMP over a RET - // TOK_CNJUMP / x / TOK_RET / LABEL x - // -> TOK_CRET / LABEL x - if(mtok(0, "TOK_CNJUMP") && mtok(2, "TOK_RET") && mlabel(3) && - lbl(3) == wlbl(1)) - { - set_tok(2, "TOK_CRET"); - del(1); - del(0); - continue; - } - // TOK_L_NOT / TOK_CRET -> TOK_CNRET - if(mtok(0, "TOK_L_NOT") && mtok(1, "TOK_CRET")) - { - set_tok(1, "TOK_CNRET"); - del(0); - continue; - } - // TOK_L_NOT / TOK_CNRET -> TOK_CRET - if(mtok(0, "TOK_L_NOT") && mtok(1, "TOK_CNRET")) - { - set_tok(1, "TOK_CRET"); - del(0); - continue; - } - // Bypass JUMP to next instruction - // TOK_JUMP / x / LABEL x - // -> LABEL x - if(mtok(0, "TOK_JUMP") && mlabel(2) && lbl(2) == wlbl(1)) - { - del(1); - del(0); - continue; - } - // Remove dead code after a JUMP - if(mtok(0, "TOK_JUMP") && !mlabel(2)) - { - del(2); - continue; - } - // Remove dead code after a RET or END - if((mtok(0, "TOK_RET") || mtok(0, "TOK_END")) && !mlabel(1)) - { - int last = 1; - while(current + last < code.size() && !mlabel(last)) - last++; - while(--last >= 1) - del(last); - continue; - } - // Convert PRINT CHR$(X) to PUT X - // TOK_CHR / TOK_PRINT_STR -> TOK_PUT - if(mtok(0, "TOK_CHR") && mtok(1, "TOK_PRINT_STR")) - { - set_tok(0, "TOK_PUT"); - del(1); - continue; - } - // Join print constant strings with a PUT, except if the color - // is not known. - // TOK_CSTRING / STR / TOK_PRINT_STR / TOK_NUM / X / TOK_PUT - // -> TOK_CSTRING / STR+X / TOK_PRINT_STR - if(mtok(0, "TOK_CSTRING") && mstring(1) < 255 && - mtok(2, "TOK_PRINT_STR") && mtok(3, "TOK_NUM") && mword(4) && - mtok(5, "TOK_PUT") && print_color >= 0) - { - set_string(1, str(1) + char(val(4) ^ print_color)); - del(5); - del(4); - del(3); - } - // Join print constant strings with a PUT, except if the color - // is not known. - // TOK_CSTRING / STR / TOK_PRINT_STR / TOK_BYTE_PUT / x - // -> TOK_CSTRING / STR+X / TOK_PRINT_STR - if(mtok(0, "TOK_CSTRING") && mstring(1) < 255 && - mtok(2, "TOK_PRINT_STR") && mtok(3, "TOK_BYTE_PUT") && - (mbyte(4) || mword(4)) && print_color >= 0) - { - set_string(1, str(1) + char(val(4) ^ print_color)); - del(4); - del(3); - } - // Join two print constant strings - // TOK_CSTRING / S1 / TOK_PRINT_STR / TOK_CSTRING / S2 / TOK_PRINT_STR - // -> TOK_CSTRING / S1+S2 / TOK_PRINT_STR - if(mtok(0, "TOK_CSTRING") && mtok(2, "TOK_PRINT_STR") && - mtok(3, "TOK_CSTRING") && mtok(5, "TOK_PRINT_STR") && - mstring(1) + mstring(4) < 256) - { - set_string(1, str(1) + str(4)); - del(5); - del(4); - del(3); - } } } while(changed); print_chars(); From 96f188111b8610bfd4c469256a3c4078fe50573f Mon Sep 17 00:00:00 2001 From: Daniel Serpell Date: Tue, 20 Oct 2026 23:53:11 -0300 Subject: [PATCH 05/11] compiler: Convert structural peephole passes to pattern tables Move number normalization, PUSH expansion and folding, SADDR folding, label-target rewriting, short print strings and I/O channel tracking to compiled rule tables. This removes the remaining procedural matchers and simplifies the optimizer loop. Aided by Opencode / DeepSeek V4.1 Flash 1017 --- src/compiler/peephole.cc | 703 +++++++++++++-------------------------- 1 file changed, 238 insertions(+), 465 deletions(-) diff --git a/src/compiler/peephole.cc b/src/compiler/peephole.cc index d5cb6b2..7f1aaee 100644 --- a/src/compiler/peephole.cc +++ b/src/compiler/peephole.cc @@ -364,6 +364,178 @@ static std::vector make_peephole_rules() }; } +static std::vector make_expand_number_rules() +{ + return { + {"TOK_BYTE %b:x", + [](const peep_match &m, peep_builder &b) { + b.write("TOK_NUM %w", m.word("x")); + }}, + {"TOK_1", + [](const peep_match &, peep_builder &b) { + b.write("TOK_NUM %w", 1); + }}, + {"TOK_0", + [](const peep_match &, peep_builder &b) { + b.write("TOK_NUM %w", 0); + }}, + }; +} + +static std::vector make_shorten_number_rules() +{ + return { + {"TOK_NUM %w:x", "TOK_0", + [](const peep_match &m) { return m.word("x") == 0; }}, + {"TOK_NUM %w:x", "TOK_1", + [](const peep_match &m) { return m.word("x") == 1; }}, + {"TOK_NUM %w:x", "TOK_1 TOK_NEG", + [](const peep_match &m) { return m.word("x") == -1; }}, + {"TOK_NUM %w:x", + [](const peep_match &m, peep_builder &b) { + b.write("TOK_BYTE %b", m.word("x")); + }, + [](const peep_match &m) { + return 0 == (m.word("x") & ~0xFF); + }}, + }; +} + +static std::vector make_expand_push_rules() +{ + return { + {"TOK_PUSH_BYTE", "TOK_PUSH TOK_BYTE"}, + {"TOK_PUSH_NUM", "TOK_PUSH TOK_NUM"}, + {"TOK_PUSH_0", "TOK_PUSH TOK_0"}, + {"TOK_PUSH_1", "TOK_PUSH TOK_1"}, + {"TOK_PUSH_VAR_LOAD", "TOK_PUSH TOK_VAR_LOAD"}, + {"TOK_VAR_SADDR %v:x", "TOK_VAR_ADDR $x TOK_SADDR"}, + }; +} + +static std::vector make_fold_push_rules() +{ + return { + {"TOK_PUSH TOK_BYTE", "TOK_PUSH_BYTE"}, + {"TOK_PUSH TOK_NUM", "TOK_PUSH_NUM"}, + {"TOK_PUSH TOK_1", "TOK_PUSH_1"}, + {"TOK_PUSH TOK_0", "TOK_PUSH_0"}, + {"TOK_PUSH TOK_VAR_LOAD", "TOK_PUSH_VAR_LOAD"}, + }; +} + +static std::vector make_fold_saddr_rules() +{ + return { + {"TOK_VAR_ADDR %v:x TOK_SADDR", "TOK_VAR_SADDR $x"}, + }; +} + +static bool can_retarget(const peep_match &m) +{ + auto it = m.state.tgt.find(m.text("target")); + return it != m.state.tgt.end() && it->second != m.text("target"); +} + +static void retarget(const peep_match &m, peep_builder &b, + const char *jump, const char *ret) +{ + auto it = m.state.tgt.find(m.text("target")); + if(it == m.state.tgt.end()) + return; + if(it->second == "__TOK_RET__") + b.tok(ret); + else + { + b.tok(jump); + b.symbol(it->second); + } +} + +static std::vector make_label_target_rules() +{ + return { + {"TOK_JUMP %l:target", + [](const peep_match &m, peep_builder &b) { + retarget(m, b, "TOK_JUMP", "TOK_RET"); + }, + can_retarget}, + {"TOK_CJUMP %l:target", + [](const peep_match &m, peep_builder &b) { + retarget(m, b, "TOK_CJUMP", "TOK_CRET"); + }, + can_retarget}, + {"TOK_CNJUMP %l:target", + [](const peep_match &m, peep_builder &b) { + retarget(m, b, "TOK_CNJUMP", "TOK_CNRET"); + }, + can_retarget}, + }; +} + +static std::vector make_print_char_rules() +{ + return { + {"TOK_NUM %w:x TOK_BYTE_POKE %B:color", + [](const peep_match &m, peep_builder &b) { + m.state.print_color = m.word("x"); + m.state.color_pending = true; + b.keep(); + }, + [](const peep_match &m) { + return m.text("color") == "PRINT_COLOR"; + }}, + {"TOK_BYTE_POKE %B:color", + [](const peep_match &m, peep_builder &b) { + if(m.state.color_pending) + m.state.color_pending = false; + else + m.state.print_color = -1; + b.keep(); + }, + [](const peep_match &m) { + return m.text("color") == "PRINT_COLOR"; + }}, + {"TOK_CSTRING %s:s TOK_PRINT_STR", + [](const peep_match &m, peep_builder &b) { + for(char c : m.text("s")) + b.write("TOK_BYTE_PUT %b", c ^ m.state.print_color); + }, + [](const peep_match &m) { + return m.text("s").size() < 3 && m.state.print_color >= 0; + }}, + }; +} + +static std::vector make_iochn_rules() +{ + return { + {"TOK_CALL", + [](const peep_match &m, peep_builder &b) { + m.state.ioch = 0; + m.state.ioch_pending = false; + b.keep(); + }}, + {"TOK_NUM %w:x TOK_IOCHN", + [](const peep_match &m, peep_builder &b) { + int x = m.word("x"); + if(x == m.state.ioch) + return; + m.state.ioch = x; + m.state.ioch_pending = true; + b.keep(); + }}, + {"TOK_IOCHN", + [](const peep_match &m, peep_builder &b) { + if(m.state.ioch_pending) + m.state.ioch_pending = false; + else + m.state.ioch = -1; + b.keep(); + }}, + }; +} + // Implements a simple peephole optimizer class peephole { @@ -371,353 +543,48 @@ class peephole bool changed; std::vector &code; peep_rules rules; - size_t current; - // Matching functions for the peephole opt - bool mtok(size_t idx, std::string tok) - { - idx += current; - return idx < code.size() && code[idx].is_tok(tok); - } - bool mcbyte(size_t idx, std::string name) - { - idx += current; - return idx < code.size() && code[idx].is_sbyte(name); - } - bool mcword(size_t idx, std::string name) - { - idx += current; - return idx < code.size() && code[idx].is_sword(name); - } - bool mlabel(size_t idx) - { - idx += current; - return idx < code.size() && code[idx].is_label(); - } - bool mlblw(size_t idx) - { - idx += current; - return idx < code.size() && code[idx].is_sword() && - code[idx].get_str().find("lbl") != std::string::npos; - } - bool mword(size_t idx) - { - idx += current; - return idx < code.size() && code[idx].is_word(); - } - bool mbyte(size_t idx) - { - idx += current; - return idx < code.size() && code[idx].is_byte(); - } - // Returns 256 if not a string - unsigned mstring(size_t idx) - { - idx += current; - if(idx < code.size() && code[idx].is_string()) - return code[idx].get_str().size(); - else - return 256; - } - std::string lbl(size_t idx) - { - idx += current; - if(idx < code.size() && code[idx].is_label()) - return code[idx].get_str(); - else - return std::string(); - } - std::string wlbl(size_t idx) - { - if(mlblw(idx)) - return code[idx + current].get_str(); - else - return std::string(); - } - int16_t val(size_t idx) - { - idx += current; - if(idx < code.size()) - return code[idx].get_val(); - else - return 0x8000; - } - int varn(size_t idx) - { - idx += current; - if(idx < code.size()) - return code[idx].get_varn(); - else - return 0x8000; - } - std::string str(size_t idx) - { - idx += current; - if(idx < code.size()) - return code[idx].get_str(); - else - return std::string(); - } - void del(size_t idx) - { - if(idx + current < code.size()) - { - changed = true; - code.erase(code.begin() + idx + current); - } - } - void ins_w(size_t idx, int16_t x) - { - int lnum = 0; - changed = true; - if(code.size() > idx + current) - lnum = code[idx + current].linenum(); - code.insert(code.begin() + idx + current, codew::cword(x, lnum)); - } - void ins_b(size_t idx, int16_t x) - { - int lnum = 0; - changed = true; - if(code.size() > idx + current) - lnum = code[idx + current].linenum(); - code.insert(code.begin() + idx + current, codew::cbyte(x & 0xFF, lnum)); - } - void ins_tok(size_t idx, std::string tok) - { - int lnum = 0; - changed = true; - if(code.size() > idx + current) - lnum = code[idx + current].linenum(); - code.insert(code.begin() + idx + current, codew::ctok(tok, lnum)); - } - void set_ws(size_t idx, std::string str) - { - changed = true; - code[idx + current] = codew::cword(str, code[idx + current].linenum()); - } - void set_w(size_t idx, int16_t x) - { - changed = true; - code[idx + current] = codew::cword(x & 0xFFFF, code[idx + current].linenum()); - } - void set_b(size_t idx, int16_t x) - { - changed = true; - code[idx + current] = codew::cbyte(x & 0xFF, code[idx + current].linenum()); - } - void set_tok(size_t idx, std::string tok) - { - changed = true; - code[idx + current] = codew::ctok(tok, code[idx + current].linenum()); - } - void set_string(size_t idx, std::string str) - { - changed = true; - code[idx + current] = codew::cstring(str, code[idx + current].linenum()); - } + peep_rules expand_push_rules; + peep_rules expand_rules; + peep_rules shorten_rules; + peep_rules fold_push_rules; + peep_rules fold_saddr_rules; + peep_rules label_target_rules; + peep_rules print_char_rules; + peep_rules iochn_rules; void replace_range(size_t begin, size_t end, std::vector &&replacement) { changed = true; code.erase(code.begin() + begin, code.begin() + end); code.insert(code.begin() + begin, replacement.begin(), replacement.end()); } - // Transforms all "numeric" tokens to TOK_NUM, so that the next phases can - // optimize - void expand_numbers() + void apply_rules_at(size_t &i, peep_rules &table, peep_state &state) { - for(size_t i = 0; i < code.size(); i++) + std::vector replacement; + size_t begin, end; + bool modified; + if(!table.apply(code, i, state, replacement, begin, end, modified)) + return; + if(modified) { - // Skip non-tokens - if(!code[i].is_tok()) - continue; - - current = i; - // Sequences: - // TOK_BYTE / x - if(mtok(0, "TOK_BYTE") && mbyte(1)) - { - set_tok(0, "TOK_NUM"); - set_w(1, val(1)); - i++; - } - // TOK_1 - else if(mtok(0, "TOK_1")) - { - set_tok(0, "TOK_NUM"); - ins_w(1, 1); - i++; - } - // TOK_0 - else if(mtok(0, "TOK_0")) - { - set_tok(0, "TOK_NUM"); - ins_w(1, 0); - i++; - } + replace_range(begin, end, std::move(replacement)); + i--; } } - // Transforms small "numeric" tokens to TOK_BYTE, TOK_1 and TOK_0 - void shorten_numbers() + void run_rules(peep_rules &table, peep_state &state) { for(size_t i = 0; i < code.size(); i++) { - // Skip non-tokens + if(code[i].is_label()) + state.on_label(); if(!code[i].is_tok()) continue; - - current = i; - // Sequences: - // TOK_NUM / x == 0 - if(mtok(0, "TOK_NUM") && mword(1) && val(1) == 0) - { - del(1); - set_tok(0, "TOK_0"); - } - // TOK_NUM / x == 1 - else if(mtok(0, "TOK_NUM") && mword(1) && val(1) == 1) - { - del(1); - set_tok(0, "TOK_1"); - } - // TOK_NUM / x == -1 - else if(mtok(0, "TOK_NUM") && mword(1) && val(1) == -1) - { - set_tok(0, "TOK_1"); - set_tok(1, "TOK_NEG"); - } - // TOK_NUM / x < 256 - else if(mtok(0, "TOK_NUM") && mword(1) && 0 == (val(1) & ~0xFF)) - { - set_tok(0, "TOK_BYTE"); - set_b(1, val(1)); - } + apply_rules_at(i, table, state); } } - // Expands PUSH and SADDR tokens - void expand_push() + void run_rules(peep_rules &table) { - for(size_t i = 0; i < code.size(); i++) - { - // Skip non-tokens - if(!code[i].is_tok()) - continue; - - current = i; - if(mtok(0, "TOK_PUSH_BYTE")) - { - set_tok(0, "TOK_BYTE"); - ins_tok(0, "TOK_PUSH"); - } - else if(mtok(0, "TOK_PUSH_NUM")) - { - set_tok(0, "TOK_NUM"); - ins_tok(0, "TOK_PUSH"); - } - else if(mtok(0, "TOK_PUSH_0")) - { - set_tok(0, "TOK_0"); - ins_tok(0, "TOK_PUSH"); - } - else if(mtok(0, "TOK_PUSH_1")) - { - set_tok(0, "TOK_1"); - ins_tok(0, "TOK_PUSH"); - } - else if(mtok(0, "TOK_PUSH_VAR_LOAD")) - { - set_tok(0, "TOK_VAR_LOAD"); - ins_tok(0, "TOK_PUSH"); - } - else if(mtok(0, "TOK_VAR_SADDR")) - { - set_tok(0, "TOK_VAR_ADDR"); - ins_tok(2, "TOK_SADDR"); - } - } - } - // Transforms print of small constant strings to sequence of BYTE_PUT - void print_chars() - { - int print_color = 0; - for(size_t i = 0; i < code.size(); i++) - { - current = i; - // Track current print color - if(mtok(2, "TOK_BYTE_POKE") && mcbyte(3, "PRINT_COLOR")) - { - if(mtok(0, "TOK_NUM") && mword(1)) - print_color = val(1); - else - print_color = -1; - } - if(print_color >= 0 && mtok(0, "TOK_CSTRING") && mstring(1) < 3 && - mtok(2, "TOK_PRINT_STR")) - { - auto s = str(1); - del(2); - del(1); - del(0); - for(char c : s) - { - ins_tok(0, "TOK_BYTE_PUT"); - ins_b(1, (c ^ print_color) & 0xFF); - current += 2; - } - } - } - } - // Folds PUSH followed by known sequences - void fold_push() - { - for(size_t i = 0; i < code.size(); i++) - { - current = i; - if(mtok(0, "TOK_PUSH")) - { - // TOK_BYTE - if(mtok(1, "TOK_BYTE")) - { - set_tok(1, "TOK_PUSH_BYTE"); - del(0); - } - // TOK_NUM - else if(mtok(1, "TOK_NUM")) - { - set_tok(1, "TOK_PUSH_NUM"); - del(0); - } - // TOK_1 - else if(mtok(1, "TOK_1")) - { - set_tok(1, "TOK_PUSH_1"); - del(0); - } - // TOK_0 - else if(mtok(1, "TOK_0")) - { - set_tok(1, "TOK_PUSH_0"); - del(0); - } - // TOK_VAR_LOAD / x - if(mtok(1, "TOK_VAR_LOAD")) - { - set_tok(1, "TOK_PUSH_VAR_LOAD"); - del(0); - } - } - } - } - // Folds SADDR after known sequences - void fold_saddr() - { - for(size_t i = 0; i < code.size(); i++) - { - current = i; - if(mtok(0, "TOK_VAR_ADDR") && mtok(2, "TOK_SADDR")) - { - set_tok(0, "TOK_VAR_SADDR"); - del(2); - } - } + peep_state state; + run_rules(table, state); } // Remove SADDR save/restore pairs around calls when no lvalue address is // pending. A push starts a region where SADDR is already saved, so nested @@ -786,119 +653,42 @@ class peephole // And go through code removing labels not in the list for(size_t i = 0; i < code.size(); i++) { - current = i; - if(mlabel(0) && !labels.count(lbl(0))) + if(code[i].is_label() && !labels.count(code[i].get_str())) { - del(0); + changed = true; + code.erase(code.begin() + i); i--; } } } - // Remove extra IOCHN0 tokens - void trace_iochn() - { - // This is the calculated current I/O channel - int ioch = 0; - for(current = 0; current < code.size(); current++) - { - if(!code[current].is_tok()) - { - if(mlabel(0)) - ioch = 0; // Assume 0 after any label or CALL - continue; - } - if(mtok(0, "TOK_CALL")) - ioch = 0; // Assume 0 after any label or CALL - else if(mtok(0, "TOK_NUM") && mword(1) && mtok(2, "TOK_IOCHN")) - { - if(ioch == val(1)) - { - // Remove redundant set IOCHN - del(2); - del(1); - del(0); - current--; - } - else - { - ioch = val(1); - current += 2; - } - } - else if(mtok(0, "TOK_IOCHN")) - { - ioch = -1; - } - else if(mtok(0, "TOK_NUM") && mword(1) && mtok(2, "TOK_IOCHN") && - mtok(3, "TOK_NUM") && mword(4) && mtok(5, "TOK_IOCHN")) - { - // Setting I/O channel just after IOCHN, delete redundant one - del(2); - del(1); - del(0); - current--; - } - } - } - // Jump threading optimization. // Replace JUMP to RET or another JUMP with a direct jump to target. - void replace_label_targets() + void build_label_targets(peep_state &state) { - // Build a MAP of label that go to another target - std::map tgt; - for(current = 0; current < code.size(); current++) + state.tgt.clear(); + // Map each label to the instruction it falls through to. + for(size_t current = 0; current < code.size(); current++) { - if(mlabel(0)) + if(code[current].is_label()) { - std::string l = lbl(0); - size_t i; + std::string l = code[current].get_str(); + size_t i = current + 1; // Search target - next "normal" instruction - for(i = 1; i < code.size() - current; i++) - if(!mlabel(i)) + for(; i < code.size(); i++) + if(!code[i].is_label()) break; else - tgt[l] = lbl(i); - if(mtok(i, "TOK_RET")) - tgt[l] = "__TOK_RET__"; - else if(mtok(i, "TOK_JUMP") && mlblw(i + 1)) - tgt[l] = wlbl(i + 1); - } - } - // Now, replace JUMPS - if(tgt.size()) - { - for(current = 0; current < code.size(); current++) - { - if(!code[current].is_tok()) - continue; - - if((mtok(0, "TOK_CJUMP") || mtok(0, "TOK_CNJUMP") || - mtok(0, "TOK_JUMP")) && - mlblw(1) && tgt.find(wlbl(1)) != tgt.end()) + state.tgt[l] = code[i].get_str(); + if(i < code.size()) { - std::string t = tgt[wlbl(1)]; - if(t == "__TOK_RET__") - { - // We can only replace JUMP to RET with RET, not ConditionalJUMP - if(mtok(0, "TOK_JUMP")) - { - set_tok(0, "TOK_RET"); - del(1); - } - else if(mtok(0, "TOK_CJUMP")) - { - set_tok(0, "TOK_CRET"); - del(1); - } - else if(mtok(0, "TOK_CNJUMP")) - { - set_tok(0, "TOK_CNRET"); - del(1); - } - } - else if(wlbl(1) != t) - set_ws(1, t); + auto &next = code[i]; + if(next.is_tok("TOK_RET")) + state.tgt[l] = "__TOK_RET__"; + else if(next.is_tok("TOK_JUMP") && i + 1 < code.size() && + code[i + 1].is_sword() && + code[i + 1].get_str().find("lbl") != + std::string::npos) + state.tgt[l] = code[i + 1].get_str(); } } } @@ -906,49 +696,32 @@ class peephole public: peephole(std::vector &code) - : code(code), rules("main", make_peephole_rules()), current(0) - { - expand_push(); - expand_numbers(); + : code(code), rules("main", make_peephole_rules()), + expand_push_rules("expand-push", make_expand_push_rules()), + expand_rules("expand-number", make_expand_number_rules()), + shorten_rules("shorten-number", make_shorten_number_rules()), + fold_push_rules("fold-push", make_fold_push_rules()), + fold_saddr_rules("fold-saddr", make_fold_saddr_rules()), + label_target_rules("label-target", make_label_target_rules()), + print_char_rules("print-char", make_print_char_rules()), + iochn_rules("iochn", make_iochn_rules()) + { + run_rules(expand_push_rules); + run_rules(expand_rules); do { changed = false; remove_unused_labels(); - replace_label_targets(); - trace_iochn(); peep_state state; - - for(size_t i = 0; i < code.size(); i++) - { - // Only go through tokens - if(!code[i].is_tok()) - continue; - - current = i; - - // Apply compiled token-rewrite rules. - { - std::vector replacement; - size_t begin, end; - bool modified; - if(rules.apply(code, i, state, replacement, begin, end, - modified)) - { - if(modified) - { - replace_range(begin, end, std::move(replacement)); - i--; - } - continue; - } - } - - } + build_label_targets(state); + run_rules(label_target_rules, state); + run_rules(iochn_rules); + run_rules(rules, state); } while(changed); - print_chars(); - shorten_numbers(); - fold_push(); - fold_saddr(); + run_rules(print_char_rules); + run_rules(shorten_rules); + run_rules(fold_push_rules); + run_rules(fold_saddr_rules); remove_saddr_saves(); } }; From 54544e69dca93d3eef3fc754c7e638f1091dd62f Mon Sep 17 00:00:00 2001 From: Daniel Serpell Date: Tue, 20 Oct 2026 20:23:12 -0300 Subject: [PATCH 06/11] compiler: Fold constant-address POKE expressions Use an expression span to handle any value expression after a constant byte POKE address. Reject spans that cross source lines, labels, or statement terminators so same-line statements and DPOKE sequences stay separate. The generic rule replaces the two redundant simple numeric-address POKE rules. Add a complex-value regression test, including same-line and DPOKE boundary cases. Aided by Opencode / DeepSeek V4.1 Flash 1017 --- src/compiler/peephole.cc | 15 ++++++++------- testsuite/tests/opt-poke-complex.bas | 20 ++++++++++++++++++++ testsuite/tests/opt-poke-complex.chk | 8 ++++++++ 3 files changed, 36 insertions(+), 7 deletions(-) create mode 100644 testsuite/tests/opt-poke-complex.bas create mode 100644 testsuite/tests/opt-poke-complex.chk diff --git a/src/compiler/peephole.cc b/src/compiler/peephole.cc index 7f1aaee..0e86835 100644 --- a/src/compiler/peephole.cc +++ b/src/compiler/peephole.cc @@ -111,14 +111,15 @@ static std::vector make_peephole_rules() }}, {"TOK_BYTE %B:x TOK_PEEK", "TOK_BYTE_PEEK $x"}, // Constant-address POKE variants. - {"TOK_NUM %c:a TOK_SADDR TOK_NUM %w:v TOK_POKE", + // Constant byte address with an arbitrary value expression. + {"TOK_NUM %c:a TOK_SADDR %e:value:TOK_POKE TOK_POKE", [](const peep_match &m, peep_builder &b) { - b.write("TOK_NUM %w", m.word("v") & 255); - b.write("TOK_BYTE_POKE %b", m.word("a")); - }}, - {"TOK_NUM %c:a TOK_SADDR TOK_VAR_LOAD %v:v TOK_POKE", - [](const peep_match &m, peep_builder &b) { - b.write("TOK_VAR_LOAD $v", m); + if(!b.valid_span(m, "value")) + { + b.keep(); + return; + } + b.raw(m, "value"); b.write("TOK_BYTE_POKE %b", m.word("a")); }}, {"TOK_BYTE %B:a TOK_SADDR TOK_NUM %w:v TOK_POKE", diff --git a/testsuite/tests/opt-poke-complex.bas b/testsuite/tests/opt-poke-complex.bas new file mode 100644 index 0000000..2066984 --- /dev/null +++ b/testsuite/tests/opt-poke-complex.bas @@ -0,0 +1,20 @@ +' POKE with a constant byte address and arbitrary value expression. +DIM A(5) +A(1) = 2 + +POKE 80, A(1) * 3 +? PEEK(80) + +POKE 80, 10 + 2 +? PEEK(80) + +POKE 80, A(1) +? PEEK(80) + +' Multiple statements on one line must not be merged. +POKE 80, 7 : POKE 81, 9 +? PEEK(80); " "; PEEK(81) + +' A preceding DPOKE must stop the expression span. +DPOKE 80, 0 : POKE 81, 5 +? PEEK(81) diff --git a/testsuite/tests/opt-poke-complex.chk b/testsuite/tests/opt-poke-complex.chk new file mode 100644 index 0000000..aea4578 --- /dev/null +++ b/testsuite/tests/opt-poke-complex.chk @@ -0,0 +1,8 @@ +Name: POKE constant address with complex values +Test: run +Output: +6 +12 +2 +7 9 +5 From 16f60d3dff1db253911009d20ab7c6749693c61b Mon Sep 17 00:00:00 2001 From: Daniel Serpell Date: Tue, 20 Oct 2026 20:44:52 -0300 Subject: [PATCH 07/11] compiler: Fold word-address POKE expressions Use the expression-span rule for constant word addresses, emitting NUM_POKE with the value expression. Remove the redundant simple word-address POKE rules and cover word-address values and statement boundaries in the regression test. Aided by Opencode / DeepSeek V4.1 Flash 1017 --- src/compiler/peephole.cc | 15 ++++++++------- testsuite/tests/opt-poke-complex.bas | 11 +++++++++++ testsuite/tests/opt-poke-complex.chk | 3 +++ 3 files changed, 22 insertions(+), 7 deletions(-) diff --git a/src/compiler/peephole.cc b/src/compiler/peephole.cc index 0e86835..eeebedc 100644 --- a/src/compiler/peephole.cc +++ b/src/compiler/peephole.cc @@ -131,16 +131,17 @@ static std::vector make_peephole_rules() [](const peep_match &m, peep_builder &b) { b.write("TOK_VAR_LOAD $v TOK_BYTE_POKE $a", m); }}, - {"TOK_NUM %W:a TOK_SADDR TOK_NUM %w:v TOK_POKE", + // Constant word address with an arbitrary value expression. + {"TOK_NUM %W:a TOK_SADDR %e:value:TOK_POKE TOK_POKE", [](const peep_match &m, peep_builder &b) { - b.write("TOK_NUM %w", m.word("v") & 255); + if(!b.valid_span(m, "value")) + { + b.keep(); + return; + } + b.raw(m, "value"); b.write("TOK_NUM_POKE $a", m); }}, - {"TOK_NUM %w:a TOK_SADDR TOK_VAR_LOAD %v:v TOK_POKE", - [](const peep_match &m, peep_builder &b) { - b.write("TOK_VAR_LOAD $v", m); - b.write("TOK_NUM_POKE %w", m.word("a")); - }}, // Constant arithmetic operations. {"TOK_NUM %w:x TOK_PUSH TOK_NUM %w:y TOK_MUL", [](const peep_match &m, peep_builder &b) { diff --git a/testsuite/tests/opt-poke-complex.bas b/testsuite/tests/opt-poke-complex.bas index 2066984..0d29792 100644 --- a/testsuite/tests/opt-poke-complex.bas +++ b/testsuite/tests/opt-poke-complex.bas @@ -18,3 +18,14 @@ POKE 80, 7 : POKE 81, 9 ' A preceding DPOKE must stop the expression span. DPOKE 80, 0 : POKE 81, 5 ? PEEK(81) + +' Word-address POKE uses NUM_POKE. +POKE 1000, A(1) * 4 +? PEEK(1000) + +POKE 1000, 11 +? PEEK(1000) + +' A preceding DPOKE must stop the word-address span too. +DPOKE 1000, 0 : POKE 1002, 5 +? PEEK(1002) diff --git a/testsuite/tests/opt-poke-complex.chk b/testsuite/tests/opt-poke-complex.chk index aea4578..8f77d15 100644 --- a/testsuite/tests/opt-poke-complex.chk +++ b/testsuite/tests/opt-poke-complex.chk @@ -6,3 +6,6 @@ Output: 2 7 9 5 +8 +11 +5 From 0a76722d8f72dd0fad9f23cc25669529216bbaad Mon Sep 17 00:00:00 2001 From: Daniel Serpell Date: Tue, 20 Oct 2026 20:47:54 -0300 Subject: [PATCH 08/11] compiler: Fold symbolic byte-address POKE expressions Generalize symbolic byte-address POKE to match arbitrary value expressions, replacing the two simple-value rules. Add a cross-only regression test for the imported byte symbol. Aided by Opencode / DeepSeek V4.1 Flash 1017 --- src/compiler/peephole.cc | 14 ++++++++------ testsuite/tests/opt-poke-symbolic.bas | 6 ++++++ testsuite/tests/opt-poke-symbolic.chk | 4 ++++ 3 files changed, 18 insertions(+), 6 deletions(-) create mode 100644 testsuite/tests/opt-poke-symbolic.bas create mode 100644 testsuite/tests/opt-poke-symbolic.chk diff --git a/src/compiler/peephole.cc b/src/compiler/peephole.cc index eeebedc..d08c94a 100644 --- a/src/compiler/peephole.cc +++ b/src/compiler/peephole.cc @@ -122,15 +122,17 @@ static std::vector make_peephole_rules() b.raw(m, "value"); b.write("TOK_BYTE_POKE %b", m.word("a")); }}, - {"TOK_BYTE %B:a TOK_SADDR TOK_NUM %w:v TOK_POKE", + // Symbolic byte address with an arbitrary value expression. + {"TOK_BYTE %B:a TOK_SADDR %e:value:TOK_POKE TOK_POKE", [](const peep_match &m, peep_builder &b) { - b.write("TOK_NUM %w", m.word("v") & 255); + if(!b.valid_span(m, "value")) + { + b.keep(); + return; + } + b.raw(m, "value"); b.write("TOK_BYTE_POKE $a", m); }}, - {"TOK_BYTE %B:a TOK_SADDR TOK_VAR_LOAD %v:v TOK_POKE", - [](const peep_match &m, peep_builder &b) { - b.write("TOK_VAR_LOAD $v TOK_BYTE_POKE $a", m); - }}, // Constant word address with an arbitrary value expression. {"TOK_NUM %W:a TOK_SADDR %e:value:TOK_POKE TOK_POKE", [](const peep_match &m, peep_builder &b) { diff --git a/testsuite/tests/opt-poke-symbolic.bas b/testsuite/tests/opt-poke-symbolic.bas new file mode 100644 index 0000000..5bb39e1 --- /dev/null +++ b/testsuite/tests/opt-poke-symbolic.bas @@ -0,0 +1,6 @@ +' POKE with a symbolic byte address and arbitrary value expression. +DIM A(5) +A(1) = 2 + +POKE @@TMPCHR, A(1) * 5 +? PEEK(@@TMPCHR) diff --git a/testsuite/tests/opt-poke-symbolic.chk b/testsuite/tests/opt-poke-symbolic.chk new file mode 100644 index 0000000..04202d0 --- /dev/null +++ b/testsuite/tests/opt-poke-symbolic.chk @@ -0,0 +1,4 @@ +Name: POKE symbolic byte address with complex values +Test: run-cross +Output: +10 From f4f039aaf46e5306bf5e97f2763468f64bfdfb7f Mon Sep 17 00:00:00 2001 From: Daniel Serpell Date: Tue, 20 Oct 2026 22:07:56 -0300 Subject: [PATCH 09/11] compiler: Store INPUT results directly into variables Fold the address/SADDR sequence around INPUT into a variable store. This removes the DPOKE address setup when the INPUT target is a word variable. Aided by Opencode / DeepSeek V4.1 Flash 1017 --- src/compiler/peephole.cc | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/compiler/peephole.cc b/src/compiler/peephole.cc index d08c94a..a8c63ae 100644 --- a/src/compiler/peephole.cc +++ b/src/compiler/peephole.cc @@ -75,6 +75,8 @@ static std::vector make_peephole_rules() "TOK_GET TOK_VAR_STORE $v"}, {"TOK_VAR_ADDR %v:v TOK_SADDR TOK_GETKEY TOK_DPOKE", "TOK_GETKEY TOK_VAR_STORE $v"}, + {"TOK_VAR_ADDR %v:v TOK_SADDR TOK_INPUT_STR TOK_VAL TOK_DPOKE", + "TOK_INPUT_STR TOK_VAL TOK_VAR_STORE $v"}, {"TOK_NUM %w:x TOK_PUT", [](const peep_match &m, peep_builder &b) { b.write("TOK_BYTE_PUT %b", m.word("x")); From c16ff7e1e842982601ead62a3072261b986107e6 Mon Sep 17 00:00:00 2001 From: Daniel Serpell Date: Tue, 20 Oct 2026 23:53:39 -0300 Subject: [PATCH 10/11] tests: Cover missing peephole rules Add arithmetic, boolean, conditional-return, address increment and byte-symbol PUT tests, and extend the boolean test to cover comparison normalization. Each test checks the optimized program's output, not only that the compiler accepts it. Aided by Opencode / DeepSeek V4.1 Flash 1017 --- testsuite/tests/opt-address.bas | 9 +++++++++ testsuite/tests/opt-address.chk | 5 +++++ testsuite/tests/opt-arith.bas | 21 +++++++++++++++++++++ testsuite/tests/opt-arith.chk | 15 +++++++++++++++ testsuite/tests/opt-bool.bas | 14 ++++++++++++++ testsuite/tests/opt-bool.chk | 9 +++++++++ testsuite/tests/opt-put-symbol.bas | 4 ++++ testsuite/tests/opt-put-symbol.chk | 4 ++++ testsuite/tests/opt-return.bas | 21 +++++++++++++++++++++ testsuite/tests/opt-return.chk | 6 ++++++ 10 files changed, 108 insertions(+) create mode 100644 testsuite/tests/opt-address.bas create mode 100644 testsuite/tests/opt-address.chk create mode 100644 testsuite/tests/opt-arith.bas create mode 100644 testsuite/tests/opt-arith.chk create mode 100644 testsuite/tests/opt-bool.bas create mode 100644 testsuite/tests/opt-bool.chk create mode 100644 testsuite/tests/opt-put-symbol.bas create mode 100644 testsuite/tests/opt-put-symbol.chk create mode 100644 testsuite/tests/opt-return.bas create mode 100644 testsuite/tests/opt-return.chk diff --git a/testsuite/tests/opt-address.bas b/testsuite/tests/opt-address.bas new file mode 100644 index 0000000..a556660 --- /dev/null +++ b/testsuite/tests/opt-address.bas @@ -0,0 +1,9 @@ +' Check peephole address increment/decrement rules. +DIM A +A = 10 + +DPOKE ADR(A), A + 1 +? A + +DPOKE ADR(A), A - 1 +? A diff --git a/testsuite/tests/opt-address.chk b/testsuite/tests/opt-address.chk new file mode 100644 index 0000000..52ea39e --- /dev/null +++ b/testsuite/tests/opt-address.chk @@ -0,0 +1,5 @@ +Name: Test peephole address increment/decrement rules +Test: run +Output: +11 +10 diff --git a/testsuite/tests/opt-arith.bas b/testsuite/tests/opt-arith.bas new file mode 100644 index 0000000..23e7931 --- /dev/null +++ b/testsuite/tests/opt-arith.bas @@ -0,0 +1,21 @@ +' Check peephole arithmetic rules. +DIM A +DIM B +DIM C +A = 10 +B = 3 +C = 2 + +? 7 - 2 +? -(1 + 2) +? A / 1 +? A * 1 +? A * 4 +? A * 256 +? A - 0 +? A - B - C +? A - B - 2 +? A - 2 - B +? A - 2 - 3 +A = A - 1 +? A diff --git a/testsuite/tests/opt-arith.chk b/testsuite/tests/opt-arith.chk new file mode 100644 index 0000000..ccabf67 --- /dev/null +++ b/testsuite/tests/opt-arith.chk @@ -0,0 +1,15 @@ +Name: Test peephole arithmetic rules +Test: run +Output: +5 +-3 +10 +10 +40 +2560 +10 +5 +5 +5 +5 +9 diff --git a/testsuite/tests/opt-bool.bas b/testsuite/tests/opt-bool.bas new file mode 100644 index 0000000..5fd09a4 --- /dev/null +++ b/testsuite/tests/opt-bool.bas @@ -0,0 +1,14 @@ +' Check peephole boolean rules. +DIM A +DIM B +A = 1 +B = 2 + +? (A = B) +? (A > B) +? ((A > B) OR (A = B)) +IF (A OR B) THEN ? "or" +IF NOT (A = B) THEN ? "ne" +IF NOT (A <> B) THEN ? "eq" +IF NOT 1 THEN ? "bad" +? "done" diff --git a/testsuite/tests/opt-bool.chk b/testsuite/tests/opt-bool.chk new file mode 100644 index 0000000..30f5767 --- /dev/null +++ b/testsuite/tests/opt-bool.chk @@ -0,0 +1,9 @@ +Name: Test peephole boolean rules +Test: run +Output: +0 +0 +0 +or +ne +done diff --git a/testsuite/tests/opt-put-symbol.bas b/testsuite/tests/opt-put-symbol.bas new file mode 100644 index 0000000..b001cda --- /dev/null +++ b/testsuite/tests/opt-put-symbol.bas @@ -0,0 +1,4 @@ +' Check the byte-symbol PUT peephole rule. +' TMPCHR is the byte symbol at $50, so PUT outputs "P". +PUT @@TMPCHR +? "!" diff --git a/testsuite/tests/opt-put-symbol.chk b/testsuite/tests/opt-put-symbol.chk new file mode 100644 index 0000000..9a9e05a --- /dev/null +++ b/testsuite/tests/opt-put-symbol.chk @@ -0,0 +1,4 @@ +Name: Test byte-symbol PUT peephole rule +Test: run-cross +Output: +P! diff --git a/testsuite/tests/opt-return.bas b/testsuite/tests/opt-return.bas new file mode 100644 index 0000000..15e8f16 --- /dev/null +++ b/testsuite/tests/opt-return.bas @@ -0,0 +1,21 @@ +' Check peephole conditional-return rules. +DIM A +A = 1 + +PROC P + IF A THEN RETURN + ? "p" +ENDPROC + +PROC Q + IF NOT A THEN RETURN + ? "q" +ENDPROC + +@P +@Q + +A = 0 +@P +@Q +? "done" diff --git a/testsuite/tests/opt-return.chk b/testsuite/tests/opt-return.chk new file mode 100644 index 0000000..3196881 --- /dev/null +++ b/testsuite/tests/opt-return.chk @@ -0,0 +1,6 @@ +Name: Test peephole conditional-return rules +Test: run +Output: +q +p +done From e1414a82c28250b60c00fba497a60644e594ee3b Mon Sep 17 00:00:00 2001 From: Daniel Serpell Date: Tue, 20 Oct 2026 23:53:58 -0300 Subject: [PATCH 11/11] compiler: Add peephole coverage checking Tag the optimizer debug output with the phase and rule number, and add a development target that compiles the test sources with both targets and fails if any peephole rule is not reached. The check uses test sources only, so an uncovered rule cannot be hidden by the compiler or IDE. Remove the rules that the coverage report proved unreachable, and keep the generated coverage files under build/ so make clean and make distclean remove them. Aided by Opencode / DeepSeek V4.1 Flash 1017 --- rules.mak | 2 ++ src/compiler/peephole.cc | 11 ------- tests.mak | 20 ++++++++++++ testsuite/README.md | 19 ++++++++++++ testsuite/peephole-coverage.sh | 56 ++++++++++++++++++++++++++++++++++ 5 files changed, 97 insertions(+), 11 deletions(-) create mode 100755 testsuite/peephole-coverage.sh diff --git a/rules.mak b/rules.mak index b01b740..8ca1deb 100644 --- a/rules.mak +++ b/rules.mak @@ -43,6 +43,8 @@ clean: $(Q)rm -f $(TESTS_ATB) $(Q)rm -f $(TESTS_LBL) $(Q)rm -f $(TESTS_STAMP) + $(Q)rm -f $(PEEPHOLE_COVERAGE_FILES) + $(Q)rmdir $(PEEPHOLE_COVERAGE_DIR) 2>/dev/null || true $(Q)if [ -d build/tests ]; then \ for manifest in build/tests/.fbtest-manifest-*; do \ [ -f "$$manifest" ] || continue; \ diff --git a/src/compiler/peephole.cc b/src/compiler/peephole.cc index a8c63ae..fe95488 100644 --- a/src/compiler/peephole.cc +++ b/src/compiler/peephole.cc @@ -188,12 +188,6 @@ static std::vector make_peephole_rules() [](const peep_match &m) { return m.word("one") == 1 && m.varn("x") == m.varn("y"); }}, - {"TOK_VAR_LOAD %v:x TOK_PUSH TOK_NUM %w:one TOK_ADD " - "TOK_VAR_STORE %v:y", - "TOK_INCVAR $x", - [](const peep_match &m) { - return m.word("one") == 1 && m.varn("x") == m.varn("y"); - }}, {"TOK_VAR_LOAD %v:x TOK_PUSH TOK_NUM %w:one TOK_SUB " "TOK_VAR_STORE %v:y", "TOK_DECVAR $x", @@ -210,7 +204,6 @@ static std::vector make_peephole_rules() {"TOK_NEQ TOK_L_NOT", "TOK_EQ"}, {"TOK_CALL %l:target TOK_RET", "TOK_JUMP $target"}, {"TOK_L_NOT TOK_CJUMP", "TOK_CNJUMP"}, - {"TOK_L_NOT TOK_CNJUMP", "TOK_CJUMP"}, {"TOK_CJUMP %l:from TOK_JUMP %l:to %L:end", "TOK_CNJUMP $to $end", [](const peep_match &m) { @@ -241,8 +234,6 @@ static std::vector make_peephole_rules() [](const peep_match &m) { return m.word("v") == 0 && m.text("from") == m.text("end"); }}, - {"TOK_L_NOT TOK_CRET", "TOK_CNRET"}, - {"TOK_L_NOT TOK_CNRET", "TOK_CRET"}, {"TOK_NUM %w:x TOK_COMP_0", [](const peep_match &m, peep_builder &b) { b.write("TOK_NUM %w", m.word("x") ? 1 : 0); @@ -412,9 +403,7 @@ static std::vector make_expand_push_rules() return { {"TOK_PUSH_BYTE", "TOK_PUSH TOK_BYTE"}, {"TOK_PUSH_NUM", "TOK_PUSH TOK_NUM"}, - {"TOK_PUSH_0", "TOK_PUSH TOK_0"}, {"TOK_PUSH_1", "TOK_PUSH TOK_1"}, - {"TOK_PUSH_VAR_LOAD", "TOK_PUSH TOK_VAR_LOAD"}, {"TOK_VAR_SADDR %v:x", "TOK_VAR_ADDR $x TOK_SADDR"}, }; } diff --git a/tests.mak b/tests.mak index 031d8e0..094c2d8 100644 --- a/tests.mak +++ b/tests.mak @@ -55,12 +55,32 @@ TESTS_ATB=$(TESTS:testsuite/%.chk=build/%.atb) TESTS_LBL=$(TESTS:testsuite/%.chk=build/%.lbl) TESTS_STAMP=$(TESTS:testsuite/%.chk=build/%.stamp) +# Files created by testsuite/peephole-coverage.sh. The coverage run uses the +# normal test sources, but writes both target outputs into its own directory. +PEEPHOLE_COVERAGE_BAS := $(sort $(wildcard testsuite/tests/*.bas)) +PEEPHOLE_COVERAGE_DIR := build/peephole-coverage +PEEPHOLE_COVERAGE_ASM = \ + $(PEEPHOLE_COVERAGE_BAS:testsuite/tests/%.bas=$(PEEPHOLE_COVERAGE_DIR)/%.atari-int.asm) \ + $(PEEPHOLE_COVERAGE_BAS:testsuite/tests/%.bas=$(PEEPHOLE_COVERAGE_DIR)/%.atari-fp.asm) +PEEPHOLE_COVERAGE_FILES = \ + $(PEEPHOLE_COVERAGE_DIR)/debug.log \ + $(PEEPHOLE_COVERAGE_DIR)/patterns \ + $(PEEPHOLE_COVERAGE_DIR)/matches \ + $(PEEPHOLE_COVERAGE_DIR)/applied \ + $(PEEPHOLE_COVERAGE_DIR)/missing \ + $(PEEPHOLE_COVERAGE_ASM) + RUNTEST_OBJS=build/obj/tests/fbtest.o $(MINI65_SRC:%.c=build/obj/tests/%.o) # Runs the test suite .PHONY: test test: $(TESTS_STAMP) $(RUNTEST) +# Checks that the test sources reach every peephole optimizer rule. +.PHONY: peephole-coverage +peephole-coverage: $(FASTBASIC_HOST) + $(Q)$(SHELL) testsuite/peephole-coverage.sh + .SECONDEXPANSION: build/tests/%.stamp: testsuite/tests/%.chk $$(wildcard testsuite/tests/$$*.bas) \ $(wildcard testsuite/tests/fixtures/*) \ diff --git a/testsuite/README.md b/testsuite/README.md index 94c027f..c8a92e1 100644 --- a/testsuite/README.md +++ b/testsuite/README.md @@ -228,6 +228,25 @@ Both dump variables are switches; the files are always written under `build/tests/`. +Peephole optimizer coverage +--------------------------- + +The cross-compiler can report every peephole rule and every successful match +when `FASTBASIC_PEEPHOLE_DEBUG` is set. The coverage check compiles all test +sources for both targets, then fails if any rule was not reached: + + make peephole-coverage + +The report lists matched and rewritten rule counts. It treats a rule as +covered when its pattern plus guard matched, not only when it produced a +rewrite, because some rules deliberately only update optimizer state. The +full compiler output is kept in `build/peephole-coverage/debug.log`. + +When adding or changing an optimizer rule, add a test that exercises its +transformation and checks the program's output. A rule that cannot be reached +from the grammar should be removed rather than left uncovered. + + Cleanup ------- diff --git a/testsuite/peephole-coverage.sh b/testsuite/peephole-coverage.sh new file mode 100755 index 0000000..4fd6091 --- /dev/null +++ b/testsuite/peephole-coverage.sh @@ -0,0 +1,56 @@ +#!/bin/sh +# +# Report peephole optimizer rule coverage from the test suite. +# +# The compiler prints every rule and every successful match when +# FASTBASIC_PEEPHOLE_DEBUG is set. Compile the test sources with both +# targets, collect the matches, and fail if any rule was not reached. +# +set -eu + +cd "$(dirname "$0")/.." + +compiler=build/bin/fastbasic +[ -x "$compiler" ] || { + echo "peephole-coverage: build/bin/fastbasic not found; run make first" >&2 + exit 2 +} + +out=build/peephole-coverage +rm -rf "$out" +mkdir -p "$out" +log=$out/debug.log +: > "$log" + +for src in testsuite/tests/*.bas; do + [ -f "$src" ] || continue + name=$(basename "$src" .bas) + for target in atari-int atari-fp; do + FASTBASIC_PEEPHOLE_DEBUG=1 \ + "$compiler" -target-path:compiler -syntax-path:src/syntax \ + -t:"$target" -c -o "$out/$name.$target.asm" "$src" \ + 2>>"$log" >/dev/null || true + done +done + +# Keep the table name and rule number with the pattern: the same source +# pattern can occur in more than one phase, or with different guards in the +# same phase. +sed -n 's/^peephole pattern \[\([^]]*\)\] #\([0-9]*\): /\1|\2|/p' "$log" | sort -u > "$out/patterns" +sed -n 's/^peephole match \[\([^]]*\)\] #\([0-9]*\): /\1|\2|/p' "$log" | sort -u > "$out/matches" +sed -n 's/^peephole apply \[\([^]]*\)\] #\([0-9]*\): /\1|\2|/p' "$log" | sort -u > "$out/applied" + +comm -23 "$out/patterns" "$out/matches" > "$out/missing" + +patterns=$(wc -l < "$out/patterns") +matches=$(wc -l < "$out/matches") +applied=$(wc -l < "$out/applied") +printf 'Peephole coverage: %s/%s rules matched, %s rewrites\n' \ + "$matches" "$patterns" "$applied" + +if [ -s "$out/missing" ]; then + echo "Rules not reached:" + awk -F'|' '{print " [" $1 "] #" $2 ": " $3}' "$out/missing" + echo "Debug log: $log" + exit 1 +fi