blob: 27232843d31eee499e1dfc9eaf5fa80e7cc4dcbc [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>
164level is used to staple more information onto a previous diagnostics.</p>
165
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>,
168<tt>Error</tt> }) of output <em>levels</em> by the diagnostics subsystem based
169on various configuration options. For example, if the user specifies
170<tt>-pedantic</tt>, <tt>EXTENSION</tt> maps to <tt>Warning</tt>, if they specify
171<tt>-pedantic-errors</tt>, it turns into <tt>Error</tt>. Clang also internally
172supports a fully fine grained mapping mechanism that allows you to map any
173diagnostic that doesn't have <tt>ERRROR</tt> severity to any output level that
174you want. This is used to implement options like <tt>-Wunused_macros</tt>,
175<tt>-Wundef</tt> etc.</p>
176
177<!-- ================= -->
178<h4>The Format String</h4>
179<!-- ================= -->
180
181<p>The format string for the diagnostic is very simple, but it has some power.
182It takes the form of a string in English with markers that indicate where and
183how arguments to the diagnostic are inserted and formatted. For example, here
184are some simple format strings:</p>
185
186<pre>
187 "binary integer literals are an extension"
188 "format string contains '\\0' within the string body"
189 "more '<b>%%</b>' conversions than data arguments"
Chris Lattner545b3682008-11-23 20:27:13 +0000190 "invalid operands to binary expression (<b>%0</b> and <b>%1</b>)"
Chris Lattner62fd2782008-11-22 21:41:31 +0000191 "overloaded '<b>%0</b>' must be a <b>%select{unary|binary|unary or binary}2</b> operator"
192 " (has <b>%1</b> parameter<b>%s1</b>)"
193</pre>
194
195<p>These examples show some important points of format strings. You can use any
196 plain ASCII character in the diagnostic string except "%" without a problem,
197 but these are C strings, so you have to use and be aware of all the C escape
198 sequences (as in the second example). If you want to produce a "%" in the
199 output, use the "%%" escape sequence, like the third diagnostic. Finally,
Chris Lattner552de0a2008-11-23 08:16:56 +0000200 Clang uses the "%...[digit]" sequences to specify where and how arguments to
Chris Lattner62fd2782008-11-22 21:41:31 +0000201 the diagnostic are formatted.</p>
202
203<p>Arguments to the diagnostic are numbered according to how they are specified
204 by the C++ code that <a href="#producingdiag">produces them</a>, and are
205 referenced by <tt>%0</tt> .. <tt>%9</tt>. If you have more than 10 arguments
Chris Lattner552de0a2008-11-23 08:16:56 +0000206 to your diagnostic, you are doing something wrong :). Unlike printf, there
Chris Lattner62fd2782008-11-22 21:41:31 +0000207 is no requirement that arguments to the diagnostic end up in the output in
208 the same order as they are specified, you could have a format string with
209 <tt>"%1 %0"</tt> that swaps them, for example. The text in between the
210 percent and digit are formatting instructions. If there are no instructions,
211 the argument is just turned into a string and substituted in.</p>
212
213<p>Here are some "best practices" for writing the English format string:</p>
214
215<ul>
216<li>Keep the string short. It should ideally fit in the 80 column limit of the
217 <tt>DiagnosticKinds.def</tt> file. This avoids the diagnostic wrapping when
218 printed, and forces you to think about the important point you are conveying
219 with the diagnostic.</li>
220<li>Take advantage of location information. The user will be able to see the
221 line and location of the caret, so you don't need to tell them that the
222 problem is with the 4th argument to the function: just point to it.</li>
223<li>Do not capitalize the diagnostic string, and do not end it with a
224 period.</li>
225<li>If you need to quote something in the diagnostic string, use single
226 quotes.</li>
227</ul>
228
229<p>Diagnostics should never take random English strings as arguments: you
230shouldn't use <tt>"you have a problem with %0"</tt> and pass in things like
231<tt>"your argument"</tt> or <tt>"your return value"</tt> as arguments. Doing
232this prevents <a href="translation">translating</a> the Clang diagnostics to
233other languages (because they'll get random English words in their otherwise
234localized diagnostic). The exceptions to this are C/C++ language keywords
235(e.g. auto, const, mutable, etc) and C/C++ operators (<tt>/=</tt>). Note
236that things like "pointer" and "reference" are not keywords. On the other
237hand, you <em>can</em> include anything that comes from the user's source code,
Chris Lattner552de0a2008-11-23 08:16:56 +0000238including variable names, types, labels, etc. The 'select' format can be
239used to achieve this sort of thing in a localizable way, see below.</p>
Chris Lattner62fd2782008-11-22 21:41:31 +0000240
241<!-- ==================================== -->
242<h4>Formatting a Diagnostic Argument</a></h4>
243<!-- ==================================== -->
244
245<p>Arguments to diagnostics are fully typed internally, and come from a couple
246different classes: integers, types, names, and random strings. Depending on
247the class of the argument, it can be optionally formatted in different ways.
248This gives the DiagnosticClient information about what the argument means
249without requiring it to use a specific presentation (consider this MVC for
250Clang :).</p>
251
252<p>Here are the different diagnostic argument formats currently supported by
253Clang:</p>
254
255<table>
256<tr><td colspan="2"><b>"s" format</b></td></tr>
257<tr><td>Example:</td><td><tt>"requires %1 parameter%s1"</tt></td></tr>
Chris Lattner552de0a2008-11-23 08:16:56 +0000258<tr><td>Class:</td><td>Integers</td></tr>
Chris Lattner62fd2782008-11-22 21:41:31 +0000259<tr><td>Description:</td><td>This is a simple formatter for integers that is
260 useful when producing English diagnostics. When the integer is 1, it prints
261 as nothing. When the integer is not 1, it prints as "s". This allows some
Chris Lattner627b7052008-11-23 00:28:33 +0000262 simple grammatical forms to be to be handled correctly, and eliminates the
263 need to use gross things like <tt>"requires %1 parameter(s)"</tt>.</td></tr>
Chris Lattner62fd2782008-11-22 21:41:31 +0000264
265<tr><td colspan="2"><b>"select" format</b></td></tr>
266<tr><td>Example:</td><td><tt>"must be a %select{unary|binary|unary or binary}2
267 operator"</tt></td></tr>
Chris Lattner552de0a2008-11-23 08:16:56 +0000268<tr><td>Class:</td><td>Integers</td></tr>
Chris Lattnercc543342008-11-22 23:50:47 +0000269<tr><td>Description:</td><td>This format specifier is used to merge multiple
270 related diagnostics together into one common one, without requiring the
Chris Lattner552de0a2008-11-23 08:16:56 +0000271 difference to be specified as an English string argument. Instead of
Chris Lattnercc543342008-11-22 23:50:47 +0000272 specifying the string, the diagnostic gets an integer argument and the
273 format string selects the numbered option. In this case, the "%2" value
274 must be an integer in the range [0..2]. If it is 0, it prints 'unary', if
275 it is 1 it prints 'binary' if it is 2, it prints 'unary or binary'. This
276 allows other language translations to substitute reasonable words (or entire
277 phrases) based on the semantics of the diagnostic instead of having to do
278 things textually.</td></tr>
Chris Lattner62fd2782008-11-22 21:41:31 +0000279
280<tr><td colspan="2"><b>"plural" format</b></td></tr>
Sebastian Redl68168562008-11-22 22:16:45 +0000281<tr><td>Example:</td><td><tt>"you have %1 %plural{1:mouse|:mice}1 connected to
282 your computer"</tt></td></tr>
Chris Lattner552de0a2008-11-23 08:16:56 +0000283<tr><td>Class:</td><td>Integers</td></tr>
Sebastian Redl68168562008-11-22 22:16:45 +0000284<tr><td>Description:</td><td><p>This is a formatter for complex plural forms.
285 It is designed to handle even the requirements of languages with very
286 complex plural forms, as many Baltic languages have. The argument consists
287 of a series of expression/form pairs, separated by ':', where the first form
288 whose expression evaluates to true is the result of the modifier.</p>
289 <p>An expression can be empty, in which case it is always true. See the
290 example at the top. Otherwise, it is a series of one or more numeric
291 conditions, separated by ','. If any condition matches, the expression
292 matches. Each numeric condition can take one of three forms.</p>
293 <ul>
294 <li>number: A simple decimal number matches if the argument is the same
Chris Lattner627b7052008-11-23 00:28:33 +0000295 as the number. Example: <tt>"%plural{1:mouse|:mice}4"</tt></li>
Sebastian Redl68168562008-11-22 22:16:45 +0000296 <li>range: A range in square brackets matches if the argument is within
Chris Lattner552de0a2008-11-23 08:16:56 +0000297 the range. Then range is inclusive on both ends. Example:
Chris Lattner627b7052008-11-23 00:28:33 +0000298 <tt>"%plural{0:none|1:one|[2,5]:some|:many}2"</tt></li>
299 <li>modulo: A modulo operator is followed by a number, and
300 equals sign and either a number or a range. The tests are the
301 same as for plain
Sebastian Redl68168562008-11-22 22:16:45 +0000302 numbers and ranges, but the argument is taken modulo the number first.
Chris Lattner627b7052008-11-23 00:28:33 +0000303 Example: <tt>"%plural{%100=0:even hundred|%100=[1,50]:lower half|:everything
304 else}1"</tt></li>
Sebastian Redl68168562008-11-22 22:16:45 +0000305 </ul>
306 <p>The parser is very unforgiving. A syntax error, even whitespace, will
307 abort, as will a failure to match the argument against any
308 expression.</p></td></tr>
Chris Lattner62fd2782008-11-22 21:41:31 +0000309
Chris Lattner077bf5e2008-11-24 03:33:13 +0000310<tr><td colspan="2"><b>"objcclass" format</b></td></tr>
311<tr><td>Example:</td><td><tt>"method %objcclass0 not found"</tt></td></tr>
312<tr><td>Class:</td><td>DeclarationName</td></tr>
313<tr><td>Description:</td><td><p>This is a simple formatter that indicates the
314 DeclarationName corresponds to an Objective-C class method selector. As
315 such, it prints the selector with a leading '+'.</p></td></tr>
316
317<tr><td colspan="2"><b>"objcinstance" format</b></td></tr>
318<tr><td>Example:</td><td><tt>"method %objcinstance0 not found"</tt></td></tr>
319<tr><td>Class:</td><td>DeclarationName</td></tr>
320<tr><td>Description:</td><td><p>This is a simple formatter that indicates the
321 DeclarationName corresponds to an Objective-C instance method selector. As
322 such, it prints the selector with a leading '-'.</p></td></tr>
323
Chris Lattner62fd2782008-11-22 21:41:31 +0000324</table>
325
Chris Lattnercc543342008-11-22 23:50:47 +0000326<p>It is really easy to add format specifiers to the Clang diagnostics system,
Chris Lattner552de0a2008-11-23 08:16:56 +0000327but they should be discussed before they are added. If you are creating a lot
328of repetitive diagnostics and/or have an idea for a useful formatter, please
329bring it up on the cfe-dev mailing list.</p>
Chris Lattnercc543342008-11-22 23:50:47 +0000330
Chris Lattner62fd2782008-11-22 21:41:31 +0000331<!-- ===================================================== -->
332<h4><a name="#producingdiag">Producing the Diagnostic</a></h4>
333<!-- ===================================================== -->
334
Chris Lattner627b7052008-11-23 00:28:33 +0000335<p>Now that you've created the diagnostic in the DiagnosticKinds.def file, you
Chris Lattner552de0a2008-11-23 08:16:56 +0000336need to write the code that detects the condition in question and emits the
337new diagnostic. Various components of Clang (e.g. the preprocessor, Sema,
Chris Lattner627b7052008-11-23 00:28:33 +0000338etc) provide a helper function named "Diag". It creates a diagnostic and
339accepts the arguments, ranges, and other information that goes along with
340it.</p>
Chris Lattner62fd2782008-11-22 21:41:31 +0000341
Chris Lattner552de0a2008-11-23 08:16:56 +0000342<p>For example, the binary expression error comes from code like this:</p>
Chris Lattner627b7052008-11-23 00:28:33 +0000343
344<pre>
345 if (various things that are bad)
346 Diag(Loc, diag::err_typecheck_invalid_operands)
347 &lt;&lt; lex-&gt;getType() &lt;&lt; rex-&gt;getType()
348 &lt;&lt; lex-&gt;getSourceRange() &lt;&lt; rex-&gt;getSourceRange();
349</pre>
350
351<p>This shows that use of the Diag method: they take a location (a <a
352href="#SourceLocation">SourceLocation</a> object) and a diagnostic enum value
353(which matches the name from DiagnosticKinds.def). If the diagnostic takes
354arguments, they are specified with the &lt;&lt; operator: the first argument
355becomes %0, the second becomes %1, etc. The diagnostic interface allows you to
Chris Lattnerfd408ea2008-11-23 00:42:53 +0000356specify arguments of many different types, including <tt>int</tt> and
357<tt>unsigned</tt> for integer arguments, <tt>const char*</tt> and
358<tt>std::string</tt> for string arguments, <tt>DeclarationName</tt> and
359<tt>const IdentifierInfo*</tt> for names, <tt>QualType</tt> for types, etc.
360SourceRanges are also specified with the &lt;&lt; operator, but do not have a
361specific ordering requirement.</p>
Chris Lattner627b7052008-11-23 00:28:33 +0000362
363<p>As you can see, adding and producing a diagnostic is pretty straightforward.
364The hard part is deciding exactly what you need to say to help the user, picking
365a suitable wording, and providing the information needed to format it correctly.
Chris Lattnerfd408ea2008-11-23 00:42:53 +0000366The good news is that the call site that issues a diagnostic should be
367completely independent of how the diagnostic is formatted and in what language
368it is rendered.
Chris Lattner627b7052008-11-23 00:28:33 +0000369</p>
Chris Lattner62fd2782008-11-22 21:41:31 +0000370
371<!-- ============================================================= -->
372<h4><a name="DiagnosticClient">The DiagnosticClient Interface</a></h4>
373<!-- ============================================================= -->
374
Chris Lattner627b7052008-11-23 00:28:33 +0000375<p>Once code generates a diagnostic with all of the arguments and the rest of
376the relevant information, Clang needs to know what to do with it. As previously
377mentioned, the diagnostic machinery goes through some filtering to map a
378severity onto a diagnostic level, then (assuming the diagnostic is not mapped to
379"<tt>Ignore</tt>") it invokes an object that implements the DiagnosticClient
380interface with the information.</p>
381
382<p>It is possible to implement this interface in many different ways. For
383example, the normal Clang DiagnosticClient (named 'TextDiagnosticPrinter') turns
384the arguments into strings (according to the various formatting rules), prints
385out the file/line/column information and the string, then prints out the line of
386code, the source ranges, and the caret. However, this behavior isn't required.
387</p>
388
389<p>Another implementation of the DiagnosticClient interface is the
Chris Lattner552de0a2008-11-23 08:16:56 +0000390'TextDiagnosticBuffer' class, which is used when Clang is in -verify mode.
Chris Lattnerfd408ea2008-11-23 00:42:53 +0000391Instead of formatting and printing out the diagnostics, this implementation just
392captures and remembers the diagnostics as they fly by. Then -verify compares
Chris Lattner552de0a2008-11-23 08:16:56 +0000393the list of produced diagnostics to the list of expected ones. If they disagree,
Chris Lattnerfd408ea2008-11-23 00:42:53 +0000394it prints out its own output.
Chris Lattner627b7052008-11-23 00:28:33 +0000395</p>
396
Chris Lattnerfd408ea2008-11-23 00:42:53 +0000397<p>There are many other possible implementations of this interface, and this is
398why we prefer diagnostics to pass down rich structured information in arguments.
399For example, an HTML output might want declaration names be linkified to where
400they come from in the source. Another example is that a GUI might let you click
401on typedefs to expand them. This application would want to pass significantly
402more information about types through to the GUI than a simple flat string. The
403interface allows this to happen.</p>
Chris Lattner62fd2782008-11-22 21:41:31 +0000404
405<!-- ====================================================== -->
406<h4><a name="translation">Adding Translations to Clang</a></h4>
407<!-- ====================================================== -->
408
Chris Lattner627b7052008-11-23 00:28:33 +0000409<p>Not possible yet! Diagnostic strings should be written in UTF-8, the client
Chris Lattnerfd408ea2008-11-23 00:42:53 +0000410can translate to the relevant code page if needed. Each translation completely
411replaces the format string for the diagnostic.</p>
Chris Lattner62fd2782008-11-22 21:41:31 +0000412
413
Chris Lattner86920d32007-07-31 05:42:17 +0000414<!-- ======================================================================= -->
415<h3 id="SourceLocation">The SourceLocation and SourceManager classes</h3>
416<!-- ======================================================================= -->
417
418<p>Strangely enough, the SourceLocation class represents a location within the
419source code of the program. Important design points include:</p>
420
421<ol>
422<li>sizeof(SourceLocation) must be extremely small, as these are embedded into
423 many AST nodes and are passed around often. Currently it is 32 bits.</li>
424<li>SourceLocation must be a simple value object that can be efficiently
425 copied.</li>
426<li>We should be able to represent a source location for any byte of any input
427 file. This includes in the middle of tokens, in whitespace, in trigraphs,
428 etc.</li>
429<li>A SourceLocation must encode the current #include stack that was active when
430 the location was processed. For example, if the location corresponds to a
431 token, it should contain the set of #includes active when the token was
432 lexed. This allows us to print the #include stack for a diagnostic.</li>
433<li>SourceLocation must be able to describe macro expansions, capturing both
434 the ultimate instantiation point and the source of the original character
435 data.</li>
436</ol>
437
438<p>In practice, the SourceLocation works together with the SourceManager class
Chris Lattner18376dd2009-01-16 07:00:50 +0000439to encode two pieces of information about a location: it's spelling location
Chris Lattner88054de2009-01-16 07:15:35 +0000440and it's instantiation location. For most tokens, these will be the same. However,
Chris Lattner86920d32007-07-31 05:42:17 +0000441for a macro expansion (or tokens that came from a _Pragma directive) these will
442describe the location of the characters corresponding to the token and the
443location where the token was used (i.e. the macro instantiation point or the
444location of the _Pragma itself).</p>
445
Chris Lattner3fcbb892008-11-23 08:32:53 +0000446<p>For efficiency, we only track one level of macro instantiations: if a token was
Chris Lattner86920d32007-07-31 05:42:17 +0000447produced by multiple instantiations, we only track the source and ultimate
448destination. Though we could track the intermediate instantiation points, this
449would require extra bookkeeping and no known client would benefit substantially
450from this.</p>
451
Chris Lattner552de0a2008-11-23 08:16:56 +0000452<p>The Clang front-end inherently depends on the location of a token being
Chris Lattner86920d32007-07-31 05:42:17 +0000453tracked correctly. If it is ever incorrect, the front-end may get confused and
454die. The reason for this is that the notion of the 'spelling' of a Token in
Chris Lattner552de0a2008-11-23 08:16:56 +0000455Clang depends on being able to find the original input characters for the token.
Chris Lattner18376dd2009-01-16 07:00:50 +0000456This concept maps directly to the "spelling location" for the token.</p>
Chris Lattner86920d32007-07-31 05:42:17 +0000457
458<!-- ======================================================================= -->
459<h2 id="liblex">The Lexer and Preprocessor Library</h2>
460<!-- ======================================================================= -->
461
462<p>The Lexer library contains several tightly-connected classes that are involved
463with the nasty process of lexing and preprocessing C source code. The main
464interface to this library for outside clients is the large <a
465href="#Preprocessor">Preprocessor</a> class.
466It contains the various pieces of state that are required to coherently read
467tokens out of a translation unit.</p>
468
469<p>The core interface to the Preprocessor object (once it is set up) is the
470Preprocessor::Lex method, which returns the next <a href="#Token">Token</a> from
471the preprocessor stream. There are two types of token providers that the
472preprocessor is capable of reading from: a buffer lexer (provided by the <a
473href="#Lexer">Lexer</a> class) and a buffered token stream (provided by the <a
Chris Lattner79281252008-03-09 02:27:26 +0000474href="#TokenLexer">TokenLexer</a> class).
Chris Lattner86920d32007-07-31 05:42:17 +0000475
476
477<!-- ======================================================================= -->
478<h3 id="Token">The Token class</h3>
479<!-- ======================================================================= -->
480
481<p>The Token class is used to represent a single lexed token. Tokens are
482intended to be used by the lexer/preprocess and parser libraries, but are not
483intended to live beyond them (for example, they should not live in the ASTs).<p>
484
485<p>Tokens most often live on the stack (or some other location that is efficient
486to access) as the parser is running, but occasionally do get buffered up. For
487example, macro definitions are stored as a series of tokens, and the C++
Chris Lattner3fcbb892008-11-23 08:32:53 +0000488front-end periodically needs to buffer tokens up for tentative parsing and
Chris Lattner86920d32007-07-31 05:42:17 +0000489various pieces of look-ahead. As such, the size of a Token matter. On a 32-bit
490system, sizeof(Token) is currently 16 bytes.</p>
491
Chris Lattner3932fe02009-01-06 06:02:08 +0000492<p>Tokens occur in two forms: "<a href="#AnnotationToken">Annotation
493Tokens</a>" and normal tokens. Normal tokens are those returned by the lexer,
494annotation tokens represent semantic information and are produced by the parser,
495replacing normal tokens in the token stream. Normal tokens contain the
496following information:</p>
Chris Lattner86920d32007-07-31 05:42:17 +0000497
498<ul>
499<li><b>A SourceLocation</b> - This indicates the location of the start of the
500token.</li>
501
502<li><b>A length</b> - This stores the length of the token as stored in the
503SourceBuffer. For tokens that include them, this length includes trigraphs and
504escaped newlines which are ignored by later phases of the compiler. By pointing
505into the original source buffer, it is always possible to get the original
506spelling of a token completely accurately.</li>
507
508<li><b>IdentifierInfo</b> - If a token takes the form of an identifier, and if
509identifier lookup was enabled when the token was lexed (e.g. the lexer was not
510reading in 'raw' mode) this contains a pointer to the unique hash value for the
511identifier. Because the lookup happens before keyword identification, this
512field is set even for language keywords like 'for'.</li>
513
514<li><b>TokenKind</b> - This indicates the kind of token as classified by the
515lexer. This includes things like <tt>tok::starequal</tt> (for the "*="
516operator), <tt>tok::ampamp</tt> for the "&amp;&amp;" token, and keyword values
517(e.g. <tt>tok::kw_for</tt>) for identifiers that correspond to keywords. Note
518that some tokens can be spelled multiple ways. For example, C++ supports
519"operator keywords", where things like "and" are treated exactly like the
520"&amp;&amp;" operator. In these cases, the kind value is set to
521<tt>tok::ampamp</tt>, which is good for the parser, which doesn't have to
522consider both forms. For something that cares about which form is used (e.g.
523the preprocessor 'stringize' operator) the spelling indicates the original
524form.</li>
525
526<li><b>Flags</b> - There are currently four flags tracked by the
527lexer/preprocessor system on a per-token basis:
528
529 <ol>
530 <li><b>StartOfLine</b> - This was the first token that occurred on its input
531 source line.</li>
532 <li><b>LeadingSpace</b> - There was a space character either immediately
533 before the token or transitively before the token as it was expanded
534 through a macro. The definition of this flag is very closely defined by
535 the stringizing requirements of the preprocessor.</li>
536 <li><b>DisableExpand</b> - This flag is used internally to the preprocessor to
537 represent identifier tokens which have macro expansion disabled. This
538 prevents them from being considered as candidates for macro expansion ever
539 in the future.</li>
540 <li><b>NeedsCleaning</b> - This flag is set if the original spelling for the
541 token includes a trigraph or escaped newline. Since this is uncommon,
542 many pieces of code can fast-path on tokens that did not need cleaning.
543 </p>
544 </ol>
545</li>
546</ul>
547
Chris Lattner3932fe02009-01-06 06:02:08 +0000548<p>One interesting (and somewhat unusual) aspect of normal tokens is that they
549don't contain any semantic information about the lexed value. For example, if
550the token was a pp-number token, we do not represent the value of the number
551that was lexed (this is left for later pieces of code to decide). Additionally,
552the lexer library has no notion of typedef names vs variable names: both are
Chris Lattner86920d32007-07-31 05:42:17 +0000553returned as identifiers, and the parser is left to decide whether a specific
554identifier is a typedef or a variable (tracking this requires scope information
Chris Lattner3932fe02009-01-06 06:02:08 +0000555among other things). The parser can do this translation by replacing tokens
556returned by the preprocessor with "Annotation Tokens".</p>
557
558<!-- ======================================================================= -->
559<h3 id="AnnotationToken">Annotation Tokens</h3>
560<!-- ======================================================================= -->
561
562<p>Annotation Tokens are tokens that are synthesized by the parser and injected
563into the preprocessor's token stream (replacing existing tokens) to record
564semantic information found by the parser. For example, if "foo" is found to be
565a typedef, the "foo" <tt>tok::identifier</tt> token is replaced with an
566<tt>tok::annot_typename</tt>. This is useful for a couple of reasons: 1) this
567makes it easy to handle qualified type names (e.g. "foo::bar::baz&lt;42&gt;::t")
568in C++ as a single "token" in the parser. 2) if the parser backtracks, the
569reparse does not need to redo semantic analysis to determine whether a token
570sequence is a variable, type, template, etc.</p>
571
572<p>Annotation Tokens are created by the parser and reinjected into the parser's
573token stream (when backtracking is enabled). Because they can only exist in
574tokens that the preprocessor-proper is done with, it doesn't need to keep around
575flags like "start of line" that the preprocessor uses to do its job.
576Additionally, an annotation token may "cover" a sequence of preprocessor tokens
577(e.g. <tt>a::b::c</tt> is five preprocessor tokens). As such, the valid fields
578of an annotation token are different than the fields for a normal token (but
579they are multiplexed into the normal Token fields):</p>
580
581<ul>
582<li><b>SourceLocation "Location"</b> - The SourceLocation for the annotation
583token indicates the first token replaced by the annotation token. In the example
584above, it would be the location of the "a" identifier.</li>
585
586<li><b>SourceLocation "AnnotationEndLoc"</b> - This holds the location of the
587last token replaced with the annotation token. In the example above, it would
588be the location of the "c" identifier.</li>
589
590<li><b>void* "AnnotationValue"</b> - This contains an opaque object that the
591parser gets from Sema through an Actions module, it is passed around and Sema
592intepretes it, based on the type of annotation token.</li>
593
594<li><b>TokenKind "Kind"</b> - This indicates the kind of Annotation token this
595is. See below for the different valid kinds.</li>
596</ul>
597
598<p>Annotation tokens currently come in three kinds:</p>
599
600<ol>
601<li><b>tok::annot_typename</b>: This annotation token represents a
602resolved typename token that is potentially qualified. The AnnotationValue
603field contains a pointer returned by Action::isTypeName(). In the case of the
604Sema actions module, this is a <tt>Decl*</tt> for the type.</li>
605
606<li><b>tok::annot_cxxscope</b>: This annotation token represents a C++ scope
607specifier, such as "A::B::". This corresponds to the grammar productions "::"
608and ":: [opt] nested-name-specifier". The AnnotationValue pointer is returned
609by the Action::ActOnCXXGlobalScopeSpecifier and
610Action::ActOnCXXNestedNameSpecifier callbacks. In the case of Sema, this is a
611<tt>DeclContext*</tt>.</li>
612
613<li><b>tok::annot_template_id</b>: This annotation token represents a C++
614template-id such as "foo&lt;int, 4&gt;", which may refer to a function or type
615depending on whether foo is a function template or class template. The
616AnnotationValue pointer is a pointer to a malloc'd TemplateIdAnnotation object.
617FIXME: I don't think the parsing logic is right for this. Shouldn't type
618templates be turned into annot_typename??</li>
619
620</ol>
621
Cedric Venetda76b282009-01-06 16:22:54 +0000622<p>As mentioned above, annotation tokens are not returned by the preprocessor,
Chris Lattner3932fe02009-01-06 06:02:08 +0000623they are formed on demand by the parser. This means that the parser has to be
624aware of cases where an annotation could occur and form it where appropriate.
625This is somewhat similar to how the parser handles Translation Phase 6 of C99:
626String Concatenation (see C99 5.1.1.2). In the case of string concatenation,
627the preprocessor just returns distinct tok::string_literal and
628tok::wide_string_literal tokens and the parser eats a sequence of them wherever
629the grammar indicates that a string literal can occur.</p>
630
631<p>In order to do this, whenever the parser expects a tok::identifier or
632tok::coloncolon, it should call the TryAnnotateTypeOrScopeToken or
633TryAnnotateCXXScopeToken methods to form the annotation token. These methods
634will maximally form the specified annotation tokens and replace the current
635token with them, if applicable. If the current tokens is not valid for an
636annotation token, it will remain an identifier or :: token.</p>
637
638
Chris Lattner86920d32007-07-31 05:42:17 +0000639
640<!-- ======================================================================= -->
641<h3 id="Lexer">The Lexer class</h3>
642<!-- ======================================================================= -->
643
644<p>The Lexer class provides the mechanics of lexing tokens out of a source
645buffer and deciding what they mean. The Lexer is complicated by the fact that
646it operates on raw buffers that have not had spelling eliminated (this is a
647necessity to get decent performance), but this is countered with careful coding
648as well as standard performance techniques (for example, the comment handling
649code is vectorized on X86 and PowerPC hosts).</p>
650
651<p>The lexer has a couple of interesting modal features:</p>
652
653<ul>
654<li>The lexer can operate in 'raw' mode. This mode has several features that
655 make it possible to quickly lex the file (e.g. it stops identifier lookup,
656 doesn't specially handle preprocessor tokens, handles EOF differently, etc).
657 This mode is used for lexing within an "<tt>#if 0</tt>" block, for
658 example.</li>
659<li>The lexer can capture and return comments as tokens. This is required to
660 support the -C preprocessor mode, which passes comments through, and is
661 used by the diagnostic checker to identifier expect-error annotations.</li>
662<li>The lexer can be in ParsingFilename mode, which happens when preprocessing
Chris Lattner84386242007-09-16 19:25:23 +0000663 after reading a #include directive. This mode changes the parsing of '&lt;'
Chris Lattner86920d32007-07-31 05:42:17 +0000664 to return an "angled string" instead of a bunch of tokens for each thing
665 within the filename.</li>
666<li>When parsing a preprocessor directive (after "<tt>#</tt>") the
667 ParsingPreprocessorDirective mode is entered. This changes the parser to
668 return EOM at a newline.</li>
669<li>The Lexer uses a LangOptions object to know whether trigraphs are enabled,
670 whether C++ or ObjC keywords are recognized, etc.</li>
671</ul>
672
673<p>In addition to these modes, the lexer keeps track of a couple of other
674 features that are local to a lexed buffer, which change as the buffer is
675 lexed:</p>
676
677<ul>
678<li>The Lexer uses BufferPtr to keep track of the current character being
679 lexed.</li>
680<li>The Lexer uses IsAtStartOfLine to keep track of whether the next lexed token
681 will start with its "start of line" bit set.</li>
682<li>The Lexer keeps track of the current #if directives that are active (which
683 can be nested).</li>
684<li>The Lexer keeps track of an <a href="#MultipleIncludeOpt">
685 MultipleIncludeOpt</a> object, which is used to
686 detect whether the buffer uses the standard "<tt>#ifndef XX</tt> /
687 <tt>#define XX</tt>" idiom to prevent multiple inclusion. If a buffer does,
688 subsequent includes can be ignored if the XX macro is defined.</li>
689</ul>
690
691<!-- ======================================================================= -->
Chris Lattner79281252008-03-09 02:27:26 +0000692<h3 id="TokenLexer">The TokenLexer class</h3>
Chris Lattner86920d32007-07-31 05:42:17 +0000693<!-- ======================================================================= -->
694
Chris Lattner79281252008-03-09 02:27:26 +0000695<p>The TokenLexer class is a token provider that returns tokens from a list
Chris Lattner86920d32007-07-31 05:42:17 +0000696of tokens that came from somewhere else. It typically used for two things: 1)
697returning tokens from a macro definition as it is being expanded 2) returning
698tokens from an arbitrary buffer of tokens. The later use is used by _Pragma and
699will most likely be used to handle unbounded look-ahead for the C++ parser.</p>
700
701<!-- ======================================================================= -->
702<h3 id="MultipleIncludeOpt">The MultipleIncludeOpt class</h3>
703<!-- ======================================================================= -->
704
705<p>The MultipleIncludeOpt class implements a really simple little state machine
706that is used to detect the standard "<tt>#ifndef XX</tt> / <tt>#define XX</tt>"
707idiom that people typically use to prevent multiple inclusion of headers. If a
708buffer uses this idiom and is subsequently #include'd, the preprocessor can
709simply check to see whether the guarding condition is defined or not. If so,
710the preprocessor can completely ignore the include of the header.</p>
711
712
713
714<!-- ======================================================================= -->
715<h2 id="libparse">The Parser Library</h2>
716<!-- ======================================================================= -->
717
718<!-- ======================================================================= -->
719<h2 id="libast">The AST Library</h2>
720<!-- ======================================================================= -->
721
722<!-- ======================================================================= -->
723<h3 id="Type">The Type class and its subclasses</h3>
724<!-- ======================================================================= -->
725
726<p>The Type class (and its subclasses) are an important part of the AST. Types
727are accessed through the ASTContext class, which implicitly creates and uniques
728them as they are needed. Types have a couple of non-obvious features: 1) they
729do not capture type qualifiers like const or volatile (See
730<a href="#QualType">QualType</a>), and 2) they implicitly capture typedef
Chris Lattner8a2bc622007-07-31 06:37:39 +0000731information. Once created, types are immutable (unlike decls).</p>
Chris Lattner86920d32007-07-31 05:42:17 +0000732
733<p>Typedefs in C make semantic analysis a bit more complex than it would
734be without them. The issue is that we want to capture typedef information
735and represent it in the AST perfectly, but the semantics of operations need to
736"see through" typedefs. For example, consider this code:</p>
737
738<code>
739void func() {<br>
Bill Wendling30d17752007-10-06 01:56:01 +0000740&nbsp;&nbsp;typedef int foo;<br>
741&nbsp;&nbsp;foo X, *Y;<br>
742&nbsp;&nbsp;typedef foo* bar;<br>
743&nbsp;&nbsp;bar Z;<br>
744&nbsp;&nbsp;*X; <i>// error</i><br>
745&nbsp;&nbsp;**Y; <i>// error</i><br>
746&nbsp;&nbsp;**Z; <i>// error</i><br>
Chris Lattner86920d32007-07-31 05:42:17 +0000747}<br>
748</code>
749
750<p>The code above is illegal, and thus we expect there to be diagnostics emitted
751on the annotated lines. In this example, we expect to get:</p>
752
753<pre>
Chris Lattner8a2bc622007-07-31 06:37:39 +0000754<b>test.c:6:1: error: indirection requires pointer operand ('foo' invalid)</b>
Chris Lattner86920d32007-07-31 05:42:17 +0000755*X; // error
756<font color="blue">^~</font>
Chris Lattner8a2bc622007-07-31 06:37:39 +0000757<b>test.c:7:1: error: indirection requires pointer operand ('foo' invalid)</b>
Chris Lattner86920d32007-07-31 05:42:17 +0000758**Y; // error
759<font color="blue">^~~</font>
Chris Lattner8a2bc622007-07-31 06:37:39 +0000760<b>test.c:8:1: error: indirection requires pointer operand ('foo' invalid)</b>
761**Z; // error
762<font color="blue">^~~</font>
Chris Lattner86920d32007-07-31 05:42:17 +0000763</pre>
764
765<p>While this example is somewhat silly, it illustrates the point: we want to
766retain typedef information where possible, so that we can emit errors about
767"<tt>std::string</tt>" instead of "<tt>std::basic_string&lt;char, std:...</tt>".
768Doing this requires properly keeping typedef information (for example, the type
769of "X" is "foo", not "int"), and requires properly propagating it through the
Chris Lattner8a2bc622007-07-31 06:37:39 +0000770various operators (for example, the type of *Y is "foo", not "int"). In order
771to retain this information, the type of these expressions is an instance of the
772TypedefType class, which indicates that the type of these expressions is a
773typedef for foo.
774</p>
Chris Lattner86920d32007-07-31 05:42:17 +0000775
Chris Lattner8a2bc622007-07-31 06:37:39 +0000776<p>Representing types like this is great for diagnostics, because the
777user-specified type is always immediately available. There are two problems
778with this: first, various semantic checks need to make judgements about the
Chris Lattner33fc68a2007-07-31 18:54:50 +0000779<em>actual structure</em> of a type, ignoring typdefs. Second, we need an
780efficient way to query whether two types are structurally identical to each
781other, ignoring typedefs. The solution to both of these problems is the idea of
Chris Lattner8a2bc622007-07-31 06:37:39 +0000782canonical types.</p>
Chris Lattner86920d32007-07-31 05:42:17 +0000783
Chris Lattner62fd2782008-11-22 21:41:31 +0000784<!-- =============== -->
Chris Lattner8a2bc622007-07-31 06:37:39 +0000785<h4>Canonical Types</h4>
Chris Lattner62fd2782008-11-22 21:41:31 +0000786<!-- =============== -->
Chris Lattner86920d32007-07-31 05:42:17 +0000787
Chris Lattner8a2bc622007-07-31 06:37:39 +0000788<p>Every instance of the Type class contains a canonical type pointer. For
789simple types with no typedefs involved (e.g. "<tt>int</tt>", "<tt>int*</tt>",
790"<tt>int**</tt>"), the type just points to itself. For types that have a
791typedef somewhere in their structure (e.g. "<tt>foo</tt>", "<tt>foo*</tt>",
792"<tt>foo**</tt>", "<tt>bar</tt>"), the canonical type pointer points to their
793structurally equivalent type without any typedefs (e.g. "<tt>int</tt>",
794"<tt>int*</tt>", "<tt>int**</tt>", and "<tt>int*</tt>" respectively).</p>
Chris Lattner86920d32007-07-31 05:42:17 +0000795
Chris Lattner8a2bc622007-07-31 06:37:39 +0000796<p>This design provides a constant time operation (dereferencing the canonical
797type pointer) that gives us access to the structure of types. For example,
798we can trivially tell that "bar" and "foo*" are the same type by dereferencing
799their canonical type pointers and doing a pointer comparison (they both point
800to the single "<tt>int*</tt>" type).</p>
801
802<p>Canonical types and typedef types bring up some complexities that must be
803carefully managed. Specifically, the "isa/cast/dyncast" operators generally
804shouldn't be used in code that is inspecting the AST. For example, when type
805checking the indirection operator (unary '*' on a pointer), the type checker
806must verify that the operand has a pointer type. It would not be correct to
807check that with "<tt>isa&lt;PointerType&gt;(SubExpr-&gt;getType())</tt>",
808because this predicate would fail if the subexpression had a typedef type.</p>
809
810<p>The solution to this problem are a set of helper methods on Type, used to
811check their properties. In this case, it would be correct to use
812"<tt>SubExpr-&gt;getType()-&gt;isPointerType()</tt>" to do the check. This
813predicate will return true if the <em>canonical type is a pointer</em>, which is
814true any time the type is structurally a pointer type. The only hard part here
815is remembering not to use the <tt>isa/cast/dyncast</tt> operations.</p>
816
817<p>The second problem we face is how to get access to the pointer type once we
818know it exists. To continue the example, the result type of the indirection
819operator is the pointee type of the subexpression. In order to determine the
820type, we need to get the instance of PointerType that best captures the typedef
821information in the program. If the type of the expression is literally a
822PointerType, we can return that, otherwise we have to dig through the
823typedefs to find the pointer type. For example, if the subexpression had type
824"<tt>foo*</tt>", we could return that type as the result. If the subexpression
825had type "<tt>bar</tt>", we want to return "<tt>foo*</tt>" (note that we do
826<em>not</em> want "<tt>int*</tt>"). In order to provide all of this, Type has
Chris Lattner11406c12007-07-31 16:50:51 +0000827a getAsPointerType() method that checks whether the type is structurally a
Chris Lattner8a2bc622007-07-31 06:37:39 +0000828PointerType and, if so, returns the best one. If not, it returns a null
829pointer.</p>
830
831<p>This structure is somewhat mystical, but after meditating on it, it will
832make sense to you :).</p>
Chris Lattner86920d32007-07-31 05:42:17 +0000833
834<!-- ======================================================================= -->
835<h3 id="QualType">The QualType class</h3>
836<!-- ======================================================================= -->
837
838<p>The QualType class is designed as a trivial value class that is small,
839passed by-value and is efficient to query. The idea of QualType is that it
840stores the type qualifiers (const, volatile, restrict) separately from the types
841themselves: QualType is conceptually a pair of "Type*" and bits for the type
842qualifiers.</p>
843
844<p>By storing the type qualifiers as bits in the conceptual pair, it is
845extremely efficient to get the set of qualifiers on a QualType (just return the
846field of the pair), add a type qualifier (which is a trivial constant-time
847operation that sets a bit), and remove one or more type qualifiers (just return
848a QualType with the bitfield set to empty).</p>
849
850<p>Further, because the bits are stored outside of the type itself, we do not
851need to create duplicates of types with different sets of qualifiers (i.e. there
852is only a single heap allocated "int" type: "const int" and "volatile const int"
853both point to the same heap allocated "int" type). This reduces the heap size
854used to represent bits and also means we do not have to consider qualifiers when
855uniquing types (<a href="#Type">Type</a> does not even contain qualifiers).</p>
856
857<p>In practice, on hosts where it is safe, the 3 type qualifiers are stored in
858the low bit of the pointer to the Type object. This means that QualType is
859exactly the same size as a pointer, and this works fine on any system where
860malloc'd objects are at least 8 byte aligned.</p>
Ted Kremenek8bc05712007-10-10 23:01:43 +0000861
862<!-- ======================================================================= -->
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000863<h3 id="DeclarationName">Declaration names</h3>
864<!-- ======================================================================= -->
865
866<p>The <tt>DeclarationName</tt> class represents the name of a
867 declaration in Clang. Declarations in the C family of languages can
Chris Lattner3fcbb892008-11-23 08:32:53 +0000868 take several different forms. Most declarations are named by
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000869 simple identifiers, e.g., "<code>f</code>" and "<code>x</code>" in
870 the function declaration <code>f(int x)</code>. In C++, declaration
871 names can also name class constructors ("<code>Class</code>"
872 in <code>struct Class { Class(); }</code>), class destructors
873 ("<code>~Class</code>"), overloaded operator names ("operator+"),
874 and conversion functions ("<code>operator void const *</code>"). In
875 Objective-C, declaration names can refer to the names of Objective-C
876 methods, which involve the method name and the parameters,
Chris Lattner3fcbb892008-11-23 08:32:53 +0000877 collectively called a <i>selector</i>, e.g.,
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000878 "<code>setWidth:height:</code>". Since all of these kinds of
Chris Lattner3fcbb892008-11-23 08:32:53 +0000879 entities - variables, functions, Objective-C methods, C++
880 constructors, destructors, and operators - are represented as
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000881 subclasses of Clang's common <code>NamedDecl</code>
882 class, <code>DeclarationName</code> is designed to efficiently
883 represent any kind of name.</p>
884
885<p>Given
886 a <code>DeclarationName</code> <code>N</code>, <code>N.getNameKind()</code>
Douglas Gregor2def4832008-11-17 20:34:05 +0000887 will produce a value that describes what kind of name <code>N</code>
Douglas Gregore94ca9e42008-11-18 14:39:36 +0000888 stores. There are 8 options (all of the names are inside
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000889 the <code>DeclarationName</code> class)</p>
890<dl>
891 <dt>Identifier</dt>
892 <dd>The name is a simple
893 identifier. Use <code>N.getAsIdentifierInfo()</code> to retrieve the
894 corresponding <code>IdentifierInfo*</code> pointing to the actual
895 identifier. Note that C++ overloaded operators (e.g.,
896 "<code>operator+</code>") are represented as special kinds of
897 identifiers. Use <code>IdentifierInfo</code>'s <code>getOverloadedOperatorID</code>
898 function to determine whether an identifier is an overloaded
899 operator name.</dd>
900
901 <dt>ObjCZeroArgSelector, ObjCOneArgSelector,
902 ObjCMultiArgSelector</dt>
903 <dd>The name is an Objective-C selector, which can be retrieved as a
904 <code>Selector</code> instance
905 via <code>N.getObjCSelector()</code>. The three possible name
906 kinds for Objective-C reflect an optimization within
907 the <code>DeclarationName</code> class: both zero- and
908 one-argument selectors are stored as a
909 masked <code>IdentifierInfo</code> pointer, and therefore require
910 very little space, since zero- and one-argument selectors are far
911 more common than multi-argument selectors (which use a different
912 structure).</dd>
913
914 <dt>CXXConstructorName</dt>
915 <dd>The name is a C++ constructor
916 name. Use <code>N.getCXXNameType()</code> to retrieve
917 the <a href="#QualType">type</a> that this constructor is meant to
918 construct. The type is always the canonical type, since all
919 constructors for a given type have the same name.</dd>
920
921 <dt>CXXDestructorName</dt>
922 <dd>The name is a C++ destructor
923 name. Use <code>N.getCXXNameType()</code> to retrieve
924 the <a href="#QualType">type</a> whose destructor is being
925 named. This type is always a canonical type.</dd>
926
927 <dt>CXXConversionFunctionName</dt>
928 <dd>The name is a C++ conversion function. Conversion functions are
929 named according to the type they convert to, e.g., "<code>operator void
930 const *</code>". Use <code>N.getCXXNameType()</code> to retrieve
931 the type that this conversion function converts to. This type is
932 always a canonical type.</dd>
Douglas Gregore94ca9e42008-11-18 14:39:36 +0000933
934 <dt>CXXOperatorName</dt>
935 <dd>The name is a C++ overloaded operator name. Overloaded operators
936 are named according to their spelling, e.g.,
937 "<code>operator+</code>" or "<code>operator new
938 []</code>". Use <code>N.getCXXOverloadedOperator()</code> to
939 retrieve the overloaded operator (a value of
940 type <code>OverloadedOperatorKind</code>).</dd>
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000941</dl>
942
943<p><code>DeclarationName</code>s are cheap to create, copy, and
944 compare. They require only a single pointer's worth of storage in
Douglas Gregore94ca9e42008-11-18 14:39:36 +0000945 the common cases (identifiers, zero-
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000946 and one-argument Objective-C selectors) and use dense, uniqued
947 storage for the other kinds of
948 names. Two <code>DeclarationName</code>s can be compared for
949 equality (<code>==</code>, <code>!=</code>) using a simple bitwise
950 comparison, can be ordered
951 with <code>&lt;</code>, <code>&gt;</code>, <code>&lt;=</code>,
952 and <code>&gt;=</code> (which provide a lexicographical ordering for
953 normal identifiers but an unspecified ordering for other kinds of
954 names), and can be placed into LLVM <code>DenseMap</code>s
955 and <code>DenseSet</code>s.</p>
956
957<p><code>DeclarationName</code> instances can be created in different
958 ways depending on what kind of name the instance will store. Normal
Douglas Gregore94ca9e42008-11-18 14:39:36 +0000959 identifiers (<code>IdentifierInfo</code> pointers) and Objective-C selectors
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000960 (<code>Selector</code>) can be implicitly converted
961 to <code>DeclarationName</code>s. Names for C++ constructors,
Douglas Gregore94ca9e42008-11-18 14:39:36 +0000962 destructors, conversion functions, and overloaded operators can be retrieved from
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000963 the <code>DeclarationNameTable</code>, an instance of which is
964 available as <code>ASTContext::DeclarationNames</code>. The member
965 functions <code>getCXXConstructorName</code>, <code>getCXXDestructorName</code>,
Douglas Gregore94ca9e42008-11-18 14:39:36 +0000966 <code>getCXXConversionFunctionName</code>, and <code>getCXXOperatorName</code>, respectively,
967 return <code>DeclarationName</code> instances for the four kinds of
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000968 C++ special function names.</p>
969
970<!-- ======================================================================= -->
Douglas Gregor074149e2009-01-05 19:45:36 +0000971<h3 id="DeclContext">Declaration contexts</h3>
972<!-- ======================================================================= -->
973<p>Every declaration in a program exists within some <i>declaration
974 context</i>, such as a translation unit, namespace, class, or
975 function. Declaration contexts in Clang are represented by
976 the <code>DeclContext</code> class, from which the various
977 declaration-context AST nodes
978 (<code>TranslationUnitDecl</code>, <code>NamespaceDecl</code>, <code>RecordDecl</code>, <code>FunctionDecl</code>,
979 etc.) will derive. The <code>DeclContext</code> class provides
980 several facilities common to each declaration context:</p>
981<dl>
982 <dt>Source-centric vs. Semantics-centric View of Declarations</dt>
983 <dd><code>DeclContext</code> provides two views of the declarations
984 stored within a declaration context. The source-centric view
985 accurately represents the program source code as written, including
986 multiple declarations of entities where present (see the
987 section <a href="#Redeclarations">Redeclarations and
988 Overloads</a>), while the semantics-centric view represents the
989 program semantics. The two views are kept synchronized by semantic
990 analysis while the ASTs are being constructed.</dd>
991
992 <dt>Storage of declarations within that context</dt>
993 <dd>Every declaration context can contain some number of
994 declarations. For example, a C++ class (represented
995 by <code>RecordDecl</code>) contains various member functions,
996 fields, nested types, and so on. All of these declarations will be
997 stored within the <code>DeclContext</code>, and one can iterate
998 over the declarations via
999 [<code>DeclContext::decls_begin()</code>,
1000 <code>DeclContext::decls_end()</code>). This mechanism provides
1001 the source-centric view of declarations in the context.</dd>
1002
1003 <dt>Lookup of declarations within that context</dt>
1004 <dd>The <code>DeclContext</code> structure provides efficient name
1005 lookup for names within that declaration context. For example,
1006 if <code>N</code> is a namespace we can look for the
1007 name <code>N::f</code>
1008 using <code>DeclContext::lookup</code>. The lookup itself is
1009 based on a lazily-constructed array (for declaration contexts
1010 with a small number of declarations) or hash table (for
1011 declaration contexts with more declarations). The lookup
1012 operation provides the semantics-centric view of the declarations
1013 in the context.</dd>
1014
1015 <dt>Ownership of declarations</dt>
1016 <dd>The <code>DeclContext</code> owns all of the declarations that
1017 were declared within its declaration context, and is responsible
1018 for the management of their memory as well as their
1019 (de-)serialization.</dd>
1020</dl>
1021
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001022<p>All declarations are stored within a declaration context, and one
1023 can query
1024 information about the context in which each declaration lives. One
Douglas Gregor074149e2009-01-05 19:45:36 +00001025 can retrieve the <code>DeclContext</code> that contains a
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001026 particular <code>Decl</code>
1027 using <code>Decl::getDeclContext</code>. However, see the
Douglas Gregor074149e2009-01-05 19:45:36 +00001028 section <a href="#LexicalAndSemanticContexts">Lexical and Semantic
1029 Contexts</a> for more information about how to interpret this
1030 context information.</p>
1031
1032<h4 id="Redeclarations">Redeclarations and Overloads</h4>
1033<p>Within a translation unit, it is common for an entity to be
1034declared several times. For example, we might declare a function "f"
1035 and then later re-declare it as part of an inlined definition:</p>
1036
1037<pre>
1038void f(int x, int y, int z = 1);
1039
1040inline void f(int x, int y, int z) { /* ... */ }
1041</pre>
1042
1043<p>The representation of "f" differs in the source-centric and
1044 semantics-centric views of a declaration context. In the
1045 source-centric view, all redeclarations will be present, in the
1046 order they occurred in the source code, making
1047 this view suitable for clients that wish to see the structure of
1048 the source code. In the semantics-centric view, only the most recent "f"
1049 will be found by the lookup, since it effectively replaces the first
1050 declaration of "f".</p>
1051
1052<p>In the semantics-centric view, overloading of functions is
1053 represented explicitly. For example, given two declarations of a
1054 function "g" that are overloaded, e.g.,</p>
1055<pre>
1056void g();
1057void g(int);
1058</pre>
1059<p>the <code>DeclContext::lookup</code> operation will return
1060 an <code>OverloadedFunctionDecl</code> that contains both
1061 declarations of "g". Clients that perform semantic analysis on a
1062 program that is not concerned with the actual source code will
1063 primarily use this semantics-centric view.</p>
1064
1065<h4 id="LexicalAndSemanticContexts">Lexical and Semantic Contexts</h4>
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001066<p>Each declaration has two potentially different
Douglas Gregor074149e2009-01-05 19:45:36 +00001067 declaration contexts: a <i>lexical</i> context, which corresponds to
1068 the source-centric view of the declaration context, and
1069 a <i>semantic</i> context, which corresponds to the
1070 semantics-centric view. The lexical context is accessible
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001071 via <code>Decl::getLexicalDeclContext</code> while the
Douglas Gregor074149e2009-01-05 19:45:36 +00001072 semantic context is accessible
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001073 via <code>Decl::getDeclContext</code>, both of which return
Douglas Gregor074149e2009-01-05 19:45:36 +00001074 <code>DeclContext</code> pointers. For most declarations, the two
1075 contexts are identical. For example:</p>
1076
1077<pre>
1078class X {
1079public:
1080 void f(int x);
1081};
1082</pre>
1083
1084<p>Here, the semantic and lexical contexts of <code>X::f</code> are
1085 the <code>DeclContext</code> associated with the
1086 class <code>X</code> (itself stored as a <code>RecordDecl</code> AST
1087 node). However, we can now define <code>X::f</code> out-of-line:</p>
1088
1089<pre>
1090void X::f(int x = 17) { /* ... */ }
1091</pre>
1092
1093<p>This definition of has different lexical and semantic
1094 contexts. The lexical context corresponds to the declaration
1095 context in which the actual declaration occurred in the source
1096 code, e.g., the translation unit containing <code>X</code>. Thus,
1097 this declaration of <code>X::f</code> can be found by traversing
1098 the declarations provided by
1099 [<code>decls_begin()</code>, <code>decls_end()</code>) in the
1100 translation unit.</p>
1101
1102<p>The semantic context of <code>X::f</code> corresponds to the
1103 class <code>X</code>, since this member function is (semantically) a
1104 member of <code>X</code>. Lookup of the name <code>f</code> into
1105 the <code>DeclContext</code> associated with <code>X</code> will
1106 then return the definition of <code>X::f</code> (including
1107 information about the default argument).</p>
1108
1109<h4 id="TransparentContexts">Transparent Declaration Contexts</h4>
1110<p>In C and C++, there are several contexts in which names that are
1111 logically declared inside another declaration will actually "leak"
1112 out into the enclosing scope from the perspective of name
1113 lookup. The most obvious instance of this behavior is in
1114 enumeration types, e.g.,</p>
1115<pre>
1116enum Color {
1117 Red,
1118 Green,
1119 Blue
1120};
1121</pre>
1122
1123<p>Here, <code>Color</code> is an enumeration, which is a declaration
1124 context that contains the
1125 enumerators <code>Red</code>, <code>Green</code>,
1126 and <code>Blue</code>. Thus, traversing the list of declarations
1127 contained in the enumeration <code>Color</code> will
1128 yield <code>Red</code>, <code>Green</code>,
1129 and <code>Blue</code>. However, outside of the scope
1130 of <code>Color</code> one can name the enumerator <code>Red</code>
1131 without qualifying the name, e.g.,</p>
1132
1133<pre>
1134Color c = Red;
1135</pre>
1136
1137<p>There are other entities in C++ that provide similar behavior. For
1138 example, linkage specifications that use curly braces:</p>
1139
1140<pre>
1141extern "C" {
1142 void f(int);
1143 void g(int);
1144}
1145// f and g are visible here
1146</pre>
1147
1148<p>For source-level accuracy, we treat the linkage specification and
1149 enumeration type as a
1150 declaration context in which its enclosed declarations ("Red",
1151 "Green", and "Blue"; "f" and "g")
1152 are declared. However, these declarations are visible outside of the
1153 scope of the declaration context.</p>
1154
1155<p>These language features (and several others, described below) have
1156 roughly the same set of
1157 requirements: declarations are declared within a particular lexical
1158 context, but the declarations are also found via name lookup in
1159 scopes enclosing the declaration itself. This feature is implemented
1160 via <i>transparent</i> declaration contexts
1161 (see <code>DeclContext::isTransparentContext()</code>), whose
1162 declarations are visible in the nearest enclosing non-transparent
1163 declaration context. This means that the lexical context of the
1164 declaration (e.g., an enumerator) will be the
1165 transparent <code>DeclContext</code> itself, as will the semantic
1166 context, but the declaration will be visible in every outer context
1167 up to and including the first non-transparent declaration context (since
1168 transparent declaration contexts can be nested).</p>
1169
1170<p>The transparent <code>DeclContexts</code> are:</p>
1171<ul>
1172 <li>Enumerations (but not C++0x "scoped enumerations"):
1173 <pre>
1174enum Color {
1175 Red,
1176 Green,
1177 Blue
1178};
1179// Red, Green, and Blue are in scope
1180 </pre></li>
1181 <li>C++ linkage specifications:
1182 <pre>
1183extern "C" {
1184 void f(int);
1185 void g(int);
1186}
1187// f and g are in scope
1188 </pre></li>
1189 <li>Anonymous unions and structs:
1190 <pre>
1191struct LookupTable {
1192 bool IsVector;
1193 union {
1194 std::vector&lt;Item&gt; *Vector;
1195 std::set&lt;Item&gt; *Set;
1196 };
1197};
1198
1199LookupTable LT;
1200LT.Vector = 0; // Okay: finds Vector inside the unnamed union
1201 </pre>
1202 </li>
1203 <li>C++0x inline namespaces:
1204<pre>
1205namespace mylib {
1206 inline namespace debug {
1207 class X;
1208 }
1209}
1210mylib::X *xp; // okay: mylib::X refers to mylib::debug::X
1211</pre>
1212</li>
1213</ul>
1214
1215
1216<h4 id="MultiDeclContext">Multiply-Defined Declaration Contexts</h4>
1217<p>C++ namespaces have the interesting--and, so far, unique--property that
1218the namespace can be defined multiple times, and the declarations
1219provided by each namespace definition are effectively merged (from
1220the semantic point of view). For example, the following two code
1221snippets are semantically indistinguishable:</p>
1222<pre>
1223// Snippet #1:
1224namespace N {
1225 void f();
1226}
1227namespace N {
1228 void f(int);
1229}
1230
1231// Snippet #2:
1232namespace N {
1233 void f();
1234 void f(int);
1235}
1236</pre>
1237
1238<p>In Clang's representation, the source-centric view of declaration
1239 contexts will actually have two separate <code>NamespaceDecl</code>
1240 nodes in Snippet #1, each of which is a declaration context that
1241 contains a single declaration of "f". However, the semantics-centric
1242 view provided by name lookup into the namespace <code>N</code> for
1243 "f" will return an <code>OverloadedFunctionDecl</code> that contains
1244 both declarations of "f".</p>
1245
1246<p><code>DeclContext</code> manages multiply-defined declaration
1247 contexts internally. The
1248 function <code>DeclContext::getPrimaryContext</code> retrieves the
1249 "primary" context for a given <code>DeclContext</code> instance,
1250 which is the <code>DeclContext</code> responsible for maintaining
1251 the lookup table used for the semantics-centric view. Given the
1252 primary context, one can follow the chain
1253 of <code>DeclContext</code> nodes that define additional
1254 declarations via <code>DeclContext::getNextContext</code>. Note that
1255 these functions are used internally within the lookup and insertion
1256 methods of the <code>DeclContext</code>, so the vast majority of
1257 clients can ignore them.</p>
1258
1259<!-- ======================================================================= -->
Ted Kremenek8bc05712007-10-10 23:01:43 +00001260<h3 id="CFG">The <tt>CFG</tt> class</h3>
1261<!-- ======================================================================= -->
1262
1263<p>The <tt>CFG</tt> class is designed to represent a source-level
1264control-flow graph for a single statement (<tt>Stmt*</tt>). Typically
1265instances of <tt>CFG</tt> are constructed for function bodies (usually
1266an instance of <tt>CompoundStmt</tt>), but can also be instantiated to
1267represent the control-flow of any class that subclasses <tt>Stmt</tt>,
1268which includes simple expressions. Control-flow graphs are especially
1269useful for performing
1270<a href="http://en.wikipedia.org/wiki/Data_flow_analysis#Sensitivities">flow-
1271or path-sensitive</a> program analyses on a given function.</p>
1272
Chris Lattner62fd2782008-11-22 21:41:31 +00001273<!-- ============ -->
Ted Kremenek8bc05712007-10-10 23:01:43 +00001274<h4>Basic Blocks</h4>
Chris Lattner62fd2782008-11-22 21:41:31 +00001275<!-- ============ -->
Ted Kremenek8bc05712007-10-10 23:01:43 +00001276
1277<p>Concretely, an instance of <tt>CFG</tt> is a collection of basic
1278blocks. Each basic block is an instance of <tt>CFGBlock</tt>, which
1279simply contains an ordered sequence of <tt>Stmt*</tt> (each referring
1280to statements in the AST). The ordering of statements within a block
1281indicates unconditional flow of control from one statement to the
1282next. <a href="#ConditionalControlFlow">Conditional control-flow</a>
1283is represented using edges between basic blocks. The statements
1284within a given <tt>CFGBlock</tt> can be traversed using
1285the <tt>CFGBlock::*iterator</tt> interface.</p>
1286
1287<p>
Ted Kremenek18e17e72007-10-18 22:50:52 +00001288A <tt>CFG</tt> object owns the instances of <tt>CFGBlock</tt> within
Ted Kremenek8bc05712007-10-10 23:01:43 +00001289the control-flow graph it represents. Each <tt>CFGBlock</tt> within a
1290CFG is also uniquely numbered (accessible
1291via <tt>CFGBlock::getBlockID()</tt>). Currently the number is
1292based on the ordering the blocks were created, but no assumptions
1293should be made on how <tt>CFGBlock</tt>s are numbered other than their
1294numbers are unique and that they are numbered from 0..N-1 (where N is
1295the number of basic blocks in the CFG).</p>
1296
Chris Lattner62fd2782008-11-22 21:41:31 +00001297<!-- ===================== -->
Ted Kremenek8bc05712007-10-10 23:01:43 +00001298<h4>Entry and Exit Blocks</h4>
Chris Lattner62fd2782008-11-22 21:41:31 +00001299<!-- ===================== -->
Ted Kremenek8bc05712007-10-10 23:01:43 +00001300
1301Each instance of <tt>CFG</tt> contains two special blocks:
1302an <i>entry</i> block (accessible via <tt>CFG::getEntry()</tt>), which
1303has no incoming edges, and an <i>exit</i> block (accessible
1304via <tt>CFG::getExit()</tt>), which has no outgoing edges. Neither
1305block contains any statements, and they serve the role of providing a
1306clear entrance and exit for a body of code such as a function body.
1307The presence of these empty blocks greatly simplifies the
1308implementation of many analyses built on top of CFGs.
1309
Chris Lattner62fd2782008-11-22 21:41:31 +00001310<!-- ===================================================== -->
Ted Kremenek8bc05712007-10-10 23:01:43 +00001311<h4 id ="ConditionalControlFlow">Conditional Control-Flow</h4>
Chris Lattner62fd2782008-11-22 21:41:31 +00001312<!-- ===================================================== -->
Ted Kremenek8bc05712007-10-10 23:01:43 +00001313
1314<p>Conditional control-flow (such as those induced by if-statements
1315and loops) is represented as edges between <tt>CFGBlock</tt>s.
1316Because different C language constructs can induce control-flow,
1317each <tt>CFGBlock</tt> also records an extra <tt>Stmt*</tt> that
1318represents the <i>terminator</i> of the block. A terminator is simply
1319the statement that caused the control-flow, and is used to identify
1320the nature of the conditional control-flow between blocks. For
1321example, in the case of an if-statement, the terminator refers to
1322the <tt>IfStmt</tt> object in the AST that represented the given
1323branch.</p>
1324
1325<p>To illustrate, consider the following code example:</p>
1326
1327<code>
1328int foo(int x) {<br>
1329&nbsp;&nbsp;x = x + 1;<br>
1330<br>
1331&nbsp;&nbsp;if (x > 2) x++;<br>
1332&nbsp;&nbsp;else {<br>
1333&nbsp;&nbsp;&nbsp;&nbsp;x += 2;<br>
1334&nbsp;&nbsp;&nbsp;&nbsp;x *= 2;<br>
1335&nbsp;&nbsp;}<br>
1336<br>
1337&nbsp;&nbsp;return x;<br>
1338}
1339</code>
1340
1341<p>After invoking the parser+semantic analyzer on this code fragment,
1342the AST of the body of <tt>foo</tt> is referenced by a
1343single <tt>Stmt*</tt>. We can then construct an instance
1344of <tt>CFG</tt> representing the control-flow graph of this function
1345body by single call to a static class method:</p>
1346
1347<code>
1348&nbsp;&nbsp;Stmt* FooBody = ...<br>
1349&nbsp;&nbsp;CFG* FooCFG = <b>CFG::buildCFG</b>(FooBody);
1350</code>
1351
1352<p>It is the responsibility of the caller of <tt>CFG::buildCFG</tt>
1353to <tt>delete</tt> the returned <tt>CFG*</tt> when the CFG is no
1354longer needed.</p>
1355
1356<p>Along with providing an interface to iterate over
1357its <tt>CFGBlock</tt>s, the <tt>CFG</tt> class also provides methods
1358that are useful for debugging and visualizing CFGs. For example, the
1359method
1360<tt>CFG::dump()</tt> dumps a pretty-printed version of the CFG to
1361standard error. This is especially useful when one is using a
1362debugger such as gdb. For example, here is the output
1363of <tt>FooCFG->dump()</tt>:</p>
1364
1365<code>
1366&nbsp;[ B5 (ENTRY) ]<br>
1367&nbsp;&nbsp;&nbsp;&nbsp;Predecessors (0):<br>
1368&nbsp;&nbsp;&nbsp;&nbsp;Successors (1): B4<br>
1369<br>
1370&nbsp;[ B4 ]<br>
1371&nbsp;&nbsp;&nbsp;&nbsp;1: x = x + 1<br>
1372&nbsp;&nbsp;&nbsp;&nbsp;2: (x > 2)<br>
1373&nbsp;&nbsp;&nbsp;&nbsp;<b>T: if [B4.2]</b><br>
1374&nbsp;&nbsp;&nbsp;&nbsp;Predecessors (1): B5<br>
1375&nbsp;&nbsp;&nbsp;&nbsp;Successors (2): B3 B2<br>
1376<br>
1377&nbsp;[ B3 ]<br>
1378&nbsp;&nbsp;&nbsp;&nbsp;1: x++<br>
1379&nbsp;&nbsp;&nbsp;&nbsp;Predecessors (1): B4<br>
1380&nbsp;&nbsp;&nbsp;&nbsp;Successors (1): B1<br>
1381<br>
1382&nbsp;[ B2 ]<br>
1383&nbsp;&nbsp;&nbsp;&nbsp;1: x += 2<br>
1384&nbsp;&nbsp;&nbsp;&nbsp;2: x *= 2<br>
1385&nbsp;&nbsp;&nbsp;&nbsp;Predecessors (1): B4<br>
1386&nbsp;&nbsp;&nbsp;&nbsp;Successors (1): B1<br>
1387<br>
1388&nbsp;[ B1 ]<br>
1389&nbsp;&nbsp;&nbsp;&nbsp;1: return x;<br>
1390&nbsp;&nbsp;&nbsp;&nbsp;Predecessors (2): B2 B3<br>
1391&nbsp;&nbsp;&nbsp;&nbsp;Successors (1): B0<br>
1392<br>
1393&nbsp;[ B0 (EXIT) ]<br>
1394&nbsp;&nbsp;&nbsp;&nbsp;Predecessors (1): B1<br>
1395&nbsp;&nbsp;&nbsp;&nbsp;Successors (0):
1396</code>
1397
1398<p>For each block, the pretty-printed output displays for each block
1399the number of <i>predecessor</i> blocks (blocks that have outgoing
1400control-flow to the given block) and <i>successor</i> blocks (blocks
1401that have control-flow that have incoming control-flow from the given
1402block). We can also clearly see the special entry and exit blocks at
1403the beginning and end of the pretty-printed output. For the entry
1404block (block B5), the number of predecessor blocks is 0, while for the
1405exit block (block B0) the number of successor blocks is 0.</p>
1406
1407<p>The most interesting block here is B4, whose outgoing control-flow
1408represents the branching caused by the sole if-statement
1409in <tt>foo</tt>. Of particular interest is the second statement in
1410the block, <b><tt>(x > 2)</tt></b>, and the terminator, printed
1411as <b><tt>if [B4.2]</tt></b>. The second statement represents the
1412evaluation of the condition of the if-statement, which occurs before
1413the actual branching of control-flow. Within the <tt>CFGBlock</tt>
1414for B4, the <tt>Stmt*</tt> for the second statement refers to the
1415actual expression in the AST for <b><tt>(x > 2)</tt></b>. Thus
1416pointers to subclasses of <tt>Expr</tt> can appear in the list of
1417statements in a block, and not just subclasses of <tt>Stmt</tt> that
1418refer to proper C statements.</p>
1419
1420<p>The terminator of block B4 is a pointer to the <tt>IfStmt</tt>
1421object in the AST. The pretty-printer outputs <b><tt>if
1422[B4.2]</tt></b> because the condition expression of the if-statement
1423has an actual place in the basic block, and thus the terminator is
1424essentially
1425<i>referring</i> to the expression that is the second statement of
1426block B4 (i.e., B4.2). In this manner, conditions for control-flow
1427(which also includes conditions for loops and switch statements) are
1428hoisted into the actual basic block.</p>
1429
Chris Lattner62fd2782008-11-22 21:41:31 +00001430<!-- ===================== -->
1431<!-- <h4>Implicit Control-Flow</h4> -->
1432<!-- ===================== -->
Ted Kremenek8bc05712007-10-10 23:01:43 +00001433
1434<!--
1435<p>A key design principle of the <tt>CFG</tt> class was to not require
1436any transformations to the AST in order to represent control-flow.
1437Thus the <tt>CFG</tt> does not perform any "lowering" of the
1438statements in an AST: loops are not transformed into guarded gotos,
1439short-circuit operations are not converted to a set of if-statements,
1440and so on.</p>
1441-->
Ted Kremenek17a295d2008-06-11 06:19:49 +00001442
Chris Lattner7bad1992008-11-16 21:48:07 +00001443
1444<!-- ======================================================================= -->
1445<h3 id="Constants">Constant Folding in the Clang AST</h3>
1446<!-- ======================================================================= -->
1447
1448<p>There are several places where constants and constant folding matter a lot to
1449the Clang front-end. First, in general, we prefer the AST to retain the source
1450code as close to how the user wrote it as possible. This means that if they
1451wrote "5+4", we want to keep the addition and two constants in the AST, we don't
1452want to fold to "9". This means that constant folding in various ways turns
1453into a tree walk that needs to handle the various cases.</p>
1454
1455<p>However, there are places in both C and C++ that require constants to be
1456folded. For example, the C standard defines what an "integer constant
1457expression" (i-c-e) is with very precise and specific requirements. The
1458language then requires i-c-e's in a lot of places (for example, the size of a
1459bitfield, the value for a case statement, etc). For these, we have to be able
1460to constant fold the constants, to do semantic checks (e.g. verify bitfield size
1461is non-negative and that case statements aren't duplicated). We aim for Clang
1462to be very pedantic about this, diagnosing cases when the code does not use an
1463i-c-e where one is required, but accepting the code unless running with
1464<tt>-pedantic-errors</tt>.</p>
1465
1466<p>Things get a little bit more tricky when it comes to compatibility with
1467real-world source code. Specifically, GCC has historically accepted a huge
1468superset of expressions as i-c-e's, and a lot of real world code depends on this
1469unfortuate accident of history (including, e.g., the glibc system headers). GCC
1470accepts anything its "fold" optimizer is capable of reducing to an integer
1471constant, which means that the definition of what it accepts changes as its
1472optimizer does. One example is that GCC accepts things like "case X-X:" even
1473when X is a variable, because it can fold this to 0.</p>
1474
1475<p>Another issue are how constants interact with the extensions we support, such
1476as __builtin_constant_p, __builtin_inf, __extension__ and many others. C99
1477obviously does not specify the semantics of any of these extensions, and the
1478definition of i-c-e does not include them. However, these extensions are often
1479used in real code, and we have to have a way to reason about them.</p>
1480
1481<p>Finally, this is not just a problem for semantic analysis. The code
1482generator and other clients have to be able to fold constants (e.g. to
1483initialize global variables) and has to handle a superset of what C99 allows.
1484Further, these clients can benefit from extended information. For example, we
1485know that "foo()||1" always evaluates to true, but we can't replace the
1486expression with true because it has side effects.</p>
1487
1488<!-- ======================= -->
1489<h4>Implementation Approach</h4>
1490<!-- ======================= -->
1491
1492<p>After trying several different approaches, we've finally converged on a
1493design (Note, at the time of this writing, not all of this has been implemented,
1494consider this a design goal!). Our basic approach is to define a single
1495recursive method evaluation method (<tt>Expr::Evaluate</tt>), which is
1496implemented in <tt>AST/ExprConstant.cpp</tt>. Given an expression with 'scalar'
1497type (integer, fp, complex, or pointer) this method returns the following
1498information:</p>
1499
1500<ul>
1501<li>Whether the expression is an integer constant expression, a general
1502 constant that was folded but has no side effects, a general constant that
1503 was folded but that does have side effects, or an uncomputable/unfoldable
1504 value.
1505</li>
1506<li>If the expression was computable in any way, this method returns the APValue
1507 for the result of the expression.</li>
1508<li>If the expression is not evaluatable at all, this method returns
1509 information on one of the problems with the expression. This includes a
1510 SourceLocation for where the problem is, and a diagnostic ID that explains
1511 the problem. The diagnostic should be have ERROR type.</li>
1512<li>If the expression is not an integer constant expression, this method returns
1513 information on one of the problems with the expression. This includes a
1514 SourceLocation for where the problem is, and a diagnostic ID that explains
1515 the problem. The diagnostic should be have EXTENSION type.</li>
1516</ul>
1517
1518<p>This information gives various clients the flexibility that they want, and we
1519will eventually have some helper methods for various extensions. For example,
1520Sema should have a <tt>Sema::VerifyIntegerConstantExpression</tt> method, which
1521calls Evaluate on the expression. If the expression is not foldable, the error
1522is emitted, and it would return true. If the expression is not an i-c-e, the
1523EXTENSION diagnostic is emitted. Finally it would return false to indicate that
1524the AST is ok.</p>
1525
1526<p>Other clients can use the information in other ways, for example, codegen can
1527just use expressions that are foldable in any way.</p>
1528
1529<!-- ========== -->
1530<h4>Extensions</h4>
1531<!-- ========== -->
1532
Chris Lattner552de0a2008-11-23 08:16:56 +00001533<p>This section describes how some of the various extensions Clang supports
Chris Lattner7bad1992008-11-16 21:48:07 +00001534interacts with constant evaluation:</p>
1535
1536<ul>
1537<li><b><tt>__extension__</tt></b>: The expression form of this extension causes
1538 any evaluatable subexpression to be accepted as an integer constant
1539 expression.</li>
1540<li><b><tt>__builtin_constant_p</tt></b>: This returns true (as a integer
Chris Lattner28daa532008-12-12 06:55:44 +00001541 constant expression) if the operand is any evaluatable constant. As a
1542 special case, if <tt>__builtin_constant_p</tt> is the (potentially
1543 parenthesized) condition of a conditional operator expression ("?:"), only
Chris Lattner42b83dd2008-12-12 18:00:51 +00001544 the true side of the conditional operator is considered, and it is evaluated
1545 with full constant folding.</li>
Chris Lattner7bad1992008-11-16 21:48:07 +00001546<li><b><tt>__builtin_choose_expr</tt></b>: The condition is required to be an
1547 integer constant expression, but we accept any constant as an "extension of
1548 an extension". This only evaluates one operand depending on which way the
1549 condition evaluates.</li>
1550<li><b><tt>__builtin_classify_type</tt></b>: This always returns an integer
1551 constant expression.</li>
1552<li><b><tt>__builtin_inf,nan,..</tt></b>: These are treated just like a
1553 floating-point literal.</li>
1554<li><b><tt>__builtin_abs,copysign,..</tt></b>: These are constant folded as
1555 general constant expressions.</li>
1556</ul>
1557
1558
1559
1560
Ted Kremenek17a295d2008-06-11 06:19:49 +00001561</div>
1562</body>
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001563</html>