StudyingCui
StudyingCui

Reputation: 21

How to convert a cpp file's source code to IR by using libtooling (clang C++ API)?

We know that the IR file can be obtained from foo.cpp through the clang driver:

clang++ -emit-llvm -S foo.cpp -o foo.ll

Now I want to do this by using the libTooling's API without clang driver.

But I don't know how these APIs are used, I would like to know if there are some examples of using them, for example:

How to generate AST from cpp file?

How to convert AST to IR in memory form?

How to convert AST to IR in human readable text form?

All of this jobs' source code is very complex, but if libTooling provides some APIs, it may be simple, so what I want to know is whether these APIs exist and how to use them. Are there any examples that can be referenced?

Upvotes: 2

Views: 563

Answers (1)

Nick Lewycky
Nick Lewycky

Reputation: 1342

  1. The libTooling tutorial documentation shows a code snippet that parses .cpp into AST: https://clang.llvm.org/docs/LibTooling.html . Remember that the hard part of doing this on real files is having all the include search paths and defines and everything set up correctly.

  2. You can use the clang::EmitLLVMOnlyAction to create LLVM IR in memory, use takeModule() to retrieve the LLVM module that clang produces. See https://github.com/llvm/llvm-project/blob/main/clang/tools/clang-fuzzer/handle-cxx/handle_cxx.cpp for an example of running an action over some AST (they use clang::EmitObjAction instead, but other than that it's the same).

  3. LLVM IR is a 1:1:1 representation between in-memory : bitcode : text. A llvm::Module has a print method, you can print to a llvm::raw_ostream backed by a string or backed by a file descriptor.

Upvotes: 2

Related Questions