blob: 6956a118b16af341ba9453b8f7d7ee7b1dc09f45 [file] [log] [blame]
Ted Kremenek17a295d2008-06-11 06:19:49 +00001<html>
2<head>
Chris Lattner552de0a2008-11-23 08:16:56 +00003<title>"Clang" CFE Internals Manual</title>
Ted Kremenek17a295d2008-06-11 06:19:49 +00004<link type="text/css" rel="stylesheet" href="../menu.css" />
5<link type="text/css" rel="stylesheet" href="../content.css" />
Sebastian Redl68168562008-11-22 22:16:45 +00006<style type="text/css">
7td {
8 vertical-align: top;
9}
10</style>
Ted Kremenek17a295d2008-06-11 06:19:49 +000011</head>
12<body>
13
14<!--#include virtual="../menu.html.incl"-->
15
16<div id="content">
Chris Lattner86920d32007-07-31 05:42:17 +000017
Chris Lattner552de0a2008-11-23 08:16:56 +000018<h1>"Clang" CFE Internals Manual</h1>
Chris Lattner86920d32007-07-31 05:42:17 +000019
20<ul>
21<li><a href="#intro">Introduction</a></li>
22<li><a href="#libsystem">LLVM System and Support Libraries</a></li>
Chris Lattner552de0a2008-11-23 08:16:56 +000023<li><a href="#libbasic">The Clang 'Basic' Library</a>
Chris Lattner86920d32007-07-31 05:42:17 +000024 <ul>
Chris Lattner62fd2782008-11-22 21:41:31 +000025 <li><a href="#Diagnostics">The Diagnostics Subsystem</a></li>
Chris Lattner86920d32007-07-31 05:42:17 +000026 <li><a href="#SourceLocation">The SourceLocation and SourceManager
27 classes</a></li>
Douglas Gregor715c92a2010-10-27 16:02:28 +000028 <li><a href="#SourceRange">SourceRange and CharSourceRange</a></li>
Chris Lattner86920d32007-07-31 05:42:17 +000029 </ul>
30</li>
Daniel Dunbar27d9e9f2009-03-30 06:50:01 +000031<li><a href="#libdriver">The Driver Library</a>
32 <ul>
33 </ul>
34</li>
Douglas Gregor32110df2009-05-20 00:16:32 +000035<li><a href="#pch">Precompiled Headers</a>
Daniel Dunbar27d9e9f2009-03-30 06:50:01 +000036<li><a href="#libfrontend">The Frontend Library</a>
37 <ul>
38 </ul>
39</li>
Chris Lattner86920d32007-07-31 05:42:17 +000040<li><a href="#liblex">The Lexer and Preprocessor Library</a>
41 <ul>
42 <li><a href="#Token">The Token class</a></li>
43 <li><a href="#Lexer">The Lexer class</a></li>
Chris Lattner3932fe02009-01-06 06:02:08 +000044 <li><a href="#AnnotationToken">Annotation Tokens</a></li>
Chris Lattner79281252008-03-09 02:27:26 +000045 <li><a href="#TokenLexer">The TokenLexer class</a></li>
Chris Lattner86920d32007-07-31 05:42:17 +000046 <li><a href="#MultipleIncludeOpt">The MultipleIncludeOpt class</a></li>
47 </ul>
48</li>
49<li><a href="#libparse">The Parser Library</a>
50 <ul>
51 </ul>
52</li>
53<li><a href="#libast">The AST Library</a>
54 <ul>
55 <li><a href="#Type">The Type class and its subclasses</a></li>
56 <li><a href="#QualType">The QualType class</a></li>
Douglas Gregor2e1cd422008-11-17 14:58:09 +000057 <li><a href="#DeclarationName">Declaration names</a></li>
Douglas Gregor074149e2009-01-05 19:45:36 +000058 <li><a href="#DeclContext">Declaration contexts</a>
59 <ul>
60 <li><a href="#Redeclarations">Redeclarations and Overloads</a></li>
61 <li><a href="#LexicalAndSemanticContexts">Lexical and Semantic
62 Contexts</a></li>
63 <li><a href="#TransparentContexts">Transparent Declaration Contexts</a></li>
64 <li><a href="#MultiDeclContext">Multiply-Defined Declaration Contexts</a></li>
65 </ul>
66 </li>
Ted Kremenek8bc05712007-10-10 23:01:43 +000067 <li><a href="#CFG">The CFG class</a></li>
Chris Lattner7bad1992008-11-16 21:48:07 +000068 <li><a href="#Constants">Constant Folding in the Clang AST</a></li>
Chris Lattner86920d32007-07-31 05:42:17 +000069 </ul>
70</li>
Argyrios Kyrtzidis7240d772009-07-10 03:41:36 +000071<li><a href="libIndex.html">The Index Library</a></li>
Jeffrey Yasskin28dadd62011-01-28 23:41:54 +000072<li><a href="#Howtos">Howto guides</a>
73 <ul>
74 <li><a href="#AddingAttributes">How to add an attribute</a></li>
75 </ul>
76</li>
Chris Lattner86920d32007-07-31 05:42:17 +000077</ul>
78
79
80<!-- ======================================================================= -->
81<h2 id="intro">Introduction</h2>
82<!-- ======================================================================= -->
83
84<p>This document describes some of the more important APIs and internal design
Chris Lattner552de0a2008-11-23 08:16:56 +000085decisions made in the Clang C front-end. The purpose of this document is to
Chris Lattner86920d32007-07-31 05:42:17 +000086both capture some of this high level information and also describe some of the
87design decisions behind it. This is meant for people interested in hacking on
Chris Lattner552de0a2008-11-23 08:16:56 +000088Clang, not for end-users. The description below is categorized by
Chris Lattner86920d32007-07-31 05:42:17 +000089libraries, and does not describe any of the clients of the libraries.</p>
90
91<!-- ======================================================================= -->
92<h2 id="libsystem">LLVM System and Support Libraries</h2>
93<!-- ======================================================================= -->
94
Chris Lattner552de0a2008-11-23 08:16:56 +000095<p>The LLVM libsystem library provides the basic Clang system abstraction layer,
Chris Lattner86920d32007-07-31 05:42:17 +000096which is used for file system access. The LLVM libsupport library provides many
97underlying libraries and <a
98href="http://llvm.org/docs/ProgrammersManual.html">data-structures</a>,
99 including command line option
100processing and various containers.</p>
101
102<!-- ======================================================================= -->
Chris Lattner552de0a2008-11-23 08:16:56 +0000103<h2 id="libbasic">The Clang 'Basic' Library</h2>
Chris Lattner86920d32007-07-31 05:42:17 +0000104<!-- ======================================================================= -->
105
106<p>This library certainly needs a better name. The 'basic' library contains a
107number of low-level utilities for tracking and manipulating source buffers,
108locations within the source buffers, diagnostics, tokens, target abstraction,
109and information about the subset of the language being compiled for.</p>
110
111<p>Part of this infrastructure is specific to C (such as the TargetInfo class),
112other parts could be reused for other non-C-based languages (SourceLocation,
113SourceManager, Diagnostics, FileManager). When and if there is future demand
114we can figure out if it makes sense to introduce a new library, move the general
115classes somewhere else, or introduce some other solution.</p>
116
117<p>We describe the roles of these classes in order of their dependencies.</p>
118
Chris Lattner62fd2782008-11-22 21:41:31 +0000119
120<!-- ======================================================================= -->
121<h3 id="Diagnostics">The Diagnostics Subsystem</h3>
122<!-- ======================================================================= -->
123
124<p>The Clang Diagnostics subsystem is an important part of how the compiler
125communicates with the human. Diagnostics are the warnings and errors produced
126when the code is incorrect or dubious. In Clang, each diagnostic produced has
Sebastian Redl9bc2a992010-07-07 23:42:27 +0000127(at the minimum) a unique ID, an English translation associated with it, a <a
128href="#SourceLocation">SourceLocation</a> to "put the caret", and a severity (e.g.
Chris Lattner62fd2782008-11-22 21:41:31 +0000129<tt>WARNING</tt> or <tt>ERROR</tt>). They can also optionally include a number
130of arguments to the dianostic (which fill in "%0"'s in the string) as well as a
131number of source ranges that related to the diagnostic.</p>
132
Chris Lattner552de0a2008-11-23 08:16:56 +0000133<p>In this section, we'll be giving examples produced by the Clang command line
Chris Lattner62fd2782008-11-22 21:41:31 +0000134driver, but diagnostics can be <a href="#DiagnosticClient">rendered in many
135different ways</a> depending on how the DiagnosticClient interface is
Sebastian Redl9bc2a992010-07-07 23:42:27 +0000136implemented. A representative example of a diagnostic is:</p>
Chris Lattner62fd2782008-11-22 21:41:31 +0000137
138<pre>
139t.c:38:15: error: invalid operands to binary expression ('int *' and '_Complex float')
140 <font color="darkgreen">P = (P-42) + Gamma*4;</font>
141 <font color="blue">~~~~~~ ^ ~~~~~~~</font>
142</pre>
143
144<p>In this example, you can see the English translation, the severity (error),
145you can see the source location (the caret ("^") and file/line/column info),
146the source ranges "~~~~", arguments to the diagnostic ("int*" and "_Complex
147float"). You'll have to believe me that there is a unique ID backing the
148diagnostic :).</p>
149
150<p>Getting all of this to happen has several steps and involves many moving
151pieces, this section describes them and talks about best practices when adding
152a new diagnostic.</p>
153
Chris Lattnercc2ac1e2011-02-14 06:42:50 +0000154<!-- ============================= -->
155<h4>The Diagnostic*Kinds.td files</h4>
156<!-- ============================= -->
Chris Lattner62fd2782008-11-22 21:41:31 +0000157
Chris Lattner4c50b692010-05-01 17:35:19 +0000158<p>Diagnostics are created by adding an entry to one of the <tt>
Chris Lattnercc2ac1e2011-02-14 06:42:50 +0000159clang/Basic/Diagnostic*Kinds.td</tt> files, depending on what library will
160be using it. From this file, tblgen generates the unique ID of the diagnostic,
161the severity of the diagnostic and the English translation + format string.</p>
Chris Lattner62fd2782008-11-22 21:41:31 +0000162
163<p>There is little sanity with the naming of the unique ID's right now. Some
164start with err_, warn_, ext_ to encode the severity into the name. Since the
165enum is referenced in the C++ code that produces the diagnostic, it is somewhat
166useful for it to be reasonably short.</p>
167
168<p>The severity of the diagnostic comes from the set {<tt>NOTE</tt>,
169<tt>WARNING</tt>, <tt>EXTENSION</tt>, <tt>EXTWARN</tt>, <tt>ERROR</tt>}. The
170<tt>ERROR</tt> severity is used for diagnostics indicating the program is never
171acceptable under any circumstances. When an error is emitted, the AST for the
172input code may not be fully built. The <tt>EXTENSION</tt> and <tt>EXTWARN</tt>
173severities are used for extensions to the language that Clang accepts. This
174means that Clang fully understands and can represent them in the AST, but we
175produce diagnostics to tell the user their code is non-portable. The difference
176is that the former are ignored by default, and the later warn by default. The
177<tt>WARNING</tt> severity is used for constructs that are valid in the currently
178selected source language but that are dubious in some way. The <tt>NOTE</tt>
Daniel Dunbar426b8632009-02-17 15:49:03 +0000179level is used to staple more information onto previous diagnostics.</p>
Chris Lattner62fd2782008-11-22 21:41:31 +0000180
181<p>These <em>severities</em> are mapped into a smaller set (the
182Diagnostic::Level enum, {<tt>Ignored</tt>, <tt>Note</tt>, <tt>Warning</tt>,
Chris Lattner0aad2972009-02-05 22:49:08 +0000183<tt>Error</tt>, <tt>Fatal</tt> }) of output <em>levels</em> by the diagnostics
Chris Lattnera180fdd2009-02-17 07:07:29 +0000184subsystem based on various configuration options. Clang internally supports a
185fully fine grained mapping mechanism that allows you to map almost any
186diagnostic to the output level that you want. The only diagnostics that cannot
187be mapped are <tt>NOTE</tt>s, which always follow the severity of the previously
188emitted diagnostic and <tt>ERROR</tt>s, which can only be mapped to
189<tt>Fatal</tt> (it is not possible to turn an error into a warning,
190for example).</p>
191
192<p>Diagnostic mappings are used in many ways. For example, if the user
193specifies <tt>-pedantic</tt>, <tt>EXTENSION</tt> maps to <tt>Warning</tt>, if
194they specify <tt>-pedantic-errors</tt>, it turns into <tt>Error</tt>. This is
195used to implement options like <tt>-Wunused_macros</tt>, <tt>-Wundef</tt> etc.
196</p>
197
198<p>
199Mapping to <tt>Fatal</tt> should only be used for diagnostics that are
200considered so severe that error recovery won't be able to recover sensibly from
201them (thus spewing a ton of bogus errors). One example of this class of error
202are failure to #include a file.
203</p>
Chris Lattner62fd2782008-11-22 21:41:31 +0000204
205<!-- ================= -->
206<h4>The Format String</h4>
207<!-- ================= -->
208
209<p>The format string for the diagnostic is very simple, but it has some power.
210It takes the form of a string in English with markers that indicate where and
211how arguments to the diagnostic are inserted and formatted. For example, here
212are some simple format strings:</p>
213
214<pre>
215 "binary integer literals are an extension"
216 "format string contains '\\0' within the string body"
217 "more '<b>%%</b>' conversions than data arguments"
Chris Lattner545b3682008-11-23 20:27:13 +0000218 "invalid operands to binary expression (<b>%0</b> and <b>%1</b>)"
Chris Lattner62fd2782008-11-22 21:41:31 +0000219 "overloaded '<b>%0</b>' must be a <b>%select{unary|binary|unary or binary}2</b> operator"
220 " (has <b>%1</b> parameter<b>%s1</b>)"
221</pre>
222
223<p>These examples show some important points of format strings. You can use any
224 plain ASCII character in the diagnostic string except "%" without a problem,
225 but these are C strings, so you have to use and be aware of all the C escape
226 sequences (as in the second example). If you want to produce a "%" in the
227 output, use the "%%" escape sequence, like the third diagnostic. Finally,
Chris Lattner552de0a2008-11-23 08:16:56 +0000228 Clang uses the "%...[digit]" sequences to specify where and how arguments to
Chris Lattner62fd2782008-11-22 21:41:31 +0000229 the diagnostic are formatted.</p>
230
231<p>Arguments to the diagnostic are numbered according to how they are specified
232 by the C++ code that <a href="#producingdiag">produces them</a>, and are
233 referenced by <tt>%0</tt> .. <tt>%9</tt>. If you have more than 10 arguments
Chris Lattner552de0a2008-11-23 08:16:56 +0000234 to your diagnostic, you are doing something wrong :). Unlike printf, there
Chris Lattner62fd2782008-11-22 21:41:31 +0000235 is no requirement that arguments to the diagnostic end up in the output in
236 the same order as they are specified, you could have a format string with
237 <tt>"%1 %0"</tt> that swaps them, for example. The text in between the
238 percent and digit are formatting instructions. If there are no instructions,
239 the argument is just turned into a string and substituted in.</p>
240
241<p>Here are some "best practices" for writing the English format string:</p>
242
243<ul>
244<li>Keep the string short. It should ideally fit in the 80 column limit of the
Chris Lattnercc2ac1e2011-02-14 06:42:50 +0000245 <tt>DiagnosticKinds.td</tt> file. This avoids the diagnostic wrapping when
Chris Lattner62fd2782008-11-22 21:41:31 +0000246 printed, and forces you to think about the important point you are conveying
247 with the diagnostic.</li>
248<li>Take advantage of location information. The user will be able to see the
249 line and location of the caret, so you don't need to tell them that the
250 problem is with the 4th argument to the function: just point to it.</li>
251<li>Do not capitalize the diagnostic string, and do not end it with a
252 period.</li>
253<li>If you need to quote something in the diagnostic string, use single
254 quotes.</li>
255</ul>
256
257<p>Diagnostics should never take random English strings as arguments: you
258shouldn't use <tt>"you have a problem with %0"</tt> and pass in things like
259<tt>"your argument"</tt> or <tt>"your return value"</tt> as arguments. Doing
Chris Lattnercc2ac1e2011-02-14 06:42:50 +0000260this prevents <a href="#translation">translating</a> the Clang diagnostics to
Chris Lattner62fd2782008-11-22 21:41:31 +0000261other languages (because they'll get random English words in their otherwise
262localized diagnostic). The exceptions to this are C/C++ language keywords
263(e.g. auto, const, mutable, etc) and C/C++ operators (<tt>/=</tt>). Note
264that things like "pointer" and "reference" are not keywords. On the other
265hand, you <em>can</em> include anything that comes from the user's source code,
Chris Lattner552de0a2008-11-23 08:16:56 +0000266including variable names, types, labels, etc. The 'select' format can be
267used to achieve this sort of thing in a localizable way, see below.</p>
Chris Lattner62fd2782008-11-22 21:41:31 +0000268
269<!-- ==================================== -->
270<h4>Formatting a Diagnostic Argument</a></h4>
271<!-- ==================================== -->
272
273<p>Arguments to diagnostics are fully typed internally, and come from a couple
274different classes: integers, types, names, and random strings. Depending on
275the class of the argument, it can be optionally formatted in different ways.
276This gives the DiagnosticClient information about what the argument means
277without requiring it to use a specific presentation (consider this MVC for
278Clang :).</p>
279
280<p>Here are the different diagnostic argument formats currently supported by
281Clang:</p>
282
283<table>
284<tr><td colspan="2"><b>"s" format</b></td></tr>
285<tr><td>Example:</td><td><tt>"requires %1 parameter%s1"</tt></td></tr>
Chris Lattner552de0a2008-11-23 08:16:56 +0000286<tr><td>Class:</td><td>Integers</td></tr>
Chris Lattner62fd2782008-11-22 21:41:31 +0000287<tr><td>Description:</td><td>This is a simple formatter for integers that is
288 useful when producing English diagnostics. When the integer is 1, it prints
289 as nothing. When the integer is not 1, it prints as "s". This allows some
Chris Lattner627b7052008-11-23 00:28:33 +0000290 simple grammatical forms to be to be handled correctly, and eliminates the
291 need to use gross things like <tt>"requires %1 parameter(s)"</tt>.</td></tr>
Chris Lattner62fd2782008-11-22 21:41:31 +0000292
293<tr><td colspan="2"><b>"select" format</b></td></tr>
294<tr><td>Example:</td><td><tt>"must be a %select{unary|binary|unary or binary}2
295 operator"</tt></td></tr>
Chris Lattner552de0a2008-11-23 08:16:56 +0000296<tr><td>Class:</td><td>Integers</td></tr>
John McCall3a47e232010-01-14 19:12:17 +0000297<tr><td>Description:</td><td><p>This format specifier is used to merge multiple
Chris Lattnercc543342008-11-22 23:50:47 +0000298 related diagnostics together into one common one, without requiring the
Chris Lattner552de0a2008-11-23 08:16:56 +0000299 difference to be specified as an English string argument. Instead of
Chris Lattnercc543342008-11-22 23:50:47 +0000300 specifying the string, the diagnostic gets an integer argument and the
301 format string selects the numbered option. In this case, the "%2" value
302 must be an integer in the range [0..2]. If it is 0, it prints 'unary', if
303 it is 1 it prints 'binary' if it is 2, it prints 'unary or binary'. This
304 allows other language translations to substitute reasonable words (or entire
305 phrases) based on the semantics of the diagnostic instead of having to do
John McCall3a47e232010-01-14 19:12:17 +0000306 things textually.</p>
307 <p>The selected string does undergo formatting.</p></td></tr>
Chris Lattner62fd2782008-11-22 21:41:31 +0000308
309<tr><td colspan="2"><b>"plural" format</b></td></tr>
Sebastian Redl68168562008-11-22 22:16:45 +0000310<tr><td>Example:</td><td><tt>"you have %1 %plural{1:mouse|:mice}1 connected to
311 your computer"</tt></td></tr>
Chris Lattner552de0a2008-11-23 08:16:56 +0000312<tr><td>Class:</td><td>Integers</td></tr>
Sebastian Redl68168562008-11-22 22:16:45 +0000313<tr><td>Description:</td><td><p>This is a formatter for complex plural forms.
314 It is designed to handle even the requirements of languages with very
315 complex plural forms, as many Baltic languages have. The argument consists
316 of a series of expression/form pairs, separated by ':', where the first form
317 whose expression evaluates to true is the result of the modifier.</p>
318 <p>An expression can be empty, in which case it is always true. See the
319 example at the top. Otherwise, it is a series of one or more numeric
320 conditions, separated by ','. If any condition matches, the expression
321 matches. Each numeric condition can take one of three forms.</p>
322 <ul>
323 <li>number: A simple decimal number matches if the argument is the same
Chris Lattner627b7052008-11-23 00:28:33 +0000324 as the number. Example: <tt>"%plural{1:mouse|:mice}4"</tt></li>
Sebastian Redl68168562008-11-22 22:16:45 +0000325 <li>range: A range in square brackets matches if the argument is within
Chris Lattner552de0a2008-11-23 08:16:56 +0000326 the range. Then range is inclusive on both ends. Example:
Chris Lattner627b7052008-11-23 00:28:33 +0000327 <tt>"%plural{0:none|1:one|[2,5]:some|:many}2"</tt></li>
328 <li>modulo: A modulo operator is followed by a number, and
329 equals sign and either a number or a range. The tests are the
330 same as for plain
Sebastian Redl68168562008-11-22 22:16:45 +0000331 numbers and ranges, but the argument is taken modulo the number first.
Chris Lattner627b7052008-11-23 00:28:33 +0000332 Example: <tt>"%plural{%100=0:even hundred|%100=[1,50]:lower half|:everything
333 else}1"</tt></li>
Sebastian Redl68168562008-11-22 22:16:45 +0000334 </ul>
335 <p>The parser is very unforgiving. A syntax error, even whitespace, will
336 abort, as will a failure to match the argument against any
337 expression.</p></td></tr>
Chris Lattner62fd2782008-11-22 21:41:31 +0000338
John McCall3a47e232010-01-14 19:12:17 +0000339<tr><td colspan="2"><b>"ordinal" format</b></td></tr>
340<tr><td>Example:</td><td><tt>"ambiguity in %ordinal0 argument"</tt></td></tr>
341<tr><td>Class:</td><td>Integers</td></tr>
342<tr><td>Description:</td><td><p>This is a formatter which represents the
343 argument number as an ordinal: the value <tt>1</tt> becomes <tt>1st</tt>,
344 <tt>3</tt> becomes <tt>3rd</tt>, and so on. Values less than <tt>1</tt>
345 are not supported.</p>
346 <p>This formatter is currently hard-coded to use English ordinals.</p></td></tr>
347
Chris Lattner077bf5e2008-11-24 03:33:13 +0000348<tr><td colspan="2"><b>"objcclass" format</b></td></tr>
349<tr><td>Example:</td><td><tt>"method %objcclass0 not found"</tt></td></tr>
350<tr><td>Class:</td><td>DeclarationName</td></tr>
351<tr><td>Description:</td><td><p>This is a simple formatter that indicates the
352 DeclarationName corresponds to an Objective-C class method selector. As
353 such, it prints the selector with a leading '+'.</p></td></tr>
354
355<tr><td colspan="2"><b>"objcinstance" format</b></td></tr>
356<tr><td>Example:</td><td><tt>"method %objcinstance0 not found"</tt></td></tr>
357<tr><td>Class:</td><td>DeclarationName</td></tr>
358<tr><td>Description:</td><td><p>This is a simple formatter that indicates the
359 DeclarationName corresponds to an Objective-C instance method selector. As
360 such, it prints the selector with a leading '-'.</p></td></tr>
361
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000362<tr><td colspan="2"><b>"q" format</b></td></tr>
363<tr><td>Example:</td><td><tt>"candidate found by name lookup is %q0"</tt></td></tr>
364<tr><td>Class:</td><td>NamedDecl*</td></tr>
365<tr><td>Description</td><td><p>This formatter indicates that the fully-qualified name of the declaration should be printed, e.g., "std::vector" rather than "vector".</p></td></tr>
366
Chris Lattner62fd2782008-11-22 21:41:31 +0000367</table>
368
Chris Lattnercc543342008-11-22 23:50:47 +0000369<p>It is really easy to add format specifiers to the Clang diagnostics system,
Chris Lattner552de0a2008-11-23 08:16:56 +0000370but they should be discussed before they are added. If you are creating a lot
371of repetitive diagnostics and/or have an idea for a useful formatter, please
372bring it up on the cfe-dev mailing list.</p>
Chris Lattnercc543342008-11-22 23:50:47 +0000373
Chris Lattner62fd2782008-11-22 21:41:31 +0000374<!-- ===================================================== -->
Chris Lattnercc2ac1e2011-02-14 06:42:50 +0000375<h4 id="producingdiag">Producing the Diagnostic</h4>
Chris Lattner62fd2782008-11-22 21:41:31 +0000376<!-- ===================================================== -->
377
Chris Lattnercc2ac1e2011-02-14 06:42:50 +0000378<p>Now that you've created the diagnostic in the DiagnosticKinds.td file, you
Chris Lattner552de0a2008-11-23 08:16:56 +0000379need to write the code that detects the condition in question and emits the
380new diagnostic. Various components of Clang (e.g. the preprocessor, Sema,
Chris Lattner627b7052008-11-23 00:28:33 +0000381etc) provide a helper function named "Diag". It creates a diagnostic and
382accepts the arguments, ranges, and other information that goes along with
383it.</p>
Chris Lattner62fd2782008-11-22 21:41:31 +0000384
Chris Lattner552de0a2008-11-23 08:16:56 +0000385<p>For example, the binary expression error comes from code like this:</p>
Chris Lattner627b7052008-11-23 00:28:33 +0000386
387<pre>
388 if (various things that are bad)
389 Diag(Loc, diag::err_typecheck_invalid_operands)
390 &lt;&lt; lex-&gt;getType() &lt;&lt; rex-&gt;getType()
391 &lt;&lt; lex-&gt;getSourceRange() &lt;&lt; rex-&gt;getSourceRange();
392</pre>
393
394<p>This shows that use of the Diag method: they take a location (a <a
395href="#SourceLocation">SourceLocation</a> object) and a diagnostic enum value
Chris Lattnercc2ac1e2011-02-14 06:42:50 +0000396(which matches the name from DiagnosticKinds.td). If the diagnostic takes
Chris Lattner627b7052008-11-23 00:28:33 +0000397arguments, they are specified with the &lt;&lt; operator: the first argument
398becomes %0, the second becomes %1, etc. The diagnostic interface allows you to
Chris Lattnerfd408ea2008-11-23 00:42:53 +0000399specify arguments of many different types, including <tt>int</tt> and
400<tt>unsigned</tt> for integer arguments, <tt>const char*</tt> and
401<tt>std::string</tt> for string arguments, <tt>DeclarationName</tt> and
402<tt>const IdentifierInfo*</tt> for names, <tt>QualType</tt> for types, etc.
403SourceRanges are also specified with the &lt;&lt; operator, but do not have a
404specific ordering requirement.</p>
Chris Lattner627b7052008-11-23 00:28:33 +0000405
406<p>As you can see, adding and producing a diagnostic is pretty straightforward.
407The hard part is deciding exactly what you need to say to help the user, picking
408a suitable wording, and providing the information needed to format it correctly.
Chris Lattnerfd408ea2008-11-23 00:42:53 +0000409The good news is that the call site that issues a diagnostic should be
410completely independent of how the diagnostic is formatted and in what language
411it is rendered.
Chris Lattner627b7052008-11-23 00:28:33 +0000412</p>
Chris Lattner62fd2782008-11-22 21:41:31 +0000413
Douglas Gregorb2fb6de2009-02-27 17:53:17 +0000414<!-- ==================================================== -->
415<h4 id="code-modification-hints">Code Modification Hints</h4>
416<!-- ==================================================== -->
417
418<p>In some cases, the front end emits diagnostics when it is clear
419that some small change to the source code would fix the problem. For
420example, a missing semicolon at the end of a statement or a use of
Chris Lattner34c05332009-02-27 19:31:12 +0000421deprecated syntax that is easily rewritten into a more modern form.
422Clang tries very hard to emit the diagnostic and recover gracefully
423in these and other cases.</p>
Douglas Gregorb2fb6de2009-02-27 17:53:17 +0000424
Chris Lattner34c05332009-02-27 19:31:12 +0000425<p>However, for these cases where the fix is obvious, the diagnostic
426can be annotated with a code
427modification "hint" that describes how to change the code referenced
Douglas Gregorb2fb6de2009-02-27 17:53:17 +0000428by the diagnostic to fix the problem. For example, it might add the
429missing semicolon at the end of the statement or rewrite the use of a
430deprecated construct into something more palatable. Here is one such
431example C++ front end, where we warn about the right-shift operator
432changing meaning from C++98 to C++0x:</p>
433
434<pre>
435test.cpp:3:7: warning: use of right-shift operator ('&gt;&gt;') in template argument will require parentheses in C++0x
436A&lt;100 &gt;&gt; 2&gt; *a;
437 ^
438 ( )
439</pre>
440
441<p>Here, the code modification hint is suggesting that parentheses be
442added, and showing exactly where those parentheses would be inserted
443into the source code. The code modification hints themselves describe
444what changes to make to the source code in an abstract manner, which
445the text diagnostic printer renders as a line of "insertions" below
446the caret line. <a href="#DiagnosticClient">Other diagnostic
447clients</a> might choose to render the code differently (e.g., as
448markup inline) or even give the user the ability to automatically fix
449the problem.</p>
450
451<p>All code modification hints are described by the
452<code>CodeModificationHint</code> class, instances of which should be
453attached to the diagnostic using the &lt;&lt; operator in the same way
454that highlighted source ranges and arguments are passed to the
455diagnostic. Code modification hints can be created with one of three
456constructors:</p>
457
458<dl>
459 <dt><code>CodeModificationHint::CreateInsertion(Loc, Code)</code></dt>
460 <dd>Specifies that the given <code>Code</code> (a string) should be inserted
461 before the source location <code>Loc</code>.</dd>
462
463 <dt><code>CodeModificationHint::CreateRemoval(Range)</code></dt>
464 <dd>Specifies that the code in the given source <code>Range</code>
465 should be removed.</dd>
466
467 <dt><code>CodeModificationHint::CreateReplacement(Range, Code)</code></dt>
468 <dd>Specifies that the code in the given source <code>Range</code>
469 should be removed, and replaced with the given <code>Code</code> string.</dd>
470</dl>
471
Chris Lattner62fd2782008-11-22 21:41:31 +0000472<!-- ============================================================= -->
473<h4><a name="DiagnosticClient">The DiagnosticClient Interface</a></h4>
474<!-- ============================================================= -->
475
Chris Lattner627b7052008-11-23 00:28:33 +0000476<p>Once code generates a diagnostic with all of the arguments and the rest of
477the relevant information, Clang needs to know what to do with it. As previously
478mentioned, the diagnostic machinery goes through some filtering to map a
479severity onto a diagnostic level, then (assuming the diagnostic is not mapped to
480"<tt>Ignore</tt>") it invokes an object that implements the DiagnosticClient
481interface with the information.</p>
482
483<p>It is possible to implement this interface in many different ways. For
484example, the normal Clang DiagnosticClient (named 'TextDiagnosticPrinter') turns
485the arguments into strings (according to the various formatting rules), prints
486out the file/line/column information and the string, then prints out the line of
487code, the source ranges, and the caret. However, this behavior isn't required.
488</p>
489
490<p>Another implementation of the DiagnosticClient interface is the
Chris Lattner552de0a2008-11-23 08:16:56 +0000491'TextDiagnosticBuffer' class, which is used when Clang is in -verify mode.
Chris Lattnerfd408ea2008-11-23 00:42:53 +0000492Instead of formatting and printing out the diagnostics, this implementation just
493captures and remembers the diagnostics as they fly by. Then -verify compares
Chris Lattner552de0a2008-11-23 08:16:56 +0000494the list of produced diagnostics to the list of expected ones. If they disagree,
Chris Lattnerfd408ea2008-11-23 00:42:53 +0000495it prints out its own output.
Chris Lattner627b7052008-11-23 00:28:33 +0000496</p>
497
Chris Lattnerfd408ea2008-11-23 00:42:53 +0000498<p>There are many other possible implementations of this interface, and this is
499why we prefer diagnostics to pass down rich structured information in arguments.
500For example, an HTML output might want declaration names be linkified to where
501they come from in the source. Another example is that a GUI might let you click
502on typedefs to expand them. This application would want to pass significantly
503more information about types through to the GUI than a simple flat string. The
504interface allows this to happen.</p>
Chris Lattner62fd2782008-11-22 21:41:31 +0000505
506<!-- ====================================================== -->
507<h4><a name="translation">Adding Translations to Clang</a></h4>
508<!-- ====================================================== -->
509
Chris Lattner627b7052008-11-23 00:28:33 +0000510<p>Not possible yet! Diagnostic strings should be written in UTF-8, the client
Chris Lattnerfd408ea2008-11-23 00:42:53 +0000511can translate to the relevant code page if needed. Each translation completely
512replaces the format string for the diagnostic.</p>
Chris Lattner62fd2782008-11-22 21:41:31 +0000513
514
Chris Lattner86920d32007-07-31 05:42:17 +0000515<!-- ======================================================================= -->
516<h3 id="SourceLocation">The SourceLocation and SourceManager classes</h3>
517<!-- ======================================================================= -->
518
519<p>Strangely enough, the SourceLocation class represents a location within the
520source code of the program. Important design points include:</p>
521
522<ol>
523<li>sizeof(SourceLocation) must be extremely small, as these are embedded into
524 many AST nodes and are passed around often. Currently it is 32 bits.</li>
525<li>SourceLocation must be a simple value object that can be efficiently
526 copied.</li>
527<li>We should be able to represent a source location for any byte of any input
528 file. This includes in the middle of tokens, in whitespace, in trigraphs,
529 etc.</li>
530<li>A SourceLocation must encode the current #include stack that was active when
531 the location was processed. For example, if the location corresponds to a
532 token, it should contain the set of #includes active when the token was
533 lexed. This allows us to print the #include stack for a diagnostic.</li>
534<li>SourceLocation must be able to describe macro expansions, capturing both
535 the ultimate instantiation point and the source of the original character
536 data.</li>
537</ol>
538
539<p>In practice, the SourceLocation works together with the SourceManager class
Nick Lewycky77561e52010-05-26 21:48:10 +0000540to encode two pieces of information about a location: its spelling location
541and its instantiation location. For most tokens, these will be the same.
542However, for a macro expansion (or tokens that came from a _Pragma directive)
543these will describe the location of the characters corresponding to the token
544and the location where the token was used (i.e. the macro instantiation point
545or the location of the _Pragma itself).</p>
Chris Lattner86920d32007-07-31 05:42:17 +0000546
Chris Lattner552de0a2008-11-23 08:16:56 +0000547<p>The Clang front-end inherently depends on the location of a token being
Chris Lattner86920d32007-07-31 05:42:17 +0000548tracked correctly. If it is ever incorrect, the front-end may get confused and
549die. The reason for this is that the notion of the 'spelling' of a Token in
Chris Lattner552de0a2008-11-23 08:16:56 +0000550Clang depends on being able to find the original input characters for the token.
Chris Lattner18376dd2009-01-16 07:00:50 +0000551This concept maps directly to the "spelling location" for the token.</p>
Chris Lattner86920d32007-07-31 05:42:17 +0000552
Douglas Gregor715c92a2010-10-27 16:02:28 +0000553
554<!-- ======================================================================= -->
555<h3 id="SourceRange">SourceRange and CharSourceRange</h3>
556<!-- ======================================================================= -->
557<!-- mostly taken from
558 http://lists.cs.uiuc.edu/pipermail/cfe-dev/2010-August/010595.html -->
559
560<p>Clang represents most source ranges by [first, last], where first and last
561each point to the beginning of their respective tokens. For example
562consider the SourceRange of the following statement:</p>
563<pre>
564x = foo + bar;
565^first ^last
566</pre>
567
568<p>To map from this representation to a character-based
569representation, the 'last' location needs to be adjusted to point to
570(or past) the end of that token with either
571<code>Lexer::MeasureTokenLength()</code> or
Chris Lattner7ef5c272010-11-17 07:05:50 +0000572<code>Lexer::getLocForEndOfToken()</code>. For the rare cases
Douglas Gregor715c92a2010-10-27 16:02:28 +0000573where character-level source ranges information is needed we use
574the <code>CharSourceRange</code> class.</p>
575
576
Chris Lattner86920d32007-07-31 05:42:17 +0000577<!-- ======================================================================= -->
Daniel Dunbar27d9e9f2009-03-30 06:50:01 +0000578<h2 id="libdriver">The Driver Library</h2>
579<!-- ======================================================================= -->
580
Ted Kremenekcfa8d572009-04-09 18:08:18 +0000581<p>The clang Driver and library are documented <a
582href="DriverInternals.html">here<a>.<p>
583
584<!-- ======================================================================= -->
Douglas Gregor32110df2009-05-20 00:16:32 +0000585<h2 id="pch">Precompiled Headers</h2>
Ted Kremenekcfa8d572009-04-09 18:08:18 +0000586<!-- ======================================================================= -->
587
Douglas Gregor32110df2009-05-20 00:16:32 +0000588<p>Clang supports two implementations of precompiled headers. The
589 default implementation, precompiled headers (<a
590 href="PCHInternals.html">PCH</a>) uses a serialized representation
591 of Clang's internal data structures, encoded with the <a
592 href="http://llvm.org/docs/BitCodeFormat.html">LLVM bitstream
593 format</a>. Pretokenized headers (<a
594 href="PTHInternals.html">PTH</a>), on the other hand, contain a
595 serialized representation of the tokens encountered when
596 preprocessing a header (and anything that header includes).</p>
597
Daniel Dunbar27d9e9f2009-03-30 06:50:01 +0000598
599<!-- ======================================================================= -->
600<h2 id="libfrontend">The Frontend Library</h2>
601<!-- ======================================================================= -->
602
603<p>The Frontend library contains functionality useful for building
604tools on top of the clang libraries, for example several methods for
605outputting diagnostics.</p>
606
607<!-- ======================================================================= -->
Chris Lattner86920d32007-07-31 05:42:17 +0000608<h2 id="liblex">The Lexer and Preprocessor Library</h2>
609<!-- ======================================================================= -->
610
611<p>The Lexer library contains several tightly-connected classes that are involved
612with the nasty process of lexing and preprocessing C source code. The main
613interface to this library for outside clients is the large <a
614href="#Preprocessor">Preprocessor</a> class.
615It contains the various pieces of state that are required to coherently read
616tokens out of a translation unit.</p>
617
618<p>The core interface to the Preprocessor object (once it is set up) is the
619Preprocessor::Lex method, which returns the next <a href="#Token">Token</a> from
620the preprocessor stream. There are two types of token providers that the
621preprocessor is capable of reading from: a buffer lexer (provided by the <a
622href="#Lexer">Lexer</a> class) and a buffered token stream (provided by the <a
Chris Lattner79281252008-03-09 02:27:26 +0000623href="#TokenLexer">TokenLexer</a> class).
Chris Lattner86920d32007-07-31 05:42:17 +0000624
625
626<!-- ======================================================================= -->
627<h3 id="Token">The Token class</h3>
628<!-- ======================================================================= -->
629
630<p>The Token class is used to represent a single lexed token. Tokens are
631intended to be used by the lexer/preprocess and parser libraries, but are not
632intended to live beyond them (for example, they should not live in the ASTs).<p>
633
634<p>Tokens most often live on the stack (or some other location that is efficient
635to access) as the parser is running, but occasionally do get buffered up. For
636example, macro definitions are stored as a series of tokens, and the C++
Chris Lattner3fcbb892008-11-23 08:32:53 +0000637front-end periodically needs to buffer tokens up for tentative parsing and
Chris Lattner86920d32007-07-31 05:42:17 +0000638various pieces of look-ahead. As such, the size of a Token matter. On a 32-bit
639system, sizeof(Token) is currently 16 bytes.</p>
640
Chris Lattner3932fe02009-01-06 06:02:08 +0000641<p>Tokens occur in two forms: "<a href="#AnnotationToken">Annotation
642Tokens</a>" and normal tokens. Normal tokens are those returned by the lexer,
643annotation tokens represent semantic information and are produced by the parser,
644replacing normal tokens in the token stream. Normal tokens contain the
645following information:</p>
Chris Lattner86920d32007-07-31 05:42:17 +0000646
647<ul>
648<li><b>A SourceLocation</b> - This indicates the location of the start of the
649token.</li>
650
651<li><b>A length</b> - This stores the length of the token as stored in the
652SourceBuffer. For tokens that include them, this length includes trigraphs and
653escaped newlines which are ignored by later phases of the compiler. By pointing
654into the original source buffer, it is always possible to get the original
655spelling of a token completely accurately.</li>
656
657<li><b>IdentifierInfo</b> - If a token takes the form of an identifier, and if
658identifier lookup was enabled when the token was lexed (e.g. the lexer was not
659reading in 'raw' mode) this contains a pointer to the unique hash value for the
660identifier. Because the lookup happens before keyword identification, this
661field is set even for language keywords like 'for'.</li>
662
663<li><b>TokenKind</b> - This indicates the kind of token as classified by the
664lexer. This includes things like <tt>tok::starequal</tt> (for the "*="
665operator), <tt>tok::ampamp</tt> for the "&amp;&amp;" token, and keyword values
666(e.g. <tt>tok::kw_for</tt>) for identifiers that correspond to keywords. Note
667that some tokens can be spelled multiple ways. For example, C++ supports
668"operator keywords", where things like "and" are treated exactly like the
669"&amp;&amp;" operator. In these cases, the kind value is set to
670<tt>tok::ampamp</tt>, which is good for the parser, which doesn't have to
671consider both forms. For something that cares about which form is used (e.g.
672the preprocessor 'stringize' operator) the spelling indicates the original
673form.</li>
674
675<li><b>Flags</b> - There are currently four flags tracked by the
676lexer/preprocessor system on a per-token basis:
677
678 <ol>
679 <li><b>StartOfLine</b> - This was the first token that occurred on its input
680 source line.</li>
681 <li><b>LeadingSpace</b> - There was a space character either immediately
682 before the token or transitively before the token as it was expanded
683 through a macro. The definition of this flag is very closely defined by
684 the stringizing requirements of the preprocessor.</li>
685 <li><b>DisableExpand</b> - This flag is used internally to the preprocessor to
686 represent identifier tokens which have macro expansion disabled. This
687 prevents them from being considered as candidates for macro expansion ever
688 in the future.</li>
689 <li><b>NeedsCleaning</b> - This flag is set if the original spelling for the
690 token includes a trigraph or escaped newline. Since this is uncommon,
691 many pieces of code can fast-path on tokens that did not need cleaning.
692 </p>
693 </ol>
694</li>
695</ul>
696
Chris Lattner3932fe02009-01-06 06:02:08 +0000697<p>One interesting (and somewhat unusual) aspect of normal tokens is that they
698don't contain any semantic information about the lexed value. For example, if
699the token was a pp-number token, we do not represent the value of the number
700that was lexed (this is left for later pieces of code to decide). Additionally,
701the lexer library has no notion of typedef names vs variable names: both are
Chris Lattner86920d32007-07-31 05:42:17 +0000702returned as identifiers, and the parser is left to decide whether a specific
703identifier is a typedef or a variable (tracking this requires scope information
Chris Lattner3932fe02009-01-06 06:02:08 +0000704among other things). The parser can do this translation by replacing tokens
705returned by the preprocessor with "Annotation Tokens".</p>
706
707<!-- ======================================================================= -->
708<h3 id="AnnotationToken">Annotation Tokens</h3>
709<!-- ======================================================================= -->
710
711<p>Annotation Tokens are tokens that are synthesized by the parser and injected
712into the preprocessor's token stream (replacing existing tokens) to record
713semantic information found by the parser. For example, if "foo" is found to be
714a typedef, the "foo" <tt>tok::identifier</tt> token is replaced with an
715<tt>tok::annot_typename</tt>. This is useful for a couple of reasons: 1) this
716makes it easy to handle qualified type names (e.g. "foo::bar::baz&lt;42&gt;::t")
717in C++ as a single "token" in the parser. 2) if the parser backtracks, the
718reparse does not need to redo semantic analysis to determine whether a token
719sequence is a variable, type, template, etc.</p>
720
721<p>Annotation Tokens are created by the parser and reinjected into the parser's
722token stream (when backtracking is enabled). Because they can only exist in
723tokens that the preprocessor-proper is done with, it doesn't need to keep around
724flags like "start of line" that the preprocessor uses to do its job.
725Additionally, an annotation token may "cover" a sequence of preprocessor tokens
726(e.g. <tt>a::b::c</tt> is five preprocessor tokens). As such, the valid fields
727of an annotation token are different than the fields for a normal token (but
728they are multiplexed into the normal Token fields):</p>
729
730<ul>
731<li><b>SourceLocation "Location"</b> - The SourceLocation for the annotation
732token indicates the first token replaced by the annotation token. In the example
733above, it would be the location of the "a" identifier.</li>
734
735<li><b>SourceLocation "AnnotationEndLoc"</b> - This holds the location of the
736last token replaced with the annotation token. In the example above, it would
737be the location of the "c" identifier.</li>
738
John McCall027ac442010-09-03 05:07:55 +0000739<li><b>void* "AnnotationValue"</b> - This contains an opaque object
740that the parser gets from Sema. The parser merely preserves the
741information for Sema to later interpret based on the annotation token
742kind.</li>
Chris Lattner3932fe02009-01-06 06:02:08 +0000743
744<li><b>TokenKind "Kind"</b> - This indicates the kind of Annotation token this
745is. See below for the different valid kinds.</li>
746</ul>
747
748<p>Annotation tokens currently come in three kinds:</p>
749
750<ol>
751<li><b>tok::annot_typename</b>: This annotation token represents a
John McCall027ac442010-09-03 05:07:55 +0000752resolved typename token that is potentially qualified. The
753AnnotationValue field contains the <tt>QualType</tt> returned by
754Sema::getTypeName(), possibly with source location information
755attached.</li>
Chris Lattner3932fe02009-01-06 06:02:08 +0000756
John McCall027ac442010-09-03 05:07:55 +0000757<li><b>tok::annot_cxxscope</b>: This annotation token represents a C++
758scope specifier, such as "A::B::". This corresponds to the grammar
759productions "::" and ":: [opt] nested-name-specifier". The
760AnnotationValue pointer is a <tt>NestedNameSpecifier*</tt> returned by
761the Sema::ActOnCXXGlobalScopeSpecifier and
762Sema::ActOnCXXNestedNameSpecifier callbacks.</li>
Chris Lattner3932fe02009-01-06 06:02:08 +0000763
Douglas Gregor39a8de12009-02-25 19:37:18 +0000764<li><b>tok::annot_template_id</b>: This annotation token represents a
765C++ template-id such as "foo&lt;int, 4&gt;", where "foo" is the name
766of a template. The AnnotationValue pointer is a pointer to a malloc'd
John McCall027ac442010-09-03 05:07:55 +0000767TemplateIdAnnotation object. Depending on the context, a parsed
768template-id that names a type might become a typename annotation token
769(if all we care about is the named type, e.g., because it occurs in a
770type specifier) or might remain a template-id token (if we want to
771retain more source location information or produce a new type, e.g.,
772in a declaration of a class template specialization). template-id
773annotation tokens that refer to a type can be "upgraded" to typename
774annotation tokens by the parser.</li>
Chris Lattner3932fe02009-01-06 06:02:08 +0000775
776</ol>
777
Cedric Venetda76b282009-01-06 16:22:54 +0000778<p>As mentioned above, annotation tokens are not returned by the preprocessor,
Chris Lattner3932fe02009-01-06 06:02:08 +0000779they are formed on demand by the parser. This means that the parser has to be
780aware of cases where an annotation could occur and form it where appropriate.
781This is somewhat similar to how the parser handles Translation Phase 6 of C99:
782String Concatenation (see C99 5.1.1.2). In the case of string concatenation,
783the preprocessor just returns distinct tok::string_literal and
784tok::wide_string_literal tokens and the parser eats a sequence of them wherever
785the grammar indicates that a string literal can occur.</p>
786
787<p>In order to do this, whenever the parser expects a tok::identifier or
788tok::coloncolon, it should call the TryAnnotateTypeOrScopeToken or
789TryAnnotateCXXScopeToken methods to form the annotation token. These methods
790will maximally form the specified annotation tokens and replace the current
791token with them, if applicable. If the current tokens is not valid for an
792annotation token, it will remain an identifier or :: token.</p>
793
794
Chris Lattner86920d32007-07-31 05:42:17 +0000795
796<!-- ======================================================================= -->
797<h3 id="Lexer">The Lexer class</h3>
798<!-- ======================================================================= -->
799
800<p>The Lexer class provides the mechanics of lexing tokens out of a source
801buffer and deciding what they mean. The Lexer is complicated by the fact that
802it operates on raw buffers that have not had spelling eliminated (this is a
803necessity to get decent performance), but this is countered with careful coding
804as well as standard performance techniques (for example, the comment handling
805code is vectorized on X86 and PowerPC hosts).</p>
806
807<p>The lexer has a couple of interesting modal features:</p>
808
809<ul>
810<li>The lexer can operate in 'raw' mode. This mode has several features that
811 make it possible to quickly lex the file (e.g. it stops identifier lookup,
812 doesn't specially handle preprocessor tokens, handles EOF differently, etc).
813 This mode is used for lexing within an "<tt>#if 0</tt>" block, for
814 example.</li>
815<li>The lexer can capture and return comments as tokens. This is required to
816 support the -C preprocessor mode, which passes comments through, and is
817 used by the diagnostic checker to identifier expect-error annotations.</li>
818<li>The lexer can be in ParsingFilename mode, which happens when preprocessing
Chris Lattner84386242007-09-16 19:25:23 +0000819 after reading a #include directive. This mode changes the parsing of '&lt;'
Chris Lattner86920d32007-07-31 05:42:17 +0000820 to return an "angled string" instead of a bunch of tokens for each thing
821 within the filename.</li>
822<li>When parsing a preprocessor directive (after "<tt>#</tt>") the
823 ParsingPreprocessorDirective mode is entered. This changes the parser to
Peter Collingbourne84021552011-02-28 02:37:51 +0000824 return EOD at a newline.</li>
Chris Lattner86920d32007-07-31 05:42:17 +0000825<li>The Lexer uses a LangOptions object to know whether trigraphs are enabled,
826 whether C++ or ObjC keywords are recognized, etc.</li>
827</ul>
828
829<p>In addition to these modes, the lexer keeps track of a couple of other
830 features that are local to a lexed buffer, which change as the buffer is
831 lexed:</p>
832
833<ul>
834<li>The Lexer uses BufferPtr to keep track of the current character being
835 lexed.</li>
836<li>The Lexer uses IsAtStartOfLine to keep track of whether the next lexed token
837 will start with its "start of line" bit set.</li>
838<li>The Lexer keeps track of the current #if directives that are active (which
839 can be nested).</li>
840<li>The Lexer keeps track of an <a href="#MultipleIncludeOpt">
841 MultipleIncludeOpt</a> object, which is used to
842 detect whether the buffer uses the standard "<tt>#ifndef XX</tt> /
843 <tt>#define XX</tt>" idiom to prevent multiple inclusion. If a buffer does,
844 subsequent includes can be ignored if the XX macro is defined.</li>
845</ul>
846
847<!-- ======================================================================= -->
Chris Lattner79281252008-03-09 02:27:26 +0000848<h3 id="TokenLexer">The TokenLexer class</h3>
Chris Lattner86920d32007-07-31 05:42:17 +0000849<!-- ======================================================================= -->
850
Chris Lattner79281252008-03-09 02:27:26 +0000851<p>The TokenLexer class is a token provider that returns tokens from a list
Chris Lattner86920d32007-07-31 05:42:17 +0000852of tokens that came from somewhere else. It typically used for two things: 1)
853returning tokens from a macro definition as it is being expanded 2) returning
854tokens from an arbitrary buffer of tokens. The later use is used by _Pragma and
855will most likely be used to handle unbounded look-ahead for the C++ parser.</p>
856
857<!-- ======================================================================= -->
858<h3 id="MultipleIncludeOpt">The MultipleIncludeOpt class</h3>
859<!-- ======================================================================= -->
860
861<p>The MultipleIncludeOpt class implements a really simple little state machine
862that is used to detect the standard "<tt>#ifndef XX</tt> / <tt>#define XX</tt>"
863idiom that people typically use to prevent multiple inclusion of headers. If a
864buffer uses this idiom and is subsequently #include'd, the preprocessor can
865simply check to see whether the guarding condition is defined or not. If so,
866the preprocessor can completely ignore the include of the header.</p>
867
868
869
870<!-- ======================================================================= -->
871<h2 id="libparse">The Parser Library</h2>
872<!-- ======================================================================= -->
873
874<!-- ======================================================================= -->
875<h2 id="libast">The AST Library</h2>
876<!-- ======================================================================= -->
877
878<!-- ======================================================================= -->
879<h3 id="Type">The Type class and its subclasses</h3>
880<!-- ======================================================================= -->
881
882<p>The Type class (and its subclasses) are an important part of the AST. Types
883are accessed through the ASTContext class, which implicitly creates and uniques
884them as they are needed. Types have a couple of non-obvious features: 1) they
885do not capture type qualifiers like const or volatile (See
886<a href="#QualType">QualType</a>), and 2) they implicitly capture typedef
Chris Lattner8a2bc622007-07-31 06:37:39 +0000887information. Once created, types are immutable (unlike decls).</p>
Chris Lattner86920d32007-07-31 05:42:17 +0000888
889<p>Typedefs in C make semantic analysis a bit more complex than it would
890be without them. The issue is that we want to capture typedef information
891and represent it in the AST perfectly, but the semantics of operations need to
892"see through" typedefs. For example, consider this code:</p>
893
894<code>
895void func() {<br>
Bill Wendling30d17752007-10-06 01:56:01 +0000896&nbsp;&nbsp;typedef int foo;<br>
897&nbsp;&nbsp;foo X, *Y;<br>
898&nbsp;&nbsp;typedef foo* bar;<br>
899&nbsp;&nbsp;bar Z;<br>
900&nbsp;&nbsp;*X; <i>// error</i><br>
901&nbsp;&nbsp;**Y; <i>// error</i><br>
902&nbsp;&nbsp;**Z; <i>// error</i><br>
Chris Lattner86920d32007-07-31 05:42:17 +0000903}<br>
904</code>
905
906<p>The code above is illegal, and thus we expect there to be diagnostics emitted
907on the annotated lines. In this example, we expect to get:</p>
908
909<pre>
Chris Lattner8a2bc622007-07-31 06:37:39 +0000910<b>test.c:6:1: error: indirection requires pointer operand ('foo' invalid)</b>
Chris Lattner86920d32007-07-31 05:42:17 +0000911*X; // error
912<font color="blue">^~</font>
Chris Lattner8a2bc622007-07-31 06:37:39 +0000913<b>test.c:7:1: error: indirection requires pointer operand ('foo' invalid)</b>
Chris Lattner86920d32007-07-31 05:42:17 +0000914**Y; // error
915<font color="blue">^~~</font>
Chris Lattner8a2bc622007-07-31 06:37:39 +0000916<b>test.c:8:1: error: indirection requires pointer operand ('foo' invalid)</b>
917**Z; // error
918<font color="blue">^~~</font>
Chris Lattner86920d32007-07-31 05:42:17 +0000919</pre>
920
921<p>While this example is somewhat silly, it illustrates the point: we want to
922retain typedef information where possible, so that we can emit errors about
923"<tt>std::string</tt>" instead of "<tt>std::basic_string&lt;char, std:...</tt>".
924Doing this requires properly keeping typedef information (for example, the type
925of "X" is "foo", not "int"), and requires properly propagating it through the
Chris Lattner8a2bc622007-07-31 06:37:39 +0000926various operators (for example, the type of *Y is "foo", not "int"). In order
927to retain this information, the type of these expressions is an instance of the
928TypedefType class, which indicates that the type of these expressions is a
929typedef for foo.
930</p>
Chris Lattner86920d32007-07-31 05:42:17 +0000931
Chris Lattner8a2bc622007-07-31 06:37:39 +0000932<p>Representing types like this is great for diagnostics, because the
933user-specified type is always immediately available. There are two problems
934with this: first, various semantic checks need to make judgements about the
Chris Lattner33fc68a2007-07-31 18:54:50 +0000935<em>actual structure</em> of a type, ignoring typdefs. Second, we need an
936efficient way to query whether two types are structurally identical to each
937other, ignoring typedefs. The solution to both of these problems is the idea of
Chris Lattner8a2bc622007-07-31 06:37:39 +0000938canonical types.</p>
Chris Lattner86920d32007-07-31 05:42:17 +0000939
Chris Lattner62fd2782008-11-22 21:41:31 +0000940<!-- =============== -->
Chris Lattner8a2bc622007-07-31 06:37:39 +0000941<h4>Canonical Types</h4>
Chris Lattner62fd2782008-11-22 21:41:31 +0000942<!-- =============== -->
Chris Lattner86920d32007-07-31 05:42:17 +0000943
Chris Lattner8a2bc622007-07-31 06:37:39 +0000944<p>Every instance of the Type class contains a canonical type pointer. For
945simple types with no typedefs involved (e.g. "<tt>int</tt>", "<tt>int*</tt>",
946"<tt>int**</tt>"), the type just points to itself. For types that have a
947typedef somewhere in their structure (e.g. "<tt>foo</tt>", "<tt>foo*</tt>",
948"<tt>foo**</tt>", "<tt>bar</tt>"), the canonical type pointer points to their
949structurally equivalent type without any typedefs (e.g. "<tt>int</tt>",
950"<tt>int*</tt>", "<tt>int**</tt>", and "<tt>int*</tt>" respectively).</p>
Chris Lattner86920d32007-07-31 05:42:17 +0000951
Chris Lattner8a2bc622007-07-31 06:37:39 +0000952<p>This design provides a constant time operation (dereferencing the canonical
953type pointer) that gives us access to the structure of types. For example,
954we can trivially tell that "bar" and "foo*" are the same type by dereferencing
955their canonical type pointers and doing a pointer comparison (they both point
956to the single "<tt>int*</tt>" type).</p>
957
958<p>Canonical types and typedef types bring up some complexities that must be
959carefully managed. Specifically, the "isa/cast/dyncast" operators generally
960shouldn't be used in code that is inspecting the AST. For example, when type
961checking the indirection operator (unary '*' on a pointer), the type checker
962must verify that the operand has a pointer type. It would not be correct to
963check that with "<tt>isa&lt;PointerType&gt;(SubExpr-&gt;getType())</tt>",
964because this predicate would fail if the subexpression had a typedef type.</p>
965
966<p>The solution to this problem are a set of helper methods on Type, used to
967check their properties. In this case, it would be correct to use
968"<tt>SubExpr-&gt;getType()-&gt;isPointerType()</tt>" to do the check. This
969predicate will return true if the <em>canonical type is a pointer</em>, which is
970true any time the type is structurally a pointer type. The only hard part here
971is remembering not to use the <tt>isa/cast/dyncast</tt> operations.</p>
972
973<p>The second problem we face is how to get access to the pointer type once we
974know it exists. To continue the example, the result type of the indirection
975operator is the pointee type of the subexpression. In order to determine the
976type, we need to get the instance of PointerType that best captures the typedef
977information in the program. If the type of the expression is literally a
978PointerType, we can return that, otherwise we have to dig through the
979typedefs to find the pointer type. For example, if the subexpression had type
980"<tt>foo*</tt>", we could return that type as the result. If the subexpression
981had type "<tt>bar</tt>", we want to return "<tt>foo*</tt>" (note that we do
982<em>not</em> want "<tt>int*</tt>"). In order to provide all of this, Type has
Chris Lattner11406c12007-07-31 16:50:51 +0000983a getAsPointerType() method that checks whether the type is structurally a
Chris Lattner8a2bc622007-07-31 06:37:39 +0000984PointerType and, if so, returns the best one. If not, it returns a null
985pointer.</p>
986
987<p>This structure is somewhat mystical, but after meditating on it, it will
988make sense to you :).</p>
Chris Lattner86920d32007-07-31 05:42:17 +0000989
990<!-- ======================================================================= -->
991<h3 id="QualType">The QualType class</h3>
992<!-- ======================================================================= -->
993
John McCall027ac442010-09-03 05:07:55 +0000994<p>The QualType class is designed as a trivial value class that is
995small, passed by-value and is efficient to query. The idea of
996QualType is that it stores the type qualifiers (const, volatile,
997restrict, plus some extended qualifiers required by language
998extensions) separately from the types themselves. QualType is
999conceptually a pair of "Type*" and the bits for these type qualifiers.</p>
Chris Lattner86920d32007-07-31 05:42:17 +00001000
1001<p>By storing the type qualifiers as bits in the conceptual pair, it is
1002extremely efficient to get the set of qualifiers on a QualType (just return the
1003field of the pair), add a type qualifier (which is a trivial constant-time
1004operation that sets a bit), and remove one or more type qualifiers (just return
1005a QualType with the bitfield set to empty).</p>
1006
1007<p>Further, because the bits are stored outside of the type itself, we do not
1008need to create duplicates of types with different sets of qualifiers (i.e. there
1009is only a single heap allocated "int" type: "const int" and "volatile const int"
1010both point to the same heap allocated "int" type). This reduces the heap size
1011used to represent bits and also means we do not have to consider qualifiers when
1012uniquing types (<a href="#Type">Type</a> does not even contain qualifiers).</p>
1013
John McCall027ac442010-09-03 05:07:55 +00001014<p>In practice, the two most common type qualifiers (const and
1015restrict) are stored in the low bits of the pointer to the Type
1016object, together with a flag indicating whether extended qualifiers
1017are present (which must be heap-allocated). This means that QualType
1018is exactly the same size as a pointer.</p>
Ted Kremenek8bc05712007-10-10 23:01:43 +00001019
1020<!-- ======================================================================= -->
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001021<h3 id="DeclarationName">Declaration names</h3>
1022<!-- ======================================================================= -->
1023
1024<p>The <tt>DeclarationName</tt> class represents the name of a
1025 declaration in Clang. Declarations in the C family of languages can
Chris Lattner3fcbb892008-11-23 08:32:53 +00001026 take several different forms. Most declarations are named by
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001027 simple identifiers, e.g., "<code>f</code>" and "<code>x</code>" in
1028 the function declaration <code>f(int x)</code>. In C++, declaration
1029 names can also name class constructors ("<code>Class</code>"
1030 in <code>struct Class { Class(); }</code>), class destructors
1031 ("<code>~Class</code>"), overloaded operator names ("operator+"),
1032 and conversion functions ("<code>operator void const *</code>"). In
1033 Objective-C, declaration names can refer to the names of Objective-C
1034 methods, which involve the method name and the parameters,
Chris Lattner3fcbb892008-11-23 08:32:53 +00001035 collectively called a <i>selector</i>, e.g.,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001036 "<code>setWidth:height:</code>". Since all of these kinds of
Chris Lattner3fcbb892008-11-23 08:32:53 +00001037 entities - variables, functions, Objective-C methods, C++
1038 constructors, destructors, and operators - are represented as
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001039 subclasses of Clang's common <code>NamedDecl</code>
1040 class, <code>DeclarationName</code> is designed to efficiently
1041 represent any kind of name.</p>
1042
1043<p>Given
1044 a <code>DeclarationName</code> <code>N</code>, <code>N.getNameKind()</code>
Douglas Gregor2def4832008-11-17 20:34:05 +00001045 will produce a value that describes what kind of name <code>N</code>
Douglas Gregore94ca9e42008-11-18 14:39:36 +00001046 stores. There are 8 options (all of the names are inside
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001047 the <code>DeclarationName</code> class)</p>
1048<dl>
1049 <dt>Identifier</dt>
1050 <dd>The name is a simple
1051 identifier. Use <code>N.getAsIdentifierInfo()</code> to retrieve the
1052 corresponding <code>IdentifierInfo*</code> pointing to the actual
1053 identifier. Note that C++ overloaded operators (e.g.,
1054 "<code>operator+</code>") are represented as special kinds of
1055 identifiers. Use <code>IdentifierInfo</code>'s <code>getOverloadedOperatorID</code>
1056 function to determine whether an identifier is an overloaded
1057 operator name.</dd>
1058
1059 <dt>ObjCZeroArgSelector, ObjCOneArgSelector,
1060 ObjCMultiArgSelector</dt>
1061 <dd>The name is an Objective-C selector, which can be retrieved as a
1062 <code>Selector</code> instance
1063 via <code>N.getObjCSelector()</code>. The three possible name
1064 kinds for Objective-C reflect an optimization within
1065 the <code>DeclarationName</code> class: both zero- and
1066 one-argument selectors are stored as a
1067 masked <code>IdentifierInfo</code> pointer, and therefore require
1068 very little space, since zero- and one-argument selectors are far
1069 more common than multi-argument selectors (which use a different
1070 structure).</dd>
1071
1072 <dt>CXXConstructorName</dt>
1073 <dd>The name is a C++ constructor
1074 name. Use <code>N.getCXXNameType()</code> to retrieve
1075 the <a href="#QualType">type</a> that this constructor is meant to
1076 construct. The type is always the canonical type, since all
1077 constructors for a given type have the same name.</dd>
1078
1079 <dt>CXXDestructorName</dt>
1080 <dd>The name is a C++ destructor
1081 name. Use <code>N.getCXXNameType()</code> to retrieve
1082 the <a href="#QualType">type</a> whose destructor is being
1083 named. This type is always a canonical type.</dd>
1084
1085 <dt>CXXConversionFunctionName</dt>
1086 <dd>The name is a C++ conversion function. Conversion functions are
1087 named according to the type they convert to, e.g., "<code>operator void
1088 const *</code>". Use <code>N.getCXXNameType()</code> to retrieve
1089 the type that this conversion function converts to. This type is
1090 always a canonical type.</dd>
Douglas Gregore94ca9e42008-11-18 14:39:36 +00001091
1092 <dt>CXXOperatorName</dt>
1093 <dd>The name is a C++ overloaded operator name. Overloaded operators
1094 are named according to their spelling, e.g.,
1095 "<code>operator+</code>" or "<code>operator new
1096 []</code>". Use <code>N.getCXXOverloadedOperator()</code> to
1097 retrieve the overloaded operator (a value of
1098 type <code>OverloadedOperatorKind</code>).</dd>
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001099</dl>
1100
1101<p><code>DeclarationName</code>s are cheap to create, copy, and
1102 compare. They require only a single pointer's worth of storage in
Douglas Gregore94ca9e42008-11-18 14:39:36 +00001103 the common cases (identifiers, zero-
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001104 and one-argument Objective-C selectors) and use dense, uniqued
1105 storage for the other kinds of
1106 names. Two <code>DeclarationName</code>s can be compared for
1107 equality (<code>==</code>, <code>!=</code>) using a simple bitwise
1108 comparison, can be ordered
1109 with <code>&lt;</code>, <code>&gt;</code>, <code>&lt;=</code>,
1110 and <code>&gt;=</code> (which provide a lexicographical ordering for
1111 normal identifiers but an unspecified ordering for other kinds of
1112 names), and can be placed into LLVM <code>DenseMap</code>s
1113 and <code>DenseSet</code>s.</p>
1114
1115<p><code>DeclarationName</code> instances can be created in different
1116 ways depending on what kind of name the instance will store. Normal
Douglas Gregore94ca9e42008-11-18 14:39:36 +00001117 identifiers (<code>IdentifierInfo</code> pointers) and Objective-C selectors
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001118 (<code>Selector</code>) can be implicitly converted
1119 to <code>DeclarationName</code>s. Names for C++ constructors,
Douglas Gregore94ca9e42008-11-18 14:39:36 +00001120 destructors, conversion functions, and overloaded operators can be retrieved from
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001121 the <code>DeclarationNameTable</code>, an instance of which is
1122 available as <code>ASTContext::DeclarationNames</code>. The member
1123 functions <code>getCXXConstructorName</code>, <code>getCXXDestructorName</code>,
Douglas Gregore94ca9e42008-11-18 14:39:36 +00001124 <code>getCXXConversionFunctionName</code>, and <code>getCXXOperatorName</code>, respectively,
1125 return <code>DeclarationName</code> instances for the four kinds of
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001126 C++ special function names.</p>
1127
1128<!-- ======================================================================= -->
Douglas Gregor074149e2009-01-05 19:45:36 +00001129<h3 id="DeclContext">Declaration contexts</h3>
1130<!-- ======================================================================= -->
1131<p>Every declaration in a program exists within some <i>declaration
1132 context</i>, such as a translation unit, namespace, class, or
1133 function. Declaration contexts in Clang are represented by
1134 the <code>DeclContext</code> class, from which the various
1135 declaration-context AST nodes
1136 (<code>TranslationUnitDecl</code>, <code>NamespaceDecl</code>, <code>RecordDecl</code>, <code>FunctionDecl</code>,
1137 etc.) will derive. The <code>DeclContext</code> class provides
1138 several facilities common to each declaration context:</p>
1139<dl>
1140 <dt>Source-centric vs. Semantics-centric View of Declarations</dt>
1141 <dd><code>DeclContext</code> provides two views of the declarations
1142 stored within a declaration context. The source-centric view
1143 accurately represents the program source code as written, including
1144 multiple declarations of entities where present (see the
1145 section <a href="#Redeclarations">Redeclarations and
1146 Overloads</a>), while the semantics-centric view represents the
1147 program semantics. The two views are kept synchronized by semantic
1148 analysis while the ASTs are being constructed.</dd>
1149
1150 <dt>Storage of declarations within that context</dt>
1151 <dd>Every declaration context can contain some number of
1152 declarations. For example, a C++ class (represented
1153 by <code>RecordDecl</code>) contains various member functions,
1154 fields, nested types, and so on. All of these declarations will be
1155 stored within the <code>DeclContext</code>, and one can iterate
1156 over the declarations via
1157 [<code>DeclContext::decls_begin()</code>,
1158 <code>DeclContext::decls_end()</code>). This mechanism provides
1159 the source-centric view of declarations in the context.</dd>
1160
1161 <dt>Lookup of declarations within that context</dt>
1162 <dd>The <code>DeclContext</code> structure provides efficient name
1163 lookup for names within that declaration context. For example,
1164 if <code>N</code> is a namespace we can look for the
1165 name <code>N::f</code>
1166 using <code>DeclContext::lookup</code>. The lookup itself is
1167 based on a lazily-constructed array (for declaration contexts
1168 with a small number of declarations) or hash table (for
1169 declaration contexts with more declarations). The lookup
1170 operation provides the semantics-centric view of the declarations
1171 in the context.</dd>
1172
1173 <dt>Ownership of declarations</dt>
1174 <dd>The <code>DeclContext</code> owns all of the declarations that
1175 were declared within its declaration context, and is responsible
1176 for the management of their memory as well as their
1177 (de-)serialization.</dd>
1178</dl>
1179
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001180<p>All declarations are stored within a declaration context, and one
1181 can query
1182 information about the context in which each declaration lives. One
Douglas Gregor074149e2009-01-05 19:45:36 +00001183 can retrieve the <code>DeclContext</code> that contains a
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001184 particular <code>Decl</code>
1185 using <code>Decl::getDeclContext</code>. However, see the
Douglas Gregor074149e2009-01-05 19:45:36 +00001186 section <a href="#LexicalAndSemanticContexts">Lexical and Semantic
1187 Contexts</a> for more information about how to interpret this
1188 context information.</p>
1189
1190<h4 id="Redeclarations">Redeclarations and Overloads</h4>
1191<p>Within a translation unit, it is common for an entity to be
1192declared several times. For example, we might declare a function "f"
1193 and then later re-declare it as part of an inlined definition:</p>
1194
1195<pre>
1196void f(int x, int y, int z = 1);
1197
1198inline void f(int x, int y, int z) { /* ... */ }
1199</pre>
1200
1201<p>The representation of "f" differs in the source-centric and
1202 semantics-centric views of a declaration context. In the
1203 source-centric view, all redeclarations will be present, in the
1204 order they occurred in the source code, making
1205 this view suitable for clients that wish to see the structure of
1206 the source code. In the semantics-centric view, only the most recent "f"
1207 will be found by the lookup, since it effectively replaces the first
1208 declaration of "f".</p>
1209
1210<p>In the semantics-centric view, overloading of functions is
1211 represented explicitly. For example, given two declarations of a
1212 function "g" that are overloaded, e.g.,</p>
1213<pre>
1214void g();
1215void g(int);
1216</pre>
1217<p>the <code>DeclContext::lookup</code> operation will return
1218 an <code>OverloadedFunctionDecl</code> that contains both
1219 declarations of "g". Clients that perform semantic analysis on a
1220 program that is not concerned with the actual source code will
1221 primarily use this semantics-centric view.</p>
1222
1223<h4 id="LexicalAndSemanticContexts">Lexical and Semantic Contexts</h4>
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001224<p>Each declaration has two potentially different
Douglas Gregor074149e2009-01-05 19:45:36 +00001225 declaration contexts: a <i>lexical</i> context, which corresponds to
1226 the source-centric view of the declaration context, and
1227 a <i>semantic</i> context, which corresponds to the
1228 semantics-centric view. The lexical context is accessible
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001229 via <code>Decl::getLexicalDeclContext</code> while the
Douglas Gregor074149e2009-01-05 19:45:36 +00001230 semantic context is accessible
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001231 via <code>Decl::getDeclContext</code>, both of which return
Douglas Gregor074149e2009-01-05 19:45:36 +00001232 <code>DeclContext</code> pointers. For most declarations, the two
1233 contexts are identical. For example:</p>
1234
1235<pre>
1236class X {
1237public:
1238 void f(int x);
1239};
1240</pre>
1241
1242<p>Here, the semantic and lexical contexts of <code>X::f</code> are
1243 the <code>DeclContext</code> associated with the
1244 class <code>X</code> (itself stored as a <code>RecordDecl</code> AST
1245 node). However, we can now define <code>X::f</code> out-of-line:</p>
1246
1247<pre>
1248void X::f(int x = 17) { /* ... */ }
1249</pre>
1250
1251<p>This definition of has different lexical and semantic
1252 contexts. The lexical context corresponds to the declaration
1253 context in which the actual declaration occurred in the source
1254 code, e.g., the translation unit containing <code>X</code>. Thus,
1255 this declaration of <code>X::f</code> can be found by traversing
1256 the declarations provided by
1257 [<code>decls_begin()</code>, <code>decls_end()</code>) in the
1258 translation unit.</p>
1259
1260<p>The semantic context of <code>X::f</code> corresponds to the
1261 class <code>X</code>, since this member function is (semantically) a
1262 member of <code>X</code>. Lookup of the name <code>f</code> into
1263 the <code>DeclContext</code> associated with <code>X</code> will
1264 then return the definition of <code>X::f</code> (including
1265 information about the default argument).</p>
1266
1267<h4 id="TransparentContexts">Transparent Declaration Contexts</h4>
1268<p>In C and C++, there are several contexts in which names that are
1269 logically declared inside another declaration will actually "leak"
1270 out into the enclosing scope from the perspective of name
1271 lookup. The most obvious instance of this behavior is in
1272 enumeration types, e.g.,</p>
1273<pre>
1274enum Color {
1275 Red,
1276 Green,
1277 Blue
1278};
1279</pre>
1280
1281<p>Here, <code>Color</code> is an enumeration, which is a declaration
1282 context that contains the
1283 enumerators <code>Red</code>, <code>Green</code>,
1284 and <code>Blue</code>. Thus, traversing the list of declarations
1285 contained in the enumeration <code>Color</code> will
1286 yield <code>Red</code>, <code>Green</code>,
1287 and <code>Blue</code>. However, outside of the scope
1288 of <code>Color</code> one can name the enumerator <code>Red</code>
1289 without qualifying the name, e.g.,</p>
1290
1291<pre>
1292Color c = Red;
1293</pre>
1294
1295<p>There are other entities in C++ that provide similar behavior. For
1296 example, linkage specifications that use curly braces:</p>
1297
1298<pre>
1299extern "C" {
1300 void f(int);
1301 void g(int);
1302}
1303// f and g are visible here
1304</pre>
1305
1306<p>For source-level accuracy, we treat the linkage specification and
1307 enumeration type as a
1308 declaration context in which its enclosed declarations ("Red",
1309 "Green", and "Blue"; "f" and "g")
1310 are declared. However, these declarations are visible outside of the
1311 scope of the declaration context.</p>
1312
1313<p>These language features (and several others, described below) have
1314 roughly the same set of
1315 requirements: declarations are declared within a particular lexical
1316 context, but the declarations are also found via name lookup in
1317 scopes enclosing the declaration itself. This feature is implemented
1318 via <i>transparent</i> declaration contexts
1319 (see <code>DeclContext::isTransparentContext()</code>), whose
1320 declarations are visible in the nearest enclosing non-transparent
1321 declaration context. This means that the lexical context of the
1322 declaration (e.g., an enumerator) will be the
1323 transparent <code>DeclContext</code> itself, as will the semantic
1324 context, but the declaration will be visible in every outer context
1325 up to and including the first non-transparent declaration context (since
1326 transparent declaration contexts can be nested).</p>
1327
1328<p>The transparent <code>DeclContexts</code> are:</p>
1329<ul>
1330 <li>Enumerations (but not C++0x "scoped enumerations"):
1331 <pre>
1332enum Color {
1333 Red,
1334 Green,
1335 Blue
1336};
1337// Red, Green, and Blue are in scope
1338 </pre></li>
1339 <li>C++ linkage specifications:
1340 <pre>
1341extern "C" {
1342 void f(int);
1343 void g(int);
1344}
1345// f and g are in scope
1346 </pre></li>
1347 <li>Anonymous unions and structs:
1348 <pre>
1349struct LookupTable {
1350 bool IsVector;
1351 union {
1352 std::vector&lt;Item&gt; *Vector;
1353 std::set&lt;Item&gt; *Set;
1354 };
1355};
1356
1357LookupTable LT;
1358LT.Vector = 0; // Okay: finds Vector inside the unnamed union
1359 </pre>
1360 </li>
1361 <li>C++0x inline namespaces:
1362<pre>
1363namespace mylib {
1364 inline namespace debug {
1365 class X;
1366 }
1367}
1368mylib::X *xp; // okay: mylib::X refers to mylib::debug::X
1369</pre>
1370</li>
1371</ul>
1372
1373
1374<h4 id="MultiDeclContext">Multiply-Defined Declaration Contexts</h4>
1375<p>C++ namespaces have the interesting--and, so far, unique--property that
1376the namespace can be defined multiple times, and the declarations
1377provided by each namespace definition are effectively merged (from
1378the semantic point of view). For example, the following two code
1379snippets are semantically indistinguishable:</p>
1380<pre>
1381// Snippet #1:
1382namespace N {
1383 void f();
1384}
1385namespace N {
1386 void f(int);
1387}
1388
1389// Snippet #2:
1390namespace N {
1391 void f();
1392 void f(int);
1393}
1394</pre>
1395
1396<p>In Clang's representation, the source-centric view of declaration
1397 contexts will actually have two separate <code>NamespaceDecl</code>
1398 nodes in Snippet #1, each of which is a declaration context that
1399 contains a single declaration of "f". However, the semantics-centric
1400 view provided by name lookup into the namespace <code>N</code> for
1401 "f" will return an <code>OverloadedFunctionDecl</code> that contains
1402 both declarations of "f".</p>
1403
1404<p><code>DeclContext</code> manages multiply-defined declaration
1405 contexts internally. The
1406 function <code>DeclContext::getPrimaryContext</code> retrieves the
1407 "primary" context for a given <code>DeclContext</code> instance,
1408 which is the <code>DeclContext</code> responsible for maintaining
1409 the lookup table used for the semantics-centric view. Given the
1410 primary context, one can follow the chain
1411 of <code>DeclContext</code> nodes that define additional
1412 declarations via <code>DeclContext::getNextContext</code>. Note that
1413 these functions are used internally within the lookup and insertion
1414 methods of the <code>DeclContext</code>, so the vast majority of
1415 clients can ignore them.</p>
1416
1417<!-- ======================================================================= -->
Ted Kremenek8bc05712007-10-10 23:01:43 +00001418<h3 id="CFG">The <tt>CFG</tt> class</h3>
1419<!-- ======================================================================= -->
1420
1421<p>The <tt>CFG</tt> class is designed to represent a source-level
1422control-flow graph for a single statement (<tt>Stmt*</tt>). Typically
1423instances of <tt>CFG</tt> are constructed for function bodies (usually
1424an instance of <tt>CompoundStmt</tt>), but can also be instantiated to
1425represent the control-flow of any class that subclasses <tt>Stmt</tt>,
1426which includes simple expressions. Control-flow graphs are especially
1427useful for performing
1428<a href="http://en.wikipedia.org/wiki/Data_flow_analysis#Sensitivities">flow-
1429or path-sensitive</a> program analyses on a given function.</p>
1430
Chris Lattner62fd2782008-11-22 21:41:31 +00001431<!-- ============ -->
Ted Kremenek8bc05712007-10-10 23:01:43 +00001432<h4>Basic Blocks</h4>
Chris Lattner62fd2782008-11-22 21:41:31 +00001433<!-- ============ -->
Ted Kremenek8bc05712007-10-10 23:01:43 +00001434
1435<p>Concretely, an instance of <tt>CFG</tt> is a collection of basic
1436blocks. Each basic block is an instance of <tt>CFGBlock</tt>, which
1437simply contains an ordered sequence of <tt>Stmt*</tt> (each referring
1438to statements in the AST). The ordering of statements within a block
1439indicates unconditional flow of control from one statement to the
1440next. <a href="#ConditionalControlFlow">Conditional control-flow</a>
1441is represented using edges between basic blocks. The statements
1442within a given <tt>CFGBlock</tt> can be traversed using
1443the <tt>CFGBlock::*iterator</tt> interface.</p>
1444
1445<p>
Ted Kremenek18e17e72007-10-18 22:50:52 +00001446A <tt>CFG</tt> object owns the instances of <tt>CFGBlock</tt> within
Ted Kremenek8bc05712007-10-10 23:01:43 +00001447the control-flow graph it represents. Each <tt>CFGBlock</tt> within a
1448CFG is also uniquely numbered (accessible
1449via <tt>CFGBlock::getBlockID()</tt>). Currently the number is
1450based on the ordering the blocks were created, but no assumptions
1451should be made on how <tt>CFGBlock</tt>s are numbered other than their
1452numbers are unique and that they are numbered from 0..N-1 (where N is
1453the number of basic blocks in the CFG).</p>
1454
Chris Lattner62fd2782008-11-22 21:41:31 +00001455<!-- ===================== -->
Ted Kremenek8bc05712007-10-10 23:01:43 +00001456<h4>Entry and Exit Blocks</h4>
Chris Lattner62fd2782008-11-22 21:41:31 +00001457<!-- ===================== -->
Ted Kremenek8bc05712007-10-10 23:01:43 +00001458
1459Each instance of <tt>CFG</tt> contains two special blocks:
1460an <i>entry</i> block (accessible via <tt>CFG::getEntry()</tt>), which
1461has no incoming edges, and an <i>exit</i> block (accessible
1462via <tt>CFG::getExit()</tt>), which has no outgoing edges. Neither
1463block contains any statements, and they serve the role of providing a
1464clear entrance and exit for a body of code such as a function body.
1465The presence of these empty blocks greatly simplifies the
1466implementation of many analyses built on top of CFGs.
1467
Chris Lattner62fd2782008-11-22 21:41:31 +00001468<!-- ===================================================== -->
Ted Kremenek8bc05712007-10-10 23:01:43 +00001469<h4 id ="ConditionalControlFlow">Conditional Control-Flow</h4>
Chris Lattner62fd2782008-11-22 21:41:31 +00001470<!-- ===================================================== -->
Ted Kremenek8bc05712007-10-10 23:01:43 +00001471
1472<p>Conditional control-flow (such as those induced by if-statements
1473and loops) is represented as edges between <tt>CFGBlock</tt>s.
1474Because different C language constructs can induce control-flow,
1475each <tt>CFGBlock</tt> also records an extra <tt>Stmt*</tt> that
1476represents the <i>terminator</i> of the block. A terminator is simply
1477the statement that caused the control-flow, and is used to identify
1478the nature of the conditional control-flow between blocks. For
1479example, in the case of an if-statement, the terminator refers to
1480the <tt>IfStmt</tt> object in the AST that represented the given
1481branch.</p>
1482
1483<p>To illustrate, consider the following code example:</p>
1484
1485<code>
1486int foo(int x) {<br>
1487&nbsp;&nbsp;x = x + 1;<br>
1488<br>
1489&nbsp;&nbsp;if (x > 2) x++;<br>
1490&nbsp;&nbsp;else {<br>
1491&nbsp;&nbsp;&nbsp;&nbsp;x += 2;<br>
1492&nbsp;&nbsp;&nbsp;&nbsp;x *= 2;<br>
1493&nbsp;&nbsp;}<br>
1494<br>
1495&nbsp;&nbsp;return x;<br>
1496}
1497</code>
1498
1499<p>After invoking the parser+semantic analyzer on this code fragment,
1500the AST of the body of <tt>foo</tt> is referenced by a
1501single <tt>Stmt*</tt>. We can then construct an instance
1502of <tt>CFG</tt> representing the control-flow graph of this function
1503body by single call to a static class method:</p>
1504
1505<code>
1506&nbsp;&nbsp;Stmt* FooBody = ...<br>
1507&nbsp;&nbsp;CFG* FooCFG = <b>CFG::buildCFG</b>(FooBody);
1508</code>
1509
1510<p>It is the responsibility of the caller of <tt>CFG::buildCFG</tt>
1511to <tt>delete</tt> the returned <tt>CFG*</tt> when the CFG is no
1512longer needed.</p>
1513
1514<p>Along with providing an interface to iterate over
1515its <tt>CFGBlock</tt>s, the <tt>CFG</tt> class also provides methods
1516that are useful for debugging and visualizing CFGs. For example, the
1517method
1518<tt>CFG::dump()</tt> dumps a pretty-printed version of the CFG to
1519standard error. This is especially useful when one is using a
1520debugger such as gdb. For example, here is the output
1521of <tt>FooCFG->dump()</tt>:</p>
1522
1523<code>
1524&nbsp;[ B5 (ENTRY) ]<br>
1525&nbsp;&nbsp;&nbsp;&nbsp;Predecessors (0):<br>
1526&nbsp;&nbsp;&nbsp;&nbsp;Successors (1): B4<br>
1527<br>
1528&nbsp;[ B4 ]<br>
1529&nbsp;&nbsp;&nbsp;&nbsp;1: x = x + 1<br>
1530&nbsp;&nbsp;&nbsp;&nbsp;2: (x > 2)<br>
1531&nbsp;&nbsp;&nbsp;&nbsp;<b>T: if [B4.2]</b><br>
1532&nbsp;&nbsp;&nbsp;&nbsp;Predecessors (1): B5<br>
1533&nbsp;&nbsp;&nbsp;&nbsp;Successors (2): B3 B2<br>
1534<br>
1535&nbsp;[ B3 ]<br>
1536&nbsp;&nbsp;&nbsp;&nbsp;1: x++<br>
1537&nbsp;&nbsp;&nbsp;&nbsp;Predecessors (1): B4<br>
1538&nbsp;&nbsp;&nbsp;&nbsp;Successors (1): B1<br>
1539<br>
1540&nbsp;[ B2 ]<br>
1541&nbsp;&nbsp;&nbsp;&nbsp;1: x += 2<br>
1542&nbsp;&nbsp;&nbsp;&nbsp;2: x *= 2<br>
1543&nbsp;&nbsp;&nbsp;&nbsp;Predecessors (1): B4<br>
1544&nbsp;&nbsp;&nbsp;&nbsp;Successors (1): B1<br>
1545<br>
1546&nbsp;[ B1 ]<br>
1547&nbsp;&nbsp;&nbsp;&nbsp;1: return x;<br>
1548&nbsp;&nbsp;&nbsp;&nbsp;Predecessors (2): B2 B3<br>
1549&nbsp;&nbsp;&nbsp;&nbsp;Successors (1): B0<br>
1550<br>
1551&nbsp;[ B0 (EXIT) ]<br>
1552&nbsp;&nbsp;&nbsp;&nbsp;Predecessors (1): B1<br>
1553&nbsp;&nbsp;&nbsp;&nbsp;Successors (0):
1554</code>
1555
1556<p>For each block, the pretty-printed output displays for each block
1557the number of <i>predecessor</i> blocks (blocks that have outgoing
1558control-flow to the given block) and <i>successor</i> blocks (blocks
1559that have control-flow that have incoming control-flow from the given
1560block). We can also clearly see the special entry and exit blocks at
1561the beginning and end of the pretty-printed output. For the entry
1562block (block B5), the number of predecessor blocks is 0, while for the
1563exit block (block B0) the number of successor blocks is 0.</p>
1564
1565<p>The most interesting block here is B4, whose outgoing control-flow
1566represents the branching caused by the sole if-statement
1567in <tt>foo</tt>. Of particular interest is the second statement in
1568the block, <b><tt>(x > 2)</tt></b>, and the terminator, printed
1569as <b><tt>if [B4.2]</tt></b>. The second statement represents the
1570evaluation of the condition of the if-statement, which occurs before
1571the actual branching of control-flow. Within the <tt>CFGBlock</tt>
1572for B4, the <tt>Stmt*</tt> for the second statement refers to the
1573actual expression in the AST for <b><tt>(x > 2)</tt></b>. Thus
1574pointers to subclasses of <tt>Expr</tt> can appear in the list of
1575statements in a block, and not just subclasses of <tt>Stmt</tt> that
1576refer to proper C statements.</p>
1577
1578<p>The terminator of block B4 is a pointer to the <tt>IfStmt</tt>
1579object in the AST. The pretty-printer outputs <b><tt>if
1580[B4.2]</tt></b> because the condition expression of the if-statement
1581has an actual place in the basic block, and thus the terminator is
1582essentially
1583<i>referring</i> to the expression that is the second statement of
1584block B4 (i.e., B4.2). In this manner, conditions for control-flow
1585(which also includes conditions for loops and switch statements) are
1586hoisted into the actual basic block.</p>
1587
Chris Lattner62fd2782008-11-22 21:41:31 +00001588<!-- ===================== -->
1589<!-- <h4>Implicit Control-Flow</h4> -->
1590<!-- ===================== -->
Ted Kremenek8bc05712007-10-10 23:01:43 +00001591
1592<!--
1593<p>A key design principle of the <tt>CFG</tt> class was to not require
1594any transformations to the AST in order to represent control-flow.
1595Thus the <tt>CFG</tt> does not perform any "lowering" of the
1596statements in an AST: loops are not transformed into guarded gotos,
1597short-circuit operations are not converted to a set of if-statements,
1598and so on.</p>
1599-->
Ted Kremenek17a295d2008-06-11 06:19:49 +00001600
Chris Lattner7bad1992008-11-16 21:48:07 +00001601
1602<!-- ======================================================================= -->
1603<h3 id="Constants">Constant Folding in the Clang AST</h3>
1604<!-- ======================================================================= -->
1605
1606<p>There are several places where constants and constant folding matter a lot to
1607the Clang front-end. First, in general, we prefer the AST to retain the source
1608code as close to how the user wrote it as possible. This means that if they
1609wrote "5+4", we want to keep the addition and two constants in the AST, we don't
1610want to fold to "9". This means that constant folding in various ways turns
1611into a tree walk that needs to handle the various cases.</p>
1612
1613<p>However, there are places in both C and C++ that require constants to be
1614folded. For example, the C standard defines what an "integer constant
1615expression" (i-c-e) is with very precise and specific requirements. The
1616language then requires i-c-e's in a lot of places (for example, the size of a
1617bitfield, the value for a case statement, etc). For these, we have to be able
1618to constant fold the constants, to do semantic checks (e.g. verify bitfield size
1619is non-negative and that case statements aren't duplicated). We aim for Clang
1620to be very pedantic about this, diagnosing cases when the code does not use an
1621i-c-e where one is required, but accepting the code unless running with
1622<tt>-pedantic-errors</tt>.</p>
1623
1624<p>Things get a little bit more tricky when it comes to compatibility with
1625real-world source code. Specifically, GCC has historically accepted a huge
1626superset of expressions as i-c-e's, and a lot of real world code depends on this
1627unfortuate accident of history (including, e.g., the glibc system headers). GCC
1628accepts anything its "fold" optimizer is capable of reducing to an integer
1629constant, which means that the definition of what it accepts changes as its
1630optimizer does. One example is that GCC accepts things like "case X-X:" even
1631when X is a variable, because it can fold this to 0.</p>
1632
1633<p>Another issue are how constants interact with the extensions we support, such
1634as __builtin_constant_p, __builtin_inf, __extension__ and many others. C99
1635obviously does not specify the semantics of any of these extensions, and the
1636definition of i-c-e does not include them. However, these extensions are often
1637used in real code, and we have to have a way to reason about them.</p>
1638
1639<p>Finally, this is not just a problem for semantic analysis. The code
1640generator and other clients have to be able to fold constants (e.g. to
1641initialize global variables) and has to handle a superset of what C99 allows.
1642Further, these clients can benefit from extended information. For example, we
1643know that "foo()||1" always evaluates to true, but we can't replace the
1644expression with true because it has side effects.</p>
1645
1646<!-- ======================= -->
1647<h4>Implementation Approach</h4>
1648<!-- ======================= -->
1649
1650<p>After trying several different approaches, we've finally converged on a
1651design (Note, at the time of this writing, not all of this has been implemented,
1652consider this a design goal!). Our basic approach is to define a single
1653recursive method evaluation method (<tt>Expr::Evaluate</tt>), which is
1654implemented in <tt>AST/ExprConstant.cpp</tt>. Given an expression with 'scalar'
1655type (integer, fp, complex, or pointer) this method returns the following
1656information:</p>
1657
1658<ul>
1659<li>Whether the expression is an integer constant expression, a general
1660 constant that was folded but has no side effects, a general constant that
1661 was folded but that does have side effects, or an uncomputable/unfoldable
1662 value.
1663</li>
1664<li>If the expression was computable in any way, this method returns the APValue
1665 for the result of the expression.</li>
1666<li>If the expression is not evaluatable at all, this method returns
1667 information on one of the problems with the expression. This includes a
1668 SourceLocation for where the problem is, and a diagnostic ID that explains
1669 the problem. The diagnostic should be have ERROR type.</li>
1670<li>If the expression is not an integer constant expression, this method returns
1671 information on one of the problems with the expression. This includes a
1672 SourceLocation for where the problem is, and a diagnostic ID that explains
1673 the problem. The diagnostic should be have EXTENSION type.</li>
1674</ul>
1675
1676<p>This information gives various clients the flexibility that they want, and we
1677will eventually have some helper methods for various extensions. For example,
1678Sema should have a <tt>Sema::VerifyIntegerConstantExpression</tt> method, which
1679calls Evaluate on the expression. If the expression is not foldable, the error
1680is emitted, and it would return true. If the expression is not an i-c-e, the
1681EXTENSION diagnostic is emitted. Finally it would return false to indicate that
1682the AST is ok.</p>
1683
1684<p>Other clients can use the information in other ways, for example, codegen can
1685just use expressions that are foldable in any way.</p>
1686
1687<!-- ========== -->
1688<h4>Extensions</h4>
1689<!-- ========== -->
1690
Chris Lattner552de0a2008-11-23 08:16:56 +00001691<p>This section describes how some of the various extensions Clang supports
Chris Lattner7bad1992008-11-16 21:48:07 +00001692interacts with constant evaluation:</p>
1693
1694<ul>
1695<li><b><tt>__extension__</tt></b>: The expression form of this extension causes
1696 any evaluatable subexpression to be accepted as an integer constant
1697 expression.</li>
1698<li><b><tt>__builtin_constant_p</tt></b>: This returns true (as a integer
Chris Lattner28daa532008-12-12 06:55:44 +00001699 constant expression) if the operand is any evaluatable constant. As a
1700 special case, if <tt>__builtin_constant_p</tt> is the (potentially
1701 parenthesized) condition of a conditional operator expression ("?:"), only
Chris Lattner42b83dd2008-12-12 18:00:51 +00001702 the true side of the conditional operator is considered, and it is evaluated
1703 with full constant folding.</li>
Chris Lattner7bad1992008-11-16 21:48:07 +00001704<li><b><tt>__builtin_choose_expr</tt></b>: The condition is required to be an
1705 integer constant expression, but we accept any constant as an "extension of
1706 an extension". This only evaluates one operand depending on which way the
1707 condition evaluates.</li>
1708<li><b><tt>__builtin_classify_type</tt></b>: This always returns an integer
1709 constant expression.</li>
1710<li><b><tt>__builtin_inf,nan,..</tt></b>: These are treated just like a
1711 floating-point literal.</li>
1712<li><b><tt>__builtin_abs,copysign,..</tt></b>: These are constant folded as
1713 general constant expressions.</li>
Douglas Gregoreb661ed2010-09-11 18:08:34 +00001714<li><b><tt>__builtin_strlen</tt></b> and <b><tt>strlen</tt></b>: These are constant folded as integer constant expressions if the argument is a string literal.</li>
Chris Lattner7bad1992008-11-16 21:48:07 +00001715</ul>
1716
1717
Jeffrey Yasskin28dadd62011-01-28 23:41:54 +00001718<!-- ======================================================================= -->
1719<h2 id="Howtos">How to change Clang</h2>
1720<!-- ======================================================================= -->
Chris Lattner7bad1992008-11-16 21:48:07 +00001721
Jeffrey Yasskin28dadd62011-01-28 23:41:54 +00001722<!-- ======================================================================= -->
1723<h3 id="AddingAttributes">How to add an attribute</h3>
1724<!-- ======================================================================= -->
1725
1726<p>To add an attribute, you'll have to add it to the list of attributes, add it
1727to the parsing phase, and look for it in the AST scan.
1728<a href="http://llvm.org/viewvc/llvm-project?view=rev&revision=124217">r124217</a>
1729has a good example of adding a warning attribute.</p>
1730
1731<p>(Beware that this hasn't been reviewed/fixed by the people who designed the
1732attributes system yet.)</p>
1733
1734<h4><a
1735href="http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/Attr.td?view=markup">include/clang/Basic/Attr.td</a></h4>
1736
1737<p>Each attribute gets a <tt>def</tt> inheriting from <tt>Attr</tt> or one of
1738its subclasses. <tt>InheritableAttr</tt> means that the attribute also applies
1739to subsequent declarations of the same name.</p>
1740
1741<p><tt>Spellings</tt> lists the strings that can appear in
1742<tt>__attribute__((here))</tt> or <tt>[[here]]</tt>. All such strings
1743will be synonymous. If you want to allow the <tt>[[]]</tt> C++0x
1744syntax, you have to define a list of <tt>Namespaces</tt>, which will
1745let users write <tt>[[namespace:spelling]]</tt>. Using the empty
1746string for a namespace will allow users to write just the spelling
1747with no "<tt>:</tt>".</p>
1748
1749<p><tt>Subjects</tt> restricts what kinds of AST node to which this attribute
1750can appertain (roughly, attach).</p>
1751
1752<p><tt>Args</tt> names the arguments the attribute takes, in order. If
1753<tt>Args</tt> is <tt>[StringArgument&lt;"Arg1">, IntArgument&lt;"Arg2">]</tt>
1754then <tt>__attribute__((myattribute("Hello", 3)))</tt> will be a valid use.</p>
1755
1756<h4>Boilerplate</h4>
1757
1758<p>Add an element to the <tt>AttributeList::Kind</tt> enum in <a
1759href="http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Sema/AttributeList.h?view=markup">include/clang/Sema/AttributeList.h</a>
1760named <tt>AT_lower_with_underscores</tt>. That is, a CamelCased
1761<tt>AttributeName</tt> in <tt>Attr.td</tt> name should become
1762<tt>AT_attribute_name</tt>.</p>
1763
1764<p>Add a case to the <tt>StringSwitch</tt> in <tt>AttributeList::getKind()</tt>
1765in <a
1766href="http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/AttributeList.cpp?view=markup">lib/Sema/AttributeList.cpp</a>
1767for each spelling of your attribute. Less common attributes should come toward
1768the end of that list.</p>
1769
1770<p>Write a new <tt>HandleYourAttr()</tt> function in <a
1771href="http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Sema/SemaDeclAttr.cpp?view=markup">lib/Sema/SemaDeclAttr.cpp</a>,
1772and add a case to the switch in <tt>ProcessNonInheritableDeclAttr()</tt> or
1773<tt>ProcessInheritableDeclAttr()</tt> forwarding to it.</p>
1774
1775<p>If your attribute causes extra warnings to fire, define a <tt>DiagGroup</tt>
1776in <a
1777href="http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/DiagnosticGroups.td?view=markup">include/clang/Basic/DiagnosticGroups.td</a>
1778named after the attribute's <tt>Spelling</tt> with "_"s replaced by "-"s. If
1779you're only defining one diagnostic, you can skip <tt>DiagnosticGroups.td</tt>
1780and use <tt>InGroup&lt;DiagGroup&lt;"your-attribute">></tt> directly in <a
1781href="http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/DiagnosticSemaKinds.td?view=markup">DiagnosticSemaKinds.td</a></p>
1782
1783<h4>The meat of your attribute</h4>
1784
1785<p>Find an appropriate place in Clang to do whatever your attribute needs to do.
1786Check for the attribute's presence using <tt>Decl::getAttr&lt;YourAttr>()</tt>.</p>
1787
1788<p>Update the <a href="LanguageExtensions.html">Clang Language Extensions</a>
1789document to describe your new attribute.</p>
Chris Lattner7bad1992008-11-16 21:48:07 +00001790
Ted Kremenek17a295d2008-06-11 06:19:49 +00001791</div>
1792</body>
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001793</html>