agg212
agg212

Reputation: 407

C++ string to LLVM IR

I would like to take a string representation of a C++ lambda function like this:

string fun = "[](int x) { return x + 5;}";
string llvm_ir = clang.get_llvm_ir(fun);  // does something like this exist?

and convert it to LLVM IR using Clang from within C++. Is there a way to do this directly using Clang's internal API?

Upvotes: 3

Views: 395

Answers (1)

Eli Bendersky
Eli Bendersky

Reputation: 273456

To the best of my knowledge, there is no stable, officially supported API to do this. The Clang C API provides front-end level information (source-code level). Neither does Clang tooling provide this.

You do have good options though. The easiest is to just invoke the Clang front-end as a subprocess clang -cc1 -emit-llvm ...<other options>. This will produce a LLVM IR file which you can then read. It's actually fairly common practice in compilers - the Clang driver itself does this - it invokes the frontend and a bunch of other tools (like the linker), depending on the specific compilation task.

Alternatively, if you feel you must have a programmatic API for this, you can dig in the code of the Clang front-end (the -cc1 invocation mentioned above) to see how it accomplishes it, and collect bits and pieces of code. Be prepared to write a huge amount of scaffolding, though, because these APIs were not designed to be used externally.

To reiterate, it is possible using internal APIs, but there's no easy or recommended way following this path.

Upvotes: 4

Related Questions