Debian Codegraph @

clang/docs/InternalsManual.rst

raw
1 ============================
2 "Clang" CFE Internals Manual
3 ============================
4
5 .. contents::
6 :local:
7
8 Introduction
9 ============
10
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.
17
18 LLVM Support Library
19 ====================
20
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.
25
26 The Clang "Basic" Library
27 =========================
28
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.
33
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
39 some other solution.
40
41 We describe the roles of these classes in order of their dependencies.
42
43 The Diagnostics Subsystem
44 -------------------------
45
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.
54
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:
59
60 .. code-block:: text
61
62 t.c:38:15: error: invalid operands to binary expression ('int *' and '_Complex float')
63 P = (P-42) + Gamma*4;
64 ~~~~~~ ^ ~~~~~~~
65
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 :).
71
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
74 a new diagnostic.
75
76 The ``Diagnostic*Kinds.td`` files
77 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
78
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
83 string.
84
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.
89
90 The severity of the diagnostic comes from the set {``NOTE``, ``REMARK``,
91 ``WARNING``,
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.
104
105 These *severities* are mapped into a smaller set (the ``Diagnostic::Level``
106 enum, {``Ignored``, ``Note``, ``Remark``, ``Warning``, ``Error``, ``Fatal``}) of
107 output
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
114 example).
115
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.
120
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.
125
126 Diagnostic Wording
127 ^^^^^^^^^^^^^^^^^^
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.
131
132 * Diagnostics in Clang do not start with a capital letter and do not end with
133 punctuation.
134
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``
137 or ``C++17``.
138 * A trailing question mark is allowed. e.g., ``unknown identifier %0; did
139 you mean %1?``.
140
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
147 of Clang``.
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
164 The Format String
165 ^^^^^^^^^^^^^^^^^
166
167 The format string for the diagnostic is very simple, but it has some power. It
168 takes the form of a string in English with markers that indicate where and how
169 arguments to the diagnostic are inserted and formatted. For example, here are
170 some simple format strings:
171
172 .. code-block:: c++
173
174 "binary integer literals are an extension"
175 "format string contains '\\0' within the string body"
176 "more '%%' conversions than data arguments"
177 "invalid operands to binary expression (%0 and %1)"
178 "overloaded '%0' must be a %select{unary|binary|unary or binary}2 operator"
179 " (has %1 parameter%s1)"
180
181 These examples show some important points of format strings. You can use any
182 plain ASCII character in the diagnostic string except "``%``" without a
183 problem, but these are C strings, so you have to use and be aware of all the C
184 escape sequences (as in the second example). If you want to produce a "``%``"
185 in the output, use the "``%%``" escape sequence, like the third diagnostic.
186 Finally, Clang uses the "``%...[digit]``" sequences to specify where and how
187 arguments to the diagnostic are formatted.
188
189 Arguments to the diagnostic are numbered according to how they are specified by
190 the C++ code that :ref:`produces them <internals-producing-diag>`, and are
191 referenced by ``%0`` .. ``%9``. If you have more than 10 arguments to your
192 diagnostic, you are doing something wrong :). Unlike ``printf``, there is no
193 requirement that arguments to the diagnostic end up in the output in the same
194 order as they are specified, you could have a format string with "``%1 %0``"
195 that swaps them, for example. The text in between the percent and digit are
196 formatting instructions. If there are no instructions, the argument is just
197 turned into a string and substituted in.
198
199 Here are some "best practices" for writing the English format string:
200
201 * Keep the string short. It should ideally fit in the 80 column limit of the
202 ``DiagnosticKinds.td`` file. This avoids the diagnostic wrapping when
203 printed, and forces you to think about the important point you are conveying
204 with the diagnostic.
205 * Take advantage of location information. The user will be able to see the
206 line and location of the caret, so you don't need to tell them that the
207 problem is with the 4th argument to the function: just point to it.
208 * Do not capitalize the diagnostic string, and do not end it with a period.
209 * If you need to quote something in the diagnostic string, use single quotes.
210
211 Diagnostics should never take random English strings as arguments: you
212 shouldn't use "``you have a problem with %0``" and pass in things like "``your
213 argument``" or "``your return value``" as arguments. Doing this prevents
214 :ref:`translating <internals-diag-translation>` the Clang diagnostics to other
215 languages (because they'll get random English words in their otherwise
216 localized diagnostic). The exceptions to this are C/C++ language keywords
217 (e.g., ``auto``, ``const``, ``mutable``, etc) and C/C++ operators (``/=``).
218 Note that things like "pointer" and "reference" are not keywords. On the other
219 hand, you *can* include anything that comes from the user's source code,
220 including variable names, types, labels, etc. The "``select``" format can be
221 used to achieve this sort of thing in a localizable way, see below.
222
223 Formatting a Diagnostic Argument
224 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
225
226 Arguments to diagnostics are fully typed internally, and come from a couple
227 different classes: integers, types, names, and random strings. Depending on
228 the class of the argument, it can be optionally formatted in different ways.
229 This gives the ``DiagnosticConsumer`` information about what the argument means
230 without requiring it to use a specific presentation (consider this MVC for
231 Clang :).
232
233 It is really easy to add format specifiers to the Clang diagnostics system, but
234 they should be discussed before they are added. If you are creating a lot of
235 repetitive diagnostics and/or have an idea for a useful formatter, please bring
236 it up on the cfe-dev mailing list.
237
238 Here are the different diagnostic argument formats currently supported by
239 Clang:
240
241 **"s" format**
242
243 Example:
244 ``"requires %0 parameter%s0"``
245 Class:
246 Integers
247 Description:
248 This is a simple formatter for integers that is useful when producing English
249 diagnostics. When the integer is 1, it prints as nothing. When the integer
250 is not 1, it prints as "``s``". This allows some simple grammatical forms to
251 be to be handled correctly, and eliminates the need to use gross things like
252 ``"requires %1 parameter(s)"``. Note, this only handles adding a simple
253 "``s``" character, it will not handle situations where pluralization is more
254 complicated such as turning ``fancy`` into ``fancies`` or ``mouse`` into
255 ``mice``. You can use the "plural" format specifier to handle such situations.
256
257 **"select" format**
258
259 Example:
260 ``"must be a %select{unary|binary|unary or binary}0 operator"``
261 Class:
262 Integers
263 Description:
264 This format specifier is used to merge multiple related diagnostics together
265 into one common one, without requiring the difference to be specified as an
266 English string argument. Instead of specifying the string, the diagnostic
267 gets an integer argument and the format string selects the numbered option.
268 In this case, the "``%0``" value must be an integer in the range [0..2]. If
269 it is 0, it prints "unary", if it is 1 it prints "binary" if it is 2, it
270 prints "unary or binary". This allows other language translations to
271 substitute reasonable words (or entire phrases) based on the semantics of the
272 diagnostic instead of having to do things textually. The selected string
273 does undergo formatting.
274
275 **"plural" format**
276
277 Example:
278 ``"you have %0 %plural{1:mouse|:mice}0 connected to your computer"``
279 Class:
280 Integers
281 Description:
282 This is a formatter for complex plural forms. It is designed to handle even
283 the requirements of languages with very complex plural forms, as many Baltic
284 languages have. The argument consists of a series of expression/form pairs,
285 separated by ":", where the first form whose expression evaluates to true is
286 the result of the modifier.
287
288 An expression can be empty, in which case it is always true. See the example
289 at the top. Otherwise, it is a series of one or more numeric conditions,
290 separated by ",". If any condition matches, the expression matches. Each
291 numeric condition can take one of three forms.
292
293 * number: A simple decimal number matches if the argument is the same as the
294 number. Example: ``"%plural{1:mouse|:mice}0"``
295 * range: A range in square brackets matches if the argument is within the
296 range. Then range is inclusive on both ends. Example:
297 ``"%plural{0:none|1:one|[2,5]:some|:many}0"``
298 * modulo: A modulo operator is followed by a number, and equals sign and
299 either a number or a range. The tests are the same as for plain numbers
300 and ranges, but the argument is taken modulo the number first. Example:
301 ``"%plural{%100=0:even hundred|%100=[1,50]:lower half|:everything else}1"``
302
303 The parser is very unforgiving. A syntax error, even whitespace, will abort,
304 as will a failure to match the argument against any expression.
305
306 **"ordinal" format**
307
308 Example:
309 ``"ambiguity in %ordinal0 argument"``
310 Class:
311 Integers
312 Description:
313 This is a formatter which represents the argument number as an ordinal: the
314 value ``1`` becomes ``1st``, ``3`` becomes ``3rd``, and so on. Values less
315 than ``1`` are not supported. This formatter is currently hard-coded to use
316 English ordinals.
317
318 **"objcclass" format**
319
320 Example:
321 ``"method %objcclass0 not found"``
322 Class:
323 ``DeclarationName``
324 Description:
325 This is a simple formatter that indicates the ``DeclarationName`` corresponds
326 to an Objective-C class method selector. As such, it prints the selector
327 with a leading "``+``".
328
329 **"objcinstance" format**
330
331 Example:
332 ``"method %objcinstance0 not found"``
333 Class:
334 ``DeclarationName``
335 Description:
336 This is a simple formatter that indicates the ``DeclarationName`` corresponds
337 to an Objective-C instance method selector. As such, it prints the selector
338 with a leading "``-``".
339
340 **"q" format**
341
342 Example:
343 ``"candidate found by name lookup is %q0"``
344 Class:
345 ``NamedDecl *``
346 Description:
347 This formatter indicates that the fully-qualified name of the declaration
348 should be printed, e.g., "``std::vector``" rather than "``vector``".
349
350 **"diff" format**
351
352 Example:
353 ``"no known conversion %diff{from $ to $|from argument type to parameter type}1,2"``
354 Class:
355 ``QualType``
356 Description:
357 This formatter takes two ``QualType``\ s and attempts to print a template
358 difference between the two. If tree printing is off, the text inside the
359 braces before the pipe is printed, with the formatted text replacing the $.
360 If tree printing is on, the text after the pipe is printed and a type tree is
361 printed after the diagnostic message.
362
363 **"sub" format**
364
365 Example:
366 Given the following record definition of type ``TextSubstitution``:
367
368 .. code-block:: text
369
370 def select_ovl_candidate : TextSubstitution<
371 "%select{function|constructor}0%select{| template| %2}1">;
372
373 which can be used as
374
375 .. code-block:: text
376
377 def note_ovl_candidate : Note<
378 "candidate %sub{select_ovl_candidate}3,2,1 not viable">;
379
380 and will act as if it was written
381 ``"candidate %select{function|constructor}3%select{| template| %1}2 not viable"``.
382 Description:
383 This format specifier is used to avoid repeating strings verbatim in multiple
384 diagnostics. The argument to ``%sub`` must name a ``TextSubstitution`` tblgen
385 record. The substitution must specify all arguments used by the substitution,
386 and the modifier indexes in the substitution are re-numbered accordingly. The
387 substituted text must itself be a valid format string before substitution.
388
389 .. _internals-producing-diag:
390
391 Producing the Diagnostic
392 ^^^^^^^^^^^^^^^^^^^^^^^^
393
394 Now that you've created the diagnostic in the ``Diagnostic*Kinds.td`` file, you
395 need to write the code that detects the condition in question and emits the new
396 diagnostic. Various components of Clang (e.g., the preprocessor, ``Sema``,
397 etc.) provide a helper function named "``Diag``". It creates a diagnostic and
398 accepts the arguments, ranges, and other information that goes along with it.
399
400 For example, the binary expression error comes from code like this:
401
402 .. code-block:: c++
403
404 if (various things that are bad)
405 Diag(Loc, diag::err_typecheck_invalid_operands)
406 << lex->getType() << rex->getType()
407 << lex->getSourceRange() << rex->getSourceRange();
408
409 This shows that use of the ``Diag`` method: it takes a location (a
410 :ref:`SourceLocation <SourceLocation>` object) and a diagnostic enum value
411 (which matches the name from ``Diagnostic*Kinds.td``). If the diagnostic takes
412 arguments, they are specified with the ``<<`` operator: the first argument
413 becomes ``%0``, the second becomes ``%1``, etc. The diagnostic interface
414 allows you to specify arguments of many different types, including ``int`` and
415 ``unsigned`` for integer arguments, ``const char*`` and ``std::string`` for
416 string arguments, ``DeclarationName`` and ``const IdentifierInfo *`` for names,
417 ``QualType`` for types, etc. ``SourceRange``\ s are also specified with the
418 ``<<`` operator, but do not have a specific ordering requirement.
419
420 As you can see, adding and producing a diagnostic is pretty straightforward.
421 The hard part is deciding exactly what you need to say to help the user,
422 picking a suitable wording, and providing the information needed to format it
423 correctly. The good news is that the call site that issues a diagnostic should
424 be completely independent of how the diagnostic is formatted and in what
425 language it is rendered.
426
427 Fix-It Hints
428 ^^^^^^^^^^^^
429
430 In some cases, the front end emits diagnostics when it is clear that some small
431 change to the source code would fix the problem. For example, a missing
432 semicolon at the end of a statement or a use of deprecated syntax that is
433 easily rewritten into a more modern form. Clang tries very hard to emit the
434 diagnostic and recover gracefully in these and other cases.
435
436 However, for these cases where the fix is obvious, the diagnostic can be
437 annotated with a hint (referred to as a "fix-it hint") that describes how to
438 change the code referenced by the diagnostic to fix the problem. For example,
439 it might add the missing semicolon at the end of the statement or rewrite the
440 use of a deprecated construct into something more palatable. Here is one such
441 example from the C++ front end, where we warn about the right-shift operator
442 changing meaning from C++98 to C++11:
443
444 .. code-block:: text
445
446 test.cpp:3:7: warning: use of right-shift operator ('>>') in template argument
447 will require parentheses in C++11
448 A<100 >> 2> *a;
449 ^
450 ( )
451
452 Here, the fix-it hint is suggesting that parentheses be added, and showing
453 exactly where those parentheses would be inserted into the source code. The
454 fix-it hints themselves describe what changes to make to the source code in an
455 abstract manner, which the text diagnostic printer renders as a line of
456 "insertions" below the caret line. :ref:`Other diagnostic clients
457 <DiagnosticConsumer>` might choose to render the code differently (e.g., as
458 markup inline) or even give the user the ability to automatically fix the
459 problem.
460
461 Fix-it hints on errors and warnings need to obey these rules:
462
463 * Since they are automatically applied if ``-Xclang -fixit`` is passed to the
464 driver, they should only be used when it's very likely they match the user's
465 intent.
466 * Clang must recover from errors as if the fix-it had been applied.
467 * Fix-it hints on a warning must not change the meaning of the code.
468 However, a hint may clarify the meaning as intentional, for example by adding
469 parentheses when the precedence of operators isn't obvious.
470
471 If a fix-it can't obey these rules, put the fix-it on a note. Fix-its on notes
472 are not applied automatically.
473
474 All fix-it hints are described by the ``FixItHint`` class, instances of which
475 should be attached to the diagnostic using the ``<<`` operator in the same way
476 that highlighted source ranges and arguments are passed to the diagnostic.
477 Fix-it hints can be created with one of three constructors:
478
479 * ``FixItHint::CreateInsertion(Loc, Code)``
480
481 Specifies that the given ``Code`` (a string) should be inserted before the
482 source location ``Loc``.
483
484 * ``FixItHint::CreateRemoval(Range)``
485
486 Specifies that the code in the given source ``Range`` should be removed.
487
488 * ``FixItHint::CreateReplacement(Range, Code)``
489
490 Specifies that the code in the given source ``Range`` should be removed,
491 and replaced with the given ``Code`` string.
492
493 .. _DiagnosticConsumer:
494
495 The ``DiagnosticConsumer`` Interface
496 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
497
498 Once code generates a diagnostic with all of the arguments and the rest of the
499 relevant information, Clang needs to know what to do with it. As previously
500 mentioned, the diagnostic machinery goes through some filtering to map a
501 severity onto a diagnostic level, then (assuming the diagnostic is not mapped
502 to "``Ignore``") it invokes an object that implements the ``DiagnosticConsumer``
503 interface with the information.
504
505 It is possible to implement this interface in many different ways. For
506 example, the normal Clang ``DiagnosticConsumer`` (named
507 ``TextDiagnosticPrinter``) turns the arguments into strings (according to the
508 various formatting rules), prints out the file/line/column information and the
509 string, then prints out the line of code, the source ranges, and the caret.
510 However, this behavior isn't required.
511
512 Another implementation of the ``DiagnosticConsumer`` interface is the
513 ``TextDiagnosticBuffer`` class, which is used when Clang is in ``-verify``
514 mode. Instead of formatting and printing out the diagnostics, this
515 implementation just captures and remembers the diagnostics as they fly by.
516 Then ``-verify`` compares the list of produced diagnostics to the list of
517 expected ones. If they disagree, it prints out its own output. Full
518 documentation for the ``-verify`` mode can be found at
519 :ref:`verifying-diagnostics`.
520
521 There are many other possible implementations of this interface, and this is
522 why we prefer diagnostics to pass down rich structured information in
523 arguments. For example, an HTML output might want declaration names be
524 linkified to where they come from in the source. Another example is that a GUI
525 might let you click on typedefs to expand them. This application would want to
526 pass significantly more information about types through to the GUI than a
527 simple flat string. The interface allows this to happen.
528
529 .. _internals-diag-translation:
530
531 Adding Translations to Clang
532 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
533
534 Not possible yet! Diagnostic strings should be written in UTF-8, the client can
535 translate to the relevant code page if needed. Each translation completely
536 replaces the format string for the diagnostic.
537
538 .. _SourceLocation:
539 .. _SourceManager:
540
541 The ``SourceLocation`` and ``SourceManager`` classes
542 ----------------------------------------------------
543
544 Strangely enough, the ``SourceLocation`` class represents a location within the
545 source code of the program. Important design points include:
546
547 #. ``sizeof(SourceLocation)`` must be extremely small, as these are embedded
548 into many AST nodes and are passed around often. Currently it is 32 bits.
549 #. ``SourceLocation`` must be a simple value object that can be efficiently
550 copied.
551 #. We should be able to represent a source location for any byte of any input
552 file. This includes in the middle of tokens, in whitespace, in trigraphs,
553 etc.
554 #. A ``SourceLocation`` must encode the current ``#include`` stack that was
555 active when the location was processed. For example, if the location
556 corresponds to a token, it should contain the set of ``#include``\ s active
557 when the token was lexed. This allows us to print the ``#include`` stack
558 for a diagnostic.
559 #. ``SourceLocation`` must be able to describe macro expansions, capturing both
560 the ultimate instantiation point and the source of the original character
561 data.
562
563 In practice, the ``SourceLocation`` works together with the ``SourceManager``
564 class to encode two pieces of information about a location: its spelling
565 location and its expansion location. For most tokens, these will be the
566 same. However, for a macro expansion (or tokens that came from a ``_Pragma``
567 directive) these will describe the location of the characters corresponding to
568 the token and the location where the token was used (i.e., the macro
569 expansion point or the location of the ``_Pragma`` itself).
570
571 The Clang front-end inherently depends on the location of a token being tracked
572 correctly. If it is ever incorrect, the front-end may get confused and die.
573 The reason for this is that the notion of the "spelling" of a ``Token`` in
574 Clang depends on being able to find the original input characters for the
575 token. This concept maps directly to the "spelling location" for the token.
576
577 ``SourceRange`` and ``CharSourceRange``
578 ---------------------------------------
579
580 .. mostly taken from https://discourse.llvm.org/t/code-ranges-of-tokens-ast-elements/16893/2
581
582 Clang represents most source ranges by [first, last], where "first" and "last"
583 each point to the beginning of their respective tokens. For example consider
584 the ``SourceRange`` of the following statement:
585
586 .. code-block:: text
587
588 x = foo + bar;
589 ^first ^last
590
591 To map from this representation to a character-based representation, the "last"
592 location needs to be adjusted to point to (or past) the end of that token with
593 either ``Lexer::MeasureTokenLength()`` or ``Lexer::getLocForEndOfToken()``. For
594 the rare cases where character-level source ranges information is needed we use
595 the ``CharSourceRange`` class.
596
597 The Driver Library
598 ==================
599
600 The clang Driver and library are documented :doc:`here <DriverInternals>`.
601
602 Precompiled Headers
603 ===================
604
605 Clang supports precompiled headers (:doc:`PCH <PCHInternals>`), which uses a
606 serialized representation of Clang's internal data structures, encoded with the
607 `LLVM bitstream format <https://llvm.org/docs/BitCodeFormat.html>`_.
608
609 The Frontend Library
610 ====================
611
612 The Frontend library contains functionality useful for building tools on top of
613 the Clang libraries, for example several methods for outputting diagnostics.
614
615 Compiler Invocation
616 -------------------
617
618 One of the classes provided by the Frontend library is ``CompilerInvocation``,
619 which holds information that describe current invocation of the Clang ``-cc1``
620 frontend. The information typically comes from the command line constructed by
621 the Clang driver or from clients performing custom initialization. The data
622 structure is split into logical units used by different parts of the compiler,
623 for example ``PreprocessorOptions``, ``LanguageOptions`` or ``CodeGenOptions``.
624
625 Command Line Interface
626 ----------------------
627
628 The command line interface of the Clang ``-cc1`` frontend is defined alongside
629 the driver options in ``clang/Driver/Options.td``. The information making up an
630 option definition includes its prefix and name (for example ``-std=``), form and
631 position of the option value, help text, aliases and more. Each option may
632 belong to a certain group and can be marked with zero or more flags. Options
633 accepted by the ``-cc1`` frontend are marked with the ``CC1Option`` flag.
634
635 Command Line Parsing
636 --------------------
637
638 Option definitions are processed by the ``-gen-opt-parser-defs`` tablegen
639 backend during early stages of the build. Options are then used for querying an
640 instance ``llvm::opt::ArgList``, a wrapper around the command line arguments.
641 This is done in the Clang driver to construct individual jobs based on the
642 driver arguments and also in the ``CompilerInvocation::CreateFromArgs`` function
643 that parses the ``-cc1`` frontend arguments.
644
645 Command Line Generation
646 -----------------------
647
648 Any valid ``CompilerInvocation`` created from a ``-cc1`` command line can be
649 also serialized back into semantically equivalent command line in a
650 deterministic manner. This enables features such as implicitly discovered,
651 explicitly built modules.
652
653 ..
654 TODO: Create and link corresponding section in Modules.rst.
655
656 Adding new Command Line Option
657 ------------------------------
658
659 When adding a new command line option, the first place of interest is the header
660 file declaring the corresponding options class (e.g. ``CodeGenOptions.h`` for
661 command line option that affects the code generation). Create new member
662 variable for the option value:
663
664 .. code-block:: diff
665
666 class CodeGenOptions : public CodeGenOptionsBase {
667
668 + /// List of dynamic shared object files to be loaded as pass plugins.
669 + std::vector<std::string> PassPlugins;
670
671 }
672
673 Next, declare the command line interface of the option in the tablegen file
674 ``clang/include/clang/Driver/Options.td``. This is done by instantiating the
675 ``Option`` class (defined in ``llvm/include/llvm/Option/OptParser.td``). The
676 instance is typically created through one of the helper classes that encode the
677 acceptable ways to specify the option value on the command line:
678
679 * ``Flag`` - the option does not accept any value,
680 * ``Joined`` - the value must immediately follow the option name within the same
681 argument,
682 * ``Separate`` - the value must follow the option name in the next command line
683 argument,
684 * ``JoinedOrSeparate`` - the value can be specified either as ``Joined`` or
685 ``Separate``,
686 * ``CommaJoined`` - the values are comma-separated and must immediately follow
687 the option name within the same argument (see ``Wl,`` for an example).
688
689 The helper classes take a list of acceptable prefixes of the option (e.g.
690 ``"-"``, ``"--"`` or ``"/"``) and the option name:
691
692 .. code-block:: diff
693
694 // Options.td
695
696 + def fpass_plugin_EQ : Joined<["-"], "fpass-plugin=">;
697
698 Then, specify additional attributes via mix-ins:
699
700 * ``HelpText`` holds the text that will be printed besides the option name when
701 the user requests help (e.g. via ``clang --help``).
702 * ``Group`` specifies the "category" of options this option belongs to. This is
703 used by various tools to categorize and sometimes filter options.
704 * ``Flags`` may contain "tags" associated with the option. These may affect how
705 the option is rendered, or if it's hidden in some contexts.
706 * ``Visibility`` should be used to specify the drivers in which a particular
707 option would be available. This attribute will impact tool --help
708 * ``Alias`` denotes that the option is an alias of another option. This may be
709 combined with ``AliasArgs`` that holds the implied value.
710
711 .. code-block:: diff
712
713 // Options.td
714
715 def fpass_plugin_EQ : Joined<["-"], "fpass-plugin=">,
716 + Group<f_Group>, Visibility<[ClangOption, CC1Option]>,
717 + HelpText<"Load pass plugin from a dynamic shared object file.">;
718
719 New options are recognized by the ``clang`` driver mode if ``Visibility`` is
720 not specified or contains ``ClangOption``. Options intended for ``clang -cc1``
721 must be explicitly marked with the ``CC1Option`` flag. Flags that specify
722 ``CC1Option`` but not ``ClangOption`` will only be accessible via ``-cc1``.
723 This is similar for other driver modes, such as ``clang-cl`` or ``flang``.
724
725 Next, parse (or manufacture) the command line arguments in the Clang driver and
726 use them to construct the ``-cc1`` job:
727
728 .. code-block:: diff
729
730 void Clang::ConstructJob(const ArgList &Args /*...*/) const {
731 ArgStringList CmdArgs;
732 // ...
733
734 + for (const Arg *A : Args.filtered(OPT_fpass_plugin_EQ)) {
735 + CmdArgs.push_back(Args.MakeArgString(Twine("-fpass-plugin=") + A->getValue()));
736 + A->claim();
737 + }
738 }
739
740 The last step is implementing the ``-cc1`` command line argument
741 parsing/generation that initializes/serializes the option class (in our case
742 ``CodeGenOptions``) stored within ``CompilerInvocation``. This can be done
743 automatically by using the marshalling annotations on the option definition:
744
745 .. code-block:: diff
746
747 // Options.td
748
749 def fpass_plugin_EQ : Joined<["-"], "fpass-plugin=">,
750 Group<f_Group>, Flags<[CC1Option]>,
751 HelpText<"Load pass plugin from a dynamic shared object file.">,
752 + MarshallingInfoStringVector<CodeGenOpts<"PassPlugins">>;
753
754 Inner workings of the system are introduced in the :ref:`marshalling
755 infrastructure <OptionMarshalling>` section and the available annotations are
756 listed :ref:`here <OptionMarshallingAnnotations>`.
757
758 In case the marshalling infrastructure does not support the desired semantics,
759 consider simplifying it to fit the existing model. This makes the command line
760 more uniform and reduces the amount of custom, manually written code. Remember
761 that the ``-cc1`` command line interface is intended only for Clang developers,
762 meaning it does not need to mirror the driver interface, maintain backward
763 compatibility or be compatible with GCC.
764
765 If the option semantics cannot be encoded via marshalling annotations, you can
766 resort to parsing/serializing the command line arguments manually:
767
768 .. code-block:: diff
769
770 // CompilerInvocation.cpp
771
772 static bool ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args /*...*/) {
773 // ...
774
775 + Opts.PassPlugins = Args.getAllArgValues(OPT_fpass_plugin_EQ);
776 }
777
778 static void GenerateCodeGenArgs(const CodeGenOptions &Opts,
779 SmallVectorImpl<const char *> &Args,
780 CompilerInvocation::StringAllocator SA /*...*/) {
781 // ...
782
783 + for (const std::string &PassPlugin : Opts.PassPlugins)
784 + GenerateArg(Args, OPT_fpass_plugin_EQ, PassPlugin, SA);
785 }
786
787 Finally, you can specify the argument on the command line:
788 ``clang -fpass-plugin=a -fpass-plugin=b`` and use the new member variable as
789 desired.
790
791 .. code-block:: diff
792
793 void EmitAssemblyHelper::EmitAssemblyWithNewPassManager(/*...*/) {
794 // ...
795 + for (auto &PluginFN : CodeGenOpts.PassPlugins)
796 + if (auto PassPlugin = PassPlugin::Load(PluginFN))
797 + PassPlugin->registerPassBuilderCallbacks(PB);
798 }
799
800 .. _OptionMarshalling:
801
802 Option Marshalling Infrastructure
803 ---------------------------------
804
805 The option marshalling infrastructure automates the parsing of the Clang
806 ``-cc1`` frontend command line arguments into ``CompilerInvocation`` and their
807 generation from ``CompilerInvocation``. The system replaces lots of repetitive
808 C++ code with simple, declarative tablegen annotations and it's being used for
809 the majority of the ``-cc1`` command line interface. This section provides an
810 overview of the system.
811
812 **Note:** The marshalling infrastructure is not intended for driver-only
813 options. Only options of the ``-cc1`` frontend need to be marshalled to/from
814 ``CompilerInvocation`` instance.
815
816 To read and modify contents of ``CompilerInvocation``, the marshalling system
817 uses key paths, which are declared in two steps. First, a tablegen definition
818 for the ``CompilerInvocation`` member is created by inheriting from
819 ``KeyPathAndMacro``:
820
821 .. code-block:: text
822
823 // Options.td
824
825 class LangOpts<string field> : KeyPathAndMacro<"LangOpts->", field, "LANG_"> {}
826 // CompilerInvocation member ^^^^^^^^^^
827 // OPTION_WITH_MARSHALLING prefix ^^^^^
828
829 The first argument to the parent class is the beginning of the key path that
830 references the ``CompilerInvocation`` member. This argument ends with ``->`` if
831 the member is a pointer type or with ``.`` if it's a value type. The child class
832 takes a single parameter ``field`` that is forwarded as the second argument to
833 the base class. The child class can then be used like so:
834 ``LangOpts<"IgnoreExceptions">``, constructing a key path to the field
835 ``LangOpts->IgnoreExceptions``. The third argument passed to the parent class is
836 a string that the tablegen backend uses as a prefix to the
837 ``OPTION_WITH_MARSHALLING`` macro. Using the key path as a mix-in on an
838 ``Option`` instance instructs the backend to generate the following code:
839
840 .. code-block:: c++
841
842 // Options.inc
843
844 #ifdef LANG_OPTION_WITH_MARSHALLING
845 LANG_OPTION_WITH_MARSHALLING([...], LangOpts->IgnoreExceptions, [...])
846 #endif // LANG_OPTION_WITH_MARSHALLING
847
848 Such definition can be used used in the function for parsing and generating
849 command line:
850
851 .. code-block:: c++
852
853 // clang/lib/Frontend/CompilerInvoation.cpp
854
855 bool CompilerInvocation::ParseLangArgs(LangOptions *LangOpts, ArgList &Args,
856 DiagnosticsEngine &Diags) {
857 bool Success = true;
858
859 #define LANG_OPTION_WITH_MARSHALLING( \
860 PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
861 HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
862 DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
863 MERGER, EXTRACTOR, TABLE_INDEX) \
864 PARSE_OPTION_WITH_MARSHALLING(Args, Diags, Success, ID, FLAGS, PARAM, \
865 SHOULD_PARSE, KEYPATH, DEFAULT_VALUE, \
866 IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, \
867 MERGER, TABLE_INDEX)
868 #include "clang/Driver/Options.inc"
869 #undef LANG_OPTION_WITH_MARSHALLING
870
871 // ...
872
873 return Success;
874 }
875
876 void CompilerInvocation::GenerateLangArgs(LangOptions *LangOpts,
877 SmallVectorImpl<const char *> &Args,
878 StringAllocator SA) {
879 #define LANG_OPTION_WITH_MARSHALLING( \
880 PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
881 HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
882 DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
883 MERGER, EXTRACTOR, TABLE_INDEX) \
884 GENERATE_OPTION_WITH_MARSHALLING( \
885 Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE, \
886 IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
887 #include "clang/Driver/Options.inc"
888 #undef LANG_OPTION_WITH_MARSHALLING
889
890 // ...
891 }
892
893 The ``PARSE_OPTION_WITH_MARSHALLING`` and ``GENERATE_OPTION_WITH_MARSHALLING``
894 macros are defined in ``CompilerInvocation.cpp`` and they implement the generic
895 algorithm for parsing and generating command line arguments.
896
897 .. _OptionMarshallingAnnotations:
898
899 Option Marshalling Annotations
900 ------------------------------
901
902 How does the tablegen backend know what to put in place of ``[...]`` in the
903 generated ``Options.inc``? This is specified by the ``Marshalling`` utilities
904 described below. All of them take a key path argument and possibly other
905 information required for parsing or generating the command line argument.
906
907 **Note:** The marshalling infrastructure is not intended for driver-only
908 options. Only options of the ``-cc1`` frontend need to be marshalled to/from
909 ``CompilerInvocation`` instance.
910
911 **Positive Flag**
912
913 The key path defaults to ``false`` and is set to ``true`` when the flag is
914 present on command line.
915
916 .. code-block:: text
917
918 def fignore_exceptions : Flag<["-"], "fignore-exceptions">,
919 Visibility<[ClangOption, CC1Option]>,
920 MarshallingInfoFlag<LangOpts<"IgnoreExceptions">>;
921
922 **Negative Flag**
923
924 The key path defaults to ``true`` and is set to ``false`` when the flag is
925 present on command line.
926
927 .. code-block:: text
928
929 def fno_verbose_asm : Flag<["-"], "fno-verbose-asm">,
930 Visibility<[ClangOption, CC1Option]>,
931 MarshallingInfoNegativeFlag<CodeGenOpts<"AsmVerbose">>;
932
933 **Negative and Positive Flag**
934
935 The key path defaults to the specified value (``false``, ``true`` or some
936 boolean value that's statically unknown in the tablegen file). Then, the key
937 path is set to the value associated with the flag that appears last on command
938 line.
939
940 .. code-block:: text
941
942 defm legacy_pass_manager : BoolOption<"f", "legacy-pass-manager",
943 CodeGenOpts<"LegacyPassManager">, DefaultFalse,
944 PosFlag<SetTrue, [], [], "Use the legacy pass manager in LLVM">,
945 NegFlag<SetFalse, [], [], "Use the new pass manager in LLVM">,
946 BothFlags<[], [ClangOption, CC1Option]>>;
947
948 With most such pair of flags, the ``-cc1`` frontend accepts only the flag that
949 changes the default key path value. The Clang driver is responsible for
950 accepting both and either forwarding the changing flag or discarding the flag
951 that would just set the key path to its default.
952
953 The first argument to ``BoolOption`` is a prefix that is used to construct the
954 full names of both flags. The positive flag would then be named
955 ``flegacy-pass-manager`` and the negative ``fno-legacy-pass-manager``.
956 ``BoolOption`` also implies the ``-`` prefix for both flags. It's also possible
957 to use ``BoolFOption`` that implies the ``"f"`` prefix and ``Group<f_Group>``.
958 The ``PosFlag`` and ``NegFlag`` classes hold the associated boolean value,
959 arrays of elements passed to the ``Flag`` and ``Visibility`` classes and the
960 help text. The optional ``BothFlags`` class holds arrays of ``Flag`` and
961 ``Visibility`` elements that are common for both the positive and negative flag
962 and their common help text suffix.
963
964 **String**
965
966 The key path defaults to the specified string, or an empty one, if omitted. When
967 the option appears on the command line, the argument value is simply copied.
968
969 .. code-block:: text
970
971 def isysroot : JoinedOrSeparate<["-"], "isysroot">,
972 Visibility<[ClangOption, CC1Option, FlangOption]>,
973 MarshallingInfoString<HeaderSearchOpts<"Sysroot">, [{"/"}]>;
974
975 **List of Strings**
976
977 The key path defaults to an empty ``std::vector<std::string>``. Values specified
978 with each appearance of the option on the command line are appended to the
979 vector.
980
981 .. code-block:: text
982
983 def frewrite_map_file : Separate<["-"], "frewrite-map-file">,
984 Visibility<[ClangOption, CC1Option]>,
985 MarshallingInfoStringVector<CodeGenOpts<"RewriteMapFiles">>;
986
987 **Integer**
988
989 The key path defaults to the specified integer value, or ``0`` if omitted. When
990 the option appears on the command line, its value gets parsed by ``llvm::APInt``
991 and the result is assigned to the key path on success.
992
993 .. code-block:: text
994
995 def mstack_probe_size : Joined<["-"], "mstack-probe-size=">,
996 Visibility<[ClangOption, CC1Option]>,
997 MarshallingInfoInt<CodeGenOpts<"StackProbeSize">, "4096">;
998
999 **Enumeration**
1000
1001 The key path defaults to the value specified in ``MarshallingInfoEnum`` prefixed
1002 by the contents of ``NormalizedValuesScope`` and ``::``. This ensures correct
1003 reference to an enum case is formed even if the enum resides in different
1004 namespace or is an enum class. If the value present on command line does not
1005 match any of the comma-separated values from ``Values``, an error diagnostics is
1006 issued. Otherwise, the corresponding element from ``NormalizedValues`` at the
1007 same index is assigned to the key path (also correctly scoped). The number of
1008 comma-separated string values and elements of the array within
1009 ``NormalizedValues`` must match.
1010
1011 .. code-block:: text
1012
1013 def mthread_model : Separate<["-"], "mthread-model">,
1014 Visibility<[ClangOption, CC1Option]>,
1015 Values<"posix,single">, NormalizedValues<["POSIX", "Single"]>,
1016 NormalizedValuesScope<"LangOptions::ThreadModelKind">,
1017 MarshallingInfoEnum<LangOpts<"ThreadModel">, "POSIX">;
1018
1019 ..
1020 Intentionally omitting MarshallingInfoBitfieldFlag. It's adding some
1021 complexity to the marshalling infrastructure and might be removed.
1022
1023 It is also possible to define relationships between options.
1024
1025 **Implication**
1026
1027 The key path defaults to the default value from the primary ``Marshalling``
1028 annotation. Then, if any of the elements of ``ImpliedByAnyOf`` evaluate to true,
1029 the key path value is changed to the specified value or ``true`` if missing.
1030 Finally, the command line is parsed according to the primary annotation.
1031
1032 .. code-block:: text
1033
1034 def fms_extensions : Flag<["-"], "fms-extensions">,
1035 Visibility<[ClangOption, CC1Option]>,
1036 MarshallingInfoFlag<LangOpts<"MicrosoftExt">>,
1037 ImpliedByAnyOf<[fms_compatibility.KeyPath], "true">;
1038
1039 **Condition**
1040
1041 The option is parsed only if the expression in ``ShouldParseIf`` evaluates to
1042 true.
1043
1044 .. code-block:: text
1045
1046 def fopenmp_enable_irbuilder : Flag<["-"], "fopenmp-enable-irbuilder">,
1047 Visibility<[ClangOption, CC1Option]>,
1048 MarshallingInfoFlag<LangOpts<"OpenMPIRBuilder">>,
1049 ShouldParseIf<fopenmp.KeyPath>;
1050
1051 The Lexer and Preprocessor Library
1052 ==================================
1053
1054 The Lexer library contains several tightly-connected classes that are involved
1055 with the nasty process of lexing and preprocessing C source code. The main
1056 interface to this library for outside clients is the large ``Preprocessor``
1057 class. It contains the various pieces of state that are required to coherently
1058 read tokens out of a translation unit.
1059
1060 The core interface to the ``Preprocessor`` object (once it is set up) is the
1061 ``Preprocessor::Lex`` method, which returns the next :ref:`Token <Token>` from
1062 the preprocessor stream. There are two types of token providers that the
1063 preprocessor is capable of reading from: a buffer lexer (provided by the
1064 :ref:`Lexer <Lexer>` class) and a buffered token stream (provided by the
1065 :ref:`TokenLexer <TokenLexer>` class).
1066
1067 .. _Token:
1068
1069 The Token class
1070 ---------------
1071
1072 The ``Token`` class is used to represent a single lexed token. Tokens are
1073 intended to be used by the lexer/preprocess and parser libraries, but are not
1074 intended to live beyond them (for example, they should not live in the ASTs).
1075
1076 Tokens most often live on the stack (or some other location that is efficient
1077 to access) as the parser is running, but occasionally do get buffered up. For
1078 example, macro definitions are stored as a series of tokens, and the C++
1079 front-end periodically needs to buffer tokens up for tentative parsing and
1080 various pieces of look-ahead. As such, the size of a ``Token`` matters. On a
1081 32-bit system, ``sizeof(Token)`` is currently 16 bytes.
1082
1083 Tokens occur in two forms: :ref:`annotation tokens <AnnotationToken>` and
1084 normal tokens. Normal tokens are those returned by the lexer, annotation
1085 tokens represent semantic information and are produced by the parser, replacing
1086 normal tokens in the token stream. Normal tokens contain the following
1087 information:
1088
1089 * **A SourceLocation** --- This indicates the location of the start of the
1090 token.
1091
1092 * **A length** --- This stores the length of the token as stored in the
1093 ``SourceBuffer``. For tokens that include them, this length includes
1094 trigraphs and escaped newlines which are ignored by later phases of the
1095 compiler. By pointing into the original source buffer, it is always possible
1096 to get the original spelling of a token completely accurately.
1097
1098 * **IdentifierInfo** --- If a token takes the form of an identifier, and if
1099 identifier lookup was enabled when the token was lexed (e.g., the lexer was
1100 not reading in "raw" mode) this contains a pointer to the unique hash value
1101 for the identifier. Because the lookup happens before keyword
1102 identification, this field is set even for language keywords like "``for``".
1103
1104 * **TokenKind** --- This indicates the kind of token as classified by the
1105 lexer. This includes things like ``tok::starequal`` (for the "``*=``"
1106 operator), ``tok::ampamp`` for the "``&&``" token, and keyword values (e.g.,
1107 ``tok::kw_for``) for identifiers that correspond to keywords. Note that
1108 some tokens can be spelled multiple ways. For example, C++ supports
1109 "operator keywords", where things like "``and``" are treated exactly like the
1110 "``&&``" operator. In these cases, the kind value is set to ``tok::ampamp``,
1111 which is good for the parser, which doesn't have to consider both forms. For
1112 something that cares about which form is used (e.g., the preprocessor
1113 "stringize" operator) the spelling indicates the original form.
1114
1115 * **Flags** --- There are currently four flags tracked by the
1116 lexer/preprocessor system on a per-token basis:
1117
1118 #. **StartOfLine** --- This was the first token that occurred on its input
1119 source line.
1120 #. **LeadingSpace** --- There was a space character either immediately before
1121 the token or transitively before the token as it was expanded through a
1122 macro. The definition of this flag is very closely defined by the
1123 stringizing requirements of the preprocessor.
1124 #. **DisableExpand** --- This flag is used internally to the preprocessor to
1125 represent identifier tokens which have macro expansion disabled. This
1126 prevents them from being considered as candidates for macro expansion ever
1127 in the future.
1128 #. **NeedsCleaning** --- This flag is set if the original spelling for the
1129 token includes a trigraph or escaped newline. Since this is uncommon,
1130 many pieces of code can fast-path on tokens that did not need cleaning.
1131
1132 One interesting (and somewhat unusual) aspect of normal tokens is that they
1133 don't contain any semantic information about the lexed value. For example, if
1134 the token was a pp-number token, we do not represent the value of the number
1135 that was lexed (this is left for later pieces of code to decide).
1136 Additionally, the lexer library has no notion of typedef names vs variable
1137 names: both are returned as identifiers, and the parser is left to decide
1138 whether a specific identifier is a typedef or a variable (tracking this
1139 requires scope information among other things). The parser can do this
1140 translation by replacing tokens returned by the preprocessor with "Annotation
1141 Tokens".
1142
1143 .. _AnnotationToken:
1144
1145 Annotation Tokens
1146 -----------------
1147
1148 Annotation tokens are tokens that are synthesized by the parser and injected
1149 into the preprocessor's token stream (replacing existing tokens) to record
1150 semantic information found by the parser. For example, if "``foo``" is found
1151 to be a typedef, the "``foo``" ``tok::identifier`` token is replaced with an
1152 ``tok::annot_typename``. This is useful for a couple of reasons: 1) this makes
1153 it easy to handle qualified type names (e.g., "``foo::bar::baz<42>::t``") in
1154 C++ as a single "token" in the parser. 2) if the parser backtracks, the
1155 reparse does not need to redo semantic analysis to determine whether a token
1156 sequence is a variable, type, template, etc.
1157
1158 Annotation tokens are created by the parser and reinjected into the parser's
1159 token stream (when backtracking is enabled). Because they can only exist in
1160 tokens that the preprocessor-proper is done with, it doesn't need to keep
1161 around flags like "start of line" that the preprocessor uses to do its job.
1162 Additionally, an annotation token may "cover" a sequence of preprocessor tokens
1163 (e.g., "``a::b::c``" is five preprocessor tokens). As such, the valid fields
1164 of an annotation token are different than the fields for a normal token (but
1165 they are multiplexed into the normal ``Token`` fields):
1166
1167 * **SourceLocation "Location"** --- The ``SourceLocation`` for the annotation
1168 token indicates the first token replaced by the annotation token. In the
1169 example above, it would be the location of the "``a``" identifier.
1170 * **SourceLocation "AnnotationEndLoc"** --- This holds the location of the last
1171 token replaced with the annotation token. In the example above, it would be
1172 the location of the "``c``" identifier.
1173 * **void* "AnnotationValue"** --- This contains an opaque object that the
1174 parser gets from ``Sema``. The parser merely preserves the information for
1175 ``Sema`` to later interpret based on the annotation token kind.
1176 * **TokenKind "Kind"** --- This indicates the kind of Annotation token this is.
1177 See below for the different valid kinds.
1178
1179 Annotation tokens currently come in three kinds:
1180
1181 #. **tok::annot_typename**: This annotation token represents a resolved
1182 typename token that is potentially qualified. The ``AnnotationValue`` field
1183 contains the ``QualType`` returned by ``Sema::getTypeName()``, possibly with
1184 source location information attached.
1185 #. **tok::annot_cxxscope**: This annotation token represents a C++ scope
1186 specifier, such as "``A::B::``". This corresponds to the grammar
1187 productions "*::*" and "*:: [opt] nested-name-specifier*". The
1188 ``AnnotationValue`` pointer is a ``NestedNameSpecifier *`` returned by the
1189 ``Sema::ActOnCXXGlobalScopeSpecifier`` and
1190 ``Sema::ActOnCXXNestedNameSpecifier`` callbacks.
1191 #. **tok::annot_template_id**: This annotation token represents a C++
1192 template-id such as "``foo<int, 4>``", where "``foo``" is the name of a
1193 template. The ``AnnotationValue`` pointer is a pointer to a ``malloc``'d
1194 ``TemplateIdAnnotation`` object. Depending on the context, a parsed
1195 template-id that names a type might become a typename annotation token (if
1196 all we care about is the named type, e.g., because it occurs in a type
1197 specifier) or might remain a template-id token (if we want to retain more
1198 source location information or produce a new type, e.g., in a declaration of
1199 a class template specialization). template-id annotation tokens that refer
1200 to a type can be "upgraded" to typename annotation tokens by the parser.
1201
1202 As mentioned above, annotation tokens are not returned by the preprocessor,
1203 they are formed on demand by the parser. This means that the parser has to be
1204 aware of cases where an annotation could occur and form it where appropriate.
1205 This is somewhat similar to how the parser handles Translation Phase 6 of C99:
1206 String Concatenation (see C99 5.1.1.2). In the case of string concatenation,
1207 the preprocessor just returns distinct ``tok::string_literal`` and
1208 ``tok::wide_string_literal`` tokens and the parser eats a sequence of them
1209 wherever the grammar indicates that a string literal can occur.
1210
1211 In order to do this, whenever the parser expects a ``tok::identifier`` or
1212 ``tok::coloncolon``, it should call the ``TryAnnotateTypeOrScopeToken`` or
1213 ``TryAnnotateCXXScopeToken`` methods to form the annotation token. These
1214 methods will maximally form the specified annotation tokens and replace the
1215 current token with them, if applicable. If the current tokens is not valid for
1216 an annotation token, it will remain an identifier or "``::``" token.
1217
1218 .. _Lexer:
1219
1220 The ``Lexer`` class
1221 -------------------
1222
1223 The ``Lexer`` class provides the mechanics of lexing tokens out of a source
1224 buffer and deciding what they mean. The ``Lexer`` is complicated by the fact
1225 that it operates on raw buffers that have not had spelling eliminated (this is
1226 a necessity to get decent performance), but this is countered with careful
1227 coding as well as standard performance techniques (for example, the comment
1228 handling code is vectorized on X86 and PowerPC hosts).
1229
1230 The lexer has a couple of interesting modal features:
1231
1232 * The lexer can operate in "raw" mode. This mode has several features that
1233 make it possible to quickly lex the file (e.g., it stops identifier lookup,
1234 doesn't specially handle preprocessor tokens, handles EOF differently, etc).
1235 This mode is used for lexing within an "``#if 0``" block, for example.
1236 * The lexer can capture and return comments as tokens. This is required to
1237 support the ``-C`` preprocessor mode, which passes comments through, and is
1238 used by the diagnostic checker to identifier expect-error annotations.
1239 * The lexer can be in ``ParsingFilename`` mode, which happens when
1240 preprocessing after reading a ``#include`` directive. This mode changes the
1241 parsing of "``<``" to return an "angled string" instead of a bunch of tokens
1242 for each thing within the filename.
1243 * When parsing a preprocessor directive (after "``#``") the
1244 ``ParsingPreprocessorDirective`` mode is entered. This changes the parser to
1245 return EOD at a newline.
1246 * The ``Lexer`` uses a ``LangOptions`` object to know whether trigraphs are
1247 enabled, whether C++ or ObjC keywords are recognized, etc.
1248
1249 In addition to these modes, the lexer keeps track of a couple of other features
1250 that are local to a lexed buffer, which change as the buffer is lexed:
1251
1252 * The ``Lexer`` uses ``BufferPtr`` to keep track of the current character being
1253 lexed.
1254 * The ``Lexer`` uses ``IsAtStartOfLine`` to keep track of whether the next
1255 lexed token will start with its "start of line" bit set.
1256 * The ``Lexer`` keeps track of the current "``#if``" directives that are active
1257 (which can be nested).
1258 * The ``Lexer`` keeps track of an :ref:`MultipleIncludeOpt
1259 <MultipleIncludeOpt>` object, which is used to detect whether the buffer uses
1260 the standard "``#ifndef XX`` / ``#define XX``" idiom to prevent multiple
1261 inclusion. If a buffer does, subsequent includes can be ignored if the
1262 "``XX``" macro is defined.
1263
1264 .. _TokenLexer:
1265
1266 The ``TokenLexer`` class
1267 ------------------------
1268
1269 The ``TokenLexer`` class is a token provider that returns tokens from a list of
1270 tokens that came from somewhere else. It typically used for two things: 1)
1271 returning tokens from a macro definition as it is being expanded 2) returning
1272 tokens from an arbitrary buffer of tokens. The later use is used by
1273 ``_Pragma`` and will most likely be used to handle unbounded look-ahead for the
1274 C++ parser.
1275
1276 .. _MultipleIncludeOpt:
1277
1278 The ``MultipleIncludeOpt`` class
1279 --------------------------------
1280
1281 The ``MultipleIncludeOpt`` class implements a really simple little state
1282 machine that is used to detect the standard "``#ifndef XX`` / ``#define XX``"
1283 idiom that people typically use to prevent multiple inclusion of headers. If a
1284 buffer uses this idiom and is subsequently ``#include``'d, the preprocessor can
1285 simply check to see whether the guarding condition is defined or not. If so,
1286 the preprocessor can completely ignore the include of the header.
1287
1288 .. _Parser:
1289
1290 The Parser Library
1291 ==================
1292
1293 This library contains a recursive-descent parser that polls tokens from the
1294 preprocessor and notifies a client of the parsing progress.
1295
1296 Historically, the parser used to talk to an abstract ``Action`` interface that
1297 had virtual methods for parse events, for example ``ActOnBinOp()``. When Clang
1298 grew C++ support, the parser stopped supporting general ``Action`` clients --
1299 it now always talks to the :ref:`Sema library <Sema>`. However, the Parser
1300 still accesses AST objects only through opaque types like ``ExprResult`` and
1301 ``StmtResult``. Only :ref:`Sema <Sema>` looks at the AST node contents of these
1302 wrappers.
1303
1304 .. _AST:
1305
1306 The AST Library
1307 ===============
1308
1309 .. _ASTPhilosophy:
1310
1311 Design philosophy
1312 -----------------
1313
1314 Immutability
1315 ^^^^^^^^^^^^
1316
1317 Clang AST nodes (types, declarations, statements, expressions, and so on) are
1318 generally designed to be immutable once created. This provides a number of key
1319 benefits:
1320
1321 * Canonicalization of the "meaning" of nodes is possible as soon as the nodes
1322 are created, and is not invalidated by later addition of more information.
1323 For example, we :ref:`canonicalize types <CanonicalType>`, and use a
1324 canonicalized representation of expressions when determining whether two
1325 function template declarations involving dependent expressions declare the
1326 same entity.
1327 * AST nodes can be reused when they have the same meaning. For example, we
1328 reuse ``Type`` nodes when representing the same type (but maintain separate
1329 ``TypeLoc``\s for each instance where a type is written), and we reuse
1330 non-dependent ``Stmt`` and ``Expr`` nodes across instantiations of a
1331 template.
1332 * Serialization and deserialization of the AST to/from AST files is simpler:
1333 we do not need to track modifications made to AST nodes imported from AST
1334 files and serialize separate "update records".
1335
1336 There are unfortunately exceptions to this general approach, such as:
1337
1338 * The first declaration of a redeclarable entity maintains a pointer to the
1339 most recent declaration of that entity, which naturally needs to change as
1340 more declarations are parsed.
1341 * Name lookup tables in declaration contexts change after the namespace
1342 declaration is formed.
1343 * We attempt to maintain only a single declaration for an instantiation of a
1344 template, rather than having distinct declarations for an instantiation of
1345 the declaration versus the definition, so template instantiation often
1346 updates parts of existing declarations.
1347 * Some parts of declarations are required to be instantiated separately (this
1348 includes default arguments and exception specifications), and such
1349 instantiations update the existing declaration.
1350
1351 These cases tend to be fragile; mutable AST state should be avoided where
1352 possible.
1353
1354 As a consequence of this design principle, we typically do not provide setters
1355 for AST state. (Some are provided for short-term modifications intended to be
1356 used immediately after an AST node is created and before it's "published" as
1357 part of the complete AST, or where language semantics require after-the-fact
1358 updates.)
1359
1360 Faithfulness
1361 ^^^^^^^^^^^^
1362
1363 The AST intends to provide a representation of the program that is faithful to
1364 the original source. We intend for it to be possible to write refactoring tools
1365 using only information stored in, or easily reconstructible from, the Clang AST.
1366 This means that the AST representation should either not desugar source-level
1367 constructs to simpler forms, or -- where made necessary by language semantics
1368 or a clear engineering tradeoff -- should desugar minimally and wrap the result
1369 in a construct representing the original source form.
1370
1371 For example, ``CXXForRangeStmt`` directly represents the syntactic form of a
1372 range-based for statement, but also holds a semantic representation of the
1373 range declaration and iterator declarations. It does not contain a
1374 fully-desugared ``ForStmt``, however.
1375
1376 Some AST nodes (for example, ``ParenExpr``) represent only syntax, and others
1377 (for example, ``ImplicitCastExpr``) represent only semantics, but most nodes
1378 will represent a combination of syntax and associated semantics. Inheritance
1379 is typically used when representing different (but related) syntaxes for nodes
1380 with the same or similar semantics.
1381
1382 .. _Type:
1383
1384 The ``Type`` class and its subclasses
1385 -------------------------------------
1386
1387 The ``Type`` class (and its subclasses) are an important part of the AST.
1388 Types are accessed through the ``ASTContext`` class, which implicitly creates
1389 and uniques them as they are needed. Types have a couple of non-obvious
1390 features: 1) they do not capture type qualifiers like ``const`` or ``volatile``
1391 (see :ref:`QualType <QualType>`), and 2) they implicitly capture typedef
1392 information. Once created, types are immutable (unlike decls).
1393
1394 Typedefs in C make semantic analysis a bit more complex than it would be without
1395 them. The issue is that we want to capture typedef information and represent it
1396 in the AST perfectly, but the semantics of operations need to "see through"
1397 typedefs. For example, consider this code:
1398
1399 .. code-block:: c++
1400
1401 void func() {
1402 typedef int foo;
1403 foo X, *Y;
1404 typedef foo *bar;
1405 bar Z;
1406 *X; // error
1407 **Y; // error
1408 **Z; // error
1409 }
1410
1411 The code above is illegal, and thus we expect there to be diagnostics emitted
1412 on the annotated lines. In this example, we expect to get:
1413
1414 .. code-block:: text
1415
1416 test.c:6:1: error: indirection requires pointer operand ('foo' invalid)
1417 *X; // error
1418 ^~
1419 test.c:7:1: error: indirection requires pointer operand ('foo' invalid)
1420 **Y; // error
1421 ^~~
1422 test.c:8:1: error: indirection requires pointer operand ('foo' invalid)
1423 **Z; // error
1424 ^~~
1425
1426 While this example is somewhat silly, it illustrates the point: we want to
1427 retain typedef information where possible, so that we can emit errors about
1428 "``std::string``" instead of "``std::basic_string<char, std:...``". Doing this
1429 requires properly keeping typedef information (for example, the type of ``X``
1430 is "``foo``", not "``int``"), and requires properly propagating it through the
1431 various operators (for example, the type of ``*Y`` is "``foo``", not
1432 "``int``"). In order to retain this information, the type of these expressions
1433 is an instance of the ``TypedefType`` class, which indicates that the type of
1434 these expressions is a typedef for "``foo``".
1435
1436 Representing types like this is great for diagnostics, because the
1437 user-specified type is always immediately available. There are two problems
1438 with this: first, various semantic checks need to make judgements about the
1439 *actual structure* of a type, ignoring typedefs. Second, we need an efficient
1440 way to query whether two types are structurally identical to each other,
1441 ignoring typedefs. The solution to both of these problems is the idea of
1442 canonical types.
1443
1444 .. _CanonicalType:
1445
1446 Canonical Types
1447 ^^^^^^^^^^^^^^^
1448
1449 Every instance of the ``Type`` class contains a canonical type pointer. For
1450 simple types with no typedefs involved (e.g., "``int``", "``int*``",
1451 "``int**``"), the type just points to itself. For types that have a typedef
1452 somewhere in their structure (e.g., "``foo``", "``foo*``", "``foo**``",
1453 "``bar``"), the canonical type pointer points to their structurally equivalent
1454 type without any typedefs (e.g., "``int``", "``int*``", "``int**``", and
1455 "``int*``" respectively).
1456
1457 This design provides a constant time operation (dereferencing the canonical type
1458 pointer) that gives us access to the structure of types. For example, we can
1459 trivially tell that "``bar``" and "``foo*``" are the same type by dereferencing
1460 their canonical type pointers and doing a pointer comparison (they both point
1461 to the single "``int*``" type).
1462
1463 Canonical types and typedef types bring up some complexities that must be
1464 carefully managed. Specifically, the ``isa``/``cast``/``dyn_cast`` operators
1465 generally shouldn't be used in code that is inspecting the AST. For example,
1466 when type checking the indirection operator (unary "``*``" on a pointer), the
1467 type checker must verify that the operand has a pointer type. It would not be
1468 correct to check that with "``isa<PointerType>(SubExpr->getType())``", because
1469 this predicate would fail if the subexpression had a typedef type.
1470
1471 The solution to this problem are a set of helper methods on ``Type``, used to
1472 check their properties. In this case, it would be correct to use
1473 "``SubExpr->getType()->isPointerType()``" to do the check. This predicate will
1474 return true if the *canonical type is a pointer*, which is true any time the
1475 type is structurally a pointer type. The only hard part here is remembering
1476 not to use the ``isa``/``cast``/``dyn_cast`` operations.
1477
1478 The second problem we face is how to get access to the pointer type once we
1479 know it exists. To continue the example, the result type of the indirection
1480 operator is the pointee type of the subexpression. In order to determine the
1481 type, we need to get the instance of ``PointerType`` that best captures the
1482 typedef information in the program. If the type of the expression is literally
1483 a ``PointerType``, we can return that, otherwise we have to dig through the
1484 typedefs to find the pointer type. For example, if the subexpression had type
1485 "``foo*``", we could return that type as the result. If the subexpression had
1486 type "``bar``", we want to return "``foo*``" (note that we do *not* want
1487 "``int*``"). In order to provide all of this, ``Type`` has a
1488 ``getAsPointerType()`` method that checks whether the type is structurally a
1489 ``PointerType`` and, if so, returns the best one. If not, it returns a null
1490 pointer.
1491
1492 This structure is somewhat mystical, but after meditating on it, it will make
1493 sense to you :).
1494
1495 .. _QualType:
1496
1497 The ``QualType`` class
1498 ----------------------
1499
1500 The ``QualType`` class is designed as a trivial value class that is small,
1501 passed by-value and is efficient to query. The idea of ``QualType`` is that it
1502 stores the type qualifiers (``const``, ``volatile``, ``restrict``, plus some
1503 extended qualifiers required by language extensions) separately from the types
1504 themselves. ``QualType`` is conceptually a pair of "``Type*``" and the bits
1505 for these type qualifiers.
1506
1507 By storing the type qualifiers as bits in the conceptual pair, it is extremely
1508 efficient to get the set of qualifiers on a ``QualType`` (just return the field
1509 of the pair), add a type qualifier (which is a trivial constant-time operation
1510 that sets a bit), and remove one or more type qualifiers (just return a
1511 ``QualType`` with the bitfield set to empty).
1512
1513 Further, because the bits are stored outside of the type itself, we do not need
1514 to create duplicates of types with different sets of qualifiers (i.e. there is
1515 only a single heap allocated "``int``" type: "``const int``" and "``volatile
1516 const int``" both point to the same heap allocated "``int``" type). This
1517 reduces the heap size used to represent bits and also means we do not have to
1518 consider qualifiers when uniquing types (:ref:`Type <Type>` does not even
1519 contain qualifiers).
1520
1521 In practice, the two most common type qualifiers (``const`` and ``restrict``)
1522 are stored in the low bits of the pointer to the ``Type`` object, together with
1523 a flag indicating whether extended qualifiers are present (which must be
1524 heap-allocated). This means that ``QualType`` is exactly the same size as a
1525 pointer.
1526
1527 .. _DeclarationName:
1528
1529 Declaration names
1530 -----------------
1531
1532 The ``DeclarationName`` class represents the name of a declaration in Clang.
1533 Declarations in the C family of languages can take several different forms.
1534 Most declarations are named by simple identifiers, e.g., "``f``" and "``x``" in
1535 the function declaration ``f(int x)``. In C++, declaration names can also name
1536 class constructors ("``Class``" in ``struct Class { Class(); }``), class
1537 destructors ("``~Class``"), overloaded operator names ("``operator+``"), and
1538 conversion functions ("``operator void const *``"). In Objective-C,
1539 declaration names can refer to the names of Objective-C methods, which involve
1540 the method name and the parameters, collectively called a *selector*, e.g.,
1541 "``setWidth:height:``". Since all of these kinds of entities --- variables,
1542 functions, Objective-C methods, C++ constructors, destructors, and operators
1543 --- are represented as subclasses of Clang's common ``NamedDecl`` class,
1544 ``DeclarationName`` is designed to efficiently represent any kind of name.
1545
1546 Given a ``DeclarationName`` ``N``, ``N.getNameKind()`` will produce a value
1547 that describes what kind of name ``N`` stores. There are 10 options (all of
1548 the names are inside the ``DeclarationName`` class).
1549
1550 ``Identifier``
1551
1552 The name is a simple identifier. Use ``N.getAsIdentifierInfo()`` to retrieve
1553 the corresponding ``IdentifierInfo*`` pointing to the actual identifier.
1554
1555 ``ObjCZeroArgSelector``, ``ObjCOneArgSelector``, ``ObjCMultiArgSelector``
1556
1557 The name is an Objective-C selector, which can be retrieved as a ``Selector``
1558 instance via ``N.getObjCSelector()``. The three possible name kinds for
1559 Objective-C reflect an optimization within the ``DeclarationName`` class:
1560 both zero- and one-argument selectors are stored as a masked
1561 ``IdentifierInfo`` pointer, and therefore require very little space, since
1562 zero- and one-argument selectors are far more common than multi-argument
1563 selectors (which use a different structure).
1564
1565 ``CXXConstructorName``
1566
1567 The name is a C++ constructor name. Use ``N.getCXXNameType()`` to retrieve
1568 the :ref:`type <QualType>` that this constructor is meant to construct. The
1569 type is always the canonical type, since all constructors for a given type
1570 have the same name.
1571
1572 ``CXXDestructorName``
1573
1574 The name is a C++ destructor name. Use ``N.getCXXNameType()`` to retrieve
1575 the :ref:`type <QualType>` whose destructor is being named. This type is
1576 always a canonical type.
1577
1578 ``CXXConversionFunctionName``
1579
1580 The name is a C++ conversion function. Conversion functions are named
1581 according to the type they convert to, e.g., "``operator void const *``".
1582 Use ``N.getCXXNameType()`` to retrieve the type that this conversion function
1583 converts to. This type is always a canonical type.
1584
1585 ``CXXOperatorName``
1586
1587 The name is a C++ overloaded operator name. Overloaded operators are named
1588 according to their spelling, e.g., "``operator+``" or "``operator new []``".
1589 Use ``N.getCXXOverloadedOperator()`` to retrieve the overloaded operator (a
1590 value of type ``OverloadedOperatorKind``).
1591
1592 ``CXXLiteralOperatorName``
1593
1594 The name is a C++11 user defined literal operator. User defined
1595 Literal operators are named according to the suffix they define,
1596 e.g., "``_foo``" for "``operator "" _foo``". Use
1597 ``N.getCXXLiteralIdentifier()`` to retrieve the corresponding
1598 ``IdentifierInfo*`` pointing to the identifier.
1599
1600 ``CXXUsingDirective``
1601
1602 The name is a C++ using directive. Using directives are not really
1603 NamedDecls, in that they all have the same name, but they are
1604 implemented as such in order to store them in DeclContext
1605 effectively.
1606
1607 ``DeclarationName``\ s are cheap to create, copy, and compare. They require
1608 only a single pointer's worth of storage in the common cases (identifiers,
1609 zero- and one-argument Objective-C selectors) and use dense, uniqued storage
1610 for the other kinds of names. Two ``DeclarationName``\ s can be compared for
1611 equality (``==``, ``!=``) using a simple bitwise comparison, can be ordered
1612 with ``<``, ``>``, ``<=``, and ``>=`` (which provide a lexicographical ordering
1613 for normal identifiers but an unspecified ordering for other kinds of names),
1614 and can be placed into LLVM ``DenseMap``\ s and ``DenseSet``\ s.
1615
1616 ``DeclarationName`` instances can be created in different ways depending on
1617 what kind of name the instance will store. Normal identifiers
1618 (``IdentifierInfo`` pointers) and Objective-C selectors (``Selector``) can be
1619 implicitly converted to ``DeclarationNames``. Names for C++ constructors,
1620 destructors, conversion functions, and overloaded operators can be retrieved
1621 from the ``DeclarationNameTable``, an instance of which is available as
1622 ``ASTContext::DeclarationNames``. The member functions
1623 ``getCXXConstructorName``, ``getCXXDestructorName``,
1624 ``getCXXConversionFunctionName``, and ``getCXXOperatorName``, respectively,
1625 return ``DeclarationName`` instances for the four kinds of C++ special function
1626 names.
1627
1628 .. _DeclContext:
1629
1630 Declaration contexts
1631 --------------------
1632
1633 Every declaration in a program exists within some *declaration context*, such
1634 as a translation unit, namespace, class, or function. Declaration contexts in
1635 Clang are represented by the ``DeclContext`` class, from which the various
1636 declaration-context AST nodes (``TranslationUnitDecl``, ``NamespaceDecl``,
1637 ``RecordDecl``, ``FunctionDecl``, etc.) will derive. The ``DeclContext`` class
1638 provides several facilities common to each declaration context:
1639
1640 Source-centric vs. Semantics-centric View of Declarations
1641
1642 ``DeclContext`` provides two views of the declarations stored within a
1643 declaration context. The source-centric view accurately represents the
1644 program source code as written, including multiple declarations of entities
1645 where present (see the section :ref:`Redeclarations and Overloads
1646 <Redeclarations>`), while the semantics-centric view represents the program
1647 semantics. The two views are kept synchronized by semantic analysis while
1648 the ASTs are being constructed.
1649
1650 Storage of declarations within that context
1651
1652 Every declaration context can contain some number of declarations. For
1653 example, a C++ class (represented by ``RecordDecl``) contains various member
1654 functions, fields, nested types, and so on. All of these declarations will
1655 be stored within the ``DeclContext``, and one can iterate over the
1656 declarations via [``DeclContext::decls_begin()``,
1657 ``DeclContext::decls_end()``). This mechanism provides the source-centric
1658 view of declarations in the context.
1659
1660 Lookup of declarations within that context
1661
1662 The ``DeclContext`` structure provides efficient name lookup for names within
1663 that declaration context. For example, if ``N`` is a namespace we can look
1664 for the name ``N::f`` using ``DeclContext::lookup``. The lookup itself is
1665 based on a lazily-constructed array (for declaration contexts with a small
1666 number of declarations) or hash table (for declaration contexts with more
1667 declarations). The lookup operation provides the semantics-centric view of
1668 the declarations in the context.
1669
1670 Ownership of declarations
1671
1672 The ``DeclContext`` owns all of the declarations that were declared within
1673 its declaration context, and is responsible for the management of their
1674 memory as well as their (de-)serialization.
1675
1676 All declarations are stored within a declaration context, and one can query
1677 information about the context in which each declaration lives. One can
1678 retrieve the ``DeclContext`` that contains a particular ``Decl`` using
1679 ``Decl::getDeclContext``. However, see the section
1680 :ref:`LexicalAndSemanticContexts` for more information about how to interpret
1681 this context information.
1682
1683 .. _Redeclarations:
1684
1685 Redeclarations and Overloads
1686 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1687
1688 Within a translation unit, it is common for an entity to be declared several
1689 times. For example, we might declare a function "``f``" and then later
1690 re-declare it as part of an inlined definition:
1691
1692 .. code-block:: c++
1693
1694 void f(int x, int y, int z = 1);
1695
1696 inline void f(int x, int y, int z) { /* ... */ }
1697
1698 The representation of "``f``" differs in the source-centric and
1699 semantics-centric views of a declaration context. In the source-centric view,
1700 all redeclarations will be present, in the order they occurred in the source
1701 code, making this view suitable for clients that wish to see the structure of
1702 the source code. In the semantics-centric view, only the most recent "``f``"
1703 will be found by the lookup, since it effectively replaces the first
1704 declaration of "``f``".
1705
1706 (Note that because ``f`` can be redeclared at block scope, or in a friend
1707 declaration, etc. it is possible that the declaration of ``f`` found by name
1708 lookup will not be the most recent one.)
1709
1710 In the semantics-centric view, overloading of functions is represented
1711 explicitly. For example, given two declarations of a function "``g``" that are
1712 overloaded, e.g.,
1713
1714 .. code-block:: c++
1715
1716 void g();
1717 void g(int);
1718
1719 the ``DeclContext::lookup`` operation will return a
1720 ``DeclContext::lookup_result`` that contains a range of iterators over
1721 declarations of "``g``". Clients that perform semantic analysis on a program
1722 that is not concerned with the actual source code will primarily use this
1723 semantics-centric view.
1724
1725 .. _LexicalAndSemanticContexts:
1726
1727 Lexical and Semantic Contexts
1728 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1729
1730 Each declaration has two potentially different declaration contexts: a
1731 *lexical* context, which corresponds to the source-centric view of the
1732 declaration context, and a *semantic* context, which corresponds to the
1733 semantics-centric view. The lexical context is accessible via
1734 ``Decl::getLexicalDeclContext`` while the semantic context is accessible via
1735 ``Decl::getDeclContext``, both of which return ``DeclContext`` pointers. For
1736 most declarations, the two contexts are identical. For example:
1737
1738 .. code-block:: c++
1739
1740 class X {
1741 public:
1742 void f(int x);
1743 };
1744
1745 Here, the semantic and lexical contexts of ``X::f`` are the ``DeclContext``
1746 associated with the class ``X`` (itself stored as a ``RecordDecl`` AST node).
1747 However, we can now define ``X::f`` out-of-line:
1748
1749 .. code-block:: c++
1750
1751 void X::f(int x = 17) { /* ... */ }
1752
1753 This definition of "``f``" has different lexical and semantic contexts. The
1754 lexical context corresponds to the declaration context in which the actual
1755 declaration occurred in the source code, e.g., the translation unit containing
1756 ``X``. Thus, this declaration of ``X::f`` can be found by traversing the
1757 declarations provided by [``decls_begin()``, ``decls_end()``) in the
1758 translation unit.
1759
1760 The semantic context of ``X::f`` corresponds to the class ``X``, since this
1761 member function is (semantically) a member of ``X``. Lookup of the name ``f``
1762 into the ``DeclContext`` associated with ``X`` will then return the definition
1763 of ``X::f`` (including information about the default argument).
1764
1765 Transparent Declaration Contexts
1766 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1767
1768 In C and C++, there are several contexts in which names that are logically
1769 declared inside another declaration will actually "leak" out into the enclosing
1770 scope from the perspective of name lookup. The most obvious instance of this
1771 behavior is in enumeration types, e.g.,
1772
1773 .. code-block:: c++
1774
1775 enum Color {
1776 Red,
1777 Green,
1778 Blue
1779 };
1780
1781 Here, ``Color`` is an enumeration, which is a declaration context that contains
1782 the enumerators ``Red``, ``Green``, and ``Blue``. Thus, traversing the list of
1783 declarations contained in the enumeration ``Color`` will yield ``Red``,
1784 ``Green``, and ``Blue``. However, outside of the scope of ``Color`` one can
1785 name the enumerator ``Red`` without qualifying the name, e.g.,
1786
1787 .. code-block:: c++
1788
1789 Color c = Red;
1790
1791 There are other entities in C++ that provide similar behavior. For example,
1792 linkage specifications that use curly braces:
1793
1794 .. code-block:: c++
1795
1796 extern "C" {
1797 void f(int);
1798 void g(int);
1799 }
1800 // f and g are visible here
1801
1802 For source-level accuracy, we treat the linkage specification and enumeration
1803 type as a declaration context in which its enclosed declarations ("``Red``",
1804 "``Green``", and "``Blue``"; "``f``" and "``g``") are declared. However, these
1805 declarations are visible outside of the scope of the declaration context.
1806
1807 These language features (and several others, described below) have roughly the
1808 same set of requirements: declarations are declared within a particular lexical
1809 context, but the declarations are also found via name lookup in scopes
1810 enclosing the declaration itself. This feature is implemented via
1811 *transparent* declaration contexts (see
1812 ``DeclContext::isTransparentContext()``), whose declarations are visible in the
1813 nearest enclosing non-transparent declaration context. This means that the
1814 lexical context of the declaration (e.g., an enumerator) will be the
1815 transparent ``DeclContext`` itself, as will the semantic context, but the
1816 declaration will be visible in every outer context up to and including the
1817 first non-transparent declaration context (since transparent declaration
1818 contexts can be nested).
1819
1820 The transparent ``DeclContext``\ s are:
1821
1822 * Enumerations (but not C++11 "scoped enumerations"):
1823
1824 .. code-block:: c++
1825
1826 enum Color {
1827 Red,
1828 Green,
1829 Blue
1830 };
1831 // Red, Green, and Blue are in scope
1832
1833 * C++ linkage specifications:
1834
1835 .. code-block:: c++
1836
1837 extern "C" {
1838 void f(int);
1839 void g(int);
1840 }
1841 // f and g are in scope
1842
1843 * Anonymous unions and structs:
1844
1845 .. code-block:: c++
1846
1847 struct LookupTable {
1848 bool IsVector;
1849 union {
1850 std::vector<Item> *Vector;
1851 std::set<Item> *Set;
1852 };
1853 };
1854
1855 LookupTable LT;
1856 LT.Vector = 0; // Okay: finds Vector inside the unnamed union
1857
1858 * C++11 inline namespaces:
1859
1860 .. code-block:: c++
1861
1862 namespace mylib {
1863 inline namespace debug {
1864 class X;
1865 }
1866 }
1867 mylib::X *xp; // okay: mylib::X refers to mylib::debug::X
1868
1869 .. _MultiDeclContext:
1870
1871 Multiply-Defined Declaration Contexts
1872 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1873
1874 C++ namespaces have the interesting property that
1875 the namespace can be defined multiple times, and the declarations provided by
1876 each namespace definition are effectively merged (from the semantic point of
1877 view). For example, the following two code snippets are semantically
1878 indistinguishable:
1879
1880 .. code-block:: c++
1881
1882 // Snippet #1:
1883 namespace N {
1884 void f();
1885 }
1886 namespace N {
1887 void f(int);
1888 }
1889
1890 // Snippet #2:
1891 namespace N {
1892 void f();
1893 void f(int);
1894 }
1895
1896 In Clang's representation, the source-centric view of declaration contexts will
1897 actually have two separate ``NamespaceDecl`` nodes in Snippet #1, each of which
1898 is a declaration context that contains a single declaration of "``f``".
1899 However, the semantics-centric view provided by name lookup into the namespace
1900 ``N`` for "``f``" will return a ``DeclContext::lookup_result`` that contains a
1901 range of iterators over declarations of "``f``".
1902
1903 ``DeclContext`` manages multiply-defined declaration contexts internally. The
1904 function ``DeclContext::getPrimaryContext`` retrieves the "primary" context for
1905 a given ``DeclContext`` instance, which is the ``DeclContext`` responsible for
1906 maintaining the lookup table used for the semantics-centric view. Given a
1907 DeclContext, one can obtain the set of declaration contexts that are
1908 semantically connected to this declaration context, in source order, including
1909 this context (which will be the only result, for non-namespace contexts) via
1910 ``DeclContext::collectAllContexts``. Note that these functions are used
1911 internally within the lookup and insertion methods of the ``DeclContext``, so
1912 the vast majority of clients can ignore them.
1913
1914 Because the same entity can be defined multiple times in different modules,
1915 it is also possible for there to be multiple definitions of (for instance)
1916 a ``CXXRecordDecl``, all of which describe a definition of the same class.
1917 In such a case, only one of those "definitions" is considered by Clang to be
1918 the definition of the class, and the others are treated as non-defining
1919 declarations that happen to also contain member declarations. Corresponding
1920 members in each definition of such multiply-defined classes are identified
1921 either by redeclaration chains (if the members are ``Redeclarable``)
1922 or by simply a pointer to the canonical declaration (if the declarations
1923 are not ``Redeclarable`` -- in that case, a ``Mergeable`` base class is used
1924 instead).
1925
1926 Error Handling
1927 --------------
1928
1929 Clang produces an AST even when the code contains errors. Clang won't generate
1930 and optimize code for it, but it's used as parsing continues to detect further
1931 errors in the input. Clang-based tools also depend on such ASTs, and IDEs in
1932 particular benefit from a high-quality AST for broken code.
1933
1934 In presence of errors, clang uses a few error-recovery strategies to present the
1935 broken code in the AST:
1936
1937 - correcting errors: in cases where clang is confident about the fix, it
1938 provides a FixIt attaching to the error diagnostic and emits a corrected AST
1939 (reflecting the written code with FixIts applied). The advantage of that is to
1940 provide more accurate subsequent diagnostics. Typo correction is a typical
1941 example.
1942 - representing invalid node: the invalid node is preserved in the AST in some
1943 form, e.g. when the "declaration" part of the declaration contains semantic
1944 errors, the Decl node is marked as invalid.
1945 - dropping invalid node: this often happens for errors that we don’t have
1946 graceful recovery. Prior to Recovery AST, a mismatched-argument function call
1947 expression was dropped though a CallExpr was created for semantic analysis.
1948
1949 With these strategies, clang surfaces better diagnostics, and provides AST
1950 consumers a rich AST reflecting the written source code as much as possible even
1951 for broken code.
1952
1953 Recovery AST
1954 ^^^^^^^^^^^^
1955
1956 The idea of Recovery AST is to use recovery nodes which act as a placeholder to
1957 maintain the rough structure of the parsing tree, preserve locations and
1958 children but have no language semantics attached to them.
1959
1960 For example, consider the following mismatched function call:
1961
1962 .. code-block:: c++
1963
1964 int NoArg();
1965 void test(int abc) {
1966 NoArg(abc); // oops, mismatched function arguments.
1967 }
1968
1969 Without Recovery AST, the invalid function call expression (and its child
1970 expressions) would be dropped in the AST:
1971
1972 ::
1973
1974 |-FunctionDecl <line:1:1, col:11> NoArg 'int ()'
1975 `-FunctionDecl <line:2:1, line:4:1> test 'void (int)'
1976 |-ParmVarDecl <col:11, col:15> col:15 used abc 'int'
1977 `-CompoundStmt <col:20, line:4:1>
1978
1979
1980 With Recovery AST, the AST looks like:
1981
1982 ::
1983
1984 |-FunctionDecl <line:1:1, col:11> NoArg 'int ()'
1985 `-FunctionDecl <line:2:1, line:4:1> test 'void (int)'
1986 |-ParmVarDecl <col:11, col:15> used abc 'int'
1987 `-CompoundStmt <col:20, line:4:1>
1988 `-RecoveryExpr <line:3:3, col:12> 'int' contains-errors
1989 |-UnresolvedLookupExpr <col:3> '<overloaded function type>' lvalue (ADL) = 'NoArg'
1990 `-DeclRefExpr <col:9> 'int' lvalue ParmVar 'abc' 'int'
1991
1992
1993 An alternative is to use existing Exprs, e.g. CallExpr for the above example.
1994 This would capture more call details (e.g. locations of parentheses) and allow
1995 it to be treated uniformly with valid CallExprs. However, jamming the data we
1996 have into CallExpr forces us to weaken its invariants, e.g. arg count may be
1997 wrong. This would introduce a huge burden on consumers of the AST to handle such
1998 "impossible" cases. So when we're representing (rather than correcting) errors,
1999 we use a distinct recovery node type with extremely weak invariants instead.
2000
2001 ``RecoveryExpr`` is the only recovery node so far. In practice, broken decls
2002 need more detailed semantics preserved (the current ``Invalid`` flag works
2003 fairly well), and completely broken statements with interesting internal
2004 structure are rare (so dropping the statements is OK).
2005
2006 Types and dependence
2007 ^^^^^^^^^^^^^^^^^^^^
2008
2009 ``RecoveryExpr`` is an ``Expr``, so it must have a type. In many cases the true
2010 type can't really be known until the code is corrected (e.g. a call to a
2011 function that doesn't exist). And it means that we can't properly perform type
2012 checks on some containing constructs, such as ``return 42 + unknownFunction()``.
2013
2014 To model this, we generalize the concept of dependence from C++ templates to
2015 mean dependence on a template parameter or how an error is repaired. The
2016 ``RecoveryExpr`` ``unknownFunction()`` has the totally unknown type
2017 ``DependentTy``, and this suppresses type-based analysis in the same way it
2018 would inside a template.
2019
2020 In cases where we are confident about the concrete type (e.g. the return type
2021 for a broken non-overloaded function call), the ``RecoveryExpr`` will have this
2022 type. This allows more code to be typechecked, and produces a better AST and
2023 more diagnostics. For example:
2024
2025 .. code-block:: C++
2026
2027 unknownFunction().size() // .size() is a CXXDependentScopeMemberExpr
2028 std::string(42).size() // .size() is a resolved MemberExpr
2029
2030 Whether or not the ``RecoveryExpr`` has a dependent type, it is always
2031 considered value-dependent, because its value isn't well-defined until the error
2032 is resolved. Among other things, this means that clang doesn't emit more errors
2033 where a RecoveryExpr is used as a constant (e.g. array size), but also won't try
2034 to evaluate it.
2035
2036 ContainsErrors bit
2037 ^^^^^^^^^^^^^^^^^^
2038
2039 Beyond the template dependence bits, we add a new “ContainsErrors” bit to
2040 express “Does this expression or anything within it contain errors” semantic,
2041 this bit is always set for RecoveryExpr, and propagated to other related nodes.
2042 This provides a fast way to query whether any (recursive) child of an expression
2043 had an error, which is often used to improve diagnostics.
2044
2045 .. code-block:: C++
2046
2047 // C++
2048 void recoveryExpr(int abc) {
2049 unknownFunction(); // type-dependent, value-dependent, contains-errors
2050
2051 std::string(42).size(); // value-dependent, contains-errors,
2052 // not type-dependent, as we know the type is std::string
2053 }
2054
2055
2056 .. code-block:: C
2057
2058 // C
2059 void recoveryExpr(int abc) {
2060 unknownVar + abc; // type-dependent, value-dependent, contains-errors
2061 }
2062
2063
2064 The ASTImporter
2065 ---------------
2066
2067 The ``ASTImporter`` class imports nodes of an ``ASTContext`` into another
2068 ``ASTContext``. Please refer to the document :doc:`ASTImporter: Merging Clang
2069 ASTs <LibASTImporter>` for an introduction. And please read through the
2070 high-level `description of the import algorithm
2071 <LibASTImporter.html#algorithm-of-the-import>`_, this is essential for
2072 understanding further implementation details of the importer.
2073
2074 .. _templated:
2075
2076 Abstract Syntax Graph
2077 ^^^^^^^^^^^^^^^^^^^^^
2078
2079 Despite the name, the Clang AST is not a tree. It is a directed graph with
2080 cycles. One example of a cycle is the connection between a
2081 ``ClassTemplateDecl`` and its "templated" ``CXXRecordDecl``. The *templated*
2082 ``CXXRecordDecl`` represents all the fields and methods inside the class
2083 template, while the ``ClassTemplateDecl`` holds the information which is
2084 related to being a template, i.e. template arguments, etc. We can get the
2085 *templated* class (the ``CXXRecordDecl``) of a ``ClassTemplateDecl`` with
2086 ``ClassTemplateDecl::getTemplatedDecl()``. And we can get back a pointer of the
2087 "described" class template from the *templated* class:
2088 ``CXXRecordDecl::getDescribedTemplate()``. So, this is a cycle between two
2089 nodes: between the *templated* and the *described* node. There may be various
2090 other kinds of cycles in the AST especially in case of declarations.
2091
2092 .. _structural-eq:
2093
2094 Structural Equivalency
2095 ^^^^^^^^^^^^^^^^^^^^^^
2096
2097 Importing one AST node copies that node into the destination ``ASTContext``. To
2098 copy one node means that we create a new node in the "to" context then we set
2099 its properties to be equal to the properties of the source node. Before the
2100 copy, we make sure that the source node is not *structurally equivalent* to any
2101 existing node in the destination context. If it happens to be equivalent then
2102 we skip the copy.
2103
2104 The informal definition of structural equivalency is the following:
2105 Two nodes are **structurally equivalent** if they are
2106
2107 - builtin types and refer to the same type, e.g. ``int`` and ``int`` are
2108 structurally equivalent,
2109 - function types and all their parameters have structurally equivalent types,
2110 - record types and all their fields in order of their definition have the same
2111 identifier names and structurally equivalent types,
2112 - variable or function declarations and they have the same identifier name and
2113 their types are structurally equivalent.
2114
2115 In C, two types are structurally equivalent if they are *compatible types*. For
2116 a formal definition of *compatible types*, please refer to 6.2.7/1 in the C11
2117 standard. However, there is no definition for *compatible types* in the C++
2118 standard. Still, we extend the definition of structural equivalency to
2119 templates and their instantiations similarly: besides checking the previously
2120 mentioned properties, we have to check for equivalent template
2121 parameters/arguments, etc.
2122
2123 The structural equivalent check can be and is used independently from the
2124 ASTImporter, e.g. the ``clang::Sema`` class uses it also.
2125
2126 The equivalence of nodes may depend on the equivalency of other pairs of nodes.
2127 Thus, the check is implemented as a parallel graph traversal. We traverse
2128 through the nodes of both graphs at the same time. The actual implementation is
2129 similar to breadth-first-search. Let's say we start the traverse with the <A,B>
2130 pair of nodes. Whenever the traversal reaches a pair <X,Y> then the following
2131 statements are true:
2132
2133 - A and X are nodes from the same ASTContext.
2134 - B and Y are nodes from the same ASTContext.
2135 - A and B may or may not be from the same ASTContext.
2136 - if A == X and B == Y (pointer equivalency) then (there is a cycle during the
2137 traverse)
2138
2139 - A and B are structurally equivalent if and only if
2140
2141 - All dependent nodes on the path from <A,B> to <X,Y> are structurally
2142 equivalent.
2143
2144 When we compare two classes or enums and one of them is incomplete or has
2145 unloaded external lexical declarations then we cannot descend to compare their
2146 contained declarations. So in these cases they are considered equal if they
2147 have the same names. This is the way how we compare forward declarations with
2148 definitions.
2149
2150 .. TODO Should we elaborate the actual implementation of the graph traversal,
2151 .. which is a very weird BFS traversal?
2152
2153 Redeclaration Chains
2154 ^^^^^^^^^^^^^^^^^^^^
2155
2156 The early version of the ``ASTImporter``'s merge mechanism squashed the
2157 declarations, i.e. it aimed to have only one declaration instead of maintaining
2158 a whole redeclaration chain. This early approach simply skipped importing a
2159 function prototype, but it imported a definition. To demonstrate the problem
2160 with this approach let's consider an empty "to" context and the following
2161 ``virtual`` function declarations of ``f`` in the "from" context:
2162
2163 .. code-block:: c++
2164
2165 struct B { virtual void f(); };
2166 void B::f() {} // <-- let's import this definition
2167
2168 If we imported the definition with the "squashing" approach then we would
2169 end-up having one declaration which is indeed a definition, but ``isVirtual()``
2170 returns ``false`` for it. The reason is that the definition is indeed not
2171 virtual, it is the property of the prototype!
2172
2173 Consequently, we must either set the virtual flag for the definition (but then
2174 we create a malformed AST which the parser would never create), or we import
2175 the whole redeclaration chain of the function. The most recent version of the
2176 ``ASTImporter`` uses the latter mechanism. We do import all function
2177 declarations - regardless if they are definitions or prototypes - in the order
2178 as they appear in the "from" context.
2179
2180 .. One definition
2181
2182 If we have an existing definition in the "to" context, then we cannot import
2183 another definition, we will use the existing definition. However, we can import
2184 prototype(s): we chain the newly imported prototype(s) to the existing
2185 definition. Whenever we import a new prototype from a third context, that will
2186 be added to the end of the redeclaration chain. This may result in long
2187 redeclaration chains in certain cases, e.g. if we import from several
2188 translation units which include the same header with the prototype.
2189
2190 .. Squashing prototypes
2191
2192 To mitigate the problem of long redeclaration chains of free functions, we
2193 could compare prototypes to see if they have the same properties and if yes
2194 then we could merge these prototypes. The implementation of squashing of
2195 prototypes for free functions is future work.
2196
2197 .. Exception: Cannot have more than 1 prototype in-class
2198
2199 Chaining functions this way ensures that we do copy all information from the
2200 source AST. Nonetheless, there is a problem with member functions: While we can
2201 have many prototypes for free functions, we must have only one prototype for a
2202 member function.
2203
2204 .. code-block:: c++
2205
2206 void f(); // OK
2207 void f(); // OK
2208
2209 struct X {
2210 void f(); // OK
2211 void f(); // ERROR
2212 };
2213 void X::f() {} // OK
2214
2215 Thus, prototypes of member functions must be squashed, we cannot just simply
2216 attach a new prototype to the existing in-class prototype. Consider the
2217 following contexts:
2218
2219 .. code-block:: c++
2220
2221 // "to" context
2222 struct X {
2223 void f(); // D0
2224 };
2225
2226 .. code-block:: c++
2227
2228 // "from" context
2229 struct X {
2230 void f(); // D1
2231 };
2232 void X::f() {} // D2
2233
2234 When we import the prototype and the definition of ``f`` from the "from"
2235 context, then the resulting redecl chain will look like this ``D0 -> D2'``,
2236 where ``D2'`` is the copy of ``D2`` in the "to" context.
2237
2238 .. Redecl chains of other declarations
2239
2240 Generally speaking, when we import declarations (like enums and classes) we do
2241 attach the newly imported declaration to the existing redeclaration chain (if
2242 there is structural equivalency). We do not import, however, the whole
2243 redeclaration chain as we do in case of functions. Up till now, we haven't
2244 found any essential property of forward declarations which is similar to the
2245 case of the virtual flag in a member function prototype. In the future, this
2246 may change, though.
2247
2248 Traversal during the Import
2249 ^^^^^^^^^^^^^^^^^^^^^^^^^^^
2250
2251 The node specific import mechanisms are implemented in
2252 ``ASTNodeImporter::VisitNode()`` functions, e.g. ``VisitFunctionDecl()``.
2253 When we import a declaration then first we import everything which is needed to
2254 call the constructor of that declaration node. Everything which can be set
2255 later is set after the node is created. For example, in case of a
2256 ``FunctionDecl`` we first import the declaration context in which the function
2257 is declared, then we create the ``FunctionDecl`` and only then we import the
2258 body of the function. This means there are implicit dependencies between AST
2259 nodes. These dependencies determine the order in which we visit nodes in the
2260 "from" context. As with the regular graph traversal algorithms like DFS, we
2261 keep track which nodes we have already visited in
2262 ``ASTImporter::ImportedDecls``. Whenever we create a node then we immediately
2263 add that to the ``ImportedDecls``. We must not start the import of any other
2264 declarations before we keep track of the newly created one. This is essential,
2265 otherwise, we would not be able to handle circular dependencies. To enforce
2266 this, we wrap all constructor calls of all AST nodes in
2267 ``GetImportedOrCreateDecl()``. This wrapper ensures that all newly created
2268 declarations are immediately marked as imported; also, if a declaration is
2269 already marked as imported then we just return its counterpart in the "to"
2270 context. Consequently, calling a declaration's ``::Create()`` function directly
2271 would lead to errors, please don't do that!
2272
2273 Even with the use of ``GetImportedOrCreateDecl()`` there is still a
2274 probability of having an infinite import recursion if things are imported from
2275 each other in wrong way. Imagine that during the import of ``A``, the import of
2276 ``B`` is requested before we could create the node for ``A`` (the constructor
2277 needs a reference to ``B``). And the same could be true for the import of ``B``
2278 (``A`` is requested to be imported before we could create the node for ``B``).
2279 In case of the :ref:`templated-described swing <templated>` we take
2280 extra attention to break the cyclical dependency: we import and set the
2281 described template only after the ``CXXRecordDecl`` is created. As a best
2282 practice, before creating the node in the "to" context, avoid importing of
2283 other nodes which are not needed for the constructor of node ``A``.
2284
2285 Error Handling
2286 ^^^^^^^^^^^^^^
2287
2288 Every import function returns with either an ``llvm::Error`` or an
2289 ``llvm::Expected<T>`` object. This enforces to check the return value of the
2290 import functions. If there was an error during one import then we return with
2291 that error. (Exception: when we import the members of a class, we collect the
2292 individual errors with each member and we concatenate them in one Error
2293 object.) We cache these errors in cases of declarations. During the next import
2294 call if there is an existing error we just return with that. So, clients of the
2295 library receive an Error object, which they must check.
2296
2297 During import of a specific declaration, it may happen that some AST nodes had
2298 already been created before we recognize an error. In this case, we signal back
2299 the error to the caller, but the "to" context remains polluted with those nodes
2300 which had been created. Ideally, those nodes should not had been created, but
2301 that time we did not know about the error, the error happened later. Since the
2302 AST is immutable (most of the cases we can't remove existing nodes) we choose
2303 to mark these nodes as erroneous.
2304
2305 We cache the errors associated with declarations in the "from" context in
2306 ``ASTImporter::ImportDeclErrors`` and the ones which are associated with the
2307 "to" context in ``ASTImporterSharedState::ImportErrors``. Note that, there may
2308 be several ASTImporter objects which import into the same "to" context but from
2309 different "from" contexts; in this case, they have to share the associated
2310 errors of the "to" context.
2311
2312 When an error happens, that propagates through the call stack, through all the
2313 dependant nodes. However, in case of dependency cycles, this is not enough,
2314 because we strive to mark the erroneous nodes so clients can act upon. In those
2315 cases, we have to keep track of the errors for those nodes which are
2316 intermediate nodes of a cycle.
2317
2318 An **import path** is the list of the AST nodes which we visit during an Import
2319 call. If node ``A`` depends on node ``B`` then the path contains an ``A->B``
2320 edge. From the call stack of the import functions, we can read the very same
2321 path.
2322
2323 Now imagine the following AST, where the ``->`` represents dependency in terms
2324 of the import (all nodes are declarations).
2325
2326 .. code-block:: text
2327
2328 A->B->C->D
2329 `->E
2330
2331 We would like to import A.
2332 The import behaves like a DFS, so we will visit the nodes in this order: ABCDE.
2333 During the visitation we will have the following import paths:
2334
2335 .. code-block:: text
2336
2337 A
2338 AB
2339 ABC
2340 ABCD
2341 ABC
2342 AB
2343 ABE
2344 AB
2345 A
2346
2347 If during the visit of E there is an error then we set an error for E, then as
2348 the call stack shrinks for B, then for A:
2349
2350 .. code-block:: text
2351
2352 A
2353 AB
2354 ABC
2355 ABCD
2356 ABC
2357 AB
2358 ABE // Error! Set an error to E
2359 AB // Set an error to B
2360 A // Set an error to A
2361
2362 However, during the import we could import C and D without any error and they
2363 are independent of A,B and E. We must not set up an error for C and D. So, at
2364 the end of the import we have an entry in ``ImportDeclErrors`` for A,B,E but
2365 not for C,D.
2366
2367 Now, what happens if there is a cycle in the import path? Let's consider this
2368 AST:
2369
2370 .. code-block:: text
2371
2372 A->B->C->A
2373 `->E
2374
2375 During the visitation, we will have the below import paths and if during the
2376 visit of E there is an error then we will set up an error for E,B,A. But what's
2377 up with C?
2378
2379 .. code-block:: text
2380
2381 A
2382 AB
2383 ABC
2384 ABCA
2385 ABC
2386 AB
2387 ABE // Error! Set an error to E
2388 AB // Set an error to B
2389 A // Set an error to A
2390
2391 This time we know that both B and C are dependent on A. This means we must set
2392 up an error for C too. As the call stack reverses back we get to A and we must
2393 set up an error to all nodes which depend on A (this includes C). But C is no
2394 longer on the import path, it just had been previously. Such a situation can
2395 happen only if during the visitation we had a cycle. If we didn't have any
2396 cycle, then the normal way of passing an Error object through the call stack
2397 could handle the situation. This is why we must track cycles during the import
2398 process for each visited declaration.
2399
2400 Lookup Problems
2401 ^^^^^^^^^^^^^^^
2402
2403 When we import a declaration from the source context then we check whether we
2404 already have a structurally equivalent node with the same name in the "to"
2405 context. If the "from" node is a definition and the found one is also a
2406 definition, then we do not create a new node, instead, we mark the found node
2407 as the imported node. If the found definition and the one we want to import
2408 have the same name but they are structurally in-equivalent, then we have an ODR
2409 violation in case of C++. If the "from" node is not a definition then we add
2410 that to the redeclaration chain of the found node. This behaviour is essential
2411 when we merge ASTs from different translation units which include the same
2412 header file(s). For example, we want to have only one definition for the class
2413 template ``std::vector``, even if we included ``<vector>`` in several
2414 translation units.
2415
2416 To find a structurally equivalent node we can use the regular C/C++ lookup
2417 functions: ``DeclContext::noload_lookup()`` and
2418 ``DeclContext::localUncachedLookup()``. These functions do respect the C/C++
2419 name hiding rules, thus you cannot find certain declarations in a given
2420 declaration context. For instance, unnamed declarations (anonymous structs),
2421 non-first ``friend`` declarations and template specializations are hidden. This
2422 is a problem, because if we use the regular C/C++ lookup then we create
2423 redundant AST nodes during the merge! Also, having two instances of the same
2424 node could result in false :ref:`structural in-equivalencies <structural-eq>`
2425 of other nodes which depend on the duplicated node. Because of these reasons,
2426 we created a lookup class which has the sole purpose to register all
2427 declarations, so later they can be looked up by subsequent import requests.
2428 This is the ``ASTImporterLookupTable`` class. This lookup table should be
2429 shared amongst the different ``ASTImporter`` instances if they happen to import
2430 to the very same "to" context. This is why we can use the importer specific
2431 lookup only via the ``ASTImporterSharedState`` class.
2432
2433 ExternalASTSource
2434 ~~~~~~~~~~~~~~~~~
2435
2436 The ``ExternalASTSource`` is an abstract interface associated with the
2437 ``ASTContext`` class. It provides the ability to read the declarations stored
2438 within a declaration context either for iteration or for name lookup. A
2439 declaration context with an external AST source may load its declarations
2440 on-demand. This means that the list of declarations (represented as a linked
2441 list, the head is ``DeclContext::FirstDecl``) could be empty. However, member
2442 functions like ``DeclContext::lookup()`` may initiate a load.
2443
2444 Usually, external sources are associated with precompiled headers. For example,
2445 when we load a class from a PCH then the members are loaded only if we do want
2446 to look up something in the class' context.
2447
2448 In case of LLDB, an implementation of the ``ExternalASTSource`` interface is
2449 attached to the AST context which is related to the parsed expression. This
2450 implementation of the ``ExternalASTSource`` interface is realized with the help
2451 of the ``ASTImporter`` class. This way, LLDB can reuse Clang's parsing
2452 machinery while synthesizing the underlying AST from the debug data (e.g. from
2453 DWARF). From the view of the ``ASTImporter`` this means both the "to" and the
2454 "from" context may have declaration contexts with external lexical storage. If
2455 a ``DeclContext`` in the "to" AST context has external lexical storage then we
2456 must take extra attention to work only with the already loaded declarations!
2457 Otherwise, we would end up with an uncontrolled import process. For instance,
2458 if we used the regular ``DeclContext::lookup()`` to find the existing
2459 declarations in the "to" context then the ``lookup()`` call itself would
2460 initiate a new import while we are in the middle of importing a declaration!
2461 (By the time we initiate the lookup we haven't registered yet that we already
2462 started to import the node of the "from" context.) This is why we use
2463 ``DeclContext::noload_lookup()`` instead.
2464
2465 Class Template Instantiations
2466 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2467
2468 Different translation units may have class template instantiations with the
2469 same template arguments, but with a different set of instantiated
2470 ``MethodDecls`` and ``FieldDecls``. Consider the following files:
2471
2472 .. code-block:: c++
2473
2474 // x.h
2475 template <typename T>
2476 struct X {
2477 int a{0}; // FieldDecl with InitListExpr
2478 X(char) : a(3) {} // (1)
2479 X(int) {} // (2)
2480 };
2481
2482 // foo.cpp
2483 void foo() {
2484 // ClassTemplateSpec with ctor (1): FieldDecl without InitlistExpr
2485 X<char> xc('c');
2486 }
2487
2488 // bar.cpp
2489 void bar() {
2490 // ClassTemplateSpec with ctor (2): FieldDecl WITH InitlistExpr
2491 X<char> xc(1);
2492 }
2493
2494 In ``foo.cpp`` we use the constructor with number ``(1)``, which explicitly
2495 initializes the member ``a`` to ``3``, thus the ``InitListExpr`` ``{0}`` is not
2496 used here and the AST node is not instantiated. However, in the case of
2497 ``bar.cpp`` we use the constructor with number ``(2)``, which does not
2498 explicitly initialize the ``a`` member, so the default ``InitListExpr`` is
2499 needed and thus instantiated. When we merge the AST of ``foo.cpp`` and
2500 ``bar.cpp`` we must create an AST node for the class template instantiation of
2501 ``X<char>`` which has all the required nodes. Therefore, when we find an
2502 existing ``ClassTemplateSpecializationDecl`` then we merge the fields of the
2503 ``ClassTemplateSpecializationDecl`` in the "from" context in a way that the
2504 ``InitListExpr`` is copied if not existent yet. The same merge mechanism should
2505 be done in the cases of instantiated default arguments and exception
2506 specifications of functions.
2507
2508 .. _visibility:
2509
2510 Visibility of Declarations
2511 ^^^^^^^^^^^^^^^^^^^^^^^^^^
2512
2513 During import of a global variable with external visibility, the lookup will
2514 find variables (with the same name) but with static visibility (linkage).
2515 Clearly, we cannot put them into the same redeclaration chain. The same is true
2516 the in case of functions. Also, we have to take care of other kinds of
2517 declarations like enums, classes, etc. if they are in anonymous namespaces.
2518 Therefore, we filter the lookup results and consider only those which have the
2519 same visibility as the declaration we currently import.
2520
2521 We consider two declarations in two anonymous namespaces to have the same
2522 visibility only if they are imported from the same AST context.
2523
2524 Strategies to Handle Conflicting Names
2525 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2526
2527 During the import we lookup existing declarations with the same name. We filter
2528 the lookup results based on their :ref:`visibility <visibility>`. If any of the
2529 found declarations are not structurally equivalent then we bumped to a name
2530 conflict error (ODR violation in C++). In this case, we return with an
2531 ``Error`` and we set up the ``Error`` object for the declaration. However, some
2532 clients of the ``ASTImporter`` may require a different, perhaps less
2533 conservative and more liberal error handling strategy.
2534
2535 E.g. static analysis clients may benefit if the node is created even if there
2536 is a name conflict. During the CTU analysis of certain projects, we recognized
2537 that there are global declarations which collide with declarations from other
2538 translation units, but they are not referenced outside from their translation
2539 unit. These declarations should be in an unnamed namespace ideally. If we treat
2540 these collisions liberally then CTU analysis can find more results. Note, the
2541 feature be able to choose between name conflict handling strategies is still an
2542 ongoing work.
2543
2544 .. _CFG:
2545
2546 The ``CFG`` class
2547 -----------------
2548
2549 The ``CFG`` class is designed to represent a source-level control-flow graph
2550 for a single statement (``Stmt*``). Typically instances of ``CFG`` are
2551 constructed for function bodies (usually an instance of ``CompoundStmt``), but
2552 can also be instantiated to represent the control-flow of any class that
2553 subclasses ``Stmt``, which includes simple expressions. Control-flow graphs
2554 are especially useful for performing `flow- or path-sensitive
2555 <https://en.wikipedia.org/wiki/Data_flow_analysis#Sensitivities>`_ program
2556 analyses on a given function.
2557
2558 Basic Blocks
2559 ^^^^^^^^^^^^
2560
2561 Concretely, an instance of ``CFG`` is a collection of basic blocks. Each basic
2562 block is an instance of ``CFGBlock``, which simply contains an ordered sequence
2563 of ``Stmt*`` (each referring to statements in the AST). The ordering of
2564 statements within a block indicates unconditional flow of control from one
2565 statement to the next. :ref:`Conditional control-flow
2566 <ConditionalControlFlow>` is represented using edges between basic blocks. The
2567 statements within a given ``CFGBlock`` can be traversed using the
2568 ``CFGBlock::*iterator`` interface.
2569
2570 A ``CFG`` object owns the instances of ``CFGBlock`` within the control-flow
2571 graph it represents. Each ``CFGBlock`` within a CFG is also uniquely numbered
2572 (accessible via ``CFGBlock::getBlockID()``). Currently the number is based on
2573 the ordering the blocks were created, but no assumptions should be made on how
2574 ``CFGBlocks`` are numbered other than their numbers are unique and that they
2575 are numbered from 0..N-1 (where N is the number of basic blocks in the CFG).
2576
2577 Entry and Exit Blocks
2578 ^^^^^^^^^^^^^^^^^^^^^
2579
2580 Each instance of ``CFG`` contains two special blocks: an *entry* block
2581 (accessible via ``CFG::getEntry()``), which has no incoming edges, and an
2582 *exit* block (accessible via ``CFG::getExit()``), which has no outgoing edges.
2583 Neither block contains any statements, and they serve the role of providing a
2584 clear entrance and exit for a body of code such as a function body. The
2585 presence of these empty blocks greatly simplifies the implementation of many
2586 analyses built on top of CFGs.
2587
2588 .. _ConditionalControlFlow:
2589
2590 Conditional Control-Flow
2591 ^^^^^^^^^^^^^^^^^^^^^^^^
2592
2593 Conditional control-flow (such as those induced by if-statements and loops) is
2594 represented as edges between ``CFGBlocks``. Because different C language
2595 constructs can induce control-flow, each ``CFGBlock`` also records an extra
2596 ``Stmt*`` that represents the *terminator* of the block. A terminator is
2597 simply the statement that caused the control-flow, and is used to identify the
2598 nature of the conditional control-flow between blocks. For example, in the
2599 case of an if-statement, the terminator refers to the ``IfStmt`` object in the
2600 AST that represented the given branch.
2601
2602 To illustrate, consider the following code example:
2603
2604 .. code-block:: c++
2605
2606 int foo(int x) {
2607 x = x + 1;
2608 if (x > 2)
2609 x++;
2610 else {
2611 x += 2;
2612 x *= 2;
2613 }
2614
2615 return x;
2616 }
2617
2618 After invoking the parser+semantic analyzer on this code fragment, the AST of
2619 the body of ``foo`` is referenced by a single ``Stmt*``. We can then construct
2620 an instance of ``CFG`` representing the control-flow graph of this function
2621 body by single call to a static class method:
2622
2623 .. code-block:: c++
2624
2625 Stmt *FooBody = ...
2626 std::unique_ptr<CFG> FooCFG = CFG::buildCFG(FooBody);
2627
2628 Along with providing an interface to iterate over its ``CFGBlocks``, the
2629 ``CFG`` class also provides methods that are useful for debugging and
2630 visualizing CFGs. For example, the method ``CFG::dump()`` dumps a
2631 pretty-printed version of the CFG to standard error. This is especially useful
2632 when one is using a debugger such as gdb. For example, here is the output of
2633 ``FooCFG->dump()``:
2634
2635 .. code-block:: text
2636
2637 [ B5 (ENTRY) ]
2638 Predecessors (0):
2639 Successors (1): B4
2640
2641 [ B4 ]
2642 1: x = x + 1
2643 2: (x > 2)
2644 T: if [B4.2]
2645 Predecessors (1): B5
2646 Successors (2): B3 B2
2647
2648 [ B3 ]
2649 1: x++
2650 Predecessors (1): B4
2651 Successors (1): B1
2652
2653 [ B2 ]
2654 1: x += 2
2655 2: x *= 2
2656 Predecessors (1): B4
2657 Successors (1): B1
2658
2659 [ B1 ]
2660 1: return x;
2661 Predecessors (2): B2 B3
2662 Successors (1): B0
2663
2664 [ B0 (EXIT) ]
2665 Predecessors (1): B1
2666 Successors (0):
2667
2668 For each block, the pretty-printed output displays for each block the number of
2669 *predecessor* blocks (blocks that have outgoing control-flow to the given
2670 block) and *successor* blocks (blocks that have control-flow that have incoming
2671 control-flow from the given block). We can also clearly see the special entry
2672 and exit blocks at the beginning and end of the pretty-printed output. For the
2673 entry block (block B5), the number of predecessor blocks is 0, while for the
2674 exit block (block B0) the number of successor blocks is 0.
2675
2676 The most interesting block here is B4, whose outgoing control-flow represents
2677 the branching caused by the sole if-statement in ``foo``. Of particular
2678 interest is the second statement in the block, ``(x > 2)``, and the terminator,
2679 printed as ``if [B4.2]``. The second statement represents the evaluation of
2680 the condition of the if-statement, which occurs before the actual branching of
2681 control-flow. Within the ``CFGBlock`` for B4, the ``Stmt*`` for the second
2682 statement refers to the actual expression in the AST for ``(x > 2)``. Thus
2683 pointers to subclasses of ``Expr`` can appear in the list of statements in a
2684 block, and not just subclasses of ``Stmt`` that refer to proper C statements.
2685
2686 The terminator of block B4 is a pointer to the ``IfStmt`` object in the AST.
2687 The pretty-printer outputs ``if [B4.2]`` because the condition expression of
2688 the if-statement has an actual place in the basic block, and thus the
2689 terminator is essentially *referring* to the expression that is the second
2690 statement of block B4 (i.e., B4.2). In this manner, conditions for
2691 control-flow (which also includes conditions for loops and switch statements)
2692 are hoisted into the actual basic block.
2693
2694 .. Implicit Control-Flow
2695 .. ^^^^^^^^^^^^^^^^^^^^^
2696
2697 .. A key design principle of the ``CFG`` class was to not require any
2698 .. transformations to the AST in order to represent control-flow. Thus the
2699 .. ``CFG`` does not perform any "lowering" of the statements in an AST: loops
2700 .. are not transformed into guarded gotos, short-circuit operations are not
2701 .. converted to a set of if-statements, and so on.
2702
2703 Constant Folding in the Clang AST
2704 ---------------------------------
2705
2706 There are several places where constants and constant folding matter a lot to
2707 the Clang front-end. First, in general, we prefer the AST to retain the source
2708 code as close to how the user wrote it as possible. This means that if they
2709 wrote "``5+4``", we want to keep the addition and two constants in the AST, we
2710 don't want to fold to "``9``". This means that constant folding in various
2711 ways turns into a tree walk that needs to handle the various cases.
2712
2713 However, there are places in both C and C++ that require constants to be
2714 folded. For example, the C standard defines what an "integer constant
2715 expression" (i-c-e) is with very precise and specific requirements. The
2716 language then requires i-c-e's in a lot of places (for example, the size of a
2717 bitfield, the value for a case statement, etc). For these, we have to be able
2718 to constant fold the constants, to do semantic checks (e.g., verify bitfield
2719 size is non-negative and that case statements aren't duplicated). We aim for
2720 Clang to be very pedantic about this, diagnosing cases when the code does not
2721 use an i-c-e where one is required, but accepting the code unless running with
2722 ``-pedantic-errors``.
2723
2724 Things get a little bit more tricky when it comes to compatibility with
2725 real-world source code. Specifically, GCC has historically accepted a huge
2726 superset of expressions as i-c-e's, and a lot of real world code depends on
2727 this unfortunate accident of history (including, e.g., the glibc system
2728 headers). GCC accepts anything its "fold" optimizer is capable of reducing to
2729 an integer constant, which means that the definition of what it accepts changes
2730 as its optimizer does. One example is that GCC accepts things like "``case
2731 X-X:``" even when ``X`` is a variable, because it can fold this to 0.
2732
2733 Another issue are how constants interact with the extensions we support, such
2734 as ``__builtin_constant_p``, ``__builtin_inf``, ``__extension__`` and many
2735 others. C99 obviously does not specify the semantics of any of these
2736 extensions, and the definition of i-c-e does not include them. However, these
2737 extensions are often used in real code, and we have to have a way to reason
2738 about them.
2739
2740 Finally, this is not just a problem for semantic analysis. The code generator
2741 and other clients have to be able to fold constants (e.g., to initialize global
2742 variables) and have to handle a superset of what C99 allows. Further, these
2743 clients can benefit from extended information. For example, we know that
2744 "``foo() || 1``" always evaluates to ``true``, but we can't replace the
2745 expression with ``true`` because it has side effects.
2746
2747 Implementation Approach
2748 ^^^^^^^^^^^^^^^^^^^^^^^
2749
2750 After trying several different approaches, we've finally converged on a design
2751 (Note, at the time of this writing, not all of this has been implemented,
2752 consider this a design goal!). Our basic approach is to define a single
2753 recursive evaluation method (``Expr::Evaluate``), which is implemented
2754 in ``AST/ExprConstant.cpp``. Given an expression with "scalar" type (integer,
2755 fp, complex, or pointer) this method returns the following information:
2756
2757 * Whether the expression is an integer constant expression, a general constant
2758 that was folded but has no side effects, a general constant that was folded
2759 but that does have side effects, or an uncomputable/unfoldable value.
2760 * If the expression was computable in any way, this method returns the
2761 ``APValue`` for the result of the expression.
2762 * If the expression is not evaluatable at all, this method returns information
2763 on one of the problems with the expression. This includes a
2764 ``SourceLocation`` for where the problem is, and a diagnostic ID that explains
2765 the problem. The diagnostic should have ``ERROR`` type.
2766 * If the expression is not an integer constant expression, this method returns
2767 information on one of the problems with the expression. This includes a
2768 ``SourceLocation`` for where the problem is, and a diagnostic ID that
2769 explains the problem. The diagnostic should have ``EXTENSION`` type.
2770
2771 This information gives various clients the flexibility that they want, and we
2772 will eventually have some helper methods for various extensions. For example,
2773 ``Sema`` should have a ``Sema::VerifyIntegerConstantExpression`` method, which
2774 calls ``Evaluate`` on the expression. If the expression is not foldable, the
2775 error is emitted, and it would return ``true``. If the expression is not an
2776 i-c-e, the ``EXTENSION`` diagnostic is emitted. Finally it would return
2777 ``false`` to indicate that the AST is OK.
2778
2779 Other clients can use the information in other ways, for example, codegen can
2780 just use expressions that are foldable in any way.
2781
2782 Extensions
2783 ^^^^^^^^^^
2784
2785 This section describes how some of the various extensions Clang supports
2786 interacts with constant evaluation:
2787
2788 * ``__extension__``: The expression form of this extension causes any
2789 evaluatable subexpression to be accepted as an integer constant expression.
2790 * ``__builtin_constant_p``: This returns true (as an integer constant
2791 expression) if the operand evaluates to either a numeric value (that is, not
2792 a pointer cast to integral type) of integral, enumeration, floating or
2793 complex type, or if it evaluates to the address of the first character of a
2794 string literal (possibly cast to some other type). As a special case, if
2795 ``__builtin_constant_p`` is the (potentially parenthesized) condition of a
2796 conditional operator expression ("``?:``"), only the true side of the
2797 conditional operator is considered, and it is evaluated with full constant
2798 folding.
2799 * ``__builtin_choose_expr``: The condition is required to be an integer
2800 constant expression, but we accept any constant as an "extension of an
2801 extension". This only evaluates one operand depending on which way the
2802 condition evaluates.
2803 * ``__builtin_classify_type``: This always returns an integer constant
2804 expression.
2805 * ``__builtin_inf, nan, ...``: These are treated just like a floating-point
2806 literal.
2807 * ``__builtin_abs, copysign, ...``: These are constant folded as general
2808 constant expressions.
2809 * ``__builtin_strlen`` and ``strlen``: These are constant folded as integer
2810 constant expressions if the argument is a string literal.
2811
2812 .. _Sema:
2813
2814 The Sema Library
2815 ================
2816
2817 This library is called by the :ref:`Parser library <Parser>` during parsing to
2818 do semantic analysis of the input. For valid programs, Sema builds an AST for
2819 parsed constructs.
2820
2821 .. _CodeGen:
2822
2823 The CodeGen Library
2824 ===================
2825
2826 CodeGen takes an :ref:`AST <AST>` as input and produces `LLVM IR code
2827 <//llvm.org/docs/LangRef.html>`_ from it.
2828
2829 How to change Clang
2830 ===================
2831
2832 How to add an attribute
2833 -----------------------
2834 Attributes are a form of metadata that can be attached to a program construct,
2835 allowing the programmer to pass semantic information along to the compiler for
2836 various uses. For example, attributes may be used to alter the code generation
2837 for a program construct, or to provide extra semantic information for static
2838 analysis. This document explains how to add a custom attribute to Clang.
2839 Documentation on existing attributes can be found `here
2840 <//clang.llvm.org/docs/AttributeReference.html>`_.
2841
2842 Attribute Basics
2843 ^^^^^^^^^^^^^^^^
2844 Attributes in Clang are handled in three stages: parsing into a parsed attribute
2845 representation, conversion from a parsed attribute into a semantic attribute,
2846 and then the semantic handling of the attribute.
2847
2848 Parsing of the attribute is determined by the various syntactic forms attributes
2849 can take, such as GNU, C++11, and Microsoft style attributes, as well as other
2850 information provided by the table definition of the attribute. Ultimately, the
2851 parsed representation of an attribute object is a ``ParsedAttr`` object.
2852 These parsed attributes chain together as a list of parsed attributes attached
2853 to a declarator or declaration specifier. The parsing of attributes is handled
2854 automatically by Clang, except for attributes spelled as so-called “custom”
2855 keywords. When implementing a custom keyword attribute, the parsing of the
2856 keyword and creation of the ``ParsedAttr`` object must be done manually.
2857
2858 Eventually, ``Sema::ProcessDeclAttributeList()`` is called with a ``Decl`` and
2859 a ``ParsedAttr``, at which point the parsed attribute can be transformed
2860 into a semantic attribute. The process by which a parsed attribute is converted
2861 into a semantic attribute depends on the attribute definition and semantic
2862 requirements of the attribute. The end result, however, is that the semantic
2863 attribute object is attached to the ``Decl`` object, and can be obtained by a
2864 call to ``Decl::getAttr<T>()``. Similarly, for statement attributes,
2865 ``Sema::ProcessStmtAttributes()`` is called with a ``Stmt`` a list of
2866 ``ParsedAttr`` objects to be converted into a semantic attribute.
2867
2868 The structure of the semantic attribute is also governed by the attribute
2869 definition given in Attr.td. This definition is used to automatically generate
2870 functionality used for the implementation of the attribute, such as a class
2871 derived from ``clang::Attr``, information for the parser to use, automated
2872 semantic checking for some attributes, etc.
2873
2874
2875 ``include/clang/Basic/Attr.td``
2876 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2877 The first step to adding a new attribute to Clang is to add its definition to
2878 `include/clang/Basic/Attr.td
2879 <https://github.com/llvm/llvm-project/blob/main/clang/include/clang/Basic/Attr.td>`_.
2880 This tablegen definition must derive from the ``Attr`` (tablegen, not
2881 semantic) type, or one of its derivatives. Most attributes will derive from the
2882 ``InheritableAttr`` type, which specifies that the attribute can be inherited by
2883 later redeclarations of the ``Decl`` it is associated with.
2884 ``InheritableParamAttr`` is similar to ``InheritableAttr``, except that the
2885 attribute is written on a parameter instead of a declaration. If the attribute
2886 applies to statements, it should inherit from ``StmtAttr``. If the attribute is
2887 intended to apply to a type instead of a declaration, such an attribute should
2888 derive from ``TypeAttr``, and will generally not be given an AST representation.
2889 (Note that this document does not cover the creation of type attributes.) An
2890 attribute that inherits from ``IgnoredAttr`` is parsed, but will generate an
2891 ignored attribute diagnostic when used, which may be useful when an attribute is
2892 supported by another vendor but not supported by clang.
2893
2894 The definition will specify several key pieces of information, such as the
2895 semantic name of the attribute, the spellings the attribute supports, the
2896 arguments the attribute expects, and more. Most members of the ``Attr`` tablegen
2897 type do not require definitions in the derived definition as the default
2898 suffice. However, every attribute must specify at least a spelling list, a
2899 subject list, and a documentation list.
2900
2901 Spellings
2902 ~~~~~~~~~
2903 All attributes are required to specify a spelling list that denotes the ways in
2904 which the attribute can be spelled. For instance, a single semantic attribute
2905 may have a keyword spelling, as well as a C++11 spelling and a GNU spelling. An
2906 empty spelling list is also permissible and may be useful for attributes which
2907 are created implicitly. The following spellings are accepted:
2908
2909 ================== =========================================================
2910 Spelling Description
2911 ================== =========================================================
2912 ``GNU`` Spelled with a GNU-style ``__attribute__((attr))``
2913 syntax and placement.
2914 ``CXX11`` Spelled with a C++-style ``[[attr]]`` syntax with an
2915 optional vendor-specific namespace.
2916 ``C23`` Spelled with a C-style ``[[attr]]`` syntax with an
2917 optional vendor-specific namespace.
2918 ``Declspec`` Spelled with a Microsoft-style ``__declspec(attr)``
2919 syntax.
2920 ``CustomKeyword`` The attribute is spelled as a keyword, and requires
2921 custom parsing.
2922 ``RegularKeyword`` The attribute is spelled as a keyword. It can be
2923 used in exactly the places that the standard
2924 ``[[attr]]`` syntax can be used, and appertains to
2925 exactly the same thing that a standard attribute
2926 would appertain to. Lexing and parsing of the keyword
2927 are handled automatically.
2928 ``GCC`` Specifies two or three spellings: the first is a
2929 GNU-style spelling, the second is a C++-style spelling
2930 with the ``gnu`` namespace, and the third is an optional
2931 C-style spelling with the ``gnu`` namespace. Attributes
2932 should only specify this spelling for attributes
2933 supported by GCC.
2934 ``Clang`` Specifies two or three spellings: the first is a
2935 GNU-style spelling, the second is a C++-style spelling
2936 with the ``clang`` namespace, and the third is an
2937 optional C-style spelling with the ``clang`` namespace.
2938 By default, a C-style spelling is provided.
2939 ``Pragma`` The attribute is spelled as a ``#pragma``, and requires
2940 custom processing within the preprocessor. If the
2941 attribute is meant to be used by Clang, it should
2942 set the namespace to ``"clang"``. Note that this
2943 spelling is not used for declaration attributes.
2944 ================== =========================================================
2945
2946 The C++ standard specifies that “any [non-standard attribute] that is not
2947 recognized by the implementation is ignored” (``[dcl.attr.grammar]``).
2948 The rule for C is similar. This makes ``CXX11`` and ``C23`` spellings
2949 unsuitable for attributes that affect the type system, that change the
2950 binary interface of the code, or that have other similar semantic meaning.
2951
2952 ``RegularKeyword`` provides an alternative way of spelling such attributes.
2953 It reuses the production rules for standard attributes, but it applies them
2954 to plain keywords rather than to ``[[…]]`` sequences. Compilers that don't
2955 recognize the keyword are likely to report an error of some kind.
2956
2957 For example, the ``ArmStreaming`` function type attribute affects
2958 both the type system and the binary interface of the function.
2959 It cannot therefore be spelled ``[[arm::streaming]]``, since compilers
2960 that don't understand ``arm::streaming`` would ignore it and miscompile
2961 the code. ``ArmStreaming`` is instead spelled ``__arm_streaming``, but it
2962 can appear wherever a hypothetical ``[[arm::streaming]]`` could appear.
2963
2964 Subjects
2965 ~~~~~~~~
2966 Attributes appertain to one or more subjects. If the attribute attempts to
2967 attach to a subject that is not in the subject list, a diagnostic is issued
2968 automatically. Whether the diagnostic is a warning or an error depends on how
2969 the attribute's ``SubjectList`` is defined, but the default behavior is to warn.
2970 The diagnostics displayed to the user are automatically determined based on the
2971 subjects in the list, but a custom diagnostic parameter can also be specified in
2972 the ``SubjectList``. The diagnostics generated for subject list violations are
2973 calculated automatically or specified by the subject list itself. If a
2974 previously unused Decl node is added to the ``SubjectList``, the logic used to
2975 automatically determine the diagnostic parameter in `utils/TableGen/ClangAttrEmitter.cpp
2976 <https://github.com/llvm/llvm-project/blob/main/clang/utils/TableGen/ClangAttrEmitter.cpp>`_
2977 may need to be updated.
2978
2979 By default, all subjects in the SubjectList must either be a Decl node defined
2980 in ``DeclNodes.td``, or a statement node defined in ``StmtNodes.td``. However,
2981 more complex subjects can be created by creating a ``SubsetSubject`` object.
2982 Each such object has a base subject which it appertains to (which must be a
2983 Decl or Stmt node, and not a SubsetSubject node), and some custom code which is
2984 called when determining whether an attribute appertains to the subject. For
2985 instance, a ``NonBitField`` SubsetSubject appertains to a ``FieldDecl``, and
2986 tests whether the given FieldDecl is a bit field. When a SubsetSubject is
2987 specified in a SubjectList, a custom diagnostic parameter must also be provided.
2988
2989 Diagnostic checking for attribute subject lists for declaration and statement
2990 attributes is automated except when ``HasCustomParsing`` is set to ``1``.
2991
2992 Documentation
2993 ~~~~~~~~~~~~~
2994 All attributes must have some form of documentation associated with them.
2995 Documentation is table generated on the public web server by a server-side
2996 process that runs daily. Generally, the documentation for an attribute is a
2997 stand-alone definition in `include/clang/Basic/AttrDocs.td
2998 <https://github.com/llvm/llvm-project/blob/main/clang/include/clang/Basic/AttrDocs.td>`_
2999 that is named after the attribute being documented.
3000
3001 If the attribute is not for public consumption, or is an implicitly-created
3002 attribute that has no visible spelling, the documentation list can specify the
3003 ``InternalOnly`` object. Otherwise, the attribute should have its documentation
3004 added to AttrDocs.td.
3005
3006 Documentation derives from the ``Documentation`` tablegen type. All derived
3007 types must specify a documentation category and the actual documentation itself.
3008 Additionally, it can specify a custom heading for the attribute, though a
3009 default heading will be chosen when possible.
3010
3011 There are four predefined documentation categories: ``DocCatFunction`` for
3012 attributes that appertain to function-like subjects, ``DocCatVariable`` for
3013 attributes that appertain to variable-like subjects, ``DocCatType`` for type
3014 attributes, and ``DocCatStmt`` for statement attributes. A custom documentation
3015 category should be used for groups of attributes with similar functionality.
3016 Custom categories are good for providing overview information for the attributes
3017 grouped under it. For instance, the consumed annotation attributes define a
3018 custom category, ``DocCatConsumed``, that explains what consumed annotations are
3019 at a high level.
3020
3021 Documentation content (whether it is for an attribute or a category) is written
3022 using reStructuredText (RST) syntax.
3023
3024 After writing the documentation for the attribute, it should be locally tested
3025 to ensure that there are no issues generating the documentation on the server.
3026 Local testing requires a fresh build of clang-tblgen. To generate the attribute
3027 documentation, execute the following command::
3028
3029 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
3030
3031 When testing locally, *do not* commit changes to ``AttributeReference.rst``.
3032 This file is generated by the server automatically, and any changes made to this
3033 file will be overwritten.
3034
3035 Arguments
3036 ~~~~~~~~~
3037 Attributes may optionally specify a list of arguments that can be passed to the
3038 attribute. Attribute arguments specify both the parsed form and the semantic
3039 form of the attribute. For example, if ``Args`` is
3040 ``[StringArgument<"Arg1">, IntArgument<"Arg2">]`` then
3041 ``__attribute__((myattribute("Hello", 3)))`` will be a valid use; it requires
3042 two arguments while parsing, and the Attr subclass' constructor for the
3043 semantic attribute will require a string and integer argument.
3044
3045 All arguments have a name and a flag that specifies whether the argument is
3046 optional. The associated C++ type of the argument is determined by the argument
3047 definition type. If the existing argument types are insufficient, new types can
3048 be created, but it requires modifying `utils/TableGen/ClangAttrEmitter.cpp
3049 <https://github.com/llvm/llvm-project/blob/main/clang/utils/TableGen/ClangAttrEmitter.cpp>`_
3050 to properly support the type.
3051
3052 Other Properties
3053 ~~~~~~~~~~~~~~~~
3054 The ``Attr`` definition has other members which control the behavior of the
3055 attribute. Many of them are special-purpose and beyond the scope of this
3056 document, however a few deserve mention.
3057
3058 If the parsed form of the attribute is more complex, or differs from the
3059 semantic form, the ``HasCustomParsing`` bit can be set to ``1`` for the class,
3060 and the parsing code in `Parser::ParseGNUAttributeArgs()
3061 <https://github.com/llvm/llvm-project/blob/main/clang/lib/Parse/ParseDecl.cpp>`_
3062 can be updated for the special case. Note that this only applies to arguments
3063 with a GNU spelling -- attributes with a __declspec spelling currently ignore
3064 this flag and are handled by ``Parser::ParseMicrosoftDeclSpec``.
3065
3066 Note that setting this member to 1 will opt out of common attribute semantic
3067 handling, requiring extra implementation efforts to ensure the attribute
3068 appertains to the appropriate subject, etc.
3069
3070 If the attribute should not be propagated from a template declaration to an
3071 instantiation of the template, set the ``Clone`` member to 0. By default, all
3072 attributes will be cloned to template instantiations.
3073
3074 Attributes that do not require an AST node should set the ``ASTNode`` field to
3075 ``0`` to avoid polluting the AST. Note that anything inheriting from
3076 ``TypeAttr`` or ``IgnoredAttr`` automatically do not generate an AST node. All
3077 other attributes generate an AST node by default. The AST node is the semantic
3078 representation of the attribute.
3079
3080 The ``LangOpts`` field specifies a list of language options required by the
3081 attribute. For instance, all of the CUDA-specific attributes specify ``[CUDA]``
3082 for the ``LangOpts`` field, and when the CUDA language option is not enabled, an
3083 "attribute ignored" warning diagnostic is emitted. Since language options are
3084 not table generated nodes, new language options must be created manually and
3085 should specify the spelling used by ``LangOptions`` class.
3086
3087 Custom accessors can be generated for an attribute based on the spelling list
3088 for that attribute. For instance, if an attribute has two different spellings:
3089 'Foo' and 'Bar', accessors can be created:
3090 ``[Accessor<"isFoo", [GNU<"Foo">]>, Accessor<"isBar", [GNU<"Bar">]>]``
3091 These accessors will be generated on the semantic form of the attribute,
3092 accepting no arguments and returning a ``bool``.
3093
3094 Attributes that do not require custom semantic handling should set the
3095 ``SemaHandler`` field to ``0``. Note that anything inheriting from
3096 ``IgnoredAttr`` automatically do not get a semantic handler. All other
3097 attributes are assumed to use a semantic handler by default. Attributes
3098 without a semantic handler are not given a parsed attribute ``Kind`` enumerator.
3099
3100 "Simple" attributes, that require no custom semantic processing aside from what
3101 is automatically provided, should set the ``SimpleHandler`` field to ``1``.
3102
3103 Target-specific attributes may share a spelling with other attributes in
3104 different targets. For instance, the ARM and MSP430 targets both have an
3105 attribute spelled ``GNU<"interrupt">``, but with different parsing and semantic
3106 requirements. To support this feature, an attribute inheriting from
3107 ``TargetSpecificAttribute`` may specify a ``ParseKind`` field. This field
3108 should be the same value between all arguments sharing a spelling, and
3109 corresponds to the parsed attribute's ``Kind`` enumerator. This allows
3110 attributes to share a parsed attribute kind, but have distinct semantic
3111 attribute classes. For instance, ``ParsedAttr`` is the shared
3112 parsed attribute kind, but ARMInterruptAttr and MSP430InterruptAttr are the
3113 semantic attributes generated.
3114
3115 By default, attribute arguments are parsed in an evaluated context. If the
3116 arguments for an attribute should be parsed in an unevaluated context (akin to
3117 the way the argument to a ``sizeof`` expression is parsed), set
3118 ``ParseArgumentsAsUnevaluated`` to ``1``.
3119
3120 If additional functionality is desired for the semantic form of the attribute,
3121 the ``AdditionalMembers`` field specifies code to be copied verbatim into the
3122 semantic attribute class object, with ``public`` access.
3123
3124 If two or more attributes cannot be used in combination on the same declaration
3125 or statement, a ``MutualExclusions`` definition can be supplied to automatically
3126 generate diagnostic code. This will disallow the attribute combinations
3127 regardless of spellings used. Additionally, it will diagnose combinations within
3128 the same attribute list, different attribute list, and redeclarations, as
3129 appropriate.
3130
3131 Boilerplate
3132 ^^^^^^^^^^^
3133 All semantic processing of declaration attributes happens in `lib/Sema/SemaDeclAttr.cpp
3134 <https://github.com/llvm/llvm-project/blob/main/clang/lib/Sema/SemaDeclAttr.cpp>`_,
3135 and generally starts in the ``ProcessDeclAttribute()`` function. If the
3136 attribute has the ``SimpleHandler`` field set to ``1`` then the function to
3137 process the attribute will be automatically generated, and nothing needs to be
3138 done here. Otherwise, write a new ``handleYourAttr()`` function, and add that to
3139 the switch statement. Please do not implement handling logic directly in the
3140 ``case`` for the attribute.
3141
3142 Unless otherwise specified by the attribute definition, common semantic checking
3143 of the parsed attribute is handled automatically. This includes diagnosing
3144 parsed attributes that do not appertain to the given ``Decl`` or ``Stmt``,
3145 ensuring the correct minimum number of arguments are passed, etc.
3146
3147 If the attribute adds additional warnings, define a ``DiagGroup`` in
3148 `include/clang/Basic/DiagnosticGroups.td
3149 <https://github.com/llvm/llvm-project/blob/main/clang/include/clang/Basic/DiagnosticGroups.td>`_
3150 named after the attribute's ``Spelling`` with "_"s replaced by "-"s. If there
3151 is only a single diagnostic, it is permissible to use ``InGroup<DiagGroup<"your-attribute">>``
3152 directly in `DiagnosticSemaKinds.td
3153 <https://github.com/llvm/llvm-project/blob/main/clang/include/clang/Basic/DiagnosticSemaKinds.td>`_
3154
3155 All semantic diagnostics generated for your attribute, including automatically-
3156 generated ones (such as subjects and argument counts), should have a
3157 corresponding test case.
3158
3159 Semantic handling
3160 ^^^^^^^^^^^^^^^^^
3161 Most attributes are implemented to have some effect on the compiler. For
3162 instance, to modify the way code is generated, or to add extra semantic checks
3163 for an analysis pass, etc. Having added the attribute definition and conversion
3164 to the semantic representation for the attribute, what remains is to implement
3165 the custom logic requiring use of the attribute.
3166
3167 The ``clang::Decl`` object can be queried for the presence or absence of an
3168 attribute using ``hasAttr<T>()``. To obtain a pointer to the semantic
3169 representation of the attribute, ``getAttr<T>`` may be used.
3170
3171 The ``clang::AttributedStmt`` object can be queried for the presence or absence
3172 of an attribute by calling ``getAttrs()`` and looping over the list of
3173 attributes.
3174
3175 How to add an expression or statement
3176 -------------------------------------
3177
3178 Expressions and statements are one of the most fundamental constructs within a
3179 compiler, because they interact with many different parts of the AST, semantic
3180 analysis, and IR generation. Therefore, adding a new expression or statement
3181 kind into Clang requires some care. The following list details the various
3182 places in Clang where an expression or statement needs to be introduced, along
3183 with patterns to follow to ensure that the new expression or statement works
3184 well across all of the C languages. We focus on expressions, but statements
3185 are similar.
3186
3187 #. Introduce parsing actions into the parser. Recursive-descent parsing is
3188 mostly self-explanatory, but there are a few things that are worth keeping
3189 in mind:
3190
3191 * Keep as much source location information as possible! You'll want it later
3192 to produce great diagnostics and support Clang's various features that map
3193 between source code and the AST.
3194 * Write tests for all of the "bad" parsing cases, to make sure your recovery
3195 is good. If you have matched delimiters (e.g., parentheses, square
3196 brackets, etc.), use ``Parser::BalancedDelimiterTracker`` to give nice
3197 diagnostics when things go wrong.
3198
3199 #. Introduce semantic analysis actions into ``Sema``. Semantic analysis should
3200 always involve two functions: an ``ActOnXXX`` function that will be called
3201 directly from the parser, and a ``BuildXXX`` function that performs the
3202 actual semantic analysis and will (eventually!) build the AST node. It's
3203 fairly common for the ``ActOnCXX`` function to do very little (often just
3204 some minor translation from the parser's representation to ``Sema``'s
3205 representation of the same thing), but the separation is still important:
3206 C++ template instantiation, for example, should always call the ``BuildXXX``
3207 variant. Several notes on semantic analysis before we get into construction
3208 of the AST:
3209
3210 * Your expression probably involves some types and some subexpressions.
3211 Make sure to fully check that those types, and the types of those
3212 subexpressions, meet your expectations. Add implicit conversions where
3213 necessary to make sure that all of the types line up exactly the way you
3214 want them. Write extensive tests to check that you're getting good
3215 diagnostics for mistakes and that you can use various forms of
3216 subexpressions with your expression.
3217 * When type-checking a type or subexpression, make sure to first check
3218 whether the type is "dependent" (``Type::isDependentType()``) or whether a
3219 subexpression is type-dependent (``Expr::isTypeDependent()``). If any of
3220 these return ``true``, then you're inside a template and you can't do much
3221 type-checking now. That's normal, and your AST node (when you get there)
3222 will have to deal with this case. At this point, you can write tests that
3223 use your expression within templates, but don't try to instantiate the
3224 templates.
3225 * For each subexpression, be sure to call ``Sema::CheckPlaceholderExpr()``
3226 to deal with "weird" expressions that don't behave well as subexpressions.
3227 Then, determine whether you need to perform lvalue-to-rvalue conversions
3228 (``Sema::DefaultLvalueConversions``) or the usual unary conversions
3229 (``Sema::UsualUnaryConversions``), for places where the subexpression is
3230 producing a value you intend to use.
3231 * Your ``BuildXXX`` function will probably just return ``ExprError()`` at
3232 this point, since you don't have an AST. That's perfectly fine, and
3233 shouldn't impact your testing.
3234
3235 #. Introduce an AST node for your new expression. This starts with declaring
3236 the node in ``include/Basic/StmtNodes.td`` and creating a new class for your
3237 expression in the appropriate ``include/AST/Expr*.h`` header. It's best to
3238 look at the class for a similar expression to get ideas, and there are some
3239 specific things to watch for:
3240
3241 * If you need to allocate memory, use the ``ASTContext`` allocator to
3242 allocate memory. Never use raw ``malloc`` or ``new``, and never hold any
3243 resources in an AST node, because the destructor of an AST node is never
3244 called.
3245 * Make sure that ``getSourceRange()`` covers the exact source range of your
3246 expression. This is needed for diagnostics and for IDE support.
3247 * Make sure that ``children()`` visits all of the subexpressions. This is
3248 important for a number of features (e.g., IDE support, C++ variadic
3249 templates). If you have sub-types, you'll also need to visit those
3250 sub-types in ``RecursiveASTVisitor``.
3251 * Add printing support (``StmtPrinter.cpp``) for your expression.
3252 * Add profiling support (``StmtProfile.cpp``) for your AST node, noting the
3253 distinguishing (non-source location) characteristics of an instance of
3254 your expression. Omitting this step will lead to hard-to-diagnose
3255 failures regarding matching of template declarations.
3256 * Add serialization support (``ASTReaderStmt.cpp``, ``ASTWriterStmt.cpp``)
3257 for your AST node.
3258
3259 #. Teach semantic analysis to build your AST node. At this point, you can wire
3260 up your ``Sema::BuildXXX`` function to actually create your AST. A few
3261 things to check at this point:
3262
3263 * If your expression can construct a new C++ class or return a new
3264 Objective-C object, be sure to update and then call
3265 ``Sema::MaybeBindToTemporary`` for your just-created AST node to be sure
3266 that the object gets properly destructed. An easy way to test this is to
3267 return a C++ class with a private destructor: semantic analysis should
3268 flag an error here with the attempt to call the destructor.
3269 * Inspect the generated AST by printing it using ``clang -cc1 -ast-print``,
3270 to make sure you're capturing all of the important information about how
3271 the AST was written.
3272 * Inspect the generated AST under ``clang -cc1 -ast-dump`` to verify that
3273 all of the types in the generated AST line up the way you want them.
3274 Remember that clients of the AST should never have to "think" to
3275 understand what's going on. For example, all implicit conversions should
3276 show up explicitly in the AST.
3277 * Write tests that use your expression as a subexpression of other,
3278 well-known expressions. Can you call a function using your expression as
3279 an argument? Can you use the ternary operator?
3280
3281 #. Teach code generation to create IR to your AST node. This step is the first
3282 (and only) that requires knowledge of LLVM IR. There are several things to
3283 keep in mind:
3284
3285 * Code generation is separated into scalar/aggregate/complex and
3286 lvalue/rvalue paths, depending on what kind of result your expression
3287 produces. On occasion, this requires some careful factoring of code to
3288 avoid duplication.
3289 * ``CodeGenFunction`` contains functions ``ConvertType`` and
3290 ``ConvertTypeForMem`` that convert Clang's types (``clang::Type*`` or
3291 ``clang::QualType``) to LLVM types. Use the former for values, and the
3292 latter for memory locations: test with the C++ "``bool``" type to check
3293 this. If you find that you are having to use LLVM bitcasts to make the
3294 subexpressions of your expression have the type that your expression
3295 expects, STOP! Go fix semantic analysis and the AST so that you don't
3296 need these bitcasts.
3297 * The ``CodeGenFunction`` class has a number of helper functions to make
3298 certain operations easy, such as generating code to produce an lvalue or
3299 an rvalue, or to initialize a memory location with a given value. Prefer
3300 to use these functions rather than directly writing loads and stores,
3301 because these functions take care of some of the tricky details for you
3302 (e.g., for exceptions).
3303 * If your expression requires some special behavior in the event of an
3304 exception, look at the ``push*Cleanup`` functions in ``CodeGenFunction``
3305 to introduce a cleanup. You shouldn't have to deal with
3306 exception-handling directly.
3307 * Testing is extremely important in IR generation. Use ``clang -cc1
3308 -emit-llvm`` and `FileCheck
3309 <https://llvm.org/docs/CommandGuide/FileCheck.html>`_ to verify that you're
3310 generating the right IR.
3311
3312 #. Teach template instantiation how to cope with your AST node, which requires
3313 some fairly simple code:
3314
3315 * Make sure that your expression's constructor properly computes the flags
3316 for type dependence (i.e., the type your expression produces can change
3317 from one instantiation to the next), value dependence (i.e., the constant
3318 value your expression produces can change from one instantiation to the
3319 next), instantiation dependence (i.e., a template parameter occurs
3320 anywhere in your expression), and whether your expression contains a
3321 parameter pack (for variadic templates). Often, computing these flags
3322 just means combining the results from the various types and
3323 subexpressions.
3324 * Add ``TransformXXX`` and ``RebuildXXX`` functions to the ``TreeTransform``
3325 class template in ``Sema``. ``TransformXXX`` should (recursively)
3326 transform all of the subexpressions and types within your expression,
3327 using ``getDerived().TransformYYY``. If all of the subexpressions and
3328 types transform without error, it will then call the ``RebuildXXX``
3329 function, which will in turn call ``getSema().BuildXXX`` to perform
3330 semantic analysis and build your expression.
3331 * To test template instantiation, take those tests you wrote to make sure
3332 that you were type checking with type-dependent expressions and dependent
3333 types (from step #2) and instantiate those templates with various types,
3334 some of which type-check and some that don't, and test the error messages
3335 in each case.
3336
3337 #. There are some "extras" that make other features work better. It's worth
3338 handling these extras to give your expression complete integration into
3339 Clang:
3340
3341 * Add code completion support for your expression in
3342 ``SemaCodeComplete.cpp``.
3343 * If your expression has types in it, or has any "interesting" features
3344 other than subexpressions, extend libclang's ``CursorVisitor`` to provide
3345 proper visitation for your expression, enabling various IDE features such
3346 as syntax highlighting, cross-referencing, and so on. The
3347 ``c-index-test`` helper program can be used to test these features.
3348
3349 Testing
3350 -------
3351 All functional changes to Clang should come with test coverage demonstrating
3352 the change in behavior.
3353
3354 .. _verifying-diagnostics:
3355
3356 Verifying Diagnostics
3357 ^^^^^^^^^^^^^^^^^^^^^
3358 Clang ``-cc1`` supports the ``-verify`` command line option as a way to
3359 validate diagnostic behavior. This option will use special comments within the
3360 test file to verify that expected diagnostics appear in the correct source
3361 locations. If all of the expected diagnostics match the actual output of Clang,
3362 then the invocation will return normally. If there are discrepancies between
3363 the expected and actual output, Clang will emit detailed information about
3364 which expected diagnostics were not seen or which unexpected diagnostics were
3365 seen, etc. A complete example is:
3366
3367 .. code-block: c++
3368
3369 // RUN: %clang_cc1 -verify %s
3370 int A = B; // expected-error {{use of undeclared identifier 'B'}}
3371
3372 If the test is run and the expected error is emitted on the expected line, the
3373 diagnostic verifier will pass. However, if the expected error does not appear
3374 or appears in a different location than expected, or if additional diagnostics
3375 appear, the diagnostic verifier will fail and emit information as to why.
3376
3377 The ``-verify`` command optionally accepts a comma-delimited list of one or
3378 more verification prefixes that can be used to craft those special comments.
3379 Each prefix must start with a letter and contain only alphanumeric characters,
3380 hyphens, and underscores. ``-verify`` by itself is equivalent to
3381 ``-verify=expected``, meaning that special comments will start with
3382 ``expected``. Using different prefixes makes it easier to have separate
3383 ``RUN:`` lines in the same test file which result in differing diagnostic
3384 behavior. For example:
3385
3386 .. code-block:: c++
3387
3388 // RUN: %clang_cc1 -verify=foo,bar %s
3389
3390 int A = B; // foo-error {{use of undeclared identifier 'B'}}
3391 int C = D; // bar-error {{use of undeclared identifier 'D'}}
3392 int E = F; // expected-error {{use of undeclared identifier 'F'}}
3393
3394 The verifier will recognize ``foo-error`` and ``bar-error`` as special comments
3395 but will not recognize ``expected-error`` as one because the ``-verify`` line
3396 does not contain that as a prefix. Thus, this test would fail verification
3397 because an unexpected diagnostic would appear on the declaration of ``E``.
3398
3399 Multiple occurrences accumulate prefixes. For example,
3400 ``-verify -verify=foo,bar -verify=baz`` is equivalent to
3401 ``-verify=expected,foo,bar,baz``.
3402
3403 Specifying Diagnostics
3404 ^^^^^^^^^^^^^^^^^^^^^^
3405 Indicating that a line expects an error or a warning is easy. Put a comment
3406 on the line that has the diagnostic, use
3407 ``expected-{error,warning,remark,note}`` to tag if it's an expected error,
3408 warning, remark, or note (respectively), and place the expected text between
3409 ``{{`` and ``}}`` markers. The full text doesn't have to be included, only
3410 enough to ensure that the correct diagnostic was emitted. (Note: full text
3411 should be included in test cases unless there is a compelling reason to use
3412 truncated text instead.)
3413
3414 For a full description of the matching behavior, including more complex
3415 matching scenarios, see :ref:`matching <DiagnosticMatching>` below.
3416
3417 Here's an example of the most commonly used way to specify expected
3418 diagnostics:
3419
3420 .. code-block:: c++
3421
3422 int A = B; // expected-error {{use of undeclared identifier 'B'}}
3423
3424 You can place as many diagnostics on one line as you wish. To make the code
3425 more readable, you can use slash-newline to separate out the diagnostics.
3426
3427 Alternatively, it is possible to specify the line on which the diagnostic
3428 should appear by appending ``@<line>`` to ``expected-<type>``, for example:
3429
3430 .. code-block:: c++
3431
3432 #warning some text
3433 // expected-warning@10 {{some text}}
3434
3435 The line number may be absolute (as above), or relative to the current line by
3436 prefixing the number with either ``+`` or ``-``.
3437
3438 If the diagnostic is generated in a separate file, for example in a shared
3439 header file, it may be beneficial to be able to declare the file in which the
3440 diagnostic will appear, rather than placing the ``expected-*`` directive in the
3441 actual file itself. This can be done using the following syntax:
3442
3443 .. code-block:: c++
3444
3445 // expected-error@path/include.h:15 {{error message}}
3446
3447 The path can be absolute or relative and the same search paths will be used as
3448 for ``#include`` directives. The line number in an external file may be
3449 substituted with ``*`` meaning that any line number will match (useful where
3450 the included file is, for example, a system header where the actual line number
3451 may change and is not critical).
3452
3453 As an alternative to specifying a fixed line number, the location of a
3454 diagnostic can instead be indicated by a marker of the form ``#<marker>``.
3455 Markers are specified by including them in a comment, and then referenced by
3456 appending the marker to the diagnostic with ``@#<marker>``, as with:
3457
3458 .. code-block:: c++
3459
3460 #warning some text // #1
3461 // ... other code ...
3462 // expected-warning@#1 {{some text}}
3463
3464 The name of a marker used in a directive must be unique within the compilation.
3465
3466 The simple syntax above allows each specification to match exactly one
3467 diagnostic. You can use the extended syntax to customize this. The extended
3468 syntax is ``expected-<type> <n> {{diag text}}``, where ``<type>`` is one of
3469 ``error``, ``warning``, ``remark``, or ``note``, and ``<n>`` is a positive
3470 integer. This allows the diagnostic to appear as many times as specified. For
3471 example:
3472
3473 .. code-block:: c++
3474
3475 void f(); // expected-note 2 {{previous declaration is here}}
3476
3477 Where the diagnostic is expected to occur a minimum number of times, this can
3478 be specified by appending a ``+`` to the number. For example:
3479
3480 .. code-block:: c++
3481
3482 void f(); // expected-note 0+ {{previous declaration is here}}
3483 void g(); // expected-note 1+ {{previous declaration is here}}
3484
3485 In the first example, the diagnostic becomes optional, i.e. it will be
3486 swallowed if it occurs, but will not generate an error if it does not occur. In
3487 the second example, the diagnostic must occur at least once. As a short-hand,
3488 "one or more" can be specified simply by ``+``. For example:
3489
3490 .. code-block:: c++
3491
3492 void g(); // expected-note + {{previous declaration is here}}
3493
3494 A range can also be specified by ``<n>-<m>``. For example:
3495
3496 .. code-block:: c++
3497
3498 void f(); // expected-note 0-1 {{previous declaration is here}}
3499
3500 In this example, the diagnostic may appear only once, if at all.
3501
3502 .. _DiagnosticMatching:
3503
3504 Matching Modes
3505 ~~~~~~~~~~~~~~
3506
3507 The default matching mode is simple string, which looks for the expected text
3508 that appears between the first `{{` and `}}` pair of the comment. The string is
3509 interpreted just as-is, with one exception: the sequence `\n` is converted to a
3510 single newline character. This mode matches the emitted diagnostic when the
3511 text appears as a substring at any position of the emitted message.
3512
3513 To enable matching against desired strings that contain `}}` or `{{`, the
3514 string-mode parser accepts opening delimiters of more than two curly braces,
3515 like `{{{`. It then looks for a closing delimiter of equal "width" (i.e `}}}`).
3516 For example:
3517
3518 .. code-block:: c++
3519
3520 // expected-note {{{evaluates to '{{2, 3, 4}} == {0, 3, 4}'}}}
3521
3522 The intent is to allow the delimeter to be wider than the longest `{` or `}`
3523 brace sequence in the content, so that if your expected text contains `{{{`
3524 (three braces) it may be delimited with `{{{{` (four braces), and so on.
3525
3526 Regex matching mode may be selected by appending ``-re`` to the diagnostic type
3527 and including regexes wrapped in double curly braces (`{{` and `}}`) in the
3528 directive, such as:
3529
3530 .. code-block:: text
3531
3532 expected-error-re {{format specifies type 'wchar_t **' (aka '{{.+}}')}}
3533
3534 Examples matching error: "variable has incomplete type 'struct s'"
3535
3536 .. code-block:: c++
3537
3538 // expected-error {{variable has incomplete type 'struct s'}}
3539 // expected-error {{variable has incomplete type}}
3540 // expected-error {{{variable has incomplete type}}}
3541 // expected-error {{{{variable has incomplete type}}}}
3542
3543 // expected-error-re {{variable has type 'struct {{.}}'}}
3544 // expected-error-re {{variable has type 'struct {{.*}}'}}
3545 // expected-error-re {{variable has type 'struct {{(.*)}}'}}
3546 // expected-error-re {{variable has type 'struct{{[[:space:]](.*)}}'}}
3547
3548 Feature Test Macros
3549 ===================
3550 Clang implements several ways to test whether a feature is supported or not.
3551 Some of these feature tests are standardized, like ``__has_cpp_attribute`` or
3552 ``__cpp_lambdas``, while others are Clang extensions, like ``__has_builtin``.
3553 The common theme among all the various feature tests is that they are a utility
3554 to tell users that we think a particular feature is complete. However,
3555 completeness is a difficult property to define because features may still have
3556 lingering bugs, may only work on some targets, etc. We use the following
3557 criteria when deciding whether to expose a feature test macro (or particular
3558 result value for the feature test):
3559
3560 * Are there known issues where we reject valid code that should be accepted?
3561 * Are there known issues where we accept invalid code that should be rejected?
3562 * Are there known crashes, failed assertions, or miscompilations?
3563 * Are there known issues on a particular relevant target?
3564
3565 If the answer to any of these is "yes", the feature test macro should either
3566 not be defined or there should be very strong rationale for why the issues
3567 should not prevent defining it. Note, it is acceptable to define the feature
3568 test macro on a per-target basis if needed.
3569
3570 When in doubt, being conservative is better than being aggressive. If we don't
3571 claim support for the feature but it does useful things, users can still use it
3572 and provide us with useful feedback on what is missing. But if we claim support
3573 for a feature that has significant bugs, we've eliminated most of the utility
3574 of having a feature testing macro at all because users are then forced to test
3575 what compiler version is in use to get a more accurate answer.
3576
3577 The status reported by the feature test macro should always be reflected in the
3578 language support page for the corresponding feature (`C++
3579 <https://clang.llvm.org/cxx_status.html>`_, `C
3580 <https://clang.llvm.org/c_status.html>`_) if applicable. This page can give
3581 more nuanced information to the user as well, such as claiming partial support
3582 for a feature and specifying details as to what remains to be done.