1============================
2"Clang" CFE Internals Manual
3============================
4
5.. contents::
6   :local:
7
8Introduction
9============
10
11This document describes some of the more important APIs and internal design
12decisions made in the Clang C front-end.  The purpose of this document is to
13both capture some of this high level information and also describe some of the
14design decisions behind it.  This is meant for people interested in hacking on
15Clang, not for end-users.  The description below is categorized by libraries,
16and does not describe any of the clients of the libraries.
17
18LLVM Support Library
19====================
20
21The LLVM ``libSupport`` library provides many underlying libraries and
22`data-structures <http://llvm.org/docs/ProgrammersManual.html>`_, including
23command line option processing, various containers and a system abstraction
24layer, which is used for file system access.
25
26The Clang "Basic" Library
27=========================
28
29This library certainly needs a better name.  The "basic" library contains a
30number of low-level utilities for tracking and manipulating source buffers,
31locations within the source buffers, diagnostics, tokens, target abstraction,
32and information about the subset of the language being compiled for.
33
34Part of this infrastructure is specific to C (such as the ``TargetInfo``
35class), other parts could be reused for other non-C-based languages
36(``SourceLocation``, ``SourceManager``, ``Diagnostics``, ``FileManager``).
37When and if there is future demand we can figure out if it makes sense to
38introduce a new library, move the general classes somewhere else, or introduce
39some other solution.
40
41We describe the roles of these classes in order of their dependencies.
42
43The Diagnostics Subsystem
44-------------------------
45
46The Clang Diagnostics subsystem is an important part of how the compiler
47communicates with the human.  Diagnostics are the warnings and errors produced
48when 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
52arguments to the diagnostic (which fill in "%0"'s in the string) as well as a
53number of source ranges that related to the diagnostic.
54
55In this section, we'll be giving examples produced by the Clang command line
56driver, but diagnostics can be :ref:`rendered in many different ways
57<DiagnosticConsumer>` depending on how the ``DiagnosticConsumer`` interface is
58implemented.  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
66In this example, you can see the English translation, the severity (error), you
67can see the source location (the caret ("``^``") and file/line/column info),
68the source ranges "``~~~~``", arguments to the diagnostic ("``int*``" and
69"``_Complex float``").  You'll have to believe me that there is a unique ID
70backing the diagnostic :).
71
72Getting all of this to happen has several steps and involves many moving
73pieces, this section describes them and talks about best practices when adding
74a new diagnostic.
75
76The ``Diagnostic*Kinds.td`` files
77^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
78
79Diagnostics are created by adding an entry to one of the
80``clang/Basic/Diagnostic*Kinds.td`` files, depending on what library will be
81using it.  From this file, :program:`tblgen` generates the unique ID of the
82diagnostic, the severity of the diagnostic and the English translation + format
83string.
84
85There is little sanity with the naming of the unique ID's right now.  Some
86start with ``err_``, ``warn_``, ``ext_`` to encode the severity into the name.
87Since the enum is referenced in the C++ code that produces the diagnostic, it
88is somewhat useful for it to be reasonably short.
89
90The severity of the diagnostic comes from the set {``NOTE``, ``REMARK``,
91``WARNING``,
92``EXTENSION``, ``EXTWARN``, ``ERROR``}.  The ``ERROR`` severity is used for
93diagnostics indicating the program is never acceptable under any circumstances.
94When an error is emitted, the AST for the input code may not be fully built.
95The ``EXTENSION`` and ``EXTWARN`` severities are used for extensions to the
96language that Clang accepts.  This means that Clang fully understands and can
97represent them in the AST, but we produce diagnostics to tell the user their
98code is non-portable.  The difference is that the former are ignored by
99default, and the later warn by default.  The ``WARNING`` severity is used for
100constructs that are valid in the currently selected source language but that
101are dubious in some way.  The ``REMARK`` severity provides generic information
102about 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
105These *severities* are mapped into a smaller set (the ``Diagnostic::Level``
106enum, {``Ignored``, ``Note``, ``Remark``, ``Warning``, ``Error``, ``Fatal``}) of
107output
108*levels* by the diagnostics subsystem based on various configuration options.
109Clang internally supports a fully fine grained mapping mechanism that allows
110you to map almost any diagnostic to the output level that you want.  The only
111diagnostics that cannot be mapped are ``NOTE``\ s, which always follow the
112severity of the previously emitted diagnostic and ``ERROR``\ s, which can only
113be mapped to ``Fatal`` (it is not possible to turn an error into a warning, for
114example).
115
116Diagnostic 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
119options like ``-Wunused_macros``, ``-Wundef`` etc.
120
121Mapping to ``Fatal`` should only be used for diagnostics that are considered so
122severe that error recovery won't be able to recover sensibly from them (thus
123spewing a ton of bogus errors).  One example of this class of error are failure
124to ``#include`` a file.
125
126The Format String
127^^^^^^^^^^^^^^^^^
128
129The format string for the diagnostic is very simple, but it has some power.  It
130takes the form of a string in English with markers that indicate where and how
131arguments to the diagnostic are inserted and formatted.  For example, here are
132some simple format strings:
133
134.. code-block:: c++
135
136  "binary integer literals are an extension"
137  "format string contains '\\0' within the string body"
138  "more '%%' conversions than data arguments"
139  "invalid operands to binary expression (%0 and %1)"
140  "overloaded '%0' must be a %select{unary|binary|unary or binary}2 operator"
141       " (has %1 parameter%s1)"
142
143These examples show some important points of format strings.  You can use any
144plain ASCII character in the diagnostic string except "``%``" without a
145problem, but these are C strings, so you have to use and be aware of all the C
146escape sequences (as in the second example).  If you want to produce a "``%``"
147in the output, use the "``%%``" escape sequence, like the third diagnostic.
148Finally, Clang uses the "``%...[digit]``" sequences to specify where and how
149arguments to the diagnostic are formatted.
150
151Arguments to the diagnostic are numbered according to how they are specified by
152the C++ code that :ref:`produces them <internals-producing-diag>`, and are
153referenced by ``%0`` .. ``%9``.  If you have more than 10 arguments to your
154diagnostic, you are doing something wrong :).  Unlike ``printf``, there is no
155requirement that arguments to the diagnostic end up in the output in the same
156order as they are specified, you could have a format string with "``%1 %0``"
157that swaps them, for example.  The text in between the percent and digit are
158formatting instructions.  If there are no instructions, the argument is just
159turned into a string and substituted in.
160
161Here are some "best practices" for writing the English format string:
162
163* Keep the string short.  It should ideally fit in the 80 column limit of the
164  ``DiagnosticKinds.td`` file.  This avoids the diagnostic wrapping when
165  printed, and forces you to think about the important point you are conveying
166  with the diagnostic.
167* Take advantage of location information.  The user will be able to see the
168  line and location of the caret, so you don't need to tell them that the
169  problem is with the 4th argument to the function: just point to it.
170* Do not capitalize the diagnostic string, and do not end it with a period.
171* If you need to quote something in the diagnostic string, use single quotes.
172
173Diagnostics should never take random English strings as arguments: you
174shouldn't use "``you have a problem with %0``" and pass in things like "``your
175argument``" or "``your return value``" as arguments.  Doing this prevents
176:ref:`translating <internals-diag-translation>` the Clang diagnostics to other
177languages (because they'll get random English words in their otherwise
178localized diagnostic).  The exceptions to this are C/C++ language keywords
179(e.g., ``auto``, ``const``, ``mutable``, etc) and C/C++ operators (``/=``).
180Note that things like "pointer" and "reference" are not keywords.  On the other
181hand, you *can* include anything that comes from the user's source code,
182including variable names, types, labels, etc.  The "``select``" format can be
183used to achieve this sort of thing in a localizable way, see below.
184
185Formatting a Diagnostic Argument
186^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
187
188Arguments to diagnostics are fully typed internally, and come from a couple
189different classes: integers, types, names, and random strings.  Depending on
190the class of the argument, it can be optionally formatted in different ways.
191This gives the ``DiagnosticConsumer`` information about what the argument means
192without requiring it to use a specific presentation (consider this MVC for
193Clang :).
194
195Here are the different diagnostic argument formats currently supported by
196Clang:
197
198**"s" format**
199
200Example:
201  ``"requires %1 parameter%s1"``
202Class:
203  Integers
204Description:
205  This is a simple formatter for integers that is useful when producing English
206  diagnostics.  When the integer is 1, it prints as nothing.  When the integer
207  is not 1, it prints as "``s``".  This allows some simple grammatical forms to
208  be to be handled correctly, and eliminates the need to use gross things like
209  ``"requires %1 parameter(s)"``.
210
211**"select" format**
212
213Example:
214  ``"must be a %select{unary|binary|unary or binary}2 operator"``
215Class:
216  Integers
217Description:
218  This format specifier is used to merge multiple related diagnostics together
219  into one common one, without requiring the difference to be specified as an
220  English string argument.  Instead of specifying the string, the diagnostic
221  gets an integer argument and the format string selects the numbered option.
222  In this case, the "``%2``" value must be an integer in the range [0..2].  If
223  it is 0, it prints "unary", if it is 1 it prints "binary" if it is 2, it
224  prints "unary or binary".  This allows other language translations to
225  substitute reasonable words (or entire phrases) based on the semantics of the
226  diagnostic instead of having to do things textually.  The selected string
227  does undergo formatting.
228
229**"plural" format**
230
231Example:
232  ``"you have %1 %plural{1:mouse|:mice}1 connected to your computer"``
233Class:
234  Integers
235Description:
236  This is a formatter for complex plural forms.  It is designed to handle even
237  the requirements of languages with very complex plural forms, as many Baltic
238  languages have.  The argument consists of a series of expression/form pairs,
239  separated by ":", where the first form whose expression evaluates to true is
240  the result of the modifier.
241
242  An expression can be empty, in which case it is always true.  See the example
243  at the top.  Otherwise, it is a series of one or more numeric conditions,
244  separated by ",".  If any condition matches, the expression matches.  Each
245  numeric condition can take one of three forms.
246
247  * number: A simple decimal number matches if the argument is the same as the
248    number.  Example: ``"%plural{1:mouse|:mice}4"``
249  * range: A range in square brackets matches if the argument is within the
250    range.  Then range is inclusive on both ends.  Example:
251    ``"%plural{0:none|1:one|[2,5]:some|:many}2"``
252  * modulo: A modulo operator is followed by a number, and equals sign and
253    either a number or a range.  The tests are the same as for plain numbers
254    and ranges, but the argument is taken modulo the number first.  Example:
255    ``"%plural{%100=0:even hundred|%100=[1,50]:lower half|:everything else}1"``
256
257  The parser is very unforgiving.  A syntax error, even whitespace, will abort,
258  as will a failure to match the argument against any expression.
259
260**"ordinal" format**
261
262Example:
263  ``"ambiguity in %ordinal0 argument"``
264Class:
265  Integers
266Description:
267  This is a formatter which represents the argument number as an ordinal: the
268  value ``1`` becomes ``1st``, ``3`` becomes ``3rd``, and so on.  Values less
269  than ``1`` are not supported.  This formatter is currently hard-coded to use
270  English ordinals.
271
272**"objcclass" format**
273
274Example:
275  ``"method %objcclass0 not found"``
276Class:
277  ``DeclarationName``
278Description:
279  This is a simple formatter that indicates the ``DeclarationName`` corresponds
280  to an Objective-C class method selector.  As such, it prints the selector
281  with a leading "``+``".
282
283**"objcinstance" format**
284
285Example:
286  ``"method %objcinstance0 not found"``
287Class:
288  ``DeclarationName``
289Description:
290  This is a simple formatter that indicates the ``DeclarationName`` corresponds
291  to an Objective-C instance method selector.  As such, it prints the selector
292  with a leading "``-``".
293
294**"q" format**
295
296Example:
297  ``"candidate found by name lookup is %q0"``
298Class:
299  ``NamedDecl *``
300Description:
301  This formatter indicates that the fully-qualified name of the declaration
302  should be printed, e.g., "``std::vector``" rather than "``vector``".
303
304**"diff" format**
305
306Example:
307  ``"no known conversion %diff{from $ to $|from argument type to parameter type}1,2"``
308Class:
309  ``QualType``
310Description:
311  This formatter takes two ``QualType``\ s and attempts to print a template
312  difference between the two.  If tree printing is off, the text inside the
313  braces before the pipe is printed, with the formatted text replacing the $.
314  If tree printing is on, the text after the pipe is printed and a type tree is
315  printed after the diagnostic message.
316
317It is really easy to add format specifiers to the Clang diagnostics system, but
318they should be discussed before they are added.  If you are creating a lot of
319repetitive diagnostics and/or have an idea for a useful formatter, please bring
320it up on the cfe-dev mailing list.
321
322**"sub" format**
323
324Example:
325  Given the following record definition of type ``TextSubstitution``:
326
327  .. code-block:: text
328
329    def select_ovl_candidate : TextSubstitution<
330      "%select{function|constructor}0%select{| template| %2}1">;
331
332  which can be used as
333
334  .. code-block:: text
335
336    def note_ovl_candidate : Note<
337      "candidate %sub{select_ovl_candidate}3,2,1 not viable">;
338
339  and will act as if it was written
340  ``"candidate %select{function|constructor}3%select{| template| %1}2 not viable"``.
341Description:
342  This format specifier is used to avoid repeating strings verbatim in multiple
343  diagnostics. The argument to ``%sub`` must name a ``TextSubstitution`` tblgen
344  record. The substitution must specify all arguments used by the substitution,
345  and the modifier indexes in the substitution are re-numbered accordingly. The
346  substituted text must itself be a valid format string before substitution.
347
348.. _internals-producing-diag:
349
350Producing the Diagnostic
351^^^^^^^^^^^^^^^^^^^^^^^^
352
353Now that you've created the diagnostic in the ``Diagnostic*Kinds.td`` file, you
354need to write the code that detects the condition in question and emits the new
355diagnostic.  Various components of Clang (e.g., the preprocessor, ``Sema``,
356etc.) provide a helper function named "``Diag``".  It creates a diagnostic and
357accepts the arguments, ranges, and other information that goes along with it.
358
359For example, the binary expression error comes from code like this:
360
361.. code-block:: c++
362
363  if (various things that are bad)
364    Diag(Loc, diag::err_typecheck_invalid_operands)
365      << lex->getType() << rex->getType()
366      << lex->getSourceRange() << rex->getSourceRange();
367
368This shows that use of the ``Diag`` method: it takes a location (a
369:ref:`SourceLocation <SourceLocation>` object) and a diagnostic enum value
370(which matches the name from ``Diagnostic*Kinds.td``).  If the diagnostic takes
371arguments, they are specified with the ``<<`` operator: the first argument
372becomes ``%0``, the second becomes ``%1``, etc.  The diagnostic interface
373allows you to specify arguments of many different types, including ``int`` and
374``unsigned`` for integer arguments, ``const char*`` and ``std::string`` for
375string arguments, ``DeclarationName`` and ``const IdentifierInfo *`` for names,
376``QualType`` for types, etc.  ``SourceRange``\ s are also specified with the
377``<<`` operator, but do not have a specific ordering requirement.
378
379As you can see, adding and producing a diagnostic is pretty straightforward.
380The hard part is deciding exactly what you need to say to help the user,
381picking a suitable wording, and providing the information needed to format it
382correctly.  The good news is that the call site that issues a diagnostic should
383be completely independent of how the diagnostic is formatted and in what
384language it is rendered.
385
386Fix-It Hints
387^^^^^^^^^^^^
388
389In some cases, the front end emits diagnostics when it is clear that some small
390change to the source code would fix the problem.  For example, a missing
391semicolon at the end of a statement or a use of deprecated syntax that is
392easily rewritten into a more modern form.  Clang tries very hard to emit the
393diagnostic and recover gracefully in these and other cases.
394
395However, for these cases where the fix is obvious, the diagnostic can be
396annotated with a hint (referred to as a "fix-it hint") that describes how to
397change the code referenced by the diagnostic to fix the problem.  For example,
398it might add the missing semicolon at the end of the statement or rewrite the
399use of a deprecated construct into something more palatable.  Here is one such
400example from the C++ front end, where we warn about the right-shift operator
401changing meaning from C++98 to C++11:
402
403.. code-block:: text
404
405  test.cpp:3:7: warning: use of right-shift operator ('>>') in template argument
406                         will require parentheses in C++11
407  A<100 >> 2> *a;
408        ^
409    (       )
410
411Here, the fix-it hint is suggesting that parentheses be added, and showing
412exactly where those parentheses would be inserted into the source code.  The
413fix-it hints themselves describe what changes to make to the source code in an
414abstract manner, which the text diagnostic printer renders as a line of
415"insertions" below the caret line.  :ref:`Other diagnostic clients
416<DiagnosticConsumer>` might choose to render the code differently (e.g., as
417markup inline) or even give the user the ability to automatically fix the
418problem.
419
420Fix-it hints on errors and warnings need to obey these rules:
421
422* Since they are automatically applied if ``-Xclang -fixit`` is passed to the
423  driver, they should only be used when it's very likely they match the user's
424  intent.
425* Clang must recover from errors as if the fix-it had been applied.
426
427If a fix-it can't obey these rules, put the fix-it on a note.  Fix-its on notes
428are not applied automatically.
429
430All fix-it hints are described by the ``FixItHint`` class, instances of which
431should be attached to the diagnostic using the ``<<`` operator in the same way
432that highlighted source ranges and arguments are passed to the diagnostic.
433Fix-it hints can be created with one of three constructors:
434
435* ``FixItHint::CreateInsertion(Loc, Code)``
436
437    Specifies that the given ``Code`` (a string) should be inserted before the
438    source location ``Loc``.
439
440* ``FixItHint::CreateRemoval(Range)``
441
442    Specifies that the code in the given source ``Range`` should be removed.
443
444* ``FixItHint::CreateReplacement(Range, Code)``
445
446    Specifies that the code in the given source ``Range`` should be removed,
447    and replaced with the given ``Code`` string.
448
449.. _DiagnosticConsumer:
450
451The ``DiagnosticConsumer`` Interface
452^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
453
454Once code generates a diagnostic with all of the arguments and the rest of the
455relevant information, Clang needs to know what to do with it.  As previously
456mentioned, the diagnostic machinery goes through some filtering to map a
457severity onto a diagnostic level, then (assuming the diagnostic is not mapped
458to "``Ignore``") it invokes an object that implements the ``DiagnosticConsumer``
459interface with the information.
460
461It is possible to implement this interface in many different ways.  For
462example, the normal Clang ``DiagnosticConsumer`` (named
463``TextDiagnosticPrinter``) turns the arguments into strings (according to the
464various formatting rules), prints out the file/line/column information and the
465string, then prints out the line of code, the source ranges, and the caret.
466However, this behavior isn't required.
467
468Another implementation of the ``DiagnosticConsumer`` interface is the
469``TextDiagnosticBuffer`` class, which is used when Clang is in ``-verify``
470mode.  Instead of formatting and printing out the diagnostics, this
471implementation just captures and remembers the diagnostics as they fly by.
472Then ``-verify`` compares the list of produced diagnostics to the list of
473expected ones.  If they disagree, it prints out its own output.  Full
474documentation for the ``-verify`` mode can be found in the Clang API
475documentation for `VerifyDiagnosticConsumer
476</doxygen/classclang_1_1VerifyDiagnosticConsumer.html#details>`_.
477
478There are many other possible implementations of this interface, and this is
479why we prefer diagnostics to pass down rich structured information in
480arguments.  For example, an HTML output might want declaration names be
481linkified to where they come from in the source.  Another example is that a GUI
482might let you click on typedefs to expand them.  This application would want to
483pass significantly more information about types through to the GUI than a
484simple flat string.  The interface allows this to happen.
485
486.. _internals-diag-translation:
487
488Adding Translations to Clang
489^^^^^^^^^^^^^^^^^^^^^^^^^^^^
490
491Not possible yet! Diagnostic strings should be written in UTF-8, the client can
492translate to the relevant code page if needed.  Each translation completely
493replaces the format string for the diagnostic.
494
495.. _SourceLocation:
496.. _SourceManager:
497
498The ``SourceLocation`` and ``SourceManager`` classes
499----------------------------------------------------
500
501Strangely enough, the ``SourceLocation`` class represents a location within the
502source code of the program.  Important design points include:
503
504#. ``sizeof(SourceLocation)`` must be extremely small, as these are embedded
505   into many AST nodes and are passed around often.  Currently it is 32 bits.
506#. ``SourceLocation`` must be a simple value object that can be efficiently
507   copied.
508#. We should be able to represent a source location for any byte of any input
509   file.  This includes in the middle of tokens, in whitespace, in trigraphs,
510   etc.
511#. A ``SourceLocation`` must encode the current ``#include`` stack that was
512   active when the location was processed.  For example, if the location
513   corresponds to a token, it should contain the set of ``#include``\ s active
514   when the token was lexed.  This allows us to print the ``#include`` stack
515   for a diagnostic.
516#. ``SourceLocation`` must be able to describe macro expansions, capturing both
517   the ultimate instantiation point and the source of the original character
518   data.
519
520In practice, the ``SourceLocation`` works together with the ``SourceManager``
521class to encode two pieces of information about a location: its spelling
522location and its expansion location.  For most tokens, these will be the
523same.  However, for a macro expansion (or tokens that came from a ``_Pragma``
524directive) these will describe the location of the characters corresponding to
525the token and the location where the token was used (i.e., the macro
526expansion point or the location of the ``_Pragma`` itself).
527
528The Clang front-end inherently depends on the location of a token being tracked
529correctly.  If it is ever incorrect, the front-end may get confused and die.
530The reason for this is that the notion of the "spelling" of a ``Token`` in
531Clang depends on being able to find the original input characters for the
532token.  This concept maps directly to the "spelling location" for the token.
533
534``SourceRange`` and ``CharSourceRange``
535---------------------------------------
536
537.. mostly taken from http://lists.llvm.org/pipermail/cfe-dev/2010-August/010595.html
538
539Clang represents most source ranges by [first, last], where "first" and "last"
540each point to the beginning of their respective tokens.  For example consider
541the ``SourceRange`` of the following statement:
542
543.. code-block:: text
544
545  x = foo + bar;
546  ^first    ^last
547
548To map from this representation to a character-based representation, the "last"
549location needs to be adjusted to point to (or past) the end of that token with
550either ``Lexer::MeasureTokenLength()`` or ``Lexer::getLocForEndOfToken()``.  For
551the rare cases where character-level source ranges information is needed we use
552the ``CharSourceRange`` class.
553
554The Driver Library
555==================
556
557The clang Driver and library are documented :doc:`here <DriverInternals>`.
558
559Precompiled Headers
560===================
561
562Clang supports two implementations of precompiled headers.  The default
563implementation, precompiled headers (:doc:`PCH <PCHInternals>`) uses a
564serialized representation of Clang's internal data structures, encoded with the
565`LLVM bitstream format <http://llvm.org/docs/BitCodeFormat.html>`_.
566Pretokenized headers (:doc:`PTH <PTHInternals>`), on the other hand, contain a
567serialized representation of the tokens encountered when preprocessing a header
568(and anything that header includes).
569
570The Frontend Library
571====================
572
573The Frontend library contains functionality useful for building tools on top of
574the Clang libraries, for example several methods for outputting diagnostics.
575
576The Lexer and Preprocessor Library
577==================================
578
579The Lexer library contains several tightly-connected classes that are involved
580with the nasty process of lexing and preprocessing C source code.  The main
581interface to this library for outside clients is the large ``Preprocessor``
582class.  It contains the various pieces of state that are required to coherently
583read tokens out of a translation unit.
584
585The core interface to the ``Preprocessor`` object (once it is set up) is the
586``Preprocessor::Lex`` method, which returns the next :ref:`Token <Token>` from
587the preprocessor stream.  There are two types of token providers that the
588preprocessor is capable of reading from: a buffer lexer (provided by the
589:ref:`Lexer <Lexer>` class) and a buffered token stream (provided by the
590:ref:`TokenLexer <TokenLexer>` class).
591
592.. _Token:
593
594The Token class
595---------------
596
597The ``Token`` class is used to represent a single lexed token.  Tokens are
598intended to be used by the lexer/preprocess and parser libraries, but are not
599intended to live beyond them (for example, they should not live in the ASTs).
600
601Tokens most often live on the stack (or some other location that is efficient
602to access) as the parser is running, but occasionally do get buffered up.  For
603example, macro definitions are stored as a series of tokens, and the C++
604front-end periodically needs to buffer tokens up for tentative parsing and
605various pieces of look-ahead.  As such, the size of a ``Token`` matters.  On a
60632-bit system, ``sizeof(Token)`` is currently 16 bytes.
607
608Tokens occur in two forms: :ref:`annotation tokens <AnnotationToken>` and
609normal tokens.  Normal tokens are those returned by the lexer, annotation
610tokens represent semantic information and are produced by the parser, replacing
611normal tokens in the token stream.  Normal tokens contain the following
612information:
613
614* **A SourceLocation** --- This indicates the location of the start of the
615  token.
616
617* **A length** --- This stores the length of the token as stored in the
618  ``SourceBuffer``.  For tokens that include them, this length includes
619  trigraphs and escaped newlines which are ignored by later phases of the
620  compiler.  By pointing into the original source buffer, it is always possible
621  to get the original spelling of a token completely accurately.
622
623* **IdentifierInfo** --- If a token takes the form of an identifier, and if
624  identifier lookup was enabled when the token was lexed (e.g., the lexer was
625  not reading in "raw" mode) this contains a pointer to the unique hash value
626  for the identifier.  Because the lookup happens before keyword
627  identification, this field is set even for language keywords like "``for``".
628
629* **TokenKind** --- This indicates the kind of token as classified by the
630  lexer.  This includes things like ``tok::starequal`` (for the "``*=``"
631  operator), ``tok::ampamp`` for the "``&&``" token, and keyword values (e.g.,
632  ``tok::kw_for``) for identifiers that correspond to keywords.  Note that
633  some tokens can be spelled multiple ways.  For example, C++ supports
634  "operator keywords", where things like "``and``" are treated exactly like the
635  "``&&``" operator.  In these cases, the kind value is set to ``tok::ampamp``,
636  which is good for the parser, which doesn't have to consider both forms.  For
637  something that cares about which form is used (e.g., the preprocessor
638  "stringize" operator) the spelling indicates the original form.
639
640* **Flags** --- There are currently four flags tracked by the
641  lexer/preprocessor system on a per-token basis:
642
643  #. **StartOfLine** --- This was the first token that occurred on its input
644     source line.
645  #. **LeadingSpace** --- There was a space character either immediately before
646     the token or transitively before the token as it was expanded through a
647     macro.  The definition of this flag is very closely defined by the
648     stringizing requirements of the preprocessor.
649  #. **DisableExpand** --- This flag is used internally to the preprocessor to
650     represent identifier tokens which have macro expansion disabled.  This
651     prevents them from being considered as candidates for macro expansion ever
652     in the future.
653  #. **NeedsCleaning** --- This flag is set if the original spelling for the
654     token includes a trigraph or escaped newline.  Since this is uncommon,
655     many pieces of code can fast-path on tokens that did not need cleaning.
656
657One interesting (and somewhat unusual) aspect of normal tokens is that they
658don't contain any semantic information about the lexed value.  For example, if
659the token was a pp-number token, we do not represent the value of the number
660that was lexed (this is left for later pieces of code to decide).
661Additionally, the lexer library has no notion of typedef names vs variable
662names: both are returned as identifiers, and the parser is left to decide
663whether a specific identifier is a typedef or a variable (tracking this
664requires scope information among other things).  The parser can do this
665translation by replacing tokens returned by the preprocessor with "Annotation
666Tokens".
667
668.. _AnnotationToken:
669
670Annotation Tokens
671-----------------
672
673Annotation tokens are tokens that are synthesized by the parser and injected
674into the preprocessor's token stream (replacing existing tokens) to record
675semantic information found by the parser.  For example, if "``foo``" is found
676to be a typedef, the "``foo``" ``tok::identifier`` token is replaced with an
677``tok::annot_typename``.  This is useful for a couple of reasons: 1) this makes
678it easy to handle qualified type names (e.g., "``foo::bar::baz<42>::t``") in
679C++ as a single "token" in the parser.  2) if the parser backtracks, the
680reparse does not need to redo semantic analysis to determine whether a token
681sequence is a variable, type, template, etc.
682
683Annotation tokens are created by the parser and reinjected into the parser's
684token stream (when backtracking is enabled).  Because they can only exist in
685tokens that the preprocessor-proper is done with, it doesn't need to keep
686around flags like "start of line" that the preprocessor uses to do its job.
687Additionally, an annotation token may "cover" a sequence of preprocessor tokens
688(e.g., "``a::b::c``" is five preprocessor tokens).  As such, the valid fields
689of an annotation token are different than the fields for a normal token (but
690they are multiplexed into the normal ``Token`` fields):
691
692* **SourceLocation "Location"** --- The ``SourceLocation`` for the annotation
693  token indicates the first token replaced by the annotation token.  In the
694  example above, it would be the location of the "``a``" identifier.
695* **SourceLocation "AnnotationEndLoc"** --- This holds the location of the last
696  token replaced with the annotation token.  In the example above, it would be
697  the location of the "``c``" identifier.
698* **void* "AnnotationValue"** --- This contains an opaque object that the
699  parser gets from ``Sema``.  The parser merely preserves the information for
700  ``Sema`` to later interpret based on the annotation token kind.
701* **TokenKind "Kind"** --- This indicates the kind of Annotation token this is.
702  See below for the different valid kinds.
703
704Annotation tokens currently come in three kinds:
705
706#. **tok::annot_typename**: This annotation token represents a resolved
707   typename token that is potentially qualified.  The ``AnnotationValue`` field
708   contains the ``QualType`` returned by ``Sema::getTypeName()``, possibly with
709   source location information attached.
710#. **tok::annot_cxxscope**: This annotation token represents a C++ scope
711   specifier, such as "``A::B::``".  This corresponds to the grammar
712   productions "*::*" and "*:: [opt] nested-name-specifier*".  The
713   ``AnnotationValue`` pointer is a ``NestedNameSpecifier *`` returned by the
714   ``Sema::ActOnCXXGlobalScopeSpecifier`` and
715   ``Sema::ActOnCXXNestedNameSpecifier`` callbacks.
716#. **tok::annot_template_id**: This annotation token represents a C++
717   template-id such as "``foo<int, 4>``", where "``foo``" is the name of a
718   template.  The ``AnnotationValue`` pointer is a pointer to a ``malloc``'d
719   ``TemplateIdAnnotation`` object.  Depending on the context, a parsed
720   template-id that names a type might become a typename annotation token (if
721   all we care about is the named type, e.g., because it occurs in a type
722   specifier) or might remain a template-id token (if we want to retain more
723   source location information or produce a new type, e.g., in a declaration of
724   a class template specialization).  template-id annotation tokens that refer
725   to a type can be "upgraded" to typename annotation tokens by the parser.
726
727As mentioned above, annotation tokens are not returned by the preprocessor,
728they are formed on demand by the parser.  This means that the parser has to be
729aware of cases where an annotation could occur and form it where appropriate.
730This is somewhat similar to how the parser handles Translation Phase 6 of C99:
731String Concatenation (see C99 5.1.1.2).  In the case of string concatenation,
732the preprocessor just returns distinct ``tok::string_literal`` and
733``tok::wide_string_literal`` tokens and the parser eats a sequence of them
734wherever the grammar indicates that a string literal can occur.
735
736In order to do this, whenever the parser expects a ``tok::identifier`` or
737``tok::coloncolon``, it should call the ``TryAnnotateTypeOrScopeToken`` or
738``TryAnnotateCXXScopeToken`` methods to form the annotation token.  These
739methods will maximally form the specified annotation tokens and replace the
740current token with them, if applicable.  If the current tokens is not valid for
741an annotation token, it will remain an identifier or "``::``" token.
742
743.. _Lexer:
744
745The ``Lexer`` class
746-------------------
747
748The ``Lexer`` class provides the mechanics of lexing tokens out of a source
749buffer and deciding what they mean.  The ``Lexer`` is complicated by the fact
750that it operates on raw buffers that have not had spelling eliminated (this is
751a necessity to get decent performance), but this is countered with careful
752coding as well as standard performance techniques (for example, the comment
753handling code is vectorized on X86 and PowerPC hosts).
754
755The lexer has a couple of interesting modal features:
756
757* The lexer can operate in "raw" mode.  This mode has several features that
758  make it possible to quickly lex the file (e.g., it stops identifier lookup,
759  doesn't specially handle preprocessor tokens, handles EOF differently, etc).
760  This mode is used for lexing within an "``#if 0``" block, for example.
761* The lexer can capture and return comments as tokens.  This is required to
762  support the ``-C`` preprocessor mode, which passes comments through, and is
763  used by the diagnostic checker to identifier expect-error annotations.
764* The lexer can be in ``ParsingFilename`` mode, which happens when
765  preprocessing after reading a ``#include`` directive.  This mode changes the
766  parsing of "``<``" to return an "angled string" instead of a bunch of tokens
767  for each thing within the filename.
768* When parsing a preprocessor directive (after "``#``") the
769  ``ParsingPreprocessorDirective`` mode is entered.  This changes the parser to
770  return EOD at a newline.
771* The ``Lexer`` uses a ``LangOptions`` object to know whether trigraphs are
772  enabled, whether C++ or ObjC keywords are recognized, etc.
773
774In addition to these modes, the lexer keeps track of a couple of other features
775that are local to a lexed buffer, which change as the buffer is lexed:
776
777* The ``Lexer`` uses ``BufferPtr`` to keep track of the current character being
778  lexed.
779* The ``Lexer`` uses ``IsAtStartOfLine`` to keep track of whether the next
780  lexed token will start with its "start of line" bit set.
781* The ``Lexer`` keeps track of the current "``#if``" directives that are active
782  (which can be nested).
783* The ``Lexer`` keeps track of an :ref:`MultipleIncludeOpt
784  <MultipleIncludeOpt>` object, which is used to detect whether the buffer uses
785  the standard "``#ifndef XX`` / ``#define XX``" idiom to prevent multiple
786  inclusion.  If a buffer does, subsequent includes can be ignored if the
787  "``XX``" macro is defined.
788
789.. _TokenLexer:
790
791The ``TokenLexer`` class
792------------------------
793
794The ``TokenLexer`` class is a token provider that returns tokens from a list of
795tokens that came from somewhere else.  It typically used for two things: 1)
796returning tokens from a macro definition as it is being expanded 2) returning
797tokens from an arbitrary buffer of tokens.  The later use is used by
798``_Pragma`` and will most likely be used to handle unbounded look-ahead for the
799C++ parser.
800
801.. _MultipleIncludeOpt:
802
803The ``MultipleIncludeOpt`` class
804--------------------------------
805
806The ``MultipleIncludeOpt`` class implements a really simple little state
807machine that is used to detect the standard "``#ifndef XX`` / ``#define XX``"
808idiom that people typically use to prevent multiple inclusion of headers.  If a
809buffer uses this idiom and is subsequently ``#include``'d, the preprocessor can
810simply check to see whether the guarding condition is defined or not.  If so,
811the preprocessor can completely ignore the include of the header.
812
813.. _Parser:
814
815The Parser Library
816==================
817
818This library contains a recursive-descent parser that polls tokens from the
819preprocessor and notifies a client of the parsing progress.
820
821Historically, the parser used to talk to an abstract ``Action`` interface that
822had virtual methods for parse events, for example ``ActOnBinOp()``.  When Clang
823grew C++ support, the parser stopped supporting general ``Action`` clients --
824it now always talks to the :ref:`Sema library <Sema>`.  However, the Parser
825still accesses AST objects only through opaque types like ``ExprResult`` and
826``StmtResult``.  Only :ref:`Sema <Sema>` looks at the AST node contents of these
827wrappers.
828
829.. _AST:
830
831The AST Library
832===============
833
834.. _Type:
835
836The ``Type`` class and its subclasses
837-------------------------------------
838
839The ``Type`` class (and its subclasses) are an important part of the AST.
840Types are accessed through the ``ASTContext`` class, which implicitly creates
841and uniques them as they are needed.  Types have a couple of non-obvious
842features: 1) they do not capture type qualifiers like ``const`` or ``volatile``
843(see :ref:`QualType <QualType>`), and 2) they implicitly capture typedef
844information.  Once created, types are immutable (unlike decls).
845
846Typedefs in C make semantic analysis a bit more complex than it would be without
847them.  The issue is that we want to capture typedef information and represent it
848in the AST perfectly, but the semantics of operations need to "see through"
849typedefs.  For example, consider this code:
850
851.. code-block:: c++
852
853  void func() {
854    typedef int foo;
855    foo X, *Y;
856    typedef foo *bar;
857    bar Z;
858    *X; // error
859    **Y; // error
860    **Z; // error
861  }
862
863The code above is illegal, and thus we expect there to be diagnostics emitted
864on the annotated lines.  In this example, we expect to get:
865
866.. code-block:: text
867
868  test.c:6:1: error: indirection requires pointer operand ('foo' invalid)
869    *X; // error
870    ^~
871  test.c:7:1: error: indirection requires pointer operand ('foo' invalid)
872    **Y; // error
873    ^~~
874  test.c:8:1: error: indirection requires pointer operand ('foo' invalid)
875    **Z; // error
876    ^~~
877
878While this example is somewhat silly, it illustrates the point: we want to
879retain typedef information where possible, so that we can emit errors about
880"``std::string``" instead of "``std::basic_string<char, std:...``".  Doing this
881requires properly keeping typedef information (for example, the type of ``X``
882is "``foo``", not "``int``"), and requires properly propagating it through the
883various operators (for example, the type of ``*Y`` is "``foo``", not
884"``int``").  In order to retain this information, the type of these expressions
885is an instance of the ``TypedefType`` class, which indicates that the type of
886these expressions is a typedef for "``foo``".
887
888Representing types like this is great for diagnostics, because the
889user-specified type is always immediately available.  There are two problems
890with this: first, various semantic checks need to make judgements about the
891*actual structure* of a type, ignoring typedefs.  Second, we need an efficient
892way to query whether two types are structurally identical to each other,
893ignoring typedefs.  The solution to both of these problems is the idea of
894canonical types.
895
896Canonical Types
897^^^^^^^^^^^^^^^
898
899Every instance of the ``Type`` class contains a canonical type pointer.  For
900simple types with no typedefs involved (e.g., "``int``", "``int*``",
901"``int**``"), the type just points to itself.  For types that have a typedef
902somewhere in their structure (e.g., "``foo``", "``foo*``", "``foo**``",
903"``bar``"), the canonical type pointer points to their structurally equivalent
904type without any typedefs (e.g., "``int``", "``int*``", "``int**``", and
905"``int*``" respectively).
906
907This design provides a constant time operation (dereferencing the canonical type
908pointer) that gives us access to the structure of types.  For example, we can
909trivially tell that "``bar``" and "``foo*``" are the same type by dereferencing
910their canonical type pointers and doing a pointer comparison (they both point
911to the single "``int*``" type).
912
913Canonical types and typedef types bring up some complexities that must be
914carefully managed.  Specifically, the ``isa``/``cast``/``dyn_cast`` operators
915generally shouldn't be used in code that is inspecting the AST.  For example,
916when type checking the indirection operator (unary "``*``" on a pointer), the
917type checker must verify that the operand has a pointer type.  It would not be
918correct to check that with "``isa<PointerType>(SubExpr->getType())``", because
919this predicate would fail if the subexpression had a typedef type.
920
921The solution to this problem are a set of helper methods on ``Type``, used to
922check their properties.  In this case, it would be correct to use
923"``SubExpr->getType()->isPointerType()``" to do the check.  This predicate will
924return true if the *canonical type is a pointer*, which is true any time the
925type is structurally a pointer type.  The only hard part here is remembering
926not to use the ``isa``/``cast``/``dyn_cast`` operations.
927
928The second problem we face is how to get access to the pointer type once we
929know it exists.  To continue the example, the result type of the indirection
930operator is the pointee type of the subexpression.  In order to determine the
931type, we need to get the instance of ``PointerType`` that best captures the
932typedef information in the program.  If the type of the expression is literally
933a ``PointerType``, we can return that, otherwise we have to dig through the
934typedefs to find the pointer type.  For example, if the subexpression had type
935"``foo*``", we could return that type as the result.  If the subexpression had
936type "``bar``", we want to return "``foo*``" (note that we do *not* want
937"``int*``").  In order to provide all of this, ``Type`` has a
938``getAsPointerType()`` method that checks whether the type is structurally a
939``PointerType`` and, if so, returns the best one.  If not, it returns a null
940pointer.
941
942This structure is somewhat mystical, but after meditating on it, it will make
943sense to you :).
944
945.. _QualType:
946
947The ``QualType`` class
948----------------------
949
950The ``QualType`` class is designed as a trivial value class that is small,
951passed by-value and is efficient to query.  The idea of ``QualType`` is that it
952stores the type qualifiers (``const``, ``volatile``, ``restrict``, plus some
953extended qualifiers required by language extensions) separately from the types
954themselves.  ``QualType`` is conceptually a pair of "``Type*``" and the bits
955for these type qualifiers.
956
957By storing the type qualifiers as bits in the conceptual pair, it is extremely
958efficient to get the set of qualifiers on a ``QualType`` (just return the field
959of the pair), add a type qualifier (which is a trivial constant-time operation
960that sets a bit), and remove one or more type qualifiers (just return a
961``QualType`` with the bitfield set to empty).
962
963Further, because the bits are stored outside of the type itself, we do not need
964to create duplicates of types with different sets of qualifiers (i.e. there is
965only a single heap allocated "``int``" type: "``const int``" and "``volatile
966const int``" both point to the same heap allocated "``int``" type).  This
967reduces the heap size used to represent bits and also means we do not have to
968consider qualifiers when uniquing types (:ref:`Type <Type>` does not even
969contain qualifiers).
970
971In practice, the two most common type qualifiers (``const`` and ``restrict``)
972are stored in the low bits of the pointer to the ``Type`` object, together with
973a flag indicating whether extended qualifiers are present (which must be
974heap-allocated).  This means that ``QualType`` is exactly the same size as a
975pointer.
976
977.. _DeclarationName:
978
979Declaration names
980-----------------
981
982The ``DeclarationName`` class represents the name of a declaration in Clang.
983Declarations in the C family of languages can take several different forms.
984Most declarations are named by simple identifiers, e.g., "``f``" and "``x``" in
985the function declaration ``f(int x)``.  In C++, declaration names can also name
986class constructors ("``Class``" in ``struct Class { Class(); }``), class
987destructors ("``~Class``"), overloaded operator names ("``operator+``"), and
988conversion functions ("``operator void const *``").  In Objective-C,
989declaration names can refer to the names of Objective-C methods, which involve
990the method name and the parameters, collectively called a *selector*, e.g.,
991"``setWidth:height:``".  Since all of these kinds of entities --- variables,
992functions, Objective-C methods, C++ constructors, destructors, and operators
993--- are represented as subclasses of Clang's common ``NamedDecl`` class,
994``DeclarationName`` is designed to efficiently represent any kind of name.
995
996Given a ``DeclarationName`` ``N``, ``N.getNameKind()`` will produce a value
997that describes what kind of name ``N`` stores.  There are 10 options (all of
998the names are inside the ``DeclarationName`` class).
999
1000``Identifier``
1001
1002  The name is a simple identifier.  Use ``N.getAsIdentifierInfo()`` to retrieve
1003  the corresponding ``IdentifierInfo*`` pointing to the actual identifier.
1004
1005``ObjCZeroArgSelector``, ``ObjCOneArgSelector``, ``ObjCMultiArgSelector``
1006
1007  The name is an Objective-C selector, which can be retrieved as a ``Selector``
1008  instance via ``N.getObjCSelector()``.  The three possible name kinds for
1009  Objective-C reflect an optimization within the ``DeclarationName`` class:
1010  both zero- and one-argument selectors are stored as a masked
1011  ``IdentifierInfo`` pointer, and therefore require very little space, since
1012  zero- and one-argument selectors are far more common than multi-argument
1013  selectors (which use a different structure).
1014
1015``CXXConstructorName``
1016
1017  The name is a C++ constructor name.  Use ``N.getCXXNameType()`` to retrieve
1018  the :ref:`type <QualType>` that this constructor is meant to construct.  The
1019  type is always the canonical type, since all constructors for a given type
1020  have the same name.
1021
1022``CXXDestructorName``
1023
1024  The name is a C++ destructor name.  Use ``N.getCXXNameType()`` to retrieve
1025  the :ref:`type <QualType>` whose destructor is being named.  This type is
1026  always a canonical type.
1027
1028``CXXConversionFunctionName``
1029
1030  The name is a C++ conversion function.  Conversion functions are named
1031  according to the type they convert to, e.g., "``operator void const *``".
1032  Use ``N.getCXXNameType()`` to retrieve the type that this conversion function
1033  converts to.  This type is always a canonical type.
1034
1035``CXXOperatorName``
1036
1037  The name is a C++ overloaded operator name.  Overloaded operators are named
1038  according to their spelling, e.g., "``operator+``" or "``operator new []``".
1039  Use ``N.getCXXOverloadedOperator()`` to retrieve the overloaded operator (a
1040  value of type ``OverloadedOperatorKind``).
1041
1042``CXXLiteralOperatorName``
1043
1044  The name is a C++11 user defined literal operator.  User defined
1045  Literal operators are named according to the suffix they define,
1046  e.g., "``_foo``" for "``operator "" _foo``".  Use
1047  ``N.getCXXLiteralIdentifier()`` to retrieve the corresponding
1048  ``IdentifierInfo*`` pointing to the identifier.
1049
1050``CXXUsingDirective``
1051
1052  The name is a C++ using directive.  Using directives are not really
1053  NamedDecls, in that they all have the same name, but they are
1054  implemented as such in order to store them in DeclContext
1055  effectively.
1056
1057``DeclarationName``\ s are cheap to create, copy, and compare.  They require
1058only a single pointer's worth of storage in the common cases (identifiers,
1059zero- and one-argument Objective-C selectors) and use dense, uniqued storage
1060for the other kinds of names.  Two ``DeclarationName``\ s can be compared for
1061equality (``==``, ``!=``) using a simple bitwise comparison, can be ordered
1062with ``<``, ``>``, ``<=``, and ``>=`` (which provide a lexicographical ordering
1063for normal identifiers but an unspecified ordering for other kinds of names),
1064and can be placed into LLVM ``DenseMap``\ s and ``DenseSet``\ s.
1065
1066``DeclarationName`` instances can be created in different ways depending on
1067what kind of name the instance will store.  Normal identifiers
1068(``IdentifierInfo`` pointers) and Objective-C selectors (``Selector``) can be
1069implicitly converted to ``DeclarationNames``.  Names for C++ constructors,
1070destructors, conversion functions, and overloaded operators can be retrieved
1071from the ``DeclarationNameTable``, an instance of which is available as
1072``ASTContext::DeclarationNames``.  The member functions
1073``getCXXConstructorName``, ``getCXXDestructorName``,
1074``getCXXConversionFunctionName``, and ``getCXXOperatorName``, respectively,
1075return ``DeclarationName`` instances for the four kinds of C++ special function
1076names.
1077
1078.. _DeclContext:
1079
1080Declaration contexts
1081--------------------
1082
1083Every declaration in a program exists within some *declaration context*, such
1084as a translation unit, namespace, class, or function.  Declaration contexts in
1085Clang are represented by the ``DeclContext`` class, from which the various
1086declaration-context AST nodes (``TranslationUnitDecl``, ``NamespaceDecl``,
1087``RecordDecl``, ``FunctionDecl``, etc.) will derive.  The ``DeclContext`` class
1088provides several facilities common to each declaration context:
1089
1090Source-centric vs. Semantics-centric View of Declarations
1091
1092  ``DeclContext`` provides two views of the declarations stored within a
1093  declaration context.  The source-centric view accurately represents the
1094  program source code as written, including multiple declarations of entities
1095  where present (see the section :ref:`Redeclarations and Overloads
1096  <Redeclarations>`), while the semantics-centric view represents the program
1097  semantics.  The two views are kept synchronized by semantic analysis while
1098  the ASTs are being constructed.
1099
1100Storage of declarations within that context
1101
1102  Every declaration context can contain some number of declarations.  For
1103  example, a C++ class (represented by ``RecordDecl``) contains various member
1104  functions, fields, nested types, and so on.  All of these declarations will
1105  be stored within the ``DeclContext``, and one can iterate over the
1106  declarations via [``DeclContext::decls_begin()``,
1107  ``DeclContext::decls_end()``).  This mechanism provides the source-centric
1108  view of declarations in the context.
1109
1110Lookup of declarations within that context
1111
1112  The ``DeclContext`` structure provides efficient name lookup for names within
1113  that declaration context.  For example, if ``N`` is a namespace we can look
1114  for the name ``N::f`` using ``DeclContext::lookup``.  The lookup itself is
1115  based on a lazily-constructed array (for declaration contexts with a small
1116  number of declarations) or hash table (for declaration contexts with more
1117  declarations).  The lookup operation provides the semantics-centric view of
1118  the declarations in the context.
1119
1120Ownership of declarations
1121
1122  The ``DeclContext`` owns all of the declarations that were declared within
1123  its declaration context, and is responsible for the management of their
1124  memory as well as their (de-)serialization.
1125
1126All declarations are stored within a declaration context, and one can query
1127information about the context in which each declaration lives.  One can
1128retrieve the ``DeclContext`` that contains a particular ``Decl`` using
1129``Decl::getDeclContext``.  However, see the section
1130:ref:`LexicalAndSemanticContexts` for more information about how to interpret
1131this context information.
1132
1133.. _Redeclarations:
1134
1135Redeclarations and Overloads
1136^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1137
1138Within a translation unit, it is common for an entity to be declared several
1139times.  For example, we might declare a function "``f``" and then later
1140re-declare it as part of an inlined definition:
1141
1142.. code-block:: c++
1143
1144  void f(int x, int y, int z = 1);
1145
1146  inline void f(int x, int y, int z) { /* ...  */ }
1147
1148The representation of "``f``" differs in the source-centric and
1149semantics-centric views of a declaration context.  In the source-centric view,
1150all redeclarations will be present, in the order they occurred in the source
1151code, making this view suitable for clients that wish to see the structure of
1152the source code.  In the semantics-centric view, only the most recent "``f``"
1153will be found by the lookup, since it effectively replaces the first
1154declaration of "``f``".
1155
1156In the semantics-centric view, overloading of functions is represented
1157explicitly.  For example, given two declarations of a function "``g``" that are
1158overloaded, e.g.,
1159
1160.. code-block:: c++
1161
1162  void g();
1163  void g(int);
1164
1165the ``DeclContext::lookup`` operation will return a
1166``DeclContext::lookup_result`` that contains a range of iterators over
1167declarations of "``g``".  Clients that perform semantic analysis on a program
1168that is not concerned with the actual source code will primarily use this
1169semantics-centric view.
1170
1171.. _LexicalAndSemanticContexts:
1172
1173Lexical and Semantic Contexts
1174^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1175
1176Each declaration has two potentially different declaration contexts: a
1177*lexical* context, which corresponds to the source-centric view of the
1178declaration context, and a *semantic* context, which corresponds to the
1179semantics-centric view.  The lexical context is accessible via
1180``Decl::getLexicalDeclContext`` while the semantic context is accessible via
1181``Decl::getDeclContext``, both of which return ``DeclContext`` pointers.  For
1182most declarations, the two contexts are identical.  For example:
1183
1184.. code-block:: c++
1185
1186  class X {
1187  public:
1188    void f(int x);
1189  };
1190
1191Here, the semantic and lexical contexts of ``X::f`` are the ``DeclContext``
1192associated with the class ``X`` (itself stored as a ``RecordDecl`` AST node).
1193However, we can now define ``X::f`` out-of-line:
1194
1195.. code-block:: c++
1196
1197  void X::f(int x = 17) { /* ...  */ }
1198
1199This definition of "``f``" has different lexical and semantic contexts.  The
1200lexical context corresponds to the declaration context in which the actual
1201declaration occurred in the source code, e.g., the translation unit containing
1202``X``.  Thus, this declaration of ``X::f`` can be found by traversing the
1203declarations provided by [``decls_begin()``, ``decls_end()``) in the
1204translation unit.
1205
1206The semantic context of ``X::f`` corresponds to the class ``X``, since this
1207member function is (semantically) a member of ``X``.  Lookup of the name ``f``
1208into the ``DeclContext`` associated with ``X`` will then return the definition
1209of ``X::f`` (including information about the default argument).
1210
1211Transparent Declaration Contexts
1212^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1213
1214In C and C++, there are several contexts in which names that are logically
1215declared inside another declaration will actually "leak" out into the enclosing
1216scope from the perspective of name lookup.  The most obvious instance of this
1217behavior is in enumeration types, e.g.,
1218
1219.. code-block:: c++
1220
1221  enum Color {
1222    Red,
1223    Green,
1224    Blue
1225  };
1226
1227Here, ``Color`` is an enumeration, which is a declaration context that contains
1228the enumerators ``Red``, ``Green``, and ``Blue``.  Thus, traversing the list of
1229declarations contained in the enumeration ``Color`` will yield ``Red``,
1230``Green``, and ``Blue``.  However, outside of the scope of ``Color`` one can
1231name the enumerator ``Red`` without qualifying the name, e.g.,
1232
1233.. code-block:: c++
1234
1235  Color c = Red;
1236
1237There are other entities in C++ that provide similar behavior.  For example,
1238linkage specifications that use curly braces:
1239
1240.. code-block:: c++
1241
1242  extern "C" {
1243    void f(int);
1244    void g(int);
1245  }
1246  // f and g are visible here
1247
1248For source-level accuracy, we treat the linkage specification and enumeration
1249type as a declaration context in which its enclosed declarations ("``Red``",
1250"``Green``", and "``Blue``"; "``f``" and "``g``") are declared.  However, these
1251declarations are visible outside of the scope of the declaration context.
1252
1253These language features (and several others, described below) have roughly the
1254same set of requirements: declarations are declared within a particular lexical
1255context, but the declarations are also found via name lookup in scopes
1256enclosing the declaration itself.  This feature is implemented via
1257*transparent* declaration contexts (see
1258``DeclContext::isTransparentContext()``), whose declarations are visible in the
1259nearest enclosing non-transparent declaration context.  This means that the
1260lexical context of the declaration (e.g., an enumerator) will be the
1261transparent ``DeclContext`` itself, as will the semantic context, but the
1262declaration will be visible in every outer context up to and including the
1263first non-transparent declaration context (since transparent declaration
1264contexts can be nested).
1265
1266The transparent ``DeclContext``\ s are:
1267
1268* Enumerations (but not C++11 "scoped enumerations"):
1269
1270  .. code-block:: c++
1271
1272    enum Color {
1273      Red,
1274      Green,
1275      Blue
1276    };
1277    // Red, Green, and Blue are in scope
1278
1279* C++ linkage specifications:
1280
1281  .. code-block:: c++
1282
1283    extern "C" {
1284      void f(int);
1285      void g(int);
1286    }
1287    // f and g are in scope
1288
1289* Anonymous unions and structs:
1290
1291  .. code-block:: c++
1292
1293    struct LookupTable {
1294      bool IsVector;
1295      union {
1296        std::vector<Item> *Vector;
1297        std::set<Item> *Set;
1298      };
1299    };
1300
1301    LookupTable LT;
1302    LT.Vector = 0; // Okay: finds Vector inside the unnamed union
1303
1304* C++11 inline namespaces:
1305
1306  .. code-block:: c++
1307
1308    namespace mylib {
1309      inline namespace debug {
1310        class X;
1311      }
1312    }
1313    mylib::X *xp; // okay: mylib::X refers to mylib::debug::X
1314
1315.. _MultiDeclContext:
1316
1317Multiply-Defined Declaration Contexts
1318^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1319
1320C++ namespaces have the interesting --- and, so far, unique --- property that
1321the namespace can be defined multiple times, and the declarations provided by
1322each namespace definition are effectively merged (from the semantic point of
1323view).  For example, the following two code snippets are semantically
1324indistinguishable:
1325
1326.. code-block:: c++
1327
1328  // Snippet #1:
1329  namespace N {
1330    void f();
1331  }
1332  namespace N {
1333    void f(int);
1334  }
1335
1336  // Snippet #2:
1337  namespace N {
1338    void f();
1339    void f(int);
1340  }
1341
1342In Clang's representation, the source-centric view of declaration contexts will
1343actually have two separate ``NamespaceDecl`` nodes in Snippet #1, each of which
1344is a declaration context that contains a single declaration of "``f``".
1345However, the semantics-centric view provided by name lookup into the namespace
1346``N`` for "``f``" will return a ``DeclContext::lookup_result`` that contains a
1347range of iterators over declarations of "``f``".
1348
1349``DeclContext`` manages multiply-defined declaration contexts internally.  The
1350function ``DeclContext::getPrimaryContext`` retrieves the "primary" context for
1351a given ``DeclContext`` instance, which is the ``DeclContext`` responsible for
1352maintaining the lookup table used for the semantics-centric view.  Given a
1353DeclContext, one can obtain the set of declaration contexts that are
1354semantically connected to this declaration context, in source order, including
1355this context (which will be the only result, for non-namespace contexts) via
1356``DeclContext::collectAllContexts``. Note that these functions are used
1357internally within the lookup and insertion methods of the ``DeclContext``, so
1358the vast majority of clients can ignore them.
1359
1360.. _CFG:
1361
1362The ``CFG`` class
1363-----------------
1364
1365The ``CFG`` class is designed to represent a source-level control-flow graph
1366for a single statement (``Stmt*``).  Typically instances of ``CFG`` are
1367constructed for function bodies (usually an instance of ``CompoundStmt``), but
1368can also be instantiated to represent the control-flow of any class that
1369subclasses ``Stmt``, which includes simple expressions.  Control-flow graphs
1370are especially useful for performing `flow- or path-sensitive
1371<http://en.wikipedia.org/wiki/Data_flow_analysis#Sensitivities>`_ program
1372analyses on a given function.
1373
1374Basic Blocks
1375^^^^^^^^^^^^
1376
1377Concretely, an instance of ``CFG`` is a collection of basic blocks.  Each basic
1378block is an instance of ``CFGBlock``, which simply contains an ordered sequence
1379of ``Stmt*`` (each referring to statements in the AST).  The ordering of
1380statements within a block indicates unconditional flow of control from one
1381statement to the next.  :ref:`Conditional control-flow
1382<ConditionalControlFlow>` is represented using edges between basic blocks.  The
1383statements within a given ``CFGBlock`` can be traversed using the
1384``CFGBlock::*iterator`` interface.
1385
1386A ``CFG`` object owns the instances of ``CFGBlock`` within the control-flow
1387graph it represents.  Each ``CFGBlock`` within a CFG is also uniquely numbered
1388(accessible via ``CFGBlock::getBlockID()``).  Currently the number is based on
1389the ordering the blocks were created, but no assumptions should be made on how
1390``CFGBlocks`` are numbered other than their numbers are unique and that they
1391are numbered from 0..N-1 (where N is the number of basic blocks in the CFG).
1392
1393Entry and Exit Blocks
1394^^^^^^^^^^^^^^^^^^^^^
1395
1396Each instance of ``CFG`` contains two special blocks: an *entry* block
1397(accessible via ``CFG::getEntry()``), which has no incoming edges, and an
1398*exit* block (accessible via ``CFG::getExit()``), which has no outgoing edges.
1399Neither block contains any statements, and they serve the role of providing a
1400clear entrance and exit for a body of code such as a function body.  The
1401presence of these empty blocks greatly simplifies the implementation of many
1402analyses built on top of CFGs.
1403
1404.. _ConditionalControlFlow:
1405
1406Conditional Control-Flow
1407^^^^^^^^^^^^^^^^^^^^^^^^
1408
1409Conditional control-flow (such as those induced by if-statements and loops) is
1410represented as edges between ``CFGBlocks``.  Because different C language
1411constructs can induce control-flow, each ``CFGBlock`` also records an extra
1412``Stmt*`` that represents the *terminator* of the block.  A terminator is
1413simply the statement that caused the control-flow, and is used to identify the
1414nature of the conditional control-flow between blocks.  For example, in the
1415case of an if-statement, the terminator refers to the ``IfStmt`` object in the
1416AST that represented the given branch.
1417
1418To illustrate, consider the following code example:
1419
1420.. code-block:: c++
1421
1422  int foo(int x) {
1423    x = x + 1;
1424    if (x > 2)
1425      x++;
1426    else {
1427      x += 2;
1428      x *= 2;
1429    }
1430
1431    return x;
1432  }
1433
1434After invoking the parser+semantic analyzer on this code fragment, the AST of
1435the body of ``foo`` is referenced by a single ``Stmt*``.  We can then construct
1436an instance of ``CFG`` representing the control-flow graph of this function
1437body by single call to a static class method:
1438
1439.. code-block:: c++
1440
1441  Stmt *FooBody = ...
1442  std::unique_ptr<CFG> FooCFG = CFG::buildCFG(FooBody);
1443
1444Along with providing an interface to iterate over its ``CFGBlocks``, the
1445``CFG`` class also provides methods that are useful for debugging and
1446visualizing CFGs.  For example, the method ``CFG::dump()`` dumps a
1447pretty-printed version of the CFG to standard error.  This is especially useful
1448when one is using a debugger such as gdb.  For example, here is the output of
1449``FooCFG->dump()``:
1450
1451.. code-block:: text
1452
1453 [ B5 (ENTRY) ]
1454    Predecessors (0):
1455    Successors (1): B4
1456
1457 [ B4 ]
1458    1: x = x + 1
1459    2: (x > 2)
1460    T: if [B4.2]
1461    Predecessors (1): B5
1462    Successors (2): B3 B2
1463
1464 [ B3 ]
1465    1: x++
1466    Predecessors (1): B4
1467    Successors (1): B1
1468
1469 [ B2 ]
1470    1: x += 2
1471    2: x *= 2
1472    Predecessors (1): B4
1473    Successors (1): B1
1474
1475 [ B1 ]
1476    1: return x;
1477    Predecessors (2): B2 B3
1478    Successors (1): B0
1479
1480 [ B0 (EXIT) ]
1481    Predecessors (1): B1
1482    Successors (0):
1483
1484For each block, the pretty-printed output displays for each block the number of
1485*predecessor* blocks (blocks that have outgoing control-flow to the given
1486block) and *successor* blocks (blocks that have control-flow that have incoming
1487control-flow from the given block).  We can also clearly see the special entry
1488and exit blocks at the beginning and end of the pretty-printed output.  For the
1489entry block (block B5), the number of predecessor blocks is 0, while for the
1490exit block (block B0) the number of successor blocks is 0.
1491
1492The most interesting block here is B4, whose outgoing control-flow represents
1493the branching caused by the sole if-statement in ``foo``.  Of particular
1494interest is the second statement in the block, ``(x > 2)``, and the terminator,
1495printed as ``if [B4.2]``.  The second statement represents the evaluation of
1496the condition of the if-statement, which occurs before the actual branching of
1497control-flow.  Within the ``CFGBlock`` for B4, the ``Stmt*`` for the second
1498statement refers to the actual expression in the AST for ``(x > 2)``.  Thus
1499pointers to subclasses of ``Expr`` can appear in the list of statements in a
1500block, and not just subclasses of ``Stmt`` that refer to proper C statements.
1501
1502The terminator of block B4 is a pointer to the ``IfStmt`` object in the AST.
1503The pretty-printer outputs ``if [B4.2]`` because the condition expression of
1504the if-statement has an actual place in the basic block, and thus the
1505terminator is essentially *referring* to the expression that is the second
1506statement of block B4 (i.e., B4.2).  In this manner, conditions for
1507control-flow (which also includes conditions for loops and switch statements)
1508are hoisted into the actual basic block.
1509
1510.. Implicit Control-Flow
1511.. ^^^^^^^^^^^^^^^^^^^^^
1512
1513.. A key design principle of the ``CFG`` class was to not require any
1514.. transformations to the AST in order to represent control-flow.  Thus the
1515.. ``CFG`` does not perform any "lowering" of the statements in an AST: loops
1516.. are not transformed into guarded gotos, short-circuit operations are not
1517.. converted to a set of if-statements, and so on.
1518
1519Constant Folding in the Clang AST
1520---------------------------------
1521
1522There are several places where constants and constant folding matter a lot to
1523the Clang front-end.  First, in general, we prefer the AST to retain the source
1524code as close to how the user wrote it as possible.  This means that if they
1525wrote "``5+4``", we want to keep the addition and two constants in the AST, we
1526don't want to fold to "``9``".  This means that constant folding in various
1527ways turns into a tree walk that needs to handle the various cases.
1528
1529However, there are places in both C and C++ that require constants to be
1530folded.  For example, the C standard defines what an "integer constant
1531expression" (i-c-e) is with very precise and specific requirements.  The
1532language then requires i-c-e's in a lot of places (for example, the size of a
1533bitfield, the value for a case statement, etc).  For these, we have to be able
1534to constant fold the constants, to do semantic checks (e.g., verify bitfield
1535size is non-negative and that case statements aren't duplicated).  We aim for
1536Clang to be very pedantic about this, diagnosing cases when the code does not
1537use an i-c-e where one is required, but accepting the code unless running with
1538``-pedantic-errors``.
1539
1540Things get a little bit more tricky when it comes to compatibility with
1541real-world source code.  Specifically, GCC has historically accepted a huge
1542superset of expressions as i-c-e's, and a lot of real world code depends on
1543this unfortunate accident of history (including, e.g., the glibc system
1544headers).  GCC accepts anything its "fold" optimizer is capable of reducing to
1545an integer constant, which means that the definition of what it accepts changes
1546as its optimizer does.  One example is that GCC accepts things like "``case
1547X-X:``" even when ``X`` is a variable, because it can fold this to 0.
1548
1549Another issue are how constants interact with the extensions we support, such
1550as ``__builtin_constant_p``, ``__builtin_inf``, ``__extension__`` and many
1551others.  C99 obviously does not specify the semantics of any of these
1552extensions, and the definition of i-c-e does not include them.  However, these
1553extensions are often used in real code, and we have to have a way to reason
1554about them.
1555
1556Finally, this is not just a problem for semantic analysis.  The code generator
1557and other clients have to be able to fold constants (e.g., to initialize global
1558variables) and has to handle a superset of what C99 allows.  Further, these
1559clients can benefit from extended information.  For example, we know that
1560"``foo() || 1``" always evaluates to ``true``, but we can't replace the
1561expression with ``true`` because it has side effects.
1562
1563Implementation Approach
1564^^^^^^^^^^^^^^^^^^^^^^^
1565
1566After trying several different approaches, we've finally converged on a design
1567(Note, at the time of this writing, not all of this has been implemented,
1568consider this a design goal!).  Our basic approach is to define a single
1569recursive evaluation method (``Expr::Evaluate``), which is implemented
1570in ``AST/ExprConstant.cpp``.  Given an expression with "scalar" type (integer,
1571fp, complex, or pointer) this method returns the following information:
1572
1573* Whether the expression is an integer constant expression, a general constant
1574  that was folded but has no side effects, a general constant that was folded
1575  but that does have side effects, or an uncomputable/unfoldable value.
1576* If the expression was computable in any way, this method returns the
1577  ``APValue`` for the result of the expression.
1578* If the expression is not evaluatable at all, this method returns information
1579  on one of the problems with the expression.  This includes a
1580  ``SourceLocation`` for where the problem is, and a diagnostic ID that explains
1581  the problem.  The diagnostic should have ``ERROR`` type.
1582* If the expression is not an integer constant expression, this method returns
1583  information on one of the problems with the expression.  This includes a
1584  ``SourceLocation`` for where the problem is, and a diagnostic ID that
1585  explains the problem.  The diagnostic should have ``EXTENSION`` type.
1586
1587This information gives various clients the flexibility that they want, and we
1588will eventually have some helper methods for various extensions.  For example,
1589``Sema`` should have a ``Sema::VerifyIntegerConstantExpression`` method, which
1590calls ``Evaluate`` on the expression.  If the expression is not foldable, the
1591error is emitted, and it would return ``true``.  If the expression is not an
1592i-c-e, the ``EXTENSION`` diagnostic is emitted.  Finally it would return
1593``false`` to indicate that the AST is OK.
1594
1595Other clients can use the information in other ways, for example, codegen can
1596just use expressions that are foldable in any way.
1597
1598Extensions
1599^^^^^^^^^^
1600
1601This section describes how some of the various extensions Clang supports
1602interacts with constant evaluation:
1603
1604* ``__extension__``: The expression form of this extension causes any
1605  evaluatable subexpression to be accepted as an integer constant expression.
1606* ``__builtin_constant_p``: This returns true (as an integer constant
1607  expression) if the operand evaluates to either a numeric value (that is, not
1608  a pointer cast to integral type) of integral, enumeration, floating or
1609  complex type, or if it evaluates to the address of the first character of a
1610  string literal (possibly cast to some other type).  As a special case, if
1611  ``__builtin_constant_p`` is the (potentially parenthesized) condition of a
1612  conditional operator expression ("``?:``"), only the true side of the
1613  conditional operator is considered, and it is evaluated with full constant
1614  folding.
1615* ``__builtin_choose_expr``: The condition is required to be an integer
1616  constant expression, but we accept any constant as an "extension of an
1617  extension".  This only evaluates one operand depending on which way the
1618  condition evaluates.
1619* ``__builtin_classify_type``: This always returns an integer constant
1620  expression.
1621* ``__builtin_inf, nan, ...``: These are treated just like a floating-point
1622  literal.
1623* ``__builtin_abs, copysign, ...``: These are constant folded as general
1624  constant expressions.
1625* ``__builtin_strlen`` and ``strlen``: These are constant folded as integer
1626  constant expressions if the argument is a string literal.
1627
1628.. _Sema:
1629
1630The Sema Library
1631================
1632
1633This library is called by the :ref:`Parser library <Parser>` during parsing to
1634do semantic analysis of the input.  For valid programs, Sema builds an AST for
1635parsed constructs.
1636
1637.. _CodeGen:
1638
1639The CodeGen Library
1640===================
1641
1642CodeGen takes an :ref:`AST <AST>` as input and produces `LLVM IR code
1643<//llvm.org/docs/LangRef.html>`_ from it.
1644
1645How to change Clang
1646===================
1647
1648How to add an attribute
1649-----------------------
1650Attributes are a form of metadata that can be attached to a program construct,
1651allowing the programmer to pass semantic information along to the compiler for
1652various uses. For example, attributes may be used to alter the code generation
1653for a program construct, or to provide extra semantic information for static
1654analysis. This document explains how to add a custom attribute to Clang.
1655Documentation on existing attributes can be found `here
1656<//clang.llvm.org/docs/AttributeReference.html>`_.
1657
1658Attribute Basics
1659^^^^^^^^^^^^^^^^
1660Attributes in Clang are handled in three stages: parsing into a parsed attribute
1661representation, conversion from a parsed attribute into a semantic attribute,
1662and then the semantic handling of the attribute.
1663
1664Parsing of the attribute is determined by the various syntactic forms attributes
1665can take, such as GNU, C++11, and Microsoft style attributes, as well as other
1666information provided by the table definition of the attribute. Ultimately, the
1667parsed representation of an attribute object is an ``ParsedAttr`` object.
1668These parsed attributes chain together as a list of parsed attributes attached
1669to a declarator or declaration specifier. The parsing of attributes is handled
1670automatically by Clang, except for attributes spelled as keywords. When
1671implementing a keyword attribute, the parsing of the keyword and creation of the
1672``ParsedAttr`` object must be done manually.
1673
1674Eventually, ``Sema::ProcessDeclAttributeList()`` is called with a ``Decl`` and
1675an ``ParsedAttr``, at which point the parsed attribute can be transformed
1676into a semantic attribute. The process by which a parsed attribute is converted
1677into a semantic attribute depends on the attribute definition and semantic
1678requirements of the attribute. The end result, however, is that the semantic
1679attribute object is attached to the ``Decl`` object, and can be obtained by a
1680call to ``Decl::getAttr<T>()``.
1681
1682The structure of the semantic attribute is also governed by the attribute
1683definition given in Attr.td. This definition is used to automatically generate
1684functionality used for the implementation of the attribute, such as a class
1685derived from ``clang::Attr``, information for the parser to use, automated
1686semantic checking for some attributes, etc.
1687
1688
1689``include/clang/Basic/Attr.td``
1690^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1691The first step to adding a new attribute to Clang is to add its definition to
1692`include/clang/Basic/Attr.td
1693<http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/Attr.td?view=markup>`_.
1694This tablegen definition must derive from the ``Attr`` (tablegen, not
1695semantic) type, or one of its derivatives. Most attributes will derive from the
1696``InheritableAttr`` type, which specifies that the attribute can be inherited by
1697later redeclarations of the ``Decl`` it is associated with.
1698``InheritableParamAttr`` is similar to ``InheritableAttr``, except that the
1699attribute is written on a parameter instead of a declaration. If the attribute
1700is intended to apply to a type instead of a declaration, such an attribute
1701should derive from ``TypeAttr``, and will generally not be given an AST
1702representation. (Note that this document does not cover the creation of type
1703attributes.) An attribute that inherits from ``IgnoredAttr`` is parsed, but will
1704generate an ignored attribute diagnostic when used, which may be useful when an
1705attribute is supported by another vendor but not supported by clang.
1706
1707The definition will specify several key pieces of information, such as the
1708semantic name of the attribute, the spellings the attribute supports, the
1709arguments the attribute expects, and more. Most members of the ``Attr`` tablegen
1710type do not require definitions in the derived definition as the default
1711suffice. However, every attribute must specify at least a spelling list, a
1712subject list, and a documentation list.
1713
1714Spellings
1715~~~~~~~~~
1716All attributes are required to specify a spelling list that denotes the ways in
1717which the attribute can be spelled. For instance, a single semantic attribute
1718may have a keyword spelling, as well as a C++11 spelling and a GNU spelling. An
1719empty spelling list is also permissible and may be useful for attributes which
1720are created implicitly. The following spellings are accepted:
1721
1722  ============  ================================================================
1723  Spelling      Description
1724  ============  ================================================================
1725  ``GNU``       Spelled with a GNU-style ``__attribute__((attr))`` syntax and
1726                placement.
1727  ``CXX11``     Spelled with a C++-style ``[[attr]]`` syntax. If the attribute
1728                is meant to be used by Clang, it should set the namespace to
1729                ``"clang"``.
1730  ``Declspec``  Spelled with a Microsoft-style ``__declspec(attr)`` syntax.
1731  ``Keyword``   The attribute is spelled as a keyword, and required custom
1732                parsing.
1733  ``GCC``       Specifies two spellings: the first is a GNU-style spelling, and
1734                the second is a C++-style spelling with the ``gnu`` namespace.
1735                Attributes should only specify this spelling for attributes
1736                supported by GCC.
1737  ``Pragma``    The attribute is spelled as a ``#pragma``, and requires custom
1738                processing within the preprocessor. If the attribute is meant to
1739                be used by Clang, it should set the namespace to ``"clang"``.
1740                Note that this spelling is not used for declaration attributes.
1741  ============  ================================================================
1742
1743Subjects
1744~~~~~~~~
1745Attributes appertain to one or more ``Decl`` subjects. If the attribute attempts
1746to attach to a subject that is not in the subject list, a diagnostic is issued
1747automatically. Whether the diagnostic is a warning or an error depends on how
1748the attribute's ``SubjectList`` is defined, but the default behavior is to warn.
1749The diagnostics displayed to the user are automatically determined based on the
1750subjects in the list, but a custom diagnostic parameter can also be specified in
1751the ``SubjectList``. The diagnostics generated for subject list violations are
1752either ``diag::warn_attribute_wrong_decl_type`` or
1753``diag::err_attribute_wrong_decl_type``, and the parameter enumeration is found
1754in `include/clang/Sema/ParsedAttr.h
1755<http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Sema/ParsedAttr.h?view=markup>`_
1756If a previously unused Decl node is added to the ``SubjectList``, the logic used
1757to automatically determine the diagnostic parameter in `utils/TableGen/ClangAttrEmitter.cpp
1758<http://llvm.org/viewvc/llvm-project/cfe/trunk/utils/TableGen/ClangAttrEmitter.cpp?view=markup>`_
1759may need to be updated.
1760
1761By default, all subjects in the SubjectList must either be a Decl node defined
1762in ``DeclNodes.td``, or a statement node defined in ``StmtNodes.td``. However,
1763more complex subjects can be created by creating a ``SubsetSubject`` object.
1764Each such object has a base subject which it appertains to (which must be a
1765Decl or Stmt node, and not a SubsetSubject node), and some custom code which is
1766called when determining whether an attribute appertains to the subject. For
1767instance, a ``NonBitField`` SubsetSubject appertains to a ``FieldDecl``, and
1768tests whether the given FieldDecl is a bit field. When a SubsetSubject is
1769specified in a SubjectList, a custom diagnostic parameter must also be provided.
1770
1771Diagnostic checking for attribute subject lists is automated except when
1772``HasCustomParsing`` is set to ``1``.
1773
1774Documentation
1775~~~~~~~~~~~~~
1776All attributes must have some form of documentation associated with them.
1777Documentation is table generated on the public web server by a server-side
1778process that runs daily. Generally, the documentation for an attribute is a
1779stand-alone definition in `include/clang/Basic/AttrDocs.td
1780<http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/AttdDocs.td?view=markup>`_
1781that is named after the attribute being documented.
1782
1783If the attribute is not for public consumption, or is an implicitly-created
1784attribute that has no visible spelling, the documentation list can specify the
1785``Undocumented`` object. Otherwise, the attribute should have its documentation
1786added to AttrDocs.td.
1787
1788Documentation derives from the ``Documentation`` tablegen type. All derived
1789types must specify a documentation category and the actual documentation itself.
1790Additionally, it can specify a custom heading for the attribute, though a
1791default heading will be chosen when possible.
1792
1793There are four predefined documentation categories: ``DocCatFunction`` for
1794attributes that appertain to function-like subjects, ``DocCatVariable`` for
1795attributes that appertain to variable-like subjects, ``DocCatType`` for type
1796attributes, and ``DocCatStmt`` for statement attributes. A custom documentation
1797category should be used for groups of attributes with similar functionality.
1798Custom categories are good for providing overview information for the attributes
1799grouped under it. For instance, the consumed annotation attributes define a
1800custom category, ``DocCatConsumed``, that explains what consumed annotations are
1801at a high level.
1802
1803Documentation content (whether it is for an attribute or a category) is written
1804using reStructuredText (RST) syntax.
1805
1806After writing the documentation for the attribute, it should be locally tested
1807to ensure that there are no issues generating the documentation on the server.
1808Local testing requires a fresh build of clang-tblgen. To generate the attribute
1809documentation, execute the following command::
1810
1811  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
1812
1813When testing locally, *do not* commit changes to ``AttributeReference.rst``.
1814This file is generated by the server automatically, and any changes made to this
1815file will be overwritten.
1816
1817Arguments
1818~~~~~~~~~
1819Attributes may optionally specify a list of arguments that can be passed to the
1820attribute. Attribute arguments specify both the parsed form and the semantic
1821form of the attribute. For example, if ``Args`` is
1822``[StringArgument<"Arg1">, IntArgument<"Arg2">]`` then
1823``__attribute__((myattribute("Hello", 3)))`` will be a valid use; it requires
1824two arguments while parsing, and the Attr subclass' constructor for the
1825semantic attribute will require a string and integer argument.
1826
1827All arguments have a name and a flag that specifies whether the argument is
1828optional. The associated C++ type of the argument is determined by the argument
1829definition type. If the existing argument types are insufficient, new types can
1830be created, but it requires modifying `utils/TableGen/ClangAttrEmitter.cpp
1831<http://llvm.org/viewvc/llvm-project/cfe/trunk/utils/TableGen/ClangAttrEmitter.cpp?view=markup>`_
1832to properly support the type.
1833
1834Other Properties
1835~~~~~~~~~~~~~~~~
1836The ``Attr`` definition has other members which control the behavior of the
1837attribute. Many of them are special-purpose and beyond the scope of this
1838document, however a few deserve mention.
1839
1840If the parsed form of the attribute is more complex, or differs from the
1841semantic form, the ``HasCustomParsing`` bit can be set to ``1`` for the class,
1842and the parsing code in `Parser::ParseGNUAttributeArgs()
1843<http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Parse/ParseDecl.cpp?view=markup>`_
1844can be updated for the special case. Note that this only applies to arguments
1845with a GNU spelling -- attributes with a __declspec spelling currently ignore
1846this flag and are handled by ``Parser::ParseMicrosoftDeclSpec``.
1847
1848Note that setting this member to 1 will opt out of common attribute semantic
1849handling, requiring extra implementation efforts to ensure the attribute
1850appertains to the appropriate subject, etc.
1851
1852If the attribute should not be propagated from a template declaration to an
1853instantiation of the template, set the ``Clone`` member to 0. By default, all
1854attributes will be cloned to template instantiations.
1855
1856Attributes that do not require an AST node should set the ``ASTNode`` field to
1857``0`` to avoid polluting the AST. Note that anything inheriting from
1858``TypeAttr`` or ``IgnoredAttr`` automatically do not generate an AST node. All
1859other attributes generate an AST node by default. The AST node is the semantic
1860representation of the attribute.
1861
1862The ``LangOpts`` field specifies a list of language options required by the
1863attribute.  For instance, all of the CUDA-specific attributes specify ``[CUDA]``
1864for the ``LangOpts`` field, and when the CUDA language option is not enabled, an
1865"attribute ignored" warning diagnostic is emitted. Since language options are
1866not table generated nodes, new language options must be created manually and
1867should specify the spelling used by ``LangOptions`` class.
1868
1869Custom accessors can be generated for an attribute based on the spelling list
1870for that attribute. For instance, if an attribute has two different spellings:
1871'Foo' and 'Bar', accessors can be created:
1872``[Accessor<"isFoo", [GNU<"Foo">]>, Accessor<"isBar", [GNU<"Bar">]>]``
1873These accessors will be generated on the semantic form of the attribute,
1874accepting no arguments and returning a ``bool``.
1875
1876Attributes that do not require custom semantic handling should set the
1877``SemaHandler`` field to ``0``. Note that anything inheriting from
1878``IgnoredAttr`` automatically do not get a semantic handler. All other
1879attributes are assumed to use a semantic handler by default. Attributes
1880without a semantic handler are not given a parsed attribute ``Kind`` enumerator.
1881
1882Target-specific attributes may share a spelling with other attributes in
1883different targets. For instance, the ARM and MSP430 targets both have an
1884attribute spelled ``GNU<"interrupt">``, but with different parsing and semantic
1885requirements. To support this feature, an attribute inheriting from
1886``TargetSpecificAttribute`` may specify a ``ParseKind`` field. This field
1887should be the same value between all arguments sharing a spelling, and
1888corresponds to the parsed attribute's ``Kind`` enumerator. This allows
1889attributes to share a parsed attribute kind, but have distinct semantic
1890attribute classes. For instance, ``ParsedAttr`` is the shared
1891parsed attribute kind, but ARMInterruptAttr and MSP430InterruptAttr are the
1892semantic attributes generated.
1893
1894By default, attribute arguments are parsed in an evaluated context. If the
1895arguments for an attribute should be parsed in an unevaluated context (akin to
1896the way the argument to a ``sizeof`` expression is parsed), set
1897``ParseArgumentsAsUnevaluated`` to ``1``.
1898
1899If additional functionality is desired for the semantic form of the attribute,
1900the ``AdditionalMembers`` field specifies code to be copied verbatim into the
1901semantic attribute class object, with ``public`` access.
1902
1903Boilerplate
1904^^^^^^^^^^^
1905All semantic processing of declaration attributes happens in `lib/Sema/SemaDeclAttr.cpp
1906<http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaDeclAttr.cpp?view=markup>`_,
1907and generally starts in the ``ProcessDeclAttribute()`` function. If the
1908attribute is a "simple" attribute -- meaning that it requires no custom semantic
1909processing aside from what is automatically  provided, add a call to
1910``handleSimpleAttribute<YourAttr>(S, D, Attr);`` to the switch statement.
1911Otherwise, write a new ``handleYourAttr()`` function, and add that to the switch
1912statement. Please do not implement handling logic directly in the ``case`` for
1913the attribute.
1914
1915Unless otherwise specified by the attribute definition, common semantic checking
1916of the parsed attribute is handled automatically. This includes diagnosing
1917parsed attributes that do not appertain to the given ``Decl``, ensuring the
1918correct minimum number of arguments are passed, etc.
1919
1920If the attribute adds additional warnings, define a ``DiagGroup`` in
1921`include/clang/Basic/DiagnosticGroups.td
1922<http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/DiagnosticGroups.td?view=markup>`_
1923named after the attribute's ``Spelling`` with "_"s replaced by "-"s. If there
1924is only a single diagnostic, it is permissible to use ``InGroup<DiagGroup<"your-attribute">>``
1925directly in `DiagnosticSemaKinds.td
1926<http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td?view=markup>`_
1927
1928All semantic diagnostics generated for your attribute, including automatically-
1929generated ones (such as subjects and argument counts), should have a
1930corresponding test case.
1931
1932Semantic handling
1933^^^^^^^^^^^^^^^^^
1934Most attributes are implemented to have some effect on the compiler. For
1935instance, to modify the way code is generated, or to add extra semantic checks
1936for an analysis pass, etc. Having added the attribute definition and conversion
1937to the semantic representation for the attribute, what remains is to implement
1938the custom logic requiring use of the attribute.
1939
1940The ``clang::Decl`` object can be queried for the presence or absence of an
1941attribute using ``hasAttr<T>()``. To obtain a pointer to the semantic
1942representation of the attribute, ``getAttr<T>`` may be used.
1943
1944How to add an expression or statement
1945-------------------------------------
1946
1947Expressions and statements are one of the most fundamental constructs within a
1948compiler, because they interact with many different parts of the AST, semantic
1949analysis, and IR generation.  Therefore, adding a new expression or statement
1950kind into Clang requires some care.  The following list details the various
1951places in Clang where an expression or statement needs to be introduced, along
1952with patterns to follow to ensure that the new expression or statement works
1953well across all of the C languages.  We focus on expressions, but statements
1954are similar.
1955
1956#. Introduce parsing actions into the parser.  Recursive-descent parsing is
1957   mostly self-explanatory, but there are a few things that are worth keeping
1958   in mind:
1959
1960   * Keep as much source location information as possible! You'll want it later
1961     to produce great diagnostics and support Clang's various features that map
1962     between source code and the AST.
1963   * Write tests for all of the "bad" parsing cases, to make sure your recovery
1964     is good.  If you have matched delimiters (e.g., parentheses, square
1965     brackets, etc.), use ``Parser::BalancedDelimiterTracker`` to give nice
1966     diagnostics when things go wrong.
1967
1968#. Introduce semantic analysis actions into ``Sema``.  Semantic analysis should
1969   always involve two functions: an ``ActOnXXX`` function that will be called
1970   directly from the parser, and a ``BuildXXX`` function that performs the
1971   actual semantic analysis and will (eventually!) build the AST node.  It's
1972   fairly common for the ``ActOnCXX`` function to do very little (often just
1973   some minor translation from the parser's representation to ``Sema``'s
1974   representation of the same thing), but the separation is still important:
1975   C++ template instantiation, for example, should always call the ``BuildXXX``
1976   variant.  Several notes on semantic analysis before we get into construction
1977   of the AST:
1978
1979   * Your expression probably involves some types and some subexpressions.
1980     Make sure to fully check that those types, and the types of those
1981     subexpressions, meet your expectations.  Add implicit conversions where
1982     necessary to make sure that all of the types line up exactly the way you
1983     want them.  Write extensive tests to check that you're getting good
1984     diagnostics for mistakes and that you can use various forms of
1985     subexpressions with your expression.
1986   * When type-checking a type or subexpression, make sure to first check
1987     whether the type is "dependent" (``Type::isDependentType()``) or whether a
1988     subexpression is type-dependent (``Expr::isTypeDependent()``).  If any of
1989     these return ``true``, then you're inside a template and you can't do much
1990     type-checking now.  That's normal, and your AST node (when you get there)
1991     will have to deal with this case.  At this point, you can write tests that
1992     use your expression within templates, but don't try to instantiate the
1993     templates.
1994   * For each subexpression, be sure to call ``Sema::CheckPlaceholderExpr()``
1995     to deal with "weird" expressions that don't behave well as subexpressions.
1996     Then, determine whether you need to perform lvalue-to-rvalue conversions
1997     (``Sema::DefaultLvalueConversions``) or the usual unary conversions
1998     (``Sema::UsualUnaryConversions``), for places where the subexpression is
1999     producing a value you intend to use.
2000   * Your ``BuildXXX`` function will probably just return ``ExprError()`` at
2001     this point, since you don't have an AST.  That's perfectly fine, and
2002     shouldn't impact your testing.
2003
2004#. Introduce an AST node for your new expression.  This starts with declaring
2005   the node in ``include/Basic/StmtNodes.td`` and creating a new class for your
2006   expression in the appropriate ``include/AST/Expr*.h`` header.  It's best to
2007   look at the class for a similar expression to get ideas, and there are some
2008   specific things to watch for:
2009
2010   * If you need to allocate memory, use the ``ASTContext`` allocator to
2011     allocate memory.  Never use raw ``malloc`` or ``new``, and never hold any
2012     resources in an AST node, because the destructor of an AST node is never
2013     called.
2014   * Make sure that ``getSourceRange()`` covers the exact source range of your
2015     expression.  This is needed for diagnostics and for IDE support.
2016   * Make sure that ``children()`` visits all of the subexpressions.  This is
2017     important for a number of features (e.g., IDE support, C++ variadic
2018     templates).  If you have sub-types, you'll also need to visit those
2019     sub-types in ``RecursiveASTVisitor``.
2020   * Add printing support (``StmtPrinter.cpp``) for your expression.
2021   * Add profiling support (``StmtProfile.cpp``) for your AST node, noting the
2022     distinguishing (non-source location) characteristics of an instance of
2023     your expression.  Omitting this step will lead to hard-to-diagnose
2024     failures regarding matching of template declarations.
2025   * Add serialization support (``ASTReaderStmt.cpp``, ``ASTWriterStmt.cpp``)
2026     for your AST node.
2027
2028#. Teach semantic analysis to build your AST node.  At this point, you can wire
2029   up your ``Sema::BuildXXX`` function to actually create your AST.  A few
2030   things to check at this point:
2031
2032   * If your expression can construct a new C++ class or return a new
2033     Objective-C object, be sure to update and then call
2034     ``Sema::MaybeBindToTemporary`` for your just-created AST node to be sure
2035     that the object gets properly destructed.  An easy way to test this is to
2036     return a C++ class with a private destructor: semantic analysis should
2037     flag an error here with the attempt to call the destructor.
2038   * Inspect the generated AST by printing it using ``clang -cc1 -ast-print``,
2039     to make sure you're capturing all of the important information about how
2040     the AST was written.
2041   * Inspect the generated AST under ``clang -cc1 -ast-dump`` to verify that
2042     all of the types in the generated AST line up the way you want them.
2043     Remember that clients of the AST should never have to "think" to
2044     understand what's going on.  For example, all implicit conversions should
2045     show up explicitly in the AST.
2046   * Write tests that use your expression as a subexpression of other,
2047     well-known expressions.  Can you call a function using your expression as
2048     an argument?  Can you use the ternary operator?
2049
2050#. Teach code generation to create IR to your AST node.  This step is the first
2051   (and only) that requires knowledge of LLVM IR.  There are several things to
2052   keep in mind:
2053
2054   * Code generation is separated into scalar/aggregate/complex and
2055     lvalue/rvalue paths, depending on what kind of result your expression
2056     produces.  On occasion, this requires some careful factoring of code to
2057     avoid duplication.
2058   * ``CodeGenFunction`` contains functions ``ConvertType`` and
2059     ``ConvertTypeForMem`` that convert Clang's types (``clang::Type*`` or
2060     ``clang::QualType``) to LLVM types.  Use the former for values, and the
2061     latter for memory locations: test with the C++ "``bool``" type to check
2062     this.  If you find that you are having to use LLVM bitcasts to make the
2063     subexpressions of your expression have the type that your expression
2064     expects, STOP!  Go fix semantic analysis and the AST so that you don't
2065     need these bitcasts.
2066   * The ``CodeGenFunction`` class has a number of helper functions to make
2067     certain operations easy, such as generating code to produce an lvalue or
2068     an rvalue, or to initialize a memory location with a given value.  Prefer
2069     to use these functions rather than directly writing loads and stores,
2070     because these functions take care of some of the tricky details for you
2071     (e.g., for exceptions).
2072   * If your expression requires some special behavior in the event of an
2073     exception, look at the ``push*Cleanup`` functions in ``CodeGenFunction``
2074     to introduce a cleanup.  You shouldn't have to deal with
2075     exception-handling directly.
2076   * Testing is extremely important in IR generation.  Use ``clang -cc1
2077     -emit-llvm`` and `FileCheck
2078     <http://llvm.org/docs/CommandGuide/FileCheck.html>`_ to verify that you're
2079     generating the right IR.
2080
2081#. Teach template instantiation how to cope with your AST node, which requires
2082   some fairly simple code:
2083
2084   * Make sure that your expression's constructor properly computes the flags
2085     for type dependence (i.e., the type your expression produces can change
2086     from one instantiation to the next), value dependence (i.e., the constant
2087     value your expression produces can change from one instantiation to the
2088     next), instantiation dependence (i.e., a template parameter occurs
2089     anywhere in your expression), and whether your expression contains a
2090     parameter pack (for variadic templates).  Often, computing these flags
2091     just means combining the results from the various types and
2092     subexpressions.
2093   * Add ``TransformXXX`` and ``RebuildXXX`` functions to the ``TreeTransform``
2094     class template in ``Sema``.  ``TransformXXX`` should (recursively)
2095     transform all of the subexpressions and types within your expression,
2096     using ``getDerived().TransformYYY``.  If all of the subexpressions and
2097     types transform without error, it will then call the ``RebuildXXX``
2098     function, which will in turn call ``getSema().BuildXXX`` to perform
2099     semantic analysis and build your expression.
2100   * To test template instantiation, take those tests you wrote to make sure
2101     that you were type checking with type-dependent expressions and dependent
2102     types (from step #2) and instantiate those templates with various types,
2103     some of which type-check and some that don't, and test the error messages
2104     in each case.
2105
2106#. There are some "extras" that make other features work better.  It's worth
2107   handling these extras to give your expression complete integration into
2108   Clang:
2109
2110   * Add code completion support for your expression in
2111     ``SemaCodeComplete.cpp``.
2112   * If your expression has types in it, or has any "interesting" features
2113     other than subexpressions, extend libclang's ``CursorVisitor`` to provide
2114     proper visitation for your expression, enabling various IDE features such
2115     as syntax highlighting, cross-referencing, and so on.  The
2116     ``c-index-test`` helper program can be used to test these features.
2117
2118