开发者

How to make use of Clang's AST?

I am looking at making use of the Clang's AST for my C code and do some analysis over the AST. Some pointers on where to start, how to obtain the Clang's AST, tutorials or an开发者_运维问答ything in this regard will be of great help!!!

I have been trying to find some and I got this link which was created 2 years back. But for some reason, it is not working for me. The sample code, in the tutorial, gives me too many errors. So I am not sure, if I build the code properly or some thing is wrong with the tutorial. But I would be happy to start from some other page as well.


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.


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜