1============= 2Clang Plugins 3============= 4 5Clang Plugins make it possible to run extra user defined actions during a 6compilation. This document will provide a basic walkthrough of how to write and 7run a Clang Plugin. 8 9Introduction 10============ 11 12Clang Plugins run FrontendActions over code. See the :doc:`FrontendAction 13tutorial <RAVFrontendAction>` on how to write a ``FrontendAction`` using the 14``RecursiveASTVisitor``. In this tutorial, we'll demonstrate how to write a 15simple clang plugin. 16 17Writing a ``PluginASTAction`` 18============================= 19 20The main difference from writing normal ``FrontendActions`` is that you can 21handle plugin command line options. The ``PluginASTAction`` base class declares 22a ``ParseArgs`` method which you have to implement in your plugin. 23 24.. code-block:: c++ 25 26 bool ParseArgs(const CompilerInstance &CI, 27 const std::vector<std::string>& args) { 28 for (unsigned i = 0, e = args.size(); i != e; ++i) { 29 if (args[i] == "-some-arg") { 30 // Handle the command line argument. 31 } 32 } 33 return true; 34 } 35 36Registering a plugin 37==================== 38 39A plugin is loaded from a dynamic library at runtime by the compiler. To 40register a plugin in a library, use ``FrontendPluginRegistry::Add<>``: 41 42.. code-block:: c++ 43 44 static FrontendPluginRegistry::Add<MyPlugin> X("my-plugin-name", "my plugin description"); 45 46Defining pragmas 47================ 48 49Plugins can also define pragmas by declaring a ``PragmaHandler`` and 50registering it using ``PragmaHandlerRegistry::Add<>``: 51 52.. code-block:: c++ 53 54 // Define a pragma handler for #pragma example_pragma 55 class ExamplePragmaHandler : public PragmaHandler { 56 public: 57 ExamplePragmaHandler() : PragmaHandler("example_pragma") { } 58 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer, 59 Token &PragmaTok) { 60 // Handle the pragma 61 } 62 }; 63 64 static PragmaHandlerRegistry::Add<ExamplePragmaHandler> Y("example_pragma","example pragma description"); 65 66Defining attributes 67=================== 68 69Plugins can define attributes by declaring a ``ParsedAttrInfo`` and registering 70it using ``ParsedAttrInfoRegister::Add<>``: 71 72.. code-block:: c++ 73 74 class ExampleAttrInfo : public ParsedAttrInfo { 75 public: 76 ExampleAttrInfo() { 77 Spellings.push_back({ParsedAttr::AS_GNU,"example"}); 78 } 79 AttrHandling handleDeclAttribute(Sema &S, Decl *D, 80 const ParsedAttr &Attr) const override { 81 // Handle the attribute 82 return AttributeApplied; 83 } 84 }; 85 86 static ParsedAttrInfoRegistry::Add<ExampleAttrInfo> Z("example_attr","example attribute description"); 87 88The members of ``ParsedAttrInfo`` that a plugin attribute must define are: 89 90 * ``Spellings``, which must be populated with every `Spelling 91 </doxygen/structclang_1_1ParsedAttrInfo_1_1Spelling.html>`_ of the 92 attribute, each of which consists of an attribute syntax and how the 93 attribute name is spelled for that syntax. If the syntax allows a scope then 94 the spelling must be "scope::attr" if a scope is present or "::attr" if not. 95 * ``handleDeclAttribute``, which is the function that applies the attribute to 96 a declaration. It is responsible for checking that the attribute's arguments 97 are valid, and typically applies the attribute by adding an ``Attr`` to the 98 ``Decl``. It returns either ``AttributeApplied``, to indicate that the 99 attribute was successfully applied, or ``AttributeNotApplied`` if it wasn't. 100 101The members of ``ParsedAttrInfo`` that may need to be defined, depending on the 102attribute, are: 103 104 * ``NumArgs`` and ``OptArgs``, which set the number of required and optional 105 arguments to the attribute. 106 * ``diagAppertainsToDecl``, which checks if the attribute has been used on the 107 right kind of declaration and issues a diagnostic if not. 108 * ``diagLangOpts``, which checks if the attribute is permitted for the current 109 language mode and issues a diagnostic if not. 110 * ``existsInTarget``, which checks if the attribute is permitted for the given 111 target. 112 113To see a working example of an attribute plugin, see `the Attribute.cpp example 114<https://github.com/llvm/llvm-project/blob/main/clang/examples/Attribute/Attribute.cpp>`_. 115 116Putting it all together 117======================= 118 119Let's look at an example plugin that prints top-level function names. This 120example is checked into the clang repository; please take a look at 121the `latest version of PrintFunctionNames.cpp 122<https://github.com/llvm/llvm-project/blob/main/clang/examples/PrintFunctionNames/PrintFunctionNames.cpp>`_. 123 124Running the plugin 125================== 126 127 128Using the cc1 command line 129-------------------------- 130 131To run a plugin, the dynamic library containing the plugin registry must be 132loaded via the `-load` command line option. This will load all plugins 133that are registered, and you can select the plugins to run by specifying the 134`-plugin` option. Additional parameters for the plugins can be passed with 135`-plugin-arg-<plugin-name>`. 136 137Note that those options must reach clang's cc1 process. There are two 138ways to do so: 139 140* Directly call the parsing process by using the `-cc1` option; this 141 has the downside of not configuring the default header search paths, so 142 you'll need to specify the full system path configuration on the command 143 line. 144* Use clang as usual, but prefix all arguments to the cc1 process with 145 `-Xclang`. 146 147For example, to run the ``print-function-names`` plugin over a source file in 148clang, first build the plugin, and then call clang with the plugin from the 149source tree: 150 151.. code-block:: console 152 153 $ export BD=/path/to/build/directory 154 $ (cd $BD && make PrintFunctionNames ) 155 $ clang++ -D_GNU_SOURCE -D_DEBUG -D__STDC_CONSTANT_MACROS \ 156 -D__STDC_FORMAT_MACROS -D__STDC_LIMIT_MACROS -D_GNU_SOURCE \ 157 -I$BD/tools/clang/include -Itools/clang/include -I$BD/include -Iinclude \ 158 tools/clang/tools/clang-check/ClangCheck.cpp -fsyntax-only \ 159 -Xclang -load -Xclang $BD/lib/PrintFunctionNames.so -Xclang \ 160 -plugin -Xclang print-fns 161 162Also see the print-function-name plugin example's 163`README <https://github.com/llvm/llvm-project/blob/main/clang/examples/PrintFunctionNames/README.txt>`_ 164 165 166Using the clang command line 167---------------------------- 168 169Using `-fplugin=plugin` on the clang command line passes the plugin 170through as an argument to `-load` on the cc1 command line. If the plugin 171class implements the ``getActionType`` method then the plugin is run 172automatically. For example, to run the plugin automatically after the main AST 173action (i.e. the same as using `-add-plugin`): 174 175.. code-block:: c++ 176 177 // Automatically run the plugin after the main AST action 178 PluginASTAction::ActionType getActionType() override { 179 return AddAfterMainAction; 180 } 181