r/Compilers • u/Livid_Way_5266 • Oct 19 '26
Recompiling Game Boy machine code to Haxe, and checking every block against an interpreter in lockstep
I work since a while on gb2swf, a static recompiler that takes Game Boy (SM83) machine code and turns it into Haxe, which then compiles to a Flash SWF that runs in Ruffle. Yes, Flash. But the part that fits this sub is the recompiler so thats what this post is about
The classic problem with static recompilation of old console code is that you dont know what is code and what is data, and you dont know all jump targets (jp hl, jump tables). So I dont try to find it statically. The ROM first runs on an interpreter in Node.js, once without input and four times with random button presses, 6000 frames each, and it records every executed instruction and every jump target. Only blocks that were actually seen get recompiled.
Codegen: every basic block becomes Haxe with the SM83 registers as local variables. Blocks are grouped into functions, so one block flows into the next without going back through a dispatch loop. The original instruction stays as a comment above each generated line so the output is still readable.
The verification is the part I would like feedback on. The game runs on the interpreter and on the recompiled code side by side with three input sequences, one of them the profiler never saw. At every block entry the registers and the cycle count have to match, and every frame has to match. If a block diverges it goes back to the interpreter and the check runs again, so a mismatch never ends up in the output. Code the profiler never reached also stays on the interpreter, the game always runs, unseen paths are just slower.
Interpreter and recompiler are both generated from one description of the instruction set so they cant drift apart. Memory accesses happen on the correct cycle inside each instruction, otherwise the cycle check would mean nothing.
Numbers on 7 open licensed homebrew games (M1, Ruffle in headless Chrome, input the profiler hadnt seen): 79 to 98% of executed instructions run as recompiled code, and a frame takes 6 to 11 ms of the 16.7 ms budget.
What still bothers me:
- the 2 to 21% that stays interpreted is mostly code behind rare input. You can record your own play and feed it back with `gb2swf --record`, on itself that works but its not really a solution
- lockstep only proves the two are equal on the inputs I tried, nothing more
Did someone here do something like this for another ISA? Mostly curious how you handled coverage, is there something smarter then random button mashing...
I made this, its MIT and the repo is public on the Burg Media github (no ROMs included ofcourse)