1@c Copyright (C) 2009-2020 Free Software Foundation, Inc. 2@c Free Software Foundation, Inc. 3@c This is part of the GCC manual. 4@c For copying conditions, see the file gcc.texi. 5 6@node Plugins 7@chapter Plugins 8@cindex Plugins 9 10GCC plugins are loadable modules that provide extra features to the 11compiler. Like GCC itself they can be distributed in source and 12binary forms. 13 14GCC plugins provide developers with a rich subset of 15the GCC API to allow them to extend GCC as they see fit. 16Whether it is writing an additional optimization pass, 17transforming code, or analyzing information, plugins 18can be quite useful. 19 20@menu 21* Plugins loading:: How can we load plugins. 22* Plugin API:: The APIs for plugins. 23* Plugins pass:: How a plugin interact with the pass manager. 24* Plugins GC:: How a plugin Interact with GCC Garbage Collector. 25* Plugins description:: Giving information about a plugin itself. 26* Plugins attr:: Registering custom attributes or pragmas. 27* Plugins recording:: Recording information about pass execution. 28* Plugins gate:: Controlling which passes are being run. 29* Plugins tracking:: Keeping track of available passes. 30* Plugins building:: How can we build a plugin. 31@end menu 32 33@node Plugins loading 34@section Loading Plugins 35 36Plugins are supported on platforms that support @option{-ldl 37-rdynamic} as well as Windows/MinGW. They are loaded by the compiler 38using @code{dlopen} or equivalent and invoked at pre-determined 39locations in the compilation process. 40 41Plugins are loaded with 42 43@option{-fplugin=/path/to/@var{name}.@var{ext}} @option{-fplugin-arg-@var{name}-@var{key1}[=@var{value1}]} 44 45Where @var{name} is the plugin name and @var{ext} is the platform-specific 46dynamic library extension. It should be @code{dll} on Windows/MinGW, 47@code{dylib} on Darwin/Mac OS X, and @code{so} on all other platforms. 48The plugin arguments are parsed by GCC and passed to respective 49plugins as key-value pairs. Multiple plugins can be invoked by 50specifying multiple @option{-fplugin} arguments. 51 52A plugin can be simply given by its short name (no dots or 53slashes). When simply passing @option{-fplugin=@var{name}}, the plugin is 54loaded from the @file{plugin} directory, so @option{-fplugin=@var{name}} is 55the same as @option{-fplugin=`gcc -print-file-name=plugin`/@var{name}.@var{ext}}, 56using backquote shell syntax to query the @file{plugin} directory. 57 58@node Plugin API 59@section Plugin API 60 61Plugins are activated by the compiler at specific events as defined in 62@file{gcc-plugin.h}. For each event of interest, the plugin should 63call @code{register_callback} specifying the name of the event and 64address of the callback function that will handle that event. 65 66The header @file{gcc-plugin.h} must be the first gcc header to be included. 67 68@subsection Plugin license check 69 70Every plugin should define the global symbol @code{plugin_is_GPL_compatible} 71to assert that it has been licensed under a GPL-compatible license. 72If this symbol does not exist, the compiler will emit a fatal error 73and exit with the error message: 74 75@smallexample 76fatal error: plugin @var{name} is not licensed under a GPL-compatible license 77@var{name}: undefined symbol: plugin_is_GPL_compatible 78compilation terminated 79@end smallexample 80 81The declared type of the symbol should be int, to match a forward declaration 82in @file{gcc-plugin.h} that suppresses C++ mangling. It does not need to be in 83any allocated section, though. The compiler merely asserts that 84the symbol exists in the global scope. Something like this is enough: 85 86@smallexample 87int plugin_is_GPL_compatible; 88@end smallexample 89 90@subsection Plugin initialization 91 92Every plugin should export a function called @code{plugin_init} that 93is called right after the plugin is loaded. This function is 94responsible for registering all the callbacks required by the plugin 95and do any other required initialization. 96 97This function is called from @code{compile_file} right before invoking 98the parser. The arguments to @code{plugin_init} are: 99 100@itemize @bullet 101@item @code{plugin_info}: Plugin invocation information. 102@item @code{version}: GCC version. 103@end itemize 104 105The @code{plugin_info} struct is defined as follows: 106 107@smallexample 108struct plugin_name_args 109@{ 110 char *base_name; /* Short name of the plugin 111 (filename without .so suffix). */ 112 const char *full_name; /* Path to the plugin as specified with 113 -fplugin=. */ 114 int argc; /* Number of arguments specified with 115 -fplugin-arg-.... */ 116 struct plugin_argument *argv; /* Array of ARGC key-value pairs. */ 117 const char *version; /* Version string provided by plugin. */ 118 const char *help; /* Help string provided by plugin. */ 119@} 120@end smallexample 121 122If initialization fails, @code{plugin_init} must return a non-zero 123value. Otherwise, it should return 0. 124 125The version of the GCC compiler loading the plugin is described by the 126following structure: 127 128@smallexample 129struct plugin_gcc_version 130@{ 131 const char *basever; 132 const char *datestamp; 133 const char *devphase; 134 const char *revision; 135 const char *configuration_arguments; 136@}; 137@end smallexample 138 139The function @code{plugin_default_version_check} takes two pointers to 140such structure and compare them field by field. It can be used by the 141plugin's @code{plugin_init} function. 142 143The version of GCC used to compile the plugin can be found in the symbol 144@code{gcc_version} defined in the header @file{plugin-version.h}. The 145recommended version check to perform looks like 146 147@smallexample 148#include "plugin-version.h" 149... 150 151int 152plugin_init (struct plugin_name_args *plugin_info, 153 struct plugin_gcc_version *version) 154@{ 155 if (!plugin_default_version_check (version, &gcc_version)) 156 return 1; 157 158@} 159@end smallexample 160 161but you can also check the individual fields if you want a less strict check. 162 163@subsection Plugin callbacks 164 165Callback functions have the following prototype: 166 167@smallexample 168/* The prototype for a plugin callback function. 169 gcc_data - event-specific data provided by GCC 170 user_data - plugin-specific data provided by the plug-in. */ 171typedef void (*plugin_callback_func)(void *gcc_data, void *user_data); 172@end smallexample 173 174Callbacks can be invoked at the following pre-determined events: 175 176 177@smallexample 178enum plugin_event 179@{ 180 PLUGIN_START_PARSE_FUNCTION, /* Called before parsing the body of a function. */ 181 PLUGIN_FINISH_PARSE_FUNCTION, /* After finishing parsing a function. */ 182 PLUGIN_PASS_MANAGER_SETUP, /* To hook into pass manager. */ 183 PLUGIN_FINISH_TYPE, /* After finishing parsing a type. */ 184 PLUGIN_FINISH_DECL, /* After finishing parsing a declaration. */ 185 PLUGIN_FINISH_UNIT, /* Useful for summary processing. */ 186 PLUGIN_PRE_GENERICIZE, /* Allows to see low level AST in C and C++ frontends. */ 187 PLUGIN_FINISH, /* Called before GCC exits. */ 188 PLUGIN_INFO, /* Information about the plugin. */ 189 PLUGIN_GGC_START, /* Called at start of GCC Garbage Collection. */ 190 PLUGIN_GGC_MARKING, /* Extend the GGC marking. */ 191 PLUGIN_GGC_END, /* Called at end of GGC. */ 192 PLUGIN_REGISTER_GGC_ROOTS, /* Register an extra GGC root table. */ 193 PLUGIN_ATTRIBUTES, /* Called during attribute registration */ 194 PLUGIN_START_UNIT, /* Called before processing a translation unit. */ 195 PLUGIN_PRAGMAS, /* Called during pragma registration. */ 196 /* Called before first pass from all_passes. */ 197 PLUGIN_ALL_PASSES_START, 198 /* Called after last pass from all_passes. */ 199 PLUGIN_ALL_PASSES_END, 200 /* Called before first ipa pass. */ 201 PLUGIN_ALL_IPA_PASSES_START, 202 /* Called after last ipa pass. */ 203 PLUGIN_ALL_IPA_PASSES_END, 204 /* Allows to override pass gate decision for current_pass. */ 205 PLUGIN_OVERRIDE_GATE, 206 /* Called before executing a pass. */ 207 PLUGIN_PASS_EXECUTION, 208 /* Called before executing subpasses of a GIMPLE_PASS in 209 execute_ipa_pass_list. */ 210 PLUGIN_EARLY_GIMPLE_PASSES_START, 211 /* Called after executing subpasses of a GIMPLE_PASS in 212 execute_ipa_pass_list. */ 213 PLUGIN_EARLY_GIMPLE_PASSES_END, 214 /* Called when a pass is first instantiated. */ 215 PLUGIN_NEW_PASS, 216/* Called when a file is #include-d or given via the #line directive. 217 This could happen many times. The event data is the included file path, 218 as a const char* pointer. */ 219 PLUGIN_INCLUDE_FILE, 220 221 PLUGIN_EVENT_FIRST_DYNAMIC /* Dummy event used for indexing callback 222 array. */ 223@}; 224@end smallexample 225 226In addition, plugins can also look up the enumerator of a named event, 227and / or generate new events dynamically, by calling the function 228@code{get_named_event_id}. 229 230To register a callback, the plugin calls @code{register_callback} with 231the arguments: 232 233@itemize 234@item @code{char *name}: Plugin name. 235@item @code{int event}: The event code. 236@item @code{plugin_callback_func callback}: The function that handles @code{event}. 237@item @code{void *user_data}: Pointer to plugin-specific data. 238@end itemize 239 240For the @i{PLUGIN_PASS_MANAGER_SETUP}, @i{PLUGIN_INFO}, and 241@i{PLUGIN_REGISTER_GGC_ROOTS} pseudo-events the @code{callback} should be null, 242and the @code{user_data} is specific. 243 244When the @i{PLUGIN_PRAGMAS} event is triggered (with a null pointer as 245data from GCC), plugins may register their own pragmas. Notice that 246pragmas are not available from @file{lto1}, so plugins used with 247@code{-flto} option to GCC during link-time optimization cannot use 248pragmas and do not even see functions like @code{c_register_pragma} or 249@code{pragma_lex}. 250 251The @i{PLUGIN_INCLUDE_FILE} event, with a @code{const char*} file path as 252GCC data, is triggered for processing of @code{#include} or 253@code{#line} directives. 254 255The @i{PLUGIN_FINISH} event is the last time that plugins can call GCC 256functions, notably emit diagnostics with @code{warning}, @code{error} 257etc. 258 259 260@node Plugins pass 261@section Interacting with the pass manager 262 263There needs to be a way to add/reorder/remove passes dynamically. This 264is useful for both analysis plugins (plugging in after a certain pass 265such as CFG or an IPA pass) and optimization plugins. 266 267Basic support for inserting new passes or replacing existing passes is 268provided. A plugin registers a new pass with GCC by calling 269@code{register_callback} with the @code{PLUGIN_PASS_MANAGER_SETUP} 270event and a pointer to a @code{struct register_pass_info} object defined as follows 271 272@smallexample 273enum pass_positioning_ops 274@{ 275 PASS_POS_INSERT_AFTER, // Insert after the reference pass. 276 PASS_POS_INSERT_BEFORE, // Insert before the reference pass. 277 PASS_POS_REPLACE // Replace the reference pass. 278@}; 279 280struct register_pass_info 281@{ 282 struct opt_pass *pass; /* New pass provided by the plugin. */ 283 const char *reference_pass_name; /* Name of the reference pass for hooking 284 up the new pass. */ 285 int ref_pass_instance_number; /* Insert the pass at the specified 286 instance number of the reference pass. */ 287 /* Do it for every instance if it is 0. */ 288 enum pass_positioning_ops pos_op; /* how to insert the new pass. */ 289@}; 290 291 292/* Sample plugin code that registers a new pass. */ 293int 294plugin_init (struct plugin_name_args *plugin_info, 295 struct plugin_gcc_version *version) 296@{ 297 struct register_pass_info pass_info; 298 299 ... 300 301 /* Code to fill in the pass_info object with new pass information. */ 302 303 ... 304 305 /* Register the new pass. */ 306 register_callback (plugin_info->base_name, PLUGIN_PASS_MANAGER_SETUP, NULL, &pass_info); 307 308 ... 309@} 310@end smallexample 311 312 313@node Plugins GC 314@section Interacting with the GCC Garbage Collector 315 316Some plugins may want to be informed when GGC (the GCC Garbage 317Collector) is running. They can register callbacks for the 318@code{PLUGIN_GGC_START} and @code{PLUGIN_GGC_END} events (for which 319the callback is called with a null @code{gcc_data}) to be notified of 320the start or end of the GCC garbage collection. 321 322Some plugins may need to have GGC mark additional data. This can be 323done by registering a callback (called with a null @code{gcc_data}) 324for the @code{PLUGIN_GGC_MARKING} event. Such callbacks can call the 325@code{ggc_set_mark} routine, preferably through the @code{ggc_mark} macro 326(and conversely, these routines should usually not be used in plugins 327outside of the @code{PLUGIN_GGC_MARKING} event). Plugins that wish to hold 328weak references to gc data may also use this event to drop weak references when 329the object is about to be collected. The @code{ggc_marked_p} function can be 330used to tell if an object is marked, or is about to be collected. The 331@code{gt_clear_cache} overloads which some types define may also be of use in 332managing weak references. 333 334Some plugins may need to add extra GGC root tables, e.g.@: to handle their own 335@code{GTY}-ed data. This can be done with the @code{PLUGIN_REGISTER_GGC_ROOTS} 336pseudo-event with a null callback and the extra root table (of type @code{struct 337ggc_root_tab*}) as @code{user_data}. Running the 338 @code{gengtype -p @var{source-dir} @var{file-list} @var{plugin*.c} ...} 339utility generates these extra root tables. 340 341You should understand the details of memory management inside GCC 342before using @code{PLUGIN_GGC_MARKING} or @code{PLUGIN_REGISTER_GGC_ROOTS}. 343 344 345@node Plugins description 346@section Giving information about a plugin 347 348A plugin should give some information to the user about itself. This 349uses the following structure: 350 351@smallexample 352struct plugin_info 353@{ 354 const char *version; 355 const char *help; 356@}; 357@end smallexample 358 359Such a structure is passed as the @code{user_data} by the plugin's 360init routine using @code{register_callback} with the 361@code{PLUGIN_INFO} pseudo-event and a null callback. 362 363@node Plugins attr 364@section Registering custom attributes or pragmas 365 366For analysis (or other) purposes it is useful to be able to add custom 367attributes or pragmas. 368 369The @code{PLUGIN_ATTRIBUTES} callback is called during attribute 370registration. Use the @code{register_attribute} function to register 371custom attributes. 372 373@smallexample 374/* Attribute handler callback */ 375static tree 376handle_user_attribute (tree *node, tree name, tree args, 377 int flags, bool *no_add_attrs) 378@{ 379 return NULL_TREE; 380@} 381 382/* Attribute definition */ 383static struct attribute_spec user_attr = 384 @{ "user", 1, 1, false, false, false, false, handle_user_attribute, NULL @}; 385 386/* Plugin callback called during attribute registration. 387Registered with register_callback (plugin_name, PLUGIN_ATTRIBUTES, register_attributes, NULL) 388*/ 389static void 390register_attributes (void *event_data, void *data) 391@{ 392 warning (0, G_("Callback to register attributes")); 393 register_attribute (&user_attr); 394@} 395 396@end smallexample 397 398 399The @i{PLUGIN_PRAGMAS} callback is called once during pragmas 400registration. Use the @code{c_register_pragma}, 401@code{c_register_pragma_with_data}, 402@code{c_register_pragma_with_expansion}, 403@code{c_register_pragma_with_expansion_and_data} functions to register 404custom pragmas and their handlers (which often want to call 405@code{pragma_lex}) from @file{c-family/c-pragma.h}. 406 407@smallexample 408/* Plugin callback called during pragmas registration. Registered with 409 register_callback (plugin_name, PLUGIN_PRAGMAS, 410 register_my_pragma, NULL); 411*/ 412static void 413register_my_pragma (void *event_data, void *data) 414@{ 415 warning (0, G_("Callback to register pragmas")); 416 c_register_pragma ("GCCPLUGIN", "sayhello", handle_pragma_sayhello); 417@} 418@end smallexample 419 420It is suggested to pass @code{"GCCPLUGIN"} (or a short name identifying 421your plugin) as the ``space'' argument of your pragma. 422 423Pragmas registered with @code{c_register_pragma_with_expansion} or 424@code{c_register_pragma_with_expansion_and_data} support 425preprocessor expansions. For example: 426 427@smallexample 428#define NUMBER 10 429#pragma GCCPLUGIN foothreshold (NUMBER) 430@end smallexample 431 432@node Plugins recording 433@section Recording information about pass execution 434 435The event PLUGIN_PASS_EXECUTION passes the pointer to the executed pass 436(the same as current_pass) as @code{gcc_data} to the callback. You can also 437inspect cfun to find out about which function this pass is executed for. 438Note that this event will only be invoked if the gate check (if 439applicable, modified by PLUGIN_OVERRIDE_GATE) succeeds. 440You can use other hooks, like @code{PLUGIN_ALL_PASSES_START}, 441@code{PLUGIN_ALL_PASSES_END}, @code{PLUGIN_ALL_IPA_PASSES_START}, 442@code{PLUGIN_ALL_IPA_PASSES_END}, @code{PLUGIN_EARLY_GIMPLE_PASSES_START}, 443and/or @code{PLUGIN_EARLY_GIMPLE_PASSES_END} to manipulate global state 444in your plugin(s) in order to get context for the pass execution. 445 446 447@node Plugins gate 448@section Controlling which passes are being run 449 450After the original gate function for a pass is called, its result 451- the gate status - is stored as an integer. 452Then the event @code{PLUGIN_OVERRIDE_GATE} is invoked, with a pointer 453to the gate status in the @code{gcc_data} parameter to the callback function. 454A nonzero value of the gate status means that the pass is to be executed. 455You can both read and write the gate status via the passed pointer. 456 457 458@node Plugins tracking 459@section Keeping track of available passes 460 461When your plugin is loaded, you can inspect the various 462pass lists to determine what passes are available. However, other 463plugins might add new passes. Also, future changes to GCC might cause 464generic passes to be added after plugin loading. 465When a pass is first added to one of the pass lists, the event 466@code{PLUGIN_NEW_PASS} is invoked, with the callback parameter 467@code{gcc_data} pointing to the new pass. 468 469 470@node Plugins building 471@section Building GCC plugins 472 473If plugins are enabled, GCC installs the headers needed to build a 474plugin (somewhere in the installation tree, e.g.@: under 475@file{/usr/local}). In particular a @file{plugin/include} directory 476is installed, containing all the header files needed to build plugins. 477 478On most systems, you can query this @code{plugin} directory by 479invoking @command{gcc -print-file-name=plugin} (replace if needed 480@command{gcc} with the appropriate program path). 481 482Inside plugins, this @code{plugin} directory name can be queried by 483calling @code{default_plugin_dir_name ()}. 484 485Plugins may know, when they are compiled, the GCC version for which 486@file{plugin-version.h} is provided. The constant macros 487@code{GCCPLUGIN_VERSION_MAJOR}, @code{GCCPLUGIN_VERSION_MINOR}, 488@code{GCCPLUGIN_VERSION_PATCHLEVEL}, @code{GCCPLUGIN_VERSION} are 489integer numbers, so a plugin could ensure it is built for GCC 4.7 with 490@smallexample 491#if GCCPLUGIN_VERSION != 4007 492#error this GCC plugin is for GCC 4.7 493#endif 494@end smallexample 495 496The following GNU Makefile excerpt shows how to build a simple plugin: 497 498@smallexample 499HOST_GCC=g++ 500TARGET_GCC=gcc 501PLUGIN_SOURCE_FILES= plugin1.c plugin2.cc 502GCCPLUGINS_DIR:= $(shell $(TARGET_GCC) -print-file-name=plugin) 503CXXFLAGS+= -I$(GCCPLUGINS_DIR)/include -fPIC -fno-rtti -O2 504 505plugin.so: $(PLUGIN_SOURCE_FILES) 506 $(HOST_GCC) -shared $(CXXFLAGS) $^ -o $@@ 507@end smallexample 508 509A single source file plugin may be built with @code{g++ -I`gcc 510-print-file-name=plugin`/include -fPIC -shared -fno-rtti -O2 plugin.c -o 511plugin.so}, using backquote shell syntax to query the @file{plugin} 512directory. 513 514Plugin support on Windows/MinGW has a number of limitations and 515additional requirements. When building a plugin on Windows we have to 516link an import library for the corresponding backend executable, for 517example, @file{cc1.exe}, @file{cc1plus.exe}, etc., in order to gain 518access to the symbols provided by GCC. This means that on Windows a 519plugin is language-specific, for example, for C, C++, etc. If you wish 520to use your plugin with multiple languages, then you will need to 521build multiple plugin libraries and either instruct your users on how 522to load the correct version or provide a compiler wrapper that does 523this automatically. 524 525Additionally, on Windows the plugin library has to export the 526@code{plugin_is_GPL_compatible} and @code{plugin_init} symbols. If you 527do not wish to modify the source code of your plugin, then you can use 528the @option{-Wl,--export-all-symbols} option or provide a suitable DEF 529file. Alternatively, you can export just these two symbols by decorating 530them with @code{__declspec(dllexport)}, for example: 531 532@smallexample 533#ifdef _WIN32 534__declspec(dllexport) 535#endif 536int plugin_is_GPL_compatible; 537 538#ifdef _WIN32 539__declspec(dllexport) 540#endif 541int plugin_init (plugin_name_args *, plugin_gcc_version *) 542@end smallexample 543 544The import libraries are installed into the @code{plugin} directory 545and their names are derived by appending the @code{.a} extension to 546the backend executable names, for example, @file{cc1.exe.a}, 547@file{cc1plus.exe.a}, etc. The following command line shows how to 548build the single source file plugin on Windows to be used with the C++ 549compiler: 550 551@smallexample 552g++ -I`gcc -print-file-name=plugin`/include -shared -Wl,--export-all-symbols \ 553-o plugin.dll plugin.c `gcc -print-file-name=plugin`/cc1plus.exe.a 554@end smallexample 555 556When a plugin needs to use @command{gengtype}, be sure that both 557@file{gengtype} and @file{gtype.state} have the same version as the 558GCC for which the plugin is built. 559