1 ============================
2 "Clang" CFE Internals Manual
3 ============================
11 This document describes some of the more important APIs and internal design
12 decisions made in the Clang C front-end. The purpose of this document is to
13 both capture some of this high level information and also describe some of the
14 design decisions behind it. This is meant for people interested in hacking on
15 Clang, not for end-users. The description below is categorized by libraries,
16 and does not describe any of the clients of the libraries.
21 The LLVM ``libSupport`` library provides many underlying libraries and
22 `data-structures <https://llvm.org/docs/ProgrammersManual.html>`_, including
23 command line option processing, various containers and a system abstraction
24 layer, which is used for file system access.
26 The Clang "Basic" Library
27 =========================
29 This library certainly needs a better name. The "basic" library contains a
30 number of low-level utilities for tracking and manipulating source buffers,
31 locations within the source buffers, diagnostics, tokens, target abstraction,
32 and information about the subset of the language being compiled for.
34 Part of this infrastructure is specific to C (such as the ``TargetInfo``
35 class), other parts could be reused for other non-C-based languages
36 (``SourceLocation``, ``SourceManager``, ``Diagnostics``, ``FileManager``).
37 When and if there is future demand we can figure out if it makes sense to
38 introduce a new library, move the general classes somewhere else, or introduce
41 We describe the roles of these classes in order of their dependencies.
43 The Diagnostics Subsystem
44 -------------------------
46 The Clang Diagnostics subsystem is an important part of how the compiler
47 communicates with the human. Diagnostics are the warnings and errors produced
48 when the code is incorrect or dubious. In Clang, each diagnostic produced has
49 (at the minimum) a unique ID, an English translation associated with it, a
50 :ref:`SourceLocation <SourceLocation>` to "put the caret", and a severity
51 (e.g., ``WARNING`` or ``ERROR``). They can also optionally include a number of
52 arguments to the diagnostic (which fill in "%0"'s in the string) as well as a
53 number of source ranges that related to the diagnostic.
55 In this section, we'll be giving examples produced by the Clang command line
56 driver, but diagnostics can be :ref:`rendered in many different ways
57 <DiagnosticConsumer>` depending on how the ``DiagnosticConsumer`` interface is
58 implemented. A representative example of a diagnostic is:
62 t.c:38:15: error: invalid operands to binary expression ('int *' and '_Complex float')
66 In this example, you can see the English translation, the severity (error), you
67 can see the source location (the caret ("``^``") and file/line/column info),
68 the source ranges "``~~~~``", arguments to the diagnostic ("``int*``" and
69 "``_Complex float``"). You'll have to believe me that there is a unique ID
70 backing the diagnostic :).
72 Getting all of this to happen has several steps and involves many moving
73 pieces, this section describes them and talks about best practices when adding
76 The ``Diagnostic*Kinds.td`` files
77 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
79 Diagnostics are created by adding an entry to one of the
80 ``clang/Basic/Diagnostic*Kinds.td`` files, depending on what library will be
81 using it. From this file, :program:`tblgen` generates the unique ID of the
82 diagnostic, the severity of the diagnostic and the English translation + format
85 There is little sanity with the naming of the unique ID's right now. Some
86 start with ``err_``, ``warn_``, ``ext_`` to encode the severity into the name.
87 Since the enum is referenced in the C++ code that produces the diagnostic, it
88 is somewhat useful for it to be reasonably short.
90 The severity of the diagnostic comes from the set {``NOTE``, ``REMARK``,
92 ``EXTENSION``, ``EXTWARN``, ``ERROR``}. The ``ERROR`` severity is used for
93 diagnostics indicating the program is never acceptable under any circumstances.
94 When an error is emitted, the AST for the input code may not be fully built.
95 The ``EXTENSION`` and ``EXTWARN`` severities are used for extensions to the
96 language that Clang accepts. This means that Clang fully understands and can
97 represent them in the AST, but we produce diagnostics to tell the user their
98 code is non-portable. The difference is that the former are ignored by
99 default, and the later warn by default. The ``WARNING`` severity is used for
100 constructs that are valid in the currently selected source language but that
101 are dubious in some way. The ``REMARK`` severity provides generic information
102 about the compilation that is not necessarily related to any dubious code. The
103 ``NOTE`` level is used to staple more information onto previous diagnostics.
105 These *severities* are mapped into a smaller set (the ``Diagnostic::Level``
106 enum, {``Ignored``, ``Note``, ``Remark``, ``Warning``, ``Error``, ``Fatal``}) of
108 *levels* by the diagnostics subsystem based on various configuration options.
109 Clang internally supports a fully fine grained mapping mechanism that allows
110 you to map almost any diagnostic to the output level that you want. The only
111 diagnostics that cannot be mapped are ``NOTE``\ s, which always follow the
112 severity of the previously emitted diagnostic and ``ERROR``\ s, which can only
113 be mapped to ``Fatal`` (it is not possible to turn an error into a warning, for
116 Diagnostic mappings are used in many ways. For example, if the user specifies
117 ``-pedantic``, ``EXTENSION`` maps to ``Warning``, if they specify
118 ``-pedantic-errors``, it turns into ``Error``. This is used to implement
119 options like ``-Wunused_macros``, ``-Wundef`` etc.
121 Mapping to ``Fatal`` should only be used for diagnostics that are considered so
122 severe that error recovery won't be able to recover sensibly from them (thus
123 spewing a ton of bogus errors). One example of this class of error are failure
124 to ``#include`` a file.
128 The wording used for a diagnostic is critical because it is the only way for a
129 user to know how to correct their code. Use the following suggestions when
130 wording a diagnostic.
132 * Diagnostics in Clang do not start with a capital letter and do not end with
135 * This does not apply to proper nouns like ``Clang`` or ``OpenMP``, to
136 acronyms like ``GCC`` or ``ARC``, or to language standards like ``C23``
138 * A trailing question mark is allowed. e.g., ``unknown identifier %0; did
141 * Appropriately capitalize proper nouns like ``Clang``, ``OpenCL``, ``GCC``,
142 ``Objective-C``, etc and language standard versions like ``C11`` or ``C++11``.
143 * The wording should be succinct. If necessary, use a semicolon to combine
144 sentence fragments instead of using complete sentences. e.g., prefer wording
145 like ``'%0' is deprecated; it will be removed in a future release of Clang``
146 over wording like ``'%0' is deprecated. It will be removed in a future release
148 * The wording should be actionable and avoid using standards terms or grammar
149 productions that a new user would not be familiar with. e.g., prefer wording
150 like ``missing semicolon`` over wording like ``syntax error`` (which is not
151 actionable) or ``expected unqualified-id`` (which uses standards terminology).
152 * The wording should clearly explain what is wrong with the code rather than
153 restating what the code does. e.g., prefer wording like ``type %0 requires a
154 value in the range %1 to %2`` over wording like ``%0 is invalid``.
155 * The wording should have enough contextual information to help the user
156 identify the issue in a complex expression. e.g., prefer wording like
157 ``both sides of the %0 binary operator are identical`` over wording like
158 ``identical operands to binary operator``.
159 * Use single quotes to denote syntactic constructs or command line arguments
160 named in a diagnostic message. e.g., prefer wording like ``'this' pointer
161 cannot be null in well-defined C++ code`` over wording like ``this pointer
162 cannot be null in well-defined C++ code``.
163 * Prefer diagnostic wording without contractions whenever possible. The single
164 quote in a contraction can be visually distracting due to its use with
165 syntactic constructs and contractions can be harder to understand for non-
166 native English speakers.
171 The format string for the diagnostic is very simple, but it has some power. It
172 takes the form of a string in English with markers that indicate where and how
173 arguments to the diagnostic are inserted and formatted. For example, here are
174 some simple format strings:
178 "binary integer literals are an extension"
179 "format string contains '\\0' within the string body"
180 "more '%%' conversions than data arguments"
181 "invalid operands to binary expression (%0 and %1)"
182 "overloaded '%0' must be a %select{unary|binary|unary or binary}2 operator"
183 " (has %1 parameter%s1)"
185 These examples show some important points of format strings. You can use any
186 plain ASCII character in the diagnostic string except "``%``" without a
187 problem, but these are C strings, so you have to use and be aware of all the C
188 escape sequences (as in the second example). If you want to produce a "``%``"
189 in the output, use the "``%%``" escape sequence, like the third diagnostic.
190 Finally, Clang uses the "``%...[digit]``" sequences to specify where and how
191 arguments to the diagnostic are formatted.
193 Arguments to the diagnostic are numbered according to how they are specified by
194 the C++ code that :ref:`produces them <internals-producing-diag>`, and are
195 referenced by ``%0`` .. ``%9``. If you have more than 10 arguments to your
196 diagnostic, you are doing something wrong :). Unlike ``printf``, there is no
197 requirement that arguments to the diagnostic end up in the output in the same
198 order as they are specified, you could have a format string with "``%1 %0``"
199 that swaps them, for example. The text in between the percent and digit are
200 formatting instructions. If there are no instructions, the argument is just
201 turned into a string and substituted in.
203 Here are some "best practices" for writing the English format string:
205 * Keep the string short. It should ideally fit in the 80 column limit of the
206 ``DiagnosticKinds.td`` file. This avoids the diagnostic wrapping when
207 printed, and forces you to think about the important point you are conveying
209 * Take advantage of location information. The user will be able to see the
210 line and location of the caret, so you don't need to tell them that the
211 problem is with the 4th argument to the function: just point to it.
212 * Do not capitalize the diagnostic string, and do not end it with a period.
213 * If you need to quote something in the diagnostic string, use single quotes.
215 Diagnostics should never take random English strings as arguments: you
216 shouldn't use "``you have a problem with %0``" and pass in things like "``your
217 argument``" or "``your return value``" as arguments. Doing this prevents
218 :ref:`translating <internals-diag-translation>` the Clang diagnostics to other
219 languages (because they'll get random English words in their otherwise
220 localized diagnostic). The exceptions to this are C/C++ language keywords
221 (e.g., ``auto``, ``const``, ``mutable``, etc) and C/C++ operators (``/=``).
222 Note that things like "pointer" and "reference" are not keywords. On the other
223 hand, you *can* include anything that comes from the user's source code,
224 including variable names, types, labels, etc. The "``select``" format can be
225 used to achieve this sort of thing in a localizable way, see below.
227 Formatting a Diagnostic Argument
228 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
230 Arguments to diagnostics are fully typed internally, and come from a couple
231 different classes: integers, types, names, and random strings. Depending on
232 the class of the argument, it can be optionally formatted in different ways.
233 This gives the ``DiagnosticConsumer`` information about what the argument means
234 without requiring it to use a specific presentation (consider this MVC for
237 It is really easy to add format specifiers to the Clang diagnostics system, but
238 they should be discussed before they are added. If you are creating a lot of
239 repetitive diagnostics and/or have an idea for a useful formatter, please bring
240 it up on the cfe-dev mailing list.
242 Here are the different diagnostic argument formats currently supported by
248 ``"requires %0 parameter%s0"``
252 This is a simple formatter for integers that is useful when producing English
253 diagnostics. When the integer is 1, it prints as nothing. When the integer
254 is not 1, it prints as "``s``". This allows some simple grammatical forms to
255 be to be handled correctly, and eliminates the need to use gross things like
256 ``"requires %1 parameter(s)"``. Note, this only handles adding a simple
257 "``s``" character, it will not handle situations where pluralization is more
258 complicated such as turning ``fancy`` into ``fancies`` or ``mouse`` into
259 ``mice``. You can use the "plural" format specifier to handle such situations.
264 ``"must be a %select{unary|binary|unary or binary}0 operator"``
268 This format specifier is used to merge multiple related diagnostics together
269 into one common one, without requiring the difference to be specified as an
270 English string argument. Instead of specifying the string, the diagnostic
271 gets an integer argument and the format string selects the numbered option.
272 In this case, the "``%0``" value must be an integer in the range [0..2]. If
273 it is 0, it prints "unary", if it is 1 it prints "binary" if it is 2, it
274 prints "unary or binary". This allows other language translations to
275 substitute reasonable words (or entire phrases) based on the semantics of the
276 diagnostic instead of having to do things textually. The selected string
277 does undergo formatting.
282 ``"you have %0 %plural{1:mouse|:mice}0 connected to your computer"``
286 This is a formatter for complex plural forms. It is designed to handle even
287 the requirements of languages with very complex plural forms, as many Baltic
288 languages have. The argument consists of a series of expression/form pairs,
289 separated by ":", where the first form whose expression evaluates to true is
290 the result of the modifier.
292 An expression can be empty, in which case it is always true. See the example
293 at the top. Otherwise, it is a series of one or more numeric conditions,
294 separated by ",". If any condition matches, the expression matches. Each
295 numeric condition can take one of three forms.
297 * number: A simple decimal number matches if the argument is the same as the
298 number. Example: ``"%plural{1:mouse|:mice}0"``
299 * range: A range in square brackets matches if the argument is within the
300 range. Then range is inclusive on both ends. Example:
301 ``"%plural{0:none|1:one|[2,5]:some|:many}0"``
302 * modulo: A modulo operator is followed by a number, and equals sign and
303 either a number or a range. The tests are the same as for plain numbers
304 and ranges, but the argument is taken modulo the number first. Example:
305 ``"%plural{%100=0:even hundred|%100=[1,50]:lower half|:everything else}1"``
307 The parser is very unforgiving. A syntax error, even whitespace, will abort,
308 as will a failure to match the argument against any expression.
313 ``"ambiguity in %ordinal0 argument"``
317 This is a formatter which represents the argument number as an ordinal: the
318 value ``1`` becomes ``1st``, ``3`` becomes ``3rd``, and so on. Values less
319 than ``1`` are not supported. This formatter is currently hard-coded to use
325 ``"total size is %human0 bytes"``
329 This is a formatter which represents the argument number in a human readable
330 format: the value ``123`` stays ``123``, ``12345`` becomes ``12.34k``,
331 ``6666666` becomes ``6.67M``, and so on for 'G' and 'T'.
333 **"objcclass" format**
336 ``"method %objcclass0 not found"``
340 This is a simple formatter that indicates the ``DeclarationName`` corresponds
341 to an Objective-C class method selector. As such, it prints the selector
342 with a leading "``+``".
344 **"objcinstance" format**
347 ``"method %objcinstance0 not found"``
351 This is a simple formatter that indicates the ``DeclarationName`` corresponds
352 to an Objective-C instance method selector. As such, it prints the selector
353 with a leading "``-``".
358 ``"candidate found by name lookup is %q0"``
362 This formatter indicates that the fully-qualified name of the declaration
363 should be printed, e.g., "``std::vector``" rather than "``vector``".
368 ``"no known conversion %diff{from $ to $|from argument type to parameter type}1,2"``
372 This formatter takes two ``QualType``\ s and attempts to print a template
373 difference between the two. If tree printing is off, the text inside the
374 braces before the pipe is printed, with the formatted text replacing the $.
375 If tree printing is on, the text after the pipe is printed and a type tree is
376 printed after the diagnostic message.
381 Given the following record definition of type ``TextSubstitution``:
385 def select_ovl_candidate : TextSubstitution<
386 "%select{function|constructor}0%select{| template| %2}1">;
392 def note_ovl_candidate : Note<
393 "candidate %sub{select_ovl_candidate}3,2,1 not viable">;
395 and will act as if it was written
396 ``"candidate %select{function|constructor}3%select{| template| %1}2 not viable"``.
398 This format specifier is used to avoid repeating strings verbatim in multiple
399 diagnostics. The argument to ``%sub`` must name a ``TextSubstitution`` tblgen
400 record. The substitution must specify all arguments used by the substitution,
401 and the modifier indexes in the substitution are re-numbered accordingly. The
402 substituted text must itself be a valid format string before substitution.
404 .. _internals-producing-diag:
406 Producing the Diagnostic
407 ^^^^^^^^^^^^^^^^^^^^^^^^
409 Now that you've created the diagnostic in the ``Diagnostic*Kinds.td`` file, you
410 need to write the code that detects the condition in question and emits the new
411 diagnostic. Various components of Clang (e.g., the preprocessor, ``Sema``,
412 etc.) provide a helper function named "``Diag``". It creates a diagnostic and
413 accepts the arguments, ranges, and other information that goes along with it.
415 For example, the binary expression error comes from code like this:
419 if (various things that are bad)
420 Diag(Loc, diag::err_typecheck_invalid_operands)
421 << lex->getType() << rex->getType()
422 << lex->getSourceRange() << rex->getSourceRange();
424 This shows that use of the ``Diag`` method: it takes a location (a
425 :ref:`SourceLocation <SourceLocation>` object) and a diagnostic enum value
426 (which matches the name from ``Diagnostic*Kinds.td``). If the diagnostic takes
427 arguments, they are specified with the ``<<`` operator: the first argument
428 becomes ``%0``, the second becomes ``%1``, etc. The diagnostic interface
429 allows you to specify arguments of many different types, including ``int`` and
430 ``unsigned`` for integer arguments, ``const char*`` and ``std::string`` for
431 string arguments, ``DeclarationName`` and ``const IdentifierInfo *`` for names,
432 ``QualType`` for types, etc. ``SourceRange``\ s are also specified with the
433 ``<<`` operator, but do not have a specific ordering requirement.
435 As you can see, adding and producing a diagnostic is pretty straightforward.
436 The hard part is deciding exactly what you need to say to help the user,
437 picking a suitable wording, and providing the information needed to format it
438 correctly. The good news is that the call site that issues a diagnostic should
439 be completely independent of how the diagnostic is formatted and in what
440 language it is rendered.
445 In some cases, the front end emits diagnostics when it is clear that some small
446 change to the source code would fix the problem. For example, a missing
447 semicolon at the end of a statement or a use of deprecated syntax that is
448 easily rewritten into a more modern form. Clang tries very hard to emit the
449 diagnostic and recover gracefully in these and other cases.
451 However, for these cases where the fix is obvious, the diagnostic can be
452 annotated with a hint (referred to as a "fix-it hint") that describes how to
453 change the code referenced by the diagnostic to fix the problem. For example,
454 it might add the missing semicolon at the end of the statement or rewrite the
455 use of a deprecated construct into something more palatable. Here is one such
456 example from the C++ front end, where we warn about the right-shift operator
457 changing meaning from C++98 to C++11:
461 test.cpp:3:7: warning: use of right-shift operator ('>>') in template argument
462 will require parentheses in C++11
467 Here, the fix-it hint is suggesting that parentheses be added, and showing
468 exactly where those parentheses would be inserted into the source code. The
469 fix-it hints themselves describe what changes to make to the source code in an
470 abstract manner, which the text diagnostic printer renders as a line of
471 "insertions" below the caret line. :ref:`Other diagnostic clients
472 <DiagnosticConsumer>` might choose to render the code differently (e.g., as
473 markup inline) or even give the user the ability to automatically fix the
476 Fix-it hints on errors and warnings need to obey these rules:
478 * Since they are automatically applied if ``-Xclang -fixit`` is passed to the
479 driver, they should only be used when it's very likely they match the user's
481 * Clang must recover from errors as if the fix-it had been applied.
482 * Fix-it hints on a warning must not change the meaning of the code.
483 However, a hint may clarify the meaning as intentional, for example by adding
484 parentheses when the precedence of operators isn't obvious.
486 If a fix-it can't obey these rules, put the fix-it on a note. Fix-its on notes
487 are not applied automatically.
489 All fix-it hints are described by the ``FixItHint`` class, instances of which
490 should be attached to the diagnostic using the ``<<`` operator in the same way
491 that highlighted source ranges and arguments are passed to the diagnostic.
492 Fix-it hints can be created with one of three constructors:
494 * ``FixItHint::CreateInsertion(Loc, Code)``
496 Specifies that the given ``Code`` (a string) should be inserted before the
497 source location ``Loc``.
499 * ``FixItHint::CreateRemoval(Range)``
501 Specifies that the code in the given source ``Range`` should be removed.
503 * ``FixItHint::CreateReplacement(Range, Code)``
505 Specifies that the code in the given source ``Range`` should be removed,
506 and replaced with the given ``Code`` string.
508 .. _DiagnosticConsumer:
510 The ``DiagnosticConsumer`` Interface
511 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
513 Once code generates a diagnostic with all of the arguments and the rest of the
514 relevant information, Clang needs to know what to do with it. As previously
515 mentioned, the diagnostic machinery goes through some filtering to map a
516 severity onto a diagnostic level, then (assuming the diagnostic is not mapped
517 to "``Ignore``") it invokes an object that implements the ``DiagnosticConsumer``
518 interface with the information.
520 It is possible to implement this interface in many different ways. For
521 example, the normal Clang ``DiagnosticConsumer`` (named
522 ``TextDiagnosticPrinter``) turns the arguments into strings (according to the
523 various formatting rules), prints out the file/line/column information and the
524 string, then prints out the line of code, the source ranges, and the caret.
525 However, this behavior isn't required.
527 Another implementation of the ``DiagnosticConsumer`` interface is the
528 ``TextDiagnosticBuffer`` class, which is used when Clang is in ``-verify``
529 mode. Instead of formatting and printing out the diagnostics, this
530 implementation just captures and remembers the diagnostics as they fly by.
531 Then ``-verify`` compares the list of produced diagnostics to the list of
532 expected ones. If they disagree, it prints out its own output. Full
533 documentation for the ``-verify`` mode can be found at
534 :ref:`verifying-diagnostics`.
536 There are many other possible implementations of this interface, and this is
537 why we prefer diagnostics to pass down rich structured information in
538 arguments. For example, an HTML output might want declaration names be
539 linkified to where they come from in the source. Another example is that a GUI
540 might let you click on typedefs to expand them. This application would want to
541 pass significantly more information about types through to the GUI than a
542 simple flat string. The interface allows this to happen.
544 .. _internals-diag-translation:
546 Adding Translations to Clang
547 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
549 Not possible yet! Diagnostic strings should be written in UTF-8, the client can
550 translate to the relevant code page if needed. Each translation completely
551 replaces the format string for the diagnostic.
556 The ``SourceLocation`` and ``SourceManager`` classes
557 ----------------------------------------------------
559 Strangely enough, the ``SourceLocation`` class represents a location within the
560 source code of the program. Important design points include:
562 #. ``sizeof(SourceLocation)`` must be extremely small, as these are embedded
563 into many AST nodes and are passed around often. Currently it is 32 bits.
564 #. ``SourceLocation`` must be a simple value object that can be efficiently
566 #. We should be able to represent a source location for any byte of any input
567 file. This includes in the middle of tokens, in whitespace, in trigraphs,
569 #. A ``SourceLocation`` must encode the current ``#include`` stack that was
570 active when the location was processed. For example, if the location
571 corresponds to a token, it should contain the set of ``#include``\ s active
572 when the token was lexed. This allows us to print the ``#include`` stack
574 #. ``SourceLocation`` must be able to describe macro expansions, capturing both
575 the ultimate instantiation point and the source of the original character
578 In practice, the ``SourceLocation`` works together with the ``SourceManager``
579 class to encode two pieces of information about a location: its spelling
580 location and its expansion location. For most tokens, these will be the
581 same. However, for a macro expansion (or tokens that came from a ``_Pragma``
582 directive) these will describe the location of the characters corresponding to
583 the token and the location where the token was used (i.e., the macro
584 expansion point or the location of the ``_Pragma`` itself).
586 The Clang front-end inherently depends on the location of a token being tracked
587 correctly. If it is ever incorrect, the front-end may get confused and die.
588 The reason for this is that the notion of the "spelling" of a ``Token`` in
589 Clang depends on being able to find the original input characters for the
590 token. This concept maps directly to the "spelling location" for the token.
592 ``SourceRange`` and ``CharSourceRange``
593 ---------------------------------------
595 .. mostly taken from https://discourse.llvm.org/t/code-ranges-of-tokens-ast-elements/16893/2
597 Clang represents most source ranges by [first, last], where "first" and "last"
598 each point to the beginning of their respective tokens. For example consider
599 the ``SourceRange`` of the following statement:
606 To map from this representation to a character-based representation, the "last"
607 location needs to be adjusted to point to (or past) the end of that token with
608 either ``Lexer::MeasureTokenLength()`` or ``Lexer::getLocForEndOfToken()``. For
609 the rare cases where character-level source ranges information is needed we use
610 the ``CharSourceRange`` class.
615 The clang Driver and library are documented :doc:`here <DriverInternals>`.
620 Clang supports precompiled headers (:doc:`PCH <PCHInternals>`), which uses a
621 serialized representation of Clang's internal data structures, encoded with the
622 `LLVM bitstream format <https://llvm.org/docs/BitCodeFormat.html>`_.
627 The Frontend library contains functionality useful for building tools on top of
628 the Clang libraries, for example several methods for outputting diagnostics.
633 One of the classes provided by the Frontend library is ``CompilerInvocation``,
634 which holds information that describe current invocation of the Clang ``-cc1``
635 frontend. The information typically comes from the command line constructed by
636 the Clang driver or from clients performing custom initialization. The data
637 structure is split into logical units used by different parts of the compiler,
638 for example ``PreprocessorOptions``, ``LanguageOptions`` or ``CodeGenOptions``.
640 Command Line Interface
641 ----------------------
643 The command line interface of the Clang ``-cc1`` frontend is defined alongside
644 the driver options in ``clang/Driver/Options.td``. The information making up an
645 option definition includes its prefix and name (for example ``-std=``), form and
646 position of the option value, help text, aliases and more. Each option may
647 belong to a certain group and can be marked with zero or more flags. Options
648 accepted by the ``-cc1`` frontend are marked with the ``CC1Option`` flag.
653 Option definitions are processed by the ``-gen-opt-parser-defs`` tablegen
654 backend during early stages of the build. Options are then used for querying an
655 instance ``llvm::opt::ArgList``, a wrapper around the command line arguments.
656 This is done in the Clang driver to construct individual jobs based on the
657 driver arguments and also in the ``CompilerInvocation::CreateFromArgs`` function
658 that parses the ``-cc1`` frontend arguments.
660 Command Line Generation
661 -----------------------
663 Any valid ``CompilerInvocation`` created from a ``-cc1`` command line can be
664 also serialized back into semantically equivalent command line in a
665 deterministic manner. This enables features such as implicitly discovered,
666 explicitly built modules.
669 TODO: Create and link corresponding section in Modules.rst.
671 Adding new Command Line Option
672 ------------------------------
674 When adding a new command line option, the first place of interest is the header
675 file declaring the corresponding options class (e.g. ``CodeGenOptions.h`` for
676 command line option that affects the code generation). Create new member
677 variable for the option value:
681 class CodeGenOptions : public CodeGenOptionsBase {
683 + /// List of dynamic shared object files to be loaded as pass plugins.
684 + std::vector<std::string> PassPlugins;
688 Next, declare the command line interface of the option in the tablegen file
689 ``clang/include/clang/Driver/Options.td``. This is done by instantiating the
690 ``Option`` class (defined in ``llvm/include/llvm/Option/OptParser.td``). The
691 instance is typically created through one of the helper classes that encode the
692 acceptable ways to specify the option value on the command line:
694 * ``Flag`` - the option does not accept any value,
695 * ``Joined`` - the value must immediately follow the option name within the same
697 * ``Separate`` - the value must follow the option name in the next command line
699 * ``JoinedOrSeparate`` - the value can be specified either as ``Joined`` or
701 * ``CommaJoined`` - the values are comma-separated and must immediately follow
702 the option name within the same argument (see ``Wl,`` for an example).
704 The helper classes take a list of acceptable prefixes of the option (e.g.
705 ``"-"``, ``"--"`` or ``"/"``) and the option name:
711 + def fpass_plugin_EQ : Joined<["-"], "fpass-plugin=">;
713 Then, specify additional attributes via mix-ins:
715 * ``HelpText`` holds the text that will be printed besides the option name when
716 the user requests help (e.g. via ``clang --help``).
717 * ``Group`` specifies the "category" of options this option belongs to. This is
718 used by various tools to categorize and sometimes filter options.
719 * ``Flags`` may contain "tags" associated with the option. These may affect how
720 the option is rendered, or if it's hidden in some contexts.
721 * ``Visibility`` should be used to specify the drivers in which a particular
722 option would be available. This attribute will impact tool --help
723 * ``Alias`` denotes that the option is an alias of another option. This may be
724 combined with ``AliasArgs`` that holds the implied value.
730 def fpass_plugin_EQ : Joined<["-"], "fpass-plugin=">,
731 + Group<f_Group>, Visibility<[ClangOption, CC1Option]>,
732 + HelpText<"Load pass plugin from a dynamic shared object file.">;
734 New options are recognized by the ``clang`` driver mode if ``Visibility`` is
735 not specified or contains ``ClangOption``. Options intended for ``clang -cc1``
736 must be explicitly marked with the ``CC1Option`` flag. Flags that specify
737 ``CC1Option`` but not ``ClangOption`` will only be accessible via ``-cc1``.
738 This is similar for other driver modes, such as ``clang-cl`` or ``flang``.
740 Next, parse (or manufacture) the command line arguments in the Clang driver and
741 use them to construct the ``-cc1`` job:
745 void Clang::ConstructJob(const ArgList &Args /*...*/) const {
746 ArgStringList CmdArgs;
749 + for (const Arg *A : Args.filtered(OPT_fpass_plugin_EQ)) {
750 + CmdArgs.push_back(Args.MakeArgString(Twine("-fpass-plugin=") + A->getValue()));
755 The last step is implementing the ``-cc1`` command line argument
756 parsing/generation that initializes/serializes the option class (in our case
757 ``CodeGenOptions``) stored within ``CompilerInvocation``. This can be done
758 automatically by using the marshalling annotations on the option definition:
764 def fpass_plugin_EQ : Joined<["-"], "fpass-plugin=">,
765 Group<f_Group>, Flags<[CC1Option]>,
766 HelpText<"Load pass plugin from a dynamic shared object file.">,
767 + MarshallingInfoStringVector<CodeGenOpts<"PassPlugins">>;
769 Inner workings of the system are introduced in the :ref:`marshalling
770 infrastructure <OptionMarshalling>` section and the available annotations are
771 listed :ref:`here <OptionMarshallingAnnotations>`.
773 In case the marshalling infrastructure does not support the desired semantics,
774 consider simplifying it to fit the existing model. This makes the command line
775 more uniform and reduces the amount of custom, manually written code. Remember
776 that the ``-cc1`` command line interface is intended only for Clang developers,
777 meaning it does not need to mirror the driver interface, maintain backward
778 compatibility or be compatible with GCC.
780 If the option semantics cannot be encoded via marshalling annotations, you can
781 resort to parsing/serializing the command line arguments manually:
785 // CompilerInvocation.cpp
787 static bool ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args /*...*/) {
790 + Opts.PassPlugins = Args.getAllArgValues(OPT_fpass_plugin_EQ);
793 static void GenerateCodeGenArgs(const CodeGenOptions &Opts,
794 SmallVectorImpl<const char *> &Args,
795 CompilerInvocation::StringAllocator SA /*...*/) {
798 + for (const std::string &PassPlugin : Opts.PassPlugins)
799 + GenerateArg(Args, OPT_fpass_plugin_EQ, PassPlugin, SA);
802 Finally, you can specify the argument on the command line:
803 ``clang -fpass-plugin=a -fpass-plugin=b`` and use the new member variable as
808 void EmitAssemblyHelper::EmitAssemblyWithNewPassManager(/*...*/) {
810 + for (auto &PluginFN : CodeGenOpts.PassPlugins)
811 + if (auto PassPlugin = PassPlugin::Load(PluginFN))
812 + PassPlugin->registerPassBuilderCallbacks(PB);
815 .. _OptionMarshalling:
817 Option Marshalling Infrastructure
818 ---------------------------------
820 The option marshalling infrastructure automates the parsing of the Clang
821 ``-cc1`` frontend command line arguments into ``CompilerInvocation`` and their
822 generation from ``CompilerInvocation``. The system replaces lots of repetitive
823 C++ code with simple, declarative tablegen annotations and it's being used for
824 the majority of the ``-cc1`` command line interface. This section provides an
825 overview of the system.
827 **Note:** The marshalling infrastructure is not intended for driver-only
828 options. Only options of the ``-cc1`` frontend need to be marshalled to/from
829 ``CompilerInvocation`` instance.
831 To read and modify contents of ``CompilerInvocation``, the marshalling system
832 uses key paths, which are declared in two steps. First, a tablegen definition
833 for the ``CompilerInvocation`` member is created by inheriting from
840 class LangOpts<string field> : KeyPathAndMacro<"LangOpts->", field, "LANG_"> {}
841 // CompilerInvocation member ^^^^^^^^^^
842 // OPTION_WITH_MARSHALLING prefix ^^^^^
844 The first argument to the parent class is the beginning of the key path that
845 references the ``CompilerInvocation`` member. This argument ends with ``->`` if
846 the member is a pointer type or with ``.`` if it's a value type. The child class
847 takes a single parameter ``field`` that is forwarded as the second argument to
848 the base class. The child class can then be used like so:
849 ``LangOpts<"IgnoreExceptions">``, constructing a key path to the field
850 ``LangOpts->IgnoreExceptions``. The third argument passed to the parent class is
851 a string that the tablegen backend uses as a prefix to the
852 ``OPTION_WITH_MARSHALLING`` macro. Using the key path as a mix-in on an
853 ``Option`` instance instructs the backend to generate the following code:
859 #ifdef LANG_OPTION_WITH_MARSHALLING
860 LANG_OPTION_WITH_MARSHALLING([...], LangOpts->IgnoreExceptions, [...])
861 #endif // LANG_OPTION_WITH_MARSHALLING
863 Such definition can be used used in the function for parsing and generating
868 // clang/lib/Frontend/CompilerInvoation.cpp
870 bool CompilerInvocation::ParseLangArgs(LangOptions *LangOpts, ArgList &Args,
871 DiagnosticsEngine &Diags) {
874 #define LANG_OPTION_WITH_MARSHALLING( \
875 PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
876 HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
877 DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
878 MERGER, EXTRACTOR, TABLE_INDEX) \
879 PARSE_OPTION_WITH_MARSHALLING(Args, Diags, Success, ID, FLAGS, PARAM, \
880 SHOULD_PARSE, KEYPATH, DEFAULT_VALUE, \
881 IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, \
883 #include "clang/Driver/Options.inc"
884 #undef LANG_OPTION_WITH_MARSHALLING
891 void CompilerInvocation::GenerateLangArgs(LangOptions *LangOpts,
892 SmallVectorImpl<const char *> &Args,
893 StringAllocator SA) {
894 #define LANG_OPTION_WITH_MARSHALLING( \
895 PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
896 HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
897 DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
898 MERGER, EXTRACTOR, TABLE_INDEX) \
899 GENERATE_OPTION_WITH_MARSHALLING( \
900 Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE, \
901 IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
902 #include "clang/Driver/Options.inc"
903 #undef LANG_OPTION_WITH_MARSHALLING
908 The ``PARSE_OPTION_WITH_MARSHALLING`` and ``GENERATE_OPTION_WITH_MARSHALLING``
909 macros are defined in ``CompilerInvocation.cpp`` and they implement the generic
910 algorithm for parsing and generating command line arguments.
912 .. _OptionMarshallingAnnotations:
914 Option Marshalling Annotations
915 ------------------------------
917 How does the tablegen backend know what to put in place of ``[...]`` in the
918 generated ``Options.inc``? This is specified by the ``Marshalling`` utilities
919 described below. All of them take a key path argument and possibly other
920 information required for parsing or generating the command line argument.
922 **Note:** The marshalling infrastructure is not intended for driver-only
923 options. Only options of the ``-cc1`` frontend need to be marshalled to/from
924 ``CompilerInvocation`` instance.
928 The key path defaults to ``false`` and is set to ``true`` when the flag is
929 present on command line.
933 def fignore_exceptions : Flag<["-"], "fignore-exceptions">,
934 Visibility<[ClangOption, CC1Option]>,
935 MarshallingInfoFlag<LangOpts<"IgnoreExceptions">>;
939 The key path defaults to ``true`` and is set to ``false`` when the flag is
940 present on command line.
944 def fno_verbose_asm : Flag<["-"], "fno-verbose-asm">,
945 Visibility<[ClangOption, CC1Option]>,
946 MarshallingInfoNegativeFlag<CodeGenOpts<"AsmVerbose">>;
948 **Negative and Positive Flag**
950 The key path defaults to the specified value (``false``, ``true`` or some
951 boolean value that's statically unknown in the tablegen file). Then, the key
952 path is set to the value associated with the flag that appears last on command
957 defm legacy_pass_manager : BoolOption<"f", "legacy-pass-manager",
958 CodeGenOpts<"LegacyPassManager">, DefaultFalse,
959 PosFlag<SetTrue, [], [], "Use the legacy pass manager in LLVM">,
960 NegFlag<SetFalse, [], [], "Use the new pass manager in LLVM">,
961 BothFlags<[], [ClangOption, CC1Option]>>;
963 With most such pair of flags, the ``-cc1`` frontend accepts only the flag that
964 changes the default key path value. The Clang driver is responsible for
965 accepting both and either forwarding the changing flag or discarding the flag
966 that would just set the key path to its default.
968 The first argument to ``BoolOption`` is a prefix that is used to construct the
969 full names of both flags. The positive flag would then be named
970 ``flegacy-pass-manager`` and the negative ``fno-legacy-pass-manager``.
971 ``BoolOption`` also implies the ``-`` prefix for both flags. It's also possible
972 to use ``BoolFOption`` that implies the ``"f"`` prefix and ``Group<f_Group>``.
973 The ``PosFlag`` and ``NegFlag`` classes hold the associated boolean value,
974 arrays of elements passed to the ``Flag`` and ``Visibility`` classes and the
975 help text. The optional ``BothFlags`` class holds arrays of ``Flag`` and
976 ``Visibility`` elements that are common for both the positive and negative flag
977 and their common help text suffix.
981 The key path defaults to the specified string, or an empty one, if omitted. When
982 the option appears on the command line, the argument value is simply copied.
986 def isysroot : JoinedOrSeparate<["-"], "isysroot">,
987 Visibility<[ClangOption, CC1Option, FlangOption]>,
988 MarshallingInfoString<HeaderSearchOpts<"Sysroot">, [{"/"}]>;
992 The key path defaults to an empty ``std::vector<std::string>``. Values specified
993 with each appearance of the option on the command line are appended to the
998 def frewrite_map_file : Separate<["-"], "frewrite-map-file">,
999 Visibility<[ClangOption, CC1Option]>,
1000 MarshallingInfoStringVector<CodeGenOpts<"RewriteMapFiles">>;
1004 The key path defaults to the specified integer value, or ``0`` if omitted. When
1005 the option appears on the command line, its value gets parsed by ``llvm::APInt``
1006 and the result is assigned to the key path on success.
1008 .. code-block:: text
1010 def mstack_probe_size : Joined<["-"], "mstack-probe-size=">,
1011 Visibility<[ClangOption, CC1Option]>,
1012 MarshallingInfoInt<CodeGenOpts<"StackProbeSize">, "4096">;
1016 The key path defaults to the value specified in ``MarshallingInfoEnum`` prefixed
1017 by the contents of ``NormalizedValuesScope`` and ``::``. This ensures correct
1018 reference to an enum case is formed even if the enum resides in different
1019 namespace or is an enum class. If the value present on command line does not
1020 match any of the comma-separated values from ``Values``, an error diagnostics is
1021 issued. Otherwise, the corresponding element from ``NormalizedValues`` at the
1022 same index is assigned to the key path (also correctly scoped). The number of
1023 comma-separated string values and elements of the array within
1024 ``NormalizedValues`` must match.
1026 .. code-block:: text
1028 def mthread_model : Separate<["-"], "mthread-model">,
1029 Visibility<[ClangOption, CC1Option]>,
1030 Values<"posix,single">, NormalizedValues<["POSIX", "Single"]>,
1031 NormalizedValuesScope<"LangOptions::ThreadModelKind">,
1032 MarshallingInfoEnum<LangOpts<"ThreadModel">, "POSIX">;
1035 Intentionally omitting MarshallingInfoBitfieldFlag. It's adding some
1036 complexity to the marshalling infrastructure and might be removed.
1038 It is also possible to define relationships between options.
1042 The key path defaults to the default value from the primary ``Marshalling``
1043 annotation. Then, if any of the elements of ``ImpliedByAnyOf`` evaluate to true,
1044 the key path value is changed to the specified value or ``true`` if missing.
1045 Finally, the command line is parsed according to the primary annotation.
1047 .. code-block:: text
1049 def fms_extensions : Flag<["-"], "fms-extensions">,
1050 Visibility<[ClangOption, CC1Option]>,
1051 MarshallingInfoFlag<LangOpts<"MicrosoftExt">>,
1052 ImpliedByAnyOf<[fms_compatibility.KeyPath], "true">;
1056 The option is parsed only if the expression in ``ShouldParseIf`` evaluates to
1059 .. code-block:: text
1061 def fopenmp_enable_irbuilder : Flag<["-"], "fopenmp-enable-irbuilder">,
1062 Visibility<[ClangOption, CC1Option]>,
1063 MarshallingInfoFlag<LangOpts<"OpenMPIRBuilder">>,
1064 ShouldParseIf<fopenmp.KeyPath>;
1066 The Lexer and Preprocessor Library
1067 ==================================
1069 The Lexer library contains several tightly-connected classes that are involved
1070 with the nasty process of lexing and preprocessing C source code. The main
1071 interface to this library for outside clients is the large ``Preprocessor``
1072 class. It contains the various pieces of state that are required to coherently
1073 read tokens out of a translation unit.
1075 The core interface to the ``Preprocessor`` object (once it is set up) is the
1076 ``Preprocessor::Lex`` method, which returns the next :ref:`Token <Token>` from
1077 the preprocessor stream. There are two types of token providers that the
1078 preprocessor is capable of reading from: a buffer lexer (provided by the
1079 :ref:`Lexer <Lexer>` class) and a buffered token stream (provided by the
1080 :ref:`TokenLexer <TokenLexer>` class).
1087 The ``Token`` class is used to represent a single lexed token. Tokens are
1088 intended to be used by the lexer/preprocess and parser libraries, but are not
1089 intended to live beyond them (for example, they should not live in the ASTs).
1091 Tokens most often live on the stack (or some other location that is efficient
1092 to access) as the parser is running, but occasionally do get buffered up. For
1093 example, macro definitions are stored as a series of tokens, and the C++
1094 front-end periodically needs to buffer tokens up for tentative parsing and
1095 various pieces of look-ahead. As such, the size of a ``Token`` matters. On a
1096 32-bit system, ``sizeof(Token)`` is currently 16 bytes.
1098 Tokens occur in two forms: :ref:`annotation tokens <AnnotationToken>` and
1099 normal tokens. Normal tokens are those returned by the lexer, annotation
1100 tokens represent semantic information and are produced by the parser, replacing
1101 normal tokens in the token stream. Normal tokens contain the following
1104 * **A SourceLocation** --- This indicates the location of the start of the
1107 * **A length** --- This stores the length of the token as stored in the
1108 ``SourceBuffer``. For tokens that include them, this length includes
1109 trigraphs and escaped newlines which are ignored by later phases of the
1110 compiler. By pointing into the original source buffer, it is always possible
1111 to get the original spelling of a token completely accurately.
1113 * **IdentifierInfo** --- If a token takes the form of an identifier, and if
1114 identifier lookup was enabled when the token was lexed (e.g., the lexer was
1115 not reading in "raw" mode) this contains a pointer to the unique hash value
1116 for the identifier. Because the lookup happens before keyword
1117 identification, this field is set even for language keywords like "``for``".
1119 * **TokenKind** --- This indicates the kind of token as classified by the
1120 lexer. This includes things like ``tok::starequal`` (for the "``*=``"
1121 operator), ``tok::ampamp`` for the "``&&``" token, and keyword values (e.g.,
1122 ``tok::kw_for``) for identifiers that correspond to keywords. Note that
1123 some tokens can be spelled multiple ways. For example, C++ supports
1124 "operator keywords", where things like "``and``" are treated exactly like the
1125 "``&&``" operator. In these cases, the kind value is set to ``tok::ampamp``,
1126 which is good for the parser, which doesn't have to consider both forms. For
1127 something that cares about which form is used (e.g., the preprocessor
1128 "stringize" operator) the spelling indicates the original form.
1130 * **Flags** --- There are currently four flags tracked by the
1131 lexer/preprocessor system on a per-token basis:
1133 #. **StartOfLine** --- This was the first token that occurred on its input
1135 #. **LeadingSpace** --- There was a space character either immediately before
1136 the token or transitively before the token as it was expanded through a
1137 macro. The definition of this flag is very closely defined by the
1138 stringizing requirements of the preprocessor.
1139 #. **DisableExpand** --- This flag is used internally to the preprocessor to
1140 represent identifier tokens which have macro expansion disabled. This
1141 prevents them from being considered as candidates for macro expansion ever
1143 #. **NeedsCleaning** --- This flag is set if the original spelling for the
1144 token includes a trigraph or escaped newline. Since this is uncommon,
1145 many pieces of code can fast-path on tokens that did not need cleaning.
1147 One interesting (and somewhat unusual) aspect of normal tokens is that they
1148 don't contain any semantic information about the lexed value. For example, if
1149 the token was a pp-number token, we do not represent the value of the number
1150 that was lexed (this is left for later pieces of code to decide).
1151 Additionally, the lexer library has no notion of typedef names vs variable
1152 names: both are returned as identifiers, and the parser is left to decide
1153 whether a specific identifier is a typedef or a variable (tracking this
1154 requires scope information among other things). The parser can do this
1155 translation by replacing tokens returned by the preprocessor with "Annotation
1158 .. _AnnotationToken:
1163 Annotation tokens are tokens that are synthesized by the parser and injected
1164 into the preprocessor's token stream (replacing existing tokens) to record
1165 semantic information found by the parser. For example, if "``foo``" is found
1166 to be a typedef, the "``foo``" ``tok::identifier`` token is replaced with an
1167 ``tok::annot_typename``. This is useful for a couple of reasons: 1) this makes
1168 it easy to handle qualified type names (e.g., "``foo::bar::baz<42>::t``") in
1169 C++ as a single "token" in the parser. 2) if the parser backtracks, the
1170 reparse does not need to redo semantic analysis to determine whether a token
1171 sequence is a variable, type, template, etc.
1173 Annotation tokens are created by the parser and reinjected into the parser's
1174 token stream (when backtracking is enabled). Because they can only exist in
1175 tokens that the preprocessor-proper is done with, it doesn't need to keep
1176 around flags like "start of line" that the preprocessor uses to do its job.
1177 Additionally, an annotation token may "cover" a sequence of preprocessor tokens
1178 (e.g., "``a::b::c``" is five preprocessor tokens). As such, the valid fields
1179 of an annotation token are different than the fields for a normal token (but
1180 they are multiplexed into the normal ``Token`` fields):
1182 * **SourceLocation "Location"** --- The ``SourceLocation`` for the annotation
1183 token indicates the first token replaced by the annotation token. In the
1184 example above, it would be the location of the "``a``" identifier.
1185 * **SourceLocation "AnnotationEndLoc"** --- This holds the location of the last
1186 token replaced with the annotation token. In the example above, it would be
1187 the location of the "``c``" identifier.
1188 * **void* "AnnotationValue"** --- This contains an opaque object that the
1189 parser gets from ``Sema``. The parser merely preserves the information for
1190 ``Sema`` to later interpret based on the annotation token kind.
1191 * **TokenKind "Kind"** --- This indicates the kind of Annotation token this is.
1192 See below for the different valid kinds.
1194 Annotation tokens currently come in three kinds:
1196 #. **tok::annot_typename**: This annotation token represents a resolved
1197 typename token that is potentially qualified. The ``AnnotationValue`` field
1198 contains the ``QualType`` returned by ``Sema::getTypeName()``, possibly with
1199 source location information attached.
1200 #. **tok::annot_cxxscope**: This annotation token represents a C++ scope
1201 specifier, such as "``A::B::``". This corresponds to the grammar
1202 productions "*::*" and "*:: [opt] nested-name-specifier*". The
1203 ``AnnotationValue`` pointer is a ``NestedNameSpecifier *`` returned by the
1204 ``Sema::ActOnCXXGlobalScopeSpecifier`` and
1205 ``Sema::ActOnCXXNestedNameSpecifier`` callbacks.
1206 #. **tok::annot_template_id**: This annotation token represents a C++
1207 template-id such as "``foo<int, 4>``", where "``foo``" is the name of a
1208 template. The ``AnnotationValue`` pointer is a pointer to a ``malloc``'d
1209 ``TemplateIdAnnotation`` object. Depending on the context, a parsed
1210 template-id that names a type might become a typename annotation token (if
1211 all we care about is the named type, e.g., because it occurs in a type
1212 specifier) or might remain a template-id token (if we want to retain more
1213 source location information or produce a new type, e.g., in a declaration of
1214 a class template specialization). template-id annotation tokens that refer
1215 to a type can be "upgraded" to typename annotation tokens by the parser.
1217 As mentioned above, annotation tokens are not returned by the preprocessor,
1218 they are formed on demand by the parser. This means that the parser has to be
1219 aware of cases where an annotation could occur and form it where appropriate.
1220 This is somewhat similar to how the parser handles Translation Phase 6 of C99:
1221 String Concatenation (see C99 5.1.1.2). In the case of string concatenation,
1222 the preprocessor just returns distinct ``tok::string_literal`` and
1223 ``tok::wide_string_literal`` tokens and the parser eats a sequence of them
1224 wherever the grammar indicates that a string literal can occur.
1226 In order to do this, whenever the parser expects a ``tok::identifier`` or
1227 ``tok::coloncolon``, it should call the ``TryAnnotateTypeOrScopeToken`` or
1228 ``TryAnnotateCXXScopeToken`` methods to form the annotation token. These
1229 methods will maximally form the specified annotation tokens and replace the
1230 current token with them, if applicable. If the current tokens is not valid for
1231 an annotation token, it will remain an identifier or "``::``" token.
1238 The ``Lexer`` class provides the mechanics of lexing tokens out of a source
1239 buffer and deciding what they mean. The ``Lexer`` is complicated by the fact
1240 that it operates on raw buffers that have not had spelling eliminated (this is
1241 a necessity to get decent performance), but this is countered with careful
1242 coding as well as standard performance techniques (for example, the comment
1243 handling code is vectorized on X86 and PowerPC hosts).
1245 The lexer has a couple of interesting modal features:
1247 * The lexer can operate in "raw" mode. This mode has several features that
1248 make it possible to quickly lex the file (e.g., it stops identifier lookup,
1249 doesn't specially handle preprocessor tokens, handles EOF differently, etc).
1250 This mode is used for lexing within an "``#if 0``" block, for example.
1251 * The lexer can capture and return comments as tokens. This is required to
1252 support the ``-C`` preprocessor mode, which passes comments through, and is
1253 used by the diagnostic checker to identifier expect-error annotations.
1254 * The lexer can be in ``ParsingFilename`` mode, which happens when
1255 preprocessing after reading a ``#include`` directive. This mode changes the
1256 parsing of "``<``" to return an "angled string" instead of a bunch of tokens
1257 for each thing within the filename.
1258 * When parsing a preprocessor directive (after "``#``") the
1259 ``ParsingPreprocessorDirective`` mode is entered. This changes the parser to
1260 return EOD at a newline.
1261 * The ``Lexer`` uses a ``LangOptions`` object to know whether trigraphs are
1262 enabled, whether C++ or ObjC keywords are recognized, etc.
1264 In addition to these modes, the lexer keeps track of a couple of other features
1265 that are local to a lexed buffer, which change as the buffer is lexed:
1267 * The ``Lexer`` uses ``BufferPtr`` to keep track of the current character being
1269 * The ``Lexer`` uses ``IsAtStartOfLine`` to keep track of whether the next
1270 lexed token will start with its "start of line" bit set.
1271 * The ``Lexer`` keeps track of the current "``#if``" directives that are active
1272 (which can be nested).
1273 * The ``Lexer`` keeps track of an :ref:`MultipleIncludeOpt
1274 <MultipleIncludeOpt>` object, which is used to detect whether the buffer uses
1275 the standard "``#ifndef XX`` / ``#define XX``" idiom to prevent multiple
1276 inclusion. If a buffer does, subsequent includes can be ignored if the
1277 "``XX``" macro is defined.
1281 The ``TokenLexer`` class
1282 ------------------------
1284 The ``TokenLexer`` class is a token provider that returns tokens from a list of
1285 tokens that came from somewhere else. It typically used for two things: 1)
1286 returning tokens from a macro definition as it is being expanded 2) returning
1287 tokens from an arbitrary buffer of tokens. The later use is used by
1288 ``_Pragma`` and will most likely be used to handle unbounded look-ahead for the
1291 .. _MultipleIncludeOpt:
1293 The ``MultipleIncludeOpt`` class
1294 --------------------------------
1296 The ``MultipleIncludeOpt`` class implements a really simple little state
1297 machine that is used to detect the standard "``#ifndef XX`` / ``#define XX``"
1298 idiom that people typically use to prevent multiple inclusion of headers. If a
1299 buffer uses this idiom and is subsequently ``#include``'d, the preprocessor can
1300 simply check to see whether the guarding condition is defined or not. If so,
1301 the preprocessor can completely ignore the include of the header.
1308 This library contains a recursive-descent parser that polls tokens from the
1309 preprocessor and notifies a client of the parsing progress.
1311 Historically, the parser used to talk to an abstract ``Action`` interface that
1312 had virtual methods for parse events, for example ``ActOnBinOp()``. When Clang
1313 grew C++ support, the parser stopped supporting general ``Action`` clients --
1314 it now always talks to the :ref:`Sema library <Sema>`. However, the Parser
1315 still accesses AST objects only through opaque types like ``ExprResult`` and
1316 ``StmtResult``. Only :ref:`Sema <Sema>` looks at the AST node contents of these
1332 Clang AST nodes (types, declarations, statements, expressions, and so on) are
1333 generally designed to be immutable once created. This provides a number of key
1336 * Canonicalization of the "meaning" of nodes is possible as soon as the nodes
1337 are created, and is not invalidated by later addition of more information.
1338 For example, we :ref:`canonicalize types <CanonicalType>`, and use a
1339 canonicalized representation of expressions when determining whether two
1340 function template declarations involving dependent expressions declare the
1342 * AST nodes can be reused when they have the same meaning. For example, we
1343 reuse ``Type`` nodes when representing the same type (but maintain separate
1344 ``TypeLoc``\s for each instance where a type is written), and we reuse
1345 non-dependent ``Stmt`` and ``Expr`` nodes across instantiations of a
1347 * Serialization and deserialization of the AST to/from AST files is simpler:
1348 we do not need to track modifications made to AST nodes imported from AST
1349 files and serialize separate "update records".
1351 There are unfortunately exceptions to this general approach, such as:
1353 * The first declaration of a redeclarable entity maintains a pointer to the
1354 most recent declaration of that entity, which naturally needs to change as
1355 more declarations are parsed.
1356 * Name lookup tables in declaration contexts change after the namespace
1357 declaration is formed.
1358 * We attempt to maintain only a single declaration for an instantiation of a
1359 template, rather than having distinct declarations for an instantiation of
1360 the declaration versus the definition, so template instantiation often
1361 updates parts of existing declarations.
1362 * Some parts of declarations are required to be instantiated separately (this
1363 includes default arguments and exception specifications), and such
1364 instantiations update the existing declaration.
1366 These cases tend to be fragile; mutable AST state should be avoided where
1369 As a consequence of this design principle, we typically do not provide setters
1370 for AST state. (Some are provided for short-term modifications intended to be
1371 used immediately after an AST node is created and before it's "published" as
1372 part of the complete AST, or where language semantics require after-the-fact
1378 The AST intends to provide a representation of the program that is faithful to
1379 the original source. We intend for it to be possible to write refactoring tools
1380 using only information stored in, or easily reconstructible from, the Clang AST.
1381 This means that the AST representation should either not desugar source-level
1382 constructs to simpler forms, or -- where made necessary by language semantics
1383 or a clear engineering tradeoff -- should desugar minimally and wrap the result
1384 in a construct representing the original source form.
1386 For example, ``CXXForRangeStmt`` directly represents the syntactic form of a
1387 range-based for statement, but also holds a semantic representation of the
1388 range declaration and iterator declarations. It does not contain a
1389 fully-desugared ``ForStmt``, however.
1391 Some AST nodes (for example, ``ParenExpr``) represent only syntax, and others
1392 (for example, ``ImplicitCastExpr``) represent only semantics, but most nodes
1393 will represent a combination of syntax and associated semantics. Inheritance
1394 is typically used when representing different (but related) syntaxes for nodes
1395 with the same or similar semantics.
1399 The ``Type`` class and its subclasses
1400 -------------------------------------
1402 The ``Type`` class (and its subclasses) are an important part of the AST.
1403 Types are accessed through the ``ASTContext`` class, which implicitly creates
1404 and uniques them as they are needed. Types have a couple of non-obvious
1405 features: 1) they do not capture type qualifiers like ``const`` or ``volatile``
1406 (see :ref:`QualType <QualType>`), and 2) they implicitly capture typedef
1407 information. Once created, types are immutable (unlike decls).
1409 Typedefs in C make semantic analysis a bit more complex than it would be without
1410 them. The issue is that we want to capture typedef information and represent it
1411 in the AST perfectly, but the semantics of operations need to "see through"
1412 typedefs. For example, consider this code:
1426 The code above is illegal, and thus we expect there to be diagnostics emitted
1427 on the annotated lines. In this example, we expect to get:
1429 .. code-block:: text
1431 test.c:6:1: error: indirection requires pointer operand ('foo' invalid)
1434 test.c:7:1: error: indirection requires pointer operand ('foo' invalid)
1437 test.c:8:1: error: indirection requires pointer operand ('foo' invalid)
1441 While this example is somewhat silly, it illustrates the point: we want to
1442 retain typedef information where possible, so that we can emit errors about
1443 "``std::string``" instead of "``std::basic_string<char, std:...``". Doing this
1444 requires properly keeping typedef information (for example, the type of ``X``
1445 is "``foo``", not "``int``"), and requires properly propagating it through the
1446 various operators (for example, the type of ``*Y`` is "``foo``", not
1447 "``int``"). In order to retain this information, the type of these expressions
1448 is an instance of the ``TypedefType`` class, which indicates that the type of
1449 these expressions is a typedef for "``foo``".
1451 Representing types like this is great for diagnostics, because the
1452 user-specified type is always immediately available. There are two problems
1453 with this: first, various semantic checks need to make judgements about the
1454 *actual structure* of a type, ignoring typedefs. Second, we need an efficient
1455 way to query whether two types are structurally identical to each other,
1456 ignoring typedefs. The solution to both of these problems is the idea of
1464 Every instance of the ``Type`` class contains a canonical type pointer. For
1465 simple types with no typedefs involved (e.g., "``int``", "``int*``",
1466 "``int**``"), the type just points to itself. For types that have a typedef
1467 somewhere in their structure (e.g., "``foo``", "``foo*``", "``foo**``",
1468 "``bar``"), the canonical type pointer points to their structurally equivalent
1469 type without any typedefs (e.g., "``int``", "``int*``", "``int**``", and
1470 "``int*``" respectively).
1472 This design provides a constant time operation (dereferencing the canonical type
1473 pointer) that gives us access to the structure of types. For example, we can
1474 trivially tell that "``bar``" and "``foo*``" are the same type by dereferencing
1475 their canonical type pointers and doing a pointer comparison (they both point
1476 to the single "``int*``" type).
1478 Canonical types and typedef types bring up some complexities that must be
1479 carefully managed. Specifically, the ``isa``/``cast``/``dyn_cast`` operators
1480 generally shouldn't be used in code that is inspecting the AST. For example,
1481 when type checking the indirection operator (unary "``*``" on a pointer), the
1482 type checker must verify that the operand has a pointer type. It would not be
1483 correct to check that with "``isa<PointerType>(SubExpr->getType())``", because
1484 this predicate would fail if the subexpression had a typedef type.
1486 The solution to this problem are a set of helper methods on ``Type``, used to
1487 check their properties. In this case, it would be correct to use
1488 "``SubExpr->getType()->isPointerType()``" to do the check. This predicate will
1489 return true if the *canonical type is a pointer*, which is true any time the
1490 type is structurally a pointer type. The only hard part here is remembering
1491 not to use the ``isa``/``cast``/``dyn_cast`` operations.
1493 The second problem we face is how to get access to the pointer type once we
1494 know it exists. To continue the example, the result type of the indirection
1495 operator is the pointee type of the subexpression. In order to determine the
1496 type, we need to get the instance of ``PointerType`` that best captures the
1497 typedef information in the program. If the type of the expression is literally
1498 a ``PointerType``, we can return that, otherwise we have to dig through the
1499 typedefs to find the pointer type. For example, if the subexpression had type
1500 "``foo*``", we could return that type as the result. If the subexpression had
1501 type "``bar``", we want to return "``foo*``" (note that we do *not* want
1502 "``int*``"). In order to provide all of this, ``Type`` has a
1503 ``getAsPointerType()`` method that checks whether the type is structurally a
1504 ``PointerType`` and, if so, returns the best one. If not, it returns a null
1507 This structure is somewhat mystical, but after meditating on it, it will make
1512 The ``QualType`` class
1513 ----------------------
1515 The ``QualType`` class is designed as a trivial value class that is small,
1516 passed by-value and is efficient to query. The idea of ``QualType`` is that it
1517 stores the type qualifiers (``const``, ``volatile``, ``restrict``, plus some
1518 extended qualifiers required by language extensions) separately from the types
1519 themselves. ``QualType`` is conceptually a pair of "``Type*``" and the bits
1520 for these type qualifiers.
1522 By storing the type qualifiers as bits in the conceptual pair, it is extremely
1523 efficient to get the set of qualifiers on a ``QualType`` (just return the field
1524 of the pair), add a type qualifier (which is a trivial constant-time operation
1525 that sets a bit), and remove one or more type qualifiers (just return a
1526 ``QualType`` with the bitfield set to empty).
1528 Further, because the bits are stored outside of the type itself, we do not need
1529 to create duplicates of types with different sets of qualifiers (i.e. there is
1530 only a single heap allocated "``int``" type: "``const int``" and "``volatile
1531 const int``" both point to the same heap allocated "``int``" type). This
1532 reduces the heap size used to represent bits and also means we do not have to
1533 consider qualifiers when uniquing types (:ref:`Type <Type>` does not even
1534 contain qualifiers).
1536 In practice, the two most common type qualifiers (``const`` and ``restrict``)
1537 are stored in the low bits of the pointer to the ``Type`` object, together with
1538 a flag indicating whether extended qualifiers are present (which must be
1539 heap-allocated). This means that ``QualType`` is exactly the same size as a
1542 .. _DeclarationName:
1547 The ``DeclarationName`` class represents the name of a declaration in Clang.
1548 Declarations in the C family of languages can take several different forms.
1549 Most declarations are named by simple identifiers, e.g., "``f``" and "``x``" in
1550 the function declaration ``f(int x)``. In C++, declaration names can also name
1551 class constructors ("``Class``" in ``struct Class { Class(); }``), class
1552 destructors ("``~Class``"), overloaded operator names ("``operator+``"), and
1553 conversion functions ("``operator void const *``"). In Objective-C,
1554 declaration names can refer to the names of Objective-C methods, which involve
1555 the method name and the parameters, collectively called a *selector*, e.g.,
1556 "``setWidth:height:``". Since all of these kinds of entities --- variables,
1557 functions, Objective-C methods, C++ constructors, destructors, and operators
1558 --- are represented as subclasses of Clang's common ``NamedDecl`` class,
1559 ``DeclarationName`` is designed to efficiently represent any kind of name.
1561 Given a ``DeclarationName`` ``N``, ``N.getNameKind()`` will produce a value
1562 that describes what kind of name ``N`` stores. There are 10 options (all of
1563 the names are inside the ``DeclarationName`` class).
1567 The name is a simple identifier. Use ``N.getAsIdentifierInfo()`` to retrieve
1568 the corresponding ``IdentifierInfo*`` pointing to the actual identifier.
1570 ``ObjCZeroArgSelector``, ``ObjCOneArgSelector``, ``ObjCMultiArgSelector``
1572 The name is an Objective-C selector, which can be retrieved as a ``Selector``
1573 instance via ``N.getObjCSelector()``. The three possible name kinds for
1574 Objective-C reflect an optimization within the ``DeclarationName`` class:
1575 both zero- and one-argument selectors are stored as a masked
1576 ``IdentifierInfo`` pointer, and therefore require very little space, since
1577 zero- and one-argument selectors are far more common than multi-argument
1578 selectors (which use a different structure).
1580 ``CXXConstructorName``
1582 The name is a C++ constructor name. Use ``N.getCXXNameType()`` to retrieve
1583 the :ref:`type <QualType>` that this constructor is meant to construct. The
1584 type is always the canonical type, since all constructors for a given type
1587 ``CXXDestructorName``
1589 The name is a C++ destructor name. Use ``N.getCXXNameType()`` to retrieve
1590 the :ref:`type <QualType>` whose destructor is being named. This type is
1591 always a canonical type.
1593 ``CXXConversionFunctionName``
1595 The name is a C++ conversion function. Conversion functions are named
1596 according to the type they convert to, e.g., "``operator void const *``".
1597 Use ``N.getCXXNameType()`` to retrieve the type that this conversion function
1598 converts to. This type is always a canonical type.
1602 The name is a C++ overloaded operator name. Overloaded operators are named
1603 according to their spelling, e.g., "``operator+``" or "``operator new []``".
1604 Use ``N.getCXXOverloadedOperator()`` to retrieve the overloaded operator (a
1605 value of type ``OverloadedOperatorKind``).
1607 ``CXXLiteralOperatorName``
1609 The name is a C++11 user defined literal operator. User defined
1610 Literal operators are named according to the suffix they define,
1611 e.g., "``_foo``" for "``operator "" _foo``". Use
1612 ``N.getCXXLiteralIdentifier()`` to retrieve the corresponding
1613 ``IdentifierInfo*`` pointing to the identifier.
1615 ``CXXUsingDirective``
1617 The name is a C++ using directive. Using directives are not really
1618 NamedDecls, in that they all have the same name, but they are
1619 implemented as such in order to store them in DeclContext
1622 ``DeclarationName``\ s are cheap to create, copy, and compare. They require
1623 only a single pointer's worth of storage in the common cases (identifiers,
1624 zero- and one-argument Objective-C selectors) and use dense, uniqued storage
1625 for the other kinds of names. Two ``DeclarationName``\ s can be compared for
1626 equality (``==``, ``!=``) using a simple bitwise comparison, can be ordered
1627 with ``<``, ``>``, ``<=``, and ``>=`` (which provide a lexicographical ordering
1628 for normal identifiers but an unspecified ordering for other kinds of names),
1629 and can be placed into LLVM ``DenseMap``\ s and ``DenseSet``\ s.
1631 ``DeclarationName`` instances can be created in different ways depending on
1632 what kind of name the instance will store. Normal identifiers
1633 (``IdentifierInfo`` pointers) and Objective-C selectors (``Selector``) can be
1634 implicitly converted to ``DeclarationNames``. Names for C++ constructors,
1635 destructors, conversion functions, and overloaded operators can be retrieved
1636 from the ``DeclarationNameTable``, an instance of which is available as
1637 ``ASTContext::DeclarationNames``. The member functions
1638 ``getCXXConstructorName``, ``getCXXDestructorName``,
1639 ``getCXXConversionFunctionName``, and ``getCXXOperatorName``, respectively,
1640 return ``DeclarationName`` instances for the four kinds of C++ special function
1645 Declaration contexts
1646 --------------------
1648 Every declaration in a program exists within some *declaration context*, such
1649 as a translation unit, namespace, class, or function. Declaration contexts in
1650 Clang are represented by the ``DeclContext`` class, from which the various
1651 declaration-context AST nodes (``TranslationUnitDecl``, ``NamespaceDecl``,
1652 ``RecordDecl``, ``FunctionDecl``, etc.) will derive. The ``DeclContext`` class
1653 provides several facilities common to each declaration context:
1655 Source-centric vs. Semantics-centric View of Declarations
1657 ``DeclContext`` provides two views of the declarations stored within a
1658 declaration context. The source-centric view accurately represents the
1659 program source code as written, including multiple declarations of entities
1660 where present (see the section :ref:`Redeclarations and Overloads
1661 <Redeclarations>`), while the semantics-centric view represents the program
1662 semantics. The two views are kept synchronized by semantic analysis while
1663 the ASTs are being constructed.
1665 Storage of declarations within that context
1667 Every declaration context can contain some number of declarations. For
1668 example, a C++ class (represented by ``RecordDecl``) contains various member
1669 functions, fields, nested types, and so on. All of these declarations will
1670 be stored within the ``DeclContext``, and one can iterate over the
1671 declarations via [``DeclContext::decls_begin()``,
1672 ``DeclContext::decls_end()``). This mechanism provides the source-centric
1673 view of declarations in the context.
1675 Lookup of declarations within that context
1677 The ``DeclContext`` structure provides efficient name lookup for names within
1678 that declaration context. For example, if ``N`` is a namespace we can look
1679 for the name ``N::f`` using ``DeclContext::lookup``. The lookup itself is
1680 based on a lazily-constructed array (for declaration contexts with a small
1681 number of declarations) or hash table (for declaration contexts with more
1682 declarations). The lookup operation provides the semantics-centric view of
1683 the declarations in the context.
1685 Ownership of declarations
1687 The ``DeclContext`` owns all of the declarations that were declared within
1688 its declaration context, and is responsible for the management of their
1689 memory as well as their (de-)serialization.
1691 All declarations are stored within a declaration context, and one can query
1692 information about the context in which each declaration lives. One can
1693 retrieve the ``DeclContext`` that contains a particular ``Decl`` using
1694 ``Decl::getDeclContext``. However, see the section
1695 :ref:`LexicalAndSemanticContexts` for more information about how to interpret
1696 this context information.
1700 Redeclarations and Overloads
1701 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1703 Within a translation unit, it is common for an entity to be declared several
1704 times. For example, we might declare a function "``f``" and then later
1705 re-declare it as part of an inlined definition:
1709 void f(int x, int y, int z = 1);
1711 inline void f(int x, int y, int z) { /* ... */ }
1713 The representation of "``f``" differs in the source-centric and
1714 semantics-centric views of a declaration context. In the source-centric view,
1715 all redeclarations will be present, in the order they occurred in the source
1716 code, making this view suitable for clients that wish to see the structure of
1717 the source code. In the semantics-centric view, only the most recent "``f``"
1718 will be found by the lookup, since it effectively replaces the first
1719 declaration of "``f``".
1721 (Note that because ``f`` can be redeclared at block scope, or in a friend
1722 declaration, etc. it is possible that the declaration of ``f`` found by name
1723 lookup will not be the most recent one.)
1725 In the semantics-centric view, overloading of functions is represented
1726 explicitly. For example, given two declarations of a function "``g``" that are
1734 the ``DeclContext::lookup`` operation will return a
1735 ``DeclContext::lookup_result`` that contains a range of iterators over
1736 declarations of "``g``". Clients that perform semantic analysis on a program
1737 that is not concerned with the actual source code will primarily use this
1738 semantics-centric view.
1740 .. _LexicalAndSemanticContexts:
1742 Lexical and Semantic Contexts
1743 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1745 Each declaration has two potentially different declaration contexts: a
1746 *lexical* context, which corresponds to the source-centric view of the
1747 declaration context, and a *semantic* context, which corresponds to the
1748 semantics-centric view. The lexical context is accessible via
1749 ``Decl::getLexicalDeclContext`` while the semantic context is accessible via
1750 ``Decl::getDeclContext``, both of which return ``DeclContext`` pointers. For
1751 most declarations, the two contexts are identical. For example:
1760 Here, the semantic and lexical contexts of ``X::f`` are the ``DeclContext``
1761 associated with the class ``X`` (itself stored as a ``RecordDecl`` AST node).
1762 However, we can now define ``X::f`` out-of-line:
1766 void X::f(int x = 17) { /* ... */ }
1768 This definition of "``f``" has different lexical and semantic contexts. The
1769 lexical context corresponds to the declaration context in which the actual
1770 declaration occurred in the source code, e.g., the translation unit containing
1771 ``X``. Thus, this declaration of ``X::f`` can be found by traversing the
1772 declarations provided by [``decls_begin()``, ``decls_end()``) in the
1775 The semantic context of ``X::f`` corresponds to the class ``X``, since this
1776 member function is (semantically) a member of ``X``. Lookup of the name ``f``
1777 into the ``DeclContext`` associated with ``X`` will then return the definition
1778 of ``X::f`` (including information about the default argument).
1780 Transparent Declaration Contexts
1781 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1783 In C and C++, there are several contexts in which names that are logically
1784 declared inside another declaration will actually "leak" out into the enclosing
1785 scope from the perspective of name lookup. The most obvious instance of this
1786 behavior is in enumeration types, e.g.,
1796 Here, ``Color`` is an enumeration, which is a declaration context that contains
1797 the enumerators ``Red``, ``Green``, and ``Blue``. Thus, traversing the list of
1798 declarations contained in the enumeration ``Color`` will yield ``Red``,
1799 ``Green``, and ``Blue``. However, outside of the scope of ``Color`` one can
1800 name the enumerator ``Red`` without qualifying the name, e.g.,
1806 There are other entities in C++ that provide similar behavior. For example,
1807 linkage specifications that use curly braces:
1815 // f and g are visible here
1817 For source-level accuracy, we treat the linkage specification and enumeration
1818 type as a declaration context in which its enclosed declarations ("``Red``",
1819 "``Green``", and "``Blue``"; "``f``" and "``g``") are declared. However, these
1820 declarations are visible outside of the scope of the declaration context.
1822 These language features (and several others, described below) have roughly the
1823 same set of requirements: declarations are declared within a particular lexical
1824 context, but the declarations are also found via name lookup in scopes
1825 enclosing the declaration itself. This feature is implemented via
1826 *transparent* declaration contexts (see
1827 ``DeclContext::isTransparentContext()``), whose declarations are visible in the
1828 nearest enclosing non-transparent declaration context. This means that the
1829 lexical context of the declaration (e.g., an enumerator) will be the
1830 transparent ``DeclContext`` itself, as will the semantic context, but the
1831 declaration will be visible in every outer context up to and including the
1832 first non-transparent declaration context (since transparent declaration
1833 contexts can be nested).
1835 The transparent ``DeclContext``\ s are:
1837 * Enumerations (but not C++11 "scoped enumerations"):
1846 // Red, Green, and Blue are in scope
1848 * C++ linkage specifications:
1856 // f and g are in scope
1858 * Anonymous unions and structs:
1862 struct LookupTable {
1865 std::vector<Item> *Vector;
1866 std::set<Item> *Set;
1871 LT.Vector = 0; // Okay: finds Vector inside the unnamed union
1873 * C++11 inline namespaces:
1878 inline namespace debug {
1882 mylib::X *xp; // okay: mylib::X refers to mylib::debug::X
1884 .. _MultiDeclContext:
1886 Multiply-Defined Declaration Contexts
1887 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1889 C++ namespaces have the interesting property that
1890 the namespace can be defined multiple times, and the declarations provided by
1891 each namespace definition are effectively merged (from the semantic point of
1892 view). For example, the following two code snippets are semantically
1911 In Clang's representation, the source-centric view of declaration contexts will
1912 actually have two separate ``NamespaceDecl`` nodes in Snippet #1, each of which
1913 is a declaration context that contains a single declaration of "``f``".
1914 However, the semantics-centric view provided by name lookup into the namespace
1915 ``N`` for "``f``" will return a ``DeclContext::lookup_result`` that contains a
1916 range of iterators over declarations of "``f``".
1918 ``DeclContext`` manages multiply-defined declaration contexts internally. The
1919 function ``DeclContext::getPrimaryContext`` retrieves the "primary" context for
1920 a given ``DeclContext`` instance, which is the ``DeclContext`` responsible for
1921 maintaining the lookup table used for the semantics-centric view. Given a
1922 DeclContext, one can obtain the set of declaration contexts that are
1923 semantically connected to this declaration context, in source order, including
1924 this context (which will be the only result, for non-namespace contexts) via
1925 ``DeclContext::collectAllContexts``. Note that these functions are used
1926 internally within the lookup and insertion methods of the ``DeclContext``, so
1927 the vast majority of clients can ignore them.
1929 Because the same entity can be defined multiple times in different modules,
1930 it is also possible for there to be multiple definitions of (for instance)
1931 a ``CXXRecordDecl``, all of which describe a definition of the same class.
1932 In such a case, only one of those "definitions" is considered by Clang to be
1933 the definition of the class, and the others are treated as non-defining
1934 declarations that happen to also contain member declarations. Corresponding
1935 members in each definition of such multiply-defined classes are identified
1936 either by redeclaration chains (if the members are ``Redeclarable``)
1937 or by simply a pointer to the canonical declaration (if the declarations
1938 are not ``Redeclarable`` -- in that case, a ``Mergeable`` base class is used
1944 Clang produces an AST even when the code contains errors. Clang won't generate
1945 and optimize code for it, but it's used as parsing continues to detect further
1946 errors in the input. Clang-based tools also depend on such ASTs, and IDEs in
1947 particular benefit from a high-quality AST for broken code.
1949 In presence of errors, clang uses a few error-recovery strategies to present the
1950 broken code in the AST:
1952 - correcting errors: in cases where clang is confident about the fix, it
1953 provides a FixIt attaching to the error diagnostic and emits a corrected AST
1954 (reflecting the written code with FixIts applied). The advantage of that is to
1955 provide more accurate subsequent diagnostics. Typo correction is a typical
1957 - representing invalid node: the invalid node is preserved in the AST in some
1958 form, e.g. when the "declaration" part of the declaration contains semantic
1959 errors, the Decl node is marked as invalid.
1960 - dropping invalid node: this often happens for errors that we don’t have
1961 graceful recovery. Prior to Recovery AST, a mismatched-argument function call
1962 expression was dropped though a CallExpr was created for semantic analysis.
1964 With these strategies, clang surfaces better diagnostics, and provides AST
1965 consumers a rich AST reflecting the written source code as much as possible even
1971 The idea of Recovery AST is to use recovery nodes which act as a placeholder to
1972 maintain the rough structure of the parsing tree, preserve locations and
1973 children but have no language semantics attached to them.
1975 For example, consider the following mismatched function call:
1980 void test(int abc) {
1981 NoArg(abc); // oops, mismatched function arguments.
1984 Without Recovery AST, the invalid function call expression (and its child
1985 expressions) would be dropped in the AST:
1989 |-FunctionDecl <line:1:1, col:11> NoArg 'int ()'
1990 `-FunctionDecl <line:2:1, line:4:1> test 'void (int)'
1991 |-ParmVarDecl <col:11, col:15> col:15 used abc 'int'
1992 `-CompoundStmt <col:20, line:4:1>
1995 With Recovery AST, the AST looks like:
1999 |-FunctionDecl <line:1:1, col:11> NoArg 'int ()'
2000 `-FunctionDecl <line:2:1, line:4:1> test 'void (int)'
2001 |-ParmVarDecl <col:11, col:15> used abc 'int'
2002 `-CompoundStmt <col:20, line:4:1>
2003 `-RecoveryExpr <line:3:3, col:12> 'int' contains-errors
2004 |-UnresolvedLookupExpr <col:3> '<overloaded function type>' lvalue (ADL) = 'NoArg'
2005 `-DeclRefExpr <col:9> 'int' lvalue ParmVar 'abc' 'int'
2008 An alternative is to use existing Exprs, e.g. CallExpr for the above example.
2009 This would capture more call details (e.g. locations of parentheses) and allow
2010 it to be treated uniformly with valid CallExprs. However, jamming the data we
2011 have into CallExpr forces us to weaken its invariants, e.g. arg count may be
2012 wrong. This would introduce a huge burden on consumers of the AST to handle such
2013 "impossible" cases. So when we're representing (rather than correcting) errors,
2014 we use a distinct recovery node type with extremely weak invariants instead.
2016 ``RecoveryExpr`` is the only recovery node so far. In practice, broken decls
2017 need more detailed semantics preserved (the current ``Invalid`` flag works
2018 fairly well), and completely broken statements with interesting internal
2019 structure are rare (so dropping the statements is OK).
2021 Types and dependence
2022 ^^^^^^^^^^^^^^^^^^^^
2024 ``RecoveryExpr`` is an ``Expr``, so it must have a type. In many cases the true
2025 type can't really be known until the code is corrected (e.g. a call to a
2026 function that doesn't exist). And it means that we can't properly perform type
2027 checks on some containing constructs, such as ``return 42 + unknownFunction()``.
2029 To model this, we generalize the concept of dependence from C++ templates to
2030 mean dependence on a template parameter or how an error is repaired. The
2031 ``RecoveryExpr`` ``unknownFunction()`` has the totally unknown type
2032 ``DependentTy``, and this suppresses type-based analysis in the same way it
2033 would inside a template.
2035 In cases where we are confident about the concrete type (e.g. the return type
2036 for a broken non-overloaded function call), the ``RecoveryExpr`` will have this
2037 type. This allows more code to be typechecked, and produces a better AST and
2038 more diagnostics. For example:
2042 unknownFunction().size() // .size() is a CXXDependentScopeMemberExpr
2043 std::string(42).size() // .size() is a resolved MemberExpr
2045 Whether or not the ``RecoveryExpr`` has a dependent type, it is always
2046 considered value-dependent, because its value isn't well-defined until the error
2047 is resolved. Among other things, this means that clang doesn't emit more errors
2048 where a RecoveryExpr is used as a constant (e.g. array size), but also won't try
2054 Beyond the template dependence bits, we add a new “ContainsErrors” bit to
2055 express “Does this expression or anything within it contain errors” semantic,
2056 this bit is always set for RecoveryExpr, and propagated to other related nodes.
2057 This provides a fast way to query whether any (recursive) child of an expression
2058 had an error, which is often used to improve diagnostics.
2063 void recoveryExpr(int abc) {
2064 unknownFunction(); // type-dependent, value-dependent, contains-errors
2066 std::string(42).size(); // value-dependent, contains-errors,
2067 // not type-dependent, as we know the type is std::string
2074 void recoveryExpr(int abc) {
2075 unknownVar + abc; // type-dependent, value-dependent, contains-errors
2082 The ``ASTImporter`` class imports nodes of an ``ASTContext`` into another
2083 ``ASTContext``. Please refer to the document :doc:`ASTImporter: Merging Clang
2084 ASTs <LibASTImporter>` for an introduction. And please read through the
2085 high-level `description of the import algorithm
2086 <LibASTImporter.html#algorithm-of-the-import>`_, this is essential for
2087 understanding further implementation details of the importer.
2091 Abstract Syntax Graph
2092 ^^^^^^^^^^^^^^^^^^^^^
2094 Despite the name, the Clang AST is not a tree. It is a directed graph with
2095 cycles. One example of a cycle is the connection between a
2096 ``ClassTemplateDecl`` and its "templated" ``CXXRecordDecl``. The *templated*
2097 ``CXXRecordDecl`` represents all the fields and methods inside the class
2098 template, while the ``ClassTemplateDecl`` holds the information which is
2099 related to being a template, i.e. template arguments, etc. We can get the
2100 *templated* class (the ``CXXRecordDecl``) of a ``ClassTemplateDecl`` with
2101 ``ClassTemplateDecl::getTemplatedDecl()``. And we can get back a pointer of the
2102 "described" class template from the *templated* class:
2103 ``CXXRecordDecl::getDescribedTemplate()``. So, this is a cycle between two
2104 nodes: between the *templated* and the *described* node. There may be various
2105 other kinds of cycles in the AST especially in case of declarations.
2109 Structural Equivalency
2110 ^^^^^^^^^^^^^^^^^^^^^^
2112 Importing one AST node copies that node into the destination ``ASTContext``. To
2113 copy one node means that we create a new node in the "to" context then we set
2114 its properties to be equal to the properties of the source node. Before the
2115 copy, we make sure that the source node is not *structurally equivalent* to any
2116 existing node in the destination context. If it happens to be equivalent then
2119 The informal definition of structural equivalency is the following:
2120 Two nodes are **structurally equivalent** if they are
2122 - builtin types and refer to the same type, e.g. ``int`` and ``int`` are
2123 structurally equivalent,
2124 - function types and all their parameters have structurally equivalent types,
2125 - record types and all their fields in order of their definition have the same
2126 identifier names and structurally equivalent types,
2127 - variable or function declarations and they have the same identifier name and
2128 their types are structurally equivalent.
2130 In C, two types are structurally equivalent if they are *compatible types*. For
2131 a formal definition of *compatible types*, please refer to 6.2.7/1 in the C11
2132 standard. However, there is no definition for *compatible types* in the C++
2133 standard. Still, we extend the definition of structural equivalency to
2134 templates and their instantiations similarly: besides checking the previously
2135 mentioned properties, we have to check for equivalent template
2136 parameters/arguments, etc.
2138 The structural equivalent check can be and is used independently from the
2139 ASTImporter, e.g. the ``clang::Sema`` class uses it also.
2141 The equivalence of nodes may depend on the equivalency of other pairs of nodes.
2142 Thus, the check is implemented as a parallel graph traversal. We traverse
2143 through the nodes of both graphs at the same time. The actual implementation is
2144 similar to breadth-first-search. Let's say we start the traverse with the <A,B>
2145 pair of nodes. Whenever the traversal reaches a pair <X,Y> then the following
2146 statements are true:
2148 - A and X are nodes from the same ASTContext.
2149 - B and Y are nodes from the same ASTContext.
2150 - A and B may or may not be from the same ASTContext.
2151 - if A == X and B == Y (pointer equivalency) then (there is a cycle during the
2154 - A and B are structurally equivalent if and only if
2156 - All dependent nodes on the path from <A,B> to <X,Y> are structurally
2159 When we compare two classes or enums and one of them is incomplete or has
2160 unloaded external lexical declarations then we cannot descend to compare their
2161 contained declarations. So in these cases they are considered equal if they
2162 have the same names. This is the way how we compare forward declarations with
2165 .. TODO Should we elaborate the actual implementation of the graph traversal,
2166 .. which is a very weird BFS traversal?
2168 Redeclaration Chains
2169 ^^^^^^^^^^^^^^^^^^^^
2171 The early version of the ``ASTImporter``'s merge mechanism squashed the
2172 declarations, i.e. it aimed to have only one declaration instead of maintaining
2173 a whole redeclaration chain. This early approach simply skipped importing a
2174 function prototype, but it imported a definition. To demonstrate the problem
2175 with this approach let's consider an empty "to" context and the following
2176 ``virtual`` function declarations of ``f`` in the "from" context:
2180 struct B { virtual void f(); };
2181 void B::f() {} // <-- let's import this definition
2183 If we imported the definition with the "squashing" approach then we would
2184 end-up having one declaration which is indeed a definition, but ``isVirtual()``
2185 returns ``false`` for it. The reason is that the definition is indeed not
2186 virtual, it is the property of the prototype!
2188 Consequently, we must either set the virtual flag for the definition (but then
2189 we create a malformed AST which the parser would never create), or we import
2190 the whole redeclaration chain of the function. The most recent version of the
2191 ``ASTImporter`` uses the latter mechanism. We do import all function
2192 declarations - regardless if they are definitions or prototypes - in the order
2193 as they appear in the "from" context.
2197 If we have an existing definition in the "to" context, then we cannot import
2198 another definition, we will use the existing definition. However, we can import
2199 prototype(s): we chain the newly imported prototype(s) to the existing
2200 definition. Whenever we import a new prototype from a third context, that will
2201 be added to the end of the redeclaration chain. This may result in long
2202 redeclaration chains in certain cases, e.g. if we import from several
2203 translation units which include the same header with the prototype.
2205 .. Squashing prototypes
2207 To mitigate the problem of long redeclaration chains of free functions, we
2208 could compare prototypes to see if they have the same properties and if yes
2209 then we could merge these prototypes. The implementation of squashing of
2210 prototypes for free functions is future work.
2212 .. Exception: Cannot have more than 1 prototype in-class
2214 Chaining functions this way ensures that we do copy all information from the
2215 source AST. Nonetheless, there is a problem with member functions: While we can
2216 have many prototypes for free functions, we must have only one prototype for a
2228 void X::f() {} // OK
2230 Thus, prototypes of member functions must be squashed, we cannot just simply
2231 attach a new prototype to the existing in-class prototype. Consider the
2247 void X::f() {} // D2
2249 When we import the prototype and the definition of ``f`` from the "from"
2250 context, then the resulting redecl chain will look like this ``D0 -> D2'``,
2251 where ``D2'`` is the copy of ``D2`` in the "to" context.
2253 .. Redecl chains of other declarations
2255 Generally speaking, when we import declarations (like enums and classes) we do
2256 attach the newly imported declaration to the existing redeclaration chain (if
2257 there is structural equivalency). We do not import, however, the whole
2258 redeclaration chain as we do in case of functions. Up till now, we haven't
2259 found any essential property of forward declarations which is similar to the
2260 case of the virtual flag in a member function prototype. In the future, this
2263 Traversal during the Import
2264 ^^^^^^^^^^^^^^^^^^^^^^^^^^^
2266 The node specific import mechanisms are implemented in
2267 ``ASTNodeImporter::VisitNode()`` functions, e.g. ``VisitFunctionDecl()``.
2268 When we import a declaration then first we import everything which is needed to
2269 call the constructor of that declaration node. Everything which can be set
2270 later is set after the node is created. For example, in case of a
2271 ``FunctionDecl`` we first import the declaration context in which the function
2272 is declared, then we create the ``FunctionDecl`` and only then we import the
2273 body of the function. This means there are implicit dependencies between AST
2274 nodes. These dependencies determine the order in which we visit nodes in the
2275 "from" context. As with the regular graph traversal algorithms like DFS, we
2276 keep track which nodes we have already visited in
2277 ``ASTImporter::ImportedDecls``. Whenever we create a node then we immediately
2278 add that to the ``ImportedDecls``. We must not start the import of any other
2279 declarations before we keep track of the newly created one. This is essential,
2280 otherwise, we would not be able to handle circular dependencies. To enforce
2281 this, we wrap all constructor calls of all AST nodes in
2282 ``GetImportedOrCreateDecl()``. This wrapper ensures that all newly created
2283 declarations are immediately marked as imported; also, if a declaration is
2284 already marked as imported then we just return its counterpart in the "to"
2285 context. Consequently, calling a declaration's ``::Create()`` function directly
2286 would lead to errors, please don't do that!
2288 Even with the use of ``GetImportedOrCreateDecl()`` there is still a
2289 probability of having an infinite import recursion if things are imported from
2290 each other in wrong way. Imagine that during the import of ``A``, the import of
2291 ``B`` is requested before we could create the node for ``A`` (the constructor
2292 needs a reference to ``B``). And the same could be true for the import of ``B``
2293 (``A`` is requested to be imported before we could create the node for ``B``).
2294 In case of the :ref:`templated-described swing <templated>` we take
2295 extra attention to break the cyclical dependency: we import and set the
2296 described template only after the ``CXXRecordDecl`` is created. As a best
2297 practice, before creating the node in the "to" context, avoid importing of
2298 other nodes which are not needed for the constructor of node ``A``.
2303 Every import function returns with either an ``llvm::Error`` or an
2304 ``llvm::Expected<T>`` object. This enforces to check the return value of the
2305 import functions. If there was an error during one import then we return with
2306 that error. (Exception: when we import the members of a class, we collect the
2307 individual errors with each member and we concatenate them in one Error
2308 object.) We cache these errors in cases of declarations. During the next import
2309 call if there is an existing error we just return with that. So, clients of the
2310 library receive an Error object, which they must check.
2312 During import of a specific declaration, it may happen that some AST nodes had
2313 already been created before we recognize an error. In this case, we signal back
2314 the error to the caller, but the "to" context remains polluted with those nodes
2315 which had been created. Ideally, those nodes should not had been created, but
2316 that time we did not know about the error, the error happened later. Since the
2317 AST is immutable (most of the cases we can't remove existing nodes) we choose
2318 to mark these nodes as erroneous.
2320 We cache the errors associated with declarations in the "from" context in
2321 ``ASTImporter::ImportDeclErrors`` and the ones which are associated with the
2322 "to" context in ``ASTImporterSharedState::ImportErrors``. Note that, there may
2323 be several ASTImporter objects which import into the same "to" context but from
2324 different "from" contexts; in this case, they have to share the associated
2325 errors of the "to" context.
2327 When an error happens, that propagates through the call stack, through all the
2328 dependant nodes. However, in case of dependency cycles, this is not enough,
2329 because we strive to mark the erroneous nodes so clients can act upon. In those
2330 cases, we have to keep track of the errors for those nodes which are
2331 intermediate nodes of a cycle.
2333 An **import path** is the list of the AST nodes which we visit during an Import
2334 call. If node ``A`` depends on node ``B`` then the path contains an ``A->B``
2335 edge. From the call stack of the import functions, we can read the very same
2338 Now imagine the following AST, where the ``->`` represents dependency in terms
2339 of the import (all nodes are declarations).
2341 .. code-block:: text
2346 We would like to import A.
2347 The import behaves like a DFS, so we will visit the nodes in this order: ABCDE.
2348 During the visitation we will have the following import paths:
2350 .. code-block:: text
2362 If during the visit of E there is an error then we set an error for E, then as
2363 the call stack shrinks for B, then for A:
2365 .. code-block:: text
2373 ABE // Error! Set an error to E
2374 AB // Set an error to B
2375 A // Set an error to A
2377 However, during the import we could import C and D without any error and they
2378 are independent of A,B and E. We must not set up an error for C and D. So, at
2379 the end of the import we have an entry in ``ImportDeclErrors`` for A,B,E but
2382 Now, what happens if there is a cycle in the import path? Let's consider this
2385 .. code-block:: text
2390 During the visitation, we will have the below import paths and if during the
2391 visit of E there is an error then we will set up an error for E,B,A. But what's
2394 .. code-block:: text
2402 ABE // Error! Set an error to E
2403 AB // Set an error to B
2404 A // Set an error to A
2406 This time we know that both B and C are dependent on A. This means we must set
2407 up an error for C too. As the call stack reverses back we get to A and we must
2408 set up an error to all nodes which depend on A (this includes C). But C is no
2409 longer on the import path, it just had been previously. Such a situation can
2410 happen only if during the visitation we had a cycle. If we didn't have any
2411 cycle, then the normal way of passing an Error object through the call stack
2412 could handle the situation. This is why we must track cycles during the import
2413 process for each visited declaration.
2418 When we import a declaration from the source context then we check whether we
2419 already have a structurally equivalent node with the same name in the "to"
2420 context. If the "from" node is a definition and the found one is also a
2421 definition, then we do not create a new node, instead, we mark the found node
2422 as the imported node. If the found definition and the one we want to import
2423 have the same name but they are structurally in-equivalent, then we have an ODR
2424 violation in case of C++. If the "from" node is not a definition then we add
2425 that to the redeclaration chain of the found node. This behaviour is essential
2426 when we merge ASTs from different translation units which include the same
2427 header file(s). For example, we want to have only one definition for the class
2428 template ``std::vector``, even if we included ``<vector>`` in several
2431 To find a structurally equivalent node we can use the regular C/C++ lookup
2432 functions: ``DeclContext::noload_lookup()`` and
2433 ``DeclContext::localUncachedLookup()``. These functions do respect the C/C++
2434 name hiding rules, thus you cannot find certain declarations in a given
2435 declaration context. For instance, unnamed declarations (anonymous structs),
2436 non-first ``friend`` declarations and template specializations are hidden. This
2437 is a problem, because if we use the regular C/C++ lookup then we create
2438 redundant AST nodes during the merge! Also, having two instances of the same
2439 node could result in false :ref:`structural in-equivalencies <structural-eq>`
2440 of other nodes which depend on the duplicated node. Because of these reasons,
2441 we created a lookup class which has the sole purpose to register all
2442 declarations, so later they can be looked up by subsequent import requests.
2443 This is the ``ASTImporterLookupTable`` class. This lookup table should be
2444 shared amongst the different ``ASTImporter`` instances if they happen to import
2445 to the very same "to" context. This is why we can use the importer specific
2446 lookup only via the ``ASTImporterSharedState`` class.
2451 The ``ExternalASTSource`` is an abstract interface associated with the
2452 ``ASTContext`` class. It provides the ability to read the declarations stored
2453 within a declaration context either for iteration or for name lookup. A
2454 declaration context with an external AST source may load its declarations
2455 on-demand. This means that the list of declarations (represented as a linked
2456 list, the head is ``DeclContext::FirstDecl``) could be empty. However, member
2457 functions like ``DeclContext::lookup()`` may initiate a load.
2459 Usually, external sources are associated with precompiled headers. For example,
2460 when we load a class from a PCH then the members are loaded only if we do want
2461 to look up something in the class' context.
2463 In case of LLDB, an implementation of the ``ExternalASTSource`` interface is
2464 attached to the AST context which is related to the parsed expression. This
2465 implementation of the ``ExternalASTSource`` interface is realized with the help
2466 of the ``ASTImporter`` class. This way, LLDB can reuse Clang's parsing
2467 machinery while synthesizing the underlying AST from the debug data (e.g. from
2468 DWARF). From the view of the ``ASTImporter`` this means both the "to" and the
2469 "from" context may have declaration contexts with external lexical storage. If
2470 a ``DeclContext`` in the "to" AST context has external lexical storage then we
2471 must take extra attention to work only with the already loaded declarations!
2472 Otherwise, we would end up with an uncontrolled import process. For instance,
2473 if we used the regular ``DeclContext::lookup()`` to find the existing
2474 declarations in the "to" context then the ``lookup()`` call itself would
2475 initiate a new import while we are in the middle of importing a declaration!
2476 (By the time we initiate the lookup we haven't registered yet that we already
2477 started to import the node of the "from" context.) This is why we use
2478 ``DeclContext::noload_lookup()`` instead.
2480 Class Template Instantiations
2481 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2483 Different translation units may have class template instantiations with the
2484 same template arguments, but with a different set of instantiated
2485 ``MethodDecls`` and ``FieldDecls``. Consider the following files:
2490 template <typename T>
2492 int a{0}; // FieldDecl with InitListExpr
2493 X(char) : a(3) {} // (1)
2499 // ClassTemplateSpec with ctor (1): FieldDecl without InitlistExpr
2505 // ClassTemplateSpec with ctor (2): FieldDecl WITH InitlistExpr
2509 In ``foo.cpp`` we use the constructor with number ``(1)``, which explicitly
2510 initializes the member ``a`` to ``3``, thus the ``InitListExpr`` ``{0}`` is not
2511 used here and the AST node is not instantiated. However, in the case of
2512 ``bar.cpp`` we use the constructor with number ``(2)``, which does not
2513 explicitly initialize the ``a`` member, so the default ``InitListExpr`` is
2514 needed and thus instantiated. When we merge the AST of ``foo.cpp`` and
2515 ``bar.cpp`` we must create an AST node for the class template instantiation of
2516 ``X<char>`` which has all the required nodes. Therefore, when we find an
2517 existing ``ClassTemplateSpecializationDecl`` then we merge the fields of the
2518 ``ClassTemplateSpecializationDecl`` in the "from" context in a way that the
2519 ``InitListExpr`` is copied if not existent yet. The same merge mechanism should
2520 be done in the cases of instantiated default arguments and exception
2521 specifications of functions.
2525 Visibility of Declarations
2526 ^^^^^^^^^^^^^^^^^^^^^^^^^^
2528 During import of a global variable with external visibility, the lookup will
2529 find variables (with the same name) but with static visibility (linkage).
2530 Clearly, we cannot put them into the same redeclaration chain. The same is true
2531 the in case of functions. Also, we have to take care of other kinds of
2532 declarations like enums, classes, etc. if they are in anonymous namespaces.
2533 Therefore, we filter the lookup results and consider only those which have the
2534 same visibility as the declaration we currently import.
2536 We consider two declarations in two anonymous namespaces to have the same
2537 visibility only if they are imported from the same AST context.
2539 Strategies to Handle Conflicting Names
2540 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2542 During the import we lookup existing declarations with the same name. We filter
2543 the lookup results based on their :ref:`visibility <visibility>`. If any of the
2544 found declarations are not structurally equivalent then we bumped to a name
2545 conflict error (ODR violation in C++). In this case, we return with an
2546 ``Error`` and we set up the ``Error`` object for the declaration. However, some
2547 clients of the ``ASTImporter`` may require a different, perhaps less
2548 conservative and more liberal error handling strategy.
2550 E.g. static analysis clients may benefit if the node is created even if there
2551 is a name conflict. During the CTU analysis of certain projects, we recognized
2552 that there are global declarations which collide with declarations from other
2553 translation units, but they are not referenced outside from their translation
2554 unit. These declarations should be in an unnamed namespace ideally. If we treat
2555 these collisions liberally then CTU analysis can find more results. Note, the
2556 feature be able to choose between name conflict handling strategies is still an
2564 The ``CFG`` class is designed to represent a source-level control-flow graph
2565 for a single statement (``Stmt*``). Typically instances of ``CFG`` are
2566 constructed for function bodies (usually an instance of ``CompoundStmt``), but
2567 can also be instantiated to represent the control-flow of any class that
2568 subclasses ``Stmt``, which includes simple expressions. Control-flow graphs
2569 are especially useful for performing `flow- or path-sensitive
2570 <https://en.wikipedia.org/wiki/Data_flow_analysis#Sensitivities>`_ program
2571 analyses on a given function.
2576 Concretely, an instance of ``CFG`` is a collection of basic blocks. Each basic
2577 block is an instance of ``CFGBlock``, which simply contains an ordered sequence
2578 of ``Stmt*`` (each referring to statements in the AST). The ordering of
2579 statements within a block indicates unconditional flow of control from one
2580 statement to the next. :ref:`Conditional control-flow
2581 <ConditionalControlFlow>` is represented using edges between basic blocks. The
2582 statements within a given ``CFGBlock`` can be traversed using the
2583 ``CFGBlock::*iterator`` interface.
2585 A ``CFG`` object owns the instances of ``CFGBlock`` within the control-flow
2586 graph it represents. Each ``CFGBlock`` within a CFG is also uniquely numbered
2587 (accessible via ``CFGBlock::getBlockID()``). Currently the number is based on
2588 the ordering the blocks were created, but no assumptions should be made on how
2589 ``CFGBlocks`` are numbered other than their numbers are unique and that they
2590 are numbered from 0..N-1 (where N is the number of basic blocks in the CFG).
2592 Entry and Exit Blocks
2593 ^^^^^^^^^^^^^^^^^^^^^
2595 Each instance of ``CFG`` contains two special blocks: an *entry* block
2596 (accessible via ``CFG::getEntry()``), which has no incoming edges, and an
2597 *exit* block (accessible via ``CFG::getExit()``), which has no outgoing edges.
2598 Neither block contains any statements, and they serve the role of providing a
2599 clear entrance and exit for a body of code such as a function body. The
2600 presence of these empty blocks greatly simplifies the implementation of many
2601 analyses built on top of CFGs.
2603 .. _ConditionalControlFlow:
2605 Conditional Control-Flow
2606 ^^^^^^^^^^^^^^^^^^^^^^^^
2608 Conditional control-flow (such as those induced by if-statements and loops) is
2609 represented as edges between ``CFGBlocks``. Because different C language
2610 constructs can induce control-flow, each ``CFGBlock`` also records an extra
2611 ``Stmt*`` that represents the *terminator* of the block. A terminator is
2612 simply the statement that caused the control-flow, and is used to identify the
2613 nature of the conditional control-flow between blocks. For example, in the
2614 case of an if-statement, the terminator refers to the ``IfStmt`` object in the
2615 AST that represented the given branch.
2617 To illustrate, consider the following code example:
2633 After invoking the parser+semantic analyzer on this code fragment, the AST of
2634 the body of ``foo`` is referenced by a single ``Stmt*``. We can then construct
2635 an instance of ``CFG`` representing the control-flow graph of this function
2636 body by single call to a static class method:
2641 std::unique_ptr<CFG> FooCFG = CFG::buildCFG(FooBody);
2643 Along with providing an interface to iterate over its ``CFGBlocks``, the
2644 ``CFG`` class also provides methods that are useful for debugging and
2645 visualizing CFGs. For example, the method ``CFG::dump()`` dumps a
2646 pretty-printed version of the CFG to standard error. This is especially useful
2647 when one is using a debugger such as gdb. For example, here is the output of
2650 .. code-block:: text
2660 Predecessors (1): B5
2661 Successors (2): B3 B2
2665 Predecessors (1): B4
2671 Predecessors (1): B4
2676 Predecessors (2): B2 B3
2680 Predecessors (1): B1
2683 For each block, the pretty-printed output displays for each block the number of
2684 *predecessor* blocks (blocks that have outgoing control-flow to the given
2685 block) and *successor* blocks (blocks that have control-flow that have incoming
2686 control-flow from the given block). We can also clearly see the special entry
2687 and exit blocks at the beginning and end of the pretty-printed output. For the
2688 entry block (block B5), the number of predecessor blocks is 0, while for the
2689 exit block (block B0) the number of successor blocks is 0.
2691 The most interesting block here is B4, whose outgoing control-flow represents
2692 the branching caused by the sole if-statement in ``foo``. Of particular
2693 interest is the second statement in the block, ``(x > 2)``, and the terminator,
2694 printed as ``if [B4.2]``. The second statement represents the evaluation of
2695 the condition of the if-statement, which occurs before the actual branching of
2696 control-flow. Within the ``CFGBlock`` for B4, the ``Stmt*`` for the second
2697 statement refers to the actual expression in the AST for ``(x > 2)``. Thus
2698 pointers to subclasses of ``Expr`` can appear in the list of statements in a
2699 block, and not just subclasses of ``Stmt`` that refer to proper C statements.
2701 The terminator of block B4 is a pointer to the ``IfStmt`` object in the AST.
2702 The pretty-printer outputs ``if [B4.2]`` because the condition expression of
2703 the if-statement has an actual place in the basic block, and thus the
2704 terminator is essentially *referring* to the expression that is the second
2705 statement of block B4 (i.e., B4.2). In this manner, conditions for
2706 control-flow (which also includes conditions for loops and switch statements)
2707 are hoisted into the actual basic block.
2709 .. Implicit Control-Flow
2710 .. ^^^^^^^^^^^^^^^^^^^^^
2712 .. A key design principle of the ``CFG`` class was to not require any
2713 .. transformations to the AST in order to represent control-flow. Thus the
2714 .. ``CFG`` does not perform any "lowering" of the statements in an AST: loops
2715 .. are not transformed into guarded gotos, short-circuit operations are not
2716 .. converted to a set of if-statements, and so on.
2718 Constant Folding in the Clang AST
2719 ---------------------------------
2721 There are several places where constants and constant folding matter a lot to
2722 the Clang front-end. First, in general, we prefer the AST to retain the source
2723 code as close to how the user wrote it as possible. This means that if they
2724 wrote "``5+4``", we want to keep the addition and two constants in the AST, we
2725 don't want to fold to "``9``". This means that constant folding in various
2726 ways turns into a tree walk that needs to handle the various cases.
2728 However, there are places in both C and C++ that require constants to be
2729 folded. For example, the C standard defines what an "integer constant
2730 expression" (i-c-e) is with very precise and specific requirements. The
2731 language then requires i-c-e's in a lot of places (for example, the size of a
2732 bitfield, the value for a case statement, etc). For these, we have to be able
2733 to constant fold the constants, to do semantic checks (e.g., verify bitfield
2734 size is non-negative and that case statements aren't duplicated). We aim for
2735 Clang to be very pedantic about this, diagnosing cases when the code does not
2736 use an i-c-e where one is required, but accepting the code unless running with
2737 ``-pedantic-errors``.
2739 Things get a little bit more tricky when it comes to compatibility with
2740 real-world source code. Specifically, GCC has historically accepted a huge
2741 superset of expressions as i-c-e's, and a lot of real world code depends on
2742 this unfortunate accident of history (including, e.g., the glibc system
2743 headers). GCC accepts anything its "fold" optimizer is capable of reducing to
2744 an integer constant, which means that the definition of what it accepts changes
2745 as its optimizer does. One example is that GCC accepts things like "``case
2746 X-X:``" even when ``X`` is a variable, because it can fold this to 0.
2748 Another issue are how constants interact with the extensions we support, such
2749 as ``__builtin_constant_p``, ``__builtin_inf``, ``__extension__`` and many
2750 others. C99 obviously does not specify the semantics of any of these
2751 extensions, and the definition of i-c-e does not include them. However, these
2752 extensions are often used in real code, and we have to have a way to reason
2755 Finally, this is not just a problem for semantic analysis. The code generator
2756 and other clients have to be able to fold constants (e.g., to initialize global
2757 variables) and have to handle a superset of what C99 allows. Further, these
2758 clients can benefit from extended information. For example, we know that
2759 "``foo() || 1``" always evaluates to ``true``, but we can't replace the
2760 expression with ``true`` because it has side effects.
2762 Implementation Approach
2763 ^^^^^^^^^^^^^^^^^^^^^^^
2765 After trying several different approaches, we've finally converged on a design
2766 (Note, at the time of this writing, not all of this has been implemented,
2767 consider this a design goal!). Our basic approach is to define a single
2768 recursive evaluation method (``Expr::Evaluate``), which is implemented
2769 in ``AST/ExprConstant.cpp``. Given an expression with "scalar" type (integer,
2770 fp, complex, or pointer) this method returns the following information:
2772 * Whether the expression is an integer constant expression, a general constant
2773 that was folded but has no side effects, a general constant that was folded
2774 but that does have side effects, or an uncomputable/unfoldable value.
2775 * If the expression was computable in any way, this method returns the
2776 ``APValue`` for the result of the expression.
2777 * If the expression is not evaluatable at all, this method returns information
2778 on one of the problems with the expression. This includes a
2779 ``SourceLocation`` for where the problem is, and a diagnostic ID that explains
2780 the problem. The diagnostic should have ``ERROR`` type.
2781 * If the expression is not an integer constant expression, this method returns
2782 information on one of the problems with the expression. This includes a
2783 ``SourceLocation`` for where the problem is, and a diagnostic ID that
2784 explains the problem. The diagnostic should have ``EXTENSION`` type.
2786 This information gives various clients the flexibility that they want, and we
2787 will eventually have some helper methods for various extensions. For example,
2788 ``Sema`` should have a ``Sema::VerifyIntegerConstantExpression`` method, which
2789 calls ``Evaluate`` on the expression. If the expression is not foldable, the
2790 error is emitted, and it would return ``true``. If the expression is not an
2791 i-c-e, the ``EXTENSION`` diagnostic is emitted. Finally it would return
2792 ``false`` to indicate that the AST is OK.
2794 Other clients can use the information in other ways, for example, codegen can
2795 just use expressions that are foldable in any way.
2800 This section describes how some of the various extensions Clang supports
2801 interacts with constant evaluation:
2803 * ``__extension__``: The expression form of this extension causes any
2804 evaluatable subexpression to be accepted as an integer constant expression.
2805 * ``__builtin_constant_p``: This returns true (as an integer constant
2806 expression) if the operand evaluates to either a numeric value (that is, not
2807 a pointer cast to integral type) of integral, enumeration, floating or
2808 complex type, or if it evaluates to the address of the first character of a
2809 string literal (possibly cast to some other type). As a special case, if
2810 ``__builtin_constant_p`` is the (potentially parenthesized) condition of a
2811 conditional operator expression ("``?:``"), only the true side of the
2812 conditional operator is considered, and it is evaluated with full constant
2814 * ``__builtin_choose_expr``: The condition is required to be an integer
2815 constant expression, but we accept any constant as an "extension of an
2816 extension". This only evaluates one operand depending on which way the
2817 condition evaluates.
2818 * ``__builtin_classify_type``: This always returns an integer constant
2820 * ``__builtin_inf, nan, ...``: These are treated just like a floating-point
2822 * ``__builtin_abs, copysign, ...``: These are constant folded as general
2823 constant expressions.
2824 * ``__builtin_strlen`` and ``strlen``: These are constant folded as integer
2825 constant expressions if the argument is a string literal.
2832 This library is called by the :ref:`Parser library <Parser>` during parsing to
2833 do semantic analysis of the input. For valid programs, Sema builds an AST for
2841 CodeGen takes an :ref:`AST <AST>` as input and produces `LLVM IR code
2842 <//llvm.org/docs/LangRef.html>`_ from it.
2847 How to add an attribute
2848 -----------------------
2849 Attributes are a form of metadata that can be attached to a program construct,
2850 allowing the programmer to pass semantic information along to the compiler for
2851 various uses. For example, attributes may be used to alter the code generation
2852 for a program construct, or to provide extra semantic information for static
2853 analysis. This document explains how to add a custom attribute to Clang.
2854 Documentation on existing attributes can be found `here
2855 <//clang.llvm.org/docs/AttributeReference.html>`_.
2859 Attributes in Clang are handled in three stages: parsing into a parsed attribute
2860 representation, conversion from a parsed attribute into a semantic attribute,
2861 and then the semantic handling of the attribute.
2863 Parsing of the attribute is determined by the various syntactic forms attributes
2864 can take, such as GNU, C++11, and Microsoft style attributes, as well as other
2865 information provided by the table definition of the attribute. Ultimately, the
2866 parsed representation of an attribute object is a ``ParsedAttr`` object.
2867 These parsed attributes chain together as a list of parsed attributes attached
2868 to a declarator or declaration specifier. The parsing of attributes is handled
2869 automatically by Clang, except for attributes spelled as so-called “custom”
2870 keywords. When implementing a custom keyword attribute, the parsing of the
2871 keyword and creation of the ``ParsedAttr`` object must be done manually.
2873 Eventually, ``Sema::ProcessDeclAttributeList()`` is called with a ``Decl`` and
2874 a ``ParsedAttr``, at which point the parsed attribute can be transformed
2875 into a semantic attribute. The process by which a parsed attribute is converted
2876 into a semantic attribute depends on the attribute definition and semantic
2877 requirements of the attribute. The end result, however, is that the semantic
2878 attribute object is attached to the ``Decl`` object, and can be obtained by a
2879 call to ``Decl::getAttr<T>()``. Similarly, for statement attributes,
2880 ``Sema::ProcessStmtAttributes()`` is called with a ``Stmt`` a list of
2881 ``ParsedAttr`` objects to be converted into a semantic attribute.
2883 The structure of the semantic attribute is also governed by the attribute
2884 definition given in Attr.td. This definition is used to automatically generate
2885 functionality used for the implementation of the attribute, such as a class
2886 derived from ``clang::Attr``, information for the parser to use, automated
2887 semantic checking for some attributes, etc.
2890 ``include/clang/Basic/Attr.td``
2891 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2892 The first step to adding a new attribute to Clang is to add its definition to
2893 `include/clang/Basic/Attr.td
2894 <https://github.com/llvm/llvm-project/blob/main/clang/include/clang/Basic/Attr.td>`_.
2895 This tablegen definition must derive from the ``Attr`` (tablegen, not
2896 semantic) type, or one of its derivatives. Most attributes will derive from the
2897 ``InheritableAttr`` type, which specifies that the attribute can be inherited by
2898 later redeclarations of the ``Decl`` it is associated with.
2899 ``InheritableParamAttr`` is similar to ``InheritableAttr``, except that the
2900 attribute is written on a parameter instead of a declaration. If the attribute
2901 applies to statements, it should inherit from ``StmtAttr``. If the attribute is
2902 intended to apply to a type instead of a declaration, such an attribute should
2903 derive from ``TypeAttr``, and will generally not be given an AST representation.
2904 (Note that this document does not cover the creation of type attributes.) An
2905 attribute that inherits from ``IgnoredAttr`` is parsed, but will generate an
2906 ignored attribute diagnostic when used, which may be useful when an attribute is
2907 supported by another vendor but not supported by clang.
2909 The definition will specify several key pieces of information, such as the
2910 semantic name of the attribute, the spellings the attribute supports, the
2911 arguments the attribute expects, and more. Most members of the ``Attr`` tablegen
2912 type do not require definitions in the derived definition as the default
2913 suffice. However, every attribute must specify at least a spelling list, a
2914 subject list, and a documentation list.
2918 All attributes are required to specify a spelling list that denotes the ways in
2919 which the attribute can be spelled. For instance, a single semantic attribute
2920 may have a keyword spelling, as well as a C++11 spelling and a GNU spelling. An
2921 empty spelling list is also permissible and may be useful for attributes which
2922 are created implicitly. The following spellings are accepted:
2924 ================== =========================================================
2925 Spelling Description
2926 ================== =========================================================
2927 ``GNU`` Spelled with a GNU-style ``__attribute__((attr))``
2928 syntax and placement.
2929 ``CXX11`` Spelled with a C++-style ``[[attr]]`` syntax with an
2930 optional vendor-specific namespace.
2931 ``C23`` Spelled with a C-style ``[[attr]]`` syntax with an
2932 optional vendor-specific namespace.
2933 ``Declspec`` Spelled with a Microsoft-style ``__declspec(attr)``
2935 ``CustomKeyword`` The attribute is spelled as a keyword, and requires
2937 ``RegularKeyword`` The attribute is spelled as a keyword. It can be
2938 used in exactly the places that the standard
2939 ``[[attr]]`` syntax can be used, and appertains to
2940 exactly the same thing that a standard attribute
2941 would appertain to. Lexing and parsing of the keyword
2942 are handled automatically.
2943 ``GCC`` Specifies two or three spellings: the first is a
2944 GNU-style spelling, the second is a C++-style spelling
2945 with the ``gnu`` namespace, and the third is an optional
2946 C-style spelling with the ``gnu`` namespace. Attributes
2947 should only specify this spelling for attributes
2949 ``Clang`` Specifies two or three spellings: the first is a
2950 GNU-style spelling, the second is a C++-style spelling
2951 with the ``clang`` namespace, and the third is an
2952 optional C-style spelling with the ``clang`` namespace.
2953 By default, a C-style spelling is provided.
2954 ``Pragma`` The attribute is spelled as a ``#pragma``, and requires
2955 custom processing within the preprocessor. If the
2956 attribute is meant to be used by Clang, it should
2957 set the namespace to ``"clang"``. Note that this
2958 spelling is not used for declaration attributes.
2959 ================== =========================================================
2961 The C++ standard specifies that “any [non-standard attribute] that is not
2962 recognized by the implementation is ignored” (``[dcl.attr.grammar]``).
2963 The rule for C is similar. This makes ``CXX11`` and ``C23`` spellings
2964 unsuitable for attributes that affect the type system, that change the
2965 binary interface of the code, or that have other similar semantic meaning.
2967 ``RegularKeyword`` provides an alternative way of spelling such attributes.
2968 It reuses the production rules for standard attributes, but it applies them
2969 to plain keywords rather than to ``[[…]]`` sequences. Compilers that don't
2970 recognize the keyword are likely to report an error of some kind.
2972 For example, the ``ArmStreaming`` function type attribute affects
2973 both the type system and the binary interface of the function.
2974 It cannot therefore be spelled ``[[arm::streaming]]``, since compilers
2975 that don't understand ``arm::streaming`` would ignore it and miscompile
2976 the code. ``ArmStreaming`` is instead spelled ``__arm_streaming``, but it
2977 can appear wherever a hypothetical ``[[arm::streaming]]`` could appear.
2981 Attributes appertain to one or more subjects. If the attribute attempts to
2982 attach to a subject that is not in the subject list, a diagnostic is issued
2983 automatically. Whether the diagnostic is a warning or an error depends on how
2984 the attribute's ``SubjectList`` is defined, but the default behavior is to warn.
2985 The diagnostics displayed to the user are automatically determined based on the
2986 subjects in the list, but a custom diagnostic parameter can also be specified in
2987 the ``SubjectList``. The diagnostics generated for subject list violations are
2988 calculated automatically or specified by the subject list itself. If a
2989 previously unused Decl node is added to the ``SubjectList``, the logic used to
2990 automatically determine the diagnostic parameter in `utils/TableGen/ClangAttrEmitter.cpp
2991 <https://github.com/llvm/llvm-project/blob/main/clang/utils/TableGen/ClangAttrEmitter.cpp>`_
2992 may need to be updated.
2994 By default, all subjects in the SubjectList must either be a Decl node defined
2995 in ``DeclNodes.td``, or a statement node defined in ``StmtNodes.td``. However,
2996 more complex subjects can be created by creating a ``SubsetSubject`` object.
2997 Each such object has a base subject which it appertains to (which must be a
2998 Decl or Stmt node, and not a SubsetSubject node), and some custom code which is
2999 called when determining whether an attribute appertains to the subject. For
3000 instance, a ``NonBitField`` SubsetSubject appertains to a ``FieldDecl``, and
3001 tests whether the given FieldDecl is a bit field. When a SubsetSubject is
3002 specified in a SubjectList, a custom diagnostic parameter must also be provided.
3004 Diagnostic checking for attribute subject lists for declaration and statement
3005 attributes is automated except when ``HasCustomParsing`` is set to ``1``.
3009 All attributes must have some form of documentation associated with them.
3010 Documentation is table generated on the public web server by a server-side
3011 process that runs daily. Generally, the documentation for an attribute is a
3012 stand-alone definition in `include/clang/Basic/AttrDocs.td
3013 <https://github.com/llvm/llvm-project/blob/main/clang/include/clang/Basic/AttrDocs.td>`_
3014 that is named after the attribute being documented.
3016 If the attribute is not for public consumption, or is an implicitly-created
3017 attribute that has no visible spelling, the documentation list can specify the
3018 ``InternalOnly`` object. Otherwise, the attribute should have its documentation
3019 added to AttrDocs.td.
3021 Documentation derives from the ``Documentation`` tablegen type. All derived
3022 types must specify a documentation category and the actual documentation itself.
3023 Additionally, it can specify a custom heading for the attribute, though a
3024 default heading will be chosen when possible.
3026 There are four predefined documentation categories: ``DocCatFunction`` for
3027 attributes that appertain to function-like subjects, ``DocCatVariable`` for
3028 attributes that appertain to variable-like subjects, ``DocCatType`` for type
3029 attributes, and ``DocCatStmt`` for statement attributes. A custom documentation
3030 category should be used for groups of attributes with similar functionality.
3031 Custom categories are good for providing overview information for the attributes
3032 grouped under it. For instance, the consumed annotation attributes define a
3033 custom category, ``DocCatConsumed``, that explains what consumed annotations are
3036 Documentation content (whether it is for an attribute or a category) is written
3037 using reStructuredText (RST) syntax.
3039 After writing the documentation for the attribute, it should be locally tested
3040 to ensure that there are no issues generating the documentation on the server.
3041 Local testing requires a fresh build of clang-tblgen. To generate the attribute
3042 documentation, execute the following command::
3044 clang-tblgen -gen-attr-docs -I /path/to/clang/include /path/to/clang/include/clang/Basic/Attr.td -o /path/to/clang/docs/AttributeReference.rst
3046 When testing locally, *do not* commit changes to ``AttributeReference.rst``.
3047 This file is generated by the server automatically, and any changes made to this
3048 file will be overwritten.
3052 Attributes may optionally specify a list of arguments that can be passed to the
3053 attribute. Attribute arguments specify both the parsed form and the semantic
3054 form of the attribute. For example, if ``Args`` is
3055 ``[StringArgument<"Arg1">, IntArgument<"Arg2">]`` then
3056 ``__attribute__((myattribute("Hello", 3)))`` will be a valid use; it requires
3057 two arguments while parsing, and the Attr subclass' constructor for the
3058 semantic attribute will require a string and integer argument.
3060 All arguments have a name and a flag that specifies whether the argument is
3061 optional. The associated C++ type of the argument is determined by the argument
3062 definition type. If the existing argument types are insufficient, new types can
3063 be created, but it requires modifying `utils/TableGen/ClangAttrEmitter.cpp
3064 <https://github.com/llvm/llvm-project/blob/main/clang/utils/TableGen/ClangAttrEmitter.cpp>`_
3065 to properly support the type.
3069 The ``Attr`` definition has other members which control the behavior of the
3070 attribute. Many of them are special-purpose and beyond the scope of this
3071 document, however a few deserve mention.
3073 If the parsed form of the attribute is more complex, or differs from the
3074 semantic form, the ``HasCustomParsing`` bit can be set to ``1`` for the class,
3075 and the parsing code in `Parser::ParseGNUAttributeArgs()
3076 <https://github.com/llvm/llvm-project/blob/main/clang/lib/Parse/ParseDecl.cpp>`_
3077 can be updated for the special case. Note that this only applies to arguments
3078 with a GNU spelling -- attributes with a __declspec spelling currently ignore
3079 this flag and are handled by ``Parser::ParseMicrosoftDeclSpec``.
3081 Note that setting this member to 1 will opt out of common attribute semantic
3082 handling, requiring extra implementation efforts to ensure the attribute
3083 appertains to the appropriate subject, etc.
3085 If the attribute should not be propagated from a template declaration to an
3086 instantiation of the template, set the ``Clone`` member to 0. By default, all
3087 attributes will be cloned to template instantiations.
3089 Attributes that do not require an AST node should set the ``ASTNode`` field to
3090 ``0`` to avoid polluting the AST. Note that anything inheriting from
3091 ``TypeAttr`` or ``IgnoredAttr`` automatically do not generate an AST node. All
3092 other attributes generate an AST node by default. The AST node is the semantic
3093 representation of the attribute.
3095 The ``LangOpts`` field specifies a list of language options required by the
3096 attribute. For instance, all of the CUDA-specific attributes specify ``[CUDA]``
3097 for the ``LangOpts`` field, and when the CUDA language option is not enabled, an
3098 "attribute ignored" warning diagnostic is emitted. Since language options are
3099 not table generated nodes, new language options must be created manually and
3100 should specify the spelling used by ``LangOptions`` class.
3102 Custom accessors can be generated for an attribute based on the spelling list
3103 for that attribute. For instance, if an attribute has two different spellings:
3104 'Foo' and 'Bar', accessors can be created:
3105 ``[Accessor<"isFoo", [GNU<"Foo">]>, Accessor<"isBar", [GNU<"Bar">]>]``
3106 These accessors will be generated on the semantic form of the attribute,
3107 accepting no arguments and returning a ``bool``.
3109 Attributes that do not require custom semantic handling should set the
3110 ``SemaHandler`` field to ``0``. Note that anything inheriting from
3111 ``IgnoredAttr`` automatically do not get a semantic handler. All other
3112 attributes are assumed to use a semantic handler by default. Attributes
3113 without a semantic handler are not given a parsed attribute ``Kind`` enumerator.
3115 "Simple" attributes, that require no custom semantic processing aside from what
3116 is automatically provided, should set the ``SimpleHandler`` field to ``1``.
3118 Target-specific attributes may share a spelling with other attributes in
3119 different targets. For instance, the ARM and MSP430 targets both have an
3120 attribute spelled ``GNU<"interrupt">``, but with different parsing and semantic
3121 requirements. To support this feature, an attribute inheriting from
3122 ``TargetSpecificAttribute`` may specify a ``ParseKind`` field. This field
3123 should be the same value between all arguments sharing a spelling, and
3124 corresponds to the parsed attribute's ``Kind`` enumerator. This allows
3125 attributes to share a parsed attribute kind, but have distinct semantic
3126 attribute classes. For instance, ``ParsedAttr`` is the shared
3127 parsed attribute kind, but ARMInterruptAttr and MSP430InterruptAttr are the
3128 semantic attributes generated.
3130 By default, attribute arguments are parsed in an evaluated context. If the
3131 arguments for an attribute should be parsed in an unevaluated context (akin to
3132 the way the argument to a ``sizeof`` expression is parsed), set
3133 ``ParseArgumentsAsUnevaluated`` to ``1``.
3135 If additional functionality is desired for the semantic form of the attribute,
3136 the ``AdditionalMembers`` field specifies code to be copied verbatim into the
3137 semantic attribute class object, with ``public`` access.
3139 If two or more attributes cannot be used in combination on the same declaration
3140 or statement, a ``MutualExclusions`` definition can be supplied to automatically
3141 generate diagnostic code. This will disallow the attribute combinations
3142 regardless of spellings used. Additionally, it will diagnose combinations within
3143 the same attribute list, different attribute list, and redeclarations, as
3148 All semantic processing of declaration attributes happens in `lib/Sema/SemaDeclAttr.cpp
3149 <https://github.com/llvm/llvm-project/blob/main/clang/lib/Sema/SemaDeclAttr.cpp>`_,
3150 and generally starts in the ``ProcessDeclAttribute()`` function. If the
3151 attribute has the ``SimpleHandler`` field set to ``1`` then the function to
3152 process the attribute will be automatically generated, and nothing needs to be
3153 done here. Otherwise, write a new ``handleYourAttr()`` function, and add that to
3154 the switch statement. Please do not implement handling logic directly in the
3155 ``case`` for the attribute.
3157 Unless otherwise specified by the attribute definition, common semantic checking
3158 of the parsed attribute is handled automatically. This includes diagnosing
3159 parsed attributes that do not appertain to the given ``Decl`` or ``Stmt``,
3160 ensuring the correct minimum number of arguments are passed, etc.
3162 If the attribute adds additional warnings, define a ``DiagGroup`` in
3163 `include/clang/Basic/DiagnosticGroups.td
3164 <https://github.com/llvm/llvm-project/blob/main/clang/include/clang/Basic/DiagnosticGroups.td>`_
3165 named after the attribute's ``Spelling`` with "_"s replaced by "-"s. If there
3166 is only a single diagnostic, it is permissible to use ``InGroup<DiagGroup<"your-attribute">>``
3167 directly in `DiagnosticSemaKinds.td
3168 <https://github.com/llvm/llvm-project/blob/main/clang/include/clang/Basic/DiagnosticSemaKinds.td>`_
3170 All semantic diagnostics generated for your attribute, including automatically-
3171 generated ones (such as subjects and argument counts), should have a
3172 corresponding test case.
3176 Most attributes are implemented to have some effect on the compiler. For
3177 instance, to modify the way code is generated, or to add extra semantic checks
3178 for an analysis pass, etc. Having added the attribute definition and conversion
3179 to the semantic representation for the attribute, what remains is to implement
3180 the custom logic requiring use of the attribute.
3182 The ``clang::Decl`` object can be queried for the presence or absence of an
3183 attribute using ``hasAttr<T>()``. To obtain a pointer to the semantic
3184 representation of the attribute, ``getAttr<T>`` may be used.
3186 The ``clang::AttributedStmt`` object can be queried for the presence or absence
3187 of an attribute by calling ``getAttrs()`` and looping over the list of
3190 How to add an expression or statement
3191 -------------------------------------
3193 Expressions and statements are one of the most fundamental constructs within a
3194 compiler, because they interact with many different parts of the AST, semantic
3195 analysis, and IR generation. Therefore, adding a new expression or statement
3196 kind into Clang requires some care. The following list details the various
3197 places in Clang where an expression or statement needs to be introduced, along
3198 with patterns to follow to ensure that the new expression or statement works
3199 well across all of the C languages. We focus on expressions, but statements
3202 #. Introduce parsing actions into the parser. Recursive-descent parsing is
3203 mostly self-explanatory, but there are a few things that are worth keeping
3206 * Keep as much source location information as possible! You'll want it later
3207 to produce great diagnostics and support Clang's various features that map
3208 between source code and the AST.
3209 * Write tests for all of the "bad" parsing cases, to make sure your recovery
3210 is good. If you have matched delimiters (e.g., parentheses, square
3211 brackets, etc.), use ``Parser::BalancedDelimiterTracker`` to give nice
3212 diagnostics when things go wrong.
3214 #. Introduce semantic analysis actions into ``Sema``. Semantic analysis should
3215 always involve two functions: an ``ActOnXXX`` function that will be called
3216 directly from the parser, and a ``BuildXXX`` function that performs the
3217 actual semantic analysis and will (eventually!) build the AST node. It's
3218 fairly common for the ``ActOnXXX`` function to do very little (often just
3219 some minor translation from the parser's representation to ``Sema``'s
3220 representation of the same thing), but the separation is still important:
3221 C++ template instantiation, for example, should always call the ``BuildXXX``
3222 variant. Several notes on semantic analysis before we get into construction
3225 * Your expression probably involves some types and some subexpressions.
3226 Make sure to fully check that those types, and the types of those
3227 subexpressions, meet your expectations. Add implicit conversions where
3228 necessary to make sure that all of the types line up exactly the way you
3229 want them. Write extensive tests to check that you're getting good
3230 diagnostics for mistakes and that you can use various forms of
3231 subexpressions with your expression.
3232 * When type-checking a type or subexpression, make sure to first check
3233 whether the type is "dependent" (``Type::isDependentType()``) or whether a
3234 subexpression is type-dependent (``Expr::isTypeDependent()``). If any of
3235 these return ``true``, then you're inside a template and you can't do much
3236 type-checking now. That's normal, and your AST node (when you get there)
3237 will have to deal with this case. At this point, you can write tests that
3238 use your expression within templates, but don't try to instantiate the
3240 * For each subexpression, be sure to call ``Sema::CheckPlaceholderExpr()``
3241 to deal with "weird" expressions that don't behave well as subexpressions.
3242 Then, determine whether you need to perform lvalue-to-rvalue conversions
3243 (``Sema::DefaultLvalueConversions``) or the usual unary conversions
3244 (``Sema::UsualUnaryConversions``), for places where the subexpression is
3245 producing a value you intend to use.
3246 * Your ``BuildXXX`` function will probably just return ``ExprError()`` at
3247 this point, since you don't have an AST. That's perfectly fine, and
3248 shouldn't impact your testing.
3250 #. Introduce an AST node for your new expression. This starts with declaring
3251 the node in ``include/Basic/StmtNodes.td`` and creating a new class for your
3252 expression in the appropriate ``include/AST/Expr*.h`` header. It's best to
3253 look at the class for a similar expression to get ideas, and there are some
3254 specific things to watch for:
3256 * If you need to allocate memory, use the ``ASTContext`` allocator to
3257 allocate memory. Never use raw ``malloc`` or ``new``, and never hold any
3258 resources in an AST node, because the destructor of an AST node is never
3260 * Make sure that ``getSourceRange()`` covers the exact source range of your
3261 expression. This is needed for diagnostics and for IDE support.
3262 * Make sure that ``children()`` visits all of the subexpressions. This is
3263 important for a number of features (e.g., IDE support, C++ variadic
3264 templates). If you have sub-types, you'll also need to visit those
3265 sub-types in ``RecursiveASTVisitor``.
3266 * Add printing support (``StmtPrinter.cpp``) for your expression.
3267 * Add profiling support (``StmtProfile.cpp``) for your AST node, noting the
3268 distinguishing (non-source location) characteristics of an instance of
3269 your expression. Omitting this step will lead to hard-to-diagnose
3270 failures regarding matching of template declarations.
3271 * Add serialization support (``ASTReaderStmt.cpp``, ``ASTWriterStmt.cpp``)
3274 #. Teach semantic analysis to build your AST node. At this point, you can wire
3275 up your ``Sema::BuildXXX`` function to actually create your AST. A few
3276 things to check at this point:
3278 * If your expression can construct a new C++ class or return a new
3279 Objective-C object, be sure to update and then call
3280 ``Sema::MaybeBindToTemporary`` for your just-created AST node to be sure
3281 that the object gets properly destructed. An easy way to test this is to
3282 return a C++ class with a private destructor: semantic analysis should
3283 flag an error here with the attempt to call the destructor.
3284 * Inspect the generated AST by printing it using ``clang -cc1 -ast-print``,
3285 to make sure you're capturing all of the important information about how
3286 the AST was written.
3287 * Inspect the generated AST under ``clang -cc1 -ast-dump`` to verify that
3288 all of the types in the generated AST line up the way you want them.
3289 Remember that clients of the AST should never have to "think" to
3290 understand what's going on. For example, all implicit conversions should
3291 show up explicitly in the AST.
3292 * Write tests that use your expression as a subexpression of other,
3293 well-known expressions. Can you call a function using your expression as
3294 an argument? Can you use the ternary operator?
3296 #. Teach code generation to create IR to your AST node. This step is the first
3297 (and only) that requires knowledge of LLVM IR. There are several things to
3300 * Code generation is separated into scalar/aggregate/complex and
3301 lvalue/rvalue paths, depending on what kind of result your expression
3302 produces. On occasion, this requires some careful factoring of code to
3304 * ``CodeGenFunction`` contains functions ``ConvertType`` and
3305 ``ConvertTypeForMem`` that convert Clang's types (``clang::Type*`` or
3306 ``clang::QualType``) to LLVM types. Use the former for values, and the
3307 latter for memory locations: test with the C++ "``bool``" type to check
3308 this. If you find that you are having to use LLVM bitcasts to make the
3309 subexpressions of your expression have the type that your expression
3310 expects, STOP! Go fix semantic analysis and the AST so that you don't
3311 need these bitcasts.
3312 * The ``CodeGenFunction`` class has a number of helper functions to make
3313 certain operations easy, such as generating code to produce an lvalue or
3314 an rvalue, or to initialize a memory location with a given value. Prefer
3315 to use these functions rather than directly writing loads and stores,
3316 because these functions take care of some of the tricky details for you
3317 (e.g., for exceptions).
3318 * If your expression requires some special behavior in the event of an
3319 exception, look at the ``push*Cleanup`` functions in ``CodeGenFunction``
3320 to introduce a cleanup. You shouldn't have to deal with
3321 exception-handling directly.
3322 * Testing is extremely important in IR generation. Use ``clang -cc1
3323 -emit-llvm`` and `FileCheck
3324 <https://llvm.org/docs/CommandGuide/FileCheck.html>`_ to verify that you're
3325 generating the right IR.
3327 #. Teach template instantiation how to cope with your AST node, which requires
3328 some fairly simple code:
3330 * Make sure that your expression's constructor properly computes the flags
3331 for type dependence (i.e., the type your expression produces can change
3332 from one instantiation to the next), value dependence (i.e., the constant
3333 value your expression produces can change from one instantiation to the
3334 next), instantiation dependence (i.e., a template parameter occurs
3335 anywhere in your expression), and whether your expression contains a
3336 parameter pack (for variadic templates). Often, computing these flags
3337 just means combining the results from the various types and
3339 * Add ``TransformXXX`` and ``RebuildXXX`` functions to the ``TreeTransform``
3340 class template in ``Sema``. ``TransformXXX`` should (recursively)
3341 transform all of the subexpressions and types within your expression,
3342 using ``getDerived().TransformYYY``. If all of the subexpressions and
3343 types transform without error, it will then call the ``RebuildXXX``
3344 function, which will in turn call ``getSema().BuildXXX`` to perform
3345 semantic analysis and build your expression.
3346 * To test template instantiation, take those tests you wrote to make sure
3347 that you were type checking with type-dependent expressions and dependent
3348 types (from step #2) and instantiate those templates with various types,
3349 some of which type-check and some that don't, and test the error messages
3352 #. There are some "extras" that make other features work better. It's worth
3353 handling these extras to give your expression complete integration into
3356 * Add code completion support for your expression in
3357 ``SemaCodeComplete.cpp``.
3358 * If your expression has types in it, or has any "interesting" features
3359 other than subexpressions, extend libclang's ``CursorVisitor`` to provide
3360 proper visitation for your expression, enabling various IDE features such
3361 as syntax highlighting, cross-referencing, and so on. The
3362 ``c-index-test`` helper program can be used to test these features.
3366 All functional changes to Clang should come with test coverage demonstrating
3367 the change in behavior.
3369 .. _verifying-diagnostics:
3371 Verifying Diagnostics
3372 ^^^^^^^^^^^^^^^^^^^^^
3373 Clang ``-cc1`` supports the ``-verify`` command line option as a way to
3374 validate diagnostic behavior. This option will use special comments within the
3375 test file to verify that expected diagnostics appear in the correct source
3376 locations. If all of the expected diagnostics match the actual output of Clang,
3377 then the invocation will return normally. If there are discrepancies between
3378 the expected and actual output, Clang will emit detailed information about
3379 which expected diagnostics were not seen or which unexpected diagnostics were
3380 seen, etc. A complete example is:
3384 // RUN: %clang_cc1 -verify %s
3385 int A = B; // expected-error {{use of undeclared identifier 'B'}}
3387 If the test is run and the expected error is emitted on the expected line, the
3388 diagnostic verifier will pass. However, if the expected error does not appear
3389 or appears in a different location than expected, or if additional diagnostics
3390 appear, the diagnostic verifier will fail and emit information as to why.
3392 The ``-verify`` command optionally accepts a comma-delimited list of one or
3393 more verification prefixes that can be used to craft those special comments.
3394 Each prefix must start with a letter and contain only alphanumeric characters,
3395 hyphens, and underscores. ``-verify`` by itself is equivalent to
3396 ``-verify=expected``, meaning that special comments will start with
3397 ``expected``. Using different prefixes makes it easier to have separate
3398 ``RUN:`` lines in the same test file which result in differing diagnostic
3399 behavior. For example:
3403 // RUN: %clang_cc1 -verify=foo,bar %s
3405 int A = B; // foo-error {{use of undeclared identifier 'B'}}
3406 int C = D; // bar-error {{use of undeclared identifier 'D'}}
3407 int E = F; // expected-error {{use of undeclared identifier 'F'}}
3409 The verifier will recognize ``foo-error`` and ``bar-error`` as special comments
3410 but will not recognize ``expected-error`` as one because the ``-verify`` line
3411 does not contain that as a prefix. Thus, this test would fail verification
3412 because an unexpected diagnostic would appear on the declaration of ``E``.
3414 Multiple occurrences accumulate prefixes. For example,
3415 ``-verify -verify=foo,bar -verify=baz`` is equivalent to
3416 ``-verify=expected,foo,bar,baz``.
3418 Specifying Diagnostics
3419 ^^^^^^^^^^^^^^^^^^^^^^
3420 Indicating that a line expects an error or a warning is easy. Put a comment
3421 on the line that has the diagnostic, use
3422 ``expected-{error,warning,remark,note}`` to tag if it's an expected error,
3423 warning, remark, or note (respectively), and place the expected text between
3424 ``{{`` and ``}}`` markers. The full text doesn't have to be included, only
3425 enough to ensure that the correct diagnostic was emitted. (Note: full text
3426 should be included in test cases unless there is a compelling reason to use
3427 truncated text instead.)
3429 For a full description of the matching behavior, including more complex
3430 matching scenarios, see :ref:`matching <DiagnosticMatching>` below.
3432 Here's an example of the most commonly used way to specify expected
3437 int A = B; // expected-error {{use of undeclared identifier 'B'}}
3439 You can place as many diagnostics on one line as you wish. To make the code
3440 more readable, you can use slash-newline to separate out the diagnostics.
3442 Alternatively, it is possible to specify the line on which the diagnostic
3443 should appear by appending ``@<line>`` to ``expected-<type>``, for example:
3448 // expected-warning@10 {{some text}}
3450 The line number may be absolute (as above), or relative to the current line by
3451 prefixing the number with either ``+`` or ``-``.
3453 If the diagnostic is generated in a separate file, for example in a shared
3454 header file, it may be beneficial to be able to declare the file in which the
3455 diagnostic will appear, rather than placing the ``expected-*`` directive in the
3456 actual file itself. This can be done using the following syntax:
3460 // expected-error@path/include.h:15 {{error message}}
3462 The path can be absolute or relative and the same search paths will be used as
3463 for ``#include`` directives. The line number in an external file may be
3464 substituted with ``*`` meaning that any line number will match (useful where
3465 the included file is, for example, a system header where the actual line number
3466 may change and is not critical).
3468 As an alternative to specifying a fixed line number, the location of a
3469 diagnostic can instead be indicated by a marker of the form ``#<marker>``.
3470 Markers are specified by including them in a comment, and then referenced by
3471 appending the marker to the diagnostic with ``@#<marker>``, as with:
3475 #warning some text // #1
3476 // ... other code ...
3477 // expected-warning@#1 {{some text}}
3479 The name of a marker used in a directive must be unique within the compilation.
3481 The simple syntax above allows each specification to match exactly one
3482 diagnostic. You can use the extended syntax to customize this. The extended
3483 syntax is ``expected-<type> <n> {{diag text}}``, where ``<type>`` is one of
3484 ``error``, ``warning``, ``remark``, or ``note``, and ``<n>`` is a positive
3485 integer. This allows the diagnostic to appear as many times as specified. For
3490 void f(); // expected-note 2 {{previous declaration is here}}
3492 Where the diagnostic is expected to occur a minimum number of times, this can
3493 be specified by appending a ``+`` to the number. For example:
3497 void f(); // expected-note 0+ {{previous declaration is here}}
3498 void g(); // expected-note 1+ {{previous declaration is here}}
3500 In the first example, the diagnostic becomes optional, i.e. it will be
3501 swallowed if it occurs, but will not generate an error if it does not occur. In
3502 the second example, the diagnostic must occur at least once. As a short-hand,
3503 "one or more" can be specified simply by ``+``. For example:
3507 void g(); // expected-note + {{previous declaration is here}}
3509 A range can also be specified by ``<n>-<m>``. For example:
3513 void f(); // expected-note 0-1 {{previous declaration is here}}
3515 In this example, the diagnostic may appear only once, if at all.
3517 .. _DiagnosticMatching:
3522 The default matching mode is simple string, which looks for the expected text
3523 that appears between the first `{{` and `}}` pair of the comment. The string is
3524 interpreted just as-is, with one exception: the sequence `\n` is converted to a
3525 single newline character. This mode matches the emitted diagnostic when the
3526 text appears as a substring at any position of the emitted message.
3528 To enable matching against desired strings that contain `}}` or `{{`, the
3529 string-mode parser accepts opening delimiters of more than two curly braces,
3530 like `{{{`. It then looks for a closing delimiter of equal "width" (i.e `}}}`).
3535 // expected-note {{{evaluates to '{{2, 3, 4}} == {0, 3, 4}'}}}
3537 The intent is to allow the delimeter to be wider than the longest `{` or `}`
3538 brace sequence in the content, so that if your expected text contains `{{{`
3539 (three braces) it may be delimited with `{{{{` (four braces), and so on.
3541 Regex matching mode may be selected by appending ``-re`` to the diagnostic type
3542 and including regexes wrapped in double curly braces (`{{` and `}}`) in the
3545 .. code-block:: text
3547 expected-error-re {{format specifies type 'wchar_t **' (aka '{{.+}}')}}
3549 Examples matching error: "variable has incomplete type 'struct s'"
3553 // expected-error {{variable has incomplete type 'struct s'}}
3554 // expected-error {{variable has incomplete type}}
3555 // expected-error {{{variable has incomplete type}}}
3556 // expected-error {{{{variable has incomplete type}}}}
3558 // expected-error-re {{variable has type 'struct {{.}}'}}
3559 // expected-error-re {{variable has type 'struct {{.*}}'}}
3560 // expected-error-re {{variable has type 'struct {{(.*)}}'}}
3561 // expected-error-re {{variable has type 'struct{{[[:space:]](.*)}}'}}
3565 Clang implements several ways to test whether a feature is supported or not.
3566 Some of these feature tests are standardized, like ``__has_cpp_attribute`` or
3567 ``__cpp_lambdas``, while others are Clang extensions, like ``__has_builtin``.
3568 The common theme among all the various feature tests is that they are a utility
3569 to tell users that we think a particular feature is complete. However,
3570 completeness is a difficult property to define because features may still have
3571 lingering bugs, may only work on some targets, etc. We use the following
3572 criteria when deciding whether to expose a feature test macro (or particular
3573 result value for the feature test):
3575 * Are there known issues where we reject valid code that should be accepted?
3576 * Are there known issues where we accept invalid code that should be rejected?
3577 * Are there known crashes, failed assertions, or miscompilations?
3578 * Are there known issues on a particular relevant target?
3580 If the answer to any of these is "yes", the feature test macro should either
3581 not be defined or there should be very strong rationale for why the issues
3582 should not prevent defining it. Note, it is acceptable to define the feature
3583 test macro on a per-target basis if needed.
3585 When in doubt, being conservative is better than being aggressive. If we don't
3586 claim support for the feature but it does useful things, users can still use it
3587 and provide us with useful feedback on what is missing. But if we claim support
3588 for a feature that has significant bugs, we've eliminated most of the utility
3589 of having a feature testing macro at all because users are then forced to test
3590 what compiler version is in use to get a more accurate answer.
3592 The status reported by the feature test macro should always be reflected in the
3593 language support page for the corresponding feature (`C++
3594 <https://clang.llvm.org/cxx_status.html>`_, `C
3595 <https://clang.llvm.org/c_status.html>`_) if applicable. This page can give
3596 more nuanced information to the user as well, such as claiming partial support
3597 for a feature and specifying details as to what remains to be done.