224 lines · plain
1=============2Clang Plugins3=============4 5Clang Plugins make it possible to run extra user defined actions during a6compilation. This document will provide a basic walkthrough of how to write and7run a Clang Plugin.8 9Introduction10============11 12Clang Plugins run FrontendActions over code. See the :doc:`FrontendAction13tutorial <RAVFrontendAction>` on how to write a ``FrontendAction`` using the14``RecursiveASTVisitor``. In this tutorial, we'll demonstrate how to write a15simple clang plugin.16 17Writing a ``PluginASTAction``18=============================19 20The main difference from writing normal ``FrontendActions`` is that you can21handle plugin command line options. The ``PluginASTAction`` base class declares22a ``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 plugin37====================38 39A plugin is loaded from a dynamic library at runtime by the compiler. To40register 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 pragmas47================48 49Plugins can also define pragmas by declaring a ``PragmaHandler`` and50registering it using ``PragmaHandlerRegistry::Add<>``:51 52.. code-block:: c++53 54 // Define a pragma handler for #pragma example_pragma55 class ExamplePragmaHandler : public PragmaHandler {56 public:57 ExamplePragmaHandler() : PragmaHandler("example_pragma") { }58 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,59 Token &PragmaTok) {60 // Handle the pragma61 }62 };63 64 static PragmaHandlerRegistry::Add<ExamplePragmaHandler> Y("example_pragma","example pragma description");65 66Defining attributes67===================68 69Plugins can define attributes by declaring a ``ParsedAttrInfo`` and registering70it 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 attribute82 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 `Spelling91 </doxygen/structclang_1_1ParsedAttrInfo_1_1Spelling.html>`_ of the92 attribute, each of which consists of an attribute syntax and how the93 attribute name is spelled for that syntax. If the syntax allows a scope then94 the spelling must be "scope::attr" if a scope is present or "::attr" if not.95 96The members of ``ParsedAttrInfo`` that may need to be defined, depending on the97attribute, are:98 99 * ``NumArgs`` and ``OptArgs``, which set the number of required and optional100 arguments to the attribute.101 * ``diagAppertainsToDecl``, which checks if the attribute has been used on the102 right kind of declaration and issues a diagnostic if not.103 * ``handleDeclAttribute``, which is the function that applies the attribute to104 a declaration. It is responsible for checking that the attribute's arguments105 are valid, and typically applies the attribute by adding an ``Attr`` to the106 ``Decl``. It returns either ``AttributeApplied``, to indicate that the107 attribute was successfully applied, or ``AttributeNotApplied`` if it wasn't.108 * ``diagAppertainsToStmt``, which checks if the attribute has been used on the109 right kind of statement and issues a diagnostic if not.110 * ``handleStmtAttribute``, which is the function that applies the attribute to111 a statement. It is responsible for checking that the attribute's arguments112 are valid, and typically applies the attribute by adding an ``Attr`` to the113 ``Stmt``. It returns either ``AttributeApplied``, to indicate that the114 attribute was successfully applied, or ``AttributeNotApplied`` if it wasn't.115 * ``diagLangOpts``, which checks if the attribute is permitted for the current116 language mode and issues a diagnostic if not.117 * ``existsInTarget``, which checks if the attribute is permitted for the given118 target.119 120To see a working example of an attribute plugin, see `the Attribute.cpp example121<https://github.com/llvm/llvm-project/blob/main/clang/examples/Attribute/Attribute.cpp>`_.122 123Putting it all together124=======================125 126Let's look at an example plugin that prints top-level function names. This127example is checked into the clang repository; please take a look at128the `latest version of PrintFunctionNames.cpp129<https://github.com/llvm/llvm-project/blob/main/clang/examples/PrintFunctionNames/PrintFunctionNames.cpp>`_.130 131Running the plugin132==================133 134 135Using the compiler driver136--------------------------137 138The Clang driver accepts the `-fplugin` option to load a plugin.139Clang plugins can receive arguments from the compiler driver command140line via the `fplugin-arg-<plugin name>-<argument>` option. Using this141method, the plugin name cannot contain dashes itself, but the argument142passed to the plugin can.143 144 145.. code-block:: console146 147 $ export BD=/path/to/build/directory148 $ make -C $BD CallSuperAttr149 $ clang++ -fplugin=$BD/lib/CallSuperAttr.so \150 -fplugin-arg-call_super_plugin-help \151 test.cpp152 153If your plugin name contains dashes, either rename the plugin or use the154cc1 command line options listed below.155 156 157Using the cc1 command line158--------------------------159 160To run a plugin, the dynamic library containing the plugin registry must be161loaded via the `-load` command line option. This will load all plugins162that are registered, and you can select the plugins to run by specifying the163`-plugin` option. Additional parameters for the plugins can be passed with164`-plugin-arg-<plugin-name>`.165 166Note that those options must reach clang's cc1 process. There are two167ways to do so:168 169* Directly call the parsing process by using the `-cc1` option; this170 has the downside of not configuring the default header search paths, so171 you'll need to specify the full system path configuration on the command172 line.173* Use clang as usual, but prefix all arguments to the cc1 process with174 `-Xclang`.175 176For example, to run the ``print-function-names`` plugin over a source file in177clang, first build the plugin, and then call clang with the plugin from the178source tree:179 180.. code-block:: console181 182 $ export BD=/path/to/build/directory183 $ (cd $BD && make PrintFunctionNames )184 $ clang++ -D_GNU_SOURCE -D_DEBUG -D__STDC_CONSTANT_MACROS \185 -D__STDC_FORMAT_MACROS -D__STDC_LIMIT_MACROS -D_GNU_SOURCE \186 -I$BD/tools/clang/include -Itools/clang/include -I$BD/include -Iinclude \187 tools/clang/tools/clang-check/ClangCheck.cpp -fsyntax-only \188 -Xclang -load -Xclang $BD/lib/PrintFunctionNames.so -Xclang \189 -plugin -Xclang print-fns190 191Also see the print-function-name plugin example's192`README <https://github.com/llvm/llvm-project/blob/main/clang/examples/PrintFunctionNames/README.txt>`_193 194 195Using the clang command line196----------------------------197 198Using `-fplugin=plugin` on the clang command line passes the plugin199through as an argument to `-load` on the cc1 command line. If the plugin200class implements the ``getActionType`` method then the plugin is run201automatically. For example, to run the plugin automatically after the main AST202action (i.e. the same as using `-add-plugin`):203 204.. code-block:: c++205 206 // Automatically run the plugin after the main AST action207 PluginASTAction::ActionType getActionType() override {208 return AddAfterMainAction;209 }210 211Interaction with ``-clear-ast-before-backend``212----------------------------------------------213 214To reduce peak memory usage of the compiler, plugins are recommended to run215*before* the main action, which is usually code generation. This is because216having any plugins that run after the codegen action automatically turns off217``-clear-ast-before-backend``. ``-clear-ast-before-backend`` reduces peak218memory by clearing the Clang AST after generating IR and before running IR219optimizations. Use ``CmdlineBeforeMainAction`` or ``AddBeforeMainAction`` as220``getActionType`` to run plugins while still benefitting from221``-clear-ast-before-backend``. Plugins must make sure not to modify the AST,222otherwise they should run after the main action.223 224