Author | Jakob Wakeling <[email protected]> |
Date | 2020-09-21 02:50:41 |
Commit | aa068e3488a7be1f4cd515e6ce7c4bf770ba01a5 |
Parent | 72ba95922f02ef96b02c1a79069fe03a3dcd8132 |
Add optimisation comments
Diffstat
M | src/obfi.c | | | 14 | ++++++++++++-- |
1 files changed, 12 insertions, 2 deletions
diff --git a/src/obfi.c b/src/obfi.c index db7f355..7ed0754 100644 --- a/src/obfi.c +++ b/src/obfi.c @@ -76,31 +76,38 @@ int main(int ac, char *av[]) { A0 = av[0]; fread(fb, 1, fl, fi); fclose(fi); + // Remove comments from instruction buffer char *p = fb, *q = fb; for (; *p; ++p) if (strchr("><+-.,[]", *p)) { *q++ = *p; } *q = 0; register size_t i, j; for (i = 0; fb[i]; ++i) { - switch (fb[i]) { + switch (fb[i]) { // Generate initial operands case '<': case '-': { fc[i] = -1; break; } default: { fc[i] = 1; break; } } - switch (fb[i]) { + switch (fb[i]) { // Standardise instructions case '>': case '<': { fb[i] = '>'; break; } case '+': case '-': { fb[i] = '+'; break; } } } + // Compress movement and additive instructions for (i = 0, j = 0; fb[i]; ++j) { fb[j] = fb[i]; fc[j] = fc[i]; if (strchr(">+", fb[++i])) for (; fb[j] == fb[i]; fc[j] += fc[i++]); } fb[j] = 0; for (i = 0; fb[i]; ++i) { + // Optimise set to zero loops if (cmp(fb + i, "[+]")) { fb[i] = 'Z'; fb[i + 1] = fb[i + 2] = ' '; } + + // Optimise move to zero loops else if (cmp(fb + i, "[>]")) { fb[i] = 'T'; fb[i + 1] = fb[i + 2] = ' '; fc[i] = fc[i + 1]; } + + // Optimise backward and forward move to loops else if (cmp(fb + i, "[+>+>]") && fc[i + 1] == -1 && fc[i + 3] == 1 && fc[i + 2] == -fc[i + 4]) { fb[i] = 'M'; @@ -115,10 +122,12 @@ int main(int ac, char *av[]) { A0 = av[0]; } } + // Remove resultant spaces of loop optimisations for (i = 0, j = 0; fb[i]; ++i) if (fb[i] != ' ') { fb[j] = fb[i]; fc[j] = fc[i]; ++j; } fb[j] = 0; + // Convert instructions to opcodes for (i = 0; fb[i]; ++i) { for (j = 0; fb[i] != ">+.,[]ZTM"[j]; ++j) {} fb[i] = j + 1; } @@ -126,6 +135,7 @@ int main(int ac, char *av[]) { A0 = av[0]; size_t l = 1024, t = 0, *S = malloc(l * sizeof (*S)); if (!S) { error(1, "%s", serr()); } + // Find and store bracket pairs for (size_t i = 0; fb[i]; ++i) switch (fb[i]) { case 5: { S[t++] = i; break; } case 6: { --t; fc[S[t]] = i - S[t]; fc[i] = S[t] - i; break; }