“Clang” CFE Internals Manual

Introduction

This document describes some of the more important APIs and internal design decisions made in the Clang C front-end. The purpose of this document is to both capture some of this high level information and also describe some of the design decisions behind it. This is meant for people interested in hacking on Clang, not for end-users. The description below is categorized by libraries, and does not describe any of the clients of the libraries.

LLVM Support Library

The LLVM libSupport library provides many underlying libraries and data-structures, including command line option processing, various containers and a system abstraction layer, which is used for file system access.

The Clang “Basic” Library

This library certainly needs a better name. The “basic” library contains a number of low-level utilities for tracking and manipulating source buffers, locations within the source buffers, diagnostics, tokens, target abstraction, and information about the subset of the language being compiled for.

Part of this infrastructure is specific to C (such as the TargetInfo class), other parts could be reused for other non-C-based languages (SourceLocation, SourceManager, Diagnostics, FileManager). When and if there is future demand we can figure out if it makes sense to introduce a new library, move the general classes somewhere else, or introduce some other solution.

We describe the roles of these classes in order of their dependencies.

The Diagnostics Subsystem

The Clang Diagnostics subsystem is an important part of how the compiler communicates with the human. Diagnostics are the warnings and errors produced when the code is incorrect or dubious. In Clang, each diagnostic produced has (at the minimum) a unique ID, an English translation associated with it, a SourceLocation to “put the caret”, and a severity (e.g., WARNING or ERROR). They can also optionally include a number of arguments to the diagnostic (which fill in “%0“‘s in the string) as well as a number of source ranges that related to the diagnostic.

In this section, we’ll be giving examples produced by the Clang command line driver, but diagnostics can be rendered in many different ways depending on how the DiagnosticConsumer interface is implemented. A representative example of a diagnostic is:

t.c:38:15: error: invalid operands to binary expression ('int *' and '_Complex float')
P = (P-42) + Gamma*4;
    ~~~~~~ ^ ~~~~~~~

In this example, you can see the English translation, the severity (error), you can see the source location (the caret (”^”) and file/line/column info), the source ranges “~~~~”, arguments to the diagnostic (”int*” and “_Complex float”). You’ll have to believe me that there is a unique ID backing the diagnostic :).

Getting all of this to happen has several steps and involves many moving pieces, this section describes them and talks about best practices when adding a new diagnostic.

The Diagnostic*Kinds.td files

Diagnostics are created by adding an entry to one of the clang/Basic/Diagnostic*Kinds.td files, depending on what library will be using it. From this file, tblgen generates the unique ID of the diagnostic, the severity of the diagnostic and the English translation + format string.

There is little sanity with the naming of the unique ID’s right now. Some start with err_, warn_, ext_ to encode the severity into the name. Since the enum is referenced in the C++ code that produces the diagnostic, it is somewhat useful for it to be reasonably short.

The severity of the diagnostic comes from the set {NOTE, REMARK, WARNING, EXTENSION, EXTWARN, ERROR}. The ERROR severity is used for diagnostics indicating the program is never acceptable under any circumstances. When an error is emitted, the AST for the input code may not be fully built. The EXTENSION and EXTWARN severities are used for extensions to the language that Clang accepts. This means that Clang fully understands and can represent them in the AST, but we produce diagnostics to tell the user their code is non-portable. The difference is that the former are ignored by default, and the later warn by default. The WARNING severity is used for constructs that are valid in the currently selected source language but that are dubious in some way. The REMARK severity provides generic information about the compilation that is not necessarily related to any dubious code. The NOTE level is used to staple more information onto previous diagnostics.

These severities are mapped into a smaller set (the Diagnostic::Level enum, {Ignored, Note, Remark, Warning, Error, Fatal}) of output levels by the diagnostics subsystem based on various configuration options. Clang internally supports a fully fine grained mapping mechanism that allows you to map almost any diagnostic to the output level that you want. The only diagnostics that cannot be mapped are NOTEs, which always follow the severity of the previously emitted diagnostic and ERRORs, which can only be mapped to Fatal (it is not possible to turn an error into a warning, for example).

Diagnostic mappings are used in many ways. For example, if the user specifies -pedantic, EXTENSION maps to Warning, if they specify -pedantic-errors, it turns into Error. This is used to implement options like -Wunused_macros, -Wundef etc.

Mapping to Fatal should only be used for diagnostics that are considered so severe that error recovery won’t be able to recover sensibly from them (thus spewing a ton of bogus errors). One example of this class of error are failure to #include a file.

Diagnostic Wording

The wording used for a diagnostic is critical because it is the only way for a user to know how to correct their code. Use the following suggestions when wording a diagnostic.

  • Diagnostics in Clang do not start with a capital letter and do not end with punctuation.

    • This does not apply to proper nouns like Clang or OpenMP, to acronyms like GCC or ARC, or to language standards like C23 or C++17.

    • A trailing question mark is allowed. e.g., unknown identifier %0; did you mean %1?.

  • Appropriately capitalize proper nouns like Clang, OpenCL, GCC, Objective-C, etc and language standard versions like C11 or C++11.

  • The wording should be succinct. If necessary, use a semicolon to combine sentence fragments instead of using complete sentences. e.g., prefer wording like '%0' is deprecated; it will be removed in a future release of Clang over wording like '%0' is deprecated. It will be removed in a future release of Clang.

  • The wording should be actionable and avoid using standards terms or grammar productions that a new user would not be familiar with. e.g., prefer wording like missing semicolon over wording like syntax error (which is not actionable) or expected unqualified-id (which uses standards terminology).

  • The wording should clearly explain what is wrong with the code rather than restating what the code does. e.g., prefer wording like type %0 requires a value in the range %1 to %2 over wording like %0 is invalid.

  • The wording should have enough contextual information to help the user identify the issue in a complex expression. e.g., prefer wording like both sides of the %0 binary operator are identical over wording like identical operands to binary operator.

  • Use single quotes to denote syntactic constructs or command line arguments named in a diagnostic message. e.g., prefer wording like 'this' pointer cannot be null in well-defined C++ code over wording like this pointer cannot be null in well-defined C++ code.

The Format String

The format string for the diagnostic is very simple, but it has some power. It takes the form of a string in English with markers that indicate where and how arguments to the diagnostic are inserted and formatted. For example, here are some simple format strings:

"binary integer literals are an extension"
"format string contains '\\0' within the string body"
"more '%%' conversions than data arguments"
"invalid operands to binary expression (%0 and %1)"
"overloaded '%0' must be a %select{unary|binary|unary or binary}2 operator"
     " (has %1 parameter%s1)"

These examples show some important points of format strings. You can use any plain ASCII character in the diagnostic string except “%” without a problem, but these are C strings, so you have to use and be aware of all the C escape sequences (as in the second example). If you want to produce a “%” in the output, use the “%%” escape sequence, like the third diagnostic. Finally, Clang uses the “%...[digit]” sequences to specify where and how arguments to the diagnostic are formatted.

Arguments to the diagnostic are numbered according to how they are specified by the C++ code that produces them, and are referenced by %0 .. %9. If you have more than 10 arguments to your diagnostic, you are doing something wrong :). Unlike printf, there is no requirement that arguments to the diagnostic end up in the output in the same order as they are specified, you could have a format string with “%1 %0” that swaps them, for example. The text in between the percent and digit are formatting instructions. If there are no instructions, the argument is just turned into a string and substituted in.

Here are some “best practices” for writing the English format string:

  • Keep the string short. It should ideally fit in the 80 column limit of the DiagnosticKinds.td file. This avoids the diagnostic wrapping when printed, and forces you to think about the important point you are conveying with the diagnostic.

  • Take advantage of location information. The user will be able to see the line and location of the caret, so you don’t need to tell them that the problem is with the 4th argument to the function: just point to it.

  • Do not capitalize the diagnostic string, and do not end it with a period.

  • If you need to quote something in the diagnostic string, use single quotes.

Diagnostics should never take random English strings as arguments: you shouldn’t use “you have a problem with %0” and pass in things like “your argument” or “your return value” as arguments. Doing this prevents translating the Clang diagnostics to other languages (because they’ll get random English words in their otherwise localized diagnostic). The exceptions to this are C/C++ language keywords (e.g., auto, const, mutable, etc) and C/C++ operators (/=). Note that things like “pointer” and “reference” are not keywords. On the other hand, you can include anything that comes from the user’s source code, including variable names, types, labels, etc. The “select” format can be used to achieve this sort of thing in a localizable way, see below.

Formatting a Diagnostic Argument

Arguments to diagnostics are fully typed internally, and come from a couple different classes: integers, types, names, and random strings. Depending on the class of the argument, it can be optionally formatted in different ways. This gives the DiagnosticConsumer information about what the argument means without requiring it to use a specific presentation (consider this MVC for Clang :).

It is really easy to add format specifiers to the Clang diagnostics system, but they should be discussed before they are added. If you are creating a lot of repetitive diagnostics and/or have an idea for a useful formatter, please bring it up on the cfe-dev mailing list.

Here are the different diagnostic argument formats currently supported by Clang:

“s” format

Example:

"requires %0 parameter%s0"

Class:

Integers

Description:

This is a simple formatter for integers that is useful when producing English diagnostics. When the integer is 1, it prints as nothing. When the integer is not 1, it prints as “s”. This allows some simple grammatical forms to be to be handled correctly, and eliminates the need to use gross things like "requires %1 parameter(s)". Note, this only handles adding a simple “s” character, it will not handle situations where pluralization is more complicated such as turning fancy into fancies or mouse into mice. You can use the “plural” format specifier to handle such situations.

“select” format

Example:

"must be a %select{unary|binary|unary or binary}0 operator"

Class:

Integers

Description:

This format specifier is used to merge multiple related diagnostics together into one common one, without requiring the difference to be specified as an English string argument. Instead of specifying the string, the diagnostic gets an integer argument and the format string selects the numbered option. In this case, the “%0” value must be an integer in the range [0..2]. If it is 0, it prints “unary”, if it is 1 it prints “binary” if it is 2, it prints “unary or binary”. This allows other language translations to substitute reasonable words (or entire phrases) based on the semantics of the diagnostic instead of having to do things textually. The selected string does undergo formatting.

“plural” format

Example:

"you have %0 %plural{1:mouse|:mice}0 connected to your computer"

Class:

Integers

Description:

This is a formatter for complex plural forms. It is designed to handle even the requirements of languages with very complex plural forms, as many Baltic languages have. The argument consists of a series of expression/form pairs, separated by “:”, where the first form whose expression evaluates to true is the result of the modifier.

An expression can be empty, in which case it is always true. See the example at the top. Otherwise, it is a series of one or more numeric conditions, separated by “,”. If any condition matches, the expression matches. Each numeric condition can take one of three forms.

  • number: A simple decimal number matches if the argument is the same as the number. Example: "%plural{1:mouse|:mice}0"

  • range: A range in square brackets matches if the argument is within the range. Then range is inclusive on both ends. Example: "%plural{0:none|1:one|[2,5]:some|:many}0"

  • modulo: A modulo operator is followed by a number, and equals sign and either a number or a range. The tests are the same as for plain numbers and ranges, but the argument is taken modulo the number first. Example: "%plural{%100=0:even hundred|%100=[1,50]:lower half|:everything else}1"

The parser is very unforgiving. A syntax error, even whitespace, will abort, as will a failure to match the argument against any expression.

“ordinal” format

Example:

"ambiguity in %ordinal0 argument"

Class:

Integers

Description:

This is a formatter which represents the argument number as an ordinal: the value 1 becomes 1st, 3 becomes 3rd, and so on. Values less than 1 are not supported. This formatter is currently hard-coded to use English ordinals.

“objcclass” format

Example:

"method %objcclass0 not found"

Class:

DeclarationName

Description:

This is a simple formatter that indicates the DeclarationName corresponds to an Objective-C class method selector. As such, it prints the selector with a leading “+”.

“objcinstance” format

Example:

"method %objcinstance0 not found"

Class:

DeclarationName

Description:

This is a simple formatter that indicates the DeclarationName corresponds to an Objective-C instance method selector. As such, it prints the selector with a leading “-“.

“q” format

Example:

"candidate found by name lookup is %q0"

Class:

NamedDecl *

Description:

This formatter indicates that the fully-qualified name of the declaration should be printed, e.g., “std::vector” rather than “vector”.

“diff” format

Example:

"no known conversion %diff{from $ to $|from argument type to parameter type}1,2"

Class:

QualType

Description:

This formatter takes two QualTypes and attempts to print a template difference between the two. If tree printing is off, the text inside the braces before the pipe is printed, with the formatted text replacing the $. If tree printing is on, the text after the pipe is printed and a type tree is printed after the diagnostic message.

“sub” format

Example:

Given the following record definition of type TextSubstitution:

def select_ovl_candidate : TextSubstitution<
  "%select{function|constructor}0%select{| template| %2}1">;

which can be used as

def note_ovl_candidate : Note<
  "candidate %sub{select_ovl_candidate}3,2,1 not viable">;

and will act as if it was written "candidate %select{function|constructor}3%select{| template| %1}2 not viable".

Description:

This format specifier is used to avoid repeating strings verbatim in multiple diagnostics. The argument to %sub must name a TextSubstitution tblgen record. The substitution must specify all arguments used by the substitution, and the modifier indexes in the substitution are re-numbered accordingly. The substituted text must itself be a valid format string before substitution.

Producing the Diagnostic

Now that you’ve created the diagnostic in the Diagnostic*Kinds.td file, you need to write the code that detects the condition in question and emits the new diagnostic. Various components of Clang (e.g., the preprocessor, Sema, etc.) provide a helper function named “Diag”. It creates a diagnostic and accepts the arguments, ranges, and other information that goes along with it.

For example, the binary expression error comes from code like this:

if (various things that are bad)
  Diag(Loc, diag::err_typecheck_invalid_operands)
    << lex->getType() << rex->getType()
    << lex->getSourceRange() << rex->getSourceRange();

This shows that use of the Diag method: it takes a location (a SourceLocation object) and a diagnostic enum value (which matches the name from Diagnostic*Kinds.td). If the diagnostic takes arguments, they are specified with the << operator: the first argument becomes %0, the second becomes %1, etc. The diagnostic interface allows you to specify arguments of many different types, including int and unsigned for integer arguments, const char* and std::string for string arguments, DeclarationName and const IdentifierInfo * for names, QualType for types, etc. SourceRanges are also specified with the << operator, but do not have a specific ordering requirement.

As you can see, adding and producing a diagnostic is pretty straightforward. The hard part is deciding exactly what you need to say to help the user, picking a suitable wording, and providing the information needed to format it correctly. The good news is that the call site that issues a diagnostic should be completely independent of how the diagnostic is formatted and in what language it is rendered.

Fix-It Hints

In some cases, the front end emits diagnostics when it is clear that some small change to the source code would fix the problem. For example, a missing semicolon at the end of a statement or a use of deprecated syntax that is easily rewritten into a more modern form. Clang tries very hard to emit the diagnostic and recover gracefully in these and other cases.

However, for these cases where the fix is obvious, the diagnostic can be annotated with a hint (referred to as a “fix-it hint”) that describes how to change the code referenced by the diagnostic to fix the problem. For example, it might add the missing semicolon at the end of the statement or rewrite the use of a deprecated construct into something more palatable. Here is one such example from the C++ front end, where we warn about the right-shift operator changing meaning from C++98 to C++11:

test.cpp:3:7: warning: use of right-shift operator ('>>') in template argument
                       will require parentheses in C++11
A<100 >> 2> *a;
      ^
  (       )

Here, the fix-it hint is suggesting that parentheses be added, and showing exactly where those parentheses would be inserted into the source code. The fix-it hints themselves describe what changes to make to the source code in an abstract manner, which the text diagnostic printer renders as a line of “insertions” below the caret line. Other diagnostic clients might choose to render the code differently (e.g., as markup inline) or even give the user the ability to automatically fix the problem.

Fix-it hints on errors and warnings need to obey these rules:

  • Since they are automatically applied if -Xclang -fixit is passed to the driver, they should only be used when it’s very likely they match the user’s intent.

  • Clang must recover from errors as if the fix-it had been applied.

  • Fix-it hints on a warning must not change the meaning of the code. However, a hint may clarify the meaning as intentional, for example by adding parentheses when the precedence of operators isn’t obvious.

If a fix-it can’t obey these rules, put the fix-it on a note. Fix-its on notes are not applied automatically.

All fix-it hints are described by the FixItHint class, instances of which should be attached to the diagnostic using the << operator in the same way that highlighted source ranges and arguments are passed to the diagnostic. Fix-it hints can be created with one of three constructors:

  • FixItHint::CreateInsertion(Loc, Code)

    Specifies that the given Code (a string) should be inserted before the source location Loc.

  • FixItHint::CreateRemoval(Range)

    Specifies that the code in the given source Range should be removed.

  • FixItHint::CreateReplacement(Range, Code)

    Specifies that the code in the given source Range should be removed, and replaced with the given Code string.

The DiagnosticConsumer Interface

Once code generates a diagnostic with all of the arguments and the rest of the relevant information, Clang needs to know what to do with it. As previously mentioned, the diagnostic machinery goes through some filtering to map a severity onto a diagnostic level, then (assuming the diagnostic is not mapped to “Ignore”) it invokes an object that implements the DiagnosticConsumer interface with the information.

It is possible to implement this interface in many different ways. For example, the normal Clang DiagnosticConsumer (named TextDiagnosticPrinter) turns the arguments into strings (according to the various formatting rules), prints out the file/line/column information and the string, then prints out the line of code, the source ranges, and the caret. However, this behavior isn’t required.

Another implementation of the DiagnosticConsumer interface is the TextDiagnosticBuffer class, which is used when Clang is in -verify mode. Instead of formatting and printing out the diagnostics, this implementation just captures and remembers the diagnostics as they fly by. Then -verify compares the list of produced diagnostics to the list of expected ones. If they disagree, it prints out its own output. Full documentation for the -verify mode can be found at Verifying Diagnostics.

There are many other possible implementations of this interface, and this is why we prefer diagnostics to pass down rich structured information in arguments. For example, an HTML output might want declaration names be linkified to where they come from in the source. Another example is that a GUI might let you click on typedefs to expand them. This application would want to pass significantly more information about types through to the GUI than a simple flat string. The interface allows this to happen.

Adding Translations to Clang

Not possible yet! Diagnostic strings should be written in UTF-8, the client can translate to the relevant code page if needed. Each translation completely replaces the format string for the diagnostic.

The SourceLocation and SourceManager classes

Strangely enough, the SourceLocation class represents a location within the source code of the program. Important design points include:

  1. sizeof(SourceLocation) must be extremely small, as these are embedded into many AST nodes and are passed around often. Currently it is 32 bits.

  2. SourceLocation must be a simple value object that can be efficiently copied.

  3. We should be able to represent a source location for any byte of any input file. This includes in the middle of tokens, in whitespace, in trigraphs, etc.

  4. A SourceLocation must encode the current #include stack that was active when the location was processed. For example, if the location corresponds to a token, it should contain the set of #includes active when the token was lexed. This allows us to print the #include stack for a diagnostic.

  5. SourceLocation must be able to describe macro expansions, capturing both the ultimate instantiation point and the source of the original character data.

In practice, the SourceLocation works together with the SourceManager class to encode two pieces of information about a location: its spelling location and its expansion location. For most tokens, these will be the same. However, for a macro expansion (or tokens that came from a _Pragma directive) these will describe the location of the characters corresponding to the token and the location where the token was used (i.e., the macro expansion point or the location of the _Pragma itself).

The Clang front-end inherently depends on the location of a token being tracked correctly. If it is ever incorrect, the front-end may get confused and die. The reason for this is that the notion of the “spelling” of a Token in Clang depends on being able to find the original input characters for the token. This concept maps directly to the “spelling location” for the token.

SourceRange and CharSourceRange

Clang represents most source ranges by [first, last], where “first” and “last” each point to the beginning of their respective tokens. For example consider the SourceRange of the following statement:

x = foo + bar;
^first    ^last

To map from this representation to a character-based representation, the “last” location needs to be adjusted to point to (or past) the end of that token with either Lexer::MeasureTokenLength() or Lexer::getLocForEndOfToken(). For the rare cases where character-level source ranges information is needed we use the CharSourceRange class.

The Driver Library

The clang Driver and library are documented here.

Precompiled Headers

Clang supports precompiled headers (PCH), which uses a serialized representation of Clang’s internal data structures, encoded with the LLVM bitstream format.

The Frontend Library

The Frontend library contains functionality useful for building tools on top of the Clang libraries, for example several methods for outputting diagnostics.

Compiler Invocation

One of the classes provided by the Frontend library is CompilerInvocation, which holds information that describe current invocation of the Clang -cc1 frontend. The information typically comes from the command line constructed by the Clang driver or from clients performing custom initialization. The data structure is split into logical units used by different parts of the compiler, for example PreprocessorOptions, LanguageOptions or CodeGenOptions.

Command Line Interface

The command line interface of the Clang -cc1 frontend is defined alongside the driver options in clang/Driver/Options.td. The information making up an option definition includes its prefix and name (for example -std=), form and position of the option value, help text, aliases and more. Each option may belong to a certain group and can be marked with zero or more flags. Options accepted by the -cc1 frontend are marked with the CC1Option flag.

Command Line Parsing

Option definitions are processed by the -gen-opt-parser-defs tablegen backend during early stages of the build. Options are then used for querying an instance llvm::opt::ArgList, a wrapper around the command line arguments. This is done in the Clang driver to construct individual jobs based on the driver arguments and also in the CompilerInvocation::CreateFromArgs function that parses the -cc1 frontend arguments.

Command Line Generation

Any valid CompilerInvocation created from a -cc1 command line can be also serialized back into semantically equivalent command line in a deterministic manner. This enables features such as implicitly discovered, explicitly built modules.

Adding new Command Line Option

When adding a new command line option, the first place of interest is the header file declaring the corresponding options class (e.g. CodeGenOptions.h for command line option that affects the code generation). Create new member variable for the option value:

  class CodeGenOptions : public CodeGenOptionsBase {

+   /// List of dynamic shared object files to be loaded as pass plugins.
+   std::vector<std::string> PassPlugins;

  }

Next, declare the command line interface of the option in the tablegen file clang/include/clang/Driver/Options.td. This is done by instantiating the Option class (defined in llvm/include/llvm/Option/OptParser.td). The instance is typically created through one of the helper classes that encode the acceptable ways to specify the option value on the command line:

  • Flag - the option does not accept any value,

  • Joined - the value must immediately follow the option name within the same argument,

  • Separate - the value must follow the option name in the next command line argument,

  • JoinedOrSeparate - the value can be specified either as Joined or Separate,

  • CommaJoined - the values are comma-separated and must immediately follow the option name within the same argument (see Wl, for an example).

The helper classes take a list of acceptable prefixes of the option (e.g. "-", "--" or "/") and the option name:

  // Options.td

+ def fpass_plugin_EQ : Joined<["-"], "fpass-plugin=">;

Then, specify additional attributes via mix-ins:

  • HelpText holds the text that will be printed besides the option name when the user requests help (e.g. via clang --help).

  • Group specifies the “category” of options this option belongs to. This is used by various tools to categorize and sometimes filter options.

  • Flags may contain “tags” associated with the option. These may affect how the option is rendered, or if it’s hidden in some contexts.

  • Visibility should be used to specify the drivers in which a particular option would be available. This attribute will impact tool –help

  • Alias denotes that the option is an alias of another option. This may be combined with AliasArgs that holds the implied value.

  // Options.td

  def fpass_plugin_EQ : Joined<["-"], "fpass-plugin=">,
+   Group<f_Group>, Visibility<[ClangOption, CC1Option]>,
+   HelpText<"Load pass plugin from a dynamic shared object file.">;

New options are recognized by the clang driver mode if Visibility is not specified or contains ClangOption. Options intended for clang -cc1 must be explicitly marked with the CC1Option flag. Flags that specify CC1Option but not ClangOption will only be accessible via -cc1. This is similar for other driver modes, such as clang-cl or flang.

Next, parse (or manufacture) the command line arguments in the Clang driver and use them to construct the -cc1 job:

  void Clang::ConstructJob(const ArgList &Args /*...*/) const {
    ArgStringList CmdArgs;
    // ...

+   for (const Arg *A : Args.filtered(OPT_fpass_plugin_EQ)) {
+     CmdArgs.push_back(Args.MakeArgString(Twine("-fpass-plugin=") + A->getValue()));
+     A->claim();
+   }
  }

The last step is implementing the -cc1 command line argument parsing/generation that initializes/serializes the option class (in our case CodeGenOptions) stored within CompilerInvocation. This can be done automatically by using the marshalling annotations on the option definition:

  // Options.td

  def fpass_plugin_EQ : Joined<["-"], "fpass-plugin=">,
    Group<f_Group>, Flags<[CC1Option]>,
    HelpText<"Load pass plugin from a dynamic shared object file.">,
+   MarshallingInfoStringVector<CodeGenOpts<"PassPlugins">>;

Inner workings of the system are introduced in the marshalling infrastructure section and the available annotations are listed here.

In case the marshalling infrastructure does not support the desired semantics, consider simplifying it to fit the existing model. This makes the command line more uniform and reduces the amount of custom, manually written code. Remember that the -cc1 command line interface is intended only for Clang developers, meaning it does not need to mirror the driver interface, maintain backward compatibility or be compatible with GCC.

If the option semantics cannot be encoded via marshalling annotations, you can resort to parsing/serializing the command line arguments manually:

  // CompilerInvocation.cpp

  static bool ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args /*...*/) {
    // ...

+   Opts.PassPlugins = Args.getAllArgValues(OPT_fpass_plugin_EQ);
  }

  static void GenerateCodeGenArgs(const CodeGenOptions &Opts,
                                  SmallVectorImpl<const char *> &Args,
                                  CompilerInvocation::StringAllocator SA /*...*/) {
    // ...

+   for (const std::string &PassPlugin : Opts.PassPlugins)
+     GenerateArg(Args, OPT_fpass_plugin_EQ, PassPlugin, SA);
  }

Finally, you can specify the argument on the command line: clang -fpass-plugin=a -fpass-plugin=b and use the new member variable as desired.

  void EmitAssemblyHelper::EmitAssemblyWithNewPassManager(/*...*/) {
    // ...
+   for (auto &PluginFN : CodeGenOpts.PassPlugins)
+     if (auto PassPlugin = PassPlugin::Load(PluginFN))
+        PassPlugin->registerPassBuilderCallbacks(PB);
  }

Option Marshalling Infrastructure

The option marshalling infrastructure automates the parsing of the Clang -cc1 frontend command line arguments into CompilerInvocation and their generation from CompilerInvocation. The system replaces lots of repetitive C++ code with simple, declarative tablegen annotations and it’s being used for the majority of the -cc1 command line interface. This section provides an overview of the system.

Note: The marshalling infrastructure is not intended for driver-only options. Only options of the -cc1 frontend need to be marshalled to/from CompilerInvocation instance.

To read and modify contents of CompilerInvocation, the marshalling system uses key paths, which are declared in two steps. First, a tablegen definition for the CompilerInvocation member is created by inheriting from KeyPathAndMacro:

// Options.td

class LangOpts<string field> : KeyPathAndMacro<"LangOpts->", field, "LANG_"> {}
//                   CompilerInvocation member  ^^^^^^^^^^
//                                    OPTION_WITH_MARSHALLING prefix ^^^^^

The first argument to the parent class is the beginning of the key path that references the CompilerInvocation member. This argument ends with -> if the member is a pointer type or with . if it’s a value type. The child class takes a single parameter field that is forwarded as the second argument to the base class. The child class can then be used like so: LangOpts<"IgnoreExceptions">, constructing a key path to the field LangOpts->IgnoreExceptions. The third argument passed to the parent class is a string that the tablegen backend uses as a prefix to the OPTION_WITH_MARSHALLING macro. Using the key path as a mix-in on an Option instance instructs the backend to generate the following code:

// Options.inc

#ifdef LANG_OPTION_WITH_MARSHALLING
LANG_OPTION_WITH_MARSHALLING([...], LangOpts->IgnoreExceptions, [...])
#endif // LANG_OPTION_WITH_MARSHALLING

Such definition can be used used in the function for parsing and generating command line:

// clang/lib/Frontend/CompilerInvoation.cpp

bool CompilerInvocation::ParseLangArgs(LangOptions *LangOpts, ArgList &Args,
                                       DiagnosticsEngine &Diags) {
  bool Success = true;

#define LANG_OPTION_WITH_MARSHALLING(                                          \
    PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,        \
    HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH,   \
    DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER,     \
    MERGER, EXTRACTOR, TABLE_INDEX)                                            \
  PARSE_OPTION_WITH_MARSHALLING(Args, Diags, Success, ID, FLAGS, PARAM,        \
                                SHOULD_PARSE, KEYPATH, DEFAULT_VALUE,          \
                                IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER,      \
                                MERGER, TABLE_INDEX)
#include "clang/Driver/Options.inc"
#undef LANG_OPTION_WITH_MARSHALLING

  // ...

  return Success;
}

void CompilerInvocation::GenerateLangArgs(LangOptions *LangOpts,
                                          SmallVectorImpl<const char *> &Args,
                                          StringAllocator SA) {
#define LANG_OPTION_WITH_MARSHALLING(                                          \
    PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,        \
    HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH,   \
    DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER,     \
    MERGER, EXTRACTOR, TABLE_INDEX)                                            \
  GENERATE_OPTION_WITH_MARSHALLING(                                            \
      Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE,    \
      IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
#include "clang/Driver/Options.inc"
#undef LANG_OPTION_WITH_MARSHALLING

  // ...
}

The PARSE_OPTION_WITH_MARSHALLING and GENERATE_OPTION_WITH_MARSHALLING macros are defined in CompilerInvocation.cpp and they implement the generic algorithm for parsing and generating command line arguments.

Option Marshalling Annotations

How does the tablegen backend know what to put in place of [...] in the generated Options.inc? This is specified by the Marshalling utilities described below. All of them take a key path argument and possibly other information required for parsing or generating the command line argument.

Note: The marshalling infrastructure is not intended for driver-only options. Only options of the -cc1 frontend need to be marshalled to/from CompilerInvocation instance.

Positive Flag

The key path defaults to false and is set to true when the flag is present on command line.

def fignore_exceptions : Flag<["-"], "fignore-exceptions">,
  Visibility<[ClangOption, CC1Option]>,
  MarshallingInfoFlag<LangOpts<"IgnoreExceptions">>;

Negative Flag

The key path defaults to true and is set to false when the flag is present on command line.

def fno_verbose_asm : Flag<["-"], "fno-verbose-asm">,
  Visibility<[ClangOption, CC1Option]>,
  MarshallingInfoNegativeFlag<CodeGenOpts<"AsmVerbose">>;

Negative and Positive Flag

The key path defaults to the specified value (false, true or some boolean value that’s statically unknown in the tablegen file). Then, the key path is set to the value associated with the flag that appears last on command line.

defm legacy_pass_manager : BoolOption<"f", "legacy-pass-manager",
  CodeGenOpts<"LegacyPassManager">, DefaultFalse,
  PosFlag<SetTrue, [], [], "Use the legacy pass manager in LLVM">,
  NegFlag<SetFalse, [], [], "Use the new pass manager in LLVM">,
  BothFlags<[], [ClangOption, CC1Option]>>;

With most such pair of flags, the -cc1 frontend accepts only the flag that changes the default key path value. The Clang driver is responsible for accepting both and either forwarding the changing flag or discarding the flag that would just set the key path to its default.

The first argument to BoolOption is a prefix that is used to construct the full names of both flags. The positive flag would then be named flegacy-pass-manager and the negative fno-legacy-pass-manager. BoolOption also implies the - prefix for both flags. It’s also possible to use BoolFOption that implies the "f" prefix and Group<f_Group>. The PosFlag and NegFlag classes hold the associated boolean value, arrays of elements passed to the Flag and Visibility classes and the help text. The optional BothFlags class holds arrays of Flag and Visibility elements that are common for both the positive and negative flag and their common help text suffix.

String

The key path defaults to the specified string, or an empty one, if omitted. When the option appears on the command line, the argument value is simply copied.

def isysroot : JoinedOrSeparate<["-"], "isysroot">,
  Visibility<[ClangOption, CC1Option, FlangOption]>,
  MarshallingInfoString<HeaderSearchOpts<"Sysroot">, [{"/"}]>;

List of Strings

The key path defaults to an empty std::vector<std::string>. Values specified with each appearance of the option on the command line are appended to the vector.

def frewrite_map_file : Separate<["-"], "frewrite-map-file">,
  Visibility<[ClangOption, CC1Option]>,
  MarshallingInfoStringVector<CodeGenOpts<"RewriteMapFiles">>;

Integer

The key path defaults to the specified integer value, or 0 if omitted. When the option appears on the command line, its value gets parsed by llvm::APInt and the result is assigned to the key path on success.

def mstack_probe_size : Joined<["-"], "mstack-probe-size=">,
  Visibility<[ClangOption, CC1Option]>,
  MarshallingInfoInt<CodeGenOpts<"StackProbeSize">, "4096">;

Enumeration

The key path defaults to the value specified in MarshallingInfoEnum prefixed by the contents of NormalizedValuesScope and ::. This ensures correct reference to an enum case is formed even if the enum resides in different namespace or is an enum class. If the value present on command line does not match any of the comma-separated values from Values, an error diagnostics is issued. Otherwise, the corresponding element from NormalizedValues at the same index is assigned to the key path (also correctly scoped). The number of comma-separated string values and elements of the array within NormalizedValues must match.

def mthread_model : Separate<["-"], "mthread-model">,
  Visibility<[ClangOption, CC1Option]>,
  Values<"posix,single">, NormalizedValues<["POSIX", "Single"]>,
  NormalizedValuesScope<"LangOptions::ThreadModelKind">,
  MarshallingInfoEnum<LangOpts<"ThreadModel">, "POSIX">;

It is also possible to define relationships between options.

Implication

The key path defaults to the default value from the primary Marshalling annotation. Then, if any of the elements of ImpliedByAnyOf evaluate to true, the key path value is changed to the specified value or true if missing. Finally, the command line is parsed according to the primary annotation.

def fms_extensions : Flag<["-"], "fms-extensions">,
  Visibility<[ClangOption, CC1Option]>,
  MarshallingInfoFlag<LangOpts<"MicrosoftExt">>,
  ImpliedByAnyOf<[fms_compatibility.KeyPath], "true">;

Condition

The option is parsed only if the expression in ShouldParseIf evaluates to true.

def fopenmp_enable_irbuilder : Flag<["-"], "fopenmp-enable-irbuilder">,
  Visibility<[ClangOption, CC1Option]>,
  MarshallingInfoFlag<LangOpts<"OpenMPIRBuilder">>,
  ShouldParseIf<fopenmp.KeyPath>;

The Lexer and Preprocessor Library

The Lexer library contains several tightly-connected classes that are involved with the nasty process of lexing and preprocessing C source code. The main interface to this library for outside clients is the large Preprocessor class. It contains the various pieces of state that are required to coherently read tokens out of a translation unit.

The core interface to the Preprocessor object (once it is set up) is the Preprocessor::Lex method, which returns the next Token from the preprocessor stream. There are two types of token providers that the preprocessor is capable of reading from: a buffer lex