Real-world garbage collection with LLVM

Published April 11, 2013
Advertisement
The last major task for release 14 of the Epoch programming language is integrating garbage collection with the LLVM-supported JIT native code generation layer.

Ostensibly, LLVM supports hooks for making garbage collection possible. It doesn't take much digging to find out that this is a complete lie, and LLVM is actually pretty terrible at interoperating with garbage collection schemes.

First of all, you can only mark stack allocations as holding GC roots. Registers must be spilled into stack values prior to running a GC pass or you can miss roots. More annoyingly, you can only declare GC root stack allocations in the prolog of a function - you can't mark them inside, say, the body of a loop. This means you either generate a lot of excess stack reads/writes, or you do something twisted to work around the problem.

I'm proud of Epoch's runtime performance right now, so I opted to go the twisted route.

The Epoch garbage collector will now only trigger on the exit from a function or after a certain number of iterations of a closed loop (to avoid excess memory consumption in tight loop code). This means that you will never trip a garbage collection in the middle of a complex expression, which in turn limits the number of stack hits I have to perform. So that much I can suffer through.

To do accurate garbage collection, we need three things:

  • A map of all stack slots that can contain GC roots
  • A way to get this map into the GC so it can use it
  • A way to crawl the machine stack based on this map and begin mark/sweep tracing from the discovered roots
So LLVM has a nifty @llvm.gcroot intrinsic which lets you accomplish the first goal; the code generation layer will output a stack map for you.

Except it doesn't.

What it does is create a stack map and then make it totally inaccessible to JIT frontends, which strikes me as more than a bit stupid. I quickly found the comment buried in the documentation suggesting that you can only access the stack map when outputting assembly language listings. WTF?! It was at this point that I started really feeling the truth that others have remarked about on the internet: LLVM just sucks for garbage collectors.

Me being stubborn and thick-headed, though, I decided to just plow forward and hope for the best.

I hacked around the unavailable stack map issue by implementing a custom GCStrategy class with CustomSafePoints set to true. When findCustomSafePoints() is called, I do the exact same logic as the LLVM default implementation of safe-point location, with two tweaks:

  • All safe points are cached in a location accessible to the frontend (and, later, the GC as running against the JITted code)
  • I actually implemented support for GC::Return safepoints so I can call garbage collection routines upon function exit. LLVM provides GC::Return and GC::Loop "kinds" of safepoints but then stupefyingly fails to implement support for either one.
The next annoying omission in LLVM is the lack of a stack walking function to actually use stack maps. I suppose this can be forgiven since LLVM is not (ostensibly) in the business of target-specific stack walking code. But it's still annoying.

Thankfully I've spent enough time doing reversing and assembly-level hacking that I'm comfortable with the idea of crawling the machine stack myself. It didn't take long to put together a function for this, although getting it to not clobber the machine state was a bit trickier.

There are two tricks to keep in mind when doing post-function-body garbage collection invocations:

  • Back up an instruction before the RET before you CALL the garbage collector. This lets you inject the CALL prior to the POP EBP that destroys the function's stack frame and makes this whole exercise pointless.
  • Don't forget that you were about to RET from a function; write some custom prolog/epilog code to ensure you don't clobber EAX during garbage collection. Or at least save it off someplace so you can restore it once you're done clobbering it.
Armed with a stack crawler, I found one final hurdle that is probably the most shining example of LLVM's complete lack of consideration for garbage collector authors: once you generate a safe point, you can't actually determine what machine address it's at in the emitted machine code! Derp.

So I wound up making a minor API tweak to the ExecutionEngine class in LLVM, adding in plumbing to get to the underlying JIT engine and ask for the address of the MCSymbol corresponding to the injected GC safe point. It took some minor arithmetic to adjust the reported address to line up with actual return addresses in each stack frame, but nothing too painful.


The results speak for themselves:

Garbage collection experiment.png


So as of now I have a working way to crawl the stack and look for GC roots. I'm starting out only supporting GC on strings since that's easier than dealing with all the other types in the language; but that'll come soon enough. I want to perfect the actual mark/sweep logic first and then mess with extending it to handle the whole type system.

Next step is to go through and actually do mark/sweep and emit a list of live strings versus garbage strings. Should be entertaining.


Overall, although I've been cursing at LLVM a lot today, it's not been too terrible. It certainly beats having to build my own machine code emission layer. Part of the reason I've stuck with it is because it does do a great job of just generating fast machine code, so I'm not totally convinced it's worth abandoning and using some other JIT engine, just for the sake of GC implementation.

If anything, I'd rather find ways to actually contribute some useful changes to LLVM that make the whole GC song and dance a little less unpleasant for the next guy.
3 likes 8 comments

Comments

ApochPiQ
As of this comment, I have mark/sweep garbage collection of strings implemented and working. There's a lot of hackery and magic involved, so I need to go back through and clean it all up at some point, but it runs and passes a rudimentary test.
April 11, 2013 05:12 AM
Mike.Popoloski

Nice. I'd like to work on a GC at some point; they're cool bits of software.

You should go all out and make yours generational.

April 11, 2013 04:09 PM
_the_phantom_

Nice indeed - I'll be interested to see the code for this :D

April 11, 2013 05:43 PM
ApochPiQ
Code is crufty as hell and needs a LOT of love, but you can get a glimpse here
April 11, 2013 05:49 PM
cr88192

FWIW: I looked at targeting LLVM before, and it looked like a big PITA (errm... SSA scares me...), so I mostly have just been using my own interpreters and occasional naive JIT backends... (generally using an assembler to convert generated ASM into machine code).

all this doesn't really make LLVM sound like happy fun time either...

April 11, 2013 11:11 PM
ApochPiQ
Actually, SSA makes codegen a lot cleaner and opens up a lot of potential for optimizations. It's also pretty easy to use once you get used to the general process.

As much as I hate on LLVM's GC non-support, I actually really like it for everything else it does. Part of why the GC situation frustrates me so much is that I do like LLVM overall, and don't want to leave it.
April 11, 2013 11:33 PM
cr88192

the problem I think is that SSA is kind of confusing though (notably the phi operator... I know what it does but don't really understand it...).

or, at least, it seems more confusing than stack machines or non-SSA three-address register machines...

granted, my interpreters and JITs could be considered fairly naive vs a "real" compiler (my most recent one mostly just spits out a mix of call-threaded code and some preformed instruction sequences).

granted, I have also ended up raging against the SysV/AMD64 ABI as well... (my stuff supports it, but "cuts a few corners").

currently, my JIT uses a stack-machine model, but I had considered moving to a register machine model, just it is hard to justify the time/effort this would require. the bytecode would remain stack-based though, using a register machine mostly as the backend model (I have done this in the past though...).

April 12, 2013 03:04 AM
AlexandreMutel

Thanks for your feedback, that's interesting!

Have you look about the generated code? I have read many times that using llvm.gcroot is removing most of the potential optimizations later done by LLVM (the issue 1917 for example was closed with 'wontfix') so I'm not sure that LLVM allows gcroot to be promoted to registers.

June 04, 2013 01:57 AM
You must log in to join the conversation.
Don't have a GameDev.net account? Sign up!
Profile
Author
Advertisement
Advertisement