[pypy-dev] Pypy custom interpreter JIT question

Andrew Brown brownan at gmail.com
Tue Mar 22 20:44:36 CET 2011

Hello PyPy team,

So I became interested in the translation toolchain plus JIT compiler
generator, and in attempt to learn more about it, I set out to write a very
simple interpreter for the language BF (brainf***). Simple enough, 8
opcodes, each with no arguments, and most have a one line implementation.
Also plenty of examples out there to run, like a mandelbrot generator =)

So I wrote up an interpreter for it in RPython. This worked great until I
tried to enable the JIT option, at which point it would produce incorrect
results. Strange, I thought I may have been using the hints incorrectly, I
couldn't find too many details on exactly what the red and green vars should

Here's the strange part though: I finally fixed it by changing an
implementation detail that shouldn't have changed semantics at all.

My implementation creates an instance of a Tape object which has two
attributes: a list of integers representing the state of the machine, and a
single integer identifying the current active cell on the tape.

The implementation of each opcode was a method of this class, and the state
of the program (what I passed as the "red" variable) was the instance of
this class.

After I manually factored the functionality of the class directly into the
main dispatch loop and got rid of the class entirely, the JIT compiler
started producing correct results.

Can anyone help me figure out why my first attempt didn't work? Do red
variables that are in class instances need to be handled different somehow?

Here's the initial version that runs incorrectly when translated with JIT:
Here's the modified version that seems to work just fine:

In particular, note the elimination of the Tape object in the second
version, and the differences in the mainloop function as well as the
differences in the "red" variables.

I've also included a few example BF programs if someone wants to try it out.
The hanoi example crashes almost immediately with the first version
translated with JIT.

By the way, I've been translating it with the latest version of PyPy off of
bitbucket. (latest as of a few weeks ago, that is)

Thanks and great work on this project!
-Andrew Brown
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/pypy-dev/attachments/20110322/11394033/attachment.html>

More information about the Pypy-dev mailing list