Fun With LLVM & Whirl

It’s been a long time since I wrote any code purely for fun - but I recently finished just such a project.

Pretty much ever since I heard about LLVM I’ve wanted to do something with it. The obvious choice was to build a compiler for one of my esoteric languages. Well, I finally got around to trying it out with Whirl - and it’s pretty sweet.

Since Whirl is actually quite dynamic, the generated code ended up being pretty much nothing more than an assembly language version of a Whirl interpreter with the given Whirl program packaged in. Oh well.

This entire project is pretty useless, frankly, but that wasn’t the point. The real point is that, with a few jumps through some hoops, I can actually compile Whirl code into a native executable. How’s that for bad ass?

Compiling the compiler is pretty easy (must have LLVM and gcc installed, of course):


g++ -O3 whirl-llvm.cpp `llvm-config --cxxflags --ldflags --libs core jit native` -o whirl

This yields an executable which will take a whirl source file and not only print the LLVM instructions to stderr, but also JIT the resulting compiled Whirl program and run it. Any results are printed to stdout. This is pretty neat by itself, of course, but the real magic comes with a few more commands:


$ ./whirl slarty-hello_world.txt 2> hello.llvm
$ llvm-as -o hello.bc hello.llvm
$ gcc -o runtime.o -c whirl-runtime.c
$ llvm-ld -native -o hello hello.bc runtime.o

After this series of commands, there’s a platform-native executable named “hello” in the directory! You can run it just like any other native binary. Freaking awesome!

The LLVM crew is working on native code generation out of the box. Right now it requires gcc (and llvm-ld cheats and calls out to gcc internally) to actually construct the native executable. (Well, technically it just needs “as” and “ld”, but my toy here relies on a couple C functions since that was an easy solution. I suppose I could have compiled it with llvm-gcc, though.) Eventually, perhaps after this year’s Google Summer of Code, there will be an all-LLVM solution which would lead to a completely standalone compiler. I’m looking forward to that!

So anyway, you can grab this (likely terrible) code for my LLVM Whirl Compiler right here. Don’t forget to grab the “runtime” code, too, which cheats a bit and uses some C functions to do the Whirl I/O commands.

Comments are closed.