| Ted Kremenek | 17a295d | 2008-06-11 06:19:49 +0000 | [diff] [blame] | 1 | <html> | 
|  | 2 | <head> | 
| Chris Lattner | 86920d3 | 2007-07-31 05:42:17 +0000 | [diff] [blame] | 3 | <title>"clang" CFE Internals Manual</title> | 
| Ted Kremenek | 17a295d | 2008-06-11 06:19:49 +0000 | [diff] [blame] | 4 | <link type="text/css" rel="stylesheet" href="../menu.css" /> | 
|  | 5 | <link type="text/css" rel="stylesheet" href="../content.css" /> | 
| Sebastian Redl | 6816856 | 2008-11-22 22:16:45 +0000 | [diff] [blame] | 6 | <style type="text/css"> | 
|  | 7 | td { | 
|  | 8 | vertical-align: top; | 
|  | 9 | } | 
|  | 10 | </style> | 
| Ted Kremenek | 17a295d | 2008-06-11 06:19:49 +0000 | [diff] [blame] | 11 | </head> | 
|  | 12 | <body> | 
|  | 13 |  | 
|  | 14 | <!--#include virtual="../menu.html.incl"--> | 
|  | 15 |  | 
|  | 16 | <div id="content"> | 
| Chris Lattner | 86920d3 | 2007-07-31 05:42:17 +0000 | [diff] [blame] | 17 |  | 
|  | 18 | <h1>"clang" CFE Internals Manual</h1> | 
|  | 19 |  | 
|  | 20 | <ul> | 
|  | 21 | <li><a href="#intro">Introduction</a></li> | 
|  | 22 | <li><a href="#libsystem">LLVM System and Support Libraries</a></li> | 
|  | 23 | <li><a href="#libbasic">The clang 'Basic' Library</a> | 
|  | 24 | <ul> | 
| Chris Lattner | 62fd278 | 2008-11-22 21:41:31 +0000 | [diff] [blame] | 25 | <li><a href="#Diagnostics">The Diagnostics Subsystem</a></li> | 
| Chris Lattner | 86920d3 | 2007-07-31 05:42:17 +0000 | [diff] [blame] | 26 | <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 Lattner | 7928125 | 2008-03-09 02:27:26 +0000 | [diff] [blame] | 34 | <li><a href="#TokenLexer">The TokenLexer class</a></li> | 
| Chris Lattner | 86920d3 | 2007-07-31 05:42:17 +0000 | [diff] [blame] | 35 | <li><a href="#MultipleIncludeOpt">The MultipleIncludeOpt class</a></li> | 
|  | 36 | </ul> | 
|  | 37 | </li> | 
|  | 38 | <li><a href="#libparse">The Parser Library</a> | 
|  | 39 | <ul> | 
|  | 40 | </ul> | 
|  | 41 | </li> | 
|  | 42 | <li><a href="#libast">The AST Library</a> | 
|  | 43 | <ul> | 
|  | 44 | <li><a href="#Type">The Type class and its subclasses</a></li> | 
|  | 45 | <li><a href="#QualType">The QualType class</a></li> | 
| Douglas Gregor | 2e1cd42 | 2008-11-17 14:58:09 +0000 | [diff] [blame] | 46 | <li><a href="#DeclarationName">Declaration names</a></li> | 
| Ted Kremenek | 8bc0571 | 2007-10-10 23:01:43 +0000 | [diff] [blame] | 47 | <li><a href="#CFG">The CFG class</a></li> | 
| Chris Lattner | 7bad199 | 2008-11-16 21:48:07 +0000 | [diff] [blame] | 48 | <li><a href="#Constants">Constant Folding in the Clang AST</a></li> | 
| Chris Lattner | 86920d3 | 2007-07-31 05:42:17 +0000 | [diff] [blame] | 49 | </ul> | 
|  | 50 | </li> | 
|  | 51 | </ul> | 
|  | 52 |  | 
|  | 53 |  | 
|  | 54 | <!-- ======================================================================= --> | 
|  | 55 | <h2 id="intro">Introduction</h2> | 
|  | 56 | <!-- ======================================================================= --> | 
|  | 57 |  | 
|  | 58 | <p>This document describes some of the more important APIs and internal design | 
|  | 59 | decisions made in the clang C front-end.  The purpose of this document is to | 
|  | 60 | both capture some of this high level information and also describe some of the | 
|  | 61 | design decisions behind it.  This is meant for people interested in hacking on | 
|  | 62 | clang, not for end-users.  The description below is categorized by | 
|  | 63 | libraries, and does not describe any of the clients of the libraries.</p> | 
|  | 64 |  | 
|  | 65 | <!-- ======================================================================= --> | 
|  | 66 | <h2 id="libsystem">LLVM System and Support Libraries</h2> | 
|  | 67 | <!-- ======================================================================= --> | 
|  | 68 |  | 
|  | 69 | <p>The LLVM libsystem library provides the basic clang system abstraction layer, | 
|  | 70 | which is used for file system access.  The LLVM libsupport library provides many | 
|  | 71 | underlying libraries and <a | 
|  | 72 | href="http://llvm.org/docs/ProgrammersManual.html">data-structures</a>, | 
|  | 73 | including command line option | 
|  | 74 | processing and various containers.</p> | 
|  | 75 |  | 
|  | 76 | <!-- ======================================================================= --> | 
|  | 77 | <h2 id="libbasic">The clang 'Basic' Library</h2> | 
|  | 78 | <!-- ======================================================================= --> | 
|  | 79 |  | 
|  | 80 | <p>This library certainly needs a better name.  The 'basic' library contains a | 
|  | 81 | number of low-level utilities for tracking and manipulating source buffers, | 
|  | 82 | locations within the source buffers, diagnostics, tokens, target abstraction, | 
|  | 83 | and information about the subset of the language being compiled for.</p> | 
|  | 84 |  | 
|  | 85 | <p>Part of this infrastructure is specific to C (such as the TargetInfo class), | 
|  | 86 | other parts could be reused for other non-C-based languages (SourceLocation, | 
|  | 87 | SourceManager, Diagnostics, FileManager).  When and if there is future demand | 
|  | 88 | we can figure out if it makes sense to introduce a new library, move the general | 
|  | 89 | classes somewhere else, or introduce some other solution.</p> | 
|  | 90 |  | 
|  | 91 | <p>We describe the roles of these classes in order of their dependencies.</p> | 
|  | 92 |  | 
| Chris Lattner | 62fd278 | 2008-11-22 21:41:31 +0000 | [diff] [blame] | 93 |  | 
|  | 94 | <!-- ======================================================================= --> | 
|  | 95 | <h3 id="Diagnostics">The Diagnostics Subsystem</h3> | 
|  | 96 | <!-- ======================================================================= --> | 
|  | 97 |  | 
|  | 98 | <p>The Clang Diagnostics subsystem is an important part of how the compiler | 
|  | 99 | communicates with the human.  Diagnostics are the warnings and errors produced | 
|  | 100 | when the code is incorrect or dubious.  In Clang, each diagnostic produced has | 
|  | 101 | (at the minimum) a unique ID, a <a href="#SourceLocation">SourceLocation</a> to | 
|  | 102 | "put the caret", an English translation associated with it, and a severity (e.g. | 
|  | 103 | <tt>WARNING</tt> or <tt>ERROR</tt>).  They can also optionally include a number | 
|  | 104 | of arguments to the dianostic (which fill in "%0"'s in the string) as well as a | 
|  | 105 | number of source ranges that related to the diagnostic.</p> | 
|  | 106 |  | 
|  | 107 | <p>In this section, we'll be giving examples produced by the clang command line | 
|  | 108 | driver, but diagnostics can be <a href="#DiagnosticClient">rendered in many | 
|  | 109 | different ways</a> depending on how the DiagnosticClient interface is | 
|  | 110 | implemented.  A representative example of a diagonstic is:</p> | 
|  | 111 |  | 
|  | 112 | <pre> | 
|  | 113 | t.c:38:15: error: invalid operands to binary expression ('int *' and '_Complex float') | 
|  | 114 | <font color="darkgreen">P = (P-42) + Gamma*4;</font> | 
|  | 115 | <font color="blue">~~~~~~ ^ ~~~~~~~</font> | 
|  | 116 | </pre> | 
|  | 117 |  | 
|  | 118 | <p>In this example, you can see the English translation, the severity (error), | 
|  | 119 | you can see the source location (the caret ("^") and file/line/column info), | 
|  | 120 | the source ranges "~~~~", arguments to the diagnostic ("int*" and "_Complex | 
|  | 121 | float").  You'll have to believe me that there is a unique ID backing the | 
|  | 122 | diagnostic :).</p> | 
|  | 123 |  | 
|  | 124 | <p>Getting all of this to happen has several steps and involves many moving | 
|  | 125 | pieces, this section describes them and talks about best practices when adding | 
|  | 126 | a new diagnostic.</p> | 
|  | 127 |  | 
|  | 128 | <!-- ============================ --> | 
|  | 129 | <h4>The DiagnosticKinds.def file</h4> | 
|  | 130 | <!-- ============================ --> | 
|  | 131 |  | 
|  | 132 | <p>Diagnostics are created by adding an entry to the <tt><a | 
|  | 133 | href="http://llvm.org/svn/llvm-project/cfe/trunk/include/clang/Basic/DiagnosticKinds.def" | 
|  | 134 | >DiagnosticKinds.def</a></tt> file.  This file encodes the unique ID of the | 
|  | 135 | diagnostic (as an enum, the first argument), the severity of the diagnostic | 
|  | 136 | (second argument) and the English translation + format string.</p> | 
|  | 137 |  | 
|  | 138 | <p>There is little sanity with the naming of the unique ID's right now.  Some | 
|  | 139 | start with err_, warn_, ext_ to encode the severity into the name.  Since the | 
|  | 140 | enum is referenced in the C++ code that produces the diagnostic, it is somewhat | 
|  | 141 | useful for it to be reasonably short.</p> | 
|  | 142 |  | 
|  | 143 | <p>The severity of the diagnostic comes from the set {<tt>NOTE</tt>, | 
|  | 144 | <tt>WARNING</tt>, <tt>EXTENSION</tt>, <tt>EXTWARN</tt>, <tt>ERROR</tt>}.  The | 
|  | 145 | <tt>ERROR</tt> severity is used for diagnostics indicating the program is never | 
|  | 146 | acceptable under any circumstances.  When an error is emitted, the AST for the | 
|  | 147 | input code may not be fully built.  The <tt>EXTENSION</tt> and <tt>EXTWARN</tt> | 
|  | 148 | severities are used for extensions to the language that Clang accepts.  This | 
|  | 149 | means that Clang fully understands and can represent them in the AST, but we | 
|  | 150 | produce diagnostics to tell the user their code is non-portable.  The difference | 
|  | 151 | is that the former are ignored by default, and the later warn by default.  The | 
|  | 152 | <tt>WARNING</tt> severity is used for constructs that are valid in the currently | 
|  | 153 | selected source language but that are dubious in some way.  The <tt>NOTE</tt> | 
|  | 154 | level is used to staple more information onto a previous diagnostics.</p> | 
|  | 155 |  | 
|  | 156 | <p>These <em>severities</em> are mapped into a smaller set (the | 
|  | 157 | Diagnostic::Level enum, {<tt>Ignored</tt>, <tt>Note</tt>, <tt>Warning</tt>, | 
|  | 158 | <tt>Error</tt> }) of output <em>levels</em> by the diagnostics subsystem based | 
|  | 159 | on various configuration options.  For example, if the user specifies | 
|  | 160 | <tt>-pedantic</tt>, <tt>EXTENSION</tt> maps to <tt>Warning</tt>, if they specify | 
|  | 161 | <tt>-pedantic-errors</tt>, it turns into <tt>Error</tt>.  Clang also internally | 
|  | 162 | supports a fully fine grained mapping mechanism that allows you to map any | 
|  | 163 | diagnostic that doesn't have <tt>ERRROR</tt> severity to any output level that | 
|  | 164 | you want.  This is used to implement options like <tt>-Wunused_macros</tt>, | 
|  | 165 | <tt>-Wundef</tt> etc.</p> | 
|  | 166 |  | 
|  | 167 | <!-- ================= --> | 
|  | 168 | <h4>The Format String</h4> | 
|  | 169 | <!-- ================= --> | 
|  | 170 |  | 
|  | 171 | <p>The format string for the diagnostic is very simple, but it has some power. | 
|  | 172 | It takes the form of a string in English with markers that indicate where and | 
|  | 173 | how arguments to the diagnostic are inserted and formatted.  For example, here | 
|  | 174 | are some simple format strings:</p> | 
|  | 175 |  | 
|  | 176 | <pre> | 
|  | 177 | "binary integer literals are an extension" | 
|  | 178 | "format string contains '\\0' within the string body" | 
|  | 179 | "more '<b>%%</b>' conversions than data arguments" | 
|  | 180 | "invalid operands to binary expression ('<b>%0</b>' and '<b>%1</b>')" | 
|  | 181 | "overloaded '<b>%0</b>' must be a <b>%select{unary|binary|unary or binary}2</b> operator" | 
|  | 182 | " (has <b>%1</b> parameter<b>%s1</b>)" | 
|  | 183 | </pre> | 
|  | 184 |  | 
|  | 185 | <p>These examples show some important points of format strings.  You can use any | 
|  | 186 | plain ASCII character in the diagnostic string except "%" without a problem, | 
|  | 187 | but these are C strings, so you have to use and be aware of all the C escape | 
|  | 188 | sequences (as in the second example).  If you want to produce a "%" in the | 
|  | 189 | output, use the "%%" escape sequence, like the third diagnostic.  Finally, | 
|  | 190 | clang uses the "%...[digit]" sequences to specify where and how arguments to | 
|  | 191 | the diagnostic are formatted.</p> | 
|  | 192 |  | 
|  | 193 | <p>Arguments to the diagnostic are numbered according to how they are specified | 
|  | 194 | by the C++ code that <a href="#producingdiag">produces them</a>, and are | 
|  | 195 | referenced by <tt>%0</tt> .. <tt>%9</tt>.  If you have more than 10 arguments | 
|  | 196 | to your diagnostic, you are doing something wrong. :).  Unlike printf, there | 
|  | 197 | is no requirement that arguments to the diagnostic end up in the output in | 
|  | 198 | the same order as they are specified, you could have a format string with | 
|  | 199 | <tt>"%1 %0"</tt> that swaps them, for example.  The text in between the | 
|  | 200 | percent and digit are formatting instructions.  If there are no instructions, | 
|  | 201 | the argument is just turned into a string and substituted in.</p> | 
|  | 202 |  | 
|  | 203 | <p>Here are some "best practices" for writing the English format string:</p> | 
|  | 204 |  | 
|  | 205 | <ul> | 
|  | 206 | <li>Keep the string short.  It should ideally fit in the 80 column limit of the | 
|  | 207 | <tt>DiagnosticKinds.def</tt> file.  This avoids the diagnostic wrapping when | 
|  | 208 | printed, and forces you to think about the important point you are conveying | 
|  | 209 | with the diagnostic.</li> | 
|  | 210 | <li>Take advantage of location information.  The user will be able to see the | 
|  | 211 | line and location of the caret, so you don't need to tell them that the | 
|  | 212 | problem is with the 4th argument to the function: just point to it.</li> | 
|  | 213 | <li>Do not capitalize the diagnostic string, and do not end it with a | 
|  | 214 | period.</li> | 
|  | 215 | <li>If you need to quote something in the diagnostic string, use single | 
|  | 216 | quotes.</li> | 
|  | 217 | </ul> | 
|  | 218 |  | 
|  | 219 | <p>Diagnostics should never take random English strings as arguments: you | 
|  | 220 | shouldn't use <tt>"you have a problem with %0"</tt> and pass in things like | 
|  | 221 | <tt>"your argument"</tt> or <tt>"your return value"</tt> as arguments. Doing | 
|  | 222 | this prevents <a href="translation">translating</a> the Clang diagnostics to | 
|  | 223 | other languages (because they'll get random English words in their otherwise | 
|  | 224 | localized diagnostic).  The exceptions to this are C/C++ language keywords | 
|  | 225 | (e.g. auto, const, mutable, etc) and C/C++ operators (<tt>/=</tt>).  Note | 
|  | 226 | that things like "pointer" and "reference" are not keywords.  On the other | 
|  | 227 | hand, you <em>can</em> include anything that comes from the user's source code, | 
|  | 228 | including variable names, types, labels, etc.</p> | 
|  | 229 |  | 
|  | 230 | <!-- ==================================== --> | 
|  | 231 | <h4>Formatting a Diagnostic Argument</a></h4> | 
|  | 232 | <!-- ==================================== --> | 
|  | 233 |  | 
|  | 234 | <p>Arguments to diagnostics are fully typed internally, and come from a couple | 
|  | 235 | different classes: integers, types, names, and random strings.  Depending on | 
|  | 236 | the class of the argument, it can be optionally formatted in different ways. | 
|  | 237 | This gives the DiagnosticClient information about what the argument means | 
|  | 238 | without requiring it to use a specific presentation (consider this MVC for | 
|  | 239 | Clang :).</p> | 
|  | 240 |  | 
|  | 241 | <p>Here are the different diagnostic argument formats currently supported by | 
|  | 242 | Clang:</p> | 
|  | 243 |  | 
|  | 244 | <table> | 
|  | 245 | <tr><td colspan="2"><b>"s" format</b></td></tr> | 
|  | 246 | <tr><td>Example:</td><td><tt>"requires %1 parameter%s1"</tt></td></tr> | 
|  | 247 | <tr><td>Classes:</td><td>Integers</td></tr> | 
|  | 248 | <tr><td>Description:</td><td>This is a simple formatter for integers that is | 
|  | 249 | useful when producing English diagnostics.  When the integer is 1, it prints | 
|  | 250 | as nothing.  When the integer is not 1, it prints as "s".  This allows some | 
| Chris Lattner | 627b705 | 2008-11-23 00:28:33 +0000 | [diff] [blame] | 251 | simple grammatical forms to be to be handled correctly, and eliminates the | 
|  | 252 | need to use gross things like <tt>"requires %1 parameter(s)"</tt>.</td></tr> | 
| Chris Lattner | 62fd278 | 2008-11-22 21:41:31 +0000 | [diff] [blame] | 253 |  | 
|  | 254 | <tr><td colspan="2"><b>"select" format</b></td></tr> | 
|  | 255 | <tr><td>Example:</td><td><tt>"must be a %select{unary|binary|unary or binary}2 | 
|  | 256 | operator"</tt></td></tr> | 
|  | 257 | <tr><td>Classes:</td><td>Integers</td></tr> | 
| Chris Lattner | cc54334 | 2008-11-22 23:50:47 +0000 | [diff] [blame] | 258 | <tr><td>Description:</td><td>This format specifier is used to merge multiple | 
|  | 259 | related diagnostics together into one common one, without requiring the | 
|  | 260 | different to be specified as an English string argument.  Instead of | 
|  | 261 | specifying the string, the diagnostic gets an integer argument and the | 
|  | 262 | format string selects the numbered option.  In this case, the "%2" value | 
|  | 263 | must be an integer in the range [0..2].  If it is 0, it prints 'unary', if | 
|  | 264 | it is 1 it prints 'binary' if it is 2, it prints 'unary or binary'.  This | 
|  | 265 | allows other language translations to substitute reasonable words (or entire | 
|  | 266 | phrases) based on the semantics of the diagnostic instead of having to do | 
|  | 267 | things textually.</td></tr> | 
| Chris Lattner | 62fd278 | 2008-11-22 21:41:31 +0000 | [diff] [blame] | 268 |  | 
|  | 269 | <tr><td colspan="2"><b>"plural" format</b></td></tr> | 
| Sebastian Redl | 6816856 | 2008-11-22 22:16:45 +0000 | [diff] [blame] | 270 | <tr><td>Example:</td><td><tt>"you have %1 %plural{1:mouse|:mice}1 connected to | 
|  | 271 | your computer"</tt></td></tr> | 
| Chris Lattner | 62fd278 | 2008-11-22 21:41:31 +0000 | [diff] [blame] | 272 | <tr><td>Classes:</td><td>Integers</td></tr> | 
| Sebastian Redl | 6816856 | 2008-11-22 22:16:45 +0000 | [diff] [blame] | 273 | <tr><td>Description:</td><td><p>This is a formatter for complex plural forms. | 
|  | 274 | It is designed to handle even the requirements of languages with very | 
|  | 275 | complex plural forms, as many Baltic languages have. The argument consists | 
|  | 276 | of a series of expression/form pairs, separated by ':', where the first form | 
|  | 277 | whose expression evaluates to true is the result of the modifier.</p> | 
|  | 278 | <p>An expression can be empty, in which case it is always true. See the | 
|  | 279 | example at the top. Otherwise, it is a series of one or more numeric | 
|  | 280 | conditions, separated by ','. If any condition matches, the expression | 
|  | 281 | matches. Each numeric condition can take one of three forms.</p> | 
|  | 282 | <ul> | 
|  | 283 | <li>number: A simple decimal number matches if the argument is the same | 
| Chris Lattner | 627b705 | 2008-11-23 00:28:33 +0000 | [diff] [blame] | 284 | as the number. Example: <tt>"%plural{1:mouse|:mice}4"</tt></li> | 
| Sebastian Redl | 6816856 | 2008-11-22 22:16:45 +0000 | [diff] [blame] | 285 | <li>range: A range in square brackets matches if the argument is within | 
|  | 286 | the range. Then range is inclusive both ends. Example: | 
| Chris Lattner | 627b705 | 2008-11-23 00:28:33 +0000 | [diff] [blame] | 287 | <tt>"%plural{0:none|1:one|[2,5]:some|:many}2"</tt></li> | 
|  | 288 | <li>modulo: A modulo operator is followed by a number, and | 
|  | 289 | equals sign and either a number or a range. The tests are the | 
|  | 290 | same as for plain | 
| Sebastian Redl | 6816856 | 2008-11-22 22:16:45 +0000 | [diff] [blame] | 291 | numbers and ranges, but the argument is taken modulo the number first. | 
| Chris Lattner | 627b705 | 2008-11-23 00:28:33 +0000 | [diff] [blame] | 292 | Example: <tt>"%plural{%100=0:even hundred|%100=[1,50]:lower half|:everything | 
|  | 293 | else}1"</tt></li> | 
| Sebastian Redl | 6816856 | 2008-11-22 22:16:45 +0000 | [diff] [blame] | 294 | </ul> | 
|  | 295 | <p>The parser is very unforgiving. A syntax error, even whitespace, will | 
|  | 296 | abort, as will a failure to match the argument against any | 
|  | 297 | expression.</p></td></tr> | 
| Chris Lattner | 62fd278 | 2008-11-22 21:41:31 +0000 | [diff] [blame] | 298 |  | 
| Chris Lattner | 62fd278 | 2008-11-22 21:41:31 +0000 | [diff] [blame] | 299 | </table> | 
|  | 300 |  | 
| Chris Lattner | cc54334 | 2008-11-22 23:50:47 +0000 | [diff] [blame] | 301 | <p>It is really easy to add format specifiers to the Clang diagnostics system, | 
|  | 302 | but they should be discussed before they are added.  If you're creating a lot | 
|  | 303 | of repetitive diagnostics and/or have an idea for a useful formater, please | 
|  | 304 | bring it up on the cfe-dev mainling list.</p> | 
|  | 305 |  | 
| Chris Lattner | 62fd278 | 2008-11-22 21:41:31 +0000 | [diff] [blame] | 306 | <!-- ===================================================== --> | 
|  | 307 | <h4><a name="#producingdiag">Producing the Diagnostic</a></h4> | 
|  | 308 | <!-- ===================================================== --> | 
|  | 309 |  | 
| Chris Lattner | 627b705 | 2008-11-23 00:28:33 +0000 | [diff] [blame] | 310 | <p>Now that you've created the diagnostic in the DiagnosticKinds.def file, you | 
|  | 311 | need to produce it.  Various components of Clang (e.g. the preprocessor, Sema, | 
|  | 312 | etc) provide a helper function named "Diag".  It creates a diagnostic and | 
|  | 313 | accepts the arguments, ranges, and other information that goes along with | 
|  | 314 | it.</p> | 
| Chris Lattner | 62fd278 | 2008-11-22 21:41:31 +0000 | [diff] [blame] | 315 |  | 
| Chris Lattner | 627b705 | 2008-11-23 00:28:33 +0000 | [diff] [blame] | 316 | <p>For example the binary expression error comes from code like this:</p> | 
|  | 317 |  | 
|  | 318 | <pre> | 
|  | 319 | if (various things that are bad) | 
|  | 320 | Diag(Loc, diag::err_typecheck_invalid_operands) | 
|  | 321 | << lex->getType() << rex->getType() | 
|  | 322 | << lex->getSourceRange() << rex->getSourceRange(); | 
|  | 323 | </pre> | 
|  | 324 |  | 
|  | 325 | <p>This shows that use of the Diag method: they take a location (a <a | 
|  | 326 | href="#SourceLocation">SourceLocation</a> object) and a diagnostic enum value | 
|  | 327 | (which matches the name from DiagnosticKinds.def).  If the diagnostic takes | 
|  | 328 | arguments, they are specified with the << operator: the first argument | 
|  | 329 | becomes %0, the second becomes %1, etc.  The diagnostic interface allows you to | 
| Chris Lattner | fd408ea | 2008-11-23 00:42:53 +0000 | [diff] [blame^] | 330 | specify arguments of many different types, including <tt>int</tt> and | 
|  | 331 | <tt>unsigned</tt> for integer arguments, <tt>const char*</tt> and | 
|  | 332 | <tt>std::string</tt> for string arguments, <tt>DeclarationName</tt> and | 
|  | 333 | <tt>const IdentifierInfo*</tt> for names, <tt>QualType</tt> for types, etc. | 
|  | 334 | SourceRanges are also specified with the << operator, but do not have a | 
|  | 335 | specific ordering requirement.</p> | 
| Chris Lattner | 627b705 | 2008-11-23 00:28:33 +0000 | [diff] [blame] | 336 |  | 
|  | 337 | <p>As you can see, adding and producing a diagnostic is pretty straightforward. | 
|  | 338 | The hard part is deciding exactly what you need to say to help the user, picking | 
|  | 339 | a suitable wording, and providing the information needed to format it correctly. | 
| Chris Lattner | fd408ea | 2008-11-23 00:42:53 +0000 | [diff] [blame^] | 340 | The good news is that the call site that issues a diagnostic should be | 
|  | 341 | completely independent of how the diagnostic is formatted and in what language | 
|  | 342 | it is rendered. | 
| Chris Lattner | 627b705 | 2008-11-23 00:28:33 +0000 | [diff] [blame] | 343 | </p> | 
| Chris Lattner | 62fd278 | 2008-11-22 21:41:31 +0000 | [diff] [blame] | 344 |  | 
|  | 345 | <!-- ============================================================= --> | 
|  | 346 | <h4><a name="DiagnosticClient">The DiagnosticClient Interface</a></h4> | 
|  | 347 | <!-- ============================================================= --> | 
|  | 348 |  | 
| Chris Lattner | 627b705 | 2008-11-23 00:28:33 +0000 | [diff] [blame] | 349 | <p>Once code generates a diagnostic with all of the arguments and the rest of | 
|  | 350 | the relevant information, Clang needs to know what to do with it.  As previously | 
|  | 351 | mentioned, the diagnostic machinery goes through some filtering to map a | 
|  | 352 | severity onto a diagnostic level, then (assuming the diagnostic is not mapped to | 
|  | 353 | "<tt>Ignore</tt>") it invokes an object that implements the DiagnosticClient | 
|  | 354 | interface with the information.</p> | 
|  | 355 |  | 
|  | 356 | <p>It is possible to implement this interface in many different ways.  For | 
|  | 357 | example, the normal Clang DiagnosticClient (named 'TextDiagnosticPrinter') turns | 
|  | 358 | the arguments into strings (according to the various formatting rules), prints | 
|  | 359 | out the file/line/column information and the string, then prints out the line of | 
|  | 360 | code, the source ranges, and the caret.  However, this behavior isn't required. | 
|  | 361 | </p> | 
|  | 362 |  | 
|  | 363 | <p>Another implementation of the DiagnosticClient interface is the | 
|  | 364 | 'TextDiagnosticBuffer' class, which is used when clang is in -verify mode. | 
| Chris Lattner | fd408ea | 2008-11-23 00:42:53 +0000 | [diff] [blame^] | 365 | Instead of formatting and printing out the diagnostics, this implementation just | 
|  | 366 | captures and remembers the diagnostics as they fly by.  Then -verify compares | 
|  | 367 | the list of produced diagnostics to the list of expected ones.  If they diagree, | 
|  | 368 | it prints out its own output. | 
| Chris Lattner | 627b705 | 2008-11-23 00:28:33 +0000 | [diff] [blame] | 369 | </p> | 
|  | 370 |  | 
| Chris Lattner | fd408ea | 2008-11-23 00:42:53 +0000 | [diff] [blame^] | 371 | <p>There are many other possible implementations of this interface, and this is | 
|  | 372 | why we prefer diagnostics to pass down rich structured information in arguments. | 
|  | 373 | For example, an HTML output might want declaration names be linkified to where | 
|  | 374 | they come from in the source.  Another example is that a GUI might let you click | 
|  | 375 | on typedefs to expand them.  This application would want to pass significantly | 
|  | 376 | more information about types through to the GUI than a simple flat string.  The | 
|  | 377 | interface allows this to happen.</p> | 
| Chris Lattner | 62fd278 | 2008-11-22 21:41:31 +0000 | [diff] [blame] | 378 |  | 
|  | 379 | <!-- ====================================================== --> | 
|  | 380 | <h4><a name="translation">Adding Translations to Clang</a></h4> | 
|  | 381 | <!-- ====================================================== --> | 
|  | 382 |  | 
| Chris Lattner | 627b705 | 2008-11-23 00:28:33 +0000 | [diff] [blame] | 383 | <p>Not possible yet!  Diagnostic strings should be written in UTF-8, the client | 
| Chris Lattner | fd408ea | 2008-11-23 00:42:53 +0000 | [diff] [blame^] | 384 | can translate to the relevant code page if needed.  Each translation completely | 
|  | 385 | replaces the format string for the diagnostic.</p> | 
| Chris Lattner | 62fd278 | 2008-11-22 21:41:31 +0000 | [diff] [blame] | 386 |  | 
|  | 387 |  | 
| Chris Lattner | 86920d3 | 2007-07-31 05:42:17 +0000 | [diff] [blame] | 388 | <!-- ======================================================================= --> | 
|  | 389 | <h3 id="SourceLocation">The SourceLocation and SourceManager classes</h3> | 
|  | 390 | <!-- ======================================================================= --> | 
|  | 391 |  | 
|  | 392 | <p>Strangely enough, the SourceLocation class represents a location within the | 
|  | 393 | source code of the program.  Important design points include:</p> | 
|  | 394 |  | 
|  | 395 | <ol> | 
|  | 396 | <li>sizeof(SourceLocation) must be extremely small, as these are embedded into | 
|  | 397 | many AST nodes and are passed around often.  Currently it is 32 bits.</li> | 
|  | 398 | <li>SourceLocation must be a simple value object that can be efficiently | 
|  | 399 | copied.</li> | 
|  | 400 | <li>We should be able to represent a source location for any byte of any input | 
|  | 401 | file.  This includes in the middle of tokens, in whitespace, in trigraphs, | 
|  | 402 | etc.</li> | 
|  | 403 | <li>A SourceLocation must encode the current #include stack that was active when | 
|  | 404 | the location was processed.  For example, if the location corresponds to a | 
|  | 405 | token, it should contain the set of #includes active when the token was | 
|  | 406 | lexed.  This allows us to print the #include stack for a diagnostic.</li> | 
|  | 407 | <li>SourceLocation must be able to describe macro expansions, capturing both | 
|  | 408 | the ultimate instantiation point and the source of the original character | 
|  | 409 | data.</li> | 
|  | 410 | </ol> | 
|  | 411 |  | 
|  | 412 | <p>In practice, the SourceLocation works together with the SourceManager class | 
|  | 413 | to encode two pieces of information about a location: it's physical location | 
|  | 414 | and it's virtual location.  For most tokens, these will be the same.  However, | 
|  | 415 | for a macro expansion (or tokens that came from a _Pragma directive) these will | 
|  | 416 | describe the location of the characters corresponding to the token and the | 
|  | 417 | location where the token was used (i.e. the macro instantiation point or the | 
|  | 418 | location of the _Pragma itself).</p> | 
|  | 419 |  | 
|  | 420 | <p>For efficiency, we only track one level of macro instantions: if a token was | 
|  | 421 | produced by multiple instantiations, we only track the source and ultimate | 
|  | 422 | destination.  Though we could track the intermediate instantiation points, this | 
|  | 423 | would require extra bookkeeping and no known client would benefit substantially | 
|  | 424 | from this.</p> | 
|  | 425 |  | 
|  | 426 | <p>The clang front-end inherently depends on the location of a token being | 
|  | 427 | tracked correctly.  If it is ever incorrect, the front-end may get confused and | 
|  | 428 | die.  The reason for this is that the notion of the 'spelling' of a Token in | 
|  | 429 | clang depends on being able to find the original input characters for the token. | 
|  | 430 | This concept maps directly to the "physical" location for the token.</p> | 
|  | 431 |  | 
|  | 432 | <!-- ======================================================================= --> | 
|  | 433 | <h2 id="liblex">The Lexer and Preprocessor Library</h2> | 
|  | 434 | <!-- ======================================================================= --> | 
|  | 435 |  | 
|  | 436 | <p>The Lexer library contains several tightly-connected classes that are involved | 
|  | 437 | with the nasty process of lexing and preprocessing C source code.  The main | 
|  | 438 | interface to this library for outside clients is the large <a | 
|  | 439 | href="#Preprocessor">Preprocessor</a> class. | 
|  | 440 | It contains the various pieces of state that are required to coherently read | 
|  | 441 | tokens out of a translation unit.</p> | 
|  | 442 |  | 
|  | 443 | <p>The core interface to the Preprocessor object (once it is set up) is the | 
|  | 444 | Preprocessor::Lex method, which returns the next <a href="#Token">Token</a> from | 
|  | 445 | the preprocessor stream.  There are two types of token providers that the | 
|  | 446 | preprocessor is capable of reading from: a buffer lexer (provided by the <a | 
|  | 447 | href="#Lexer">Lexer</a> class) and a buffered token stream (provided by the <a | 
| Chris Lattner | 7928125 | 2008-03-09 02:27:26 +0000 | [diff] [blame] | 448 | href="#TokenLexer">TokenLexer</a> class). | 
| Chris Lattner | 86920d3 | 2007-07-31 05:42:17 +0000 | [diff] [blame] | 449 |  | 
|  | 450 |  | 
|  | 451 | <!-- ======================================================================= --> | 
|  | 452 | <h3 id="Token">The Token class</h3> | 
|  | 453 | <!-- ======================================================================= --> | 
|  | 454 |  | 
|  | 455 | <p>The Token class is used to represent a single lexed token.  Tokens are | 
|  | 456 | intended to be used by the lexer/preprocess and parser libraries, but are not | 
|  | 457 | intended to live beyond them (for example, they should not live in the ASTs).<p> | 
|  | 458 |  | 
|  | 459 | <p>Tokens most often live on the stack (or some other location that is efficient | 
|  | 460 | to access) as the parser is running, but occasionally do get buffered up.  For | 
|  | 461 | example, macro definitions are stored as a series of tokens, and the C++ | 
|  | 462 | front-end will eventually need to buffer tokens up for tentative parsing and | 
|  | 463 | various pieces of look-ahead.  As such, the size of a Token matter.  On a 32-bit | 
|  | 464 | system, sizeof(Token) is currently 16 bytes.</p> | 
|  | 465 |  | 
|  | 466 | <p>Tokens contain the following information:</p> | 
|  | 467 |  | 
|  | 468 | <ul> | 
|  | 469 | <li><b>A SourceLocation</b> - This indicates the location of the start of the | 
|  | 470 | token.</li> | 
|  | 471 |  | 
|  | 472 | <li><b>A length</b> - This stores the length of the token as stored in the | 
|  | 473 | SourceBuffer.  For tokens that include them, this length includes trigraphs and | 
|  | 474 | escaped newlines which are ignored by later phases of the compiler.  By pointing | 
|  | 475 | into the original source buffer, it is always possible to get the original | 
|  | 476 | spelling of a token completely accurately.</li> | 
|  | 477 |  | 
|  | 478 | <li><b>IdentifierInfo</b> - If a token takes the form of an identifier, and if | 
|  | 479 | identifier lookup was enabled when the token was lexed (e.g. the lexer was not | 
|  | 480 | reading in 'raw' mode) this contains a pointer to the unique hash value for the | 
|  | 481 | identifier.  Because the lookup happens before keyword identification, this | 
|  | 482 | field is set even for language keywords like 'for'.</li> | 
|  | 483 |  | 
|  | 484 | <li><b>TokenKind</b> - This indicates the kind of token as classified by the | 
|  | 485 | lexer.  This includes things like <tt>tok::starequal</tt> (for the "*=" | 
|  | 486 | operator), <tt>tok::ampamp</tt> for the "&&" token, and keyword values | 
|  | 487 | (e.g. <tt>tok::kw_for</tt>) for identifiers that correspond to keywords.  Note | 
|  | 488 | that some tokens can be spelled multiple ways.  For example, C++ supports | 
|  | 489 | "operator keywords", where things like "and" are treated exactly like the | 
|  | 490 | "&&" operator.  In these cases, the kind value is set to | 
|  | 491 | <tt>tok::ampamp</tt>, which is good for the parser, which doesn't have to | 
|  | 492 | consider both forms.  For something that cares about which form is used (e.g. | 
|  | 493 | the preprocessor 'stringize' operator) the spelling indicates the original | 
|  | 494 | form.</li> | 
|  | 495 |  | 
|  | 496 | <li><b>Flags</b> - There are currently four flags tracked by the | 
|  | 497 | lexer/preprocessor system on a per-token basis: | 
|  | 498 |  | 
|  | 499 | <ol> | 
|  | 500 | <li><b>StartOfLine</b> - This was the first token that occurred on its input | 
|  | 501 | source line.</li> | 
|  | 502 | <li><b>LeadingSpace</b> - There was a space character either immediately | 
|  | 503 | before the token or transitively before the token as it was expanded | 
|  | 504 | through a macro.  The definition of this flag is very closely defined by | 
|  | 505 | the stringizing requirements of the preprocessor.</li> | 
|  | 506 | <li><b>DisableExpand</b> - This flag is used internally to the preprocessor to | 
|  | 507 | represent identifier tokens which have macro expansion disabled.  This | 
|  | 508 | prevents them from being considered as candidates for macro expansion ever | 
|  | 509 | in the future.</li> | 
|  | 510 | <li><b>NeedsCleaning</b> - This flag is set if the original spelling for the | 
|  | 511 | token includes a trigraph or escaped newline.  Since this is uncommon, | 
|  | 512 | many pieces of code can fast-path on tokens that did not need cleaning. | 
|  | 513 | </p> | 
|  | 514 | </ol> | 
|  | 515 | </li> | 
|  | 516 | </ul> | 
|  | 517 |  | 
|  | 518 | <p>One interesting (and somewhat unusual) aspect of tokens is that they don't | 
|  | 519 | contain any semantic information about the lexed value.  For example, if the | 
|  | 520 | token was a pp-number token, we do not represent the value of the number that | 
|  | 521 | was lexed (this is left for later pieces of code to decide).  Additionally, the | 
|  | 522 | lexer library has no notion of typedef names vs variable names: both are | 
|  | 523 | returned as identifiers, and the parser is left to decide whether a specific | 
|  | 524 | identifier is a typedef or a variable (tracking this requires scope information | 
|  | 525 | among other things).</p> | 
|  | 526 |  | 
|  | 527 | <!-- ======================================================================= --> | 
|  | 528 | <h3 id="Lexer">The Lexer class</h3> | 
|  | 529 | <!-- ======================================================================= --> | 
|  | 530 |  | 
|  | 531 | <p>The Lexer class provides the mechanics of lexing tokens out of a source | 
|  | 532 | buffer and deciding what they mean.  The Lexer is complicated by the fact that | 
|  | 533 | it operates on raw buffers that have not had spelling eliminated (this is a | 
|  | 534 | necessity to get decent performance), but this is countered with careful coding | 
|  | 535 | as well as standard performance techniques (for example, the comment handling | 
|  | 536 | code is vectorized on X86 and PowerPC hosts).</p> | 
|  | 537 |  | 
|  | 538 | <p>The lexer has a couple of interesting modal features:</p> | 
|  | 539 |  | 
|  | 540 | <ul> | 
|  | 541 | <li>The lexer can operate in 'raw' mode.  This mode has several features that | 
|  | 542 | make it possible to quickly lex the file (e.g. it stops identifier lookup, | 
|  | 543 | doesn't specially handle preprocessor tokens, handles EOF differently, etc). | 
|  | 544 | This mode is used for lexing within an "<tt>#if 0</tt>" block, for | 
|  | 545 | example.</li> | 
|  | 546 | <li>The lexer can capture and return comments as tokens.  This is required to | 
|  | 547 | support the -C preprocessor mode, which passes comments through, and is | 
|  | 548 | used by the diagnostic checker to identifier expect-error annotations.</li> | 
|  | 549 | <li>The lexer can be in ParsingFilename mode, which happens when preprocessing | 
| Chris Lattner | 8438624 | 2007-09-16 19:25:23 +0000 | [diff] [blame] | 550 | after reading a #include directive.  This mode changes the parsing of '<' | 
| Chris Lattner | 86920d3 | 2007-07-31 05:42:17 +0000 | [diff] [blame] | 551 | to return an "angled string" instead of a bunch of tokens for each thing | 
|  | 552 | within the filename.</li> | 
|  | 553 | <li>When parsing a preprocessor directive (after "<tt>#</tt>") the | 
|  | 554 | ParsingPreprocessorDirective mode is entered.  This changes the parser to | 
|  | 555 | return EOM at a newline.</li> | 
|  | 556 | <li>The Lexer uses a LangOptions object to know whether trigraphs are enabled, | 
|  | 557 | whether C++ or ObjC keywords are recognized, etc.</li> | 
|  | 558 | </ul> | 
|  | 559 |  | 
|  | 560 | <p>In addition to these modes, the lexer keeps track of a couple of other | 
|  | 561 | features that are local to a lexed buffer, which change as the buffer is | 
|  | 562 | lexed:</p> | 
|  | 563 |  | 
|  | 564 | <ul> | 
|  | 565 | <li>The Lexer uses BufferPtr to keep track of the current character being | 
|  | 566 | lexed.</li> | 
|  | 567 | <li>The Lexer uses IsAtStartOfLine to keep track of whether the next lexed token | 
|  | 568 | will start with its "start of line" bit set.</li> | 
|  | 569 | <li>The Lexer keeps track of the current #if directives that are active (which | 
|  | 570 | can be nested).</li> | 
|  | 571 | <li>The Lexer keeps track of an <a href="#MultipleIncludeOpt"> | 
|  | 572 | MultipleIncludeOpt</a> object, which is used to | 
|  | 573 | detect whether the buffer uses the standard "<tt>#ifndef XX</tt> / | 
|  | 574 | <tt>#define XX</tt>" idiom to prevent multiple inclusion.  If a buffer does, | 
|  | 575 | subsequent includes can be ignored if the XX macro is defined.</li> | 
|  | 576 | </ul> | 
|  | 577 |  | 
|  | 578 | <!-- ======================================================================= --> | 
| Chris Lattner | 7928125 | 2008-03-09 02:27:26 +0000 | [diff] [blame] | 579 | <h3 id="TokenLexer">The TokenLexer class</h3> | 
| Chris Lattner | 86920d3 | 2007-07-31 05:42:17 +0000 | [diff] [blame] | 580 | <!-- ======================================================================= --> | 
|  | 581 |  | 
| Chris Lattner | 7928125 | 2008-03-09 02:27:26 +0000 | [diff] [blame] | 582 | <p>The TokenLexer class is a token provider that returns tokens from a list | 
| Chris Lattner | 86920d3 | 2007-07-31 05:42:17 +0000 | [diff] [blame] | 583 | of tokens that came from somewhere else.  It typically used for two things: 1) | 
|  | 584 | returning tokens from a macro definition as it is being expanded 2) returning | 
|  | 585 | tokens from an arbitrary buffer of tokens.  The later use is used by _Pragma and | 
|  | 586 | will most likely be used to handle unbounded look-ahead for the C++ parser.</p> | 
|  | 587 |  | 
|  | 588 | <!-- ======================================================================= --> | 
|  | 589 | <h3 id="MultipleIncludeOpt">The MultipleIncludeOpt class</h3> | 
|  | 590 | <!-- ======================================================================= --> | 
|  | 591 |  | 
|  | 592 | <p>The MultipleIncludeOpt class implements a really simple little state machine | 
|  | 593 | that is used to detect the standard "<tt>#ifndef XX</tt> / <tt>#define XX</tt>" | 
|  | 594 | idiom that people typically use to prevent multiple inclusion of headers.  If a | 
|  | 595 | buffer uses this idiom and is subsequently #include'd, the preprocessor can | 
|  | 596 | simply check to see whether the guarding condition is defined or not.  If so, | 
|  | 597 | the preprocessor can completely ignore the include of the header.</p> | 
|  | 598 |  | 
|  | 599 |  | 
|  | 600 |  | 
|  | 601 | <!-- ======================================================================= --> | 
|  | 602 | <h2 id="libparse">The Parser Library</h2> | 
|  | 603 | <!-- ======================================================================= --> | 
|  | 604 |  | 
|  | 605 | <!-- ======================================================================= --> | 
|  | 606 | <h2 id="libast">The AST Library</h2> | 
|  | 607 | <!-- ======================================================================= --> | 
|  | 608 |  | 
|  | 609 | <!-- ======================================================================= --> | 
|  | 610 | <h3 id="Type">The Type class and its subclasses</h3> | 
|  | 611 | <!-- ======================================================================= --> | 
|  | 612 |  | 
|  | 613 | <p>The Type class (and its subclasses) are an important part of the AST.  Types | 
|  | 614 | are accessed through the ASTContext class, which implicitly creates and uniques | 
|  | 615 | them as they are needed.  Types have a couple of non-obvious features: 1) they | 
|  | 616 | do not capture type qualifiers like const or volatile (See | 
|  | 617 | <a href="#QualType">QualType</a>), and 2) they implicitly capture typedef | 
| Chris Lattner | 8a2bc62 | 2007-07-31 06:37:39 +0000 | [diff] [blame] | 618 | information.  Once created, types are immutable (unlike decls).</p> | 
| Chris Lattner | 86920d3 | 2007-07-31 05:42:17 +0000 | [diff] [blame] | 619 |  | 
|  | 620 | <p>Typedefs in C make semantic analysis a bit more complex than it would | 
|  | 621 | be without them.  The issue is that we want to capture typedef information | 
|  | 622 | and represent it in the AST perfectly, but the semantics of operations need to | 
|  | 623 | "see through" typedefs.  For example, consider this code:</p> | 
|  | 624 |  | 
|  | 625 | <code> | 
|  | 626 | void func() {<br> | 
| Bill Wendling | 30d1775 | 2007-10-06 01:56:01 +0000 | [diff] [blame] | 627 |   typedef int foo;<br> | 
|  | 628 |   foo X, *Y;<br> | 
|  | 629 |   typedef foo* bar;<br> | 
|  | 630 |   bar Z;<br> | 
|  | 631 |   *X;   <i>// error</i><br> | 
|  | 632 |   **Y;  <i>// error</i><br> | 
|  | 633 |   **Z;  <i>// error</i><br> | 
| Chris Lattner | 86920d3 | 2007-07-31 05:42:17 +0000 | [diff] [blame] | 634 | }<br> | 
|  | 635 | </code> | 
|  | 636 |  | 
|  | 637 | <p>The code above is illegal, and thus we expect there to be diagnostics emitted | 
|  | 638 | on the annotated lines.  In this example, we expect to get:</p> | 
|  | 639 |  | 
|  | 640 | <pre> | 
| Chris Lattner | 8a2bc62 | 2007-07-31 06:37:39 +0000 | [diff] [blame] | 641 | <b>test.c:6:1: error: indirection requires pointer operand ('foo' invalid)</b> | 
| Chris Lattner | 86920d3 | 2007-07-31 05:42:17 +0000 | [diff] [blame] | 642 | *X; // error | 
|  | 643 | <font color="blue">^~</font> | 
| Chris Lattner | 8a2bc62 | 2007-07-31 06:37:39 +0000 | [diff] [blame] | 644 | <b>test.c:7:1: error: indirection requires pointer operand ('foo' invalid)</b> | 
| Chris Lattner | 86920d3 | 2007-07-31 05:42:17 +0000 | [diff] [blame] | 645 | **Y; // error | 
|  | 646 | <font color="blue">^~~</font> | 
| Chris Lattner | 8a2bc62 | 2007-07-31 06:37:39 +0000 | [diff] [blame] | 647 | <b>test.c:8:1: error: indirection requires pointer operand ('foo' invalid)</b> | 
|  | 648 | **Z; // error | 
|  | 649 | <font color="blue">^~~</font> | 
| Chris Lattner | 86920d3 | 2007-07-31 05:42:17 +0000 | [diff] [blame] | 650 | </pre> | 
|  | 651 |  | 
|  | 652 | <p>While this example is somewhat silly, it illustrates the point: we want to | 
|  | 653 | retain typedef information where possible, so that we can emit errors about | 
|  | 654 | "<tt>std::string</tt>" instead of "<tt>std::basic_string<char, std:...</tt>". | 
|  | 655 | Doing this requires properly keeping typedef information (for example, the type | 
|  | 656 | of "X" is "foo", not "int"), and requires properly propagating it through the | 
| Chris Lattner | 8a2bc62 | 2007-07-31 06:37:39 +0000 | [diff] [blame] | 657 | various operators (for example, the type of *Y is "foo", not "int").  In order | 
|  | 658 | to retain this information, the type of these expressions is an instance of the | 
|  | 659 | TypedefType class, which indicates that the type of these expressions is a | 
|  | 660 | typedef for foo. | 
|  | 661 | </p> | 
| Chris Lattner | 86920d3 | 2007-07-31 05:42:17 +0000 | [diff] [blame] | 662 |  | 
| Chris Lattner | 8a2bc62 | 2007-07-31 06:37:39 +0000 | [diff] [blame] | 663 | <p>Representing types like this is great for diagnostics, because the | 
|  | 664 | user-specified type is always immediately available.  There are two problems | 
|  | 665 | with this: first, various semantic checks need to make judgements about the | 
| Chris Lattner | 33fc68a | 2007-07-31 18:54:50 +0000 | [diff] [blame] | 666 | <em>actual structure</em> of a type, ignoring typdefs.  Second, we need an | 
|  | 667 | efficient way to query whether two types are structurally identical to each | 
|  | 668 | other, ignoring typedefs.  The solution to both of these problems is the idea of | 
| Chris Lattner | 8a2bc62 | 2007-07-31 06:37:39 +0000 | [diff] [blame] | 669 | canonical types.</p> | 
| Chris Lattner | 86920d3 | 2007-07-31 05:42:17 +0000 | [diff] [blame] | 670 |  | 
| Chris Lattner | 62fd278 | 2008-11-22 21:41:31 +0000 | [diff] [blame] | 671 | <!-- =============== --> | 
| Chris Lattner | 8a2bc62 | 2007-07-31 06:37:39 +0000 | [diff] [blame] | 672 | <h4>Canonical Types</h4> | 
| Chris Lattner | 62fd278 | 2008-11-22 21:41:31 +0000 | [diff] [blame] | 673 | <!-- =============== --> | 
| Chris Lattner | 86920d3 | 2007-07-31 05:42:17 +0000 | [diff] [blame] | 674 |  | 
| Chris Lattner | 8a2bc62 | 2007-07-31 06:37:39 +0000 | [diff] [blame] | 675 | <p>Every instance of the Type class contains a canonical type pointer.  For | 
|  | 676 | simple types with no typedefs involved (e.g. "<tt>int</tt>", "<tt>int*</tt>", | 
|  | 677 | "<tt>int**</tt>"), the type just points to itself.  For types that have a | 
|  | 678 | typedef somewhere in their structure (e.g. "<tt>foo</tt>", "<tt>foo*</tt>", | 
|  | 679 | "<tt>foo**</tt>", "<tt>bar</tt>"), the canonical type pointer points to their | 
|  | 680 | structurally equivalent type without any typedefs (e.g. "<tt>int</tt>", | 
|  | 681 | "<tt>int*</tt>", "<tt>int**</tt>", and "<tt>int*</tt>" respectively).</p> | 
| Chris Lattner | 86920d3 | 2007-07-31 05:42:17 +0000 | [diff] [blame] | 682 |  | 
| Chris Lattner | 8a2bc62 | 2007-07-31 06:37:39 +0000 | [diff] [blame] | 683 | <p>This design provides a constant time operation (dereferencing the canonical | 
|  | 684 | type pointer) that gives us access to the structure of types.  For example, | 
|  | 685 | we can trivially tell that "bar" and "foo*" are the same type by dereferencing | 
|  | 686 | their canonical type pointers and doing a pointer comparison (they both point | 
|  | 687 | to the single "<tt>int*</tt>" type).</p> | 
|  | 688 |  | 
|  | 689 | <p>Canonical types and typedef types bring up some complexities that must be | 
|  | 690 | carefully managed.  Specifically, the "isa/cast/dyncast" operators generally | 
|  | 691 | shouldn't be used in code that is inspecting the AST.  For example, when type | 
|  | 692 | checking the indirection operator (unary '*' on a pointer), the type checker | 
|  | 693 | must verify that the operand has a pointer type.  It would not be correct to | 
|  | 694 | check that with "<tt>isa<PointerType>(SubExpr->getType())</tt>", | 
|  | 695 | because this predicate would fail if the subexpression had a typedef type.</p> | 
|  | 696 |  | 
|  | 697 | <p>The solution to this problem are a set of helper methods on Type, used to | 
|  | 698 | check their properties.  In this case, it would be correct to use | 
|  | 699 | "<tt>SubExpr->getType()->isPointerType()</tt>" to do the check.  This | 
|  | 700 | predicate will return true if the <em>canonical type is a pointer</em>, which is | 
|  | 701 | true any time the type is structurally a pointer type.  The only hard part here | 
|  | 702 | is remembering not to use the <tt>isa/cast/dyncast</tt> operations.</p> | 
|  | 703 |  | 
|  | 704 | <p>The second problem we face is how to get access to the pointer type once we | 
|  | 705 | know it exists.  To continue the example, the result type of the indirection | 
|  | 706 | operator is the pointee type of the subexpression.  In order to determine the | 
|  | 707 | type, we need to get the instance of PointerType that best captures the typedef | 
|  | 708 | information in the program.  If the type of the expression is literally a | 
|  | 709 | PointerType, we can return that, otherwise we have to dig through the | 
|  | 710 | typedefs to find the pointer type.  For example, if the subexpression had type | 
|  | 711 | "<tt>foo*</tt>", we could return that type as the result.  If the subexpression | 
|  | 712 | had type "<tt>bar</tt>", we want to return "<tt>foo*</tt>" (note that we do | 
|  | 713 | <em>not</em> want "<tt>int*</tt>").  In order to provide all of this, Type has | 
| Chris Lattner | 11406c1 | 2007-07-31 16:50:51 +0000 | [diff] [blame] | 714 | a getAsPointerType() method that checks whether the type is structurally a | 
| Chris Lattner | 8a2bc62 | 2007-07-31 06:37:39 +0000 | [diff] [blame] | 715 | PointerType and, if so, returns the best one.  If not, it returns a null | 
|  | 716 | pointer.</p> | 
|  | 717 |  | 
|  | 718 | <p>This structure is somewhat mystical, but after meditating on it, it will | 
|  | 719 | make sense to you :).</p> | 
| Chris Lattner | 86920d3 | 2007-07-31 05:42:17 +0000 | [diff] [blame] | 720 |  | 
|  | 721 | <!-- ======================================================================= --> | 
|  | 722 | <h3 id="QualType">The QualType class</h3> | 
|  | 723 | <!-- ======================================================================= --> | 
|  | 724 |  | 
|  | 725 | <p>The QualType class is designed as a trivial value class that is small, | 
|  | 726 | passed by-value and is efficient to query.  The idea of QualType is that it | 
|  | 727 | stores the type qualifiers (const, volatile, restrict) separately from the types | 
|  | 728 | themselves: QualType is conceptually a pair of "Type*" and bits for the type | 
|  | 729 | qualifiers.</p> | 
|  | 730 |  | 
|  | 731 | <p>By storing the type qualifiers as bits in the conceptual pair, it is | 
|  | 732 | extremely efficient to get the set of qualifiers on a QualType (just return the | 
|  | 733 | field of the pair), add a type qualifier (which is a trivial constant-time | 
|  | 734 | operation that sets a bit), and remove one or more type qualifiers (just return | 
|  | 735 | a QualType with the bitfield set to empty).</p> | 
|  | 736 |  | 
|  | 737 | <p>Further, because the bits are stored outside of the type itself, we do not | 
|  | 738 | need to create duplicates of types with different sets of qualifiers (i.e. there | 
|  | 739 | is only a single heap allocated "int" type: "const int" and "volatile const int" | 
|  | 740 | both point to the same heap allocated "int" type).  This reduces the heap size | 
|  | 741 | used to represent bits and also means we do not have to consider qualifiers when | 
|  | 742 | uniquing types (<a href="#Type">Type</a> does not even contain qualifiers).</p> | 
|  | 743 |  | 
|  | 744 | <p>In practice, on hosts where it is safe, the 3 type qualifiers are stored in | 
|  | 745 | the low bit of the pointer to the Type object.  This means that QualType is | 
|  | 746 | exactly the same size as a pointer, and this works fine on any system where | 
|  | 747 | malloc'd objects are at least 8 byte aligned.</p> | 
| Ted Kremenek | 8bc0571 | 2007-10-10 23:01:43 +0000 | [diff] [blame] | 748 |  | 
|  | 749 | <!-- ======================================================================= --> | 
| Douglas Gregor | 2e1cd42 | 2008-11-17 14:58:09 +0000 | [diff] [blame] | 750 | <h3 id="DeclarationName">Declaration names</h3> | 
|  | 751 | <!-- ======================================================================= --> | 
|  | 752 |  | 
|  | 753 | <p>The <tt>DeclarationName</tt> class represents the name of a | 
|  | 754 | declaration in Clang. Declarations in the C family of languages can | 
|  | 755 | take several different forms. Most declarations are named by are | 
|  | 756 | simple identifiers, e.g., "<code>f</code>" and "<code>x</code>" in | 
|  | 757 | the function declaration <code>f(int x)</code>. In C++, declaration | 
|  | 758 | names can also name class constructors ("<code>Class</code>" | 
|  | 759 | in <code>struct Class { Class(); }</code>), class destructors | 
|  | 760 | ("<code>~Class</code>"), overloaded operator names ("operator+"), | 
|  | 761 | and conversion functions ("<code>operator void const *</code>"). In | 
|  | 762 | Objective-C, declaration names can refer to the names of Objective-C | 
|  | 763 | methods, which involve the method name and the parameters, | 
|  | 764 | collectively called a <i>selector</i>, e.g.., | 
|  | 765 | "<code>setWidth:height:</code>". Since all of these kinds of | 
|  | 766 | entities--variables, functions, Objective-C methods, C++ | 
|  | 767 | constructors, destructors, and operators---are represented as | 
|  | 768 | subclasses of Clang's common <code>NamedDecl</code> | 
|  | 769 | class, <code>DeclarationName</code> is designed to efficiently | 
|  | 770 | represent any kind of name.</p> | 
|  | 771 |  | 
|  | 772 | <p>Given | 
|  | 773 | a <code>DeclarationName</code> <code>N</code>, <code>N.getNameKind()</code> | 
| Douglas Gregor | 2def483 | 2008-11-17 20:34:05 +0000 | [diff] [blame] | 774 | will produce a value that describes what kind of name <code>N</code> | 
| Douglas Gregor | e94ca9e4 | 2008-11-18 14:39:36 +0000 | [diff] [blame] | 775 | stores. There are 8 options (all of the names are inside | 
| Douglas Gregor | 2e1cd42 | 2008-11-17 14:58:09 +0000 | [diff] [blame] | 776 | the <code>DeclarationName</code> class)</p> | 
|  | 777 | <dl> | 
|  | 778 | <dt>Identifier</dt> | 
|  | 779 | <dd>The name is a simple | 
|  | 780 | identifier. Use <code>N.getAsIdentifierInfo()</code> to retrieve the | 
|  | 781 | corresponding <code>IdentifierInfo*</code> pointing to the actual | 
|  | 782 | identifier. Note that C++ overloaded operators (e.g., | 
|  | 783 | "<code>operator+</code>") are represented as special kinds of | 
|  | 784 | identifiers. Use <code>IdentifierInfo</code>'s <code>getOverloadedOperatorID</code> | 
|  | 785 | function to determine whether an identifier is an overloaded | 
|  | 786 | operator name.</dd> | 
|  | 787 |  | 
|  | 788 | <dt>ObjCZeroArgSelector, ObjCOneArgSelector, | 
|  | 789 | ObjCMultiArgSelector</dt> | 
|  | 790 | <dd>The name is an Objective-C selector, which can be retrieved as a | 
|  | 791 | <code>Selector</code> instance | 
|  | 792 | via <code>N.getObjCSelector()</code>. The three possible name | 
|  | 793 | kinds for Objective-C reflect an optimization within | 
|  | 794 | the <code>DeclarationName</code> class: both zero- and | 
|  | 795 | one-argument selectors are stored as a | 
|  | 796 | masked <code>IdentifierInfo</code> pointer, and therefore require | 
|  | 797 | very little space, since zero- and one-argument selectors are far | 
|  | 798 | more common than multi-argument selectors (which use a different | 
|  | 799 | structure).</dd> | 
|  | 800 |  | 
|  | 801 | <dt>CXXConstructorName</dt> | 
|  | 802 | <dd>The name is a C++ constructor | 
|  | 803 | name. Use <code>N.getCXXNameType()</code> to retrieve | 
|  | 804 | the <a href="#QualType">type</a> that this constructor is meant to | 
|  | 805 | construct. The type is always the canonical type, since all | 
|  | 806 | constructors for a given type have the same name.</dd> | 
|  | 807 |  | 
|  | 808 | <dt>CXXDestructorName</dt> | 
|  | 809 | <dd>The name is a C++ destructor | 
|  | 810 | name. Use <code>N.getCXXNameType()</code> to retrieve | 
|  | 811 | the <a href="#QualType">type</a> whose destructor is being | 
|  | 812 | named. This type is always a canonical type.</dd> | 
|  | 813 |  | 
|  | 814 | <dt>CXXConversionFunctionName</dt> | 
|  | 815 | <dd>The name is a C++ conversion function. Conversion functions are | 
|  | 816 | named according to the type they convert to, e.g., "<code>operator void | 
|  | 817 | const *</code>". Use <code>N.getCXXNameType()</code> to retrieve | 
|  | 818 | the type that this conversion function converts to. This type is | 
|  | 819 | always a canonical type.</dd> | 
| Douglas Gregor | e94ca9e4 | 2008-11-18 14:39:36 +0000 | [diff] [blame] | 820 |  | 
|  | 821 | <dt>CXXOperatorName</dt> | 
|  | 822 | <dd>The name is a C++ overloaded operator name. Overloaded operators | 
|  | 823 | are named according to their spelling, e.g., | 
|  | 824 | "<code>operator+</code>" or "<code>operator new | 
|  | 825 | []</code>". Use <code>N.getCXXOverloadedOperator()</code> to | 
|  | 826 | retrieve the overloaded operator (a value of | 
|  | 827 | type <code>OverloadedOperatorKind</code>).</dd> | 
| Douglas Gregor | 2e1cd42 | 2008-11-17 14:58:09 +0000 | [diff] [blame] | 828 | </dl> | 
|  | 829 |  | 
|  | 830 | <p><code>DeclarationName</code>s are cheap to create, copy, and | 
|  | 831 | compare. They require only a single pointer's worth of storage in | 
| Douglas Gregor | e94ca9e4 | 2008-11-18 14:39:36 +0000 | [diff] [blame] | 832 | the common cases (identifiers, zero- | 
| Douglas Gregor | 2e1cd42 | 2008-11-17 14:58:09 +0000 | [diff] [blame] | 833 | and one-argument Objective-C selectors) and use dense, uniqued | 
|  | 834 | storage for the other kinds of | 
|  | 835 | names. Two <code>DeclarationName</code>s can be compared for | 
|  | 836 | equality (<code>==</code>, <code>!=</code>) using a simple bitwise | 
|  | 837 | comparison, can be ordered | 
|  | 838 | with <code><</code>, <code>></code>, <code><=</code>, | 
|  | 839 | and <code>>=</code> (which provide a lexicographical ordering for | 
|  | 840 | normal identifiers but an unspecified ordering for other kinds of | 
|  | 841 | names), and can be placed into LLVM <code>DenseMap</code>s | 
|  | 842 | and <code>DenseSet</code>s.</p> | 
|  | 843 |  | 
|  | 844 | <p><code>DeclarationName</code> instances can be created in different | 
|  | 845 | ways depending on what kind of name the instance will store. Normal | 
| Douglas Gregor | e94ca9e4 | 2008-11-18 14:39:36 +0000 | [diff] [blame] | 846 | identifiers (<code>IdentifierInfo</code> pointers) and Objective-C selectors | 
| Douglas Gregor | 2e1cd42 | 2008-11-17 14:58:09 +0000 | [diff] [blame] | 847 | (<code>Selector</code>) can be implicitly converted | 
|  | 848 | to <code>DeclarationName</code>s. Names for C++ constructors, | 
| Douglas Gregor | e94ca9e4 | 2008-11-18 14:39:36 +0000 | [diff] [blame] | 849 | destructors, conversion functions, and overloaded operators can be retrieved from | 
| Douglas Gregor | 2e1cd42 | 2008-11-17 14:58:09 +0000 | [diff] [blame] | 850 | the <code>DeclarationNameTable</code>, an instance of which is | 
|  | 851 | available as <code>ASTContext::DeclarationNames</code>. The member | 
|  | 852 | functions <code>getCXXConstructorName</code>, <code>getCXXDestructorName</code>, | 
| Douglas Gregor | e94ca9e4 | 2008-11-18 14:39:36 +0000 | [diff] [blame] | 853 | <code>getCXXConversionFunctionName</code>, and <code>getCXXOperatorName</code>, respectively, | 
|  | 854 | return <code>DeclarationName</code> instances for the four kinds of | 
| Douglas Gregor | 2e1cd42 | 2008-11-17 14:58:09 +0000 | [diff] [blame] | 855 | C++ special function names.</p> | 
|  | 856 |  | 
|  | 857 | <!-- ======================================================================= --> | 
| Ted Kremenek | 8bc0571 | 2007-10-10 23:01:43 +0000 | [diff] [blame] | 858 | <h3 id="CFG">The <tt>CFG</tt> class</h3> | 
|  | 859 | <!-- ======================================================================= --> | 
|  | 860 |  | 
|  | 861 | <p>The <tt>CFG</tt> class is designed to represent a source-level | 
|  | 862 | control-flow graph for a single statement (<tt>Stmt*</tt>).  Typically | 
|  | 863 | instances of <tt>CFG</tt> are constructed for function bodies (usually | 
|  | 864 | an instance of <tt>CompoundStmt</tt>), but can also be instantiated to | 
|  | 865 | represent the control-flow of any class that subclasses <tt>Stmt</tt>, | 
|  | 866 | which includes simple expressions.  Control-flow graphs are especially | 
|  | 867 | useful for performing | 
|  | 868 | <a href="http://en.wikipedia.org/wiki/Data_flow_analysis#Sensitivities">flow- | 
|  | 869 | or path-sensitive</a> program analyses on a given function.</p> | 
|  | 870 |  | 
| Chris Lattner | 62fd278 | 2008-11-22 21:41:31 +0000 | [diff] [blame] | 871 | <!-- ============ --> | 
| Ted Kremenek | 8bc0571 | 2007-10-10 23:01:43 +0000 | [diff] [blame] | 872 | <h4>Basic Blocks</h4> | 
| Chris Lattner | 62fd278 | 2008-11-22 21:41:31 +0000 | [diff] [blame] | 873 | <!-- ============ --> | 
| Ted Kremenek | 8bc0571 | 2007-10-10 23:01:43 +0000 | [diff] [blame] | 874 |  | 
|  | 875 | <p>Concretely, an instance of <tt>CFG</tt> is a collection of basic | 
|  | 876 | blocks.  Each basic block is an instance of <tt>CFGBlock</tt>, which | 
|  | 877 | simply contains an ordered sequence of <tt>Stmt*</tt> (each referring | 
|  | 878 | to statements in the AST).  The ordering of statements within a block | 
|  | 879 | indicates unconditional flow of control from one statement to the | 
|  | 880 | next.  <a href="#ConditionalControlFlow">Conditional control-flow</a> | 
|  | 881 | is represented using edges between basic blocks.  The statements | 
|  | 882 | within a given <tt>CFGBlock</tt> can be traversed using | 
|  | 883 | the <tt>CFGBlock::*iterator</tt> interface.</p> | 
|  | 884 |  | 
|  | 885 | <p> | 
| Ted Kremenek | 18e17e7 | 2007-10-18 22:50:52 +0000 | [diff] [blame] | 886 | A <tt>CFG</tt> object owns the instances of <tt>CFGBlock</tt> within | 
| Ted Kremenek | 8bc0571 | 2007-10-10 23:01:43 +0000 | [diff] [blame] | 887 | the control-flow graph it represents.  Each <tt>CFGBlock</tt> within a | 
|  | 888 | CFG is also uniquely numbered (accessible | 
|  | 889 | via <tt>CFGBlock::getBlockID()</tt>).  Currently the number is | 
|  | 890 | based on the ordering the blocks were created, but no assumptions | 
|  | 891 | should be made on how <tt>CFGBlock</tt>s are numbered other than their | 
|  | 892 | numbers are unique and that they are numbered from 0..N-1 (where N is | 
|  | 893 | the number of basic blocks in the CFG).</p> | 
|  | 894 |  | 
| Chris Lattner | 62fd278 | 2008-11-22 21:41:31 +0000 | [diff] [blame] | 895 | <!-- ===================== --> | 
| Ted Kremenek | 8bc0571 | 2007-10-10 23:01:43 +0000 | [diff] [blame] | 896 | <h4>Entry and Exit Blocks</h4> | 
| Chris Lattner | 62fd278 | 2008-11-22 21:41:31 +0000 | [diff] [blame] | 897 | <!-- ===================== --> | 
| Ted Kremenek | 8bc0571 | 2007-10-10 23:01:43 +0000 | [diff] [blame] | 898 |  | 
|  | 899 | Each instance of <tt>CFG</tt> contains two special blocks: | 
|  | 900 | an <i>entry</i> block (accessible via <tt>CFG::getEntry()</tt>), which | 
|  | 901 | has no incoming edges, and an <i>exit</i> block (accessible | 
|  | 902 | via <tt>CFG::getExit()</tt>), which has no outgoing edges.  Neither | 
|  | 903 | block contains any statements, and they serve the role of providing a | 
|  | 904 | clear entrance and exit for a body of code such as a function body. | 
|  | 905 | The presence of these empty blocks greatly simplifies the | 
|  | 906 | implementation of many analyses built on top of CFGs. | 
|  | 907 |  | 
| Chris Lattner | 62fd278 | 2008-11-22 21:41:31 +0000 | [diff] [blame] | 908 | <!-- ===================================================== --> | 
| Ted Kremenek | 8bc0571 | 2007-10-10 23:01:43 +0000 | [diff] [blame] | 909 | <h4 id ="ConditionalControlFlow">Conditional Control-Flow</h4> | 
| Chris Lattner | 62fd278 | 2008-11-22 21:41:31 +0000 | [diff] [blame] | 910 | <!-- ===================================================== --> | 
| Ted Kremenek | 8bc0571 | 2007-10-10 23:01:43 +0000 | [diff] [blame] | 911 |  | 
|  | 912 | <p>Conditional control-flow (such as those induced by if-statements | 
|  | 913 | and loops) is represented as edges between <tt>CFGBlock</tt>s. | 
|  | 914 | Because different C language constructs can induce control-flow, | 
|  | 915 | each <tt>CFGBlock</tt> also records an extra <tt>Stmt*</tt> that | 
|  | 916 | represents the <i>terminator</i> of the block.  A terminator is simply | 
|  | 917 | the statement that caused the control-flow, and is used to identify | 
|  | 918 | the nature of the conditional control-flow between blocks.  For | 
|  | 919 | example, in the case of an if-statement, the terminator refers to | 
|  | 920 | the <tt>IfStmt</tt> object in the AST that represented the given | 
|  | 921 | branch.</p> | 
|  | 922 |  | 
|  | 923 | <p>To illustrate, consider the following code example:</p> | 
|  | 924 |  | 
|  | 925 | <code> | 
|  | 926 | int foo(int x) {<br> | 
|  | 927 |   x = x + 1;<br> | 
|  | 928 | <br> | 
|  | 929 |   if (x > 2) x++;<br> | 
|  | 930 |   else {<br> | 
|  | 931 |     x += 2;<br> | 
|  | 932 |     x *= 2;<br> | 
|  | 933 |   }<br> | 
|  | 934 | <br> | 
|  | 935 |   return x;<br> | 
|  | 936 | } | 
|  | 937 | </code> | 
|  | 938 |  | 
|  | 939 | <p>After invoking the parser+semantic analyzer on this code fragment, | 
|  | 940 | the AST of the body of <tt>foo</tt> is referenced by a | 
|  | 941 | single <tt>Stmt*</tt>.  We can then construct an instance | 
|  | 942 | of <tt>CFG</tt> representing the control-flow graph of this function | 
|  | 943 | body by single call to a static class method:</p> | 
|  | 944 |  | 
|  | 945 | <code> | 
|  | 946 |   Stmt* FooBody = ...<br> | 
|  | 947 |   CFG*  FooCFG = <b>CFG::buildCFG</b>(FooBody); | 
|  | 948 | </code> | 
|  | 949 |  | 
|  | 950 | <p>It is the responsibility of the caller of <tt>CFG::buildCFG</tt> | 
|  | 951 | to <tt>delete</tt> the returned <tt>CFG*</tt> when the CFG is no | 
|  | 952 | longer needed.</p> | 
|  | 953 |  | 
|  | 954 | <p>Along with providing an interface to iterate over | 
|  | 955 | its <tt>CFGBlock</tt>s, the <tt>CFG</tt> class also provides methods | 
|  | 956 | that are useful for debugging and visualizing CFGs.  For example, the | 
|  | 957 | method | 
|  | 958 | <tt>CFG::dump()</tt> dumps a pretty-printed version of the CFG to | 
|  | 959 | standard error.  This is especially useful when one is using a | 
|  | 960 | debugger such as gdb.  For example, here is the output | 
|  | 961 | of <tt>FooCFG->dump()</tt>:</p> | 
|  | 962 |  | 
|  | 963 | <code> | 
|  | 964 |  [ B5 (ENTRY) ]<br> | 
|  | 965 |     Predecessors (0):<br> | 
|  | 966 |     Successors (1): B4<br> | 
|  | 967 | <br> | 
|  | 968 |  [ B4 ]<br> | 
|  | 969 |     1: x = x + 1<br> | 
|  | 970 |     2: (x > 2)<br> | 
|  | 971 |     <b>T: if [B4.2]</b><br> | 
|  | 972 |     Predecessors (1): B5<br> | 
|  | 973 |     Successors (2): B3 B2<br> | 
|  | 974 | <br> | 
|  | 975 |  [ B3 ]<br> | 
|  | 976 |     1: x++<br> | 
|  | 977 |     Predecessors (1): B4<br> | 
|  | 978 |     Successors (1): B1<br> | 
|  | 979 | <br> | 
|  | 980 |  [ B2 ]<br> | 
|  | 981 |     1: x += 2<br> | 
|  | 982 |     2: x *= 2<br> | 
|  | 983 |     Predecessors (1): B4<br> | 
|  | 984 |     Successors (1): B1<br> | 
|  | 985 | <br> | 
|  | 986 |  [ B1 ]<br> | 
|  | 987 |     1: return x;<br> | 
|  | 988 |     Predecessors (2): B2 B3<br> | 
|  | 989 |     Successors (1): B0<br> | 
|  | 990 | <br> | 
|  | 991 |  [ B0 (EXIT) ]<br> | 
|  | 992 |     Predecessors (1): B1<br> | 
|  | 993 |     Successors (0): | 
|  | 994 | </code> | 
|  | 995 |  | 
|  | 996 | <p>For each block, the pretty-printed output displays for each block | 
|  | 997 | the number of <i>predecessor</i> blocks (blocks that have outgoing | 
|  | 998 | control-flow to the given block) and <i>successor</i> blocks (blocks | 
|  | 999 | that have control-flow that have incoming control-flow from the given | 
|  | 1000 | block).  We can also clearly see the special entry and exit blocks at | 
|  | 1001 | the beginning and end of the pretty-printed output.  For the entry | 
|  | 1002 | block (block B5), the number of predecessor blocks is 0, while for the | 
|  | 1003 | exit block (block B0) the number of successor blocks is 0.</p> | 
|  | 1004 |  | 
|  | 1005 | <p>The most interesting block here is B4, whose outgoing control-flow | 
|  | 1006 | represents the branching caused by the sole if-statement | 
|  | 1007 | in <tt>foo</tt>.  Of particular interest is the second statement in | 
|  | 1008 | the block, <b><tt>(x > 2)</tt></b>, and the terminator, printed | 
|  | 1009 | as <b><tt>if [B4.2]</tt></b>.  The second statement represents the | 
|  | 1010 | evaluation of the condition of the if-statement, which occurs before | 
|  | 1011 | the actual branching of control-flow.  Within the <tt>CFGBlock</tt> | 
|  | 1012 | for B4, the <tt>Stmt*</tt> for the second statement refers to the | 
|  | 1013 | actual expression in the AST for <b><tt>(x > 2)</tt></b>.  Thus | 
|  | 1014 | pointers to subclasses of <tt>Expr</tt> can appear in the list of | 
|  | 1015 | statements in a block, and not just subclasses of <tt>Stmt</tt> that | 
|  | 1016 | refer to proper C statements.</p> | 
|  | 1017 |  | 
|  | 1018 | <p>The terminator of block B4 is a pointer to the <tt>IfStmt</tt> | 
|  | 1019 | object in the AST.  The pretty-printer outputs <b><tt>if | 
|  | 1020 | [B4.2]</tt></b> because the condition expression of the if-statement | 
|  | 1021 | has an actual place in the basic block, and thus the terminator is | 
|  | 1022 | essentially | 
|  | 1023 | <i>referring</i> to the expression that is the second statement of | 
|  | 1024 | block B4 (i.e., B4.2).  In this manner, conditions for control-flow | 
|  | 1025 | (which also includes conditions for loops and switch statements) are | 
|  | 1026 | hoisted into the actual basic block.</p> | 
|  | 1027 |  | 
| Chris Lattner | 62fd278 | 2008-11-22 21:41:31 +0000 | [diff] [blame] | 1028 | <!-- ===================== --> | 
|  | 1029 | <!-- <h4>Implicit Control-Flow</h4> --> | 
|  | 1030 | <!-- ===================== --> | 
| Ted Kremenek | 8bc0571 | 2007-10-10 23:01:43 +0000 | [diff] [blame] | 1031 |  | 
|  | 1032 | <!-- | 
|  | 1033 | <p>A key design principle of the <tt>CFG</tt> class was to not require | 
|  | 1034 | any transformations to the AST in order to represent control-flow. | 
|  | 1035 | Thus the <tt>CFG</tt> does not perform any "lowering" of the | 
|  | 1036 | statements in an AST: loops are not transformed into guarded gotos, | 
|  | 1037 | short-circuit operations are not converted to a set of if-statements, | 
|  | 1038 | and so on.</p> | 
|  | 1039 | --> | 
| Ted Kremenek | 17a295d | 2008-06-11 06:19:49 +0000 | [diff] [blame] | 1040 |  | 
| Chris Lattner | 7bad199 | 2008-11-16 21:48:07 +0000 | [diff] [blame] | 1041 |  | 
|  | 1042 | <!-- ======================================================================= --> | 
|  | 1043 | <h3 id="Constants">Constant Folding in the Clang AST</h3> | 
|  | 1044 | <!-- ======================================================================= --> | 
|  | 1045 |  | 
|  | 1046 | <p>There are several places where constants and constant folding matter a lot to | 
|  | 1047 | the Clang front-end.  First, in general, we prefer the AST to retain the source | 
|  | 1048 | code as close to how the user wrote it as possible.  This means that if they | 
|  | 1049 | wrote "5+4", we want to keep the addition and two constants in the AST, we don't | 
|  | 1050 | want to fold to "9".  This means that constant folding in various ways turns | 
|  | 1051 | into a tree walk that needs to handle the various cases.</p> | 
|  | 1052 |  | 
|  | 1053 | <p>However, there are places in both C and C++ that require constants to be | 
|  | 1054 | folded.  For example, the C standard defines what an "integer constant | 
|  | 1055 | expression" (i-c-e) is with very precise and specific requirements.  The | 
|  | 1056 | language then requires i-c-e's in a lot of places (for example, the size of a | 
|  | 1057 | bitfield, the value for a case statement, etc).  For these, we have to be able | 
|  | 1058 | to constant fold the constants, to do semantic checks (e.g. verify bitfield size | 
|  | 1059 | is non-negative and that case statements aren't duplicated).  We aim for Clang | 
|  | 1060 | to be very pedantic about this, diagnosing cases when the code does not use an | 
|  | 1061 | i-c-e where one is required, but accepting the code unless running with | 
|  | 1062 | <tt>-pedantic-errors</tt>.</p> | 
|  | 1063 |  | 
|  | 1064 | <p>Things get a little bit more tricky when it comes to compatibility with | 
|  | 1065 | real-world source code.  Specifically, GCC has historically accepted a huge | 
|  | 1066 | superset of expressions as i-c-e's, and a lot of real world code depends on this | 
|  | 1067 | unfortuate accident of history (including, e.g., the glibc system headers).  GCC | 
|  | 1068 | accepts anything its "fold" optimizer is capable of reducing to an integer | 
|  | 1069 | constant, which means that the definition of what it accepts changes as its | 
|  | 1070 | optimizer does.  One example is that GCC accepts things like "case X-X:" even | 
|  | 1071 | when X is a variable, because it can fold this to 0.</p> | 
|  | 1072 |  | 
|  | 1073 | <p>Another issue are how constants interact with the extensions we support, such | 
|  | 1074 | as __builtin_constant_p, __builtin_inf, __extension__ and many others.  C99 | 
|  | 1075 | obviously does not specify the semantics of any of these extensions, and the | 
|  | 1076 | definition of i-c-e does not include them.  However, these extensions are often | 
|  | 1077 | used in real code, and we have to have a way to reason about them.</p> | 
|  | 1078 |  | 
|  | 1079 | <p>Finally, this is not just a problem for semantic analysis.  The code | 
|  | 1080 | generator and other clients have to be able to fold constants (e.g. to | 
|  | 1081 | initialize global variables) and has to handle a superset of what C99 allows. | 
|  | 1082 | Further, these clients can benefit from extended information.  For example, we | 
|  | 1083 | know that "foo()||1" always evaluates to true, but we can't replace the | 
|  | 1084 | expression with true because it has side effects.</p> | 
|  | 1085 |  | 
|  | 1086 | <!-- ======================= --> | 
|  | 1087 | <h4>Implementation Approach</h4> | 
|  | 1088 | <!-- ======================= --> | 
|  | 1089 |  | 
|  | 1090 | <p>After trying several different approaches, we've finally converged on a | 
|  | 1091 | design (Note, at the time of this writing, not all of this has been implemented, | 
|  | 1092 | consider this a design goal!).  Our basic approach is to define a single | 
|  | 1093 | recursive method evaluation method (<tt>Expr::Evaluate</tt>), which is | 
|  | 1094 | implemented in <tt>AST/ExprConstant.cpp</tt>.  Given an expression with 'scalar' | 
|  | 1095 | type (integer, fp, complex, or pointer) this method returns the following | 
|  | 1096 | information:</p> | 
|  | 1097 |  | 
|  | 1098 | <ul> | 
|  | 1099 | <li>Whether the expression is an integer constant expression, a general | 
|  | 1100 | constant that was folded but has no side effects, a general constant that | 
|  | 1101 | was folded but that does have side effects, or an uncomputable/unfoldable | 
|  | 1102 | value. | 
|  | 1103 | </li> | 
|  | 1104 | <li>If the expression was computable in any way, this method returns the APValue | 
|  | 1105 | for the result of the expression.</li> | 
|  | 1106 | <li>If the expression is not evaluatable at all, this method returns | 
|  | 1107 | information on one of the problems with the expression.  This includes a | 
|  | 1108 | SourceLocation for where the problem is, and a diagnostic ID that explains | 
|  | 1109 | the problem.  The diagnostic should be have ERROR type.</li> | 
|  | 1110 | <li>If the expression is not an integer constant expression, this method returns | 
|  | 1111 | information on one of the problems with the expression.  This includes a | 
|  | 1112 | SourceLocation for where the problem is, and a diagnostic ID that explains | 
|  | 1113 | the problem.  The diagnostic should be have EXTENSION type.</li> | 
|  | 1114 | </ul> | 
|  | 1115 |  | 
|  | 1116 | <p>This information gives various clients the flexibility that they want, and we | 
|  | 1117 | will eventually have some helper methods for various extensions.  For example, | 
|  | 1118 | Sema should have a <tt>Sema::VerifyIntegerConstantExpression</tt> method, which | 
|  | 1119 | calls Evaluate on the expression.  If the expression is not foldable, the error | 
|  | 1120 | is emitted, and it would return true.  If the expression is not an i-c-e, the | 
|  | 1121 | EXTENSION diagnostic is emitted.  Finally it would return false to indicate that | 
|  | 1122 | the AST is ok.</p> | 
|  | 1123 |  | 
|  | 1124 | <p>Other clients can use the information in other ways, for example, codegen can | 
|  | 1125 | just use expressions that are foldable in any way.</p> | 
|  | 1126 |  | 
|  | 1127 | <!-- ========== --> | 
|  | 1128 | <h4>Extensions</h4> | 
|  | 1129 | <!-- ========== --> | 
|  | 1130 |  | 
|  | 1131 | <p>This section describes how some of the various extensions clang supports | 
|  | 1132 | interacts with constant evaluation:</p> | 
|  | 1133 |  | 
|  | 1134 | <ul> | 
|  | 1135 | <li><b><tt>__extension__</tt></b>: The expression form of this extension causes | 
|  | 1136 | any evaluatable subexpression to be accepted as an integer constant | 
|  | 1137 | expression.</li> | 
|  | 1138 | <li><b><tt>__builtin_constant_p</tt></b>: This returns true (as a integer | 
|  | 1139 | constant expression) if the operand is any evaluatable constant.</li> | 
|  | 1140 | <li><b><tt>__builtin_choose_expr</tt></b>: The condition is required to be an | 
|  | 1141 | integer constant expression, but we accept any constant as an "extension of | 
|  | 1142 | an extension".  This only evaluates one operand depending on which way the | 
|  | 1143 | condition evaluates.</li> | 
|  | 1144 | <li><b><tt>__builtin_classify_type</tt></b>: This always returns an integer | 
|  | 1145 | constant expression.</li> | 
|  | 1146 | <li><b><tt>__builtin_inf,nan,..</tt></b>: These are treated just like a | 
|  | 1147 | floating-point literal.</li> | 
|  | 1148 | <li><b><tt>__builtin_abs,copysign,..</tt></b>: These are constant folded as | 
|  | 1149 | general constant expressions.</li> | 
|  | 1150 | </ul> | 
|  | 1151 |  | 
|  | 1152 |  | 
|  | 1153 |  | 
|  | 1154 |  | 
| Ted Kremenek | 17a295d | 2008-06-11 06:19:49 +0000 | [diff] [blame] | 1155 | </div> | 
|  | 1156 | </body> | 
| Douglas Gregor | 2e1cd42 | 2008-11-17 14:58:09 +0000 | [diff] [blame] | 1157 | </html> |