# "clang" CFE Internals Manual

- Introduction
- LLVM System and Support Libraries
- The clang 'Basic' Library
  - The SourceLocation and SourceManager classes
- The Lexer and Preprocessor Library
  - The Token class
  - The Lexer class
  - The MacroExpander class
  - The MultipleIncludeOpt class
- The Parser Library
- The AST Library
  - The Type class and its subclasses
  - The QualType class

## Introduction

This document describes some of the more important APIs and internal design decisions made in the clang C front-end. The purpose of this document is to both capture some of this high level information and also describe some of the design decisions behind it. This is meant for people interested in hacking on clang, not for end-users. The description below is categorized by libraries, and does not describe any of the clients of the libraries.

## LLVM System and Support Libraries

The LLVM libsystem library provides the basic clang system abstraction layer, which is used for file system access. The LLVM libsupport library provides many underlying libraries and data-structures, including command line option processing and various containers.

## The clang 'Basic' Library

This library certainly needs a better name. The 'basic' library contains a number of low-level utilities for tracking and manipulating source buffers, locations within the source buffers, diagnostics, tokens, target abstraction, and information about the subset of the language being compiled for.

Part of this infrastructure is specific to C (such as the TargetInfo class), other parts could be reused for other non-C-based languages (SourceLocation, SourceManager, Diagnostics, FileManager). When and if there is future demand we can figure out if it makes sense to introduce a new library, move the general classes somewhere else, or introduce some other solution.

We describe the roles of these classes in order of their dependencies.

### The SourceLocation and SourceManager classes

Strangely enough, the SourceLocation class represents a location within the source code of the program. Important design points include:

1. sizeof(SourceLocation) must be extremely small, as these are embedded into many AST nodes and are passed around often. Currently it is 32 bits.
2. SourceLocation must be a simple value object that can be efficiently copied.
3. We should be able to represent a source location for any byte of any input file. This includes in the middle of tokens, in whitespace, in trigraphs, etc.
4. A SourceLocation must encode the current #include stack that was active when the location was processed. For example, if the location corresponds to a token, it should contain the set of #includes active when the token was lexed. This allows us to print the #include stack for a diagnostic.
5. SourceLocation must be able to describe macro expansions, capturing both the ultimate instantiation point and the source of the original character data.

In practice, the SourceLocation works together with the SourceManager class to encode two pieces of information about a location: it's physical location and it's virtual location. For most tokens, these will be the same. However, for a macro expansion (or tokens that came from a _Pragma directive) these will describe the location of the characters corresponding to the token and the location where the token was used (i.e. the macro instantiation point or the location of the _Pragma itself).

For efficiency, we only track one level of macro instantions: if a token was produced by multiple instantiations, we only track the source and ultimate destination. Though we could track the intermediate instantiation points, this would require extra bookkeeping and no known client would benefit substantially from this.

The clang front-end inherently depends on the location of a token being tracked correctly. If it is ever incorrect, the front-end may get confused and die. The reason for this is that the notion of the 'spelling' of a Token in clang depends on being able to find the original input characters for the token. This concept maps directly to the "physical" location for the token.

## The Lexer and Preprocessor Library

The Lexer library contains several tightly-connected classes that are involved with the nasty process of lexing and preprocessing C source code. The main interface to this library for outside clients is the large Preprocessor class. It contains the various pieces of state that are required to coherently read tokens out of a translation unit.

The core interface to the Preprocessor object (once it is set up) is the Preprocessor::Lex method, which returns the next Token from the preprocessor stream. There are two types of token providers that the preprocessor is capable of reading from: a buffer lexer (provided by the Lexer class) and a buffered token stream (provided by the MacroExpander class).

### The Token class

The Token class is used to represent a single lexed token. Tokens are intended to be used by the lexer/preprocess and parser libraries, but are not intended to live beyond them (for example, they should not live in the ASTs).

Tokens most often live on the stack (or some other location that is efficient to access) as the parser is running, but occasionally do get buffered up. For example, macro definitions are stored as a series of tokens, and the C++ front-end will eventually need to buffer tokens up for tentative parsing and various pieces of look-ahead. As such, the size of a Token matter. On a 32-bit system, sizeof(Token) is currently 16 bytes.

Tokens contain the following information:

- A SourceLocation - This indicates the location of the start of the token.
- A length - This stores the length of the token as stored in the SourceBuffer. For tokens that include them, this length includes trigraphs and escaped newlines which are ignored by later phases of the compiler. By pointing into the original source buffer, it is always possible to get the original spelling of a token completely accurately.
- IdentifierInfo - If a token takes the form of an identifier, and if identifier lookup was enabled when the token was lexed (e.g. the lexer was not reading in 'raw' mode) this contains a pointer to the unique hash value for the identifier. Because the lookup happens before keyword identification, this field is set even for language keywords like 'for'.
- TokenKind - This indicates the kind of token as classified by the lexer. This includes things like `tok::starequal` (for the "*=" operator), `tok::ampamp` for the "&&" token, and keyword values (e.g. `tok::kw_for`) for identifiers that correspond to keywords. Note that some tokens can be spelled multiple ways. For example, C++ supports "operator keywords", where things like "and" are treated exactly like the "&&" operator. In these cases, the kind value is set to `tok::ampamp`, which is good for the parser, which doesn't have to consider both forms. For something that cares about which form is used (e.g. the preprocessor 'stringize' operator) the spelling indicates the original form.
- Flags - There are currently four flags tracked by the lexer/preprocessor system on a per-token basis:
  1. StartOfLine - This was the first token that occurred on its input source line.
  2. LeadingSpace - There was a space character either immediately before the token or transitively before the token as it was expanded through a macro. The definition of this flag is very closely defined by the stringizing requirements of the preprocessor.
  3. DisableExpand - This flag is used internally to the preprocessor to represent identifier tokens which have macro expansion disabled. This prevents them from being considered as candidates for macro expansion ever in the future.
  4. NeedsCleaning - This flag is set if the original spelling for the token includes a trigraph or escaped newline. Since this is uncommon, many pieces of code can fast-path on tokens that did not need cleaning.

One interesting (and somewhat unusual) aspect of tokens is that they don't contain any semantic information about the lexed value. For example, if the token was a pp-number token, we do not represent the value of the number that was lexed (this is left for later pieces of code to decide). Additionally, the lexer library has no notion of typedef names vs variable names: both are returned as identifiers, and the parser is left to decide whether a specific identifier is a typedef or a variable (tracking this requires scope information among other things).

### The Lexer class

The Lexer class provides the mechanics of lexing tokens out of a source buffer and deciding what they mean. The Lexer is complicated by the fact that it operates on raw buffers that have not had spelling eliminated (this is a necessity to get decent performance), but this is countered with careful coding as well as standard performance techniques (for example, the comment handling code is vectorized on X86 and PowerPC hosts).

The lexer has a couple of interesting modal features:

- The lexer can operate in 'raw' mode. This mode has several features that make it possible to quickly lex the file (e.g. it stops identifier lookup, doesn't specially handle preprocessor tokens, handles EOF differently, etc). This mode is used for lexing within an "`#if 0`" block, for example.
- The lexer can capture and return comments as tokens. This is required to support the -C preprocessor mode, which passes comments through, and is used by the diagnostic checker to identifier expect-error annotations.
- The lexer can be in ParsingFilename mode, which happens when preprocessing after reading a #include directive. This mode changes the parsing of '<' to return an "angled string" instead of a bunch of tokens for each thing within the filename.
- When parsing a preprocessor directive (after "`#`") the ParsingPreprocessorDirective mode is entered. This changes the parser to return EOM at a newline.
- The Lexer uses a LangOptions object to know whether trigraphs are enabled, whether C++ or ObjC keywords are recognized, etc.

In addition to these modes, the lexer keeps track of a couple of other features that are local to a lexed buffer, which change as the buffer is lexed:

- The Lexer uses BufferPtr to keep track of the current character being lexed.
- The Lexer uses IsAtStartOfLine to keep track of whether the next lexed token will start with its "start of line" bit set.
- The Lexer keeps track of the current #if directives that are active (which can be nested).
- The Lexer keeps track of an MultipleIncludeOpt object, which is used to detect whether the buffer uses the standard "`#ifndef XX` / `#define XX`" idiom to prevent multiple inclusion. If a buffer does, subsequent includes can be ignored if the XX macro is defined.

### The MacroExpander class

The MacroExpander class is a token provider that returns tokens from a list of tokens that came from somewhere else. It typically used for two things: 1) returning tokens from a macro definition as it is being expanded 2) returning tokens from an arbitrary buffer of tokens. The later use is used by _Pragma and will most likely be used to handle unbounded look-ahead for the C++ parser.

### The MultipleIncludeOpt class

The MultipleIncludeOpt class implements a really simple little state machine that is used to detect the standard "`#ifndef XX` / `#define XX`" idiom that people typically use to prevent multiple inclusion of headers. If a buffer uses this idiom and is subsequently #include'd, the preprocessor can simply check to see whether the guarding condition is defined or not. If so, the preprocessor can completely ignore the include of the header.

## The Parser Library

## The AST Library

### The Type class and its subclasses

The Type class (and its subclasses) are an important part of the AST. Types are accessed through the ASTContext class, which implicitly creates and uniques them as they are needed. Types have a couple of non-obvious features: 1) they do not capture type qualifiers like const or volatile (See QualType), and 2) they implicitly capture typedef information. Once created, types are immutable (unlike decls).

Typedefs in C make semantic analysis a bit more complex than it would be without them. The issue is that we want to capture typedef information and represent it in the AST perfectly, but the semantics of operations need to "see through" typedefs. For example, consider this code:

`void func() {
typedef int foo;
foo X, *Y;
typedef foo* bar;
bar Z;
*X; // error
**Y; // error
**Z; // error
}
`

The code above is illegal, and thus we expect there to be diagnostics emitted on the annotated lines. In this example, we expect to get:

    test.c:6:1: error: indirection requires pointer operand ('foo' invalid)
    *X; // error
    ^~
    test.c:7:1: error: indirection requires pointer operand ('foo' invalid)
    **Y; // error
    ^~~
    test.c:8:1: error: indirection requires pointer operand ('foo' invalid)
    **Z; // error
    ^~~

While this example is somewhat silly, it illustrates the point: we want to retain typedef information where possible, so that we can emit errors about "`std::string`" instead of "`std::basic_string<char, std:...`". Doing this requires properly keeping typedef information (for example, the type of "X" is "foo", not "int"), and requires properly propagating it through the various operators (for example, the type of *Y is "foo", not "int"). In order to retain this information, the type of these expressions is an instance of the TypedefType class, which indicates that the type of these expressions is a typedef for foo.

Representing types like this is great for diagnostics, because the user-specified type is always immediately available. There are two problems with this: first, various semantic checks need to make judgements about the actual structure of a type, ignoring typdefs. Second, we need an efficient way to query whether two types are structurally identical to each other, ignoring typedefs. The solution to both of these problems is the idea of canonical types.

#### Canonical Types

Every instance of the Type class contains a canonical type pointer. For simple types with no typedefs involved (e.g. "`int`", "`int*`", "`int**`"), the type just points to itself. For types that have a typedef somewhere in their structure (e.g. "`foo`", "`foo*`", "`foo**`", "`bar`"), the canonical type pointer points to their structurally equivalent type without any typedefs (e.g. "`int`", "`int*`", "`int**`", and "`int*`" respectively).

This design provides a constant time operation (dereferencing the canonical type pointer) that gives us access to the structure of types. For example, we can trivially tell that "bar" and "foo*" are the same type by dereferencing their canonical type pointers and doing a pointer comparison (they both point to the single "`int*`" type).

Canonical types and typedef types bring up some complexities that must be carefully managed. Specifically, the "isa/cast/dyncast" operators generally shouldn't be used in code that is inspecting the AST. For example, when type checking the indirection operator (unary '*' on a pointer), the type checker must verify that the operand has a pointer type. It would not be correct to check that with "`isa<PointerType>(SubExpr->getType())`", because this predicate would fail if the subexpression had a typedef type.

The solution to this problem are a set of helper methods on Type, used to check their properties. In this case, it would be correct to use "`SubExpr->getType()->isPointerType()`" to do the check. This predicate will return true if the canonical type is a pointer, which is true any time the type is structurally a pointer type. The only hard part here is remembering not to use the `isa/cast/dyncast` operations.

The second problem we face is how to get access to the pointer type once we know it exists. To continue the example, the result type of the indirection operator is the pointee type of the subexpression. In order to determine the type, we need to get the instance of PointerType that best captures the typedef information in the program. If the type of the expression is literally a PointerType, we can return that, otherwise we have to dig through the typedefs to find the pointer type. For example, if the subexpression had type "`foo*`", we could return that type as the result. If the subexpression had type "`bar`", we want to return "`foo*`" (note that we do not want "`int*`"). In order to provide all of this, Type has a getAsPointerType() method that checks whether the type is structurally a PointerType and, if so, returns the best one. If not, it returns a null pointer.

This structure is somewhat mystical, but after meditating on it, it will make sense to you :).

### The QualType class

The QualType class is designed as a trivial value class that is small, passed by-value and is efficient to query. The idea of QualType is that it stores the type qualifiers (const, volatile, restrict) separately from the types themselves: QualType is conceptually a pair of "Type*" and bits for the type qualifiers.

By storing the type qualifiers as bits in the conceptual pair, it is extremely efficient to get the set of qualifiers on a QualType (just return the field of the pair), add a type qualifier (which is a trivial constant-time operation that sets a bit), and remove one or more type qualifiers (just return a QualType with the bitfield set to empty).

Further, because the bits are stored outside of the type itself, we do not need to create duplicates of types with different sets of qualifiers (i.e. there is only a single heap allocated "int" type: "const int" and "volatile const int" both point to the same heap allocated "int" type). This reduces the heap size used to represent bits and also means we do not have to consider qualifiers when uniquing types (Type does not even contain qualifiers).

In practice, on hosts where it is safe, the 3 type qualifiers are stored in the low bit of the pointer to the Type object. This means that QualType is exactly the same size as a pointer, and this works fine on any system where malloc'd objects are at least 8 byte aligned.