Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store the generated LLVM-IR code of a llvm::Module to a string?

Tags:

llvm

The Fibonacciexample of LLVM prints out LLVM IR using errs() << *theModule.

Is there any function that is able to store the generated LLVM IR to a (vector of) string or any other variable rather than just print it out? (e.g., std::string llvm_IR = theModule->getIR())

I been searching llvm::Module Class Reference and get nothing helpful on it.

Part of Fibonacci.cpp:

//CreateFibFunction is defined previously to generate the fibonacci function.

LLVMContext Context;

// Create some module to put our function into it.
std::unique_ptr<Module> Owner(new Module("test", Context));
Module *theModule = Owner.get();

// We are about to create the "fib" function:
Function *FibF = CreateFibFunction(M, Context);
errs() << "OK\n";
errs() << "We just constructed this LLVM module:\n\n---------\n";
errs() << *theModule;
errs() << "---------\nstarting fibonacci(" << n << ") with JIT...\n";
like image 918
Rahn Avatar asked Nov 27 '15 15:11

Rahn


People also ask

What is IR in LLVM?

LLVM is designed around a language-independent intermediate representation (IR) that serves as a portable, high-level assembly language that can be optimized with a variety of transformations over multiple passes. LLVM.

Does LLVM compile to machine code?

LLVM is a language-agnostic compiler toolchain that handles program optimization and code generation. It is based on its own internal representation, called LLVM IR, which is then transformed into machine code.

What is an LLVM module?

Modules represent the top-level structure in an LLVM program. An LLVM module is effectively a translation unit or a collection of translation units merged together.

What is NSW in LLVM?

• nsw – no signed wrap for add, sub, mul, shl. • nuw – no unsigned wrap for add, sub, mul, shl. • exact – no remainder for sdiv, udiv, lshr, ashr.


1 Answers

You can do it the same way -- instead of using errs(), which is a raw_ostream, you can use a raw_string_ostream, like this:

std::string Str;
raw_string_ostream OS(Str);
OS << *theModule;
OS.flush()
// Str now contains the module text
like image 183
Ismail Badawi Avatar answered Nov 11 '22 19:11

Ismail Badawi