LibASTMatchersTutorial.rst 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560
  1. ===============================================================
  2. Tutorial for building tools using LibTooling and LibASTMatchers
  3. ===============================================================
  4. This document is intended to show how to build a useful source-to-source
  5. translation tool based on Clang's `LibTooling <LibTooling.html>`_. It is
  6. explicitly aimed at people who are new to Clang, so all you should need
  7. is a working knowledge of C++ and the command line.
  8. In order to work on the compiler, you need some basic knowledge of the
  9. abstract syntax tree (AST). To this end, the reader is incouraged to
  10. skim the :doc:`Introduction to the Clang
  11. AST <IntroductionToTheClangAST>`
  12. Step 0: Obtaining Clang
  13. =======================
  14. As Clang is part of the LLVM project, you'll need to download LLVM's
  15. source code first. Both Clang and LLVM are maintained as Subversion
  16. repositories, but we'll be accessing them through the git mirror. For
  17. further information, see the `getting started
  18. guide <http://llvm.org/docs/GettingStarted.html>`_.
  19. .. code-block:: console
  20. mkdir ~/clang-llvm && cd ~/clang-llvm
  21. git clone http://llvm.org/git/llvm.git
  22. cd llvm/tools
  23. git clone http://llvm.org/git/clang.git
  24. cd clang/tools
  25. git clone http://llvm.org/git/clang-tools-extra.git extra
  26. Next you need to obtain the CMake build system and Ninja build tool. You
  27. may already have CMake installed, but current binary versions of CMake
  28. aren't built with Ninja support.
  29. .. code-block:: console
  30. cd ~/clang-llvm
  31. git clone https://github.com/martine/ninja.git
  32. cd ninja
  33. git checkout release
  34. ./bootstrap.py
  35. sudo cp ninja /usr/bin/
  36. cd ~/clang-llvm
  37. git clone git://cmake.org/stage/cmake.git
  38. cd cmake
  39. git checkout next
  40. ./bootstrap
  41. make
  42. sudo make install
  43. Okay. Now we'll build Clang!
  44. .. code-block:: console
  45. cd ~/clang-llvm
  46. mkdir build && cd build
  47. cmake -G Ninja ../llvm -DLLVM_BUILD_TESTS=ON # Enable tests; default is off.
  48. ninja
  49. ninja check # Test LLVM only.
  50. ninja clang-test # Test Clang only.
  51. ninja install
  52. And we're live.
  53. All of the tests should pass, though there is a (very) small chance that
  54. you can catch LLVM and Clang out of sync. Running ``'git svn rebase'``
  55. in both the llvm and clang directories should fix any problems.
  56. Finally, we want to set Clang as its own compiler.
  57. .. code-block:: console
  58. cd ~/clang-llvm/build
  59. ccmake ../llvm
  60. The second command will bring up a GUI for configuring Clang. You need
  61. to set the entry for ``CMAKE_CXX_COMPILER``. Press ``'t'`` to turn on
  62. advanced mode. Scroll down to ``CMAKE_CXX_COMPILER``, and set it to
  63. ``/usr/bin/clang++``, or wherever you installed it. Press ``'c'`` to
  64. configure, then ``'g'`` to generate CMake's files.
  65. Finally, run ninja one last time, and you're done.
  66. Step 1: Create a ClangTool
  67. ==========================
  68. Now that we have enough background knowledge, it's time to create the
  69. simplest productive ClangTool in existence: a syntax checker. While this
  70. already exists as ``clang-check``, it's important to understand what's
  71. going on.
  72. First, we'll need to create a new directory for our tool and tell CMake
  73. that it exists. As this is not going to be a core clang tool, it will
  74. live in the ``tools/extra`` repository.
  75. .. code-block:: console
  76. cd ~/clang-llvm/llvm/tools/clang
  77. mkdir tools/extra/loop-convert
  78. echo 'add_subdirectory(loop-convert)' >> tools/extra/CMakeLists.txt
  79. vim tools/extra/loop-convert/CMakeLists.txt
  80. CMakeLists.txt should have the following contents:
  81. ::
  82. set(LLVM_LINK_COMPONENTS support)
  83. set(LLVM_USED_LIBS clangTooling clangBasic clangAST)
  84. add_clang_executable(loop-convert
  85. LoopConvert.cpp
  86. )
  87. target_link_libraries(loop-convert
  88. clangTooling
  89. clangBasic
  90. clangASTMatchers
  91. )
  92. With that done, Ninja will be able to compile our tool. Let's give it
  93. something to compile! Put the following into
  94. ``tools/extra/loop-convert/LoopConvert.cpp``. A detailed explanation of
  95. why the different parts are needed can be found in the `LibTooling
  96. documentation <LibTooling.html>`_.
  97. .. code-block:: c++
  98. // Declares clang::SyntaxOnlyAction.
  99. #include "clang/Frontend/FrontendActions.h"
  100. #include "clang/Tooling/CommonOptionsParser.h"
  101. #include "clang/Tooling/Tooling.h"
  102. // Declares llvm::cl::extrahelp.
  103. #include "llvm/Support/CommandLine.h"
  104. using namespace clang::tooling;
  105. using namespace llvm;
  106. // Apply a custom category to all command-line options so that they are the
  107. // only ones displayed.
  108. static llvm::cl::OptionCategory MyToolCategory("my-tool options");
  109. // CommonOptionsParser declares HelpMessage with a description of the common
  110. // command-line options related to the compilation database and input files.
  111. // It's nice to have this help message in all tools.
  112. static cl::extrahelp CommonHelp(CommonOptionsParser::HelpMessage);
  113. // A help message for this specific tool can be added afterwards.
  114. static cl::extrahelp MoreHelp("\nMore help text...");
  115. int main(int argc, const char **argv) {
  116. CommonOptionsParser OptionsParser(argc, argv, MyToolCategory);
  117. ClangTool Tool(OptionsParser.getCompilations(),
  118. OptionsParser.getSourcePathList());
  119. return Tool.run(newFrontendActionFactory<clang::SyntaxOnlyAction>().get());
  120. }
  121. And that's it! You can compile our new tool by running ninja from the
  122. ``build`` directory.
  123. .. code-block:: console
  124. cd ~/clang-llvm/build
  125. ninja
  126. You should now be able to run the syntax checker, which is located in
  127. ``~/clang-llvm/build/bin``, on any source file. Try it!
  128. .. code-block:: console
  129. cat "int main() { return 0; }" > test.cpp
  130. bin/loop-convert test.cpp --
  131. Note the two dashes after we specify the source file. The additional
  132. options for the compiler are passed after the dashes rather than loading
  133. them from a compilation database - there just aren't any options needed
  134. right now.
  135. Intermezzo: Learn AST matcher basics
  136. ====================================
  137. Clang recently introduced the :doc:`ASTMatcher
  138. library <LibASTMatchers>` to provide a simple, powerful, and
  139. concise way to describe specific patterns in the AST. Implemented as a
  140. DSL powered by macros and templates (see
  141. `ASTMatchers.h <../doxygen/ASTMatchers_8h_source.html>`_ if you're
  142. curious), matchers offer the feel of algebraic data types common to
  143. functional programming languages.
  144. For example, suppose you wanted to examine only binary operators. There
  145. is a matcher to do exactly that, conveniently named ``binaryOperator``.
  146. I'll give you one guess what this matcher does:
  147. .. code-block:: c++
  148. binaryOperator(hasOperatorName("+"), hasLHS(integerLiteral(equals(0))))
  149. Shockingly, it will match against addition expressions whose left hand
  150. side is exactly the literal 0. It will not match against other forms of
  151. 0, such as ``'\0'`` or ``NULL``, but it will match against macros that
  152. expand to 0. The matcher will also not match against calls to the
  153. overloaded operator ``'+'``, as there is a separate ``operatorCallExpr``
  154. matcher to handle overloaded operators.
  155. There are AST matchers to match all the different nodes of the AST,
  156. narrowing matchers to only match AST nodes fulfilling specific criteria,
  157. and traversal matchers to get from one kind of AST node to another. For
  158. a complete list of AST matchers, take a look at the `AST Matcher
  159. References <LibASTMatchersReference.html>`_
  160. All matcher that are nouns describe entities in the AST and can be
  161. bound, so that they can be referred to whenever a match is found. To do
  162. so, simply call the method ``bind`` on these matchers, e.g.:
  163. .. code-block:: c++
  164. variable(hasType(isInteger())).bind("intvar")
  165. Step 2: Using AST matchers
  166. ==========================
  167. Okay, on to using matchers for real. Let's start by defining a matcher
  168. which will capture all ``for`` statements that define a new variable
  169. initialized to zero. Let's start with matching all ``for`` loops:
  170. .. code-block:: c++
  171. forStmt()
  172. Next, we want to specify that a single variable is declared in the first
  173. portion of the loop, so we can extend the matcher to
  174. .. code-block:: c++
  175. forStmt(hasLoopInit(declStmt(hasSingleDecl(varDecl()))))
  176. Finally, we can add the condition that the variable is initialized to
  177. zero.
  178. .. code-block:: c++
  179. forStmt(hasLoopInit(declStmt(hasSingleDecl(varDecl(
  180. hasInitializer(integerLiteral(equals(0))))))))
  181. It is fairly easy to read and understand the matcher definition ("match
  182. loops whose init portion declares a single variable which is initialized
  183. to the integer literal 0"), but deciding that every piece is necessary
  184. is more difficult. Note that this matcher will not match loops whose
  185. variables are initialized to ``'\0'``, ``0.0``, ``NULL``, or any form of
  186. zero besides the integer 0.
  187. The last step is giving the matcher a name and binding the ``ForStmt``
  188. as we will want to do something with it:
  189. .. code-block:: c++
  190. StatementMatcher LoopMatcher =
  191. forStmt(hasLoopInit(declStmt(hasSingleDecl(varDecl(
  192. hasInitializer(integerLiteral(equals(0)))))))).bind("forLoop");
  193. Once you have defined your matchers, you will need to add a little more
  194. scaffolding in order to run them. Matchers are paired with a
  195. ``MatchCallback`` and registered with a ``MatchFinder`` object, then run
  196. from a ``ClangTool``. More code!
  197. Add the following to ``LoopConvert.cpp``:
  198. .. code-block:: c++
  199. #include "clang/ASTMatchers/ASTMatchers.h"
  200. #include "clang/ASTMatchers/ASTMatchFinder.h"
  201. using namespace clang;
  202. using namespace clang::ast_matchers;
  203. StatementMatcher LoopMatcher =
  204. forStmt(hasLoopInit(declStmt(hasSingleDecl(varDecl(
  205. hasInitializer(integerLiteral(equals(0)))))))).bind("forLoop");
  206. class LoopPrinter : public MatchFinder::MatchCallback {
  207. public :
  208. virtual void run(const MatchFinder::MatchResult &Result) {
  209. if (const ForStmt *FS = Result.Nodes.getNodeAs<clang::ForStmt>("forLoop"))
  210. FS->dump();
  211. }
  212. };
  213. And change ``main()`` to:
  214. .. code-block:: c++
  215. int main(int argc, const char **argv) {
  216. CommonOptionsParser OptionsParser(argc, argv, MyToolCategory);
  217. ClangTool Tool(OptionsParser.getCompilations(),
  218. OptionsParser.getSourcePathList());
  219. LoopPrinter Printer;
  220. MatchFinder Finder;
  221. Finder.addMatcher(LoopMatcher, &Printer);
  222. return Tool.run(newFrontendActionFactory(&Finder).get());
  223. }
  224. Now, you should be able to recompile and run the code to discover for
  225. loops. Create a new file with a few examples, and test out our new
  226. handiwork:
  227. .. code-block:: console
  228. cd ~/clang-llvm/llvm/llvm_build/
  229. ninja loop-convert
  230. vim ~/test-files/simple-loops.cc
  231. bin/loop-convert ~/test-files/simple-loops.cc
  232. Step 3.5: More Complicated Matchers
  233. ===================================
  234. Our simple matcher is capable of discovering for loops, but we would
  235. still need to filter out many more ourselves. We can do a good portion
  236. of the remaining work with some cleverly chosen matchers, but first we
  237. need to decide exactly which properties we want to allow.
  238. How can we characterize for loops over arrays which would be eligible
  239. for translation to range-based syntax? Range based loops over arrays of
  240. size ``N`` that:
  241. - start at index ``0``
  242. - iterate consecutively
  243. - end at index ``N-1``
  244. We already check for (1), so all we need to add is a check to the loop's
  245. condition to ensure that the loop's index variable is compared against
  246. ``N`` and another check to ensure that the increment step just
  247. increments this same variable. The matcher for (2) is straightforward:
  248. require a pre- or post-increment of the same variable declared in the
  249. init portion.
  250. Unfortunately, such a matcher is impossible to write. Matchers contain
  251. no logic for comparing two arbitrary AST nodes and determining whether
  252. or not they are equal, so the best we can do is matching more than we
  253. would like to allow, and punting extra comparisons to the callback.
  254. In any case, we can start building this sub-matcher. We can require that
  255. the increment step be a unary increment like this:
  256. .. code-block:: c++
  257. hasIncrement(unaryOperator(hasOperatorName("++")))
  258. Specifying what is incremented introduces another quirk of Clang's AST:
  259. Usages of variables are represented as ``DeclRefExpr``'s ("declaration
  260. reference expressions") because they are expressions which refer to
  261. variable declarations. To find a ``unaryOperator`` that refers to a
  262. specific declaration, we can simply add a second condition to it:
  263. .. code-block:: c++
  264. hasIncrement(unaryOperator(
  265. hasOperatorName("++"),
  266. hasUnaryOperand(declRefExpr())))
  267. Furthermore, we can restrict our matcher to only match if the
  268. incremented variable is an integer:
  269. .. code-block:: c++
  270. hasIncrement(unaryOperator(
  271. hasOperatorName("++"),
  272. hasUnaryOperand(declRefExpr(to(varDecl(hasType(isInteger())))))))
  273. And the last step will be to attach an identifier to this variable, so
  274. that we can retrieve it in the callback:
  275. .. code-block:: c++
  276. hasIncrement(unaryOperator(
  277. hasOperatorName("++"),
  278. hasUnaryOperand(declRefExpr(to(
  279. varDecl(hasType(isInteger())).bind("incrementVariable"))))))
  280. We can add this code to the definition of ``LoopMatcher`` and make sure
  281. that our program, outfitted with the new matcher, only prints out loops
  282. that declare a single variable initialized to zero and have an increment
  283. step consisting of a unary increment of some variable.
  284. Now, we just need to add a matcher to check if the condition part of the
  285. ``for`` loop compares a variable against the size of the array. There is
  286. only one problem - we don't know which array we're iterating over
  287. without looking at the body of the loop! We are again restricted to
  288. approximating the result we want with matchers, filling in the details
  289. in the callback. So we start with:
  290. .. code-block:: c++
  291. hasCondition(binaryOperator(hasOperatorName("<"))
  292. It makes sense to ensure that the left-hand side is a reference to a
  293. variable, and that the right-hand side has integer type.
  294. .. code-block:: c++
  295. hasCondition(binaryOperator(
  296. hasOperatorName("<"),
  297. hasLHS(declRefExpr(to(varDecl(hasType(isInteger()))))),
  298. hasRHS(expr(hasType(isInteger())))))
  299. Why? Because it doesn't work. Of the three loops provided in
  300. ``test-files/simple.cpp``, zero of them have a matching condition. A
  301. quick look at the AST dump of the first for loop, produced by the
  302. previous iteration of loop-convert, shows us the answer:
  303. ::
  304. (ForStmt 0x173b240
  305. (DeclStmt 0x173afc8
  306. 0x173af50 "int i =
  307. (IntegerLiteral 0x173afa8 'int' 0)")
  308. <<>>
  309. (BinaryOperator 0x173b060 '_Bool' '<'
  310. (ImplicitCastExpr 0x173b030 'int'
  311. (DeclRefExpr 0x173afe0 'int' lvalue Var 0x173af50 'i' 'int'))
  312. (ImplicitCastExpr 0x173b048 'int'
  313. (DeclRefExpr 0x173b008 'const int' lvalue Var 0x170fa80 'N' 'const int')))
  314. (UnaryOperator 0x173b0b0 'int' lvalue prefix '++'
  315. (DeclRefExpr 0x173b088 'int' lvalue Var 0x173af50 'i' 'int'))
  316. (CompoundStatement ...
  317. We already know that the declaration and increments both match, or this
  318. loop wouldn't have been dumped. The culprit lies in the implicit cast
  319. applied to the first operand (i.e. the LHS) of the less-than operator,
  320. an L-value to R-value conversion applied to the expression referencing
  321. ``i``. Thankfully, the matcher library offers a solution to this problem
  322. in the form of ``ignoringParenImpCasts``, which instructs the matcher to
  323. ignore implicit casts and parentheses before continuing to match.
  324. Adjusting the condition operator will restore the desired match.
  325. .. code-block:: c++
  326. hasCondition(binaryOperator(
  327. hasOperatorName("<"),
  328. hasLHS(ignoringParenImpCasts(declRefExpr(
  329. to(varDecl(hasType(isInteger())))))),
  330. hasRHS(expr(hasType(isInteger())))))
  331. After adding binds to the expressions we wished to capture and
  332. extracting the identifier strings into variables, we have array-step-2
  333. completed.
  334. Step 4: Retrieving Matched Nodes
  335. ================================
  336. So far, the matcher callback isn't very interesting: it just dumps the
  337. loop's AST. At some point, we will need to make changes to the input
  338. source code. Next, we'll work on using the nodes we bound in the
  339. previous step.
  340. The ``MatchFinder::run()`` callback takes a
  341. ``MatchFinder::MatchResult&`` as its parameter. We're most interested in
  342. its ``Context`` and ``Nodes`` members. Clang uses the ``ASTContext``
  343. class to represent contextual information about the AST, as the name
  344. implies, though the most functionally important detail is that several
  345. operations require an ``ASTContext*`` parameter. More immediately useful
  346. is the set of matched nodes, and how we retrieve them.
  347. Since we bind three variables (identified by ConditionVarName,
  348. InitVarName, and IncrementVarName), we can obtain the matched nodes by
  349. using the ``getNodeAs()`` member function.
  350. In ``LoopConvert.cpp`` add
  351. .. code-block:: c++
  352. #include "clang/AST/ASTContext.h"
  353. Change ``LoopMatcher`` to
  354. .. code-block:: c++
  355. StatementMatcher LoopMatcher =
  356. forStmt(hasLoopInit(declStmt(
  357. hasSingleDecl(varDecl(hasInitializer(integerLiteral(equals(0))))
  358. .bind("initVarName")))),
  359. hasIncrement(unaryOperator(
  360. hasOperatorName("++"),
  361. hasUnaryOperand(declRefExpr(
  362. to(varDecl(hasType(isInteger())).bind("incVarName")))))),
  363. hasCondition(binaryOperator(
  364. hasOperatorName("<"),
  365. hasLHS(ignoringParenImpCasts(declRefExpr(
  366. to(varDecl(hasType(isInteger())).bind("condVarName"))))),
  367. hasRHS(expr(hasType(isInteger())))))).bind("forLoop");
  368. And change ``LoopPrinter::run`` to
  369. .. code-block:: c++
  370. void LoopPrinter::run(const MatchFinder::MatchResult &Result) {
  371. ASTContext *Context = Result.Context;
  372. const ForStmt *FS = Result.Nodes.getStmtAs<ForStmt>("forLoop");
  373. // We do not want to convert header files!
  374. if (!FS || !Context->getSourceManager().isFromMainFile(FS->getForLoc()))
  375. return;
  376. const VarDecl *IncVar = Result.Nodes.getNodeAs<VarDecl>("incVarName");
  377. const VarDecl *CondVar = Result.Nodes.getNodeAs<VarDecl>("condVarName");
  378. const VarDecl *InitVar = Result.Nodes.getNodeAs<VarDecl>("initVarName");
  379. if (!areSameVariable(IncVar, CondVar) || !areSameVariable(IncVar, InitVar))
  380. return;
  381. llvm::outs() << "Potential array-based loop discovered.\n";
  382. }
  383. Clang associates a ``VarDecl`` with each variable to represent the variable's
  384. declaration. Since the "canonical" form of each declaration is unique by
  385. address, all we need to do is make sure neither ``ValueDecl`` (base class of
  386. ``VarDecl``) is ``NULL`` and compare the canonical Decls.
  387. .. code-block:: c++
  388. static bool areSameVariable(const ValueDecl *First, const ValueDecl *Second) {
  389. return First && Second &&
  390. First->getCanonicalDecl() == Second->getCanonicalDecl();
  391. }
  392. If execution reaches the end of ``LoopPrinter::run()``, we know that the
  393. loop shell that looks like
  394. .. code-block:: c++
  395. for (int i= 0; i < expr(); ++i) { ... }
  396. For now, we will just print a message explaining that we found a loop.
  397. The next section will deal with recursively traversing the AST to
  398. discover all changes needed.
  399. As a side note, it's not as trivial to test if two expressions are the same,
  400. though Clang has already done the hard work for us by providing a way to
  401. canonicalize expressions:
  402. .. code-block:: c++
  403. static bool areSameExpr(ASTContext *Context, const Expr *First,
  404. const Expr *Second) {
  405. if (!First || !Second)
  406. return false;
  407. llvm::FoldingSetNodeID FirstID, SecondID;
  408. First->Profile(FirstID, *Context, true);
  409. Second->Profile(SecondID, *Context, true);
  410. return FirstID == SecondID;
  411. }
  412. This code relies on the comparison between two
  413. ``llvm::FoldingSetNodeIDs``. As the documentation for
  414. ``Stmt::Profile()`` indicates, the ``Profile()`` member function builds
  415. a description of a node in the AST, based on its properties, along with
  416. those of its children. ``FoldingSetNodeID`` then serves as a hash we can
  417. use to compare expressions. We will need ``areSameExpr`` later. Before
  418. you run the new code on the additional loops added to
  419. test-files/simple.cpp, try to figure out which ones will be considered
  420. potentially convertible.