1<!--===- docs/FlangDriver.md
2
3   Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4   See https://llvm.org/LICENSE.txt for license information.
5   SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
7-->
8
9# Flang drivers
10
11```eval_rst
12.. contents::
13   :local:
14```
15
16
17> **_NOTE:_** This document assumes that Flang's drivers can already generate code and
18> produce executables. However, this is still work-in-progress. By making this
19> assumption, we are able to prepare this document ahead-of-time and to provide
20> an overview of the design that we are working towards.
21
22There are two main drivers in Flang:
23* the compiler driver, `flang-new`
24* the frontend driver, `flang-new -fc1`
25
26> **_NOTE:_** The diagrams in this document refer to `flang` as opposed to
27> `flang-new`. This is because the diagrams reflect the final design that we
28> are still working towards. See the note on [the flang script](https://github.com/llvm/llvm-project/blob/main/flang/docs/FlangDriver.md#the-flang-script)
29> below for more context.
30
31The **compiler driver** will allow you to control all compilation phases (e.g.
32preprocessing, semantic checks, code-generation, code-optimisation, lowering
33and linking). For frontend specific tasks, the compiler driver creates a
34Fortran compilation job and delegates it to `flang-new -fc1`, the frontend
35driver. For linking, it creates a linker job and calls an external linker (e.g.
36LLVM's [`lld`](https://lld.llvm.org/)). It can also call other tools such as
37external assemblers (e.g. [`as`](https://www.gnu.org/software/binutils/)). In
38Clang, the compiler driver can also link the generated binaries with LLVM's
39static analysis/sanitizer libraries (e.g.
40[MemorySanitizer](https://clang.llvm.org/docs/MemorySanitizer.html)). This is
41not yet available in Flang, but will be relatively easy to support once such
42libraries become available. Flang's compiler driver is intended for Flang's
43end-users - its interface needs to remain stable. Otherwise, Flang's users will
44have to adjust their build scripts every time a compiler flag is changed.
45
46| ![Compiler Driver](compiler_driver.png) |
47|:--:|
48| *Flang’s compiler driver and the **tools** that it runs* |
49
50The **frontend driver** glues together and drives all of the Flang's frontend
51libraries. As such, it provides an easy-to-use and intuitive interface to the
52frontend. It uses MLIR and LLVM for code-generation and can be viewed as a
53driver for Flang, LLVM and MLIR libraries. Contrary to the compiler driver, it
54is not capable of calling any external tools (including linkers).  It is aware
55of all the frontend internals that are "hidden" from the compiler driver. It
56accepts many frontend-specific options not available in `flang-new` and as such
57it provides a finer control over the frontend. Note that this tool is mostly
58intended for Flang developers. In particular, there are no guarantees about the
59stability of its interface and compiler developers can use it to experiment
60with new flags.
61
62| ![Frontend Driver](frontend_driver.png) |
63|:-:|
64| *Flang's frontend driver and the **libraries** that it drives* |
65
66Note that similarly to `-Xclang` in `clang`, you can use `-Xflang` to forward a
67frontend specific flag from the _compiler_ directly to the _frontend_ driver,
68e.g.:
69
70```lang=bash
71flang-new -Xflang -fdebug-dump-parse-tree input.f95
72```
73
74In the invocation above, `-fdebug-dump-parse-tree` is forwarded to `flang-new
75-fc1`. Without the forwarding flag, `-Xflang`, you would see the following
76warning:
77
78```lang=bash
79flang-new: warning: argument unused during compilation:
80```
81
82As `-fdebug-dump-parse-tree` is only supported by `flang-new -fc1`, `flang-new`
83will ignore it when used without `Xflang`.
84
85## Why Do We Need Two Drivers?
86As hinted above, `flang-new` and `flang-new -fc1` are two separate tools. The
87fact that these tools are accessed through one binary, `flang-new`, is just an
88implementation detail. Each tool has a separate list of options, albeit defined
89in the same file: `clang/include/clang/Driver/Options.td`.
90
91The separation helps us split various tasks and allows us to implement more
92specialised tools. In particular, `flang-new` is not aware of various
93compilation phases within the frontend (e.g. scanning, parsing or semantic
94checks). It does not have to be. Conversely, the frontend driver, `flang-new
95-fc1`, needs not to be concerned with linkers or other external tools like
96assemblers. Nor does it need to know where to look for various systems
97libraries, which is usually OS and platform specific.
98
99One helpful way of differentiating these tools is to keep in mind that:
100
101* the compiler driver is an end-user tool
102* frontend driver is a compiler developer tool with many additional options,
103
104Also, Since the compiler driver can call external tools, e.g. linkers, it can
105be used to generate **executables**. The frontend driver cannot call external
106tools and hence can only generate **object files**. A similar model is
107implemented in Clang (`clang` vs `clang -cc1` vs `clang -cc1as`), which is
108based on the [architecture of
109GCC](https://en.wikibooks.org/wiki/GNU_C_Compiler_Internals/GNU_C_Compiler_Architecture).
110In fact, Flang needs to adhere to this model in order to be able to re-use
111Clang's driver library. If you are more familiar with the [architecture of
112GFortran](https://gcc.gnu.org/onlinedocs/gcc-4.7.4/gfortran/About-GNU-Fortran.html)
113than Clang, then `flang-new` corresponds to `gfortran` and `flang-new -fc1` to
114`f951`.
115
116## Compiler Driver
117The main entry point for Flang's compiler driver is implemented in
118`flang/tools/flang-driver/driver.cpp`.  Flang's compiler driver is implemented
119in terms of Clang's driver library, `clangDriver`. This approach allows us to:
120* benefit from Clang's support for various targets, platforms and operating systems
121* leverage Clang's ability to drive various backends available in LLVM, as well
122  as linkers and assemblers.
123One implication of this dependency on Clang is that all of Flang's compiler
124options are defined alongside Clang's options in
125`clang/include/clang/Driver/Options.td`. For options that are common for both
126Flang and Clang, the corresponding definitions are shared.
127
128Internally, a `clangDriver` based compiler driver works by creating actions
129that correspond to various compilation phases, e.g. `PreprocessJobClass`,
130`CompileJobClass`, `BackendJobClass` or `LinkJobClass` from the
131`clang::driver::Action::ActionClass` enum. There are also other, more
132specialised actions, e.g. `MigrateJobClass` or `InputClass`, that do not map
133directly to common compilation steps. The actions to run are determined from
134the supplied compiler flags, e.g.
135
136* `-E` for `PreprocessJobClass`,
137* `-c` for `CompileJobClass`.
138
139In most cases, the driver creates a chain of actions/jobs/phases where the
140output from one action is the input for the subsequent one. You can use the
141`-ccc-print-phases` flag to see the sequence of actions that the driver will
142create for your compiler invocation:
143```bash
144flang-new -ccc-print-phases -E file.f
145+- 0: input, "file.f", f95-cpp-input
1461: preprocessor, {0}, f95
147```
148As you can see, for `-E` the driver creates only two jobs and stops immediately
149after preprocessing. The first job simply prepares the input. For `-c`, the
150pipeline of the created jobs is more complex:
151```bash
152flang-new -ccc-print-phases -c file.f
153         +- 0: input, "file.f", f95-cpp-input
154      +- 1: preprocessor, {0}, f95
155   +- 2: compiler, {1}, ir
156+- 3: backend, {2}, assembler
1574: assembler, {3}, object
158```
159Note that currently Flang does not support code-generation and `flang-new` will
160fail during the second step above with the following error:
161```bash
162error: code-generation is not available yet
163```
164The other phases are printed nonetheless when using `-ccc-print-phases`, as
165that reflects what `clangDriver`, the library, will try to create and run.
166
167For actions specific to the frontend (e.g. preprocessing or code generation), a
168command to call the frontend driver is generated (more specifically, an
169instance of `clang::driver::Command`). Every command is bound to an instance of
170`clang::driver::Tool`. For Flang we introduced a specialisation of this class:
171`clang::driver::Flang`. This class implements the logic to either translate or
172forward compiler options to the frontend driver, `flang-new -fc1`.
173
174You can read more on the design of `clangDriver` in Clang's [Driver Design &
175Internals](https://clang.llvm.org/docs/DriverInternals.html).
176
177## Frontend Driver
178Flang's frontend driver is the main interface between compiler developers and
179the Flang frontend. The high-level design is similar to Clang's frontend
180driver, `clang -cc1` and consists of the following classes:
181* `CompilerInstance`, which is a helper class that encapsulates and manages
182  various objects that are always required by the frontend (e.g. `AllSources`,
183  `AllCookedSources, `Parsing`, `CompilerInvocation`, etc.). In most cases
184  `CompilerInstance` owns these objects, but it also can share them with its
185  clients when required. It also implements utility methods to construct and
186  manipulate them.
187* `CompilerInvocation` encapsulates the configuration of the current
188  invocation of the compiler as derived from the command-line options and the
189  input files (in particular, file extensions). Among other things, it holds an
190  instance of `FrontendOptions`. Like `CompilerInstance`, it owns the objects
191  that it manages. It can share them with its clients that want to access them
192  even after the corresponding `CompilerInvocation` has been destructed.
193* `FrontendOptions` holds options that control the behaviour of the frontend,
194  as well as e.g. the list of the input files. These options come either
195  directly from the users (through command-line flags) or are derived from
196  e.g. the host system configuration.
197* `FrontendAction` and `FrontendActions` (the former being the base class for
198  the latter) implement the actual actions to perform by the frontend. Usually
199  there is one specialisation of `FrontendActions` for every compiler action flag
200  (e.g. `-E`, `-fdebug-unparse`). These classes also contain various hooks that
201  allow you to e.g. fine-tune the configuration of the frontend based on the
202  input.
203
204This list is not exhaustive and only covers the main classes that implement the
205driver. The main entry point for the frontend driver, `fc1_main`, is
206implemented in `flang/tools/flang-driver/driver.cpp`. It can be accessed by
207invoking the compiler driver, `flang-new`, with the `-fc1` flag.
208
209The frontend driver will only run one action at a time. If you specify multiple
210action flags, only the last one will be taken into account. The default action
211is `ParseSyntaxOnlyAction`, which corresponds to `-fsyntax-only`. In other
212words, `flang-new -fc1 <input-file>` is equivalent to `flang-new -fc1 -fsyntax-only
213<input-file>`.
214
215## The `flang` script
216The `flang` wrapper script for `flang-new` was introduced as a development tool
217and to facilitate testing. While code-generation is not available in Flang, you
218can use it as a drop-in replacement for other Fortran compilers in your build
219scripts.
220
221The `flang` wrapper script will:
222* use `flang-new` to unparse the input source file (i.e. it will run `flang-new
223  -fc1 -fdebug-unparse <input-file>`), and then
224* call a host Fortran compiler, e.g. `gfortran`, to compile the unparsed file.
225
226Here's a basic breakdown of what happens inside `flang` when you run `flang
227file.f90`:
228```bash
229flang-new -fc1 -fdebug-unparse file.f90 -o file-unparsed.f90
230gfortran file-unparsed.f90
231```
232This is a simplified version for illustration purposes only. In practice,
233`flang` adds a few more frontend options and it also supports various other use
234cases (e.g. compiling C files, linking existing object files). `gfortran` is
235the default host compiler used by `flang`. You can change it by setting the
236`FLANG_FC` environment variable.
237
238Our intention is to replace `flang` with `flang-new`. Please consider `flang`
239as a temporary substitute for Flang's compiler driver while the actual driver
240is in development.
241
242## Adding new Compiler Options
243Adding a new compiler option in Flang consists of two steps:
244* define the new option in a dedicated TableGen file,
245* parse and implement the option in the relevant drivers that support it.
246
247### Option Definition
248All of Flang's compiler and frontend driver options are defined in
249`clang/include/clang/Driver/Options.td` in Clang. When adding a new option to
250Flang, you will either:
251  * extend the existing definition for an option that is already available
252    in one of Clang's drivers (e.g.  `clang`), but not yet available in Flang, or
253  * add a completely new definition if the option that you are adding has not
254    been defined yet.
255
256There are many predefined TableGen classes and records that you can use to fine
257tune your new option. The list of available configurations can be overwhelming
258at times. Sometimes the easiest approach is to find an existing option that has
259similar semantics to your new option and start by copying that.
260
261For every new option, you will also have to define the visibility of the new
262option. This is controlled through the `Flags` field. You can use the following
263Flang specific option flags to control this:
264  * `FlangOption` - this option will be available in the `flang-new` compiler driver,
265  * `FC1Option` - this option will be available in the `flang-new -fc1` frontend driver,
266  * `FlangOnlyOption` - this option will not be visible in Clang drivers.
267
268Please make sure that options that you add are only visible in drivers that can
269support it. For example, options that only make sense for Fortran input files
270(e.g. `-ffree-form`) should not be visible in Clang and be marked as
271`FlangOnlyOption`.
272
273When deciding what `OptionGroup` to use when defining a new option in the
274`Options.td` file, many new options fall into one of the following two
275categories:
276  * `Action_Group` - options that define an action to run (e.g.
277    `-fsyntax-only`, `-E`)
278  * `f_Group` - target independent compiler flags (e.g. `-ffixed-form`,
279    `-fopenmp`)
280There are also other groups and occasionally you will use them instead of the
281groups listed above.
282
283### Option Implementation
284First, every option needs to be parsed. Flang compiler options are parsed in
285two different places, depending on which driver they belong to:
286
287* frontend driver: `flang/lib/Frontend/CompilerInvocation.cpp`,
288* compiler driver: `clang/lib/Driver/ToolChains/Flang.cpp`.
289
290The parsing will depend on the semantics encoded in the TableGen definition.
291
292When adding a compiler driver option (i.e. an option that contains
293`FlangOption` among its `Flags`) that you also intend to be understood by the
294frontend, make sure that it is either forwarded to `flang-new -fc1` or translated
295into some other option that is accepted by the frontend driver. In the case of
296options that contain both `FlangOption` and `FC1Option` among its flags, we
297usually just forward from `flang-new` to `flang-new -fc1`. This is then tested in
298`flang/test/Driver/frontend-forward.F90`.
299
300What follows is usually very dependant on the meaning of the corresponding
301option. In general, regular compiler flags (e.g. `-ffree-form`) are mapped to
302some state within the driver. A lot of this state is stored within an instance
303of `FrontendOptions`, but there are other more specialised classes too. Action
304flags (e.g. `-fsyntax-only`) are usually more complex overall, but also more
305structured in terms of the implementation.
306
307### Action Options
308For options that correspond to an action (i.e. marked as `Action_Group`), you
309will have to define a dedicated instance of `FrontendActions` in
310`flang/include/flang/Frontend/FrontendOptions.h`. For example, for
311`-fsyntax-only` we defined:
312```cpp
313class ParseSyntaxOnlyAction : public PrescanAndSemaAction {
314  void ExecuteAction() override;
315};
316```
317Command line options are mapped to frontend actions through the
318`Fortran::frontend::ActionKind` enum.  For every new action option that you
319add, you will have to add a dedicated entry in that enum (e.g.
320`ParseSyntaxOnly` for `-fsyntax-only`) and a corresponding `case` in
321`ParseFrontendArgs` function in the `CompilerInvocation.cpp` file, e.g.:
322```cpp
323    case clang::driver::options::OPT_fsyntax_only:
324      opts.programAction = ParseSyntaxOnly;
325      break;
326```
327Note that this simply sets the program/frontend action within the frontend
328driver. You still have make sure that the corresponding frontend action class
329is instantiated when your new action option is used. The relevant `switch`
330statement is implemented in `Fortran::frontend::CreatedFrontendBaseAction` in
331the `ExecuteCompilerInvocation.cpp` file. Here's an example for
332`-fsyntax-only`:
333```cpp
334  case ParseSyntaxOnly:
335    return std::make_unique<ParseSyntaxOnlyAction>();
336```
337At this point you should be able to trigger that frontend action that you have
338just added using your new frontend option.
339
340# Testing
341In LIT, we define two variables that you can use to invoke Flang's drivers:
342* `%flang` is expanded as `flang-new` (i.e. the compiler driver)
343* `%flang_fc1` is expanded as `flang-new -fc1` (i.e. the frontend driver)
344
345For most regression tests for the frontend, you will want to use `%flang_fc1`.
346In some cases, the observable behaviour will be identical regardless of whether
347`%flang` or `%flang_fc1` is used. However, when you are using `%flang` instead
348of `%flang_fc1`, the compiler driver will add extra flags to the frontend
349driver invocation (i.e. `flang-new -fc1 -<extra-flags>`). In some cases that might
350be exactly what you want to test.  In fact, you can check these additional
351flags by using the `-###` compiler driver command line option.
352
353Lastly, you can use `! REQUIRES: <feature>` for tests that will only work when
354`<feature>` is available. For example, you can use`! REQUIRES: shell` to mark a
355test as only available on Unix-like systems (i.e. systems that contain a Unix
356shell). In practice this means that the corresponding test is skipped on
357Windows.
358
359# Frontend Driver Plugins
360Plugins are an extension to the frontend driver that make it possible to run
361extra user defined frontend actions, in the form of a specialization of a
362`PluginParseTreeAction`. These actions are run during compilation, after
363semantic checks. Similarly to Clang, Flang leverages `LoadLibraryPermanently`
364from LLVM's `llvm::sys::DynamicLibrary` to load dynamic objects that implement
365plugins. The process for using plugins includes:
366* [Creating a plugin](#creating-a-plugin)
367* [Loading and running a plugin](#loading-and-running-a-plugin)
368
369Flang plugins are limited to `flang-new -fc1` and are currently only available /
370been tested on Linux.
371
372## Creating a Plugin
373There are three parts required for plugins to work:
3741. [`PluginParseTreeAction` subclass](#a-pluginparsetreeaction-subclass)
3751. [Implementation of `ExecuteAction`](#implementation-of-executeaction)
3761. [Plugin registration](#plugin-registration)
377
378There is an example plugin located in `flang/example/PrintFlangFunctionNames`
379that demonstrates these points by using the `ParseTree` API to print out
380function and subroutine names declared in the input file.
381
382### A `PluginParseTreeAction` Subclass
383This subclass will wrap everything together and represent the `FrontendAction`
384corresponding to your plugin. It will need to inherit from
385`PluginParseTreeAction` (defined in `flang/include/flang/FrontendActions.h`), in
386order to have access to the parse tree post semantic checks, and also so that it
387can be registered, e.g.
388```cpp
389class PrintFunctionNamesAction : public PluginParseTreeAction
390```
391
392### Implementation of `ExecuteAction`
393Like in other frontend actions, the driver looks for an `ExecuteAction` function
394to run, so in order for your plugin to do something, you will need to implement
395the `ExecuteAction` method in your plugin class. This method will contain the
396implementation of what the plugin actually does, for example:
397```cpp
398// Forward declaration
399struct ParseTreeVisitor;
400
401void ExecuteAction() override {
402  ParseTreeVisitor visitor;
403  Fortran::parser::Walk(getParsing().parseTree(), visitor);
404}
405```
406In the example plugin, the `ExecuteAction` method first creates an instance of
407`visitor` struct, before passing it together with the parse tree to the
408`Fortran::parser::Walk` function that will traverse the parse tree. The parse
409tree will normally be generated by the frontend driver and can be retrieved in
410your plugin through the `getParsing()` member method. Implementation and
411details of the `Walk` function can be found in
412`flang/include/flang/Parser/parse-tree-visitor.h`.
413
414You will have to define your own `visitor` struct. It should define different
415`Pre` and `Post` functions that take the type of a specific `ParseTree` node as
416an argument. When the `Walk` function is traversing the parse tree, these
417functions will be run before/after a node of that type is visited. Template
418functions for `Pre`/`Post` are defined so that when a node is visited that you
419have not defined a function for, it will still be able to continue. `Pre`
420returns a `bool` indicating whether to visit that node's children or not. For
421example:
422```cpp
423struct ParseTreeVisitor {
424  template <typename A> bool Pre(const A&) { return true; }
425  template <typename A> void Post(const A&) {}
426  void Post(const Fortran::parser::FunctionStmt &f) {
427    llvm::outs() << std::get<Fortran::parser::Name>(f.t).ToString() << "\n" ;
428  }
429}
430```
431The different types of nodes and also what each node structure contains are
432defined in `flang/include/flang/Parser/parse-tree.h`. In the example, there is a
433`Post` function, with a line that gets the `Name` element from a tuple `t` in
434the `FunctionStmt` struct and prints it. This function will be run after every
435`FunctionStmt` node is visited in the parse tree.
436
437### Plugin Registration
438A plugin registry is used to store names and descriptions of a collection of
439plugins. The Flang plugin registry, defined in
440`flang/include/flang/Frontend/FrontendPluginRegistry.h`, is an alias of
441`llvm::Registry` of type `PluginParseTreeAction`.
442
443The plugin will need to be registered, which will add the Plugin to the registry
444and allow it to be used. The format is as follows, with `print-fns` being the
445plugin name that is used later to call the plugin and `Print Function names`
446being the description:
447```cpp
448static FrontendPluginRegistry::Add<PrintFunctionNamesAction> X(
449    "print-fns", "Print Function names");
450```
451
452## Loading and Running a Plugin
453In order to use plugins, there are 2 command line options made available to the
454frontend driver, `flang-new -fc1`:
455* [`-load <dsopath>`](#the--load-dsopath-option) for loading the dynamic shared
456  object of the plugin
457* [`-plugin <name>`](#the--plugin-name-option) for calling the registered plugin
458
459Invocation of the example plugin is done through:
460```bash
461flang-new -fc1 -load flangPrintFunctionNames.so -plugin print-fns file.f90
462```
463
464Both these options are parsed in `flang/lib/Frontend/CompilerInvocation.cpp` and
465fulfil their actions in
466`flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp`
467
468### The `-load <dsopath>` option
469This loads the plugin shared object library, with the path given at `<dsopath>`,
470using `LoadLibraryPermantly` from LLVM's `llvm::sys::DynamicLibrary`, which
471itself uses `dlopen`. During this stage, the plugin is registered with the
472registration line from the plugin, storing the name and description.
473
474### The `-plugin <name>` option
475This sets `frontend::ActionKind programAction` in `FrontendOptions` to
476`PluginAction`, through which it searches the plugin registry for the plugin
477name from `<name>`. If found, it returns the instantiated plugin, otherwise it
478reports an error diagnostic and returns `nullptr`.
479
480## Enabling In-Tree Plugins
481For in-tree plugins, there is the CMake flag `FLANG_PLUGIN_SUPPORT`, enabled by
482default, that controls the exporting of executable symbols from `flang-new`,
483which plugins need access to. Additionally, there is the CMake flag
484`FLANG_BUILD_EXAMPLES`, turned off by default, that is used to control if the
485example programs are built. This includes plugins that are in the
486`flang/example` directory and added as a `sub_directory` to the
487`flang/examples/CMakeLists.txt`, for example, the `PrintFlangFunctionNames`
488plugin. It is also possible to develop plugins out-of-tree.
489
490## Limitations
491Note that the traversal API presented here is under active development and
492might change in the future. We expect it to evolve as support for new
493language features are added. This document and the examples will be updated
494accordingly.
495
496The current `ParseTree` structure is not suitable for modifications. The
497copy constructors are not available and hence duplicating code might not be
498trivial. Please take this into consideration when designing your plugin. In
499particular, creating a transformation plugin will be noticeably harder than
500analysis plugins that just consume (rather than edit) `ParseTree`.
501
502Lastly, if `ParseTree` modifications are performed, then it might be necessary
503to re-analyze expressions and modify scope or symbols. You can check
504[Semantics.md](Semantics.md) for more details on how `ParseTree` is edited
505e.g. during the semantic checks.
506