[LLVMdev] Saving code for later execution

Óscar Fuentes ofv at wanadoo.es
Wed Sep 19 09:25:46 PDT 2012

"Paul J. Lucas" <paul at lucasmail.org> writes:

> I'm using the LLVM C++ API to create code on-the-fly for execution.
> This works fine.  But what if I want to save this code to disk, quit,
> relaunch my app at some later time, reload the previously generated
> code off disk, and execute it?
> How can I do that?  Can somebody point me to some documentation or
> examples?  Thanks.

For starters, you need the BitWriter and BitReader libraries. See the
lli tool (under tools/lli/lli.cpp) for an example on how to use the
BitReader and llc or llvm-as to see how to use the BitWriter.

It is quite easy. The critical part for saving is:

      std::string errorInfo;
      llvm::raw_fd_ostream f("mybitcode.bc", errorInfo, raw_fd_ostream::F_Binary);
      WriteBitcodeToFile(M, f);

where M is a llvm::Module*.

For reading:

    LLVMContext Context;
    SMDiagnostic Err;
    Module *M = ParseIRFile("mybitcode.bc", Err, Context);

You need to add the dependencies to your build, header files, etc. See
the llvm tools mentioned above.

More information about the llvm-dev mailing list