How to make use of Clang's AST?

依然范特西╮ 提交于 2019-11-30 00:06:51

Start with the tutorial linked by sharth. Then go through Clang's Doxygen. Start with SemaConsumer.

Read a lot of source code. Clang is a moving target. If you are writing tools based on clang, then you need to recognize that clang is adding and fixing features daily, so you should be prepared to read a lot of code!

You probably want the stable C API provided in the libclang library, as opposed to the unstable C++ internal APIs that others have mentioned.

The best documentation to start with currently is the video/slides of the talk, "libclang: Thinking Beyond the Compiler" available on the LLVM Developers Meeting website.

However, do note that the stability of the API comes at a cost of comprehensiveness. You won't be able to do everything with this API, but it is much easier to use.

I find this ASTUnit::LoadFromCompilerInvocation() fn as the most easiest way to construct the AST.

This link may give you some ideas http://comments.gmane.org/gmane.comp.compilers.clang.devel/12471

To obtain the AST as well as get to know stages of the frontend, there is a frontend chapter in the book "LLVM core libraries". Basically it has such a flow (in the case of llvm-4.0.1 and should similar for later versions):

  • cc1_main.cpp:cc1_main (ExecuteCompilerInvocation)
  • CompilerInstance.cpp:CompilerInstance::ExecuteAction
  • ParseAST.cpp:clang::ParseAST (Consumer>HandleTranslationUnit(S.getASTContext())
  • CodeGenAction.cpp:HandleTranslationUnit

The last function handles the whole translation unit(top level decls are already handled at this point), and calls EmitBackendOutput to do backend stuff. So this function is a good spot where you can do something with the complete AST and before emitting backend output.

In terms of how to manipulate the AST, clang has some basic tutorial on this: http://clang.llvm.org/docs/RAVFrontendAction.html.

Also look at ASTDumper.cpp. It's the best example of visiting the AST.

Another good tutorial: https://jonasdevlieghere.com/understanding-the-clang-ast/ teaches you how to find a specific call expr in the AST via three different approaches.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!