Building an LLVM Pass

April 18, 2014 · 2 minute read

Sometimes you want to write an LLVM pass without having to download and build the entire LLVM source tree. For instance, you may want to use an existing LLVM binary package, or you may have already built LLVM and simply want to create a shared library that contains an add-on pass.

Unfortunately, if you’ve ever read LLVM’s tutorial on Writing An LLVM Pass , you’ll know that it instructs you to make modifications to the LLVM source tree. When you compile LLVM, your pass gets built with the rest: the build system generates a shared library in the lib directory that can be loaded with opt. Although this is a straightforward way to get things done, it seems rather heavy-handed to compile all of LLVM when all you wanted to do was build a single pass.

Here’s an alternate technique that lets you develop your pass outside the LLVM source tree. Just write your code as normal in a directory of your choosing. Then, when you want to compile, here’s the special recipe:

CXXFLAGS=`llvm-config --cxxflags` LLVMLIBS=`llvm-config --libs` LDFLAGS=`llvm-config --ldflags` LOADABLEOPTS=-Wl,-flat_namespace -Wl,-undefined,suppress g++ $(CXXFLAGS) -fpic -c ./*.cpp g++ $(LLVMLIBS) $(LDFLAGS) -shared $(LOADABLEOPTS) -o libMine.so ./*.o

The first call to g++ generates object files in PIC format, and the second call links the objects into a shared object called libMine.so.1 The magic comes from llvm-config, which is a utility that comes with LLVM whose only purpose is to generate the compiler flags necessary to build tools that link against LLVM. The other things to note are the special linker flags in LOADABLEOPTS required to create loadable modules compatible with opt.2


  1. If you’re using Mac OS X, replace -shared with -dynamiclib. [return]
  2. I found these options by examining Makefile.rules under the LLVM source tree: the options are stored in the variable LoadableModuleOptions. I confess I haven’t dug deeper to understand why these linker flags are necessary. [return]