It took about 2 days of programming and 2 days of debugging (one of which was
Rainer's :-) ) to get an x86 code generator working for the toy compiler I wrote
last year.
There were two bugs in the generated code; Rainer caught the first one, to do
with comparisons. The second was that I was failing to assign to any array
elements. Turned out to be simple: I had "mov eax,[ecx]" when I should have had
"mov [ecx], eax"
It now runs my test program, Ecce, perfectly. (Ecce is an old line-based text
editor; I actually still use a later variant of it, embedded within emacs, as my
main editor)
I defined a very simple stack machine, and then wrote a program that read the
stack-machine assembly code and macro expanded each instruction into a
functionally equivalent set of x86 instructions.
The generated code is something like a third the speed and three times the size
of 'proper' x86 code, but it works.
What I'll be doing in the long term is making my toy language look more like a
cut down version of C (rather than a lot like Rainer's "LC", which is what it
started out to be based on), and I'll simplify the source code of my compiler
until it can compile itself, at which point it's officially not a toy compiler
any more :-) (Toy being defined as any compiler that cannot compile itself)
Then with this virtual stack machine as an intermediate code, I have a way to
rapidy bootstrap the compiler to any other architecture.
I still have a fair bit of work to do, eg to make sure that I can cross-call C
etc, but the hard part is now done. Now that I can write solid reliable simple
code, expanding the features supported should happen quickly.
The test program is here:
http://www.gtoal.com/compilers101/intro/gtoal/interp/ecce.t.txt (source)
http://www.gtoal.com/compilers101/intro/gtoal/interp/ecce.asm.txt (stack
machine)
http://www.gtoal.com/compilers101/intro/gtoal/interp/ecce.S.txt (x86 code)
http://www.gtoal.com/compilers101/intro/gtoal/interp/ecce (linux executable)
I even have some documentation:
http://history.dcs.ed.ac.uk/archive/apps/ecce/hwhitfield/ecce.txt (man page)
http://history.dcs.ed.ac.uk/archive/apps/ecce/hmd/ecce8.txt (primer)
This version doesn't have any file I/O yet, it just starts with an empty buffer,
and throws everything away on exit. I expect that will probably be improved
before the weekend is over :-)
G