blob: dfd487aa45de89d519a7f544ec0caf5dcc7b882a [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>
28 </ul>
29</li>
30<li><a href="#liblex">The Lexer and Preprocessor Library</a>
31 <ul>
32 <li><a href="#Token">The Token class</a></li>
33 <li><a href="#Lexer">The Lexer class</a></li>
Chris Lattner3932fe02009-01-06 06:02:08 +000034 <li><a href="#AnnotationToken">Annotation Tokens</a></li>
Chris Lattner79281252008-03-09 02:27:26 +000035 <li><a href="#TokenLexer">The TokenLexer class</a></li>
Chris Lattner86920d32007-07-31 05:42:17 +000036 <li><a href="#MultipleIncludeOpt">The MultipleIncludeOpt class</a></li>
37 </ul>
38</li>
39<li><a href="#libparse">The Parser Library</a>
40 <ul>
41 </ul>
42</li>
43<li><a href="#libast">The AST Library</a>
44 <ul>
45 <li><a href="#Type">The Type class and its subclasses</a></li>
46 <li><a href="#QualType">The QualType class</a></li>
Douglas Gregor2e1cd422008-11-17 14:58:09 +000047 <li><a href="#DeclarationName">Declaration names</a></li>
Douglas Gregor074149e2009-01-05 19:45:36 +000048 <li><a href="#DeclContext">Declaration contexts</a>
49 <ul>
50 <li><a href="#Redeclarations">Redeclarations and Overloads</a></li>
51 <li><a href="#LexicalAndSemanticContexts">Lexical and Semantic
52 Contexts</a></li>
53 <li><a href="#TransparentContexts">Transparent Declaration Contexts</a></li>
54 <li><a href="#MultiDeclContext">Multiply-Defined Declaration Contexts</a></li>
55 </ul>
56 </li>
Ted Kremenek8bc05712007-10-10 23:01:43 +000057 <li><a href="#CFG">The CFG class</a></li>
Chris Lattner7bad1992008-11-16 21:48:07 +000058 <li><a href="#Constants">Constant Folding in the Clang AST</a></li>
Chris Lattner86920d32007-07-31 05:42:17 +000059 </ul>
60</li>
61</ul>
62
63
64<!-- ======================================================================= -->
65<h2 id="intro">Introduction</h2>
66<!-- ======================================================================= -->
67
68<p>This document describes some of the more important APIs and internal design
Chris Lattner552de0a2008-11-23 08:16:56 +000069decisions made in the Clang C front-end. The purpose of this document is to
Chris Lattner86920d32007-07-31 05:42:17 +000070both capture some of this high level information and also describe some of the
71design decisions behind it. This is meant for people interested in hacking on
Chris Lattner552de0a2008-11-23 08:16:56 +000072Clang, not for end-users. The description below is categorized by
Chris Lattner86920d32007-07-31 05:42:17 +000073libraries, and does not describe any of the clients of the libraries.</p>
74
75<!-- ======================================================================= -->
76<h2 id="libsystem">LLVM System and Support Libraries</h2>
77<!-- ======================================================================= -->
78
Chris Lattner552de0a2008-11-23 08:16:56 +000079<p>The LLVM libsystem library provides the basic Clang system abstraction layer,
Chris Lattner86920d32007-07-31 05:42:17 +000080which is used for file system access. The LLVM libsupport library provides many
81underlying libraries and <a
82href="http://llvm.org/docs/ProgrammersManual.html">data-structures</a>,
83 including command line option
84processing and various containers.</p>
85
86<!-- ======================================================================= -->
Chris Lattner552de0a2008-11-23 08:16:56 +000087<h2 id="libbasic">The Clang 'Basic' Library</h2>
Chris Lattner86920d32007-07-31 05:42:17 +000088<!-- ======================================================================= -->
89
90<p>This library certainly needs a better name. The 'basic' library contains a
91number of low-level utilities for tracking and manipulating source buffers,
92locations within the source buffers, diagnostics, tokens, target abstraction,
93and information about the subset of the language being compiled for.</p>
94
95<p>Part of this infrastructure is specific to C (such as the TargetInfo class),
96other parts could be reused for other non-C-based languages (SourceLocation,
97SourceManager, Diagnostics, FileManager). When and if there is future demand
98we can figure out if it makes sense to introduce a new library, move the general
99classes somewhere else, or introduce some other solution.</p>
100
101<p>We describe the roles of these classes in order of their dependencies.</p>
102
Chris Lattner62fd2782008-11-22 21:41:31 +0000103
104<!-- ======================================================================= -->
105<h3 id="Diagnostics">The Diagnostics Subsystem</h3>
106<!-- ======================================================================= -->
107
108<p>The Clang Diagnostics subsystem is an important part of how the compiler
109communicates with the human. Diagnostics are the warnings and errors produced
110when the code is incorrect or dubious. In Clang, each diagnostic produced has
111(at the minimum) a unique ID, a <a href="#SourceLocation">SourceLocation</a> to
112"put the caret", an English translation associated with it, and a severity (e.g.
113<tt>WARNING</tt> or <tt>ERROR</tt>). They can also optionally include a number
114of arguments to the dianostic (which fill in "%0"'s in the string) as well as a
115number of source ranges that related to the diagnostic.</p>
116
Chris Lattner552de0a2008-11-23 08:16:56 +0000117<p>In this section, we'll be giving examples produced by the Clang command line
Chris Lattner62fd2782008-11-22 21:41:31 +0000118driver, but diagnostics can be <a href="#DiagnosticClient">rendered in many
119different ways</a> depending on how the DiagnosticClient interface is
120implemented. A representative example of a diagonstic is:</p>
121
122<pre>
123t.c:38:15: error: invalid operands to binary expression ('int *' and '_Complex float')
124 <font color="darkgreen">P = (P-42) + Gamma*4;</font>
125 <font color="blue">~~~~~~ ^ ~~~~~~~</font>
126</pre>
127
128<p>In this example, you can see the English translation, the severity (error),
129you can see the source location (the caret ("^") and file/line/column info),
130the source ranges "~~~~", arguments to the diagnostic ("int*" and "_Complex
131float"). You'll have to believe me that there is a unique ID backing the
132diagnostic :).</p>
133
134<p>Getting all of this to happen has several steps and involves many moving
135pieces, this section describes them and talks about best practices when adding
136a new diagnostic.</p>
137
138<!-- ============================ -->
139<h4>The DiagnosticKinds.def file</h4>
140<!-- ============================ -->
141
142<p>Diagnostics are created by adding an entry to the <tt><a
143href="http://llvm.org/svn/llvm-project/cfe/trunk/include/clang/Basic/DiagnosticKinds.def"
144>DiagnosticKinds.def</a></tt> file. This file encodes the unique ID of the
145diagnostic (as an enum, the first argument), the severity of the diagnostic
146(second argument) and the English translation + format string.</p>
147
148<p>There is little sanity with the naming of the unique ID's right now. Some
149start with err_, warn_, ext_ to encode the severity into the name. Since the
150enum is referenced in the C++ code that produces the diagnostic, it is somewhat
151useful for it to be reasonably short.</p>
152
153<p>The severity of the diagnostic comes from the set {<tt>NOTE</tt>,
154<tt>WARNING</tt>, <tt>EXTENSION</tt>, <tt>EXTWARN</tt>, <tt>ERROR</tt>}. The
155<tt>ERROR</tt> severity is used for diagnostics indicating the program is never
156acceptable under any circumstances. When an error is emitted, the AST for the
157input code may not be fully built. The <tt>EXTENSION</tt> and <tt>EXTWARN</tt>
158severities are used for extensions to the language that Clang accepts. This
159means that Clang fully understands and can represent them in the AST, but we
160produce diagnostics to tell the user their code is non-portable. The difference
161is that the former are ignored by default, and the later warn by default. The
162<tt>WARNING</tt> severity is used for constructs that are valid in the currently
163selected source language but that are dubious in some way. The <tt>NOTE</tt>
Daniel Dunbar426b8632009-02-17 15:49:03 +0000164level is used to staple more information onto previous diagnostics.</p>
Chris Lattner62fd2782008-11-22 21:41:31 +0000165
166<p>These <em>severities</em> are mapped into a smaller set (the
167Diagnostic::Level enum, {<tt>Ignored</tt>, <tt>Note</tt>, <tt>Warning</tt>,
Chris Lattner0aad2972009-02-05 22:49:08 +0000168<tt>Error</tt>, <tt>Fatal</tt> }) of output <em>levels</em> by the diagnostics
Chris Lattnera180fdd2009-02-17 07:07:29 +0000169subsystem based on various configuration options. Clang internally supports a
170fully fine grained mapping mechanism that allows you to map almost any
171diagnostic to the output level that you want. The only diagnostics that cannot
172be mapped are <tt>NOTE</tt>s, which always follow the severity of the previously
173emitted diagnostic and <tt>ERROR</tt>s, which can only be mapped to
174<tt>Fatal</tt> (it is not possible to turn an error into a warning,
175for example).</p>
176
177<p>Diagnostic mappings are used in many ways. For example, if the user
178specifies <tt>-pedantic</tt>, <tt>EXTENSION</tt> maps to <tt>Warning</tt>, if
179they specify <tt>-pedantic-errors</tt>, it turns into <tt>Error</tt>. This is
180used to implement options like <tt>-Wunused_macros</tt>, <tt>-Wundef</tt> etc.
181</p>
182
183<p>
184Mapping to <tt>Fatal</tt> should only be used for diagnostics that are
185considered so severe that error recovery won't be able to recover sensibly from
186them (thus spewing a ton of bogus errors). One example of this class of error
187are failure to #include a file.
188</p>
Chris Lattner62fd2782008-11-22 21:41:31 +0000189
190<!-- ================= -->
191<h4>The Format String</h4>
192<!-- ================= -->
193
194<p>The format string for the diagnostic is very simple, but it has some power.
195It takes the form of a string in English with markers that indicate where and
196how arguments to the diagnostic are inserted and formatted. For example, here
197are some simple format strings:</p>
198
199<pre>
200 "binary integer literals are an extension"
201 "format string contains '\\0' within the string body"
202 "more '<b>%%</b>' conversions than data arguments"
Chris Lattner545b3682008-11-23 20:27:13 +0000203 "invalid operands to binary expression (<b>%0</b> and <b>%1</b>)"
Chris Lattner62fd2782008-11-22 21:41:31 +0000204 "overloaded '<b>%0</b>' must be a <b>%select{unary|binary|unary or binary}2</b> operator"
205 " (has <b>%1</b> parameter<b>%s1</b>)"
206</pre>
207
208<p>These examples show some important points of format strings. You can use any
209 plain ASCII character in the diagnostic string except "%" without a problem,
210 but these are C strings, so you have to use and be aware of all the C escape
211 sequences (as in the second example). If you want to produce a "%" in the
212 output, use the "%%" escape sequence, like the third diagnostic. Finally,
Chris Lattner552de0a2008-11-23 08:16:56 +0000213 Clang uses the "%...[digit]" sequences to specify where and how arguments to
Chris Lattner62fd2782008-11-22 21:41:31 +0000214 the diagnostic are formatted.</p>
215
216<p>Arguments to the diagnostic are numbered according to how they are specified
217 by the C++ code that <a href="#producingdiag">produces them</a>, and are
218 referenced by <tt>%0</tt> .. <tt>%9</tt>. If you have more than 10 arguments
Chris Lattner552de0a2008-11-23 08:16:56 +0000219 to your diagnostic, you are doing something wrong :). Unlike printf, there
Chris Lattner62fd2782008-11-22 21:41:31 +0000220 is no requirement that arguments to the diagnostic end up in the output in
221 the same order as they are specified, you could have a format string with
222 <tt>"%1 %0"</tt> that swaps them, for example. The text in between the
223 percent and digit are formatting instructions. If there are no instructions,
224 the argument is just turned into a string and substituted in.</p>
225
226<p>Here are some "best practices" for writing the English format string:</p>
227
228<ul>
229<li>Keep the string short. It should ideally fit in the 80 column limit of the
230 <tt>DiagnosticKinds.def</tt> file. This avoids the diagnostic wrapping when
231 printed, and forces you to think about the important point you are conveying
232 with the diagnostic.</li>
233<li>Take advantage of location information. The user will be able to see the
234 line and location of the caret, so you don't need to tell them that the
235 problem is with the 4th argument to the function: just point to it.</li>
236<li>Do not capitalize the diagnostic string, and do not end it with a
237 period.</li>
238<li>If you need to quote something in the diagnostic string, use single
239 quotes.</li>
240</ul>
241
242<p>Diagnostics should never take random English strings as arguments: you
243shouldn't use <tt>"you have a problem with %0"</tt> and pass in things like
244<tt>"your argument"</tt> or <tt>"your return value"</tt> as arguments. Doing
245this prevents <a href="translation">translating</a> the Clang diagnostics to
246other languages (because they'll get random English words in their otherwise
247localized diagnostic). The exceptions to this are C/C++ language keywords
248(e.g. auto, const, mutable, etc) and C/C++ operators (<tt>/=</tt>). Note
249that things like "pointer" and "reference" are not keywords. On the other
250hand, you <em>can</em> include anything that comes from the user's source code,
Chris Lattner552de0a2008-11-23 08:16:56 +0000251including variable names, types, labels, etc. The 'select' format can be
252used to achieve this sort of thing in a localizable way, see below.</p>
Chris Lattner62fd2782008-11-22 21:41:31 +0000253
254<!-- ==================================== -->
255<h4>Formatting a Diagnostic Argument</a></h4>
256<!-- ==================================== -->
257
258<p>Arguments to diagnostics are fully typed internally, and come from a couple
259different classes: integers, types, names, and random strings. Depending on
260the class of the argument, it can be optionally formatted in different ways.
261This gives the DiagnosticClient information about what the argument means
262without requiring it to use a specific presentation (consider this MVC for
263Clang :).</p>
264
265<p>Here are the different diagnostic argument formats currently supported by
266Clang:</p>
267
268<table>
269<tr><td colspan="2"><b>"s" format</b></td></tr>
270<tr><td>Example:</td><td><tt>"requires %1 parameter%s1"</tt></td></tr>
Chris Lattner552de0a2008-11-23 08:16:56 +0000271<tr><td>Class:</td><td>Integers</td></tr>
Chris Lattner62fd2782008-11-22 21:41:31 +0000272<tr><td>Description:</td><td>This is a simple formatter for integers that is
273 useful when producing English diagnostics. When the integer is 1, it prints
274 as nothing. When the integer is not 1, it prints as "s". This allows some
Chris Lattner627b7052008-11-23 00:28:33 +0000275 simple grammatical forms to be to be handled correctly, and eliminates the
276 need to use gross things like <tt>"requires %1 parameter(s)"</tt>.</td></tr>
Chris Lattner62fd2782008-11-22 21:41:31 +0000277
278<tr><td colspan="2"><b>"select" format</b></td></tr>
279<tr><td>Example:</td><td><tt>"must be a %select{unary|binary|unary or binary}2
280 operator"</tt></td></tr>
Chris Lattner552de0a2008-11-23 08:16:56 +0000281<tr><td>Class:</td><td>Integers</td></tr>
Chris Lattnercc543342008-11-22 23:50:47 +0000282<tr><td>Description:</td><td>This format specifier is used to merge multiple
283 related diagnostics together into one common one, without requiring the
Chris Lattner552de0a2008-11-23 08:16:56 +0000284 difference to be specified as an English string argument. Instead of
Chris Lattnercc543342008-11-22 23:50:47 +0000285 specifying the string, the diagnostic gets an integer argument and the
286 format string selects the numbered option. In this case, the "%2" value
287 must be an integer in the range [0..2]. If it is 0, it prints 'unary', if
288 it is 1 it prints 'binary' if it is 2, it prints 'unary or binary'. This
289 allows other language translations to substitute reasonable words (or entire
290 phrases) based on the semantics of the diagnostic instead of having to do
291 things textually.</td></tr>
Chris Lattner62fd2782008-11-22 21:41:31 +0000292
293<tr><td colspan="2"><b>"plural" format</b></td></tr>
Sebastian Redl68168562008-11-22 22:16:45 +0000294<tr><td>Example:</td><td><tt>"you have %1 %plural{1:mouse|:mice}1 connected to
295 your computer"</tt></td></tr>
Chris Lattner552de0a2008-11-23 08:16:56 +0000296<tr><td>Class:</td><td>Integers</td></tr>
Sebastian Redl68168562008-11-22 22:16:45 +0000297<tr><td>Description:</td><td><p>This is a formatter for complex plural forms.
298 It is designed to handle even the requirements of languages with very
299 complex plural forms, as many Baltic languages have. The argument consists
300 of a series of expression/form pairs, separated by ':', where the first form
301 whose expression evaluates to true is the result of the modifier.</p>
302 <p>An expression can be empty, in which case it is always true. See the
303 example at the top. Otherwise, it is a series of one or more numeric
304 conditions, separated by ','. If any condition matches, the expression
305 matches. Each numeric condition can take one of three forms.</p>
306 <ul>
307 <li>number: A simple decimal number matches if the argument is the same
Chris Lattner627b7052008-11-23 00:28:33 +0000308 as the number. Example: <tt>"%plural{1:mouse|:mice}4"</tt></li>
Sebastian Redl68168562008-11-22 22:16:45 +0000309 <li>range: A range in square brackets matches if the argument is within
Chris Lattner552de0a2008-11-23 08:16:56 +0000310 the range. Then range is inclusive on both ends. Example:
Chris Lattner627b7052008-11-23 00:28:33 +0000311 <tt>"%plural{0:none|1:one|[2,5]:some|:many}2"</tt></li>
312 <li>modulo: A modulo operator is followed by a number, and
313 equals sign and either a number or a range. The tests are the
314 same as for plain
Sebastian Redl68168562008-11-22 22:16:45 +0000315 numbers and ranges, but the argument is taken modulo the number first.
Chris Lattner627b7052008-11-23 00:28:33 +0000316 Example: <tt>"%plural{%100=0:even hundred|%100=[1,50]:lower half|:everything
317 else}1"</tt></li>
Sebastian Redl68168562008-11-22 22:16:45 +0000318 </ul>
319 <p>The parser is very unforgiving. A syntax error, even whitespace, will
320 abort, as will a failure to match the argument against any
321 expression.</p></td></tr>
Chris Lattner62fd2782008-11-22 21:41:31 +0000322
Chris Lattner077bf5e2008-11-24 03:33:13 +0000323<tr><td colspan="2"><b>"objcclass" format</b></td></tr>
324<tr><td>Example:</td><td><tt>"method %objcclass0 not found"</tt></td></tr>
325<tr><td>Class:</td><td>DeclarationName</td></tr>
326<tr><td>Description:</td><td><p>This is a simple formatter that indicates the
327 DeclarationName corresponds to an Objective-C class method selector. As
328 such, it prints the selector with a leading '+'.</p></td></tr>
329
330<tr><td colspan="2"><b>"objcinstance" format</b></td></tr>
331<tr><td>Example:</td><td><tt>"method %objcinstance0 not found"</tt></td></tr>
332<tr><td>Class:</td><td>DeclarationName</td></tr>
333<tr><td>Description:</td><td><p>This is a simple formatter that indicates the
334 DeclarationName corresponds to an Objective-C instance method selector. As
335 such, it prints the selector with a leading '-'.</p></td></tr>
336
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000337<tr><td colspan="2"><b>"q" format</b></td></tr>
338<tr><td>Example:</td><td><tt>"candidate found by name lookup is %q0"</tt></td></tr>
339<tr><td>Class:</td><td>NamedDecl*</td></tr>
340<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>
341
Chris Lattner62fd2782008-11-22 21:41:31 +0000342</table>
343
Chris Lattnercc543342008-11-22 23:50:47 +0000344<p>It is really easy to add format specifiers to the Clang diagnostics system,
Chris Lattner552de0a2008-11-23 08:16:56 +0000345but they should be discussed before they are added. If you are creating a lot
346of repetitive diagnostics and/or have an idea for a useful formatter, please
347bring it up on the cfe-dev mailing list.</p>
Chris Lattnercc543342008-11-22 23:50:47 +0000348
Chris Lattner62fd2782008-11-22 21:41:31 +0000349<!-- ===================================================== -->
350<h4><a name="#producingdiag">Producing the Diagnostic</a></h4>
351<!-- ===================================================== -->
352
Chris Lattner627b7052008-11-23 00:28:33 +0000353<p>Now that you've created the diagnostic in the DiagnosticKinds.def file, you
Chris Lattner552de0a2008-11-23 08:16:56 +0000354need to write the code that detects the condition in question and emits the
355new diagnostic. Various components of Clang (e.g. the preprocessor, Sema,
Chris Lattner627b7052008-11-23 00:28:33 +0000356etc) provide a helper function named "Diag". It creates a diagnostic and
357accepts the arguments, ranges, and other information that goes along with
358it.</p>
Chris Lattner62fd2782008-11-22 21:41:31 +0000359
Chris Lattner552de0a2008-11-23 08:16:56 +0000360<p>For example, the binary expression error comes from code like this:</p>
Chris Lattner627b7052008-11-23 00:28:33 +0000361
362<pre>
363 if (various things that are bad)
364 Diag(Loc, diag::err_typecheck_invalid_operands)
365 &lt;&lt; lex-&gt;getType() &lt;&lt; rex-&gt;getType()
366 &lt;&lt; lex-&gt;getSourceRange() &lt;&lt; rex-&gt;getSourceRange();
367</pre>
368
369<p>This shows that use of the Diag method: they take a location (a <a
370href="#SourceLocation">SourceLocation</a> object) and a diagnostic enum value
371(which matches the name from DiagnosticKinds.def). If the diagnostic takes
372arguments, they are specified with the &lt;&lt; operator: the first argument
373becomes %0, the second becomes %1, etc. The diagnostic interface allows you to
Chris Lattnerfd408ea2008-11-23 00:42:53 +0000374specify arguments of many different types, including <tt>int</tt> and
375<tt>unsigned</tt> for integer arguments, <tt>const char*</tt> and
376<tt>std::string</tt> for string arguments, <tt>DeclarationName</tt> and
377<tt>const IdentifierInfo*</tt> for names, <tt>QualType</tt> for types, etc.
378SourceRanges are also specified with the &lt;&lt; operator, but do not have a
379specific ordering requirement.</p>
Chris Lattner627b7052008-11-23 00:28:33 +0000380
381<p>As you can see, adding and producing a diagnostic is pretty straightforward.
382The hard part is deciding exactly what you need to say to help the user, picking
383a suitable wording, and providing the information needed to format it correctly.
Chris Lattnerfd408ea2008-11-23 00:42:53 +0000384The good news is that the call site that issues a diagnostic should be
385completely independent of how the diagnostic is formatted and in what language
386it is rendered.
Chris Lattner627b7052008-11-23 00:28:33 +0000387</p>
Chris Lattner62fd2782008-11-22 21:41:31 +0000388
Douglas Gregorb2fb6de2009-02-27 17:53:17 +0000389<!-- ==================================================== -->
390<h4 id="code-modification-hints">Code Modification Hints</h4>
391<!-- ==================================================== -->
392
393<p>In some cases, the front end emits diagnostics when it is clear
394that some small change to the source code would fix the problem. For
395example, a missing semicolon at the end of a statement or a use of
396deprecated syntax that is easily rewritten into a more modern form. In
397these cases, the front end should emit the diagnostic and recover
398gracefully.</p>
399
400<p>In these cases, the diagnostic can be annotation with a code
401modification "hint" that describes how to modify the code referenced
402by the diagnostic to fix the problem. For example, it might add the
403missing semicolon at the end of the statement or rewrite the use of a
404deprecated construct into something more palatable. Here is one such
405example C++ front end, where we warn about the right-shift operator
406changing meaning from C++98 to C++0x:</p>
407
408<pre>
409test.cpp:3:7: warning: use of right-shift operator ('&gt;&gt;') in template argument will require parentheses in C++0x
410A&lt;100 &gt;&gt; 2&gt; *a;
411 ^
412 ( )
413</pre>
414
415<p>Here, the code modification hint is suggesting that parentheses be
416added, and showing exactly where those parentheses would be inserted
417into the source code. The code modification hints themselves describe
418what changes to make to the source code in an abstract manner, which
419the text diagnostic printer renders as a line of "insertions" below
420the caret line. <a href="#DiagnosticClient">Other diagnostic
421clients</a> might choose to render the code differently (e.g., as
422markup inline) or even give the user the ability to automatically fix
423the problem.</p>
424
425<p>All code modification hints are described by the
426<code>CodeModificationHint</code> class, instances of which should be
427attached to the diagnostic using the &lt;&lt; operator in the same way
428that highlighted source ranges and arguments are passed to the
429diagnostic. Code modification hints can be created with one of three
430constructors:</p>
431
432<dl>
433 <dt><code>CodeModificationHint::CreateInsertion(Loc, Code)</code></dt>
434 <dd>Specifies that the given <code>Code</code> (a string) should be inserted
435 before the source location <code>Loc</code>.</dd>
436
437 <dt><code>CodeModificationHint::CreateRemoval(Range)</code></dt>
438 <dd>Specifies that the code in the given source <code>Range</code>
439 should be removed.</dd>
440
441 <dt><code>CodeModificationHint::CreateReplacement(Range, Code)</code></dt>
442 <dd>Specifies that the code in the given source <code>Range</code>
443 should be removed, and replaced with the given <code>Code</code> string.</dd>
444</dl>
445
Chris Lattner62fd2782008-11-22 21:41:31 +0000446<!-- ============================================================= -->
447<h4><a name="DiagnosticClient">The DiagnosticClient Interface</a></h4>
448<!-- ============================================================= -->
449
Chris Lattner627b7052008-11-23 00:28:33 +0000450<p>Once code generates a diagnostic with all of the arguments and the rest of
451the relevant information, Clang needs to know what to do with it. As previously
452mentioned, the diagnostic machinery goes through some filtering to map a
453severity onto a diagnostic level, then (assuming the diagnostic is not mapped to
454"<tt>Ignore</tt>") it invokes an object that implements the DiagnosticClient
455interface with the information.</p>
456
457<p>It is possible to implement this interface in many different ways. For
458example, the normal Clang DiagnosticClient (named 'TextDiagnosticPrinter') turns
459the arguments into strings (according to the various formatting rules), prints
460out the file/line/column information and the string, then prints out the line of
461code, the source ranges, and the caret. However, this behavior isn't required.
462</p>
463
464<p>Another implementation of the DiagnosticClient interface is the
Chris Lattner552de0a2008-11-23 08:16:56 +0000465'TextDiagnosticBuffer' class, which is used when Clang is in -verify mode.
Chris Lattnerfd408ea2008-11-23 00:42:53 +0000466Instead of formatting and printing out the diagnostics, this implementation just
467captures and remembers the diagnostics as they fly by. Then -verify compares
Chris Lattner552de0a2008-11-23 08:16:56 +0000468the list of produced diagnostics to the list of expected ones. If they disagree,
Chris Lattnerfd408ea2008-11-23 00:42:53 +0000469it prints out its own output.
Chris Lattner627b7052008-11-23 00:28:33 +0000470</p>
471
Chris Lattnerfd408ea2008-11-23 00:42:53 +0000472<p>There are many other possible implementations of this interface, and this is
473why we prefer diagnostics to pass down rich structured information in arguments.
474For example, an HTML output might want declaration names be linkified to where
475they come from in the source. Another example is that a GUI might let you click
476on typedefs to expand them. This application would want to pass significantly
477more information about types through to the GUI than a simple flat string. The
478interface allows this to happen.</p>
Chris Lattner62fd2782008-11-22 21:41:31 +0000479
480<!-- ====================================================== -->
481<h4><a name="translation">Adding Translations to Clang</a></h4>
482<!-- ====================================================== -->
483
Chris Lattner627b7052008-11-23 00:28:33 +0000484<p>Not possible yet! Diagnostic strings should be written in UTF-8, the client
Chris Lattnerfd408ea2008-11-23 00:42:53 +0000485can translate to the relevant code page if needed. Each translation completely
486replaces the format string for the diagnostic.</p>
Chris Lattner62fd2782008-11-22 21:41:31 +0000487
488
Chris Lattner86920d32007-07-31 05:42:17 +0000489<!-- ======================================================================= -->
490<h3 id="SourceLocation">The SourceLocation and SourceManager classes</h3>
491<!-- ======================================================================= -->
492
493<p>Strangely enough, the SourceLocation class represents a location within the
494source code of the program. Important design points include:</p>
495
496<ol>
497<li>sizeof(SourceLocation) must be extremely small, as these are embedded into
498 many AST nodes and are passed around often. Currently it is 32 bits.</li>
499<li>SourceLocation must be a simple value object that can be efficiently
500 copied.</li>
501<li>We should be able to represent a source location for any byte of any input
502 file. This includes in the middle of tokens, in whitespace, in trigraphs,
503 etc.</li>
504<li>A SourceLocation must encode the current #include stack that was active when
505 the location was processed. For example, if the location corresponds to a
506 token, it should contain the set of #includes active when the token was
507 lexed. This allows us to print the #include stack for a diagnostic.</li>
508<li>SourceLocation must be able to describe macro expansions, capturing both
509 the ultimate instantiation point and the source of the original character
510 data.</li>
511</ol>
512
513<p>In practice, the SourceLocation works together with the SourceManager class
Chris Lattner18376dd2009-01-16 07:00:50 +0000514to encode two pieces of information about a location: it's spelling location
Chris Lattner88054de2009-01-16 07:15:35 +0000515and it's instantiation location. For most tokens, these will be the same. However,
Chris Lattner86920d32007-07-31 05:42:17 +0000516for a macro expansion (or tokens that came from a _Pragma directive) these will
517describe the location of the characters corresponding to the token and the
518location where the token was used (i.e. the macro instantiation point or the
519location of the _Pragma itself).</p>
520
Chris Lattner3fcbb892008-11-23 08:32:53 +0000521<p>For efficiency, we only track one level of macro instantiations: if a token was
Chris Lattner86920d32007-07-31 05:42:17 +0000522produced by multiple instantiations, we only track the source and ultimate
523destination. Though we could track the intermediate instantiation points, this
524would require extra bookkeeping and no known client would benefit substantially
525from this.</p>
526
Chris Lattner552de0a2008-11-23 08:16:56 +0000527<p>The Clang front-end inherently depends on the location of a token being
Chris Lattner86920d32007-07-31 05:42:17 +0000528tracked correctly. If it is ever incorrect, the front-end may get confused and
529die. The reason for this is that the notion of the 'spelling' of a Token in
Chris Lattner552de0a2008-11-23 08:16:56 +0000530Clang depends on being able to find the original input characters for the token.
Chris Lattner18376dd2009-01-16 07:00:50 +0000531This concept maps directly to the "spelling location" for the token.</p>
Chris Lattner86920d32007-07-31 05:42:17 +0000532
533<!-- ======================================================================= -->
534<h2 id="liblex">The Lexer and Preprocessor Library</h2>
535<!-- ======================================================================= -->
536
537<p>The Lexer library contains several tightly-connected classes that are involved
538with the nasty process of lexing and preprocessing C source code. The main
539interface to this library for outside clients is the large <a
540href="#Preprocessor">Preprocessor</a> class.
541It contains the various pieces of state that are required to coherently read
542tokens out of a translation unit.</p>
543
544<p>The core interface to the Preprocessor object (once it is set up) is the
545Preprocessor::Lex method, which returns the next <a href="#Token">Token</a> from
546the preprocessor stream. There are two types of token providers that the
547preprocessor is capable of reading from: a buffer lexer (provided by the <a
548href="#Lexer">Lexer</a> class) and a buffered token stream (provided by the <a
Chris Lattner79281252008-03-09 02:27:26 +0000549href="#TokenLexer">TokenLexer</a> class).
Chris Lattner86920d32007-07-31 05:42:17 +0000550
551
552<!-- ======================================================================= -->
553<h3 id="Token">The Token class</h3>
554<!-- ======================================================================= -->
555
556<p>The Token class is used to represent a single lexed token. Tokens are
557intended to be used by the lexer/preprocess and parser libraries, but are not
558intended to live beyond them (for example, they should not live in the ASTs).<p>
559
560<p>Tokens most often live on the stack (or some other location that is efficient
561to access) as the parser is running, but occasionally do get buffered up. For
562example, macro definitions are stored as a series of tokens, and the C++
Chris Lattner3fcbb892008-11-23 08:32:53 +0000563front-end periodically needs to buffer tokens up for tentative parsing and
Chris Lattner86920d32007-07-31 05:42:17 +0000564various pieces of look-ahead. As such, the size of a Token matter. On a 32-bit
565system, sizeof(Token) is currently 16 bytes.</p>
566
Chris Lattner3932fe02009-01-06 06:02:08 +0000567<p>Tokens occur in two forms: "<a href="#AnnotationToken">Annotation
568Tokens</a>" and normal tokens. Normal tokens are those returned by the lexer,
569annotation tokens represent semantic information and are produced by the parser,
570replacing normal tokens in the token stream. Normal tokens contain the
571following information:</p>
Chris Lattner86920d32007-07-31 05:42:17 +0000572
573<ul>
574<li><b>A SourceLocation</b> - This indicates the location of the start of the
575token.</li>
576
577<li><b>A length</b> - This stores the length of the token as stored in the
578SourceBuffer. For tokens that include them, this length includes trigraphs and
579escaped newlines which are ignored by later phases of the compiler. By pointing
580into the original source buffer, it is always possible to get the original
581spelling of a token completely accurately.</li>
582
583<li><b>IdentifierInfo</b> - If a token takes the form of an identifier, and if
584identifier lookup was enabled when the token was lexed (e.g. the lexer was not
585reading in 'raw' mode) this contains a pointer to the unique hash value for the
586identifier. Because the lookup happens before keyword identification, this
587field is set even for language keywords like 'for'.</li>
588
589<li><b>TokenKind</b> - This indicates the kind of token as classified by the
590lexer. This includes things like <tt>tok::starequal</tt> (for the "*="
591operator), <tt>tok::ampamp</tt> for the "&amp;&amp;" token, and keyword values
592(e.g. <tt>tok::kw_for</tt>) for identifiers that correspond to keywords. Note
593that some tokens can be spelled multiple ways. For example, C++ supports
594"operator keywords", where things like "and" are treated exactly like the
595"&amp;&amp;" operator. In these cases, the kind value is set to
596<tt>tok::ampamp</tt>, which is good for the parser, which doesn't have to
597consider both forms. For something that cares about which form is used (e.g.
598the preprocessor 'stringize' operator) the spelling indicates the original
599form.</li>
600
601<li><b>Flags</b> - There are currently four flags tracked by the
602lexer/preprocessor system on a per-token basis:
603
604 <ol>
605 <li><b>StartOfLine</b> - This was the first token that occurred on its input
606 source line.</li>
607 <li><b>LeadingSpace</b> - There was a space character either immediately
608 before the token or transitively before the token as it was expanded
609 through a macro. The definition of this flag is very closely defined by
610 the stringizing requirements of the preprocessor.</li>
611 <li><b>DisableExpand</b> - This flag is used internally to the preprocessor to
612 represent identifier tokens which have macro expansion disabled. This
613 prevents them from being considered as candidates for macro expansion ever
614 in the future.</li>
615 <li><b>NeedsCleaning</b> - This flag is set if the original spelling for the
616 token includes a trigraph or escaped newline. Since this is uncommon,
617 many pieces of code can fast-path on tokens that did not need cleaning.
618 </p>
619 </ol>
620</li>
621</ul>
622
Chris Lattner3932fe02009-01-06 06:02:08 +0000623<p>One interesting (and somewhat unusual) aspect of normal tokens is that they
624don't contain any semantic information about the lexed value. For example, if
625the token was a pp-number token, we do not represent the value of the number
626that was lexed (this is left for later pieces of code to decide). Additionally,
627the lexer library has no notion of typedef names vs variable names: both are
Chris Lattner86920d32007-07-31 05:42:17 +0000628returned as identifiers, and the parser is left to decide whether a specific
629identifier is a typedef or a variable (tracking this requires scope information
Chris Lattner3932fe02009-01-06 06:02:08 +0000630among other things). The parser can do this translation by replacing tokens
631returned by the preprocessor with "Annotation Tokens".</p>
632
633<!-- ======================================================================= -->
634<h3 id="AnnotationToken">Annotation Tokens</h3>
635<!-- ======================================================================= -->
636
637<p>Annotation Tokens are tokens that are synthesized by the parser and injected
638into the preprocessor's token stream (replacing existing tokens) to record
639semantic information found by the parser. For example, if "foo" is found to be
640a typedef, the "foo" <tt>tok::identifier</tt> token is replaced with an
641<tt>tok::annot_typename</tt>. This is useful for a couple of reasons: 1) this
642makes it easy to handle qualified type names (e.g. "foo::bar::baz&lt;42&gt;::t")
643in C++ as a single "token" in the parser. 2) if the parser backtracks, the
644reparse does not need to redo semantic analysis to determine whether a token
645sequence is a variable, type, template, etc.</p>
646
647<p>Annotation Tokens are created by the parser and reinjected into the parser's
648token stream (when backtracking is enabled). Because they can only exist in
649tokens that the preprocessor-proper is done with, it doesn't need to keep around
650flags like "start of line" that the preprocessor uses to do its job.
651Additionally, an annotation token may "cover" a sequence of preprocessor tokens
652(e.g. <tt>a::b::c</tt> is five preprocessor tokens). As such, the valid fields
653of an annotation token are different than the fields for a normal token (but
654they are multiplexed into the normal Token fields):</p>
655
656<ul>
657<li><b>SourceLocation "Location"</b> - The SourceLocation for the annotation
658token indicates the first token replaced by the annotation token. In the example
659above, it would be the location of the "a" identifier.</li>
660
661<li><b>SourceLocation "AnnotationEndLoc"</b> - This holds the location of the
662last token replaced with the annotation token. In the example above, it would
663be the location of the "c" identifier.</li>
664
665<li><b>void* "AnnotationValue"</b> - This contains an opaque object that the
666parser gets from Sema through an Actions module, it is passed around and Sema
667intepretes it, based on the type of annotation token.</li>
668
669<li><b>TokenKind "Kind"</b> - This indicates the kind of Annotation token this
670is. See below for the different valid kinds.</li>
671</ul>
672
673<p>Annotation tokens currently come in three kinds:</p>
674
675<ol>
676<li><b>tok::annot_typename</b>: This annotation token represents a
677resolved typename token that is potentially qualified. The AnnotationValue
Steve Naroffb43a50f2009-01-28 19:39:02 +0000678field contains a pointer returned by Action::getTypeName(). In the case of the
Chris Lattner3932fe02009-01-06 06:02:08 +0000679Sema actions module, this is a <tt>Decl*</tt> for the type.</li>
680
681<li><b>tok::annot_cxxscope</b>: This annotation token represents a C++ scope
682specifier, such as "A::B::". This corresponds to the grammar productions "::"
683and ":: [opt] nested-name-specifier". The AnnotationValue pointer is returned
684by the Action::ActOnCXXGlobalScopeSpecifier and
685Action::ActOnCXXNestedNameSpecifier callbacks. In the case of Sema, this is a
686<tt>DeclContext*</tt>.</li>
687
Douglas Gregor39a8de12009-02-25 19:37:18 +0000688<li><b>tok::annot_template_id</b>: This annotation token represents a
689C++ template-id such as "foo&lt;int, 4&gt;", where "foo" is the name
690of a template. The AnnotationValue pointer is a pointer to a malloc'd
691TemplateIdAnnotation object. Depending on the context, a parsed template-id that names a type might become a typename annotation token (if all we care about is the named type, e.g., because it occurs in a type specifier) or might remain a template-id token (if we want to retain more source location information or produce a new type, e.g., in a declaration of a class template specialization). template-id annotation tokens that refer to a type can be "upgraded" to typename annotation tokens by the parser.</li>
Chris Lattner3932fe02009-01-06 06:02:08 +0000692
693</ol>
694
Cedric Venetda76b282009-01-06 16:22:54 +0000695<p>As mentioned above, annotation tokens are not returned by the preprocessor,
Chris Lattner3932fe02009-01-06 06:02:08 +0000696they are formed on demand by the parser. This means that the parser has to be
697aware of cases where an annotation could occur and form it where appropriate.
698This is somewhat similar to how the parser handles Translation Phase 6 of C99:
699String Concatenation (see C99 5.1.1.2). In the case of string concatenation,
700the preprocessor just returns distinct tok::string_literal and
701tok::wide_string_literal tokens and the parser eats a sequence of them wherever
702the grammar indicates that a string literal can occur.</p>
703
704<p>In order to do this, whenever the parser expects a tok::identifier or
705tok::coloncolon, it should call the TryAnnotateTypeOrScopeToken or
706TryAnnotateCXXScopeToken methods to form the annotation token. These methods
707will maximally form the specified annotation tokens and replace the current
708token with them, if applicable. If the current tokens is not valid for an
709annotation token, it will remain an identifier or :: token.</p>
710
711
Chris Lattner86920d32007-07-31 05:42:17 +0000712
713<!-- ======================================================================= -->
714<h3 id="Lexer">The Lexer class</h3>
715<!-- ======================================================================= -->
716
717<p>The Lexer class provides the mechanics of lexing tokens out of a source
718buffer and deciding what they mean. The Lexer is complicated by the fact that
719it operates on raw buffers that have not had spelling eliminated (this is a
720necessity to get decent performance), but this is countered with careful coding
721as well as standard performance techniques (for example, the comment handling
722code is vectorized on X86 and PowerPC hosts).</p>
723
724<p>The lexer has a couple of interesting modal features:</p>
725
726<ul>
727<li>The lexer can operate in 'raw' mode. This mode has several features that
728 make it possible to quickly lex the file (e.g. it stops identifier lookup,
729 doesn't specially handle preprocessor tokens, handles EOF differently, etc).
730 This mode is used for lexing within an "<tt>#if 0</tt>" block, for
731 example.</li>
732<li>The lexer can capture and return comments as tokens. This is required to
733 support the -C preprocessor mode, which passes comments through, and is
734 used by the diagnostic checker to identifier expect-error annotations.</li>
735<li>The lexer can be in ParsingFilename mode, which happens when preprocessing
Chris Lattner84386242007-09-16 19:25:23 +0000736 after reading a #include directive. This mode changes the parsing of '&lt;'
Chris Lattner86920d32007-07-31 05:42:17 +0000737 to return an "angled string" instead of a bunch of tokens for each thing
738 within the filename.</li>
739<li>When parsing a preprocessor directive (after "<tt>#</tt>") the
740 ParsingPreprocessorDirective mode is entered. This changes the parser to
741 return EOM at a newline.</li>
742<li>The Lexer uses a LangOptions object to know whether trigraphs are enabled,
743 whether C++ or ObjC keywords are recognized, etc.</li>
744</ul>
745
746<p>In addition to these modes, the lexer keeps track of a couple of other
747 features that are local to a lexed buffer, which change as the buffer is
748 lexed:</p>
749
750<ul>
751<li>The Lexer uses BufferPtr to keep track of the current character being
752 lexed.</li>
753<li>The Lexer uses IsAtStartOfLine to keep track of whether the next lexed token
754 will start with its "start of line" bit set.</li>
755<li>The Lexer keeps track of the current #if directives that are active (which
756 can be nested).</li>
757<li>The Lexer keeps track of an <a href="#MultipleIncludeOpt">
758 MultipleIncludeOpt</a> object, which is used to
759 detect whether the buffer uses the standard "<tt>#ifndef XX</tt> /
760 <tt>#define XX</tt>" idiom to prevent multiple inclusion. If a buffer does,
761 subsequent includes can be ignored if the XX macro is defined.</li>
762</ul>
763
764<!-- ======================================================================= -->
Chris Lattner79281252008-03-09 02:27:26 +0000765<h3 id="TokenLexer">The TokenLexer class</h3>
Chris Lattner86920d32007-07-31 05:42:17 +0000766<!-- ======================================================================= -->
767
Chris Lattner79281252008-03-09 02:27:26 +0000768<p>The TokenLexer class is a token provider that returns tokens from a list
Chris Lattner86920d32007-07-31 05:42:17 +0000769of tokens that came from somewhere else. It typically used for two things: 1)
770returning tokens from a macro definition as it is being expanded 2) returning
771tokens from an arbitrary buffer of tokens. The later use is used by _Pragma and
772will most likely be used to handle unbounded look-ahead for the C++ parser.</p>
773
774<!-- ======================================================================= -->
775<h3 id="MultipleIncludeOpt">The MultipleIncludeOpt class</h3>
776<!-- ======================================================================= -->
777
778<p>The MultipleIncludeOpt class implements a really simple little state machine
779that is used to detect the standard "<tt>#ifndef XX</tt> / <tt>#define XX</tt>"
780idiom that people typically use to prevent multiple inclusion of headers. If a
781buffer uses this idiom and is subsequently #include'd, the preprocessor can
782simply check to see whether the guarding condition is defined or not. If so,
783the preprocessor can completely ignore the include of the header.</p>
784
785
786
787<!-- ======================================================================= -->
788<h2 id="libparse">The Parser Library</h2>
789<!-- ======================================================================= -->
790
791<!-- ======================================================================= -->
792<h2 id="libast">The AST Library</h2>
793<!-- ======================================================================= -->
794
795<!-- ======================================================================= -->
796<h3 id="Type">The Type class and its subclasses</h3>
797<!-- ======================================================================= -->
798
799<p>The Type class (and its subclasses) are an important part of the AST. Types
800are accessed through the ASTContext class, which implicitly creates and uniques
801them as they are needed. Types have a couple of non-obvious features: 1) they
802do not capture type qualifiers like const or volatile (See
803<a href="#QualType">QualType</a>), and 2) they implicitly capture typedef
Chris Lattner8a2bc622007-07-31 06:37:39 +0000804information. Once created, types are immutable (unlike decls).</p>
Chris Lattner86920d32007-07-31 05:42:17 +0000805
806<p>Typedefs in C make semantic analysis a bit more complex than it would
807be without them. The issue is that we want to capture typedef information
808and represent it in the AST perfectly, but the semantics of operations need to
809"see through" typedefs. For example, consider this code:</p>
810
811<code>
812void func() {<br>
Bill Wendling30d17752007-10-06 01:56:01 +0000813&nbsp;&nbsp;typedef int foo;<br>
814&nbsp;&nbsp;foo X, *Y;<br>
815&nbsp;&nbsp;typedef foo* bar;<br>
816&nbsp;&nbsp;bar Z;<br>
817&nbsp;&nbsp;*X; <i>// error</i><br>
818&nbsp;&nbsp;**Y; <i>// error</i><br>
819&nbsp;&nbsp;**Z; <i>// error</i><br>
Chris Lattner86920d32007-07-31 05:42:17 +0000820}<br>
821</code>
822
823<p>The code above is illegal, and thus we expect there to be diagnostics emitted
824on the annotated lines. In this example, we expect to get:</p>
825
826<pre>
Chris Lattner8a2bc622007-07-31 06:37:39 +0000827<b>test.c:6:1: error: indirection requires pointer operand ('foo' invalid)</b>
Chris Lattner86920d32007-07-31 05:42:17 +0000828*X; // error
829<font color="blue">^~</font>
Chris Lattner8a2bc622007-07-31 06:37:39 +0000830<b>test.c:7:1: error: indirection requires pointer operand ('foo' invalid)</b>
Chris Lattner86920d32007-07-31 05:42:17 +0000831**Y; // error
832<font color="blue">^~~</font>
Chris Lattner8a2bc622007-07-31 06:37:39 +0000833<b>test.c:8:1: error: indirection requires pointer operand ('foo' invalid)</b>
834**Z; // error
835<font color="blue">^~~</font>
Chris Lattner86920d32007-07-31 05:42:17 +0000836</pre>
837
838<p>While this example is somewhat silly, it illustrates the point: we want to
839retain typedef information where possible, so that we can emit errors about
840"<tt>std::string</tt>" instead of "<tt>std::basic_string&lt;char, std:...</tt>".
841Doing this requires properly keeping typedef information (for example, the type
842of "X" is "foo", not "int"), and requires properly propagating it through the
Chris Lattner8a2bc622007-07-31 06:37:39 +0000843various operators (for example, the type of *Y is "foo", not "int"). In order
844to retain this information, the type of these expressions is an instance of the
845TypedefType class, which indicates that the type of these expressions is a
846typedef for foo.
847</p>
Chris Lattner86920d32007-07-31 05:42:17 +0000848
Chris Lattner8a2bc622007-07-31 06:37:39 +0000849<p>Representing types like this is great for diagnostics, because the
850user-specified type is always immediately available. There are two problems
851with this: first, various semantic checks need to make judgements about the
Chris Lattner33fc68a2007-07-31 18:54:50 +0000852<em>actual structure</em> of a type, ignoring typdefs. Second, we need an
853efficient way to query whether two types are structurally identical to each
854other, ignoring typedefs. The solution to both of these problems is the idea of
Chris Lattner8a2bc622007-07-31 06:37:39 +0000855canonical types.</p>
Chris Lattner86920d32007-07-31 05:42:17 +0000856
Chris Lattner62fd2782008-11-22 21:41:31 +0000857<!-- =============== -->
Chris Lattner8a2bc622007-07-31 06:37:39 +0000858<h4>Canonical Types</h4>
Chris Lattner62fd2782008-11-22 21:41:31 +0000859<!-- =============== -->
Chris Lattner86920d32007-07-31 05:42:17 +0000860
Chris Lattner8a2bc622007-07-31 06:37:39 +0000861<p>Every instance of the Type class contains a canonical type pointer. For
862simple types with no typedefs involved (e.g. "<tt>int</tt>", "<tt>int*</tt>",
863"<tt>int**</tt>"), the type just points to itself. For types that have a
864typedef somewhere in their structure (e.g. "<tt>foo</tt>", "<tt>foo*</tt>",
865"<tt>foo**</tt>", "<tt>bar</tt>"), the canonical type pointer points to their
866structurally equivalent type without any typedefs (e.g. "<tt>int</tt>",
867"<tt>int*</tt>", "<tt>int**</tt>", and "<tt>int*</tt>" respectively).</p>
Chris Lattner86920d32007-07-31 05:42:17 +0000868
Chris Lattner8a2bc622007-07-31 06:37:39 +0000869<p>This design provides a constant time operation (dereferencing the canonical
870type pointer) that gives us access to the structure of types. For example,
871we can trivially tell that "bar" and "foo*" are the same type by dereferencing
872their canonical type pointers and doing a pointer comparison (they both point
873to the single "<tt>int*</tt>" type).</p>
874
875<p>Canonical types and typedef types bring up some complexities that must be
876carefully managed. Specifically, the "isa/cast/dyncast" operators generally
877shouldn't be used in code that is inspecting the AST. For example, when type
878checking the indirection operator (unary '*' on a pointer), the type checker
879must verify that the operand has a pointer type. It would not be correct to
880check that with "<tt>isa&lt;PointerType&gt;(SubExpr-&gt;getType())</tt>",
881because this predicate would fail if the subexpression had a typedef type.</p>
882
883<p>The solution to this problem are a set of helper methods on Type, used to
884check their properties. In this case, it would be correct to use
885"<tt>SubExpr-&gt;getType()-&gt;isPointerType()</tt>" to do the check. This
886predicate will return true if the <em>canonical type is a pointer</em>, which is
887true any time the type is structurally a pointer type. The only hard part here
888is remembering not to use the <tt>isa/cast/dyncast</tt> operations.</p>
889
890<p>The second problem we face is how to get access to the pointer type once we
891know it exists. To continue the example, the result type of the indirection
892operator is the pointee type of the subexpression. In order to determine the
893type, we need to get the instance of PointerType that best captures the typedef
894information in the program. If the type of the expression is literally a
895PointerType, we can return that, otherwise we have to dig through the
896typedefs to find the pointer type. For example, if the subexpression had type
897"<tt>foo*</tt>", we could return that type as the result. If the subexpression
898had type "<tt>bar</tt>", we want to return "<tt>foo*</tt>" (note that we do
899<em>not</em> want "<tt>int*</tt>"). In order to provide all of this, Type has
Chris Lattner11406c12007-07-31 16:50:51 +0000900a getAsPointerType() method that checks whether the type is structurally a
Chris Lattner8a2bc622007-07-31 06:37:39 +0000901PointerType and, if so, returns the best one. If not, it returns a null
902pointer.</p>
903
904<p>This structure is somewhat mystical, but after meditating on it, it will
905make sense to you :).</p>
Chris Lattner86920d32007-07-31 05:42:17 +0000906
907<!-- ======================================================================= -->
908<h3 id="QualType">The QualType class</h3>
909<!-- ======================================================================= -->
910
911<p>The QualType class is designed as a trivial value class that is small,
912passed by-value and is efficient to query. The idea of QualType is that it
913stores the type qualifiers (const, volatile, restrict) separately from the types
914themselves: QualType is conceptually a pair of "Type*" and bits for the type
915qualifiers.</p>
916
917<p>By storing the type qualifiers as bits in the conceptual pair, it is
918extremely efficient to get the set of qualifiers on a QualType (just return the
919field of the pair), add a type qualifier (which is a trivial constant-time
920operation that sets a bit), and remove one or more type qualifiers (just return
921a QualType with the bitfield set to empty).</p>
922
923<p>Further, because the bits are stored outside of the type itself, we do not
924need to create duplicates of types with different sets of qualifiers (i.e. there
925is only a single heap allocated "int" type: "const int" and "volatile const int"
926both point to the same heap allocated "int" type). This reduces the heap size
927used to represent bits and also means we do not have to consider qualifiers when
928uniquing types (<a href="#Type">Type</a> does not even contain qualifiers).</p>
929
930<p>In practice, on hosts where it is safe, the 3 type qualifiers are stored in
931the low bit of the pointer to the Type object. This means that QualType is
932exactly the same size as a pointer, and this works fine on any system where
933malloc'd objects are at least 8 byte aligned.</p>
Ted Kremenek8bc05712007-10-10 23:01:43 +0000934
935<!-- ======================================================================= -->
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000936<h3 id="DeclarationName">Declaration names</h3>
937<!-- ======================================================================= -->
938
939<p>The <tt>DeclarationName</tt> class represents the name of a
940 declaration in Clang. Declarations in the C family of languages can
Chris Lattner3fcbb892008-11-23 08:32:53 +0000941 take several different forms. Most declarations are named by
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000942 simple identifiers, e.g., "<code>f</code>" and "<code>x</code>" in
943 the function declaration <code>f(int x)</code>. In C++, declaration
944 names can also name class constructors ("<code>Class</code>"
945 in <code>struct Class { Class(); }</code>), class destructors
946 ("<code>~Class</code>"), overloaded operator names ("operator+"),
947 and conversion functions ("<code>operator void const *</code>"). In
948 Objective-C, declaration names can refer to the names of Objective-C
949 methods, which involve the method name and the parameters,
Chris Lattner3fcbb892008-11-23 08:32:53 +0000950 collectively called a <i>selector</i>, e.g.,
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000951 "<code>setWidth:height:</code>". Since all of these kinds of
Chris Lattner3fcbb892008-11-23 08:32:53 +0000952 entities - variables, functions, Objective-C methods, C++
953 constructors, destructors, and operators - are represented as
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000954 subclasses of Clang's common <code>NamedDecl</code>
955 class, <code>DeclarationName</code> is designed to efficiently
956 represent any kind of name.</p>
957
958<p>Given
959 a <code>DeclarationName</code> <code>N</code>, <code>N.getNameKind()</code>
Douglas Gregor2def4832008-11-17 20:34:05 +0000960 will produce a value that describes what kind of name <code>N</code>
Douglas Gregore94ca9e42008-11-18 14:39:36 +0000961 stores. There are 8 options (all of the names are inside
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000962 the <code>DeclarationName</code> class)</p>
963<dl>
964 <dt>Identifier</dt>
965 <dd>The name is a simple
966 identifier. Use <code>N.getAsIdentifierInfo()</code> to retrieve the
967 corresponding <code>IdentifierInfo*</code> pointing to the actual
968 identifier. Note that C++ overloaded operators (e.g.,
969 "<code>operator+</code>") are represented as special kinds of
970 identifiers. Use <code>IdentifierInfo</code>'s <code>getOverloadedOperatorID</code>
971 function to determine whether an identifier is an overloaded
972 operator name.</dd>
973
974 <dt>ObjCZeroArgSelector, ObjCOneArgSelector,
975 ObjCMultiArgSelector</dt>
976 <dd>The name is an Objective-C selector, which can be retrieved as a
977 <code>Selector</code> instance
978 via <code>N.getObjCSelector()</code>. The three possible name
979 kinds for Objective-C reflect an optimization within
980 the <code>DeclarationName</code> class: both zero- and
981 one-argument selectors are stored as a
982 masked <code>IdentifierInfo</code> pointer, and therefore require
983 very little space, since zero- and one-argument selectors are far
984 more common than multi-argument selectors (which use a different
985 structure).</dd>
986
987 <dt>CXXConstructorName</dt>
988 <dd>The name is a C++ constructor
989 name. Use <code>N.getCXXNameType()</code> to retrieve
990 the <a href="#QualType">type</a> that this constructor is meant to
991 construct. The type is always the canonical type, since all
992 constructors for a given type have the same name.</dd>
993
994 <dt>CXXDestructorName</dt>
995 <dd>The name is a C++ destructor
996 name. Use <code>N.getCXXNameType()</code> to retrieve
997 the <a href="#QualType">type</a> whose destructor is being
998 named. This type is always a canonical type.</dd>
999
1000 <dt>CXXConversionFunctionName</dt>
1001 <dd>The name is a C++ conversion function. Conversion functions are
1002 named according to the type they convert to, e.g., "<code>operator void
1003 const *</code>". Use <code>N.getCXXNameType()</code> to retrieve
1004 the type that this conversion function converts to. This type is
1005 always a canonical type.</dd>
Douglas Gregore94ca9e42008-11-18 14:39:36 +00001006
1007 <dt>CXXOperatorName</dt>
1008 <dd>The name is a C++ overloaded operator name. Overloaded operators
1009 are named according to their spelling, e.g.,
1010 "<code>operator+</code>" or "<code>operator new
1011 []</code>". Use <code>N.getCXXOverloadedOperator()</code> to
1012 retrieve the overloaded operator (a value of
1013 type <code>OverloadedOperatorKind</code>).</dd>
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001014</dl>
1015
1016<p><code>DeclarationName</code>s are cheap to create, copy, and
1017 compare. They require only a single pointer's worth of storage in
Douglas Gregore94ca9e42008-11-18 14:39:36 +00001018 the common cases (identifiers, zero-
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001019 and one-argument Objective-C selectors) and use dense, uniqued
1020 storage for the other kinds of
1021 names. Two <code>DeclarationName</code>s can be compared for
1022 equality (<code>==</code>, <code>!=</code>) using a simple bitwise
1023 comparison, can be ordered
1024 with <code>&lt;</code>, <code>&gt;</code>, <code>&lt;=</code>,
1025 and <code>&gt;=</code> (which provide a lexicographical ordering for
1026 normal identifiers but an unspecified ordering for other kinds of
1027 names), and can be placed into LLVM <code>DenseMap</code>s
1028 and <code>DenseSet</code>s.</p>
1029
1030<p><code>DeclarationName</code> instances can be created in different
1031 ways depending on what kind of name the instance will store. Normal
Douglas Gregore94ca9e42008-11-18 14:39:36 +00001032 identifiers (<code>IdentifierInfo</code> pointers) and Objective-C selectors
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001033 (<code>Selector</code>) can be implicitly converted
1034 to <code>DeclarationName</code>s. Names for C++ constructors,
Douglas Gregore94ca9e42008-11-18 14:39:36 +00001035 destructors, conversion functions, and overloaded operators can be retrieved from
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001036 the <code>DeclarationNameTable</code>, an instance of which is
1037 available as <code>ASTContext::DeclarationNames</code>. The member
1038 functions <code>getCXXConstructorName</code>, <code>getCXXDestructorName</code>,
Douglas Gregore94ca9e42008-11-18 14:39:36 +00001039 <code>getCXXConversionFunctionName</code>, and <code>getCXXOperatorName</code>, respectively,
1040 return <code>DeclarationName</code> instances for the four kinds of
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001041 C++ special function names.</p>
1042
1043<!-- ======================================================================= -->
Douglas Gregor074149e2009-01-05 19:45:36 +00001044<h3 id="DeclContext">Declaration contexts</h3>
1045<!-- ======================================================================= -->
1046<p>Every declaration in a program exists within some <i>declaration
1047 context</i>, such as a translation unit, namespace, class, or
1048 function. Declaration contexts in Clang are represented by
1049 the <code>DeclContext</code> class, from which the various
1050 declaration-context AST nodes
1051 (<code>TranslationUnitDecl</code>, <code>NamespaceDecl</code>, <code>RecordDecl</code>, <code>FunctionDecl</code>,
1052 etc.) will derive. The <code>DeclContext</code> class provides
1053 several facilities common to each declaration context:</p>
1054<dl>
1055 <dt>Source-centric vs. Semantics-centric View of Declarations</dt>
1056 <dd><code>DeclContext</code> provides two views of the declarations
1057 stored within a declaration context. The source-centric view
1058 accurately represents the program source code as written, including
1059 multiple declarations of entities where present (see the
1060 section <a href="#Redeclarations">Redeclarations and
1061 Overloads</a>), while the semantics-centric view represents the
1062 program semantics. The two views are kept synchronized by semantic
1063 analysis while the ASTs are being constructed.</dd>
1064
1065 <dt>Storage of declarations within that context</dt>
1066 <dd>Every declaration context can contain some number of
1067 declarations. For example, a C++ class (represented
1068 by <code>RecordDecl</code>) contains various member functions,
1069 fields, nested types, and so on. All of these declarations will be
1070 stored within the <code>DeclContext</code>, and one can iterate
1071 over the declarations via
1072 [<code>DeclContext::decls_begin()</code>,
1073 <code>DeclContext::decls_end()</code>). This mechanism provides
1074 the source-centric view of declarations in the context.</dd>
1075
1076 <dt>Lookup of declarations within that context</dt>
1077 <dd>The <code>DeclContext</code> structure provides efficient name
1078 lookup for names within that declaration context. For example,
1079 if <code>N</code> is a namespace we can look for the
1080 name <code>N::f</code>
1081 using <code>DeclContext::lookup</code>. The lookup itself is
1082 based on a lazily-constructed array (for declaration contexts
1083 with a small number of declarations) or hash table (for
1084 declaration contexts with more declarations). The lookup
1085 operation provides the semantics-centric view of the declarations
1086 in the context.</dd>
1087
1088 <dt>Ownership of declarations</dt>
1089 <dd>The <code>DeclContext</code> owns all of the declarations that
1090 were declared within its declaration context, and is responsible
1091 for the management of their memory as well as their
1092 (de-)serialization.</dd>
1093</dl>
1094
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001095<p>All declarations are stored within a declaration context, and one
1096 can query
1097 information about the context in which each declaration lives. One
Douglas Gregor074149e2009-01-05 19:45:36 +00001098 can retrieve the <code>DeclContext</code> that contains a
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001099 particular <code>Decl</code>
1100 using <code>Decl::getDeclContext</code>. However, see the
Douglas Gregor074149e2009-01-05 19:45:36 +00001101 section <a href="#LexicalAndSemanticContexts">Lexical and Semantic
1102 Contexts</a> for more information about how to interpret this
1103 context information.</p>
1104
1105<h4 id="Redeclarations">Redeclarations and Overloads</h4>
1106<p>Within a translation unit, it is common for an entity to be
1107declared several times. For example, we might declare a function "f"
1108 and then later re-declare it as part of an inlined definition:</p>
1109
1110<pre>
1111void f(int x, int y, int z = 1);
1112
1113inline void f(int x, int y, int z) { /* ... */ }
1114</pre>
1115
1116<p>The representation of "f" differs in the source-centric and
1117 semantics-centric views of a declaration context. In the
1118 source-centric view, all redeclarations will be present, in the
1119 order they occurred in the source code, making
1120 this view suitable for clients that wish to see the structure of
1121 the source code. In the semantics-centric view, only the most recent "f"
1122 will be found by the lookup, since it effectively replaces the first
1123 declaration of "f".</p>
1124
1125<p>In the semantics-centric view, overloading of functions is
1126 represented explicitly. For example, given two declarations of a
1127 function "g" that are overloaded, e.g.,</p>
1128<pre>
1129void g();
1130void g(int);
1131</pre>
1132<p>the <code>DeclContext::lookup</code> operation will return
1133 an <code>OverloadedFunctionDecl</code> that contains both
1134 declarations of "g". Clients that perform semantic analysis on a
1135 program that is not concerned with the actual source code will
1136 primarily use this semantics-centric view.</p>
1137
1138<h4 id="LexicalAndSemanticContexts">Lexical and Semantic Contexts</h4>
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001139<p>Each declaration has two potentially different
Douglas Gregor074149e2009-01-05 19:45:36 +00001140 declaration contexts: a <i>lexical</i> context, which corresponds to
1141 the source-centric view of the declaration context, and
1142 a <i>semantic</i> context, which corresponds to the
1143 semantics-centric view. The lexical context is accessible
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001144 via <code>Decl::getLexicalDeclContext</code> while the
Douglas Gregor074149e2009-01-05 19:45:36 +00001145 semantic context is accessible
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001146 via <code>Decl::getDeclContext</code>, both of which return
Douglas Gregor074149e2009-01-05 19:45:36 +00001147 <code>DeclContext</code> pointers. For most declarations, the two
1148 contexts are identical. For example:</p>
1149
1150<pre>
1151class X {
1152public:
1153 void f(int x);
1154};
1155</pre>
1156
1157<p>Here, the semantic and lexical contexts of <code>X::f</code> are
1158 the <code>DeclContext</code> associated with the
1159 class <code>X</code> (itself stored as a <code>RecordDecl</code> AST
1160 node). However, we can now define <code>X::f</code> out-of-line:</p>
1161
1162<pre>
1163void X::f(int x = 17) { /* ... */ }
1164</pre>
1165
1166<p>This definition of has different lexical and semantic
1167 contexts. The lexical context corresponds to the declaration
1168 context in which the actual declaration occurred in the source
1169 code, e.g., the translation unit containing <code>X</code>. Thus,
1170 this declaration of <code>X::f</code> can be found by traversing
1171 the declarations provided by
1172 [<code>decls_begin()</code>, <code>decls_end()</code>) in the
1173 translation unit.</p>
1174
1175<p>The semantic context of <code>X::f</code> corresponds to the
1176 class <code>X</code>, since this member function is (semantically) a
1177 member of <code>X</code>. Lookup of the name <code>f</code> into
1178 the <code>DeclContext</code> associated with <code>X</code> will
1179 then return the definition of <code>X::f</code> (including
1180 information about the default argument).</p>
1181
1182<h4 id="TransparentContexts">Transparent Declaration Contexts</h4>
1183<p>In C and C++, there are several contexts in which names that are
1184 logically declared inside another declaration will actually "leak"
1185 out into the enclosing scope from the perspective of name
1186 lookup. The most obvious instance of this behavior is in
1187 enumeration types, e.g.,</p>
1188<pre>
1189enum Color {
1190 Red,
1191 Green,
1192 Blue
1193};
1194</pre>
1195
1196<p>Here, <code>Color</code> is an enumeration, which is a declaration
1197 context that contains the
1198 enumerators <code>Red</code>, <code>Green</code>,
1199 and <code>Blue</code>. Thus, traversing the list of declarations
1200 contained in the enumeration <code>Color</code> will
1201 yield <code>Red</code>, <code>Green</code>,
1202 and <code>Blue</code>. However, outside of the scope
1203 of <code>Color</code> one can name the enumerator <code>Red</code>
1204 without qualifying the name, e.g.,</p>
1205
1206<pre>
1207Color c = Red;
1208</pre>
1209
1210<p>There are other entities in C++ that provide similar behavior. For
1211 example, linkage specifications that use curly braces:</p>
1212
1213<pre>
1214extern "C" {
1215 void f(int);
1216 void g(int);
1217}
1218// f and g are visible here
1219</pre>
1220
1221<p>For source-level accuracy, we treat the linkage specification and
1222 enumeration type as a
1223 declaration context in which its enclosed declarations ("Red",
1224 "Green", and "Blue"; "f" and "g")
1225 are declared. However, these declarations are visible outside of the
1226 scope of the declaration context.</p>
1227
1228<p>These language features (and several others, described below) have
1229 roughly the same set of
1230 requirements: declarations are declared within a particular lexical
1231 context, but the declarations are also found via name lookup in
1232 scopes enclosing the declaration itself. This feature is implemented
1233 via <i>transparent</i> declaration contexts
1234 (see <code>DeclContext::isTransparentContext()</code>), whose
1235 declarations are visible in the nearest enclosing non-transparent
1236 declaration context. This means that the lexical context of the
1237 declaration (e.g., an enumerator) will be the
1238 transparent <code>DeclContext</code> itself, as will the semantic
1239 context, but the declaration will be visible in every outer context
1240 up to and including the first non-transparent declaration context (since
1241 transparent declaration contexts can be nested).</p>
1242
1243<p>The transparent <code>DeclContexts</code> are:</p>
1244<ul>
1245 <li>Enumerations (but not C++0x "scoped enumerations"):
1246 <pre>
1247enum Color {
1248 Red,
1249 Green,
1250 Blue
1251};
1252// Red, Green, and Blue are in scope
1253 </pre></li>
1254 <li>C++ linkage specifications:
1255 <pre>
1256extern "C" {
1257 void f(int);
1258 void g(int);
1259}
1260// f and g are in scope
1261 </pre></li>
1262 <li>Anonymous unions and structs:
1263 <pre>
1264struct LookupTable {
1265 bool IsVector;
1266 union {
1267 std::vector&lt;Item&gt; *Vector;
1268 std::set&lt;Item&gt; *Set;
1269 };
1270};
1271
1272LookupTable LT;
1273LT.Vector = 0; // Okay: finds Vector inside the unnamed union
1274 </pre>
1275 </li>
1276 <li>C++0x inline namespaces:
1277<pre>
1278namespace mylib {
1279 inline namespace debug {
1280 class X;
1281 }
1282}
1283mylib::X *xp; // okay: mylib::X refers to mylib::debug::X
1284</pre>
1285</li>
1286</ul>
1287
1288
1289<h4 id="MultiDeclContext">Multiply-Defined Declaration Contexts</h4>
1290<p>C++ namespaces have the interesting--and, so far, unique--property that
1291the namespace can be defined multiple times, and the declarations
1292provided by each namespace definition are effectively merged (from
1293the semantic point of view). For example, the following two code
1294snippets are semantically indistinguishable:</p>
1295<pre>
1296// Snippet #1:
1297namespace N {
1298 void f();
1299}
1300namespace N {
1301 void f(int);
1302}
1303
1304// Snippet #2:
1305namespace N {
1306 void f();
1307 void f(int);
1308}
1309</pre>
1310
1311<p>In Clang's representation, the source-centric view of declaration
1312 contexts will actually have two separate <code>NamespaceDecl</code>
1313 nodes in Snippet #1, each of which is a declaration context that
1314 contains a single declaration of "f". However, the semantics-centric
1315 view provided by name lookup into the namespace <code>N</code> for
1316 "f" will return an <code>OverloadedFunctionDecl</code> that contains
1317 both declarations of "f".</p>
1318
1319<p><code>DeclContext</code> manages multiply-defined declaration
1320 contexts internally. The
1321 function <code>DeclContext::getPrimaryContext</code> retrieves the
1322 "primary" context for a given <code>DeclContext</code> instance,
1323 which is the <code>DeclContext</code> responsible for maintaining
1324 the lookup table used for the semantics-centric view. Given the
1325 primary context, one can follow the chain
1326 of <code>DeclContext</code> nodes that define additional
1327 declarations via <code>DeclContext::getNextContext</code>. Note that
1328 these functions are used internally within the lookup and insertion
1329 methods of the <code>DeclContext</code>, so the vast majority of
1330 clients can ignore them.</p>
1331
1332<!-- ======================================================================= -->
Ted Kremenek8bc05712007-10-10 23:01:43 +00001333<h3 id="CFG">The <tt>CFG</tt> class</h3>
1334<!-- ======================================================================= -->
1335
1336<p>The <tt>CFG</tt> class is designed to represent a source-level
1337control-flow graph for a single statement (<tt>Stmt*</tt>). Typically
1338instances of <tt>CFG</tt> are constructed for function bodies (usually
1339an instance of <tt>CompoundStmt</tt>), but can also be instantiated to
1340represent the control-flow of any class that subclasses <tt>Stmt</tt>,
1341which includes simple expressions. Control-flow graphs are especially
1342useful for performing
1343<a href="http://en.wikipedia.org/wiki/Data_flow_analysis#Sensitivities">flow-
1344or path-sensitive</a> program analyses on a given function.</p>
1345
Chris Lattner62fd2782008-11-22 21:41:31 +00001346<!-- ============ -->
Ted Kremenek8bc05712007-10-10 23:01:43 +00001347<h4>Basic Blocks</h4>
Chris Lattner62fd2782008-11-22 21:41:31 +00001348<!-- ============ -->
Ted Kremenek8bc05712007-10-10 23:01:43 +00001349
1350<p>Concretely, an instance of <tt>CFG</tt> is a collection of basic
1351blocks. Each basic block is an instance of <tt>CFGBlock</tt>, which
1352simply contains an ordered sequence of <tt>Stmt*</tt> (each referring
1353to statements in the AST). The ordering of statements within a block
1354indicates unconditional flow of control from one statement to the
1355next. <a href="#ConditionalControlFlow">Conditional control-flow</a>
1356is represented using edges between basic blocks. The statements
1357within a given <tt>CFGBlock</tt> can be traversed using
1358the <tt>CFGBlock::*iterator</tt> interface.</p>
1359
1360<p>
Ted Kremenek18e17e72007-10-18 22:50:52 +00001361A <tt>CFG</tt> object owns the instances of <tt>CFGBlock</tt> within
Ted Kremenek8bc05712007-10-10 23:01:43 +00001362the control-flow graph it represents. Each <tt>CFGBlock</tt> within a
1363CFG is also uniquely numbered (accessible
1364via <tt>CFGBlock::getBlockID()</tt>). Currently the number is
1365based on the ordering the blocks were created, but no assumptions
1366should be made on how <tt>CFGBlock</tt>s are numbered other than their
1367numbers are unique and that they are numbered from 0..N-1 (where N is
1368the number of basic blocks in the CFG).</p>
1369
Chris Lattner62fd2782008-11-22 21:41:31 +00001370<!-- ===================== -->
Ted Kremenek8bc05712007-10-10 23:01:43 +00001371<h4>Entry and Exit Blocks</h4>
Chris Lattner62fd2782008-11-22 21:41:31 +00001372<!-- ===================== -->
Ted Kremenek8bc05712007-10-10 23:01:43 +00001373
1374Each instance of <tt>CFG</tt> contains two special blocks:
1375an <i>entry</i> block (accessible via <tt>CFG::getEntry()</tt>), which
1376has no incoming edges, and an <i>exit</i> block (accessible
1377via <tt>CFG::getExit()</tt>), which has no outgoing edges. Neither
1378block contains any statements, and they serve the role of providing a
1379clear entrance and exit for a body of code such as a function body.
1380The presence of these empty blocks greatly simplifies the
1381implementation of many analyses built on top of CFGs.
1382
Chris Lattner62fd2782008-11-22 21:41:31 +00001383<!-- ===================================================== -->
Ted Kremenek8bc05712007-10-10 23:01:43 +00001384<h4 id ="ConditionalControlFlow">Conditional Control-Flow</h4>
Chris Lattner62fd2782008-11-22 21:41:31 +00001385<!-- ===================================================== -->
Ted Kremenek8bc05712007-10-10 23:01:43 +00001386
1387<p>Conditional control-flow (such as those induced by if-statements
1388and loops) is represented as edges between <tt>CFGBlock</tt>s.
1389Because different C language constructs can induce control-flow,
1390each <tt>CFGBlock</tt> also records an extra <tt>Stmt*</tt> that
1391represents the <i>terminator</i> of the block. A terminator is simply
1392the statement that caused the control-flow, and is used to identify
1393the nature of the conditional control-flow between blocks. For
1394example, in the case of an if-statement, the terminator refers to
1395the <tt>IfStmt</tt> object in the AST that represented the given
1396branch.</p>
1397
1398<p>To illustrate, consider the following code example:</p>
1399
1400<code>
1401int foo(int x) {<br>
1402&nbsp;&nbsp;x = x + 1;<br>
1403<br>
1404&nbsp;&nbsp;if (x > 2) x++;<br>
1405&nbsp;&nbsp;else {<br>
1406&nbsp;&nbsp;&nbsp;&nbsp;x += 2;<br>
1407&nbsp;&nbsp;&nbsp;&nbsp;x *= 2;<br>
1408&nbsp;&nbsp;}<br>
1409<br>
1410&nbsp;&nbsp;return x;<br>
1411}
1412</code>
1413
1414<p>After invoking the parser+semantic analyzer on this code fragment,
1415the AST of the body of <tt>foo</tt> is referenced by a
1416single <tt>Stmt*</tt>. We can then construct an instance
1417of <tt>CFG</tt> representing the control-flow graph of this function
1418body by single call to a static class method:</p>
1419
1420<code>
1421&nbsp;&nbsp;Stmt* FooBody = ...<br>
1422&nbsp;&nbsp;CFG* FooCFG = <b>CFG::buildCFG</b>(FooBody);
1423</code>
1424
1425<p>It is the responsibility of the caller of <tt>CFG::buildCFG</tt>
1426to <tt>delete</tt> the returned <tt>CFG*</tt> when the CFG is no
1427longer needed.</p>
1428
1429<p>Along with providing an interface to iterate over
1430its <tt>CFGBlock</tt>s, the <tt>CFG</tt> class also provides methods
1431that are useful for debugging and visualizing CFGs. For example, the
1432method
1433<tt>CFG::dump()</tt> dumps a pretty-printed version of the CFG to
1434standard error. This is especially useful when one is using a
1435debugger such as gdb. For example, here is the output
1436of <tt>FooCFG->dump()</tt>:</p>
1437
1438<code>
1439&nbsp;[ B5 (ENTRY) ]<br>
1440&nbsp;&nbsp;&nbsp;&nbsp;Predecessors (0):<br>
1441&nbsp;&nbsp;&nbsp;&nbsp;Successors (1): B4<br>
1442<br>
1443&nbsp;[ B4 ]<br>
1444&nbsp;&nbsp;&nbsp;&nbsp;1: x = x + 1<br>
1445&nbsp;&nbsp;&nbsp;&nbsp;2: (x > 2)<br>
1446&nbsp;&nbsp;&nbsp;&nbsp;<b>T: if [B4.2]</b><br>
1447&nbsp;&nbsp;&nbsp;&nbsp;Predecessors (1): B5<br>
1448&nbsp;&nbsp;&nbsp;&nbsp;Successors (2): B3 B2<br>
1449<br>
1450&nbsp;[ B3 ]<br>
1451&nbsp;&nbsp;&nbsp;&nbsp;1: x++<br>
1452&nbsp;&nbsp;&nbsp;&nbsp;Predecessors (1): B4<br>
1453&nbsp;&nbsp;&nbsp;&nbsp;Successors (1): B1<br>
1454<br>
1455&nbsp;[ B2 ]<br>
1456&nbsp;&nbsp;&nbsp;&nbsp;1: x += 2<br>
1457&nbsp;&nbsp;&nbsp;&nbsp;2: x *= 2<br>
1458&nbsp;&nbsp;&nbsp;&nbsp;Predecessors (1): B4<br>
1459&nbsp;&nbsp;&nbsp;&nbsp;Successors (1): B1<br>
1460<br>
1461&nbsp;[ B1 ]<br>
1462&nbsp;&nbsp;&nbsp;&nbsp;1: return x;<br>
1463&nbsp;&nbsp;&nbsp;&nbsp;Predecessors (2): B2 B3<br>
1464&nbsp;&nbsp;&nbsp;&nbsp;Successors (1): B0<br>
1465<br>
1466&nbsp;[ B0 (EXIT) ]<br>
1467&nbsp;&nbsp;&nbsp;&nbsp;Predecessors (1): B1<br>
1468&nbsp;&nbsp;&nbsp;&nbsp;Successors (0):
1469</code>
1470
1471<p>For each block, the pretty-printed output displays for each block
1472the number of <i>predecessor</i> blocks (blocks that have outgoing
1473control-flow to the given block) and <i>successor</i> blocks (blocks
1474that have control-flow that have incoming control-flow from the given
1475block). We can also clearly see the special entry and exit blocks at
1476the beginning and end of the pretty-printed output. For the entry
1477block (block B5), the number of predecessor blocks is 0, while for the
1478exit block (block B0) the number of successor blocks is 0.</p>
1479
1480<p>The most interesting block here is B4, whose outgoing control-flow
1481represents the branching caused by the sole if-statement
1482in <tt>foo</tt>. Of particular interest is the second statement in
1483the block, <b><tt>(x > 2)</tt></b>, and the terminator, printed
1484as <b><tt>if [B4.2]</tt></b>. The second statement represents the
1485evaluation of the condition of the if-statement, which occurs before
1486the actual branching of control-flow. Within the <tt>CFGBlock</tt>
1487for B4, the <tt>Stmt*</tt> for the second statement refers to the
1488actual expression in the AST for <b><tt>(x > 2)</tt></b>. Thus
1489pointers to subclasses of <tt>Expr</tt> can appear in the list of
1490statements in a block, and not just subclasses of <tt>Stmt</tt> that
1491refer to proper C statements.</p>
1492
1493<p>The terminator of block B4 is a pointer to the <tt>IfStmt</tt>
1494object in the AST. The pretty-printer outputs <b><tt>if
1495[B4.2]</tt></b> because the condition expression of the if-statement
1496has an actual place in the basic block, and thus the terminator is
1497essentially
1498<i>referring</i> to the expression that is the second statement of
1499block B4 (i.e., B4.2). In this manner, conditions for control-flow
1500(which also includes conditions for loops and switch statements) are
1501hoisted into the actual basic block.</p>
1502
Chris Lattner62fd2782008-11-22 21:41:31 +00001503<!-- ===================== -->
1504<!-- <h4>Implicit Control-Flow</h4> -->
1505<!-- ===================== -->
Ted Kremenek8bc05712007-10-10 23:01:43 +00001506
1507<!--
1508<p>A key design principle of the <tt>CFG</tt> class was to not require
1509any transformations to the AST in order to represent control-flow.
1510Thus the <tt>CFG</tt> does not perform any "lowering" of the
1511statements in an AST: loops are not transformed into guarded gotos,
1512short-circuit operations are not converted to a set of if-statements,
1513and so on.</p>
1514-->
Ted Kremenek17a295d2008-06-11 06:19:49 +00001515
Chris Lattner7bad1992008-11-16 21:48:07 +00001516
1517<!-- ======================================================================= -->
1518<h3 id="Constants">Constant Folding in the Clang AST</h3>
1519<!-- ======================================================================= -->
1520
1521<p>There are several places where constants and constant folding matter a lot to
1522the Clang front-end. First, in general, we prefer the AST to retain the source
1523code as close to how the user wrote it as possible. This means that if they
1524wrote "5+4", we want to keep the addition and two constants in the AST, we don't
1525want to fold to "9". This means that constant folding in various ways turns
1526into a tree walk that needs to handle the various cases.</p>
1527
1528<p>However, there are places in both C and C++ that require constants to be
1529folded. For example, the C standard defines what an "integer constant
1530expression" (i-c-e) is with very precise and specific requirements. The
1531language then requires i-c-e's in a lot of places (for example, the size of a
1532bitfield, the value for a case statement, etc). For these, we have to be able
1533to constant fold the constants, to do semantic checks (e.g. verify bitfield size
1534is non-negative and that case statements aren't duplicated). We aim for Clang
1535to be very pedantic about this, diagnosing cases when the code does not use an
1536i-c-e where one is required, but accepting the code unless running with
1537<tt>-pedantic-errors</tt>.</p>
1538
1539<p>Things get a little bit more tricky when it comes to compatibility with
1540real-world source code. Specifically, GCC has historically accepted a huge
1541superset of expressions as i-c-e's, and a lot of real world code depends on this
1542unfortuate accident of history (including, e.g., the glibc system headers). GCC
1543accepts anything its "fold" optimizer is capable of reducing to an integer
1544constant, which means that the definition of what it accepts changes as its
1545optimizer does. One example is that GCC accepts things like "case X-X:" even
1546when X is a variable, because it can fold this to 0.</p>
1547
1548<p>Another issue are how constants interact with the extensions we support, such
1549as __builtin_constant_p, __builtin_inf, __extension__ and many others. C99
1550obviously does not specify the semantics of any of these extensions, and the
1551definition of i-c-e does not include them. However, these extensions are often
1552used in real code, and we have to have a way to reason about them.</p>
1553
1554<p>Finally, this is not just a problem for semantic analysis. The code
1555generator and other clients have to be able to fold constants (e.g. to
1556initialize global variables) and has to handle a superset of what C99 allows.
1557Further, these clients can benefit from extended information. For example, we
1558know that "foo()||1" always evaluates to true, but we can't replace the
1559expression with true because it has side effects.</p>
1560
1561<!-- ======================= -->
1562<h4>Implementation Approach</h4>
1563<!-- ======================= -->
1564
1565<p>After trying several different approaches, we've finally converged on a
1566design (Note, at the time of this writing, not all of this has been implemented,
1567consider this a design goal!). Our basic approach is to define a single
1568recursive method evaluation method (<tt>Expr::Evaluate</tt>), which is
1569implemented in <tt>AST/ExprConstant.cpp</tt>. Given an expression with 'scalar'
1570type (integer, fp, complex, or pointer) this method returns the following
1571information:</p>
1572
1573<ul>
1574<li>Whether the expression is an integer constant expression, a general
1575 constant that was folded but has no side effects, a general constant that
1576 was folded but that does have side effects, or an uncomputable/unfoldable
1577 value.
1578</li>
1579<li>If the expression was computable in any way, this method returns the APValue
1580 for the result of the expression.</li>
1581<li>If the expression is not evaluatable at all, this method returns
1582 information on one of the problems with the expression. This includes a
1583 SourceLocation for where the problem is, and a diagnostic ID that explains
1584 the problem. The diagnostic should be have ERROR type.</li>
1585<li>If the expression is not an integer constant expression, this method returns
1586 information on one of the problems with the expression. This includes a
1587 SourceLocation for where the problem is, and a diagnostic ID that explains
1588 the problem. The diagnostic should be have EXTENSION type.</li>
1589</ul>
1590
1591<p>This information gives various clients the flexibility that they want, and we
1592will eventually have some helper methods for various extensions. For example,
1593Sema should have a <tt>Sema::VerifyIntegerConstantExpression</tt> method, which
1594calls Evaluate on the expression. If the expression is not foldable, the error
1595is emitted, and it would return true. If the expression is not an i-c-e, the
1596EXTENSION diagnostic is emitted. Finally it would return false to indicate that
1597the AST is ok.</p>
1598
1599<p>Other clients can use the information in other ways, for example, codegen can
1600just use expressions that are foldable in any way.</p>
1601
1602<!-- ========== -->
1603<h4>Extensions</h4>
1604<!-- ========== -->
1605
Chris Lattner552de0a2008-11-23 08:16:56 +00001606<p>This section describes how some of the various extensions Clang supports
Chris Lattner7bad1992008-11-16 21:48:07 +00001607interacts with constant evaluation:</p>
1608
1609<ul>
1610<li><b><tt>__extension__</tt></b>: The expression form of this extension causes
1611 any evaluatable subexpression to be accepted as an integer constant
1612 expression.</li>
1613<li><b><tt>__builtin_constant_p</tt></b>: This returns true (as a integer
Chris Lattner28daa532008-12-12 06:55:44 +00001614 constant expression) if the operand is any evaluatable constant. As a
1615 special case, if <tt>__builtin_constant_p</tt> is the (potentially
1616 parenthesized) condition of a conditional operator expression ("?:"), only
Chris Lattner42b83dd2008-12-12 18:00:51 +00001617 the true side of the conditional operator is considered, and it is evaluated
1618 with full constant folding.</li>
Chris Lattner7bad1992008-11-16 21:48:07 +00001619<li><b><tt>__builtin_choose_expr</tt></b>: The condition is required to be an
1620 integer constant expression, but we accept any constant as an "extension of
1621 an extension". This only evaluates one operand depending on which way the
1622 condition evaluates.</li>
1623<li><b><tt>__builtin_classify_type</tt></b>: This always returns an integer
1624 constant expression.</li>
1625<li><b><tt>__builtin_inf,nan,..</tt></b>: These are treated just like a
1626 floating-point literal.</li>
1627<li><b><tt>__builtin_abs,copysign,..</tt></b>: These are constant folded as
1628 general constant expressions.</li>
1629</ul>
1630
1631
1632
1633
Ted Kremenek17a295d2008-06-11 06:19:49 +00001634</div>
1635</body>
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001636</html>