# Technical Documentation: llvm/llvm-project

> ℹ️ **Provenance:** Multi-Tier Ingestion · [CodeWiki Reference](https://codewiki.google/github.com/llvm/llvm-project)

### Overview (README.md)

# The LLVM Compiler Infrastructure

[](https://securityscorecards.dev/viewer/?uri=github.com/llvm/llvm-project)
[](https://www.bestpractices.dev/projects/8273)
[](https://github.com/llvm/llvm-project/actions/workflows/libcxx-pr-conformance-tests.yaml?query=event%3Aschedule)

Welcome to the LLVM project!

This repository contains the source code for LLVM, a toolkit for the
construction of highly optimized compilers, optimizers, and run-time
environments.

The LLVM project has multiple components. The core of the project is
itself called "LLVM". This contains all of the tools, libraries, and header
files needed to process intermediate representations and convert them into
object files. Tools include an assembler, disassembler, bitcode analyzer, and
bitcode optimizer.

C-like languages use the [Clang](https://clang.llvm.org/) frontend. This
component compiles C, C++, Objective-C, and Objective-C++ code into LLVM bitcode
-- and from there into object files, using LLVM.

Other components include:
the [libc++ C++ standard library](https://libcxx.llvm.org),
the [LLD linker](https://lld.llvm.org), and more.

## Getting the Source Code and Building LLVM

Consult the
[Getting Started with LLVM](https://llvm.org/docs/GettingStarted.html#getting-the-source-code-and-building-llvm)
page for information on building and running LLVM.

For information on how to contribute to the LLVM project, please take a look at
the [Contributing to LLVM](https://llvm.org/docs/Contributing.html) guide.

## Getting in touch

Join the [LLVM Discourse forums](https://discourse.llvm.org/), [Discord
chat](https://discord.gg/xS7Z362),
[LLVM Office Hours](https://llvm.org/docs/GettingInvolved.html#office-hours) or
[Regular sync-ups](https://llvm.org/docs/GettingInvolved.html#online-sync-ups).

The LLVM project has adopted a [code of conduct](https://llvm.org/docs/CodeOfConduct.html) for
participants to all modes of communication within the project.

---

### Bolt Docs Index (`bolt/docs/index.md`)

# BOLT

```{toctree}
:hidden: true

BOLTAArch64OptimizationStatus
```

BOLT is a post-link optimizer developed to speed up large applications.
It achieves the improvements by optimizing application’s code layout
based on execution profile gathered by sampling profiler, such as Linux
`perf` tool. An overview of the ideas implemented in BOLT along with a
discussion of its potential and current results is available in [CGO’19
paper](https://research.fb.com/publications/bolt-a-practical-binary-optimizer-for-data-centers-and-beyond/).

# User Guides

```{toctree}
:maxdepth: 1

GettingStarted
OptimizingClang
OptimizingLinux
Heatmaps
```

# Reference

```{toctree}
:maxdepth: 1

CommandLineArgumentReference
profiles
BOLTAArch64OptimizationStatus
```

# Design Documentation

```{toctree}
:maxdepth: 1

BAT
BinaryAnalysis
NewBackend
PointerAuthDesign
RuntimeLibrary
```

---

### Clang Tools Extra Docs Index (`clang-tools-extra/docs/index.md`)

```{title} Welcome to Extra Clang Tools's documentation!
```

# Introduction

Welcome to the clang-tools-extra project which contains extra tools built using
Clang's tooling APIs.

```{toctree}
:maxdepth: 1

ReleaseNotes
```

# Contents

```{toctree}
:maxdepth: 2

clang-tidy/index
clang-include-fixer
clang-change-namespace
clang-reorder-fields
modularize
pp-trace
clangd <https://clangd.llvm.org/>
clang-doc
Maintainers
```

# Doxygen Documentation

The Doxygen documentation describes the **internal** software that makes up the
tools of clang-tools-extra, not the **external** use of these tools. The Doxygen
documentation contains no instructions about how to use the tools, only the APIs
that make up the software. For usage instructions, please see the user's guide
or reference manual for each tool.

- <a href="doxygen/annotated.html">Doxygen documentation</a>

:::{note}
This documentation is generated directly from the source code with doxygen.
Since the tools of clang-tools-extra are constantly under active
development, what you're about to read is out of date!
:::

# Indices and tables

- {ref}`genindex`
- {ref}`search`

---

### Clang Docs DataFlowAnalysisIntro (`clang/docs/DataFlowAnalysisIntro.md`)

# Data flow analysis: an informal introduction

## Abstract

This document introduces data flow analysis in an informal way. The goal is to
give the reader an intuitive understanding of how it works, and show how it
applies to a range of refactoring and bug finding problems.

Data flow analysis is a well-established technique; it is described in many
papers, books, and videos. If you would like a more formal, or a more thorough
explanation of the concepts mentioned in this document, please refer to the
following resources:

*   [The Lattice article in Wikipedia](https://en.wikipedia.org/wiki/Lattice_\(order\)).
*   Videos on the PacketPrep YouTube channel that introduce lattices and the
    necessary background information:
    [#20](https://www.youtube.com/watch?v=73j_FXBXGm8),
    [#21](https://www.youtube.com/watch?v=b5sDjo9tfE8),
    [#22](https://www.youtube.com/watch?v=saOG7Uooeho),
    [#23](https://www.youtube.com/watch?v=3EAYX-wZH0g),
    [#24](https://www.youtube.com/watch?v=KRkHwQtW6Cc),
    [#25](https://www.youtube.com/watch?v=7Gwzsc4rAgw).
*   [Introduction to Dataflow Analysis](https://www.youtube.com/watch?v=OROXJ9-wUQE)
*   [Introduction to abstract interpretation](http://www.cs.tau.ac.il/~msagiv/courses/asv/absint-1.pdf).
*   [Introduction to symbolic execution](https://www.cs.umd.edu/~mwh/se-tutorial/symbolic-exec.pdf).
*   [Static Program Analysis by Anders Møller and Michael I. Schwartzbach](https://cs.au.dk/~amoeller/spa/).
*   [EXE: automatically generating inputs of death](https://css.csail.mit.edu/6.858/2020/readings/exe.pdf)
    (a paper that successfully applies symbolic execution to real-world
    software).

## Data flow analysis

### The purpose of data flow analysis

Data flow analysis is a static analysis technique that proves facts about a
program or its fragment. It can make conclusions about all paths through the
program, while taking control flow into account and scaling to large programs.
The basic idea is propagating facts about the program through the edges of the
control flow graph (CFG) until a fixpoint is reached.

### Sample problem and an ad-hoc solution

We would like to explain data flow analysis while discussing an example. Let's
imagine that we want to track possible values of an integer variable in our
program. Here is how a human could annotate the code:

```c++
void Example(int n) {
  int x = 0;
  // x is {0}
  if (n > 0) {
    x = 5;
    // x is {5}
  } else {
    x = 42;
    // x is {42}
  }
  // x is {5; 42}
  print(x);
}
```

We use sets of integers to represent possible values of `x`. Local variables
have unambiguous values between statements, so we annotate program points
between statements with sets of possible values.

Here is how we arrived at these annotations. Assigning a constant to `x` allows
us to make a conclusion that `x` can only have one value. When control flow from
the "then" and "else" branches joins, `x` can have either value.

Abstract algebra provides a nice formalism that models this kind of structure,
namely, a lattice. A join-semilattice is a partially ordered set, in which every
two elements have a least upper bound (called a *join*).

```
join(a, b) ⩾ a   and   join(a, b) ⩾ b   and   join(x, x) = x
```

For this problem we will use the lattice of subsets of integers, with set
inclusion relation as ordering and set union as a join.

Lattices are often represented visually as Hasse diagrams. Here is a Hasse
diagram for our lattice that tracks subsets of integers:

:::{figure} DataFlowAnalysisIntroImages/IntegerSetsInfiniteLattice.svg
:class: light-background
:alt: Hasse diagram for a lattice of integer sets
:::

Computing the join in the lattice corresponds to finding the lowest common
ancestor (LCA) between two nodes in its Hasse diagram. There is a vast amount of
literature on efficiently implementing LCA queries for a DAG, however Efficient
Implementation of Lattice Operations (1989)
([CiteSeerX](https://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.106.4911),
[doi](https://doi.org/10.1145%2F59287.59293)) describes a scheme that
particularly well-suited for programmatic implementation.

### Too much information and "top" values

Let's try to find the possible sets of values of `x` in a function that modifies
`x` in a loop:

```c++
void ExampleOfInfiniteSets() {
  int x = 0; // x is {0}
  while (condition()) {
    x += 1;  // x is {0; 1; 2; …}
  }
  print(x);  // x is {0; 1; 2; …}
}
```

We have an issue: `x` can have any value greater than zero; that's an infinite
set of values, if the program operated on mathematical integers. In C++ `int` is
limited by `INT_MAX` so technically we have a set `{0; 1; …; INT_MAX}` which is
still really big.

To make our analysis practical to compute, we have to limit the amount of
information that we track. In this case, we can, for example, arbitrarily limit
the size of sets to 3 elements. If at a certain program point `x` has more than
3 possible values, we stop tracking specific values at that program point.
Instead, we denote possible values of `x` with the symbol `⊤` (pronounced "top"
according to a convention in abstract algebra).

```c++
void ExampleOfTopWithALoop() {
  int x = 0;  // x is {0}
  while (condition()) {
    x += 1;   // x is ⊤
  }
  print(x);   // x is ⊤
}
```

The statement "at this program point, `x`'s possible values are `⊤`" is
understood as "at this program point `x` can have any value because we have too
much information, or the information is conflicting".

Note that we can get more than 3 possible values even without a loop:

```c++
void ExampleOfTopWithoutLoops(int n) {
  int x = 0;  // x is {0}
  switch(n) {
    case 0:  x = 1; break; // x is {1}
    case 1:  x = 9; break; // x is {9}
    case 2:  x = 7; break; // x is {7}
    default: x = 3; break; // x is {3}
  }
  // x is ⊤
}
```

### Uninitialized variables and "bottom" values

When `x` is declared but not initialized, it has no possible values. We
represent this fact symbolically as `⊥` (pronounced "bottom").

```c++
void ExampleOfBottom() {
  int x;    // x is ⊥
  x = 42;   // x is {42}
  print(x);
}
```

Note that using values read from uninitialized variables is undefined behaviour
in C++. Generally, compilers and static analysis tools can assume undefined
behavior does not happen. We must model uninitialized variables only when we are
implementing a checker that specifically is trying to find uninitialized reads.
In this example we show how to model uninitialized variables only to demonstrate
the concept of "bottom", and how it applies to possible value analysis. We
describe an analysis that finds uninitialized reads in a section below.

### A practical lattice that tracks sets of concrete values

Taking into account all corner cases covered above, we can put together a
lattice that we can use in practice to track possible values of integer
variables. This lattice represents sets of integers with 1, 2, or 3 elements, as
well as top and bottom. Here is a Hasse diagram for it:

:::{figure} DataFlowAnalysisIntroImages/IntegerSetsFiniteLattice.svg
:class: light-background
:alt: Hasse diagram for a lattice of integer sets
:::

### Formalization

Let's consider a slightly more complex example, and think about how we can
compute the sets of possible values algorithmically.

```c++
void Example(int n) {
  int x;          // x is ⊥
  if (n > 0) {
    if (n == 42) {
       x = 44;    // x is {44}
    } else {
       x = 5;     // x is {5}
    }
    print(x);     // x is {44; 5}
  } else {
    x = n;        // x is ⊤
  }
  print(x);       // x is ⊤
}
```

As humans, we understand the control flow from the program text. We used our
understanding of control flow to find program points where two flows join.
Formally, control flow is represented by a CFG (control flow graph):

:::{figure} DataFlowAnalysisIntroImages/CFGExample.svg
:class: light-background
:alt: CFG for the code above
:::

We can compute sets of possible values by propagating them through the CFG of
the function:

*   When `x` is declared but not initialized, its possible values are `{}`. The
    empty set plays the role of `⊥` in this lattice.

*   When `x` is assigned a concrete value, its possible set of values contains
    just that specific value.

*   When `x` is assigned some unknown value, it can have any value. We represent
    this fact as `⊤`.

*   When two control flow paths join, we compute the set union of incoming
    values (limiting the number of elements to 3, representing larger sets as
    `⊤`).

The sets of possible values are influenced by:

*   Statements, for example, assignments.

*   Joins in control flow, for example, ones that appear at the end of "if"
    statements.

**Effects of statements** are modeled by what is formally known as a transfer
function. A transfer function takes two arguments: the statement, and the state
of `x` at the previous program point. It produces the state of `x` at the next
program point. For example, the transfer function for assignment ignores the
state at the previous program point:

```c++
// GIVEN: x is {42; 44}
x = 0;
// CONCLUSION: x is {0}
```

The transfer function for `+` performs arithmetic on every set member:

```c++
// GIVEN: x is {42, 44}
x = x + 100;
// CONCLUSION: x is {142, 144}
```

**Effects of control flow** are modeled by joining the knowledge from all
possible previous program points.

```c++
if (...) {
  ...
  // GIVEN: x is {42}
} else {
  ...
  // GIVEN: x is {44}
}
// CONCLUSION: x is {42; 44}
```

```c++
// GIVEN: x is {42}
while (...) {
  ...
  // GIVEN: x is {44}
}
// CONCLUSION: {42; 44}
```

The predicate that we marked "given" is usually called a precondition, and the
conclusion is called a postcondition.

In terms of the CFG, we join the information from all predecessor basic blocks.

:::{figure} DataFlowAnalysisIntroImages/CFGJoinRule.svg
:class: light-background
:alt: Modeling the effects of a CFG basic block
:::

Putting it all together, to model the effects of a basic block we compute:

```
out = transfer(basic_block, join(in_1, in_2, ..., in_n))
```

(Note that there are other ways to write this equation that produce higher
precision analysis results. The trick is to keep exploring the execution paths
separately and delay joining until later. However, we won't discuss those
variations here.)

To make a conclusion about all paths through the program, we repeat this
computation on all basic blocks until we reach a fixpoint. In other words, we
keep propagating information through the CFG until the computed sets of values
stop changing.

If the lattice has a finite height and transfer functions are monotonic the
algorithm is guaranteed to terminate.  Each iteration of the algorithm can
change computed values only to larger values from the lattice. In the worst
case, all computed values become `⊤`, which is not very useful, but at least the
analysis terminates at that point, because it can't change any of the values.

Fixpoint iteration can be optimised by only reprocessing basic blocks which had
one of their inputs changed on the previous iteration. This is typically
implemented using a worklist queue. With this optimisation the time complexity
becomes `O(m * |L|)`, where `m` is the number of basic blocks in the CFG and
`|L|` is the size of lattice used by the analysis.

## Symbolic execution: a very short informal introduction

### Symbolic values

In the previous example where we tried to figure out what values a variable can
have, the analysis had to be seeded with a concrete value. What if there are no
assignments of concrete values in the program? We can still deduce some
interesting information by representing unknown input values symbolically, and
computing results as symbolic expressions:

```c++
void PrintAbs(int x) {
  int result;
  if (x >= 0) {
    result = x;   // result is {x}
  } else {
    result = -x;  // result is {-x}
  }
  print(result);  // result is {x; -x}
}
```

We can't say what specific value gets printed, but we know that it is either `x`
or `-x`.

Dataflow analysis is an instance of abstract interpretation, and does not dictate
how exactly the lattice and transfer functions should be designed, beyond the
necessary conditions for the analysis to converge. Nevertheless, we can use
symbolic execution ideas to guide our design of the lattice and transfer
functions: lattice values can be symbolic expressions, and transfer functions
can construct more complex symbolic expressions from symbolic expressions that
represent arguments. See [this StackOverflow
discussion](https://cstheory.stackexchange.com/questions/19708/symbolic-execution-is-a-case-of-abstract-interpretation)
for a further comparison of abstract interpretation and symbolic execution.

### Flow condition

A human can say about the previous example that the function returns `x` when
`x >= 0`, and `-x` when `x < 0`. We can make this conclusion programmatically by
tracking a flow condition. A flow condition is a predicate written in terms of
the program state that is true at a specific program point regardless of the
execution path that led to this statement. For example, the flow condition for
the program point right before evaluating `result = x` is `x >= 0`.

If we enhance the lattice to be a set of pairs of values and predicates, the
dataflow analysis computes the following values:

```c++
void PrintAbs(int x) {
  int result;
  if (x >= 0) {
    // Flow condition: x >= 0.
    result = x;   // result is {x if x >= 0}
  } else {
    // Flow condition: x < 0.
    result = -x;  // result is {-x if x < 0}
  }
  print(result);  // result is {x if x >= 0; -x if x < 0}
}
```

Of course, in a program with loops, symbolic expressions for flow conditions can
grow unbounded. A practical static analysis system must control this growth to
keep the symbolic representations manageable and ensure that the data flow
analysis terminates. For example, it can use a constraint solver to prune
impossible flow conditions, and/or it can abstract them, losing precision, after
their symbolic representations grow beyond some threshold. This is similar to
how we had to limit the sizes of computed sets of possible values to 3 elements.

### Symbolic pointers

This approach proves to be particularly useful for modeling pointer values,
since we don't care about specific addresses but just want to give a unique
identifier to a memory location.

```c++
void ExampleOfSymbolicPointers(bool b) {
  int x = 0;     // x is {0}
  int* ptr = &x; // x is {0}      ptr is {&x}
  if (b) {
    *ptr = 42;   // x is {42}     ptr is {&x}
  }
  print(x);      // x is {0; 42}  ptr is {&x}
}
```

## Example: finding output parameters

Let's explore how data flow analysis can help with a problem that is hard to
solve with other tools in Clang.

### Problem description

Output parameters are function parameters of pointer or reference type whose
pointee is completely overwritten by the function, and not read before it is
overwritten. They are common in pre-C++11 code due to the absence of move
semantics. In modern C++ output parameters are non-idiomatic, and return values
are used instead.

Imagine that we would like to refactor output parameters to return values to
modernize old code. The first step is to identify refactoring candidates through
static analysis.

For example, in the following code snippet the pointer `c` is an output
parameter:

```c++
struct Customer {
  int account_id;
  std::string name;
}

void GetCustomer(Customer *c) {
  c->account_id = ...;
  if (...) {
    c->name = ...;
  } else {
    c->name = ...;
  }
}
```

We would like to refactor this code into:

```c++
Customer GetCustomer() {
  Customer c;
  c.account_id = ...;
  if (...) {
    c.name = ...;
  } else {
    c.name = ...;
  }
  return c;
}
```

However, in the function below the parameter `c` is not an output parameter
because its field `name` is not overwritten on every path through the function.

```c++
void GetCustomer(Customer *c) {
  c->account_id = ...;
  if (...) {
    c->name = ...;
  }
}
```

The code also cannot read the value of the parameter before overwriting it:

```c++
void GetCustomer(Customer *c) {
  use(c->account_id);
  c->name = ...;
  c->account_id = ...;
}
```

Functions that escape the pointer also block the refactoring:

```c++
Customer* kGlobalCustomer;

void GetCustomer(Customer *c) {
  c->name = ...;
  c->account_id = ...;
  kGlobalCustomer = c;
}
```

To identify a candidate function for refactoring, we need to do the following:

*   Find a function with a non-const pointer or reference parameter.

*   Find the definition of that function.

*   Prove that the function completely overwrites the pointee on all paths
    before returning.

*   Prove that the function reads the pointee only after overwriting it.

*   Prove that the function does not persist the pointer in a data structure
    that is live after the function returns.

There are also requirements that all usage sites of the candidate function must
satisfy, for example, that function arguments do not alias, that users are not
taking the address of the function, and so on. Let's consider verifying usage
site conditions to be a separate static analysis problem.

### Lattice design

To analyze the function body we can use a lattice which consists of normal
states and failure states. A normal state describes program points where we are
sure that no behaviors that block the refactoring have occurred. Normal states
keep track of all parameter's member fields that are known to be overwritten on
every path from function entry to the corresponding program point. Failure
states accumulate observed violations (unsafe reads and pointer escapes) that
block the refactoring.

In the partial order of the lattice failure states compare greater than normal
states, which guarantees that they "win" when joined with normal states. Order
between failure states is determined by inclusion relation on the set of
accumulated violations (lattice's `⩽` is `⊆` on the set of violations). Order
between normal states is determined by reversed inclusion relation on the set of
overwritten parameter's member fields (lattice's `⩽` is `⊇` on the set of
overwritten fields).

:::{figure} DataFlowAnalysisIntroImages/OutputParameterIdentificationLattice.svg
:class: light-background
:alt: Lattice for data flow analysis that identifies output parameters
:::

To determine whether a statement reads or writes a field we can implement
symbolic evaluation of `DeclRefExpr`s, `LValueToRValue` casts, pointer
dereference operator and `MemberExpr`s.

### Using data flow results to identify output parameters

Let's take a look at how we use data flow analysis to identify an output
parameter. The refactoring can be safely done when the data flow algorithm
computes a normal state with all of the fields proven to be overwritten in the
exit basic block of the function.

```c++
struct Customer {
  int account_id;
  std::string name;
};

void GetCustomer(Customer* c) {
  // Overwritten: {}
  c->account_id = ...; // Overwritten: {c->account_id}
  if (...) {
    c->name = ...;     // Overwritten: {c->account_id, c->name}
  } else {
    c->name = ...;     // Overwritten: {c->account_id, c->name}
  }
  // Overwritten: {c->account_id, c->name}
}
```

When the data flow algorithm computes a normal state, but not all fields are
proven to be overwritten we can't perform the refactoring.

```c++
void target(bool b, Customer* c) {
  // Overwritten: {}
  if (b) {
    c->account_id = 42;     // Overwritten: {c->account_id}
  } else {
    c->name = "Konrad";  // Overwritten: {c->name}
  }
  // Overwritten: {}
}
```

Similarly, when the data flow algorithm computes a failure state, we also can't
perform the refactoring.

```c++
Customer* kGlobalCustomer;

void GetCustomer(Customer* c) {
  // Overwritten: {}
  c->account_id = ...;    // Overwritten: {c->account_id}
  if (...) {
    print(c->name);       // Unsafe read
  } else {
    kGlobalCustomer = c;  // Pointer escape
  }
  // Unsafe read, Pointer escape
}
```

## Example: finding dead stores

Let's say we want to find redundant stores, because they indicate potential
bugs.

```c++
x = GetX();
x = GetY();
```

The first store to `x` is never read, probably there is a bug.

The implementation of dead store analysis is very similar to output parameter
analysis: we need to track stores and loads, and find stores that were never
read.

[Liveness analysis](https://en.wikipedia.org/wiki/Live_variable_analysis) is a
generalization of this idea, which is often used to answer many related
questions, for example:

* finding dead stores,
* finding uninitialized variables,
* finding a good point to deallocate memory,
* finding out if it would be safe to move an object.

## Example: definitive initialization

Definitive initialization proves that variables are known to be initialized when
read. If we find a variable which is read when not initialized then we generate
a warning.

```c++
void Init() {
  int x;    // x is uninitialized
  if (cond()) {
    x = 10; // x is initialized
  } else {
    x = 20; // x is initialized
  }
  print(x); // x is initialized
}
```

```c++
void Uninit() {
  int x;    // x is uninitialized
  if (cond()) {
    x = 10; // x is initialized
  }
  print(x); // x is maybe uninitialized, x is being read, report a bug.
}
```

For this purpose we can use lattice in a form of a mapping from variable
declarations to initialization states; each initialization state is represented
by the following lattice:

:::{figure} DataFlowAnalysisIntroImages/DefinitiveInitializationLattice.svg
:class: light-background
:alt: Lattice for definitive initialization analysis
:::

A lattice element could also capture the source locations of the branches that
lead us to the corresponding program point. Diagnostics would use this
information to show a sample buggy code path to the user.

## Example: refactoring raw pointers to `unique_ptr`

Modern idiomatic C++ uses smart pointers to express memory ownership, however in
pre-C++11 code one can often find raw pointers that own heap memory blocks.

Imagine that we would like to refactor raw pointers that own memory to
`unique_ptr`. There are multiple ways to design a data flow analysis for this
problem; let's look at one way to do it.

For example, we would like to refactor the following code that uses raw
pointers:

```c++
void UniqueOwnership1() {
  int *pi = new int;
  if (...) {
    Borrow(pi);
    delete pi;
  } else {
    TakeOwnership(pi);
  }
}
```

into code that uses `unique_ptr`:

```c++
void UniqueOwnership1() {
  auto pi = std::make_unique<int>();
  if (...) {
    Borrow(pi.get());
  } else {
    TakeOwnership(pi.release());
  }
}
```

This problem can be solved with a lattice in form of map from value declarations
to pointer states:

:::{figure} DataFlowAnalysisIntroImages/UniquePtrLattice.svg
:class: light-background
:alt: Lattice that identifies candidates for unique_ptr refactoring
:::

We can perform the refactoring if at the exit of a function `pi` is
`Compatible`.

```c++
void UniqueOwnership1() {
  int *pi;             // pi is Compatible
  pi = new int;        // pi is Defined
  if (...) {
    Borrow(pi);        // pi is Defined
    delete pi;         // pi is Compatible
  } else {
    TakeOwnership(pi); // pi is Compatible
  }
  // pi is Compatible
}
```

Let's look at an example where the raw pointer owns two different memory blocks:

```c++
void UniqueOwnership2() {
  int *pi = new int;  // pi is Defined
  Borrow(pi);
  delete pi;          // pi is Compatible
  if (smth) {
    pi = new int;     // pi is Defined
    Borrow(pi);
    delete pi;        // pi is Compatible
  }
  // pi is Compatible
}
```

It can be refactored to use `unique_ptr` like this:

```c++
void UniqueOwnership2() {
  auto pi = make_unique<int>();
  Borrow(pi);
  if (smth) {
    pi = make_unique<int>();
    Borrow(pi);
  }
}
```

In the following example, the raw pointer is used to access the heap object
after the ownership has been transferred.

```c++
void UniqueOwnership3() {
  int *pi = new int; // pi is Defined
  if (...) {
    Borrow(pi);
    delete pi;       // pi is Compatible
  } else {
    vector<unique_ptr<int>> v = {std::unique_ptr(pi)}; // pi is Compatible
    print(*pi);
    use(v);
  }
  // pi is Compatible
}
```

We can refactor this code to use `unique_ptr`, however we would have to
introduce a non-owning pointer variable, since we can't use the moved-from
`unique_ptr` to access the object:

```c++
void UniqueOwnership3() {
  std::unique_ptr<int> pi = std::make_unique<int>();
  if (...) {
    Borrow(pi);
  } else {
    int *pi_non_owning = pi.get();
    vector<unique_ptr<int>> v = {std::move(pi)};
    print(*pi_non_owning);
    use(v);
  }
}
```

If the original code didn't call `delete` at the very end of the function, then
our refactoring may change the point at which we run the destructor and release
memory. Specifically, if there is some user code after `delete`, then extending
the lifetime of the object until the end of the function may hold locks for
longer than necessary, introduce memory overhead etc.

One solution is to always replace `delete` with a call to `reset()`, and then
perform another analysis that removes unnecessary `reset()` calls.

```c++
void AddedMemoryOverhead() {
  HugeObject *ho = new HugeObject();
  use(ho);
  delete ho; // Release the large amount of memory quickly.
  LongRunningFunction();
}
```

This analysis will refuse to refactor code that mixes borrowed pointer values
and unique ownership. In the following code, `GetPtr()` returns a borrowed
pointer, which is assigned to `pi`. Then, `pi` is used to hold a uniquely-owned
pointer. We don't distinguish between these two assignments, and we want each
assignment to be paired with a corresponding sink; otherwise, we transition the
pointer to a `Conflicting` state, like in this example.

```c++
void ConflictingOwnership() {
  int *pi;           // pi is Compatible
  pi = GetPtr();     // pi is Defined
  Borrow(pi);        // pi is Defined

  pi = new int;      // pi is Conflicting
  Borrow(pi);
  delete pi;
  // pi is Conflicting
}
```

We could still handle this case by finding a maximal range in the code where
`pi` could be in the Compatible state, and only refactoring that part.

```c++
void ConflictingOwnership() {
  int *pi;
  pi = GetPtr();
  Borrow(pi);

  std::unique_ptr<int> pi_unique = std::make_unique<int>();
  Borrow(pi_unique.get());
}
```

## Example: finding redundant branch conditions

In the code below `b1` should not be checked in both the outer and inner "if"
statements. It is likely there is a bug in this code.

```c++
int F(bool b1, bool b2) {
  if (b1) {
    f();
    if (b1 && b2) {  // Check `b1` again -- unnecessary!
      g();
    }
  }
}
```

A checker that finds this pattern syntactically is already implemented in
ClangTidy using AST matchers (`bugprone-redundant-branch-condition`).

To implement it using the data flow analysis framework, we can produce a warning
if any part of the branch condition is implied by the flow condition.

```c++
int F(bool b1, bool b2) {
  // Flow condition: true.
  if (b1) {
    // Flow condition: b1.
    f();
    if (b1 && b2) { // `b1` is implied by the flow condition.
      g();
    }
  }
}
```

One way to check this implication is to use a SAT solver. Without a SAT solver,
we could keep the flow condition in the CNF form and then it would be easy to
check the implication.

## Example: finding unchecked `std::optional` unwraps

Calling `optional::value()` is only valid if `optional::has_value()` is true. We
want to show that when `x.value()` is executed, the flow condition implies
`x.has_value()`.

In the example below `x.value()` is accessed safely because it is guarded by the
`x.has_value()` check.

```c++
void Example(std::optional<int> &x) {
  if (x.has_value()) {
    use(x.value());
  }
}
```

While entering the if branch we deduce that `x.has_value()` is implied by the
flow condition.

```c++
void Example(std::optional<int> x) {
  // Flow condition: true.
  if (x.has_value()) {
    // Flow condition: x.has_value() == true.
    use(x.value());
  }
  // Flow condition: true.
}
```

We also need to prove that `x` is not modified between check and value access.
The modification of `x` may be very subtle:

```c++
void F(std::optional<int> &x);

void Example(std::optional<int> &x) {
  if (x.has_value()) {
    // Flow condition: x.has_value() == true.
    unknown_function(x); // may change x.
    // Flow condition: true.
    use(x.value());
  }
}
```

## Example: finding dead code behind A/B experiment flags

Finding dead code is a classic application of data flow analysis.

Unused flags for A/B experiment hide dead code. However, this flavor of dead
code is invisible to the compiler because the flag can be turned on at any
moment.

We could make a tool that deletes experiment flags. The user tells us which flag
they want to delete, and we assume that the it's value is a given constant.

For example, the user could use the tool to remove `example_flag` from this
code:

```c++
DEFINE_FLAG(std::string, example_flag, "", "A sample flag.");

void Example() {
  bool x = GetFlag(FLAGS_example_flag).empty();
  f();
  if (x) {
    g();
  } else {
    h();
  }
}
```

The tool would simplify the code to:

```c++
void Example() {
  f();
  g();
}
```

We can solve this problem with a classic constant propagation lattice combined
with symbolic evaluation.

## Example: finding inefficient usages of associative containers

Real-world code often accidentally performs repeated lookups in associative
containers:

```c++
map<int, Employee> xs;
xs[42]->name = "...";
xs[42]->title = "...";
```

To find the above inefficiency we can use the available expressions analysis to
understand that `m[42]` is evaluated twice.

```c++
map<int, Employee> xs;
Employee &e = xs[42];
e->name = "...";
e->title = "...";
```

We can also track the `m.contains()` check in the flow condition to find
redundant checks, like in the example below.

```c++
std::map<int, Employee> xs;
if (!xs.contains(42)) {
  xs.insert({42, someEmployee});
}
```

## Example: refactoring types that implicitly convert to each other

Refactoring one strong type to another is difficult, but the compiler can help:
once you refactor one reference to the type, the compiler will flag other places
where this information flows with type mismatch errors. Unfortunately this
strategy does not work when you are refactoring types that implicitly convert to
each other, for example, replacing `int32_t` with `int64_t`.

Imagine that we want to change user IDs from 32 to 64-bit integers. In other
words, we need to find all integers tainted with user IDs. We can use data flow
analysis to implement taint analysis.

```c++
void UseUser(int32_t user_id) {
  int32_t id = user_id;
  // Variable `id` is tainted with a user ID.
  ...
}
```

Taint analysis is very well suited to this problem because the program rarely
branches on user IDs, and almost certainly does not perform any computation
(like arithmetic).

---

### Clang Docs Index (`clang/docs/index.md`)

% Clang documentation master file, created by
% sphinx-quickstart on Sun Dec  9 20:01:55 2012.
% You can adapt this file completely to your liking, but it should at least
% contain the root `toctree` directive.

```{title} Welcome to Clang's documentation!
```

```
/* Detailed source-code truncated for AI context efficiency. */
```

* {doc}`ReleaseNotes`

# Using Clang as a Compiler

* {doc}`UsersManual`
* {doc}`Toolchain`
* {doc}`LanguageExtensions`
* {doc}`ClangCommandLineReference`
* {doc}`AttributeReference`
* {doc}`DiagnosticsReference`
* {doc}`AMDGPUBuiltinReference`
* {doc}`WarningSuppressionMappings`
* {doc}`CrossCompilation`
* {doc}`ClangStaticAnalyzer`
* {doc}`ThreadSafetyAnalysis`
* {doc}`LifetimeSafety`
* {doc}`SafeBuffers`
* {doc}`ScalableStaticAnalysis/index`
* {doc}`DataFlowAnalysisIntro`
* {doc}`FunctionEffectAnalysis`
* {doc}`AddressSanitizer`
* {doc}`HardwareAssistedAddressSanitizer`
* {doc}`ThreadSanitizer`
* {doc}`MemorySanitizer`
* {doc}`UndefinedBehaviorSanitizer`
* {doc}`DataFlowSanitizer`
* {doc}`LeakSanitizer`
* {doc}`TypeSanitizer`
* {doc}`RealtimeSanitizer`
* {doc}`SanitizerCoverage`
* {doc}`SanitizerStats`
* {doc}`SanitizerSpecialCaseList`
* {doc}`AllocToken`
* {doc}`OverflowBehaviorTypes`
* {doc}`BoundsSafety`
* {doc}`BoundsSafetyAdoptionGuide`
* {doc}`BoundsSafetyImplPlans`
* {doc}`ControlFlowIntegrity`
* {doc}`LTOVisibility`
* {doc}`PointerAuthentication`
* {doc}`ReturnAddressAuthenticationHardening`
* {doc}`SafeStack`
* {doc}`ShadowCallStack`
* {doc}`StructureProtection`
* {doc}`SourceBasedCodeCoverage`
* {doc}`StandardCPlusPlusModules`
* {doc}`Modules`
* {doc}`MSVCCompatibility`
* {doc}`MisExpect`
* {doc}`OpenCLSupport`
* {doc}`OpenMPSupport`
* {doc}`SYCLSupport`
* {doc}`HIPSupport`
* {doc}`HLSL/HLSLDocs`
* {doc}`ThinLTO`
* {doc}`APINotes`
* {doc}`DebuggingCoroutines`
* {doc}`AMDGPUSupport`
* {doc}`RISCVSupport`
* {doc}`CXXTypeAwareAllocators`
* {doc}`CIR/index`
* {doc}`CommandGuide/index`
* {doc}`FAQ`

# Using Clang as a Library

* {doc}`Tooling`
* {doc}`ExternalClangExamples`
* {doc}`IntroductionToTheClangAST`
* {doc}`LibTooling`
* {doc}`LibClang`
* {doc}`LibFormat`
* {doc}`ClangPlugins`
* {doc}`RAVFrontendAction`
* {doc}`LibASTMatchersTutorial`
* {doc}`LibASTMatchers`
* {doc}`ClangTransformerTutorial`
* {doc}`LibASTImporter`
* {doc}`HowToSetupToolingForLLVM`
* {doc}`JSONCompilationDatabase`
* {doc}`RefactoringEngine`

# Using Clang Tools

* {doc}`ClangTools`
* {doc}`ClangCheck`
* {doc}`ClangFormat`
* {doc}`ClangFormatStyleOptions`
* {doc}`ClangLinkerWrapper`
* {doc}`ClangNVLinkWrapper`
* {doc}`ClangOffloadBundler`
* {doc}`ClangRepl`
* {doc}`ClangSYCLLinker`

# Design Documents

* {doc}`Maintainers`
* {doc}`InternalsManual`
* {doc}`DriverInternals`
* {doc}`Multilib`
* {doc}`OffloadingDesign`
* {doc}`PCHInternals`
* {doc}`ItaniumMangleAbiTags`
* {doc}`ControlFlowIntegrityDesign`
* {doc}`HardwareAssistedAddressSanitizerDesign`
* {doc}`ConstantInterpreter`
* {doc}`LLVMExceptionHandlingCodeGen`

# Indices and tables

- {ref}`genindex`
- {ref}`search`

---

### Flang Docs Overview (`flang/docs/Overview.md`)

# Overview of Compiler Phases

The Flang compiler transforms Fortran source code into an executable file.
This transformation proceeds in three high level phases -- analysis, lowering,
and code generation/linking.

The first high level phase (analysis) transforms Fortran source code into a
decorated parse tree and a symbol table.  During this phase, all user
related errors are detected and reported.

The second high level phase (lowering), changes the decorated parse tree and
symbol table into the Fortran Intermediate Representation (FIR), which is a
dialect of LLVM's Multi-Level Intermediate Representation or MLIR.  It then
runs a series of passes on the FIR code which verify its validity, perform a
series of optimizations, and finally transform it into LLVM's Intermediate
Representation, or LLVM IR

The third high level phase generates machine code and invokes a linker to
produce an executable file.

This document describes the first two high level phases.  Each of these is
described in more detailed phases.

Each detailed phase is described -- its inputs and outputs along with how to
produce a readable version of the outputs.

Each detailed phase produces either correct output or fatal errors.

## Analysis

This high level phase validates that the program is correct and creates all of
the information needed for lowering.

### Prescan and Preprocess

See [Preprocessing.md](Preprocessing.md).

**Input:** Fortran source and header files, command line macro definitions,
  set of enabled compiler directives (to be treated as directives rather than
  comments).

**Output:**
- A "cooked" character stream: the entire program as a contiguous stream of
  normalized Fortran source.
  Extraneous whitespace and comments are removed (except comments that are
  compiler directives that are not disabled) and case is normalized.  Also,
  directives are processed and macros expanded.
- Provenance information mapping each character back to the source it came from.
  This is used in subsequent phases that need source locations.  This includes
  error messages, optimization reports, and debugging information.

**Entry point:** `parser::Parsing::Prescan`

**Commands:**
 - `flang -fc1 -E src.f90` dumps the cooked character stream
 - `flang -fc1 -fdebug-dump-provenance src.f90` dumps provenance
   information

### Parsing

**Input:** Cooked character stream

**Output:** A parse tree for each Fortran program unit in the source code
representing a syntactically correct program, rooted at the program unit.  See:
[Parsing.md](Parsing.md) and [ParserCombinators.md](ParserCombinators.md).

**Entry point:** `parser::Parsing::Parse`

**Commands:**
  - `flang -fc1 -fdebug-dump-parse-tree-no-sema src.f90` dumps the parse tree
  - `flang -fc1 -fdebug-unparse src.f90` converts the parse tree to normalized Fortran
  - `flang -fc1 -fdebug-dump-parsing-log src.f90` runs an instrumented parse and dumps the log
  - `flang -fc1 -fdebug-measure-parse-tree src.f90` measures the parse tree

### Semantic processing

**Input:** the parse tree, the cooked character stream, and provenance
information

**Output:**
* a symbol table
* modified parse tree
* module files, (see: [ModFiles.md](ModFiles.md))
* the intrinsic procedure table
* the target characteristics
* the runtime derived type derived type tables (see: [RuntimeTypeInfo.md](RuntimeTypeInfo.md))

**Entry point:** `semantics::Semantics::Perform`

For more detail on semantic analysis, see: [Semantics.md](Semantics.md).
Semantic processing performs several tasks:
* validates labels, see: [LabelResolution.md](LabelResolution.md).
* canonicalizes DO statements,
* canonicalizes OpenACC and OpenMP code
* resolves names, building a tree of scopes and symbols
* rewrites the parse tree to correct parsing mistakes (when needed) once semantic information is available to clarify the program's meaning
* checks the validity of declarations
* analyzes expressions and statements, emitting error messages where appropriate
* creates module files if the source code contains modules,
  see [ModFiles.md](ModFiles.md).

In the course of semantic analysis, the compiler:
* creates the symbol table
* decorates the parse tree with semantic information (such as pointers into the symbol table)
* creates the intrinsic procedure table
* folds constant expressions

At the end of semantic processing, all validation of the user's program is complete.  This is the last detailed phase of analysis processing.

**Commands:**
  - `flang -fc1 -fdebug-dump-parse-tree src.f90` dumps the parse tree after semantic analysis
  - `flang -fc1 -fdebug-dump-symbols src.f90` dumps the symbol table
  - `flang -fc1 -fdebug-dump-all src.f90` dumps both the parse tree and the symbol table

## Lowering

Lowering takes the parse tree and symbol table produced by analysis and
produces LLVM IR.

### Create the lowering bridge

**Inputs:**
  - the parse tree
  - the symbol table
  - The default KINDs for intrinsic types (specified by default or command line option)
  - The intrinsic procedure table (created in semantics processing)
  - The target characteristics (created during semantics processing)
  - The cooked character stream
  - The target triple -- CPU type, vendor, operating system
  - The mapping between Fortran KIND values to FIR KIND values

The lowering bridge is a container that holds all of the information needed for lowering.

**Output:** A container with all of the information needed for lowering

**Entry point:** lower::LoweringBridge::create

### Initial lowering

**Input:** the lowering bridge

**Output:** A Fortran IR (FIR) representation of the program.

**Entry point:** `lower::LoweringBridge::lower`

The compiler then takes the information in the lowering bridge and creates a
pre-FIR tree or PFT.  The PFT is a list of programs and modules.  The programs
and modules contain lists of function-like units.  The function-like units
contain a list of evaluations.  All of these contain pointers back into the
parse tree.  The compiler walks the PFT generating FIR.

**Commands:**
  - `flang -fc1 -fdebug-dump-pft src.f90` dumps the pre-FIR tree
  - `flang -fc1 -emit-mlir src.f90` dumps the FIR to the files src.mlir

### Transformation passes

**Input:** initial version of the FIR code

**Output:** An LLVM IR representation of the program

**Entry point:** `mlir::PassManager::run`

The compiler then runs a series of passes over the FIR code.  The first is a
verification pass.  It's followed by a series of transformation passes that
perform various optimizations and transformations.  The final pass creates an
LLVM IR representation of the program.

**Commands:**
  - `flang -fc1 -emit-llvm src.f90` dumps the LLVM IR to src.ll
  - `flang -mmlir --mlir-print-ir-after-all -S src.f90` dumps the FIR code after each pass to standard error
  - `flang -mmlir --mlir-print-ir-before=<pass> -S src.f90` dumps the FIR code before a specific pass to standard error
  - `flang -mmlir --mlir-print-ir-after=<pass> -S src.f90` dumps the FIR code after a specific pass to standard error

Note: The exact set of passes depends on compilation options.  For example,
`stack-arrays` only appears when `-fstack-arrays` is enabled.  To see the
complete list for a given compilation, use `--mlir-print-ir-before-all` and
look at the `IR Dump Before` headers.

## Object code generation and linking

After the LLVM IR is created, the flang driver invokes LLVM's existing
infrastructure to generate object code and invoke a linker to create the
executable file.

---

### Flang Docs Index (`flang/docs/index.md`)

# Welcome to Flang's documentation

Flang is LLVM's Fortran frontend that can be found
[here](https://github.com/llvm/llvm-project/tree/main/flang). It is often
referred to as "LLVM Flang" to differentiate itself from ["Classic
Flang"](https://github.com/flang-compiler/flang) - these are two separate and
independent Fortran compilers. LLVM Flang is under active development. While it
is capable of generating executables for a number of examples, some
functionality is still missing. See [Getting Involved](GettingInvolved.md) for tips
on how to get in touch with us and to learn more about the current status.

```{eval-rst}
.. toctree::
   :titlesonly:

   ReleaseNotes
```

# Using Flang

```{eval-rst}
.. toctree::
   :titlesonly:

   GettingStarted
   FlangCommandLineReference
   FortranStandardsSupport
   Extensions
   Directives
   OpenMPSupport
   OpenMP-extensions
   Real16MathSupport
   Unsigned
   FAQ
```

# Contributing to Flang

```{eval-rst}
.. toctree::
   :titlesonly:

   C++17
   C++style
   DesignGuideline
   FortranForCProgrammers
   GettingInvolved
   ImplementingASemanticCheck
   PullRequestChecklist
```

# Design Documents

```{eval-rst}
.. toctree::
   :titlesonly:

   Aliasing
   AliasingAnalysisFIR
   ArrayComposition
   ArrayRepacking
   AssumedRank
   BijectiveInternalNameUniquing
   Calls
   Character
   ComplexOperations
   ControlFlowGraph
   DebugGeneration
   DoConcurrent
   DoConcurrentConversionToOpenMP
   F202X
   FIRLangRef
   FlangDriver
   FortranFeatureHistory
   FortranIR
   FortranLLVMTestSuite
   HighLevelFIR
   IORuntimeInternals
   InlineRuntimeChecks
   InternalProcedureTrampolines
   Intrinsics
   IntrinsicTypes
   LabelResolution
   ModFiles
   OpenACC
   OpenACC-extensions
   OpenACC-descriptor-management.md
   OpenMP-4.5-grammar.md
   OpenMP-declare-target
   OpenMP-descriptor-management
   OpenMP-semantics
   OptionComparison
   Overview
   ParallelMultiImageFortranRuntime
   ParameterizedDerivedTypes
   ParserCombinators
   Parsing
   PolymorphicEntities
   Preprocessing
   ProcedurePointer
   RuntimeDescriptor
   RuntimeEnvironment
   RuntimeTypeInfo
   Semantics
   f2018-grammar.md
   fstack-arrays
```

# Historical References

```{eval-rst}
.. toctree::
   :titlesonly:

   HLFIRTransition
```

# Indices and tables

```{eval-rst}
* :ref:`genindex`
* :ref:`search`
```

---

### Libc Docs Index (`libc/docs/index.md`)

```{image} ./_static/llvm_libc_logo.svg
:alt: The LLVM-libc logo, drawn by Jordan Abrahams-Whitehead
:align: right
:width: 25%
```

# The LLVM C Library

LLVM-libc is a from-scratch implementation of the C standard library, built as
part of the LLVM project. It is designed to be **modular** (any piece can be
used independently), **multiplatform** (Linux, GPU, baremetal embedded, UEFI,
macOS, Windows), and written in modern C++ for correctness, performance, and
safety.

The logo was drawn by Jordan Abrahams-Whitehead

## What Works Today

LLVM-libc is **actively used in production** for a targeted set of use cases,
though coverage is still growing and many programs that depend on the full C
standard library (regex, locale, wide-character I/O, etc.) will not yet compile
against it:

- **Static-linked Linux servers and containers** — used in production at Google
  (servers and Pixel Buds) on x86-64 and AArch64.
- **GPU compute (AMDGPU, NVPTX)** — libc functions available in GPU kernels
  via LLVM's offloading runtime. {doc}`GPU docs <gpu/index>`
- **Baremetal embedded (ARM, RISC-V, AArch64)** — minimal footprint builds
  for microcontrollers and custom hardware.
- **UEFI applications** — experimental support for firmware development.
  {doc}`UEFI docs <uefi/index>`
- **LLVM ecosystem internals** — libc++ and the offloading runtime consume
  LLVM-libc directly via {doc}`Hand-in-Hand <hand_in_hand>`.
- **Toolchain integrations** — pieces of LLVM-libc are used in Android Bionic,
  Fuchsia, Emscripten, and the ARM embedded toolchain.

Coverage is still growing. See the {doc}`implementation status <headers/index>`
pages for per-header detail, and the
{doc}`platform support <platform_support>` page for OS/architecture coverage.

## Getting Started

If you are new to LLVM-libc, {doc}`getting_started` is the right first stop.
It covers cloning, building, testing, and verifying your installation in one
place.

Want to use LLVM-libc *alongside* your system libc instead of replacing it?
See {doc}`overlay_mode`.

## Get Involved

LLVM-libc is an active project and welcomes contributors of all experience
levels. See {doc}`contributing` to learn how to help.

- [Source code](https://github.com/llvm/llvm-project/tree/main/libc)
- [Bug reports](https://github.com/llvm/llvm-project/labels/libc)
- [Discourse](https://discourse.llvm.org/c/runtimes/libc)
- [Discord](https://discord.com/channels/636084430946959380/636732994891284500)
  ([invite](https://discord.gg/xS7Z362))
- [Buildbot](https://lab.llvm.org/buildbot/#/builders?tags=libc)

```{toctree}
:caption: Using LLVM-libc
:hidden: true
:maxdepth: 1

getting_started
build_concepts
overlay_mode
full_host_build
full_cross_build
configure
hand_in_hand
```

```{toctree}
:caption: Platforms
:hidden: true
:maxdepth: 1

gpu/index
uefi/index
```

```{toctree}
:caption: Implementation Status
:hidden: true
:maxdepth: 1

headers/index
arch_support
platform_support
compiler_support
```

```{toctree}
:caption: Development
:hidden: true
:maxdepth: 1

contributing
build_and_test
dev/index
porting
Maintainers
```

```{toctree}
:caption: Links
:hidden: true
:maxdepth: 1

talks
Source Code <https://github.com/llvm/llvm-project/tree/main/libc>
Bug Reports <https://github.com/llvm/llvm-project/labels/libc>
Discourse <https://discourse.llvm.org/c/runtimes/libc>
Join the Discord <https://discord.gg/xS7Z362>
Discord Channel <https://discord.com/channels/636084430946959380/636732994891284500>
Buildbot <https://lab.llvm.org/buildbot/#/builders?tags=libc>
```

---

### Clang Docs CIR Index (`clang/docs/CIR/index.md`)

# ClangIR

:::{warning}
The project of upstreaming ClangIR support from the incubator repository is
still in progress, and ClangIR is not included in a default clang build. The
documentation may be incomplete and out-of-date.
:::

ClangIR is a high-level representation in Clang that reflects aspects of the
C/C++ languages and their extensions. It is implemented using MLIR and occupies
a position between Clang's AST and LLVM IR.

## ClangIR Design Documents

```{toctree}
:maxdepth: 1
:numbered:

ABILowering
CleanupAndEHDesign
CodeDuplication
```

---

### Clang Docs CommandGuide Index (`clang/docs/CommandGuide/index.md`)

# Clang "man" pages

The following documents are command descriptions for all of the Clang tools.
These pages describe how to use the Clang commands and what their options are.
Note that these pages do not describe all of the options available for all
tools. To get a complete listing, pass the `--help` (general options) or
`--help-hidden` (general and debugging options) arguments to the tool you are
interested in.

## Basic Commands

```{toctree}
:maxdepth: 1

clang
diagtool
```

---

### Clang Docs ScalableStaticAnalysis Index (`clang/docs/ScalableStaticAnalysis/index.md`)

# Scalable Static Analysis Framework

This is a framework for writing cross-translation unit analyses in a scalable and extensible setting.

```{toctree}
:glob: true
:maxdepth: 2
:numbered:

user-docs/*
```

{doc}`Developer documentation <developer-docs/index>`

```{toctree}
:hidden: true

developer-docs/index
```

---

### Flang Docs CommandGuide Index (`flang/docs/CommandGuide/index.md`)

# flang - the Flang Fortran compiler

## SYNOPSIS

{program}`flang` \[*options*\] *filename ...*

## DESCRIPTION

{program}`flang` is a Fortran compiler which supports all of the Fortran 95 and
many newer language features. Flang supports OpenMP and has some support for
OpenACC and CUDA. It encompasses preprocessing, parsing, optimization, code
generation, assembly, and linking. Depending on the options passed in, Flang
will perform only some, or all, of these actions. While Flang is highly
integrated, it is important to understand the stages of compilation in order to
understand how to invoke it. These stages are:

Driver

: The flang executable is actually a small driver that orchestrates the
  execution of other tools such as the compiler, assembler and linker.
  Typically you do not need to interact with the driver, but you
  transparently use it to run the other tools.

Preprocessing

: This stage performs tokenization of the input source file, macro expansion,
  #include expansion and handles other preprocessor directives.

Parsing and Semantic Analysis

: This stage parses the input file, translating preprocessor tokens into a
  parse tree. Once in the form of a parse tree, it applies semantic
  analysis to compute types for expressions and determine whether
  the code is well formed. Parse errors and most compiler warnings
  are generated by this stage.

Code Generation and Optimization

: This stage translates the parse tree into intermediate code (known as
  "LLVM IR") and, ultimately, machine code. It also optimizes this
  intermediate code and handles target-specific code generation. The output
  of this stage is typically a ".s" file, referred to as an "assembly" file.

  Flang also supports the use of an integrated assembler, in which the code
  generator produces object files directly. This avoids the overhead of
  generating the ".s" file and calling the target assembler explicitly.

Assembler

: This stage runs the target assembler to translate the output of the
  compiler into a target object file. The output of this stage is typically
  a ".o" file, referred to as an "object" file.

Linker

: This stage runs the target linker to merge multiple object files into an
  executable or dynamic library. The output of this stage is typically
  an "a.out", ".dylib" or ".so" file.

## OPTIONS

:::{toctree}
:maxdepth: 1

FlangCommandLineOptions
:::

---

### Flang Docs MeetingNotes README (`flang/docs/MeetingNotes/README.md`)

# Combined Flang Community Call Notes

## About these notes

This directory combines the notes from the Flang Technical and Community Calls. This was done to make the call notes more easily available than before. All references to Flang in these documents refer to the Fortran compiler being developed as part of the LLVM project and located in the LLVM monorepo ([github.com/llvm/llvm-project](http://github.com/llvm/llvm-project)). Information about "Classic Flang", a separate and independent Fortran compiler, can be found at [github.com/flang-compiler/flang](http://github.com/flang-compiler/flang).

## Call Information
- Details about the call can be found in the [Getting Involved](https://flang.llvm.org/docs/GettingInvolved.html#flang-biweekly-call) page in flang's documentation.

## Flang Community

* **Websites:**  
  * **Flang:** [https://flang.llvm.org](https://flang.llvm.org)   

* **Issues:**  
  * Issues for Flang should be reported in GitHub: [https://github.com/llvm/llvm-project/issues](https://github.com/llvm/llvm-project/issues). Please use the "flang" tag for flang-related issues.

* **LLVM mailing lists and Discourse channels:** There are now two communication channels hosted by llvm.org:  
  * The Flang Discourse channel (used primarily for discussions): [https://discourse.llvm.org/c/subprojects/flang/33](https://discourse.llvm.org/c/subprojects/flang/33)
  * The flang-commits mailing list (used primarily for routine notifications): subscribe at [https://lists.llvm.org/cgi-bin/mailman/listinfo/flang-commits](https://lists.llvm.org/cgi-bin/mailman/listinfo/flang-commits)

* **Slack:** The [flang-compiler.slack.com](http://flang-compiler.slack.com)
workspace is used for informal real-time communication in the Flang community.  
See the [Getting Involved](https://flang.llvm.org/docs/GettingInvolved.html#flang-slack-workspace) page in flang's documentation for instructions on joining the workspace.

* **Flang Development:**  
  * On GitHub: The source code for Flang is available on [https://github.com/llvm/llvm-project/tree/main/flang](https://github.com/llvm/llvm-project/tree/main/flang). It is recommended to start in the "docs" directory.

---

### Libc Docs Dev Index (`libc/docs/dev/index.md`)

(developer_guides)=

# Developer Guides

Navigate to the links below for information on the respective topics:

```{toctree}
:maxdepth: 1

building_docs
code_style
source_tree_layout
entrypoints
implementing_a_function
config_options
date_and_time
fuzzing
header_generation
implementation_standard
undefined_behavior
printf_behavior
builtin_compatibility
syscall_wrapper_refactor
modular_format
code_coverage
```

---

### Clang Docs ScalableStaticAnalysis Developer Docs Index (`clang/docs/ScalableStaticAnalysis/developer-docs/index.md`)

# Developer Documentation

```{toctree}
:glob: true
:maxdepth: 2
:numbered:

*
```

---

### Clang Tools Extra Docs Clang Tidy Checks Cppcoreguidelines Pro Bounds Constant Array Index (`clang-tools-extra/docs/clang-tidy/checks/cppcoreguidelines/pro-bounds-constant-array-index.md`)

```{title} clang-tidy - cppcoreguidelines-pro-bounds-constant-array-index
```

# cppcoreguidelines-pro-bounds-constant-array-index

This check flags all array subscript expressions on static arrays and
`std::arrays` that either do not have a constant integer expression index or
are out of bounds (for `std::array`). For out-of-bounds checking of static
arrays, see the `-Warray-bounds` Clang diagnostic.

This rule is part of the [Bounds safety (Bounds 2)](https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#pro-bounds-arrayindex)
profile from the C++ Core Guidelines.

Optionally, this check can generate fixes using `gsl::at` for indexing.

## Options

```{option} GslHeader

The check can generate fixes after this option has been set to the name of
the include file that contains `gsl::at()`, e.g. `"gsl/gsl.h"`.
Default is an empty string.
```

```{option} IncludeStyle

A string specifying which include-style is used, `llvm` or `google`. Default
is `llvm`.
```

---

### Clang Tools Extra Docs Clang Tidy Checks Readability Misplaced Array Index (`clang-tools-extra/docs/clang-tidy/checks/readability/misplaced-array-index.md`)

```{title} clang-tidy - readability-misplaced-array-index
```

# readability-misplaced-array-index

This check warns for unusual array index syntax.

The following code has unusual array index syntax:

```cpp
void f(int *X, int Y) {
  Y[X] = 0;
}
```

becomes

```cpp
void f(int *X, int Y) {
  X[Y] = 0;
}
```

The check warns about such unusual syntax for readability reasons:

- There are programmers that are not familiar with this unusual syntax.
- It is possible that variables are mixed up.

---

### Bolt Docs BAT (`bolt/docs/BAT.md`)

# BOLT Address Translation (BAT)
# Purpose
A regular profile collection for BOLT involves collecting samples from
unoptimized binary. BOLT Address Translation allows collecting profile
from BOLT-optimized binary and using it for optimizing the input (pre-BOLT)
binary.

# Overview
BOLT Address Translation is an extra section (`.note.bolt_bat`) inserted by BOLT
into the output binary containing translation tables and split functions linkage
information. This information enables mapping the profile back from optimized
binary onto the original binary.

# Usage
`--enable-bat` flag controls the generation of BAT section. Sampled profile
needs to be passed along with the optimized binary containing BAT section to
`perf2bolt` which reads BAT section and produces profile for the original
binary.

# Internals
## Section contents
The section is organized as follows:
- Hot functions table
  - Address translation tables
- Cold functions table

## Construction and parsing
BAT section is created from `BoltAddressTranslation` class which captures
address translation information provided by BOLT linker. It is then encoded as a
note section in the output binary.

During profile conversion when BAT-enabled binary is passed to perf2bolt,
`BoltAddressTranslation` class is populated from BAT section. The class is then
queried by `DataAggregator` during sample processing to reconstruct addresses/
offsets in the input binary.

## Encoding format
The encoding is specified in
[BoltAddressTranslation.h](https://github.com/llvm/llvm-project/blob/main/bolt/include/bolt/Profile/BoltAddressTranslation.h)
and [BoltAddressTranslation.cpp](https://github.com/llvm/llvm-project/blob/main/bolt/lib/Profile/BoltAddressTranslation.cpp).

### Layout
The general layout is as follows:
```
Hot functions table
Cold functions table

Functions table:
|------------------|
|  Function entry  |
|                  |
|     Address      |
|   translation    |
|      table       |
|                  |
| Secondary entry  |
|      points      |
|------------------|

```

### Functions table
Hot and cold functions tables share the encoding except differences marked below.

Header:
| Entry  | Encoding | Description |
| ------ | ----- | ----------- |
| `NumFuncs` | ULEB128 | Number of functions in the functions table |

The header is followed by Functions table with `NumFuncs` entries.
Output binary addresses are delta encoded, meaning that only the difference with
the last previous output address is stored. Addresses implicitly start at zero.
Output addresses are continuous through function start addresses and function
internal offsets, and between hot and cold fragments, to better spread deltas
and save space.

Hot indices are delta encoded, implicitly starting at zero.
| Entry  | Encoding | Description | Hot/Cold |
| ------ | ------| ----------- | ------ |
| `Address` | Continuous, Delta, ULEB128 | Function address in the output binary | Both |
| `HotIndex` | Delta, ULEB128 | Index of corresponding hot function in hot functions table | Cold |
| `FuncHash` | 8b | Function hash for input function | Hot |
| `NumBlocks` | ULEB128 | Number of basic blocks in the original function | Hot |
| `NumSecEntryPoints` | ULEB128 | Number of secondary entry points in the original function | Hot |
| `ColdInputSkew` | ULEB128 | Skew to apply to all input offsets | Cold |
| `NumEntries` | ULEB128 | Number of address translation entries for a function | Both |
| `EqualElems` | ULEB128 | Number of equal offsets in the beginning of a function | Both |
| `BranchEntries` | Bitmask, `alignTo(EqualElems, 8)` bits | If `EqualElems` is non-zero, bitmask denoting entries with `BRANCHENTRY` bit | Both |

Function header is followed by *Address Translation Table* with `NumEntries`
total entries, and *Secondary Entry Points* table with `NumSecEntryPoints`
entries (hot functions only).

### Address translation table
Delta encoding means that only the difference with the previous corresponding
entry is encoded. Input offsets implicitly start at zero.
| Entry  | Encoding | Description | Branch/BB |
| ------ | ------| ----------- | ------ |
| `OutputOffset` | Continuous, Delta, ULEB128 | Function offset in output binary | Both |
| `InputOffset` | Optional, Delta, SLEB128 | Function offset in input binary with `BRANCHENTRY` LSB bit | Both |
| `BBHash` | Optional, 8b | Basic block hash in input binary | BB |
| `BBIdx`  | Optional, Delta, ULEB128 | Basic block index in input binary | BB |

The table omits the first `EqualElems` input offsets where the input offset
equals output offset.

`BRANCHENTRY` bit denotes whether a given offset pair is a control flow source
(branch or call instruction). If not set, it signifies a control flow target
(basic block offset).

`InputAddr` is omitted for equal offsets in input and output function. In this
case, `BRANCHENTRY` bits are encoded separately in a `BranchEntries` bitvector.

Deleted basic blocks are emitted as having `OutputOffset` equal to the size of
the function. They don't affect address translation and only participate in
input basic block mapping.

### Secondary Entry Points table
The table is emitted for hot fragments only. It contains `NumSecEntryPoints`
offsets denoting secondary entry points, delta encoded, implicitly starting at zero.
| Entry | Encoding | Description |
| ----- | -------- | ----------- |
| `SecEntryPoint` | Delta, ULEB128 | Secondary entry point offset |

---

### Bolt Docs BOLTAArch64OptimizationStatus (`bolt/docs/BOLTAArch64OptimizationStatus.md`)

# AArch64 Optimization and Flags Status

## Overview

This page summarizes default-off BOLT optimization flags that users may
explicitly enable when optimizing AArch64 binaries.

BOLT is to be used with binaries linked with
relocations (`--emit-relocs` or `-Wl,-q`) and representative profile data.

## Main Code-Layout Optimizations

The following code-layout optimizations are typically the first options to
consider when optimizing AArch64 binaries with representative profile data.
They typically provide the largest performance gains among BOLT optimizations.

:::{list-table}
:header-rows: 1
:widths: 34 42
:align: left

* - Flag
  - Optimization
* - `--reorder-functions=exec-count|hfsort|cdsort|pettis-hansen|random|user`
    `--function-order=<file>`
  - Reorder functions
* - `--reorder-blocks=normal|ext-tsp|cache|branch-predictor|reverse|cluster-shuffle`
  - Reorder basic blocks
* - `--split-functions`
    `--split-strategy=profile2|random2|randomN|all`
    `--split-all-cold`
    `--split-eh`
  - Split hot and cold code
:::

## Other Supported Optimizations

The following optimizations are also supported for AArch64.

:::{list-table}
:header-rows: 1
:widths: 34 42
:align: left

* - Flag
  - Optimization
* - `--align-blocks`
    `--block-alignment=<uint>`
  - Align basic blocks
* - `--tail-duplication=aggressive|moderate|cache`
  - Duplicate branch tails
* - `--peepholes=double-jumps|tailcall-traps|useless-branches|all`
  - Run peephole optimizations
* - `--inline-all`
    `--inline-small-functions`
    Related options:
    `--inline-ap`
    `--inline-limit=<uint>`
    `--inline-small-functions-bytes=<uint>`
  - Inline functions
* - `--icf=safe|all`
  - Fold identical functions
:::

## Supported Flags With Limitations

The following flags are implemented for AArch64, but require specific runtime
or option conditions. Enabling them without the required conditions may report
an error or perform no transformation.

:::{list-table}
:header-rows: 1
:widths: 30 28 44
:align: left

* - Flag
  - Optimization
  - Notes
* - `--inline-memcpy`
  - Inline fixed-size `memcpy` calls
  - Only applies when the copy size is a known constant; AArch64 skips sizes over 64 bytes.
* - `--plt=hot|all`
  - Optimize PLT calls
  - Requires immediate binding. If BOLT cannot update the binary, relink with `-znow`.
* - `--hugify`
  - Place hot code on huge pages
  - Applies to binaries with a recognized entry point; skipped when `--instrument` is used.
* - `--reorder-data=<section1,section2,...>`
    `--reorder-data-algo=count|funcs`
  - Reorder data sections
  - `move`, `split` and `aggressive` disable data reordering.
* - `--split-strategy=cdsplit`
  - Split functions using cache-directed splitting
  - Requires `--compact-code-model` on AArch64.
:::

## Unsupported Flags

The following flags are not available for AArch64. `Not applicable to
AArch64` means the optimization targets architectural features or mechanisms
that do not apply to AArch64. `Not implemented for AArch64` means the
optimization could be relevant, but is not currently implemented for this
target.

:::{list-table}
:header-rows: 1
:widths: 30 28 42
:align: left

* - Flag
  - Optimization
  - Notes
* - `--jt-footprint-reduction`
  - Reduce jump-table footprint
  - Not implemented for AArch64.
* - `--three-way-branch`
  - Reorder three-way branches
  - Not implemented for AArch64.
* - `--simplify-rodata-loads`
  - Replace read-only data loads with constants
  - Not implemented for AArch64.
* - `--frame-opt=hot|all`
  - Optimize stack-frame accesses
  - Not implemented for AArch64.
* - `--indirect-call-promotion=calls|jump-tables|all`
  - Promote indirect calls
  - Not implemented for AArch64.
* - `--memcpy1-spec=<func1,func2:cs1:cs2,...>`
  - Specialize one-byte `memcpy` calls
  - Not implemented for AArch64.
* - `--reg-reassign`
  - Reassign registers to reduce encoding size
  - Not applicable to AArch64.
* - `--cmov-conversion`
  - Convert branches to conditional moves
  - Not applicable to AArch64.
* - `--stoke`

    `--stoke-out`
  - Emit STOKE optimization data
  - Not applicable to AArch64.
* - `--insert-retpolines`
  - Insert retpolines
  - Not applicable to AArch64.
:::

---

### Bolt Docs BinaryAnalysis (`bolt/docs/BinaryAnalysis.md`)

# BOLT-based binary analysis

As part of post-link-time optimization, BOLT needs to perform a range of analyses
on binaries such as reconstructing control flow graphs, and more.

The `llvm-bolt-binary-analysis` tool enables running requested analyses
on binaries, and generating reports. It does this by building on top of the
analyses implemented in the BOLT libraries.

For now, the only analysis implemented is validation of Pointer Authentication
hardening on AArch64, more types of analyses can be added later.

## Contents

1. [Background and motivation](#background-and-motivation)
2. [Usage](#usage)
3. [Pointer Authentication validator](#pointer-authentication-validator)
4. [How to add your own analysis](#how-to-add-your-own-analysis)

## Background and motivation

### Security scanners

For the past 25 years, a large numbers of exploits have been built and used in
the wild to undermine computer security. The majority of these exploits abuse
memory vulnerabilities in programs, see evidence from
[Microsoft](https://youtu.be/PjbGojjnBZQ?t=836),
[Chromium](https://www.chromium.org/Home/chromium-security/memory-safety/) and
[Android](https://security.googleblog.com/2021/01/data-driven-security-hardening-in.html).

It is not surprising therefore, that a large number of mitigations have been
added to instruction sets and toolchains to make it harder to build an exploit
using a memory vulnerability. Examples are: stack canaries, stack clash,
pac-ret, shadow stacks, arm64e, and many more.

These mitigations guarantee a so-called "security property" on the binaries they
produce. For example, for stack canaries, the security property is roughly that
a canary is located on the stack between the set of saved registers and the set
of local variables. For pac-ret, it is roughly that either the return address is
never stored/retrieved to/from memory; or, there are no writes to the register
containing the return address between an instruction authenticating it and a
return instruction using it.

From time to time, however, a bug gets found in the implementation of such
mitigations in toolchains. Also, code that is manually written in assembly
requires the developer to ensure these security properties by hand.

In short, it is sometimes found that a few places in the binary code are not
protected as well as expected given the requested mitigations. Attackers could
make use of those places (sometimes called gadgets) to circumvent the protection
that the mitigation should give.

One of the reasons that such gadgets, or holes in the mitigation implementation,
exist is that typically the amount of testing and verification for these
security properties is limited to checking results on specific examples.

In comparison, for testing functional correctness, or for testing performance,
toolchain and software in general typically get tested with large test suites
and benchmarks. In contrast, this typically does not get done for testing the
security properties of binary code.

Unlike functional correctness where compilation errors result in test failures,
and performance where speed and size differences are measurable, broken security
properties cannot be easily observed using existing testing and benchmarking
tools.

The security scanners implemented in `llvm-bolt-binary-analysis` aim to enable
the testing of security hardening in arbitrary programs and not just specific
examples.

### Pointer Authentication

[Pointer Authentication](https://clang.llvm.org/docs/PointerAuthentication.html)
is intended to make it harder for an attacker to replace pointers at run time.
This is achieved by making it possible for the compiler or the programmer to
produce a *signed* pointer from a raw one, and then to probabilistically
*authenticate the signature* at another site in the program.
On AArch64 this is achieved by injecting a cryptographic hash, called a
["Pointer Authentication Code" (PAC)](https://llsoftsec.github.io/llsoftsecbook/#sec:pointer-authentication),
to the upper bits of the pointer.
While this approach can be applied to any pointers in the program, the most
frequent use case, at least in C and C++, is protecting the code pointers.
The language rules for such pointers are more restrictive, thus allowing the
compiler to implement various hardenings transparently to the programmer.

Probably the most simple variant of hardening based on Pointer Authentication is
[`pac-ret`](https://llsoftsec.github.io/llsoftsecbook/#sec:pac-ret), a security
hardening scheme implemented in compilers such as GCC and Clang, which can be
enabled with a command line option like `-mbranch-protection=pac-ret`.
On AArch64, `pac-ret` hardening is enabled by default on most widely used Linux
distributions. The hardening scheme mitigates
[Return-Oriented Programming (ROP)](https://llsoftsec.github.io/llsoftsecbook/#return-oriented-programming)
attacks by making sure that return addresses are only ever stored to memory
in a signed form. This makes it substantially harder for attackers to divert
control flow by overwriting a return address with a different value.

It is possible to link object files with different pac-ret hardening modes together,
as each particular function is responsible for signing the LR value in the prologue
and authenticating it in the epilogue. Other hardening variants exist that break
ABI compatibility, see the description of
[PAuth ABI Extensions](https://github.com/ARM-software/abi-aa/blob/main/pauthabielf64/pauthabielf64.rst)
for details. While pac-ret hardens (signs and authenticates) return addresses,
PAuth ABI may harden most other code pointers as well, such as function pointers
and labels used as the destination of computed goto.

The approach to validation of Pointer Authentication hardening implemented in
`llvm-bolt-binary-analysis` is tracking register properties using dataflow analysis.
At each program point it is computed whether the particular register can be
controlled and whether it can be inspected by an attacker under the
[Pointer Authentication threat model](https://clang.llvm.org/docs/PointerAuthentication.html#theory-of-operation).
Then, for a number of sensitive instruction kinds (such as function calls and
pointer signing instructions), the properties of input or output operands are
inspected to check if the particular instruction is emitted in a safe manner.
As an example, for a return instruction this usually means that either the link
register (`x30`, which is also referred to as LR on AArch64) was never clobbered
in the function, or that it was authenticated at some point and never written to
since then:

```
foo:
    ; x30 is assumed to be trusted on function entry
  cbnz    x0, .L1
    ; For every possible execution path leading to this point, x30 was never
    ; clobbered and is thus safe to be used by `ret`.
  ret
.L1:
  paciasp
  stp     x29, x30, [sp, #-16]!
  mov     x29, sp

  bl      bar

  ldp     x29, x30, [sp], #16
  autiasp
    ; At this point, x30 was never written to since `autiasp`.
  ret
```

The real rules being used by `llvm-bolt-binary-analysis` are somewhat more
complex, see the below sections for the detailed explanation.

## Usage

```
llvm-bolt-binary-analysis --scanners=<list> [options] <binary>
```

The `--scanners=` option accepts a comma-separated list of analyses to run on
the provided binary. The binary to be analyzed can be either an ELF executable or
a shared object. Similar to other BOLT tools, `llvm-bolt-binary-analysis` expects
`binary` to be unstripped and preferably linked with `--emit-relocs` linker option.

In addition to options printed by `llvm-bolt-binary-analysis --help-hidden`,
other relevant BOLT options can generally be passed, see `llvm-bolt --help-hidden`.
Incomplete help message is a known issue and is tracked in
[#176969](https://github.com/llvm/llvm-project/issues/176969).

The only analysis which is currently implemented is validation of a number of
Pointer Authentication-based hardening schemes such as pac-ret and PAuth ABI.
The specific set of gadget kinds which are searched for depends on command line
options. Each gadget found by PtrAuth gadget scanner results in a plain text
report printed at the end of the analysis. Furthermore, an attempt is made to
provide additional information on the instructions that made the register unsafe.
Please note that this extra information is provided on a best-effort basis and
is not expected to be as accurate as the reports themselves.

Here is an example of the report:

```
GS-PAUTH: signing oracle found in function function_name, basic block .LBB08, at address 102b8
  The instruction is     000102b8:      pacda   x0, x1
  The 1 instructions that write to the affected registers after any authentication are:
  1.     000102b4:      ldr     x0, [x1]
  This happens in the following basic block:
    000102b4:   ldr     x0, [x1]
    000102b8:   pacda   x0, x1
    000102bc:   ret
```

A similar report without the associated extra information looks like this:

```
GS-PAUTH: signing oracle found in function function_name, basic block .LBB016, at address 10384
  The instruction is     00010384:      pacda   x0, x1
  The 0 instructions that write to the affected registers after any authentication are:
```

## Pointer Authentication validator

Pointer Authentication analysis is able to search for a number of gadget kinds,
with the specific set depending on command line options:
* [`ptrauth-pac-ret`](#return-address-protection-ptrauth-pac-ret) -
  non-protected return instruction
* [`ptrauth-tail-calls`](#return-address-protection-before-tail-call-ptrauth-tail-calls) -
  performing a tail call with an untrusted value in the link register
* [`ptrauth-forward-cf`](#ptrauth-forward-cf) -
  non-protected destination of branch or call instruction
* [`ptrauth-sign-oracles`](#signing-oracles-ptrauth-sign-oracles) -
  signing of untrusted value (signing oracle)
* [`ptrauth-auth-oracles`](#authentication-oracles-ptrauth-auth-oracles) -
  revealing the result of authentication without crashing the program on failure
  (authentication oracle)

Validation is performed by `llvm-bolt-binary-analysis` on a per-function basis.
First, the register properties are computed by analyzing the function as a whole.
Then, the instructions are considered in isolation. For each kind of gadget,
the set of susceptible instructions is computed. The properties of input or
output registers of each such instruction are analyzed and reports are produced
for each detected gadget.

Each gadget kind that is searched for can be characterized by the combination of
* the set of instructions to analyze
* the properties of input or output operands to check

Currently, three properties can be computed for each register at any given
program point:
* **"trusted"** - the register is known not to be attacker-controlled, either because
  it successfully passed authentication or because its value was materialized
  using an instruction sequence that an attacker cannot tamper with
  * **"safe-to-dereference"** (sometimes referred to as "s-t-d" below) -
    a weaker property that the register can be controlled by an attacker to some
    extent, but any memory access using a value crafted by an attacker is known
    to result in an access to an unmapped memory ("segmentation fault").
    This makes it possible for authentication instructions to return an invalid
    address on failure as long as it is known to crash the program on accessing
    memory, but may require extra care to be taken when implementing operations
    like re-signing a pointer with a different signing schema without accessing
    that address in-between. If any failed authentication instruction is
    guaranteed to terminate the program abnormally, then "safe-to-dereference"
    and "trusted" properties are equivalent.
* **"cannot escape unchecked"** - at every possible execution path after this point,
  it is known to be impossible for an attacker to determine that the value is
  a result of a failed authentication operation (for example, the register is
  zeroed, or its value is checked to be valid, so that failure results in
  immediate abnormal program termination).

Generally, BOLT strives to reconstruct the control-flow graph of each function,
which is important for dataflow analysis. However, when BOLT fails to recognize
some control flow in the particular function, that function ends up being
represented as a flat list of instructions - in such cases
`llvm-bolt-binary-analysis` computes register properties using a fallback
analysis implementation, which is less precise.

The below sub-sections describe the particular detectors. Please note that while
the descriptions refer to AArch64 for simplicity, the implementation of gadget
detectors in `llvm-bolt-binary-analysis` attempts to be target-neutral by
isolating AArch64 specifics in target-dependent hooks.

### Return address protection (`ptrauth-pac-ret`)

**Instructions:** Return instructions without built-in authentication:
either `ret` (implicit `x30` register) or `ret <reg>`, but not `retaa` and
similar instructions.

**Property:** The register holding the return address must be safe-to-dereference.

**Notes:** Cross-exception-level return instructions (`eret`) are not analyzed yet.

A report is generated for a return instruction whose destination is possibly
attacker-controlled.

**Examples:**
```asm
authenticated_return:
  pacibsp
  ; ...
  ; ... some code here ...
  ; ...
  retab ; Built-in authentication, thus out of scope.

good_leaf_function:
  ; x30 is implicitly safe-to-dereference (s-t-d) and trusted at function entry.
  mov     x0, #42
  ; x30 was not written to by this function, thus remains s-t-d.
  ret

good_non_leaf_function:
  pacibsp

  ; Spilling signed return address.
  stp     x29, x30, [sp, #-16]!
  mov     x29, sp

  bl      callee

  ; Re-loading signed return address.
  ; LDP writes to x30 and thus resets it to neither s-t-d nor trusted state.
  ldp     x29, x30, [sp], #16

  ; Checking that signature is valid.
  ; AUTIBSP sets "s-t-d" property of x30, but not "trusted" (unless FEAT_FPAC
  ; is known to be implemented).
  autibsp

  ; x30 is s-t-d at this point.
  ret

bad_spill:
  ; x30 is implicitly s-t-d at function entry.
  stp     x29, x30, [sp, #-16]!
  mov     x29, sp

  bl      callee ; Spilled x30 may have been overwritten on stack.

  ; Writing to x30 resets its s-t-d property.
  ldp     x29, x30, [sp], #16
  ; x30 is unsafe by the time it is used by ret, thus generating a report.
  ret

bad_clobber:
  pacibsp
  ; ...
  ; ... some code here ...
  ; ...
  autibsp
  mov     x30, x1
  ; The value in LR is unsafe, even though there was autibsp above.
  ret
```

### Return address protection before tail call (`ptrauth-tail-calls`)

**Instructions:** Branch instructions (both direct and indirect, regular or
with built-in authentication), classified as tail calls either by BOLT or by
PtrAuth gadget scanner's heuristic.

**Property:** link register (`x30` on AArch64) must be trusted.

**Notes:** Heuristics are involved to classify instructions either as a tail
call or as another kind of branch (such as jump table or computed goto).

A report is generated if a tail call is performed with an untrusted link register.
This basically means that the tail-called function would have the link register
untrusted on its entry (unlike the inherently correct address placed in the link
register by one of the `bl*` instructions when a non-tail call is performed).

```asm
non_protected_tail_call:
  stp     x29, x30, [sp, #-16]!
  mov     x29, sp
  bl      callee
  ldp     x29, x30, [sp], #16
  ; x30 is neither trusted nor safe-to-dereference at this point.
  b       tail_callee

non_checked_tail_call:
  pacibsp
  stp     x29, x30, [sp, #-16]!
  mov     x29, sp
  bl      callee
  ldp     x29, x30, [sp], #16
  autibsp
  ; x30 is safe-to-dereference, but not fully trusted at this point.
  b       tail_callee

tail_callee:
  pacibsp
  ; ...
```

Even though `x30` is likely to be safe-to-dereference before exit from a function
(whether via return or tail call) in a consistently pac-ret-protected program,
with respect to this gadget kind it further must be fully "trusted".
This corresponds to the way tail calls are emitted when `--aarch64-authenticated-lr-check-method=`
option is specified with an argument other than `none`, or when such checks are
requested for the particular subtarget by default.

Properly mitigating this issue would usually require inserting an explicit
check after a regular authentication instruction, which may be either too
expensive (if a fully-generic XPAC-based sequence is being used) on one hand,
or not required at all (if `FEAT_FPAC` is known to be implemented) on the other hand.

(ptrauth-forward-cf)=
### Indirect branch / call target protection (`ptrauth-forward-cf`)

**Instructions:** Indirect call and branch instructions without built-in
authentication: either `blr <reg>` or `br <reg>`, but not `blraa`, `braa`
and similar instructions.

**Property:** The call or branch target register must be safe-to-dereference.

A report is generated for an indirect branch or call instruction whose destination
is possibly attacker-controlled.

**Examples:**

```asm
direct_call:
  ; ...
  bl     callee ; Direct call, thus out of scope.
  ; ...

authenticated_call:
  ; ...
  ldr     x2, [x1]
  blraa   x2, x1   ; Built-in authentication, thus out of scope.
  ; ...

good_call:
  ; ...
  ldr     x2, [x1]
  autia   x2, x1
  blr     x2
  ; ...

bad_call:
  ; ...
  ldr     x2, [x1]
  autia   x2, x1
  ; Store unprotected address.
  str     x2, [x3]
  ; ...
  ; The callee address may have been overwritten in memory.
  ldr     x2, [x3]
  blr     x2
  ; ...

good_call_dataflow:
  cbz     x0, .L1
  ldr     x2, [x1]
  autia   x2, x1
  b       .L2
.L1:
  adrp    x2, callee
  add     x2, x2, :lo12:callee
.L2:
  ; Dataflow analysis can deduce that x2 is s-t-d on any possible execution
  ; path leading to the below "br x2" instruction.
  br      x2

bad_call_dataflow:
  cbz     x0, .L3
  adrp    x2, callee
  add     x2, x2, :lo12:callee
.L3:
  ; x2 is untrusted if x0 is 0.
  br      x2

```

### Signing oracles (`ptrauth-sign-oracles`)

**Instructions:** Address-signing instructions.

**Property:** The address being signed must be trusted.

Reports signing of untrusted values, as this could make arbitrary and possibly
attacker-controlled values indistinguishable from perfectly trusted and protected ones.

Note that in absence of `--auth-traps-on-failure` command line option, this detector
reports auth+sign pairs unless an explicit check is emitted to make sure the
authentication operation succeeded. This corresponds to the way LLVM emits
instructions on AArch64.

**Examples:**

```asm
good_sign_constant:
  ; ...
  adrp    x0, sym
  add     x0, x0, :lo12:sym
  pacda   x0, x1
  ; ...

good_resign:
  ; ...
  autda   x0, x1
  ; x0 is s-t-d here.
  ldr     x2, [x0]
  ; If we got here without crashing on the above ldr, x0 is fully trusted.
  pacdb   x0, x1
  ; ...

bad_resign_if_not_fpac:
  ; ...
  autda   x0, x1
  ; x0 is only s-t-d, but not trusted here, unless autda raises an error on failure.
  pacdb   x0, x1
  ; ...

very_bad_function:
  pacda   x0, x1
  ret
```

### Authentication oracles (`ptrauth-auth-oracles`)

**Instructions:** Standalone authentication instructions: `autda`, `autdb`, etc.
(i.e. not those built into corresponding memory-accessing instructions, such as
`ldraa` or `blraa`).

**Property:** The **result** of authentication must be written to a register
that cannot escape unchecked.

Reports authentication instructions, whose result (success or failure) can be
observed by the attacker and used to guess the correct PAC field by trial-and-error.

The authentication oracles searched for by this detector are impossible if all
authentication instructions are known to generate an irrecoverable error on
failure. On AArch64 this is the case if CPU is known to implement `FEAT_FPAC`
(though recoverability depends on the OS: for example, on Linux such errors
result in signals that can be handled if configured accordingly).
This check is disabled by `--auth-traps-on-failure` command line option.

**Examples:**

```asm
; The descriptions assume FEAT_FPAC is not implemented.

good_auth_call:
  paciasp
  stp     x29, x30, [sp, #-16]!
  mov     x29, sp

  ; The result of authentication is inevitably dereferenced by blr.
  ; If autia returns a non-canonical address due to incorrect signature,
  ; the program crashes when the resulting address is jumped-to by blr.
  cbz     x2, .L1
  autia   x0, x1
  blr     x0

.L1:
  ldp     x29, x30, [sp], #16
  autiasp
  ret

bad_auth_call:
  paciasp
  stp     x29, x30, [sp, #-16]!
  mov     x29, sp

  ; x0 may be observed by the caller of bad_auth_call if x2 is 0.
  autia   x0, x1
  cbz     x2, .L2
  blr     x0

.L2:
  ldp     x29, x30, [sp], #16
  autiasp
  ret

bad_leaks_to_callee:
  paciasp
  stp     x29, x30, [sp, #-16]!
  mov     x29, sp

  ldr     x20, [x0]
  autda   x20, x0
  ; The result of authentication is leaked to the called function.
  bl      callee
  ; The below ldr instruction would properly check x20 if placed above the call.
  ldr     x0, [x20]

  ldp     x29, x30, [sp], #16
  autiasp
  ret
```

### Known issues and missing features

#### Control-flow graph availability

The analysis quality is degraded if BOLT is unable to reconstruct control-flow
graph of the function correctly.

When reconstructing CFG for a particular function, it is possible that BOLT
finds a code pattern that it is unable to handle. In that case PtrAuth validator
processes a function containing a flat list of instructions (as opposed to
interlinked basic blocks) and the reports (if any) are printed without the
`, basic block <name>` part in the first line.

Furthermore, it is possible that CFG information is returned by BOLT for a
function, even though the graph is imprecise. Inaccurate CFG information may
result in false positives and false negatives, thus PtrAuth gadget scanner
produces warning messages (at most once per function) for non-entry basic blocks
without any predecessors in CFG: while unreachable basic blocks are technically
correct, truly unreachable blocks are unlikely to exist in an optimized code.

Known gadget scanner issues related to CFG reconstruction are tracked in
[#177761](https://github.com/llvm/llvm-project/issues/177761),
[#178058](https://github.com/llvm/llvm-project/issues/178058),
[#178232](https://github.com/llvm/llvm-project/issues/178232).

#### Last writing instructions

Some of the reports contain extra information along these lines

```
  The 1 instructions that write to the affected registers after any authentication are:
  1.     000102b4:      ldr     x0, [x1]
  This happens in the following basic block:
    000102b4:   ldr     x0, [x1]
    000102b8:   pacda   x0, x1
    000102bc:   ret
```

This information is provided on a best-effort basis and is less reliable than
gadget reports themselves.

#### Feature: scan for unsafe computation of discriminators

On AArch64, signing and authentication operations are parameterized by the pair
of the key identifier and a 64-bit *discriminator* value. The key is one of
`IA`, `IB`, `DA`, or `DB`, and its identifier is directly encoded into the
instruction (the `GA` key differs significantly and is thus out of scope here).
The discriminator, on the other hand, is computed at run-time and is intended
to be [derived independently](https://clang.llvm.org/docs/PointerAuthentication.html#discriminators)
at the signing and authentication sites.

There is a common pattern on AArch64 to compute the discriminator as a blend
of an address and an integer modifier by inserting a compile-time constant
value into the top 16 bits of the storage address. It is not necessarily
possible to prevent an attacker from modifying the storage address, but the
insertion of 16-bit constant modifier can always be performed immediately before
the discriminator value is used by signing or authentication instruction.

While not as bad as signing an arbitrary untrusted pointer, spilling a
"ready-to-use" discriminator and then reloading a potentially modified value
later is something we would rather avoid. On the other hand, using an arbitrary
value as the discriminator should probably be allowed, making it hard to
distinguish the below patterns:

```asm
; Valid and not reported.
good_store_with_address_and_constant_diversity:
  mov     x16, x1
  movk    x16, #1234, lsl #48
  pacda   x0, x16
  str     x0, [x1]
  ret

; Valid and not reported.
good_store_with_address_diversity:
  pacda   x0, x1
  str     x0, [x1]
  ret

; Spilled discriminator. Not critically wrong, but could rather be avoided.
; Not reported, but probably should (false negative).
bad_spilling:
  mov     x16, x1
  movk    x16, #1234, lsl #48

  ; Spilling the discriminator to memory.
  str     x16, [x2]
  ; Reloaded value could have been modified by an attacker.
  ldr     x16, [x2]

  pacda   x0, x16
  str     x0, [x1]
  ret

; Not reported (and should probably not).
better_spilling:
  mov     x16, x1
  str     x16, [x2]
  ; Reloaded value could have been modified by an attacker.
  ldr     x16, [x2]

  movk    x16, #1234, lsl #48
  pacda   x0, x16
  str     x0, [x1]
  ret
```

#### Handling of constants

While (PC-relative) address constants are tracked as "trusted" register state
by `SrcSafetyAnalysis`, constant values are not generally accounted for.

This results in false-positives like reporting

```asm
  ; Let assume FEAT_FPAC is implemented.
  autda   x16, x22
  mov     x17, #0x128
  add     x16, x16, x17
  pacda   x16, x22
```

as a signing oracle, even though

```asm
  ; Let assume FEAT_FPAC is implemented.
  autda   x16, x22
  add     x16, x16, #8
  pacda   x16, x22
```

is not reported, because `add Xdst, Xsrc, #imm` is recognized as a safe address
computation.

As an example of false-negative, it is possible that an instruction like
`add x0, x0, #1` could be called in a loop with an attacker-controlled number
of iterations, making it technically possible for an attacker to replace a
valid pointer with a pointer to an arbitrary address.

#### Tail call detection

`ptrauth-tail-calls` detector uses a heuristic to guess which branch instructions
(both direct and indirect) correspond to performing tail calls, as opposed to
other kinds of control flow.

Most other parts of BOLT should not break code when rewriting. Unlike them,
this analyzer tries to keep reasonable balance between false positive reports
and missed issues. For this reason, it inspects some other branch instructions
in addition to those BOLT is sure about.

While it should provide reasonable balance between false positives and false
negatives on general code, this may not be the case for some specific patterns.
An example of a generally uncommon code pattern that is likely to yield false
positives is [labels-as-values GCC extension](https://gcc.gnu.org/onlinedocs/gcc/Labels-as-Values.html)
which is also supported by Clang.

#### Other known issues

* No lightweight variant of [`ptrauth-tail-calls`](#return-address-protection-before-tail-call-ptrauth-tail-calls),
  see issue [#186204](https://github.com/llvm/llvm-project/issues/186204)
  for the details.
* Not handling "no-return" functions. See issue
  [#115154](https://github.com/llvm/llvm-project/issues/115154) for details and
  pointers to open PRs to fix this.
* Scanning of binaries compiled by Clang at `-Oz` optimization level produces a
  lot of reports due to outlining. Many such reports could probably be considered
  false negatives as long as an attacker is unable to call `OUTLINED_FUNCTION`s
  as ROP gadgets in the first place.
* False positives are possible due to multi-instruction pointer-checking sequences
  not being detected without CFG.
* While obviously "checking" the result of pointer authentication, store
  instructions do not transition their address operand register from safe-to-
  dereference to trusted state yet. This does not affect scanning regular code
  hardened neither by `pac-ret`, nor by `arm64e` or `pauthtest`.

## How to add your own analysis

### Pointer Authentication validator

To implement the detection of a new gadget kind, add new
`shouldReport*Gadget` function to `bolt/lib/Passes/PAuthGadgetScanner.cpp` and
call it either from `FunctionAnalysisContext::findUnsafeUses` or
`FunctionAnalysisContext::findUnsafeDefs`.

To improve overall analysis quality by better computing register properties,
either modify one of `*SafetyAnalysis` classes in `PAuthGadgetScanner.cpp`
(if the improvement is target-neutral), or one of target-specific hooks in
the subclass of `MCPlusBuilder` corresponding to your target (if an analysis of
target-specific instruction patterns is to be improved).

To add support for a new target, if one eventually implements similar pointer
protection technique, implement PtrAuth-related hooks in the subclass of
`MCPlusBuilder` corresponding to your target. Ideally, no changes should be
needed in `PAuthGadgetScanner.cpp`, as it is intended to be reasonably target-
independent, though it is possible that some amount of further generalization
may be required.

### New types of analyses

_TODO: this section needs to be written. Ideally, we should have a simple
"example" or "template" analysis that can be the starting point for implementing
custom analyses_

---

### Bolt Docs CMakeLists (`bolt/docs/CMakeLists.txt`)

if (DOXYGEN_FOUND)
if (LLVM_ENABLE_DOXYGEN)
  set(abs_top_srcdir ${CMAKE_CURRENT_SOURCE_DIR})
  set(abs_top_builddir ${CMAKE_CURRENT_BINARY_DIR})

  if (HAVE_DOT)
    set(DOT ${LLVM_PATH_DOT})
  endif()

  if (LLVM_DOXYGEN_EXTERNAL_SEARCH)
    set(enable_searchengine "YES")
    set(searchengine_url "${LLVM_DOXYGEN_SEARCHENGINE_URL}")
    set(enable_server_based_search "YES")
    set(enable_external_search "YES")
    set(extra_search_mappings "${LLVM_DOXYGEN_SEARCH_MAPPINGS}")
  else()
    set(enable_searchengine "NO")
    set(searchengine_url "")
    set(enable_server_based_search "NO")
    set(enable_external_search "NO")
    set(extra_search_mappings "")
  endif()

  # If asked, configure doxygen for the creation of a Qt Compressed Help file.
  if (LLVM_ENABLE_DOXYGEN_QT_HELP)
    set(BOLT_DOXYGEN_QCH_FILENAME "org.llvm.bolt.qch" CACHE STRING
      "Filename of the Qt Compressed help file")
    set(BOLT_DOXYGEN_QHP_NAMESPACE "org.llvm.bolt" CACHE STRING
      "Namespace under which the intermediate Qt Help Project file lives")
    set(BOLT_DOXYGEN_QHP_CUST_FILTER_NAME "Clang ${BOLT_VERSION}" CACHE STRING
      "See http://qt-project.org/doc/qt-4.8/qthelpproject.html#custom-filters")
    set(BOLT_DOXYGEN_QHP_CUST_FILTER_ATTRS "Clang,${BOLT_VERSION}" CACHE STRING
      "See http://qt-project.org/doc/qt-4.8/qthelpproject.html#filter-attributes")
    set(bolt_doxygen_generate_qhp "YES")
    set(bolt_doxygen_qch_filename "${BOLT_DOXYGEN_QCH_FILENAME}")
    set(bolt_doxygen_qhp_namespace "${BOLT_DOXYGEN_QHP_NAMESPACE}")
    set(bolt_doxygen_qhelpgenerator_path "${LLVM_DOXYGEN_QHELPGENERATOR_PATH}")
    set(bolt_doxygen_qhp_cust_filter_name "${BOLT_DOXYGEN_QHP_CUST_FILTER_NAME}")
    set(bolt_doxygen_qhp_cust_filter_attrs "${BOLT_DOXYGEN_QHP_CUST_FILTER_ATTRS}")
  else()
    set(bolt_doxygen_generate_qhp "NO")
    set(bolt_doxygen_qch_filename "")
    set(bolt_doxygen_qhp_namespace "")
    set(bolt_doxygen_qhelpgenerator_path "")
    set(bolt_doxygen_qhp_cust_filter_name "")
    set(bolt_doxygen_qhp_cust_filter_attrs "")
  endif()

  llvm_configure_doxygen()

  set(abs_top_srcdir)
  set(abs_top_builddir)
  set(DOT)
  set(enable_searchengine)
  set(searchengine_url)
  set(enable_server_based_search)
  set(enable_external_search)
  set(extra_search_mappings)
  set(bolt_doxygen_generate_qhp)
  set(bolt_doxygen_qch_filename)
  set(bolt_doxygen_qhp_namespace)
  set(bolt_doxygen_qhelpgenerator_path)
  set(bolt_doxygen_qhp_cust_filter_name)
  set(bolt_doxygen_qhp_cust_filter_attrs)

  add_custom_target(doxygen-bolt
    COMMAND ${DOXYGEN_EXECUTABLE} ${CMAKE_CURRENT_BINARY_DIR}/doxygen.cfg
    WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
    COMMENT "Generating bolt doxygen documentation." VERBATIM)
  set_target_properties(doxygen-bolt PROPERTIES FOLDER "BOLT/Docs")

  if (LLVM_BUILD_DOCS)
    add_dependencies(doxygen doxygen-bolt)
  endif()

  if (NOT LLVM_INSTALL_TOOLCHAIN_ONLY AND LLVM_BUILD_DOCS)
    install(DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/doxygen/html
      DESTINATION docs/html)
  endif()
endif()
endif()

if (LLVM_ENABLE_SPHINX)
  include(AddSphinxTarget)
  if (SPHINX_FOUND)
    if (${SPHINX_OUTPUT_HTML})
      add_sphinx_target(html bolt)
    endif()
  endif()
endif()

---

### Bolt Docs CommandLineArgumentReference (`bolt/docs/CommandLineArgumentReference.md`)

# BOLT - a post-link optimizer developed to speed up large applications

## SYNOPSIS

`llvm-bolt <executable> [-o outputfile] <executable>.bolt [-data=perf.fdata] [options]`

## OPTIONS

### Generic options:

- `-h`

  Alias for --help

- `--help`

  Display available options (--help-hidden for more)

- `--help-hidden`

  Display all available options

- `--help-list`

  Display list of available options (--help-list-hidden for more)

- `--help-list-hidden`

  Display list of all available options

- `--version`

  Display the version of this program

### Output options:

- `--bolt-info`

  Write bolt info section in the output binary

- `-o <string>`

  output file

- `-w <string>`

  Save recorded profile to a file

### BOLT generic options:

- `--align-text=<uint>`

  Alignment of .text section

- `--allow-stripped`

  Allow processing of stripped binaries

- `--alt-inst-feature-size=<uint>`

  Size of feature field in .altinstructions

- `--alt-inst-has-padlen`

  Specify that .altinstructions has padlen field

- `--asm-dump[=<dump folder>]`

  Dump function into assembly

- `-b`

  Alias for -data

- `--bolt-id=<string>`

  Add any string to tag this execution in the output binary via bolt info section

- `--break-funcs=<func1,func2,func3,...>`

  List of functions to core dump on (debugging)

- `--check-encoding`

  Perform verification of LLVM instruction encoding/decoding. Every instruction
  in the input is decoded and re-encoded. If the resulting bytes do not match
  the input, a warning message is printed.

- `--comp-dir-override=<string>`

  Overrides DW_AT_comp_dir, and provides an alternative base location, which is
  used with DW_AT_dwo_name to construct a path to *.dwo files.

- `--create-debug-names-section`

  Creates .debug_names section, if the input binary doesn't have it already, for
  DWARF5 CU/TUs.

- `--cu-processing-batch-size=<uint>`

  Specifies the size of batches for processing CUs. Higher number has better
  performance, but more memory usage. Default value is 1.

- `--data=<string>`

  data file

- `--data2=<string>`

  data file

- `--debug-skeleton-cu`

  Prints out offsets for abbrev and debug_info of Skeleton CUs that get patched.

- `--debug-thread-count=<uint>`

  Specifies the number of threads to be used when processing DWO debug information.

- `--dot-tooltip-code`

  Add basic block instructions as tool tips on nodes

- `--dump-alt-instructions`

  Dump Linux alternative instructions info

- `--dump-cg=<string>`

  Dump callgraph to the given file

- `--dump-data`

  Dump parsed bolt data for debugging

- `--dump-dot-all`

  Dump function CFGs to graphviz format after each stage;enable '-print-loops'
  for color-coded blocks

- `--dump-dot-func=<func1,func2,func3...>`

  Dump function CFGs to graphviz format for specified functions only;
  takes function name patterns (regex supported). Note: C++ function names
  must be passed using their mangled names

- `--dump-linux-exceptions`

  Dump Linux kernel exception table

- `--dump-orc`

  Dump raw ORC unwind information (sorted)

- `--dump-para-sites`

  Dump Linux kernel paravitual patch sites

- `--dump-pci-fixups`

  Dump Linux kernel PCI fixup table

- `--dump-smp-locks`

  Dump Linux kernel SMP locks

- `--dump-static-calls`

  Dump Linux kernel static calls

- `--dump-static-keys`

  Dump Linux kernel static keys jump table

- `--dwarf-output-path=<string>`

  Path to where .dwo files or dwp file will be written out to.

- `--dwp=<string>`

  Path and name to DWP file.

- `--dyno-stats`

  Print execution info based on profile

- `--dyno-stats-all`

  Print dyno stats after each stage

- `--dyno-stats-scale=<uint>`

  Scale to be applied while reporting dyno stats

- `--enable-bat`

  Write BOLT Address Translation tables

- `--fix-branches-with-liveness`

  Use liveness analysis to decide whether AArch64 branch inversion must
  preserve condition flags

- `--force-data-relocations`

  Force relocations to data sections to always be processed

- `--force-patch`

  Force patching of original entry points

- `--funcs=<func1,func2,func3,...>`

  Limit optimizations to functions from the list

- `--funcs-file=<string>`

  File with list of functions to optimize

- `--funcs-file-no-regex=<string>`

  File with list of functions to optimize (non-regex)

- `--funcs-no-regex=<func1,func2,func3,...>`

  Limit optimizations to functions from the list (non-regex)

- `--hot-data`

  Hot data symbols support (relocation mode)

- `--hot-functions-at-end`

  If reorder-functions is used, order functions putting hottest last

- `--hot-text`

  Generate hot text symbols. Apply this option to a precompiled binary that
  manually calls into hugify, such that at runtime hugify call will put hot code
  into 2M pages. This requires relocation.

- `--hot-text-move-sections=<sec1,sec2,sec3,...>`

  List of sections containing functions used for hugifying hot text. BOLT makes
  sure these functions are not placed on the same page as the hot text.
  (default='.stub,.mover').

- `--insert-retpolines`

  Run retpoline insertion pass

- `--keep-aranges`

  Keep or generate .debug_aranges section if .gdb_index is written

- `--keep-tmp`

  Preserve intermediate .o file

- `--lite`

  Skip processing of cold functions

- `--log-file=<string>`

  Redirect journaling to a file instead of stdout/stderr

- `--long-jump-labels`

  Always use long jumps/nops for Linux kernel static keys

- `--match-profile-with-function-hash`

  Match profile with function hash

- `--max-data-relocations=<uint>`

  Maximum number of data relocations to process

- `--max-funcs=<uint>`

  Maximum number of functions to process

- `--no-huge-pages`

  Use regular size pages for code alignment

- `--no-threads`

  Disable multithreading

- `--pad-funcs=<func1:pad1,func2:pad2,func3:pad3,...>`

  List of functions to pad with amount of bytes

- `--print-mappings`

  Print mappings in the legend, between characters/blocks and text sections
  (default false).


- `--profile-format=<value>`

  Format to dump profile output in aggregation mode, default is fdata
  - `fdata`: offset-based plaintext format
  - `yaml`: dense YAML representation

- `--r11-availability=<value>`

  Determine the availability of r11 before indirect branches
  - `never`: r11 not available
  - `always`: r11 available before calls and jumps
  - `abi`: r11 available before calls but not before jumps

- `--relocs`

  Use relocations in the binary (default=autodetect)

- `--remove-symtab`

  Remove .symtab section

- `--reorder-skip-symbols=<symbol1,symbol2,symbol3,...>`

  List of symbol names that cannot be reordered

- `--reorder-symbols=<symbol1,symbol2,symbol3,...>`

  List of symbol names that can be reordered

- `--retpoline-lfence`

  Determine if lfence instruction should exist in the retpoline

- `--skip-funcs=<func1,func2,func3,...>`

  List of functions to skip

- `--skip-funcs-file=<string>`

  File with list of functions to skip

- `--strict`

  Trust the input to be from a well-formed source

- `--tasks-per-thread=<uint>`

  Number of tasks to be created per thread

- `--terminal-trap`

  Assume that execution stops at trap instruction

- `--thread-count=<uint>`

  Number of threads

- `--top-called-limit=<uint>`

  Maximum number of functions to print in top called functions section

- `--trap-avx512`

  In relocation mode trap upon entry to any function that uses AVX-512
  instructions

- `--trap-old-code`

  Insert traps in old function bodies (relocation mode)

- `--update-debug-sections`

  Update DWARF debug sections of the executable

- `--use-gnu-stack`

  Use GNU_STACK program header for new segment (workaround for issues with
  strip/objcopy)

- `--use-old-text`

  Reuse space in old .text if possible (relocation mode)

- `-v <uint>`

  Set verbosity level for diagnostic output

### BOLT optimization options:

- `--align-blocks`

  Align basic blocks

- `--align-blocks-min-size=<uint>`

  Minimal size of the basic block that should be aligned

- `--align-blocks-threshold=<uint>`

  Align only blocks with frequency larger than containing function execution
  frequency specified in percent. E.g. 1000 means aligning blocks that are 10
  times more frequently executed than the containing function.

- `--align-functions=<uint>`

  Align functions at a given value (relocation mode)

- `--align-functions-max-bytes=<uint>`

  Maximum number of bytes to use to align functions

- `--assume-abi`

  Assume the ABI is never violated

- `--block-alignment=<uint>`

  Boundary to use for alignment of basic blocks

- `--bolt-seed=<uint>`

  Seed for randomization

- `--cg-from-perf-data`

  Use perf data directly when constructing the call graph for stale functions

- `--cg-ignore-recursive-calls`

  Ignore recursive calls when constructing the call graph

- `--cg-use-split-hot-size`

  Use hot/cold data on basic blocks to determine hot sizes for call graph
  functions

- `--cold-threshold=<uint>`

  Tenths of percents of main entry frequency to use as a threshold when
  evaluating whether a basic block is cold (0 means it is only considered cold
  if the block has zero samples). Default: 0

- `--elim-link-veneers`

  Run veneer elimination pass

- `--eliminate-unreachable`

  Eliminate unreachable code

- `--equalize-bb-counts`

  Use same count for BBs that should have equivalent count (used in non-LBR and
  shrink wrapping)

- `--execution-count-threshold=<uint>`

  Perform profiling accuracy-sensitive optimizations only if function execution
  count >= the threshold (default: 0)

- `--fix-block-counts`

  Adjust block counts based on outgoing branch counts

- `--fix-func-counts`

  Adjust function counts based on basic blocks execution count

- `--force-inline=<func1,func2,func3,...>`

  List of functions to always consider for inlining

- `--frame-opt=<value>`

  Optimize stack frame accesses
  - `none`: do not perform frame optimization
  - `hot`: perform FOP on hot functions
  - `all`: perform FOP on all functions

- `--frame-opt-rm-stores`

  Apply additional analysis to remove stores (experimental)

- `--function-order=<string>`

  File containing an ordered list of functions to use for function reordering

- `--generate-function-order=<string>`

  File to dump the ordered list of functions to use for function reordering

- `--generate-link-sections=<string>`

  Generate a list of function sections in a format suitable for inclusion in a
  linker script

- `--group-stubs`

  Share stubs across functions

- `--hugify`

  Automatically put hot code on 2MB page(s) (hugify) at runtime. No manual call
  to hugify is needed in the binary (which is what --hot-text relies on).

- `--icf=<value>`

  Fold functions with identical code
  - `all`:  Enable identical code folding
  - `none`: Disable identical code folding (default)
  - `safe`: Enable safe identical code folding

- `--icp`

  Alias for --indirect-call-promotion

- `--icp-calls-remaining-percent-threshold=<uint>`

  The percentage threshold against remaining unpromoted indirect call count for
  the promotion for calls

- `--icp-calls-topn`

  Alias for --indirect-call-promotion-calls-topn

- `--icp-calls-total-percent-threshold=<uint>`

  The percentage threshold against total count for the promotion for calls

- `--icp-eliminate-loads`

  Enable load elimination using memory profiling data when performing ICP

- `--icp-funcs=<func1,func2,func3,...>`

  List of functions to enable ICP for

- `--icp-inline`

  Only promote call targets eligible for inlining

- `--icp-jt-remaining-percent-threshold=<uint>`

  The percentage threshold against remaining unpromoted indirect call count for
  the promotion for jump tables

- `--icp-jt-targets`

  Alias for --icp-jump-tables-targets

- `--icp-jt-topn`

  Alias for --indirect-call-promotion-jump-tables-topn

- `--icp-jt-total-percent-threshold=<uint>`

  The percentage threshold against total count for the promotion for jump tables

- `--icp-jump-tables-targets`

  For jump tables, optimize indirect jmp targets instead of indices

- `--icp-mp-threshold`

  Alias for --indirect-call-promotion-mispredict-threshold

- `--icp-old-code-sequence`

  Use old code sequence for promoted calls

- `--icp-top-callsites=<uint>`

  Optimize hottest calls until at least this percentage of all indirect calls
  frequency is covered. 0 = all callsites

- `--icp-topn`

  Alias for --indirect-call-promotion-topn

- `--icp-use-mp`

  Alias for --indirect-call-promotion-use-mispredicts

- `--indirect-call-promotion=<value>`

  Indirect call promotion
  - `none`: do not perform indirect call promotion
  - `calls`: perform ICP on indirect calls
  - `jump-tables`: perform ICP on jump tables
  - `all`: perform ICP on calls and jump tables

- `--indirect-call-promotion-calls-topn=<uint>`

  Limit number of targets to consider when doing indirect call promotion on
  calls. 0 = no limit

- `--indirect-call-promotion-jump-tables-topn=<uint>`

  Limit number of targets to consider when doing indirect call promotion on jump
  tables. 0 = no limit

- `--indirect-call-promotion-topn=<uint>`

  Limit number of targets to consider when doing indirect call promotion. 0 = no
  limit

- `--indirect-call-promotion-use-mispredicts`

  Use misprediction frequency for determining whether or not ICP should be
  applied at a callsite.  The -indirect-call-promotion-mispredict-threshold
  value will be used by this heuristic

- `--infer-fall-throughs`

  Infer execution count for fall-through blocks

- `--infer-stale-profile`

  Infer counts from stale profile data.

- `--inline-all`

  Inline all functions

- `--inline-ap`

  Adjust function profile after inlining

- `--inline-limit=<uint>`

  Maximum number of call sites to inline

- `--inline-max-iters=<uint>`

  Maximum number of inline iterations

- `--inline-memcpy`

  Inline memcpy using optimized instruction sequences (X86: 'rep movsb', AArch64: width-optimized register operations)

- `--inline-small-functions`

  Inline functions if increase in size is less than defined by -inline-small-
  functions-bytes

- `--inline-small-functions-bytes=<uint>`

  Max number of bytes for the function to be considered small for inlining
  purposes

- `--instrument`

  Instrument code to generate accurate profile data

- `--iterative-guess`

  In non-LBR mode, guess edge counts using iterative technique

- `--jt-footprint-optimize-for-icache`

  With jt-footprint-reduction, only process PIC jumptables and turn off other
  transformations that increase code size

- `--jt-footprint-reduction`

  Make jump tables size smaller at the cost of using more instructions at jump
  sites

- `--jump-tables=<value>`

  Jump tables support (default=basic)
  - `none`: do not optimize functions with jump tables
  - `basic`: optimize functions with jump tables
  - `move`: move jump tables to a separate section
  - `split`: split jump tables section into hot and cold based on function
  execution frequency
  - `aggressive`: aggressively split jump tables section based on usage of the
  tables

- `--keep-nops`

  Keep no-op instructions. By default they are removed.

- `--lite-threshold-count=<uint>`

  Similar to '-lite-threshold-pct' but specify threshold using absolute function
  call count. I.e. limit processing to functions executed at least the specified
  number of times.

- `--lite-threshold-pct=<uint>`

  Threshold (in percent) for selecting functions to process in lite mode. Higher
  threshold means fewer functions to process. E.g threshold of 90 means only top
  10 percent of functions with profile will be processed.

- `--match-with-call-graph`

  Match functions with call graph

- `--memcpy1-spec=<func1,func2:cs1:cs2,func3:cs1,...>`

  List of functions with call sites for which to specialize memcpy() for size 1

- `--min-branch-clusters`

  Use a modified clustering algorithm geared towards minimizing branches

- `--name-similarity-function-matching-threshold=<uint>`

  Match functions using namespace and edit distance.

- `--no-inline`

  Disable all inlining (overrides other inlining options)

- `--no-scan`

  Do not scan cold functions for external references (may result in slower binary)

- `--peepholes=<value>`

  Enable peephole optimizations
  - `none`: disable peepholes
  - `double-jumps`: remove double jumps when able
  - `tailcall-traps`: insert tail call traps
  - `useless-branches`: remove useless conditional branches
  - `all`: enable all peephole optimizations

- `--plt=<value>`

  Optimize PLT calls (requires linking with -znow on non-x86 architectures)
  - `none`: do not optimize PLT calls
  - `hot`: optimize executed (hot) PLT calls
  - `all`: optimize all PLT calls

- `--preserve-blocks-alignment`

  Try to preserve basic block alignment

- `--profile-ignore-hash`

  Ignore hash while reading function profile

- `--profile-use-dfs`

  Use DFS order for YAML profile

- `--reg-reassign`

  Reassign registers so as to avoid using REX prefixes in hot code

- `--reorder-blocks=<value>`

  Change layout of basic blocks in a function
  - `none`: do not reorder basic blocks
  - `reverse`: layout blocks in reverse order
  - `normal`: perform optimal layout based on profile
  - `branch-predictor`: perform optimal layout prioritizing branch predictions
  - `cache`: perform optimal layout prioritizing I-cache behavior
  - `cache+`: perform layout optimizing I-cache behavior
  - `ext-tsp`: perform layout optimizing I-cache behavior
  - `cluster-shuffle`: perform random layout of clusters

- `--reorder-data=<section1,section2,section3,...>`

  List of sections to reorder

- `--reorder-data-algo=<value>`

  Algorithm used to reorder data sections
  - `count`: sort hot data by read counts
  - `funcs`: sort hot data by hot function usage and count

- `--reorder-data-inplace`

  Reorder data sections in place

- `--reorder-data-max-bytes=<uint>`

  Maximum number of bytes to reorder

- `--reorder-data-max-symbols=<uint>`

  Maximum number of symbols to reorder

- `--reorder-functions=<value>`

  Reorder and cluster functions (works only with relocations)
  - `none`: do not reorder functions
  - `exec-count`: order by execution count
  - `hfsort`: use hfsort algorithm
  - `hfsort+`: use cache-directed sort
  - `cdsort`: use cache-directed sort
  - `pettis-hansen`: use Pettis-Hansen algorithm
  - `random`: reorder functions randomly
  - `user`: use function order specified by -function-order

- `--reorder-functions-use-hot-size`

  Use a function's hot size when doing clustering

- `--report-bad-layout=<uint>`

  Print top <uint> functions with suboptimal code layout on input

- `--report-stale`

  Print the list of functions with stale profile

- `--runtime-hugify-lib=<string>`

  Specify file name of the runtime hugify library

- `--runtime-instrumentation-lib=<string>`

  Specify file name of the runtime instrumentation library

- `--runtime-lib-init-hook=<value>`

  Primary target for hooking runtime library initialization, used in
  fallback order of availability in input binary (entry_point -> init
   -> init_array) (default: entry_point)
  - `entry_point`: use ELF Header Entry Point
  - `init`: use ELF DT_INIT entry
  - `init_array`: use ELF .init_array entry

- `--sctc-mode=<value>`

  Mode for simplify conditional tail calls
  - `always`: always perform sctc
  - `preserve`: only perform sctc when branch direction is preserved
  - `heuristic`: use branch prediction data to control sctc

- `--sequential-disassembly`

  Performs disassembly sequentially

- `--shrink-wrapping-threshold=<uint>`

  Percentage of prologue execution count to use as threshold when evaluating
  whether a block is cold enough to be profitable to move eligible spills there

- `--simplify-conditional-tail-calls`

  Simplify conditional tail calls by removing unnecessary jumps

- `--simplify-rodata-loads`

  Simplify loads from read-only sections by replacing the memory operand with
  the constant found in the corresponding section

- `--split-align-threshold=<uint>`

  When deciding to split a function, apply this alignment while doing the size
  comparison (see -split-threshold). Default value: 2.

- `--split-all-cold`

  Outline as many cold basic blocks as possible

- `--split-eh`

  Split C++ exception handling code

- `--split-functions`

  Split functions into fragments

- `--split-strategy=<value>`

  Strategy used to partition blocks into fragments
  - `profile2`: split each function into a hot and cold fragment using profiling
  information
  - `cdsplit`: split each function into a hot, warm, and cold fragment using
  profiling information
  - `random2`: split each function into a hot and cold fragment at a randomly
  chosen split point (ignoring any available profiling information)
  - `randomN`: split each function into N fragments at a randomly chosen split
  points (ignoring any available profiling information)
  - `all`: split all basic blocks of each function into fragments such that each
  fragment contains exactly a single basic block

- `--split-threshold=<uint>`

  Split function only if its main size is reduced by more than given amount of
  bytes. Default value: 0, i.e. split iff the size is reduced. Note that on some
  architectures the size can increase after splitting.

- `--stale-matching-max-func-size=<uint>`

  The maximum size of a function to consider for inference.

- `--stale-matching-min-matched-block=<uint>`

  Percentage threshold of matched basic blocks at which stale profile inference
  is executed.

- `--stale-threshold=<uint>`

  Maximum percentage of stale functions to tolerate (default: 100)

- `--stoke`

  Turn on the stoke analysis

- `--strip-rep-ret`

  Strip 'repz' prefix from 'repz retq' sequence (on by default)

- `--tail-duplication=<value>`

  Duplicate unconditional branches that cross a cache line
  - `none`: do not apply
  - `aggressive`: aggressive strategy
  - `moderate`: moderate strategy
  - `cache`: cache-aware duplication strategy

- `--tsp-threshold=<uint>`

  Maximum number of hot basic blocks in a function for which to use a precise
  TSP solution while re-ordering basic blocks

- `--use-aggr-reg-reassign`

  Use register liveness analysis to try to find more opportunities for -reg-
  reassign optimization

- `--use-compact-aligner`

  Use compact approach for aligning functions

- `--use-edge-counts`

  Use edge count data when doing clustering

- `--verify-cfg`

  Verify the CFG after every pass

- `--x86-align-branch-boundary-hot-only`

  Only apply branch boundary alignment in hot code

- `--x86-strip-redundant-address-size`

  Remove redundant Address-Size override prefix

### BOLT instrumentation options:

`llvm-bolt <executable> -instrument [-o outputfile] <instrumented-executable>`

- `--conservative-instrumentation`

  Disable instrumentation optimizations that sacrifice profile accuracy (for
  debugging, default: false)

- `--instrument-calls`

  Record profile for inter-function control flow activity (default: true)

- `--instrument-hot-only`

  Only insert instrumentation on hot functions (needs profile, default: false)

- `--instrumentation-binpath=<string>`

  Path to instrumented binary in case if /proc/self/map_files is not accessible
  due to access restriction issues

- `--instrumentation-file=<string>`

  File name where instrumented profile will be saved (default: /tmp/prof.fdata)

- `--instrumentation-file-append-pid`

  Append PID to saved profile file name (default: false)

- `--instrumentation-no-counters-clear`

  Don't clear counters across dumps (use with instrumentation-sleep-time option)

- `--instrumentation-sleep-time=<uint>`

  Interval between profile writes (default: 0 = write only at program end).
  This is useful for service workloads when you want to dump profile every X
  minutes or if you are killing the program and the profile is not being dumped
  at the end.

- `--instrumentation-wait-forks`

  Wait until all forks of instrumented process will finish (use with
  instrumentation-sleep-time option)

### BOLT printing options:

- `--print-aliases`

  Print aliases when printing objects

- `--print-all`

  Print functions after each stage

- `--print-cfg`

  Print functions after CFG construction

- `--print-debug-info`

  Print debug info when printing functions

- `--print-disasm`

  Print function after disassembly

- `--print-dyno-opcode-stats=<uint>`

  Print per instruction opcode dyno stats and the functionnames:BB offsets of
  the nth highest execution counts

- `--print-dyno-stats-only`

  While printing functions output dyno-stats and skip instructions

- `--print-exceptions`

  Print exception handling data

- `--print-globals`

  Print global symbols after disassembly

- `--print-jump-tables`

  Print jump tables

- `--print-loops`

  Print loop related information

- `--print-mem-data`

  Print memory data annotations when printing functions

- `--print-normalized`

  Print functions after CFG is normalized

- `--print-only=<func1,func2,func3,...>`

  List of functions to print

- `--print-orc`

  Print ORC unwind information for instructions

- `--print-profile`

  Print functions after attaching profile

- `--print-profile-stats`

  Print profile quality/bias analysis

- `--print-pseudo-probes=<value>`

  Print pseudo probe info
  - `decode`: decode probes section from binary
  - `address_conversion`: update address2ProbesMap with output block address
  - `encoded_probes`: display the encoded probes in binary section
  - `all`: enable all debugging printout

- `--print-relocations`

  Print relocations when printing functions/objects

- `--print-reordered-data`

  Print section contents after reordering

- `--print-retpoline-insertion`

  Print functions after retpoline insertion pass

- `--print-sdt`

  Print all SDT markers

- `--print-sections`

  Print all registered sections

- `--print-unknown`

  Print names of functions with unknown control flow

- `--time-build`

  Print time spent constructing binary functions

- `--time-rewrite`

  Print time spent in rewriting passes

- `--print-after-branch-fixup`

  Print function after fixing local branches

- `--print-after-jt-footprint-reduction`

  Print function after jt-footprint-reduction pass

- `--print-after-lowering`

  Print function after instruction lowering

- `--print-cache-metrics`

  Calculate and print various metrics for instruction cache

- `--print-clusters`

  Print clusters

- `--print-estimate-edge-counts`

  Print function after edge counts are set for no-LBR profile

- `--print-finalized`

  Print function after CFG is finalized

- `--print-fix-relaxations`

  Print functions after fix relaxations pass

- `--print-fix-riscv-calls`

  Print functions after fix RISCV calls pass

- `--print-fop`

  Print functions after frame optimizer pass

- `--print-function-statistics=<uint>`

  Print statistics about basic block ordering

- `--print-icf`

  Print functions after ICF optimization

- `--print-icp`

  Print functions after indirect call promotion

- `--print-inline`

  Print functions after inlining optimization

- `--print-large-functions`

  Print functions that could not be overwritten due to excessive size

- `--print-longjmp`

  Print functions after longjmp pass

- `--print-optimize-bodyless`

  Print functions after bodyless optimization

- `--print-output-address-range`

  Print output address range for each basic block in the function
  whenBinaryFunction::print is called

- `--print-peepholes`

  Print functions after peephole optimization

- `--print-plt`

  Print functions after PLT optimization

- `--print-regreassign`

  Print functions after regreassign pass

- `--print-reordered`

  Print functions after layout optimization

- `--print-reordered-functions`

  Print functions after clustering

- `--print-sctc`

  Print functions after conditional tail call simplification

- `--print-simplify-rodata-loads`

  Print functions after simplification of RO data loads

- `--print-sorted-by=<value>`

  Print functions sorted by order of dyno stats
  - `executed-forward-branches`: executed forward branches
  - `taken-forward-branches`: taken forward branches
  - `executed-backward-branches`: executed backward branches
  - `taken-backward-branches`: taken backward branches
  - `executed-unconditional-branches`: executed unconditional branches
  - `all-function-calls`: all function calls
  - `indirect-calls`: indirect calls
  - `PLT-calls`: PLT calls
  - `executed-instructions`: executed instructions
  - `executed-load-instructions`: executed load instructions
  - `executed-store-instructions`: executed store instructions
  - `taken-jump-table-branches`: taken jump table branches
  - `taken-unknown-indirect-branches`: taken unknown indirect branches
  - `total-branches`: total branches
  - `taken-branches`: taken branches
  - `non-taken-conditional-branches`: non-taken conditional branches
  - `taken-conditional-branches`: taken conditional branches
  - `all-conditional-branches`: all conditional branches
  - `linker-inserted-veneer-calls`: linker-inserted veneer calls
  - `all`: sorted by all names

- `--print-sorted-by-order=<value>`

  Use ascending or descending order when printing functions ordered by dyno stats

- `--print-split`

  Print functions after code splitting

- `--print-stoke`

  Print functions after stoke analysis

- `--print-uce`

  Print functions after unreachable code elimination

- `--print-veneer-elimination`

  Print functions after veneer elimination pass

- `--time-opts`

  Print time spent in each optimization

- `--print-all-options`

  Print all option values after command line parsing

- `--print-options`

  Print non-default options after command line parsing

---

### Bolt Docs GettingStarted (`bolt/docs/GettingStarted.md`)

# Getting Started with BOLT

## Input Binary Requirements

BOLT operates on X86-64 and AArch64 ELF binaries. At the minimum, the
binaries should have an unstripped symbol table, and, to get maximum
performance gains, they should be linked with relocations
(`--emit-relocs` or `-q` linker flag).

BOLT disassembles functions and reconstructs the control flow graph
(CFG) before it runs optimizations. Since this is a nontrivial task,
especially when indirect branches are present, we rely on certain
heuristics to accomplish it. These heuristics have been tested on a code
generated with Clang and GCC compilers. The main requirement for C/C++
code is not to rely on code layout properties, such as function pointer
deltas. Assembly code can be processed too. Requirements for it include
a clear separation of code and data, with data objects being placed into
data sections/segments. If indirect jumps are used for intra-function
control transfer (e.g., jump tables), the code patterns should be
matching those generated by Clang/GCC.

NOTE: BOLT is currently incompatible with the
`-freorder-blocks-and-partition` compiler option. Since GCC8 enables
this option by default, you have to explicitly disable it by adding
`-fno-reorder-blocks-and-partition` flag if you are compiling with
GCC8 or above.

NOTE2: DWARF v5 is the new debugging format generated by the latest LLVM
and GCC compilers. It offers several benefits over the previous DWARF
v4. Currently, the support for v5 is a work in progress for BOLT. While
you will be able to optimize binaries produced by the latest compilers,
until the support is complete, you will not be able to update the debug
info with `-update-debug-sections`. To temporarily work around the
issue, we recommend compiling binaries with `-gdwarf-4` option that
forces DWARF v4 output.

PIE and .so support has been added recently. Please report bugs if you
encounter any issues.

## Installation

### Docker Image

You can build and use the docker image containing BOLT using our [docker
file](https://github.com/llvm/llvm-project/blob/main/bolt/utils/docker/Dockerfile).
Alternatively, you can build BOLT manually using the steps below.

### Manual Build

BOLT heavily uses LLVM libraries, and by design, it is built as one of
LLVM tools. The build process is not much different from a regular LLVM
build. The following instructions are assuming that you are running
under Linux.

Start with cloning LLVM repo:

```console
> git clone https://github.com/llvm/llvm-project.git
> mkdir build
> cd build
> cmake -G Ninja ../llvm-project/llvm -DLLVM_TARGETS_TO_BUILD="X86;AArch64" -DCMAKE_BUILD_TYPE=Release -DLLVM_ENABLE_ASSERTIONS=ON -DLLVM_ENABLE_PROJECTS="bolt"
> ninja bolt
```

`llvm-bolt` will be available under `bin/`. Add this directory to
your path to ensure the rest of the commands in this tutorial work.

## Optimizing BOLT’s Performance

BOLT runs many internal passes in parallel. If you foresee heavy usage
of BOLT, you can improve the processing time by linking against one of
memory allocation libraries with good support for concurrency. E.g. to
use jemalloc:

```console
> sudo yum install jemalloc-devel
> LD_PRELOAD=/usr/lib64/libjemalloc.so llvm-bolt ....
```

Or if you rather use tcmalloc:

```console
> sudo yum install gperftools-devel
> LD_PRELOAD=/usr/lib64/libtcmalloc_minimal.so llvm-bolt ....
```

## Usage

For a complete practical guide of using BOLT see {doc}`OptimizingClang`.

### Step 0

In order to allow BOLT to re-arrange functions (in addition to
re-arranging code within functions) in your program, it needs a little
help from the linker. Add `--emit-relocs` to the final link step of
your application. You can verify the presence of relocations by checking
for `.rela.text` section in the binary. BOLT will also report if it
detects relocations while processing the binary.

### Step 1: Collect Profile

This step is different for different kinds of executables. If you can
invoke your program to run on a representative input from a command
line, then check **For Applications** section below. If your program
typically runs as a server/service, then skip to **For Services**
section.

The version of `perf` command used for the following steps has to
support `-F brstack` option. We recommend using `perf` version 4.5
or later.

#### For Applications

This assumes you can run your program from a command line with a typical
input. In this case, simply prepend the command line invocation with
`perf`:

```console
$ perf record -e cycles:u -j any,u -o perf.data -- <executable> <args> ...
```

#### For Services

Once you get the service deployed and warmed-up, it is time to collect
perf data with LBR (branch information). The exact perf command to use
will depend on the service. E.g., to collect the data for all processes
running on the server for the next 3 minutes use:

```console
$ perf record -e cycles:u -j any,u -a -o perf.data -- sleep 180
```

Depending on the application, you may need more samples to be included
with your profile. It’s hard to tell upfront what would be a sweet spot
for your application. We recommend the profile to cover 1B instructions
as reported by BOLT `-dyno-stats` option. If you need to increase the
number of samples in the profile, you can either run the `sleep`
command for longer and use `-F<N>` option with `perf` to increase
sampling frequency.

Note that for profile collection we recommend using cycle events and not
`BR_INST_RETIRED.*`. Empirically we found it to produce better
results.

If the collection of a profile with branches is not available, e.g.,
when you run on a VM or on hardware that does not support it, then you
can use only sample events, such as cycles. In this case, the quality of
the profile information would not be as good, and performance gains with
BOLT are expected to be lower.

#### With instrumentation

If perf record is not available to you, you may collect profile by first
instrumenting the binary with BOLT and then running it.

```console
llvm-bolt <executable> -instrument -o <instrumented-executable>
```

After you run instrumented-executable with the desired workload, its
BOLT profile should be ready for you in `/tmp/prof.fdata` and you can
skip **Step 2**.

Run BOLT with the `-help` option and check the category “BOLT
instrumentation options” for a quick reference on instrumentation knobs.

### Step 2: Convert Profile to BOLT Format

NOTE: you can skip this step and feed `perf.data` directly to BOLT
using experimental `-p perf.data` option.

For this step, you will need `perf.data` file collected from the
previous step and a copy of the binary that was running. The binary has
to be either unstripped, or should have a symbol table intact (i.e.,
running `strip -g` is okay).

Make sure `perf` is in your `PATH`, and execute `perf2bolt`:

```console
$ perf2bolt -p perf.data -o perf.fdata <executable>
```

This command will aggregate branch data from `perf.data` and store it
in a format that is both more compact and more resilient to binary
modifications.

If the profile was collected without brstacks, you will need to add `-ba` flag to
the command line above.

### Step 3: Optimize with BOLT

Once you have `perf.fdata` ready, you can use it for optimizations
with BOLT. Assuming your environment is setup to include the right path,
execute `llvm-bolt`:

```console
$ llvm-bolt <executable> -o <executable>.bolt -data=perf.fdata -reorder-blocks=ext-tsp -reorder-functions=hfsort -split-functions -split-all-cold -split-eh -dyno-stats
```

If you do need an updated debug info, then add
`-update-debug-sections` option to the command above. The processing
time will be slightly longer.

For a full list of options see `-help`/`-help-hidden` output.

The input binary for this step does not have to 100% match the binary
used for profile collection in **Step 1**. This could happen when you
are doing active development, and the source code constantly changes,
yet you want to benefit from profile-guided optimizations. However,
since the binary is not precisely the same, the profile information
could become invalid or stale, and BOLT will report the number of
functions with a stale profile. The higher the number, the less
performance improvement should be expected. Thus, it is crucial to
update `.fdata` for release branches.

## Multiple Profiles

Suppose your application can run in different modes, and you can
generate multiple profiles for each one of them. To generate a single
binary that can benefit all modes (assuming the profiles don’t
contradict each other) you can use `merge-fdata` tool:

```console
$ merge-fdata *.fdata > combined.fdata
```

Use `combined.fdata` for **Step 3** above to generate a universally
optimized binary.

## Profile Formats

See {doc}`profiles` for comprehensive documentation of all profile formats
accepted by BOLT: perf.data, fdata, YAML, and pre-aggregated.

## License

BOLT is licensed under the [Apache License v2.0 with LLVM
Exceptions](https://github.com/llvm/llvm-project/blob/main/LICENSE.TXT).

---

### Bolt Docs Heatmaps (`bolt/docs/Heatmaps.md`)

# Code Heatmaps

BOLT has gained the ability to print code heatmaps based on
sampling-based profiles generated by `perf`, either with `brstack` data or not.
The output is produced in colored ASCII to be displayed in a color-capable
terminal. It looks something like this:



Heatmaps can be generated for BOLTed and non-BOLTed binaries. You can
use them to compare the code layout before and after optimizations.

To generate a heatmap, start with running your app under `perf`:

```bash
$ perf record -e cycles:u -j any,u -- <executable with args>
```
or if you want to monitor the existing process(es):
```bash
$ perf record -e cycles:u -j any,u [-p PID|-a] -- sleep <interval>
```

Running with brstack (`-j any,u` or `-b`) is recommended. Heatmaps can be generated
from basic events by using the llvm-bolt-heatmap option `-ba` (basic events) but
such heatmaps do not have the coverage provided by brstack and may only be useful
for finding event hotspots at larger code block granularities.

Once the run is complete, and `perf.data` is generated, run llvm-bolt-heatmap:

```bash
$ llvm-bolt-heatmap -p perf.data <executable>
```

By default the heatmap will be dumped to *stdout*. You can change it
with `-o <heatmapfile>` option.


If you prefer to look at the data in a browser (or would like to share
it that way), then you can use an HTML conversion tool. E.g.:

```bash
$ aha -b -f <heatmapfile> > <heatmapfile>.html
```

---

## Background on heatmaps:
A heatmap is effectively a histogram that is rendered into a grid for better
visualization.
In theory we can generate a heatmap using any binary and a perf profile.

Each block/character in the heatmap shows the execution data accumulated for
corresponding 64 bytes of code. You can change this granularity with a
`-block-size` option.
E.g. set it to 4096 to see code usage grouped by 4K pages.


When a block is shown as a dot, it means that no samples were found for that
address.
When it is shown as a letter, it indicates a captured sample on a particular
text section of the binary.
To show a mapping between letters and text sections in the legend, use
`-print-mappings`.
When a sampled address does not belong to any of the text sections, the
characters 'o' or 'O' will be shown.

The legend shows by default the ranges in the heatmap according to the number
of samples per block.
A color is assigned per range, except the first two ranges that distinguished by
lower and upper case letters.

On the Y axis, each row/line starts with an actual address of the binary.
Consecutive lines in the heatmap advance by the same amount, with the binary
size covered by a line dependent on the block size and the line size.
An empty new line is inserted for larger gaps between samples.

On the X axis, the horizontally emitted hex numbers can help *estimate* where
in the line the samples lie, but they cannot be combined to provide a full
address, as they are relative to both the bucket and line sizes.

In the example below, the highlighted `0x100` column is not an offset to each
row's address, but instead, it points to the middle of the line.
For the generation, the default bucket size was used with a line size of 128.





Some useful options are:

```
-line-size=<uint>   - number of entries per line (default 256).
                      Use a smaller value (e.g. 128) if the heatmap doesn't fit
                      the screen horizontally.
-block-size=<initial size>[,<zoom-out size>,...] - heatmap bucket size,
                      optionally followed by zoom-out sizes to produce coarse-
                      grained heatmaps. Size can be specified in human-readable
                      format with [kKmMgG][i][B] suffix. Default 64B, 4K, 256K.
-max-address=<uint> - maximum address considered valid for heatmap (default 4GB)
-print-mappings     - print mappings in the legend, between characters/blocks and text sections (default false)
```

---

### Bolt Docs NewBackend (`bolt/docs/NewBackend.md`)

# Adding a New BOLT Backend

A new BOLT backend should follow LLVM's
[policy for adding a new target](https://llvm.org/docs/DeveloperPolicy.html#adding-a-new-target).
New BOLT targets are experimental and are not built by default.

Most target-specific work should be isolated in an `MCPlusBuilder`
implementation under `bolt/lib/Target/<Target>`, together with
platform-specific relocation handling in `bolt/lib/Core/Relocation.cpp`.

Changes to common infrastructure, particularly `MCPlusBuilder`, must be
separate from the target changes and land first. Such changes require thorough
tests and must state their processing-time and peak-memory impact on existing
targets. Measurements should use large binaries, including at least Clang
itself.

A backend does not need to implement every `MCPlusBuilder` interface initially.
However, omitted interfaces must be checked against their callers. Analyses and
passes that depend on missing functionality, such as stack frame analysis or
register liveness, must remain disabled.

BOLT passes are not cleanly partitioned into common and target-specific code.
Enable them for a new target only after auditing their target assumptions and
proving them stable with target-specific and end-to-end tests. Otherwise, keep
them disabled.

RISC targets generally need the `LongJmp` pass for branch relaxation. This
requires correct branch-range checks and short- and long-jump construction,
with tests covering range boundaries, calls, tail calls, and linker relaxation.

The initial backend should include focused tests for instruction analysis,
relocations, CFG construction, rewriting, and each enabled pass. Validation
must include rewriting and executing large real-world binaries, with Clang as
the minimum large-binary test.

---

### Bolt Docs OptimizingClang (`bolt/docs/OptimizingClang.md`)

# Optimizing Clang : A Practical Example of Applying BOLT

## Preface

*BOLT* (Binary Optimization and Layout Tool) is designed to improve the application
performance by laying out code in a manner that helps CPU better utilize its caching and
branch predicting resources.

The most obvious candidates for BOLT optimizations
are programs that suffer from many instruction cache and iTLB misses, such as
large applications measuring over hundreds of megabytes in size. However, medium-sized
programs can benefit too. Clang, one of the most popular open-source C/C++ compilers,
is a good example of the latter. Its code size could easily be in the order of tens of megabytes.
As we will see, the Clang binary suffers from many instruction cache
misses and can be significantly improved with BOLT, even on top of profile-guided and
link-time optimizations.

In this tutorial we will first build Clang with PGO and LTO, and then will show steps on how to
apply BOLT optimizations to make Clang up to 15% faster. We will also analyze where
the compile-time performance gains are coming from, and verify that the speed-ups are
sustainable while building other applications.

## Building Clang

The process of getting Clang sources and performing the build is very similar to the
one described at http://clang.llvm.org/get_started.html. For completeness, we provide the detailed steps
on how to obtain and build Clang in [Bootstrapping Clang-7 with PGO and LTO](#bootstrapping-clang-7-with-pgo-and-lto) section.

The only difference from the standard Clang build is that we require the `-Wl,-q` flag to be present during
the final link. This option saves relocation metadata in the executable file, but does not affect
the generated code in any way.

## Optimizing Clang with BOLT

We will use the setup described in [Bootstrapping Clang-7 with PGO and LTO](#bootstrapping-clang-7-with-pgo-and-lto).
Adjust the steps accordingly if you skipped that section. We will also assume that `llvm-bolt` is present in your `$PATH`.

Before we can run BOLT optimizations, we need to collect the profile for Clang, and we will use
Clang/LLVM sources for that.
Collecting accurate profile requires running `perf` on a hardware that
implements taken branch sampling (`-b/-j` flag). For that reason, it may not be possible to
collect the accurate profile in a virtualized environment, e.g. in the cloud.
We do support regular sampling profiles, but the performance
improvements are expected to be more modest.

```bash
$ mkdir ${TOPLEV}/stage3
$ cd ${TOPLEV}/stage3
$ CPATH=${TOPLEV}/stage2-prof-use-lto/install/bin/
$ cmake -G Ninja ${TOPLEV}/llvm -DLLVM_TARGETS_TO_BUILD=X86 -DCMAKE_BUILD_TYPE=Release \
    -DCMAKE_C_COMPILER=$CPATH/clang -DCMAKE_CXX_COMPILER=$CPATH/clang++ \
    -DLLVM_ENABLE_PROJECTS="clang" \
    -DLLVM_USE_LINKER=lld -DCMAKE_INSTALL_PREFIX=${TOPLEV}/stage3/install
$ perf record -e cycles:u -j any,u -- ninja clang
```

Once the last command is finished, it will create a `perf.data` file larger than 10GiB.
We will first convert this profile into a more compact aggregated
form suitable to be consumed by BOLT:
```bash
  $ perf2bolt $CPATH/clang-7 -p perf.data -o clang-7.fdata -w clang-7.yaml
```
Notice that we are passing `clang-7` to `perf2bolt` which is the real binary that
`clang` and `clang++` are symlinking to. The next step will optimize Clang using
the generated profile:
```bash
$ llvm-bolt $CPATH/clang-7 -o $CPATH/clang-7.bolt -b clang-7.yaml \
    -reorder-blocks=ext-tsp -reorder-functions=hfsort+ -split-functions \
    -split-all-cold -dyno-stats -icf=1 -use-gnu-stack
```
The output will look similar to the one below:
```text
...
BOLT-INFO: enabling relocation mode
BOLT-INFO: 11415 functions out of 104526 simple functions (10.9%) have non-empty execution profile.
...
BOLT-INFO: ICF folded 29144 out of 105177 functions in 8 passes. 82 functions had jump tables.
BOLT-INFO: Removing all identical functions will save 5466.69 KB of code space. Folded functions were called 2131985 times based on profile.
BOLT-INFO: basic block reordering modified layout of 7848 (10.32%) functions
...
           660155947 : executed forward branches (-2.3%)
            48252553 : taken forward branches (-57.2%)
           129897961 : executed backward branches (+13.8%)
            52389551 : taken backward branches (-19.5%)
            35650038 : executed unconditional branches (-33.2%)
           128338874 : all function calls (=)
            19010563 : indirect calls (=)
             9918250 : PLT calls (=)
          6113398840 : executed instructions (-0.6%)
          1519537463 : executed load instructions (=)
           943321306 : executed store instructions (=)
            20467109 : taken jump table branches (=)
           825703946 : total branches (-2.1%)
           136292142 : taken branches (-41.1%)
           689411804 : non-taken conditional branches (+12.6%)
           100642104 : taken conditional branches (-43.4%)
           790053908 : all conditional branches (=)
...
```
The statistics in the output is based on the brstack profile (LBR) collected with `perf`, and since we were using
the `cycles` counter, its accuracy is affected. However, the relative improvement in `taken conditional
 branches` is a good indication that BOLT was able to straighten out the code even after PGO.

## Measuring Compile-time Improvement

`clang-7.bolt` can be used as a replacement for *PGO+LTO* Clang:
```bash
$ mv $CPATH/clang-7 $CPATH/clang-7.org
$ ln -fs $CPATH/clang-7.bolt $CPATH/clang-7
```
Doing a new build of Clang using the new binary shows a significant overall
build time reduction on a 48-core Haswell system:
```bash
$ ln -fs $CPATH/clang-7.org $CPATH/clang-7
$ ninja clean && /bin/time -f %e ninja clang -j48
202.72
$ ln -fs $CPATH/clang-7.bolt $CPATH/clang-7
$ ninja clean && /bin/time -f %e ninja clang -j48
180.11
```
That's 22.61 seconds (or 12%) faster compared to the *PGO+LTO* build.
Notice that we are measuring an improvement of the total build time, which includes the time spent in the linker.
Compilation time improvements for individual files differ, and speedups over 15% are not uncommon.
If we run BOLT on a Clang binary compiled without *PGO+LTO* (in which case the build is finished in 253.32 seconds),
the gains we see are over 50 seconds (25%),
but, as expected, the result is still slower than *PGO+LTO+BOLT* build.

## Source of the Wins

We mentioned that Clang suffers from considerable instruction cache misses. This can be measured with `perf`:
```bash
$ ln -fs $CPATH/clang-7.org $CPATH/clang-7
$ ninja clean && perf stat -e instructions,L1-icache-misses -- ninja clang -j48
  ...
   16,366,101,626,647      instructions
      359,996,216,537      L1-icache-misses
```
That's about 22 instruction cache misses per thousand instructions. As a rule of thumb, if the application
has over 10 misses per thousand instructions, it is a good indication that it will be improved by BOLT.
Now let's see how many misses are in the BOLTed binary:
```bash
$ ln -fs $CPATH/clang-7.bolt $CPATH/clang-7
$ ninja clean && perf stat -e instructions,L1-icache-misses -- ninja clang -j48
  ...
  16,319,818,488,769      instructions
     244,888,677,972      L1-icache-misses
```
The number of misses per thousand instructions went down from 22 to 15, significantly reducing
the number of stalls in the CPU front-end.
Notice how the number of executed instructions stayed roughly the same. That's because we didn't
run any optimizations beyond the ones affecting the code layout. Other than instruction cache misses,
BOLT also improves branch mispredictions, iTLB misses, and misses in L2 and L3.

## Using Clang for Other Applications

We have collected profile for Clang using its own source code. Would it be enough to speed up
the compilation of other projects? We picked `mysqld`, an open-source database, to do the test.

On our 48-core Haswell system using the *PGO+LTO* Clang, the build finished in 136.06 seconds, while using the *PGO+LTO+BOLT* Clang, 126.10 seconds.
That's a noticeable improvement, but not as significant as the one we saw on Clang itself.
This is partially because the number of instruction cache misses is slightly lower on this scenario : 19 vs 22.
Another reason is that Clang is run with a different set of options while building `mysqld` compared
to the training run.

Different options exercise different code paths, and
if we trained without a specific option, we may have misplaced parts of the code responsible for handling it.
To test this theory, we have collected another `perf` profile while building `mysqld`, and merged it with an existing profile
using the `merge-fdata` utility that comes with BOLT. Optimized with that profile, the *PGO+LTO+BOLT* Clang was able
to perform the `mysqld` build in 124.74 seconds, i.e. 11 seconds or 9% faster compared to *PGO+LGO* Clang.
The merged profile didn't make the original Clang compilation slower either, while the number of profiled functions in Clang increased from 11,415 to 14,025.

Ideally, the profile run has to be done with a superset of all commonly used options. However, the main improvement is expected with just the basic set.

## Summary

In this tutorial we demonstrated how to use BOLT to improve the
performance of the Clang compiler. Similarly, BOLT could be used to improve the performance
of GCC, or any other application suffering from a high number of instruction
cache misses.

----
# Appendix

## Bootstrapping Clang-7 with PGO and LTO

Below we describe detailed steps to build Clang, and make it ready for BOLT
optimizations. If you already have the build setup, you can skip this section,
except for the last step that adds `-Wl,-q` linker flag to the final build.

### Getting Clang-7 Sources

Set `$TOPLEV` to the directory of your preference where you would like to do
builds. E.g. `TOPLEV=~/clang-7/`. Follow with commands to clone the `release_70`
branch of LLVM monorepo:
```bash
$ mkdir ${TOPLEV}
$ cd ${TOPLEV}
$ git clone --branch=release/7.x https://github.com/llvm/llvm-project.git
```

### Building Stage 1 Compiler

Stage 1 will be the first build we are going to do, and we will be using the
default system compiler to build Clang. If your system lacks a compiler, use
your distribution package manager to install one that supports C++11. In this
example we are going to use GCC. In addition to the compiler, you will need the
`cmake` and `ninja` packages. Note that we disable the build of certain
compiler-rt components that are known to cause build issues at release/7.x.
```bash
$ mkdir ${TOPLEV}/stage1
$ cd ${TOPLEV}/stage1
$ cmake -G Ninja ${TOPLEV}/llvm-project/llvm -DLLVM_TARGETS_TO_BUILD=X86 \
      -DCMAKE_BUILD_TYPE=Release \
      -DCMAKE_C_COMPILER=gcc -DCMAKE_CXX_COMPILER=g++ -DCMAKE_ASM_COMPILER=gcc \
      -DLLVM_ENABLE_PROJECTS="clang;lld" \
      -DLLVM_ENABLE_RUNTIMES="compiler-rt" \
      -DCOMPILER_RT_BUILD_SANITIZERS=OFF -DCOMPILER_RT_BUILD_XRAY=OFF \
      -DCOMPILER_RT_BUILD_LIBFUZZER=OFF \
      -DCMAKE_INSTALL_PREFIX=${TOPLEV}/stage1/install
$ ninja install
```

### Building Stage 2 Compiler With Instrumentation

Using the freshly-baked stage 1 Clang compiler, we are going to build Clang with
profile generation capabilities:
```bash
$ mkdir ${TOPLEV}/stage2-prof-gen
$ cd ${TOPLEV}/stage2-prof-gen
$ CPATH=${TOPLEV}/stage1/install/bin/
$ cmake -G Ninja ${TOPLEV}/llvm-project/llvm -DLLVM_TARGETS_TO_BUILD=X86 \
    -DCMAKE_BUILD_TYPE=Release \
    -DCMAKE_C_COMPILER=$CPATH/clang -DCMAKE_CXX_COMPILER=$CPATH/clang++ \
    -DLLVM_ENABLE_PROJECTS="clang;lld" \
    -DLLVM_USE_LINKER=lld -DLLVM_BUILD_INSTRUMENTED=ON \
    -DCMAKE_INSTALL_PREFIX=${TOPLEV}/stage2-prof-gen/install
$ ninja install
```

### Generating Profile for PGO

While there are many ways to obtain the profile data, we are going to use the
source code already at our disposal, i.e. we are going to collect the profile
while building Clang itself:
```bash
$ mkdir ${TOPLEV}/stage3-train
$ cd ${TOPLEV}/stage3-train
$ CPATH=${TOPLEV}/stage2-prof-gen/install/bin
$ cmake -G Ninja ${TOPLEV}/llvm-project/llvm -DLLVM_TARGETS_TO_BUILD=X86 \
    -DCMAKE_BUILD_TYPE=Release \
    -DCMAKE_C_COMPILER=$CPATH/clang -DCMAKE_CXX_COMPILER=$CPATH/clang++ \
    -DLLVM_ENABLE_PROJECTS="clang" \
    -DLLVM_USE_LINKER=lld -DCMAKE_INSTALL_PREFIX=${TOPLEV}/stage3-train/install
$ ninja clang
```
Once the build is completed, the profile files will be saved under
`${TOPLEV}/stage2-prof-gen/profiles`. We will merge them before they can be
passed back into Clang:
```bash
$ cd ${TOPLEV}/stage2-prof-gen/profiles
$ ${TOPLEV}/stage1/install/bin/llvm-profdata merge -output=clang.profdata *
```

### Building Clang with PGO and LTO

Now the profile can be used to guide optimizations to produce better code for
our scenario, i.e. building Clang. We will also enable link-time optimizations
to allow cross-module inlining and other optimizations. Finally, we are going to
add one extra step that is useful for BOLT: a linker flag instructing it to
preserve relocations in the output binary. Note that this flag does not affect
the generated code or data used at runtime, it only writes metadata to the file
on disk:
```bash
$ mkdir ${TOPLEV}/stage2-prof-use-lto
$ cd ${TOPLEV}/stage2-prof-use-lto
$ CPATH=${TOPLEV}/stage1/install/bin/
$ export LDFLAGS="-Wl,-q"
$ cmake -G Ninja ${TOPLEV}/llvm-project/llvm -DLLVM_TARGETS_TO_BUILD=X86 \
    -DCMAKE_BUILD_TYPE=Release \
    -DCMAKE_C_COMPILER=$CPATH/clang -DCMAKE_CXX_COMPILER=$CPATH/clang++ \
    -DLLVM_ENABLE_PROJECTS="clang;lld" \
    -DLLVM_ENABLE_LTO=Full \
    -DLLVM_PROFDATA_FILE=${TOPLEV}/stage2-prof-gen/profiles/clang.profdata \
    -DLLVM_USE_LINKER=lld \
    -DCMAKE_INSTALL_PREFIX=${TOPLEV}/stage2-prof-use-lto/install
$ ninja install
```
Now we have a Clang compiler that can build itself much faster. As we will see,
it builds other applications faster as well, and, with BOLT, the compile time
can be improved even further.

---

### Bolt Docs OptimizingLinux (`bolt/docs/OptimizingLinux.md`)

# Optimizing Linux Kernel with BOLT


## Introduction

Many Linux applications spend a significant amount of their execution time in the kernel. Thus, when we consider code optimization for system performance, it is essential to improve the CPU utilization not only in the user-space applications and libraries but also in the kernel. BOLT has demonstrated double-digit gains while being applied to user-space programs. This guide shows how to apply BOLT to the x86-64 Linux kernel and enhance your system's performance. In our experiments, BOLT boosted database TPS by 2 percent when applied to the kernel compiled with the highest level optimizations, including PGO and LTO. The database spent ~40% of the time in the kernel and was quite sensitive to kernel performance.

BOLT optimizes code layout based on a low-level execution profile collected with the Linux `perf` tool. The best quality profile should include branch history (brstack), such as Intel's last branch records (LBR) or AArch64's Branch Record Buffer Extension (BRBE). BOLT runs on a linked binary and reorders the code while combining frequently executed blocks of instructions in a manner best suited for the hardware. Other than branch instructions, most of the code is left unchanged. Additionally, BOLT updates all metadata associated with the modified code, including DWARF debug information and Linux ORC unwind information.

While BOLT optimizations are not specific to the Linux kernel, certain quirks distinguish the kernel from user-level applications.

BOLT has been successfully applied to and tested with several flavors of the x86-64 Linux kernel.


## QuickStart Guide

BOLT operates on a statically-linked kernel executable, a.k.a. `vmlinux` binary. However, most Linux distributions use a `vmlinuz` compressed image for system booting. To use BOLT on the kernel, you must either repackage `vmlinuz` after BOLT optimizations or add steps for running BOLT into the kernel build and rebuild `vmlinuz`. Uncompressing `vmlinuz` and repackaging it with a new `vmlinux` binary falls beyond the scope of this guide, and at some point, we may add the capability to run BOLT directly on `vmlinuz`. Meanwhile, this guide focuses on steps for integrating BOLT into the kernel build process.


### Building the Kernel

After downloading the kernel sources and configuration for your distribution, you should be able to build `vmlinuz` using the `make bzImage` command. Ideally, the kernel should binary match the kernel on the system you are about to optimize (the target system). The binary matching part is critical as BOLT performs profile matching and optimizations at the binary level. We recommend installing a freshly built kernel on the target system to avoid any discrepancies.

Note that the kernel build will produce several artifacts besides bzImage. The most important of them is the uncompressed `vmlinux` binary, which will be used in the next steps. Make sure to save this file.

Build and target systems should have a `perf` tool installed for collecting and processing profiles. If your build system differs from the target, make sure `perf` versions are compatible. The build system should also have the latest BOLT binary and tools (`llvm-bolt`, `perf2bolt`).

Once the target system boots with the freshly-built kernel, start your workload, such as a database benchmark. While the system is under load, collect the kernel profile using perf:


```bash
$ sudo perf record -a -e cycles -j any,k -F 5000 -- sleep 600
```


Convert `perf` profile into a format suitable for BOLT passing the `vmlinux` binary to `perf2bolt`:


```bash
$ sudo chown $USER perf.data
$ perf2bolt -p perf.data -o perf.fdata vmlinux
```


Under a high load, `perf.data` should be several gigabytes in size and you should expect the converted `perf.fdata` not to exceed 100 MB.

Profiles collected from multiple workloads could be joined into a single profile using `merge-fdata` utility:
```bash
$ merge-fdata perf.1.fdata perf.2.fdata ... perf.<N>.fdata > perf.merged.fdata
```

Two changes are required for the kernel build. The first one is optional but highly recommended. It introduces a BOLT-reserved space into `vmlinux` code section:


```diff
--- a/arch/x86/kernel/vmlinux.lds.S
+++ b/arch/x86/kernel/vmlinux.lds.S
@@ -139,6 +139,11 @@ SECTIONS
                STATIC_CALL_TEXT
                *(.gnu.warning)

+    /* Allocate space for BOLT */
+    __bolt_reserved_start = .;
+               . += 2048 * 1024;
+    __bolt_reserved_end = .;
+
 #ifdef CONFIG_RETPOLINE
                __indirect_thunk_start = .;
                *(.text.__x86.*)
```


The second patch adds a step that runs BOLT on `vmlinux` binary:


```diff
--- a/scripts/link-vmlinux.sh
+++ b/scripts/link-vmlinux.sh
@@ -340,5 +340,13 @@ if is_enabled CONFIG_KALLSYMS; then
        fi
 fi

+# Apply BOLT
+BOLT=llvm-bolt
+BOLT_PROFILE=perf.fdata
+BOLT_OPTS="--dyno-stats --eliminate-unreachable=0 --reorder-blocks=ext-tsp --simplify-conditional-tail-calls=0 --skip-funcs=__entry_text_start,irq_entries_start --split-functions"
+mv vmlinux vmlinux.pre-bolt
+echo BOLTing vmlinux
+${BOLT} vmlinux.pre-bolt -o vmlinux --data ${BOLT_PROFILE} ${BOLT_OPTS}
+
 # For fixdep
 echo "vmlinux: $0" > .vmlinux.d
```


If you skipped the first step or are running BOLT on a pre-built `vmlinux` binary, drop the `--split-functions` option.


## Performance Expectations

By improving the code layout, BOLT can boost the kernel's performance by up to 5% by reducing instruction cache misses and branch mispredictions. When measuring total system performance, you should scale this number accordingly based on the time your application spends in the kernel (excluding I/O time).


## Profile Quality

The timing and duration of the profiling may have a significant effect on the performance of the BOLTed kernel. If you don't know your workload well, it's recommended that you profile for the whole duration of the benchmark run. As longer times will result in larger `perf.data` files, you can lower the profiling frequency by providing a smaller value of `-F` flag. E.g., to record the kernel profile for half an hour, use the following command:


```bash
$ sudo perf record -a -e cycles -j any,k -F 1000 -- sleep 1800
```



## BOLT Disassembly

BOLT annotates the disassembly with control-flow information and attaches Linux-specific metadata to the code. To view annotated disassembly, run:


```bash
$ llvm-bolt vmlinux -o /dev/null --print-cfg
```


If you want to limit the disassembly to a set of functions, add `--print-only=<func1regex>,<func2regex>,...`, where a function name is specified using regular expressions.

---

### Bolt Docs PointerAuthDesign (`bolt/docs/PointerAuthDesign.md`)

# Optimizing binaries with pac-ret hardening

This is a design document about processing the `DW_CFA_AARCH64_negate_ra_state`
DWARF instruction in BOLT. As it describes internal design decisions, the
intended audience is BOLT developers. The document is an updated version of the
[RFC posted on the LLVM Discourse](https://discourse.llvm.org/t/rfc-bolt-aarch64-handle-opnegaterastate-to-enable-optimizing-binaries-with-pac-ret-hardening/86594).


`DW_CFA_AARCH64_negate_ra_state` is also referred to as  `.cfi_negate_ra_state`
in assembly, or `OpNegateRAState` in BOLT sources. In this document, I will use
**negate-ra-state** as a shorthand.

Note: there are two resolutions for CFI:
- Call Frame Instruction: individual DWARF instruction, e.g. negate-ra-state
- Control Flow Integrity: a security mechanism, e.g. pointer authentication.

## Introduction

### Pointer Authentication

For more information, see the [pac-ret section of the BOLT-binary-analysis document](BinaryAnalysis.md#return-address-protection-ptrauth-pac-ret).

### DW_CFA_AARCH64_negate_ra_state

The negate-ra-state CFI is a vendor-specific Call Frame Instruction defined in
the [Arm ABI](https://github.com/ARM-software/abi-aa/blob/main/aadwarf64/aadwarf64.rst#id1).

```
The DW_CFA_AARCH64_negate_ra_state operation negates bit[0] of the RA_SIGN_STATE pseudo-register.
```

This bit indicates to the unwinder whether the current return address is signed
or not (hence the name). The unwinder uses this information to authenticate the
pointer, and remove the Pointer Authentication Code (PAC) bits.
Incorrect placement of negate-ra-state CFIs causes the unwinder to either attempt
to authenticate an unsigned pointer (resulting in a segmentation fault), or skip
authentication on a signed pointer, which can also cause a fault.

Note: some unwinders use the `xpac` instruction to strip the PAC bits without
authenticating the pointer. This is an incorrect (incomplete) implementation,
as it allows control-flow modification in the case of unwinding.

There are no DWARF instructions to directly set or clear the RA State. However,
two other CFIs can also affect the RA state:
- `DW_CFA_remember_state`: this CFI stores register rules onto an implicit stack.
- `DW_CFA_restore_state`:  this CFI pops rules from this stack.

Example:

| CFI                            | Effect on RA state             |
| ------------------------------ | ------------------------------ |
| (default)                      | 0                              |
| DW_CFA_AARCH64_negate_ra_state | 0 -> 1                         |
| DW_CFA_remember_state          | 1 pushed to the stack          |
| DW_CFA_AARCH64_negate_ra_state | 1 -> 0                         |
| DW_CFA_restore_state           | 0 -> 1 (popped from the stack) |

The Arm ABI also defines the DW_CFA_AARCH64_negate_ra_state_with_pc CFI, but it
is not widely used, and is [likely to become deprecated](https://github.com/ARM-software/abi-aa/issues/327).

### Where are these CFIs needed?

Whenever two consecutive instructions have different RA states, the unwinder must
be informed of the change. This typically occurs during pointer signing or
authentication. If adjacent instructions differ in RA state but neither signs
nor authenticates the return address, they must belong to different control flow
paths. One is part of an execution path with signed RA, the other is part of a
path with an unsigned RA.

In the example below, the first BasicBlock ends in a conditional branch, and
jumps to two different BasicBlocks, each with their own authentication, and
return. The instructions on the border of the second and third BasicBlock have
different RA states. The `ret` at the end of the second BasicBlock is in unsigned
state. The start of the third BasicBlock is after the `paciasp` in the control
flow, but before the authentication. In this case, a negate-ra-state is needed
at the end of the second BasicBlock.

```
        +----------------+
        |     paciasp    |
        |                |
        |      b.cc      |
        +--------+-------+
                 |
+----------------+
|                |
|       +--------v-------+
|       |                |
|       |    autiasp     |
|       |      ret       |   // RA: unsigned
|       +----------------+
+----------------+
                 |
        +--------v-------+  // RA: signed
        |                |
        |     autiasp    |
        |      ret       |
        +----------------+
```

> [!important]
> The unwinder does not follow the control flow graph. It reads unwind
> information in the layout order.

Because these locations are dependent on how the function layout looks,
negate-ra-state CFIs will become invalid during BasicBlock reordering.

## Solution design

The implementation introduces two new passes:
1. `PointerAuthCFIAnalyzer`: assigns the RA state to each instruction based on
    the CFIs in the input binary
2. `PointerAuthCFIFixup`: reads those assigned instruction RA states after
    optimizations, and emits `DW_CFA_AARCH64_negate_ra_state` CFIs at the correct
    places: wherever there is a state change between two consecutive instructions
    in the layout order.

To track metadata on individual instructions, the `MCAnnotation` class was
extended. These also have helper functions in `MCPlusBuilder`.

### Saving annotations at CFI reading

CFIs are read and added to BinaryFunctions in `CFIReaderWriter::FillCFIInfoFor`.
At this point, we add MCAnnotations about negate-ra-state, remember-state and
restore-state CFIs to the instructions they refer to. This is to not interfere
with the CFI processing that already happens in BOLT (e.g. remember-state and
restore-state CFIs are removed in `normalizeCFIState` for reasons unrelated to PAC).

As we add the MCAnnotations *to instructions*, we have to account for the case
where the function starts with a CFI altering the RA state. As CFIs modify the RA
state of the instructions before them, we cannot add the annotation to the first
instruction.
This special case is handled by adding an `initialRAState` bool to each BinaryFunction.
If the `Offset` the CFI refers to is zero, we don't store an annotation, but set
the `initialRAState` in `FillCFIInfoFor`. This information is then used in
`PointerAuthCFIAnalyzer`.

### Binaries without DWARF info

In some cases, the DWARF tables are stripped from the binary. These programs
usually have some other unwind-mechanism.
These passes only run on functions that include at least one negate-ra-state CFI.
This avoids processing functions that do not use Pointer Authentication, or on
functions that use Pointer Authentication, but do not have DWARF info.

In summary:
- pointer auth is not used: no change, the new passes do not run.
- pointer auth is used, but DWARF info is stripped: no change, the new passes
  do not run.
- pointer auth is used, and we have DWARF CFIs: passes run, and rewrite the
  negate-ra-state CFI.

### PointerAuthCFIAnalyzer pass

This pass runs before optimizations reorder anything.

It processes MCAnnotations generated during the CFI reading stage to check if
instructions have either of the three CFIs that can modify RA state:
- negate-ra-state,
- remember-state,
- restore-state.

Then it adds new MCAnnotations to each instruction, indicating their RA state.
Those annotations are:
- Signed,
- Unsigned.

Below is a simple example, that shows the two different type of annotations:
what we have before the pass, and after it.

| Instruction                   | Before          |  After   |
| ----------------------------- | --------------- | -------- |
| paciasp                       | negate-ra-state | unsigned |
| stp	x29, x30, [sp, #-0x10]! |                 | signed   |
| mov	x29, sp                 |                 | signed   |
| ldp	x29, x30, [sp], #0x10   |                 | signed   |
| autiasp                       | negate-ra-state | signed   |
| ret                           |                 | unsigned |

#### Error handling in PointerAuthCFIAnalyzer pass:

Whenever the PointerAuthCFIAnalyzer pass finds inconsistencies in the current
BinaryFunction, it marks the function as ignored using `BF.setIgnored()`. BOLT
will not optimize this function but will emit it unchanged in the original section
(`.bolt.org.text`).

The inconsistencies are as follows:
- finding a `pac*` instruction when already in signed state
- finding an `aut*` instruction when already in unsigned state
- finding `pac*` and `aut*` instructions without `.cfi_negate_ra_state`.

Users will be informed about the number of ignored functions in the pass, the
exact functions ignored, and the found inconsistency.

### PointerAuthCFIFixup

This pass runs after optimizations. It performs the _inverse_ of PointerAuthCFIAnalyzer
pass:
1. it reads the RA state annotations attached to the instructions, and
2. whenever the state changes, it adds a PseudoInstruction that holds an
   OpNegateRAState CFI.

#### Covering newly generated instructions:

Some BOLT passes can add new Instructions. In PointerAuthCFIFixup, we have
to know what RA state these have.

> [!important]
> As issue #160989 explains, unwind info is missing from stubs.
> For this same reason, we cannot generate correct pac-specific unwind info: the
> signedness of the _incorrect_ return address is meaningless.

Assignment of RAStates to newly generated instructions is done in `inferUnknownStates`.
We have two different cases to cover:

1. If a BasicBlock has some instructions with known RA state, and some without, we
   can copy the RAState of known instructions to the unknown ones. As the control
   flow only changes between BasicBlocks, instructions in the same BasicBlock have
   the same return address. (The exception is noreturn calls, but these would only
   cause problems, if the newly inserted instruction is right after the call.)

2. If a BasicBlock has no instructions with known RAState, we have to copy the
   RAState of the previous BasicBlock in layout order.

### Optimizations requiring special attention

Marking states before optimizations ensure that instructions can be moved around
freely. The only special case is function splitting. When a function is split,
the split part becomes a new function in the emitted binary. For unwinding to
work, it needs to "replay" all CFIs that lead up to the split point. BOLT does
this for other CFIs. As negate-ra-state is not read (only stored as an Annotation),
we have to do this manually in PointerAuthCFIFixup. Here, if the split part
starts with an instruction that has Signed RA state, we add a negate-ra-state CFI
to indicate this.

## Option to disallow the feature

The feature can be guarded with the `--update-branch-prediction` flag, which is
on by default. If the flag is set to false, and a function
`containedNegateRAState()` after `FillCFIInfoFor()`, BOLT exits with an error.

---

### Bolt Docs README (`bolt/docs/README.txt`)

BOLT Documentation
====================

The BOLT documentation is written using the Sphinx documentation generator. It
is currently tested with Sphinx 1.1.3.

To build the documents into html configure BOLT with the following cmake options:

  * -DLLVM_ENABLE_SPHINX=ON
  * -DBOLT_INCLUDE_DOCS=ON

After configuring BOLT with these options the make rule `docs-bolt-html` should
be available.

---

### Bolt Docs RuntimeLibrary (`bolt/docs/RuntimeLibrary.md`)

# BOLT ORC-based linker

A high-level view on the simple linker used to insert auxiliary/library code into the final binary produced by BOLT. This is built on top of LLVM's ORC infra (the newest iteration on JITting for LLVM).

## Several levels of code injection

When BOLT starts processing an input executable, its first task is to raise the binary to a low-level IR with CFG. After this is done, we are ready to change code in this binary. Throughout BOLT's pipeline of code transformations, there are plenty of situations when we need to insert new code or fix existing code.

If operating with small code changes inside a basic block, we typically defer this work to MCPlusBuilder. This is our target-independent interface to create new instructions, but it also contains some functions that may create code spanning multiple basic blocks (for instance, when doing indirect call promotion and unrolling an indirect call into a ladder of comparisons/direct calls). The implementation here usually boils down to programmatically creating new MCInst instructions while setting their opcodes according to the target list (see X86GenInstOpcodes.inc generated by tablegen in an LLVM build).

However, this approach quickly becomes awkward if we want to insert a lot of code, especially if this code is frozen and never changes. In these situations, it is more convenient to have a runtime library with all the code you need to insert. This library defines some symbols and can be linked into the final binary. In this case, all you need to do in a BOLT transformation is to insert a call to your library.

## The runtime library

Currently, our runtime library is written in C++ and contains code that helps us instrument a binary.

### Limitations
Our library is not written with regular C++ code as it is not linked against any other libraries (this means we cannot rely on anything defined on libstdc++, glibc, libgcc etc), but is self sufficient. In runtime/CMakeLists.txt, we can see it is built with -ffreestanding, which requires the compiler to avoid using a runtime library by itself.

While this requires us to make our own syscalls, it does simplify our linker a lot, which is very limited and can only do basic function name resolving. However, this is a big improvement in comparison with programmatically generating the code in assembly language using MCInsts.

A few more quirks:

* No BSS section: don't use uninitialized globals
* No dependencies on foreign code: self sufficient
* You should closely watch the generated bolt_rt object files, anything requiring fancy linker features will break. We only support bare bones .text, .data and nothing else.

Read instr.cpp opening comment for more details.


## Linking

While RewriteInstance::emitAndLink() will perform an initial link step to resolve all references of the input program, it will not start linking the runtime library right away. The input program lives in its own module that may end up with unresolved references to the runtime library.

RewriteInstance::linkRuntime() has the job of actually reading individual .o files and adding them to the binary. We currently have a single .o file, so after it is read, ORC can finally resolve references from the first module to the newly inserted .o objects.

This sequence of steps is done by calls to addObject() and emitAndFinalize(). The latter will trigger symbol resolution, relying on the symbol resolver provided by us when calling createLegacyLookupResolver().

---

### Bolt Docs Profiles (`bolt/docs/profiles.md`)

# BOLT Profile Formats

BOLT accepts profile data in several formats. This document describes each
format, how to generate it, and how BOLT consumes it.

The general recommended workflow is to convert unsymbolized profiles (perf.data
or pre-aggregated) into symbolized (fdata or YAML):

```
$ perf2bolt executable \
# perf.data is consumed directly:
  -p perf.data
# OR pre-aggregated requires `--pa` switch:
  -p preagg --pa
# fdata is the default output format, YAML is optionally emitted using `-w` flag:
  -o perf.fdata [-w perf.yaml]
# the output format for `-o` can be switched with `--profile-format`:
  -o perf.yaml --profile-format=yaml
# perf.data can also be cached as pre-aggregated trace data:
  -o perf.preagg --profile-format=preagg
```

# Unsymbolized profiles
Sample or trace profiles without symbol information accepted by
perf2bolt, to be converted into symbolized profile formats, used by llvm-bolt.

## Linux perf data

### Collection
Example with brstack:
```bash
perf record -j any,u -e cycles:u -o perf.data -- ./binary
```

### Consumption modes

- **Branch samples (default)**: Branch stack samples from capable hardware
  (Intel LBR, AMD LBRv2/BRS, ARM BRBE).
  Used by default with `perf2bolt` and `llvm-bolt -p perf.data`.
- **Basic aggregation (`-ba`)**: Sample-based profile without branch stacks.
  Lower quality but works on hardware/VMs without branch sampling support.
- **Tracing (`--itrace`)**: Synthesizing branch stacks from trace profile (Intel PT, ARM ETM).
Requires a value (e.g. `i10usl`), see
[perf documentation](https://github.com/torvalds/linux/blob/35f5aa9ccc83f4a4171cdb6ba023e514e2b2ecff/tools/perf/Documentation/itrace.txt)
for details.
- **ARM SPE (`--spe`)**: Statistical Profiling Extension on supported ARM
  platforms providing short (1-deep) branch stacks.

### Build-id verification

BOLT verifies that the build-id in `perf.data` matches the input binary.
Use `--ignore-build-id` to skip this check.

## Pre-aggregated format

Pre-aggregated profile for direct consumption by `perf2bolt --pa` or
`llvm-bolt --pa`. Enables external tools to generate BOLT-compatible profiles
without going through `perf.data`.

### Entry types

```
E <event>
S <start> <count>
[TR] <branch> <ft_start> <ft_end> <count> [<mispred_count>]
B <start> <end> <count> [<mispred_count>]
[Ff] <start> <end> <count>
r <start> <end> <count>
```

Where:
- `E` — Name of the sampling event used for subsequent entries.
- `S` — Aggregated basic sample at `<start>`.
- `T` — Aggregated trace: branch from `<branch>` to `<ft_start>` with a
  fall-through to `<ft_end>`.
- `R` — Aggregated trace originating at a return.
- `B` — Aggregated branch from `<start>` to `<end>`.
- `F` — Aggregated fall-through from `<start>` to `<end>`.
- `f` — Aggregated fall-through with external origin.
- `r` — Aggregated fall-through with external return as origin.

### Trace mapping
Internally, all branch/fall-through formats are represented as traces, with the
following field mapping:
- `B <start> <end>` -> `T <start> <end> BR_ONLY`
- `F <start> <end>` -> `T FT_ONLY <start> <end>`
- `f <start> <end>` -> `T FT_EXTERNAL_ORIGIN <start> <end>`
- `r <start> <end>` -> `R FT_EXTERNAL_RETURN <start> <end>`

The constants have the following values and can be specified directly:
- `BR_ONLY`/`FT_ONLY`: UINT64_MAX: ffffffffffffffff or -1
- `FT_EXTERNAL_ORIGIN`: UINT64_MAX-1: fffffffffffffffe or -2
- `FT_EXTERNAL_RETURN`: UINT64_MAX-2: fffffffffffffffd or -3

### Call continuation fall-throughs
Where applicable, call continuation fall-throughs are extended back to cover
the call site, improving profile continuity:
- `f`: check that the fall-through start is a block start, not an entry point
  or a landing pad.
- `R`/`r`: unconditional.
- `T`: local origin: extend only if it's a return. External origin: use `f`.

Return hint is only needed for external returns (e.g. from a PLT call), where
the address can't be disassembled to distinguish a return from a jump.

### Best practices
Use T/R format. To capture branch type using Linux perf events, set
the `PERF_SAMPLE_BRANCH_TYPE_SAVE` flag in `perf_event_attr::branch_sample_type`.

To represent top of brstack entry with no fall-through, use `BR_ONLY` as `ft_end`.
Such traces can be extended with an average fall-through length by passing
`--impute-trace-fall-through`.

### Location format

Locations have the format `[<buildid>:]<addr>`:
- `<addr>` — Hex vaddr (non-PIE) or offset from the object base load address (PIE).
- `<buildid>:<offset>` — Offset within the object identified by `<buildid>`.
- `X:<addr>` — External address (outside the profiled binary).

Base load address is the address of the first `PT_LOAD` segment in the binary, which
may not be the same as the segment containing code address.

### Examples

Basic samples profile:
```
E cycles
S 41be50 3
E br_inst_retired.near_taken
S 41be60 6
```

Trace profile combining branches and fall-throughs:
```
T 4b196f 4b19e0 4b19ef 2
```

Trace with unknown fall-through:
```
T 4b196f 4b19e0 -1 2
```

Legacy branch profile with separate branches and fall-throughs:
```
F 41be50 41be50 3
F 41be90 41be90 4
B 4b1942 39b57f0 3 0
B 4b196f 4b19e0 2 0
```

### Generation

Pre-aggregated profiles can be generated by external tools. See
[ebpf-bolt](https://github.com/aaupov/ebpf-bolt) for a reference
implementation using eBPF-based collection.

`perf2bolt` can generate a pre-aggregated profile from`perf.data`:
```
perf2bolt ./binary -p perf.data -o perf.preagg --profile-format=preagg
```

# Symbolized profiles
The profiles accepted by llvm-bolt. fdata is the legacy format, YAML is the rich (metadata-enabled) format.

As local symbol names are not guaranteed to be unique, BOLT disambiguates them with suffixes:
- short form `<name>/<id>`,
- long form `<name>/<file>/<id>`, where `<file>` is the containing debug file symbol.

(Debug file symbols can be preserved when stripping debug information using `--keep-file-symbols`).

As such, symbolized profiles are not expected to be produced by external tools, except the **symbols** fdata
format mode which accepts names without suffixes but matches all aliases.

## fdata format

Plaintext, space-separated branch profile format written by `perf2bolt` and
consumed by `llvm-bolt -data <file>`. Also produced by BOLT instrumentation.

### LBR mode format

Each line records a branch:

```
<is_sym_from> <sym_from> <off_from> <is_sym_to> <sym_to> <off_to> <mispreds> <branches>
```

Where:
- `<is_sym_from>`, `<is_sym_to>`: `1` if the name is an ELF symbol, `0` if
  it is a DSO name. Special values: `2` for local symbols (includes
  filename), `3`/`4`/`5` for memory events.
- `<sym_from>`, `<sym_to>`: Symbol name or DSO name.
- `<off_from>`, `<off_to>`: Hex offset relative to the symbol/DSO.
- `<mispreds>`: Number of branch mispredictions.
- `<branches>`: Total number of branches.

Example:
```
1 main 3fb 0 /lib/ld-2.21.so 12 4 221
```

### No-LBR mode format

Requires `no_lbr` header followed by an optional event name:

```
no_lbr <event_name>
<is_sym> <sym> <off> <count>
```

### Symbols mode format

Requires `symbols` header, followed by a list of (mangled) symbol names:

```
symbols
main
BZ2_compressBlock
```

Each line matches all aliases of the symbol, each matching function is assigned
an execution count of `1`.

### Special headers

- `boltedcollection`: Indicates profile collected on a BOLTed binary.
  Requires BAT (BOLT Address Translation) tables for remapping.

### Memory events format

Memory event types use `<is_sym>` values 3, 4, 5 to record load address
information alongside the instruction location.

## YAML format

Structured profile format with block-level granularity. More resilient to
binary changes and supports stale profile matching.

### Schema

Defined in `ProfileYAMLMapping.h`:

```yaml
header:
  profile-version: <uint32>
  binary-name: <string>
  binary-build-id: <string>        # optional
  profile-flags: [lbr|sample|memevent]
  profile-origin: <string>         # optional, how profile was obtained
  profile-events: <string>         # optional, event names
  dfs-order: <bool>                # optional, default true
  hash-func: <std-hash|xxh3>      # optional, default std-hash
functions:
  - name: <string>
    fid: <uint32>
    hash: <hex64>
    exec: <uint64>
    nblocks: <uint32>
    blocks:
      - bid: <uint32>
        insns: <uint32>
        hash: <hex64>              # optional
        exec: <uint64>             # optional
        succ: [{bid, cnt, mis}]    # optional
        calls: [{off, fid, cnt}]   # optional
    inline_tree: [...]             # optional, pseudo probe info
```

### Hash functions

- `std-hash`: Standard hash function (default for backward compatibility).
- `xxh3`: XXH3 hash function (recommended, better distribution).

### Stale profile matching

BOLT supports matching profiles to modified binaries using block hashes and
call graph matching. When the binary changes between profile collection and
optimization, BOLT uses the hash values to find corresponding blocks in the
new binary.

---

### Clang Tools Extra Docs CMakeLists (`clang-tools-extra/docs/CMakeLists.txt`)

if (DOXYGEN_FOUND)
  if (LLVM_ENABLE_DOXYGEN)
    set(abs_srcdir ${CMAKE_CURRENT_SOURCE_DIR})
    set(abs_builddir ${CMAKE_CURRENT_BINARY_DIR})

    if (HAVE_DOT)
      set(DOT ${LLVM_PATH_DOT})
    endif()

    if (LLVM_DOXYGEN_EXTERNAL_SEARCH)
      set(enable_searchengine "YES")
      set(searchengine_url "${LLVM_DOXYGEN_SEARCHENGINE_URL}")
      set(enable_server_based_search "YES")
      set(enable_external_search "YES")
      set(extra_search_mappings "${LLVM_DOXYGEN_SEARCH_MAPPINGS}")
    else()
      set(enable_searchengine "NO")
      set(searchengine_url "")
      set(enable_server_based_search "NO")
      set(enable_external_search "NO")
      set(extra_search_mappings "")
    endif()

    # If asked, configure doxygen for the creation of a Qt Compressed Help file.
    if (LLVM_ENABLE_DOXYGEN_QT_HELP)
      set(CLANG_TOOLS_DOXYGEN_QCH_FILENAME "org.llvm.clang.qch" CACHE STRING
        "Filename of the Qt Compressed help file")
      set(CLANG_TOOLS_DOXYGEN_QHP_NAMESPACE "org.llvm.clang" CACHE STRING
        "Namespace under which the intermediate Qt Help Project file lives")
      set(CLANG_TOOLS_DOXYGEN_QHP_CUST_FILTER_NAME "Clang ${CLANG_VERSION}" CACHE STRING
        "See http://qt-project.org/doc/qt-4.8/qthelpproject.html#custom-filters")
      set(CLANG_TOOLS_DOXYGEN_QHP_CUST_FILTER_ATTRS "Clang,${CLANG_VERSION}" CACHE STRING
        "See http://qt-project.org/doc/qt-4.8/qthelpproject.html#filter-attributes")
      set(clang_tools_doxygen_generate_qhp "YES")
      set(clang_tools_doxygen_qch_filename "${CLANG_DOXYGEN_QCH_FILENAME}")
      set(clang_tools_doxygen_qhp_namespace "${CLANG_DOXYGEN_QHP_NAMESPACE}")
      set(clang_tools_doxygen_qhelpgenerator_path "${LLVM_DOXYGEN_QHELPGENERATOR_PATH}")
      set(clang_tools_doxygen_qhp_cust_filter_name "${CLANG_DOXYGEN_QHP_CUST_FILTER_NAME}")
      set(clang_tools_doxygen_qhp_cust_filter_attrs "${CLANG_DOXYGEN_QHP_CUST_FILTER_ATTRS}")
    else()
      set(clang_tools_doxygen_generate_qhp "NO")
      set(clang_tools_doxygen_qch_filename "")
      set(clang_tools_doxygen_qhp_namespace "")
      set(clang_tools_doxygen_qhelpgenerator_path "")
      set(clang_tools_doxygen_qhp_cust_filter_name "")
      set(clang_tools_doxygen_qhp_cust_filter_attrs "")
    endif()

    llvm_configure_doxygen()

    set(abs_top_srcdir)
    set(abs_top_builddir)
    set(DOT)
    set(enable_searchengine)
    set(searchengine_url)
    set(enable_server_based_search)
    set(enable_external_search)
    set(extra_search_mappings)
    set(clang_tools_doxygen_generate_qhp)
    set(clang_tools_doxygen_qch_filename)
    set(clang_tools_doxygen_qhp_namespace)
    set(clang_tools_doxygen_qhelpgenerator_path)
    set(clang_tools_doxygen_qhp_cust_filter_name)
    set(clang_tools_doxygen_qhp_cust_filter_attrs)

    add_custom_target(doxygen-clang-tools
      COMMAND ${DOXYGEN_EXECUTABLE} ${CMAKE_CURRENT_BINARY_DIR}/doxygen.cfg
      WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
      COMMENT "Generating clang doxygen documentation." VERBATIM)
    set_target_properties(doxygen-clang-tools PROPERTIES FOLDER "Clang Tools Extra/Docs")

    if (LLVM_BUILD_DOCS)
      add_dependencies(doxygen doxygen-clang-tools)
    endif()

    if (NOT LLVM_INSTALL_TOOLCHAIN_ONLY)
      install(DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/doxygen/html
        DESTINATION docs/html)
    endif()
  endif()
endif()

if (LLVM_ENABLE_SPHINX)
  include(AddSphinxTarget)
  if (SPHINX_FOUND)
    if (${SPHINX_OUTPUT_HTML})
      add_sphinx_target(html clang-tools)
    endif()
    if (${SPHINX_OUTPUT_MAN})
      add_sphinx_target(man clang-tools)
    endif()
  endif()
endif()

---

### Clang Tools Extra Docs ModularizeUsage (`clang-tools-extra/docs/ModularizeUsage.md`)

# Modularize Usage

`modularize [<modularize-options>] [<module-map>|<include-files-list>]*
[<front-end-options>...]`

`<modularize-options>` is a place-holder for options
specific to modularize, which are described below in
`Modularize Command Line Options`.

`<module-map>` specifies the path of a file name for an
existing module map. The module map must be well-formed in
terms of syntax. Modularize will extract the header file names
from the map. Only normal headers are checked, assuming headers
marked "private", "textual", or "exclude" are not to be checked
as a top-level include, assuming they either are included by
other headers which are checked, or they are not suitable for
modules.

`<include-files-list>` specifies the path of a file name for a
file containing the newline-separated list of headers to check
with respect to each other. Lines beginning with '#' and empty
lines are ignored. Header file names followed by a colon and
other space-separated file names will include those extra files
as dependencies. The file names can be relative or full paths,
but must be on the same line. For example:

```
header1.h
header2.h
header3.h: header1.h header2.h
```

Note that unless a `-prefix (header path)` option is specified,
non-absolute file paths in the header list file will be relative
to the header list file directory. Use -prefix to specify a different
directory.

`<front-end-options>` is a place-holder for regular Clang
front-end arguments, which must follow the `<include-files-list>`.
Note that by default, modularize assumes .h files
contain C++ source, so if you are using a different language,
you might need to use a `-x` option to tell Clang that the
header contains another language, i.e.: `-x c`

Note also that because modularize does not use the clang driver,
you will likely need to pass in additional compiler front-end
arguments to match those passed in by default by the driver.

## Modularize Command Line Options

:::{option} -prefix=<header-path>
Prepend the given path to non-absolute file paths in the header list file.
By default, headers are assumed to be relative to the header list file
directory. Use `-prefix` to specify a different directory.
:::

:::{option} -module-map-path=<module-map-path>
Generate a module map and output it to the given file. See the description
in {ref}`module-map-generation`.
:::

:::{option} -problem-files-list=<problem-files-list-file-name>
For use only with module map assistant. Input list of files that
have problems with respect to modules. These will still be
included in the generated module map, but will be marked as
"excluded" headers.
:::

:::{option} -root-module=<root-name>
Put modules generated by the -module-map-path option in an enclosing
module with the given name. See the description in {ref}`module-map-generation`.
:::

:::{option} -block-check-header-list-only
Limit the #include-inside-extern-or-namespace-block
check to only those headers explicitly listed in the header list.
This is a work-around for avoiding error messages for private includes that
purposefully get included inside blocks.
:::

:::{option} -no-coverage-check
Don't do the coverage check for a module map.
:::

:::{option} -coverage-check-only
Only do the coverage check for a module map.
:::

:::{option} -display-file-lists
Display lists of good files (no compile errors), problem files,
and a combined list with problem files preceded by a '#'.
This can be used to quickly determine which files have problems.
The latter combined list might be useful in starting to modularize
a set of headers. You can start with a full list of headers,
use -display-file-lists option, and then use the combined list as
your intermediate list, uncommenting-out headers as you fix them.
:::

---

### Clang Tools Extra Docs README (`clang-tools-extra/docs/README.txt`)

----------------------------------
Documentation in clang-tools-extra
----------------------------------

To generate documentation in HTML format from files in clang-tools-extra/docs,
build the docs-clang-tools-html target.

To generate documentation from the source code using Doxygen, build the
doxygen-clang-tools target.

---

### Clang Tools Extra Docs ReleaseNotes (`clang-tools-extra/docs/ReleaseNotes.md`)

---
myst:
  enable_extensions:
    - attrs_block
    - colon_fence
    - substitution
---

% If you want to modify sections/contents permanently, you should modify both
% ReleaseNotes.md and ReleaseNotesTemplate.txt.

{#extra-clang-tools-release-releasenotestitle}
# Extra Clang Tools {{env.config.release}} {{ (('(In-Progress) ' if env.app.tags.has('PreRelease') else '') ~ 'Release Notes') }}


Written by the [LLVM Team](https://llvm.org/)

::::{only} PreRelease

:::{warning}
These are in-progress notes for the upcoming Extra Clang Tools {{env.config.version}} release.
Release notes for previous releases can be found on
[the Download Page](https://releases.llvm.org/download.html).
:::
::::

## Introduction

This document contains the release notes for the Extra Clang Tools, part of the
Clang release {{env.config.release}}. Here we describe the status of the Extra Clang Tools in
some detail, including major improvements from the previous release and new
feature work. All LLVM releases may be downloaded from the [LLVM releases web
site](https://llvm.org/releases/).

For more information about Clang or LLVM, including information about
the latest release, please see the [Clang Web Site](https://clang.llvm.org) or
the [LLVM Web Site](https://llvm.org).

Note that if you are reading this file from a Git checkout or the
main Clang web page, this document applies to the *next* release, not
the current one. To see the release notes for a specific release, please
see the [releases page](https://llvm.org/releases/).

{#what-s-new-in-extra-clang-tools-release}
## What's New in Extra Clang Tools {{env.config.release}}?

Some of the major new features and improvements to Extra Clang Tools are listed
here. Generic improvements to Extra Clang Tools as a whole or to its underlying
infrastructure are described first, followed by tool-specific sections.

### Major New Features

### Potentially Breaking Changes

- The deprecated `zircon` clang-tidy module has been removed. Users of
  `zircon-temporary-objects` should migrate to {doc}`fuchsia-temporary-objects
  <clang-tidy/checks/fuchsia/temporary-objects>`.

- In 22nd release, The `clang-tidy/ClangTidyModuleRegistry.h` header was deprecated.
  All of the symbols it used to define were moved into `clang-tidy/ClangTidyModule.h`.
  The deprecated header has been removed in this release.

### Improvements to clangd

#### Inlay hints

#### Diagnostics

- Query-based custom clang-tidy checks can now be enabled with the
  `Diagnostics.ClangTidy.ExperimentalCustomChecks` clangd configuration option.
  Custom checks are subject to `FastCheckFilter`, and therefore require
  `FastCheckFilter: Loose` or `None` to run.

#### Semantic Highlighting

#### Compile flags

#### Hover

- The type a `decltype` resolves to is now also shown for composite types,
  e.g. `decltype(x)&` is displayed as `int&`. Qualifiers applied to a
  `decltype` are no longer dropped, so `const decltype(x)` is displayed as
  `const int` rather than `int`.

#### Code completion

- Parameters declared with a `decltype` are now displayed as the type the
  `decltype` resolves to, e.g. `set_x(int val)` rather than
  `set_x(decltype(x) val)`.

#### Code actions

- clangd now applies clang-tidy fix-it post-processing before exposing fixes.

- The `Extract to function` tweak is now offered for selections consisting of
  a single expression-statement (e.g. a lone function call or an overloaded
  operator call such as `stream << 42;`), which it previously refused to
  extract.

- The `Extract to function` tweak is now also available in C files, where
  it previously always refused to apply. Captured variables are passed by
  value when possible, and otherwise via a pointer parameter, since C has
  no references.

#### Signature help

- Parameters declared with a `decltype` are now displayed as the type the
  `decltype` resolves to, as for code completion.

#### Cross-references

#### Objective-C

#### Miscellaneous

- Fixed `clangd-indexer --format=yaml` emitting invalid YAML when indexing
  C++20 concepts.
  ([#206875](https://github.com/llvm/llvm-project/issues/206875))

- `clangd-indexer` now reads clangd configuration files (`.clangd` and the
  user config) by default. Pass `--enable-config=false` to restore the previous
  behavior.

- Added support for loading dynamic plugins via the `-load` command-line
  option.

### Improvements to clang-doc

### Improvements to clang-query

### Improvements to clang-tidy

- Improved {program}`check_clang_tidy.py` by adding support of
  `-std=cXX-or-earlier` values, mirroring the existing `-std=cXX-or-later`.
  New construct expands to the given standard and every earlier one.

- On Windows, {program}`clang-tidy` will now better match mixes of forwards and
  backwards slashes when using the `--line-filter` option. This also improves
  piping from {program}`git` to {program}`clang-tidy-diff.py`, where slashes
  will now be automatically normalized.

#### New checks

- New {doc}`llvm-invalid-regex-pattern
  <clang-tidy/checks/llvm/invalid-regex-pattern>` check.

  Detects malformed regex patterns defined in a single string literal.

- New {doc}`modernize-use-to-underlying
  <clang-tidy/checks/modernize/use-to-underlying>` check.

  Finds casts from a scoped enumeration (`enum class`) to an integer type and
  replaces them with a call to `std::to_underlying` (introduced in C++23).

- New {doc}`performance-expensive-value-or
  <clang-tidy/checks/performance/expensive-value-or>` check.

  Finds calls to `value_or` (and alternative spellings `valueOr`,
  `ValueOr`) on optional types where the return type is expensive to copy.

- New {doc}`portability-avoid-pragma-comment
  <clang-tidy/checks/portability/avoid-pragma-comment>` check.

  Finds uses of `#pragma comment` and, for `lib` or `linker` comments, suggests
  using the build system for improved portability.

- New {doc}`readability-redundant-zero-initializer
  <clang-tidy/checks/readability/redundant-zero-initializer>` check.

  Finds explicit zero initializers of arrays that can be replaced with empty
  braces.

#### New check aliases

#### Changes in existing checks

- Improved {doc}`bugprone-easily-swappable-parameters
  <clang-tidy/checks/bugprone/easily-swappable-parameters>` check by no longer
  emitting empty notes for type aliases when {option}`ModelImplicitConversions`
  is enabled.

- Improved {doc}`bugprone-implicit-widening-of-multiplication-result
  <clang-tidy/checks/bugprone/implicit-widening-of-multiplication-result>` check
  by suggesting a wider type of the same signedness as the original operands,
  instead of forcing a signed type, when a multiplication of two unsigned
  operands narrower than `int` is only signed due to integer promotion.

- Improved {doc}`bugprone-macro-parentheses
  <clang-tidy/checks/bugprone/macro-parentheses>` by fixing invalid fixes for
  macro arguments used as names in alias declarations.

- Fixed a crash in {doc}`bugprone-misplaced-operator-in-strlen-in-alloc
  <clang-tidy/checks/bugprone/misplaced-operator-in-strlen-in-alloc>` when
  checking an array new expression without a size expression.

- Fixed a crash in {doc}`bugprone-misplaced-pointer-arithmetic-in-alloc
  <clang-tidy/checks/bugprone/misplaced-pointer-arithmetic-in-alloc>` when
  pointer arithmetic is applied to a non-array `new` expression whose
  constructor has no arguments.

- Fixed a crash in {doc}`bugprone-pointer-arithmetic-on-polymorphic-object
  <clang-tidy/checks/bugprone/pointer-arithmetic-on-polymorphic-object>` when
  the pointer points to an incomplete (forward-declared) type.

- Improved {doc}`bugprone-redundant-branch-condition
  <clang-tidy/checks/bugprone/redundant-branch-condition>` check by fixing
  false positives when the condition variable is changed later in a loop that
  encloses the inner `if`.

- Fixed a crash in {doc}`bugprone-std-namespace-modification
  <clang-tidy/checks/bugprone/std-namespace-modification>` when checking
  lambda closure types used as template arguments.

- Improved {doc}`bugprone-unchecked-optional-access
  <clang-tidy/checks/bugprone/unchecked-optional-access>` by fixing false
  positives on `bsl::optional` and `bdlb::NullableValue` constructed from a
  value or returned by `bsl::make_optional`.

- Improved {doc}`cppcoreguidelines-missing-std-forward
  <clang-tidy/checks/cppcoreguidelines/missing-std-forward>` check by diagnosing
  unforwarded `auto&&` parameters in C++20 abbreviated function templates.

- Improved {doc}`cppcoreguidelines-pro-type-member-init
  <clang-tidy/checks/cppcoreguidelines/pro-type-member-init>` check by treating
  `std::array` the same as built-in arrays when `IgnoreArrays` option is enabled.

- Improved {doc}`cppcoreguidelines-use-enum-class
  <clang-tidy/checks/cppcoreguidelines/use-enum-class>` check by omitting unnamed enums from the `enum class` requirement, as previously the check suggested users an ill-formed fix.

- Improved {doc}`cppcoreguidelines-virtual-class-destructor
  <clang-tidy/checks/cppcoreguidelines/virtual-class-destructor>` check by
  emitting the diagnostic and its fix-it notes at the destructor's location
  instead of the class name, whenever the destructor is user-declared. The
  diagnostics are still emitted at the class name for implicitly declared
  destructors.

- Improved {doc}`misc-const-correctness
  <clang-tidy/checks/misc/const-correctness>` check:

  - Fixed false positives when the pointee is written through a pointer that
    is incremented, decremented or adjusted with `+=` or `-=`, such as
    `*p++ = 0`.

  - Fixed false positives when the pointee is written through a pointer
    assignment, such as `*(p = q) = 0`.

  - No longer diagnoses variables declared with `decltype(auto)`, where the
    suggested `const` does not compile.
    
  - No longer diagnoses parameters of `main`, whose signature is fixed by the
    standard.

- Fixed an infinite loop in {doc}`misc-multiple-inheritance
  <clang-tidy/checks/misc/multiple-inheritance>` when checking a class that
  inherits from itself or has a circular inheritance graph.

- Improved {doc}`misc-redundant-expression
  <clang-tidy/checks/misc/redundant-expression>` by fixing false positives in
  nested expressions involving different macros or a mix of macro and
  non-macro operands.

- Fixed a crash in {doc}`modernize-raw-string-literal
  <clang-tidy/checks/modernize/raw-string-literal>` on synthetic string
  literals created for raw user-defined literal operators, such as `12_w`.

- Improved {doc}`modernize-return-braced-init-list
  <clang-tidy/checks/modernize/return-braced-init-list>` check to no longer
  rewrite the return value when the constructed type has a
  `std::initializer_list` constructor, as the braced form could select a
  different constructor.

- Fixed a crash in {doc}`modernize-use-designated-initializers
  <clang-tidy/checks/modernize/use-designated-initializers>` when analyzing
  malformed code with nested classes and ambiguous initializer.

- Improved {doc}`modernize-use-equals-default
  <clang-tidy/checks/modernize/use-equals-default>` check to also capture
  default constructor with explicit default-initialization of parents.

- Fixed a crash in {doc}`modernize-use-noexcept
  <clang-tidy/checks/modernize/use-noexcept>` when analyzing malformed template
  code with an unparsed exception specification.

- Extend {doc}`modernize-use-nullptr
  <clang-tidy/checks/modernize/use-nullptr>` to turn `decltype(nullptr)` into
  `std::nullptr_t` from `<cstdef>`.

- Improved {doc}`modernize-use-nullptr
  <clang-tidy/checks/modernize/use-nullptr>` check to avoid replacing `0`
  with `nullptr` in comparisons with ordering types such as
  `std::strong_ordering`.

- Improved {doc}`modernize-use-ranges
  <clang-tidy/checks/modernize/use-ranges>` check by preserving used output
  iterator results when replacing output algorithms such as `std::copy`.

  - Preserved used callable results when replacing `std::for_each` and
    structured binding results when replacing algorithms such as
    `std::equal_range`.

  - Kept diagnostics but suppressed unsafe fix-its when no safe
    result-preserving rewrite is available.

- Improved {doc}`performance-inefficient-algorithm
  <clang-tidy/checks/performance/inefficient-algorithm>` check to no longer
  produce a fix with the container or the searched-for value missing, such as
  `.find(43)` or `s.find()`, when either comes from a macro. The value is
  copied as written rather than with its parentheses stripped, and no fix is
  offered when an argument covers only part of a macro expansion, as it then
  has no source text of its own.

- Improved {doc}`performance-inefficient-vector-operation
  <clang-tidy/checks/performance/inefficient-vector-operation>` by adding the
  {option}`ForRangeLoopClasses` to configure container classes that can be used
  as sources in range-based `for` loops.

- Improved {doc}`performance-no-automatic-move
  <clang-tidy/checks/performance/no-automatic-move>` check by no longer
  warning when returning a variable captured by a lambda or a block, which is
  never implicitly moved from.

- Improved {doc}`performance-prefer-single-char-overloads
  <clang-tidy/checks/performance/prefer-single-char-overloads>` check to
  avoid offering fix-its for string literals originating from macro
  expansions.

- Improved {doc}`readability-convert-member-functions-to-static
  <clang-tidy/checks/readability/convert-member-functions-to-static>` check by
  fixing a crash when checking a const-qualified method declared with the
  `lifetimebound` attribute.

- Improved {doc}`readability-enum-initial-value
  <clang-tidy/checks/readability/enum-initial-value>` check by adding
  the {option}`AllowReferencedInitialValues` to support the
  `INT09-C-EX1` exception, allowing enumerators initialized by referencing
  another enumerator in the same enum (e.g., `last = first`).

- Improved {doc}`readability-function-cognitive-complexity
  <clang-tidy/checks/readability/function-cognitive-complexity>` check by fixing
  a crash when checking a function declared with the `alias` attribute.

- Improved {doc}`readability-identifier-naming
  <clang-tidy/checks/readability/identifier-naming>` check:

  - Fixed a crash when a class inherits from a forward-declared base class.

  - Fixed a crash when checking forward-declared classes with
    {option}`DefaultHungarianPrefix` enabled.

  - Fixed {option}`DefaultHungarianPrefix` being incorrectly diagnosed as an
    invalid option.

  - Fixed invalid fixes when renaming parameter packs used in `sizeof...`
    expressions.

  - Added the {option}`TypedefInheritAnonTagConfig`, which checks a
    typedef or type alias that provides the only name of an otherwise unnamed
    tag, such as `typedef enum {} MyEnum;`, against the style configured for
    that tag kind instead of the typedef or type alias style.

  - Added support for naming lambda init-captures (e.g. `[Captured = Var]`) via
    the new `LambdaCapture` options. Simple, non-init captures continue to follow
    the naming style of the variable they capture.

  - Added the {option}`AllowTrailingUnderscore`, which permits a
    single trailing underscore on any identifier.

- Improved {doc}`readability-named-parameter
  <clang-tidy/checks/readability/named-parameter>` check by ignoring
  standard tag types (e.g. `std::in_place_t`, `std::allocator_arg_t`,
  `std::nothrow_t`, iterator tags, lock tags, etc.) that are used
  exclusively for overload resolution. Added the {option}`IgnoredTypes`
  option to allow customizing the set of ignored types.

- Improved {doc}`readability-non-const-parameter
  <clang-tidy/checks/readability/non-const-parameter>` check by fixing false
  positives on pointers passed to atomic builtins, whose operands may be
  written to, such as the `expected` parameter of
  `atomic_compare_exchange_strong()`.

- Improved {doc}`readability-redundant-parentheses
  <clang-tidy/checks/readability/redundant-parentheses>` check:

  - Fixed a false positive on the required parentheses of `typeof` and
    `typeof_unqual` operands.

  - Fixed false positives and incorrect fixes caused by synthetic parentheses
    in reference non-type template parameter uses, `__builtin_dump_struct` calls,
    and OpenMP `linear` clauses.

- Fixed {doc}`readability-simplify-boolean-expr
  <clang-tidy/checks/readability/simplify-boolean-expr>` producing invalid
  fixes when applying De Morgan's theorem to overloaded comparison operators.

- Improved {doc}`readability-suspicious-call-argument
  <clang-tidy/checks/readability/suspicious-call-argument>` check by fixing the
  default `dist` and `dst` abbreviations of `distance` not being recognized.

- Improved {doc}`readability-trailing-comma
  <clang-tidy/checks/readability/trailing-comma>` check:

  - Fixed false positives on designated initializers, where initializer lists
    synthesized for intermediate subobjects caused the trailing comma of the
    enclosing list to be incorrectly rewritten.

  - Ignored preprocessor directives such as `#endif` that appear immediately
    before an enum's closing brace, which previously produced a false positive
    and a fix-it that inserted a comma after the directive.
    
  - Fixed a false positive on empty brace initializers of types with default
    member initializers.

- Improved {doc}`readability-use-std-min-max
  <clang-tidy/checks/readability/use-std-min-max>` check by fixing spurious
  trailing semicolons and lost comments when the `if` body has no braces.

#### Removed checks

- Removed the deprecated `zircon-temporary-objects` check. Users should migrate to
  {doc}`fuchsia-temporary-objects <clang-tidy/checks/fuchsia/temporary-objects>`.

#### Miscellaneous

- Fixed {program}`clang-tidy` adding an unwanted blank line when automatically
  inserting a missing `#include`, which stopped {program}`clang-format` and
  the `llvm-include-order` check from being able to sort it correctly afterwards.

### Improvements to include-fixer

### Improvements to clang-include-fixer

### Improvements to modularize

### Improvements to pp-trace

### Clang-tidy Visual Studio plugin

---

### Clang Tools Extra Docs ReleaseNotesTemplate (`clang-tools-extra/docs/ReleaseNotesTemplate.txt`)

---
myst:
  enable_extensions:
    - attrs_block
    - colon_fence
    - substitution
---

% If you want to modify sections/contents permanently, you should modify both
% ReleaseNotes.md and ReleaseNotesTemplate.txt.

{#extra-clang-tools-release-releasenotestitle}
# Extra Clang Tools {{env.config.release}} {{ (('(In-Progress) ' if env.app.tags.has('PreRelease') else '') ~ 'Release Notes') }}

```{contents}
:depth: 3
:local: true
```

Written by the [LLVM Team](https://llvm.org/)

::::{only} PreRelease

:::{warning}
These are in-progress notes for the upcoming Extra Clang Tools {{env.config.version}} release.
Release notes for previous releases can be found on
[the Download Page](https://releases.llvm.org/download.html).
:::
::::

## Introduction

This document contains the release notes for the Extra Clang Tools, part of the
Clang release {{env.config.release}}. Here we describe the status of the Extra Clang Tools in
some detail, including major improvements from the previous release and new
feature work. All LLVM releases may be downloaded from the [LLVM releases web
site](https://llvm.org/releases/).

For more information about Clang or LLVM, including information about
the latest release, please see the [Clang Web Site](https://clang.llvm.org) or
the [LLVM Web Site](https://llvm.org).

Note that if you are reading this file from a Git checkout or the
main Clang web page, this document applies to the *next* release, not
the current one. To see the release notes for a specific release, please
see the [releases page](https://llvm.org/releases/).

{#what-s-new-in-extra-clang-tools-release}
## What's New in Extra Clang Tools {{env.config.release}}?

Some of the major new features and improvements to Extra Clang Tools are listed
here. Generic improvements to Extra Clang Tools as a whole or to its underlying
infrastructure are described first, followed by tool-specific sections.

### Major New Features

### Potentially Breaking Changes

### Improvements to clangd

#### Inlay hints

#### Diagnostics

#### Semantic Highlighting

#### Compile flags

#### Hover

#### Code completion

#### Code actions

#### Signature help

#### Cross-references

#### Objective-C

#### Miscellaneous

### Improvements to clang-doc

### Improvements to clang-query

### Improvements to clang-tidy

#### New checks

#### New check aliases

#### Changes in existing checks

#### Removed checks

#### Miscellaneous

### Improvements to include-fixer

### Improvements to clang-include-fixer

### Improvements to modularize

### Improvements to pp-trace

### Clang-tidy Visual Studio plugin

---

### Clang Tools Extra Docs Clang Change Namespace (`clang-tools-extra/docs/clang-change-namespace.md`)

# Clang-Change-Namespace


{program}`clang-change-namespace` can be used to change the surrounding
namespaces of class/function definitions.

Classes/functions in the moved namespace will have new namespaces while
references to symbols (e.g. types, functions) which are not defined in the
changed namespace will be correctly qualified by prepending namespace specifiers
before them. This will try to add shortest namespace specifiers possible.

When a symbol reference needs to be fully-qualified, this adds a `::` prefix to
the namespace specifiers unless the new namespace is the global namespace. For
classes, only classes that are declared/defined in the given namespace in
specified files will be moved: forward declarations will remain in the old
namespace. The will be demonstrated in the next example.

## Example usage

For example, consider this `test.cc` example here with the forward declared
class `FWD` and the defined class `A`, both in the namespace `a`.

```c++
namespace a {
class FWD;
class A {
  FWD *fwd;
};
} // namespace a
```

And now let's change the namespace `a` to `x`.

```console
clang-change-namespace \
  --old_namespace "a" \
  --new_namespace "x" \
  --file_pattern "test.cc" \
  --i \
  test.cc
```

Note that in the code below there's still the forward decalred class `FWD` that
stayed in the namespace `a`. It wasn't moved to the new namespace because it
wasn't defined/declared here in `a` but only forward declared.

```c++
namespace a {
class FWD;
} // namespace a
namespace x {

class A {
  a::FWD *fwd;
};
} // namespace x
```

## Another example

Consider this `test.cc` file:

```c++
namespace na {
class X {};
namespace nb {
class Y {
  X x;
};
} // namespace nb
} // namespace na
```

To move the definition of class `Y` from namespace `na::nb` to `x::y`, run:

```console
clang-change-namespace \
  --old_namespace "na::nb" \
  --new_namespace "x::y" \
  --file_pattern "test.cc" \
  --i \
  test.cc
```

This will overwrite `test.cc` to look like this:

```c++
namespace na {
class X {};

} // namespace na
namespace x {
namespace y {
class Y {
  na::X x;
};
} // namespace y
} // namespace x
```

Note, that we've successfully moved the class `Y` from namespace `na::nb` to
namespace `x::y`.

### Caveats

## Content already exists in new namespace

Consider this `test.cc` example that defines two `class A` one inside the
namespace `a` and one in namespace `b`:

```c++
namespace a {
class A {
    int classAFromWithinNamespace_a;
};
} // namespace a

namespace b {
class A {
    int classAFromWithinNamespace_b;
};
} //namespace b
```

Let's move everything from namespace `a` to namespace `b`:

```console
clang-change-namespace \
  --old_namespace "a" \
  --new_namespace "b" \
  --file_pattern test.cc \
  test.cc
```

As expected we now have to definitions of `class A` inside the namespace `b`:

```c++
namespace b {
class A {
  int classAFromWithinNamespace_a;
};
} // namespace b

namespace b {
class A {
    int classAFromWithinNamespace_b;
};
} //namespace b
```

The re-factoring looks correct but the code will not compile due to the name
duplication. It is not up to the tool to ensure compilability in that sense.
But one has to be aware of that.

## Inline namespace doesn't work

Consider this usage of two versions of implementations for a `greet` function:

```c++
#include <cstdio>

namespace Greeter {
inline namespace Version1 {
  const char* greet() { return "Hello from version 1!"; }
} // namespace Version1
namespace Version2 {
  const char* greet() { return "Hello from version 2!"; }
} // namespace Version2
} // namespace Greeter

int main(int argc, char* argv[]) {
  printf("%s\n", Greeter::greet());
  return 0;
}
```

Note, that currently `Greeter::greet()` will result in a call to
`Greeter::Version1::greet()` because that's the inlined namespace.

Let's say you want to move one and make `Version2` the default now and remove
the `inline` from the `Version1`. First let's try to turn `namespace Version2`
into `inline namespace Version2`:

```console
clang-change-namespace \
  --old_namespace "Greeter::Version2" \
  --new_namespace "inline Version2" \
  --file_pattern main.cc main.cc
```

But this will put the `inline` keyword in the wrong place resulting in:

```c++
#include <cstdio>

namespace Greeter {
inline namespace Version1 {
        const char* greet() { return "Hello from version 1!"; }
} // namespace Version1

} // namespace Greeter
namespace inline Greeter {
namespace Version2 {
const char *greet() { return "Hello from version 2!"; }
} // namespace Version2
} // namespace inline Greeter

int main(int argc, char* argv[]) {
        printf("%s\n", Greeter::greet());
        return 0;
}
```

One cannot use {program}`clang-change-namespace` to inline a namespace.

## Symbol references not updated

Consider this `test.cc` file:

```c++
namespace old {
struct foo {};
}  // namespace old

namespace b {
old::foo g_foo;
}  // namespace b
```

Notice that namespace `b` defines a global variable of type `old::foo`. If we
now change the name of the `old` namespace to `modern`, the reference will not
be updated:

```console
clang-change-namespace \
  --old_namespace "old" \
  --new_namespace "modern" \
  --file_pattern test.cc \
  test.cc
```

```c++
namespace modern {
struct foo {};
} // namespace modern

namespace b {
old::foo g_foo;
}  // namespace b
```

`g_foo` is still of the no longer existing type `old::foo` while instead it
should use `modern::foo`.

Only symbol references in the moved namespace are updated, not outside of it.

### {program}`clang-change-namespace` Command Line Options

:::{option} --allowed_file=<string>
A file containing regexes of symbol names that are not expected to be updated
when changing namespaces around them.
:::

:::{option} --dump_result
Dump new file contents in YAML, if specified.
:::

:::{option} --extra-arg=<string>
Additional argument to append to the compiler command line
:::

:::{option} --extra-arg-before=<string>
Additional argument to prepend to the compiler command line
:::

:::{option} --file_pattern=<string>
Only rename namespaces in files that match the given regular expression
pattern.
:::

:::{option} -i
Inplace edit `<file>`s, if specified.
:::

:::{option} --new_namespace=<string>
New namespace. Use `""` when you target the global namespace.
:::

:::{option} --old_namespace=<string>
Old namespace.
:::

:::{option} -p <string>
Build path
:::

:::{option} --style=<string>
The style name used for reformatting.
:::

---

### Clang Tools Extra Docs Clang Doc (`clang-tools-extra/docs/clang-doc.md`)

# Clang-Doc


{program}`clang-doc` is a tool for generating C and C++ documentation from
source code and comments.

The tool is in a very early development stage, so you might encounter bugs and
crashes. Submitting reports with information about how to reproduce the issue
to [the LLVM bug tracker](https://github.com/llvm/llvm-project/issues/) will definitely help the
project. If you have any ideas or suggestions, please to put a feature request
there.

## Use

{program}`clang-doc` is a [LibTooling](https://clang.llvm.org/docs/LibTooling.html)-based tool, and so requires a
compile command database for your project (for an example of how to do this
see [How To Setup Tooling For LLVM](https://clang.llvm.org/docs/HowToSetupToolingForLLVM.html)).

The tool will process a list of files by default:

```console
$ clang-doc File1.cpp File2.cpp ... FileN.cpp
```

The tool can be also used with a compile commands database:

```console
$ clang-doc --executor=all-TUs compile_commands.json
```

To select only a subset of files from the database, use the `--filter` flag:

```console
$ clang-doc --executor=all-TUs --filter=File[0-9]+.cpp compile_commands.json
```

## Output

{program}`clang-doc` produces a directory of documentation. One file is produced
for each namespace and record in the project source code, containing all
documentation (including contained functions, methods, and enums) for that item.

The top-level directory is configurable through the `output` flag:

```console
$ clang-doc --output=output/directory/ compile_commands.json
```

## Configuration

Configuration for {program}`clang-doc` is currently limited to command-line options.
In the future, it may develop the ability to use a configuration file, but no such
efforts are currently in progress.

### Options

{program}`clang-doc` offers the following options:

```
/* Detailed source-code truncated for AI context efficiency. */
```

The following flags should only be used if `format` is set to `html`:
- `repository`
- `source-root`
- `stylesheets`

---

### Clang Tools Extra Docs Clang Include Fixer (`clang-tools-extra/docs/clang-include-fixer.md`)

# Clang-Include-Fixer


One of the major nuisances of C++ compared to other languages is the manual
management of `#include` directives in any file.
{program}`clang-include-fixer` addresses one aspect of this problem by providing
an automated way of adding `#include` directives for missing symbols in one
translation unit.

While inserting missing `#include`, {program}`clang-include-fixer` adds
missing namespace qualifiers to all instances of an unidentified symbol if
the symbol is missing some prefix namespace qualifiers.

## Setup

To use {program}`clang-include-fixer` two databases are required. Both can be
generated with existing tools.

- Compilation database. Contains the compiler commands for any given file in a
  project and can be generated by CMake, see [How To Setup Tooling For LLVM][how to setup tooling for llvm].
- Symbol index. Contains all symbol information in a project to match a given
  identifier to a header file.

Ideally both databases (`compile_commands.json` and
`find_all_symbols_db.yaml`) are linked into the root of the source tree they
correspond to. Then the {program}`clang-include-fixer` can automatically pick
them up if called with a source file from that tree. Note that by default
`compile_commands.json` as generated by CMake does not include header files,
so only implementation files can be handled by tools.

### Creating a Symbol Index From a Compilation Database

The include fixer contains {program}`find-all-symbols`, a tool to create a
symbol database in YAML format from a compilation database by parsing all
source files listed in it. The following list of commands shows how to set up a
database for LLVM, any project built by CMake should follow similar steps.

```console
$ cd path/to/llvm-build
$ ninja find-all-symbols // build find-all-symbols tool.
$ ninja clang-include-fixer // build clang-include-fixer tool.
$ ls compile_commands.json # Make sure compile_commands.json exists.
  compile_commands.json
$ path/to/llvm/source/clang-tools-extra/clang-include-fixer/find-all-symbols/tool/run-find-all-symbols.py
  ... wait as clang indexes the code base ...
$ ln -s $PWD/find_all_symbols_db.yaml path/to/llvm/source/ # Link database into the source tree.
$ ln -s $PWD/compile_commands.json path/to/llvm/source/ # Also link compilation database if it's not there already.
$ cd path/to/llvm/source
$ /path/to/clang-include-fixer -db=yaml path/to/file/with/missing/include.cpp
  Added #include "foo.h"
```

### Integrate with Vim

To run `clang-include-fixer` on a potentially unsaved buffer in Vim. Add the
following key binding to your `.vimrc`:

```console
noremap <leader>cf :pyf path/to/llvm/source/clang-tools-extra/clang-include-fixer/tool/clang-include-fixer.py<cr>
```

This enables `clang-include-fixer` for NORMAL and VISUAL mode. Change
`<leader>cf` to another binding if you need clang-include-fixer on a different
key. The [\<leader> key](<http://vim.wikia.com/wiki/Mapping_keys_in_Vim_-_Tutorial_(Part_3)#Map_leader>)
is a reference to a specific key defined by the mapleader variable and is bound
to backslash by default.

Make sure vim can find {program}`clang-include-fixer`:

- Add the path to {program}`clang-include-fixer` to the PATH environment variable.
- Or set `g:clang_include_fixer_path` in vimrc: `let g:clang_include_fixer_path=path/to/clang-include-fixer`

You can customize the number of headers being shown by setting
`let g:clang_include_fixer_maximum_suggested_headers=5`

Customized settings in `.vimrc`:

- `let g:clang_include_fixer_path = "clang-include-fixer"`

  Set clang-include-fixer binary file path.

- `let g:clang_include_fixer_maximum_suggested_headers = 3`

  Set the maximum number of `#includes` to show. Default is 3.

- `let g:clang_include_fixer_increment_num = 5`

  Set the increment number of #includes to show every time when pressing `m`.
  Default is 5.

- `let g:clang_include_fixer_jump_to_include = 0`

  Set to 1 if you want to jump to the new inserted `#include` line. Default is
  0.

- `let g:clang_include_fixer_query_mode = 0`

  Set to 1 if you want to insert `#include` for the symbol under the cursor.
  Default is 0. Compared to normal mode, this mode won't parse the source file
  and only search the symbol from database, which is faster than normal mode.

See `clang-include-fixer.py` for more details.

### Integrate with Emacs

To run `clang-include-fixer` on a potentially unsaved buffer in Emacs.
Ensure that Emacs finds `clang-include-fixer.el` by adding the directory
containing the file to the `load-path` and requiring the `clang-include-fixer`
in your `.emacs`:

```console
(add-to-list 'load-path "path/to/llvm/source/clang-tools-extra/clang-include-fixer/tool/"
(require 'clang-include-fixer)
```

Within Emacs the tool can be invoked with the command
`M-x clang-include-fixer`. This will insert the header that defines the
first undefined symbol; if there is more than one header that would define the
symbol, the user is prompted to select one.

To include the header that defines the symbol at point, run
`M-x clang-include-fixer-at-point`.

Make sure Emacs can find {program}`clang-include-fixer`:

- Either add the parent directory of {program}`clang-include-fixer` to the PATH
  environment variable, or customize the Emacs user option
  `clang-include-fixer-executable` to point to the file name of the program.

## How it Works

To get the most information out of Clang at parse time,
{program}`clang-include-fixer` runs in tandem with the parse and receives
callbacks from Clang's semantic analysis. In particular it reuses the existing
support for typo corrections. Whenever Clang tries to correct a potential typo
it emits a callback to the include fixer which then looks for a corresponding
file. At this point rich lookup information is still available, which is not
available in the AST at a later stage.

The identifier that should be typo corrected is then sent to the database, if a
header file is returned it is added as an include directive at the top of the
file.

Currently {program}`clang-include-fixer` only inserts a single include at a
time to avoid getting caught in follow-up errors. If multiple `#include`
additions are desired the program can be rerun until a fix-point is reached.

[how to setup tooling for llvm]: https://clang.llvm.org/docs/HowToSetupToolingForLLVM.html

---

### Clang Tools Extra Docs Clang Modernize (`clang-tools-extra/docs/clang-modernize.md`)

---
orphan: true
---

All {program}`clang-modernize` transforms have moved to {doc}`clang-tidy/index`
(see the `modernize` module).

---

### Clang Tools Extra Docs Clang Reorder Fields (`clang-tools-extra/docs/clang-reorder-fields.md`)

# Clang-Reorder-Fields


{program}`clang-reorder-fields` is a refactoring tool to reorder fields in
C/C++ structs and classes. This tool automatically updates:

- Field declarations in the record definition
- Constructor initializer lists in C++ classes
- Aggregate initialization expressions (both C and C++)
- Designated initializer lists (C++20)

This can be useful for optimizing memory layout, improving cache performance,
or conforming to coding standards that require specific field orderings.

## Example usage

### Basic struct reordering

Consider this simple struct in `example.c`:

```c
struct Foo {
  const int *x;
  int y;
  double z;
  int w;
};

int main() {
  const int val = 42;
  struct Foo foo = { &val, 0, 1.5, 17 };
  return 0;
}
```

To reorder the fields to `z, w, y, x`, run:

```console
clang-reorder-fields -record-name Foo -fields-order z,w,y,x example.c --
```

This will reorder both the struct definition and the initialization:

```c
struct Foo {
  double z;
  int w;
  int y;
  const int *x;
};

int main() {
  const int val = 42;
  struct Foo foo = { 1.5, 17, 0, &val };
  return 0;
}
```

### Namespaced structs

For C++ code with namespaces, use the fully-qualified name:

```c++
namespace bar {
struct Foo {
  const int *x;
  int y;
  double z;
  int w;
};
}
```

```console
clang-reorder-fields -record-name ::bar::Foo -fields-order z,w,y,x example.cpp --
```

For classes defined in the global namespace (without any namespace), you can
use either the simple class name or prefix it with `::`:

```console
clang-reorder-fields -record-name Foo -fields-order z,w,y,x example.cpp --
# or
clang-reorder-fields -record-name ::Foo -fields-order z,w,y,x example.cpp --
```

### C++ constructor initializer lists

The tool also reorders constructor initializer lists. Given:

```c++
class Foo {
public:
  Foo();

private:
  int x;
  const char *s1;
  const char *s2;
  double z;
};

Foo::Foo():
  x(12),
  s1("abc"),
  s2("def"),
  z(3.14)
{}
```

Running:

```console
clang-reorder-fields -record-name Foo -fields-order s1,x,z,s2 example.cpp --
```

Will reorder both the field declarations and the constructor initializers:

```c++
class Foo {
public:
  Foo();

private:
  const char *s1;
  int x;
  double z;
  const char *s2;
};

Foo::Foo():
  s1("abc"),
  x(12),
  z(3.14),
  s2("def")
{}
```

### Designated initializers

For C++20 code using designated initializers:

```c++
struct Bar {
  char a;
  int b;
  int c;
};

int main() {
  Bar bar1 = { 'a', 0, 123 };
  Bar bar2 = { .a = 'a', .b = 0, .c = 123 };
  return 0;
}
```

```console
clang-reorder-fields --extra-arg="-std=c++20" -record-name Bar \
  -fields-order c,a,b example.cpp --
```

Will produce:

```c++
struct Bar {
  int c;
  char a;
  int b;
};

int main() {
  Bar bar1 = { 123, 'a', 0 };
  Bar bar2 = { .c = 123, .a = 'a', .b = 0 };
  return 0;
}
```

### In-place editing

Use the `-i` flag to modify files in-place:

```console
clang-reorder-fields -record-name Foo -fields-order z,w,y,x -i example.c --
```

## Limitations and Caveats

### Different access specifiers

The tool cannot reorder fields with different access specifiers
(`public/private/protected`). All fields being reordered must have the same
access level.

```c++
class Example {
private:
  int x;
public:
  int y;  // Cannot reorder x and y - different access levels
};
```

### Multiple field declarations

Declarations with multiple fields in one statement are not supported:

```c
struct Example {
  int a, b;  // Not supported - multiple fields in one declaration
};
```

### Macro-expanded fields

Macros that expand to multiple field declarations are not supported. However,
macros that expand to a single field declaration work correctly:

```c
#define INT_FIELD(NAME) int NAME     // Supported - expands to one field
#define TWO_FIELDS int a; int b;     // Not supported - expands to two fields

struct Supported {
  INT_FIELD(x);  // OK - this is a single field
  int y;
  INT_FIELD(z);  // OK - this is a single field
};

struct NotSupported {
  TWO_FIELDS     // Not OK - expands to multiple fields
  int c;
};
```

The tool can reorder fields declared via macros as long as each macro invocation
expands to exactly one field declaration.

### Preprocessor directives

Structs with preprocessor directives between fields cannot be reordered:

```c
struct Example {
  int a;
#ifdef FEATURE
  int b;
#endif
  int c;  // Not supported - preprocessor directives present
};
```

### Flexible array members

In C, a flexible array member is an incomplete array type that must be the last
member of a struct (as specified by C99 and later standards). This allows the
struct to have a variable-length array at the end. Since this is a language
requirement, the tool enforces that flexible array members remain in the last
position:

```c
struct Example {
  int count;
  int data[];  // Flexible array member - must remain last
};
```

Attempting to reorder fields such that the flexible array member is no longer
last will result in an error:

```console
clang-reorder-fields -record-name Example -fields-order data,count example.c --
```

Will produce:

```text
Flexible array member must remain the last field in the struct
```

This ensures the generated code remains valid C.

### Field dependencies in initializers

The tool will issue a warning if reordering causes a field to be used in an
initializer before it's initialized. Consider this example:

```c++
class Foo {
public:
  Foo(int x, char c);
  int x;
  char c;
  Dummy z;
};

Foo::Foo(int x, char c) :
  x(x),
  c(c),
  z(this->x, c)  // z's initializer uses x and c
{}
```

If you reorder the fields to `z, c, x`:

```console
clang-reorder-fields -record-name Foo -fields-order z,c,x example.cpp --
```

The tool will produce warnings:

```text
example.cpp:10:3: warning: reordering field x after z makes x uninitialized when used in init expression
example.cpp:10:3: warning: reordering field c after z makes c uninitialized when used in init expression
```

This warns you that in C++, member initializers are executed in the order that
fields are declared in the class, not the order they appear in the initializer
list. After reordering, `z` would be initialized first, but its initializer
tries to use `x` and `c` which haven't been initialized yet.

The tool will still perform the reordering but warns about the potential issue.
You should review these warnings and adjust your code accordingly.

## {program}`clang-reorder-fields` Command Line Options

:::{option} --record-name=<string>
The fully-qualified name of the struct or class to reorder. Required.

For C structs, use the struct name directly (e.g., `Foo`).

For C++ classes/structs in namespaces, use the fully-qualified name including
namespaces (e.g., `::namespace::ClassName`).

For C++ classes/structs in the global namespace, you can use either the simple
name (e.g., `Foo`) or prefix with `::` (e.g., `::Foo`).
:::

:::{option} --fields-order=<string>
Comma-separated list of field names in the desired order. Required.

All field names must exactly match the fields in the struct/class definition.
The number of fields must match the number in the definition.
:::

:::{option} -i
Overwrite edited files in-place. If not specified, the rewritten code is
printed to stdout.
:::

:::{option} --extra-arg=<string>
Additional argument to append to the compiler command line.

Useful for specifying language standards (e.g., `--extra-arg="-std=c++20"`).
:::

:::{option} --extra-arg-before=<string>
Additional argument to prepend to the compiler command line.
:::

:::{option} -p <string>
Build path. Specifies the directory containing `compile_commands.json` for
compilation database support.
:::

## Use Cases

### Memory layout optimization

Reorder fields to minimize padding and improve cache locality:

```c
// Before: 24 bytes (with padding)
struct Data {
  char a;     // 1 byte + 7 padding
  double b;   // 8 bytes
  char c;     // 1 byte + 7 padding
};
```

```console
clang-reorder-fields -record-name Data -fields-order b,a,c data.c --
```

```c
// After: 16 bytes (less padding)
struct Data {
  double b;   // 8 bytes
  char a;     // 1 byte
  char c;     // 1 byte + 6 padding
};
```

### Coding standard compliance

Ensure fields are ordered according to project conventions (e.g., alphabetically,
by type, or by access pattern).

### Field grouping

Group related fields together for better code organization and readability.

---

### Clang Tools Extra Docs Clang Tidy (`clang-tools-extra/docs/clang-tidy.md`)

---
orphan: true
---

```{eval-rst}
.. meta::
   :http-equiv=refresh: 0;URL='clang-tidy/'
```

clang-tidy documentation has moved here: [clang-tidy](clang-tidy/index.rst)

---

### Clang Tools Extra Docs Clangd (`clang-tools-extra/docs/clangd.md`)

---
orphan: true
redirect_target: https://clangd.llvm.org/
template: clangd_redirect.html
---

---

### Clang Tools Extra Docs Cpp11 Migrate (`clang-tools-extra/docs/cpp11-migrate.md`)

---
orphan: true
---

All {program}`clang-modernize` transforms have moved to {doc}`clang-tidy/index`
(see the `modernize` module).

---

### Clang Tools Extra Docs Modularize (`clang-tools-extra/docs/modularize.md`)

```{index} modularize
```

# Modularize User's Manual

```{toctree}
:hidden: true

ModularizeUsage
```

{program}`modularize` is a standalone tool that checks whether a set of headers
provides the consistent definitions required to use modules. For example, it
detects whether the same entity (say, a NULL macro or size_t typedef) is
defined in multiple headers or whether a header produces different definitions
under different circumstances. These conditions cause modules built from the
headers to behave poorly, and should be fixed before introducing a module
map.

{program}`modularize` also has an assistant mode option for generating
a module map file based on the provided header list. The generated file
is a functional module map that can be used as a starting point for a
module.modulemap file.

## Getting Started

To build from source:

1. Read [Getting Started with the LLVM System][getting started with the llvm system] and [Clang Tools
   Documentation][clang tools documentation] for information on getting sources for LLVM, Clang, and
   Clang Extra Tools.

2. [Getting Started with the LLVM System][getting started with the llvm system] and [Building LLVM with CMake][building llvm with cmake] give
   directions for how to build. With sources all checked out into the
   right place the LLVM build will build Clang Extra Tools and their
   dependencies automatically.

   - If using CMake, you can also use the `modularize` target to build
     just the modularize tool and its dependencies.

Before continuing, take a look at {doc}`ModularizeUsage` to see how to invoke
modularize.

## What Modularize Checks

Modularize will check for the following:

- Duplicate global type and variable definitions
- Duplicate macro definitions
- Macro instances, 'defined(macro)', or #if, #elif, #ifdef, #ifndef conditions
  that evaluate differently in a header
- #include directives inside 'extern "C/C++" {}' or 'namespace (name) {}' blocks
- Module map header coverage completeness (in the case of a module map input
  only)

Modularize will do normal C/C++ parsing, reporting normal errors and warnings,
but will also report special error messages like the following:

```
error: '(symbol)' defined at multiple locations:
   (file):(row):(column)
   (file):(row):(column)

error: header '(file)' has different contents depending on how it was included
```

The latter might be followed by messages like the following:

```
note: '(symbol)' in (file) at (row):(column) not always provided
```

Checks will also be performed for macro expansions, defined(macro)
expressions, and preprocessor conditional directives that evaluate
inconsistently, and can produce error messages like the following:

```
 (...)/SubHeader.h:11:5:
#if SYMBOL == 1
    ^
error: Macro instance 'SYMBOL' has different values in this header,
       depending on how it was included.
  'SYMBOL' expanded to: '1' with respect to these inclusion paths:
    (...)/Header1.h
      (...)/SubHeader.h
(...)/SubHeader.h:3:9:
#define SYMBOL 1
        ^
Macro defined here.
  'SYMBOL' expanded to: '2' with respect to these inclusion paths:
    (...)/Header2.h
        (...)/SubHeader.h
(...)/SubHeader.h:7:9:
#define SYMBOL 2
        ^
Macro defined here.
```

Checks will also be performed for '#include' directives that are
nested inside 'extern "C/C++" {}' or 'namespace (name) {}' blocks,
and can produce error message like the following:

```
IncludeInExtern.h:2:3:
#include "Empty.h"
^
error: Include directive within extern "C" {}.
IncludeInExtern.h:1:1:
extern "C" {
^
The "extern "C" {}" block is here.
```

(module-map-coverage)=

## Module Map Coverage Check

The coverage check uses the Clang library to read and parse the
module map file. Starting at the module map file directory, or just the
include paths, if specified, it will collect the names of all the files it
considers headers (no extension, .h, or .inc--if you need more, modify the
isHeader function). It then compares the headers against those referenced
in the module map, either explicitly named, or implicitly named via an
umbrella directory or umbrella file, as parsed by the ModuleMap object.
If headers are found which are not referenced or covered by an umbrella
directory or file, warning messages will be produced, and this program
will return an error code of 1. If no problems are found, an error code of
0 is returned.

Note that in the case of umbrella headers, this tool invokes the compiler
to preprocess the file, and uses a callback to collect the header files
included by the umbrella header or any of its nested includes. If any
front end options are needed for these compiler invocations, these
can be included on the command line after the module map file argument.

Warning message have the form:

> warning: module.modulemap does not account for file: Level3A.h

Note that for the case of the module map referencing a file that does
not exist, the module map parser in Clang will (at the time of this
writing) display an error message.

To limit the checks {program}`modularize` does to just the module
map coverage check, use the `-coverage-check-only option`.

For example:

```
modularize -coverage-check-only module.modulemap
```

(module-map-generation)=

## Module Map Generation

If you specify the `-module-map-path=<module map file>`,
{program}`modularize` will output a module map based on the input header list.
A module will be created for each header. Also, if the header in the header
list is a partial path, a nested module hierarchy will be created in which a
module will be created for each subdirectory component in the header path,
with the header itself represented by the innermost module. If other headers
use the same subdirectories, they will be enclosed in these same modules also.

For example, for the header list:

```
SomeTypes.h
SomeDecls.h
SubModule1/Header1.h
SubModule1/Header2.h
SubModule2/Header3.h
SubModule2/Header4.h
SubModule2.h
```

The following module map will be generated:

```
// Output/NoProblemsAssistant.txt
// Generated by: modularize -module-map-path=Output/NoProblemsAssistant.txt \
     -root-module=Root NoProblemsAssistant.modularize

module SomeTypes {
  header "SomeTypes.h"
  export *
}
module SomeDecls {
  header "SomeDecls.h"
  export *
}
module SubModule1 {
  module Header1 {
    header "SubModule1/Header1.h"
    export *
  }
  module Header2 {
    header "SubModule1/Header2.h"
    export *
  }
}
module SubModule2 {
  module Header3 {
    header "SubModule2/Header3.h"
    export *
  }
  module Header4 {
    header "SubModule2/Header4.h"
    export *
  }
  header "SubModule2.h"
  export *
}
```

An optional `-root-module=<root-name>` option can be used to cause a root module
to be created which encloses all the modules.

An optional `-problem-files-list=<problem-file-name>` can be used to input
a list of files to be excluded, perhaps as a temporary stop-gap measure until
problem headers can be fixed.

For example, with the same header list from above:

```
// Output/NoProblemsAssistant.txt
// Generated by: modularize -module-map-path=Output/NoProblemsAssistant.txt \
     -root-module=Root NoProblemsAssistant.modularize

module Root {
  module SomeTypes {
    header "SomeTypes.h"
    export *
  }
  module SomeDecls {
    header "SomeDecls.h"
    export *
  }
  module SubModule1 {
    module Header1 {
      header "SubModule1/Header1.h"
      export *
    }
    module Header2 {
      header "SubModule1/Header2.h"
      export *
    }
  }
  module SubModule2 {
    module Header3 {
      header "SubModule2/Header3.h"
      export *
    }
    module Header4 {
      header "SubModule2/Header4.h"
      export *
    }
    header "SubModule2.h"
    export *
  }
}
```

Note that headers with dependents will be ignored with a warning, as the
Clang module mechanism doesn't support headers that rely on other headers
being included first.

The module map format defines some keywords which can't be used in module
names. If a header has one of these names, an underscore ('\_') will be
prepended to the name. For example, if the header name is `header.h`,
because `header` is a keyword, the module name will be `_header`.
For a list of the module map keywords, please see:
[Lexical structure](https://clang.llvm.org/docs/Modules.html#lexical-structure)

[building llvm with cmake]: https://llvm.org/docs/CMake.html
[clang tools documentation]: https://clang.llvm.org/docs/ClangTools.html
[getting started with the llvm system]: https://llvm.org/docs/GettingStarted.html

---

### Clang Tools Extra Docs Pp Trace (`clang-tools-extra/docs/pp-trace.md`)

```{index} pp-trace
```

# pp-trace User's Manual

{program}`pp-trace` is a standalone tool that traces preprocessor
activity. It's also used as a test of Clang's PPCallbacks interface.
It runs a given source file through the Clang preprocessor, displaying
selected information from callback functions overridden in a
[PPCallbacks](https://clang.llvm.org/doxygen/classclang_1_1PPCallbacks.html)
derivation. The output is in a high-level YAML format, described in
{ref}`OutputFormat`.

(usage)=

## pp-trace Usage

### Command Line Format

`pp-trace [<pp-trace-options>] <source-file> [-- <front-end-options>]`

`<pp-trace-options>` is a place-holder for options
specific to pp-trace, which are described below in
{ref}`CommandLineOptions`.

`<source-file>` specifies the source file to run through the preprocessor.

`<front-end-options>` is a place-holder for regular
[Clang Compiler Options](https://clang.llvm.org/docs/UsersManual.html#command-line-options),
which must follow the \<source-file>.

(commandlineoptions)=

### Command Line Options

:::{option} -callbacks <comma-separated-globs>
This option specifies a comma-separated list of globs describing the list of
callbacks that should be traced. Globs are processed in order of appearance.
Positive globs add matched callbacks to the set, negative globs (those with
the '-' prefix) remove callacks from the set.

- FileChanged
- FileSkipped
- InclusionDirective
- moduleImport
- EndOfMainFile
- Ident
- PragmaDirective
- PragmaComment
- PragmaDetectMismatch
- PragmaDebug
- PragmaMessage
- PragmaDiagnosticPush
- PragmaDiagnosticPop
- PragmaDiagnostic
- PragmaOpenCLExtension
- PragmaWarning
- PragmaWarningPush
- PragmaWarningPop
- MacroExpands
- MacroDefined
- MacroUndefined
- Defined
- SourceRangeSkipped
- If
- Elif
- Ifdef
- Ifndef
- Else
- Endif
:::

:::{option} -output <output-file>
By default, pp-trace outputs the trace information to stdout. Use this
option to output the trace information to a file.
:::

(outputformat)=

## pp-trace Output Format

The pp-trace output is formatted as YAML. See <https://yaml.org/> for general
YAML information. It's arranged as a sequence of information about the
callback call, including the callback name and argument information, for
example:

```yaml
---
- Callback: Name
  Argument1: Value1
  Argument2: Value2
(etc.)
...
```

With real data:

```yaml
---
- Callback: FileChanged
  Loc: "c:/Clang/llvm/clang-tools-extra/test/pp-trace/pp-trace-include.cpp:1:1"
  Reason: EnterFile
  FileType: C_User
  PrevFID: (invalid)
  (etc.)
- Callback: FileChanged
  Loc: "D:/Clang/llvm/clang-tools-extra/test/pp-trace/pp-trace-include.cpp:5:1"
  Reason: ExitFile
  FileType: C_User
  PrevFID: "D:/Clang/llvm/clang-tools-extra/test/pp-trace/Input/Level1B.h"
- Callback: EndOfMainFile
...
```

In all but one case (MacroDirective) the "Argument" scalars have the same
name as the argument in the corresponding PPCallbacks callback function.

### Callback Details

The following sections describe the purpose and output format for each callback.

Click on the callback name in the section heading to see the Doxygen
documentation for the callback.

The argument descriptions table describes the callback argument information
displayed.

The Argument Name field in most (but not all) cases is the same name as the
callback function parameter.

The Argument Value Syntax field describes the values that will be displayed
for the argument value. It uses an ad hoc representation that mixes literal
and symbolic representations. Enumeration member symbols are shown as the
actual enum member in a (member1|member2|...) form. A name in parentheses
can either represent a place holder for the described value, or confusingly,
it might be a literal, such as (null), for a null pointer.
Locations are shown as quoted only to avoid confusing the documentation generator.

The Clang C++ Type field is the type from the callback function declaration.

The description describes the argument or what is displayed for it.

Note that in some cases, such as when a structure pointer is an argument
value, only some key member or members are shown to represent the value,
instead of trying to display all members of the structure.

#### [FileChanged](https://clang.llvm.org/doxygen/classclang_1_1PPCallbacks.html#a7cc8cfaf34114fc65e92af621cd6464e) Callback

FileChanged is called when the preprocessor enters or exits a file, both the
top level file being compiled, as well as any #include directives. It will
also be called as a result of a system header pragma or in internal renaming
of a file.

Argument descriptions:

| Argument Name | Argument Value Syntax                                 | Clang C++ Type                | Description                    |
| ------------- | ----------------------------------------------------- | ----------------------------- | ------------------------------ |
| Loc           | "(file):(line):(col)"                                 | SourceLocation                | The location of the directive. |
| Reason        | (EnterFile\|ExitFile\|SystemHeaderPragma\|RenameFile) | PPCallbacks::FileChangeReason | Reason for change.             |
| FileType      | (C_User\|C_System\|C_ExternCSystem)                   | SrcMgr::CharacteristicKind    | Include type.                  |
| PrevFID       | ((file)\|(invalid))                                   | FileID                        | Previous file, if any.         |

Example:

```yaml
- Callback: FileChanged
  Loc: "D:/Clang/llvm/clang-tools-extra/test/pp-trace/pp-trace-include.cpp:1:1"
  Reason: EnterFile
  FileType: C_User
  PrevFID: (invalid)
```

#### [FileSkipped](https://clang.llvm.org/doxygen/classclang_1_1PPCallbacks.html#ab5b338a0670188eb05fa7685bbfb5128) Callback

FileSkipped is called when a source file is skipped as the result of header
guard optimization.

Argument descriptions:

| Argument Name | Argument Value Syntax               | Clang C++ Type             | Description                                              |
| ------------- | ----------------------------------- | -------------------------- | -------------------------------------------------------- |
| ParentFile    | ("(file)" or (null))                | const FileEntry            | The file that #included the skipped file.                |
| FilenameTok   | (token)                             | const Token                | The token in ParentFile that indicates the skipped file. |
| FileType      | (C_User\|C_System\|C_ExternCSystem) | SrcMgr::CharacteristicKind | The file type.                                           |

Example:

```yaml
- Callback: FileSkipped
  ParentFile: "/path/filename.h"
  FilenameTok: "filename.h"
  FileType: C_User
```

#### [InclusionDirective](https://clang.llvm.org/doxygen/classclang_1_1PPCallbacks.html#a557d9738c329793513a6f57d6b60de52) Callback

InclusionDirective is called when an inclusion directive of any kind (#include\</code>, #import\</code>, etc.) has been processed, regardless of whether the inclusion will actually result in an inclusion.

Argument descriptions:

| Argument Name | Argument Value Syntax   | Clang C++ Type  | Description                                                                                                  |
| ------------- | ----------------------- | --------------- | ------------------------------------------------------------------------------------------------------------ |
| HashLoc       | "(file):(line):(col)"   | SourceLocation  | The location of the '#' that starts the inclusion directive.                                                 |
| IncludeTok    | (token)                 | const Token     | The token that indicates the kind of inclusion directive, e.g., 'include' or 'import'.                       |
| FileName      | "(file)"                | StringRef       | The name of the file being included, as written in the source code.                                          |
| IsAngled      | (true\|false)           | bool            | Whether the file name was enclosed in angle brackets; otherwise, it was enclosed in quotes.                  |
| FilenameRange | "(file)"                | CharSourceRange | The character range of the quotes or angle brackets for the written file name.                               |
| File          | "(file)"                | const FileEntry | The actual file that may be included by this inclusion directive.                                            |
| SearchPath    | "(path)"                | StringRef       | Contains the search path which was used to find the file in the file system.                                 |
| RelativePath  | "(path)"                | StringRef       | The path relative to SearchPath, at which the include file was found.                                        |
| Imported      | ((module name)\|(null)) | const Module    | The module, whenever an inclusion directive was automatically turned into a module import or null otherwise. |

Example:

```yaml
- Callback: InclusionDirective
  HashLoc: "D:/Clang/llvmnewmod/clang-tools-extra/test/pp-trace/pp-trace-include.cpp:4:1"
  IncludeTok: include
  FileName: "Input/Level1B.h"
  IsAngled: false
  FilenameRange: "Input/Level1B.h"
  File: "D:/Clang/llvmnewmod/clang-tools-extra/test/pp-trace/Input/Level1B.h"
  SearchPath: "D:/Clang/llvmnewmod/clang-tools-extra/test/pp-trace"
  RelativePath: "Input/Level1B.h"
  Imported: (null)
```

#### [moduleImport](https://clang.llvm.org/doxygen/classclang_1_1PPCallbacks.html#af32dcf1b8b7c179c7fcd3e24e89830fe) Callback

moduleImport is called when there was an explicit module-import syntax.

Argument descriptions:

| Argument Name | Argument Value Syntax   | Clang C++ Type | Description                                                 |
| ------------- | ----------------------- | -------------- | ----------------------------------------------------------- |
| ImportLoc     | "(file):(line):(col)"   | SourceLocation | The location of import directive token.                     |
| Path          | "(path)"                | ModuleIdPath   | The identifiers (and their locations) of the module "path". |
| Imported      | ((module name)\|(null)) | const Module   | The imported module; can be null if importing failed.       |

Example:

```yaml
- Callback: moduleImport
  ImportLoc: "d:/Clang/llvm/clang-tools-extra/test/pp-trace/pp-trace-modules.cpp:4:2"
  Path: [{Name: Level1B, Loc: "d:/Clang/llvmnewmod/clang-tools-extra/test/pp-trace/pp-trace-modules.cpp:4:9"}, {Name: Level2B, Loc: "d:/Clang/llvmnewmod/clang-tools-extra/test/pp-trace/pp-trace-modules.cpp:4:17"}]
  Imported: Level2B
```

#### [EndOfMainFile](https://clang.llvm.org/doxygen/classclang_1_1PPCallbacks.html#a63e170d069e99bc1c9c7ea0f3bed8bcc) Callback

EndOfMainFile is called when the end of the main file is reached.

Argument descriptions:

| Argument Name  | Argument Value Syntax | Clang C++ Type | Description |
| -------------- | --------------------- | -------------- | ----------- |
| (no arguments) |                       |                |             |

Example:

```yaml
- Callback: EndOfMainFile
```

#### [Ident](https://clang.llvm.org/doxygen/classclang_1_1PPCallbacks.html#a3683f1d1fa513e9b6193d446a5cc2b66) Callback

Ident is called when a #ident or #sccs directive is read.

Argument descriptions:

| Argument Name | Argument Value Syntax | Clang C++ Type    | Description                    |
| ------------- | --------------------- | ----------------- | ------------------------------ |
| Loc           | "(file):(line):(col)" | SourceLocation    | The location of the directive. |
| str           | (name)                | const std::string | The text of the directive.     |

Example:

```yaml
- Callback: Ident
  Loc: "D:/Clang/llvm/clang-tools-extra/test/pp-trace/pp-trace-ident.cpp:3:1"
  str: "$Id$"
```

#### [PragmaDirective](https://clang.llvm.org/doxygen/classclang_1_1PPCallbacks.html#a0a2d7a72c62184b3cbde31fb62c6f2f7) Callback

PragmaDirective is called when start reading any pragma directive.

Argument descriptions:

| Argument Name | Argument Value Syntax                            | Clang C++ Type       | Description                       |
| ------------- | ------------------------------------------------ | -------------------- | --------------------------------- |
| Loc           | "(file):(line):(col)"                            | SourceLocation       | The location of the directive.    |
| Introducer    | (PIK_HashPragma\|PIK\_\_Pragma\|PIK\_\_\_pragma) | PragmaIntroducerKind | The type of the pragma directive. |

Example:

```yaml
- Callback: PragmaDirective
  Loc: "D:/Clang/llvm/clang-tools-extra/test/pp-trace/pp-trace-pragma.cpp:3:1"
  Introducer: PIK_HashPragma
```

#### [PragmaComment](https://clang.llvm.org/doxygen/classclang_1_1PPCallbacks.html#ace0d940fc2c12ab76441466aab58dc37) Callback

PragmaComment is called when a #pragma comment directive is read.

Argument descriptions:

| Argument Name | Argument Value Syntax | Clang C++ Type       | Description                    |
| ------------- | --------------------- | -------------------- | ------------------------------ |
| Loc           | "(file):(line):(col)" | SourceLocation       | The location of the directive. |
| Kind          | ((name)\|(null))      | const IdentifierInfo | The comment kind symbol.       |
| Str           | (message directive)   | const std::string    | The comment message directive. |

Example:

```yaml
- Callback: PragmaComment
  Loc: "D:/Clang/llvm/clang-tools-extra/test/pp-trace/pp-trace-pragma.cpp:3:1"
  Kind: library
  Str: kernel32.lib
```

#### [PragmaDetectMismatch](https://clang.llvm.org/doxygen/classclang_1_1PPCallbacks.html#ab11158c9149fb8ad8af1903f4a6cd65d) Callback

PragmaDetectMismatch is called when a #pragma detect_mismatch directive is read.

Argument descriptions:

| Argument Name | Argument Value Syntax | Clang C++ Type    | Description                    |
| ------------- | --------------------- | ----------------- | ------------------------------ |
| Loc           | "(file):(line):(col)" | SourceLocation    | The location of the directive. |
| Name          | "(name)"              | const std::string | The name.                      |
| Value         | (string)              | const std::string | The value.                     |

Example:

```yaml
- Callback: PragmaDetectMismatch
  Loc: "D:/Clang/llvm/clang-tools-extra/test/pp-trace/pp-trace-pragma.cpp:3:1"
  Name: name
  Value: value
```

#### [PragmaDebug](https://clang.llvm.org/doxygen/classclang_1_1PPCallbacks.html#a57cdccb6dcc07e926513ac3d5b121466) Callback

PragmaDebug is called when a #pragma clang \_\_debug directive is read.

Argument descriptions:

| Argument Name | Argument Value Syntax | Clang C++ Type | Description                      |
| ------------- | --------------------- | -------------- | -------------------------------- |
| Loc           | "(file):(line):(col)" | SourceLocation | The location of the directive.   |
| DebugType     | (string)              | StringRef      | Indicates type of debug message. |

Example:

```yaml
- Callback: PragmaDebug
  Loc: "D:/Clang/llvm/clang-tools-extra/test/pp-trace/pp-trace-pragma.cpp:3:1"
  DebugType: warning
```

#### [PragmaMessage](https://clang.llvm.org/doxygen/classclang_1_1PPCallbacks.html#abb42935d9a9fd8e2c4f51cfdc4ea2ae1) Callback

PragmaMessage is called when a #pragma message directive is read.

Argument descriptions:

| Argument Name | Argument Value Syntax                 | Clang C++ Type                 | Description                             |
| ------------- | ------------------------------------- | ------------------------------ | --------------------------------------- |
| Loc           | "(file):(line):(col)"                 | SourceLocation                 | The location of the directive.          |
| Namespace     | (name)                                | StringRef                      | The namespace of the message directive. |
| Kind          | (PMK_Message\|PMK_Warning\|PMK_Error) | PPCallbacks::PragmaMessageKind | The type of the message directive.      |
| Str           | (string)                              | StringRef                      | The text of the message directive.      |

Example:

```yaml
- Callback: PragmaMessage
  Loc: "D:/Clang/llvm/clang-tools-extra/test/pp-trace/pp-trace-pragma.cpp:3:1"
  Namespace: "GCC"
  Kind: PMK_Message
  Str: The message text.
```

#### [PragmaDiagnosticPush](https://clang.llvm.org/doxygen/classclang_1_1PPCallbacks.html#a0f3ff19762baa38fe6c5c58022d32979) Callback

PragmaDiagnosticPush is called when a #pragma gcc diagnostic push directive is read.

Argument descriptions:

| Argument Name | Argument Value Syntax | Clang C++ Type | Description                    |
| ------------- | --------------------- | -------------- | ------------------------------ |
| Loc           | "(file):(line):(col)" | SourceLocation | The location of the directive. |
| Namespace     | (name)                | StringRef      | Namespace name.                |

Example:

```yaml
- Callback: PragmaDiagnosticPush
  Loc: "D:/Clang/llvm/clang-tools-extra/test/pp-trace/pp-trace-pragma.cpp:3:1"
  Namespace: "GCC"
```

#### [PragmaDiagnosticPop](https://clang.llvm.org/doxygen/classclang_1_1PPCallbacks.html#ac94d789873122221fba8d76f6c5ea45e) Callback

PragmaDiagnosticPop is called when a #pragma gcc diagnostic pop directive is read.

Argument descriptions:

| Argument Name | Argument Value Syntax | Clang C++ Type | Description                    |
| ------------- | --------------------- | -------------- | ------------------------------ |
| Loc           | "(file):(line):(col)" | SourceLocation | The location of the directive. |
| Namespace     | (name)                | StringRef      | Namespace name.                |

Example:

```yaml
- Callback: PragmaDiagnosticPop
  Loc: "D:/Clang/llvm/clang-tools-extra/test/pp-trace/pp-trace-pragma.cpp:3:1"
  Namespace: "GCC"
```

#### [PragmaDiagnostic](https://clang.llvm.org/doxygen/classclang_1_1PPCallbacks.html#afe7938f38a83cb7b4b25a13edfdd7bdd) Callback

PragmaDiagnostic is called when a #pragma gcc diagnostic directive is read.

Argument descriptions:

| Argument Name | Argument Value Syntax                              | Clang C++ Type | Description                    |
| ------------- | -------------------------------------------------- | -------------- | ------------------------------ |
| Loc           | "(file):(line):(col)"                              | SourceLocation | The location of the directive. |
| Namespace     | (name)                                             | StringRef      | Namespace name.                |
| mapping       | (0\|MAP_IGNORE\|MAP_WARNING\|MAP_ERROR\|MAP_FATAL) | diag::Severity | Mapping type.                  |
| Str           | (string)                                           | StringRef      | Warning/error name.            |

Example:

```yaml
- Callback: PragmaDiagnostic
  Loc: "D:/Clang/llvm/clang-tools-extra/test/pp-trace/pp-trace-pragma.cpp:3:1"
  Namespace: "GCC"
  mapping: MAP_WARNING
  Str: WarningName
```

#### [PragmaOpenCLExtension](https://clang.llvm.org/doxygen/classclang_1_1PPCallbacks.html#a92a20a21fadbab4e2c788f4e27fe07e7) Callback

PragmaOpenCLExtension is called when OpenCL extension is either disabled or enabled with a pragma.

Argument descriptions:

| Argument Name | Argument Value Syntax | Clang C++ Type       | Description                |
| ------------- | --------------------- | -------------------- | -------------------------- |
| NameLoc       | "(file):(line):(col)" | SourceLocation       | The location of the name.  |
| Name          | (name)                | const IdentifierInfo | Name symbol.               |
| StateLoc      | "(file):(line):(col)" | SourceLocation       | The location of the state. |
| State         | (1\|0)                | unsigned             | Enabled/disabled state.    |

Example:

```yaml
- Callback: PragmaOpenCLExtension
  NameLoc: "D:/Clang/llvm/clang-tools-extra/test/pp-trace/pp-trace-pragma.cpp:3:10"
  Name: Name
  StateLoc: "D:/Clang/llvm/clang-tools-extra/test/pp-trace/pp-trace-pragma.cpp:3:18"
  State: 1
```

#### [PragmaWarning](https://clang.llvm.org/doxygen/classclang_1_1PPCallbacks.html#aa17169d25fa1cf0a6992fc944d1d8730) Callback

PragmaWarning is called when a #pragma warning directive is read.

Argument descriptions:

| Argument Name | Argument Value Syntax | Clang C++ Type | Description                    |
| ------------- | --------------------- | -------------- | ------------------------------ |
| Loc           | "(file):(line):(col)" | SourceLocation | The location of the directive. |
| WarningSpec   | (string)              | StringRef      | The warning specifier.         |
| Ids           | \[(number)[, ...]\]   | ArrayRef\<int> | The warning numbers.           |

Example:

```yaml
- Callback: PragmaWarning
  Loc: "D:/Clang/llvm/clang-tools-extra/test/pp-trace/pp-trace-pragma.cpp:3:1"
  WarningSpec: disable
  Ids: 1,2,3
```

#### [PragmaWarningPush](https://clang.llvm.org/doxygen/classclang_1_1PPCallbacks.html#ae5626ef70502687a859f323a809ed0b6) Callback

PragmaWarningPush is called when a #pragma warning(push) directive is read.

Argument descriptions:

| Argument Name | Argument Value Syntax | Clang C++ Type | Description                    |
| ------------- | --------------------- | -------------- | ------------------------------ |
| Loc           | "(file):(line):(col)" | SourceLocation | The location of the directive. |
| Level         | (number)              | int            | Warning level.                 |

Example:

```yaml
- Callback: PragmaWarningPush
  Loc: "D:/Clang/llvm/clang-tools-extra/test/pp-trace/pp-trace-pragma.cpp:3:1"
  Level: 1
```

#### [PragmaWarningPop](https://clang.llvm.org/doxygen/classclang_1_1PPCallbacks.html#ac98d502af8811b8a6e7342d7cd2b3b95) Callback

PragmaWarningPop is called when a #pragma warning(pop) directive is read.

Argument descriptions:

| Argument Name | Argument Value Syntax | Clang C++ Type | Description                    |
| ------------- | --------------------- | -------------- | ------------------------------ |
| Loc           | "(file):(line):(col)" | SourceLocation | The location of the directive. |

Example:

```yaml
- Callback: PragmaWarningPop
  Loc: "D:/Clang/llvm/clang-tools-extra/test/pp-trace/pp-trace-pragma.cpp:3:1"
```

#### [MacroExpands](https://clang.llvm.org/doxygen/classclang_1_1PPCallbacks.html#a9bc725209d3a071ea649144ab996d515) Callback

MacroExpands is called when ::HandleMacroExpandedIdentifier when a macro invocation is found.

Argument descriptions:

| Argument Name  | Argument Value Syntax                          | Clang C++ Type       | Description                                                                                            |
| -------------- | ---------------------------------------------- | -------------------- | ------------------------------------------------------------------------------------------------------ |
| MacroNameTok   | (token)                                        | const Token          | The macro name token.                                                                                  |
| MacroDirective | (MD_Define\|MD_Undefine\|MD_Visibility)        | const MacroDirective | The kind of macro directive from the MacroDirective structure.                                         |
| Range          | ["(file):(line):(col)", "(file):(line):(col)"] | SourceRange          | The source range for the expansion.                                                                    |
| Args           | \[(name)\|(number)\|\<(token name)>[, ...]\]   | const MacroArgs      | The argument tokens. Names and numbers are literal, everything else is of the form '\<' tokenName '>'. |

Example:

```yaml
- Callback: MacroExpands
  MacroNameTok: X_IMPL
  MacroDirective: MD_Define
  Range: [(nonfile), (nonfile)]
  Args: [a <plus> y, b]
```

#### [MacroDefined](https://clang.llvm.org/doxygen/classclang_1_1PPCallbacks.html#a8448fc9f96f22ad1b93ff393cffc5a76) Callback

MacroDefined is called when a macro definition is seen.

Argument descriptions:

| Argument Name  | Argument Value Syntax                   | Clang C++ Type       | Description                                                    |
| -------------- | --------------------------------------- | -------------------- | -------------------------------------------------------------- |
| MacroNameTok   | (token)                                 | const Token          | The macro name token.                                          |
| MacroDirective | (MD_Define\|MD_Undefine\|MD_Visibility) | const MacroDirective | The kind of macro directive from the MacroDirective structure. |

Example:

```yaml
- Callback: MacroDefined
  MacroNameTok: X_IMPL
  MacroDirective: MD_Define
```

#### [MacroUndefined](https://clang.llvm.org/doxygen/classclang_1_1PPCallbacks.html#acb80fc6171a839db8e290945bf2c9d7a) Callback

MacroUndefined is called when a macro #undef is seen.

Argument descriptions:

| Argument Name  | Argument Value Syntax                   | Clang C++ Type       | Description                                                    |
| -------------- | --------------------------------------- | -------------------- | -------------------------------------------------------------- |
| MacroNameTok   | (token)                                 | const Token          | The macro name token.                                          |
| MacroDirective | (MD_Define\|MD_Undefine\|MD_Visibility) | const MacroDirective | The kind of macro directive from the MacroDirective structure. |

Example:

```yaml
- Callback: MacroUndefined
  MacroNameTok: X_IMPL
  MacroDirective: MD_Define
```

#### [Defined](https://clang.llvm.org/doxygen/classclang_1_1PPCallbacks.html#a3cc2a644533d0e4088a13d2baf90db94) Callback

Defined is called when the 'defined' operator is seen.

Argument descriptions:

| Argument Name  | Argument Value Syntax                          | Clang C++ Type       | Description                                                    |
| -------------- | ---------------------------------------------- | -------------------- | -------------------------------------------------------------- |
| MacroNameTok   | (token)                                        | const Token          | The macro name token.                                          |
| MacroDirective | (MD_Define\|MD_Undefine\|MD_Visibility)        | const MacroDirective | The kind of macro directive from the MacroDirective structure. |
| Range          | ["(file):(line):(col)", "(file):(line):(col)"] | SourceRange          | The source range for the directive.                            |

Example:

```yaml
- Callback: Defined
  MacroNameTok: MACRO
  MacroDirective: (null)
  Range: ["D:/Clang/llvm/clang-tools-extra/test/pp-trace/pp-trace-macro.cpp:8:5", "D:/Clang/llvm/clang-tools-extra/test/pp-trace/pp-trace-macro.cpp:8:19"]
```

#### [SourceRangeSkipped](https://clang.llvm.org/doxygen/classclang_1_1PPCallbacks.html#abdb4ebe11610f079ac33515965794b46) Callback

SourceRangeSkipped is called when a source range is skipped.

Argument descriptions:

| Argument Name | Argument Value Syntax                          | Clang C++ Type | Description               |
| ------------- | ---------------------------------------------- | -------------- | ------------------------- |
| Range         | ["(file):(line):(col)", "(file):(line):(col)"] | SourceRange    | The source range skipped. |

Example:

```yaml
- Callback: SourceRangeSkipped
  Range: [":/Clang/llvm/clang-tools-extra/test/pp-trace/pp-trace-macro.cpp:8:2", ":/Clang/llvm/clang-tools-extra/test/pp-trace/pp-trace-macro.cpp:9:2"]
```

#### [If](https://clang.llvm.org/doxygen/classclang_1_1PPCallbacks.html#a645edcb0d6becbc6f256f02fd1287778) Callback

If is called when an #if is seen.

Argument descriptions:

| Argument Name  | Argument Value Syntax                          | Clang C++ Type | Description                         |
| -------------- | ---------------------------------------------- | -------------- | ----------------------------------- |
| Loc            | "(file):(line):(col)"                          | SourceLocation | The location of the directive.      |
| ConditionRange | ["(file):(line):(col)", "(file):(line):(col)"] | SourceRange    | The source range for the condition. |
| ConditionValue | (true\|false)                                  | bool           | The condition value.                |

Example:

```yaml
- Callback: If
  Loc: "D:/Clang/llvm/clang-tools-extra/test/pp-trace/pp-trace-macro.cpp:8:2"
  ConditionRange: ["D:/Clang/llvm/clang-tools-extra/test/pp-trace/pp-trace-macro.cpp:8:4", "D:/Clang/llvm/clang-tools-extra/test/pp-trace/pp-trace-macro.cpp:9:1"]
  ConditionValue: false
```

#### [Elif](https://clang.llvm.org/doxygen/classclang_1_1PPCallbacks.html#a180c9e106a28d60a6112e16b1bb8302a) Callback

Elif is called when an #elif is seen.

Argument descriptions:

| Argument Name  | Argument Value Syntax                          | Clang C++ Type | Description                         |
| -------------- | ---------------------------------------------- | -------------- | ----------------------------------- |
| Loc            | "(file):(line):(col)"                          | SourceLocation | The location of the directive.      |
| ConditionRange | ["(file):(line):(col)", "(file):(line):(col)"] | SourceRange    | The source range for the condition. |
| ConditionValue | (true\|false)                                  | bool           | The condition value.                |
| IfLoc          | "(file):(line):(col)"                          | SourceLocation | The location of the directive.      |

Example:

```yaml
- Callback: Elif
  Loc: "D:/Clang/llvm/clang-tools-extra/test/pp-trace/pp-trace-macro.cpp:10:2"
  ConditionRange: ["D:/Clang/llvm/clang-tools-extra/test/pp-trace/pp-trace-macro.cpp:10:4", "D:/Clang/llvm/clang-tools-extra/test/pp-trace/pp-trace-macro.cpp:11:1"]
  ConditionValue: false
  IfLoc: "D:/Clang/llvm/clang-tools-extra/test/pp-trace/pp-trace-macro.cpp:8:2"
```

#### [Ifdef](https://clang.llvm.org/doxygen/classclang_1_1PPCallbacks.html#a0ce79575dda307784fd51a6dd4eec33d) Callback

Ifdef is called when an #ifdef is seen.

Argument descriptions:

| Argument Name  | Argument Value Syntax                   | Clang C++ Type       | Description                                                    |
| -------------- | --------------------------------------- | -------------------- | -------------------------------------------------------------- |
| Loc            | "(file):(line):(col)"                   | SourceLocation       | The location of the directive.                                 |
| MacroNameTok   | (token)                                 | const Token          | The macro name token.                                          |
| MacroDirective | (MD_Define\|MD_Undefine\|MD_Visibility) | const MacroDirective | The kind of macro directive from the MacroDirective structure. |

Example:

```yaml
- Callback: Ifdef
  Loc: "D:/Clang/llvm/clang-tools-extra/test/pp-trace/pp-trace-conditional.cpp:3:1"
  MacroNameTok: MACRO
  MacroDirective: MD_Define
```

#### [Ifndef](https://clang.llvm.org/doxygen/classclang_1_1PPCallbacks.html#a767af69f1cdcc4cd880fa2ebf77ad3ad) Callback

Ifndef is called when an #ifndef is seen.

Argument descriptions:

| Argument Name  | Argument Value Syntax                   | Clang C++ Type       | Description                                                    |
| -------------- | --------------------------------------- | -------------------- | -------------------------------------------------------------- |
| Loc            | "(file):(line):(col)"                   | SourceLocation       | The location of the directive.                                 |
| MacroNameTok   | (token)                                 | const Token          | The macro name token.                                          |
| MacroDirective | (MD_Define\|MD_Undefine\|MD_Visibility) | const MacroDirective | The kind of macro directive from the MacroDirective structure. |

Example:

```yaml
- Callback: Ifndef
  Loc: "D:/Clang/llvm/clang-tools-extra/test/pp-trace/pp-trace-conditional.cpp:3:1"
  MacroNameTok: MACRO
  MacroDirective: MD_Define
```

#### [Else](https://clang.llvm.org/doxygen/classclang_1_1PPCallbacks.html#ad57f91b6d9c3cbcca326a2bfb49e0314) Callback

Else is called when an #else is seen.

Argument descriptions:

| Argument Name | Argument Value Syntax | Clang C++ Type | Description                         |
| ------------- | --------------------- | -------------- | ----------------------------------- |
| Loc           | "(file):(line):(col)" | SourceLocation | The location of the else directive. |
| IfLoc         | "(file):(line):(col)" | SourceLocation | The location of the if directive.   |

Example:

```yaml
- Callback: Else
  Loc: "D:/Clang/llvm/clang-tools-extra/test/pp-trace/pp-trace-macro.cpp:10:2"
  IfLoc: "D:/Clang/llvm/clang-tools-extra/test/pp-trace/pp-trace-macro.cpp:8:2"
```

#### [Endif](https://clang.llvm.org/doxygen/classclang_1_1PPCallbacks.html#afc62ca1401125f516d58b1629a2093ce) Callback

Endif is called when an #endif is seen.

Argument descriptions:

| Argument Name | Argument Value Syntax | Clang C++ Type | Description                          |
| ------------- | --------------------- | -------------- | ------------------------------------ |
| Loc           | "(file):(line):(col)" | SourceLocation | The location of the endif directive. |
| IfLoc         | "(file):(line):(col)" | SourceLocation | The location of the if directive.    |

Example:

```yaml
- Callback: Endif
  Loc: "D:/Clang/llvm/clang-tools-extra/test/pp-trace/pp-trace-macro.cpp:10:2"
  IfLoc: "D:/Clang/llvm/clang-tools-extra/test/pp-trace/pp-trace-macro.cpp:8:2"
```

## Building pp-trace

To build from source:

1. Read [Getting Started with the LLVM System][getting started with the llvm system] and [Clang Tools
   Documentation][clang tools documentation] for information on getting sources for LLVM, Clang, and
   Clang Extra Tools.

2. [Getting Started with the LLVM System][getting started with the llvm system] and [Building LLVM with CMake][building llvm with cmake] give
   directions for how to build. With sources all checked out into the
   right place the LLVM build will build Clang Extra Tools and their
   dependencies automatically.

   - If using CMake, you can also use the `pp-trace` target to build
     just the pp-trace tool and its dependencies.

[building llvm with cmake]: https://llvm.org/docs/CMake.html
[clang tools documentation]: https://clang.llvm.org/docs/ClangTools.html
[getting started with the llvm system]: https://llvm.org/docs/GettingStarted.html

---

### Clang Docs AMDGPUSupport (`clang/docs/AMDGPUSupport.md`)

# AMDGPU Support

Clang supports OpenCL, HIP and OpenMP on AMD GPU targets.

## Predefined Macros

| Macro | Description |
| --- | --- |
| `__AMDGPU__` | Indicates that the code is being compiled for an AMD GPU. |
| `__AMDGCN__` | Defined if the GPU target is AMDGCN. |
| `__R600__` | Defined if the GPU target is R600. |
| `__<ArchName>__` | Defined with the name of the architecture (e.g., `__gfx906__` for the gfx906 architecture). |
| `__<GFXN>__` | Defines the GFX family (e.g., for gfx906, this macro would be `__GFX9__`). |
| `__amdgcn_processor__` | Defined with the processor name as a string (e.g., `"gfx906"`). |
| `__amdgcn_target_id__` | Defined with the target ID as a string. |
| `__amdgcn_feature_<feature-name>__` | Defined for each supported target feature. The value is 1 if the feature is enabled and 0 if it is disabled. Allowed feature names are sramecc and xnack. |
| `__AMDGCN_CUMODE__` | Defined as 1 if the CU mode is enabled and 0 if the WGP mode is enabled. |
| `__AMDGCN_UNSAFE_FP_ATOMICS__` | Defined if unsafe floating-point atomics are allowed. |
| `__HAS_FMAF__` | Defined if FMAF instruction is available (deprecated). |
| `__HAS_LDEXPF__` | Defined if LDEXPF instruction is available (deprecated). |
| `__HAS_FP64__` | Defined if FP64 instruction is available (deprecated). |

Please note that the specific architecture and feature names will vary depending on the GPU. Also, some macros are deprecated and may be removed in future releases.

## Target-Specific Builtins

Clang exposes AMDGPU hardware intrinsics as target-specific builtins with the
`__builtin_amdgcn_` prefix. These are documented in {doc}`AMDGPUBuiltinReference`.

## Target-Specific Types

### Named Workgroup Barrier Type

The `__amdgpu_named_workgroup_barrier_t` type is used to represent the GFX12.5 named barriers.

This type is subject to certain restrictions when used to declare non-static fields of classes.
See the {ref}`named barrier wrappers<namedbarrierwrappers>` section below for more information.

Example usage:

```c
__amdgpu_named_workgroup_barrier_t x;
__amdgpu_named_workgroup_barrier_t arr[2]; // Arrays are also fine

struct SimpleWrapper {
  __amdgpu_named_workgroup_barrier_t foo;
};

void foo(int a)
{
  __builtin_amdgcn_s_barrier_init(&x, a);
}
```

(namedbarrierwrappers)=
### Named Barrier Wrappers

A "named barrier wrapper" is a class that contains exactly one non-static field
of one of the following types:

* `__amdgpu_named_workgroup_barrier_t`, or an array thereof.
* Another named barrier wrapper, or an array thereof.

In C++, a class that inherits from a named barrier wrapper is also considered a
named barrier wrapper, and all named barrier wrappers must be standard-layout
types (see `std::is_standard_layout`). This means that named barrier wrappers:

* May not have a virtual table: they cannot declare or inherit any virtual
  functions, or inherit from a virtual base class.
* May not have any extra fields, either declared by the class or inherited
  from a base class.

---

### Clang Docs APINotes (`clang/docs/APINotes.md`)

# API Notes: Annotations Without Modifying Headers

**The Problem:** You have headers you want to use, but you also want to add
extra information to the API. You don't want to put that information in the
headers themselves --- perhaps because you want to keep them clean for other
clients, or perhaps because they're from some open source project and you don't
want to modify them at all.

**Incomplete solution:** Redeclare all the interesting parts of the API in your
own header and add the attributes you want. Unfortunately, this:

- doesn't work with attributes that must be present on a definition
- doesn't allow changing the definition in other ways
- requires your header to be included in any client code to take effect

**Better solution:** Provide a "sidecar" file with the information you want to
add, and have that automatically get picked up by the module-building logic in
the compiler.

That's API notes.

API notes use a YAML-based file format. YAML is a format best explained by
example, so here is a [small example](https://github.com/llvm/llvm-project/blob/main/clang/test/APINotes/Inputs/Frameworks/SomeKit.framework/Headers/SomeKit.apinotes)
from the compiler test suite of API
notes for a hypothetical "SomeKit" framework.

## Usage

API notes files are found relative to the module map that defines a module,
under the name "SomeKit.apinotes" for a module named "SomeKit". Additionally, a
file named "SomeKit_private.apinotes" will also be picked up to go with a
private module map. For bare modules these two files will be in the same
directory as the corresponding module map; for framework modules, they should
be placed in the Headers and PrivateHeaders directories, respectively. The
module map for a private top-level framework module should be placed in the
PrivateHeaders directory as well, though it does not need an additional
"_private" suffix on its name.

Clang will search for API notes files next to module maps only when passed the
`-fapinotes-modules` option.

## Limitations

- Since they're identified by module name, API notes cannot be used to modify
  arbitrary textual headers.

## "Versioned" API Notes

Many API notes affect how a C API is imported into Swift. In order to change
that behavior while still remaining backwards-compatible, API notes can be
selectively applied based on the Swift compatibility version provided to the
compiler (e.g. `-fapi-notes-swift-version=5`). The rule is that an
explicitly-versioned API note applies to that version *and all earlier
versions,* and any applicable explicitly-versioned API note takes precedence
over an unversioned API note.

## Reference

An API notes file contains a YAML dictionary with the following top-level
entries:

```
/* Detailed source-code truncated for AI context efficiency. */
```

---

### Clang Docs AddressSanitizer (`clang/docs/AddressSanitizer.md`)

# AddressSanitizer


## Introduction

AddressSanitizer is a fast memory error detector. It consists of a compiler
instrumentation module and a run-time library. The tool can detect the
following types of bugs:

- Out-of-bounds accesses to heap, stack and globals
- Use-after-free
- Use-after-return (clang flag `-fsanitize-address-use-after-return=(never|runtime|always)` default: `runtime`)
  :   - Enable with: `ASAN_OPTIONS=detect_stack_use_after_return=1` (already enabled on Linux).
      - Disable with: `ASAN_OPTIONS=detect_stack_use_after_return=0`.
- Use-after-scope (clang flag `-fsanitize-address-use-after-scope`)
- Double-free, invalid free
- Memory leaks (experimental)

Typical slowdown introduced by AddressSanitizer is **2x**.

## How to build

Build LLVM/Clang with [CMake](https://llvm.org/docs/CMake.html) and enable
the `compiler-rt` runtime. An example CMake configuration that will allow
for the use/testing of AddressSanitizer:

```console
$ cmake -DCMAKE_BUILD_TYPE=Release -DLLVM_ENABLE_PROJECTS="clang" -DLLVM_ENABLE_RUNTIMES="compiler-rt" <path to source>/llvm
```

## Usage

Simply compile and link your program with `-fsanitize=address` flag. The
AddressSanitizer run-time library should be linked to the final executable, so
make sure to use `clang` (not `ld`) for the final link step. When linking
shared libraries, the AddressSanitizer run-time is not linked, so
`-Wl,-z,defs` may cause link errors (don't use it with AddressSanitizer). To
get a reasonable performance add `-O1` or higher. To get nicer stack traces
in error messages add `-fno-omit-frame-pointer`. To get perfect stack traces
you may need to disable inlining (just use `-O1`) and tail call elimination
(`-fno-optimize-sibling-calls`).

```console
% cat example_UseAfterFree.cc
int main(int argc, char **argv) {
  int *array = new int[100];
  delete [] array;
  return array[argc];  // BOOM
}

# Compile and link
% clang++ -O1 -g -fsanitize=address -fno-omit-frame-pointer example_UseAfterFree.cc
```

or:

```console
# Compile
% clang++ -O1 -g -fsanitize=address -fno-omit-frame-pointer -c example_UseAfterFree.cc
# Link
% clang++ -g -fsanitize=address example_UseAfterFree.o
```

If a bug is detected, the program will print an error message to stderr and
exit with a non-zero exit code. AddressSanitizer exits on the first detected error.
This is by design:

- This approach allows AddressSanitizer to produce faster and smaller generated code
  (both by ~5%).
- Fixing bugs becomes unavoidable. AddressSanitizer does not produce
  false alarms. Once a memory corruption occurs, the program is in an inconsistent
  state, which could lead to confusing results and potentially misleading
  subsequent reports.

If your process is sandboxed and you are running on OS X 10.10 or earlier, you
will need to set `DYLD_INSERT_LIBRARIES` environment variable and point it to
the ASan library that is packaged with the compiler used to build the
executable. (You can find the library by searching for dynamic libraries with
`asan` in their name.) If the environment variable is not set, the process will
try to re-exec. Also keep in mind that when moving the executable to another machine,
the ASan library will also need to be copied over.

## Symbolizing the Reports

To make AddressSanitizer symbolize its output
you need to set the `ASAN_SYMBOLIZER_PATH` environment variable to point to
the `llvm-symbolizer` binary (or make sure `llvm-symbolizer` is in your
`$PATH`):

```console
% ASAN_SYMBOLIZER_PATH=/usr/local/bin/llvm-symbolizer ./a.out
==9442== ERROR: AddressSanitizer heap-use-after-free on address 0x7f7ddab8c084 at pc 0x403c8c bp 0x7fff87fb82d0 sp 0x7fff87fb82c8
READ of size 4 at 0x7f7ddab8c084 thread T0
    #0 0x403c8c in main example_UseAfterFree.cc:4
    #1 0x7f7ddabcac4d in __libc_start_main ??:0
0x7f7ddab8c084 is located 4 bytes inside of 400-byte region [0x7f7ddab8c080,0x7f7ddab8c210)
freed by thread T0 here:
    #0 0x404704 in operator delete[](void*) ??:0
    #1 0x403c53 in main example_UseAfterFree.cc:4
    #2 0x7f7ddabcac4d in __libc_start_main ??:0
previously allocated by thread T0 here:
    #0 0x404544 in operator new[](unsigned long) ??:0
    #1 0x403c43 in main example_UseAfterFree.cc:2
    #2 0x7f7ddabcac4d in __libc_start_main ??:0
==9442== ABORTING
```

If that does not work for you (e.g. your process is sandboxed), you can use a
separate script to symbolize the result offline (online symbolization can be
force disabled by setting `ASAN_OPTIONS=symbolize=0`):

```console
% ASAN_OPTIONS=symbolize=0 ./a.out 2> log
% projects/compiler-rt/lib/asan/scripts/asan_symbolize.py / < log | c++filt
==9442== ERROR: AddressSanitizer heap-use-after-free on address 0x7f7ddab8c084 at pc 0x403c8c bp 0x7fff87fb82d0 sp 0x7fff87fb82c8
READ of size 4 at 0x7f7ddab8c084 thread T0
    #0 0x403c8c in main example_UseAfterFree.cc:4
    #1 0x7f7ddabcac4d in __libc_start_main ??:0
...
```

Note that on macOS you may need to run `dsymutil` on your binary to have the
file:line info in the AddressSanitizer reports.

## Additional Checks

### Initialization order checking

AddressSanitizer can optionally detect dynamic initialization order problems,
when initialization of globals defined in one translation unit uses
globals defined in another translation unit. To enable this check at runtime,
you should set environment variable
`ASAN_OPTIONS=check_initialization_order=1`.

Note that this option is not supported on macOS.

### Stack Use After Return (UAR)

AddressSanitizer can optionally detect stack use after return problems.
This is available by default, or explicitly
(`-fsanitize-address-use-after-return=runtime`).
To disable this check at runtime, set the environment variable
`ASAN_OPTIONS=detect_stack_use_after_return=0`.

Enabling this check (`-fsanitize-address-use-after-return=always`) will
reduce code size. The code size may be reduced further by completely
eliminating this check (`-fsanitize-address-use-after-return=never`).

To summarize: `-fsanitize-address-use-after-return=<mode>`
:   - `never`: Completely disables detection of UAR errors (reduces code size).
    - `runtime`: Adds the code for detection, but it can be disabled via the
      runtime environment (`ASAN_OPTIONS=detect_stack_use_after_return=0`).
    - `always`: Enables detection of UAR errors in all cases. (reduces code
      size, but not as much as `never`).

### Container Overflow Detection

AddressSanitizer can detect overflows in containers with custom allocators
(such as std::vector) where the library developers have added calls into the
AddressSanitizer runtime to indicate which memory is poisoned etc.

Note that this feature is prone to false positives:
:   - Partially poisoning objects on stack, e.g. for small string optimization, can
      cause both false positives and negatives.
    - If the binary is partially AddressSanitizer instrumented, these
      checks can cause false positives.

See [Disabling container overflow checks](#disabling-container-overflow-checks) for details on suppressing checks.

### Memory leak detection

For more information on leak detector in AddressSanitizer, see
{doc}`LeakSanitizer`. The leak detection is turned on by default on Linux,
and can be enabled using `ASAN_OPTIONS=detect_leaks=1` on macOS;
however, it is not yet supported on other platforms.

## Flags and Options

Runtime flags can be passed to AddressSanitizer via the `ASAN_OPTIONS` environment
variable:

```console
$ ASAN_OPTIONS="verbosity=1:detect_stack_use_after_return=1" ./a.out
```

To see the full list of available flags, run an instrumented binary with
`ASAN_OPTIONS="help=1"`.

Flags passed via the `ASAN_OPTIONS` environment variable take precedence over
compile-time default options.

### Compile-time Default Options

Default options can be specified at compile/link time by defining
the `__asan_default_options` function in your source code:

```c++
#include <sanitizer/asan_interface.h>

extern "C" const char *__asan_default_options() {
  return "verbosity=1:detect_stack_use_after_return=1";
}
```

### Options Evaluation with Integrated Sanitizers

When running AddressSanitizer with integrated {doc}`LeakSanitizer` or {doc}`UndefinedBehaviorSanitizer`:

- `__asan_default_options()`, `__lsan_default_options()`, and `__ubsan_default_options()` are all evaluated independently by the runtime.
- The environment variables `ASAN_OPTIONS`, `LSAN_OPTIONS`, and `UBSAN_OPTIONS` are also parsed independently.

LSan and UBSan flags should be passed via their own environment variables (`LSAN_OPTIONS`, `UBSAN_OPTIONS`) or default option hooks (`__lsan_default_options()`, `__ubsan_default_options()`) rather than packed into `ASAN_OPTIONS` or `__asan_default_options()`.

## Issue Suppression

AddressSanitizer is not expected to produce false positives. If you see one,
look again; most likely it is a true positive!

### Suppressing Reports in External Libraries

Runtime interposition allows AddressSanitizer to find bugs in code that is
not being recompiled. If you run into an issue in external libraries, we
recommend immediately reporting it to the library maintainer so that it
gets addressed. However, you can use the following suppression mechanism
to unblock yourself and continue on with the testing. This suppression
mechanism should only be used for suppressing issues in external code; it
does not work on code recompiled with AddressSanitizer. To suppress errors
in external libraries, set the `ASAN_OPTIONS` environment variable to point
to a suppression file. You can either specify the full path to the file or the
path of the file relative to the location of your executable.

```bash
ASAN_OPTIONS=suppressions=MyASan.supp
```

Each non-empty line of the suppression file represents one suppression of the
form `suppression_type:suppression_pattern`. Supported types are:

- `interceptor_via_fun`: Suppress errors when the given function is in the caller stack trace.
- `interceptor_via_lib`: Suppress errors when the call originates from the given library.
- `interceptor_name`: Suppress an interceptor by function name directly (e.g., `interceptor_name:memcpy`).
- `odr_violation`: Suppress One Definition Rule violation reports for global variables.
- `alloc_dealloc_mismatch`: Suppress allocation/deallocation mismatch errors for specific functions in the stack trace.

```bash
interceptor_via_fun:NameOfCFunctionToSuppress
interceptor_via_fun:-[ClassName objCMethodToSuppress:]
interceptor_via_lib:NameOfTheLibraryToSuppress
interceptor_name:memcpy
odr_violation:my_global_var
alloc_dealloc_mismatch:my_allocator_fn
```

Alternatively, you can provide default suppressions at compile time by defining
the `__asan_default_suppressions` function in your source code:

```c++
#include <sanitizer/asan_interface.h>

extern "C" const char *__asan_default_suppressions() {
  return "interceptor_via_lib:NameOfTheLibraryToSuppress\n"
         "interceptor_name:memcpy\n";
}
```

### Conditional Compilation with `__has_feature(address_sanitizer)`

In some cases one may need to execute different code depending on whether
AddressSanitizer is enabled.
{ref}`__has_feature <langext-__has_feature-__has_extension>` can be used for
this purpose.

```c
#if defined(__has_feature)
#  if __has_feature(address_sanitizer)
// code that builds only under AddressSanitizer
#  endif
#endif
```

### Disabling Instrumentation with `__attribute__((no_sanitize("address")))`

Some code should not be instrumented by AddressSanitizer. One may use
the attribute `__attribute__((no_sanitize("address")))` (which has
deprecated synonyms `no_sanitize_address` and
`no_address_safety_analysis`) to disable instrumentation of a
particular function. This attribute may not be supported by other
compilers, so we suggest to use it together with
`__has_feature(address_sanitizer)`.

The same attribute used on a global variable prevents AddressSanitizer
from adding redzones around it and detecting out of bounds accesses.

AddressSanitizer also supports
`__attribute__((disable_sanitizer_instrumentation))`. This attribute
works similarly to `__attribute__((no_sanitize("address")))`, but it also
prevents instrumentation performed by other sanitizers.

### Interaction of Inlining with Disabling Sanitizer Instrumentation

- A `no_sanitize` function will not be inlined heuristically by the compiler into a sanitized function.
- An `always_inline` function will adopt the instrumentation status of the function it is inlined into.
- Forcibly combining `no_sanitize` and `__attribute__((always_inline))` is not supported, and will often lead to unexpected results. To avoid mixing these attributes, use:

```c
// Note, __has_feature test for sanitizers is deprecated, and Clang will support __SANITIZE_<sanitizer>__ similar to GCC.
#if __has_feature(address_sanitizer) || defined(__SANITIZE_ADDRESS__) || ... <other sanitizers>
#define ALWAYS_INLINE_IF_UNINSTRUMENTED
#else
#define ALWAYS_INLINE_IF_UNINSTRUMENTED __attribute__((always_inline))
#endif
```

### Explicit Sanitizer Checks with `__builtin_allow_sanitize_check`

The `__builtin_allow_sanitize_check("address")` builtin can be used to
conditionally execute code depending on whether AddressSanitizer checks are
enabled and permitted by the current policy (after inlining). This is
particularly useful for inserting explicit, sanitizer-specific checks around
operations like syscalls or inline assembly, which might otherwise be unchecked
by the sanitizer.

Example:

```c
void __asan_load8(void *);

inline __attribute__((always_inline))
void my_helper(void *addr) {
  if (__builtin_allow_sanitize_check("address"))
    __asan_load8(addr);
  // ... actual logic, e.g. inline assembly ...
  asm volatile ("..." : : "r" (addr) : "memory");
}

void instrumented_function() {
  ...
  my_helper(buf); // checks are active
  ...
}

__attribute__((no_sanitize("address")))
void uninstrumented_function() {
  ...
  my_helper(buf); // checks are skipped
  ...
}
```

### Disabling container overflow checks

#### Runtime suppression

Container overflow checks can be disabled at runtime using the
`ASAN_OPTIONS=detect_container_overflow=0` environment variable.

#### Compile time suppression

`-D__SANITIZER_DISABLE_CONTAINER_OVERFLOW__` can be used at compile time to
disable container overflow checks if the container library has added support
for this define.

To support a standard way to disable container overflow checks at compile time,
library developers should use this definition in conjunction with the
AddressSanitizer feature test to conditionally include container overflow
related code compiled into user code:

The recommended form is

```c
// include the sanitizer common interfaces
#include <sanitizer/common_interface_defs.h>

#if __has_feature(address_sanitizer)
// Container overflow detection enabled - include annotations
__sanitizer_annotate_contiguous_container(beg, end, old_mid, new_mid);
#endif
```

This pattern ensures that:

- Container overflow annotations are only included when AddressSanitizer is
  enabled
- Container overflow detection can be disabled by passing
  `-D__SANITIZER_DISABLE_CONTAINER_OVERFLOW__` to the compiler

### Suppressing Errors in Recompiled Code (Ignorelist)

AddressSanitizer supports `src` and `fun` entity types in
{doc}`SanitizerSpecialCaseList`, that can be used to suppress error reports
in the specified source files or functions. Additionally, AddressSanitizer
introduces `global` and `type` entity types that can be used to
suppress error reports for out-of-bound access to globals with certain
names and types (you may only specify class or struct types).

You may use an `init` category to suppress reports about initialization-order
problems happening in certain source files or with certain global variables.

```bash
# Suppress error reports for code in a file or in a function:
src:bad_file.cpp
# Ignore all functions with names containing MyFooBar:
fun:*MyFooBar*
# Disable out-of-bound checks for global:
global:bad_array
# Disable out-of-bound checks for global instances of a given class ...
type:Namespace::BadClassName
# ... or a given struct. Use wildcard to deal with anonymous namespace.
type:Namespace2::*::BadStructName
# Disable initialization-order checks for globals:
global:bad_init_global=init
type:*BadInitClassSubstring*=init
src:bad/init/files/*=init
```

### Suppressing memory leaks

Memory leak reports produced by {doc}`LeakSanitizer` (when run as part of
AddressSanitizer) can be suppressed at runtime via `LSAN_OPTIONS=suppressions=...`
or at compile time via `__lsan_default_suppressions()`. See {doc}`LeakSanitizer`
for full details on suppression rules, default options, and programmatic APIs.

## Code generation control

### Instrumentation code outlining

By default AddressSanitizer inlines the instrumentation code to improve the
run-time performance, which leads to increased binary size. Using the
(clang flag `-fsanitize-address-outline-instrumentation` default: `false`)
flag forces all code instrumentation to be outlined, which reduces the size
of the generated code, but also reduces the run-time performance.

## Limitations

- AddressSanitizer uses more real memory than a native run. Exact overhead
  depends on the allocation sizes. The smaller the allocations you make the
  bigger the overhead is.
- AddressSanitizer uses more stack memory. We have seen up to 3x increase.
- On 64-bit platforms AddressSanitizer maps (but not reserves) 16+ Terabytes of
  virtual address space. This means that tools like `ulimit` may not work as
  usually expected.
- Static linking of executables is not supported.

## Security Considerations

AddressSanitizer is a bug detection tool and its runtime is not meant to be
linked against production executables. While it may be useful for testing,
AddressSanitizer's runtime was not developed with security-sensitive
constraints in mind and may compromise the security of the resulting executable.

## Supported Platforms

AddressSanitizer is supported on:

- Linux
- macOS
- iOS Simulator
- Android
- NetBSD
- FreeBSD
- Windows 8.1+

## Current Status

AddressSanitizer is fully functional on supported platforms starting from LLVM
3.1. The test suite is integrated into CMake build and can be run with `make
check-asan` command.

The Windows port is functional and is used by Chrome and Firefox, but it is not
as well supported as the other ports.

## More Information

[https://github.com/google/sanitizers/wiki/AddressSanitizer](https://github.com/google/sanitizers/wiki/AddressSanitizer)

---

### Clang Docs AllocToken (`clang/docs/AllocToken.md`)

# Allocation Tokens


## Introduction

Clang provides support for allocation tokens to enable allocator-level heap
organization strategies. Clang assigns mode-dependent token IDs to allocation
calls; the runtime behavior depends entirely on the implementation of a
compatible memory allocator.

Possible allocator strategies include:

- **Security Hardening**: Placing allocations into separate, isolated heap
  partitions. For example, separating pointer-containing types from raw data
  can mitigate exploits that rely on overflowing a primitive buffer to corrupt
  object metadata.
- **Memory Layout Optimization**: Grouping related allocations to improve data
  locality and cache utilization.
- **Custom Allocation Policies**: Applying different management strategies to
  different partitions.

## Token Assignment Mode

The default mode to calculate tokens is:

- `typehashpointersplit`: This mode assigns a token ID based on the hash of
  the allocated type's name, where the top half ID-space is reserved for types
  that contain pointers and the bottom half for types that do not contain
  pointers.

Other token ID assignment modes are supported, but they may be subject to
change or removal. These may (experimentally) be selected with `-Xclang
-falloc-token-mode=<mode>`:

- `typehash`: This mode assigns a token ID based on the hash of the allocated
  type's name.
- `typefunchashpointersplit`: This mode assigns a token ID based on the hash of
  the allocated type's name and the hash of the name of the function containing
  the allocation. The upper half of the token ID bits is the type name hash,
  the lower half of the token ID bits is the function name hash, and the most
  significant bit is a flag indicating whether the type contains pointers.
- `typefunchash`: Like `typefunchashpointersplit`, but without the pointer flag.
- `random`: This mode assigns a statically-determined random token ID to each
  allocation site.
- `increment`: This mode assigns a simple, incrementally increasing token ID
  to each allocation site.

The following command-line options affect generated token IDs:

- `-falloc-token-max=<N>`
  : Configures the maximum number of token IDs. By default the number of tokens
    is bounded by `SIZE_MAX`.

    - In the `typefunchashpointersplit` and `typefunchash` modes, the number of
      token IDs is `N` rounded down to a power of two. As an exception, if `N`
      is of the form `2^k-1` (e.g. the default `SIZE_MAX`), all `k` bits are
      used and token IDs are in `[0, N]`, i.e. a token ID may be equal to `N`.

## Querying Token IDs with `__builtin_infer_alloc_token`

For use cases where the token ID must be known at compile time, Clang provides
a builtin function:

```c
size_t __builtin_infer_alloc_token(<args>, ...);
```

This builtin returns the token ID inferred from its argument expressions, which
mirror arguments normally passed to any allocation function. The argument
expressions are **unevaluated**, so it can be used with expressions that would
have side effects without any runtime impact. In the `typefunchashpointersplit`,
`typefunchash`, `random`, and `increment` modes, the builtin cannot be used in
constant expressions.

For example, it can be used as follows:

```c
struct MyType { ... };
void *__partition_alloc(size_t size, size_t partition);
#define partition_alloc(...) __partition_alloc(__VA_ARGS__, __builtin_infer_alloc_token(__VA_ARGS__))

void foo(void) {
    MyType *x = partition_alloc(sizeof(*x));
}
```

## Allocation Token Instrumentation

To enable instrumentation of allocation functions, code can be compiled with
the `-fsanitize=alloc-token` flag:

```console
% clang++ -fsanitize=alloc-token example.cc
```

The instrumentation transforms allocation calls to include a token ID. For
example:

```c
// Original:
ptr = malloc(size);

// Instrumented:
ptr = __alloc_token_malloc(size, <token id>);
```

### Runtime Interface

A compatible runtime must be provided that implements the token-enabled
allocation functions. The instrumentation generates calls to functions that
take a final `size_t token_id` argument.

```c
// C standard library functions
void *__alloc_token_malloc(size_t size, size_t token_id);
void *__alloc_token_calloc(size_t count, size_t size, size_t token_id);
void *__alloc_token_realloc(void *ptr, size_t size, size_t token_id);
// ...

// C++ operators (mangled names)
// operator new(size_t, size_t)
void *__alloc_token__Znwm(size_t size, size_t token_id);
// operator new[](size_t, size_t)
void *__alloc_token__Znam(size_t size, size_t token_id);
// ... other variants like nothrow, etc., are also instrumented.
```

### Fast ABI

An alternative ABI can be enabled with `-fsanitize-alloc-token-fast-abi`,
which encodes the token ID in the allocation function name.

```c
void *__alloc_token_0_malloc(size_t size);
void *__alloc_token_1_malloc(size_t size);
void *__alloc_token_2_malloc(size_t size);
...
void *__alloc_token_0_Znwm(size_t size);
void *__alloc_token_1_Znwm(size_t size);
void *__alloc_token_2_Znwm(size_t size);
...
```

This ABI provides a more efficient alternative where
`-falloc-token-max` is small.

### Instrumenting Non-Standard Allocation Functions

By default, AllocToken only instruments standard library allocation functions.
This simplifies adoption, as a compatible allocator only needs to provide
token-enabled variants for a well-defined set of standard functions.

To extend instrumentation to custom allocation functions, enable broader
coverage with `-fsanitize-alloc-token-extended`. Such functions require being
marked with the [malloc][malloc-attribute] or
[alloc_size][alloc-size-attribute] attributes
(or a combination).

For example:

```c
void *custom_malloc(size_t size) __attribute__((malloc));
void *my_malloc(size_t size) __attribute__((alloc_size(1)));

// Original:
ptr1 = custom_malloc(size);
ptr2 = my_malloc(size);

// Instrumented:
ptr1 = __alloc_token_custom_malloc(size, token_id);
ptr2 = __alloc_token_my_malloc(size, token_id);
```

Note: Even in the default mode (without `-fsanitize-alloc-token-extended`),
an *inline* allocation wrapper marked with the [malloc][malloc-attribute] or
[alloc_size][alloc-size-attribute] attribute is
supported if it is inlined into its caller: the inferred token is propagated to
the allocation call the wrapper returns, which is then instrumented normally.
Wrappers that are not inlined still require
`-fsanitize-alloc-token-extended`.

[malloc-attribute]: AttributeReference.md#malloc
[alloc-size-attribute]: AttributeReference.md#alloc-size

### Disabling Instrumentation

To exclude specific functions from instrumentation, you can use the
`no_sanitize("alloc-token")` attribute:

```c
__attribute__((no_sanitize("alloc-token")))
void* custom_allocator(size_t size) {
    return malloc(size);  // Uses original malloc
}
```

Note: Independent of any given allocator support, the instrumentation aims to
remain performance neutral. As such, `no_sanitize("alloc-token")`
functions may be inlined into instrumented functions and vice-versa. If
correctness is affected, such functions should explicitly be marked
`noinline`.

The `__attribute__((disable_sanitizer_instrumentation))` is also supported to
disable this and other sanitizer instrumentations.

### Suppressions File (Ignorelist)

AllocToken respects the `src` and `fun` entity types in the
{doc}`SanitizerSpecialCaseList`, which can be used to omit specified source
files or functions from instrumentation.

```bash
[alloc-token]
# Exclude specific source files
src:third_party/allocator.c
# Exclude function name patterns
fun:*custom_malloc*
fun:LowLevel::*
```

```console
% clang++ -fsanitize=alloc-token -fsanitize-ignorelist=my_ignorelist.txt example.cc
```

### Conditional Compilation with `__SANITIZE_ALLOC_TOKEN__`

In some cases, one may need to execute different code depending on whether
AllocToken instrumentation is enabled. The `__SANITIZE_ALLOC_TOKEN__` macro
can be used for this purpose.

```c
#ifdef __SANITIZE_ALLOC_TOKEN__
// Code specific to -fsanitize=alloc-token builds
#endif
```

---

### Clang Docs AutomaticReferenceCounting (`clang/docs/AutomaticReferenceCounting.md`)

% FIXME: move to the stylesheet or Sphinx plugin

```{raw} html
<style>
  .arc-term { font-style: italic; font-weight: bold; }
  .revision { font-style: italic; }
  .when-revised { font-weight: bold; font-style: normal; }

  /*
   * Automatic numbering is described in this article:
   * https://dev.opera.com/articles/view/automatic-numbering-with-css-counters/
   */
  /*
   * Automatic numbering for the TOC.
   * This is wrong from the semantics point of view, since it is an ordered
   * list, but uses "ul" tag.
   */
  div#contents.contents.local ul {
    counter-reset: toc-section;
    list-style-type: none;
  }
  div#contents.contents.local ul li {
    counter-increment: toc-section;
    background: none; // Remove bullets
  }
  div#contents.contents.local ul li a.reference:before {
    content: counters(toc-section, ".") " ";
  }

  /* Automatic numbering for the body. */
  body {
    counter-reset: section subsection subsubsection;
  }
  .section h2 {
    counter-reset: subsection subsubsection;
    counter-increment: section;
  }
  .section h2 a.toc-backref:before {
    content: counter(section) " ";
  }
  .section h3 {
    counter-reset: subsubsection;
    counter-increment: subsection;
  }
  .section h3 a.toc-backref:before {
    content: counter(section) "." counter(subsection) " ";
  }
  .section h4 {
    counter-increment: subsubsection;
  }
  .section h4 a.toc-backref:before {
    content: counter(section) "." counter(subsection) "." counter(subsubsection) " ";
  }
</style>
```

```{role} arc-term
```

```{role} revision
```

```{role} when-revised
```

# Objective-C Automatic Reference Counting (ARC)


(arc.meta)=

## About this document

(arc.meta.purpose)=

### Purpose

The first and primary purpose of this document is to serve as a complete
technical specification of Automatic Reference Counting. Given a core
Objective-C compiler and runtime, it should be possible to write a compiler and
runtime which implements these new semantics.

The secondary purpose is to act as a rationale for why ARC was designed in this
way. This should remain tightly focused on the technical design and should not
stray into marketing speculation.

(arc.meta.background)=

### Background

This document assumes a basic familiarity with C.

{arc-term}`Blocks` are a C language extension for creating anonymous functions.
Users interact with and transfer block objects using {arc-term}`block
pointers`, which are represented like a normal pointer. A block may capture
values from local variables; when this occurs, memory must be dynamically
allocated. The initial allocation is done on the stack, but the runtime
provides a `Block_copy` function which, given a block pointer, either copies
the underlying block object to the heap, setting its reference count to 1 and
returning the new block pointer, or (if the block object is already on the
heap) increases its reference count by 1. The paired function is
`Block_release`, which decreases the reference count by 1 and destroys the
object if the count reaches zero and is on the heap.

Objective-C is a set of language extensions, significant enough to be
considered a different language. It is a strict superset of C. The extensions
can also be imposed on C++, producing a language called Objective-C++. The
primary feature is a single-inheritance object system; we briefly describe the
modern dialect.

Objective-C defines a new type kind, collectively called the {arc-term}`object
pointer types`. This kind has two notable builtin members, `id` and
`Class`; `id` is the final supertype of all object pointers. The validity
of conversions between object pointer types is not checked at runtime. Users
may define {arc-term}`classes`; each class is a type, and the pointer to that
type is an object pointer type. A class may have a superclass; its pointer
type is a subtype of its superclass's pointer type. A class has a set of
{arc-term}`ivars`, fields which appear on all instances of that class. For
every class *T* there's an associated metaclass; it has no fields, its
superclass is the metaclass of *T*'s superclass, and its metaclass is a global
class. Every class has a global object whose class is the class's metaclass;
metaclasses have no associated type, so pointers to this object have type
`Class`.

A class declaration (`@interface`) declares a set of {arc-term}`methods`. A
method has a return type, a list of argument types, and a {arc-term}`selector`:
a name like `foo:bar:baz:`, where the number of colons corresponds to the
number of formal arguments. A method may be an instance method, in which case
it can be invoked on objects of the class, or a class method, in which case it
can be invoked on objects of the metaclass. A method may be invoked by
providing an object (called the {arc-term}`receiver`) and a list of formal
arguments interspersed with the selector, like so:

```objc
[receiver foo: fooArg bar: barArg baz: bazArg]
```

This looks in the dynamic class of the receiver for a method with this name,
then in that class's superclass, etc., until it finds something it can execute.
The receiver "expression" may also be the name of a class, in which case the
actual receiver is the class object for that class, or (within method
definitions) it may be `super`, in which case the lookup algorithm starts
with the static superclass instead of the dynamic class. The actual methods
dynamically found in a class are not those declared in the `@interface`, but
those defined in a separate `@implementation` declaration; however, when
compiling a call, typechecking is done based on the methods declared in the
`@interface`.

Method declarations may also be grouped into {arc-term}`protocols`, which are not
inherently associated with any class, but which classes may claim to follow.
Object pointer types may be qualified with additional protocols that the object
is known to support.

{arc-term}`Class extensions` are collections of ivars and methods, designed to
allow a class's `@interface` to be split across multiple files; however,
there is still a primary implementation file which must see the
`@interface`s of all class extensions. {arc-term}`Categories` allow
methods (but not ivars) to be declared *post hoc* on an arbitrary class; the
methods in the category's `@implementation` will be dynamically added to that
class's method tables which the category is loaded at runtime, replacing those
methods in case of a collision.

In the standard environment, objects are allocated on the heap, and their
lifetime is manually managed using a reference count. This is done using two
instance methods which all classes are expected to implement: `retain`
increases the object's reference count by 1, whereas `release` decreases it
by 1 and calls the instance method `dealloc` if the count reaches 0. To
simplify certain operations, there is also an {arc-term}`autorelease pool`, a
thread-local list of objects to call `release` on later; an object can be
added to this pool by calling `autorelease` on it.

Block pointers may be converted to type `id`; block objects are laid out in a
way that makes them compatible with Objective-C objects. There is a builtin
class that all block objects are considered to be objects of; this class
implements `retain` by adjusting the reference count, not by calling
`Block_copy`.

(arc.meta.evolution)=

### Evolution

ARC is under continual evolution, and this document must be updated as the
language progresses.

If a change increases the expressiveness of the language, for example by
lifting a restriction or by adding new syntax, the change will be annotated
with a revision marker, like so:

> ARC applies to Objective-C pointer types, block pointer types, and
> {when-revised}`[beginning Apple 8.0, LLVM 3.8]` {revision}`BPTRs declared
> within` `extern "BCPL"` blocks.

For now, it is sensible to version this document by the releases of its sole
implementation (and its host project), clang. "LLVM X.Y" refers to an
open-source release of clang from the LLVM project. "Apple X.Y" refers to an
Apple-provided release of the Apple LLVM Compiler. Other organizations that
prepare their own, separately-versioned clang releases and wish to maintain
similar information in this document should send requests to cfe-dev.

If a change decreases the expressiveness of the language, for example by
imposing a new restriction, this should be taken as an oversight in the
original specification and something to be avoided in all versions. Such
changes are generally to be avoided.

(arc.general)=

## General

Automatic Reference Counting implements automatic memory management for
Objective-C objects and blocks, freeing the programmer from the need to
explicitly insert retains and releases. It does not provide a cycle collector;
users must explicitly manage the lifetime of their objects, breaking cycles
manually or with weak or unsafe references.

ARC may be explicitly enabled with the compiler flag `-fobjc-arc`. It may
also be explicitly disabled with the compiler flag `-fno-objc-arc`. The last
of these two flags appearing on the compile line "wins".

If ARC is enabled, `__has_feature(objc_arc)` will expand to 1 in the
preprocessor. For more information about `__has_feature`, see the
{ref}`language extensions <langext-__has_feature-__has_extension>` document.

(arc.objects)=

## Retainable object pointers

This section describes retainable object pointers, their basic operations, and
the restrictions imposed on their use under ARC. Note in particular that it
covers the rules for pointer *values* (patterns of bits indicating the location
of a pointed-to object), not pointer *objects* (locations in memory which store
pointer values). The rules for objects are covered in the next section.

A {arc-term}`retainable object pointer` (or "retainable pointer") is a value of
a {arc-term}`retainable object pointer type` ("retainable type"). There are
three kinds of retainable object pointer types:

- block pointers (formed by applying the caret (`^`) declarator sigil to a
  function type)
- Objective-C object pointers (`id`, `Class`, `NSFoo*`, etc.)
- typedefs marked with `__attribute__((NSObject))`

Other pointer types, such as `int*` and `CFStringRef`, are not subject to
ARC's semantics and restrictions.

:::{admonition} Rationale
We are not at liberty to require all code to be recompiled with ARC;
therefore, ARC must interoperate with Objective-C code which manages retains
and releases manually. In general, there are three requirements in order for
a compiler-supported reference-count system to provide reliable
interoperation:

- The type system must reliably identify which objects are to be managed. An
  `int*` might be a pointer to a `malloc`'ed array, or it might be an
  interior pointer to such an array, or it might point to some field or local
  variable. In contrast, values of the retainable object pointer types are
  never interior.
- The type system must reliably indicate how to manage objects of a type.
  This usually means that the type must imply a procedure for incrementing
  and decrementing retain counts. Supporting single-ownership objects
  requires a lot more explicit mediation in the language.
- There must be reliable conventions for whether and when "ownership" is
  passed between caller and callee, for both arguments and return values.
  Objective-C methods follow such a convention very reliably, at least for
  system libraries on macOS, and functions always pass objects at +0. The
  C-based APIs for Core Foundation objects, on the other hand, have much more
  varied transfer semantics.
:::

The use of `__attribute__((NSObject))` typedefs is not recommended. If it's
absolutely necessary to use this attribute, be very explicit about using the
typedef, and do not assume that it will be preserved by language features like
`__typeof` and C++ template argument substitution.

:::{admonition} Rationale
Any compiler operation which incidentally strips type "sugar" from a type
will yield a type without the attribute, which may result in unexpected
behavior.
:::

(arc.objects.retains)=

### Retain count semantics

A retainable object pointer is either a {arc-term}`null pointer` or a pointer
to a valid object. Furthermore, if it has block pointer type and is not
`null` then it must actually be a pointer to a block object, and if it has
`Class` type (possibly protocol-qualified) then it must actually be a pointer
to a class object. Otherwise ARC does not enforce the Objective-C type system
as long as the implementing methods follow the signature of the static type.
It is undefined behavior if ARC is exposed to an invalid pointer.

For ARC's purposes, a valid object is one with "well-behaved" retaining
operations. Specifically, the object must be laid out such that the
Objective-C message send machinery can successfully send it the following
messages:

- `retain`, taking no arguments and returning a pointer to the object.
- `release`, taking no arguments and returning `void`.
- `autorelease`, taking no arguments and returning a pointer to the object.

The behavior of these methods is constrained in the following ways. The term
{arc-term}`high-level semantics` is an intentionally vague term; the intent is
that programmers must implement these methods in a way such that the compiler,
modifying code in ways it deems safe according to these constraints, will not
violate their requirements. For example, if the user puts logging statements
in `retain`, they should not be surprised if those statements are executed
more or less often depending on optimization settings. These constraints are
not exhaustive of the optimization opportunities: values held in local
variables are subject to additional restrictions, described later in this
document.

It is undefined behavior if a computation history featuring a send of
`retain` followed by a send of `release` to the same object, with no
intervening `release` on that object, is not equivalent under the high-level
semantics to a computation history in which these sends are removed. Note that
this implies that these methods may not raise exceptions.

It is undefined behavior if a computation history features any use whatsoever
of an object following the completion of a send of `release` that is not
preceded by a send of `retain` to the same object.

The behavior of `autorelease` must be equivalent to sending `release` when
one of the autorelease pools currently in scope is popped. It may not throw an
exception.

When the semantics call for performing one of these operations on a retainable
object pointer, if that pointer is `null` then the effect is a no-op.

All of the semantics described in this document are subject to additional
{ref}`optimization rules <arc.optimization>` which permit the removal or
optimization of operations based on local knowledge of data flow. The
semantics describe the high-level behaviors that the compiler implements, not
an exact sequence of operations that a program will be compiled into.

(arc.objects.operands)=

### Retainable object pointers as operands and arguments

In general, ARC does not perform retain or release operations when simply using
a retainable object pointer as an operand within an expression. This includes:

- loading a retainable pointer from an object with non-weak {ref}`ownership
  <arc.ownership>`,
- passing a retainable pointer as an argument to a function or method, and
- receiving a retainable pointer as the result of a function or method call.

:::{admonition} Rationale
While this might seem uncontroversial, it is actually unsafe when multiple
expressions are evaluated in "parallel", as with binary operators and calls,
because (for example) one expression might load from an object while another
writes to it. However, C and C++ already call this undefined behavior
because the evaluations are unsequenced, and ARC simply exploits that here to
avoid needing to retain arguments across a large number of calls.
:::

The remainder of this section describes exceptions to these rules, how those
exceptions are detected, and what those exceptions imply semantically.

(arc.objects.operands.consumed)=

#### Consumed parameters

A function or method parameter of retainable object pointer type may be marked
as {arc-term}`consumed`, signifying that the callee expects to take ownership
of a +1 retain count. This is done by adding the `ns_consumed` attribute to
the parameter declaration, like so:

```objc
void foo(__attribute((ns_consumed)) id x);
- (void) foo: (id) __attribute((ns_consumed)) x;
```

This attribute is part of the type of the function or method, not the type of
the parameter. It controls only how the argument is passed and received.

When passing such an argument, ARC retains the argument prior to making the
call.

When receiving such an argument, ARC releases the argument at the end of the
function, subject to the usual optimizations for local values.

:::{admonition} Rationale
This formalizes direct transfers of ownership from a caller to a callee. The
most common scenario here is passing the `self` parameter to `init`, but
it is useful to generalize. Typically, local optimization will remove any
extra retains and releases: on the caller side the retain will be merged with
a +1 source, and on the callee side the release will be rolled into the
initialization of the parameter.
:::

The implicit `self` parameter of a method may be marked as consumed by adding
`__attribute__((ns_consumes_self))` to the method declaration. Methods in
the `init` {ref}`family <arc.method-families>` are treated as if they were
implicitly marked with this attribute.

It is undefined behavior if an Objective-C message send to a method with
`ns_consumed` parameters (other than self) is made with a null receiver. It
is undefined behavior if the method to which an Objective-C message send
statically resolves to has a different set of `ns_consumed` parameters than
the method it dynamically resolves to. It is undefined behavior if a block or
function call is made through a static type with a different set of
`ns_consumed` parameters than the implementation of the called block or
function.

:::{admonition} Rationale
Consumed parameters with null receiver are a guaranteed leak. Mismatches
with consumed parameters will cause over-retains or over-releases, depending
on the direction. The rule about function calls is really just an
application of the existing C/C++ rule about calling functions through an
incompatible function type, but it's useful to state it explicitly.
:::

(arc.object.operands.retained-return-values)=

#### Retained return values

A function or method which returns a retainable object pointer type may be
marked as returning a retained value, signifying that the caller expects to take
ownership of a +1 retain count. This is done by adding the
`ns_returns_retained` attribute to the function or method declaration, like
so:

```objc
id foo(void) __attribute((ns_returns_retained));
- (id) foo __attribute((ns_returns_retained));
```

This attribute is part of the type of the function or method.

When returning from such a function or method, ARC retains the value at the
point of evaluation of the return statement, before leaving all local scopes.

When receiving a return result from such a function or method, ARC releases the
value at the end of the full-expression it is contained within, subject to the
usual optimizations for local values.

:::{admonition} Rationale
This formalizes direct transfers of ownership from a callee to a caller. The
most common scenario this models is the retained return from `init`,
`alloc`, `new`, and `copy` methods, but there are other cases in the
frameworks. After optimization there are typically no extra retains and
releases required.
:::

Methods in the `alloc`, `copy`, `init`, `mutableCopy`, and `new`
{ref}`families <arc.method-families>` are implicitly marked
`__attribute__((ns_returns_retained))`. This may be suppressed by explicitly
marking the method `__attribute__((ns_returns_not_retained))`.

It is undefined behavior if the method to which an Objective-C message send
statically resolves has different retain semantics on its result from the
method it dynamically resolves to. It is undefined behavior if a block or
function call is made through a static type with different retain semantics on
its result from the implementation of the called block or function.

:::{admonition} Rationale
Mismatches with returned results will cause over-retains or over-releases,
depending on the direction. Again, the rule about function calls is really
just an application of the existing C/C++ rule about calling functions
through an incompatible function type.
:::

(arc.objects.operands.unretained-returns)=

#### Unretained return values

A method or function which returns a retainable object type but does not return
a retained value must ensure that the object is still valid across the return
boundary.

When returning from such a function or method, ARC retains the value at the
point of evaluation of the return statement, then leaves all local scopes, and
then balances out the retain while ensuring that the value lives across the
call boundary. In the worst case, this may involve an `autorelease`, but
callers must not assume that the value is actually in the autorelease pool.

ARC performs no extra mandatory work on the caller side, although it may elect
to do something to shorten the lifetime of the returned value.

:::{admonition} Rationale
It is common in non-ARC code to not return an autoreleased value; therefore
the convention does not force either path. It is convenient to not be
required to do unnecessary retains and autoreleases; this permits
optimizations such as eliding retain/autoreleases when it can be shown that
the original pointer will still be valid at the point of return.
:::

A method or function may be marked with
`__attribute__((ns_returns_autoreleased))` to indicate that it returns a
pointer which is guaranteed to be valid at least as long as the innermost
autorelease pool. There are no additional semantics enforced in the definition
of such a method; it merely enables optimizations in callers.

(arc.objects.operands.casts)=

#### Bridged casts

A {arc-term}`bridged cast` is a C-style cast annotated with one of three
keywords:

- `(__bridge T) op` casts the operand to the destination type `T`. If
  `T` is a retainable object pointer type, then `op` must have a
  non-retainable pointer type. If `T` is a non-retainable pointer type,
  then `op` must have a retainable object pointer type. Otherwise the cast
  is ill-formed. There is no transfer of ownership, and ARC inserts no retain
  operations.
- `(__bridge_retained T) op` casts the operand, which must have retainable
  object pointer type, to the destination type, which must be a non-retainable
  pointer type. ARC retains the value, subject to the usual optimizations on
  local values, and the recipient is responsible for balancing that +1.
- `(__bridge_transfer T) op` casts the operand, which must have
  non-retainable pointer type, to the destination type, which must be a
  retainable object pointer type. ARC will release the value at the end of
  the enclosing full-expression, subject to the usual optimizations on local
  values.

These casts are required in order to transfer objects in and out of ARC
control; see the rationale in the section on {ref}`conversion of retainable
object pointers <arc.objects.restrictions.conversion>`.

Using a `__bridge_retained` or `__bridge_transfer` cast purely to convince
ARC to emit an unbalanced retain or release, respectively, is poor form.

(arc.objects.restrictions)=

### Restrictions

(arc.objects.restrictions.conversion)=

#### Conversion of retainable object pointers

In general, a program which attempts to implicitly or explicitly convert a
value of retainable object pointer type to any non-retainable type, or
vice-versa, is ill-formed. For example, an Objective-C object pointer shall
not be converted to `void*`. As an exception, cast to `intptr_t` is
allowed because such casts are not transferring ownership. The {ref}`bridged
casts <arc.objects.operands.casts>` may be used to perform these conversions
where necessary.

:::{admonition} Rationale
We cannot ensure the correct management of the lifetime of objects if they
may be freely passed around as unmanaged types. The bridged casts are
provided so that the programmer may explicitly describe whether the cast
transfers control into or out of ARC.
:::

However, the following exceptions apply.

(arc.objects.restrictions.conversion.with.known.semantics)=

#### Conversion to retainable object pointer type of expressions with known semantics

{when-revised}`[beginning Apple 4.0, LLVM 3.1]`
{revision}`These exceptions have been greatly expanded; they previously applied
only to a much-reduced subset which is difficult to categorize but which
included null pointers, message sends (under the given rules), and the various
global constants.`

An unbridged conversion to a retainable object pointer type from a type other
than a retainable object pointer type is ill-formed, as discussed above, unless
the operand of the cast has a syntactic form which is known retained, known
unretained, or known retain-agnostic.

An expression is {arc-term}`known retain-agnostic` if it is:

- an Objective-C string literal,
- a load from a `const` system global variable of {ref}`C retainable pointer
  type <arc.misc.c-retainable>`, or
- a null pointer constant.

An expression is {arc-term}`known unretained` if it is an rvalue of {ref}`C
retainable pointer type <arc.misc.c-retainable>` and it is:

- a direct call to a function, and either that function has the
  `cf_returns_not_retained` attribute or it is an {ref}`audited
  <arc.misc.c-retainable.audit>` function that does not have the
  `cf_returns_retained` attribute and does not follow the create/copy naming
  convention,
- a message send, and the declared method either has the
  `cf_returns_not_retained` attribute or it has neither the
  `cf_returns_retained` attribute nor a {ref}`selector family
  <arc.method-families>` that implies a retained result, or
- {when-revised}`[beginning LLVM 3.6]` {revision}`a load from a` `const`
  {revision}`non-system global variable.`

An expression is {arc-term}`known retained` if it is an rvalue of {ref}`C
retainable pointer type <arc.misc.c-retainable>` and it is:

- a message send, and the declared method either has the
  `cf_returns_retained` attribute, or it does not have the
  `cf_returns_not_retained` attribute but it does have a {ref}`selector
  family <arc.method-families>` that implies a retained result.

Furthermore:

- a comma expression is classified according to its right-hand side,
- a statement expression is classified according to its result expression, if
  it has one,
- an lvalue-to-rvalue conversion applied to an Objective-C property lvalue is
  classified according to the underlying message send, and
- a conditional operator is classified according to its second and third
  operands, if they agree in classification, or else the other if one is known
  retain-agnostic.

If the cast operand is known retained, the conversion is treated as a
`__bridge_transfer` cast. If the cast operand is known unretained or known
retain-agnostic, the conversion is treated as a `__bridge` cast.

:::{admonition} Rationale
Bridging casts are annoying. Absent the ability to completely automate the
management of CF objects, however, we are left with relatively poor attempts
to reduce the need for a glut of explicit bridges. Hence these rules.

We've so far consciously refrained from implicitly turning retained CF
results from function calls into `__bridge_transfer` casts. The worry is
that some code patterns --- for example, creating a CF value, assigning it
to an ObjC-typed local, and then calling `CFRelease` when done --- are a
bit too likely to be accidentally accepted, leading to mysterious behavior.

For loads from `const` global variables of {ref}`C retainable pointer type
<arc.misc.c-retainable>`, it is reasonable to assume that global system
constants were initialized with true constants (e.g. string literals), but
user constants might have been initialized with something dynamically
allocated, using a global initializer.
:::

(arc.objects.restrictions.conversion-exception-contextual)=

#### Conversion from retainable object pointer type in certain contexts

{when-revised}`[beginning Apple 4.0, LLVM 3.1]`

If an expression of retainable object pointer type is explicitly cast to a
{ref}`C retainable pointer type <arc.misc.c-retainable>`, the program is
ill-formed as discussed above unless the result is immediately used:

- to initialize a parameter in an Objective-C message send where the parameter
  is not marked with the `cf_consumed` attribute, or
- to initialize a parameter in a direct call to an
  {ref}`audited <arc.misc.c-retainable.audit>` function where the parameter is
  not marked with the `cf_consumed` attribute.

:::{admonition} Rationale
Consumed parameters are left out because ARC would naturally balance them
with a retain, which was judged too treacherous. This is in part because
several of the most common consuming functions are in the `Release` family,
and it would be quite unfortunate for explicit releases to be silently
balanced out in this way.
:::

(arc.ownership)=

## Ownership qualification

This section describes the behavior of *objects* of retainable object pointer
type; that is, locations in memory which store retainable object pointers.

A type is a {arc-term}`retainable object owner type` if it is a retainable
object pointer type or an array type whose element type is a retainable object
owner type.

An {arc-term}`ownership qualifier` is a type qualifier which applies only to
retainable object owner types. An array type is ownership-qualified according
to its element type, and adding an ownership qualifier to an array type so
qualifies its element type.

A program is ill-formed if it attempts to apply an ownership qualifier to a
type which is already ownership-qualified, even if it is the same qualifier.
There is a single exception to this rule: an ownership qualifier may be applied
to a substituted template type parameter, which overrides the ownership
qualifier provided by the template argument.

When forming a function type, the result type is adjusted so that any
top-level ownership qualifier is deleted.

Except as described under the {ref}`inference rules <arc.ownership.inference>`,
a program is ill-formed if it attempts to form a pointer or reference type to a
retainable object owner type which lacks an ownership qualifier.

:::{admonition} Rationale
These rules, together with the inference rules, ensure that all objects and
lvalues of retainable object pointer type have an ownership qualifier. The
ability to override an ownership qualifier during template substitution is
required to counteract the {ref}`inference of __strong for template type
arguments <arc.ownership.inference.template.arguments>`. Ownership qualifiers
on return types are dropped because they serve no purpose there except to
cause spurious problems with overloading and templates.
:::

There are four ownership qualifiers:

- `__autoreleasing`
- `__strong`
- `__unsafe_unretained`
- `__weak`

A type is {arc-term}`nontrivially ownership-qualified` if it is qualified with
`__autoreleasing`, `__strong`, or `__weak`.

(arc.ownership.spelling)=

### Spelling

The names of the ownership qualifiers are reserved for the implementation. A
program may not assume that they are or are not implemented with macros, or
what those macros expand to.

An ownership qualifier may be written anywhere that any other type qualifier
may be written.

If an ownership qualifier appears in the *declaration-specifiers*, the
following rules apply:

- if the type specifier is a retainable object owner type, the qualifier
  initially applies to that type;
- otherwise, if the outermost non-array declarator is a pointer
  or block pointer declarator, the qualifier initially applies to
  that type;
- otherwise the program is ill-formed.
- If the qualifier is so applied at a position in the declaration
  where the next-innermost declarator is a function declarator, and
  there is a block declarator within that function declarator, then
  the qualifier applies instead to that block declarator and this rule
  is considered afresh beginning from the new position.

If an ownership qualifier appears on the declarator name, or on the declared
object, it is applied to the innermost pointer or block-pointer type.

If an ownership qualifier appears anywhere else in a declarator, it applies to
the type there.

:::{admonition} Rationale
Ownership qualifiers are like `const` and `volatile` in the sense
that they may sensibly apply at multiple distinct positions within a
declarator. However, unlike those qualifiers, there are many
situations where they are not meaningful, and so we make an effort
to "move" the qualifier to a place where it will be meaningful. The
general goal is to allow the programmer to write, say, `__strong`
before the entire declaration and have it apply in the leftmost
sensible place.
:::

(arc.ownership.spelling.property)=

#### Property declarations

A property of retainable object pointer type may have ownership. If the
property's type is ownership-qualified, then the property has that ownership.
If the property has one of the following modifiers, then the property has the
corresponding ownership. A property is ill-formed if it has conflicting
sources of ownership, or if it has redundant ownership modifiers, or if it has
`__autoreleasing` ownership.

- `assign` implies `__unsafe_unretained` ownership.
- `copy` implies `__strong` ownership, as well as the usual behavior of
  copy semantics on the setter.
- `retain` implies `__strong` ownership.
- `strong` implies `__strong` ownership.
- `unsafe_unretained` implies `__unsafe_unretained` ownership.
- `weak` implies `__weak` ownership.

With the exception of `weak`, these modifiers are available in non-ARC
modes.

A property's specified ownership is preserved in its metadata, but otherwise
the meaning is purely conventional unless the property is synthesized. If a
property is synthesized, then the {arc-term}`associated instance variable` is
the instance variable which is named, possibly implicitly, by the
`@synthesize` declaration. If the associated instance variable already
exists, then its ownership qualification must equal the ownership of the
property; otherwise, the instance variable is created with that ownership
qualification.

A property of retainable object pointer type which is synthesized without a
source of ownership has the ownership of its associated instance variable, if it
already exists; otherwise, {when-revised}`[beginning Apple 3.1, LLVM 3.1]`
{revision}`its ownership is implicitly` `strong`. Prior to this revision, it
was ill-formed to synthesize such a property.

:::{admonition} Rationale
Using `strong` by default is safe and consistent with the generic ARC rule
about {ref}`inferring ownership <arc.ownership.inference.variables>`. It is,
unfortunately, inconsistent with the non-ARC rule which states that such
properties are implicitly `assign`. However, that rule is clearly
untenable in ARC, since it leads to default-unsafe code. The main merit to
banning the properties is to avoid confusion with non-ARC practice, which did
not ultimately strike us as sufficient to justify requiring extra syntax and
(more importantly) forcing novices to understand ownership rules just to
declare a property when the default is so reasonable. Changing the rule away
from non-ARC practice was acceptable because we had conservatively banned the
synthesis in order to give ourselves exactly this leeway.
:::

Applying `__attribute__((NSObject))` to a property not of retainable object
pointer type has the same behavior it does outside of ARC: it requires the
property type to be some sort of pointer and permits the use of modifiers other
than `assign`. These modifiers only affect the synthesized getter and
setter; direct accesses to the ivar (even if synthesized) still have primitive
semantics, and the value in the ivar will not be automatically released during
deallocation.

(arc.ownership.semantics)=

### Semantics

There are five {arc-term}`managed operations` which may be performed on an
object of retainable object pointer type. Each qualifier specifies different
semantics for each of these operations. It is still undefined behavior to
access an object outside of its lifetime.

A load or store with "primitive semantics" has the same semantics as the
respective operation would have on an `void*` lvalue with the same alignment
and non-ownership qualification.

{arc-term}`Reading` occurs when performing a lvalue-to-rvalue conversion on an
object lvalue.

- For `__weak` objects, the current pointee is retained and then released at
  the end of the current full-expression. In particular, messaging a `__weak`
  object keeps the object retained until the end of the full expression.

  ```objc
  __weak MyObject *weakObj;

  void foo() {
    // weakObj is retained before the message send and released at the end of
    // the full expression.
    [weakObj m];
  }
  ```

  This must execute atomically with respect to assignments and to the final
  release of the pointee.

- For all other objects, the lvalue is loaded with primitive semantics.

{arc-term}`Assignment` occurs when evaluating an assignment operator. The
semantics vary based on the qualification:

- For `__strong` objects, the new pointee is first retained; second, the
  lvalue is loaded with primitive semantics; third, the new pointee is stored
  into the lvalue with primitive semantics; and finally, the old pointee is
  released. This is not performed atomically; external synchronization must be
  used to make this safe in the face of concurrent loads and stores.
- For `__weak` objects, the lvalue is updated to point to the new pointee,
  unless the new pointee is an object currently undergoing deallocation, in
  which case the lvalue is updated to a null pointer. This must execute
  atomically with respect to other assignments to the object, to reads from the
  object, and to the final release of the new pointee.
- For `__unsafe_unretained` objects, the new pointee is stored into the
  lvalue using primitive semantics.
- For `__autoreleasing` objects, the new pointee is retained, autoreleased,
  and stored into the lvalue using primitive semantics.

{arc-term}`Initialization` occurs when an object's lifetime begins, which
depends on its storage duration. Initialization proceeds in two stages:

1. First, a null pointer is stored into the lvalue using primitive semantics.
   This step is skipped if the object is `__unsafe_unretained`.
2. Second, if the object has an initializer, that expression is evaluated and
   then assigned into the object using the usual assignment semantics.

{arc-term}`Destruction` occurs when an object's lifetime ends. In all cases it
is semantically equivalent to assigning a null pointer to the object, with the
proviso that of course the object cannot be legally read after the object's
lifetime ends.

{arc-term}`Moving` occurs in specific situations where an lvalue is "moved
from", meaning that its current pointee will be used but the object may be left
in a different (but still valid) state. This arises with `__block` variables
and rvalue references in C++. For `__strong` lvalues, moving is equivalent
to loading the lvalue with primitive semantics, writing a null pointer to it
with primitive semantics, and then releasing the result of the load at the end
of the current full-expression. For all other lvalues, moving is equivalent to
reading the object.

(arc.ownership.restrictions)=

### Restrictions

(arc.ownership.restrictions.weak)=

#### Weak-unavailable types

It is explicitly permitted for Objective-C classes to not support `__weak`
references. It is undefined behavior to perform an operation with weak
assignment semantics with a pointer to an Objective-C object whose class does
not support `__weak` references.

:::{admonition} Rationale
Historically, it has been possible for a class to provide its own
reference-count implementation by overriding `retain`, `release`, etc.
However, weak references to an object require coordination with its class's
reference-count implementation because, among other things, weak loads and
stores must be atomic with respect to the final release. Therefore, existing
custom reference-count implementations will generally not support weak
references without additional effort. This is unavoidable without breaking
binary compatibility.
:::

A class may indicate that it does not support weak references by providing the
`objc_arc_weak_reference_unavailable` attribute on the class's interface declaration. A
retainable object pointer type is **weak-unavailable** if it
is a pointer to an (optionally protocol-qualified) Objective-C class `T` where
`T` or one of its superclasses has the `objc_arc_weak_reference_unavailable`
attribute. A program is ill-formed if it applies the `__weak` ownership
qualifier to a weak-unavailable type or if the value operand of a weak
assignment operation has a weak-unavailable type.

(arc.ownership.restrictions.autoreleasing)=

#### Storage duration of `__autoreleasing` objects

A program is ill-formed if it declares an `__autoreleasing` object of
non-automatic storage duration. A program is ill-formed if it captures an
`__autoreleasing` object in a block or, unless by reference, in a C++11
lambda.

:::{admonition} Rationale
Autorelease pools are tied to the current thread and scope by their nature.
While it is possible to have temporary objects whose instance variables are
filled with autoreleased objects, there is no way that ARC can provide any
sort of safety guarantee there.
:::

It is undefined behavior if a non-null pointer is assigned to an
`__autoreleasing` object while an autorelease pool is in scope and then that
object is read after the autorelease pool's scope is left.

(arc.ownership.restrictions.conversion.indirect)=

#### Conversion of pointers to ownership-qualified types

A program is ill-formed if an expression of type `T*` is converted,
explicitly or implicitly, to the type `U*`, where `T` and `U` have
different ownership qualification, unless:

- `T` is qualified with `__strong`, `__autoreleasing`, or
  `__unsafe_unretained`, and `U` is qualified with both `const` and
  `__unsafe_unretained`; or
- either `T` or `U` is `cv void`, where `cv` is an optional sequence
  of non-ownership qualifiers; or
- the conversion is requested with a `reinterpret_cast` in Objective-C++; or
- the conversion is a well-formed {ref}`pass-by-writeback
  <arc.ownership.restrictions.pass_by_writeback>`.

The analogous rule applies to `T&` and `U&` in Objective-C++.

:::{admonition} Rationale
These rules provide a reasonable level of type-safety for indirect pointers,
as long as the underlying memory is not deallocated. The conversion to
`const __unsafe_unretained` is permitted because the semantics of reads are
equivalent across all these ownership semantics, and that's a very useful and
common pattern. The interconversion with `void*` is useful for allocating
memory or otherwise escaping the type system, but use it carefully.
`reinterpret_cast` is considered to be an obvious enough sign of taking
responsibility for any problems.
:::

It is undefined behavior to access an ownership-qualified object through an
lvalue of a differently-qualified type, except that any non-`__weak` object
may be read through an `__unsafe_unretained` lvalue.

It is undefined behavior if the storage of a `__strong` or `__weak`
object is not properly initialized before the first managed operation
is performed on the object, or if the storage of such an object is freed
or reused before the object has been properly deinitialized. Storage for
a `__strong` or `__weak` object may be properly initialized by filling
it with the representation of a null pointer, e.g. by acquiring the memory
with `calloc` or using `bzero` to zero it out. A `__strong` or
`__weak` object may be properly deinitialized by assigning a null pointer
into it. A `__strong` object may also be properly initialized
by copying into it (e.g. with `memcpy`) the representation of a
different `__strong` object whose storage has been properly initialized;
doing this properly deinitializes the source object and causes its storage
to no longer be properly initialized. A `__weak` object may not be
representation-copied in this way.

These requirements are followed automatically for objects whose
initialization and deinitialization are under the control of ARC:

- objects of static, automatic, and temporary storage duration
- instance variables of Objective-C objects
- elements of arrays where the array object's initialization and
  deinitialization are under the control of ARC
- fields of Objective-C struct types where the struct object's
  initialization and deinitialization are under the control of ARC
- non-static data members of Objective-C++ non-union class types
- Objective-C++ objects and arrays of dynamic storage duration created
  with the `new` or `new[]` operators and destroyed with the
  corresponding `delete` or `delete[]` operator

They are not followed automatically for these objects:

- objects of dynamic storage duration created in other memory, such as
  that returned by `malloc`
- union members

:::{admonition} Rationale
ARC must perform special operations when initializing an object and
when destroying it. In many common situations, ARC knows when an
object is created and when it is destroyed and can ensure that these
operations are performed correctly. Otherwise, however, ARC requires
programmer cooperation to establish its initialization invariants
because it is infeasible for ARC to dynamically infer whether they
are intact. For example, there is no syntactic difference in C between
an assignment that is intended by the programmer to initialize a variable
and one that is intended to replace the existing value stored there,
but ARC must perform one operation or the other. ARC chooses to always
assume that objects are initialized (except when it is in charge of
initializing them) because the only workable alternative would be to
ban all code patterns that could potentially be used to access
uninitialized memory, and that would be too limiting. In practice,
this is rarely a problem because programmers do not generally need to
work with objects for which the requirements are not handled
automatically.
:::

Note that dynamically-allocated Objective-C++ arrays of
nontrivially-ownership-qualified type are not ABI-compatible with non-ARC
code because the non-ARC code will consider the element type to be POD.
Such arrays that are `new[]`'d in ARC translation units cannot be
`delete[]`'d in non-ARC translation units and vice-versa.

(arc.ownership.restrictions.pass_by_writeback)=

#### Passing to an out parameter by writeback

If the argument passed to a parameter of type `T __autoreleasing *` has type
`U oq *`, where `oq` is an ownership qualifier, then the argument is a
candidate for {arc-term}`pass-by-writeback`` if:

- `oq` is `__strong` or `__weak`, and
- it would be legal to initialize a `T __strong *` with a `U __strong *`.

For purposes of overload resolution, an implicit conversion sequence requiring
a pass-by-writeback is always worse than an implicit conversion sequence not
requiring a pass-by-writeback.

The pass-by-writeback is ill-formed if the argument expression does not have a
legal form:

- `&var`, where `var` is a scalar variable of automatic storage duration
  with retainable object pointer type
- a conditional expression where the second and third operands are both legal
  forms
- a cast whose operand is a legal form
- a null pointer constant

:::{admonition} Rationale
The restriction in the form of the argument serves two purposes. First, it
makes it impossible to pass the address of an array to the argument, which
serves to protect against an otherwise serious risk of mis-inferring an
"array" argument as an out-parameter. Second, it makes it much less likely
that the user will see confusing aliasing problems due to the implementation,
below, where their store to the writeback temporary is not immediately seen
in the original argument variable.
:::

A pass-by-writeback is evaluated as follows:

1. The argument is evaluated to yield a pointer `p` of type `U oq *`.
2. If `p` is a null pointer, then a null pointer is passed as the argument,
   and no further work is required for the pass-by-writeback.
3. Otherwise, a temporary of type `T __autoreleasing` is created and
   initialized to a null pointer.
4. If the parameter is not an Objective-C method parameter marked `out`,
   then `*p` is read, and the result is written into the temporary with
   primitive semantics.
5. The address of the temporary is passed as the argument to the actual call.
6. After the call completes, the temporary is loaded with primitive
   semantics, and that value is assigned into `*p`.

:::{admonition} Rationale
This is all admittedly convoluted. In an ideal world, we would see that a
local variable is being passed to an out-parameter and retroactively modify
its type to be `__autoreleasing` rather than `__strong`. This would be
remarkably difficult and not always well-founded under the C type system.
However, it was judged unacceptably invasive to require programmers to write
`__autoreleasing` on all the variables they intend to use for
out-parameters. This was the least bad solution.
:::

(arc.ownership.restrictions.records)=

#### Ownership-qualified fields of structs and unions

A member of a struct or union may be declared to have ownership-qualified
type. If the type is qualified with `__unsafe_unretained`, the semantics
of the containing aggregate are unchanged from the semantics of an unqualified type in a non-ARC mode. If the type is qualified with `__autoreleasing`, the program is ill-formed. Otherwise, if the type is nontrivially ownership-qualified, additional rules apply.

Both Objective-C and Objective-C++ support nontrivially ownership-qualified
fields. Due to formal differences between the standards, the formal
treatment is different; however, the basic language model is intended to
be the same for identical code.

:::{admonition} Rationale
Permitting `__strong` and `__weak` references in aggregate types
allows programmers to take advantage of the normal language tools of
C and C++ while still automatically managing memory. While it is
usually simpler and more idiomatic to use Objective-C objects for
secondary data structures, doing so can introduce extra allocation
and message-send overhead, which can cause unacceptable
performance. Using structs can resolve some of this tension.

`__autoreleasing` is forbidden because it is treacherous to rely
on autoreleases as an ownership tool outside of a function-local
contexts.

Earlier releases of Clang permitted `__strong` and `__weak` only
references in Objective-C++ classes, not in Objective-C. This
restriction was an undesirable short-term constraint arising from the
complexity of adding support for non-trivial struct types to C.
:::

In Objective-C++, nontrivially ownership-qualified types are treated
for nearly all purposes as if they were class types with non-trivial
default constructors, copy constructors, move constructors, copy assignment
operators, move assignment operators, and destructors. This includes the
determination of the triviality of special members of classes with a
non-static data member of such a type.

In Objective-C, the definition cannot be so succinct: because the C
standard lacks rules for non-trivial types, those rules must first be
developed. They are given in the next section. The intent is that these
rules are largely consistent with the rules of C++ for code expressible
in both languages.

##### Formal rules for non-trivial types in C

The following are base rules which can be added to C to support
implementation-defined non-trivial types.

A type in C is said to be *non-trivial to copy*, *non-trivial to destroy*,
or *non-trivial to default-initialize* if:

- it is a struct or union containing a member whose type is non-trivial
  to (respectively) copy, destroy, or default-initialize;
- it is a qualified type whose unqualified type is non-trivial to
  (respectively) copy, destroy, or default-initialize (for at least
  the standard C qualifiers); or
- it is an array type whose element type is non-trivial to (respectively)
  copy, destroy, or default-initialize.

A type in C is said to be *illegal to copy*, *illegal to destroy*, or
*illegal to default-initialize* if:

- it is a union which contains a member whose type is either illegal
  or non-trivial to (respectively) copy, destroy, or initialize;
- it is a qualified type whose unqualified type is illegal to
  (respectively) copy, destroy, or default-initialize (for at least
  the standard C qualifiers); or
- it is an array type whose element type is illegal to (respectively)
  copy, destroy, or default-initialize.

No type describable under the rules of the C standard shall be either
non-trivial or illegal to copy, destroy, or default-initialize.
An implementation may provide additional types which have one or more
of these properties.

An expression calls for a type to be copied if it:

- passes an argument of that type to a function call,
- defines a function which declares a parameter of that type,
- calls or defines a function which returns a value of that type,
- assigns to an l-value of that type, or
- converts an l-value of that type to an r-value.

A program calls for a type to be destroyed if it:

- passes an argument of that type to a function call,
- defines a function which declares a parameter of that type,
- calls or defines a function which returns a value of that type,
- creates an object of automatic storage duration of that type,
- assigns to an l-value of that type, or
- converts an l-value of that type to an r-value.

A program calls for a type to be default-initialized if it:

- declares a variable of that type without an initializer.

An expression is ill-formed if calls for a type to be copied,
destroyed, or default-initialized and that type is illegal to
(respectively) copy, destroy, or default-initialize.

A program is ill-formed if it contains a function type specifier
with a parameter or return type that is illegal to copy or
destroy. If a function type specifier would be ill-formed for this
reason except that the parameter or return type was incomplete at
that point in the translation unit, the program is ill-formed but
no diagnostic is required.

A `goto` or `switch` is ill-formed if it jumps into the scope of
an object of automatic storage duration whose type is non-trivial to
destroy.

C specifies that it is generally undefined behavior to access an l-value
if there is no object of that type at that location. Implementations
are often lenient about this, but non-trivial types generally require
it to be enforced more strictly. The following rules apply:

The *static subobjects* of a type `T` at a location `L` are:

- an object of type `T` spanning from `L` to `L + sizeof(T)`;
- if `T` is a struct type, then for each field `f` of that struct,
  the static subobjects of `T` at location `L + offsetof(T, .f)`; and
- if `T` is the array type `E[N]`, then for each `i` satisfying
  `0 <= i < N`, the static subobjects of `E` at location
  `L + i * sizeof(E)`.

If an l-value is converted to an r-value, then all static subobjects
whose types are non-trivial to copy are accessed. If an l-value is
assigned to, or if an object of automatic storage duration goes out of
scope, then all static subobjects of types that are non-trivial to destroy
are accessed.

A dynamic object is created at a location if an initialization initializes
an object of that type there. A dynamic object ceases to exist at a
location if the memory is repurposed. Memory is repurposed if it is
freed or if a different dynamic object is created there, for example by
assigning into a different union member. An implementation may provide
additional rules for what constitutes creating or destroying a dynamic
object.

If an object is accessed under these rules at a location where no such
dynamic object exists, the program has undefined behavior.
If memory for a location is repurposed while a dynamic object that is
non-trivial to destroy exists at that location, the program has
undefined behavior.

:::{admonition} Rationale
While these rules are far less fine-grained than C++, they are
nonetheless sufficient to express a wide spectrum of types.
Types that express some sort of ownership will generally be non-trivial
to both copy and destroy and either non-trivial or illegal to
default-initialize. Types that don't express ownership may still
be non-trivial to copy because of some sort of address sensitivity;
for example, a relative reference. Distinguishing default
initialization allows types to impose policies about how they are
created.

These rules assume that assignment into an l-value is always a
modification of an existing object rather than an initialization.
Assignment is then a compound operation where the old value is
read and destroyed, if necessary, and the new value is put into
place. These are the natural semantics of value propagation, where
all basic operations on the type come down to copies and destroys,
and everything else is just an optimization on top of those.

The most glaring weakness of programming with non-trivial types in C
is that there are no language mechanisms (akin to C++'s placement
`new` and explicit destructor calls) for explicitly creating and
destroying objects. Clang should consider adding builtins for this
purpose, as well as for common optimizations like destructive
relocation.
:::

##### Application of the formal C rules to nontrivial ownership qualifiers

Nontrivially ownership-qualified types are considered non-trivial
to copy, destroy, and default-initialize.

A dynamic object of nontrivially ownership-qualified type contingently
exists at a location if the memory is filled with a zero pattern, e.g.
by `calloc` or `bzero`. Such an object can be safely accessed in
all of the cases above, but its memory can also be safely repurposed.
Assigning a null pointer into an l-value of `__weak` or
`__strong`-qualified type accesses the dynamic object there (and thus
may have undefined behavior if no such object exists), but afterwards
the object's memory is guaranteed to be filled with a zero pattern
and thus may be either further accessed or repurposed as needed.
The upshot is that programs may safely initialize dynamically-allocated
memory for nontrivially ownership-qualified types by ensuring it is zero-initialized, and they may safely deinitialize memory before
freeing it by storing `nil` into any `__strong` or `__weak`
references previously created in that memory.

##### C/C++ compatibility for structs and unions with non-trivial members

Structs and unions with non-trivial members are compatible in
different language modes (e.g. between Objective-C and Objective-C++,
or between ARC and non-ARC modes) under the following conditions:

- The types must be compatible ignoring ownership qualifiers according
  to the baseline, non-ARC rules (e.g. C struct compatibility or C++'s
  ODR). This condition implies a pairwise correspondence between
  fields.

  Note that an Objective-C++ class with base classes, a user-provided
  copy or move constructor, or a user-provided destructor is never
  compatible with an Objective-C type.

- If two fields correspond as above, and at least one of the fields is
  ownership-qualified, then:

  - the fields must be identically qualified, or else
  - one type must be unqualified (and thus declared in a non-ARC mode),
    and the other type must be qualified with `__unsafe_unretained`
    or `__strong`.

  Note that `__weak` fields must always be declared `__weak` because
  of the need to pin those fields in memory and keep them properly
  registered with the Objective-C runtime. Non-ARC modes may still
  declare fields `__weak` by enabling `-fobjc-weak`.

These compatibility rules permit a function that takes a parameter
of non-trivial struct type to be written in ARC and called from
non-ARC or vice-versa. The convention for this always transfers
ownership of objects stored in `__strong` fields from the caller
to the callee, just as for an `ns_consumed` argument. Therefore,
non-ARC callers must ensure that such fields are initialized to a +1
reference, and non-ARC callees must balance that +1 by releasing the
reference or transferring it as appropriate.

Likewise, a function returning a non-trivial struct may be written in
ARC and called from non-ARC or vice-versa. The convention for this
always transfers ownership of objects stored in `__strong` fields
from the callee to the caller, and so callees must initialize such
fields with +1 references, and callers must balance that +1 by releasing
or transferring them.

Similar transfers of responsibility occur for `__weak` fields, but
since both sides must use native `__weak` support to ensure
calling convention compatibility, this transfer is always handled
automatically by the compiler.

:::{admonition} Rationale
In earlier releases, when non-trivial ownership was only permitted
on fields in Objective-C++, the ABI used for such classes was the
ordinary ABI for non-trivial C++ classes, which passes arguments and
returns indirectly and does not transfer responsibility for arguments.
When support for Objective-C structs was added, it was decided to
change to the current ABI for three reasons:

- It permits ARC / non-ARC compatibility for structs containing only
  `__strong` references, as long as the non-ARC side is careful about
  transferring ownership.
- It avoids unnecessary indirection for sufficiently small types that
  the C ABI would prefer to pass in registers.
- Given that struct arguments must be produced at +1 to satisfy C's
  semantics of initializing the local parameter variable, transferring
  ownership of that copy to the callee is generally better for ARC
  optimization, since otherwise there will be releases in the caller
  that are much harder to pair with transfers in the callee.

Breaking compatibility with existing Objective-C++ structures was
considered an acceptable cost, as most Objective-C++ code does not have
binary-compatibility requirements. Any existing code which cannot accept
this compatibility break, which is necessarily Objective-C++, should
force the use of the standard C++ ABI by declaring an empty (but
non-defaulted) destructor.
:::

(arc.ownership.inference)=

### Ownership inference

(arc.ownership.inference.variables)=

#### Objects

If an object is declared with retainable object owner type, but without an
explicit ownership qualifier, its type is implicitly adjusted to have
`__strong` qualification.

As a special case, if the object's base type is `Class` (possibly
protocol-qualified), the type is adjusted to have `__unsafe_unretained`
qualification instead.

(arc.ownership.inference.indirect_parameters)=

#### Indirect parameters

If a function or method parameter has type `T*`, where `T` is an
ownership-unqualified retainable object pointer type, then:

- if `T` is `const`-qualified or `Class`, then it is implicitly
  qualified with `__unsafe_unretained`;
- otherwise, it is implicitly qualified with `__autoreleasing`.

:::{admonition} Rationale
`__autoreleasing` exists mostly for this case, the Cocoa convention for
out-parameters. Since a pointer to `const` is obviously not an
out-parameter, we instead use a type more useful for passing arrays. If the
user instead intends to pass in a *mutable* array, inferring
`__autoreleasing` is the wrong thing to do; this directs some of the
caution in the following rules about writeback.
:::

Such a type written anywhere else would be ill-formed by the general rule
requiring ownership qualifiers.

This rule does not apply in Objective-C++ if a parameter's type is dependent in
a template pattern and is only *instantiated* to a type which would be a
pointer to an unqualified retainable object pointer type. Such code is still
ill-formed.

:::{admonition} Rationale
The convention is very unlikely to be intentional in template code.
:::

(arc.ownership.inference.template.arguments)=

#### Template arguments

If a template argument for a template type parameter is a retainable object
owner type that does not have an explicit ownership qualifier, it is adjusted
to have `__strong` qualification. This adjustment occurs regardless of
whether the template argument was deduced or explicitly specified.

:::{admonition} Rationale
`__strong` is a useful default for containers (e.g., `std::vector<id>`),
which would otherwise require explicit qualification. Moreover, unqualified
retainable object pointer types are unlikely to be useful within templates,
since they generally need to have a qualifier applied to the before being
used.
:::

(arc.method-families)=

## Method families

An Objective-C method may fall into a {arc-term}`method family`, which is a
conventional set of behaviors ascribed to it by the Cocoa conventions.

A method is in a certain method family if:

- it has a `objc_method_family` attribute placing it in that family; or if
  not that,
- it does not have an `objc_method_family` attribute placing it in a
  different or no family, and
- its selector falls into the corresponding selector family, and
- its signature obeys the added restrictions of the method family.

A selector is in a certain selector family if, ignoring any leading
underscores, the first component of the selector either consists entirely of
the name of the method family or it begins with that name followed by a
character other than a lowercase letter. For example, `_perform:with:` and
`performWith:` would fall into the `perform` family (if we recognized one),
but `performing:with` would not.

The families and their added restrictions are:

- `alloc` methods must return a retainable object pointer type.

- `copy` methods must return a retainable object pointer type.

- `mutableCopy` methods must return a retainable object pointer type.

- `new` methods must return a retainable object pointer type.

- `init` methods must be instance methods and must return an Objective-C
  pointer type. Additionally, a program is ill-formed if it declares or
  contains a call to an `init` method whose return type is neither `id` nor
  a pointer to a super-class or sub-class of the declaring class (if the method
  was declared on a class) or the static receiver type of the call (if it was
  declared on a protocol).

  :::{admonition} Rationale
  There are a fair number of existing methods with `init`-like selectors
  which nonetheless don't follow the `init` conventions. Typically these
  are either accidental naming collisions or helper methods called during
  initialization. Because of the peculiar retain/release behavior of
  `init` methods, it's very important not to treat these methods as
  `init` methods if they aren't meant to be. It was felt that implicitly
  defining these methods out of the family based on the exact relationship
  between the return type and the declaring class would be much too subtle
  and fragile. Therefore we identify a small number of legitimate-seeming
  return types and call everything else an error. This serves the secondary
  purpose of encouraging programmers not to accidentally give methods names
  in the `init` family.

  Note that a method with an `init`-family selector which returns a
  non-Objective-C type (e.g. `void`) is perfectly well-formed; it simply
  isn't in the `init` family.
  :::

A program is ill-formed if a method's declarations, implementations, and
overrides do not all have the same method family.

(arc.family.attribute)=

### Explicit method family control

A method may be annotated with the `objc_method_family` attribute to
precisely control which method family it belongs to. If a method in an
`@implementation` does not have this attribute, but there is a method
declared in the corresponding `@interface` that does, then the attribute is
copied to the declaration in the `@implementation`. The attribute is
available outside of ARC, and may be tested for with the preprocessor query
`__has_attribute(objc_method_family)`.

The attribute is spelled
`__attribute__((objc_method_family(` *family* `)))`. If *family* is
`none`, the method has no family, even if it would otherwise be considered to
have one based on its selector and type. Otherwise, *family* must be one of
`alloc`, `copy`, `init`, `mutableCopy`, or `new`, in which case the
method is considered to belong to the corresponding family regardless of its
selector. It is an error if a method that is explicitly added to a family in
this way does not meet the requirements of the family other than the selector
naming convention.

:::{admonition} Rationale
The rules codified in this document describe the standard conventions of
Objective-C. However, as these conventions have not heretofore been enforced
by an unforgiving mechanical system, they are only imperfectly kept,
especially as they haven't always even been precisely defined. While it is
possible to define low-level ownership semantics with attributes like
`ns_returns_retained`, this attribute allows the user to communicate
semantic intent, which is of use both to ARC (which, e.g., treats calls to
`init` specially) and the static analyzer.
:::

(arc.family.semantics)=

### Semantics of method families

A method's membership in a method family may imply non-standard semantics for
its parameters and return type.

Methods in the `alloc`, `copy`, `mutableCopy`, and `new` families ---
that is, methods in all the currently-defined families except `init` ---
implicitly {ref}`return a retained object
<arc.object.operands.retained-return-values>` as if they were annotated with
the `ns_returns_retained` attribute. This can be overridden by annotating
the method with either of the `ns_returns_autoreleased` or
`ns_returns_not_retained` attributes.

Properties also follow same naming rules as methods. This means that those in
the `alloc`, `copy`, `mutableCopy`, and `new` families provide access
to {ref}`retained objects <arc.object.operands.retained-return-values>`. This
can be overridden by annotating the property with `ns_returns_not_retained`
attribute.

(arc.family.semantics.init)=

#### Semantics of `init`

Methods in the `init` family implicitly {ref}`consume
<arc.objects.operands.consumed>` their `self` parameter and {ref}`return a
retained object <arc.object.operands.retained-return-values>`. Neither of
these properties can be altered through attributes.

A call to an `init` method with a receiver that is either `self` (possibly
parenthesized or casted) or `super` is called a {arc-term}`delegate init
call`. It is an error for a delegate init call to be made except from an
`init` method, and excluding blocks within such methods.

As an exception to the {ref}`usual rule <arc.misc.self>`, the variable `self`
is mutable in an `init` method and has the usual semantics for a `__strong`
variable. However, it is undefined behavior and the program is ill-formed, no
diagnostic required, if an `init` method attempts to use the previous value
of `self` after the completion of a delegate init call. It is conventional,
but not required, for an `init` method to return `self`.

It is undefined behavior for a program to cause two or more calls to `init`
methods on the same object, except that each `init` method invocation may
perform at most one delegate init call.

(arc.family.semantics.result_type)=

#### Related result types

Certain methods are candidates to have {arc-term}`related result types`:

- class methods in the `alloc` and `new` method families
- instance methods in the `init` family
- the instance method `self`
- outside of ARC, the instance methods `retain` and `autorelease`

If the formal result type of such a method is `id` or protocol-qualified
`id`, or a type equal to the declaring class or a superclass, then it is said
to have a related result type. In this case, when invoked in an explicit
message send, it is assumed to return a type related to the type of the
receiver:

- if it is a class method, and the receiver is a class name `T`, the message
  send expression has type `T*`; otherwise
- if it is an instance method, and the receiver has type `T`, the message
  send expression has type `T`; otherwise
- the message send expression has the normal result type of the method.

This is a new rule of the Objective-C language and applies outside of ARC.

:::{admonition} Rationale
ARC's automatic code emission is more prone than most code to signature
errors, i.e. errors where a call was emitted against one method signature,
but the implementing method has an incompatible signature. Having more
precise type information helps drastically lower this risk, as well as
catching a number of latent bugs.
:::

(arc.optimization)=

## Optimization

Within this section, the word {arc-term}`function` will be used to
refer to any structured unit of code, be it a C function, an
Objective-C method, or a block.

This specification describes ARC as performing specific `retain` and
`release` operations on retainable object pointers at specific
points during the execution of a program. These operations make up a
non-contiguous subsequence of the computation history of the program.
The portion of this sequence for a particular retainable object
pointer for which a specific function execution is directly
responsible is the {arc-term}`formal local retain history` of the
object pointer. The corresponding actual sequence executed is the
`dynamic local retain history`.

However, under certain circumstances, ARC is permitted to re-order and
eliminate operations in a manner which may alter the overall
computation history beyond what is permitted by the general "as if"
rule of C/C++ and the {ref}`restrictions <arc.objects.retains>` on
the implementation of `retain` and `release`.

:::{admonition} Rationale
Specifically, ARC is sometimes permitted to optimize `release`
operations in ways which might cause an object to be deallocated
before it would otherwise be. Without this, it would be almost
impossible to eliminate any `retain`/`release` pairs. For
example, consider the following code:

```objc
id x = _ivar;
[x foo];
```

If we were not permitted in any event to shorten the lifetime of the
object in `x`, then we would not be able to eliminate this retain
and release unless we could prove that the message send could not
modify `_ivar` (or deallocate `self`). Since message sends are
opaque to the optimizer, this is not possible, and so ARC's hands
would be almost completely tied.
:::

ARC makes no guarantees about the execution of a computation history
which contains undefined behavior. In particular, ARC makes no
guarantees in the presence of race conditions.

ARC may assume that any retainable object pointers it receives or
generates are instantaneously valid from that point until a point
which, by the concurrency model of the host language, happens-after
the generation of the pointer and happens-before a release of that
object (possibly via an aliasing pointer or indirectly due to
destruction of a different object).

:::{admonition} Rationale
There is very little point in trying to guarantee correctness in the
presence of race conditions. ARC does not have a stack-scanning
garbage collector, and guaranteeing the atomicity of every load and
store operation would be prohibitive and preclude a vast amount of
optimization.
:::

ARC may assume that non-ARC code engages in sensible balancing
behavior and does not rely on exact or minimum retain count values
except as guaranteed by `__strong` object invariants or +1 transfer
conventions. For example, if an object is provably double-retained
and double-released, ARC may eliminate the inner retain and release;
it does not need to guard against code which performs an unbalanced
release followed by a "balancing" retain.

(arc.optimization.liveness)=

### Object liveness

ARC may not allow a retainable object `X` to be deallocated at a
time `T` in a computation history if:

- `X` is the value stored in a `__strong` object `S` with
  {ref}`precise lifetime semantics <arc.optimization.precise>`, or
- `X` is the value stored in a `__strong` object `S` with
  imprecise lifetime semantics and, at some point after `T` but
  before the next store to `S`, the computation history features a
  load from `S` and in some way depends on the value loaded, or
- `X` is a value described as being released at the end of the
  current full-expression and, at some point after `T` but before
  the end of the full-expression, the computation history depends
  on that value.

:::{admonition} Rationale
The intent of the second rule is to say that objects held in normal
`__strong` local variables may be released as soon as the value in
the variable is no longer being used: either the variable stops
being used completely or a new value is stored in the variable.

The intent of the third rule is to say that return values may be
released after they've been used.
:::

A computation history depends on a pointer value `P` if it:

- performs a pointer comparison with `P`,
- loads from `P`,
- stores to `P`,
- depends on a pointer value `Q` derived via pointer arithmetic
  from `P` (including an instance-variable or field access), or
- depends on a pointer value `Q` loaded from `P`.

Dependency applies only to values derived directly or indirectly from
a particular expression result and does not occur merely because a
separate pointer value dynamically aliases `P`. Furthermore, this
dependency is not carried by values that are stored to objects.

:::{admonition} Rationale
The restrictions on dependency are intended to make this analysis
feasible by an optimizer with only incomplete information about a
program. Essentially, dependence is carried to "obvious" uses of a
pointer. Merely passing a pointer argument to a function does not
itself cause dependence, but since generally the optimizer will not
be able to prove that the function doesn't depend on that parameter,
it will be forced to conservatively assume it does.

Dependency propagates to values loaded from a pointer because those
values might be invalidated by deallocating the object. For
example, given the code `__strong id x = p->ivar;`, ARC must not
move the release of `p` to between the load of `p->ivar` and the
retain of that value for storing into `x`.

Dependency does not propagate through stores of dependent pointer
values because doing so would allow dependency to outlive the
full-expression which produced the original value. For example, the
address of an instance variable could be written to some global
location and then freely accessed during the lifetime of the local,
or a function could return an inner pointer of an object and store
it to a local. These cases would be potentially impossible to
reason about and so would basically prevent any optimizations based
on imprecise lifetime. There are also uncommon enough to make it
reasonable to require the precise-lifetime annotation if someone
really wants to rely on them.

Dependency does propagate through return values of pointer type.
The compelling source of need for this rule is a property accessor
which returns an un-autoreleased result; the calling function must
have the chance to operate on the value, e.g. to retain it, before
ARC releases the original pointer. Note again, however, that
dependence does not survive a store, so ARC does not guarantee the
continued validity of the return value past the end of the
full-expression.
:::

(arc.optimization.object_lifetime)=

### No object lifetime extension

If, in the formal computation history of the program, an object `X`
has been deallocated by the time of an observable side-effect, then
ARC must cause `X` to be deallocated by no later than the occurrence
of that side-effect, except as influenced by the re-ordering of the
destruction of objects.

:::{admonition} Rationale
This rule is intended to prohibit ARC from observably extending the
lifetime of a retainable object, other than as specified in this
document. Together with the rule limiting the transformation of
releases, this rule requires ARC to eliminate retains and release
only in pairs.

ARC's power to reorder the destruction of objects is critical to its
ability to do any optimization, for essentially the same reason that
it must retain the power to decrease the lifetime of an object.
Unfortunately, while it's generally poor style for the destruction
of objects to have arbitrary side-effects, it's certainly possible.
Hence the caveat.
:::

(arc.optimization.precise)=

### Precise lifetime semantics

In general, ARC maintains an invariant that a retainable object pointer held in
a `__strong` object will be retained for the full formal lifetime of the
object. Objects subject to this invariant have {arc-term}`precise lifetime
semantics`.

By default, local variables of automatic storage duration do not have precise
lifetime semantics. Such objects are simply strong references which hold
values of retainable object pointer type, and these values are still fully
subject to the optimizations on values under local control.

:::{admonition} Rationale
Applying these precise-lifetime semantics strictly would be prohibitive.
Many useful optimizations that might theoretically decrease the lifetime of
an object would be rendered impossible. Essentially, it promises too much.
:::

A local variable of retainable object owner type and automatic storage duration
may be annotated with the `objc_precise_lifetime` attribute to indicate that
it should be considered to be an object with precise lifetime semantics.

:::{admonition} Rationale
Nonetheless, it is sometimes useful to be able to force an object to be
released at a precise time, even if that object does not appear to be used.
This is likely to be uncommon enough that the syntactic weight of explicitly
requesting these semantics will not be burdensome, and may even make the code
clearer.
:::

(arc.misc)=

## Miscellaneous

(arc.misc.special_methods)=

### Special methods

(arc.misc.special_methods.retain)=

#### Memory management methods

A program is ill-formed if it contains a method definition, message send, or
`@selector` expression for any of the following selectors:

- `autorelease`
- `release`
- `retain`
- `retainCount`

:::{admonition} Rationale
`retainCount` is banned because ARC robs it of consistent semantics. The
others were banned after weighing three options for how to deal with message
sends:

**Honoring** them would work out very poorly if a programmer naively or
accidentally tried to incorporate code written for manual retain/release code
into an ARC program. At best, such code would do twice as much work as
necessary; quite frequently, however, ARC and the explicit code would both
try to balance the same retain, leading to crashes. The cost is losing the
ability to perform "unrooted" retains, i.e. retains not logically
corresponding to a strong reference in the object graph.

**Ignoring** them would badly violate user expectations about their code.
While it *would* make it easier to develop code simultaneously for ARC and
non-ARC, there is very little reason to do so except for certain library
developers. ARC and non-ARC translation units share an execution model and
can seamlessly interoperate. Within a translation unit, a developer who
faithfully maintains their code in non-ARC mode is suffering all the
restrictions of ARC for zero benefit, while a developer who isn't testing the
non-ARC mode is likely to be unpleasantly surprised if they try to go back to
it.

**Banning** them has the disadvantage of making it very awkward to migrate
existing code to ARC. The best answer to that, given a number of other
changes and restrictions in ARC, is to provide a specialized tool to assist
users in that migration.

Implementing these methods was banned because they are too integral to the
semantics of ARC; many tricks which worked tolerably under manual reference
counting will misbehave if ARC performs an ephemeral extra retain or two. If
absolutely required, it is still possible to implement them in non-ARC code,
for example in a category; the implementations must obey the {ref}`semantics
<arc.objects.retains>` laid out elsewhere in this document.
:::

(arc.misc.special_methods.dealloc)=

#### `dealloc`

A program is ill-formed if it contains a message send or `@selector`
expression for the selector `dealloc`.

:::{admonition} Rationale
There are no legitimate reasons to call `dealloc` directly.
:::

A class may provide a method definition for an instance method named
`dealloc`. This method will be called after the final `release` of the
object but before it is deallocated or any of its instance variables are
destroyed. The superclass's implementation of `dealloc` will be called
automatically when the method returns.

:::{admonition} Rationale
Even though ARC destroys instance variables automatically, there are still
legitimate reasons to write a `dealloc` method, such as freeing
non-retainable resources. Failing to call `[super dealloc]` in such a
method is nearly always a bug. Sometimes, the object is simply trying to
prevent itself from being destroyed, but `dealloc` is really far too late
for the object to be raising such objections. Somewhat more legitimately, an
object may have been pool-allocated and should not be deallocated with
`free`; for now, this can only be supported with a `dealloc`
implementation outside of ARC. Such an implementation must be very careful
to do all the other work that `NSObject`'s `dealloc` would, which is
outside the scope of this document to describe.
:::

The instance variables for an ARC-compiled class will be destroyed at some
point after control enters the `dealloc` method for the root class of the
class. The ordering of the destruction of instance variables is unspecified,
both within a single class and between subclasses and superclasses.

:::{admonition} Rationale
The traditional, non-ARC pattern for destroying instance variables is to
destroy them immediately before calling `[super dealloc]`. Unfortunately,
message sends from the superclass are quite capable of reaching methods in
the subclass, and those methods may well read or write to those instance
variables. Making such message sends from dealloc is generally discouraged,
since the subclass may well rely on other invariants that were broken during
`dealloc`, but it's not so inescapably dangerous that we felt comfortable
calling it undefined behavior. Therefore we chose to delay destroying the
instance variables to a point at which message sends are clearly disallowed:
the point at which the root class's deallocation routines take over.

In most code, the difference is not observable. It can, however, be observed
if an instance variable holds a strong reference to an object whose
deallocation will trigger a side-effect which must be carefully ordered with
respect to the destruction of the super class. Such code violates the design
principle that semantically important behavior should be explicit. A simple
fix is to clear the instance variable manually during `dealloc`; a more
holistic solution is to move semantically important side-effects out of
`dealloc` and into a separate teardown phase which can rely on working with
well-formed objects.
:::

(arc.misc.autoreleasepool)=

### `@autoreleasepool`

To simplify the use of autorelease pools, and to bring them under the control
of the compiler, a new kind of statement is available in Objective-C. It is
written `@autoreleasepool` followed by a *compound-statement*, i.e. by a new
scope delimited by curly braces. Upon entry to this block, the current state
of the autorelease pool is captured. When the block is exited normally,
whether by fallthrough or directed control flow (such as `return` or
`break`), the autorelease pool is restored to the saved state, releasing all
the objects in it. When the block is exited with an exception, the pool is not
drained.

`@autoreleasepool` may be used in non-ARC translation units, with equivalent
semantics.

A program is ill-formed if it refers to the `NSAutoreleasePool` class.

:::{admonition} Rationale
Autorelease pools are clearly important for the compiler to reason about, but
it is far too much to expect the compiler to accurately reason about control
dependencies between two calls. It is also very easy to accidentally forget
to drain an autorelease pool when using the manual API, and this can
significantly inflate the process's high-water-mark. The introduction of a
new scope is unfortunate but basically required for sane interaction with the
rest of the language. Not draining the pool during an unwind is apparently
required by the Objective-C exceptions implementation.
:::

(arc.misc.externally_retained)=

### Externally-Retained Variables

In some situations, variables with strong ownership are considered
externally-retained by the implementation. This means that the variable is
retained elsewhere, and therefore the implementation can elide retaining and
releasing its value. Such a variable is implicitly `const` for safety. In
contrast with `__unsafe_unretained`, an externally-retained variable still
behaves as a strong variable outside of initialization and destruction. For
instance, when an externally-retained variable is captured in a block the value
of the variable is retained and released on block capture and destruction. It
also affects C++ features such as lambda capture, `decltype`, and template
argument deduction.

Implicitly, the implementation assumes that the {ref}`self parameter in a
non-init method <arc.misc.self>` and the {ref}`variable in a for-in loop
<arc.misc.enumeration>` are externally-retained.

Externally-retained semantics can also be opted into with the
`objc_externally_retained` attribute. This attribute can apply to strong local
variables, functions, methods, or blocks:

```objc
@class WobbleAmount;

@interface Widget : NSObject
-(void)wobble:(WobbleAmount *)amount;
@end

@implementation Widget

-(void)wobble:(WobbleAmount *)amount
         __attribute__((objc_externally_retained)) {
  // 'amount' and 'alias' aren't retained on entry, nor released on exit.
  __attribute__((objc_externally_retained)) WobbleAmount *alias = amount;
}
@end
```

Annotating a function with this attribute makes every parameter with strong
retainable object pointer type externally-retained, unless the variable was
explicitly qualified with `__strong`. For instance, `first_param` is
externally-retained (and therefore `const`) below, but not `second_param`:

```objc
__attribute__((objc_externally_retained))
void f(NSArray *first_param, __strong NSArray *second_param) {
  // ...
}
```

You can test if your compiler has support for `objc_externally_retained` with
`__has_attribute`:

```objc
#if __has_attribute(objc_externally_retained)
// Use externally retained...
#endif
```

(arc.misc.self)=

### `self`

The `self` parameter variable of a non-init Objective-C method is considered
{ref}`externally-retained <arc.misc.externally_retained>` by the implementation.
It is undefined behavior, or at least dangerous, to cause an object to be
deallocated during a message send to that object. In an init method, `self`
follows the {ref}`init family rules <arc.family.semantics.init>`.

:::{admonition} Rationale
The cost of retaining `self` in all methods was found to be prohibitive, as
it tends to be live across calls, preventing the optimizer from proving that
the retain and release are unnecessary --- for good reason, as it's quite
possible in theory to cause an object to be deallocated during its execution
without this retain and release. Since it's extremely uncommon to actually
do so, even unintentionally, and since there's no natural way for the
programmer to remove this retain/release pair otherwise (as there is for
other parameters by, say, making the variable `objc_externally_retained` or
qualifying it with `__unsafe_unretained`), we chose to make this optimizing
assumption and shift some amount of risk to the user.
:::

(arc.misc.enumeration)=

### Fast enumeration iteration variables

If a variable is declared in the condition of an Objective-C fast enumeration
loop, and the variable has no explicit ownership qualifier, then it is
implicitly {ref}`externally-retained <arc.misc.externally_retained>` so that
objects encountered during the enumeration are not actually retained and
released.

:::{admonition} Rationale
This is an optimization made possible because fast enumeration loops promise
to keep the objects retained during enumeration, and the collection itself
cannot be synchronously modified. It can be overridden by explicitly
qualifying the variable with `__strong`, which will make the variable
mutable again and cause the loop to retain the objects it encounters.
:::

(arc.misc.blocks)=

### Blocks

The implicit `const` capture variables created when evaluating a block
literal expression have the same ownership semantics as the local variables
they capture. The capture is performed by reading from the captured variable
and initializing the capture variable with that value; the capture variable is
destroyed when the block literal is, i.e. at the end of the enclosing scope.

The {ref}`inference <arc.ownership.inference>` rules apply equally to
`__block` variables, which is a shift in semantics from non-ARC, where
`__block` variables did not implicitly retain during capture.

`__block` variables of retainable object owner type are moved off the stack
by initializing the heap copy with the result of moving from the stack copy.

With the exception of retains done as part of initializing a `__strong`
parameter variable or reading a `__weak` variable, whenever these semantics
call for retaining a value of block-pointer type, it has the effect of a
`Block_copy`. The optimizer may remove such copies when it sees that the
result is used only as an argument to a call.

When a block pointer type is converted to a non-block pointer type (such as
`id`), `Block_copy` is called. This is necessary because a block allocated
on the stack won't get copied to the heap when the non-block pointer escapes.
A block pointer is implicitly converted to `id` when it is passed to a
function as a variadic argument.

(arc.misc.exceptions)=

### Exceptions

By default in Objective C, ARC is not exception-safe for normal releases:

- It does not end the lifetime of `__strong` variables when their scopes are
  abnormally terminated by an exception.
- It does not perform releases which would occur at the end of a
  full-expression if that full-expression throws an exception.

A program may be compiled with the option `-fobjc-arc-exceptions` in order to
enable these, or with the option `-fno-objc-arc-exceptions` to explicitly
disable them, with the last such argument "winning".

:::{admonition} Rationale
The standard Cocoa convention is that exceptions signal programmer error and
are not intended to be recovered from. Making code exceptions-safe by
default would impose severe runtime and code size penalties on code that
typically does not actually care about exceptions safety. Therefore,
ARC-generated code leaks by default on exceptions, which is just fine if the
process is going to be immediately terminated anyway. Programs which do care
about recovering from exceptions should enable the option.
:::

In Objective-C++, `-fobjc-arc-exceptions` is enabled by default.

:::{admonition} Rationale
C++ already introduces pervasive exceptions-cleanup code of the sort that ARC
introduces. C++ programmers who have not already disabled exceptions are
much more likely to actual require exception-safety.
:::

ARC does end the lifetimes of `__weak` objects when an exception terminates
their scope unless exceptions are disabled in the compiler.

:::{admonition} Rationale
The consequence of a local `__weak` object not being destroyed is very
likely to be corruption of the Objective-C runtime, so we want to be safer
here. Of course, potentially massive leaks are about as likely to take down
the process as this corruption is if the program does try to recover from
exceptions.
:::

(arc.misc.interior)=

### Interior pointers

An Objective-C method returning a non-retainable pointer may be annotated with
the `objc_returns_inner_pointer` attribute to indicate that it returns a
handle to the internal data of an object, and that this reference will be
invalidated if the object is destroyed. When such a message is sent to an
object, the object's lifetime will be extended until at least the earliest of:

- the last use of the returned pointer, or any pointer derived from it, in the
  calling function or
- the autorelease pool is restored to a previous state.

:::{admonition} Rationale
Rationale: not all memory and resources are managed with reference counts; it
is common for objects to manage private resources in their own, private way.
Typically these resources are completely encapsulated within the object, but
some classes offer their users direct access for efficiency. If ARC is not
aware of methods that return such "interior" pointers, its optimizations can
cause the owning object to be reclaimed too soon. This attribute informs ARC
that it must tread lightly.

The extension rules are somewhat intentionally vague. The autorelease pool
limit is there to permit a simple implementation to simply retain and
autorelease the receiver. The other limit permits some amount of
optimization. The phrase "derived from" is intended to encompass the results
both of pointer transformations, such as casts and arithmetic, and of loading
from such derived pointers; furthermore, it applies whether or not such
derivations are applied directly in the calling code or by other utility code
(for example, the C library routine `strchr`). However, the implementation
never need account for uses after a return from the code which calls the
method returning an interior pointer.
:::

As an exception, no extension is required if the receiver is loaded directly
from a `__strong` object with {ref}`precise lifetime semantics
<arc.optimization.precise>`.

:::{admonition} Rationale
Implicit autoreleases carry the risk of significantly inflating memory use,
so it's important to provide users a way of avoiding these autoreleases.
Tying this to precise lifetime semantics is ideal, as for local variables
this requires a very explicit annotation, which allows ARC to trust the user
with good cheer.
:::

(arc.misc.c-retainable)=

### C retainable pointer types

A type is a {arc-term}`C retainable pointer type` if it is a pointer to
(possibly qualified) `void` or a pointer to a (possibly qualifier) `struct`
or `class` type.

:::{admonition} Rationale
ARC does not manage pointers of CoreFoundation type (or any of the related
families of retainable C pointers which interoperate with Objective-C for
retain/release operation). In fact, ARC does not even know how to
distinguish these types from arbitrary C pointer types. The intent of this
concept is to filter out some obviously non-object types while leaving a hook
for later tightening if a means of exhaustively marking CF types is made
available.
:::

(arc.misc.c-retainable.audit)=

#### Auditing of C retainable pointer interfaces

{when-revised}`[beginning Apple 4.0, LLVM 3.1]`

A C function may be marked with the `cf_audited_transfer` attribute to
express that, except as otherwise marked with attributes, it obeys the
parameter (consuming vs. non-consuming) and return (retained vs. non-retained)
conventions for a C function of its name, namely:

- A parameter of C retainable pointer type is assumed to not be consumed
  unless it is marked with the `cf_consumed` attribute, and
- A result of C retainable pointer type is assumed to not be returned retained
  unless the function is either marked `cf_returns_retained` or it follows
  the create/copy naming convention and is not marked
  `cf_returns_not_retained`.

A function obeys the {arc-term}`create/copy` naming convention if its name
contains as a substring:

- either "Create" or "Copy" not followed by a lowercase letter, or
- either "create" or "copy" not followed by a lowercase letter and
  not preceded by any letter, whether uppercase or lowercase.

A second attribute, `cf_unknown_transfer`, signifies that a function's
transfer semantics cannot be accurately captured using any of these
annotations. A program is ill-formed if it annotates the same function with
both `cf_audited_transfer` and `cf_unknown_transfer`.

A pragma is provided to facilitate the mass annotation of interfaces:

```objc
#pragma clang arc_cf_code_audited begin
...
#pragma clang arc_cf_code_audited end
```

All C functions declared within the extent of this pragma are treated as if
annotated with the `cf_audited_transfer` attribute unless they otherwise have
the `cf_unknown_transfer` attribute. The pragma is accepted in all language
modes. A program is ill-formed if it attempts to change files, whether by
including a file or ending the current file, within the extent of this pragma.

It is possible to test for all the features in this section with
`__has_feature(arc_cf_code_audited)`.

:::{admonition} Rationale
A significant inconvenience in ARC programming is the necessity of
interacting with APIs based around C retainable pointers. These features are
designed to make it relatively easy for API authors to quickly review and
annotate their interfaces, in turn improving the fidelity of tools such as
the static analyzer and ARC. The single-file restriction on the pragma is
designed to eliminate the risk of accidentally annotating some other header's
interfaces.
:::

(arc.runtime)=

## Runtime support

This section describes the interaction between the ARC runtime and the code
generated by the ARC compiler. This is not part of the ARC language
specification; instead, it is effectively a language-specific ABI supplement,
akin to the "Itanium" generic ABI for C++.

Ownership qualification does not alter the storage requirements for objects,
except that it is undefined behavior if a `__weak` object is inadequately
aligned for an object of type `id`. The other qualifiers may be used on
explicitly under-aligned memory.

The runtime tracks `__weak` objects which holds non-null values. It is
undefined behavior to directly modify a `__weak` object which is being tracked
by the runtime except through an
{ref}`objc_storeWeak <arc.runtime.objc_storeWeak>`,
{ref}`objc_destroyWeak <arc.runtime.objc_destroyWeak>`, or
{ref}`objc_moveWeak <arc.runtime.objc_moveWeak>` call.

The runtime must provide a number of new entrypoints which the compiler may
emit, which are described in the remainder of this section.

:::{admonition} Rationale
Several of these functions are semantically equivalent to a message send; we
emit calls to C functions instead because:

- the machine code to do so is significantly smaller,
- it is much easier to recognize the C functions in the ARC optimizer, and
- a sufficiently sophisticated runtime may be able to avoid the message send in
  common cases.

Several other of these functions are "fused" operations which can be
described entirely in terms of other operations. We use the fused operations
primarily as a code-size optimization, although in some cases there is also a
real potential for avoiding redundant operations in the runtime.
:::

(arc.runtime.objc_autorelease)=

### `id objc_autorelease(id value);`

*Precondition:* `value` is null or a pointer to a valid object.

If `value` is null, this call has no effect. Otherwise, it adds the object
to the innermost autorelease pool exactly as if the object had been sent the
`autorelease` message.

Always returns `value`.

(arc.runtime.objc_autoreleasePoolPop)=

### `void objc_autoreleasePoolPop(void *pool);`

*Precondition:* `pool` is the result of a previous call to
{ref}`objc_autoreleasePoolPush <arc.runtime.objc_autoreleasePoolPush>` on the
current thread, where neither `pool` nor any enclosing pool have previously
been popped.

Releases all the objects added to the given autorelease pool and any
autorelease pools it encloses, then sets the current autorelease pool to the
pool directly enclosing `pool`.

(arc.runtime.objc_autoreleasePoolPush)=

### `void *objc_autoreleasePoolPush(void);`

Creates a new autorelease pool that is enclosed by the current pool, makes that
the current pool, and returns an opaque "handle" to it.

:::{admonition} Rationale
While the interface is described as an explicit hierarchy of pools, the rules
allow the implementation to just keep a stack of objects, using the stack
depth as the opaque pool handle.
:::

(arc.runtime.objc_autoreleaseReturnValue)=

### `id objc_autoreleaseReturnValue(id value);`

*Precondition:* `value` is null or a pointer to a valid object.

If `value` is null, this call has no effect. Otherwise, it makes a best
effort to hand off ownership of a retain count on the object to a call to
{ref}`objc_retainAutoreleasedReturnValue
<arc.runtime.objc_retainAutoreleasedReturnValue>` (or
{ref}`objc_unsafeClaimAutoreleasedReturnValue
<arc.runtime.objc_unsafeClaimAutoreleasedReturnValue>`) for the same object in
an enclosing call frame. If this is not possible, the object is autoreleased as
above.

Always returns `value`.

(arc.runtime.objc_copyWeak)=

### `void objc_copyWeak(id *dest, id *src);`

*Precondition:* `src` is a valid pointer which either contains a null pointer
or has been registered as a `__weak` object. `dest` is a valid pointer
which has not been registered as a `__weak` object.

`dest` is initialized to be equivalent to `src`, potentially registering it
with the runtime. Equivalent to the following code:

```objc
void objc_copyWeak(id *dest, id *src) {
  objc_release(objc_initWeak(dest, objc_loadWeakRetained(src)));
}
```

Must be atomic with respect to calls to `objc_storeWeak` on `src`.

(arc.runtime.objc_destroyWeak)=

### `void objc_destroyWeak(id *object);`

*Precondition:* `object` is a valid pointer which either contains a null
pointer or has been registered as a `__weak` object.

`object` is unregistered as a weak object, if it ever was. The current value
of `object` is left unspecified; otherwise, equivalent to the following code:

```objc
void objc_destroyWeak(id *object) {
  objc_storeWeak(object, nil);
}
```

Does not need to be atomic with respect to calls to `objc_storeWeak` on
`object`.

(arc.runtime.objc_initWeak)=

### `id objc_initWeak(id *object, id value);`

*Precondition:* `object` is a valid pointer which has not been registered as
a `__weak` object. `value` is null or a pointer to a valid object.

If `value` is a null pointer or the object to which it points has begun
deallocation, `object` is zero-initialized. Otherwise, `object` is
registered as a `__weak` object pointing to `value`. Equivalent to the
following code:

```objc
id objc_initWeak(id *object, id value) {
  *object = nil;
  return objc_storeWeak(object, value);
}
```

Returns the value of `object` after the call.

Does not need to be atomic with respect to calls to `objc_storeWeak` on
`object`.

(arc.runtime.objc_loadWeak)=

### `id objc_loadWeak(id *object);`

*Precondition:* `object` is a valid pointer which either contains a null
pointer or has been registered as a `__weak` object.

If `object` is registered as a `__weak` object, and the last value stored
into `object` has not yet been deallocated or begun deallocation, retains and
autoreleases that value and returns it. Otherwise returns null. Equivalent to
the following code:

```objc
id objc_loadWeak(id *object) {
  return objc_autorelease(objc_loadWeakRetained(object));
}
```

Must be atomic with respect to calls to `objc_storeWeak` on `object`.

:::{admonition} Rationale
Loading weak references would be inherently prone to race conditions without
the retain.
:::

(arc.runtime.objc_loadWeakRetained)=

### `id objc_loadWeakRetained(id *object);`

*Precondition:* `object` is a valid pointer which either contains a null
pointer or has been registered as a `__weak` object.

If `object` is registered as a `__weak` object, and the last value stored
into `object` has not yet been deallocated or begun deallocation, retains
that value and returns it. Otherwise returns null.

Must be atomic with respect to calls to `objc_storeWeak` on `object`.

(arc.runtime.objc_moveWeak)=

### `void objc_moveWeak(id *dest, id *src);`

*Precondition:* `src` is a valid pointer which either contains a null pointer
or has been registered as a `__weak` object. `dest` is a valid pointer
which has not been registered as a `__weak` object.

`dest` is initialized to be equivalent to `src`, potentially registering it
with the runtime. `src` may then be left in its original state, in which
case this call is equivalent to {ref}`objc_copyWeak
<arc.runtime.objc_copyWeak>`, or it may be left as null.

Must be atomic with respect to calls to `objc_storeWeak` on `src`.

(arc.runtime.objc_release)=

### `void objc_release(id value);`

*Precondition:* `value` is null or a pointer to a valid object.

If `value` is null, this call has no effect. Otherwise, it performs a
release operation exactly as if the object had been sent the `release`
message.

(arc.runtime.objc_retain)=

### `id objc_retain(id value);`

*Precondition:* `value` is null or a pointer to a valid object.

If `value` is null, this call has no effect. Otherwise, it performs a retain
operation exactly as if the object had been sent the `retain` message.

Always returns `value`.

(arc.runtime.objc_retainAutorelease)=

### `id objc_retainAutorelease(id value);`

*Precondition:* `value` is null or a pointer to a valid object.

If `value` is null, this call has no effect. Otherwise, it performs a retain
operation followed by an autorelease operation. Equivalent to the following
code:

```objc
id objc_retainAutorelease(id value) {
  return objc_autorelease(objc_retain(value));
}
```

Always returns `value`.

(arc.runtime.objc_retainAutoreleaseReturnValue)=

### `id objc_retainAutoreleaseReturnValue(id value);`

*Precondition:* `value` is null or a pointer to a valid object.

If `value` is null, this call has no effect. Otherwise, it performs a retain
operation followed by the operation described in
{ref}`objc_autoreleaseReturnValue <arc.runtime.objc_autoreleaseReturnValue>`.
Equivalent to the following code:

```objc
id objc_retainAutoreleaseReturnValue(id value) {
  return objc_autoreleaseReturnValue(objc_retain(value));
}
```

Always returns `value`.

(arc.runtime.objc_retainAutoreleasedReturnValue)=

### `id objc_retainAutoreleasedReturnValue(id value);`

*Precondition:* `value` is null or a pointer to a valid object.

If `value` is null, this call has no effect. Otherwise, it attempts to
accept a hand off of a retain count from a call to
{ref}`objc_autoreleaseReturnValue <arc.runtime.objc_autoreleaseReturnValue>` on
`value` in a recently-called function or something it tail-calls. If that
fails, it performs a retain operation exactly like {ref}`objc_retain
<arc.runtime.objc_retain>`.

Always returns `value`.

(arc.runtime.objc_retainBlock)=

### `id objc_retainBlock(id value);`

*Precondition:* `value` is null or a pointer to a valid block object.

If `value` is null, this call has no effect. Otherwise, if the block pointed
to by `value` is still on the stack, it is copied to the heap and the address
of the copy is returned. Otherwise a retain operation is performed on the
block exactly as if it had been sent the `retain` message.

(arc.runtime.objc_storeStrong)=

### `void objc_storeStrong(id *object, id value);`

*Precondition:* `object` is a valid pointer to a `__strong` object which is
adequately aligned for a pointer. `value` is null or a pointer to a valid
object.

Performs the complete sequence for assigning to a `__strong` object of
non-block type [^arc-store-strong-block]. Equivalent to the following code:

```objc
void objc_storeStrong(id *object, id value) {
  id oldValue = *object;
  value = [value retain];
  *object = value;
  [oldValue release];
}
```

[^arc-store-strong-block]: This does not imply that a `__strong` object of block
    type is an invalid argument to this function. Rather it implies that an
    `objc_retain` and not an `objc_retainBlock` operation will be emitted if the
    argument is a block.

(arc.runtime.objc_storeWeak)=

### `id objc_storeWeak(id *object, id value);`

*Precondition:* `object` is a valid pointer which either contains a null
pointer or has been registered as a `__weak` object. `value` is null or a
pointer to a valid object.

If `value` is a null pointer or the object to which it points has begun
deallocation, `object` is assigned null and unregistered as a `__weak`
object. Otherwise, `object` is registered as a `__weak` object or has its
registration updated to point to `value`.

Returns the value of `object` after the call.

(arc.runtime.objc_unsafeClaimAutoreleasedReturnValue)=

### `id objc_unsafeClaimAutoreleasedReturnValue(id value);`

*Precondition:* `value` is null or a pointer to a valid object.

If `value` is null, this call has no effect. Otherwise, it attempts to
accept a hand off of a retain count from a call to
{ref}`objc_autoreleaseReturnValue <arc.runtime.objc_autoreleaseReturnValue>` on
`value` in a recently-called function or something it tail-calls (in a manner
similar to {ref}`objc_retainAutoreleasedReturnValue
<arc.runtime.objc_retainAutoreleasedReturnValue>`). If that succeeds,
it performs a release operation exactly like {ref}`objc_release
<arc.runtime.objc_release>`. If the handoff fails, this call has no effect.

Always returns `value`.

---

### Clang Docs Block ABI Apple (`clang/docs/Block-ABI-Apple.md`)

# Block Implementation Specification


## History

- 2008/7/14 - created.
- 2008/8/21 - revised, C++.
- 2008/9/24 - add `NULL` `isa` field to `__block` storage.
- 2008/10/1 - revise block layout to use a `static` descriptor structure.
- 2008/10/6 - revise block layout to use an unsigned long int flags.
- 2008/10/28 - specify use of `_Block_object_assign` and
  `_Block_object_dispose` for all "Object" types in helper functions.
- 2008/10/30 - revise new layout to have invoke function in same place.
- 2008/10/30 - add `__weak` support.
- 2010/3/16 - rev for stret return, signature field.
- 2010/4/6 - improved wording.
- 2013/1/6 - improved wording and converted to rst.

This document describes the Apple ABI implementation specification of Blocks.

The first shipping version of this ABI is found in Mac OS X 10.6, and shall be
referred to as 10.6.ABI. As of 2010/3/16, the following describes the ABI
contract with the runtime and the compiler, and, as necessary, will be referred
to as ABI.2010.3.16.

Since the Apple ABI references symbols from other elements of the system, any
attempt to use this ABI on systems prior to SnowLeopard is undefined.

## High Level

The ABI of `Blocks` consists of their layout and the runtime functions required
by the compiler. A `Block` of type `R (^)(P...)` consists of a structure of
the following form:

```c
struct Block_literal_1 {
    void *isa; // initialized to &_NSConcreteStackBlock or &_NSConcreteGlobalBlock
    int flags;
    int reserved;
    R (*invoke)(struct Block_literal_1 *, P...);
    struct Block_descriptor_1 {
        unsigned long int reserved;     // NULL
        unsigned long int size;         // sizeof(struct Block_literal_1)
        // optional helper functions
        void (*copy_helper)(void *dst, void *src);     // IFF (1<<25)
        void (*dispose_helper)(void *src);             // IFF (1<<25)
        // required ABI.2010.3.16
        const char *signature;                         // IFF (1<<30)
    } *descriptor;
    // imported variables
};
```

The following flags bits are in use thusly for a possible ABI.2010.3.16:

```c
enum {
    // Set to true on blocks that have captures (and thus are not true
    // global blocks) but are known not to escape for various other
    // reasons. For backward compatibility with old runtimes, whenever
    // BLOCK_IS_NOESCAPE is set, BLOCK_IS_GLOBAL is set too. Copying a
    // non-escaping block returns the original block and releasing such a
    // block is a no-op, which is exactly how global blocks are handled.
    BLOCK_IS_NOESCAPE      =  (1 << 23),

    BLOCK_HAS_COPY_DISPOSE =  (1 << 25),
    BLOCK_HAS_CTOR =          (1 << 26), // helpers have C++ code
    BLOCK_IS_GLOBAL =         (1 << 28),
    BLOCK_HAS_STRET =         (1 << 29), // IFF BLOCK_HAS_SIGNATURE
    BLOCK_HAS_SIGNATURE =     (1 << 30),
};
```

In 10.6.ABI the (1\<<29) was usually set and was always ignored by the runtime -
it had been a transitional marker that did not get deleted after the
transition. This bit is now paired with (1\<<30), and represented as the pair
(3\<<29), for the following combinations of valid bit settings, and their
meanings:

```c
switch (flags & (3<<29)) {
  case (0<<29):      10.6.ABI, no signature field available
  case (1<<29):      10.6.ABI, no signature field available
  case (2<<29): ABI.2010.3.16, regular calling convention, presence of signature field
  case (3<<29): ABI.2010.3.16, stret calling convention, presence of signature field,
}
```

The signature field is not always populated.

The following discussions are presented as 10.6.ABI otherwise.

`Block` literals may occur within functions where the structure is created in
stack local memory. They may also appear as initialization expressions for
`Block` variables of global or `static` local variables.

When a `Block` literal expression is evaluated the stack based structure is
initialized as follows:

1. A `static` descriptor structure is declared and initialized as follows:

   a. The `invoke` function pointer is set to a function that takes the
      `Block` structure as its first argument and the rest of the arguments (if
      any) to the `Block` and executes the `Block` compound statement.

   b. The `size` field is set to the size of the following `Block` literal
      structure.

   c. The `copy_helper` and `dispose_helper` function pointers are set to
      respective helper functions if they are required by the `Block` literal.

2. A stack (or global) `Block` literal data structure is created and
   initialized as follows:

   a. The `isa` field is set to the address of the external
   `_NSConcreteStackBlock`, which is a block of uninitialized memory supplied
   in `libSystem`, or `_NSConcreteGlobalBlock` if this is a static or file
   level `Block` literal.

   b. The `flags` field is set to zero unless there are variables imported
   into the `Block` that need helper functions for program level
   `Block_copy()` and `Block_release()` operations, in which case the
     `(1<<25)` flags bit is set.

As an example, the `Block` literal expression:

```c
^ { printf("hello world\n"); }
```

would cause the following to be created on a 32-bit system:

```c
struct __block_literal_1 {
    void *isa;
    int flags;
    int reserved;
    void (*invoke)(struct __block_literal_1 *);
    struct __block_descriptor_1 *descriptor;
};

void __block_invoke_1(struct __block_literal_1 *_block) {
    printf("hello world\n");
}

static struct __block_descriptor_1 {
    unsigned long int reserved;
    unsigned long int Block_size;
} __block_descriptor_1 = { 0, sizeof(struct __block_literal_1) };
```

and where the `Block` literal itself appears:

```c
struct __block_literal_1 _block_literal = {
     &_NSConcreteStackBlock,
     (1<<29), <uninitialized>,
     __block_invoke_1,
     &__block_descriptor_1
};
```

A `Block` imports other `Block` references, `const` copies of other
variables, and variables marked `__block`. In Objective-C, variables may
additionally be objects.

When a `Block` literal expression is used as the initial value of a global
or `static` local variable, it is initialized as follows:

```c
struct __block_literal_1 __block_literal_1 = {
      &_NSConcreteGlobalBlock,
      (1<<28)|(1<<29), <uninitialized>,
      __block_invoke_1,
      &__block_descriptor_1
};
```

that is, a different address is provided as the first value and a particular
(1\<<28) bit is set in the `flags` field, and otherwise it is the same as for
stack based `Block` literals. This is an optimization that can be used for
any `Block` literal that imports no `const` or `__block` storage
variables.

## Imported Variables

Variables of `auto` storage class are imported as `const` copies. Variables
of `__block` storage class are imported as a pointer to an enclosing data
structure. Global variables are simply referenced and not considered as
imported.

### Imported `const` copy variables

Automatic storage variables not marked with `__block` are imported as
`const` copies.

The simplest example is that of importing a variable of type `int`:

```c
int x = 10;
void (^vv)(void) = ^{ printf("x is %d\n", x); }
x = 11;
vv();
```

which would be compiled to:

```c
struct __block_literal_2 {
    void *isa;
    int flags;
    int reserved;
    void (*invoke)(struct __block_literal_2 *);
    struct __block_descriptor_2 *descriptor;
    const int x;
};

void __block_invoke_2(struct __block_literal_2 *_block) {
    printf("x is %d\n", _block->x);
}

static struct __block_descriptor_2 {
    unsigned long int reserved;
    unsigned long int Block_size;
} __block_descriptor_2 = { 0, sizeof(struct __block_literal_2) };
```

and:

```c
struct __block_literal_2 __block_literal_2 = {
      &_NSConcreteStackBlock,
      (1<<29), <uninitialized>,
      __block_invoke_2,
      &__block_descriptor_2,
      x
 };
```

In summary, scalars, structures, unions, and function pointers are generally
imported as `const` copies with no need for helper functions.

### Imported `const` copy of `Block` reference

The first case where copy and dispose helper functions are required is for the
case of when a `Block` itself is imported. In this case both a
`copy_helper` function and a `dispose_helper` function are needed. The
`copy_helper` function is passed both the existing stack based pointer and the
pointer to the new heap version and should call back into the runtime to
actually do the copy operation on the imported fields within the `Block`. The
runtime functions are all described in {ref}`RuntimeHelperFunctions`.

A quick example:

```c
void (^existingBlock)(void) = ...;
void (^vv)(void) = ^{ existingBlock(); }
vv();

struct __block_literal_3 {
   ...; // existing block
};

struct __block_literal_4 {
    void *isa;
    int flags;
    int reserved;
    void (*invoke)(struct __block_literal_4 *);
    struct __block_literal_3 *const existingBlock;
};

void __block_invoke_4(struct __block_literal_2 *_block) {
   __block->existingBlock->invoke(__block->existingBlock);
}

void __block_copy_4(struct __block_literal_4 *dst, struct __block_literal_4 *src) {
     //_Block_copy_assign(&dst->existingBlock, src->existingBlock, 0);
     _Block_object_assign(&dst->existingBlock, src->existingBlock, BLOCK_FIELD_IS_BLOCK);
}

void __block_dispose_4(struct __block_literal_4 *src) {
     // was _Block_destroy
     _Block_object_dispose(src->existingBlock, BLOCK_FIELD_IS_BLOCK);
}

static struct __block_descriptor_4 {
    unsigned long int reserved;
    unsigned long int Block_size;
    void (*copy_helper)(struct __block_literal_4 *dst, struct __block_literal_4 *src);
    void (*dispose_helper)(struct __block_literal_4 *);
} __block_descriptor_4 = {
    0,
    sizeof(struct __block_literal_4),
    __block_copy_4,
    __block_dispose_4,
};
```

and where said `Block` is used:

```c
struct __block_literal_4 _block_literal = {
      &_NSConcreteStackBlock,
      (1<<25)|(1<<29), <uninitialized>
      __block_invoke_4,
      & __block_descriptor_4
      existingBlock,
};
```

#### Importing `__attribute__((NSObject))` variables

GCC introduces `__attribute__((NSObject))` on structure pointers to mean "this
is an object". This is useful because many low level data structures are
declared as opaque structure pointers, e.g. `CFStringRef`, `CFArrayRef`,
etc. When used from C, however, these are still really objects and are the
second case where that requires copy and dispose helper functions to be
generated. The copy helper functions generated by the compiler should use the
`_Block_object_assign` runtime helper function and in the dispose helper the
`_Block_object_dispose` runtime helper function should be called.

For example, `Block` foo in the following:

```c
struct Opaque *__attribute__((NSObject)) objectPointer = ...;
...
void (^foo)(void) = ^{  CFPrint(objectPointer); };
```

would have the following helper functions generated:

```c
void __block_copy_foo(struct __block_literal_5 *dst, struct __block_literal_5 *src) {
     _Block_object_assign(&dst->objectPointer, src-> objectPointer, BLOCK_FIELD_IS_OBJECT);
}

void __block_dispose_foo(struct __block_literal_5 *src) {
     _Block_object_dispose(src->objectPointer, BLOCK_FIELD_IS_OBJECT);
}
```

### Imported `__block` marked variables

#### Layout of `__block` marked variables

The compiler must embed variables that are marked `__block` in a specialized
structure of the form:

```c
struct _block_byref_foo {
    void *isa;
    struct Block_byref *forwarding;
    int flags;   //refcount;
    int size;
    typeof(marked_variable) marked_variable;
};
```

Variables of certain types require helper functions for when `Block_copy()`
and `Block_release()` are performed upon a referencing `Block`. At the "C"
level only variables that are of type `Block` or ones that have
`__attribute__((NSObject))` marked require helper functions. In Objective-C
objects require helper functions and in C++ stack based objects require helper
functions. Variables that require helper functions use the form:

```c
struct _block_byref_foo {
    void *isa;
    struct _block_byref_foo *forwarding;
    int flags;   //refcount;
    int size;
    // helper functions called via Block_copy() and Block_release()
    void (*byref_keep)(void  *dst, void *src);
    void (*byref_dispose)(void *);
    typeof(marked_variable) marked_variable;
};
```

The structure is initialized such that:

a. The `forwarding` pointer is set to the beginning of its enclosing
   structure.

b. The `size` field is initialized to the total size of the enclosing
   structure.

c. The `flags` field is set to either 0 if no helper functions are needed
   or `(1<<25)` if they are.

d. The helper functions are initialized (if present).
e. The variable itself is set to its initial value.
f. The `isa` field is set to `NULL`.

#### Access to `__block` variables from within its lexical scope

In order to "move" the variable to the heap upon a `copy_helper` operation the
compiler must rewrite access to such a variable to be indirect through the
structures `forwarding` pointer. For example:

```c
int __block i = 10;
i = 11;
```

would be rewritten to be:

```c
struct _block_byref_i {
  void *isa;
  struct _block_byref_i *forwarding;
  int flags;   //refcount;
  int size;
  int captured_i;
} i = { NULL, &i, 0, sizeof(struct _block_byref_i), 10 };

i.forwarding->captured_i = 11;
```

In the case of a `Block` reference variable being marked `__block` the
helper code generated must use the `_Block_object_assign` and
`_Block_object_dispose` routines supplied by the runtime to make the
copies. For example:

```c
__block void (voidBlock)(void) = blockA;
voidBlock = blockB;
```

would translate into:

```c
struct _block_byref_voidBlock {
    void *isa;
    struct _block_byref_voidBlock *forwarding;
    int flags;   //refcount;
    int size;
    void (*byref_keep)(struct _block_byref_voidBlock *dst, struct _block_byref_voidBlock *src);
    void (*byref_dispose)(struct _block_byref_voidBlock *);
    void (^captured_voidBlock)(void);
};

void _block_byref_keep_helper(struct _block_byref_voidBlock *dst, struct _block_byref_voidBlock *src) {
    //_Block_copy_assign(&dst->captured_voidBlock, src->captured_voidBlock, 0);
    _Block_object_assign(&dst->captured_voidBlock, src->captured_voidBlock, BLOCK_FIELD_IS_BLOCK | BLOCK_BYREF_CALLER);
}

void _block_byref_dispose_helper(struct _block_byref_voidBlock *param) {
    //_Block_destroy(param->captured_voidBlock, 0);
    _Block_object_dispose(param->captured_voidBlock, BLOCK_FIELD_IS_BLOCK | BLOCK_BYREF_CALLER)}
```

and:

```c
struct _block_byref_voidBlock voidBlock = {( .forwarding=&voidBlock, .flags=(1<<25), .size=sizeof(struct _block_byref_voidBlock *),
    .byref_keep=_block_byref_keep_helper, .byref_dispose=_block_byref_dispose_helper,
    .captured_voidBlock=blockA )};

voidBlock.forwarding->captured_voidBlock = blockB;
```

#### Importing `__block` variables into `Blocks`

A `Block` that uses a `__block` variable in its compound statement body must
import the variable and emit `copy_helper` and `dispose_helper` helper
functions that, in turn, call back into the runtime to actually copy or release
the `byref` data block using the functions `_Block_object_assign` and
`_Block_object_dispose`.

For example:

```c
int __block i = 2;
functioncall(^{ i = 10; });
```

would translate to:

```c
struct _block_byref_i {
    void *isa;  // set to NULL
    struct _block_byref_voidBlock *forwarding;
    int flags;   //refcount;
    int size;
    void (*byref_keep)(struct _block_byref_i *dst, struct _block_byref_i *src);
    void (*byref_dispose)(struct _block_byref_i *);
    int captured_i;
};


struct __block_literal_5 {
    void *isa;
    int flags;
    int reserved;
    void (*invoke)(struct __block_literal_5 *);
    struct __block_descriptor_5 *descriptor;
    struct _block_byref_i *i_holder;
};

void __block_invoke_5(struct __block_literal_5 *_block) {
   _block->forwarding->captured_i = 10;
}

void __block_copy_5(struct __block_literal_5 *dst, struct __block_literal_5 *src) {
     //_Block_byref_assign_copy(&dst->captured_i, src->captured_i);
     _Block_object_assign(&dst->captured_i, src->captured_i, BLOCK_FIELD_IS_BYREF | BLOCK_BYREF_CALLER);
}

void __block_dispose_5(struct __block_literal_5 *src) {
     //_Block_byref_release(src->captured_i);
     _Block_object_dispose(src->captured_i, BLOCK_FIELD_IS_BYREF | BLOCK_BYREF_CALLER);
}

static struct __block_descriptor_5 {
    unsigned long int reserved;
    unsigned long int Block_size;
    void (*copy_helper)(struct __block_literal_5 *dst, struct __block_literal_5 *src);
    void (*dispose_helper)(struct __block_literal_5 *);
} __block_descriptor_5 = { 0, sizeof(struct __block_literal_5) __block_copy_5, __block_dispose_5 };
```

and:

```c
struct _block_byref_i i = {( .isa=NULL, .forwarding=&i, .flags=0, .size=sizeof(struct _block_byref_i), .captured_i=2 )};
struct __block_literal_5 _block_literal = {
      &_NSConcreteStackBlock,
      (1<<25)|(1<<29), <uninitialized>,
      __block_invoke_5,
      &__block_descriptor_5,
      &i,
};
```

#### Importing `__attribute__((NSObject))` `__block` variables

A `__block` variable that is also marked `__attribute__((NSObject))` should
have `byref_keep` and `byref_dispose` helper functions that use
`_Block_object_assign` and `_Block_object_dispose`.

#### `__block` escapes

Because `Blocks` referencing `__block` variables may have `Block_copy()`
performed upon them the underlying storage for the variables may move to the
heap. In Objective-C Garbage Collection Only compilation environments the heap
used is the garbage collected one and no further action is required. Otherwise
the compiler must issue a call to potentially release any heap storage for
`__block` variables at all escapes or terminations of their scope. The call
should be:

```c
_Block_object_dispose(&_block_byref_foo, BLOCK_FIELD_IS_BYREF);
```

#### Nesting

`Blocks` may contain `Block` literal expressions. Any variables used within
inner blocks are imported into all enclosing `Block` scopes even if the
variables are not used. This includes `const` imports as well as `__block`
variables.

## Objective C Extensions to `Blocks`

### Importing Objects

Objects should be treated as `__attribute__((NSObject))` variables; all
`copy_helper`, `dispose_helper`, `byref_keep`, and `byref_dispose`
helper functions should use `_Block_object_assign` and
`_Block_object_dispose`. There should be no code generated that uses
`*-retain` or `*-release` methods.

### `Blocks` as Objects

The compiler will treat `Blocks` as objects when synthesizing property setters
and getters, will characterize them as objects when generating garbage
collection strong and weak layout information in the same manner as objects, and
will issue strong and weak write-barrier assignments in the same manner as
objects.

### `__weak __block` Support

Objective-C (and Objective-C++) support the `__weak` attribute on `__block`
variables. Under normal circumstances the compiler uses the Objective-C runtime
helper support functions `objc_assign_weak` and `objc_read_weak`. Both
should continue to be used for all reads and writes of `__weak __block`
variables:

```c
objc_read_weak(&block->byref_i->forwarding->i)
```

The `__weak` variable is stored in a `_block_byref_foo` structure and the
`Block` has copy and dispose helpers for this structure that call:

```c
_Block_object_assign(&dest->_block_byref_i, src-> _block_byref_i, BLOCK_FIELD_IS_WEAK | BLOCK_FIELD_IS_BYREF);
```

and:

```c
_Block_object_dispose(src->_block_byref_i, BLOCK_FIELD_IS_WEAK | BLOCK_FIELD_IS_BYREF);
```

In turn, the `block_byref` copy support helpers distinguish between whether
the `__block` variable is a `Block` or not and should either call:

```c
_Block_object_assign(&dest->_block_byref_i, src->_block_byref_i, BLOCK_FIELD_IS_WEAK | BLOCK_FIELD_IS_OBJECT | BLOCK_BYREF_CALLER);
```

for something declared as an object or:

```c
_Block_object_assign(&dest->_block_byref_i, src->_block_byref_i, BLOCK_FIELD_IS_WEAK | BLOCK_FIELD_IS_BLOCK | BLOCK_BYREF_CALLER);
```

for something declared as a `Block`.

A full example follows:

```c
__block __weak id obj = <initialization expression>;
functioncall(^{ [obj somemessage]; });
```

would translate to:

```c
struct _block_byref_obj {
    void *isa;  // uninitialized
    struct _block_byref_obj *forwarding;
    int flags;   //refcount;
    int size;
    void (*byref_keep)(struct _block_byref_i *dst, struct _block_byref_i *src);
    void (*byref_dispose)(struct _block_byref_i *);
    id captured_obj;
};

void _block_byref_obj_keep(struct _block_byref_voidBlock *dst, struct _block_byref_voidBlock *src) {
    //_Block_copy_assign(&dst->captured_obj, src->captured_obj, 0);
    _Block_object_assign(&dst->captured_obj, src->captured_obj, BLOCK_FIELD_IS_OBJECT | BLOCK_FIELD_IS_WEAK | BLOCK_BYREF_CALLER);
}

void _block_byref_obj_dispose(struct _block_byref_voidBlock *param) {
    //_Block_destroy(param->captured_obj, 0);
    _Block_object_dispose(param->captured_obj, BLOCK_FIELD_IS_OBJECT | BLOCK_FIELD_IS_WEAK | BLOCK_BYREF_CALLER);
};
```

for the block `byref` part and:

```c
struct __block_literal_5 {
    void *isa;
    int flags;
    int reserved;
    void (*invoke)(struct __block_literal_5 *);
    struct __block_descriptor_5 *descriptor;
    struct _block_byref_obj *byref_obj;
};

void __block_invoke_5(struct __block_literal_5 *_block) {
   [objc_read_weak(&_block->byref_obj->forwarding->captured_obj) somemessage];
}

void __block_copy_5(struct __block_literal_5 *dst, struct __block_literal_5 *src) {
     //_Block_byref_assign_copy(&dst->byref_obj, src->byref_obj);
     _Block_object_assign(&dst->byref_obj, src->byref_obj, BLOCK_FIELD_IS_BYREF | BLOCK_FIELD_IS_WEAK);
}

void __block_dispose_5(struct __block_literal_5 *src) {
     //_Block_byref_release(src->byref_obj);
     _Block_object_dispose(src->byref_obj, BLOCK_FIELD_IS_BYREF | BLOCK_FIELD_IS_WEAK);
}

static struct __block_descriptor_5 {
    unsigned long int reserved;
    unsigned long int Block_size;
    void (*copy_helper)(struct __block_literal_5 *dst, struct __block_literal_5 *src);
    void (*dispose_helper)(struct __block_literal_5 *);
} __block_descriptor_5 = { 0, sizeof(struct __block_literal_5), __block_copy_5, __block_dispose_5 };
```

and within the compound statement:

```c
truct _block_byref_obj obj = {( .forwarding=&obj, .flags=(1<<25), .size=sizeof(struct _block_byref_obj),
                 .byref_keep=_block_byref_obj_keep, .byref_dispose=_block_byref_obj_dispose,
                 .captured_obj = <initialization expression> )};

truct __block_literal_5 _block_literal = {
     &_NSConcreteStackBlock,
     (1<<25)|(1<<29), <uninitialized>,
     __block_invoke_5,
     &__block_descriptor_5,
     &obj,        // a reference to the on-stack structure containing "captured_obj"
};


functioncall(_block_literal->invoke(&_block_literal));
```

## C++ Support

Within a block stack based C++ objects are copied into `const` copies using
the copy constructor. It is an error if a stack based C++ object is used within
a block if it does not have a copy constructor. In addition both copy and
destroy helper routines must be synthesized for the block to support the
`Block_copy()` operation, and the flags work marked with the (1\<<26) bit in
addition to the (1\<<25) bit. The copy helper should call the constructor using
appropriate offsets of the variable within the supplied stack based block source
and heap based destination for all `const` constructed copies, and similarly
should call the destructor in the destroy routine.

As an example, suppose a C++ class `FOO` existed with a copy constructor.
Within a code block a stack version of a `FOO` object is declared and used
within a `Block` literal expression:

```c++
{
    FOO foo;
    void (^block)(void) = ^{ printf("%d\n", foo.value()); };
}
```

The compiler would synthesize:

```c++
struct __block_literal_10 {
    void *isa;
    int flags;
    int reserved;
    void (*invoke)(struct __block_literal_10 *);
    struct __block_descriptor_10 *descriptor;
    const FOO foo;
};

void __block_invoke_10(struct __block_literal_10 *_block) {
   printf("%d\n", _block->foo.value());
}

void __block_copy_10(struct __block_literal_10 *dst, struct __block_literal_10 *src) {
     FOO_ctor(&dst->foo, &src->foo);
}

void __block_dispose_10(struct __block_literal_10 *src) {
     FOO_dtor(&src->foo);
}

static struct __block_descriptor_10 {
    unsigned long int reserved;
    unsigned long int Block_size;
    void (*copy_helper)(struct __block_literal_10 *dst, struct __block_literal_10 *src);
    void (*dispose_helper)(struct __block_literal_10 *);
} __block_descriptor_10 = { 0, sizeof(struct __block_literal_10), __block_copy_10, __block_dispose_10 };
```

and the code would be:

```c++
{
  FOO foo;
  comp_ctor(&foo); // default constructor
  struct __block_literal_10 _block_literal = {
    &_NSConcreteStackBlock,
    (1<<25)|(1<<26)|(1<<29), <uninitialized>,
    __block_invoke_10,
    &__block_descriptor_10,
   };
   comp_ctor(&_block_literal->foo, &foo);  // const copy into stack version
   struct __block_literal_10 &block = &_block_literal;  // assign literal to block variable
   block->invoke(block);    // invoke block
   comp_dtor(&_block_literal->foo); // destroy stack version of const block copy
   comp_dtor(&foo); // destroy original version
}
```

C++ objects stored in `__block` storage start out on the stack in a
`block_byref` data structure as do other variables. Such objects (if not
`const` objects) must support a regular copy constructor. The `block_byref`
data structure will have copy and destroy helper routines synthesized by the
compiler. The copy helper will have code created to perform the copy
constructor based on the initial stack `block_byref` data structure, and will
also set the (1\<<26) bit in addition to the (1\<<25) bit. The destroy helper
will have code to do the destructor on the object stored within the supplied
`block_byref` heap data structure. For example,

```c++
__block FOO blockStorageFoo;
```

requires the normal constructor for the embedded `blockStorageFoo` object:

```c++
FOO_ctor(& _block_byref_blockStorageFoo->blockStorageFoo);
```

and at scope termination the destructor:

```c++
FOO_dtor(& _block_byref_blockStorageFoo->blockStorageFoo);
```

Note that the forwarding indirection is *NOT* used.

The compiler would need to generate (if used from a block literal) the following
copy/dispose helpers:

```c++
void _block_byref_obj_keep(struct _block_byref_blockStorageFoo *dst, struct _block_byref_blockStorageFoo *src) {
     FOO_ctor(&dst->blockStorageFoo, &src->blockStorageFoo);
}

void _block_byref_obj_dispose(struct _block_byref_blockStorageFoo *src) {
     FOO_dtor(&src->blockStorageFoo);
}
```

for the appropriately named constructor and destructor for the class/struct
`FOO`.

To support member variable and function access the compiler will synthesize a
`const` pointer to a block version of the `this` pointer.

(RuntimeHelperFunctions)=

## Runtime Helper Functions

The runtime helper functions are described in
`/usr/local/include/Block_private.h`. To summarize their use, a `Block`
requires copy/dispose helpers if it imports any block variables, `__block`
storage variables, `__attribute__((NSObject))` variables, or C++ `const`
copied objects with constructor/destructors. The (1\<<26) bit is set and
functions are generated.

The block copy helper function should, for each of the variables of the type
mentioned above, call:

```c
_Block_object_assign(&dst->target, src->target, BLOCK_FIELD_<apropos>);
```

in the copy helper and:

```c
_Block_object_dispose(->target, BLOCK_FIELD_<apropos>);
```

in the dispose helper where `<apropos>` is:

```c
enum {
    BLOCK_FIELD_IS_OBJECT   =  3,  // id, NSObject, __attribute__((NSObject)), block, ...
    BLOCK_FIELD_IS_BLOCK    =  7,  // a block variable
    BLOCK_FIELD_IS_BYREF    =  8,  // the on stack structure holding the __block variable

    BLOCK_FIELD_IS_WEAK     = 16,  // declared __weak

    BLOCK_BYREF_CALLER      = 128, // called from byref copy/dispose helpers
};
```

and of course the constructors/destructors for `const` copied C++ objects.

The `block_byref` data structure similarly requires copy/dispose helpers for
block variables, `__attribute__((NSObject))` variables, or C++ `const`
copied objects with constructor/destructors, and again the (1\<<26) bit is set
and functions are generated in the same manner.

Under ObjC we allow `__weak` as an attribute on `__block` variables, and
this causes the addition of `BLOCK_FIELD_IS_WEAK` orred onto the
`BLOCK_FIELD_IS_BYREF` flag when copying the `block_byref` structure in the
`Block` copy helper, and onto the `BLOCK_FIELD_<apropos>` field within the
`block_byref` copy/dispose helper calls.

The prototypes, and summary, of the helper functions are:

```c
/* Certain field types require runtime assistance when being copied to the
   heap.  The following function is used to copy fields of types: blocks,
   pointers to byref structures, and objects (including
   __attribute__((NSObject)) pointers.  BLOCK_FIELD_IS_WEAK is orthogonal to
   the other choices which are mutually exclusive.  Only in a Block copy
   helper will one see BLOCK_FIELD_IS_BYREF.
*/
void _Block_object_assign(void *destAddr, const void *object, const int flags);

/* Similarly a compiler generated dispose helper needs to call back for each
   field of the byref data structure.  (Currently the implementation only
   packs one field into the byref structure but in principle there could be
   more).  The same flags used in the copy helper should be used for each
   call generated to this function:
*/
void _Block_object_dispose(const void *object, const int flags);
```

## Copyright

Copyright 2008-2010 Apple, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

---

### Clang Docs BlockLanguageSpec (`clang/docs/BlockLanguageSpec.md`)

```{role} block-term
```

# Language Specification for Blocks


## Revisions

- 2008/2/25 --- created
- 2008/7/28 --- revised, `__block` syntax
- 2008/8/13 --- revised, Block globals
- 2008/8/21 --- revised, C++ elaboration
- 2008/11/1 --- revised, `__weak` support
- 2009/1/12 --- revised, explicit return types
- 2009/2/10 --- revised, `__block` objects need retain

## Overview

A new derived type is introduced to C and, by extension, Objective-C,
C++, and Objective-C++

## The Block Type

Like function types, the {block-term}`Block type` is a pair consisting
of a result value type and a list of parameter types very similar to a
function type. Blocks are intended to be used much like functions with
the key distinction being that in addition to executable code they
also contain various variable bindings to automatic (stack) or managed
(heap) memory.

The abstract declarator,

```c
int (^)(char, float)
```

describes a reference to a Block that, when invoked, takes two
parameters, the first of type char and the second of type float, and
returns a value of type int. The Block referenced is of opaque data
that may reside in automatic (stack) memory, global memory, or heap
memory.

## Block Variable Declarations

A {block-term}`variable with Block type` is declared using function
pointer style notation substituting `^` for `*`. The following are
valid Block variable declarations:

```c
void (^blockReturningVoidWithVoidArgument)(void);
int (^blockReturningIntWithIntAndCharArguments)(int, char);
void (^arrayOfTenBlocksReturningVoidWithIntArgument[10])(int);
```

Variadic `...` arguments are supported. [variadic.c] A Block that
takes no arguments must specify void in the argument list [voidarg.c].
An empty parameter list does not represent, as K&R provide, an
unspecified argument list. Note: both gcc and clang support K&R style
as a convenience.

A Block reference may be cast to a pointer of arbitrary type and vice
versa. [cast.c] A Block reference may not be dereferenced via the
pointer dereference operator `*`, and thus a Block's size may not be
computed at compile time. [sizeof.c]

## Block Literal Expressions

A {block-term}`Block literal expression` produces a reference to a
Block. It is introduced by the use of the `^` token as a unary
operator.

```c
Block_literal_expression ::=   ^ block_decl compound_statement_body
block_decl ::=
block_decl ::= parameter_list
block_decl ::= type_expression
```

where type expression is extended to allow `^` as a Block reference
(pointer) where `*` is allowed as a function reference (pointer).

The following Block literal:

```c
^ void (void) { printf("hello world\n"); }
```

produces a reference to a Block with no arguments with no return value.

The return type is optional and is inferred from the return
statements. If the return statements return a value, they all must
return a value of the same type. If there is no value returned the
inferred type of the Block is void; otherwise it is the type of the
return statement value.

If the return type is omitted and the argument list is `( void )`,
the `( void )` argument list may also be omitted.

So:

```c
^ ( void ) { printf("hello world\n"); }
```

and:

```c
^ { printf("hello world\n"); }
```

are exactly equivalent constructs for the same expression.

The type_expression extends C expression parsing to accommodate Block
reference declarations as it accommodates function pointer
declarations.

Given:

```c
typedef int (*pointerToFunctionThatReturnsIntWithCharArg)(char);
pointerToFunctionThatReturnsIntWithCharArg functionPointer;
^ pointerToFunctionThatReturnsIntWithCharArg (float x) { return functionPointer; }
```

and:

```c
^ int ((*)(float x))(char) { return functionPointer; }
```

are equivalent expressions, as is:

```c
^(float x) { return functionPointer; }
```

[returnfunctionptr.c]

The compound statement body establishes a new lexical scope within
that of its parent. Variables used within the scope of the compound
statement are bound to the Block in the normal manner with the
exception of those in automatic (stack) storage. Thus one may access
functions and global variables as one would expect, as well as static
local variables. [testme]

Local automatic (stack) variables referenced within the compound
statement of a Block are imported and captured by the Block as const
copies. The capture (binding) is performed at the time of the Block
literal expression evaluation.

The compiler is not required to capture a variable if it can prove
that no references to the variable will actually be evaluated.
Programmers can force a variable to be captured by referencing it in a
statement at the beginning of the Block, like so:

```c
(void) foo;
```

This matters when capturing the variable has side-effects, as it can
in Objective-C or C++.

The lifetime of variables declared in a Block is that of a function;
each activation frame contains a new copy of variables declared within
the local scope of the Block. Such variable declarations should be
allowed anywhere [testme] rather than only when C99 parsing is
requested, including for statements. [testme]

Block literal expressions may occur within Block literal expressions
(nest) and all variables captured by any nested blocks are implicitly
also captured in the scopes of their enclosing Blocks.

A Block literal expression may be used as the initialization value for
Block variables at global or local static scope.

## The Invoke Operator

Blocks are {block-term}`invoked` using function call syntax with a
list of expression parameters of types corresponding to the
declaration and returning a result type also according to the
declaration. Given:

```c
int (^x)(char);
void (^z)(void);
int (^(*y))(char) = &x;
```

the following are all legal Block invocations:

```c
x('a');
(*y)('a');
(true ? x : *y)('a')
```

## The Copy and Release Operations

The compiler and runtime provide {block-term}`copy` and
{block-term}`release` operations for Block references that create and,
in matched use, release allocated storage for referenced Blocks.

The copy operation `Block_copy()` is styled as a function that takes
an arbitrary Block reference and returns a Block reference of the same
type. The release operation, `Block_release()`, is styled as a
function that takes an arbitrary Block reference and, if dynamically
matched to a Block copy operation, allows recovery of the referenced
allocated memory.

## The `__block` Storage Qualifier

In addition to the new Block type we also introduce a new storage
qualifier, {block-term}`__block`, for local variables. [testme: a
\_\_block declaration within a block literal] The `__block` storage
qualifier is mutually exclusive to the existing local storage
qualifiers auto, register, and static. [testme] Variables qualified by
`__block` act as if they were in allocated storage and this storage
is automatically recovered after last use of said variable. An
implementation may choose an optimization where the storage is
initially automatic and only "moved" to allocated (heap) storage upon
a Block_copy of a referencing Block. Such variables may be mutated as
normal variables are.

In the case where a `__block` variable is a Block one must assume
that the `__block` variable resides in allocated storage and as such
is assumed to reference a Block that is also in allocated storage
(that it is the result of a `Block_copy` operation). Despite this
there is no provision to do a `Block_copy` or a `Block_release` if
an implementation provides initial automatic storage for Blocks. This
is due to the inherent race condition of potentially several threads
trying to update the shared variable and the need for synchronization
around disposing of older values and copying new ones. Such
synchronization is beyond the scope of this language specification.

## Control Flow

The compound statement of a Block is treated much like a function body
with respect to control flow in that goto, break, and continue do not
escape the Block. Exceptions are treated *normally* in that when
thrown they pop stack frames until a catch clause is found.

## Objective-C Extensions

Objective-C extends the definition of a Block reference type to be
that also of id. A variable or expression of Block type may be
messaged or used as a parameter wherever an id may be. The converse is
also true. Block references may thus appear as properties and are
subject to the assign, retain, and copy attribute logic that is
reserved for objects.

All Blocks are constructed to be Objective-C objects regardless of
whether the Objective-C runtime is operational in the program or
not. Blocks using automatic (stack) memory are objects and may be
messaged, although they may not be assigned into `__weak` locations
if garbage collection is enabled.

Within a Block literal expression within a method definition
references to instance variables are also imported into the lexical
scope of the compound statement. These variables are implicitly
qualified as references from self, and so self is imported as a const
copy. The net effect is that instance variables can be mutated.

The {block-term}`Block_copy` operator retains all objects held in
variables of automatic storage referenced within the Block expression
(or forms strong references if running under garbage collection).
Object variables of `__block` storage type are assumed to hold
normal pointers with no provision for retain and release messages.

Foundation defines (and supplies) `-copy` and `-release` methods for
Blocks.

In the Objective-C and Objective-C++ languages, we allow the
`__weak` specifier for `__block` variables of object type. If
garbage collection is not enabled, this qualifier causes these
variables to be kept without retain messages being sent. This
knowingly leads to dangling pointers if the Block (or a copy) outlives
the lifetime of this object.

In garbage collected environments, the `__weak` variable is set to
nil when the object it references is collected, as long as the
`__block` variable resides in the heap (either by default or via
`Block_copy()`). The initial Apple implementation does in fact
start `__block` variables on the stack and migrate them to the heap
only as a result of a `Block_copy()` operation.

It is a runtime error to attempt to assign a reference to a
stack-based Block into any storage marked `__weak`, including
`__weak` `__block` variables.

## C++ Extensions

Block literal expressions within functions are extended to allow const
use of C++ objects, pointers, or references held in automatic storage.

As usual, within the block, references to captured variables become
const-qualified, as if they were references to members of a const
object. Note that this does not change the type of a variable of
reference type.

For example, given a class Foo:

```c
Foo foo;
Foo &fooRef = foo;
Foo *fooPtr = &foo;
```

A Block that referenced these variables would import the variables as
const variations:

```c
const Foo block_foo = foo;
Foo &block_fooRef = fooRef;
Foo *const block_fooPtr = fooPtr;
```

Captured variables are copied into the Block at the instant of
evaluating the Block literal expression. They are also copied when
calling `Block_copy()` on a Block allocated on the stack. In both
cases, they are copied as if the variable were const-qualified, and
it's an error if there's no such constructor.

Captured variables in Blocks on the stack are destroyed when control
leaves the compound statement that contains the Block literal
expression. Captured variables in Blocks on the heap are destroyed
when the reference count of the Block drops to zero.

Variables declared as residing in `__block` storage may be initially
allocated in the heap or may first appear on the stack and be copied
to the heap as a result of a `Block_copy()` operation. When copied
from the stack, `__block` variables are copied using their normal
qualification (i.e. without adding const). In C++11, `__block`
variables are copied as x-values if that is possible, then as l-values
if not; if both fail, it's an error. The destructor for any initial
stack-based version is called at the variable's normal end of scope.

References to `this`, as well as references to non-static members of
any enclosing class, are evaluated by capturing `this` just like a
normal variable of C pointer type.

Member variables that are Blocks may not be overloaded by the types of
their arguments.

---

### Clang Docs BoundsSafety (`clang/docs/BoundsSafety.md`)

# `-fbounds-safety`: Enforcing bounds safety for C


## Overview

**NOTE:** This is a design document and the feature is not available for users yet.
Please see {doc}`BoundsSafetyImplPlans` for more details.

`-fbounds-safety` is a C extension to enforce bounds safety to prevent
out-of-bounds (OOB) memory accesses, which remain a major source of security
vulnerabilities in C. `-fbounds-safety` aims to eliminate this class of bugs
by turning OOB accesses into deterministic traps.

The `-fbounds-safety` extension offers bounds annotations that programmers can
use to attach bounds to pointers. For example, programmers can add the
`__counted_by(N)` annotation to parameter `ptr`, indicating that the pointer
has `N` valid elements:

```c
void foo(int *__counted_by(N) ptr, size_t N);
```

Using this bounds information, the compiler inserts bounds checks on every
pointer dereference, ensuring that the program does not access memory outside
the specified bounds. The compiler requires programmers to provide enough bounds
information so that the accesses can be checked at either run time or compile
time — and it rejects code if it cannot.

The most important contribution of `-fbounds-safety` is how it reduces the
programmer's annotation burden by reconciling bounds annotations at ABI
boundaries with the use of implicit wide pointers (a.k.a. "fat" pointers) that
carry bounds information on local variables without the need for annotations. We
designed this model so that it preserves ABI compatibility with C while
minimizing adoption effort.

The `-fbounds-safety` extension has been adopted on millions of lines of
production C code and proven to work in a consumer operating system setting. The
extension was designed to enable incremental adoption — a key requirement in
real-world settings where modifying an entire project and its dependencies all
at once is often not possible. It also addresses multiple of other practical
challenges that have made existing approaches to safer C dialects difficult to
adopt, offering these properties that make it widely adoptable in practice:

- It is designed to preserve the Application Binary Interface (ABI).
- It interoperates well with plain C code.
- It can be adopted partially and incrementally while still providing safety
  benefits.
- It is a conforming extension to C.
- Consequently, source code that adopts the extension can continue to be
  compiled by toolchains that do not support the extension (CAVEAT: this still
  requires inclusion of a header file macro-defining bounds annotations to
  empty).
- It has a relatively low adoption cost.

This document discusses the key designs of `-fbounds-safety`. The document is
subject to active updates with a more detailed specification.

## Programming Model

### Overview

`-fbounds-safety` ensures that pointers are not used to access memory beyond
their bounds by performing bounds checking. If a bounds check fails, the program
will deterministically trap before out-of-bounds memory is accessed.

In our model, every pointer has an explicit or implicit bounds attribute that
determines its bounds and ensures guaranteed bounds checking. Consider the
example below where the `__counted_by(count)` annotation indicates that
parameter `p` points to a buffer of integers containing `count` elements. An
off-by-one error is present in the loop condition, leading to `p[i]` being
out-of-bounds access during the loop's final iteration. The compiler inserts a
bounds check before `p` is dereferenced to ensure that the access remains
within the specified bounds.

```c
void fill_array_with_indices(int *__counted_by(count) p, unsigned count) {
   // off-by-one error (i < count)
   for (unsigned i = 0; i <= count; ++i) {
      // bounds check inserted:
      //   if (i >= count) trap();
      p[i] = i;
   }
}
```

A bounds annotation defines an invariant for the pointer type, and the model
ensures that this invariant remains true. In the example below, pointer `p`
annotated with `__counted_by(count)` must always point to a memory buffer
containing at least `count` elements of the pointee type. Changing the value
of `count`, like in the example below, may violate this invariant and permit
out-of-bounds access to the pointer. To avoid this, the compiler employs
compile-time restrictions and emits run-time checks as necessary to ensure the
new count value doesn't exceed the actual length of the buffer. Section
[Maintaining correctness of bounds annotations](#maintaining-correctness-of-bounds-annotations)
provides more details about this programming model.

```c
int g;

void foo(int *__counted_by(count) p, size_t count) {
   count++; // may violate the invariant of __counted_by
   count--; // may violate the invariant of __counted_by if count was 0.
   count = g; // may violate the invariant of __counted_by
              // depending on the value of `g`.
}
```

The requirement to annotate all pointers with explicit bounds information could
present a significant adoption burden. To tackle this issue, the model
incorporates the concept of a "wide pointer" (a.k.a. fat pointer) – a larger
pointer that carries bounds information alongside the pointer value. Utilizing
wide pointers can potentially reduce the adoption burden, as it contains bounds
information internally and eliminates the need for explicit bounds annotations.
However, wide pointers differ from standard C pointers in their data layout,
which may result in incompatibilities with the application binary interface
(ABI). Breaking the ABI complicates interoperability with external code that has
not adopted the same programming model.

`-fbounds-safety` harmonizes the wide pointer and the bounds annotation
approaches to reduce the adoption burden while maintaining the ABI. In this
model, local variables of pointer type are implicitly treated as wide pointers,
allowing them to carry bounds information without requiring explicit bounds
annotations. Please note that this approach doesn't apply to function parameters
which are considered ABI-visible. As local variables are typically hidden from
the ABI, this approach has a marginal impact on it. In addition,
`-fbounds-safety` employs compile-time restrictions to prevent implicit wide
pointers from silently breaking the ABI (see [ABI implications of default bounds
annotations](#abi-implications-of-default-bounds-annotations)). Pointers associated with any other variables, including function
parameters, are treated as single object pointers (i.e., `__single`), ensuring
that they always have the tightest bounds by default and offering a strong
bounds safety guarantee.

By implementing default bounds annotations based on ABI visibility, a
considerable portion of C code can operate without modifications within this
programming model, reducing the adoption burden.

The rest of the section will discuss individual bounds annotations and the
programming model in more detail.

### Bounds annotations

#### Annotation for pointers to a single object

The C language allows pointer arithmetic on arbitrary pointers and this has been
a source of many bounds safety issues. In practice, many pointers are merely
pointing to a single object and incrementing or decrementing such a pointer
immediately makes the pointer go out-of-bounds. To prevent this unsafety,
`-fbounds-safety` provides the annotation `__single` that causes pointer
arithmetic on annotated pointers to be a compile time error.

- `__single` : indicates that the pointer is either pointing to a single
  object or null. Hence, pointers with `__single` do not permit pointer
  arithmetic nor being subscripted with a non-zero index. Dereferencing a
  `__single` pointer is allowed but it requires a null check. Upper and lower
  bounds checks are not required because the `__single` pointer should point
  to a valid object unless it's null.

`__single` is the default annotation for ABI-visible pointers. This
gives strong security guarantees in that these pointers cannot be incremented or
decremented unless they have an explicit, overriding bounds annotation that can
be used to verify the safety of the operation. The compiler issues an error when
a `__single` pointer is utilized for pointer arithmetic or array access, as
these operations would immediately cause the pointer to exceed its bounds.
Consequently, this prompts programmers to provide sufficient bounds information
to pointers. In the following example, the pointer on parameter p is
single-by-default, and is employed for array access. As a result, the compiler
generates an error suggesting to add `__counted_by` to the pointer.

```c
void fill_array_with_indices(int *p, unsigned count) {
   for (unsigned i = 0; i < count; ++i) {
      p[i] = i; // error
   }
}
```

#### External bounds annotations

"External" bounds annotations provide a way to express a relationship between a
pointer variable and another variable (or expression) containing the bounds
information of the pointer. In the following example, `__counted_by(count)`
annotation expresses the bounds of parameter p using another parameter count.
This model works naturally with many C interfaces and structs because the bounds
of a pointer is often available adjacent to the pointer itself, e.g., at another
parameter of the same function prototype, or at another field of the same struct
declaration.

```c
void fill_array_with_indices(int *__counted_by(count) p, size_t count) {
   // off-by-one error
   for (size_t i = 0; i <= count; ++i)
      p[i] = i;
}
```

External bounds annotations include `__counted_by`, `__sized_by`, and
`__ended_by`. These annotations do not change the pointer representation,
meaning they do not have ABI implications.

- `__counted_by(N)` : The pointer points to memory that contains `N`
  elements of pointee type. `N` is an expression of integer type which can be
  a simple reference to declaration, a constant including calls to constant
  functions, or an arithmetic expression that does not have side effect. The
  `__counted_by` annotation cannot apply to pointers to incomplete types or
  types without size such as `void *`. Instead, `__sized_by` can be used to
  describe the byte count.
- `__sized_by(N)` : The pointer points to memory that contains `N` bytes.
  Just like the argument of `__counted_by`, `N` is an expression of integer
  type which can be a constant, a simple reference to a declaration, or an
  arithmetic expression that does not have side effects. This is mainly used for
  pointers to incomplete types or types without size such as `void *`.
- `__ended_by(P)` : The pointer has the upper bound of value `P`, which is
  one past the last element of the pointer. In other words, this annotation
  describes a range that starts with the pointer that has this annotation and
  ends with `P` which is the argument of the annotation. `P` itself may be
  annotated with `__ended_by(Q)`. In this case, the end of the range extends
  to the pointer `Q`. This is used for "iterator" support in C where you're
  iterating from one pointer value to another until a final pointer value is
  reached (and the final pointer value is not dereferenceable).

Accessing a pointer outside the specified bounds causes a run-time trap or a
compile-time error. Also, the model maintains correctness of bounds annotations
when the pointer and/or the related value containing the bounds information are
updated or passed as arguments. This is done by compile-time restrictions or
run-time checks (see [Maintaining correctness of bounds annotations](#maintaining-correctness-of-bounds-annotations)
for more detail). For instance, initializing `buf` with `null` while
assigning non-zero value to `count`, as shown in the following example, would
violate the `__counted_by` annotation because a null pointer does not point to
any valid memory location. To avoid this, the compiler produces either a
compile-time error or run-time trap.

```c
void null_with_count_10(int *__counted_by(count) buf, unsigned count) {
   buf = 0;
   // This is not allowed as it creates a null pointer with non-zero length
   count = 10;
}
```

However, there are use cases where a pointer is either a null pointer or is
pointing to memory of the specified size. To support this idiom,
`-fbounds-safety` provides `*_or_null` variants,
`__counted_by_or_null(N)`, `__sized_by_or_null(N)`, and
`__ended_by_or_null(P)`. Accessing a pointer with any of these bounds
annotations will require an extra null check to avoid a null pointer
dereference.

#### Internal bounds annotations

A wide pointer (sometimes known as a "fat" pointer) is a pointer that carries
additional bounds information internally (as part of its data). The bounds
require additional storage space making wide pointers larger than normal
pointers, hence the name "wide pointer". The memory layout of a wide pointer is
equivalent to a struct with the pointer, upper bound, and (optionally) lower
bound as its fields as shown below.

```c
struct wide_pointer_datalayout {
   void* pointer; // Address used for dereferences and pointer arithmetic
   void* upper_bound; // Points one past the highest address that can be
                      // accessed
   void* lower_bound; // (Optional) Points to lowest address that can be
                      // accessed
};
```

Even with this representational change, wide pointers act syntactically as
normal pointers to allow standard pointer operations, such as pointer
dereference (`*p`), array subscript (`p[i]`), member access (`p->`), and
pointer arithmetic, with some restrictions on bounds-unsafe uses.

`-fbounds-safety` has a set of "internal" bounds annotations to turn pointers
into wide pointers. These are `__bidi_indexable` and `__indexable`. When a
pointer has either of these annotations, the compiler changes the pointer to the
corresponding wide pointer. This means these annotations will break the ABI and
will not be compatible with plain C, and thus they should generally not be used
in ABI surfaces.

- `__bidi_indexable` : A pointer with this annotation becomes a wide pointer
  to carry the upper bound and the lower bound, the layout of which is
  equivalent to `struct { T *ptr; T *upper_bound; T *lower_bound; };`. As the
  name indicates, pointers with this annotation are "bidirectionally indexable",
  meaning that they can be indexed with either a negative or a positive offset
  and the pointers can be incremented or decremented using pointer arithmetic. A
  `__bidi_indexable` pointer is allowed to hold an out-of-bounds pointer
  value. While creating an OOB pointer is undefined behavior in C,
  `-fbounds-safety` makes it well-defined behavior. That is, pointer
  arithmetic overflow with `__bidi_indexable` is defined as equivalent of
  two's complement integer computation, and at the LLVM IR level this means
  `getelementptr` won't get `inbounds` keyword. Accessing memory using the
  OOB pointer is prevented via a run-time bounds check.
- `__indexable` : A pointer with this annotation becomes a wide pointer
  carrying the upper bound (but no explicit lower bound), the layout of which is
  equivalent to `struct { T *ptr; T *upper_bound; };`. Since `__indexable`
  pointers do not have a separate lower bound, the pointer value itself acts as
  the lower bound. An `__indexable` pointer can only be incremented or indexed
  in the positive direction. Indexing it in the negative direction will trigger
  a compile-time error. Otherwise, the compiler inserts a run-time
  check to ensure pointer arithmetic doesn't make the pointer smaller than the
  original `__indexable` pointer (Note that `__indexable` doesn't have a
  lower bound so the pointer value is effectively the lower bound). As pointer
  arithmetic overflow will make the pointer smaller than the original pointer,
  it will cause a trap at runtime. Similar to `__bidi_indexable`, an
  `__indexable` pointer is allowed to have a pointer value above the upper
  bound and creating such a pointer is well-defined behavior. Dereferencing such
  a pointer, however, will cause a run-time trap.
- `__bidi_indexable` offers the best flexibility out of all the pointer
  annotations in this model, as `__bidi_indexable` pointers can be used for
  any pointer operation. However, this comes with the largest code size and
  memory cost out of the available pointer annotations in this model. In some
  cases, use of the `__bidi_indexable` annotation may be duplicating bounds
  information that exists elsewhere in the program. In such cases, using
  external bounds annotations may be a better choice.

`__bidi_indexable` is the default annotation for non-ABI visible pointers,
such as local pointer variables — that is, if the programmer does not specify
another bounds annotation, a local pointer variable is implicitly
`__bidi_indexable`. Since `__bidi_indexable` pointers automatically carry
bounds information and have no restrictions on kinds of pointer operations that
can be used with these pointers, most code inside a function works as is without
modification. In the example below, `int *buf` doesn't require manual
annotation as it's implicitly `int *__bidi_indexable buf`, carrying the bounds
information passed from the return value of malloc, which is necessary to insert
bounds checking for `buf[i]`.

```c
void *__sized_by(size) malloc(size_t size);

int *__counted_by(n) get_array_with_0_to_n_1(size_t n) {
   int *buf = malloc(sizeof(int) * n);
   for (size_t i = 0; i < n; ++i)
      buf[i] = i;
   return buf;
}
```

#### Annotations for sentinel-delimited arrays

A C string is an array of characters. The null terminator — the first null
character (`'\0'`) element in the array — marks the end of the string.
`-fbounds-safety` provides `__null_terminated` to annotate C strings and the
generalized form `__terminated_by(T)` to annotate pointers and arrays with an
end marked by a sentinel value. The model prevents dereferencing a
`__terminated_by` pointer beyond its end. Calculating the location of the end
(i.e., the address of the sentinel value), requires reading the entire array in
memory and would have some performance costs. To avoid an unintended performance
hit, the model puts some restrictions on how these pointers can be used.
`__terminated_by` pointers cannot be indexed and can only be incremented one
element at a time. To allow these operations, the pointers must be explicitly
converted to `__indexable` pointers using the intrinsic function
`__unsafe_terminated_by_to_indexable(P, T)` (or
`__unsafe_null_terminated_to_indexable(P)`) which converts the
`__terminated_by` pointer `P` to an `__indexable` pointer.

- `__null_terminated` : The pointer or array is terminated by `NULL` or
  `0`. Modifying the terminator or incrementing the pointer beyond it is
  prevented at run time.
- `__terminated_by(T)` : The pointer or array is terminated by `T` which is
  a constant expression. Accessing or incrementing the pointer beyond the
  terminator is not allowed. This is a generalization of `__null_terminated`
  which is defined as `__terminated_by(0)`.

#### Annotation for interoperating with bounds-unsafe code

A pointer with the `__unsafe_indexable` annotation behaves the same as a plain
C pointer. That is, the pointer does not have any bounds information and pointer
operations are not checked.

`__unsafe_indexable` can be used to mark pointers from system headers or
pointers from code that has not adopted -fbounds safety. This enables
interoperation between code using `-fbounds-safety` and code that does not.

### Default pointer types

#### ABI visibility and default annotations

Requiring `-fbounds-safety` adopters to add bounds annotations to all pointers
in the codebase would be a significant adoption burden. To avoid this and to
secure all pointers by default, `-fbounds-safety` applies default bounds
annotations to pointer types.
Default annotations apply to pointer types of declarations

`-fbounds-safety` applies default bounds annotations to pointer types used in
declarations. The default annotations are determined by the ABI visibility of
the pointer. A pointer type is ABI-visible if changing its size or
representation affects the ABI. For instance, changing the size of a type used
in a function parameter will affect the ABI and thus pointers used in function
parameters are ABI-visible pointers. On the other hand, changing the types of
local variables won't have such ABI implications. Hence, `-fbounds-safety`
considers the outermost pointer types of local variables as non-ABI visible. The
rest of the pointers such as nested pointer types, pointer types of global
variables, struct fields, and function prototypes are considered ABI-visible.

All ABI-visible pointers are treated as `__single` by default unless annotated
otherwise. This default both preserves ABI and makes these pointers safe by
default. This behavior can be controlled with macros, i.e.,
`__ptrcheck_abi_assume_*ATTR*()`, to set the default annotation for
ABI-visible pointers to be either `__single`, `__bidi_indexable`,
`__indexable`, or `__unsafe_indexable`. For instance,
`__ptrcheck_abi_assume_unsafe_indexable()` will make all ABI-visible pointers
be `__unsafe_indexable`. Non-ABI visible pointers — the outermost pointer
types of local variables — are `__bidi_indexable` by default, so that these
pointers have the bounds information necessary to perform bounds checks without
the need for a manual annotation. All `const char` pointers or any typedefs
equivalent to `const char` pointers are `__null_terminated` by default. This
means that `char8_t` is `unsigned char` so `const char8_t *` won't be
`__null_terminated` by default. Similarly, `const wchar_t *` won't be
`__null_terminated` by default unless the platform defines it as `typedef
char wchar_t`. Please note, however, that the programmers can still explicitly
use `__null_terminated` in any other pointers, e.g., `char8_t
*__null_terminated`, `wchar_t *__null_terminated`, `int
*__null_terminated`, etc. if they should be treated as `__null_terminated`.
The same applies to other annotations.
In system headers, the default pointer attribute for ABI-visible pointers is set
to `__unsafe_indexable` by default.

The `__ptrcheck_abi_assume_*ATTR*()` macros are defined as pragmas in the
toolchain header (See [Portability with toolchains that do not support the
extension](#portability-with-toolchains-that-do-not-support-the-extension) for more details about the toolchain header):

```C
#define __ptrcheck_abi_assume_single() \
   _Pragma("clang abi_ptr_attr set(single)")

#define __ptrcheck_abi_assume_indexable() \
  _Pragma("clang abi_ptr_attr set(indexable)")

#define __ptrcheck_abi_assume_bidi_indexable() \
  _Pragma("clang abi_ptr_attr set(bidi_indexable)")

#define __ptrcheck_abi_assume_unsafe_indexable() \
  _Pragma("clang abi_ptr_attr set(unsafe_indexable)")
```

#### ABI implications of default bounds annotations

Although simply modifying types of a local variable doesn't normally impact the
ABI, taking the address of such a modified type could create a pointer type that
has an ABI mismatch. Looking at the following example, `int *local` is
implicitly `int *__bidi_indexable` and thus the type of `&local` is a
pointer to `int *__bidi_indexable`. On the other hand, in `void foo(int
**)`, the parameter type is a pointer to `int *__single` (i.e., `void
foo(int *__single *__single)`) (or a pointer to `int *__unsafe_indexable` if
it's from a system header). The compiler reports an error for casts between
pointers whose elements have incompatible pointer attributes. This way,
`-fbounds-safety` prevents pointers that are implicitly `__bidi_indexable`
from silently escaping thereby breaking the ABI.

```c
void foo(int **);

void bar(void) {
   int *local = 0;
   // error: passing 'int *__bidi_indexable*__bidi_indexable' to parameter of
   // incompatible nested pointer type 'int *__single*__single'
   foo(&local);
}
```

A local variable may still be exposed to the ABI if `typeof()` takes the type
of local variable to define an interface as shown in the following example.

```C
// bar.c
void bar(int *) { ... }

// foo.c
void foo(void) {
   int *p; // implicitly `int *__bidi_indexable p`
   extern void bar(typeof(p)); // creates an interface of type
                               // `void bar(int *__bidi_indexable)`
}
```

Doing this may break the ABI if the parameter is not `__bidi_indexable` at the
definition of function `bar()` which is likely the case because parameters are
`__single` by default without an explicit annotation.

In order to avoid an implicitly wide pointer from silently breaking the ABI, the
compiler reports a warning when `typeof()` is used on an implicit wide pointer
at any ABI visible context (e.g., function prototype, struct definition, etc.).

(default-pointer-types-in-typeof)=

#### Default pointer types in `typeof()`

When `typeof()` takes an expression, it respects the bounds annotation on
the expression type, including the bounds annotation is implicit. For example,
the global variable `g` in the following code is implicitly `__single` so
`typeof(g)` gets `char *__single`. The similar is true for the parameter
`p`, so `typeof(p)` returns `void *__single`. The local variable `l` is
implicitly `__bidi_indexable`, so `typeof(l)` becomes
`int *__bidi_indexable`.

```C
char *g; // typeof(g) == char *__single

void foo(void *p) {
   // typeof(p) == void *__single

   int *l; // typeof(l) == int *__bidi_indexable
}
```

When the type of expression has an "external" bounds annotation, e.g.,
`__sized_by`, `__counted_by`, etc., the compiler may report an error on
`typeof` if the annotation creates a dependency with another declaration or
variable. For example, the compiler reports an error on `typeof(p1)` shown in
the following code because allowing it can potentially create another type
dependent on the parameter `size` in a different context (Please note that an
external bounds annotation on a parameter may only refer to another parameter of
the same function). On the other hand, `typeof(p2)` works resulting in `int
*__counted_by(10)`, since it doesn't depend on any other declaration.

% TODO: add a section describing constraints on external bounds annotations

```C
void foo(int *__counted_by(size) p1, size_t size) {
   // typeof(p1) == int *__counted_by(size)
   // -> a compiler error as it tries to create another type
   // dependent on `size`.

   int *__counted_by(10) p2; // typeof(p2) == int *__counted_by(10)
                             // -> no error

}
```

When `typeof()` takes a type name, the compiler doesn't apply an implicit
bounds annotation on the named pointer types. For example, `typeof(int*)`
returns `int *` without any bounds annotation. A bounds annotation may be
added after the fact depending on the context. In the following example,
`typeof(int *)` returns `int *` so it's equivalent as the local variable is
declared as `int *l`, so it eventually becomes implicitly
`__bidi_indexable`.

```c
void foo(void) {
   typeof(int *) l; // `int *__bidi_indexable` (same as `int *l`)
}
```

The programmers can still explicitly add a bounds annotation on the types named
inside `typeof`, e.g., `typeof(int *__bidi_indexable)`, which evaluates to
`int *__bidi_indexable`.

#### Default pointer types in `sizeof()`

When `sizeof()` takes a type name, the compiler doesn't apply an implicit
bounds annotation on the named pointer types. This means if a bounds annotation
is not specified, the evaluated pointer type is treated identically to a plain C
pointer type. Therefore, `sizeof(int*)` remains the same with or without
`-fbounds-safety`. That said, programmers can explicitly add attributes to the
types, e.g., `sizeof(int *__bidi_indexable)`, in which case the sizeof
evaluates to the size of type `int *__bidi_indexable` (the value equivalent to
`3 * sizeof(int*)`).

When `sizeof()` takes an expression, i.e., `sizeof(expr`, it behaves as
`sizeof(typeof(expr))`, except that `sizeof(expr)` does not report an error
with `expr` that has a type with an external bounds annotation dependent on
another declaration, whereas `typeof()` on the same expression would be an
error as described in [Default pointer types in typeof()](#default-pointer-types-in-typeof).
The following example describes this behavior.

```c
void foo(int *__counted_by(size) p, size_t size) {
   // sizeof(p) == sizeof(int *__counted_by(size)) == sizeof(int *)
   // typeof(p): error
};
```

#### Default pointer types in `alignof()`

`alignof()` only takes a type name as the argument and it doesn't take an
expression. Similar to `sizeof()` and `typeof`, the compiler doesn't apply
an implicit bounds annotation on the pointer types named inside `alignof()`.
Therefore, `alignof(T *)` remains the same with or without
`-fbounds-safety`, evaluating into the alignment of the raw pointer `T *`.
The programmers can explicitly add a bounds annotation to the types, e.g.,
`alignof(int *__bidi_indexable)`, which returns the alignment of `int
*__bidi_indexable`. A bounds annotation including an internal bounds annotation
(i.e., `__indexable` and `__bidi_indexable`) doesn't affect the alignment of
the original pointer. Therefore, `alignof(int *__bidi_indexable)` is equal to
`alignof(int *)`.

#### Default pointer types used in C-style casts

A pointer type used in a C-style cast (e.g., `(int *)src`) inherits the same
pointer attribute in the type of src. For instance, if the type of src is `T
*__single` (with `T` being an arbitrary C type), `(int *)src` will be `int
*__single`. The reasoning behind this behavior is so that a C-style cast
doesn't introduce any unexpected side effects caused by an implicit cast of
bounds attribute.

Pointer casts can have explicit bounds annotations. For instance, `(int
*__bidi_indexable)src` casts to `int *__bidi_indexable` as long as src has a
bounds annotation that can implicitly convert to `__bidi_indexable`. If
`src` has type `int *__single`, it can implicitly convert to `int
*__bidi_indexable` which then will have the upper bound pointing to one past
the first element. However, if src has type `int *__unsafe_indexable`, the
explicit cast `(int *__bidi_indexable)src` will cause an error because
`__unsafe_indexable` cannot cast to `__bidi_indexable` as
`__unsafe_indexable` doesn't have bounds information. [Cast rules](#cast-rules)
describes in more detail what kinds of casts are allowed between pointers with
different bounds annotations.

#### Default pointer types in typedef

Pointer types in `typedef`s do not have implicit default bounds annotations.
Instead, the bounds annotation is determined when the `typedef` is used. The
following example shows that no pointer annotation is specified in the `typedef
pint_t` while each instance of `typedef`'ed pointer gets its bounds
annotation based on the context in which the type is used.

```c
typedef int * pint_t; // int *

pint_t glob; // int *__single glob;

void foo(void) {
   pint_t local; // int *__bidi_indexable local;
}
```

Pointer types in a `typedef` can still have explicit annotations, e.g.,
`typedef int *__single`, in which case the bounds annotation `__single` will
apply to every use of the `typedef`.

### Array to pointer promotion to secure arrays (including VLAs)

#### Arrays on function prototypes

In C, arrays on function prototypes are promoted (or "decayed") to a pointer to
its first element (e.g., `&arr[0]`). In `-fbounds-safety`, arrays are also
decayed to pointers, but with the addition of an implicit bounds annotation,
which includes variable-length arrays (VLAs). As shown in the following example,
arrays on function prototypes are decayed to corresponding `__counted_by`
pointers.

```c
// Function prototype: void foo(int n, int *__counted_by(n) arr);
void foo(int n, int arr[n]);

// Function prototype: void bar(int *__counted_by(10) arr);
void bar(int arr[10]);
```

This means the array parameters are treated as `__counted_by` pointers within
the function and callers of the function also see them as the corresponding
`__counted_by` pointers.

Incomplete arrays on function prototypes will cause a compiler error unless it
has `__counted_by` annotation in its bracket.

```c
void f1(int n, int arr[]); // error

void f3(int n, int arr[__counted_by(n)]); // ok

void f2(int n, int arr[n]); // ok, decays to int *__counted_by(n)

void f4(int n, int *__counted_by(n) arr); // ok

void f5(int n, int *arr); // ok, but decays to int *__single,
                          // and cannot be used for pointer arithmetic
```

#### Array references

In C, similar to arrays on the function prototypes, a reference to array is
automatically promoted (or "decayed") to a pointer to its first element (e.g.,
`&arr[0]`).

In `-fbounds-safety`, array references are promoted to `__bidi_indexable`
pointers which contain the upper and lower bounds of the array, with the
equivalent of `&arr[0]` serving as the lower bound and `&arr[array_size]`
(or one past the last element) serving as the upper bound. This applies to all
types of arrays including constant-length arrays, variable-length arrays (VLAs),
and flexible array members annotated with `__counted_by`.

In the following example, reference to `vla` promotes to `int
*__bidi_indexable`, with `&vla[n]` as the upper bound and `&vla[0]` as the
lower bound. Then, it's copied to `int *p`, which is implicitly `int
*__bidi_indexable p`. Please note that value of `n` used to create the upper
bound is `10`, not `100`, in this case because `10` is the actual length
of `vla`, the value of `n` at the time when the array is being allocated.

```c
void foo(void) {
   int n = 10;
   int vla[n];
   n = 100;
   int *p = vla; // { .ptr: &vla[0], .upper: &vla[10], .lower: &vla[0] }
                 // it's `&vla[10]` because the value of `n` was 10 at the
                 // time when the array is actually allocated.
   // ...
}
```

By promoting array references to `__bidi_indexable`, all array accesses are
bounds checked in `-fbounds-safety`, just as `__bidi_indexable` pointers
are.

### Maintaining correctness of bounds annotations

`-fbounds-safety` maintains correctness of bounds annotations by performing
additional checks when a pointer object and/or its related value containing the
bounds information is updated.

For example, `__single` expresses an invariant that the pointer must either
point to a single valid object or be a null pointer. To maintain this invariant,
the compiler inserts checks when initializing a `__single` pointer, as shown
in the following example:

```c
void foo(void *__sized_by(size) vp, size_t size) {
   // Inserted check:
   // if ((int*)upper_bound(vp) - (int*)vp < sizeof(int) && !!vp) trap();
   int *__single ip = (int *)vp;
}
```

Additionally, an explicit bounds annotation such as `int *__counted_by(count)
buf` defines a relationship between two variables, `buf` and `count`:
namely, that `buf` has `count` number of elements available. This
relationship must hold even after any of these related variables are updated. To
this end, the model requires that assignments to `buf` and `count` must be
side by side, with no side effects between them. This prevents `buf` and
`count` from temporarily falling out of sync due to updates happening at a
distance.

The example below shows a function `alloc_buf` that initializes a struct that
members that use the `__counted_by` annotation. The compiler allows these
assignments because `sbuf->buf` and `sbuf->count` are updated side by side
without any side effects in between the assignments.

Furthermore, the compiler inserts additional run-time checks to ensure the new
`buf` has at least as many elements as the new `count` indicates as shown in
the transformed pseudo code of function `alloc_buf()` in the example below.

```c
typedef struct {
   int *__counted_by(count) buf;
   size_t count;
} sized_buf_t;

void alloc_buf(sized_buf_t *sbuf, size_t nelems) {
   sbuf->buf = (int *)malloc(sizeof(int) * nelems);
   sbuf->count = nelems;
}

// Transformed pseudo code:
void alloc_buf(sized_buf_t *sbuf, size_t nelems) {
   // Materialize RHS values:
   int *tmp_ptr = (int *)malloc(sizeof(int) * nelems);
   int tmp_count = nelems;
   // Inserted check:
   //   - checks to ensure that `lower <= tmp_ptr <= upper`
   //   - if (upper(tmp_ptr) - tmp_ptr < tmp_count) trap();
   sbuf->buf = tmp_ptr;
   sbuf->count = tmp_count;
}
```

Whether the compiler can optimize such run-time checks depends on how the upper
bound of the pointer is derived. If the source pointer has `__sized_by`,
`__counted_by`, or a variant of such, the compiler assumes that the upper
bound calculation doesn't overflow, e.g., `ptr + size` (where the type of
`ptr` is `void *__sized_by(size)`), because when the `__sized_by` pointer
is initialized, `-fbounds-safety` inserts run-time checks to ensure that `ptr
+ size` doesn't overflow and that `size >= 0`.

Assuming the upper bound calculation doesn't overflow, the compiler can simplify
the trap condition `upper(tmp_ptr) - tmp_ptr < tmp_count` to `size <
tmp_count` so if both `size` and `tmp_count` values are known at compile
time such that `0 <= tmp_count <= size`, the optimizer can remove the check.

`ptr + size` may still overflow if the `__sized_by` pointer is created from
code that doesn't enable `-fbounds-safety`, which is undefined behavior.

In the previous code example with the transformed `alloc_buf()`, the upper
bound of `tmp_ptr` is derived from `void *__sized_by_or_null(size)`, which
is the return type of `malloc()`. Hence, the pointer arithmetic doesn't
overflow or `tmp_ptr` is null. Therefore, if `nelems` was given as a
compile-time constant, the compiler could remove the checks.

### Cast rules

`-fbounds-safety` does not enforce overall type safety and bounds invariants
can still be violated by incorrect casts in some cases. That said,
`-fbounds-safety` prevents type conversions that change bounds attributes in a
way to violate the bounds invariant of the destination's pointer annotation.
Type conversions that change bounds attributes may be allowed if it does not
violate the invariant of the destination or that can be verified at run time.
Here are some of the important cast rules.

Two pointers that have different bounds annotations on their nested pointer
types are incompatible and cannot implicitly cast to each other. For example,
`T *__single *__single` cannot be converted to `T *__bidi_indexable
*__single`. Such a conversion between incompatible nested bounds annotations
can be allowed using an explicit cast (e.g., C-style cast). Hereafter, the rules
only apply to the top pointer types. `__unsafe_indexable` cannot be converted
to any other safe pointer types (`__single`, `__bidi_indexable`,
`__counted_by`, etc) using a cast. The extension provides builtins to force
this conversion, `__unsafe_forge_bidi_indexable(type, pointer, char_count)` to
convert pointer to a `__bidi_indexable` pointer of type with `char_count`
bytes available and `__unsafe_forge_single(type, pointer)` to convert pointer
to a single pointer of type type. The following examples show the usage of these
functions. Function `example_forge_bidi()` gets an external buffer from an
unsafe library by calling `get_buf()` which returns `void
*__unsafe_indexable.` Under the type rules, this cannot be directly assigned to
`void *buf` (implicitly `void *__bidi_indexable`). Thus,
`__unsafe_forge_bidi_indexable` is used to manually create a
`__bidi_indexable` from the unsafe buffer.

```c
// unsafe_library.h
void *__unsafe_indexable get_buf(void);
size_t get_buf_size(void);

// my_source1.c (enables -fbounds-safety)
#include "unsafe_library.h"
void example_forge_bidi(void) {
   void *buf =
     __unsafe_forge_bidi_indexable(void *, get_buf(), get_buf_size());
   // ...
}

// my_source2.c (enables -fbounds-safety)
#include <stdio.h>
void example_forge_single(void) {
   FILE *fp = __unsafe_forge_single(FILE *, fopen("mypath", "rb"));
   // ...
}
```

- Function `example_forge_single` takes a file handle by calling fopen defined
  in system header `stdio.h`. Assuming `stdio.h` did not adopt
  `-fbounds-safety`, the return type of `fopen` would implicitly be `FILE
  *__unsafe_indexable` and thus it cannot be directly assigned to `FILE *fp`
  in the bounds-safe source. To allow this operation, `__unsafe_forge_single`
  is used to create a `__single` from the return value of `fopen`.

- Similar to `__unsafe_indexable`, any non-pointer type (including `int`,
  `intptr_t`, `uintptr_t`, etc.) cannot be converted to any safe pointer
  type because these don't have bounds information. `__unsafe_forge_single` or
  `__unsafe_forge_bidi_indexable` must be used to force the conversion.

- Any safe pointer types can cast to `__unsafe_indexable` because it doesn't
  have any invariant to maintain.

- `__single` casts to `__bidi_indexable` if the pointee type has a known
  size. After the conversion, the resulting `__bidi_indexable` has the size of
  a single object of the pointee type of `__single`. `__single` cannot cast
  to `__bidi_indexable` if the pointee type is incomplete or sizeless. For
  example, `void *__single` cannot convert to `void *__bidi_indexable`
  because void is an incomplete type and thus the compiler cannot correctly
  determine the upper bound of a single void pointer.

- Similarly, `__single` can cast to `__indexable` if the pointee type has a
  known size. The resulting `__indexable` has the size of a single object of
  the pointee type.

- `__single` casts to `__counted_by(E)` only if `E` is 0 or 1.

- `__single` can cast to `__single` including when they have different
  pointee types as long as it is allowed in the underlying C standard.
  `-fbounds-safety` doesn't guarantee type safety.

- `__bidi_indexable` and `__indexable` can cast to `__single`. The
  compiler may insert run-time checks to ensure the pointer has at least a
  single element or is a null pointer.

- `__bidi_indexable` casts to `__indexable` if the pointer does not have an
  underflow. The compiler may insert run-time checks to ensure the pointer is
  not below the lower bound.

- `__indexable` casts to `__bidi_indexable`. The resulting
  `__bidi_indexable` gets the lower bound same as the pointer value.

- A type conversion may involve both a bitcast and a bounds annotation cast. For
  example, casting from `int *__bidi_indexable` to `char *__single` involves
  a bitcast (`int *` to `char *`) and a bounds annotation cast
  (`__bidi_indexable` to `__single`). In this case, the compiler performs
  the bitcast and then converts the bounds annotation. This means, `int
  *__bidi_indexable` will be converted to `char *__bidi_indexable` and then
  to `char *__single`.

- `__terminated_by(T)` cannot cast to any safe pointer type without the same
  `__terminated_by(T)` attribute. To perform the cast, programmers can use an
  intrinsic function such as `__unsafe_terminated_by_to_indexable(P)` to force
  the conversion.

- `__terminated_by(T)` can cast to `__unsafe_indexable`.

- Any type without `__terminated_by(T)` cannot cast to `__terminated_by(T)`
  without explicitly using an intrinsic function to allow it.

  - `__unsafe_terminated_by_from_indexable(T, PTR [, PTR_TO_TERM])` casts any
    safe pointer PTR to a `__terminated_by(T)` pointer. `PTR_TO_TERM` is an
    optional argument where the programmer can provide the exact location of the
    terminator. With this argument, the function can skip reading the entire
    array in order to locate the end of the pointer (or the upper bound).
    Providing an incorrect `PTR_TO_TERM` causes a run-time trap.
  - `__unsafe_forge_terminated_by(T, P, E)` creates `T __terminated_by(E)`
    pointer given any pointer `P`. Tmust be a pointer type.

### Portability with toolchains that do not support the extension

The language model is designed so that it doesn't alter the semantics of the
original C program, other than introducing deterministic traps where otherwise
the behavior is undefined and/or unsafe. Clang provides a toolchain header
(`ptrcheck.h`) that macro-defines the annotations as type attributes when
`-fbounds-safety` is enabled and defines them to empty when the extension is
disabled. Thus, the code adopting `-fbounds-safety` can compile with
toolchains that do not support this extension, by including the header or adding
macros to define the annotations to empty. For example, the toolchain not
supporting this extension may not have a header defining `__counted_by`, so
the code using `__counted_by` must define it as nothing or include a header
that has the define.

```c
#if defined(__has_feature) && __has_feature(bounds_safety)
#define __counted_by(T) __attribute__((__counted_by__(T)))
// ... other bounds annotations
#else
#define __counted_by(T) // defined as nothing
// ... other bounds annotations
#endif

// expands to `void foo(int * ptr, size_t count);`
// when extension is not enabled or not available
void foo(int *__counted_by(count) ptr, size_t count);
```

## Other potential applications of bounds annotations

The bounds annotations provided by the `-fbounds-safety` programming model
have potential use cases beyond the language extension itself. For example,
static and dynamic analysis tools could use the bounds information to improve
diagnostics for out-of-bounds accesses, even if `-fbounds-safety` is not used.
The bounds annotations could be used to improve C interoperability with
bounds-safe languages, providing a better mapping to bounds-safe types in the
safe language interface. The bounds annotations can also serve as documentation
specifying the relationship between declarations.

## Limitations

`-fbounds-safety` aims to bring the bounds safety guarantee to the C language,
and it does not guarantee other types of memory safety properties. Consequently,
it may not prevent some of the secondary bounds safety violations caused by
other types of safety violations such as type confusion. For instance,
`-fbounds-safety` does not perform type-safety checks on conversions between
`__single` pointers of different pointee types (e.g., `char *__single` →
`void *__single` → `int *__single`) beyond what the foundation languages
(C/C++) already offer.

`-fbounds-safety` heavily relies on run-time checks to keep the bounds safety
and the soundness of the type system. This may incur significant code size
overhead in unoptimized builds and leave some of the adoption mistakes to be
caught only at run time. This is not a fundamental limitation, however, because
incrementally adding necessary static analysis will allow us to catch issues
early on and remove unnecessary bounds checks in unoptimized builds.

## Try it out

Your feedback on the programming model is valuable. You may want to follow the
instruction in {doc}`BoundsSafetyAdoptionGuide` to play with `-fbounds-safety`
and please send your feedback to [Yeoul Na](mailto:yeoul_na@apple.com).

---

### Clang Docs BoundsSafetyAdoptionGuide (`clang/docs/BoundsSafetyAdoptionGuide.md`)

# Adoption Guide for `-fbounds-safety`


## Where to get `-fbounds-safety`

The open sourcing to llvm.org's `llvm-project` is still on going and the
feature is not available yet. In the mean time, the preview implementation is
available
[here](https://github.com/swiftlang/llvm-project/tree/stable/20240723) in a
fork of `llvm-project`. Please follow
[Building LLVM with CMake](https://llvm.org/docs/CMake.html) to build the
compiler.

## Feature flag

Pass `-fbounds-safety` as a Clang compilation flag for the C file that you
want to adopt. We recommend adopting the model file by file, because adoption
requires some effort to add bounds annotations and fix compiler diagnostics.

## Include `ptrcheck.h`

`ptrcheck.h` is a Clang toolchain header to provide definition of the bounds
annotations such as `__counted_by`, `__counted_by_or_null`, `__sized_by`,
etc. In the LLVM source tree, the header is located in
`llvm-project/clang/lib/Headers/ptrcheck.h`.

## Add bounds annotations on pointers as necessary

Annotate pointers on struct fields and function parameters if they are pointing
to an array of object, with appropriate bounds annotations. Please see
{doc}`BoundsSafety` to learn what kind of bounds annotations are available and
their semantics. Note that local pointer variables typically don't need bounds
annotations because they are implicitly a wide pointer (`__bidi_indexable`)
that automatically carries the bounds information.

## Address compiler diagnostics

Once you pass `-fbounds-safety` to compile a C file, you will see some new
compiler warnings and errors, which guide adoption of `-fbounds-safety`.
Consider the following example:

```c
#include <ptrcheck.h>

void init_buf(int *p, int n) {
   for (int i = 0; i < n; ++i)
      p[i] = 0; // error: array subscript on single pointer 'p' must use a constant index of 0 to be in bounds
}
```

The parameter `int *p` doesn't have a bounds annotation, so the compiler will
complain about the code indexing into it (`p[i]`) as it assumes that `p` is
pointing to a single `int` object or null. To address the diagnostics, you
should add a bounds annotation on `int *p` so that the compiler can reason
about the safety of the array subscript. In the following example, `p` is now
`int *__counted_by(n)`, so the compiler will allow the array subscript with
additional run-time checks as necessary.

```c
#include <ptrcheck.h>

void init_buf(int *__counted_by(n) p, int n) {
   for (int i = 0; i < n; ++i)
      p[i] = 0; // ok; `p` is now has a type with bounds annotation.
}
```

## Run test suites to fix new run-time traps

Adopting `-fbounds-safety` may cause your program to trap if it violates
bounds safety or it has incorrect adoption. Thus, it is necessary to perform
run-time testing of your program to gain confidence that it won't trap at
run time.

## Repeat the process for each remaining file

Once you've done with adopting a single C file, please repeat the same process
for each remaining C file that you want to adopt.

---

### Clang Docs BoundsSafetyImplPlans (`clang/docs/BoundsSafetyImplPlans.md`)

# Implementation plans for `-fbounds-safety`


(bounds-safety-current-upstream-status)=
## Current status of `-fbounds-safety` support in upstream Clang


Not fully implemented upstream.

## Gradual updates with experimental flag

The feature will be implemented as a series of smaller PRs and we will guard our
implementation with an experimental flag `-fexperimental-bounds-safety` until
the usable model is fully available. Once the model is ready for use, we will
expose the flag `-fbounds-safety`.

### Possible patch sets

- External bounds annotations and the (late) parsing logic.
- Internal bounds annotations (wide pointers) and their parsing logic.
- Clang code generation for wide pointers with debug information.
- Pointer cast semantics involving bounds annotations (this could be divided
  into multiple sub-PRs).
- CFG analysis for pairs of related pointer and count assignments and the likes.
- Bounds check expressions in AST and the Clang code generation (this could also
  be divided into multiple sub-PRs).

## Proposed implementation

### External bounds annotations

The bounds annotations are C type attributes appertaining to pointer types. If
an attribute is added to the position of a declaration attribute, e.g., `int
*ptr __counted_by(size)`, the attribute appertains to the outermost pointer
type of the declaration (`int *`).

### New sugar types

An external bounds annotation creates a type sugar of the underlying pointer
types. We will introduce a new sugar type, `DynamicBoundsPointerType` to
represent `__counted_by` or `__sized_by`. Using `AttributedType` would not
be sufficient because the type needs to hold the count or size expression as
well as some metadata necessary for analysis, while this type may be implemented
through inheritance from `AttributedType`. Treating the annotations as type
sugars means two types with incompatible external bounds annotations may be
considered canonically the same types. This is sometimes necessary, for example,
to make the `__counted_by` and friends not participate in function
overloading. However, this design requires a separate logic to walk through the
entire type hierarchy to check type compatibility of bounds annotations.

### Late parsing for C

A bounds annotation such as `__counted_by(count)` can be added to type of a
struct field declaration where count is another field of the same struct
declared later. Similarly, the annotation may apply to type of a function
parameter declaration which precedes the parameter count in the same function.
This means parsing the argument of bounds annotations must be done after the
parser has the whole context of a struct or a function declaration. Clang has
late parsing logic for C++ declaration attributes that require late parsing,
while the C declaration attributes and C/C++ type attributes do not have the
same logic. This requires introducing late parsing logic for C/C++ type
attributes.

### Internal bounds annotations

`__indexable` and `__bidi_indexable` alter pointer representations to be
equivalent to a struct with the pointer and the corresponding bounds fields.
Despite this difference in their representations, they are still pointers in
terms of types of operations that are allowed and their semantics. For instance,
a pointer dereference on a `__bidi_indexable` pointer will return the
dereferenced value same as plain C pointers, modulo the extra bounds checks
being performed before dereferencing the wide pointer. This means mapping the
wide pointers to struct types with equivalent layout won’t be sufficient. To
represent the wide pointers in Clang AST, we add an extra field in the
PointerType class to indicate the internal bounds of the pointer. This ensures
pointers of different representations are mapped to different canonical types
while they are still treated as pointers.

In LLVM IR, wide pointers will be emitted as structs of equivalent
representations. Clang CodeGen will handle them as Aggregate in
`TypeEvaluationKind (TEK)`. `AggExprEmitter` was extended to handle pointer
operations returning wide pointers. Alternatively, a new `TEK` and an
expression emitter dedicated to wide pointers could be introduced.

### Default bounds annotations

The model may implicitly add `__bidi_indexable` or `__single` depending on
the context of the declaration that has the pointer type. `__bidi_indexable`
implicitly adds to local variables, while `__single` implicitly adds to
pointer types specifying struct fields, function parameters, or global
variables. This means the parser may first create the pointer type without any
default pointer attribute and then recreate the type once the parser has the
declaration context and determined the default attribute accordingly.

This also requires the parser to reset the type of the declaration with the
newly created type with the right default attribute.

### Promotion expression

A new expression will be introduced to represent the conversion from a pointer
with an external bounds annotation, such as `__counted_by`, to
`__bidi_indexable`. This type of conversion cannot be handled by normal
CastExprs because it requires an extra subexpression(s) to provide the bounds
information necessary to create a wide pointer.

### Bounds check expression

Bounds checks are part of semantics defined in the `-fbounds-safety` language
model. Hence, exposing the bounds checks and other semantic actions in the AST
is desirable. A new expression for bounds checks has been added to the AST. The
bounds check expression has a `BoundsCheckKind` to indicate the kind of checks
and has the additional sub-expressions that are necessary to perform the check
according to the kind.

### Paired assignment check

`-fbounds-safety` enforces that variables or fields related with the same
external bounds annotation (e.g., `buf` and `count` related with
`__counted_by` in the example below) must be updated side by side within the
same basic block and without side effect in between.

```c
typedef struct {
   int *__counted_by(count) buf; size_t count;
} sized_buf_t;

void alloc_buf(sized_buf_t *sbuf, size_t nelems) {
   sbuf->buf = (int *)malloc(sizeof(int) * nelems);
   sbuf->count = nelems;
}
```

To implement this rule, the compiler requires a linear representation of
statements to understand the ordering and the adjacency between the two or more
assignments. The Clang CFG is used to implement this analysis as Clang CFG
provides a linear view of statements within each `CFGBlock` (Clang
`CFGBlock` represents a single basic block in a source-level CFG).

### Bounds check optimizations

In `-fbounds-safety`, the Clang frontend emits run-time checks for every
memory dereference if the type system or analyses in the frontend couldn’t
verify its bounds safety. The implementation relies on LLVM optimizations to
remove redundant run-time checks. Using this optimization strategy, if the
original source code already has bounds checks, the fewer additional checks
`-fbounds-safety` will introduce. The LLVM `ConstraintElimination` pass is
designed to remove provable redundant checks (please check Florian Hahn’s
presentation in 2021 LLVM Dev Meeting and the implementation to learn more). In
the following example, `-fbounds-safety` implicitly adds the redundant bounds
checks that the optimizer can remove:

```c
void fill_array_with_indices(int *__counted_by(count) p, size_t count) {
   for (size_t i = 0; i < count; ++i) {
      // implicit bounds checks:
      //   if (p + i < p || p + i + 1 > p + count) trap();
      p[i] = i;
   }
}
```

`ConstraintElimination` collects the following facts and determines if the
bounds checks can be safely removed:

- Inside the for-loop, `0 <= i < count`, hence `1 <= i + 1 <= count`.
- Pointer arithmetic `p + count` in the if-condition doesn’t wrap.
- `-fbounds-safety` treats pointer arithmetic overflow as deterministically
  two’s complement computation, not an undefined behavior. Therefore,
  getelementptr does not typically have inbounds keyword. However, the compiler
  does emit inbounds for `p + count` in this case because
  `__counted_by(count)` has the invariant that p has at least as many as
  elements as count. Using this information, `ConstraintElimination` is able
  to determine `p + count` doesn’t wrap.
- Accordingly, `p + i` and `p + i + 1` also don’t wrap.
- Therefore, `p <= p + i` and `p + i + 1 <= p + count`.
- The if-condition simplifies to false and becomes dead code that the subsequent
  optimization passes can remove.

`OptRemarks` can be utilized to provide insights into performance tuning. It
has the capability to report on checks that it cannot eliminate, possibly with
reasons, allowing programmers to adjust their code to unlock further
optimizations.

## Debugging

### Internal bounds annotations

Internal bounds annotations change a pointer into a wide pointer. The debugger
needs to understand that wide pointers are essentially pointers with a struct
layout. To handle this, a wide pointer is described as a record type in the
debug info. The type name has a special name prefix (e.g.,
`__bounds_safety$bidi_indexable`) which can be recognized by a debug info
consumer to provide support that goes beyond showing the internal structure of
the wide pointer. There are no DWARF extensions needed to support wide pointers.
In our implementation, LLDB recognizes wide pointer types by name and
reconstructs them as wide pointer Clang AST types for use in the expression
evaluator.

### External bounds annotations

Similar to internal bounds annotations, external bound annotations are described
as a typedef to their underlying pointer type in the debug info, and the bounds
are encoded as strings in the typedef’s name (e.g.,
`__bounds_safety$counted_by:N`).

### Recognizing `-fbounds-safety` traps

Clang emits debug info for `-fbounds-safety` traps as inlined functions, where
the function name encodes the error message. LLDB implements a frame recognizer
to surface a human-readable error cause to the end user. A debug info consumer
that is unaware of this sees an inlined function whose name encodes an error
message (e.g., : `__bounds_safety$Bounds check failed`).

### Expression Parsing

In our implementation, LLDB’s expression evaluator does not enable the
`-fbounds-safety` language option because it’s currently unable to fully
reconstruct the pointers with external bounds annotations, and also because the
evaluator operates in C++ mode, utilizing C++ reference types, while
`-fbounds-safety` does not currently support C++. This means LLDB’s expression
evaluator can only evaluate a subset of the `-fbounds-safety` language model.
Specifically, it’s capable of evaluating the wide pointers that already exist in
the source code. All other expressions are evaluated according to C/C++
semantics.

## C++ support

C++ has multiple options to write code in a bounds-safe manner, such as
following the bounds-safety core guidelines and/or using hardened libc++ along
with the [C++ Safe Buffer model](https://discourse.llvm.org/t/rfc-c-buffer-hardening/65734). However, these
techniques may require ABI changes and may not be applicable to code
interoperating with C. When the ABI of an existing program needs to be preserved
and for headers shared between C and C++, `-fbounds-safety` offers a potential
solution.

`-fbounds-safety` is not currently supported in C++, but we believe the
general approach would be applicable for future efforts.

---

### Clang Docs CMakeLists (`clang/docs/CMakeLists.txt`)

if (DOXYGEN_FOUND)
if (LLVM_ENABLE_DOXYGEN)
  set(abs_srcdir ${CMAKE_CURRENT_SOURCE_DIR})
  set(abs_builddir ${CMAKE_CURRENT_BINARY_DIR})

  if (HAVE_DOT)
    set(DOT ${LLVM_PATH_DOT})
  endif()

  if (LLVM_DOXYGEN_EXTERNAL_SEARCH)
    set(enable_searchengine "YES")
    set(searchengine_url "${LLVM_DOXYGEN_SEARCHENGINE_URL}")
    set(enable_server_based_search "YES")
    set(enable_external_search "YES")
    set(extra_search_mappings "${LLVM_DOXYGEN_SEARCH_MAPPINGS}")
  else()
    set(enable_searchengine "NO")
    set(searchengine_url "")
    set(enable_server_based_search "NO")
    set(enable_external_search "NO")
    set(extra_search_mappings "")
  endif()

  # If asked, configure doxygen for the creation of a Qt Compressed Help file.
  if (LLVM_ENABLE_DOXYGEN_QT_HELP)
    set(CLANG_DOXYGEN_QCH_FILENAME "org.llvm.clang.qch" CACHE STRING
      "Filename of the Qt Compressed help file")
    set(CLANG_DOXYGEN_QHP_NAMESPACE "org.llvm.clang" CACHE STRING
      "Namespace under which the intermediate Qt Help Project file lives")
    set(CLANG_DOXYGEN_QHP_CUST_FILTER_NAME "Clang ${CLANG_VERSION}" CACHE STRING
      "See http://qt-project.org/doc/qt-4.8/qthelpproject.html#custom-filters")
    set(CLANG_DOXYGEN_QHP_CUST_FILTER_ATTRS "Clang,${CLANG_VERSION}" CACHE STRING
      "See http://qt-project.org/doc/qt-4.8/qthelpproject.html#filter-attributes")
    set(clang_doxygen_generate_qhp "YES")
    set(clang_doxygen_qch_filename "${CLANG_DOXYGEN_QCH_FILENAME}")
    set(clang_doxygen_qhp_namespace "${CLANG_DOXYGEN_QHP_NAMESPACE}")
    set(clang_doxygen_qhelpgenerator_path "${LLVM_DOXYGEN_QHELPGENERATOR_PATH}")
    set(clang_doxygen_qhp_cust_filter_name "${CLANG_DOXYGEN_QHP_CUST_FILTER_NAME}")
    set(clang_doxygen_qhp_cust_filter_attrs "${CLANG_DOXYGEN_QHP_CUST_FILTER_ATTRS}")
  else()
    set(clang_doxygen_generate_qhp "NO")
    set(clang_doxygen_qch_filename "")
    set(clang_doxygen_qhp_namespace "")
    set(clang_doxygen_qhelpgenerator_path "")
    set(clang_doxygen_qhp_cust_filter_name "")
    set(clang_doxygen_qhp_cust_filter_attrs "")
  endif()

  llvm_configure_doxygen()

  set(abs_top_srcdir)
  set(abs_top_builddir)
  set(DOT)
  set(enable_searchengine)
  set(searchengine_url)
  set(enable_server_based_search)
  set(enable_external_search)
  set(extra_search_mappings)
  set(clang_doxygen_generate_qhp)
  set(clang_doxygen_qch_filename)
  set(clang_doxygen_qhp_namespace)
  set(clang_doxygen_qhelpgenerator_path)
  set(clang_doxygen_qhp_cust_filter_name)
  set(clang_doxygen_qhp_cust_filter_attrs)

  add_custom_target(doxygen-clang
    COMMAND ${DOXYGEN_EXECUTABLE} ${CMAKE_CURRENT_BINARY_DIR}/doxygen.cfg
    WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
    COMMENT "Generating clang doxygen documentation." VERBATIM)
  set_target_properties(doxygen-clang PROPERTIES FOLDER "Clang/Docs")

  if (LLVM_BUILD_DOCS)
    add_dependencies(doxygen doxygen-clang)
  endif()

  if (NOT LLVM_INSTALL_TOOLCHAIN_ONLY)
    install(DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/doxygen/html
      DESTINATION docs/html)
  endif()
endif()
endif()

function (gen_sphinx_file_from_td output_file td_option source docs_targets)
  if (NOT EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/${source}")
    message(FATAL_ERROR "Cannot find source file: ${source} in ${CMAKE_CURRENT_SOURCE_DIR}")
  endif()
  get_filename_component(TABLEGEN_INCLUDE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/${source}" DIRECTORY)
  list(APPEND LLVM_TABLEGEN_FLAGS "-I${TABLEGEN_INCLUDE_DIR}")
  clang_tablegen(${output_file} ${td_option} SOURCE ${source} TARGET "gen-${output_file}")
  add_dependencies("gen-${output_file}" copy-clang-rst-docs)
  foreach(target ${docs_targets})
    add_dependencies(${target} gen-${output_file})
  endforeach()
endfunction()

if (LLVM_ENABLE_SPHINX)
  include(AddSphinxTarget)
  if (SPHINX_FOUND AND (${SPHINX_OUTPUT_HTML} OR ${SPHINX_OUTPUT_MAN}))
    # Copy documentation sources to the build directory before generating
    # documentation.  Some of the files are generated, so they
    # only exist in the build directory.  Sphinx needs all files in
    # the same directory in order to generate the html, so we need to
    # copy all the non-generated source files from the source to the build
    # directory before we run sphinx.
    set(clang_generated_docs
      AttributeReference.md
      DiagnosticsReference.md
      AMDGPUBuiltinReference.rst
      ClangCommandLineReference.md
      analyzer/user-docs/Options.rst)
    add_sphinx_source_sync_target(copy-clang-rst-docs
      "${CMAKE_CURRENT_SOURCE_DIR}" "${CMAKE_CURRENT_BINARY_DIR}"
      PRESERVE_DOCS ${clang_generated_docs})
    add_custom_command(TARGET copy-clang-rst-docs POST_BUILD
      COMMAND "${CMAKE_COMMAND}" -E copy_if_different
      "${CMAKE_CURRENT_SOURCE_DIR}/../Maintainers.md"
      "${CMAKE_CURRENT_BINARY_DIR}"
    )

    add_custom_command(TARGET copy-clang-rst-docs POST_BUILD
      COMMAND "${Python3_EXECUTABLE}"
      ARGS "${CMAKE_CURRENT_BINARY_DIR}/CIR/_raw/PostProcessCIRDocs.py"
           "${CMAKE_CURRENT_SOURCE_DIR}" "${CMAKE_CURRENT_BINARY_DIR}"
      BYPRODUCTS ${CMAKE_CURRENT_BINARY_DIR}/CIR/CIRDialect.md
    )
    if (CLANG_ENABLE_CIR)
      add_dependencies(copy-clang-rst-docs clang-cir-doc)
    endif()

    set(docs_targets "")

    if (${SPHINX_OUTPUT_HTML})
      add_sphinx_target(html clang SOURCE_DIR "${CMAKE_CURRENT_BINARY_DIR}")

      add_custom_command(TARGET docs-clang-html POST_BUILD
        COMMAND "${CMAKE_COMMAND}" -E copy
        "${CMAKE_CURRENT_SOURCE_DIR}/LibASTMatchersReference.html"
        "${CMAKE_CURRENT_BINARY_DIR}/html/LibASTMatchersReference.html")

      list(APPEND docs_targets "docs-clang-html")
    endif()
    if (${SPHINX_OUTPUT_MAN})
      add_sphinx_target(man clang SOURCE_DIR "${CMAKE_CURRENT_BINARY_DIR}")
      list(APPEND docs_targets "docs-clang-man")
    endif()

    # Generated files
    gen_sphinx_file_from_td(AttributeReference.md -gen-attr-docs ../include/clang/Basic/Attr.td "${docs_targets}")
    gen_sphinx_file_from_td(DiagnosticsReference.md -gen-diag-docs ../include/clang/Basic/Diagnostic.td "${docs_targets}")
    gen_sphinx_file_from_td(AMDGPUBuiltinReference.rst -gen-builtin-docs ../include/clang/Basic/BuiltinsAMDGPU.td "${docs_targets}")
    gen_sphinx_file_from_td(ClangCommandLineReference.md -gen-opt-docs ../include/clang/Options/ClangOptionDocs.td "${docs_targets}")

    # Another generated file from a different source
    set(docs_tools_dir ${CMAKE_CURRENT_SOURCE_DIR}/tools)
    set(aopts_rst_rel_path analyzer/user-docs/Options.rst)
    set(aopts_rst "${CMAKE_CURRENT_BINARY_DIR}/${aopts_rst_rel_path}")
    set(analyzeroptions_def "${CMAKE_CURRENT_SOURCE_DIR}/../include/clang/StaticAnalyzer/Core/AnalyzerOptions.def")
    set(aopts_rst_in "${CMAKE_CURRENT_SOURCE_DIR}/${aopts_rst_rel_path}.in")
    add_custom_command(
      OUTPUT ${aopts_rst}
      COMMAND ${Python3_EXECUTABLE} generate_analyzer_options_docs.py
              --options-def "${analyzeroptions_def}"
              --template "${aopts_rst_in}"
              --out "${aopts_rst}"
      WORKING_DIRECTORY ${docs_tools_dir}
      VERBATIM
      COMMENT "Generating ${aopts_rst}"
      DEPENDS ${docs_tools_dir}/${generate_aopts_docs}
              ${aopts_rst_in}
              copy-clang-rst-docs
      )
    add_custom_target(generate-analyzer-options-rst DEPENDS ${aopts_rst})
    foreach(target ${docs_targets})
      add_dependencies(${target} generate-analyzer-options-rst)
    endforeach()

    # Technically this is redundant because generate-analyzer-options-rst
    # depends on the copy operation (because it wants to drop a generated file
    # into a subdirectory of the copied tree), but I'm leaving it here for the
    # sake of clarity.
    foreach(target ${docs_targets})
      add_dependencies(${target} copy-clang-rst-docs)
    endforeach()
  endif()
endif()

---

### Clang Docs CXXTypeAwareAllocators (`clang/docs/CXXTypeAwareAllocators.md`)

# C++ Type Aware Allocators


## Introduction

Clang includes an implementation of P2719 "Type-aware allocation and deallocation
functions".

This is a feature that extends the semantics of `new`, `new[]`, `delete` and
`delete[]` operators to expose the type being allocated to the operator. This
can be used to customize allocation of types without needing to modify the
type declaration, or via template definitions fully generic type aware
allocators.

P2719 introduces a type-identity tag as valid parameter type for all allocation
operators. This tag is a default initialized value of type `std::type_identity<T>`
where T is the type being allocated or deallocated. Unlike the other placement
arguments this tag is passed as the first parameter to the operator.

The most basic use case is as follows

```c++
#include <new>
#include <type_traits>

struct S {
 // ...
};

void *operator new(std::type_identity<S>, size_t, std::align_val_t);
void operator delete(std::type_identity<S>, void *, size_t, std::align_val_t);

void f() {
  S *s = new S; // calls ::operator new(std::type_identity<S>(), sizeof(S), alignof(S))
  delete s; // calls ::operator delete(std::type_identity<S>(), s, sizeof(S), alignof(S))
}
```

While this functionality alone is powerful and useful, the true power comes
by using templates. In addition to adding the type-identity tag, P2719 allows
the tag parameter to be a dependent specialization of `std::type_identity`,
updates the overload resolution rules to support full template deduction and
constraint semantics, and updates the definition of usual deallocation functions
to include `operator delete` definitions that are templatized on the
type-identity tag.

This allows arbitrarily constrained definitions of the operators that resolve
as would be expected for any other template function resolution, e.g (only
showing `operator new` for brevity)

```c++
template <typename T, unsigned Size> struct Array {
  T buffer[Size];
};

// Starting with a concrete type
void *operator new(std::type_identity<Array<int, 5>>, size_t, std::align_val_t);

// Only care about five element arrays
template <typename T>
void *operator new(std::type_identity<Array<T, 5>>, size_t, std::align_val_t);

// An array of N floats
template <unsigned N>
void *operator new(std::type_identity<Array<float, N>>, size_t, std::align_val_t);

// Any array
template <typename T, unsigned N>
void *operator new(std::type_identity<Array<T, N>>, size_t, std::align_val_t);

// A handy concept
template <typename T> concept Polymorphic = std::is_polymorphic_v<T>;

// Only applies is T is Polymorphic
template <Polymorphic T, unsigned N>
void *operator new(std::type_identity<Array<T, N>>, size_t, std::align_val_t);

// Any even length array
template <typename T, unsigned N>
void *operator new(std::type_identity<Array<T, N>>, size_t, std::align_val_t)
    requires(N%2 == 0);
```

Operator selection then proceeds according to the usual rules for choosing
the best/most constrained match.

Any declaration of a type aware operator new or operator delete must include a
matching complementary operator defined in the same scope.

## Notes

### Unconstrained Global Operators

Declaring an unconstrained type aware global operator `new` or `delete` (or
`[]` variants) creates numerous hazards, similar to, but different from, those
created by attempting to replace the non-type aware global operators. For that
reason unconstrained operators are strongly discouraged.

### Mismatching Constraints

When declaring global type aware operators you should ensure the constraints
applied to new and delete match exactly, and declare them together. This
limits the risk of having mismatching operators selected due to differing
constraints resulting in changes to prioritization when determining the most
viable candidate.

### Declarations Across Libraries

Declaring a typed allocator for a type in a separate TU or library creates
similar hazards as different libraries and TUs may see (or select) different
definitions.

Under this model something like this would be risky

```c++
template<typename T>
void *operator new(std::type_identity<std::vector<T>>, size_t, std::align_val_t);
```

However this hazard is not present simply due to the use of the a type from
another library:

```c++
template<typename T>
struct MyType {
  T thing;
};
template<typename T>
void *operator new(std::type_identity<MyType<std::vector<T>>>, size_t, std::align_val_t);
```

Here we see `std::vector` being used, but that is not the actual type being
allocated.

### Implicit and Placement Parameters

Type aware allocators are always passed both the implicit alignment and size
parameters in all cases. Explicit placement parameters are supported after the
mandatory implicit parameters.

## Publication

[Type-aware allocation and deallocation functions](https://wg21.link/P2719).
Louis Dionne, Oliver Hunt.

---

### Clang Docs ClangCheck (`clang/docs/ClangCheck.md`)

# ClangCheck

`ClangCheck` is a small wrapper around {doc}`LibTooling` which can be used to
do basic error checking and AST dumping.

```console
$ cat <<EOF > snippet.cc
> void f() {
>   int a = 0
> }
> EOF
$ ~/clang/build/bin/clang-check snippet.cc -ast-dump --
Processing: /Users/danieljasper/clang/llvm/tools/clang/docs/snippet.cc.
/Users/danieljasper/clang/llvm/tools/clang/docs/snippet.cc:2:12: error: expected ';' at end of
      declaration
  int a = 0
           ^
           ;
(TranslationUnitDecl 0x7ff3a3029ed0 <<invalid sloc>>
  (TypedefDecl 0x7ff3a302a410 <<invalid sloc>> __int128_t '__int128')
  (TypedefDecl 0x7ff3a302a470 <<invalid sloc>> __uint128_t 'unsigned __int128')
  (TypedefDecl 0x7ff3a302a830 <<invalid sloc>> __builtin_va_list '__va_list_tag [1]')
  (FunctionDecl 0x7ff3a302a8d0 </Users/danieljasper/clang/llvm/tools/clang/docs/snippet.cc:1:1, line:3:1> f 'void (void)'
    (CompoundStmt 0x7ff3a302aa10 <line:1:10, line:3:1>
      (DeclStmt 0x7ff3a302a9f8 <line:2:3, line:3:1>
        (VarDecl 0x7ff3a302a980 <line:2:3, col:11> a 'int'
          (IntegerLiteral 0x7ff3a302a9d8 <col:11> 'int' 0))))))
1 error generated.
Error while processing snippet.cc.
```

The '--' at the end is important as it prevents {program}`clang-check` from
searching for a compilation database. For more information on how to setup and
use {program}`clang-check` in a project, see {doc}`HowToSetupToolingForLLVM`.

---

### Clang Docs ClangFormat (`clang/docs/ClangFormat.md`)

# ClangFormat

`ClangFormat` describes a set of tools that are built on top of
{doc}`LibFormat`. It can support your workflow in a variety of ways including a
standalone tool and editor integrations.

## Standalone Tool

{program}`clang-format` is located in `clang/tools/clang-format` and can be used
to format C/C++/Java/JavaScript/JSON/Objective-C/Protobuf/C# code.

% START_FORMAT_HELP

```
/* Detailed source-code truncated for AI context efficiency. */
```

% END_FORMAT_HELP

When the desired code formatting style is different from the available options,
the style can be customized using the `-style="{key: value, ...}"` option or
by putting your style configuration in the `.clang-format` or `_clang-format`
file in your project's directory and using `clang-format -style=file`.

An easy way to create the `.clang-format` file is:

```console
clang-format -style=llvm -dump-config > .clang-format
```

Available style options are described in {doc}`ClangFormatStyleOptions`.

## .clang-format-ignore

You can create `.clang-format-ignore` files to make `clang-format` ignore
certain files. A `.clang-format-ignore` file consists of patterns of file path
names. It has the following format:

- A blank line is skipped.
- Leading and trailing spaces of a line are trimmed.
- A line starting with a hash (`#`) is a comment.
- A non-comment line is a single pattern.
- The slash (`/`) is used as the directory separator.
- A pattern is relative to the directory of the `.clang-format-ignore` file
  (or the root directory if the pattern starts with a slash). Patterns
  containing drive names (e.g. `C:`) are not supported.
- Patterns follow the rules specified in [POSIX 2.13.1, 2.13.2, and Rule 1 of
  2.13.3](https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_13).
- Bash globstar (`**`) is supported.
- A pattern is negated if it starts with a bang (`!`).

To match all files in a directory, use e.g. `foo/bar/*`. To match all files in
the directory of the `.clang-format-ignore` file, use `*`.
Multiple `.clang-format-ignore` files are supported similar to the
`.clang-format` files, with a lower directory level file voiding the higher
level ones.

## Vim Integration

There is an integration for {program}`vim` which lets you run the
{program}`clang-format` standalone tool on your current buffer, optionally
selecting regions to reformat. The integration has the form of a `python`-file
which can be found under `clang/tools/clang-format/clang-format.py`.

This can be integrated by adding the following to your `.vimrc`:

```vim
if has('python')
  map <C-K> :pyf <path-to-this-file>/clang-format.py<cr>
  imap <C-K> <c-o>:pyf <path-to-this-file>/clang-format.py<cr>
elseif has('python3')
  map <C-K> :py3f <path-to-this-file>/clang-format.py<cr>
  imap <C-K> <c-o>:py3f <path-to-this-file>/clang-format.py<cr>
endif
```

The first line enables {program}`clang-format` for NORMAL and VISUAL mode, the
second line adds support for INSERT mode. Change "C-K" to another binding if
you need {program}`clang-format` on a different key (C-K stands for Ctrl+k).

With this integration you can press the bound key and clang-format will
format the current line in NORMAL and INSERT mode or the selected region in
VISUAL mode. The line or region is extended to the next bigger syntactic
entity.

It operates on the current, potentially unsaved buffer and does not create
or save any files. To revert a formatting, just undo.

An alternative option is to format changes when saving a file and thus to
have a zero-effort integration into the coding workflow. To do this, add this to
your `.vimrc`:

```vim
function! Formatonsave()
  let l:formatdiff = 1
  pyf <path-to-this-file>/clang-format.py
endfunction
autocmd BufWritePre *.h,*.cc,*.cpp call Formatonsave()
```

## Emacs Integration

Similar to the integration for {program}`vim`, there is an integration for
{program}`emacs`. It can be found at `clang/tools/clang-format/clang-format.el`
and used by adding this to your `.emacs`:

```common-lisp
(load "<path-to-clang>/tools/clang-format/clang-format.el")
(global-set-key [C-M-tab] 'clang-format-region)
```

This binds the function `clang-format-region` to C-M-tab, which then formats the
current line or selected region.

## BBEdit Integration

{program}`clang-format` cannot be used as a text filter with BBEdit, but works
well via a script. The AppleScript to do this integration can be found at
`clang/tools/clang-format/clang-format-bbedit.applescript`; place a copy in
`~/Library/Application Support/BBEdit/Scripts`, and edit the path within it to
point to your local copy of {program}`clang-format`.

With this integration you can select the script from the Script menu and
{program}`clang-format` will format the selection. Note that you can rename the
menu item by renaming the script, and can assign the menu item a keyboard
shortcut in the BBEdit preferences, under Menus & Shortcuts.

## CLion Integration

{program}`clang-format` is integrated into
[CLion](https://www.jetbrains.com/clion/) as an alternative code formatter.
CLion turns it on automatically when there is a `.clang-format` file under the
project root. Code style rules are applied as you type, including indentation,
auto-completion, code generation, and refactorings.

{program}`clang-format` can also be enabled without a `.clang-format` file.
In this case, CLion prompts you to create one based on the current IDE settings
or the default LLVM style.

## Visual Studio Integration

Download the latest Visual Studio extension from the [alpha build
site](https://llvm.org/builds/). The default key-binding is Ctrl-R,Ctrl-F.

## Visual Studio Code Integration

Get the latest Visual Studio Code extension from the [Visual Studio
Marketplace](https://marketplace.visualstudio.com/items?itemName=xaver.clang-format).
The default key-binding is Alt-Shift-F.

## Git integration

The script `clang/tools/clang-format/git-clang-format` can be used to
format just the lines touched in git commits:

```
/* Detailed source-code truncated for AI context efficiency. */
```

## Script for patch reformatting

The python script `clang/tools/clang-format/clang-format-diff.py` parses the
output of a unified diff and reformats all contained lines with
{program}`clang-format`.

```
/* Detailed source-code truncated for AI context efficiency. */
```

To reformat all the lines in the latest Mercurial/{program}`hg` commit, do:

```console
hg diff -U0 --color=never | clang-format-diff.py -i -p1
```

The option `-U0` will create a diff without context lines (the script would format
those as well).

These commands use the file paths shown in the diff output
so they will only work from the root of the repository.

---

### Clang Docs ClangFormatStyleOptions (`clang/docs/ClangFormatStyleOptions.md`)

% !!!!NOTE!!!!
% This file is automatically generated, in part. Do not edit the style options
% in this file directly. Instead, modify them in include/clang/Format/Format.h
% and run the docs/tools/dump_format_style.py script to update this file.

```{raw} html
<style type="text/css">
  .versionbadge { background-color: #1c913d; height: 20px; display: inline-block; min-width: 120px; text-align: center; border-radius: 5px; color: #FFFFFF; font-family: "Verdana,Geneva,DejaVu Sans,sans-serif"; }
</style>
```

```{eval-rst}
.. role:: versionbadge
```

# Clang-Format Style Options

{doc}`ClangFormatStyleOptions` describes configurable formatting style options
supported by {doc}`LibFormat` and {doc}`ClangFormat`.

When using {program}`clang-format` command line utility or
`clang::format::reformat(...)` functions from code, one can either use one of
the predefined styles (LLVM, Google, Chromium, Mozilla, WebKit, Microsoft) or
create a custom style by configuring specific style options.

## Configuring Style with clang-format

{program}`clang-format` supports two ways to provide custom style options:
directly specify style configuration in the `-style=` command line option or
use `-style=file` and put style configuration in the `.clang-format` or
`_clang-format` file in the project directory.

When using `-style=file`, {program}`clang-format` for each input file will
try to find the `.clang-format` file located in the closest parent directory
of the input file. When the standard input is used, the search is started from
the current directory.

When using `-style=file:<format_file_path>`, {program}`clang-format` for
each input file will use the format file located at `<format_file_path>`.
The path may be absolute or relative to the working directory.

The `.clang-format` file uses YAML format:

```yaml
key1: value1
key2: value2
# A comment.
...
```

The configuration file can consist of several sections each having different
`Language:` parameter denoting the programming language this section of the
configuration is targeted at. See the description of the **Language** option
below for the list of supported languages. The first section may have no
language set, it will set the default style options for all languages.
Configuration sections for specific language will override options set in the
default section.

When {program}`clang-format` formats a file, it auto-detects the language using
the file name. When formatting standard input or a file that doesn't have the
extension corresponding to its language, `-assume-filename=` option can be
used to override the file name {program}`clang-format` uses to detect the
language.

An example of a configuration file for multiple languages:

```yaml
---
# We'll use defaults from the LLVM style, but with 4 columns indentation.
BasedOnStyle: LLVM
IndentWidth: 4
---
Language: Cpp
# Force pointers to the type for C++.
DerivePointerAlignment: false
PointerAlignment: Left
---
Language: JavaScript
# Use 100 columns for JS.
ColumnLimit: 100
---
Language: Proto
# Don't format .proto files.
DisableFormat: true
---
Language: CSharp
# Use 100 columns for C#.
ColumnLimit: 100
...
```

An easy way to get a valid `.clang-format` file containing all configuration
options of a certain predefined style is:

```console
clang-format -style=llvm -dump-config > .clang-format
```

When specifying configuration in the `-style=` option, the same configuration
is applied for all input files. The format of the configuration is:

```console
-style='{key1: value1, key2: value2, ...}'
```

## Disabling Formatting on a Piece of Code

Clang-format understands also special comments that switch formatting in a
delimited range. The code between a comment `// clang-format off` or
`/* clang-format off */` up to a comment `// clang-format on` or
`/* clang-format on */` will not be formatted. The comments themselves will be
formatted (aligned) normally. Also, a colon (`:`) and additional text may
follow `// clang-format off` or `// clang-format on` to explain why
clang-format is turned off or back on.

```c++
int formatted_code;
// clang-format off
    void    unformatted_code  ;
// clang-format on
void formatted_code_again;
```

In addition, the `OneLineFormatOffRegex` option gives you a concise way to
disable formatting for all of the lines that match the regular expression.

## Configuring Style in Code

When using `clang::format::reformat(...)` functions, the format is specified
by supplying the [clang::format::FormatStyle](https://clang.llvm.org/doxygen/structclang_1_1format_1_1FormatStyle.html)
structure.

## Configurable Format Style Options

This section lists the supported style options. Value type is specified for
each option. For enumeration types possible values are specified both as a C++
enumeration member (with a prefix, e.g. `LS_Auto`), and as a value usable in
the configuration (without a prefix: `Auto`).

(basedonstyle)=

**BasedOnStyle** (`String`) {ref}`¶ <BasedOnStyle>`

: The style used for all options not specifically set in the configuration.

  This option is supported only in the {program}`clang-format` configuration
  (both within `-style='{...}'` and the `.clang-format` file).

  Possible values:

  - `LLVM`
    A style complying with the [LLVM coding standards](https://llvm.org/docs/CodingStandards.html)
  - `Google`
    A style complying with [Google's C++ style guide](https://google.github.io/styleguide/cppguide.html)
  - `Chromium`
    A style complying with [Chromium's style guide](https://chromium.googlesource.com/chromium/src/+/refs/heads/main/styleguide/styleguide.md)
  - `Mozilla`
    A style complying with [Mozilla's style guide](https://firefox-source-docs.mozilla.org/code-quality/coding-style/index.html)
  - `WebKit`
    A style complying with [WebKit's style guide](https://www.webkit.org/coding/coding-style.html)
  - `Microsoft`
    A style complying with [Microsoft's style guide](https://docs.microsoft.com/en-us/visualstudio/ide/editorconfig-code-style-settings-reference)
  - `GNU`
    A style complying with the [GNU coding standards](https://www.gnu.org/prep/standards/standards.html)
  - `InheritParentConfig`
    Not a real style, but allows to use the `.clang-format` file from the
    parent directory (or its parent if there is none). If there is no parent
    file found it falls back to the `fallback` style, and applies the changes
    to that. With this option you can overwrite some parts of your main style
    for your subdirectories. This is also possible through the command line,
    e.g.:
    `--style={BasedOnStyle: InheritParentConfig, ColumnLimit: 20}`
  - `InheritParentConfig=<directory-path>`
    Same as the above except that the inheritance is redirected to
    `<directory-path>`. This is only supported in configuration files.

% START_FORMAT_STYLE_OPTIONS

(accessmodifieroffset)=

**AccessModifierOffset** (`Integer`) {versionbadge}`clang-format 3.3` {ref}`¶ <AccessModifierOffset>`

: The extra indent or outdent of access modifiers, e.g. `public:`.

(alignafteropenbracket)=

**AlignAfterOpenBracket** (`Boolean`) {versionbadge}`clang-format 3.8` {ref}`¶ <AlignAfterOpenBracket>`

: If `true`, horizontally aligns arguments after an open bracket.

  ```c++
  true:                         vs.   false
  someLongFunction(argument1,         someLongFunction(argument1,
                   argument2);            argument2);
  ```

  :::{note}
  As of clang-format 22 this option is a bool with the previous
  option of `Align` replaced with `true`, `DontAlign` replaced
  with `false`, and the options of `AlwaysBreak` and `BlockIndent`
  replaced with `true` and with setting of new style options using
  `BreakAfterOpenBracketBracedList`, `BreakAfterOpenBracketFunction`,
  `BreakAfterOpenBracketIf`, `BreakBeforeCloseBracketBracedList`,
  `BreakBeforeCloseBracketFunction`, and `BreakBeforeCloseBracketIf`.
  :::

  This applies to round brackets (parentheses), angle brackets and square
  brackets.

(alignarrayofstructures)=

**AlignArrayOfStructures** (`ArrayInitializerAlignmentStyle`) {versionbadge}`clang-format 13` {ref}`¶ <AlignArrayOfStructures>`

: If not `None`, when using initialization for an array of structs
  aligns the fields into columns.

  :::{note}
  As of clang-format 15 this option only applied to arrays with equal
  number of columns per row.
  :::

  Possible values:

  - `AIAS_Left` (in configuration: `Left`)
    Align array column and left justify the columns e.g.:

    ```c++
    struct test demo[] =
    {
        {56, 23,    "hello"},
        {-1, 93463, "world"},
        {7,  5,     "!!"   }
    };
    ```

  - `AIAS_Right` (in configuration: `Right`)
    Align array column and right justify the columns e.g.:

    ```c++
    struct test demo[] =
    {
        {56,    23, "hello"},
        {-1, 93463, "world"},
        { 7,     5,    "!!"}
    };
    ```

  - `AIAS_None` (in configuration: `None`)
    Don't align array initializer columns.



(alignconsecutiveassignments)=

**AlignConsecutiveAssignments** (`AlignConsecutiveStyle`) {versionbadge}`clang-format 3.8` {ref}`¶ <AlignConsecutiveAssignments>`

: Style of aligning consecutive assignments.

  `Consecutive` will result in formattings like:

  ```c++
  int a            = 1;
  int somelongname = 2;
  double c         = 3;
  ```

  Nested configuration flags:

  Alignment options.

  They can also be read as a whole for compatibility. The choices are:

  - `None`
  - `Consecutive`
  - `AcrossEmptyLines`
  - `AcrossComments`
  - `AcrossEmptyLinesAndComments`

  For example, to align across empty lines and not across comments, either
  of these work.

  ```c++
  AlignConsecutiveAssignments: AcrossEmptyLines

  AlignConsecutiveAssignments:
    Enabled: true
    AcrossEmptyLines: true
    AcrossComments: false
  ```

  - `bool Enabled` Whether aligning is enabled.

    ```c++
    #define SHORT_NAME       42
    #define LONGER_NAME      0x007f
    #define EVEN_LONGER_NAME (2)
    #define foo(x)           (x * x)
    #define bar(y, z)        (y + z)

    int a            = 1;
    int somelongname = 2;
    double c         = 3;

    int aaaa : 1;
    int b    : 12;
    int ccc  : 8;

    int         aaaa = 12;
    float       b = 23;
    std::string ccc;
    ```

  - `bool AcrossEmptyLines` Whether to align across empty lines.

    ```c++
    true:
    int a            = 1;
    int somelongname = 2;
    double c         = 3;

    int d            = 3;

    false:
    int a            = 1;
    int somelongname = 2;
    double c         = 3;

    int d = 3;
    ```

  - `bool AcrossComments` Whether to align across comments.

    ```c++
    true:
    int d    = 3;
    /* A comment. */
    double e = 4;

    false:
    int d = 3;
    /* A comment. */
    double e = 4;
    ```

  - `bool AlignCompound` Only for `AlignConsecutiveAssignments`.  Whether compound assignments
    like `+=` are aligned along with `=`.

    ```c++
    true:
    a   &= 2;
    bbb  = 2;

    false:
    a &= 2;
    bbb = 2;
    ```

  - `bool AlignFunctionDeclarations` Only for `AlignConsecutiveDeclarations`. Whether function declarations
    are aligned.

    ```c++
    true:
    unsigned int f1(void);
    void         f2(void);
    size_t       f3(void);

    false:
    unsigned int f1(void);
    void f2(void);
    size_t f3(void);
    ```

  - `bool AlignFunctionPointers` Only for `AlignConsecutiveDeclarations`. Whether function pointers are
    aligned.

    ```c++
    true:
    unsigned i;
    int     &r;
    int     *p;
    int      (*f)();

    false:
    unsigned i;
    int     &r;
    int     *p;
    int (*f)();
    ```

  - `bool EnumAssignments` Only for `AlignConsecutiveAssignments`.
    Whether enum assignments are aligned. If `Enabled` is `false`,
    setting this to `true` forces alignment for enum assignments only.
    If `Enabled` is `true`, enum assignments are always aligned.

  - `bool PadOperators` Only for `AlignConsecutiveAssignments`.  Whether short assignment
    operators are left-padded to the same length as long ones in order to
    put all assignment operators to the right of the left hand side.

    ```c++
    true:
    a   >>= 2;
    bbb   = 2;

    a     = 2;
    bbb >>= 2;

    false:
    a >>= 2;
    bbb = 2;

    a     = 2;
    bbb >>= 2;
    ```


(alignconsecutivebitfields)=

**AlignConsecutiveBitFields** (`AlignConsecutiveStyle`) {versionbadge}`clang-format 11` {ref}`¶ <AlignConsecutiveBitFields>`

: Style of aligning consecutive bit fields.

  `Consecutive` will align the bitfield separators of consecutive lines.
  This will result in formattings like:

  ```c++
  int aaaa : 1;
  int b    : 12;
  int ccc  : 8;
  ```

  Nested configuration flags:

  Alignment options.

  They can also be read as a whole for compatibility. The choices are:

  - `None`
  - `Consecutive`
  - `AcrossEmptyLines`
  - `AcrossComments`
  - `AcrossEmptyLinesAndComments`

  For example, to align across empty lines and not across comments, either
  of these work.

  ```c++
  AlignConsecutiveBitFields: AcrossEmptyLines

  AlignConsecutiveBitFields:
    Enabled: true
    AcrossEmptyLines: true
    AcrossComments: false
  ```

  - `bool Enabled` Whether aligning is enabled.

    ```c++
    #define SHORT_NAME       42
    #define LONGER_NAME      0x007f
    #define EVEN_LONGER_NAME (2)
    #define foo(x)           (x * x)
    #define bar(y, z)        (y + z)

    int a            = 1;
    int somelongname = 2;
    double c         = 3;

    int aaaa : 1;
    int b    : 12;
    int ccc  : 8;

    int         aaaa = 12;
    float       b = 23;
    std::string ccc;
    ```

  - `bool AcrossEmptyLines` Whether to align across empty lines.

    ```c++
    true:
    int a            = 1;
    int somelongname = 2;
    double c         = 3;

    int d            = 3;

    false:
    int a            = 1;
    int somelongname = 2;
    double c         = 3;

    int d = 3;
    ```

  - `bool AcrossComments` Whether to align across comments.

    ```c++
    true:
    int d    = 3;
    /* A comment. */
    double e = 4;

    false:
    int d = 3;
    /* A comment. */
    double e = 4;
    ```

  - `bool AlignCompound` Only for `AlignConsecutiveAssignments`.  Whether compound assignments
    like `+=` are aligned along with `=`.

    ```c++
    true:
    a   &= 2;
    bbb  = 2;

    false:
    a &= 2;
    bbb = 2;
    ```

  - `bool AlignFunctionDeclarations` Only for `AlignConsecutiveDeclarations`. Whether function declarations
    are aligned.

    ```c++
    true:
    unsigned int f1(void);
    void         f2(void);
    size_t       f3(void);

    false:
    unsigned int f1(void);
    void f2(void);
    size_t f3(void);
    ```

  - `bool AlignFunctionPointers` Only for `AlignConsecutiveDeclarations`. Whether function pointers are
    aligned.

    ```c++
    true:
    unsigned i;
    int     &r;
    int     *p;
    int      (*f)();

    false:
    unsigned i;
    int     &r;
    int     *p;
    int (*f)();
    ```

  - `bool EnumAssignments` Only for `AlignConsecutiveAssignments`.
    Whether enum assignments are aligned. If `Enabled` is `false`,
    setting this to `true` forces alignment for enum assignments only.
    If `Enabled` is `true`, enum assignments are always aligned.

  - `bool PadOperators` Only for `AlignConsecutiveAssignments`.  Whether short assignment
    operators are left-padded to the same length as long ones in order to
    put all assignment operators to the right of the left hand side.

    ```c++
    true:
    a   >>= 2;
    bbb   = 2;

    a     = 2;
    bbb >>= 2;

    false:
    a >>= 2;
    bbb = 2;

    a     = 2;
    bbb >>= 2;
    ```


(alignconsecutivedeclarations)=

**AlignConsecutiveDeclarations** (`AlignConsecutiveStyle`) {versionbadge}`clang-format 3.8` {ref}`¶ <AlignConsecutiveDeclarations>`

: Style of aligning consecutive declarations.

  `Consecutive` will align the declaration names of consecutive lines.
  This will result in formattings like:

  ```c++
  int         aaaa = 12;
  float       b = 23;
  std::string ccc;
  ```

  Nested configuration flags:

  Alignment options.

  They can also be read as a whole for compatibility. The choices are:

  - `None`
  - `Consecutive`
  - `AcrossEmptyLines`
  - `AcrossComments`
  - `AcrossEmptyLinesAndComments`

  For example, to align across empty lines and not across comments, either
  of these work.

  ```c++
  AlignConsecutiveDeclarations: AcrossEmptyLines

  AlignConsecutiveDeclarations:
    Enabled: true
    AcrossEmptyLines: true
    AcrossComments: false
  ```

  - `bool Enabled` Whether aligning is enabled.

    ```c++
    #define SHORT_NAME       42
    #define LONGER_NAME      0x007f
    #define EVEN_LONGER_NAME (2)
    #define foo(x)           (x * x)
    #define bar(y, z)        (y + z)

    int a            = 1;
    int somelongname = 2;
    double c         = 3;

    int aaaa : 1;
    int b    : 12;
    int ccc  : 8;

    int         aaaa = 12;
    float       b = 23;
    std::string ccc;
    ```

  - `bool AcrossEmptyLines` Whether to align across empty lines.

    ```c++
    true:
    int a            = 1;
    int somelongname = 2;
    double c         = 3;

    int d            = 3;

    false:
    int a            = 1;
    int somelongname = 2;
    double c         = 3;

    int d = 3;
    ```

  - `bool AcrossComments` Whether to align across comments.

    ```c++
    true:
    int d    = 3;
    /* A comment. */
    double e = 4;

    false:
    int d = 3;
    /* A comment. */
    double e = 4;
    ```

  - `bool AlignCompound` Only for `AlignConsecutiveAssignments`.  Whether compound assignments
    like `+=` are aligned along with `=`.

    ```c++
    true:
    a   &= 2;
    bbb  = 2;

    false:
    a &= 2;
    bbb = 2;
    ```

  - `bool AlignFunctionDeclarations` Only for `AlignConsecutiveDeclarations`. Whether function declarations
    are aligned.

    ```c++
    true:
    unsigned int f1(void);
    void         f2(void);
    size_t       f3(void);

    false:
    unsigned int f1(void);
    void f2(void);
    size_t f3(void);
    ```

  - `bool AlignFunctionPointers` Only for `AlignConsecutiveDeclarations`. Whether function pointers are
    aligned.

    ```c++
    true:
    unsigned i;
    int     &r;
    int     *p;
    int      (*f)();

    false:
    unsigned i;
    int     &r;
    int     *p;
    int (*f)();
    ```

  - `bool EnumAssignments` Only for `AlignConsecutiveAssignments`.
    Whether enum assignments are aligned. If `Enabled` is `false`,
    setting this to `true` forces alignment for enum assignments only.
    If `Enabled` is `true`, enum assignments are always aligned.

  - `bool PadOperators` Only for `AlignConsecutiveAssignments`.  Whether short assignment
    operators are left-padded to the same length as long ones in order to
    put all assignment operators to the right of the left hand side.

    ```c++
    true:
    a   >>= 2;
    bbb   = 2;

    a     = 2;
    bbb >>= 2;

    false:
    a >>= 2;
    bbb = 2;

    a     = 2;
    bbb >>= 2;
    ```


(alignconsecutivemacros)=

**AlignConsecutiveMacros** (`AlignConsecutiveStyle`) {versionbadge}`clang-format 9` {ref}`¶ <AlignConsecutiveMacros>`

: Style of aligning consecutive macro definitions.

  `Consecutive` will result in formattings like:

  ```c++
  #define SHORT_NAME       42
  #define LONGER_NAME      0x007f
  #define EVEN_LONGER_NAME (2)
  #define foo(x)           (x * x)
  #define bar(y, z)        (y + z)
  ```

  Nested configuration flags:

  Alignment options.

  They can also be read as a whole for compatibility. The choices are:

  - `None`
  - `Consecutive`
  - `AcrossEmptyLines`
  - `AcrossComments`
  - `AcrossEmptyLinesAndComments`

  For example, to align across empty lines and not across comments, either
  of these work.

  ```c++
  AlignConsecutiveMacros: AcrossEmptyLines

  AlignConsecutiveMacros:
    Enabled: true
    AcrossEmptyLines: true
    AcrossComments: false
  ```

  - `bool Enabled` Whether aligning is enabled.

    ```c++
    #define SHORT_NAME       42
    #define LONGER_NAME      0x007f
    #define EVEN_LONGER_NAME (2)
    #define foo(x)           (x * x)
    #define bar(y, z)        (y + z)

    int a            = 1;
    int somelongname = 2;
    double c         = 3;

    int aaaa : 1;
    int b    : 12;
    int ccc  : 8;

    int         aaaa = 12;
    float       b = 23;
    std::string ccc;
    ```

  - `bool AcrossEmptyLines` Whether to align across empty lines.

    ```c++
    true:
    int a            = 1;
    int somelongname = 2;
    double c         = 3;

    int d            = 3;

    false:
    int a            = 1;
    int somelongname = 2;
    double c         = 3;

    int d = 3;
    ```

  - `bool AcrossComments` Whether to align across comments.

    ```c++
    true:
    int d    = 3;
    /* A comment. */
    double e = 4;

    false:
    int d = 3;
    /* A comment. */
    double e = 4;
    ```

  - `bool AlignCompound` Only for `AlignConsecutiveAssignments`.  Whether compound assignments
    like `+=` are aligned along with `=`.

    ```c++
    true:
    a   &= 2;
    bbb  = 2;

    false:
    a &= 2;
    bbb = 2;
    ```

  - `bool AlignFunctionDeclarations` Only for `AlignConsecutiveDeclarations`. Whether function declarations
    are aligned.

    ```c++
    true:
    unsigned int f1(void);
    void         f2(void);
    size_t       f3(void);

    false:
    unsigned int f1(void);
    void f2(void);
    size_t f3(void);
    ```

  - `bool AlignFunctionPointers` Only for `AlignConsecutiveDeclarations`. Whether function pointers are
    aligned.

    ```c++
    true:
    unsigned i;
    int     &r;
    int     *p;
    int      (*f)();

    false:
    unsigned i;
    int     &r;
    int     *p;
    int (*f)();
    ```

  - `bool EnumAssignments` Only for `AlignConsecutiveAssignments`.
    Whether enum assignments are aligned. If `Enabled` is `false`,
    setting this to `true` forces alignment for enum assignments only.
    If `Enabled` is `true`, enum assignments are always aligned.

  - `bool PadOperators` Only for `AlignConsecutiveAssignments`.  Whether short assignment
    operators are left-padded to the same length as long ones in order to
    put all assignment operators to the right of the left hand side.

    ```c++
    true:
    a   >>= 2;
    bbb   = 2;

    a     = 2;
    bbb >>= 2;

    false:
    a >>= 2;
    bbb = 2;

    a     = 2;
    bbb >>= 2;
    ```


(alignconsecutiveshortcasestatements)=

**AlignConsecutiveShortCaseStatements** (`ShortCaseStatementsAlignmentStyle`) {versionbadge}`clang-format 17` {ref}`¶ <AlignConsecutiveShortCaseStatements>`

: Style of aligning consecutive short case labels.
  Only applies if `AllowShortCaseExpressionOnASingleLine` or
  `AllowShortCaseLabelsOnASingleLine` is `true`.

  ```yaml
  # Example of usage:
  AlignConsecutiveShortCaseStatements:
    Enabled: true
    AcrossEmptyLines: true
    AcrossComments: true
    AlignCaseColons: false
  ```

  Nested configuration flags:

  Alignment options.

  - `bool Enabled` Whether aligning is enabled.

    ```c++
    true:
    switch (level) {
    case log::info:    return "info:";
    case log::warning: return "warning:";
    default:           return "";
    }

    false:
    switch (level) {
    case log::info: return "info:";
    case log::warning: return "warning:";
    default: return "";
    }
    ```

  - `bool AcrossEmptyLines` Whether to align across empty lines.

    ```c++
    true:
    switch (level) {
    case log::info:    return "info:";
    case log::warning: return "warning:";

    default:           return "";
    }

    false:
    switch (level) {
    case log::info:    return "info:";
    case log::warning: return "warning:";

    default: return "";
    }
    ```

  - `bool AcrossComments` Whether to align across comments.

    ```c++
    true:
    switch (level) {
    case log::info:    return "info:";
    case log::warning: return "warning:";
    /* A comment. */
    default:           return "";
    }

    false:
    switch (level) {
    case log::info:    return "info:";
    case log::warning: return "warning:";
    /* A comment. */
    default: return "";
    }
    ```

  - `bool AlignCaseArrows` Whether to align the case arrows when aligning short case expressions.

    ```java
    true:
    i = switch (day) {
      case THURSDAY, SATURDAY -> 8;
      case WEDNESDAY          -> 9;
      default                 -> 0;
    };

    false:
    i = switch (day) {
      case THURSDAY, SATURDAY -> 8;
      case WEDNESDAY ->          9;
      default ->                 0;
    };
    ```

  - `bool AlignCaseColons` Whether aligned case labels are aligned on the colon, or on the tokens
    after the colon.

    ```c++
    true:
    switch (level) {
    case log::info   : return "info:";
    case log::warning: return "warning:";
    default          : return "";
    }

    false:
    switch (level) {
    case log::info:    return "info:";
    case log::warning: return "warning:";
    default:           return "";
    }
    ```


(alignconsecutivetablegenbreakingdagargcolons)=

**AlignConsecutiveTableGenBreakingDAGArgColons** (`AlignConsecutiveStyle`) {versionbadge}`clang-format 19` {ref}`¶ <AlignConsecutiveTableGenBreakingDAGArgColons>`

: Style of aligning consecutive TableGen DAGArg operator colons.
  If enabled, align the colon inside DAGArg which have line break inside.
  This works only when TableGenBreakInsideDAGArg is BreakElements or
  BreakAll and the DAGArg is not excepted by
  TableGenBreakingDAGArgOperators's effect.

  ```c++
  let dagarg = (ins
      a  :$src1,
      aa :$src2,
      aaa:$src3
  )
  ```

  Nested configuration flags:

  Alignment options.

  They can also be read as a whole for compatibility. The choices are:

  - `None`
  - `Consecutive`
  - `AcrossEmptyLines`
  - `AcrossComments`
  - `AcrossEmptyLinesAndComments`

  For example, to align across empty lines and not across comments, either
  of these work.

  ```c++
  AlignConsecutiveTableGenBreakingDAGArgColons: AcrossEmptyLines

  AlignConsecutiveTableGenBreakingDAGArgColons:
    Enabled: true
    AcrossEmptyLines: true
    AcrossComments: false
  ```

  - `bool Enabled` Whether aligning is enabled.

    ```c++
    #define SHORT_NAME       42
    #define LONGER_NAME      0x007f
    #define EVEN_LONGER_NAME (2)
    #define foo(x)           (x * x)
    #define bar(y, z)        (y + z)

    int a            = 1;
    int somelongname = 2;
    double c         = 3;

    int aaaa : 1;
    int b    : 12;
    int ccc  : 8;

    int         aaaa = 12;
    float       b = 23;
    std::string ccc;
    ```

  - `bool AcrossEmptyLines` Whether to align across empty lines.

    ```c++
    true:
    int a            = 1;
    int somelongname = 2;
    double c         = 3;

    int d            = 3;

    false:
    int a            = 1;
    int somelongname = 2;
    double c         = 3;

    int d = 3;
    ```

  - `bool AcrossComments` Whether to align across comments.

    ```c++
    true:
    int d    = 3;
    /* A comment. */
    double e = 4;

    false:
    int d = 3;
    /* A comment. */
    double e = 4;
    ```

  - `bool AlignCompound` Only for `AlignConsecutiveAssignments`.  Whether compound assignments
    like `+=` are aligned along with `=`.

    ```c++
    true:
    a   &= 2;
    bbb  = 2;

    false:
    a &= 2;
    bbb = 2;
    ```

  - `bool AlignFunctionDeclarations` Only for `AlignConsecutiveDeclarations`. Whether function declarations
    are aligned.

    ```c++
    true:
    unsigned int f1(void);
    void         f2(void);
    size_t       f3(void);

    false:
    unsigned int f1(void);
    void f2(void);
    size_t f3(void);
    ```

  - `bool AlignFunctionPointers` Only for `AlignConsecutiveDeclarations`. Whether function pointers are
    aligned.

    ```c++
    true:
    unsigned i;
    int     &r;
    int     *p;
    int      (*f)();

    false:
    unsigned i;
    int     &r;
    int     *p;
    int (*f)();
    ```

  - `bool EnumAssignments` Only for `AlignConsecutiveAssignments`.
    Whether enum assignments are aligned. If `Enabled` is `false`,
    setting this to `true` forces alignment for enum assignments only.
    If `Enabled` is `true`, enum assignments are always aligned.

  - `bool PadOperators` Only for `AlignConsecutiveAssignments`.  Whether short assignment
    operators are left-padded to the same length as long ones in order to
    put all assignment operators to the right of the left hand side.

    ```c++
    true:
    a   >>= 2;
    bbb   = 2;

    a     = 2;
    bbb >>= 2;

    false:
    a >>= 2;
    bbb = 2;

    a     = 2;
    bbb >>= 2;
    ```


(alignconsecutivetablegencondoperatorcolons)=

**AlignConsecutiveTableGenCondOperatorColons** (`AlignConsecutiveStyle`) {versionbadge}`clang-format 19` {ref}`¶ <AlignConsecutiveTableGenCondOperatorColons>`

: Style of aligning consecutive TableGen cond operator colons.
  Align the colons of cases inside !cond operators.

  ```c++
  !cond(!eq(size, 1) : 1,
        !eq(size, 16): 1,
        true         : 0)
  ```

  Nested configuration flags:

  Alignment options.

  They can also be read as a whole for compatibility. The choices are:

  - `None`
  - `Consecutive`
  - `AcrossEmptyLines`
  - `AcrossComments`
  - `AcrossEmptyLinesAndComments`

  For example, to align across empty lines and not across comments, either
  of these work.

  ```c++
  AlignConsecutiveTableGenCondOperatorColons: AcrossEmptyLines

  AlignConsecutiveTableGenCondOperatorColons:
    Enabled: true
    AcrossEmptyLines: true
    AcrossComments: false
  ```

  - `bool Enabled` Whether aligning is enabled.

    ```c++
    #define SHORT_NAME       42
    #define LONGER_NAME      0x007f
    #define EVEN_LONGER_NAME (2)
    #define foo(x)           (x * x)
    #define bar(y, z)        (y + z)

    int a            = 1;
    int somelongname = 2;
    double c         = 3;

    int aaaa : 1;
    int b    : 12;
    int ccc  : 8;

    int         aaaa = 12;
    float       b = 23;
    std::string ccc;
    ```

  - `bool AcrossEmptyLines` Whether to align across empty lines.

    ```c++
    true:
    int a            = 1;
    int somelongname = 2;
    double c         = 3;

    int d            = 3;

    false:
    int a            = 1;
    int somelongname = 2;
    double c         = 3;

    int d = 3;
    ```

  - `bool AcrossComments` Whether to align across comments.

    ```c++
    true:
    int d    = 3;
    /* A comment. */
    double e = 4;

    false:
    int d = 3;
    /* A comment. */
    double e = 4;
    ```

  - `bool AlignCompound` Only for `AlignConsecutiveAssignments`.  Whether compound assignments
    like `+=` are aligned along with `=`.

    ```c++
    true:
    a   &= 2;
    bbb  = 2;

    false:
    a &= 2;
    bbb = 2;
    ```

  - `bool AlignFunctionDeclarations` Only for `AlignConsecutiveDeclarations`. Whether function declarations
    are aligned.

    ```c++
    true:
    unsigned int f1(void);
    void         f2(void);
    size_t       f3(void);

    false:
    unsigned int f1(void);
    void f2(void);
    size_t f3(void);
    ```

  - `bool AlignFunctionPointers` Only for `AlignConsecutiveDeclarations`. Whether function pointers are
    aligned.

    ```c++
    true:
    unsigned i;
    int     &r;
    int     *p;
    int      (*f)();

    false:
    unsigned i;
    int     &r;
    int     *p;
    int (*f)();
    ```

  - `bool EnumAssignments` Only for `AlignConsecutiveAssignments`.
    Whether enum assignments are aligned. If `Enabled` is `false`,
    setting this to `true` forces alignment for enum assignments only.
    If `Enabled` is `true`, enum assignments are always aligned.

  - `bool PadOperators` Only for `AlignConsecutiveAssignments`.  Whether short assignment
    operators are left-padded to the same length as long ones in order to
    put all assignment operators to the right of the left hand side.

    ```c++
    true:
    a   >>= 2;
    bbb   = 2;

    a     = 2;
    bbb >>= 2;

    false:
    a >>= 2;
    bbb = 2;

    a     = 2;
    bbb >>= 2;
    ```


(alignconsecutivetablegendefinitioncolons)=

**AlignConsecutiveTableGenDefinitionColons** (`AlignConsecutiveStyle`) {versionbadge}`clang-format 19` {ref}`¶ <AlignConsecutiveTableGenDefinitionColons>`

: Style of aligning consecutive TableGen definition colons.
  This aligns the inheritance colons of consecutive definitions.

  ```c++
  def Def       : Parent {}
  def DefDef    : Parent {}
  def DefDefDef : Parent {}
  ```

  Nested configuration flags:

  Alignment options.

  They can also be read as a whole for compatibility. The choices are:

  - `None`
  - `Consecutive`
  - `AcrossEmptyLines`
  - `AcrossComments`
  - `AcrossEmptyLinesAndComments`

  For example, to align across empty lines and not across comments, either
  of these work.

  ```c++
  AlignConsecutiveTableGenDefinitionColons: AcrossEmptyLines

  AlignConsecutiveTableGenDefinitionColons:
    Enabled: true
    AcrossEmptyLines: true
    AcrossComments: false
  ```

  - `bool Enabled` Whether aligning is enabled.

    ```c++
    #define SHORT_NAME       42
    #define LONGER_NAME      0x007f
    #define EVEN_LONGER_NAME (2)
    #define foo(x)           (x * x)
    #define bar(y, z)        (y + z)

    int a            = 1;
    int somelongname = 2;
    double c         = 3;

    int aaaa : 1;
    int b    : 12;
    int ccc  : 8;

    int         aaaa = 12;
    float       b = 23;
    std::string ccc;
    ```

  - `bool AcrossEmptyLines` Whether to align across empty lines.

    ```c++
    true:
    int a            = 1;
    int somelongname = 2;
    double c         = 3;

    int d            = 3;

    false:
    int a            = 1;
    int somelongname = 2;
    double c         = 3;

    int d = 3;
    ```

  - `bool AcrossComments` Whether to align across comments.

    ```c++
    true:
    int d    = 3;
    /* A comment. */
    double e = 4;

    false:
    int d = 3;
    /* A comment. */
    double e = 4;
    ```

  - `bool AlignCompound` Only for `AlignConsecutiveAssignments`.  Whether compound assignments
    like `+=` are aligned along with `=`.

    ```c++
    true:
    a   &= 2;
    bbb  = 2;

    false:
    a &= 2;
    bbb = 2;
    ```

  - `bool AlignFunctionDeclarations` Only for `AlignConsecutiveDeclarations`. Whether function declarations
    are aligned.

    ```c++
    true:
    unsigned int f1(void);
    void         f2(void);
    size_t       f3(void);

    false:
    unsigned int f1(void);
    void f2(void);
    size_t f3(void);
    ```

  - `bool AlignFunctionPointers` Only for `AlignConsecutiveDeclarations`. Whether function pointers are
    aligned.

    ```c++
    true:
    unsigned i;
    int     &r;
    int     *p;
    int      (*f)();

    false:
    unsigned i;
    int     &r;
    int     *p;
    int (*f)();
    ```

  - `bool EnumAssignments` Only for `AlignConsecutiveAssignments`.
    Whether enum assignments are aligned. If `Enabled` is `false`,
    setting this to `true` forces alignment for enum assignments only.
    If `Enabled` is `true`, enum assignments are always aligned.

  - `bool PadOperators` Only for `AlignConsecutiveAssignments`.  Whether short assignment
    operators are left-padded to the same length as long ones in order to
    put all assignment operators to the right of the left hand side.

    ```c++
    true:
    a   >>= 2;
    bbb   = 2;

    a     = 2;
    bbb >>= 2;

    false:
    a >>= 2;
    bbb = 2;

    a     = 2;
    bbb >>= 2;
    ```


(alignescapednewlines)=

**AlignEscapedNewlines** (`EscapedNewlineAlignmentStyle`) {versionbadge}`clang-format 5` {ref}`¶ <AlignEscapedNewlines>`

: Options for aligning backslashes in escaped newlines.

  Possible values:

  - `ENAS_DontAlign` (in configuration: `DontAlign`)
    Don't align escaped newlines.

    ```c++
    #define A \
      int aaaa; \
      int b; \
      int dddddddddd;
    ```

  - `ENAS_Left` (in configuration: `Left`)
    Align escaped newlines as far left as possible.

    ```c++
    #define A   \
      int aaaa; \
      int b;    \
      int dddddddddd;
    ```

  - `ENAS_LeftWithLastLine` (in configuration: `LeftWithLastLine`)
    Align escaped newlines as far left as possible, using the last line of
    the preprocessor directive as the reference if it's the longest.

    ```c++
    #define A         \
      int aaaa;       \
      int b;          \
      int dddddddddd;
    ```

  - `ENAS_Right` (in configuration: `Right`)
    Align escaped newlines in the right-most column.

    ```c++
    #define A                                                            \
      int aaaa;                                                          \
      int b;                                                             \
      int dddddddddd;
    ```



(alignoperands)=

**AlignOperands** (`OperandAlignmentStyle`) {versionbadge}`clang-format 3.5` {ref}`¶ <AlignOperands>`

: If `true`, horizontally align operands of binary and ternary
  expressions.

  Possible values:

  - `OAS_DontAlign` (in configuration: `DontAlign`)
    Do not align operands of binary and ternary expressions.
    The wrapped lines are indented `ContinuationIndentWidth` spaces from
    the start of the line.

  - `OAS_Align` (in configuration: `Align`)
    Horizontally align operands of binary and ternary expressions.

    Specifically, this aligns operands of a single expression that needs
    to be split over multiple lines, e.g.:

    ```c++
    int aaa = bbbbbbbbbbbbbbb +
              ccccccccccccccc;
    ```

    When `BreakBeforeBinaryOperators` is set, the wrapped operator is
    aligned with the operand on the first line.

    ```c++
    int aaa = bbbbbbbbbbbbbbb
              + ccccccccccccccc;
    ```

  - `OAS_AlignAfterOperator` (in configuration: `AlignAfterOperator`)
    Horizontally align operands of binary and ternary expressions.

    This is similar to `OAS_Align`, except when
    `BreakBeforeBinaryOperators` is set, the operator is un-indented so
    that the wrapped operand is aligned with the operand on the first line.

    ```c++
    int aaa = bbbbbbbbbbbbbbb
            + ccccccccccccccc;
    ```



(aligntrailingcomments)=

**AlignTrailingComments** (`TrailingCommentsAlignmentStyle`) {versionbadge}`clang-format 3.7` {ref}`¶ <AlignTrailingComments>`

: Control of trailing comments.

  The alignment stops at closing braces after a line break, and only
  followed by other closing braces, a (`do-`) `while`, a lambda call, or
  a semicolon.

  :::{note}
  As of clang-format 16 this option is not a bool but can be set
  to the options. Conventional bool options still can be parsed as before.
  :::

  ```yaml
  # Example of usage:
  AlignTrailingComments:
    Kind: Always
    OverEmptyLines: 2
  ```

  Nested configuration flags:

  Alignment options

  - `TrailingCommentsAlignmentKinds Kind`
    Specifies the way to align trailing comments.

    Possible values:

    - `TCAS_Leave` (in configuration: `Leave`)
      Leave trailing comments as they are.

      ```c++
      int a;    // comment
      int ab;       // comment

      int abc;  // comment
      int abcd;     // comment
      ```

    - `TCAS_Always` (in configuration: `Always`)
      Align trailing comments.

      ```c++
      int a;  // comment
      int ab; // comment

      int abc;  // comment
      int abcd; // comment
      ```

    - `TCAS_Never` (in configuration: `Never`)
      Don't align trailing comments but other formatter applies.

      ```c++
      int a; // comment
      int ab; // comment

      int abc; // comment
      int abcd; // comment
      ```


  - `unsigned OverEmptyLines` How many empty lines to apply alignment.
    When both `MaxEmptyLinesToKeep` and `OverEmptyLines` are set to 2,
    it formats like below.

    ```c++
    int a;      // all these

    int ab;     // comments are


    int abcdef; // aligned
    ```

    When `MaxEmptyLinesToKeep` is set to 2 and `OverEmptyLines` is set
    to 1, it formats like below.

    ```c++
    int a;  // these are

    int ab; // aligned


    int abcdef; // but this isn't
    ```

  - `bool AlignPPAndNotPP` If comments following preprocessor directive should be aligned with
    comments that don't.

    ```c++
    true:                               false:
    #define A  // Comment   vs.         #define A  // Comment
    #define AB // Aligned               #define AB // Aligned
    int i;     // Aligned               int i; // Not aligned
    ```


(allowallargumentsonnextline)=

**AllowAllArgumentsOnNextLine** (`Boolean`) {versionbadge}`clang-format 9` {ref}`¶ <AllowAllArgumentsOnNextLine>`

: If a function call or braced initializer list doesn't fit on a line, allow
  putting all arguments onto the next line, even if `BinPackArguments` is
  `false`.

  ```c++
  true:
  callFunction(
      a, b, c, d);

  false:
  callFunction(a,
               b,
               c,
               d);
  ```

(allowallconstructorinitializersonnextline)=

**AllowAllConstructorInitializersOnNextLine** (`Boolean`) {versionbadge}`clang-format 9` {ref}`¶ <AllowAllConstructorInitializersOnNextLine>`

: This option is **deprecated**. See `NextLine` of
  `PackConstructorInitializers`.

(allowallparametersofdeclarationonnextline)=

**AllowAllParametersOfDeclarationOnNextLine** (`Boolean`) {versionbadge}`clang-format 3.3` {ref}`¶ <AllowAllParametersOfDeclarationOnNextLine>`

: If the function declaration doesn't fit on a line,
  allow putting all parameters of a function declaration onto
  the next line even if `BinPackParameters` is `OnePerLine`.

  ```c++
  true:
  void myFunction(
      int a, int b, int c, int d, int e);

  false:
  void myFunction(int a,
                  int b,
                  int c,
                  int d,
                  int e);
  ```

(allowbreakbeforenoexceptspecifier)=

**AllowBreakBeforeNoexceptSpecifier** (`BreakBeforeNoexceptSpecifierStyle`) {versionbadge}`clang-format 18` {ref}`¶ <AllowBreakBeforeNoexceptSpecifier>`

: Controls if there could be a line break before a `noexcept` specifier.

  Possible values:

  - `BBNSS_Never` (in configuration: `Never`)
    No line break allowed.

    ```c++
    void foo(int arg1,
             double arg2) noexcept;

    void bar(int arg1, double arg2) noexcept(
        noexcept(baz(arg1)) &&
        noexcept(baz(arg2)));
    ```

  - `BBNSS_OnlyWithParen` (in configuration: `OnlyWithParen`)
    For a simple `noexcept` there is no line break allowed, but when we
    have a condition it is.

    ```c++
    void foo(int arg1,
             double arg2) noexcept;

    void bar(int arg1, double arg2)
        noexcept(noexcept(baz(arg1)) &&
                 noexcept(baz(arg2)));
    ```

  - `BBNSS_Always` (in configuration: `Always`)
    Line breaks are allowed. But note that because of the associated
    penalties `clang-format` often prefers not to break before the
    `noexcept`.

    ```c++
    void foo(int arg1,
             double arg2) noexcept;

    void bar(int arg1, double arg2)
        noexcept(noexcept(baz(arg1)) &&
                 noexcept(baz(arg2)));
    ```



(allowbreakbeforeqtproperty)=

**AllowBreakBeforeQtProperty** (`Boolean`) {versionbadge}`clang-format 22` {ref}`¶ <AllowBreakBeforeQtProperty>`

: Allow breaking before `Q_Property` keywords `READ`, `WRITE`, etc. as
  if they were preceded by a comma (`,`). This allows them to be formatted
  according to `BinPackParameters`.

(allowshortblocksonasingleline)=

**AllowShortBlocksOnASingleLine** (`ShortBlockStyle`) {versionbadge}`clang-format 3.5` {ref}`¶ <AllowShortBlocksOnASingleLine>`

: Dependent on the value, `while (true) { continue; }` can be put on a
  single line.

  Possible values:

  - `SBS_Never` (in configuration: `Never`)
    Never merge blocks into a single line.

    ```c++
    while (true) {
    }
    while (true) {
      continue;
    }
    ```

  - `SBS_Empty` (in configuration: `Empty`)
    Only merge empty blocks.

    ```c++
    while (true) {}
    while (true) {
      continue;
    }
    ```

  - `SBS_Always` (in configuration: `Always`)
    Always merge short blocks into a single line.

    ```c++
    while (true) {}
    while (true) { continue; }
    ```



(allowshortcaseexpressiononasingleline)=

**AllowShortCaseExpressionOnASingleLine** (`Boolean`) {versionbadge}`clang-format 19` {ref}`¶ <AllowShortCaseExpressionOnASingleLine>`

: Whether to merge a short switch labeled rule into a single line.

  ```java
  true:                               false:
  switch (a) {           vs.          switch (a) {
  case 1 -> 1;                        case 1 ->
  default -> 0;                         1;
  };                                  default ->
                                        0;
                                      };
  ```

(allowshortcaselabelsonasingleline)=

**AllowShortCaseLabelsOnASingleLine** (`Boolean`) {versionbadge}`clang-format 3.6` {ref}`¶ <AllowShortCaseLabelsOnASingleLine>`

: If `true`, short case labels will be contracted to a single line.

  ```c++
  true:                                   false:
  switch (a) {                    vs.     switch (a) {
  case 1: x = 1; break;                   case 1:
  case 2: return;                           x = 1;
  }                                         break;
                                          case 2:
                                            return;
                                          }
  ```

(allowshortcompoundrequirementonasingleline)=

**AllowShortCompoundRequirementOnASingleLine** (`Boolean`) {versionbadge}`clang-format 18` {ref}`¶ <AllowShortCompoundRequirementOnASingleLine>`

: Allow short compound requirement on a single line.

  ```c++
  true:
  template <typename T>
  concept c = requires(T x) {
    { x + 1 } -> std::same_as<int>;
  };

  false:
  template <typename T>
  concept c = requires(T x) {
    {
      x + 1
    } -> std::same_as<int>;
  };
  ```

(allowshortenumsonasingleline)=

**AllowShortEnumsOnASingleLine** (`Boolean`) {versionbadge}`clang-format 11` {ref}`¶ <AllowShortEnumsOnASingleLine>`

: Allow short enums on a single line.

  ```c++
  true:
  enum { A, B } myEnum;

  false:
  enum {
    A,
    B
  } myEnum;
  ```

(allowshortfunctionsonasingleline)=

**AllowShortFunctionsOnASingleLine** (`ShortFunctionStyle`) {versionbadge}`clang-format 3.5` {ref}`¶ <AllowShortFunctionsOnASingleLine>`

: Dependent on the value, `int f() { return 0; }` can be put on a
  single line.

  Nested configuration flags:

  Different styles for merging short functions containing at most one
  statement.

  They can be read as a whole for compatibility. The choices are:

  - `None`
    Never merge functions into a single line.

  - `InlineOnly`
    Only merge functions defined inside a class. Same as `inline`,
    except it does not imply `empty`: i.e. top level empty functions
    are not merged either. See `Inline` of `ShortFunctionStyle`.

    ```c++
    class Foo {
      void f() { foo(); }
    };
    void f() {
      foo();
    }
    void f() {
    }
    ```

  - `Empty`
    Only merge empty functions. See `Empty` of `ShortFunctionStyle`.

    ```c++
    void f() {}
    void f2() {
      bar2();
    }
    ```

  - `Inline`
    Only merge functions defined inside a class. Implies `empty`. See
    `Inline` and `Empty` of `ShortFunctionStyle`.

    ```c++
    class Foo {
      void f() { foo(); }
    };
    void f() {
      foo();
    }
    void f() {}
    ```

  - `All`
    Merge all functions fitting on a single line.

    ```c++
    class Foo {
      void f() { foo(); }
    };
    void f() { bar(); }
    ```

  Also can be specified as a nested configuration flag:

  ```yaml
  # Example of usage:
  AllowShortFunctionsOnASingleLine: InlineOnly

  # or more granular control:
  AllowShortFunctionsOnASingleLine:
    Empty: false
    Inline: true
    Other: false
  ```

  - `bool Empty` Merge top-level empty functions.

    ```c++
    void f() {}
    void f2() {
      bar2();
    }
    void f3() { /* comment */ }
    ```

  - `bool Inline` Merge functions defined inside a class.

    ```c++
    class Foo {
      void f() { foo(); }
      void g() {}
    };
    void f() {
      foo();
    }
    void f() {
    }
    ```

  - `bool Other` Merge all functions fitting on a single line. Please note that this
    control does not include Empty

    ```c++
    class Foo {
      void f() { foo(); }
    };
    void f() { bar(); }
    ```


(allowshortifstatementsonasingleline)=

**AllowShortIfStatementsOnASingleLine** (`ShortIfStyle`) {versionbadge}`clang-format 3.3` {ref}`¶ <AllowShortIfStatementsOnASingleLine>`

: Dependent on the value, `if (a) return;` can be put on a single line.

  Possible values:

  - `SIS_Never` (in configuration: `Never`)
    Never put short ifs on the same line.

    ```c++
    if (a)
      return;

    if (b)
      return;
    else
      return;

    if (c)
      return;
    else {
      return;
    }
    ```

  - `SIS_WithoutElse` (in configuration: `WithoutElse`)
    Put short ifs on the same line only if there is no else statement.

    ```c++
    if (a) return;

    if (b)
      return;
    else
      return;

    if (c)
      return;
    else {
      return;
    }
    ```

  - `SIS_OnlyFirstIf` (in configuration: `OnlyFirstIf`)
    Put short ifs, but not else ifs nor else statements, on the same line.

    ```c++
    if (a) return;

    if (b) return;
    else if (b)
      return;
    else
      return;

    if (c) return;
    else {
      return;
    }
    ```

  - `SIS_AllIfsAndElse` (in configuration: `AllIfsAndElse`)
    Always put short ifs, else ifs and else statements on the same
    line.

    ```c++
    if (a) return;

    if (b) return;
    else return;

    if (c) return;
    else {
      return;
    }
    ```



(allowshortlambdasonasingleline)=

**AllowShortLambdasOnASingleLine** (`ShortLambdaStyle`) {versionbadge}`clang-format 9` {ref}`¶ <AllowShortLambdasOnASingleLine>`

: Dependent on the value, `auto lambda []() { return 0; }` can be put on a
  single line.

  Possible values:

  - `SLS_None` (in configuration: `None`)
    Never merge lambdas into a single line.

  - `SLS_Empty` (in configuration: `Empty`)
    Only merge empty lambdas.

    ```c++
    auto lambda = [](int a) {};
    auto lambda2 = [](int a) {
        return a;
    };
    ```

  - `SLS_Inline` (in configuration: `Inline`)
    Merge lambda into a single line if the lambda is argument of a function.

    ```c++
    auto lambda = [](int x, int y) {
        return x < y;
    };
    sort(a.begin(), a.end(), [](int x, int y) { return x < y; });
    ```

  - `SLS_All` (in configuration: `All`)
    Merge all lambdas fitting on a single line.

    ```c++
    auto lambda = [](int a) {};
    auto lambda2 = [](int a) { return a; };
    ```



(allowshortloopsonasingleline)=

**AllowShortLoopsOnASingleLine** (`Boolean`) {versionbadge}`clang-format 3.7` {ref}`¶ <AllowShortLoopsOnASingleLine>`

: If `true`, `while (true) continue;` can be put on a single
  line.

(allowshortnamespacesonasingleline)=

**AllowShortNamespacesOnASingleLine** (`Boolean`) {versionbadge}`clang-format 20` {ref}`¶ <AllowShortNamespacesOnASingleLine>`

: If `true`, `namespace a { class b; }` can be put on a single line.

(allowshortrecordonasingleline)=

**AllowShortRecordOnASingleLine** (`ShortRecordStyle`) {versionbadge}`clang-format 23` {ref}`¶ <AllowShortRecordOnASingleLine>`

: Dependent on the value, `struct bar { int i; };` can be put on a single
  line.

  Possible values:

  - `SRS_Never` (in configuration: `Never`)
    Never merge records into a single line.

  - `SRS_EmptyAndAttached` (in configuration: `EmptyAndAttached`)
    Only merge empty records if the opening brace was not wrapped,
    i.e. the corresponding `BraceWrapping.After...` option was not set.

  - `SRS_Empty` (in configuration: `Empty`)
    Only merge empty records.

    ```c++
    struct foo {};
    struct bar
    {
      int i;
    };
    ```

  - `SRS_Always` (in configuration: `Always`)
    Merge all records that fit on a single line.

    ```c++
    struct foo {};
    struct bar { int i; };
    ```



(alwaysbreakafterdefinitionreturntype)=

**AlwaysBreakAfterDefinitionReturnType** (`DefinitionReturnTypeBreakingStyle`) {versionbadge}`clang-format 3.7` {ref}`¶ <AlwaysBreakAfterDefinitionReturnType>`

: The function definition return type breaking style to use.  This
  option is **deprecated** and is retained for backwards compatibility.

  Possible values:

  - `DRTBS_None` (in configuration: `None`)
    Break after return type automatically.
    `PenaltyReturnTypeOnItsOwnLine` is taken into account.

  - `DRTBS_All` (in configuration: `All`)
    Always break after the return type.

  - `DRTBS_TopLevel` (in configuration: `TopLevel`)
    Always break after the return types of top-level functions.



(alwaysbreakafterreturntype)=

**AlwaysBreakAfterReturnType** (`deprecated`) {versionbadge}`clang-format 3.8` {ref}`¶ <AlwaysBreakAfterReturnType>`

: This option is renamed to `BreakAfterReturnType`.

(alwaysbreakbeforemultilinestrings)=

**AlwaysBreakBeforeMultilineStrings** (`Boolean`) {versionbadge}`clang-format 3.4` {ref}`¶ <AlwaysBreakBeforeMultilineStrings>`

: If `true`, always break before multiline string literals.

  This flag is mean to make cases where there are multiple multiline strings
  in a file look more consistent. Thus, it will only take effect if wrapping
  the string at that point leads to it being indented
  `ContinuationIndentWidth` spaces from the start of the line.

  ```c++
  true:                                  false:
  aaaa =                         vs.     aaaa = "bbbb"
      "bbbb"                                    "cccc";
      "cccc";
  ```

(alwaysbreaktemplatedeclarations)=

**AlwaysBreakTemplateDeclarations** (`deprecated`) {versionbadge}`clang-format 3.4` {ref}`¶ <AlwaysBreakTemplateDeclarations>`

: This option is renamed to `BreakTemplateDeclarations`.

(attributemacros)=

**AttributeMacros** (`List of Strings`) {versionbadge}`clang-format 12` {ref}`¶ <AttributeMacros>`

: A vector of strings that should be interpreted as attributes/qualifiers
  instead of identifiers. This can be useful for language extensions or
  static analyzer annotations.

  For example:

  ```c++
  x = (char *__capability)&y;
  int function(void) __unused;
  void only_writes_to_buffer(char *__output buffer);
  ```

  In the .clang-format configuration file, this can be configured like:

  ```yaml
  AttributeMacros: [__capability, __output, __unused]
  ```

(binpackarguments)=

**BinPackArguments** (`Boolean`) {versionbadge}`clang-format 3.7` {ref}`¶ <BinPackArguments>`

: This option is **deprecated**. See `BinPack` of `PackArguments`.

(binpacklongbracedlist)=

**BinPackLongBracedList** (`Boolean`) {versionbadge}`clang-format 21` {ref}`¶ <BinPackLongBracedList>`

: If `BinPackLongBracedList` is `true` it overrides
  `BinPackArguments` if there are 20 or more items in a braced
  initializer list.

  ```c++
  BinPackLongBracedList: false  vs.    BinPackLongBracedList: true
  vector<int> x{                       vector<int> x{1, 2, ...,
                                                     20, 21};
              1,
              2,
              ...,
              20,
              21};
  ```

(binpackparameters)=

**BinPackParameters** (`BinPackParametersStyle`) {versionbadge}`clang-format 3.7` {ref}`¶ <BinPackParameters>`

: This option is **deprecated**. See `BinPack` of `PackParameters`.

  Possible values:

  - `BPPS_BinPack` (in configuration: `BinPack`)
    Bin-pack parameters.

    ```c++
    void f(int a, int bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,
           int ccccccccccccccccccccccccccccccccccccccccccc);
    ```

  - `BPPS_OnePerLine` (in configuration: `OnePerLine`)
    Put all parameters on the current line if they fit.
    Otherwise, put each one on its own line.

    ```c++
    void f(int a, int b, int c);

    void f(int a,
           int b,
           int ccccccccccccccccccccccccccccccccccccc);
    ```

  - `BPPS_AlwaysOnePerLine` (in configuration: `AlwaysOnePerLine`)
    Always put each parameter on its own line.

    ```c++
    void f(int a,
           int b,
           int c);
    ```

  - `BPPS_UseBreakAfter` (in configuration: `UseBreakAfter`)
    Use the `BreakAfter` option to handle parameter packing instead.
    If the `BreakAfter` limit is not exceeded, behave like `BinPack`.



(bitfieldcolonspacing)=

**BitFieldColonSpacing** (`BitFieldColonSpacingStyle`) {versionbadge}`clang-format 12` {ref}`¶ <BitFieldColonSpacing>`

: The BitFieldColonSpacingStyle to use for bitfields.

  Possible values:

  - `BFCS_Both` (in configuration: `Both`)
    Add one space on each side of the `:`

    ```c++
    unsigned bf : 2;
    ```

  - `BFCS_None` (in configuration: `None`)
    Add no space around the `:` (except when needed for
    `AlignConsecutiveBitFields`).

    ```c++
    unsigned bf:2;
    ```

  - `BFCS_Before` (in configuration: `Before`)
    Add space before the `:` only

    ```c++
    unsigned bf :2;
    ```

  - `BFCS_After` (in configuration: `After`)
    Add space after the `:` only (space may be added before if
    needed for `AlignConsecutiveBitFields`).

    ```c++
    unsigned bf: 2;
    ```



(bracewrapping)=

**BraceWrapping** (`BraceWrappingFlags`) {versionbadge}`clang-format 3.8` {ref}`¶ <BraceWrapping>`

: Control of individual brace wrapping cases.

  If `BreakBeforeBraces` is set to `Custom`, use this to specify how
  each individual brace case should be handled. Otherwise, this is ignored.

  ```yaml
  # Example of usage:
  BreakBeforeBraces: Custom
  BraceWrapping:
    AfterEnum: true
    AfterStruct: false
    SplitEmptyFunction: false
  ```

  Nested configuration flags:

  Precise control over the wrapping of braces.

  ```yaml
  # Should be declared this way:
  BreakBeforeBraces: Custom
  BraceWrapping:
      AfterClass: true
  ```

  - `bool AfterCaseLabel` Wrap case labels.

    ```c++
    false:                                true:
    switch (foo) {                vs.     switch (foo) {
      case 1: {                             case 1:
        bar();                              {
        break;                                bar();
      }                                       break;
      default: {                            }
        plop();                             default:
      }                                     {
    }                                         plop();
                                            }
                                          }
    ```

  - `bool AfterClass` Wrap class definitions.

    ```c++
    true:
    class foo
    {};

    false:
    class foo {};
    ```

  - `BraceWrappingAfterControlStatementStyle AfterControlStatement`
    Wrap control statements (`if`/`for`/`while`/`switch`/..).

    Possible values:

    - `BWACS_Never` (in configuration: `Never`)
      Never wrap braces after a control statement.

      ```c++
      if (foo()) {
      } else {
      }
      for (int i = 0; i < 10; ++i) {
      }
      ```

    - `BWACS_MultiLine` (in configuration: `MultiLine`)
      Only wrap braces after a multi-line control statement.

      ```c++
      if (foo && bar &&
          baz)
      {
        quux();
      }
      while (foo || bar) {
      }
      ```

    - `BWACS_Always` (in configuration: `Always`)
      Always wrap braces after a control statement.

      ```c++
      if (foo())
      {
      } else
      {}
      for (int i = 0; i < 10; ++i)
      {}
      ```


  - `bool AfterEnum` Wrap enum definitions.

    ```c++
    true:
    enum X : int
    {
      B
    };

    false:
    enum X : int { B };
    ```

  - `bool AfterFunction` Wrap function definitions.

    ```c++
    true:
    void foo()
    {
      bar();
      bar2();
    }

    false:
    void foo() {
      bar();
      bar2();
    }
    ```

  - `bool AfterNamespace` Wrap namespace definitions.

    ```c++
    true:
    namespace
    {
    int foo();
    int bar();
    }

    false:
    namespace {
    int foo();
    int bar();
    }
    ```

  - `bool AfterObjCDeclaration` Wrap ObjC definitions (interfaces, implementations...).

    :::{note}
    @autoreleasepool and @synchronized blocks are wrapped
    according to `AfterControlStatement` flag.
    :::

  - `bool AfterRequiresExpression` Wrap requires expression body.

    ```c++
    true:
    template <typename T>
    concept C = requires(T t)
    {
      foo(t);
    };

    false:
    template <typename T>
    concept C = requires(T t) {
      foo(t);
    };
    ```

  - `bool AfterStruct` Wrap struct definitions.

    ```c++
    true:
    struct foo
    {
      int x;
    };

    false:
    struct foo {
      int x;
    };
    ```

  - `bool AfterUnion` Wrap union definitions.

    ```c++
    true:
    union foo
    {
      int x;
    }

    false:
    union foo {
      int x;
    }
    ```

  - `bool AfterExportBlock` Wrap export blocks.

    ```c++
    true:                            false:
    export             vs.           export {
    {                                  int foo();
      int foo();                     }
    }
    ```

  - `bool AfterExternBlock` Wrap extern blocks.

    ```c++
    true:
    extern "C"
    {
      int foo();
    }

    false:
    extern "C" {
    int foo();
    }
    ```

  - `bool BeforeCatch` Wrap before `catch`.

    ```c++
    true:
    try {
      foo();
    }
    catch () {
    }

    false:
    try {
      foo();
    } catch () {
    }
    ```

  - `bool BeforeElse` Wrap before `else`.

    ```c++
    true:
    if (foo()) {
    }
    else {
    }

    false:
    if (foo()) {
    } else {
    }
    ```

  - `bool BeforeLambdaBody` Wrap lambda block.

    ```c++
    true:
    connect(
      []()
      {
        foo();
        bar();
      });

    false:
    connect([]() {
      foo();
      bar();
    });
    ```

  - `bool BeforeWhile` Wrap before `while`.

    ```c++
    true:
    do {
      foo();
    }
    while (1);

    false:
    do {
      foo();
    } while (1);
    ```

  - `bool IndentBraces` Indent the wrapped braces themselves.

  - `bool SplitEmptyFunction` If `false`, empty function body can be put on a single line.
    This option is used only if the opening brace of the function has
    already been wrapped, i.e. the `AfterFunction` brace wrapping mode is
    set, and the function could/should not be put on a single line (as per
    `AllowShortFunctionsOnASingleLine` and constructor formatting
    options).

    ```c++
    false:          true:
    int f()   vs.   int f()
    {}              {
                    }
    ```

  - `bool SplitEmptyRecord` If `false`, empty record (e.g. class, struct or union) body
    can be put on a single line. This option is used only if the opening
    brace of the record has already been wrapped, i.e. the `AfterClass`
    (for classes) brace wrapping mode is set.

    ```c++
    false:           true:
    class Foo   vs.  class Foo
    {}               {
                     }
    ```

  - `bool SplitEmptyNamespace` If `false`, empty namespace body can be put on a single line.
    This option is used only if the opening brace of the namespace has
    already been wrapped, i.e. the `AfterNamespace` brace wrapping mode is
    set.

    ```c++
    false:               true:
    namespace Foo   vs.  namespace Foo
    {}                   {
                         }
    ```


(bracedinitializerindentwidth)=

**BracedInitializerIndentWidth** (`Integer`) {versionbadge}`clang-format 17` {ref}`¶ <BracedInitializerIndentWidth>`

: The number of columns to use to indent the contents of braced init lists.
  If unset or negative, `ContinuationIndentWidth` is used.

  ```c++
  AlignAfterOpenBracket: AlwaysBreak
  BracedInitializerIndentWidth: 2

  void f() {
    SomeClass c{
      "foo",
      "bar",
      "baz",
    };
    auto s = SomeStruct{
      .foo = "foo",
      .bar = "bar",
      .baz = "baz",
    };
    SomeArrayT a[3] = {
      {
        foo,
        bar,
      },
      {
        foo,
        bar,
      },
      SomeArrayT{},
    };
  }
  ```

(breakadjacentstringliterals)=

**BreakAdjacentStringLiterals** (`Boolean`) {versionbadge}`clang-format 18` {ref}`¶ <BreakAdjacentStringLiterals>`

: Break between adjacent string literals.

  ```c++
  true:
  return "Code"
         "\0\52\26\55\55\0"
         "x013"
         "\02\xBA";
  false:
  return "Code" "\0\52\26\55\55\0" "x013" "\02\xBA";
  ```

(breakafterattributes)=

**BreakAfterAttributes** (`AttributeBreakingStyle`) {versionbadge}`clang-format 16` {ref}`¶ <BreakAfterAttributes>`

: Break after a group of C++11 attributes before variable or function
  (including constructor/destructor) declaration/definition names or before
  control statements, i.e. `if`, `switch` (including `case` and
  `default` labels), `for`, and `while` statements.

  Possible values:

  - `ABS_Always` (in configuration: `Always`)
    Always break after the last attribute of the group.

    ```c++
    [[maybe_unused]]
    const int i;
    [[gnu::const]] [[maybe_unused]]
    int j;

    [[nodiscard]]
    inline int f();
    [[gnu::const]] [[nodiscard]]
    int g();

    [[likely]]
    if (a)
      f();
    else
      g();

    switch (b) {
    [[unlikely]]
    case 1:
      ++b;
      break;
    [[likely]]
    default:
      return;
    }
    ```

  - `ABS_Leave` (in configuration: `Leave`)
    Leave the line breaking after the last attribute of the group as is.

    ```c++
    [[maybe_unused]] const int i;
    [[gnu::const]] [[maybe_unused]]
    int j;

    [[nodiscard]] inline int f();
    [[gnu::const]] [[nodiscard]]
    int g();

    [[likely]] if (a)
      f();
    else
      g();

    switch (b) {
    [[unlikely]] case 1:
      ++b;
      break;
    [[likely]]
    default:
      return;
    }
    ```

  - `ABS_LeaveAll` (in configuration: `LeaveAll`)
    Same as `Leave` except that it applies to all attributes of the group.

    ```c++
    [[deprecated("Don't use this version")]]
    [[nodiscard]]
    bool foo() {
      return true;
    }

    [[deprecated("Don't use this version")]]
    [[nodiscard]] bool bar() {
      return true;
    }
    ```

  - `ABS_Never` (in configuration: `Never`)
    Never break after the last attribute of the group.

    ```c++
    [[maybe_unused]] const int i;
    [[gnu::const]] [[maybe_unused]] int j;

    [[nodiscard]] inline int f();
    [[gnu::const]] [[nodiscard]] int g();

    [[likely]] if (a)
      f();
    else
      g();

    switch (b) {
    [[unlikely]] case 1:
      ++b;
      break;
    [[likely]] default:
      return;
    }
    ```



(breakafterjavafieldannotations)=

**BreakAfterJavaFieldAnnotations** (`Boolean`) {versionbadge}`clang-format 3.8` {ref}`¶ <BreakAfterJavaFieldAnnotations>`

: Break after each annotation on a field in Java files.

  ```java
  true:                                  false:
  @Partial                       vs.     @Partial @Mock DataLoad loader;
  @Mock
  DataLoad loader;
  ```

(breakafteropenbracketbracedlist)=

**BreakAfterOpenBracketBracedList** (`Boolean`) {versionbadge}`clang-format 22` {ref}`¶ <BreakAfterOpenBracketBracedList>`

: Force break after the left bracket of a braced initializer list (when
  `Cpp11BracedListStyle` is `true`) when the list exceeds the column
  limit.

  ```c++
  true:                             false:
  vector<int> x {         vs.       vector<int> x {1,
     1, 2, 3}                            2, 3}
  ```

(breakafteropenbracketfunction)=

**BreakAfterOpenBracketFunction** (`Boolean`) {versionbadge}`clang-format 22` {ref}`¶ <BreakAfterOpenBracketFunction>`

: Force break after the left parenthesis of a function (declaration,
  definition, call) when the parameters exceed the column limit.

  ```c++
  true:                             false:
  foo (                   vs.       foo (a,
     a , b)                              b)
  ```

(breakafteropenbracketif)=

**BreakAfterOpenBracketIf** (`Boolean`) {versionbadge}`clang-format 22` {ref}`¶ <BreakAfterOpenBracketIf>`

: Force break after the left parenthesis of an if control statement
  when the expression exceeds the column limit.

  ```c++
  true:                             false:
  if constexpr (          vs.       if constexpr (a ||
     a || b)                                      b)
  ```

(breakafteropenbracketloop)=

**BreakAfterOpenBracketLoop** (`Boolean`) {versionbadge}`clang-format 22` {ref}`¶ <BreakAfterOpenBracketLoop>`

: Force break after the left parenthesis of a loop control statement
  when the expression exceeds the column limit.

  ```c++
  true:                             false:
  while (                  vs.      while (a &&
     a && b) {                             b) {
  ```

(breakafteropenbracketswitch)=

**BreakAfterOpenBracketSwitch** (`Boolean`) {versionbadge}`clang-format 22` {ref}`¶ <BreakAfterOpenBracketSwitch>`

: Force break after the left parenthesis of a switch control statement
  when the expression exceeds the column limit.

  ```c++
  true:                             false:
  switch (                 vs.      switch (a +
     a + b) {                               b) {
  ```

(breakafterreturntype)=

**BreakAfterReturnType** (`ReturnTypeBreakingStyle`) {versionbadge}`clang-format 19` {ref}`¶ <BreakAfterReturnType>`

: The function declaration return type breaking style to use.

  Possible values:

  - `RTBS_None` (in configuration: `None`)
    This is **deprecated**. See `Automatic` below.

  - `RTBS_Automatic` (in configuration: `Automatic`)
    Break after return type based on `PenaltyReturnTypeOnItsOwnLine`.

    ```c++
    class A {
      int f() { return 0; };
    };
    int f();
    int f() { return 1; }
    int
    LongName::AnotherLongName();
    ```

  - `RTBS_ExceptShortType` (in configuration: `ExceptShortType`)
    Same as `Automatic` above, except that there is no break after short
    return types.

    ```c++
    class A {
      int f() { return 0; };
    };
    int f();
    int f() { return 1; }
    int LongName::
        AnotherLongName();
    ```

  - `RTBS_All` (in configuration: `All`)
    Always break after the return type.

    ```c++
    class A {
      int
      f() {
        return 0;
      };
    };
    int
    f();
    int
    f() {
      return 1;
    }
    int
    LongName::AnotherLongName();
    ```

  - `RTBS_TopLevel` (in configuration: `TopLevel`)
    Always break after the return types of top-level functions.

    ```c++
    class A {
      int f() { return 0; };
    };
    int
    f();
    int
    f() {
      return 1;
    }
    int
    LongName::AnotherLongName();
    ```

  - `RTBS_AllDefinitions` (in configuration: `AllDefinitions`)
    Always break after the return type of function definitions.

    ```c++
    class A {
      int
      f() {
        return 0;
      };
    };
    int f();
    int
    f() {
      return 1;
    }
    int
    LongName::AnotherLongName();
    ```

  - `RTBS_TopLevelDefinitions` (in configuration: `TopLevelDefinitions`)
    Always break after the return type of top-level definitions.

    ```c++
    class A {
      int f() { return 0; };
    };
    int f();
    int
    f() {
      return 1;
    }
    int
    LongName::AnotherLongName();
    ```



(breakarrays)=

**BreakArrays** (`Boolean`) {versionbadge}`clang-format 16` {ref}`¶ <BreakArrays>`

: If `true`, clang-format will always break after a Json array `[`
  otherwise it will scan until the closing `]` to determine if it should
  add newlines between elements (prettier compatible).

  :::{note}
  This is currently only for formatting JSON.
  :::

  ```c++
  true:                                  false:
  [                          vs.      [1, 2, 3, 4]
    1,
    2,
    3,
    4
  ]
  ```

(breakbeforebinaryoperators)=

**BreakBeforeBinaryOperators** (`BinaryOperatorStyle`) {versionbadge}`clang-format 3.6` {ref}`¶ <BreakBeforeBinaryOperators>`

: The way to wrap binary operators.

  Possible values:

  - `BOS_None` (in configuration: `None`)
    Break after operators.

    ```c++
    LooooooooooongType loooooooooooooooooooooongVariable =
        someLooooooooooooooooongFunction();

    bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +
                         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==
                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa &&
                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >
                     ccccccccccccccccccccccccccccccccccccccccc;
    ```

  - `BOS_NonAssignment` (in configuration: `NonAssignment`)
    Break before operators that aren't assignments.

    ```c++
    LooooooooooongType loooooooooooooooooooooongVariable =
        someLooooooooooooooooongFunction();

    bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
                         + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
                     == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
                 && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
                        > ccccccccccccccccccccccccccccccccccccccccc;
    ```

  - `BOS_All` (in configuration: `All`)
    Break before operators.

    ```c++
    LooooooooooongType loooooooooooooooooooooongVariable
        = someLooooooooooooooooongFunction();

    bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
                         + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
                     == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
                 && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
                        > ccccccccccccccccccccccccccccccccccccccccc;
    ```



(breakbeforebraces)=

**BreakBeforeBraces** (`BraceBreakingStyle`) {versionbadge}`clang-format 3.7` {ref}`¶ <BreakBeforeBraces>`

: The brace breaking style to use.

  Possible values:

  - `BS_Attach` (in configuration: `Attach`)
    Always attach braces to surrounding context.

    ```c++
    namespace N {
    enum E {
      E1,
      E2,
    };

    class C {
    public:
      C();
    };

    bool baz(int i) {
      try {
        do {
          switch (i) {
          case 1: {
            foobar();
            break;
          }
          default: {
            break;
          }
          }
        } while (--i);
        return true;
      } catch (...) {
        handleError();
        return false;
      }
    }

    void foo(bool b) {
      if (b) {
        baz(2);
      } else {
        baz(5);
      }
    }

    void bar() { foo(true); }
    } // namespace N
    ```

  - `BS_Linux` (in configuration: `Linux`)
    Like `Attach`, but break before braces on function, namespace and
    class definitions.

    ```c++
    namespace N
    {
    enum E {
      E1,
      E2,
    };

    class C
    {
    public:
      C();
    };

    bool baz(int i)
    {
      try {
        do {
          switch (i) {
          case 1: {
            foobar();
            break;
          }
          default: {
            break;
          }
          }
        } while (--i);
        return true;
      } catch (...) {
        handleError();
        return false;
      }
    }

    void foo(bool b)
    {
      if (b) {
        baz(2);
      } else {
        baz(5);
      }
    }

    void bar() { foo(true); }
    } // namespace N
    ```

  - `BS_Mozilla` (in configuration: `Mozilla`)
    Like `Attach`, but break before braces on enum, function, and record
    definitions.

    ```c++
    namespace N {
    enum E
    {
      E1,
      E2,
    };

    class C
    {
    public:
      C();
    };

    bool baz(int i)
    {
      try {
        do {
          switch (i) {
          case 1: {
            foobar();
            break;
          }
          default: {
            break;
          }
          }
        } while (--i);
        return true;
      } catch (...) {
        handleError();
        return false;
      }
    }

    void foo(bool b)
    {
      if (b) {
        baz(2);
      } else {
        baz(5);
      }
    }

    void bar() { foo(true); }
    } // namespace N
    ```

  - `BS_Stroustrup` (in configuration: `Stroustrup`)
    Like `Attach`, but break before function definitions, `catch`, and
    `else`.

    ```c++
    namespace N {
    enum E {
      E1,
      E2,
    };

    class C {
    public:
      C();
    };

    bool baz(int i)
    {
      try {
        do {
          switch (i) {
          case 1: {
            foobar();
            break;
          }
          default: {
            break;
          }
          }
        } while (--i);
        return true;
      }
      catch (...) {
        handleError();
        return false;
      }
    }

    void foo(bool b)
    {
      if (b) {
        baz(2);
      }
      else {
        baz(5);
      }
    }

    void bar() { foo(true); }
    } // namespace N
    ```

  - `BS_Allman` (in configuration: `Allman`)
    Always break before braces.

    ```c++
    namespace N
    {
    enum E
    {
      E1,
      E2,
    };

    class C
    {
    public:
      C();
    };

    bool baz(int i)
    {
      try
      {
        do
        {
          switch (i)
          {
          case 1:
          {
            foobar();
            break;
          }
          default:
          {
            break;
          }
          }
        } while (--i);
        return true;
      }
      catch (...)
      {
        handleError();
        return false;
      }
    }

    void foo(bool b)
    {
      if (b)
      {
        baz(2);
      }
      else
      {
        baz(5);
      }
    }

    void bar() { foo(true); }
    } // namespace N
    ```

  - `BS_Whitesmiths` (in configuration: `Whitesmiths`)
    Like `Allman` but always indent braces and line up code with braces.

    ```c++
    namespace N
      {
    enum E
      {
      E1,
      E2,
      };

    class C
      {
    public:
      C();
      };

    bool baz(int i)
      {
      try
        {
        do
          {
          switch (i)
            {
            case 1:
            {
            foobar();
            break;
            }
            default:
            {
            break;
            }
            }
          } while (--i);
        return true;
        }
      catch (...)
        {
        handleError();
        return false;
        }
      }

    void foo(bool b)
      {
      if (b)
        {
        baz(2);
        }
      else
        {
        baz(5);
        }
      }

    void bar() { foo(true); }
      } // namespace N
    ```

  - `BS_GNU` (in configuration: `GNU`)
    Always break before braces and add an extra level of indentation to
    braces of control statements, not to those of class, function
    or other definitions.

    ```c++
    namespace N
    {
    enum E
    {
      E1,
      E2,
    };

    class C
    {
    public:
      C();
    };

    bool baz(int i)
    {
      try
        {
          do
            {
              switch (i)
                {
                case 1:
                  {
                    foobar();
                    break;
                  }
                default:
                  {
                    break;
                  }
                }
            }
          while (--i);
          return true;
        }
      catch (...)
        {
          handleError();
          return false;
        }
    }

    void foo(bool b)
    {
      if (b)
        {
          baz(2);
        }
      else
        {
          baz(5);
        }
    }

    void bar() { foo(true); }
    } // namespace N
    ```

  - `BS_WebKit` (in configuration: `WebKit`)
    Like `Attach`, but break before functions.

    ```c++
    namespace N {
    enum E {
      E1,
      E2,
    };

    class C {
    public:
      C();
    };

    bool baz(int i)
    {
      try {
        do {
          switch (i) {
          case 1: {
            foobar();
            break;
          }
          default: {
            break;
          }
          }
        } while (--i);
        return true;
      } catch (...) {
        handleError();
        return false;
      }
    }

    void foo(bool b)
    {
      if (b) {
        baz(2);
      } else {
        baz(5);
      }
    }

    void bar() { foo(true); }
    } // namespace N
    ```

  - `BS_Custom` (in configuration: `Custom`)
    Configure each individual brace in `BraceWrapping`.



(breakbeforeclosebracketbracedlist)=

**BreakBeforeCloseBracketBracedList** (`Boolean`) {versionbadge}`clang-format 22` {ref}`¶ <BreakBeforeCloseBracketBracedList>`

: Force break before the right bracket of a braced initializer list (when
  `Cpp11BracedListStyle` is `true`) when the list exceeds the column
  limit. The break before the right bracket is only made if there is a
  break after the opening bracket.

  ```c++
  true:                             false:
  vector<int> x {         vs.       vector<int> x {
     1, 2, 3                           1, 2, 3}
  }
  ```

(breakbeforeclosebracketfunction)=

**BreakBeforeCloseBracketFunction** (`Boolean`) {versionbadge}`clang-format 22` {ref}`¶ <BreakBeforeCloseBracketFunction>`

: Force break before the right parenthesis of a function (declaration,
  definition, call) when the parameters exceed the column limit.

  ```c++
  true:                             false:
  foo (                   vs.       foo (
     a , b                             a , b)
  )
  ```

(breakbeforeclosebracketif)=

**BreakBeforeCloseBracketIf** (`Boolean`) {versionbadge}`clang-format 22` {ref}`¶ <BreakBeforeCloseBracketIf>`

: Force break before the right parenthesis of an if control statement
  when the expression exceeds the column limit. The break before the
  closing parenthesis is only made if there is a break after the opening
  parenthesis.

  ```c++
  true:                             false:
  if constexpr (          vs.       if constexpr (
     a || b                            a || b )
  )
  ```

(breakbeforeclosebracketloop)=

**BreakBeforeCloseBracketLoop** (`Boolean`) {versionbadge}`clang-format 22` {ref}`¶ <BreakBeforeCloseBracketLoop>`

: Force break before the right parenthesis of a loop control statement
  when the expression exceeds the column limit. The break before the
  closing parenthesis is only made if there is a break after the opening
  parenthesis.

  ```c++
  true:                             false:
  while (                  vs.      while (
     a && b                            a && b) {
  ) {
  ```

(breakbeforeclosebracketswitch)=

**BreakBeforeCloseBracketSwitch** (`Boolean`) {versionbadge}`clang-format 22` {ref}`¶ <BreakBeforeCloseBracketSwitch>`

: Force break before the right parenthesis of a switch control statement
  when the expression exceeds the column limit. The break before the
  closing parenthesis is only made if there is a break after the opening
  parenthesis.

  ```c++
  true:                             false:
  switch (                 vs.      switch (
     a + b                             a + b) {
  ) {
  ```

(breakbeforeconceptdeclarations)=

**BreakBeforeConceptDeclarations** (`BreakBeforeConceptDeclarationsStyle`) {versionbadge}`clang-format 12` {ref}`¶ <BreakBeforeConceptDeclarations>`

: The concept declaration style to use.

  Possible values:

  - `BBCDS_Never` (in configuration: `Never`)
    Keep the template declaration line together with `concept`.

    ```c++
    template <typename T> concept C = ...;
    ```

  - `BBCDS_Allowed` (in configuration: `Allowed`)
    Breaking between template declaration and `concept` is allowed. The
    actual behavior depends on the content and line breaking rules and
    penalties.

  - `BBCDS_Always` (in configuration: `Always`)
    Always break before `concept`, putting it in the line after the
    template declaration.

    ```c++
    template <typename T>
    concept C = ...;
    ```



(breakbeforeinlineasmcolon)=

**BreakBeforeInlineASMColon** (`BreakBeforeInlineASMColonStyle`) {versionbadge}`clang-format 16` {ref}`¶ <BreakBeforeInlineASMColon>`

: The inline ASM colon style to use.

  Possible values:

  - `BBIAS_Never` (in configuration: `Never`)
    No break before inline ASM colon.

    ```c++
    asm volatile("string", : : val);
    ```

  - `BBIAS_OnlyMultiline` (in configuration: `OnlyMultiline`)
    Break before inline ASM colon if the line length is longer than column
    limit.

    ```c++
    asm volatile("string", : : val);
    asm("cmoveq %1, %2, %[result]"
        : [result] "=r"(result)
        : "r"(test), "r"(new), "[result]"(old));
    ```

  - `BBIAS_Always` (in configuration: `Always`)
    Always break before inline ASM colon.

    ```c++
    asm volatile("string",
                 :
                 : val);
    ```



(breakbeforereturntype)=

**BreakBeforeReturnType** (`BreakBeforeReturnTypeStyle`) {versionbadge}`clang-format 23` {ref}`¶ <BreakBeforeReturnType>`

: The function declaration/definition return type breaking style to use.
  Trailing return types (`auto f() -> T`) are not affected. To have
  identifier macros (e.g. `__always_inline`) treated as specifiers,
  add them to `AttributeMacros`.

  Possible values:

  - `BBRTS_None` (in configuration: `None`)
    Do not force a break before the return type.

  - `BBRTS_All` (in configuration: `All`)
    Always break before the return type.

    ```c++
    static inline
    void f();
    ```

  - `BBRTS_TopLevel` (in configuration: `TopLevel`)
    Break before the return type of top-level functions only.

  - `BBRTS_AllDefinitions` (in configuration: `AllDefinitions`)
    Break before the return type of function definitions only.

  - `BBRTS_TopLevelDefinitions` (in configuration: `TopLevelDefinitions`)
    Break before the return type of top-level definitions only.



(breakbeforetemplatecloser)=

**BreakBeforeTemplateCloser** (`Boolean`) {versionbadge}`clang-format 21` {ref}`¶ <BreakBeforeTemplateCloser>`

: If `true`, break before a template closing bracket (`>`) when there is
  a line break after the matching opening bracket (`<`).

  ```c++
  true:
  template <typename Foo, typename Bar>

  template <typename Foo,
            typename Bar>

  template <
      typename Foo,
      typename Bar
  >

  false:
  template <typename Foo, typename Bar>

  template <typename Foo,
            typename Bar>

  template <
      typename Foo,
      typename Bar>
  ```

(breakbeforeternaryoperators)=

**BreakBeforeTernaryOperators** (`Boolean`) {versionbadge}`clang-format 3.7` {ref}`¶ <BreakBeforeTernaryOperators>`

: If `true`, ternary operators will be placed after line breaks.

  ```c++
  true:
  veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongDescription
      ? firstValue
      : SecondValueVeryVeryVeryVeryLong;

  false:
  veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongDescription ?
      firstValue :
      SecondValueVeryVeryVeryVeryLong;
  ```

(breakbinaryoperations)=

**BreakBinaryOperations** (`BreakBinaryOperationsOptions`) {versionbadge}`clang-format 20` {ref}`¶ <BreakBinaryOperations>`

: The break binary operations style to use.

  Nested configuration flags:

  Options for `BreakBinaryOperations`.

  If specified as a simple string (e.g. `OnePerLine`), it behaves like
  the original enum and applies to all binary operators.

  If specified as a struct, allows per-operator configuration:

  ```yaml
  BreakBinaryOperations:
    Default: Never
    PerOperator:
      - Operators: ['&&', '||']
        Style: OnePerLine
        MinChainLength: 3
  ```

  - `BreakBinaryOperationsStyle Default` {versionbadge}`clang-format 23`

    The default break style for operators not covered by `PerOperator`.

    Possible values:

    - `BBO_Never` (in configuration: `Never`)
      Don't break binary operations

      ```c++
      aaa + bbbb * ccccc - ddddd +
      eeeeeeeeeeeeeeee;
      ```

    - `BBO_OnePerLine` (in configuration: `OnePerLine`)
      Binary operations will either be all on the same line, or each operation
      will have one line each.

      ```c++
      aaa +
      bbbb *
      ccccc -
      ddddd +
      eeeeeeeeeeeeeeee;
      ```

    - `BBO_RespectPrecedence` (in configuration: `RespectPrecedence`)
      Binary operations of a particular precedence that exceed the column
      limit will have one line each.

      ```c++
      aaa +
      bbbb * ccccc -
      ddddd +
      eeeeeeeeeeeeeeee;
      ```


  - `List of BinaryOperationBreakRules PerOperator` Per-operator override rules.

  - `List of Strings Operators` {versionbadge}`clang-format 23` The list of operators this rule applies to, e.g. `&&`, `||`, `|`.
    Alternative spellings (e.g. `and` for `&&`) are accepted.

  - `BreakBinaryOperationsStyle Style`
    The break style for these operators (defaults to `OnePerLine`).

    Possible values:

    - `BBO_Never` (in configuration: `Never`)
      Don't break binary operations

      ```c++
      aaa + bbbb * ccccc - ddddd +
      eeeeeeeeeeeeeeee;
      ```

    - `BBO_OnePerLine` (in configuration: `OnePerLine`)
      Binary operations will either be all on the same line, or each operation
      will have one line each.

      ```c++
      aaa +
      bbbb *
      ccccc -
      ddddd +
      eeeeeeeeeeeeeeee;
      ```

    - `BBO_RespectPrecedence` (in configuration: `RespectPrecedence`)
      Binary operations of a particular precedence that exceed the column
      limit will have one line each.

      ```c++
      aaa +
      bbbb * ccccc -
      ddddd +
      eeeeeeeeeeeeeeee;
      ```


  - `unsigned MinChainLength` Minimum number of operands in a chain before the rule triggers.
    For example, `a && b && c` is a chain of length 3.
    `0` means always break (when the line is too long).


(breakconstructorinitializers)=

**BreakConstructorInitializers** (`BreakConstructorInitializersStyle`) {versionbadge}`clang-format 5` {ref}`¶ <BreakConstructorInitializers>`

: The break constructor initializers style to use.

  Possible values:

  - `BCIS_BeforeColon` (in configuration: `BeforeColon`)
    Break constructor initializers before the colon and after the commas.

    ```c++
    Constructor()
        : initializer1(),
          initializer2()
    ```

  - `BCIS_BeforeComma` (in configuration: `BeforeComma`)
    Break constructor initializers before the colon and commas, and align
    the commas with the colon.

    ```c++
    Constructor()
        : initializer1()
        , initializer2()
    ```

  - `BCIS_AfterColon` (in configuration: `AfterColon`)
    Break constructor initializers after the colon and commas.

    ```c++
    Constructor() :
        initializer1(),
        initializer2()
    ```

  - `BCIS_AfterComma` (in configuration: `AfterComma`)
    Break constructor initializers only after the commas.

    ```c++
    Constructor() : initializer1(),
                    initializer2()
    ```



(breakfunctiondeclarationparameters)=

**BreakFunctionDeclarationParameters** (`Boolean`) {versionbadge}`clang-format 23` {ref}`¶ <BreakFunctionDeclarationParameters>`

: If `true`, clang-format will always break before function declaration
  parameters.

  ```c++
  true:
  void functionDeclaration(
           int A, int B);

  false:
  void functionDeclaration(int A, int B);

  ```

(breakfunctiondefinitionparameters)=

**BreakFunctionDefinitionParameters** (`Boolean`) {versionbadge}`clang-format 19` {ref}`¶ <BreakFunctionDefinitionParameters>`

: If `true`, clang-format will always break before function definition
  parameters.

  ```c++
  true:
  void functionDefinition(
           int A, int B) {}

  false:
  void functionDefinition(int A, int B) {}

  ```

(breakinheritancelist)=

**BreakInheritanceList** (`BreakInheritanceListStyle`) {versionbadge}`clang-format 7` {ref}`¶ <BreakInheritanceList>`

: The inheritance list style to use.

  Possible values:

  - `BILS_BeforeColon` (in configuration: `BeforeColon`)
    Break inheritance list before the colon and after the commas.

    ```c++
    class Foo
        : Base1,
          Base2
    {};
    ```

  - `BILS_BeforeComma` (in configuration: `BeforeComma`)
    Break inheritance list before the colon and commas, and align
    the commas with the colon.

    ```c++
    class Foo
        : Base1
        , Base2
    {};
    ```

  - `BILS_AfterColon` (in configuration: `AfterColon`)
    Break inheritance list after the colon and commas.

    ```c++
    class Foo :
        Base1,
        Base2
    {};
    ```

  - `BILS_AfterComma` (in configuration: `AfterComma`)
    Break inheritance list only after the commas.

    ```c++
    class Foo : Base1,
                Base2
    {};
    ```



(breakstringliterals)=

**BreakStringLiterals** (`Boolean`) {versionbadge}`clang-format 3.9` {ref}`¶ <BreakStringLiterals>`

: Allow breaking string literals when formatting.

  In C, C++, and Objective-C:

  ```c++
  true:
  const char* x = "veryVeryVeryVeryVeryVe"
                  "ryVeryVeryVeryVeryVery"
                  "VeryLongString";

  false:
  const char* x =
      "veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongString";
  ```

  In C# and Java:

  ```c++
  true:
  string x = "veryVeryVeryVeryVeryVe" +
             "ryVeryVeryVeryVeryVery" +
             "VeryLongString";

  false:
  string x =
      "veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongString";
  ```

  C# interpolated strings are not broken.

  In Verilog:

  ```c++
  true:
  string x = {"veryVeryVeryVeryVeryVe",
              "ryVeryVeryVeryVeryVery",
              "VeryLongString"};

  false:
  string x =
      "veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongString";
  ```

(breaktemplatedeclarations)=

**BreakTemplateDeclarations** (`BreakTemplateDeclarationsStyle`) {versionbadge}`clang-format 19` {ref}`¶ <BreakTemplateDeclarations>`

: The template declaration breaking style to use.

  Possible values:

  - `BTDS_Leave` (in configuration: `Leave`)
    Do not change the line breaking before the declaration.

    ```c++
    template <typename T>
    T foo() {
    }
    template <typename T> T foo(int aaaaaaaaaaaaaaaaaaaaa,
                                int bbbbbbbbbbbbbbbbbbbbb) {
    }
    ```

  - `BTDS_No` (in configuration: `No`)
    Do not force break before declaration.
    `PenaltyBreakTemplateDeclaration` is taken into account.

    ```c++
    template <typename T> T foo() {
    }
    template <typename T> T foo(int aaaaaaaaaaaaaaaaaaaaa,
                                int bbbbbbbbbbbbbbbbbbbbb) {
    }
    ```

  - `BTDS_MultiLine` (in configuration: `MultiLine`)
    Force break after template declaration only when the following
    declaration spans multiple lines.

    ```c++
    template <typename T> T foo() {
    }
    template <typename T>
    T foo(int aaaaaaaaaaaaaaaaaaaaa,
          int bbbbbbbbbbbbbbbbbbbbb) {
    }
    ```

  - `BTDS_Yes` (in configuration: `Yes`)
    Always break after template declaration.

    ```c++
    template <typename T>
    T foo() {
    }
    template <typename T>
    T foo(int aaaaaaaaaaaaaaaaaaaaa,
          int bbbbbbbbbbbbbbbbbbbbb) {
    }
    ```



(columnlimit)=

**ColumnLimit** (`Unsigned`) {versionbadge}`clang-format 3.7` {ref}`¶ <ColumnLimit>`

: The column limit.

  A column limit of `0` means that there is no column limit. In this case,
  clang-format will respect the input's line breaking decisions within
  statements unless they contradict other rules.

(commentpragmas)=

**CommentPragmas** (`String`) {versionbadge}`clang-format 3.7` {ref}`¶ <CommentPragmas>`

: A regular expression that describes comments with special meaning,
  which should not be split into lines or otherwise changed.

  ```c++
  // CommentPragmas: '^ FOOBAR pragma:'
  // Will leave the following line unaffected
  #include <vector> // FOOBAR pragma: keep
  ```

(compactnamespaces)=

**CompactNamespaces** (`Boolean`) {versionbadge}`clang-format 5` {ref}`¶ <CompactNamespaces>`

: If `true`, consecutive namespace declarations will be on the same
  line. If `false`, each namespace is declared on a new line.

  ```c++
  true:
  namespace Foo { namespace Bar {
  }}

  false:
  namespace Foo {
  namespace Bar {
  }
  }
  ```

  If it does not fit on a single line, the overflowing namespaces get
  wrapped:

  ```c++
  namespace Foo { namespace Bar {
  namespace Extra {
  }}}
  ```

(constructorinitializerallononelineoroneperline)=

**ConstructorInitializerAllOnOneLineOrOnePerLine** (`Boolean`) {versionbadge}`clang-format 3.7` {ref}`¶ <ConstructorInitializerAllOnOneLineOrOnePerLine>`

: This option is **deprecated**. See `CurrentLine` of
  `PackConstructorInitializers`.

(constructorinitializerindentwidth)=

**ConstructorInitializerIndentWidth** (`Unsigned`) {versionbadge}`clang-format 3.7` {ref}`¶ <ConstructorInitializerIndentWidth>`

: The number of characters to use for indentation of constructor
  initializer lists as well as inheritance lists.

(continuationindentwidth)=

**ContinuationIndentWidth** (`Unsigned`) {versionbadge}`clang-format 3.7` {ref}`¶ <ContinuationIndentWidth>`

: Indent width for line continuations.

  ```c++
  ContinuationIndentWidth: 2

  int i =         //  VeryVeryVeryVeryVeryLongComment
    longFunction( // Again a long comment
      arg);
  ```

(cpp11bracedliststyle)=

**Cpp11BracedListStyle** (`BracedListStyle`) {versionbadge}`clang-format 3.4` {ref}`¶ <Cpp11BracedListStyle>`

: The style to handle braced lists.

  Possible values:

  - `BLS_Block` (in configuration: `Block`)
    Best suited for pre C++11 braced lists.

    - Spaces inside the braced list.
    - Line break before the closing brace.
    - Indentation with the block indent.

    ```c++
    vector<int> x{ 1, 2, 3, 4 };
    vector<T> x{ {}, {}, {}, {} };
    f(MyMap[{ composite, key }]);
    new int[3]{ 1, 2, 3 };
    Type name{ // Comment
               value
    };
    ```

  - `BLS_FunctionCall` (in configuration: `FunctionCall`)
    Best suited for C++11 braced lists.

    - No spaces inside the braced list.
    - No line break before the closing brace.
    - Indentation with the continuation indent.

    Fundamentally, C++11 braced lists are formatted exactly like function
    calls would be formatted in their place. If the braced list follows a
    name (e.g. a type or variable name), clang-format formats as if the
    `{}` were the parentheses of a function call with that name. If there
    is no name, a zero-length name is assumed.

    ```c++
    vector<int> x{1, 2, 3, 4};
    vector<T> x{{}, {}, {}, {}};
    f(MyMap[{composite, key}]);
    new int[3]{1, 2, 3};
    Type name{ // Comment
        value};
    ```

  - `BLS_AlignFirstComment` (in configuration: `AlignFirstComment`)
    Same as `FunctionCall`, except for the handling of a comment at the
    begin, it then aligns everything following with the comment.

    - No spaces inside the braced list. (Even for a comment at the first
      position.)
    - No line break before the closing brace.
    - Indentation with the continuation indent, except when followed by a
      line comment, then it uses the block indent.

    ```c++
    vector<int> x{1, 2, 3, 4};
    vector<T> x{{}, {}, {}, {}};
    f(MyMap[{composite, key}]);
    new int[3]{1, 2, 3};
    Type name{// Comment
              value};
    ```



(derivelineending)=

**DeriveLineEnding** (`Boolean`) {versionbadge}`clang-format 10` {ref}`¶ <DeriveLineEnding>`

: This option is **deprecated**. See `DeriveLF` and `DeriveCRLF` of
  `LineEnding`.

(derivepointeralignment)=

**DerivePointerAlignment** (`Boolean`) {versionbadge}`clang-format 3.7` {ref}`¶ <DerivePointerAlignment>`

: If `true`, analyze the formatted file for the most common
  alignment of `&` and `*`.
  Pointer and reference alignment styles are going to be updated according
  to the preferences found in the file.
  `PointerAlignment` is then used only as fallback.

(disableformat)=

**DisableFormat** (`Boolean`) {versionbadge}`clang-format 3.7` {ref}`¶ <DisableFormat>`

: Disables formatting completely.

(emptylineafteraccessmodifier)=

**EmptyLineAfterAccessModifier** (`EmptyLineAfterAccessModifierStyle`) {versionbadge}`clang-format 13` {ref}`¶ <EmptyLineAfterAccessModifier>`

: Defines when to put an empty line after access modifiers.
  `EmptyLineBeforeAccessModifier` configuration handles the number of
  empty lines between two access modifiers.

  Possible values:

  - `ELAAMS_Never` (in configuration: `Never`)
    Remove all empty lines after access modifiers.

    ```c++
    struct foo {
    private:
      int i;
    protected:
      int j;
      /* comment */
    public:
      foo() {}
    private:
    protected:
    };
    ```

  - `ELAAMS_Leave` (in configuration: `Leave`)
    Keep existing empty lines after access modifiers.
    MaxEmptyLinesToKeep is applied instead.

  - `ELAAMS_Always` (in configuration: `Always`)
    Always add empty line after access modifiers if there are none.
    MaxEmptyLinesToKeep is applied also.

    ```c++
    struct foo {
    private:

      int i;
    protected:

      int j;
      /* comment */
    public:

      foo() {}
    private:

    protected:

    };
    ```



(emptylinebeforeaccessmodifier)=

**EmptyLineBeforeAccessModifier** (`EmptyLineBeforeAccessModifierStyle`) {versionbadge}`clang-format 12` {ref}`¶ <EmptyLineBeforeAccessModifier>`

: Defines in which cases to put empty line before access modifiers.

  Possible values:

  - `ELBAMS_Never` (in configuration: `Never`)
    Remove all empty lines before access modifiers.

    ```c++
    struct foo {
    private:
      int i;
    protected:
      int j;
      /* comment */
    public:
      foo() {}
    private:
    protected:
    };
    ```

  - `ELBAMS_Leave` (in configuration: `Leave`)
    Keep existing empty lines before access modifiers.

  - `ELBAMS_LogicalBlock` (in configuration: `LogicalBlock`)
    Add empty line only when access modifier starts a new logical block.
    Logical block is a group of one or more member fields or functions.

    ```c++
    struct foo {
    private:
      int i;

    protected:
      int j;
      /* comment */
    public:
      foo() {}

    private:
    protected:
    };
    ```

  - `ELBAMS_Always` (in configuration: `Always`)
    Always add empty line before access modifiers unless access modifier
    is at the start of struct or class definition.

    ```c++
    struct foo {
    private:
      int i;

    protected:
      int j;
      /* comment */

    public:
      foo() {}

    private:

    protected:
    };
    ```



(enumtrailingcomma)=

**EnumTrailingComma** (`EnumTrailingCommaStyle`) {versionbadge}`clang-format 21` {ref}`¶ <EnumTrailingComma>`

: Insert a comma (if missing) or remove the comma at the end of an `enum`
  enumerator list.

  :::{warning}
  Setting this option to any value other than `Leave` could lead to
  incorrect code formatting due to clang-format's lack of complete semantic
  information. As such, extra care should be taken to review code changes
  made by this option.
  :::

  Possible values:

  - `ETC_Leave` (in configuration: `Leave`)
    Don't insert or remove trailing commas.

    ```c++
    enum { a, b, c, };
    enum Color { red, green, blue };
    ```

  - `ETC_Insert` (in configuration: `Insert`)
    Insert trailing commas.

    ```c++
    enum { a, b, c, };
    enum Color { red, green, blue, };
    ```

  - `ETC_Remove` (in configuration: `Remove`)
    Remove trailing commas.

    ```c++
    enum { a, b, c };
    enum Color { red, green, blue };
    ```



(experimentalautodetectbinpacking)=

**ExperimentalAutoDetectBinPacking** (`Boolean`) {versionbadge}`clang-format 3.7` {ref}`¶ <ExperimentalAutoDetectBinPacking>`

: If `true`, clang-format detects whether function calls and
  definitions are formatted with one parameter per line.

  Each call can be bin-packed, one-per-line or inconclusive. If it is
  inconclusive, e.g. completely on one line, but a decision needs to be
  made, clang-format analyzes whether there are other bin-packed cases in
  the input file and act accordingly.

  :::{note}
  This is an experimental flag, that might go away or be renamed. Do
  not use this in config files, etc. Use at your own risk.
  :::

(fixnamespacecomments)=

**FixNamespaceComments** (`Boolean`) {versionbadge}`clang-format 5` {ref}`¶ <FixNamespaceComments>`

: If `true`, clang-format adds missing namespace end comments for
  namespaces and fixes invalid existing ones. This doesn't affect short
  namespaces, which are controlled by `ShortNamespaceLines`.

  ```c++
  true:                                  false:
  namespace longNamespace {      vs.     namespace longNamespace {
  void foo();                            void foo();
  void bar();                            void bar();
  } // namespace a                       }
  namespace shortNamespace {             namespace shortNamespace {
  void baz();                            void baz();
  }                                      }
  ```

(foreachmacros)=

**ForEachMacros** (`List of Strings`) {versionbadge}`clang-format 3.7` {ref}`¶ <ForEachMacros>`

: A vector of macros that should be interpreted as foreach loops
  instead of as function calls.

  These are expected to be macros of the form:

  ```c++
  FOREACH(<variable-declaration>, ...)
    <loop-body>
  ```

  In the .clang-format configuration file, this can be configured like:

  ```yaml
  ForEachMacros: [RANGES_FOR, FOREACH]
  ```

  For example: BOOST_FOREACH.

(ifmacros)=

**IfMacros** (`List of Strings`) {versionbadge}`clang-format 13` {ref}`¶ <IfMacros>`

: A vector of macros that should be interpreted as conditionals
  instead of as function calls.

  These are expected to be macros of the form:

  ```c++
  IF(...)
    <conditional-body>
  else IF(...)
    <conditional-body>
  ```

  In the .clang-format configuration file, this can be configured like:

  ```yaml
  IfMacros: [IF]
  ```

  For example:
  [KJ_IF_MAYBE](https://github.com/capnproto/capnproto/blob/master/kjdoc/tour.md#maybes)

(includeblocks)=

**IncludeBlocks** (`IncludeBlocksStyle`) {versionbadge}`clang-format 6` {ref}`¶ <IncludeBlocks>`

: Dependent on the value, multiple `#include` blocks can be sorted
  as one and divided based on category.

  Possible values:

  - `IBS_Preserve` (in configuration: `Preserve`)
    Sort each `#include` block separately.

    ```c++
    #include "b.h"               into      #include "b.h"

    #include <lib/main.h>                  #include "a.h"
    #include "a.h"                         #include <lib/main.h>
    ```

  - `IBS_Merge` (in configuration: `Merge`)
    Merge multiple `#include` blocks together and sort as one.

    ```c++
    #include "b.h"               into      #include "a.h"
                                           #include "b.h"
    #include <lib/main.h>                  #include <lib/main.h>
    #include "a.h"
    ```

  - `IBS_Regroup` (in configuration: `Regroup`)
    Merge multiple `#include` blocks together and sort as one.
    Then split into groups based on category priority. See
    `IncludeCategories`.

    ```c++
    #include "b.h"               into      #include "a.h"
                                           #include "b.h"
    #include <lib/main.h>
    #include "a.h"                         #include <lib/main.h>
    ```



(includecategories)=

**IncludeCategories** (`List of IncludeCategories`) {versionbadge}`clang-format 3.8` {ref}`¶ <IncludeCategories>`

: Regular expressions denoting the different `#include` categories
  used for ordering `#includes`.

  [POSIX
  extended](https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap09.html)
  regular expressions are supported.

  These regular expressions are matched against the filename of an include
  (including the <> or "") in order. The value belonging to the first
  matching regular expression is assigned and `#includes` are sorted first
  according to increasing category number and then alphabetically within
  each category.

  If none of the regular expressions match, INT_MAX is assigned as
  category. The main header for a source file automatically gets category 0.
  so that it is generally kept at the beginning of the `#includes`
  (see [LLVM
  style](https://llvm.org/docs/CodingStandards.html#include-style)).
  However, you can also assign negative priorities if you have certain
  headers that always need to be first.

  There is a third and optional field `SortPriority` which can used while
  `IncludeBlocks = IBS_Regroup` to define the priority in which
  `#includes` should be ordered. The value of `Priority` defines the
  order of `#include blocks` and also allows the grouping of `#includes`
  of different priority. `SortPriority` is set to the value of
  `Priority` as default if it is not assigned.

  Each regular expression can be marked as case sensitive with the field
  `CaseSensitive`, per default it is not.

  To configure this in the .clang-format file, use:

  ```yaml
  IncludeCategories:
    - Regex:           '^"(llvm|llvm-c|clang|clang-c)/'
      Priority:        2
      SortPriority:    2
      CaseSensitive:   true
    - Regex:           '^((<|")(gtest|gmock|isl|json)/)'
      Priority:        3
    - Regex:           '<[[:alnum:].]+>'
      Priority:        4
    - Regex:           '.*'
      Priority:        1
      SortPriority:    0
  ```

(includeismainregex)=

**IncludeIsMainRegex** (`String`) {versionbadge}`clang-format 3.9` {ref}`¶ <IncludeIsMainRegex>`

: Specify a regular expression of suffixes that are allowed in the
  file-to-main-include mapping.

  When guessing whether a #include is the "main" include (to assign
  category 0, see above), use this regex of allowed suffixes to the header
  stem. A partial match is done, so that:
  - `""` means "arbitrary suffix"
  - `"$"` means "no suffix"

  For example, if configured to `"(_test)?$"`, then a header a.h would be
  seen as the "main" include in both a.cc and a_test.cc.

(includeismainsourceregex)=

**IncludeIsMainSourceRegex** (`String`) {versionbadge}`clang-format 10` {ref}`¶ <IncludeIsMainSourceRegex>`

: Specify a regular expression for files being formatted
  that are allowed to be considered "main" in the
  file-to-main-include mapping.

  By default, clang-format considers files as "main" only when they end
  with: `.c`, `.cc`, `.cpp`, `.c++`, `.cxx`, `.m` or `.mm`
  extensions.
  For these files a guessing of "main" include takes place
  (to assign category 0, see above). This config option allows for
  additional suffixes and extensions for files to be considered as "main".

  For example, if this option is configured to `(Impl\.hpp)$`,
  then a file `ClassImpl.hpp` is considered "main" (in addition to
  `Class.c`, `Class.cc`, `Class.cpp` and so on) and "main
  include file" logic will be executed (with *IncludeIsMainRegex* setting
  also being respected in later phase). Without this option set,
  `ClassImpl.hpp` would not have the main include file put on top
  before any other include.

(indentaccessmodifiers)=

**IndentAccessModifiers** (`IndentAccessModifierStyle`) {versionbadge}`clang-format 13` {ref}`¶ <IndentAccessModifiers>`

: Specify how access modifiers and record members are indented.

  Possible values:

  - `IAMS_Never` (in configuration: `Never`)
    Use `AccessModifierOffset` for access modifiers and indent members one
    level below the record.

    ```c++
    struct S {
      int before;

    public:
      int after;
    };
    ```

  - `IAMS_Always` (in configuration: `Always`)
    Give access modifiers their own indentation level and indent all
    members two levels below the record. Value of the `AccessModifierOffset`
    is ignored.

    ```c++
    struct S {
        int before;

      public:
        int after;
    };
    ```

  - `IAMS_AfterFirstAccessModifier` (in configuration: `AfterFirstAccessModifier`)
    In C, C++, and Objective-C, indent members one level until the first
    explicit access modifier, then two levels. Other languages use the
    `Always` behavior. Value of the `AccessModifierOffset` is ignored.

    ```c++
    struct S {
      int before;

      public:
        int after;
    };
    ```



(indentcaseblocks)=

**IndentCaseBlocks** (`Boolean`) {versionbadge}`clang-format 11` {ref}`¶ <IndentCaseBlocks>`

: Indent case label blocks one level from the case label.

  When `false`, the block following the case label uses the same
  indentation level as for the case label, treating the case label the same
  as an if-statement.
  When `true`, the block gets indented as a scope block.

  ```c++
  false:                                 true:
  switch (fool) {                vs.     switch (fool) {
  case 1: {                              case 1:
    bar();                                 {
  } break;                                   bar();
  default: {                               }
    plop();                                break;
  }                                      default:
  }                                        {
                                             plop();
                                           }
                                         }
  ```

(indentcaselabels)=

**IndentCaseLabels** (`Boolean`) {versionbadge}`clang-format 3.3` {ref}`¶ <IndentCaseLabels>`

: Indent case labels one level from the switch statement.

  When `false`, use the same indentation level as for the switch
  statement. Switch statement body is always indented one level more than
  case labels (except the first block following the case label, which
  itself indents the code - unless IndentCaseBlocks is enabled).

  ```c++
  false:                                 true:
  switch (fool) {                vs.     switch (fool) {
  case 1:                                  case 1:
    bar();                                   bar();
    break;                                   break;
  default:                                 default:
    plop();                                  plop();
  }                                      }
  ```

(indentexportblock)=

**IndentExportBlock** (`Boolean`) {versionbadge}`clang-format 20` {ref}`¶ <IndentExportBlock>`

: If `true`, clang-format will indent the body of an `export { ... }`
  block. This doesn't affect the formatting of anything else related to
  exported declarations.

  ```c++
  true:                     false:
  export {          vs.     export {
    void foo();             void foo();
    void bar();             void bar();
  }                         }
  ```

(indentexternblock)=

**IndentExternBlock** (`IndentExternBlockStyle`) {versionbadge}`clang-format 11` {ref}`¶ <IndentExternBlock>`

: IndentExternBlockStyle is the type of indenting of extern blocks.

  Possible values:

  - `IEBS_AfterExternBlock` (in configuration: `AfterExternBlock`)
    Backwards compatible with AfterExternBlock's indenting.

    ```c++
    IndentExternBlock: AfterExternBlock
    BraceWrapping.AfterExternBlock: true
    extern "C"
    {
        void foo();
    }
    ```

    ```c++
    IndentExternBlock: AfterExternBlock
    BraceWrapping.AfterExternBlock: false
    extern "C" {
    void foo();
    }
    ```

  - `IEBS_NoIndent` (in configuration: `NoIndent`)
    Does not indent extern blocks.

    ```c++
    extern "C" {
    void foo();
    }
    ```

  - `IEBS_Indent` (in configuration: `Indent`)
    Indents extern blocks.

    ```c++
    extern "C" {
      void foo();
    }
    ```



(indentgotolabels)=

**IndentGotoLabels** (`IndentGotoLabelStyle`) {versionbadge}`clang-format 10` {ref}`¶ <IndentGotoLabels>`

: The goto label indenting style to use.

  Possible values:

  - `IGLS_NoIndent` (in configuration: `NoIndent`)
    Do not indent goto labels.

    ```c++
    int f() {
      if (foo()) {
    label1:
        bar();
      }
    label2:
      return 1;
    }
    ```

  - `IGLS_OuterIndent` (in configuration: `OuterIndent`)
    Indent goto labels to the enclosing block (previous indenting level).

    ```c++
    int f() {
      if (foo()) {
      label1:
        bar();
      }
    label2:
      return 1;
    }
    ```

  - `IGLS_InnerIndent` (in configuration: `InnerIndent`)
    Indent goto labels to the surrounding statements (current indenting
    level).

    ```c++
    int f() {
      if (foo()) {
        label1:
        bar();
      }
      label2:
      return 1;
    }
    ```

  - `IGLS_HalfIndent` (in configuration: `HalfIndent`)
    Indent goto labels to half the indentation of the surrounding code.
    If the indentation width is an odd number, it will round up.

    ```c++
    int f() {
      if (foo()) {
       label1:
        bar();
      }
     label2:
      return 1;
    }
    ```



(indentppdirectives)=

**IndentPPDirectives** (`PPDirectiveIndentStyle`) {versionbadge}`clang-format 6` {ref}`¶ <IndentPPDirectives>`

: The preprocessor directive indenting style to use.

  Possible values:

  - `PPDIS_None` (in configuration: `None`)
    Does not indent any directives.

    ```c++
    #if FOO
    #if BAR
    #include <foo>
    #endif
    #endif
    ```

  - `PPDIS_AfterHash` (in configuration: `AfterHash`)
    Indents directives after the hash.

    ```c++
    #if FOO
    #  if BAR
    #    include <foo>
    #  endif
    #endif
    ```

  - `PPDIS_BeforeHash` (in configuration: `BeforeHash`)
    Indents directives before the hash.

    ```c++
    #if FOO
      #if BAR
        #include <foo>
      #endif
    #endif
    ```

  - `PPDIS_Leave` (in configuration: `Leave`)
    Leaves indentation of directives as-is.

    :::{note}
    Ignores `PPIndentWidth`.
    :::

    ```c++
    #if FOO
      #if BAR
    #include <foo>
      #endif
    #endif
    ```



(indentrequiresclause)=

**IndentRequiresClause** (`Boolean`) {versionbadge}`clang-format 15` {ref}`¶ <IndentRequiresClause>`

: Indent the requires clause in a template. This only applies when
  `RequiresClausePosition` is `OwnLine`, `OwnLineWithBrace`,
  or `WithFollowing`.

  In clang-format 12, 13 and 14 it was named `IndentRequires`.

  ```c++
  true:
  template <typename It>
    requires Iterator<It>
  void sort(It begin, It end) {
    //....
  }

  false:
  template <typename It>
  requires Iterator<It>
  void sort(It begin, It end) {
    //....
  }
  ```

(indentwidth)=

**IndentWidth** (`Unsigned`) {versionbadge}`clang-format 3.7` {ref}`¶ <IndentWidth>`

: The number of columns to use for indentation.

  ```c++
  IndentWidth: 3

  void f() {
     someFunction();
     if (true, false) {
        f();
     }
  }
  ```

(indentwrappedfunctionnames)=

**IndentWrappedFunctionNames** (`Boolean`) {versionbadge}`clang-format 3.7` {ref}`¶ <IndentWrappedFunctionNames>`

: Indent if a function definition or declaration is wrapped after the
  type.

  ```c++
  true:
  LoooooooooooooooooooooooooooooooooooooooongReturnType
      LoooooooooooooooooooooooooooooooongFunctionDeclaration();

  false:
  LoooooooooooooooooooooooooooooooooooooooongReturnType
  LoooooooooooooooooooooooooooooooongFunctionDeclaration();
  ```

(insertbraces)=

**InsertBraces** (`Boolean`) {versionbadge}`clang-format 15` {ref}`¶ <InsertBraces>`

: Insert braces after control statements (`if`, `else`, `for`, `do`,
  and `while`) in C++ unless the control statements are inside macro
  definitions or the braces would enclose preprocessor directives.

  :::{warning}
  Setting this option to `true` could lead to incorrect code formatting
  due to clang-format's lack of complete semantic information. As such,
  extra care should be taken to review code changes made by this option.
  :::

  ```c++
  false:                                    true:

  if (isa<FunctionDecl>(D))        vs.      if (isa<FunctionDecl>(D)) {
    handleFunctionDecl(D);                    handleFunctionDecl(D);
  else if (isa<VarDecl>(D))                 } else if (isa<VarDecl>(D)) {
    handleVarDecl(D);                         handleVarDecl(D);
  else                                      } else {
    return;                                   return;
                                            }

  while (i--)                      vs.      while (i--) {
    for (auto *A : D.attrs())                 for (auto *A : D.attrs()) {
      handleAttr(A);                            handleAttr(A);
                                              }
                                            }

  do                               vs.      do {
    --i;                                      --i;
  while (i);                                } while (i);
  ```

(insertnewlineateof)=

**InsertNewlineAtEOF** (`Boolean`) {versionbadge}`clang-format 16` {ref}`¶ <InsertNewlineAtEOF>`

: Insert a newline at end of file if missing.

(inserttrailingcommas)=

**InsertTrailingCommas** (`TrailingCommaStyle`) {versionbadge}`clang-format 11` {ref}`¶ <InsertTrailingCommas>`

: If set to `TCS_Wrapped` will insert trailing commas in container
  literals (arrays and objects) that wrap across multiple lines.
  It is currently only available for JavaScript
  and disabled by default `TCS_None`.
  `InsertTrailingCommas` cannot be used together with `BinPackArguments`
  as inserting the comma disables bin-packing.

  ```c++
  TSC_Wrapped:
  const someArray = [
  aaaaaaaaaaaaaaaaaaaaaaaaaa,
  aaaaaaaaaaaaaaaaaaaaaaaaaa,
  aaaaaaaaaaaaaaaaaaaaaaaaaa,
  //                        ^ inserted
  ]
  ```

  Possible values:

  - `TCS_None` (in configuration: `None`)
    Do not insert trailing commas.

  - `TCS_Wrapped` (in configuration: `Wrapped`)
    Insert trailing commas in container literals that were wrapped over
    multiple lines. Note that this is conceptually incompatible with
    bin-packing, because the trailing comma is used as an indicator
    that a container should be formatted one-per-line (i.e. not bin-packed).
    So inserting a trailing comma counteracts bin-packing.



(integerliteralseparator)=

**IntegerLiteralSeparator** (`IntegerLiteralSeparatorStyle`) {versionbadge}`clang-format 16` {ref}`¶ <IntegerLiteralSeparator>`

: Format integer literal separators (`'` for C/C++ and `_` for C#, Java,
  and JavaScript).

  Nested configuration flags:

  Separator format of integer literals of different bases.

  If negative, remove separators. If  `0`, leave the literal as is. If
  positive, insert separators between digits starting from the rightmost
  digit.

  For example, the config below will leave separators in binary literals
  alone, insert separators in decimal literals to separate the digits into
  groups of 3, and remove separators in hexadecimal literals.

  ```c++
  IntegerLiteralSeparator:
    Binary: 0
    Decimal: 3
    Hex: -1
  ```

  You can also specify a minimum number of digits
  (`BinaryMinDigitsInsert`, `DecimalMinDigitsInsert`, and
  `HexMinDigitsInsert`) the integer literal must have in order for the
  separators to be inserted, and a maximum number of digits
  (`BinaryMaxDigitsRemove`, `DecimalMaxDigitsRemove`, and
  `HexMaxDigitsRemove`) until the separators are removed. This divides the
  literals in 3 regions, always without separator (up until including
  `xxxMaxDigitsRemove`), maybe with, or without separators (up until
  excluding `xxxMinDigitsInsert`), and finally always with separators.

  :::{note}
  `BinaryMinDigits`, `DecimalMinDigits`, and `HexMinDigits` are
  deprecated and renamed to `BinaryMinDigitsInsert`,
  `DecimalMinDigitsInsert`, and `HexMinDigitsInsert`, respectively.
  :::

  - `int8_t Binary` Format separators in binary literals.

    ```text
    /* -1: */ b = 0b100111101101;
    /*  0: */ b = 0b10011'11'0110'1;
    /*  3: */ b = 0b100'111'101'101;
    /*  4: */ b = 0b1001'1110'1101;
    ```

  - `int8_t BinaryMinDigitsInsert` Format separators in binary literals with a minimum number of digits.

    ```text
    // Binary: 3
    // BinaryMinDigitsInsert: 7
    b1 = 0b101101;
    b2 = 0b1'101'101;
    ```

  - `int8_t BinaryMaxDigitsRemove` Remove separators in binary literals with a maximum number of digits.

    ```text
    // Binary: 3
    // BinaryMinDigitsInsert: 7
    // BinaryMaxDigitsRemove: 4
    b0 = 0b1011; // Always removed.
    b1 = 0b101101; // Not added.
    b2 = 0b1'01'101; // Not removed, not corrected.
    b3 = 0b1'101'101; // Always added.
    b4 = 0b10'1101; // Corrected to 0b101'101.
    ```

  - `int8_t Decimal` Format separators in decimal literals.

    ```text
    /* -1: */ d = 18446744073709550592ull;
    /*  0: */ d = 184467'440737'0'95505'92ull;
    /*  3: */ d = 18'446'744'073'709'550'592ull;
    ```

  - `int8_t DecimalMinDigitsInsert` Format separators in decimal literals with a minimum number of digits.

    ```text
    // Decimal: 3
    // DecimalMinDigitsInsert: 5
    d1 = 2023;
    d2 = 10'000;
    ```

  - `int8_t DecimalMaxDigitsRemove` Remove separators in decimal literals with a maximum number of digits.

    ```text
    // Decimal: 3
    // DecimalMinDigitsInsert: 7
    // DecimalMaxDigitsRemove: 4
    d0 = 2023; // Always removed.
    d1 = 123456; // Not added.
    d2 = 1'23'456; // Not removed, not corrected.
    d3 = 5'000'000; // Always added.
    d4 = 1'23'45; // Corrected to 12'345.
    ```

  - `int8_t Hex` Format separators in hexadecimal literals.

    ```text
    /* -1: */ h = 0xDEADBEEFDEADBEEFuz;
    /*  0: */ h = 0xDEAD'BEEF'DE'AD'BEE'Fuz;
    /*  2: */ h = 0xDE'AD'BE'EF'DE'AD'BE'EFuz;
    ```

  - `int8_t HexMinDigitsInsert` Format separators in hexadecimal literals with a minimum number of
    digits.

    ```text
    // Hex: 2
    // HexMinDigitsInsert: 6
    h1 = 0xABCDE;
    h2 = 0xAB'CD'EF;
    ```

  - `int8_t HexMaxDigitsRemove` Remove separators in hexadecimal literals with a maximum number of
    digits.

    ```text
    // Hex: 2
    // HexMinDigitsInsert: 6
    // HexMaxDigitsRemove: 4
    h0 = 0xAFFE; // Always removed.
    h1 = 0xABCDE; // Not added.
    h2 = 0xABC'DE; // Not removed, not corrected.
    h3 = 0xAB'CD'EF; // Always added.
    h4 = 0xABCD'E; // Corrected to 0xA'BC'DE.
    ```


(javaimportgroups)=

**JavaImportGroups** (`List of Strings`) {versionbadge}`clang-format 8` {ref}`¶ <JavaImportGroups>`

: A vector of prefixes ordered by the desired groups for Java imports.

  One group's prefix can be a subset of another - the longest prefix is
  always matched. Within a group, the imports are ordered lexicographically.
  Static imports are grouped separately and follow the same group rules.
  By default, static imports are placed before non-static imports,
  but this behavior is changed by another option,
  `SortJavaStaticImport`.

  In the .clang-format configuration file, this can be configured like
  in the following yaml example. This will result in imports being
  formatted as in the Java example below.

  ```yaml
  JavaImportGroups: [com.example, com, org]
  ```

  ```java
  import static com.example.function1;

  import static com.test.function2;

  import static org.example.function3;

  import com.example.ClassA;
  import com.example.Test;
  import com.example.a.ClassB;

  import com.test.ClassC;

  import org.example.ClassD;
  ```

(javascriptquotes)=

**JavaScriptQuotes** (`JavaScriptQuoteStyle`) {versionbadge}`clang-format 3.9` {ref}`¶ <JavaScriptQuotes>`

: The JavaScriptQuoteStyle to use for JavaScript strings.

  Possible values:

  - `JSQS_Leave` (in configuration: `Leave`)
    Leave string quotes as they are.

    ```js
    string1 = "foo";
    string2 = 'bar';
    ```

  - `JSQS_Single` (in configuration: `Single`)
    Always use single quotes.

    ```js
    string1 = 'foo';
    string2 = 'bar';
    ```

  - `JSQS_Double` (in configuration: `Double`)
    Always use double quotes.

    ```js
    string1 = "foo";
    string2 = "bar";
    ```



(javascriptwrapimports)=

**JavaScriptWrapImports** (`Boolean`) {versionbadge}`clang-format 3.9` {ref}`¶ <JavaScriptWrapImports>`

: Whether to wrap JavaScript import/export statements.

  ```js
  true:
  import {
      VeryLongImportsAreAnnoying,
      VeryLongImportsAreAnnoying,
      VeryLongImportsAreAnnoying,
  } from "some/module.js"

  false:
  import {VeryLongImportsAreAnnoying, VeryLongImportsAreAnnoying, VeryLongImportsAreAnnoying,} from "some/module.js"
  ```

(keepemptylines)=

**KeepEmptyLines** (`KeepEmptyLinesStyle`) {versionbadge}`clang-format 19` {ref}`¶ <KeepEmptyLines>`

: Which empty lines are kept.  See `MaxEmptyLinesToKeep` for how many
  consecutive empty lines are kept.

  Nested configuration flags:

  Options regarding which empty lines are kept.

  For example, the config below will remove empty lines at start of the
  file, end of the file, and start of blocks.

  ```c++
  KeepEmptyLines:
    AtEndOfBlock: false
    AtEndOfFile: false
    AtStartOfBlock: false
    AtStartOfFile: false
  ```

  - `bool AtEndOfBlock` Keep empty lines at end of a block.

    ```c++
    true:                                  false:
    if (foo) {                     vs.     if (foo) {
      bar();                                 bar();
                                           }
    }
    ```

  - `bool AtEndOfFile` Keep empty lines at end of file.

  - `bool AtStartOfBlock` Keep empty lines at start of a block.

    ```c++
    true:                                  false:
    if (foo) {                     vs.     if (foo) {
                                             bar();
      bar();                               }
    }
    ```

  - `bool AtStartOfFile` Keep empty lines at start of file.


(keepemptylinesateof)=

**KeepEmptyLinesAtEOF** (`Boolean`) {versionbadge}`clang-format 17` {ref}`¶ <KeepEmptyLinesAtEOF>`

: This option is **deprecated**. See `AtEndOfFile` of `KeepEmptyLines`.

(keepemptylinesatthestartofblocks)=

**KeepEmptyLinesAtTheStartOfBlocks** (`Boolean`) {versionbadge}`clang-format 3.7` {ref}`¶ <KeepEmptyLinesAtTheStartOfBlocks>`

: This option is **deprecated**. See `AtStartOfBlock` of
  `KeepEmptyLines`.

(keepformfeed)=

**KeepFormFeed** (`Boolean`) {versionbadge}`clang-format 20` {ref}`¶ <KeepFormFeed>`

: Keep the form feed character if it's immediately preceded and followed by
  a newline. Multiple form feeds and newlines within a whitespace range are
  replaced with a single newline and form feed followed by the remaining
  newlines. (See
  www.gnu.org/prep/standards/html_node/Formatting.html#:~:text=formfeed.)

(lambdabodyindentation)=

**LambdaBodyIndentation** (`LambdaBodyIndentationKind`) {versionbadge}`clang-format 13` {ref}`¶ <LambdaBodyIndentation>`

: The indentation style of lambda bodies. `Signature` (the default)
  causes the lambda body to be indented one additional level relative to
  the indentation level of the signature. `OuterScope` forces the lambda
  body to be indented one additional level relative to the parent scope
  containing the lambda signature.

  Possible values:

  - `LBI_Signature` (in configuration: `Signature`)
    Align lambda body relative to the lambda signature. This is the default.

    ```c++
    someMethod(
        [](SomeReallyLongLambdaSignatureArgument foo) {
          return;
        });
    ```

  - `LBI_OuterScope` (in configuration: `OuterScope`)
    For statements within block scope, align lambda body relative to the
    indentation level of the outer scope the lambda signature resides in.

    ```c++
    someMethod(
        [](SomeReallyLongLambdaSignatureArgument foo) {
      return;
    });

    someMethod(someOtherMethod(
        [](SomeReallyLongLambdaSignatureArgument foo) {
      return;
    }));
    ```



(language)=

**Language** (`LanguageKind`) {versionbadge}`clang-format 3.5` {ref}`¶ <Language>`

: The language that this format style targets.

  :::{note}
  You can specify the language (`C`, `Cpp`, or `ObjC`) for `.h`
  files by adding a `// clang-format Language:` line before the first
  non-comment (and non-empty) line, e.g. `// clang-format Language: Cpp`.
  :::

  Possible values:

  - `LK_None` (in configuration: `None`)
    Do not use.

  - `LK_C` (in configuration: `C`)
    Should be used for C.

  - `LK_Cpp` (in configuration: `Cpp`)
    Should be used for C++.

  - `LK_CSharp` (in configuration: `CSharp`)
    Should be used for C#.

  - `LK_Java` (in configuration: `Java`)
    Should be used for Java.

  - `LK_JavaScript` (in configuration: `JavaScript`)
    Should be used for JavaScript.

  - `LK_Json` (in configuration: `Json`)
    Should be used for JSON.

  - `LK_ObjC` (in configuration: `ObjC`)
    Should be used for Objective-C, Objective-C++.

  - `LK_Proto` (in configuration: `Proto`)
    Should be used for [Protocol Buffers](https://protobuf.dev/)

  - `LK_TableGen` (in configuration: `TableGen`)
    Should be used for TableGen code.

  - `LK_TextProto` (in configuration: `TextProto`)
    Should be used for [Protocol Buffer](https://protobuf.dev/) messages in
    text format

  - `LK_Verilog` (in configuration: `Verilog`)
    Should be used for Verilog and SystemVerilog.
    https://standards.ieee.org/ieee/1800/6700/
    https://sci-hub.st/10.1109/IEEESTD.2018.8299595



(lineending)=

**LineEnding** (`LineEndingStyle`) {versionbadge}`clang-format 16` {ref}`¶ <LineEnding>`

: Line ending style (`\n` or `\r\n`) to use.

  Possible values:

  - `LE_LF` (in configuration: `LF`)
    Use `\n`.

  - `LE_CRLF` (in configuration: `CRLF`)
    Use `\r\n`.

  - `LE_DeriveLF` (in configuration: `DeriveLF`)
    Use `\n` unless the input has more lines ending in `\r\n`.

  - `LE_DeriveCRLF` (in configuration: `DeriveCRLF`)
    Use `\r\n` unless the input has more lines ending in `\n`.



(macroblockbegin)=

**MacroBlockBegin** (`String`) {versionbadge}`clang-format 3.7` {ref}`¶ <MacroBlockBegin>`

: A regular expression matching macros that start a block.

  ```c++
  # With:
  MacroBlockBegin: "^NS_MAP_BEGIN|\
  NS_TABLE_HEAD$"
  MacroBlockEnd: "^\
  NS_MAP_END|\
  NS_TABLE_.*_END$"

  NS_MAP_BEGIN
    foo();
  NS_MAP_END

  NS_TABLE_HEAD
    bar();
  NS_TABLE_FOO_END

  # Without:
  NS_MAP_BEGIN
  foo();
  NS_MAP_END

  NS_TABLE_HEAD
  bar();
  NS_TABLE_FOO_END
  ```

(macroblockend)=

**MacroBlockEnd** (`String`) {versionbadge}`clang-format 3.7` {ref}`¶ <MacroBlockEnd>`

: A regular expression matching macros that end a block.

(macros)=

**Macros** (`List of Strings`) {versionbadge}`clang-format 17` {ref}`¶ <Macros>`

: A list of macros of the form `<definition>=<expansion>` .

  Code will be parsed with macros expanded, in order to determine how to
  interpret and format the macro arguments.

  For example, the code:

  ```c++
  A(a*b);
  ```

  will usually be interpreted as a call to a function A, and the
  multiplication expression will be formatted as `a * b`.

  If we specify the macro definition:

  ```yaml
  Macros:
  - A(x)=x
  ```

  the code will now be parsed as a declaration of the variable b of type a*,
  and formatted as `a* b` (depending on pointer-binding rules).

  Features and restrictions:

  - Both function-like macros and object-like macros are supported.
  - Macro arguments must be used exactly once in the expansion.
  - No recursive expansion; macros referencing other macros will be
    ignored.
  - Overloading by arity is supported: for example, given the macro
    definitions A=x, A()=y, A(a)=a

  ```c++
  A; -> x;
  A(); -> y;
  A(z); -> z;
  A(a, b); // will not be expanded.
  ```

(macrosskippedbyremoveparentheses)=

**MacrosSkippedByRemoveParentheses** (`List of Strings`) {versionbadge}`clang-format 21` {ref}`¶ <MacrosSkippedByRemoveParentheses>`

: A vector of function-like macros whose invocations should be skipped by
  `RemoveParentheses`.

(mainincludechar)=

**MainIncludeChar** (`MainIncludeCharDiscriminator`) {versionbadge}`clang-format 19` {ref}`¶ <MainIncludeChar>`

: When guessing whether a #include is the "main" include, only the include
  directives that use the specified character are considered.

  Possible values:

  - `MICD_Quote` (in configuration: `Quote`)
    Main include uses quotes: `#include "foo.hpp"` (the default).

  - `MICD_AngleBracket` (in configuration: `AngleBracket`)
    Main include uses angle brackets: `#include <foo.hpp>`.

  - `MICD_Any` (in configuration: `Any`)
    Main include uses either quotes or angle brackets.



(maxemptylinestokeep)=

**MaxEmptyLinesToKeep** (`Unsigned`) {versionbadge}`clang-format 3.7` {ref}`¶ <MaxEmptyLinesToKeep>`

: The maximum number of consecutive empty lines to keep.

  ```c++
  MaxEmptyLinesToKeep: 1         vs.     MaxEmptyLinesToKeep: 0
  int f() {                              int f() {
    int = 1;                                 int i = 1;
                                             i = foo();
    i = foo();                               return i;
                                         }
    return i;
  }
  ```

(namespaceindentation)=

**NamespaceIndentation** (`NamespaceIndentationKind`) {versionbadge}`clang-format 3.7` {ref}`¶ <NamespaceIndentation>`

: The indentation used for namespaces.

  Possible values:

  - `NI_None` (in configuration: `None`)
    Don't indent in namespaces.

    ```c++
    namespace out {
    int i;
    namespace in {
    int i;
    }
    }
    ```

  - `NI_Inner` (in configuration: `Inner`)
    Indent only in inner namespaces (nested in other namespaces).

    ```c++
    namespace out {
    int i;
    namespace in {
      int i;
    }
    }
    ```

  - `NI_All` (in configuration: `All`)
    Indent in all namespaces.

    ```c++
    namespace out {
      int i;
      namespace in {
        int i;
      }
    }
    ```



(namespacemacros)=

**NamespaceMacros** (`List of Strings`) {versionbadge}`clang-format 9` {ref}`¶ <NamespaceMacros>`

: A vector of macros which are used to open namespace blocks.

  These are expected to be macros of the form:

  ```c++
  NAMESPACE(<namespace-name>, ...) {
    <namespace-content>
  }
  ```

  For example: TESTSUITE

(numericliteralcase)=

**NumericLiteralCase** (`NumericLiteralCaseStyle`) {versionbadge}`clang-format 22` {ref}`¶ <NumericLiteralCase>`

: Capitalization style for numeric literals.

  Nested configuration flags:

  Separate control for each numeric literal component.

  For example, the config below will leave exponent letters alone, reformat
  hexadecimal digits in lowercase, reformat numeric literal prefixes in
  uppercase, and reformat suffixes in lowercase.

  ```c++
  NumericLiteralCase:
    ExponentLetter: Leave
    HexDigit: Lower
    Prefix: Upper
    Suffix: Lower
  ```

  - `NumericLiteralComponentStyle ExponentLetter`
    Format floating point exponent separator letter case.

    ```c++
    float a = 6.02e23 + 1.0E10; // Leave
    float a = 6.02E23 + 1.0E10; // Upper
    float a = 6.02e23 + 1.0e10; // Lower
    ```

    Possible values:

    - `NLCS_Leave` (in configuration: `Leave`)
      Leave this component of the literal as is.

    - `NLCS_Upper` (in configuration: `Upper`)
      Format this component with uppercase characters.

    - `NLCS_Lower` (in configuration: `Lower`)
      Format this component with lowercase characters.


  - `NumericLiteralComponentStyle HexDigit`
    Format hexadecimal digit case.

    ```c++
    a = 0xaBcDeF; // Leave
    a = 0xABCDEF; // Upper
    a = 0xabcdef; // Lower
    ```

    Possible values:

    - `NLCS_Leave` (in configuration: `Leave`)
      Leave this component of the literal as is.

    - `NLCS_Upper` (in configuration: `Upper`)
      Format this component with uppercase characters.

    - `NLCS_Lower` (in configuration: `Lower`)
      Format this component with lowercase characters.


  - `NumericLiteralComponentStyle Prefix`
    Format integer prefix case.

    ```c++
    a = 0XF0 | 0b1; // Leave
    a = 0XF0 | 0B1; // Upper
    a = 0xF0 | 0b1; // Lower
    ```

    Possible values:

    - `NLCS_Leave` (in configuration: `Leave`)
      Leave this component of the literal as is.

    - `NLCS_Upper` (in configuration: `Upper`)
      Format this component with uppercase characters.

    - `NLCS_Lower` (in configuration: `Lower`)
      Format this component with lowercase characters.


  - `NumericLiteralComponentStyle Suffix`
    Format suffix case. This option excludes case-sensitive reserved
    suffixes, such as `min` in C++.

    ```c++
    a = 1uLL; // Leave
    a = 1ULL; // Upper
    a = 1ull; // Lower
    ```

    Possible values:

    - `NLCS_Leave` (in configuration: `Leave`)
      Leave this component of the literal as is.

    - `NLCS_Upper` (in configuration: `Upper`)
      Format this component with uppercase characters.

    - `NLCS_Lower` (in configuration: `Lower`)
      Format this component with lowercase characters.



(objcbinpackprotocollist)=

**ObjCBinPackProtocolList** (`BinPackStyle`) {versionbadge}`clang-format 7` {ref}`¶ <ObjCBinPackProtocolList>`

: Controls bin-packing Objective-C protocol conformance list
  items into as few lines as possible when they go over `ColumnLimit`.

  If `Auto` (the default), delegates to the value in
  `BinPackParameters`. If that is `BinPack`, bin-packs Objective-C
  protocol conformance list items into as few lines as possible
  whenever they go over `ColumnLimit`.

  If `Always`, always bin-packs Objective-C protocol conformance
  list items into as few lines as possible whenever they go over
  `ColumnLimit`.

  If `Never`, lays out Objective-C protocol conformance list items
  onto individual lines whenever they go over `ColumnLimit`.

  ```objc
  Always (or Auto, if BinPackParameters==BinPack):
  @interface ccccccccccccc () <
      ccccccccccccc, ccccccccccccc,
      ccccccccccccc, ccccccccccccc> {
  }

  Never (or Auto, if BinPackParameters!=BinPack):
  @interface ddddddddddddd () <
      ddddddddddddd,
      ddddddddddddd,
      ddddddddddddd,
      ddddddddddddd> {
  }
  ```

  Possible values:

  - `BPS_Auto` (in configuration: `Auto`)
    Automatically determine parameter bin-packing behavior.

  - `BPS_Always` (in configuration: `Always`)
    Always bin-pack parameters.

  - `BPS_Never` (in configuration: `Never`)
    Never bin-pack parameters.



(objcblockindentwidth)=

**ObjCBlockIndentWidth** (`Unsigned`) {versionbadge}`clang-format 3.7` {ref}`¶ <ObjCBlockIndentWidth>`

: The number of characters to use for indentation of ObjC blocks.

  ```objc
  ObjCBlockIndentWidth: 4

  [operation setCompletionBlock:^{
      [self onOperationDone];
  }];
  ```

(objcbreakbeforenestedblockparam)=

**ObjCBreakBeforeNestedBlockParam** (`Boolean`) {versionbadge}`clang-format 11` {ref}`¶ <ObjCBreakBeforeNestedBlockParam>`

: Break parameters list into lines when there is nested block
  parameters in a function call.

  ```c++
  false:
   - (void)_aMethod
   {
       [self.test1 t:self w:self callback:^(typeof(self) self, NSNumber
       *u, NSNumber *v) {
           u = c;
       }]
   }
   true:
   - (void)_aMethod
   {
      [self.test1 t:self
                   w:self
          callback:^(typeof(self) self, NSNumber *u, NSNumber *v) {
               u = c;
           }]
   }
  ```

(objcpropertyattributeorder)=

**ObjCPropertyAttributeOrder** (`List of Strings`) {versionbadge}`clang-format 18` {ref}`¶ <ObjCPropertyAttributeOrder>`

: The order in which ObjC property attributes should appear.

  Attributes in code will be sorted in the order specified. Any attributes
  encountered that are not mentioned in this array will be sorted last, in
  stable order. Comments between attributes will leave the attributes
  untouched.

  :::{warning}
  Using this option could lead to incorrect code formatting due to
  clang-format's lack of complete semantic information. As such, extra
  care should be taken to review code changes made by this option.
  :::

  ```yaml
  ObjCPropertyAttributeOrder: [
      class, direct,
      atomic, nonatomic,
      assign, retain, strong, copy, weak, unsafe_unretained,
      readonly, readwrite, getter, setter,
      nullable, nonnull, null_resettable, null_unspecified
  ]
  ```

(objcspaceaftermethoddeclarationprefix)=

**ObjCSpaceAfterMethodDeclarationPrefix** (`Boolean`) {versionbadge}`clang-format 23` {ref}`¶ <ObjCSpaceAfterMethodDeclarationPrefix>`

: Add or remove a space between the '-'/'+' and the return type in
  Objective-C method declarations. i.e

  ```objc
  false:                      true:

  -(void)method      vs.      - (void)method
  ```

(objcspaceafterproperty)=

**ObjCSpaceAfterProperty** (`Boolean`) {versionbadge}`clang-format 3.7` {ref}`¶ <ObjCSpaceAfterProperty>`

: Add a space after `@property` in Objective-C, i.e. use
  `@property (readonly)` instead of `@property(readonly)`.

(objcspacebeforeprotocollist)=

**ObjCSpaceBeforeProtocolList** (`Boolean`) {versionbadge}`clang-format 3.7` {ref}`¶ <ObjCSpaceBeforeProtocolList>`

: Add a space in front of an Objective-C protocol list, i.e. use
  `Foo <Protocol>` instead of `Foo<Protocol>`.

(onelineformatoffregex)=

**OneLineFormatOffRegex** (`String`) {versionbadge}`clang-format 21` {ref}`¶ <OneLineFormatOffRegex>`

: A regular expression that describes markers for turning formatting off for
  one line. If it matches a comment that is the only token of a line,
  clang-format skips the comment and the next line. Otherwise, clang-format
  skips lines containing a matched token.

  :::{note}
  This option does not apply to `IntegerLiteralSeparator` and
  `NumericLiteralCase`.
  :::

  ```c++
  // OneLineFormatOffRegex: ^(// NOLINT|logger$)
  // results in the output below:
  int a;
  int b ;  // NOLINT
  int c;
   // NOLINTNEXTLINE
  int d ;
  int e;
  s = "// NOLINT";
   logger() ;
  logger2();
  my_logger();
  ```

(ppindentwidth)=

**PPIndentWidth** (`Integer`) {versionbadge}`clang-format 13` {ref}`¶ <PPIndentWidth>`

: The number of columns to use for indentation of preprocessor statements.
  When set to -1 (default) `IndentWidth` is used also for preprocessor
  statements.

  ```c++
  PPIndentWidth: 1

  #ifdef __linux__
  # define FOO
  #else
  # define BAR
  #endif
  ```

(packarguments)=

**PackArguments** (`PackArgumentsStyle`) {versionbadge}`clang-format 23` {ref}`¶ <PackArguments>`

: Options related to packing arguments of function calls.

  Nested configuration flags:

  Options related to packing arguments of function calls.

  - `BinPackArgumentsStyle BinPack` {versionbadge}`clang-format 3.7`

    The bin pack arguments style to use.

    Possible values:

    - `BPAS_BinPack` (in configuration: `BinPack`)
      Bin-pack arguments.

      ```c++
      void f() {
        f(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaa,
          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);
      }
      ```

    - `BPAS_OnePerLine` (in configuration: `OnePerLine`)
      Put all arguments on the current line if they fit.
      Otherwise, put each one on its own line.

      ```c++
      void f() {
        f(aaaaaaaaaaaaaaaaaaaa,
          aaaaaaaaaaaaaaaaaaaa,
          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);
      }
      ```

    - `BPAS_UseBreakAfter` (in configuration: `UseBreakAfter`)
      Use the `BreakAfter` option to handle argument packing instead.
      If the `BreakAfter` limit is not exceeded, behave like `BinPack`.


  - `unsigned BreakAfter` {versionbadge}`clang-format 23` An argument list with more arguments than the specified number will be
    formatted with one argument per line. This option must be used with
    `BinPack: UseBreakAfter`.

    ```c++
    PackArguments:
      BinPack: UseBreakAfter
      BreakAfter: 3

    void f() {
      foo(1);

      bar(1, 2, 3);

      baz(1,
          2,
          3,
          4);
    }
    ```


(packconstructorinitializers)=

**PackConstructorInitializers** (`PackConstructorInitializersStyle`) {versionbadge}`clang-format 14` {ref}`¶ <PackConstructorInitializers>`

: The pack constructor initializers style to use.

  Possible values:

  - `PCIS_Never` (in configuration: `Never`)
    Always put each constructor initializer on its own line.

    ```c++
    Constructor()
        : a(),
          b()
    ```

  - `PCIS_BinPack` (in configuration: `BinPack`)
    Bin-pack constructor initializers.

    ```c++
    Constructor()
        : aaaaaaaaaaaaaaaaaaaa(), bbbbbbbbbbbbbbbbbbbb(),
          cccccccccccccccccccc()
    ```

  - `PCIS_CurrentLine` (in configuration: `CurrentLine`)
    Put all constructor initializers on the current line if they fit.
    Otherwise, put each one on its own line.

    ```c++
    Constructor() : a(), b()

    Constructor()
        : aaaaaaaaaaaaaaaaaaaa(),
          bbbbbbbbbbbbbbbbbbbb(),
          ddddddddddddd()
    ```

  - `PCIS_NextLine` (in configuration: `NextLine`)
    Same as `PCIS_CurrentLine` except that if all constructor initializers
    do not fit on the current line, try to fit them on the next line.

    ```c++
    Constructor() : a(), b()

    Constructor()
        : aaaaaaaaaaaaaaaaaaaa(), bbbbbbbbbbbbbbbbbbbb(), ddddddddddddd()

    Constructor()
        : aaaaaaaaaaaaaaaaaaaa(),
          bbbbbbbbbbbbbbbbbbbb(),
          cccccccccccccccccccc()
    ```

  - `PCIS_NextLineOnly` (in configuration: `NextLineOnly`)
    Put all constructor initializers on the next line if they fit.
    Otherwise, put each one on its own line.

    ```c++
    Constructor()
        : a(), b()

    Constructor()
        : aaaaaaaaaaaaaaaaaaaa(), bbbbbbbbbbbbbbbbbbbb(), ddddddddddddd()

    Constructor()
        : aaaaaaaaaaaaaaaaaaaa(),
          bbbbbbbbbbbbbbbbbbbb(),
          cccccccccccccccccccc()
    ```



(packparameters)=

**PackParameters** (`PackParametersStyle`) {versionbadge}`clang-format 23` {ref}`¶ <PackParameters>`

: Options related to packing parameters of function declarations and
  definitions.

  Nested configuration flags:

  Options related to packing parameters of function declarations and
  definitions.

  - `BinPackParametersStyle BinPack` {versionbadge}`clang-format 3.7`

    The bin pack parameters style to use.

    Possible values:

    - `BPPS_BinPack` (in configuration: `BinPack`)
      Bin-pack parameters.

      ```c++
      void f(int a, int bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,
             int ccccccccccccccccccccccccccccccccccccccccccc);
      ```

    - `BPPS_OnePerLine` (in configuration: `OnePerLine`)
      Put all parameters on the current line if they fit.
      Otherwise, put each one on its own line.

      ```c++
      void f(int a, int b, int c);

      void f(int a,
             int b,
             int ccccccccccccccccccccccccccccccccccccc);
      ```

    - `BPPS_AlwaysOnePerLine` (in configuration: `AlwaysOnePerLine`)
      Always put each parameter on its own line.

      ```c++
      void f(int a,
             int b,
             int c);
      ```

    - `BPPS_UseBreakAfter` (in configuration: `UseBreakAfter`)
      Use the `BreakAfter` option to handle parameter packing instead.
      If the `BreakAfter` limit is not exceeded, behave like `BinPack`.


  - `unsigned BreakAfter` {versionbadge}`clang-format 23` A parameter list with more parameters than the specified number will be
    formatted with one parameter per line. This option must be used with
    `BinPack: UseBreakAfter`.

    ```c++
    PackParameters:
      BinPack: UseBreakAfter
      BreakAfter: 3

    void foo(int a);

    void bar(int a, int b, int c);

    void baz(int a,
             int b,
             int c,
             int d);
    ```


(penaltybreakassignment)=

**PenaltyBreakAssignment** (`Unsigned`) {versionbadge}`clang-format 5` {ref}`¶ <PenaltyBreakAssignment>`

: The penalty for breaking around an assignment operator.

(penaltybreakbeforefirstcallparameter)=

**PenaltyBreakBeforeFirstCallParameter** (`Unsigned`) {versionbadge}`clang-format 3.7` {ref}`¶ <PenaltyBreakBeforeFirstCallParameter>`

: The penalty for breaking a function call after `call(`.

(penaltybreakbeforememberaccess)=

**PenaltyBreakBeforeMemberAccess** (`Unsigned`) {versionbadge}`clang-format 20` {ref}`¶ <PenaltyBreakBeforeMemberAccess>`

: The penalty for breaking before a member access operator (`.`, `->`).

(penaltybreakcomment)=

**PenaltyBreakComment** (`Unsigned`) {versionbadge}`clang-format 3.7` {ref}`¶ <PenaltyBreakComment>`

: The penalty for each line break introduced inside a comment.

(penaltybreakfirstlessless)=

**PenaltyBreakFirstLessLess** (`Unsigned`) {versionbadge}`clang-format 3.7` {ref}`¶ <PenaltyBreakFirstLessLess>`

: The penalty for breaking before the first `<<`.

(penaltybreakopenparenthesis)=

**PenaltyBreakOpenParenthesis** (`Unsigned`) {versionbadge}`clang-format 14` {ref}`¶ <PenaltyBreakOpenParenthesis>`

: The penalty for breaking after `(`.

(penaltybreakscoperesolution)=

**PenaltyBreakScopeResolution** (`Unsigned`) {versionbadge}`clang-format 18` {ref}`¶ <PenaltyBreakScopeResolution>`

: The penalty for breaking after `::`.

(penaltybreakstring)=

**PenaltyBreakString** (`Unsigned`) {versionbadge}`clang-format 3.7` {ref}`¶ <PenaltyBreakString>`

: The penalty for each line break introduced inside a string literal.

(penaltybreaktemplatedeclaration)=

**PenaltyBreakTemplateDeclaration** (`Unsigned`) {versionbadge}`clang-format 7` {ref}`¶ <PenaltyBreakTemplateDeclaration>`

: The penalty for breaking after template declaration.

(penaltyexcesscharacter)=

**PenaltyExcessCharacter** (`Unsigned`) {versionbadge}`clang-format 3.7` {ref}`¶ <PenaltyExcessCharacter>`

: The penalty for each character outside of the column limit.

(penaltyindentedwhitespace)=

**PenaltyIndentedWhitespace** (`Unsigned`) {versionbadge}`clang-format 12` {ref}`¶ <PenaltyIndentedWhitespace>`

: Penalty for each character of whitespace indentation
  (counted relative to leading non-whitespace column).

(penaltyreturntypeonitsownline)=

**PenaltyReturnTypeOnItsOwnLine** (`Unsigned`) {versionbadge}`clang-format 3.7` {ref}`¶ <PenaltyReturnTypeOnItsOwnLine>`

: Penalty for putting the return type of a function onto its own line.

(pointeralignment)=

**PointerAlignment** (`PointerAlignmentStyle`) {versionbadge}`clang-format 3.7` {ref}`¶ <PointerAlignment>`

: Pointer and reference alignment style.

  Possible values:

  - `PAS_Left` (in configuration: `Left`)
    Align pointer to the left.

    ```c++
    int* a;
    ```

  - `PAS_Right` (in configuration: `Right`)
    Align pointer to the right.

    ```c++
    int *a;
    ```

  - `PAS_Middle` (in configuration: `Middle`)
    Align pointer in the middle.

    ```c++
    int * a;
    ```



(qualifieralignment)=

**QualifierAlignment** (`QualifierAlignmentStyle`) {versionbadge}`clang-format 14` {ref}`¶ <QualifierAlignment>`

: Different ways to arrange specifiers and qualifiers (e.g. const/volatile).

  :::{warning}
  Setting `QualifierAlignment`  to something other than `Leave`, COULD
  lead to incorrect code formatting due to incorrect decisions made due to
  clang-formats lack of complete semantic information.
  As such extra care should be taken to review code changes made by the use
  of this option.
  :::

  Possible values:

  - `QAS_Leave` (in configuration: `Leave`)
    Don't change specifiers/qualifiers to either Left or Right alignment
    (default).

    ```c++
    int const a;
    const int *a;
    ```

  - `QAS_Left` (in configuration: `Left`)
    Change specifiers/qualifiers to be left-aligned.

    ```c++
    const int a;
    const int *a;
    ```

  - `QAS_Right` (in configuration: `Right`)
    Change specifiers/qualifiers to be right-aligned.

    ```c++
    int const a;
    int const *a;
    ```

  - `QAS_Custom` (in configuration: `Custom`)
    Change specifiers/qualifiers to be aligned based on `QualifierOrder`.
    With:

    ```yaml
    QualifierOrder: [inline, static, type, const]
    ```

    ```c++

    int const a;
    int const *a;
    ```



(qualifierorder)=

**QualifierOrder** (`List of Strings`) {versionbadge}`clang-format 14` {ref}`¶ <QualifierOrder>`

: The order in which the qualifiers appear.
  The order is an array that can contain any of the following:

    - `const`
    - `inline`
    - `static`
    - `friend`
    - `constexpr`
    - `volatile`
    - `restrict`
    - `typedef`
    - `consteval`
    - `constinit`
    - `thread_local`
    - `extern`
    - `mutable`
    - `signed`
    - `unsigned`
    - `long`
    - `short`
    - `explicit`
    - `type`

  :::{note}
  It must contain `type`.
  :::

  Items to the left of `type` will be placed to the left of the type and
  aligned in the order supplied. Items to the right of `type` will be
  placed to the right of the type and aligned in the order supplied.
  If only one of `signed` and `unsigned` is specified, both are placed at
  that position. The same applies to `long` and `short`. Specifying both
  members of a pair allows them to be placed independently.

  ```yaml
  QualifierOrder: [inline, static, type, const, volatile]
  ```

(rawstringformats)=

**RawStringFormats** (`List of RawStringFormats`) {versionbadge}`clang-format 6` {ref}`¶ <RawStringFormats>`

: Defines hints for detecting supported languages code blocks in raw
  strings.

  A raw string with a matching delimiter or a matching enclosing function
  name will be reformatted assuming the specified language based on the
  style for that language defined in the .clang-format file. If no style has
  been defined in the .clang-format file for the specific language, a
  predefined style given by `BasedOnStyle` is used. If `BasedOnStyle` is
  not found, the formatting is based on `LLVM` style. A matching delimiter
  takes precedence over a matching enclosing function name for determining
  the language of the raw string contents.

  If a canonical delimiter is specified, occurrences of other delimiters for
  the same language will be updated to the canonical if possible.

  There should be at most one specification per language and each delimiter
  and enclosing function should not occur in multiple specifications.

  To configure this in the .clang-format file, use:

  ```yaml
  RawStringFormats:
    - Language: TextProto
        Delimiters:
          - pb
          - proto
        EnclosingFunctions:
          - PARSE_TEXT_PROTO
        BasedOnStyle: google
    - Language: Cpp
        Delimiters:
          - cc
          - cpp
        BasedOnStyle: LLVM
        CanonicalDelimiter: cc
  ```

(referencealignment)=

**ReferenceAlignment** (`ReferenceAlignmentStyle`) {versionbadge}`clang-format 13` {ref}`¶ <ReferenceAlignment>`

: Reference alignment style (overrides `PointerAlignment` for references).

  Possible values:

  - `RAS_Pointer` (in configuration: `Pointer`)
    Align reference like `PointerAlignment`.

  - `RAS_Left` (in configuration: `Left`)
    Align reference to the left.

    ```c++
    int& a;
    ```

  - `RAS_Right` (in configuration: `Right`)
    Align reference to the right.

    ```c++
    int &a;
    ```

  - `RAS_Middle` (in configuration: `Middle`)
    Align reference in the middle.

    ```c++
    int & a;
    ```



(reflowcomments)=

**ReflowComments** (`ReflowCommentsStyle`) {versionbadge}`clang-format 3.8` {ref}`¶ <ReflowComments>`

: Comment reformatting style.

  Possible values:

  - `RCS_Never` (in configuration: `Never`)
    Leave comments untouched.

    ```c++
    // veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with plenty of information
    /* second veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with plenty of information */
    /* third veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with plenty of information
         - and a misaligned second line */
    ```

  - `RCS_IndentOnly` (in configuration: `IndentOnly`)
    Only apply indentation rules, moving comments left or right, without
    changing formatting inside the comments.

    ```c++
    // veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with plenty of information
    /* second veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with plenty of information */
    /* third veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with plenty of information
     - and a misaligned second line */
    ```

  - `RCS_Always` (in configuration: `Always`)
    Apply indentation rules and reflow long comments into new lines, trying
    to obey the `ColumnLimit`.

    ```c++
    // veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with plenty of
    // information
    /* second veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with plenty of
     - information */
    /* third veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with plenty of
     - information and a misaligned second line */
    ```



(removebracesllvm)=

**RemoveBracesLLVM** (`Boolean`) {versionbadge}`clang-format 14` {ref}`¶ <RemoveBracesLLVM>`

: Remove optional braces of control statements (`if`, `else`, `for`,
  and `while`) in C++ according to the LLVM coding style.

  :::{warning}
  This option will be renamed and expanded to support other styles.
  :::

  :::{warning}
  Setting this option to `true` could lead to incorrect code formatting
  due to clang-format's lack of complete semantic information. As such,
  extra care should be taken to review code changes made by this option.
  :::

  ```
/* Detailed source-code truncated for AI context efficiency. */
```

(removeemptylinesinunwrappedlines)=

**RemoveEmptyLinesInUnwrappedLines** (`Boolean`) {versionbadge}`clang-format 20` {ref}`¶ <RemoveEmptyLinesInUnwrappedLines>`

: Remove empty lines within unwrapped lines.

  ```c++
  false:                            true:

  int c                  vs.        int c = a + b;

      = a + b;

  enum : unsigned        vs.        enum : unsigned {
                                      AA = 0,
  {                                   BB
    AA = 0,                         } myEnum;
    BB
  } myEnum;

  while (                vs.        while (true) {
                                    }
      true) {
  }
  ```

(removeparentheses)=

**RemoveParentheses** (`RemoveParenthesesStyle`) {versionbadge}`clang-format 17` {ref}`¶ <RemoveParentheses>`

: Remove redundant parentheses.

  :::{warning}
  Setting this option to any value other than `Leave` could lead to
  incorrect code formatting due to clang-format's lack of complete semantic
  information. As such, extra care should be taken to review code changes
  made by this option.
  :::

  Possible values:

  - `RPS_Leave` (in configuration: `Leave`)
    Do not remove parentheses.

    ```c++
    class __declspec((dllimport)) X {};
    co_return (((0)));
    return ((a + b) - ((c + d)));
    ```

  - `RPS_MultipleParentheses` (in configuration: `MultipleParentheses`)
    Replace multiple parentheses with single parentheses.

    ```c++
    class __declspec(dllimport) X {};
    co_return (0);
    return ((a + b) - (c + d));
    ```

  - `RPS_ReturnStatement` (in configuration: `ReturnStatement`)
    Also remove parentheses enclosing the expression in a
    `return`/`co_return` statement.

    ```c++
    class __declspec(dllimport) X {};
    co_return 0;
    return (a + b) - (c + d);
    ```



(removesemicolon)=

**RemoveSemicolon** (`Boolean`) {versionbadge}`clang-format 16` {ref}`¶ <RemoveSemicolon>`

: Remove semicolons after the closing braces of functions and
  constructors/destructors.

  :::{warning}
  Setting this option to `true` could lead to incorrect code formatting
  due to clang-format's lack of complete semantic information. As such,
  extra care should be taken to review code changes made by this option.
  :::

  ```c++
  false:                                     true:

  int max(int a, int b) {                    int max(int a, int b) {
    return a > b ? a : b;                      return a > b ? a : b;
  };                                         }

  ```

(requiresclauseposition)=

**RequiresClausePosition** (`RequiresClausePositionStyle`) {versionbadge}`clang-format 15` {ref}`¶ <RequiresClausePosition>`

: The position of the `requires` clause.

  Possible values:

  - `RCPS_OwnLine` (in configuration: `OwnLine`)
    Always put the `requires` clause on its own line (possibly followed by
    a semicolon).

    ```c++
    template <typename T>
      requires C<T>
    struct Foo {...

    template <typename T>
    void bar(T t)
      requires C<T>;

    template <typename T>
      requires C<T>
    void bar(T t) {...

    template <typename T>
    void baz(T t)
      requires C<T>
    {...
    ```

  - `RCPS_OwnLineWithBrace` (in configuration: `OwnLineWithBrace`)
    As with `OwnLine`, except, unless otherwise prohibited, place a
    following open brace (of a function definition) to follow on the same
    line.

    ```c++
    void bar(T t)
      requires C<T> {
      return;
    }

    void bar(T t)
      requires C<T> {}

    template <typename T>
      requires C<T>
    void baz(T t) {
      ...
    ```

  - `RCPS_WithPreceding` (in configuration: `WithPreceding`)
    Try to put the clause together with the preceding part of a declaration.
    For class templates: stick to the template declaration.
    For function templates: stick to the template declaration.
    For function declaration followed by a requires clause: stick to the
    parameter list.

    ```c++
    template <typename T> requires C<T>
    struct Foo {...

    template <typename T> requires C<T>
    void bar(T t) {...

    template <typename T>
    void baz(T t) requires C<T>
    {...
    ```

  - `RCPS_WithFollowing` (in configuration: `WithFollowing`)
    Try to put the `requires` clause together with the class or function
    declaration.

    ```c++
    template <typename T>
    requires C<T> struct Foo {...

    template <typename T>
    requires C<T> void bar(T t) {...

    template <typename T>
    void baz(T t)
    requires C<T> {...
    ```

  - `RCPS_SingleLine` (in configuration: `SingleLine`)
    Try to put everything in the same line if possible. Otherwise normal
    line breaking rules take over.

    ```c++
    // Fitting:
    template <typename T> requires C<T> struct Foo {...

    template <typename T> requires C<T> void bar(T t) {...

    template <typename T> void bar(T t) requires C<T> {...

    // Not fitting, one possible example:
    template <typename LongName>
    requires C<LongName>
    struct Foo {...

    template <typename LongName>
    requires C<LongName>
    void bar(LongName ln) {

    template <typename LongName>
    void bar(LongName ln)
        requires C<LongName> {
    ```



(requiresexpressionindentation)=

**RequiresExpressionIndentation** (`RequiresExpressionIndentationKind`) {versionbadge}`clang-format 16` {ref}`¶ <RequiresExpressionIndentation>`

: The indentation used for requires expression bodies.

  Possible values:

  - `REI_OuterScope` (in configuration: `OuterScope`)
    Align requires expression body relative to the indentation level of the
    outer scope the requires expression resides in.
    This is the default.

    ```c++
    template <typename T>
    concept C = requires(T t) {
      ...
    }
    ```

  - `REI_Keyword` (in configuration: `Keyword`)
    Align requires expression body relative to the `requires` keyword.

    ```c++
    template <typename T>
    concept C = requires(T t) {
                  ...
                }
    ```



(separatedefinitionblocks)=

**SeparateDefinitionBlocks** (`SeparateDefinitionStyle`) {versionbadge}`clang-format 14` {ref}`¶ <SeparateDefinitionBlocks>`

: Specifies the use of empty lines to separate definition blocks, including
  classes, structs, enums, and functions.

  ```
/* Detailed source-code truncated for AI context efficiency. */
```

  Possible values:

  - `SDS_Leave` (in configuration: `Leave`)
    Leave definition blocks as they are.

  - `SDS_Always` (in configuration: `Always`)
    Insert an empty line between definition blocks.

  - `SDS_Never` (in configuration: `Never`)
    Remove any empty line between definition blocks.



(shortnamespacelines)=

**ShortNamespaceLines** (`Unsigned`) {versionbadge}`clang-format 13` {ref}`¶ <ShortNamespaceLines>`

: The maximal number of unwrapped lines that a short namespace spans.
  Defaults to 1.

  This determines the maximum length of short namespaces by counting
  unwrapped lines (i.e. containing neither opening nor closing
  namespace brace) and makes `FixNamespaceComments` omit adding
  end comments for those.

  ```c++
  ShortNamespaceLines: 1     vs.     ShortNamespaceLines: 0
  namespace a {                      namespace a {
    int foo;                           int foo;
  }                                  } // namespace a

  ShortNamespaceLines: 1     vs.     ShortNamespaceLines: 0
  namespace b {                      namespace b {
    int foo;                           int foo;
    int bar;                           int bar;
  } // namespace b                   } // namespace b
  ```

(skipmacrodefinitionbody)=

**SkipMacroDefinitionBody** (`Boolean`) {versionbadge}`clang-format 18` {ref}`¶ <SkipMacroDefinitionBody>`

: Do not format macro definition body.

(sortincludes)=

**SortIncludes** (`SortIncludesOptions`) {versionbadge}`clang-format 3.8` {ref}`¶ <SortIncludes>`

: Controls if and how clang-format will sort `#includes`.

  Nested configuration flags:

  Includes sorting options.

  - `bool Enabled` If `true`, includes are sorted based on the other suboptions below.
    (`Never` is deprecated by `Enabled: false`.)

  - `bool IgnoreCase` Whether or not includes are sorted in a case-insensitive fashion.
    (`CaseSensitive` and `CaseInsensitive` are deprecated by
    `IgnoreCase: false` and `IgnoreCase: true`, respectively.)

    ```c++
    true:                      false:
    #include "A/B.h"    vs.    #include "A/B.h"
    #include "A/b.h"           #include "A/b.h"
    #include "a/b.h"           #include "B/A.h"
    #include "B/A.h"           #include "B/a.h"
    #include "B/a.h"           #include "a/b.h"
    ```

  - `bool IgnoreExtension` When sorting includes in each block, only take file extensions into
    account if two includes compare equal otherwise.

    ```c++
    true:                          false:
    # include "A.h"         vs.    # include "A-util.h"
    # include "A.inc"              # include "A.h"
    # include "A-util.h"           # include "A.inc"
    ```

  - `bool Natural` Whether or not includes are sorted by natural ordering i.e., whether
    embedded runs of digits are compared as numbers rather than sequences of
    characters.

    ```c++
    true:                      false:
    #include "A2.h"     vs.    #include "A10.h"
    #include "A10.h"           #include "A2.h"
    ```

  - `bool FilesBeforeFolders` When `true`, sort includes so that files in a directory appear
    before subdirectories at each level, recursively. Within a level,
    files and folders are each sorted alphabetically.
    When `false` (default), sorts includes purely alphabetically.

    This option is a secondary sort key within each `Priority` group
    defined by `IncludeCategories`. Includes in different `Priority`
    groups are still separated by that primary ordering.

    ```c++
    true:                             false (default):
    #include "x.h"             vs.    #include "bar/alpha/e.h"
    #include "y.h"                    #include "bar/alpha/f.h"
    #include "z.h"                    #include "bar/beta/d.h"
    #include "bar/g.h"                #include "bar/g.h"
    #include "bar/h.h"                #include "bar/h.h"
    #include "bar/i.h"                #include "bar/i.h"
    #include "bar/alpha/e.h"          #include "foo/a.h"
    #include "bar/alpha/f.h"          #include "x.h"
    #include "bar/beta/d.h"           #include "y.h"
    #include "foo/a.h"                #include "z.h"
    ```


(sortjavastaticimport)=

**SortJavaStaticImport** (`SortJavaStaticImportOptions`) {versionbadge}`clang-format 12` {ref}`¶ <SortJavaStaticImport>`

: When sorting Java imports, by default static imports are placed before
  non-static imports. If `JavaStaticImportAfterImport` is `After`,
  static imports are placed after non-static imports.

  Possible values:

  - `SJSIO_Before` (in configuration: `Before`)
    Static imports are placed before non-static imports.

    ```java
    import static org.example.function1;

    import org.example.ClassA;
    ```

  - `SJSIO_After` (in configuration: `After`)
    Static imports are placed after non-static imports.

    ```java
    import org.example.ClassA;

    import static org.example.function1;
    ```



(sortusingdeclarations)=

**SortUsingDeclarations** (`SortUsingDeclarationsOptions`) {versionbadge}`clang-format 5` {ref}`¶ <SortUsingDeclarations>`

: Controls if and how clang-format will sort using declarations.

  Possible values:

  - `SUD_Never` (in configuration: `Never`)
    Using declarations are never sorted.

    ```c++
    using std::chrono::duration_cast;
    using std::move;
    using boost::regex;
    using boost::regex_constants::icase;
    using std::string;
    ```

  - `SUD_Lexicographic` (in configuration: `Lexicographic`)
    Using declarations are sorted in the order defined as follows:
    Split the strings by `::` and discard any initial empty strings. Sort
    the lists of names lexicographically, and within those groups, names are
    in case-insensitive lexicographic order.

    ```c++
    using boost::regex;
    using boost::regex_constants::icase;
    using std::chrono::duration_cast;
    using std::move;
    using std::string;
    ```

  - `SUD_LexicographicNumeric` (in configuration: `LexicographicNumeric`)
    Using declarations are sorted in the order defined as follows:
    Split the strings by `::` and discard any initial empty strings. The
    last element of each list is a non-namespace name; all others are
    namespace names. Sort the lists of names lexicographically, where the
    sort order of individual names is that all non-namespace names come
    before all namespace names, and within those groups, names are in
    case-insensitive lexicographic order.

    ```c++
    using boost::regex;
    using boost::regex_constants::icase;
    using std::move;
    using std::string;
    using std::chrono::duration_cast;
    ```



(spaceaftercstylecast)=

**SpaceAfterCStyleCast** (`Boolean`) {versionbadge}`clang-format 3.5` {ref}`¶ <SpaceAfterCStyleCast>`

: If `true`, a space is inserted after C style casts.

  ```c++
  true:                                  false:
  (int) i;                       vs.     (int)i;
  ```

(spaceafterlogicalnot)=

**SpaceAfterLogicalNot** (`Boolean`) {versionbadge}`clang-format 9` {ref}`¶ <SpaceAfterLogicalNot>`

: If `true`, a space is inserted after the logical not operator (`!`).

  ```c++
  true:                                  false:
  ! someExpression();            vs.     !someExpression();
  ```

(spaceafteroperatorkeyword)=

**SpaceAfterOperatorKeyword** (`Boolean`) {versionbadge}`clang-format 21` {ref}`¶ <SpaceAfterOperatorKeyword>`

: If `true`, a space will be inserted after the `operator` keyword.

  ```c++
  true:                                false:
  bool operator ==(int a);     vs.     bool operator==(int a);
  ```

(spaceaftertemplatekeyword)=

**SpaceAfterTemplateKeyword** (`Boolean`) {versionbadge}`clang-format 4` {ref}`¶ <SpaceAfterTemplateKeyword>`

: If `true`, a space will be inserted after the `template` keyword.

  ```c++
  true:                                  false:
  template <int> void foo();     vs.     template<int> void foo();
  ```

(spacearoundpointerqualifiers)=

**SpaceAroundPointerQualifiers** (`SpaceAroundPointerQualifiersStyle`) {versionbadge}`clang-format 12` {ref}`¶ <SpaceAroundPointerQualifiers>`

: Defines in which cases to put a space before or after pointer qualifiers

  Possible values:

  - `SAPQ_Default` (in configuration: `Default`)
    Don't ensure spaces around pointer qualifiers and use PointerAlignment
    instead.

    ```c++
    PointerAlignment: Left                 PointerAlignment: Right
    void* const* x = NULL;         vs.     void *const *x = NULL;
    ```

  - `SAPQ_Before` (in configuration: `Before`)
    Ensure that there is a space before pointer qualifiers.

    ```c++
    PointerAlignment: Left                 PointerAlignment: Right
    void* const* x = NULL;         vs.     void * const *x = NULL;
    ```

  - `SAPQ_After` (in configuration: `After`)
    Ensure that there is a space after pointer qualifiers.

    ```c++
    PointerAlignment: Left                 PointerAlignment: Right
    void* const * x = NULL;         vs.     void *const *x = NULL;
    ```

  - `SAPQ_Both` (in configuration: `Both`)
    Ensure that there is a space both before and after pointer qualifiers.

    ```c++
    PointerAlignment: Left                 PointerAlignment: Right
    void* const * x = NULL;         vs.     void * const *x = NULL;
    ```



(spacebeforeassignmentoperators)=

**SpaceBeforeAssignmentOperators** (`Boolean`) {versionbadge}`clang-format 3.7` {ref}`¶ <SpaceBeforeAssignmentOperators>`

: If `false`, spaces will be removed before assignment operators.

  ```c++
  true:                                  false:
  int a = 5;                     vs.     int a= 5;
  a += 42;                               a+= 42;
  ```

(spacebeforecasecolon)=

**SpaceBeforeCaseColon** (`Boolean`) {versionbadge}`clang-format 12` {ref}`¶ <SpaceBeforeCaseColon>`

: If `false`, spaces will be removed before case colon.

  ```c++
  true:                                   false
  switch (x) {                    vs.     switch (x) {
    case 1 : break;                         case 1: break;
  }                                       }
  ```

(spacebeforecpp11bracedlist)=

**SpaceBeforeCpp11BracedList** (`Boolean`) {versionbadge}`clang-format 7` {ref}`¶ <SpaceBeforeCpp11BracedList>`

: If `true`, a space will be inserted before a C++11 braced list
  used to initialize an object (after the preceding identifier or type).

  ```c++
  true:                                  false:
  Foo foo { bar };               vs.     Foo foo{ bar };
  Foo {};                                Foo{};
  vector<int> { 1, 2, 3 };               vector<int>{ 1, 2, 3 };
  new int[3] { 1, 2, 3 };                new int[3]{ 1, 2, 3 };
  ```

(spacebeforectorinitializercolon)=

**SpaceBeforeCtorInitializerColon** (`Boolean`) {versionbadge}`clang-format 7` {ref}`¶ <SpaceBeforeCtorInitializerColon>`

: If `false`, spaces will be removed before constructor initializer
  colon.

  ```c++
  true:                                  false:
  Foo::Foo() : a(a) {}                   Foo::Foo(): a(a) {}
  ```

(spacebeforeenumunderlyingtypecolon)=

**SpaceBeforeEnumUnderlyingTypeColon** (`Boolean`) {versionbadge}`clang-format 23` {ref}`¶ <SpaceBeforeEnumUnderlyingTypeColon>`

: If `false`, spaces will be removed before enum underlying type colon.

  ```c++
  true:                                  false:
  enum E : int {}                        enum E: int {}
  ```

(spacebeforeinheritancecolon)=

**SpaceBeforeInheritanceColon** (`Boolean`) {versionbadge}`clang-format 7` {ref}`¶ <SpaceBeforeInheritanceColon>`

: If `false`, spaces will be removed before inheritance colon.

  ```c++
  true:                                  false:
  class Foo : Bar {}             vs.     class Foo: Bar {}
  ```

(spacebeforejsoncolon)=

**SpaceBeforeJsonColon** (`Boolean`) {versionbadge}`clang-format 17` {ref}`¶ <SpaceBeforeJsonColon>`

: If `true`, a space will be added before a JSON colon. For other
  languages, e.g. JavaScript, use `SpacesInContainerLiterals` instead.

  ```c++
  true:                                  false:
  {                                      {
    "key" : "value"              vs.       "key": "value"
  }                                      }
  ```

(spacebeforeparens)=

**SpaceBeforeParens** (`SpaceBeforeParensStyle`) {versionbadge}`clang-format 3.5` {ref}`¶ <SpaceBeforeParens>`

: Defines in which cases to put a space before opening parentheses.

  Possible values:

  - `SBPO_Never` (in configuration: `Never`)
    This is **deprecated** and replaced by `Custom` below, with all
    `SpaceBeforeParensOptions` but `AfterPlacementOperator` set to
    `false`.

  - `SBPO_ControlStatements` (in configuration: `ControlStatements`)
    Put a space before opening parentheses only after control statement
    keywords (`for/if/while...`).

    ```c++
    void f() {
      if (true) {
        f();
      }
    }
    ```

  - `SBPO_ControlStatementsExceptControlMacros` (in configuration: `ControlStatementsExceptControlMacros`)
    Same as `SBPO_ControlStatements` except this option doesn't apply to
    ForEach and If macros. This is useful in projects where ForEach/If
    macros are treated as function calls instead of control statements.
    `SBPO_ControlStatementsExceptForEachMacros` remains an alias for
    backward compatibility.

    ```c++
    void f() {
      Q_FOREACH(...) {
        f();
      }
    }
    ```

  - `SBPO_NonEmptyParentheses` (in configuration: `NonEmptyParentheses`)
    Put a space before opening parentheses only if the parentheses are not
    empty.

    ```c++
    void() {
      if (true) {
        f();
        g (x, y, z);
      }
    }
    ```

  - `SBPO_Always` (in configuration: `Always`)
    Always put a space before opening parentheses, except when it's
    prohibited by the syntax rules (in function-like macro definitions) or
    when determined by other style rules (after unary operators, opening
    parentheses, etc.)

    ```c++
    void f () {
      if (true) {
        f ();
      }
    }
    ```

  - `SBPO_Custom` (in configuration: `Custom`)
    Configure each individual space before parentheses in
    `SpaceBeforeParensOptions`.



(spacebeforeparensoptions)=

**SpaceBeforeParensOptions** (`SpaceBeforeParensCustom`) {versionbadge}`clang-format 14` {ref}`¶ <SpaceBeforeParensOptions>`

: Control of individual space before parentheses.

  If `SpaceBeforeParens` is set to `Custom`, use this to specify
  how each individual space before parentheses case should be handled.
  Otherwise, this is ignored.

  ```yaml
  # Example of usage:
  SpaceBeforeParens: Custom
  SpaceBeforeParensOptions:
    AfterControlStatements: true
    AfterFunctionDefinitionName: true
  ```

  Nested configuration flags:

  Precise control over the spacing before parentheses.

  ```yaml
  # Should be declared this way:
  SpaceBeforeParens: Custom
  SpaceBeforeParensOptions:
    AfterControlStatements: true
    AfterFunctionDefinitionName: true
  ```

  - `bool AfterControlStatements` If `true`, put space between control statement keywords
    (for/if/while...) and opening parentheses.

    ```c++
    true:                                  false:
    if (...) {}                     vs.    if(...) {}
    ```

  - `bool AfterForeachMacros` If `true`, put space between foreach macros and opening parentheses.

    ```c++
    true:                                  false:
    FOREACH (...)                   vs.    FOREACH(...)
      <loop-body>                            <loop-body>
    ```

  - `bool AfterFunctionDeclarationName` If `true`, put a space between function declaration name and opening
    parentheses.

    ```c++
    true:                                  false:
    void f ();                      vs.    void f();
    ```

  - `bool AfterFunctionDefinitionName` If `true`, put a space between function definition name and opening
    parentheses.

    ```c++
    true:                                  false:
    void f () {}                    vs.    void f() {}
    ```

  - `bool AfterIfMacros` If `true`, put space between if macros and opening parentheses.

    ```c++
    true:                                  false:
    IF (...)                        vs.    IF(...)
      <conditional-body>                     <conditional-body>
    ```

  - `bool AfterNot` If `true`, put a space between alternative operator `not` and the
    opening parenthesis.

    ```c++
    true:                                  false:
    return not (a || b);            vs.    return not(a || b);
    ```

  - `bool AfterOverloadedOperator` If `true`, put a space between operator overloading and opening
    parentheses.

    ```c++
    true:                                  false:
    void operator++ (int a);        vs.    void operator++(int a);
    object.operator++ (10);                object.operator++(10);
    ```

  - `bool AfterPlacementOperator` If `true`, put a space between operator `new`/`delete` and opening
    parenthesis.

    ```c++
    true:                                  false:
    new (buf) T;                    vs.    new(buf) T;
    delete (buf) T;                        delete(buf) T;
    ```

  - `bool AfterRequiresInClause` If `true`, put space between requires keyword in a requires clause and
    opening parentheses, if there is one.

    ```c++
    true:                                  false:
    template<typename T>            vs.    template<typename T>
    requires (A<T> && B<T>)                requires(A<T> && B<T>)
    ...                                    ...
    ```

  - `bool AfterRequiresInExpression` If `true`, put space between requires keyword in a requires expression
    and opening parentheses.

    ```c++
    true:                                  false:
    template<typename T>            vs.    template<typename T>
    concept C = requires (T t) {           concept C = requires(T t) {
                  ...                                    ...
                }                                      }
    ```

  - `bool BeforeNonEmptyParentheses` If `true`, put a space before opening parentheses only if the
    parentheses are not empty.

    ```c++
    true:                                  false:
    void f (int a);                 vs.    void f();
    f (a);                                 f();
    ```


(spacebeforerangebasedforloopcolon)=

**SpaceBeforeRangeBasedForLoopColon** (`Boolean`) {versionbadge}`clang-format 7` {ref}`¶ <SpaceBeforeRangeBasedForLoopColon>`

: If `false`, spaces will be removed before range-based for loop
  colon.

  ```c++
  true:                                  false:
  for (auto v : values) {}       vs.     for(auto v: values) {}
  ```

(spacebeforesquarebrackets)=

**SpaceBeforeSquareBrackets** (`Boolean`) {versionbadge}`clang-format 10` {ref}`¶ <SpaceBeforeSquareBrackets>`

: If `true`, spaces will be before  `[`.
  Lambdas will not be affected. Only the first `[` will get a space added.

  ```c++
  true:                                  false:
  int a [5];                    vs.      int a[5];
  int a [5][5];                 vs.      int a[5][5];
  ```

(spaceinemptyblock)=

**SpaceInEmptyBlock** (`Boolean`) {versionbadge}`clang-format 10` {ref}`¶ <SpaceInEmptyBlock>`

: This option is **deprecated**. See `Block` of `SpaceInEmptyBraces`.

(spaceinemptybraces)=

**SpaceInEmptyBraces** (`SpaceInEmptyBracesStyle`) {versionbadge}`clang-format 22` {ref}`¶ <SpaceInEmptyBraces>`

: Specifies when to insert a space in empty braces.

  :::{note}
  This option doesn't apply to initializer braces if
  `Cpp11BracedListStyle` is not `Block`.
  :::

  Possible values:

  - `SIEB_Always` (in configuration: `Always`)
    Always insert a space in empty braces.

    ```c++
    void f() { }
    class Unit { };
    auto a = [] { };
    int x{ };
    ```

  - `SIEB_Block` (in configuration: `Block`)
    Only insert a space in empty blocks.

    ```c++
    void f() { }
    class Unit { };
    auto a = [] { };
    int x{};
    ```

  - `SIEB_Never` (in configuration: `Never`)
    Never insert a space in empty braces.

    ```c++
    void f() {}
    class Unit {};
    auto a = [] {};
    int x{};
    ```



(spaceinemptyparentheses)=

**SpaceInEmptyParentheses** (`Boolean`) {versionbadge}`clang-format 3.7` {ref}`¶ <SpaceInEmptyParentheses>`

: If `true`, spaces may be inserted into `()`.
  This option is **deprecated**. See `InEmptyParentheses` of
  `SpacesInParensOptions`.

(spacesbeforetrailingcomments)=

**SpacesBeforeTrailingComments** (`Unsigned`) {versionbadge}`clang-format 3.7` {ref}`¶ <SpacesBeforeTrailingComments>`

: The number of spaces before trailing line comments
  (`//` - comments).

  This does not affect trailing block comments (`/*` - comments) as those
  commonly have different usage patterns and a number of special cases.  In
  the case of Verilog, it doesn't affect a comment right after the opening
  parenthesis in the port or parameter list in a module header, because it
  is probably for the port on the following line instead of the parenthesis
  it follows.

  ```c++
  SpacesBeforeTrailingComments: 3
  void f() {
    if (true) {   // foo1
      f();        // bar
    }             // foo
  }
  ```

(spacesinangles)=

**SpacesInAngles** (`SpacesInAnglesStyle`) {versionbadge}`clang-format 3.4` {ref}`¶ <SpacesInAngles>`

: The SpacesInAnglesStyle to use for template argument lists.

  Possible values:

  - `SIAS_Never` (in configuration: `Never`)
    Remove spaces after `<` and before `>`.

    ```c++
    static_cast<int>(arg);
    std::function<void(int)> fct;
    ```

  - `SIAS_Always` (in configuration: `Always`)
    Add spaces after `<` and before `>`.

    ```c++
    static_cast< int >(arg);
    std::function< void(int) > fct;
    ```

  - `SIAS_Leave` (in configuration: `Leave`)
    Keep a single space after `<` and before `>` if any spaces were
    present. Option `Standard: Cpp03` takes precedence.



(spacesinblockcomments)=

**SpacesInBlockComments** (`SpacesInBlockCommentsStyle`) {versionbadge}`clang-format 24` {ref}`¶ <SpacesInBlockComments>`

: The SpacesInBlockCommentsStyle to use for ordinary block comments.
  Documentation comments such as `/** ... */` and `/*! ... */`
  and parameter comments ending with `=` before the closing `*/` are
  left unchanged.

  Possible values:

  - `SIBCS_Never` (in configuration: `Never`)
    Remove spaces after `/*` and before `*/`.

    ```c++
    /*comment*/
    ```

  - `SIBCS_Always` (in configuration: `Always`)
    Add spaces after `/*` and before `*/`.

    ```c++
    /* comment */
    ```

  - `SIBCS_Leave` (in configuration: `Leave`)
    Leave existing spaces unchanged.



(spacesincstylecastparentheses)=

**SpacesInCStyleCastParentheses** (`Boolean`) {versionbadge}`clang-format 3.7` {ref}`¶ <SpacesInCStyleCastParentheses>`

: If `true`, spaces may be inserted into C style casts.
  This option is **deprecated**. See `InCStyleCasts` of
  `SpacesInParensOptions`.

(spacesinconditionalstatement)=

**SpacesInConditionalStatement** (`Boolean`) {versionbadge}`clang-format 10` {ref}`¶ <SpacesInConditionalStatement>`

: If `true`, spaces will be inserted around if/for/switch/while
  conditions.
  This option is **deprecated**. See `InConditionalStatements` of
  `SpacesInParensOptions`.

(spacesincontainerliterals)=

**SpacesInContainerLiterals** (`Boolean`) {versionbadge}`clang-format 3.7` {ref}`¶ <SpacesInContainerLiterals>`

: If `true`, spaces are inserted inside container literals (e.g.  ObjC and
  Javascript array and dict literals). For JSON, use
  `SpaceBeforeJsonColon` instead.

  ```js
  true:                                  false:
  var arr = [ 1, 2, 3 ];         vs.     var arr = [1, 2, 3];
  f({a : 1, b : 2, c : 3});              f({a: 1, b: 2, c: 3});
  ```

(spacesinlinecommentprefix)=

**SpacesInLineCommentPrefix** (`SpacesInLineComment`) {versionbadge}`clang-format 13` {ref}`¶ <SpacesInLineCommentPrefix>`

: How many spaces are allowed at the start of a line comment. To disable the
  maximum set it to `-1`, apart from that the maximum takes precedence
  over the minimum.

  ```c++
  Minimum = 1
  Maximum = -1
  // One space is forced

  //  but more spaces are possible

  Minimum = 0
  Maximum = 0
  //Forces to start every comment directly after the slashes
  ```

  Note that in line comment sections the relative indent of the subsequent
  lines is kept, that means the following:

  ```c++
  before:                                   after:
  Minimum: 1
  //if (b) {                                // if (b) {
  //  return true;                          //   return true;
  //}                                       // }

  Maximum: 0
  /// List:                                 ///List:
  ///  - Foo                                /// - Foo
  ///    - Bar                              ///   - Bar
  ```

  This option has only effect if `ReflowComments` is set to `true`.

  Nested configuration flags:

  Control of spaces within a single line comment.

  - `unsigned Minimum` The minimum number of spaces at the start of the comment.

  - `unsigned Maximum` The maximum number of spaces at the start of the comment.


(spacesinparens)=

**SpacesInParens** (`SpacesInParensStyle`) {versionbadge}`clang-format 17` {ref}`¶ <SpacesInParens>`

: Defines in which cases spaces will be inserted after `(` and before
  `)`.

  Possible values:

  - `SIPO_Never` (in configuration: `Never`)
    Never put a space in parentheses.

    ```c++
    void f() {
      if(true) {
        f();
      }
    }
    ```

  - `SIPO_Custom` (in configuration: `Custom`)
    Configure each individual space in parentheses in
    `SpacesInParensOptions`.



(spacesinparensoptions)=

**SpacesInParensOptions** (`SpacesInParensCustom`) {versionbadge}`clang-format 17` {ref}`¶ <SpacesInParensOptions>`

: Control of individual spaces in parentheses.

  If `SpacesInParens` is set to `Custom`, use this to specify
  how each individual space in parentheses case should be handled.
  Otherwise, this is ignored.

  ```yaml
  # Example of usage:
  SpacesInParens: Custom
  SpacesInParensOptions:
    ExceptDoubleParentheses: false
    InConditionalStatements: true
    InEmptyParentheses: true
  ```

  Nested configuration flags:

  Precise control over the spacing in parentheses.

  ```yaml
  # Should be declared this way:
  SpacesInParens: Custom
  SpacesInParensOptions:
    ExceptDoubleParentheses: false
    InConditionalStatements: true
    Other: true
  ```

  - `bool ExceptDoubleParentheses` Override any of the following options to prevent addition of space
    when both opening and closing parentheses use multiple parentheses.

    ```c++
    true:
    __attribute__(( noreturn ))
    __decltype__(( x ))
    if (( a = b ))
     false:
       Uses the applicable option.
    ```


  - `bool InConditionalStatements` Put a space in parentheses only inside conditional statements
    (`for/if/while/switch...`).

    ```c++
    true:                                  false:
    if ( a )  { ... }              vs.     if (a) { ... }
    while ( i < 5 )  { ... }               while (i < 5) { ... }
    ```

  - `bool InCStyleCasts` Put a space in C style casts.

    ```c++
    true:                                  false:
    x = ( int32 )y                  vs.    x = (int32)y
    y = (( int (*)(int) )foo)(x);          y = ((int (*)(int))foo)(x);
    ```

  - `bool InEmptyParentheses` Insert a space in empty parentheses, i.e. `()`.

    ```c++
    true:                                false:
    void f( ) {                    vs.   void f() {
      int x[] = {foo( ), bar( )};          int x[] = {foo(), bar()};
      if (true) {                          if (true) {
        f( );                                f();
      }                                    }
    }                                    }
    ```

  - `bool Other` Put a space in parentheses not covered by preceding options.

    ```c++
    true:                                 false:
    t f( Deleted & ) & = delete;    vs.   t f(Deleted &) & = delete;
    ```


(spacesinparentheses)=

**SpacesInParentheses** (`Boolean`) {versionbadge}`clang-format 3.7` {ref}`¶ <SpacesInParentheses>`

: If `true`, spaces will be inserted after `(` and before `)`.
  This option is **deprecated**. The previous behavior is preserved by using
  `SpacesInParens` with `Custom` and by setting all
  `SpacesInParensOptions` to `true` except for `InCStyleCasts` and
  `InEmptyParentheses`.

(spacesinsquarebrackets)=

**SpacesInSquareBrackets** (`Boolean`) {versionbadge}`clang-format 3.7` {ref}`¶ <SpacesInSquareBrackets>`

: If `true`, spaces will be inserted after `[` and before `]`.
  Lambdas without arguments or unspecified size array declarations will not
  be affected.

  ```c++
  true:                                  false:
  int a[ 5 ];                    vs.     int a[5];
  std::unique_ptr<int[]> foo() {} // Won't be affected
  ```

(standard)=

**Standard** (`LanguageStandard`) {versionbadge}`clang-format 3.7` {ref}`¶ <Standard>`

: Parse and format C++ constructs compatible with this standard.

  ```c++
  c++03:                                 latest:
  vector<set<int> > x;           vs.     vector<set<int>> x;
  ```

  Possible values:

  - `LS_Cpp03` (in configuration: `c++03`)
    Parse and format as C++03.
    `Cpp03` is a deprecated alias for `c++03`

  - `LS_Cpp11` (in configuration: `c++11`)
    Parse and format as C++11.

  - `LS_Cpp14` (in configuration: `c++14`)
    Parse and format as C++14.

  - `LS_Cpp17` (in configuration: `c++17`)
    Parse and format as C++17.

  - `LS_Cpp20` (in configuration: `c++20`)
    Parse and format as C++20.

  - `LS_Cpp23` (in configuration: `c++23`)
    Parse and format as C++23.

  - `LS_Cpp26` (in configuration: `c++26`)
    Parse and format as C++26.

  - `LS_Latest` (in configuration: `Latest`)
    Parse and format using the latest supported language version.
    `Cpp11` is a deprecated alias for `Latest`

  - `LS_Auto` (in configuration: `Auto`)
    Automatic detection based on the input.



(statementattributelikemacros)=

**StatementAttributeLikeMacros** (`List of Strings`) {versionbadge}`clang-format 12` {ref}`¶ <StatementAttributeLikeMacros>`

: Macros which are ignored in front of a statement, as if they were an
  attribute. So that they are not parsed as identifier, for example for Qts
  emit.

  ```c++
  AlignConsecutiveDeclarations: true
  StatementAttributeLikeMacros: []
  unsigned char data = 'x';
  emit          signal(data); // This is parsed as variable declaration.

  AlignConsecutiveDeclarations: true
  StatementAttributeLikeMacros: [emit]
  unsigned char data = 'x';
  emit signal(data); // Now it's fine again.
  ```

(statementmacros)=

**StatementMacros** (`List of Strings`) {versionbadge}`clang-format 8` {ref}`¶ <StatementMacros>`

: A vector of macros that should be interpreted as complete statements.

  Typical macros are expressions and require a semicolon to be added.
  Sometimes this is not the case, and this allows to make clang-format aware
  of such cases.

  For example: Q_UNUSED

(tabwidth)=

**TabWidth** (`Unsigned`) {versionbadge}`clang-format 3.7` {ref}`¶ <TabWidth>`

: The number of columns used for tab stops.

(tablegenbreakinsidedagarg)=

**TableGenBreakInsideDAGArg** (`DAGArgStyle`) {versionbadge}`clang-format 19` {ref}`¶ <TableGenBreakInsideDAGArg>`

: The styles of the line break inside the DAGArg in TableGen.

  Possible values:

  - `DAS_DontBreak` (in configuration: `DontBreak`)
    Never break inside DAGArg.

    ```c++
    let DAGArgIns = (ins i32:$src1, i32:$src2);
    ```

  - `DAS_BreakElements` (in configuration: `BreakElements`)
    Break inside DAGArg after each list element but for the last.
    This aligns to the first element.

    ```c++
    let DAGArgIns = (ins i32:$src1,
                         i32:$src2);
    ```

  - `DAS_BreakAll` (in configuration: `BreakAll`)
    Break inside DAGArg after the operator and the all elements.

    ```c++
    let DAGArgIns = (ins
        i32:$src1,
        i32:$src2
    );
    ```



(tablegenbreakingdagargoperators)=

**TableGenBreakingDAGArgOperators** (`List of Strings`) {versionbadge}`clang-format 19` {ref}`¶ <TableGenBreakingDAGArgOperators>`

: Works only when TableGenBreakInsideDAGArg is not DontBreak.
  The string list needs to consist of identifiers in TableGen.
  If any identifier is specified, this limits the line breaks by
  TableGenBreakInsideDAGArg option only on DAGArg values beginning with
  the specified identifiers.

  For example the configuration,

  ```yaml
  TableGenBreakInsideDAGArg: BreakAll
  TableGenBreakingDAGArgOperators: [ins, outs]
  ```

  makes the line break only occurs inside DAGArgs beginning with the
  specified identifiers `ins` and `outs`.

  ```c++
  let DAGArgIns = (ins
      i32:$src1,
      i32:$src2
  );
  let DAGArgOtherID = (other i32:$other1, i32:$other2);
  let DAGArgBang = (!cast<SomeType>("Some") i32:$src1, i32:$src2)
  ```

(templatenames)=

**TemplateNames** (`List of Strings`) {versionbadge}`clang-format 20` {ref}`¶ <TemplateNames>`

: A vector of non-keyword identifiers that should be interpreted as template
  names.

  A `<` after a template name is annotated as a template opener instead of
  a binary operator.

(typenames)=

**TypeNames** (`List of Strings`) {versionbadge}`clang-format 17` {ref}`¶ <TypeNames>`

: A vector of non-keyword identifiers that should be interpreted as type
  names.

  A `*`, `&`, or `&&` between a type name and another non-keyword
  identifier is annotated as a pointer or reference token instead of a
  binary operator.

(typenamemacros)=

**TypenameMacros** (`List of Strings`) {versionbadge}`clang-format 9` {ref}`¶ <TypenameMacros>`

: A vector of macros that should be interpreted as type declarations instead
  of as function calls.

  These are expected to be macros of the form:

  ```c++
  STACK_OF(...)
  ```

  In the .clang-format configuration file, this can be configured like:

  ```yaml
  TypenameMacros: [STACK_OF, LIST]
  ```

  For example: OpenSSL STACK_OF, BSD LIST_ENTRY.

(usecrlf)=

**UseCRLF** (`Boolean`) {versionbadge}`clang-format 10` {ref}`¶ <UseCRLF>`

: This option is **deprecated**. See `LF` and `CRLF` of `LineEnding`.

(usetab)=

**UseTab** (`UseTabStyle`) {versionbadge}`clang-format 3.7` {ref}`¶ <UseTab>`

: The way to use tab characters in the resulting file.

  Possible values:

  - `UT_Never` (in configuration: `Never`)
    Never use tab.

  - `UT_ForIndentation` (in configuration: `ForIndentation`)
    Use tabs only for indentation.

  - `UT_ForContinuationAndIndentation` (in configuration: `ForContinuationAndIndentation`)
    Fill all leading whitespace with tabs, and use spaces for alignment that
    appears within a line (e.g. consecutive assignments and declarations).

  - `UT_AlignWithSpaces` (in configuration: `AlignWithSpaces`)
    Use tabs for line continuation and indentation, and spaces for
    alignment.

  - `UT_Always` (in configuration: `Always`)
    Use tabs whenever we need to fill whitespace that spans at least from
    one tab stop to the next one.



(variabletemplates)=

**VariableTemplates** (`List of Strings`) {versionbadge}`clang-format 20` {ref}`¶ <VariableTemplates>`

: A vector of non-keyword identifiers that should be interpreted as variable
  template names.

  A `)` after a variable template instantiation is **not** annotated as
  the closing parenthesis of C-style cast operator.

(verilogbreakbetweeninstanceports)=

**VerilogBreakBetweenInstancePorts** (`Boolean`) {versionbadge}`clang-format 17` {ref}`¶ <VerilogBreakBetweenInstancePorts>`

: For Verilog, put each port on its own line in module instantiations.

  ```c++
  true:
  ffnand ff1(.q(),
             .qbar(out1),
             .clear(in1),
             .preset(in2));

  false:
  ffnand ff1(.q(), .qbar(out1), .clear(in1), .preset(in2));
  ```

(whitespacesensitivemacros)=

**WhitespaceSensitiveMacros** (`List of Strings`) {versionbadge}`clang-format 11` {ref}`¶ <WhitespaceSensitiveMacros>`

: A vector of macros which are whitespace-sensitive and should not
  be touched.

  These are expected to be macros of the form:

  ```c++
  STRINGIZE(...)
  ```

  In the .clang-format configuration file, this can be configured like:

  ```yaml
  WhitespaceSensitiveMacros: [STRINGIZE, PP_STRINGIZE]
  ```

  For example: BOOST_PP_STRINGIZE

(wrapnamespacebodywithemptylines)=

**WrapNamespaceBodyWithEmptyLines** (`WrapNamespaceBodyWithEmptyLinesStyle`) {versionbadge}`clang-format 20` {ref}`¶ <WrapNamespaceBodyWithEmptyLines>`

: Wrap namespace body with empty lines.

  Possible values:

  - `WNBWELS_Never` (in configuration: `Never`)
    Remove all empty lines at the beginning and the end of namespace body.

    ```c++
    namespace N1 {
    namespace N2 {
    function();
    }
    }
    ```

  - `WNBWELS_Always` (in configuration: `Always`)
    Always have at least one empty line at the beginning and the end of
    namespace body except that the number of empty lines between consecutive
    nested namespace definitions is not increased.

    ```c++
    namespace N1 {
    namespace N2 {

    function();

    }
    }
    ```

  - `WNBWELS_Leave` (in configuration: `Leave`)
    Keep existing newlines at the beginning and the end of namespace body.
    `MaxEmptyLinesToKeep` still applies.



% END_FORMAT_STYLE_OPTIONS

## Adding additional style options

Each additional style option adds costs to the clang-format project. Some of
these costs affect the clang-format development itself, as we need to make
sure that any given combination of options work and that new features don't
break any of the existing options in any way. There are also costs for end users
as options become less discoverable and people have to think about and make a
decision on options they don't really care about.

The goal of the clang-format project is more on the side of supporting a
limited set of styles really well as opposed to supporting every single style
used by a codebase somewhere in the wild. Of course, we do want to support all
major projects and thus have established the following bar for adding style
options. Each new style option must:

> - be used in a project of significant size (have dozens of contributors)
> - have a publicly accessible style guide
> - have a person willing to contribute and maintain patches

## Examples

A style similar to the [Linux Kernel style](https://www.kernel.org/doc/html/latest/process/coding-style.html):

```yaml
BasedOnStyle: LLVM
IndentWidth: 8
UseTab: Always
BreakBeforeBraces: Linux
AllowShortIfStatementsOnASingleLine: false
IndentCaseLabels: false
```

The result is (imagine that tabs are used for indentation here):

```c++
void test()
{
        switch (x) {
        case 0:
        case 1:
                do_something();
                break;
        case 2:
                do_something_else();
                break;
        default:
                break;
        }
        if (condition)
                do_something_completely_different();

        if (x == y) {
                q();
        } else if (x > y) {
                w();
        } else {
                r();
        }
}
```

A style similar to the default Visual Studio formatting style:

```yaml
UseTab: Never
IndentWidth: 4
BreakBeforeBraces: Allman
AllowShortIfStatementsOnASingleLine: false
IndentCaseLabels: false
ColumnLimit: 0
```

The result is:

```c++
void test()
{
    switch (suffix)
    {
    case 0:
    case 1:
        do_something();
        break;
    case 2:
        do_something_else();
        break;
    default:
        break;
    }
    if (condition)
        do_something_completely_different();

    if (x == y)
    {
        q();
    }
    else if (x > y)
    {
        w();
    }
    else
    {
        r();
    }
}
```

---

### Clang Docs ClangLinkerWrapper (`clang/docs/ClangLinkerWrapper.md`)

# Clang Linker Wrapper


## Introduction

This tool works as a wrapper of the normal host linking job. This tool is used
to create linked device images for offloading and the necessary runtime calls to
register them. It works by first scanning the linker's input for embedded device
offloading data stored at the `.llvm.offloading` section. This section
contains binary data created by the `llvm-offload-binary` utility. The
extracted device files will then be linked. The linked modules will then be
wrapped into a new object file containing the code necessary to register it with
the offloading runtime.

## Usage

This tool can be used with the following options. Any arguments not intended
only for the linker wrapper will be forwarded to the wrapped linker job.

```
/* Detailed source-code truncated for AI context efficiency. */
```

The linker wrapper will generate the appropriate runtime calls to register the
generated device binary with the offloading runtime. To do this step manually we
provide the `llvm-offload-wrapper` utility.

## Relocatable Linking

The `clang-linker-wrapper` handles linking embedded device code and then
registering it with the appropriate runtime. Normally, this is only done when
the executable is created so other files containing device code can be linked
together. This can be somewhat problematic for users who wish to ship static
libraries that contain offloading code to users without a compatible offloading
toolchain.

When using a relocatable link with `-r`, the `clang-linker-wrapper` will
perform the device linking and registration eagerly. This will remove the
embedded device code and register it correctly with the runtime. Semantically,
this is similar to creating a shared library object. If standard relocatable
linking is desired, simply do not run the binaries through the
`clang-linker-wrapper`. This will simply append the embedded device code so
that it can be linked later.

## Matching

The linker wrapper will link extracted device code that is compatible with each
other. Generally, this requires that the target triple and architecture match.
An exception is made when the architecture is listed as `generic`, which will
cause it be linked with any other device code with the same target triple.

## Debugging

The linker wrapper performs a lot of steps internally, such as input matching,
symbol resolution, and image registration. This makes it difficult to debug in
some scenarios. The behavior of the linker-wrapper is controlled mostly through
metadata, described in [Clang documentation](OffloadingDesign.md).

The individual tool invocations the wrapper performs can be printed with the
`--wrapper-verbose` flag, and the intermediate files they operate on can be
kept with `--save-temps`. When both are enabled the wrapper emits a
self-contained sequence of commands that reproduce its output. The example below
shows the sequence for a single OpenMP image.

```sh
$> clang openmp.c -fopenmp --offload-arch=gfx90a -c
$> clang openmp.o -fopenmp --offload-arch=gfx90a -Wl,--wrapper-verbose -Wl,--save-temps

# 1. Extract each embedded device image from the host object.
llvm-offload-binary openmp.o --image=kind=openmp,triple=amdgcn-amd-amdhsa,arch=gfx90a,file=openmp.gfx90a.o

# 2. Link the extracted image for the device target.
clang --target=amdgcn-amd-amdhsa -mcpu=gfx90a openmp.gfx90a.o -o openmp.gfx90a.img <...>

# 3. Bundle the linked image back into the offloading binary format.
llvm-offload-binary -o openmp.gfx90a.offload --image=file=openmp.gfx90a.img,kind=openmp,triple=amdgcn-amd-amdhsa,arch=gfx90a

# 4. Generate the host runtime registration code for the bundled images.
llvm-offload-wrapper --kind=openmp --triple=x86_64-unknown-linux-gnu -o openmp.wrapper.bc openmp.gfx90a.offload

# 5. Compile the registration code into a host object.
clang --target=x86_64-unknown-linux-gnu -c -fPIC -o openmp.wrapper.o openmp.wrapper.bc

# 6. Link the host objects with the registration code into the executable.
ld.lld openmp.host.o openmp.wrapper.o -o a.out <...>
```

To replace the output of a single stage, edit the relevant intermediate file and
re-run the remaining commands. To bypass the device link entirely and substitute
a pre-built image, use the `--override-image=<kind>=<file>` flag.

## Example

This tool links object files with offloading images embedded within it using the
`-fembed-offload-object` flag in Clang. Given an input file containing the
magic section we can pass it to this tool to extract the data contained at that
section and run a device linking job on it.

```console
clang-linker-wrapper --host-triple=x86_64 --linker-path=/usr/bin/ld -- <Args>
```

---

### Clang Docs ClangNVLinkWrapper (`clang/docs/ClangNVLinkWrapper.md`)

# Clang nvlink Wrapper


## Introduction

This tool works as a wrapper around the NVIDIA `nvlink` linker. The purpose
of this wrapper is to provide an interface similar to the `ld.lld` linker
while still relying on NVIDIA's proprietary linker to produce the final output.

`nvlink` has a number of known quirks that make it difficult to use in a
unified offloading setting. For example, it does not accept `.o` files as they
must be named `.cubin`. Static archives do not work, so passing a `.a` will
provide a linker error. `nvlink` also does not support link time optimization
and ignores many standard linker arguments. This tool works around these issues.

## Usage

This tool can be used with the following options. Any arguments not intended
only for the linker wrapper will be forwarded to `nvlink`.

```
/* Detailed source-code truncated for AI context efficiency. */
```

## Example

This tool is intended to be invoked when targeting the NVPTX toolchain directly
as a cross-compiling target. This can be used to create standalone GPU
executables with normal linking semantics similar to standard compilation.

```console
clang --target=nvptx64-nvidia-cuda -march=native -flto=full input.c
```

---

### Clang Docs ClangOffloadBundler (`clang/docs/ClangOffloadBundler.md`)

# Clang Offload Bundler


## Introduction

For heterogeneous single source programming languages, use one or more
`--offload-arch=<target-id>` Clang options to specify the target IDs of the
code to generate for the offload code regions.

The tool chain may perform multiple compilations of a translation unit to
produce separate code objects for the host and potentially multiple offloaded
devices. The `clang-offload-bundler` tool may be used as part of the tool
chain to combine these multiple code objects into a single bundled code object.

The tool chain may use a bundled code object as an intermediate step so that
each tool chain step consumes and produces a single file as in traditional
non-heterogeneous tool chains. The bundled code object contains the code objects
for the host and all the offload devices.

A bundled code object may also be used to bundle just the offloaded code
objects, and embedded as data into the host code object. The host compilation
includes an `init` function that will use the runtime corresponding to the
offload kind (see {ref}`clang-offload-kind-table`) to load the offload code
objects appropriate for the devices present when the host program is executed.

{program}`clang-offload-bundler` is located in
`clang/tools/clang-offload-bundler`.

```
/* Detailed source-code truncated for AI context efficiency. */
```

## Usage

This tool can be used as follows for bundling:

```
clang-offload-bundler -targets=triple1,triple2 -type=ii -inputs=a.triple1.ii,a.triple2.ii -outputs=a.ii
```

or, it can be used as follows for unbundling:

```
clang-offload-bundler -targets=triple1,triple2 -type=ii -outputs=a.triple1.ii,a.triple2.ii -inputs=a.ii -unbundle
```

## Supported File Formats

Multiple text and binary file formats are supported for bundling/unbundling. See
{ref}`supported-file-formats-table` for a list of currently supported input
formats. Use the `File Type` column to determine the value to pass to the
`--type` option based on the type of input files while bundling/unbundling.

```{table} Supported File Formats
:name: supported-file-formats-table

| File Format              | File Type | Text/Binary |
| ------------------------ | --------- | ----------- |
| CPP output               | i         | Text        |
| C++ CPP output           | ii        | Text        |
| CUDA/HIP output          | cui       | Text        |
| Dependency               | d         | Text        |
| LLVM                     | ll        | Text        |
| LLVM Bitcode             | bc        | Binary      |
| Assembler                | s         | Text        |
| Object                   | o         | Binary      |
| Archive of bundled files | a         | Binary      |
| Precompiled header       | gch       | Binary      |
| Clang AST file           | ast       | Binary      |
```

(clang-bundled-code-object-layout-text)=

## Bundled Text File Layout

The text file formats are concatenated with comments that have a magic string
and bundle entry ID in between. The BNF syntax to represent a code object
bundle file is:

```
<file>    ::== <bundle> | <bundle> <file>
<bundle>  ::== <comment> <start> <bundle_id> <eol> <bundle> <eol>
               <comment> end <bundle_id> <eol>
<start>   ::== OFFLOAD_BUNDLER_MAGIC_STR__START__
<end>     ::== OFFLOAD_BUNDLER_MAGIC_STR__END__
```

**comment**

: The symbol used for starting a single-line comment in the file type of
  constituting bundles. E.g. it is ";" for ll `File Type` and "#" for "s"
  `File Type`.

**bundle_id**

: The {ref}`clang-bundle-entry-id` for the enclosing bundle.

**eol**

: The end-of-line character.

**bundle**

: The code object stored in one of the supported text file formats.

**OFFLOAD_BUNDLER_MAGIC_STR\_\_**

: The magic string that marks the existence of offloading data i.e.
  "\_\_CLANG_OFFLOAD_BUNDLE\_\_".

(clang-bundled-code-object-layout)=

## Bundled Binary File Layout

The layout of a bundled code object is defined by the following table:

:::{list-table} Bundled Code Object Layout
:name: bundled-code-object-layout-table
:header-rows: 1

* - Field
  - Type
  - Size in Bytes
  - Description
* - Magic String
  - string
  - 24
  - `__CLANG_OFFLOAD_BUNDLE__`
* - Number Of Bundle Entries
  - integer
  - 8
  - Number of bundle entries.
* - 1st Bundle Entry Code Object Offset
  - integer
  - 8
  - Byte offset from beginning of bundled code object to 1st code object.
* - 1st Bundle Entry Code Object Size
  - integer
  - 8
  - Byte size of 1st code object.
* - 1st Bundle Entry ID Length
  - integer
  - 8
  - Character length of bundle entry ID of 1st code object.
* - 1st Bundle Entry ID
  - string
  - 1st Bundle Entry ID Length
  - Bundle entry ID of 1st code object. This is not NUL terminated. See
    {ref}`clang-bundle-entry-id`.
* - ...
  -
  -
  -
* - Nth Bundle Entry Code Object Offset
  - integer
  - 8
  -
* - Nth Bundle Entry Code Object Size
  - integer
  - 8
  -
* - Nth Bundle Entry ID Length
  - integer
  - 8
  -
* - Nth Bundle Entry ID
  - string
  - 1st Bundle Entry ID Length
  -
* - 1st Bundle Entry Code Object
  - bytes
  - 1st Bundle Entry Code Object Size
  -
* - ...
  -
  -
  -
* - Nth Bundle Entry Code Object
  - bytes
  - Nth Bundle Entry Code Object Size
  -
:::

(clang-bundle-entry-id)=

## Bundle Entry ID

Each entry in a bundled code object (see {ref}`clang-bundled-code-object-layout-text`
and {ref}`clang-bundled-code-object-layout`) has a bundle entry ID that indicates
the kind of the entry's code object and the runtime that manages it.

Bundle entry ID syntax is defined by the following BNF syntax:

```
<bundle-entry-id> ::== <offload-kind> "-" <target-triple> [ "-" <target-id> ]
```

Where:

**offload-kind**

: The runtime responsible for managing the bundled entry code object. See
  {ref}`clang-offload-kind-table`.

:::{list-table} Bundled Code Object Offload Kind
:name: clang-offload-kind-table
:header-rows: 1

* - Offload Kind
  - Description
* - host
  - Host code object. `clang-offload-bundler` always includes this entry as the
    first bundled code object entry. For an embedded bundled code object, this
    entry is not used by the runtime and so is generally an empty code object.
* - hip
  - Offload code object for the HIP language. Used for all HIP language offload
    code objects when the `clang-offload-bundler` is used to bundle code objects
    as intermediate steps of the tool chain. Also used for AMD GPU code objects
    before ABI version V4 when the `clang-offload-bundler` is used to create a
    *fat binary* to be loaded by the HIP runtime. The fat binary can be loaded
    directly from a file, or be embedded in the host code object as a data
    section with the name `.hip_fatbin`.
* - hipv4
  - Offload code object for the HIP language. Used for AMD GPU code objects with
    at least ABI version V4 and above when the `clang-offload-bundler` is used
    to create a *fat binary* to be loaded by the HIP runtime. The fat binary can
    be loaded directly from a file, or be embedded in the host code object as a
    data section with the name `.hip_fatbin`.
* - openmp
  - Offload code object for the OpenMP language extension.
:::

Note: The distinction between the `hip` and `hipv4` offload kinds is historically based.
Originally, these designations might have indicated different versions of the
code object ABI. However, as the system has evolved, the ABI version is now embedded
directly within the code object itself, making these historical distinctions irrelevant
during the unbundling process. Consequently, `hip` and `hipv4` are treated as compatible
in current implementations, facilitating interchangeable handling of code objects
without differentiation based on offload kind.

**target-triple**

: The target triple of the code object. See [Target Triple](CrossCompilation.md#target-triple).

  LLVM target triples can be with or without the optional environment field:

  `<arch><sub>-<vendor>-<sys>`, or
  `<arch><sub>-<vendor>-<sys>-<env>`

  However, in order to standardize outputs for tools that consume bitcode bundles
  and to parse a target ID containing dashes, the bundler only accepts target
  triples in the 4-field format:

  `<arch><sub>-<vendor>-<sys>-<env>`

**target-id**

: The canonical target ID of the code object. Present only if the target
  supports a target ID. See {ref}`clang-target-id`.

(code-object-composition)=

### Bundled Code Object Composition

- Each entry of a bundled code object must have a different bundle entry ID.
- There can be multiple entries for the same processor provided they differ
  in target feature settings.
- If there is an entry with a target feature specified as *Any*, then all
  entries must specify that target feature as *Any* for the same processor.

There may be additional target-specific restrictions.

(compatibility-bundle-entry-id)=

### Compatibility Rules for Bundle Entry ID

A code object, specified using its Bundle Entry ID, can be loaded and
executed on a target processor if:

- Their offload kinds are the same or compatible.
- Their target triples are compatible.
- Their Target IDs are compatible as defined in {ref}`compatibility-target-id`.

(clang-target-id)=

## Target ID

A target ID is used to indicate the processor and optionally its configuration,
expressed by a set of target features, that affect ISA generation. It is target
specific if a target ID is supported, or if the target triple alone is
sufficient to specify the ISA generation.

It is used with the `-mcpu=<target-id>` and `--offload-arch=<target-id>`
Clang compilation options to specify the kind of code to generate.

It is also used as part of the bundle entry ID to identify the code object. See
{ref}`clang-bundle-entry-id`.

Target ID syntax is defined by the following BNF syntax:

```
<target-id> ::== <processor> ( ":" <target-feature> ( "+" | "-" ) )*
```

Where:

**processor**

: Is the target-specific processor or any alternative processor name.

**target-feature**

: Is a target feature name that is supported by the processor. Each target
  feature must appear at most once in a target ID and can have one of three
  values:

  *Any*

  : Specified by omitting the target feature from the target ID.
    A code object compiled with a target ID specifying the default
    value of a target feature can be loaded and executed on a processor
    configured with the target feature on or off.

  *On*

  : Specified by `+`, indicating the target feature is enabled. A code
    object compiled with a target ID specifying a target feature on
    can only be loaded on a processor configured with the target feature on.

  *Off*

  : Specified by `-`, indicating the target feature is disabled. A code
    object compiled with a target ID specifying a target feature off
    can only be loaded on a processor configured with the target feature off.

(compatibility-target-id)=

### Compatibility Rules for Target ID

A code object compiled for a Target ID is considered compatible for a
target if:

- Their processor is the same.
- Their feature set is compatible as defined above.

There are two forms of target ID:

*Non-Canonical Form*

: The non-canonical form is used as the input to user commands to allow the user
  greater convenience. It allows both the primary and alternative processor name
  to be used and the target features may be specified in any order.

*Canonical Form*

: The canonical form is used for all generated output to allow greater
  convenience for tools that consume the information. It is also used for
  internal passing of information between tools. Only the primary and not
  alternative processor name is used and the target features are specified in
  alphabetic order. Command line tools convert non-canonical form to canonical
  form.

## Target-Specific information

Target-specific information is available for the following:

*AMD GPU*

: AMD GPU supports target ID and target features. See [User Guide for AMDGPU
  Backend](https://llvm.org/docs/AMDGPUUsage.html) which defines the
  [processors](https://llvm.org/docs/AMDGPUUsage.html#amdgpu-processors) and
  [target
  features](https://llvm.org/docs/AMDGPUUsage.html#amdgpu-target-features)
  supported.

Most other targets do not support target IDs.

## Archive Unbundling

Unbundling of a heterogeneous device archive (HDA) is done to create device-specific
archives. HDA is in a format compatible with GNU `ar` utility and contains a
collection of bundled device binaries where each bundle file will contain
device binaries for a host and one or more targets. The output device-specific
archive is in a format compatible with GNU `ar` utility and contains a
collection of device binaries for a specific target.

```
Heterogeneous Device Archive, HDA = {F1.X, F2.X, ..., FN.Y}
where, Fi = Bundle{Host-DeviceBinary, T1-DeviceBinary, T2-DeviceBinary, ...,
                   Tm-DeviceBinary},
       Ti = {Target i, qualified using Bundle Entry ID},
       X/Y = \*.bc for AMDGPU and \*.cubin for NVPTX

Device Specific Archive, DSA(Tk) = {F1-Tk-DeviceBinary.X, F2-Tk-DeviceBinary.X, ...
                                    FN-Tk-DeviceBinary.Y}
where, Fi-Tj-DeviceBinary.X represents device binary of i-th bundled device
binary file for target Tj.
```

The clang-offload-bundler extracts compatible device binaries for a given target
from the bundled device binaries in a heterogeneous device archive and creates
a target-specific device archive without bundling.

The clang-offload-bundler determines whether a device binary is compatible
with a target by comparing bundle IDs. Two bundle IDs are considered
compatible if:

- Their offload kinds are the same
- Their target triples are the same
- Their Target IDs are the same

### Creating a Heterogeneous Device Archive

1. Compile source file(s) to generate object file(s)

   ```
   clang -O2 -fopenmp -fopenmp-targets=amdgcn-amd-amdhsa,amdgcn-amd-amdhsa,\
      nvptx64-nvidia-cuda, nvptx64-nvidia-cuda \
     -Xopenmp-target=amdgcn-amd-amdhsa -march=gfx906:sramecc-:xnack+ \
     -Xopenmp-target=amdgcn-amd-amdhsa -march=gfx906:sramecc+:xnack+ \
     -Xopenmp-target=nvptx64-nvidia-cuda -march=sm_70 \
     -Xopenmp-target=nvptx64-nvidia-cuda -march=sm_80 \
     -c func_1.c -o func_1.o

   clang -O2 -fopenmp -fopenmp-targets=amdgcn-amd-amdhsa,amdgcn-amd-amdhsa,
     nvptx64-nvidia-cuda, nvptx64-nvidia-cuda \
     -Xopenmp-target=amdgcn-amd-amdhsa -march=gfx906:sramecc-:xnack+ \
     -Xopenmp-target=amdgcn-amd-amdhsa -march=gfx906:sramecc+:xnack+ \
     -Xopenmp-target=nvptx64-nvidia-cuda -march=sm_70 \
     -Xopenmp-target=nvptx64-nvidia-cuda -march=sm_80 \
     -c func_2.c -o func_2.o
   ```

2. Create a heterogeneous device archive by combining all the object file(s)

   ```
   llvm-ar cr libFatArchive.a func_1.o func_2.o
   ```

### Extracting a Device Specific Archive

UnbundleArchive takes a heterogeneous device archive file (".a") as input
containing bundled device binary files, and a list of offload targets (not
host), and extracts the device binaries into a new archive file for each
offload target. Each resulting archive file contains all device binaries
compatible with that particular offload target. Compatibility between a
device binary in HDA and a target is based on the compatibility between their
bundle entry IDs as defined in {ref}`compatibility-bundle-entry-id`.

The following cases may arise during compatibility testing:

- A binary is compatible with one or more targets: Insert the binary into the
  device-specific archive of each compatible target.
- A binary is not compatible with any target: Skip the binary.
- One or more binaries are compatible with a target: Insert all binaries into
  the device-specific archive of the target. The insertion need not be ordered.
- No binary is compatible with a target: If `allow-missing-bundles` option is
  present then create an empty archive for the target. Otherwise, produce an
  error without creating an archive.

The created archive file does not contain an index of the symbols and device
binary files are named as `<Parent Bundle Name>-<DeviceBinary's TargetID>`,
with ':' replaced with `_`.

### Usage

```
clang-offload-bundler --unbundle --inputs=libFatArchive.a -type=a \
 -targets=openmp-amdgcn-amdhsa-gfx906:sramecc+:xnack+, \
          openmp-amdgcn-amdhsa-gfx908:sramecc-:xnack+  \
 -outputs=devicelib-gfx906.a,deviceLib-gfx908.a
```

(additional-options-archive-unbundling)=

### Additional Options while Archive Unbundling

**-allow-missing-bundles**

: Create an empty archive file if no compatible device binary is found.

**-check-input-archive**

: Check if input heterogeneous device archive follows rules for composition
  as defined in {ref}`code-object-composition` before creating device-specific
  archive(s).

**-debug-only=CodeObjectCompatibility**

: Verbose printing of matched/unmatched comparisons between bundle entry id of
  a device binary from HDA and bundle entry ID of a given target processor
  (see {ref}`compatibility-bundle-entry-id`).

## Compression and Decompression

`clang-offload-bundler` provides features to compress and decompress the full
bundle, leveraging inherent redundancies within the bundle entries. Use the
`-compress` command-line option to enable this compression capability.

The compressed offload bundle begins with a header followed by the compressed binary data:

**Magic Number (4 bytes)**:

: This is a unique identifier to distinguish compressed offload bundles. The
  value is the string 'CCOB' (Compressed Clang Offload Bundle).

**Version Number (16-bit unsigned int)**:
: This denotes the version of the compressed offload bundle format. The current
  version is `3`.

**Compression Method (16-bit unsigned int)**:
: This field indicates the compression method used. The value corresponds to
  either `zlib` or `zstd`, represented as a 16-bit unsigned integer cast from
  the LLVM compression enumeration.

**Total File Size (unsigned int, 32-bit in v2, 64-bit in v3)**:
: This is the total size (in bytes) of the file, including the header.
  Available in version 2 and above.

**Uncompressed Binary Size (unsigned int, 32-bit in v2, 64-bit in v3)**:
: This is the size (in bytes) of the binary data before it was compressed.

**Hash (64-bit unsigned int)**:
: This is a 64-bit truncated MD5 hash of the uncompressed binary data. It
  serves for verification and caching purposes.

**Compressed Data**:
: The actual compressed binary data follows the header. Its size can be
  inferred from the total size of the file minus the header size.

:::{note} Version 3 is now the default format. For backward compatibility
with older HIP runtimes that support version 2 only, set the environment
variable `COMPRESSED_BUNDLE_FORMAT_VERSION=2`.
:::

---

### Clang Docs ClangPlugins (`clang/docs/ClangPlugins.md`)

# Clang Plugins

Clang Plugins make it possible to run extra user defined actions during a
compilation. This document will provide a basic walkthrough of how to write and
run a Clang Plugin.

## Introduction

Clang Plugins run FrontendActions over code. See the {doc}`FrontendAction
tutorial <RAVFrontendAction>` on how to write a `FrontendAction` using the
`RecursiveASTVisitor`. In this tutorial, we'll demonstrate how to write a
simple clang plugin.

## Writing a `PluginASTAction`

The main difference from writing normal `FrontendActions` is that you can
handle plugin command line options. The `PluginASTAction` base class declares
a `ParseArgs` method which you have to implement in your plugin.

```c++
bool ParseArgs(const CompilerInstance &CI,
               const std::vector<std::string>& args) {
  for (unsigned i = 0, e = args.size(); i != e; ++i) {
    if (args[i] == "-some-arg") {
      // Handle the command line argument.
    }
  }
  return true;
}
```

## Registering a plugin

A plugin is loaded from a dynamic library at runtime by the compiler. To
register a plugin in a library, use `FrontendPluginRegistry::Add<>`:

```c++
static FrontendPluginRegistry::Add<MyPlugin> X("my-plugin-name", "my plugin description");
```

## Defining pragmas

Plugins can also define pragmas by declaring a `PragmaHandler` and
registering it using `PragmaHandlerRegistry::Add<>`:

```c++
// Define a pragma handler for #pragma example_pragma
class ExamplePragmaHandler : public PragmaHandler {
public:
  ExamplePragmaHandler() : PragmaHandler("example_pragma") { }
  void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
                    Token &PragmaTok) {
    // Handle the pragma
  }
};

static PragmaHandlerRegistry::Add<ExamplePragmaHandler> Y("example_pragma","example pragma description");
```

## Defining attributes

Plugins can define attributes by declaring a `ParsedAttrInfo` and registering
it using `ParsedAttrInfoRegister::Add<>`:

```c++
class ExampleAttrInfo : public ParsedAttrInfo {
public:
  ExampleAttrInfo() {
    Spellings.push_back({ParsedAttr::AS_GNU,"example"});
  }
  AttrHandling handleDeclAttribute(Sema &S, Decl *D,
                                   const ParsedAttr &Attr) const override {
    // Handle the attribute
    return AttributeApplied;
  }
};

static ParsedAttrInfoRegistry::Add<ExampleAttrInfo> Z("example_attr","example attribute description");
```

The members of `ParsedAttrInfo` that a plugin attribute must define are:

- `Spellings`, which must be populated with every [Spelling](https://clang.llvm.org/doxygen/structclang_1_1ParsedAttrInfo_1_1Spelling.html) of the
  attribute, each of which consists of an attribute syntax and how the
  attribute name is spelled for that syntax. If the syntax allows a scope then
  the spelling must be "scope::attr" if a scope is present or "::attr" if not.

The members of `ParsedAttrInfo` that may need to be defined, depending on the
attribute, are:

- `NumArgs` and `OptArgs`, which set the number of required and optional
  arguments to the attribute.
- `diagAppertainsToDecl`, which checks if the attribute has been used on the
  right kind of declaration and issues a diagnostic if not.
- `handleDeclAttribute`, which is the function that applies the attribute to
  a declaration. It is responsible for checking that the attribute's arguments
  are valid, and typically applies the attribute by adding an `Attr` to the
  `Decl`. It returns either `AttributeApplied`, to indicate that the
  attribute was successfully applied, or `AttributeNotApplied` if it wasn't.
- `diagAppertainsToStmt`, which checks if the attribute has been used on the
  right kind of statement and issues a diagnostic if not.
- `handleStmtAttribute`, which is the function that applies the attribute to
  a statement. It is responsible for checking that the attribute's arguments
  are valid, and typically applies the attribute by adding an `Attr` to the
  `Stmt`. It returns either `AttributeApplied`, to indicate that the
  attribute was successfully applied, or `AttributeNotApplied` if it wasn't.
- `diagLangOpts`, which checks if the attribute is permitted for the current
  language mode and issues a diagnostic if not.
- `existsInTarget`, which checks if the attribute is permitted for the given
  target.

To see a working example of an attribute plugin, see [the Attribute.cpp example](https://github.com/llvm/llvm-project/blob/main/clang/examples/Attribute/Attribute.cpp).

## Putting it all together

Let's look at an example plugin that prints top-level function names. This
example is checked into the clang repository; please take a look at
the [latest version of PrintFunctionNames.cpp](https://github.com/llvm/llvm-project/blob/main/clang/examples/PrintFunctionNames/PrintFunctionNames.cpp).

## Running the plugin

### Using the compiler driver

The Clang driver accepts the `-fplugin` option to load a plugin.
Clang plugins can receive arguments from the compiler driver command
line via the `fplugin-arg-<plugin name>-<argument>` option. Using this
method, the plugin name cannot contain dashes itself, but the argument
passed to the plugin can.

```console
$ export BD=/path/to/build/directory
$ make -C $BD CallSuperAttr
$ clang++ -fplugin=$BD/lib/CallSuperAttr.so \
          -fplugin-arg-call_super_plugin-help \
          test.cpp
```

If your plugin name contains dashes, either rename the plugin or use the
cc1 command line options listed below.

### Using the cc1 command line

To run a plugin, the dynamic library containing the plugin registry must be
loaded via the `-load` command line option. This will load all plugins
that are registered, and you can select the plugins to run by specifying the
`-plugin` option. Additional parameters for the plugins can be passed with
`-plugin-arg-<plugin-name>`.

Note that those options must reach clang's cc1 process. There are two
ways to do so:

- Directly call the parsing process by using the `-cc1` option; this
  has the downside of not configuring the default header search paths, so
  you'll need to specify the full system path configuration on the command
  line.
- Use clang as usual, but prefix all arguments to the cc1 process with
  `-Xclang`.

For example, to run the `print-function-names` plugin over a source file in
clang, first build the plugin, and then call clang with the plugin from the
source tree:

```console
$ export BD=/path/to/build/directory
$ (cd $BD && make PrintFunctionNames )
$ clang++ -D_GNU_SOURCE -D_DEBUG -D__STDC_CONSTANT_MACROS \
          -D__STDC_FORMAT_MACROS -D__STDC_LIMIT_MACROS -D_GNU_SOURCE \
          -I$BD/tools/clang/include -Itools/clang/include -I$BD/include -Iinclude \
          tools/clang/tools/clang-check/ClangCheck.cpp -fsyntax-only \
          -Xclang -load -Xclang $BD/lib/PrintFunctionNames.so -Xclang \
          -plugin -Xclang print-fns
```

Also see the print-function-name plugin example's
[README](https://github.com/llvm/llvm-project/blob/main/clang/examples/PrintFunctionNames/README.txt)

### Using the clang command line

Using `-fplugin=plugin` on the clang command line passes the plugin
through as an argument to `-load` on the cc1 command line. If the plugin
class implements the `getActionType` method then the plugin is run
automatically. For example, to run the plugin automatically after the main AST
action (i.e. the same as using `-add-plugin`):

```c++
// Automatically run the plugin after the main AST action
PluginASTAction::ActionType getActionType() override {
  return AddAfterMainAction;
}
```

### Interaction with `-clear-ast-before-backend`

To reduce peak memory usage of the compiler, plugins are recommended to run
*before* the main action, which is usually code generation. This is because
having any plugins that run after the codegen action automatically turns off
`-clear-ast-before-backend`. `-clear-ast-before-backend` reduces peak
memory by clearing the Clang AST after generating IR and before running IR
optimizations. Use `CmdlineBeforeMainAction` or `AddBeforeMainAction` as
`getActionType` to run plugins while still benefitting from
`-clear-ast-before-backend`. Plugins must make sure not to modify the AST,
otherwise they should run after the main action.

---

### Clang Docs ClangRepl (`clang/docs/ClangRepl.md`)

# Clang-Repl

**Clang-Repl** is an interactive C++ interpreter that allows for incremental
compilation. It supports interactive programming for C++ in a
read-evaluate-print-loop (REPL) style. It uses Clang as a library to compile the
high level programming language into LLVM IR. Then the LLVM IR is executed by
the LLVM just-in-time (JIT) infrastructure.

Clang-Repl is suitable for exploratory programming and in places where time
to insight is important. Clang-Repl is a project inspired by the work in
[Cling](https://github.com/root-project/cling), a LLVM-based C/C++ interpreter
developed by the field of high energy physics and used by the scientific data
analysis framework [ROOT](https://root.cern/). Clang-Repl allows to move parts
of Cling upstream, making them useful and available to a broader audience.

## Clang-Repl Basic Data Flow

```{image} ClangRepl_design.png
:align: center
:alt: ClangRepl design
```

Clang-Repl data flow can be divided into roughly 8 phases:

1. Clang-Repl controls the input infrastructure by an interactive prompt or by
   an interface allowing the incremental processing of input.

2. Then it sends the input to the underlying incremental facilities in Clang
   infrastructure.

3. Clang compiles the input into an AST representation.

4. When required the AST can be further transformed in order to attach specific
   behavior.

5. The AST representation is then lowered to LLVM IR.

6. The LLVM IR is the input format for LLVM’s JIT compilation infrastructure.
   The tool will instruct the JIT to run specified functions, translating them
   into machine code targeting the underlying device architecture (eg. Intel
   x86 or NVPTX).

7. The LLVM JIT lowers the LLVM IR to machine code.

8. The machine code is then executed.

## Build Instructions:

```console
$ cd llvm-project
$ mkdir build
$ cd build
$ cmake -DCMAKE_BUILD_TYPE=RelWithDebInfo -DLLVM_ENABLE_PROJECTS=clang -G "Unix Makefiles" ../llvm
```

**Note here**, above RelWithDebInfo - Debug / Release

```console
cmake --build . --target clang clang-repl -j n
   OR
cmake --build . --target clang clang-repl
```

**Clang-repl** is built under llvm-project/build/bin. Proceed into the directory **llvm-project/build/bin**

```console
./clang-repl
clang-repl>
```

## Clang-Repl Usage

**Clang-Repl** is an interactive C++ interpreter that allows for incremental
compilation. It supports interactive programming for C++ in a
read-evaluate-print-loop (REPL) style. It uses Clang as a library to compile the
high level programming language into LLVM IR. Then the LLVM IR is executed by
the LLVM just-in-time (JIT) infrastructure.

## Basic:

```text
clang-repl> #include <iostream>
clang-repl> int f() { std::cout << "Hello Interpreted World!\n"; return 0; }
clang-repl> auto r = f();
 // Prints Hello Interpreted World!
```

```text
clang-repl> #include<iostream>
clang-repl> using namespace std;
clang-repl> std::cout << "Welcome to CLANG-REPL" << std::endl;
Welcome to CLANG-REPL
// Prints Welcome to CLANG-REPL
```

## Function Definitions and Calls:

```text
clang-repl> #include <iostream>
clang-repl> int sum(int a, int b){ return a+b; };
clang-repl> int c = sum(9,10);
clang-repl> std::cout << c << std::endl;
19
clang-repl>
```

## Iterative Structures:

```text
clang-repl> #include <iostream>
clang-repl> for (int i = 0;i < 3;i++){ std::cout << i << std::endl;}
0
1
2
clang-repl> while(i < 7){ i++; std::cout << i << std::endl;}
4
5
6
7
```

## Classes and Structures:

```text
clang-repl> #include <iostream>
clang-repl> class Rectangle {int width, height; public: void set_values (int,int);\
clang-repl... int area() {return width*height;}};
clang-repl>  void Rectangle::set_values (int x, int y) { width = x;height = y;}
clang-repl> int main () { Rectangle rect;rect.set_values (3,4);\
clang-repl... std::cout << "area: " << rect.area() << std::endl;\
clang-repl... return 0;}
clang-repl> main();
area: 12
clang-repl>
// Note: This '\' can be used for continuation of the statements in the next line
```

## Lamdas:

```text
clang-repl> #include <iostream>
clang-repl> using namespace std;
clang-repl> auto welcome = []()  { std::cout << "Welcome to REPL" << std::endl;};
clang-repl> welcome();
Welcome to REPL
```

## Comments:

```text
clang-repl> // Comments in Clang-Repl
clang-repl> /* Comments in Clang-Repl */
```

## Built in Commands:

clang-repl has some special commands that are of the form `%<something>`. To list all these commands, use the `%help` command:

### Help:

The `%help` command lists all built in clang-repl commands.

```text
clang-repl> %help
```

### Using Dynamic Libraries:

The `%lib` command links a dynamic library.

```text
clang-repl> %lib print.so
clang-repl> #include"print.hpp"
clang-repl> print(9);
9
```

**Generation of dynamic library**

```text
// print.cpp
#include <iostream>
#include "print.hpp"

void print(int a)
{
   std::cout << a << std::endl;
}

// print.hpp
void print (int a);

// Commands
clang++-17  -c -o print.o print.cpp
clang-17 -shared print.o -o print.so
```

### Undo:

The `%undo` command undoes the previous input.

```text
clang-repl> int a = 1; a
(int) 1
clang-repl> %undo
clang-repl> a
In file included from <<< inputs >>>:1:
input_line_2:1:1: error: use of undeclared identifier 'a'
1 | a
* | ^
error: Parsing failed.
```

### Quit:

The `%quit` command terminates clang-repl.

```text
clang-repl> %quit
```

Just like Clang, Clang-Repl can be integrated in existing applications as a library
(using the clangInterpreter library). This turns your C++ compiler into a service that
can incrementally consume and execute code. The **Compiler as A Service** (**CaaS**)
concept helps support advanced use cases such as template instantiations on demand and
automatic language interoperability. It also helps static languages such as C/C++ become
apt for data science.

## Execution Results Handling in Clang-Repl

Execution Results Handling features discussed below help extend the Clang-Repl
functionality by creating an interface between the execution results of a
program and the compiled program.

1\. **Capture Execution Results**: This feature helps capture the execution results
of a program and bring them back to the compiled program.

2\. **Dump Captured Execution Results**: This feature helps create a temporary dump
for Value Printing/Automatic Printf, that is, to display the value and type of
the captured data.

## 1. Capture Execution Results

In many cases, it is useful to bring back the program execution result to the
compiled program. This result can be stored in an object of type **Value**.

### How Execution Results are captured (Value Synthesis):

The synthesizer chooses which expression to synthesize, and then it replaces
the original expression with the synthesized expression. Depending on the
expression type, it may choose to save an object (`LastValue`) of type 'value'
while allocating memory to it (`SetValueWithAlloc()`), or not
(`SetValueNoAlloc()`).

```
/* Detailed source-code truncated for AI context efficiency. */
```

### Where is the captured result stored?

`LastValue` holds the last result of the value printing. It is a class member
because it can be accessed even after subsequent inputs.

**Note:** If no value printing happens, then it is in an invalid state.

### Improving Efficiency and User Experience

The Value object is essentially used to create a mapping between an expression
'type' and the allocated 'memory'. Built-in types (bool, char, int,
float, double, etc.) are copyable. Their memory allocation size is known
and the Value object can introduce a small-buffer optimization.
In case of objects, the `Value` class provides reference-counted memory
management.

The implementation maps the type as written and the Clang Type to be able to use
the preprocessor to synthesize the relevant cast operations. For example,
`X(char, Char_S)`, where `char` is the type from the language's type system
and `Char_S` is the Clang builtin type which represents it. This mapping helps
to import execution results from the interpreter in a compiled program and vice
versa. The `Value.h` header file can be included at runtime and this is why it
has a very low token count and was developed with strict constraints in mind.

This also enables the user to receive the computed 'type' back in their code
and then transform the type into something else (e.g., re-cast a double into
a float). Normally, the compiler can handle these conversions transparently,
but in interpreter mode, the compiler cannot see all the 'from' and 'to' types,
so it cannot implicitly do the conversions. So this logic enables providing
these conversions on request.

On-request conversions can help improve the user experience, by allowing
conversion to a desired 'to' type, when the 'from' type is unknown or unclear.

### Significance of this Feature

The 'Value' object enables wrapping a memory region that comes from the
JIT, and bringing it back to the compiled code (and vice versa).
This is a very useful functionality when:

- connecting an interpreter to the compiled code, or
- connecting an interpreter in another language.

For example, this feature helps transport values across boundaries. A notable
example is the cppyy project code makes use of this feature to enable running C++
within Python. It enables transporting values/information between C++
and Python.

Note: [cppyy](https://github.com/wlav/cppyy/) is an automatic, run-time,
Python-to-C++ bindings generator, for calling C++ from Python and Python from C++.
It uses LLVM along with a C++ interpreter (e.g., Cling) to enable features like
run-time instantiation of C++ templates, cross-inheritance, callbacks,
auto-casting, transparent use of smart pointers, etc.

In a nutshell, this feature enables a new way of developing code, paving the
way for language interoperability and easier interactive programming.

## Implementation Details

### Interpreter as a REPL vs. as a Library

1 - If we're using the interpreter in interactive (REPL) mode, it will dump
the value (i.e., value printing).

```console
if (LastValue.isValid()) {
  if (!V) {
    LastValue.dump();
    LastValue.clear();
  } else
    *V = std::move(LastValue);
}
```

2 - If we're using the interpreter as a library, then it will pass the value
to the user.

### Incremental AST Consumer

The `IncrementalASTConsumer` class wraps the original code generator
`ASTConsumer` and it performs a hook, to traverse all the top-level decls, to
look for expressions to synthesize, based on the `isSemiMissing()` condition.

If this condition is found to be true, then `Interp.SynthesizeExpr()` will be
invoked.

**Note:** Following is a sample code snippet. Actual code may vary over time.

```console
for (Decl *D : DGR)
  if (auto *TSD = llvm::dyn_cast<TopLevelStmtDecl>(D);
      TSD && TSD->isSemiMissing())
    TSD->setStmt(Interp.SynthesizeExpr(cast<Expr>(TSD->getStmt())));

return Consumer->HandleTopLevelDecl(DGR);
```

The synthesizer will then choose the relevant expression, based on its type.

### Communication between Compiled Code and Interpreted Code

In Clang-Repl there is **interpreted code**, and this feature adds a 'value'
runtime that can talk to the **compiled code**.

Following is an example where the compiled code interacts with the interpreter
code. The execution results of an expression are stored in the object 'V' of
type Value. This value is then printed, effectively helping the interpreter
use a value from the compiled code.

```console
int Global = 42;
void setGlobal(int val) { Global = val; }
int getGlobal() { return Global; }
Interp.ParseAndExecute(“void setGlobal(int val);”);
Interp.ParseAndExecute(“int getGlobal();”);
Value V;
Interp.ParseAndExecute(“getGlobal()”, &V);
std::cout << V.getAs<int>() << “\n”; // Prints 42
```

**Note:** Above is an example of interoperability between the compiled code and
the interpreted code. Interoperability between languages (e.g., C++ and Python)
works similarly.

## 2. Dump Captured Execution Results

This feature helps create a temporary dump to display the value and type
(pretty print) of the desired data. This is a good way to interact with the
interpreter during interactive programming.

### How value printing is simplified (Automatic Printf)

The `Automatic Printf` feature makes it easy to display variable values during
program execution. Using the `printf` function repeatedly is not required.
This is achieved using an extension in the `libclangInterpreter` library.

To automatically print the value of an expression, simply write the expression
in the global scope **without a semicolon**.

```{graphviz}
:name: automaticprintf
:caption: Automatic PrintF
:alt: Shows how Automatic PrintF can be used
:align: center

     digraph "AutomaticPrintF" {
         size="6,4";
         rankdir="LR";
         graph [fontname="Verdana", fontsize="12"];
         node [fontname="Verdana", fontsize="12"];
         edge [fontname="Sans", fontsize="9"];

         manual [label=" Manual PrintF ", shape="box"];
         int1 [label=" int ( &) 42 ", shape="box"]
         auto [label=" Automatic PrintF ", shape="box"];
         int2 [label=" int ( &) 42 ", shape="box"]

         auto -> int2 [label="int x = 42; \n x"];
         manual -> int1 [label="int x = 42; \n printf(&quot;(int &) %d \\n&quot;, x);"];
     }

```

### Significance of this feature

Inspired by a similar implementation in [Cling](https://github.com/root-project/cling),
this feature added to upstream Clang repo has essentially extended the syntax of
C++, so that it can be more helpful for people that are writing code for data
science applications.

This is useful, for example, when you want to experiment with a set of values
against a set of functions, and you'd like to know the results right away.
This is similar to how Python works (hence its popularity in data science
research), but the superior performance of C++, along with this flexibility
makes it a more attractive option.

## Implementation Details

### Parsing mechanism:

The Interpreter in Clang-Repl (`Interpreter.cpp`) includes the function
`ParseAndExecute()` that can accept a 'Value' parameter to capture the result.
But if the value parameter is made optional and it is omitted (i.e., that the
user does not want to utilize it elsewhere), then the last value can be
validated and pushed into the `dump()` function.

```{graphviz}
:name: parsing
:caption: Parsing Mechanism
:alt: Shows the Parsing Mechanism for Pretty Printing
:align: center


     digraph "prettyprint" {
         rankdir="LR";
         graph [fontname="Verdana", fontsize="12"];
         node [fontname="Verdana", fontsize="12"];
         edge [fontname="Verdana", fontsize="9"];

         parse [label=" ParseAndExecute() \n in Clang ", shape="box"];
         capture [label=" Capture 'Value' parameter \n for processing? ", shape="diamond"];
         use [label="  Use for processing  ", shape="box"];
         dump [label="  Validate and push  \n to dump()", shape="box"];
         callp [label="  call print() function ", shape="box"];
         type [label="  Print the Type \n ReplPrintTypeImpl()", shape="box"];
         data [label="  Print the Data \n ReplPrintDataImpl() ", shape="box"];
         output [label="  Output Pretty Print \n to the user  ", shape="box", fontcolor=white, fillcolor="#3333ff", style=filled];

         parse -> capture [label="Optional 'Value' Parameter"];
         capture -> use [label="Yes"];
         use -> End;
         capture -> dump [label="No"];
         dump -> callp;
         callp -> type;
         callp -> data;
         type -> output;
         data -> output;
      }
```

**Note:** Following is a sample code snippet. Actual code may vary over time.

```console
llvm::Error Interpreter::ParseAndExecute(llvm::StringRef Code, Value *V) {

auto PTU = Parse(Code);
if (!PTU)
    return PTU.takeError();
if (PTU->TheModule)
    if (llvm::Error Err = Execute(*PTU))
    return Err;

if (LastValue.isValid()) {
    if (!V) {
    LastValue.dump();
    LastValue.clear();
    } else
    *V = std::move(LastValue);
}
return llvm::Error::success();
}
```

The `dump()` function (in `value.cpp`) calls the `print()` function.

Printing the Data and Type are handled in their respective functions:
`ReplPrintDataImpl()` and `ReplPrintTypeImpl()`.

### Annotation Token (annot_repl_input_end)

This feature uses a new token (`annot_repl_input_end`) to consider printing the
value of an expression if it doesn't end with a semicolon. When parsing an
Expression Statement, if the last semicolon is missing, then the code will
pretend that there one and set a marker there for later utilization, and
continue parsing.

A semicolon is normally required in C++, but this feature expands the C++
syntax to handle cases where a missing semicolon is expected (i.e., when
handling an expression statement). It also makes sure that an error is not
generated for the missing semicolon in this specific case.

This is accomplished by identifying the end position of the user input
(expression statement). This helps store and return the expression statement
effectively, so that it can be printed (displayed to the user automatically).

**Note:** This logic is only available for C++ for now, since part of the
implementation itself requires C++ features. Future versions may support more
languages.

```console
Token *CurTok = nullptr;
// If the semicolon is missing at the end of REPL input, consider if
// we want to do value printing. Note this is only enabled in C++ mode
// since part of the implementation requires C++ language features.
// Note we shouldn't eat the token since the callback needs it.
if (Tok.is(tok::annot_repl_input_end) && Actions.getLangOpts().CPlusPlus)
  CurTok = &Tok;
else
  // Otherwise, eat the semicolon.
  ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);

StmtResult R = handleExprStmt(Expr, StmtCtx);
if (CurTok && !R.isInvalid())
  CurTok->setAnnotationValue(R.get());

return R;
  }
```

### AST Transformation

When Sema encounters the `annot_repl_input_end` token, it knows to transform
the AST before the real CodeGen process. It will consume the token and set a
'semi missing' bit in the respective decl.

```console
if (Tok.is(tok::annot_repl_input_end) &&
    Tok.getAnnotationValue() != nullptr) {
    ConsumeAnnotationToken();
    cast<TopLevelStmtDecl>(DeclsInGroup.back())->setSemiMissing();
}
```

In the AST Consumer, traverse all the Top Level Decls, to look for expressions
to synthesize. If the current Decl is the Top Level Statement
Decl(`TopLevelStmtDecl`) and has a semicolon missing, then ask the interpreter
to synthesize another expression (an internal function call) to replace this
original expression.

### Detailed RFC and Discussion:

For more technical details, community discussion and links to patches related
to these features,
Please visit: [RFC on LLVM Discourse](https://discourse.llvm.org/t/rfc-handle-execution-results-in-clang-repl/68493).

Some logic presented in the RFC (e.g. ValueGetter()) may be outdated,
compared to the final developed solution.

## Related Reading

[Cling Transitions to LLVM's Clang-Repl](https://root.cern/blog/cling-in-llvm/)

[Moving (parts of) the Cling REPL in Clang](https://lists.llvm.org/pipermail/llvm-dev/2020-July/143257.html)

[GPU Accelerated Automatic Differentiation With Clad](https://arxiv.org/pdf/2203.06139.pdf)

---

### Clang Docs ClangSYCLLinker (`clang/docs/ClangSYCLLinker.md`)

# Clang SYCL Linker


## Introduction

This tool works as a wrapper around the SYCL device code linking process.
The purpose of this tool is to provide an interface to link SYCL device bitcode
in LLVM IR format together with LLVM bitcode libraries, and then run SPIR-V
code generation on the fully linked device code to produce the final output.
After the linking stage, the fully linked device code in LLVM IR format may
undergo several SYCL-specific finalization steps before the SPIR-V code
generation step.
The tool will also support the Ahead-Of-Time (AOT) compilation flow. AOT
compilation is the process of invoking the back-end at compile time to produce
the final binary, as opposed to just-in-time (JIT) compilation when final code
generation is deferred until application runtime.

Device code linking for SYCL offloading has known quirks that make it
difficult to use in a unified offloading setting. The primary issue is that
several finalization steps are required to be run on the fully linked LLVM
IR bitcode to guarantee conformance to SYCL standards. This step is unique to
the SYCL offloading compilation flow.

This tool has been proposed to work around this issue.

## Usage

This tool can be used with the following options. Several of these options will
be passed down to downstream AOT compilation tools like 'ocloc' and 'opencl-aot'.

```
/* Detailed source-code truncated for AI context efficiency. */
```

## Library Linking

Device bitcode libraries can be packaged into archive libraries (`.a` files)
using `llvm-ar` and linked using the `-l` option:

```console
llvm-ar rc libdevice.a func1.bc func2.bc func3.bc
clang-sycl-linker input.bc -l device -L /path/to/libs
```

The linker supports standard archive library search semantics:

- `-l <name>` searches for `lib<name>.a` in the directories specified by `-L`
- `-l :<exact-name>` searches for the exact filename in the `-L` paths
- Absolute paths can be passed as positional arguments: `clang-sycl-linker input.bc /path/to/libdevice.a`

By default, archive linking is **lazy** - only archive members (individual `.bc` files)
that resolve undefined symbols are extracted and linked. This happens at file
granularity: if any symbol in a `.bc` file is needed, all symbols in that file
are included. The linker uses a symbol-driven fixed-point algorithm: it
repeatedly scans archives to extract members that resolve currently undefined
symbols until no more extractions occur.

To force extraction of all archive members regardless of symbol resolution, use
`--whole-archive`:

```console
clang-sycl-linker input.bc --whole-archive -l device --no-whole-archive -l other
```

The `-u <symbol>` option can be used to force a symbol to be undefined, which
can trigger extraction of archive members that define that symbol:

```console
clang-sycl-linker input.bc -u my_init_function -l device
```

## Examples

### Basic Usage

This tool is intended to be invoked when targeting any of the target offloading
toolchains. When the --sycl-link option is passed to the clang driver, the
driver will invoke the linking job of the target offloading toolchain, which in
turn will invoke this tool. This tool can be used to create one or more fully
linked device images that are ready to be wrapped and linked with host code to
generate the final executable.

```console
clang-sycl-linker --triple spirv64 --arch bmg_g21 input.bc
```

### Linking with Device Libraries

To link device bitcode libraries, first package them into archive files:

```console
# Create device library archives
llvm-ar rc libmath.a sin.bc cos.bc tan.bc
llvm-ar rc libutils.a helper1.bc helper2.bc

# Link with lazy loading (only needed members extracted)
clang-sycl-linker --triple spirv64 kernel.bc -l math -l utils -L /path/to/libs -o kernel.spv

# Force all members to be included from libmath.a
clang-sycl-linker --triple spirv64 kernel.bc --whole-archive -l math --no-whole-archive -l utils -L /path/to/libs -o kernel.spv

# Use exact archive filename or absolute path
clang-sycl-linker --triple spirv64 kernel.bc -l :libmath.a -L /path/to/libs -o kernel.spv
clang-sycl-linker --triple spirv64 kernel.bc /absolute/path/libmath.a -o kernel.spv
```

---

### Clang Docs ClangStaticAnalyzer (`clang/docs/ClangStaticAnalyzer.md`)

# Clang Static Analyzer

The Clang Static Analyzer is a source code analysis tool that finds bugs in C, C++, and Objective-C programs.
It implements *path-sensitive*, *inter-procedural analysis* based on *symbolic execution* technique.

The Static Analyzer is a part of Clang; for downloading and installing Clang visit the [LLVM releases page](https://releases.llvm.org/).

This is the documentation page of the Static Analyzer; there is also an old [Official Tool Page](https://clang-analyzer.llvm.org/) which provides a short overview of features and limitations.

```{toctree}
:caption: Table of Contents
:maxdepth: 2
:numbered:

analyzer/checkers
analyzer/user-docs
analyzer/developer-docs
```

---

### Clang Docs ClangTools (`clang/docs/ClangTools.md`)

# Overview

Clang Tools are standalone command line (and potentially GUI) tools
designed for use by C++ developers who are already using and enjoying
Clang as their compiler. These tools provide developer-oriented
functionality such as fast syntax checking, automatic formatting,
refactoring, etc.

Only a couple of the most basic and fundamental tools are kept in the
primary Clang tree. The rest of the tools are kept in a separate
directory tree, [clang-tools-extra](https://github.com/llvm/llvm-project/tree/main/clang-tools-extra).

This document describes a high-level overview of the organization of
Clang Tools within the project as well as giving an introduction to some
of the more important tools. However, it should be noted that this
document is currently focused on Clang and Clang Tool developers, not on
end users of these tools.

## Clang Tools Organization

Clang Tools are CLI or GUI programs that are intended to be directly
used by C++ developers. That is they are *not* primarily for use by
Clang developers, although they are hopefully useful to C++ developers
who happen to work on Clang, and we try to actively dogfood their
functionality. They are developed in three components: the underlying
infrastructure for building a standalone tool based on Clang, core
shared logic used by many different tools in the form of refactoring and
rewriting libraries, and the tools themselves.

The underlying infrastructure for Clang Tools is the
{doc}`LibTooling <LibTooling>` platform. See its documentation for much
more detailed information about how this infrastructure works. The
common refactoring and rewriting toolkit-style library is also part of
LibTooling organizationally.

A few Clang Tools are developed along side the core Clang libraries as
examples and test cases of fundamental functionality. However, most of
the tools are developed in a side repository to provide easy separation
from the core libraries. We intentionally do not support public
libraries in the side repository, as we want to carefully review and
find good APIs for libraries as they are lifted out of a few tools and
into the core Clang library set.

Regardless of which repository Clang Tools' code resides in, the
development process and practices for all Clang Tools are exactly those
of Clang itself. They are entirely within the Clang *project*,
regardless of the version control scheme.

## Core Clang Tools

The core set of Clang tools that are within the main repository are
tools that very specifically complement, and allow use and testing of
*Clang* specific functionality.

### `clang-check`

{doc}`ClangCheck` combines the LibTooling framework for running a
Clang tool with the basic Clang diagnostics by syntax checking specific files
in a fast, command line interface. It can also accept flags to re-display the
diagnostics in different formats with different flags, suitable for use driving
an IDE or editor. Furthermore, it can be used in fixit-mode to directly apply
fixit-hints offered by clang. See {doc}`HowToSetupToolingForLLVM` for
instructions on how to setup and use `clang-check`.

### `clang-format`

Clang-format is both a {doc}`library <LibFormat>` and a {doc}`stand-alone tool
<ClangFormat>` with the goal of automatically reformatting C++ source files
according to configurable style guides. To do so, clang-format uses Clang's
`Lexer` to transform an input file into a token stream and then changes all
the whitespace around those tokens. The goal is for clang-format to serve both
as a user tool (ideally with powerful IDE integrations) and as part of other
refactoring tools, e.g. to do a reformatting of all the lines changed during a
renaming.

## Extra Clang Tools

As various categories of Clang Tools are added to the extra repository,
they'll be tracked here. The focus of this documentation is on the scope
and features of the tools for other tool developers; each tool should
provide its own user-focused documentation.

### `Clang-Doc`

[Clang-Doc](https://clang.llvm.org/extra/clang-doc.html) is a tool for
generating C and C++ documentation from source code and comments.

### `Clang-Include-Fixer`

[Clang-Include-Fixer](https://clang.llvm.org/extra/clang-include-fixer.html)
is a tool to automate the addition of missing `#include` directives in a C++
file. It adds missing namespace qualifiers to unidentified symbols when
necessary and also removes unused headers.

### `Clang-Tidy`

[Clang-Tidy](https://clang.llvm.org/extra/clang-tidy/) is a Clang-based C++
linter tool. It provides an extensible framework for building compiler-based
static analyses detecting and fixing bug-prone patterns, performance,
portability and maintainability issues. It also has checks for modernizing code
to newer language standards.

### `Clangd`

[Clangd](https://clangd.llvm.org/) is a language server that can work with
many editors via a plugin. It understands your C++ code and adds smart
features to your editor: code completion, compile errors, go-to-definition and
more.

### `Modularize`

[Modularize](https://clang.llvm.org/extra/modularize.html) is a standalone
tool that checks whether a set of headers provides the consistent definitions
required to use modules.

### `pp-trace`

[pp-trace](https://clang.llvm.org/extra/pp-trace.html) is a standalone tool
that traces preprocessor activity. It’s also used as a test of Clang’s
`PPCallbacks` interface.

## Ideas for new Tools

- C++ cast conversion tool. Will convert C-style casts (`(type) value`) to
  appropriate C++ cast (`static_cast`, `const_cast` or
  `reinterpret_cast`).

- Non-member `begin()` and `end()` conversion tool. Will convert
  `foo.begin()` into `begin(foo)` and similarly for `end()`, where
  `foo` is a standard container. We could also detect similar patterns for
  arrays.

- `tr1` removal tool. Will migrate source code from using TR1 library
  features to C++11 library. For example:

  ```c++
  #include <tr1/unordered_map>
  int main()
  {
      std::tr1::unordered_map <int, int> ma;
      std::cout << ma.size () << std::endl;
      return 0;
  }
  ```

  should be rewritten to:

  ```c++
  #include <unordered_map>
  int main()
  {
      std::unordered_map <int, int> ma;
      std::cout << ma.size () << std::endl;
      return 0;
  }
  ```

- A tool to remove `auto`. Will convert `auto` to an explicit type or add
  comments with deduced types. The motivation is that there are developers
  that don't want to use `auto` because they are afraid that they might lose
  control over their code.

- C++14: less verbose operator function objects ([N3421](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3421.htm)).
  For example:

  ```c++
  sort(v.begin(), v.end(), greater<ValueType>());
  ```

  should be rewritten to:

  ```c++
  sort(v.begin(), v.end(), greater<>());
  ```

---

### Clang Docs ClangTransformerTutorial (`clang/docs/ClangTransformerTutorial.md`)

# Clang Transformer Tutorial

A tutorial on how to write a source-to-source translation tool using Clang Transformer.


## What is Clang Transformer?

Clang Transformer is a framework for writing C++ diagnostics and program
transformations. It is built on the clang toolchain and the LibTooling library,
but aims to hide much of the complexity of clang's native, low-level libraries.

The core abstraction of Transformer is the *rewrite rule*, which specifies how
to change a given program pattern into a new form. Here are some examples of
tasks you can achieve with Transformer:

- warn against using the name `MkX` for a declared function,
- change `MkX` to `MakeX`, where `MkX` is the name of a declared function,
- change `s.size()` to `Size(s)`, where `s` is a `string`,
- collapse `e.child().m()` to `e.m()`, for any expression `e` and method named
  `m`.

All of the examples have a common form: they identify a pattern that is the
target of the transformation, they specify an *edit* to the code identified by
the pattern, and their pattern and edit refer to common variables, like `s`,
`e`, and `m`, that range over code fragments. Our first and second examples also
specify constraints on the pattern that aren't apparent from the syntax alone,
like "`s` is a `string`." Even the first example ("warn ...") shares this form,
even though it doesn't change any of the code -- it's "edit" is simply a no-op.

Transformer helps users succinctly specify rules of this sort and easily execute
them locally over a collection of files, apply them to selected portions of
a codebase, or even bundle them as a clang-tidy check for ongoing application.

## Who is Clang Transformer for?

Clang Transformer is for developers who want to write clang-tidy checks or write
tools to modify a large number of C++ files in (roughly) the same way. What
qualifies as "large" really depends on the nature of the change and your
patience for repetitive editing. In our experience, automated solutions become
worthwhile somewhere between 100 and 500 files.

## Getting Started

Patterns in Transformer are expressed with {doc}`clang's AST matchers <LibASTMatchers>`.
Matchers are a language of combinators for describing portions of a clang
Abstract Syntax Tree (AST). Since clang's AST includes complete type information
(within the limits of single [Translation Unit (TU)]),
these patterns can even encode rich constraints on the type properties of AST
nodes.

[Translation Unit (TU)]: https://en.wikipedia.org/wiki/Translation_unit_(programming)

We assume a familiarity with the clang AST and the corresponding AST matchers
for the purpose of this tutorial. Users who are unfamiliar with either are
encouraged to start with the recommended references in [Related Reading](#related-reading).

### Example: style-checking names

Assume you have a style-guide rule which forbids functions from being named
"MkX" and you want to write a check that catches any violations of this rule. We
can express this a Transformer rewrite rule:

```c++
makeRule(functionDecl(hasName("MkX")).bind("fun"),
         noopEdit(node("fun")),
         cat("The name ``MkX`` is not allowed for functions; please rename"));
```

`makeRule` is our go-to function for generating rewrite rules. It takes three
arguments: the pattern, the edit, and (optionally) an explanatory note. In our
example, the pattern (`functionDecl(...)`) identifies the declaration of the
function `MkX`. Since we're just diagnosing the problem, but not suggesting a
fix, our edit is a no-op. But, it contains an *anchor* for the diagnostic
message: `node("fun")` says to associate the message with the source range of
the AST node bound to "fun"; in this case, the ill-named function declaration.
Finally, we use `cat` to build a message that explains the change. Regarding the
name `cat` -- we'll discuss it in more detail below, but suffice it to say that
it can also take multiple arguments and concatenate their results.

Note that the result of `makeRule` is a value of type
`clang::transformer::RewriteRule`, but most users don't need to care about the
details of this type.

### Example: renaming a function

Now, let's extend this example to a *transformation*; specifically, the second
example above:

```c++
makeRule(declRefExpr(to(functionDecl(hasName("MkX")))),
         changeTo(cat("MakeX")),
         cat("MkX has been renamed MakeX"));
```

In this example, the pattern (`declRefExpr(...)`) identifies any *reference* to
the function `MkX`, rather than the declaration itself, as in our previous
example. Our edit (`changeTo(...)`) says to *change* the code matched by the
pattern *to* the text "MakeX". Finally, we use `cat` again to build a message
that explains the change.

Here are some example changes that this rule would make:

| Original               | Result                   |
| ---------------------- | ------------------------ |
| `X x = MkX(3);`        | `X x = MakeX(3);`        |
| `CallFactory(MkX, 3);` | `CallFactory(MakeX, 3);` |
| `auto f = MkX;`        | `auto f = MakeX;`        |

### Example: method to function

Next, let's write a rule to replace a method call with a (free) function call,
applied to the original method call's target object. Specifically, "change
`s.size()` to `Size(s)`, where `s` is a `string`." We start with a simpler
change that ignores the type of `s`. That is, it will modify *any* method call
where the method is named "size":

```c++
llvm::StringRef s = "str";
makeRule(
  cxxMemberCallExpr(
    on(expr().bind(s)),
    callee(cxxMethodDecl(hasName("size")))),
  changeTo(cat("Size(", node(s), ")")),
  cat("Method ``size`` is deprecated in favor of free function ``Size``"));
```

We express the pattern with the given AST matcher, which binds the method call's
target to `s` [^f1]. For the edit, we again use `changeTo`, but this
time we construct the term from multiple parts, which we compose with `cat`. The
second part of our term is `node(s)`, which selects the source code
corresponding to the AST node `s` that was bound when a match was found in the
AST for our rule's pattern. `node(s)` constructs a `RangeSelector`, which, when
used in `cat`, indicates that the selected source should be inserted in the
output at that point.

Now, we probably don't want to rewrite *all* invocations of "size" methods, just
those on `std::string`s. We can achieve this change simply by refining our
matcher. The rest of the rule remains unchanged:

```c++
llvm::StringRef s = "str";
makeRule(
  cxxMemberCallExpr(
    on(expr(hasType(namedDecl(hasName("std::string"))))
      .bind(s)),
    callee(cxxMethodDecl(hasName("size")))),
  changeTo(cat("Size(", node(s), ")")),
  cat("Method ``size`` is deprecated in favor of free function ``Size``"));
```

### Example: rewriting method calls

In this example, we delete an "intermediary" method call in a string of
invocations. This scenario can arise, for example, if you want to collapse a
substructure into its parent.

```c++
llvm::StringRef e = "expr", m = "member";
auto child_call = cxxMemberCallExpr(on(expr().bind(e)),
                                    callee(cxxMethodDecl(hasName("child"))));
makeRule(cxxMemberCallExpr(on(child_call), callee(memberExpr().bind(m)),
         changeTo(cat(e, ".", member(m), "()"))),
         cat("``child`` accessor is being removed; call ",
             member(m), " directly on parent"));
```

This rule isn't quite what we want: it will rewrite `my_object.child().foo()` to
`my_object.foo()`, but it will also rewrite `my_ptr->child().foo()` to
`my_ptr.foo()`, which is not what we intend. We could fix this by restricting
the pattern with `not(isArrow())` in the definition of `child_call`. Yet, we
*want* to rewrite calls through pointers.

To capture this idiom, we provide the `access` combinator to intelligently
construct a field/method access. In our example, the member access is expressed
as:

```c++
access(e, cat(member(m)))
```

The first argument specifies the object being accessed and the second, a
description of the field/method name. In this case, we specify that the method
name should be copied from the source -- specifically, the source range of `m`'s
member. To construct the method call, we would use this expression in `cat`:

```c++
cat(access(e, cat(member(m))), "()")
```

## Reference: ranges, stencils, edits, rules

The above examples demonstrate just the basics of rewrite rules. Every element
we touched on has more available constructors: range selectors, stencils, edits
and rules. In this section, we'll briefly review each in turn, with references
to the source headers for up-to-date information. First, though, we clarify what
rewrite rules are actually rewriting.

### Rewriting ASTs to... Text?

The astute reader may have noticed that we've been somewhat vague in our
explanation of what the rewrite rules are actually rewriting. We've referred to
"code", but code can be represented both as raw source text and as an abstract
syntax tree. So, which one is it?

Ideally, we'd be rewriting the input AST to a new AST, but clang's AST is not
terribly amenable to this kind of transformation. So, we compromise: we express
our patterns and the names that they bind in terms of the AST, but our changes
in terms of source code text. We've designed Transformer's language to bridge
the gap between the two representations, in an attempt to minimize the user's
need to reason about source code locations and other, low-level syntactic
details.

### Range Selectors

Transformer provides a small API for describing source ranges: the
`RangeSelector` combinators. These ranges are most commonly used to specify the
source code affected by an edit and to extract source code in constructing new
text.

Roughly, there are two kinds of range combinators: ones that select a source
range based on the AST, and others that combine existing ranges into new ranges.
For example, `node` selects the range of source spanned by a particular AST
node, as we've seen, while `after` selects the (empty) range located immediately
after its argument range. So, `after(node("id"))` is the empty range immediately
following the AST node bound to `id`.

For the full collection of `RangeSelector`s, see the header,
[clang/Tooling/Transformer/RangeSelector.h](https://github.com/llvm/llvm-project/blob/main/clang/include/clang/Tooling/Transformer/RangeSelector.h)

### Stencils

Transformer offers a large and growing collection of combinators for
constructing output. Above, we demonstrated `cat`, the core function for
constructing stencils. It takes a series of arguments, of three possible kinds:

1. Raw text, to be copied directly to the output.
2. Selector: specified with a `RangeSelector`, indicates a range of source text
   to copy to the output.
3. Builder: an operation that constructs a code snippet from its arguments. For
   example, the `access` function we saw above.

Data of these different types are all represented (generically) by a `Stencil`.
`cat` takes text and `RangeSelector`s directly as arguments, rather than
requiring that they be constructed with a builder; other builders are
constructed explicitly.

In general, `Stencil`s produce text from a match result. So, they are not
limited to generating source code, but can also be used to generate diagnostic
messages that reference (named) elements of the matched code, like we saw in the
example of rewriting method calls.

Further details of the `Stencil` type are documented in the header file
[clang/Tooling/Transformer/Stencil.h](https://github.com/llvm/llvm-project/blob/main/clang/include/clang/Tooling/Transformer/Stencil.h).

### Edits

Transformer supports additional forms of edits. First, in a `changeTo`, we can
specify the particular portion of code to be replaced, using the same
`RangeSelector` we saw earlier. For example, we could change the function name
in a function declaration with:

```c++
makeRule(functionDecl(hasName("bad")).bind(f),
         changeTo(name(f), cat("good")),
         cat("bad is now good"));
```

We also provide simpler editing primitives for insertion and deletion:
`insertBefore`, `insertAfter` and `remove`. These can all be found in the header
file
[clang/Tooling/Transformer/RewriteRule.h](https://github.com/llvm/llvm-project/blob/main/clang/include/clang/Tooling/Transformer/RewriteRule.h).

We are not limited one edit per match found. Some situations require making
multiple edits for each match. For example, suppose we wanted to swap two
arguments of a function call.

For this, we provide an overload of `makeRule` that takes a list of edits,
rather than just a single one. Our example might look like:

```c++
makeRule(callExpr(...),
        {changeTo(node(arg0), cat(node(arg2))),
         changeTo(node(arg2), cat(node(arg0)))},
        cat("swap the first and third arguments of the call"));
```

### `EditGenerator`s (Advanced)

The particular edits we've seen so far are all instances of the `ASTEdit` class,
or a list of such. But, not all edits can be expressed as `ASTEdit`s. So, we
also support a very general signature for edit generators:

```c++
using EditGenerator = MatchConsumer<llvm::SmallVector<Edit, 1>>;
```

That is, an `EditGenerator` is function that maps a `MatchResult` to a set
of edits, or fails. This signature supports a very general form of computation
over match results. Transformer provides a number of functions for working with
`EditGenerator`s, most notably
[flatten](https://github.com/llvm/llvm-project/blob/1fabe6e51917bcd7a1242294069c682fe6dffa45/clang/include/clang/Tooling/Transformer/RewriteRule.h#L165-L167)
`EditGenerator`s, like list flattening. For the full list, see the header file
[clang/Tooling/Transformer/RewriteRule.h](https://github.com/llvm/llvm-project/blob/main/clang/include/clang/Tooling/Transformer/RewriteRule.h).

### Rules

We can also compose multiple *rules*, rather than just edits within a rule,
using `applyFirst`: it composes a list of rules as an ordered choice, where
Transformer applies the first rule whose pattern matches, ignoring others in the
list that follow. If the matchers are independent then order doesn't matter. In
that case, `applyFirst` is simply joining the set of rules into one.

The benefit of `applyFirst` is that, for some problems, it allows the user to
more concisely formulate later rules in the list, since their patterns need not
explicitly exclude the earlier patterns of the list. For example, consider a set
of rules that rewrite compound statements, where one rule handles the case of an
empty compound statement and the other handles non-empty compound statements.
With `applyFirst`, these rules can be expressed compactly as:

```c++
applyFirst({
  makeRule(compoundStmt(statementCountIs(0)).bind("empty"), ...),
  makeRule(compoundStmt().bind("non-empty"),...)
})
```

The second rule does not need to explicitly specify that the compound statement
is non-empty -- it follows from the rules position in `applyFirst`. For more
complicated examples, this can lead to substantially more readable code.

Sometimes, a modification to the code might require the inclusion of a
particular header file. To this end, users can modify rules to specify include
directives with `addInclude`.

For additional documentation on these functions, see the header file
[clang/Tooling/Transformer/RewriteRule.h](https://github.com/llvm/llvm-project/blob/main/clang/include/clang/Tooling/Transformer/RewriteRule.h).

## Using a RewriteRule as a clang-tidy check

Transformer supports executing a rewrite rule as a
[clang-tidy](https://clang.llvm.org/extra/clang-tidy/) check, with the class
`clang::tidy::utils::TransformerClangTidyCheck`. It is designed to require
minimal code in the definition. For example, given a rule
`MyCheckAsRewriteRule`, one can define a tidy check as follows:

```c++
class MyCheck : public TransformerClangTidyCheck {
 public:
  MyCheck(StringRef Name, ClangTidyContext *Context)
      : TransformerClangTidyCheck(MyCheckAsRewriteRule, Name, Context) {}
};
```

`TransformerClangTidyCheck` implements the virtual `registerMatchers` and
`check` methods based on your rule specification, so you don't need to implement
them yourself. If the rule needs to be configured based on the language options
and/or the clang-tidy configuration, it can be expressed as a function taking
these as parameters and (optionally) returning a `RewriteRule`. This would be
useful, for example, for our method-renaming rule, which is parameterized by the
original name and the target. For details, see
[clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.h](https://github.com/llvm/llvm-project/blob/main/clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.h)

## Related Reading

A good place to start understanding the clang AST and its matchers is with the
introductions on clang's site:

- {doc}`Introduction to the Clang AST <IntroductionToTheClangAST>`
- {doc}`Matching the Clang AST <LibASTMatchers>`
- [AST Matcher Reference](LibASTMatchersReference.html){.external}

:::{rubric} Footnotes
:::

[^f1]: Technically, it binds it to the string "str", to which our
    variable `s` is bound. But, the choice of that id string is
    irrelevant, so elide the difference.

---

### Clang Docs ConstantInterpreter (`clang/docs/ConstantInterpreter.md`)

# Constant Interpreter


## Introduction

The bytecode interpreter aims to replace the existing AST traversal-based
evaluator in Clang, improving performance on constructs which are executed
inefficiently by the evaluator. The interpreter is activated by passing
`-fexperimental-new-constant-interpreter` to clang.

Since Clang 23, the bytecode interpreter can also be enabled by default
by passing `-DCLANG_USE_EXPERIMENTAL_CONST_INTERP=ON` to cmake. In
that case, it can be deactivated again via
`-fno-experimental-new-constant-interpreter`.

## Bytecode Compilation

Bytecode compilation is handled in `Compiler.h` for statements
and for expressions. The compiler has two different
backends: one to generate bytecode for functions (`ByteCodeEmitter`) and
one to directly evaluate expressions as they are compiled, without
generating bytecode (`EvalEmitter`). All functions are compiled to
bytecode, while toplevel expressions used in constant contexts are directly
evaluated since the bytecode would never be reused. This mechanism aims to
pave the way towards replacing the evaluator, improving its performance on
functions and loops, while being just as fast on single-use toplevel
expressions.

The interpreter relies on stack-based, strongly-typed opcodes. The glue
logic between the code generator, along with the enumeration and
description of opcodes, can be found in `Opcodes.td`. The opcodes are
implemented as generic template methods in `Interp.h` and instantiated
with the relevant primitive types by the interpreter loop or by the
evaluating emitter.

### Primitive Types

- `PT_{U|S}int{8|16|32|64}`

  Signed or unsigned integers of a specific bit width.
  1-byte types are also 1 byte in size. Sizes >= 16 bits are implemented
  using the `Integral` class. They take up 24 bytes each since they
  need to be able to represent a pointer that has been casted to an integer.

- `PT_IntAP{S}`

  Signed or unsigned integers of an arbitrary, but fixed width used to
  implement integral types which are required by the target, but are not
  supported by the host. Under the hood, they rely on `APInt`. The
  `Integral` specialisation for these types is required by opcodes to
  share an implementation with fixed integrals.

- `PT_Bool`

  Representation for boolean types, essentially a 1-bit unsigned
  `Integral`.

- `PT_Float`

  Arbitrary, but fixed precision floating point numbers. Could be
  specialised in the future similarly to integers in order to improve
  floating point performance.

- `PT_Ptr`

  Pointer type, defined in `"Pointer.h"`. The most common type of
  pointer is a "BlockPointer", which points to an `interp::Block`.
  But other pointer types exist, such as typeid pointers or
  integral pointers.

- `PT_MemberPtr`

  Member pointer type, can also be a null member pointer. Defined
  in `"MemberPointer.h"`

### Composite types

The interpreter distinguishes two kinds of composite types: arrays and
records (structs and classes). Unions are represented as records, except
at most a single field can be marked as active. The contents of inactive
fields are kept until they are reactivated and overwritten.
Complex numbers (`_Complex`) and vectors
(`__attribute((vector_size(16)))`) are treated as arrays.

## Bytecode Execution

Bytecode is executed using a stack-based interpreter. The execution
context consists of an `InterpStack`, along with a chain of
`InterpFrame` objects storing the call frames. Frames are built by
call instructions and destroyed by return instructions. They perform
one allocation to reserve space for all locals in a single block.
These objects store all the required information to emit stack traces
whenever evaluation fails.

## Memory Organisation

Memory management in the interpreter relies on 3 data structures: `Block`
objects which store the data and associated inline metadata, `Pointer`
objects which refer to or into blocks, and `Descriptor` structures which
describe blocks and subobjects nested inside blocks.

### Blocks

Blocks contain data interleaved with metadata. They are allocated either
statically in the code generator (globals, static members, dummy parameter
values etc.) or dynamically in the interpreter, when creating the frame
containing the local variables of a function. Blocks are associated with a
descriptor that characterises the entire allocation, along with a few
additional attributes:

- `IsStatic` indicates whether the block has static duration in the
  interpreter, i.e. it is not a local in a frame.
- `DeclID` identifies each global declaration (it is set to an invalid
  and irrelevant value for locals) in order to prevent illegal writes and
  reads involving globals and temporaries with static storage duration.

Static blocks are never deallocated, but local ones might be deallocated
even when there are live pointers to them. Pointers are only valid as
long as the blocks they point to are valid, so a block with pointers to
it whose lifetime ends is kept alive until all pointers to it go out of
scope. Since the frame is destroyed on function exit, such blocks are
turned into a `DeadBlock` and copied to storage managed by the
interpreter itself, not the frame. Reads and writes to these blocks are
illegal and cause an appropriate diagnostic to be emitted. When the last
pointer goes out of scope, dead blocks are also deallocated.

The lifetime of blocks is managed through 2 methods stored in the
descriptor of the block:

- **CtorFn**: initializes the metadata which is stored in the block,
  alongside actual data. Invokes the default constructors of objects
  which are not trivial (`Pointer`, `Floating`, etc.)
- **DtorFn**: invokes the destructors of non-trivial objects.

Blocks track all the pointers into them through an intrusive
doubly-linked list, required to adjust and invalidate all pointers when
transforming a block into a dead block. If the lifetime of an object ends,
all pointers to it are invalidated, emitting the appropriate diagnostics when
dereferenced.

Records are laid out identically to arrays of composites: each field and base
class is preceded by an inline descriptor. The `InlineDescriptor` saves
information about the initialization state, constness, mutability, lifetime,
etc. of a field.

Consider this struct:

```c++
struct S {
    char c;
};
constexpr S s{12};
```

When allocating space for `s`, we allocate 24 bytes (not counting the `Descriptor`
instances we created for the `Record` and the field). The field `c` needs 8 bytes,
since we align to pointer size (this example uses a 64 bit system). The
`InlineDescriptor` preceding the field data uses up the remaining 16 bytes.

Inline descriptors are filled in by the `CtorFn` of blocks, which leaves storage
in an uninitialised, but valid state.

### Descriptors

Descriptors are generated at bytecode compilation time and contain information
required to determine if a particular memory access is allowed in constexpr.
They also carry all the information required to emit a diagnostic involving
a memory access, such as the declaration which originates the block.
Currently there is a single kind of descriptor encoding information for all
block types.

### Pointers

Pointers, implemented in `Pointer.h` are represented as a tagged union.

- **BlockPointer**: used to reference memory allocated and managed by the
  interpreter, being the only pointer kind which allows dereferencing in the
  interpreter
- **TypeIDPointer**: tracks information for the opaque type returned by
  `typeid`
- **IntegralPointer**: a pointer formed from an integer, think `(int*)123`.
- **FunctionPointer**: a pointer to a function.

Besides the previously mentioned union, a number of other pointer-like types
have their own type:

- **FunctionPointer** tracks functions.
- **MemberPointer** tracks C++ object members

#### BlockPointer

Block pointers track a `Pointee`, the block to which they point, along
with a `Base` and an `Offset`. The base identifies the innermost field,
while the offset points to an array element relative to the base (including
one-past-end pointers). The offset identifies the array element or field
which is referenced, while the base points to the outer object or array which
contains the field. These two fields allow all pointers to be uniquely
identified, disambiguated and characterised.

As an example, consider the following structure:

```c
struct A {
    struct B {
        int x;
        int y;
    } b;
    struct C {
        int a;
        int b;
    } c[2];
    int z;
};
constexpr A a;
```

On the target, `&a` and `&a.b.x` are equal. So are `&a.c[0]` and
`&a.c[0].a`. In the interpreter, all these pointers must be
distinguished since they are all allowed to address a distinct range of
memory.

In the interpreter, the object would require 240 bytes of storage and
would have its fields interleaved with metadata. The pointers which can
be derived to the object are illustrated in the following diagram:

```text
    0   16  32  40  56  64  80  96  112 120 136 144 160 176 184 200 208 224 240
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
+ B | D | D | x | D | y | D | D | D | a | D | b | D | D | a | D | b | D | z |
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
    ^   ^   ^       ^       ^   ^   ^       ^       ^   ^       ^       ^
    |   |   |       |       |   |   |   &a.c[0].b   |   |   &a.c[1].b   |
    a   |&a.b.x  &a.b.y   &a.c  |&a.c[0].a          |&a.c[1].a          |
      &a.b                   &a.c[0]            &a.c[1]               &a.z
```

The `Base` offset of all pointers points to the start of a field or
an array and is preceded by an inline descriptor (unless `Base` is
zero, pointing to the root). All the relevant attributes can be read
from either the inline descriptor or the descriptor of the block.

Array elements are identified by the `Offset` field of pointers,
pointing to past the inline descriptors for composites and before
the actual data in the case of primitive arrays. The `Offset`
points to the offset where primitives can be read from. As an example,
`a.c + 1` would have the same base as `a.c` since it is an element
of `a.c`, but its offset would point to `&a.c[1]`. The
array-to-pointer decay operation adjusts a pointer to an array (where
the offset is equal to the base) to a pointer to the first element.

#### TypeInfoPointer

`TypeInfoPointer` tracks two types: the type assigned to
`std::type_info` and the type which was passed to `typeinfo`.
It is part of the tagged union in `Pointer`.

### Interpretation

After bytecode has been generated (or not, for expressions), the bytecode
is then interpreted. The bytecode is stack-based and uses `InterpStack`
to allocate memory for the produced values.

Here is an example function:

```c++
constexpr int add(int a, int b) {
  return a + b;
}
static_assert(add(1, 2) == 3);
```

Which generates the following bytecode (this can be produced via `interp::Function::dump()`):

```text
add 0x7cb97f7e2000
[...]
0     GetParamSint32    0
16    GetParamSint32    1
32    AddSint32
40    RetSint32
48    NoRet
```

As you can see, all instructions here are type-aware. We're first pushing both parameter values
to the stack. Then the `Add` opcode will add them up and push the result to the stack, which
will be returned via the `Ret` opcode.

### Debugging

Here are a few hints when working on the bytecode interpreter:

- Setting a breakpoint on `CCEDiag` and `FFDiag` will stop the debugger when a diagnostic
  is emitted.
- If you want to see the bytecode of a function call `dump()` on the `interp::Function`.
- Additionally to the last point, `interp::Function::dump(CodePtr)` exists, which you can
  pass the current `OpPC` and it will then show you where in the bytecode that opcode is.
- `interp::Pointer` has an `operator<<` that prints useful information. Try it e.g.
  via `llvm::errs() << Ptr << '\n';`.
- Printing `APValue` instances also works via `APValue::dump()`.
- If you want to see *everything* that's being evaluated, add debugging output to
  the `evaluate*` functions in `Context.cpp`.

---

### Clang Docs ControlFlowIntegrity (`clang/docs/ControlFlowIntegrity.md`)

# Control Flow Integrity

```{toctree}
:hidden: true

ControlFlowIntegrityDesign
```


## Introduction

Clang includes an implementation of a number of control flow integrity (CFI)
schemes, which are designed to abort the program upon detecting certain forms
of undefined behavior that can potentially allow attackers to subvert the
program's control flow. These schemes have been optimized for performance,
allowing developers to enable them in release builds.

To enable Clang's available CFI schemes, use the flag
`-fsanitize=cfi`. You can also enable a subset of available
{ref}`schemes <cfi-schemes>`. As currently implemented, all schemes
except for `kcfi` rely on link-time optimization (LTO); so it is
required to specify `-flto` or `-flto=thin`, and the linker used
must support LTO, for example via the [gold plugin].

To allow the checks to be implemented efficiently, the program must
be structured such that certain object files are compiled with CFI
enabled, and are statically linked into the program. This may preclude
the use of shared libraries in some cases.

The compiler will only produce CFI checks for a class if it can infer hidden
LTO visibility for that class. LTO visibility is a property of a class that
is inferred from flags and attributes. For more details, see the documentation
for {doc}`LTO visibility <LTOVisibility>`.

The `-fsanitize=cfi-{vcall,nvcall,derived-cast,unrelated-cast}` flags
require that a `-fvisibility=` flag also be specified. This is because the
default visibility setting is `-fvisibility=default`, which would disable
CFI checks for classes without visibility attributes. Most users will want
to specify `-fvisibility=hidden`, which enables CFI checks for such classes.

When using `-fsanitize=cfi*` with `-flto=thin`, it is recommended
to reduce link times by passing {option}`-funique-source-file-names <-f[no-]unique-source-file-names>`, provided
that your program is compatible with it.

Experimental support for {ref}`cross-DSO control flow integrity
<cfi-cross-dso>` exists that does not require classes to have hidden LTO
visibility. This cross-DSO support has unstable ABI at this time.

(cfi-schemes)=

## Available schemes

Available schemes are:

- `-fsanitize=cfi-cast-strict`: Enables {ref}`strict cast checks
  <cfi-strictness>`.
- `-fsanitize=cfi-derived-cast`: Base-to-derived cast to the wrong
  dynamic type.
- `-fsanitize=cfi-unrelated-cast`: Cast from `void*` or another
  unrelated type to the wrong dynamic type.
- `-fsanitize=cfi-nvcall`: Non-virtual call via an object whose vptr is of
  the wrong dynamic type.
- `-fsanitize=cfi-vcall`: Virtual call via an object whose vptr is of the
  wrong dynamic type.
- `-fsanitize=cfi-icall`: Indirect call of a function with wrong dynamic
  type.
- `-fsanitize=cfi-mfcall`: Indirect call via a member function pointer with
  wrong dynamic type.

You can use `-fsanitize=cfi` to enable all the schemes and use
`-fno-sanitize` flag to narrow down the set of schemes as desired.
For example, you can build your program with
`-fsanitize=cfi -fno-sanitize=cfi-nvcall,cfi-icall`
to use all schemes except for non-virtual member function call and indirect call
checking.

Remember that you have to provide `-flto` or `-flto=thin` if at
least one CFI scheme is enabled.

## Trapping and Diagnostics

By default, CFI will abort the program immediately upon detecting a control
flow integrity violation. You can use the {ref}`-fno-sanitize-trap=
<controlling-code-generation>` flag to cause CFI to print a diagnostic
similar to the one below before the program aborts.

```console
bad-cast.cpp:109:7: runtime error: control flow integrity check for type 'B' failed during base-to-derived cast (vtable address 0x000000425a50)
0x000000425a50: note: vtable is of type 'A'
 00 00 00 00  f0 f1 41 00 00 00 00 00  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  20 5a 42 00
              ^
```

If diagnostics are enabled, you can also configure CFI to continue program
execution instead of aborting by using the {ref}`-fsanitize-recover=
<controlling-code-generation>` flag.

## Forward-Edge CFI for Virtual Calls

This scheme checks that virtual calls take place using a vptr of the correct
dynamic type; that is, the dynamic type of the called object must be a
derived class of the static type of the object used to make the call.
This CFI scheme can be enabled on its own using `-fsanitize=cfi-vcall`.

For this scheme to work, all translation units containing the definition
of a virtual member function (whether inline or not), other than members
of {ref}`ignored <cfi-ignorelist>` types or types with public {doc}`LTO
visibility <LTOVisibility>`, must be compiled with `-flto` or `-flto=thin`
enabled and be statically linked into the program.

### Performance

A performance overhead of less than 1% has been measured by running the
Dromaeo benchmark suite against an instrumented version of the Chromium
web browser. Another good performance benchmark for this mechanism is the
virtual-call-heavy SPEC 2006 xalancbmk.

Note that this scheme has not yet been optimized for binary size; an increase
of up to 15% has been observed for Chromium.

## Bad Cast Checking

This scheme checks that pointer casts are made to an object of the correct
dynamic type; that is, the dynamic type of the object must be a derived class
of the pointee type of the cast. The checks are currently only introduced
where the class being cast to is a polymorphic class.

Bad casts are not in themselves control flow integrity violations, but they
can also create security vulnerabilities, and the implementation uses many
of the same mechanisms.

There are two types of bad cast that may be forbidden: bad casts
from a base class to a derived class (which can be checked with
`-fsanitize=cfi-derived-cast`), and bad casts from a pointer of
type `void*` or another unrelated type (which can be checked with
`-fsanitize=cfi-unrelated-cast`).

The difference between these two types of casts is that the first is defined
by the C++ standard to produce an undefined value, while the second is not
in itself undefined behavior (it is well defined to cast the pointer back
to its original type) unless the object is uninitialized and the cast is a
`static_cast` (see C++14 [basic.life]p5).

If a program as a matter of policy forbids the second type of cast, that
restriction can normally be enforced. However it may in some cases be necessary
for a function to perform a forbidden cast to conform with an external API
(e.g. the `allocate` member function of a standard library allocator). Such
functions may be {ref}`ignored <cfi-ignorelist>`.

For this scheme to work, all translation units containing the definition
of a virtual member function (whether inline or not), other than members
of {ref}`ignored <cfi-ignorelist>` types or types with public {doc}`LTO
visibility <LTOVisibility>`, must be compiled with `-flto` or `-flto=thin`
enabled and be statically linked into the program.

## Non-Virtual Member Function Call Checking

This scheme checks that non-virtual calls take place using an object of
the correct dynamic type; that is, the dynamic type of the called object
must be a derived class of the static type of the object used to make the
call. The checks are currently only introduced where the object is of a
polymorphic class type. This CFI scheme can be enabled on its own using
`-fsanitize=cfi-nvcall`.

For this scheme to work, all translation units containing the definition
of a virtual member function (whether inline or not), other than members
of {ref}`ignored <cfi-ignorelist>` types or types with public {doc}`LTO
visibility <LTOVisibility>`, must be compiled with `-flto` or `-flto=thin`
enabled and be statically linked into the program.

(cfi-strictness)=

### Strictness

If a class has a single non-virtual base and does not introduce or override
virtual member functions or fields other than an implicitly defined virtual
destructor, it will have the same layout and virtual function semantics as
its base. By default, casts to such classes are checked as if they were made
to the least derived such class.

Casting an instance of a base class to such a derived class is technically
undefined behavior, but it is a relatively common hack for introducing
member functions on class instances with specific properties that works under
most compilers and should not have security implications, so we allow it by
default. It can be disabled with `-fsanitize=cfi-cast-strict`.

## Indirect Function Call Checking

This scheme checks that function calls take place using a function of the
correct dynamic type; that is, the dynamic type of the function must match
the static type used at the call. This CFI scheme can be enabled on its own
using `-fsanitize=cfi-icall`.

For this scheme to work, each indirect function call in the program, other
than calls in {ref}`ignored <cfi-ignorelist>` functions, must call a
function which was either compiled with `-fsanitize=cfi-icall` enabled,
or whose address was taken by a function in a translation unit compiled with
`-fsanitize=cfi-icall`.

If a function in a translation unit compiled with `-fsanitize=cfi-icall`
takes the address of a function not compiled with `-fsanitize=cfi-icall`,
that address may differ from the address taken by a function in a translation
unit not compiled with `-fsanitize=cfi-icall`. This is technically a
violation of the C and C++ standards, but it should not affect most programs.

Each translation unit compiled with `-fsanitize=cfi-icall` must be
statically linked into the program or shared library, and calls across
shared library boundaries are handled as if the callee was not compiled with
`-fsanitize=cfi-icall`.

This scheme is currently supported on a limited set of targets: x86,
x86_64, arm, arch64 and wasm.

### `-fsanitize-cfi-icall-generalize-pointers`

Mismatched pointer types are a common cause of cfi-icall check failures.
Translation units compiled with the `-fsanitize-cfi-icall-generalize-pointers`
flag relax pointer type checking for call sites in that translation unit,
applied across all functions compiled with `-fsanitize=cfi-icall`.

Specifically, pointers in return and argument types are treated as equivalent as
long as the qualifiers for the type they point to match. For example, `char*`,
`char**`, and `int*` are considered equivalent types. However, `char*` and
`const char*` are considered separate types.

`-fsanitize-cfi-icall-generalize-pointers` is not compatible with
`-fsanitize-cfi-cross-dso`.

(cfi-icall-experimental-normalize-integers)=

### `-fsanitize-cfi-icall-experimental-normalize-integers`

This option enables normalizing integer types as vendor extended types for
cross-language LLVM CFI/KCFI support with other languages that can't represent
and encode C/C++ integer types.

Specifically, integer types are encoded as their defined representations (e.g.,
8-bit signed integer, 16-bit signed integer, 32-bit signed integer, ...) for
compatibility with languages that define explicitly-sized integer types (e.g.,
i8, i16, i32, ..., in Rust).

`-fsanitize-cfi-icall-experimental-normalize-integers` is compatible with
`-fsanitize-cfi-icall-generalize-pointers`.

This option is currently experimental.

(cfi-canonical-jump-tables)=

### `-fsanitize-cfi-canonical-jump-tables`

The default behavior of Clang's indirect function call checker will replace
the address of each CFI-checked function in the output file's symbol table
with the address of a jump table entry which will pass CFI checks. We refer
to this as making the jump table *canonical*. This property allows code that
was not compiled with `-fsanitize=cfi-icall` to take a CFI-valid address
of a function, but it comes with a couple of caveats that are especially
relevant for users of cross-DSO CFI:

- There is a performance and code size overhead associated with each
  exported function, because each such function must have an associated
  jump table entry, which must be emitted even in the common case where the
  function is never address-taken anywhere in the program, and must be used
  even for direct calls between DSOs, in addition to the PLT overhead.
- There is no good way to take a CFI-valid address of a function written in
  assembly or a language not supported by Clang. The reason is that the code
  generator would need to insert a jump table in order to form a CFI-valid
  address for assembly functions, but there is no way in general for the
  code generator to determine the language of the function. This may be
  possible with LTO in the intra-DSO case, but in the cross-DSO case the only
  information available is the function declaration. One possible solution
  is to add a C wrapper for each assembly function, but these wrappers can
  present a significant maintenance burden for heavy users of assembly in
  addition to adding runtime overhead.

For these reasons, we provide the option of making the jump table non-canonical
with the flag `-fno-sanitize-cfi-canonical-jump-tables`. When the jump
table is made non-canonical, symbol table entries point directly to the
function body. Any instances of a function's address being taken in C will
be replaced with a jump table address.

This scheme does have its own caveats, however. It does end up breaking
function address equality more aggressively than the default behavior,
especially in cross-DSO mode which normally preserves function address
equality entirely.

Furthermore, it is occasionally necessary for code not compiled with
`-fsanitize=cfi-icall` to take a function address that is valid
for CFI. For example, this is necessary when a function's address
is taken by assembly code and then called by CFI-checking C code. The
`__attribute__((cfi_canonical_jump_table))` attribute may be used to make
the jump table entry of a specific function canonical so that the external
code will end up taking an address for the function that will pass CFI checks.

### `-fsanitize=cfi-icall` and `-fsanitize=function`

This tool is similar to `-fsanitize=function` in that both tools check
the types of function calls. However, the two tools occupy different points
on the design space; `-fsanitize=function` is a developer tool designed
to find bugs in local development builds, whereas `-fsanitize=cfi-icall`
is a security hardening mechanism designed to be deployed in release builds.

`-fsanitize=function` has a higher space and time overhead due to a more
complex type check at indirect call sites, which may make it unsuitable for
deployment.

On the other hand, `-fsanitize=function` conforms more closely with the C++
standard and user expectations around interaction with shared libraries;
the identity of function pointers is maintained, and calls across shared
library boundaries are no different from calls within a single program or
shared library.

(kcfi)=

### `-fsanitize=kcfi`

This is an alternative indirect call control-flow integrity scheme designed
for low-level system software, such as operating system kernels. Unlike
`-fsanitize=cfi-icall`, it doesn't require `-flto`, won't result in
function pointers being replaced with jump table references, and never breaks
cross-DSO function address equality. These properties make KCFI easier to
adopt in low-level software. KCFI is limited to checking only function
pointers, and isn't compatible with executable-only memory.

### `-fsanitize-kcfi-arity`

For supported targets, this feature extends kCFI by telling the compiler to
record information about each indirect-callable function's arity (i.e., the
number of arguments passed in registers) into the binary. Some kernel CFI
techniques, such as FineIBT, may be able to use this information to provide
enhanced security.

## Member Function Pointer Call Checking

This scheme checks that indirect calls via a member function pointer
take place using an object of the correct dynamic type. Specifically, we
check that the dynamic type of the member function referenced by the member
function pointer matches the "function pointer" part of the member function
pointer, and that the member function's class type is related to the base
type of the member function. This CFI scheme can be enabled on its own using
`-fsanitize=cfi-mfcall`.

The compiler will only emit a full CFI check if the member function pointer's
base type is complete. This is because the complete definition of the base
type contains information that is necessary to correctly compile the CFI
check. To ensure that the compiler always emits a full CFI check, it is
recommended to also pass the flag `-fcomplete-member-pointers`, which
enables a non-conforming language extension that requires member pointer
base types to be complete if they may be used for a call.

For this scheme to work, all translation units containing the definition
of a virtual member function (whether inline or not), other than members
of {ref}`ignored <cfi-ignorelist>` types or types with public {doc}`LTO
visibility <LTOVisibility>`, must be compiled with `-flto` or `-flto=thin`
enabled and be statically linked into the program.

This scheme is currently not compatible with cross-DSO CFI or the
Microsoft ABI.

(cfi-ignorelist)=

## Ignorelist

A {doc}`SanitizerSpecialCaseList` can be used to relax CFI checks for certain
source files, functions and types using the `src`, `fun` and `type`
entity types. Specific CFI modes can be be specified using `[section]`
headers.

```bash
# Suppress all CFI checking for code in a file.
src:bad_file.cpp
src:bad_header.h
# Ignore all functions with names containing MyFooBar.
fun:*MyFooBar*
# Ignore all types in the standard library.
type:std::*
# Disable only unrelated cast checks for this function
[cfi-unrelated-cast]
fun:*UnrelatedCast*
# Disable CFI call checks for this function without affecting cast checks
[cfi-vcall|cfi-nvcall|cfi-icall]
fun:*BadCall*
```

(cfi-cross-dso)=

## Shared library support

Use **-f[no-]sanitize-cfi-cross-dso** to enable the cross-DSO control
flow integrity mode, which allows all CFI schemes listed above to
apply across DSO boundaries. As in the regular CFI, each DSO must be
built with `-flto` or `-flto=thin`.

Normally, CFI checks will only be performed for classes that have hidden LTO
visibility. With this flag enabled, the compiler will emit cross-DSO CFI
checks for all classes, except for those which appear in the CFI ignorelist
or which use a `no_sanitize` attribute.

## Design

Please refer to the {doc}`design document<ControlFlowIntegrityDesign>`.

## Publications

[Control-Flow Integrity: Principles, Implementations, and Applications](https://research.microsoft.com/pubs/64250/ccs05.pdf).
Martin Abadi, Mihai Budiu, Úlfar Erlingsson, Jay Ligatti.

[Enforcing Forward-Edge Control-Flow Integrity in GCC & LLVM](https://www.usenix.org/system/files/conference/usenixsecurity14/sec14-paper-tice.pdf).
Caroline Tice, Tom Roeder, Peter Collingbourne, Stephen Checkoway,
Úlfar Erlingsson, Luis Lozano, Geoff Pike.

[gold plugin]: https://llvm.org/docs/GoldPlugin.html

---

### Clang Docs ControlFlowIntegrityDesign (`clang/docs/ControlFlowIntegrityDesign.md`)

# Control Flow Integrity Design Documentation

This page documents the design of the {doc}`ControlFlowIntegrity` schemes
supported by Clang.

## Forward-Edge CFI for Virtual Calls

This scheme works by allocating, for each static type used to make a virtual
call, a region of read-only storage in the object file holding a bit vector
that maps onto to the region of storage used for those virtual tables. Each
set bit in the bit vector corresponds to the [address point][address point] for a virtual
table compatible with the static type for which the bit vector is being built.

For example, consider the following three C++ classes:

```c++
struct A {
  virtual void f1();
  virtual void f2();
  virtual void f3();
};

struct B : A {
  virtual void f1();
  virtual void f2();
  virtual void f3();
};

struct C : A {
  virtual void f1();
  virtual void f2();
  virtual void f3();
};
```

The scheme will cause the virtual tables for A, B and C to be laid out
consecutively:

:::{table} Virtual Table Layout for A, B, C
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |
|---|---|---|---|---|---|---|---|---|---|----|----|----|----|----|
| A::offset-to-top | &A::rtti | &A::f1 | &A::f2 | &A::f3 | B::offset-to-top | &B::rtti | &B::f1 | &B::f2 | &B::f3 | C::offset-to-top | &C::rtti | &C::f1 | &C::f2 | &C::f3 |
:::

The bit vector for static types A, B and C will look like this:

:::{table} Bit Vectors for A, B, C
| Class | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |
|-------|---|---|---|---|---|---|---|---|---|---|----|----|----|----|----|
| A | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 |
| B | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| C | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 |
:::

Bit vectors are represented in the object file as byte arrays. By loading
from indexed offsets into the byte array and applying a mask, a program can
test bits from the bit set with a relatively short instruction sequence. Bit
vectors may overlap so long as they use different bits. For the full details,
see the [ByteArrayBuilder][bytearraybuilder] class.

In this case, assuming A is laid out at offset 0 in bit 0, B at offset 0 in
bit 1 and C at offset 0 in bit 2, the byte array would look like this:

```c++
char bits[] = { 0, 0, 1, 0, 0, 0, 3, 0, 0, 0, 0, 5, 0, 0 };
```

To emit a virtual call, the compiler will assemble code that checks that
the object's virtual table pointer is in-bounds and aligned and that the
relevant bit is set in the bit vector.

For example on x86 a typical virtual call may look like this:

```objdump
ca7fbb:       48 8b 0f                mov    (%rdi),%rcx
ca7fbe:       48 8d 15 c3 42 fb 07    lea    0x7fb42c3(%rip),%rdx
ca7fc5:       48 89 c8                mov    %rcx,%rax
ca7fc8:       48 29 d0                sub    %rdx,%rax
ca7fcb:       48 c1 c0 3d             rol    $0x3d,%rax
ca7fcf:       48 3d 7f 01 00 00       cmp    $0x17f,%rax
ca7fd5:       0f 87 36 05 00 00       ja     ca8511
ca7fdb:       48 8d 15 c0 0b f7 06    lea    0x6f70bc0(%rip),%rdx
ca7fe2:       f6 04 10 10             testb  $0x10,(%rax,%rdx,1)
ca7fe6:       0f 84 25 05 00 00       je     ca8511
ca7fec:       ff 91 98 00 00 00       callq  *0x98(%rcx)
  [...]
ca8511:       0f 0b                   ud2
```

The compiler relies on co-operation from the linker in order to assemble
the bit vectors for the whole program. It currently does this using LLVM's
[type metadata][type metadata] mechanism together with link-time optimization.

### Optimizations

The scheme as described above is the fully general variant of the scheme.
Most of the time we are able to apply one or more of the following
optimizations to improve binary size or performance.

In fact, if you try the above example with the current version of the
compiler, you will probably find that it will not use the described virtual
table layout or machine instructions. Some of the optimizations we are about
to introduce cause the compiler to use a different layout or a different
sequence of machine instructions.

#### Stripping Leading/Trailing Zeros in Bit Vectors

If a bit vector contains leading or trailing zeros, we can strip them from
the vector. The compiler will emit code to check if the pointer is in range
of the region covered by ones, and perform the bit vector check using a
truncated version of the bit vector. For example, the bit vectors for our
example class hierarchy will be emitted like this:

:::{table} Bit Vectors for A, B, C
| Class | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |
|-------|---|---|---|---|---|---|---|---|---|---|----|----|----|----|----|
| A |   |   | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 |   |   |
| B |   |   |   |   |   |   |   | 1 |   |   |   |   |   |   |   |
| C |   |   |   |   |   |   |   |   |   |   |   |   | 1 |   |   |
:::

#### Short Inline Bit Vectors

If the vector is sufficiently short, we can represent it as an inline constant
on x86. This saves us a few instructions when reading the correct element
of the bit vector.

If the bit vector fits in 32 bits, the code looks like this:

```objdump
 dc2:       48 8b 03                mov    (%rbx),%rax
 dc5:       48 8d 15 14 1e 00 00    lea    0x1e14(%rip),%rdx
 dcc:       48 89 c1                mov    %rax,%rcx
 dcf:       48 29 d1                sub    %rdx,%rcx
 dd2:       48 c1 c1 3d             rol    $0x3d,%rcx
 dd6:       48 83 f9 03             cmp    $0x3,%rcx
 dda:       77 2f                   ja     e0b <main+0x9b>
 ddc:       ba 09 00 00 00          mov    $0x9,%edx
 de1:       0f a3 ca                bt     %ecx,%edx
 de4:       73 25                   jae    e0b <main+0x9b>
 de6:       48 89 df                mov    %rbx,%rdi
 de9:       ff 10                   callq  *(%rax)
[...]
 e0b:       0f 0b                   ud2
```

Or if the bit vector fits in 64 bits:

```objdump
11a6:       48 8b 03                mov    (%rbx),%rax
11a9:       48 8d 15 d0 28 00 00    lea    0x28d0(%rip),%rdx
11b0:       48 89 c1                mov    %rax,%rcx
11b3:       48 29 d1                sub    %rdx,%rcx
11b6:       48 c1 c1 3d             rol    $0x3d,%rcx
11ba:       48 83 f9 2a             cmp    $0x2a,%rcx
11be:       77 35                   ja     11f5 <main+0xb5>
11c0:       48 ba 09 00 00 00 00    movabs $0x40000000009,%rdx
11c7:       04 00 00
11ca:       48 0f a3 ca             bt     %rcx,%rdx
11ce:       73 25                   jae    11f5 <main+0xb5>
11d0:       48 89 df                mov    %rbx,%rdi
11d3:       ff 10                   callq  *(%rax)
[...]
11f5:       0f 0b                   ud2
```

If the bit vector consists of a single bit, there is only one possible
virtual table, and the check can consist of a single equality comparison:

```objdump
9a2:   48 8b 03                mov    (%rbx),%rax
9a5:   48 8d 0d a4 13 00 00    lea    0x13a4(%rip),%rcx
9ac:   48 39 c8                cmp    %rcx,%rax
9af:   75 25                   jne    9d6 <main+0x86>
9b1:   48 89 df                mov    %rbx,%rdi
9b4:   ff 10                   callq  *(%rax)
[...]
9d6:   0f 0b                   ud2
```

#### Virtual Table Layout

The compiler lays out classes of disjoint hierarchies in separate regions
of the object file. At worst, bit vectors in disjoint hierarchies only
need to cover their disjoint hierarchy. But the closer that classes in
sub-hierarchies are laid out to each other, the smaller the bit vectors for
those sub-hierarchies need to be (see "Stripping Leading/Trailing Zeros in Bit
Vectors" above). The [GlobalLayoutBuilder][globallayoutbuilder] class is responsible for laying
out the globals efficiently to minimize the sizes of the underlying bitsets.

#### Alignment

If all gaps between address points in a particular bit vector are multiples
of powers of 2, the compiler can compress the bit vector by strengthening
the alignment requirements of the virtual table pointer. For example, given
this class hierarchy:

```c++
struct A {
  virtual void f1();
  virtual void f2();
};

struct B : A {
  virtual void f1();
  virtual void f2();
  virtual void f3();
  virtual void f4();
  virtual void f5();
  virtual void f6();
};

struct C : A {
  virtual void f1();
  virtual void f2();
};
```

The virtual tables will be laid out like this:

:::{table} Virtual Table Layout for A, B, C
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 |
|---|---|---|---|---|---|---|---|---|---|----|----|----|----|----|----|
| A::offset-to-top | &A::rtti | &A::f1 | &A::f2 | B::offset-to-top | &B::rtti | &B::f1 | &B::f2 | &B::f3 | &B::f4 | &B::f5 | &B::f6 | C::offset-to-top | &C::rtti | &C::f1 | &C::f2 |
:::

Notice that each address point for A is separated by 4 words. This lets us
emit a compressed bit vector for A that looks like this:

| 2 | 6 | 10 | 14 |
|---|---|----|----|
| 1 | 1 | 0 | 1 |

At call sites, the compiler will strengthen the alignment requirements by
using a different rotate count. For example, on a 64-bit machine where the
address points are 4-word aligned (as in A from our example), the `rol`
instruction may look like this:

```objdump
dd2:       48 c1 c1 3b             rol    $0x3b,%rcx
```

#### Padding to Powers of 2

Of course, this alignment scheme works best if the address points are
in fact aligned correctly. To make this more likely to happen, we insert
padding between virtual tables that in many cases aligns address points to
a power of 2. Specifically, our padding aligns virtual tables to the next
highest power of 2 bytes; because address points for specific base classes
normally appear at fixed offsets within the virtual table, this normally
has the effect of aligning the address points as well.

This scheme introduces tradeoffs between decreased space overhead for
instructions and bit vectors and increased overhead in the form of padding. We
therefore limit the amount of padding so that we align to no more than 128
bytes. This number was found experimentally to provide a good tradeoff.

#### Eliminating Bit Vector Checks for All-Ones Bit Vectors

If the bit vector is all ones, the bit vector check is redundant; we simply
need to check that the address is in range and well aligned. This is more
likely to occur if the virtual tables are padded.

### Forward-Edge CFI for Virtual Calls by Interleaving Virtual Tables

Dimitar et. al. proposed a novel approach that interleaves virtual tables in
[^ivtbl].
This approach is more efficient in terms of space because padding and bit vectors are no longer needed.
At the same time, it is also more efficient in terms of performance because in the interleaved layout
address points of the virtual tables are consecutive, thus the validity check of a virtual
vtable pointer is always a range check.

At a high level, the interleaving scheme consists of three steps: 1) split virtual table groups into
separate virtual tables, 2) order virtual tables by a pre-order traversal of the class hierarchy
and 3) interleave virtual tables.

The interleaving scheme implemented in LLVM is inspired by
[Protecting C++ Dynamic Dispatch Through VTable Interleaving](https://cseweb.ucsd.edu/~lerner/papers/ivtbl-ndss16.pdf)
by Dimitar Bounov, Rami Gökhan Kıcı, and Sorin Lerner, but has its own
enhancements (more in [Interleave virtual tables]).

[^ivtbl]: [Protecting C++ Dynamic Dispatch Through VTable Interleaving](https://cseweb.ucsd.edu/~lerner/papers/ivtbl-ndss16.pdf). Dimitar Bounov, Rami Gökhan Kıcı, Sorin Lerner.

#### Split virtual table groups into separate virtual tables

The Itanium C++ ABI glues multiple individual virtual tables for a class into a combined virtual table (virtual table group).
The interleaving scheme, however, can only work with individual virtual tables so it must split the combined virtual tables first.
In comparison, the old scheme does not require the splitting but it is more efficient when the combined virtual tables have been split.
The [GlobalSplit][globalsplit] pass is responsible for splitting combined virtual tables into individual ones.

#### Order virtual tables by a pre-order traversal of the class hierarchy

This step is common to both the old scheme described above and the interleaving scheme.
For the interleaving scheme, since the combined virtual tables have been split in the previous step,
this step ensures that for any class all the compatible virtual tables will appear consecutively.
For the old scheme, the same property may not hold since it may work on combined virtual tables.

For example, consider the following four C++ classes:

```c++
struct A {
  virtual void f1();
};

struct B : A {
  virtual void f1();
  virtual void f2();
};

struct C : A {
  virtual void f1();
  virtual void f3();
};

struct D : B {
  virtual void f1();
  virtual void f2();
};
```

This step will arrange the virtual tables for A, B, C, and D in the order of *vtable-of-A, vtable-of-B, vtable-of-D, vtable-of-C*.

#### Interleave virtual tables

This step is where the interleaving scheme deviates from the old scheme. Instead of laying out
whole virtual tables in the previously computed order, the interleaving scheme lays out table
entries of the virtual tables strategically to ensure the following properties:

1. offset-to-top and RTTI fields layout property

The Itanium C++ ABI specifies that offset-to-top and RTTI fields appear at the offsets behind the
address point. Note that libraries like libcxxabi do assume this property.

2. virtual function entry layout property

For each virtual function the distance between a virtual table entry for this function and the corresponding
address point is always the same. This property ensures that dynamic dispatch still works with the interleaving layout.

Note that the interleaving scheme in the CFI implementation guarantees both properties above whereas the original scheme proposed
in [^ivtbl] only guarantees the second property.

To illustrate how the interleaving algorithm works, let us continue with the running example.
The algorithm first separates all the virtual table entries into two work lists. To do so,
it starts by allocating two work lists, one initialized with all the offset-to-top entries of virtual tables in the order
computed in the last step, one initialized with all the RTTI entries in the same order.

:::{table} Work list 1 Layout
| 0 | 1 | 2 | 3 |
|---|---|---|---|
| A::offset-to-top | B::offset-to-top | D::offset-to-top | C::offset-to-top |
:::

:::{table} Work list 2 layout
| 0 | 1 | 2 | 3 |
|---|---|---|---|
| &A::rtti | &B::rtti | &D::rtti | &C::rtti |
:::

Then for each virtual function the algorithm goes through all the virtual tables in the previously computed order
to collect all the related entries into a virtual function list.
After this step, there are the following virtual function lists:

:::{table} f1 list
| 0 | 1 | 2 | 3 |
|---|---|---|---|
| &A::f1 | &B::f1 | &D::f1 | &C::f1 |
:::

:::{table} f2 list
| 0 | 1 |
|---|---|
| &B::f2 | &D::f2 |
:::

:::{table} f3 list
| 0 |
|---|
| &C::f3 |
:::

Next, the algorithm picks the longest remaining virtual function list and appends the whole list to the shortest work list
until no function lists are left, and pads the shorter work list so that they are of the same length.
In the example, f1 list will be first added to work list 1, then f2 list will be added
to work list 2, and finally f3 list will be added to the work list 2. Since work list 1 now has one more entry than
work list 2, a padding entry is added to the latter. After this step, the two work lists look like:

:::{table} Work list 1 Layout
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
|---|---|---|---|---|---|---|---|
| A::offset-to-top | B::offset-to-top | D::offset-to-top | C::offset-to-top | &A::f1 | &B::f1 | &D::f1 | &C::f1 |
:::

:::{table} Work list 2 layout
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
|---|---|---|---|---|---|---|---|
| &A::rtti | &B::rtti | &D::rtti | &C::rtti | &B::f2 | &D::f2 | &C::f3 | padding |
:::

Finally, the algorithm merges the two work lists into the interleaved layout by alternatingly
moving the head of each list to the final layout. After this step, the final interleaved layout looks like:

:::{table} Interleaved layout
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 |
|---|---|---|---|---|---|---|---|---|---|----|----|----|----|----|----|
| A::offset-to-top | &A::rtti | B::offset-to-top | &B::rtti | D::offset-to-top | &D::rtti | C::offset-to-top | &C::rtti | &A::f1 | &B::f2 | &B::f1 | &D::f2 | &D::f1 | &C::f3 | &C::f1 | padding |
:::

In the above interleaved layout, each virtual table's offset-to-top and RTTI are always adjacent, which shows that the layout has the first property.
For the second property, let us look at f2 as an example. In the interleaved layout,
there are two entries for f2: B::f2 and D::f2. The distance between &B::f2
and its address point D::offset-to-top (the entry immediately after &B::rtti) is 5 entry-length, so is the distance between &D::f2 and C::offset-to-top (the entry immediately after &D::rtti).

## Forward-Edge CFI for Indirect Function Calls

Under forward-edge CFI for indirect function calls, each unique function
type has its own bit vector, and at each call site we need to check that the
function pointer is a member of the function type's bit vector. This scheme
works in a similar way to forward-edge CFI for virtual calls, the distinction
being that we need to build bit vectors of function entry points rather than
of virtual tables.

Unlike when re-arranging global variables, we cannot re-arrange functions
in a particular order and base our calculations on the layout of the
functions' entry points, as we have no idea how large a particular function
will end up being (the function sizes could even depend on how we arrange
the functions). Instead, we build a jump table, which is a block of code
consisting of one branch instruction for each of the functions in the bit
set that branches to the target function, and redirect any taken function
addresses to the corresponding jump table entry. In this way, the distance
between function entry points is predictable and controllable. In the object
file's symbol table, the symbols for the target functions also refer to the
jump table entries, so that addresses taken outside the module will pass
any verification done inside the module.

In more concrete terms, suppose we have three functions `f`, `g`,
`h` which are all of the same type, and a function foo that returns their
addresses:

```gas
f:
mov 0, %eax
ret

g:
mov 1, %eax
ret

h:
mov 2, %eax
ret

foo:
mov f, %eax
mov g, %edx
mov h, %ecx
ret
```

Our jump table will (conceptually) look like this:

```gas
f:
jmp .Ltmp0 ; 5 bytes
int3       ; 1 byte
int3       ; 1 byte
int3       ; 1 byte

g:
jmp .Ltmp1 ; 5 bytes
int3       ; 1 byte
int3       ; 1 byte
int3       ; 1 byte

h:
jmp .Ltmp2 ; 5 bytes
int3       ; 1 byte
int3       ; 1 byte
int3       ; 1 byte

.Ltmp0:
mov 0, %eax
ret

.Ltmp1:
mov 1, %eax
ret

.Ltmp2:
mov 2, %eax
ret

foo:
mov f, %eax
mov g, %edx
mov h, %ecx
ret
```

Because the addresses of `f`, `g`, `h` are evenly spaced at a power of
2, and function types do not overlap (unlike class types with base classes),
we can normally apply the [Alignment] and [Eliminating Bit Vector Checks
for All-Ones Bit Vectors][eliminating bit vector checks for all-ones bit vectors] optimizations thus simplifying the check at each
call site to a range and alignment check.

## Shared library support

**EXPERIMENTAL**

The basic CFI mode described above assumes that the application is a
monolithic binary; at least that all possible virtual/indirect call
targets and the entire class hierarchy are known at link time. The
cross-DSO mode, enabled with **-f[no-]sanitize-cfi-cross-dso** relaxes
this requirement by allowing virtual and indirect calls to cross the
DSO boundary.

Assuming the following setup: the binary consists of several
instrumented and several uninstrumented DSOs. Some of them may be
dlopen-ed/dlclose-d periodically, even frequently.

- Calls made from uninstrumented DSOs are not checked and just work.
- Calls inside any instrumented DSO are fully protected.
- Calls between different instrumented DSOs are also protected, with a
  performance penalty (in addition to the monolithic CFI overhead).
- Calls from an instrumented DSO to an uninstrumented one are unchecked and
  just work, with performance penalty.
- Calls from an instrumented DSO outside of any known DSO are detected as CFI
  violations.

In the monolithic scheme a call site is instrumented as

```text
if (!InlinedFastCheck(f))
  abort();
call *f
```

In the cross-DSO scheme it becomes

```text
if (!InlinedFastCheck(f))
  __cfi_slowpath(CallSiteTypeId, f);
call *f
```

### CallSiteTypeId

`CallSiteTypeId` is a stable process-wide identifier of the
call-site type. For a virtual call site, the type in question is the class
type; for an indirect function call it is the function signature. The
mapping from a type to an identifier is an ABI detail. In the current,
experimental, implementation the identifier of type T is calculated as
follows:

- Obtain the mangled name for "typeinfo name for T".
- Calculate MD5 hash of the name as a string.
- Reinterpret the first 8 bytes of the hash as a little-endian
  64-bit integer.

It is possible, but unlikely, that collisions in the
`CallSiteTypeId` hashing will result in weaker CFI checks that would
still be conservatively correct.

### CFI_Check

In the general case, only the target DSO knows whether the call to
function `f` with type `CallSiteTypeId` is valid or not. To
export this information, every DSO implements

```c++
void __cfi_check(uint64 CallSiteTypeId, void *TargetAddr, void *DiagData)
```

This function provides external modules with access to CFI checks for
the targets inside this DSO. For each known `CallSiteTypeId`, this
function performs an `llvm.type.test` with the corresponding type
identifier. It reports an error if the type is unknown, or if the
check fails. Depending on the values of compiler flags
`-fsanitize-trap` and `-fsanitize-recover`, this function may
print an error, abort and/or return to the caller. `DiagData` is an
opaque pointer to the diagnostic information about the error, or
`null` if the caller does not provide this information.

The basic implementation is a large switch statement over all values
of CallSiteTypeId supported by this DSO, and each case is similar to
the InlinedFastCheck() in the basic CFI mode.

### CFI Shadow

To route CFI checks to the target DSO's \_\_cfi_check function, a
mapping from possible virtual / indirect call targets to the
corresponding \_\_cfi_check functions is maintained. This mapping is
implemented as a sparse array of 2 bytes for every possible page (4096
bytes) of memory. The table is kept readonly most of the time.

There are 3 types of shadow values:

- Address in a CFI-instrumented DSO.
- Unchecked address (a “trusted” non-instrumented DSO). Encoded as
  value 0xFFFF.
- Invalid address (everything else). Encoded as value 0.

For a CFI-instrumented DSO, a shadow value encodes the address of the
\_\_cfi_check function for all call targets in the corresponding memory
page. If Addr is the target address, and V is the shadow value, then
the address of \_\_cfi_check is calculated as

```text
__cfi_check = AlignUpTo(Addr, 4096) - (V + 1) * 4096
```

This works as long as \_\_cfi_check is aligned by 4096 bytes and located
below any call targets in its DSO, but not more than 256MB apart from
them.

### CFI_SlowPath

The slow path check is implemented in a runtime support library as

```c++
void __cfi_slowpath(uint64 CallSiteTypeId, void *TargetAddr)
void __cfi_slowpath_diag(uint64 CallSiteTypeId, void *TargetAddr, void *DiagData)
```

These functions loads a shadow value for `TargetAddr`, finds the
address of `__cfi_check` as described above and calls
that. `DiagData` is an opaque pointer to diagnostic data which is
passed verbatim to `__cfi_check`, and `__cfi_slowpath` passes
`nullptr` instead.

Compiler-RT library contains reference implementations of slowpath
functions, but they have unresolvable issues with correctness and
performance in the handling of dlopen(). It is recommended that
platforms provide their own implementations, usually as part of libc
or libdl.

### Position-independent executable requirement

Cross-DSO CFI mode requires that the main executable is built as PIE.
In non-PIE executables the address of an external function (taken from
the main executable) is the address of that function’s PLT record in
the main executable. This would break the CFI checks.

## Backward-edge CFI for return statements (RCFI)

This section is a proposal. As of March 2017 it is not implemented.

Backward-edge control flow (`RET` instructions) can be hijacked
via overwriting the return address (`RA`) on stack.
Various mitigation techniques (e.g. [SafeStack][safestack], [RFG][rfg], [Intel CET][intel cet])
try to detect or prevent `RA` corruption on stack.

RCFI enforces the expected control flow in several different ways described below.
RCFI heavily relies on LTO.

### Leaf Functions

If `f()` is a leaf function (i.e. it has no calls
except maybe no-return calls) it can be called using a special calling convention
that stores `RA` in a dedicated register `R` before the `CALL` instruction.
`f()` does not spill `R` and does not use the `RET` instruction,
instead it uses the value in `R` to `JMP` to `RA`.

This flavour of CFI is *precise*, i.e. the function is guaranteed to return
to the point exactly following the call.

An alternative approach is to
copy `RA` from stack to `R` in the first instruction of `f()`,
then `JMP` to `R`.
This approach is simpler to implement (does not require changing the caller)
but weaker (there is a small window when `RA` is actually stored on stack).

### Functions called once

Suppose `f()` is called in just one place in the program
(assuming we can verify this in LTO mode).
In this case we can replace the `RET` instruction with a `JMP` instruction
with the immediate constant for `RA`.
This will *precisely* enforce the return control flow no matter what is stored on stack.

Another variant is to compare `RA` on stack with the known constant and abort
if they don't match; then `JMP` to the known constant address.

### Functions called in a small number of call sites

We may extend the above approach to cases where `f()`
is called more than once (but still a small number of times).
With LTO we know all possible values of `RA` and we check them
one-by-one (or using binary search) against the value on stack.
If the match is found, we `JMP` to the known constant address, otherwise abort.

This protection is *near-precise*, i.e. it guarantees that the control flow will
be transferred to one of the valid return addresses for this function,
but not necessary to the point of the most recent `CALL`.

### General case

For functions called multiple times a *return jump table* is constructed
in the same manner as jump tables for indirect function calls (see above).
The correct jump table entry (or its index) is passed by `CALL` to `f()`
(as an extra argument) and then spilled to stack.
The `RET` instruction is replaced with a load of the jump table entry,
jump table range check, and `JMP` to the jump table entry.

This protection is also *near-precise*.

### Returns from functions called indirectly

If a function is called indirectly, the return jump table is constructed for the
equivalence class of functions instead of a single function.

### Cross-DSO calls

Consider two instrumented DSOs, `A` and `B`. `A` defines `f()` and `B` calls it.

This case will be handled similarly to the cross-DSO scheme using the slow path callback.

### Non-goals

RCFI does not protect `RET` instructions:

- in non-instrumented DSOs,
- in instrumented DSOs for functions that are called from non-instrumented DSOs,
- embedded into other instructions (e.g. `0f4fc3 cmovg %ebx,%eax`).

## Hardware support

We believe that the above design can be efficiently implemented in hardware.
A single new instruction added to an ISA would allow to perform the forward-edge CFI check
with fewer bytes per check (smaller code size overhead) and potentially more
efficiently. The current software-only instrumentation requires at least
32-bytes per check (on x86_64).
A hardware instruction may probably be less than ~ 12 bytes.
Such instruction would check that the argument pointer is in-bounds,
and is properly aligned, and if the checks fail it will either trap (in monolithic scheme)
or call the slow path function (cross-DSO scheme).
The bit vector lookup is probably too complex for a hardware implementation.

```c++
//  This instruction checks that 'Ptr'
//   * is aligned by (1 << kAlignment) and
//   * is inside [kRangeBeg, kRangeBeg+(kRangeSize<<kAlignment))
//  and if the check fails it jumps to the given target (slow path).
//
// 'Ptr' is a register, pointing to the virtual function table
//    or to the function which we need to check. We may require an explicit
//    fixed register to be used.
// 'kAlignment' is a 4-bit constant.
// 'kRangeSize' is a ~20-bit constant.
// 'kRangeBeg' is a PC-relative constant (~28 bits)
//    pointing to the beginning of the allowed range for 'Ptr'.
// 'kFailedCheckTarget': is a PC-relative constant (~28 bits)
//    representing the target to branch to when the check fails.
//    If kFailedCheckTarget==0, the process will trap
//    (monolithic binary scheme).
//    Otherwise it will jump to a handler that implements `CFI_SlowPath`
//    (cross-DSO scheme).
CFI_Check(Ptr, kAlignment, kRangeSize, kRangeBeg, kFailedCheckTarget) {
   if (Ptr < kRangeBeg ||
       Ptr >= kRangeBeg + (kRangeSize << kAlignment) ||
       Ptr & ((1 << kAlignment) - 1))
         Jump(kFailedCheckTarget);
}
```

An alternative and more compact encoding would not use `kFailedCheckTarget`,
and will trap on check failure instead.
This will allow us to fit the instruction into **8-9 bytes**.
The cross-DSO checks will be performed by a trap handler and
performance-critical ones will have to be black-listed and checked using the
software-only scheme.

Note that such hardware extension would be complementary to checks
at the callee side, such as e.g. **Intel ENDBRANCH**.
Moreover, CFI would have two benefits over ENDBRANCH: a) precision and b)
ability to protect against invalid casts between polymorphic types.

[address point]: https://itanium-cxx-abi.github.io/cxx-abi/abi.html#vtable-general
[bytearraybuilder]: https://llvm.org/docs/doxygen/html/structllvm_1_1ByteArrayBuilder.html
[globallayoutbuilder]: https://github.com/llvm/llvm-project/blob/main/llvm/include/llvm/Transforms/IPO/LowerTypeTests.h
[globalsplit]: https://github.com/llvm/llvm-project/blob/main/llvm/lib/Transforms/IPO/GlobalSplit.cpp
[intel cet]: https://software.intel.com/en-us/blogs/2016/06/09/intel-release-new-technology-specifications-protect-rop-attacks
[rfg]: https://xlab.tencent.com/en/2016/11/02/return-flow-guard
[safestack]: SafeStack.md
[type metadata]: https://llvm.org/docs/TypeMetadata.html

---

### Clang Docs CrossCompilation (`clang/docs/CrossCompilation.md`)

# Cross-compilation using Clang

## Introduction

This document will guide you in choosing the right Clang options
for cross-compiling your code to a different architecture. It assumes you
already know how to compile the code in question for the host architecture,
and that you know how to choose additional include and library paths.

However, this document is *not* a "how to" and won't help you setting your
build system or Makefiles, nor choosing the right CMake options, etc.
Also, it does not cover all the possible options, nor does it contain
specific examples for specific architectures. For a concrete example, the
[instructions for cross-compiling LLVM itself](https://llvm.org/docs/HowToCrossCompileLLVM.html) may be of interest.

After reading this document, you should be familiar with the main issues
related to cross-compilation, and what main compiler options Clang provides
for performing cross-compilation.

## Cross compilation issues

In GCC world, every host/target combination has its own set of binaries,
headers, libraries, etc. So, it's usually simple to download a package
with all files in, unzip to a directory and point the build system to
that compiler, that will know about its location and find all it needs to
when compiling your code.

On the other hand, Clang/LLVM is natively a cross-compiler, meaning that
one set of programs can compile to all targets by setting the `-target`
option. That makes it a lot easier for programmers wishing to compile to
different platforms and architectures, and for compiler developers that
only have to maintain one build system, and for OS distributions, that
need only one set of main packages.

But, as is true to any cross-compiler, and given the complexity of
different architectures, OS's and options, it's not always easy finding
the headers, libraries or binutils to generate target specific code.
So you'll need special options to help Clang understand what target
you're compiling to, where your tools are, etc.

Another problem is that compilers come with standard libraries only (like
`compiler-rt`, `libcxx`, `libgcc`, `libm`, etc), so you'll have to
find and make available to the build system, every other library required
to build your software, that is specific to your target. It's not enough to
have your host's libraries installed.

Finally, not all toolchains are the same, and consequently, not every Clang
option will work magically. Some options, like `--sysroot` (which
effectively changes the logical root for headers and libraries), assume
all your binaries and libraries are in the same directory, which may not
true when your cross-compiler was installed by the distribution's package
management. So, for each specific case, you may use more than one
option, and in most cases, you'll end up setting include paths (`-I`) and
library paths (`-L`) manually.

To sum up, different toolchains can:
: - be host/target specific or more flexible
  - be in a single directory, or spread out across your system
  - have different sets of libraries and headers by default
  - need special options, which your build system won't be able to figure
    out by itself

## General Cross-Compilation Options in Clang

### Target Triple

The basic option is to define the target architecture. For that, use
`-target <triple>`. If you don't specify the target, CPU names won't
match (since Clang assumes the host triple), and the compilation will
go ahead, creating code for the host platform, which will break later
on when assembling or linking.

The triple has the general format `<arch><sub>-<vendor>-<sys>-<env>`, where:
: - `arch` = `x86_64`, `i386`, `arm`, `thumb`, `mips`, etc.
  - `sub` = for ex. on ARM: `v5`, `v6m`, `v7a`, `v7m`, etc.
  - `vendor` = `pc`, `apple`, `nvidia`, `ibm`, etc.
  - `sys` = `none`, `linux`, `win32`, `darwin`, `cuda`, etc.
  - `env` = `eabi`, `gnu`, `android`, `macho`, `elf`, etc.

The sub-architecture options are available for their own architectures,
of course, so "x86v7a" doesn't make sense. The vendor needs to be
specified only if there's a relevant change, for instance between PC
and Apple. Most of the time it can be omitted (and Unknown)
will be assumed, which sets the defaults for the specified architecture.
The system name is generally the OS (linux, darwin), but could be special
like the bare-metal "none".

When a parameter is not important, it can be omitted, or you can
choose `unknown` and the defaults will be used. If you choose a parameter
that Clang doesn't know, like `blerg`, it'll ignore and assume
`unknown`, which is not always desired, so be careful.

Finally, the env (environment) option is something that will pick default
CPU/FPU, define the specific behaviour of your code (PCS, extensions),
and also choose the correct library calls, etc.

### CPU, FPU, ABI

Once your target is specified, it's time to pick the hardware you'll
be compiling to. For every architecture, a default set of CPU/FPU/ABI
will be chosen, so you'll almost always have to change it via flags.

Typical flags include:
: - `-mcpu=<cpu-name>`, like x86-64, swift, cortex-a15
  - `-mfpu=<fpu-name>`, like SSE3, NEON, controlling the FP unit available
  - `-mfloat-abi=<fabi>`, like soft, hard, controlling which registers
    to use for floating-point

The default is normally the common denominator, so that Clang doesn't
generate code that breaks. But that also means you won't get the best
code for your specific hardware, which may mean orders of magnitude
slower than you expect.

For example, if your target is `arm-none-eabi`, the default CPU will
be `arm7tdmi` using soft float, which is extremely slow on modern cores,
whereas if your triple is `armv7a-none-eabi`, it'll be Cortex-A8 with
NEON, but still using soft-float, which is much better, but still not
great.

### Toolchain Options

There are three main options to control access to your cross-compiler:
`--sysroot`, `-I`, and `-L`. The two last ones are well known,
but they're particularly important for additional libraries
and headers that are specific to your target.

There are two main ways to have a cross-compiler:

1. When you have extracted your cross-compiler from a zip file into
   a directory, you have to use `--sysroot=<path>`. The path is the
   root directory where you have unpacked your file, and Clang will
   look for the directories `bin`, `lib`, `include` in there.

   In this case, your setup should be pretty much done (if no
   additional headers or libraries are needed), as Clang will find
   all binaries it needs (assembler, linker, etc) in there.

2. When you have installed via a package manager (modern Linux
   distributions have cross-compiler packages available), make
   sure the target triple you set is *also* the prefix of your
   cross-compiler toolchain.

   In this case, Clang will find the other binaries (assembler,
   linker), but not always where the target headers and libraries
   are. People add system-specific clues to Clang often, but as
   things change, it's more likely that it won't find than the
   other way around.

   So, here, you'll be a lot safer if you specify the include/library
   directories manually (via `-I` and `-L`).

## Target-Specific Libraries

All libraries that you compile as part of your build will be
cross-compiled to your target, and your build system will probably
find them in the right place. But all dependencies that are
normally checked against (like `libxml` or `libz` etc) will match
against the host platform, not the target.

So, if the build system is not aware that you want to cross-compile
your code, it will get every dependency wrong, and your compilation
will fail during build time, not configure time.

Also, finding the libraries for your target are not as easy
as for your host machine. There aren't many cross-libraries available
as packages to most OS's, so you'll have to either cross-compile them
from source, or download the package for your target platform,
extract the libraries and headers, put them in specific directories
and add `-I` and `-L` pointing to them.

Also, some libraries have different dependencies on different targets,
so configuration tools to find dependencies in the host can get the
list wrong for the target platform. This means that the configuration
of your build can get things wrong when setting their own library
paths, and you'll have to augment it via additional flags (configure,
Make, CMake, etc).

### Multilibs

When you want to cross-compile to more than one configuration, for
example hard-float-ARM and soft-float-ARM, you'll have to have multiple
copies of your libraries and (possibly) headers.

Some Linux distributions have support for Multilib, which handle that
for you in an easier way, but if you're not careful and, for instance,
forget to specify `-ccc-gcc-name armv7l-linux-gnueabihf-gcc` (which
uses hard-float), Clang will pick the `armv7l-linux-gnueabi-ld`
(which uses soft-float) and linker errors will happen.

The same is true if you're compiling for different environments, like
`gnueabi` and `androideabi`, and might even link and run, but produce
run-time errors, which are much harder to track down and fix.

---

### Clang Docs DataFlowSanitizer (`clang/docs/DataFlowSanitizer.md`)

# DataFlowSanitizer

```{toctree}
:hidden: true

DataFlowSanitizerDesign
```


## Introduction

DataFlowSanitizer is a generalised dynamic data flow analysis.

Unlike other Sanitizer tools, this tool is not designed to detect a
specific class of bugs on its own. Instead, it provides a generic
dynamic data flow analysis framework to be used by clients to help
detect application-specific issues within their own code.

## How to build libc++ with DFSan

DFSan requires either all of your code to be instrumented or for uninstrumented
functions to be listed as `uninstrumented` in the {ref}`ABI list`.

If you'd like to have instrumented libc++ functions, then you need to build it
with DFSan instrumentation from source. Here is an example of how to build
libc++ and the libc++ ABI with data flow sanitizer instrumentation.

```console
mkdir libcxx-build
cd libcxx-build

# An example using ninja
cmake -GNinja -S <monorepo-root>/runtimes \
  -DCMAKE_C_COMPILER=clang \
  -DCMAKE_CXX_COMPILER=clang++ \
  -DLLVM_USE_SANITIZER="DataFlow" \
  -DLLVM_ENABLE_RUNTIMES="libcxx;libcxxabi"

ninja cxx cxxabi
```

Note: Ensure you are building with a sufficiently new version of Clang.

## Usage

With no program changes, applying DataFlowSanitizer to a program
will not alter its behavior. To use DataFlowSanitizer, the program
uses API functions to apply tags to data to cause it to be tracked, and to
check the tag of a specific data item. DataFlowSanitizer manages
the propagation of tags through the program according to its data flow.

The APIs are defined in the header file `sanitizer/dfsan_interface.h`.
For further information about each function, please refer to the header
file.

(abi-list)=
(ABI list)=

### ABI List

DataFlowSanitizer uses a list of functions known as an ABI list to decide
whether a call to a specific function should use the operating system's native
ABI or whether it should use a variant of this ABI that also propagates labels
through function parameters and return values. The ABI list file also controls
how labels are propagated in the former case. DataFlowSanitizer comes with a
default ABI list which is intended to eventually cover the glibc library on
Linux but it may become necessary for users to extend the ABI list in cases
where a particular library or function cannot be instrumented (e.g. because
it is implemented in assembly or another language which DataFlowSanitizer does
not support) or a function is called from a library or function which cannot
be instrumented.

DataFlowSanitizer's ABI list file is a {doc}`SanitizerSpecialCaseList`.
The pass treats every function in the `uninstrumented` category in the
ABI list file as conforming to the native ABI. Unless the ABI list contains
additional categories for those functions, a call to one of those functions
will produce a warning message, as the labelling behavior of the function
is unknown. The other supported categories are `discard`, `functional`
and `custom`.

- `discard` -- To the extent that this function writes to (user-accessible)
  memory, it also updates labels in shadow memory (this condition is trivially
  satisfied for functions which do not write to user-accessible memory). Its
  return value is unlabelled.
- `functional` -- Like `discard`, except that the label of its return value
  is the union of the label of its arguments.
- `custom` -- Instead of calling the function, a custom wrapper `__dfsw_F`
  is called, where `F` is the name of the function. This function may wrap
  the original function or provide its own implementation. This category is
  generally used for uninstrumentable functions which write to user-accessible
  memory or which have more complex label propagation behavior. The signature
  of `__dfsw_F` is based on that of `F` with each argument having a
  label of type `dfsan_label` appended to the argument list. If `F`
  is of non-void return type a final argument of type `dfsan_label *`
  is appended to which the custom function can store the label for the
  return value. For example:

```c++
void f(int x);
void __dfsw_f(int x, dfsan_label x_label);

void *memcpy(void *dest, const void *src, size_t n);
void *__dfsw_memcpy(void *dest, const void *src, size_t n,
                    dfsan_label dest_label, dfsan_label src_label,
                    dfsan_label n_label, dfsan_label *ret_label);
```

If a function defined in the translation unit being compiled belongs to the
`uninstrumented` category, it will be compiled so as to conform to the
native ABI. Its arguments will be assumed to be unlabelled, but it will
propagate labels in shadow memory.

For example:

```none
# main is called by the C runtime using the native ABI.
fun:main=uninstrumented
fun:main=discard

# malloc only writes to its internal data structures, not user-accessible memory.
fun:malloc=uninstrumented
fun:malloc=discard

# tolower is a pure function.
fun:tolower=uninstrumented
fun:tolower=functional

# memcpy needs to copy the shadow from the source to the destination region.
# This is done in a custom function.
fun:memcpy=uninstrumented
fun:memcpy=custom
```

For instrumented functions, the ABI list supports a `force_zero_labels`
category, which will make all stores and return values set zero labels.
Functions should never be labelled with both `force_zero_labels`
and `uninstrumented` or any of the uninstrumented wrapper kinds.

For example:

```none
# e.g. void writes_data(char* out_buf, int out_buf_len) {...}
# Applying force_zero_labels will force out_buf shadow to zero.
fun:writes_data=force_zero_labels
```

### Compilation Flags

- `-dfsan-abilist` -- The additional ABI list files that control how shadow
  parameters are passed. File names are separated by comma.
- `-dfsan-combine-pointer-labels-on-load` -- Controls whether to include or
  ignore the labels of pointers in load instructions. Its default value is true.
  For example:

```c++
v = *p;
```

If the flag is true, the label of `v` is the union of the label of `p` and
the label of `*p`. If the flag is false, the label of `v` is the label of
just `*p`.

- `-dfsan-combine-pointer-labels-on-store` -- Controls whether to include or
  ignore the labels of pointers in store instructions. Its default value is
  false. For example:

```c++
*p = v;
```

If the flag is true, the label of `*p` is the union of the label of `p` and
the label of `v`. If the flag is false, the label of `*p` is the label of
just `v`.

- `-dfsan-combine-offset-labels-on-gep` -- Controls whether to propagate
  labels of offsets in GEP instructions. Its default value is true. For example:

```c++
p += i;
```

If the flag is true, the label of `p` is the union of the label of `p` and
the label of `i`. If the flag is false, the label of `p` is unchanged.

- `-dfsan-track-select-control-flow` -- Controls whether to track the control
  flow of select instructions. Its default value is true. For example:

```c++
v = b? v1: v2;
```

If the flag is true, the label of `v` is the union of the labels of `b`,
`v1` and `v2`. If the flag is false, the label of `v` is the union of the
labels of just `v1` and `v2`.

- `-dfsan-event-callbacks` -- An experimental feature that inserts callbacks for
  certain data events. Currently callbacks are only inserted for loads, stores,
  memory transfers (i.e. memcpy and memmove), and comparisons. Its default value
  is false. If this flag is set to true, a user must provide definitions for the
  following callback functions:

```c++
void __dfsan_load_callback(dfsan_label Label, void* Addr);
void __dfsan_store_callback(dfsan_label Label, void* Addr);
void __dfsan_mem_transfer_callback(dfsan_label *Start, size_t Len);
void __dfsan_cmp_callback(dfsan_label CombinedLabel);
```

- `-dfsan-conditional-callbacks` -- An experimental feature that inserts
  callbacks for control flow conditional expressions.
  This can be used to find where tainted values can control execution.

  In addition to this compilation flag, a callback handler must be registered
  using `dfsan_set_conditional_callback(my_callback);`, where my_callback is
  a function with a signature matching
  `void my_callback(dfsan_label l, dfsan_origin o);`.
  This signature is the same when origin tracking is disabled - in this case
  the dfsan_origin passed in it will always be 0.

  The callback will only be called when a tainted value reaches a conditional
  expression for control flow (such as an if's condition).
  The callback will be skipped for conditional expressions inside signal
  handlers, as this is prone to deadlock. Tainted values used in conditional
  expressions inside signal handlers will instead be aggregated via bitwise
  or, and can be accessed using
  `dfsan_label dfsan_get_labels_in_signal_conditional();`.

- `-dfsan-reaches-function-callbacks` -- An experimental feature that inserts
  callbacks for data entering a function.

  In addition to this compilation flag, a callback handler must be registered
  using `dfsan_set_reaches_function_callback(my_callback);`, where my_callback is
  a function with a signature matching
  `void my_callback(dfsan_label label, dfsan_origin origin, const char *file, unsigned int line, const char *function);`
  This signature is the same when origin tracking is disabled - in this case
  the dfsan_origin passed in it will always be 0.

  The callback will be called when a tainted value reaches stack/registers
  in the context of a function. Tainted values can reach a function:
  \* via the arguments of the function
  \* via the return value of a call that occurs in the function
  \* via the loaded value of a load that occurs in the function

  The callback will be skipped for conditional expressions inside signal
  handlers, as this is prone to deadlock. Tainted values reaching functions
  inside signal handlers will instead be aggregated via bitwise or, and can
  be accessed using
  `dfsan_label dfsan_get_labels_in_signal_reaches_function()`.

- `-dfsan-track-origins` -- Controls how to track origins. When its value is
  0, the runtime does not track origins. When its value is 1, the runtime tracks
  origins at memory store operations. When its value is 2, the runtime tracks
  origins at memory load and store operations. Its default value is 0.

- `-dfsan-instrument-with-call-threshold` -- If a function being instrumented
  requires more than this number of origin stores, use callbacks instead of
  inline checks (-1 means never use callbacks). Its default value is 3500.

### Environment Variables

- `warn_unimplemented` -- Whether to warn on unimplemented functions. Its
  default value is false.
- `strict_data_dependencies` -- Whether to propagate labels only when there is
  explicit obvious data dependency (e.g., when comparing strings, ignore the fact
  that the output of the comparison might be implicit data-dependent on the
  content of the strings). This applies only to functions with `custom` category
  in ABI list. Its default value is true.
- `origin_history_size` -- The limit of origin chain length. Non-positive values
  mean unlimited. Its default value is 16.
- `origin_history_per_stack_limit` -- The limit of origin node's references count.
  Non-positive values mean unlimited. Its default value is 20000.
- `store_context_size` -- The depth limit of origin tracking stack traces. Its
  default value is 20.
- `zero_in_malloc` -- Whether to zero shadow space of new allocated memory. Its
  default value is true.
- `zero_in_free` --- Whether to zero shadow space of deallocated memory. Its
  default value is true.

## Example

DataFlowSanitizer supports up to 8 labels, to achieve low CPU and code
size overhead. Base labels are simply 8-bit unsigned integers that are
powers of 2 (i.e. 1, 2, 4, 8, ..., 128), and union labels are created
by ORing base labels.

The following program demonstrates label propagation by checking that
the correct labels are propagated.

```c++
#include <sanitizer/dfsan_interface.h>
#include <assert.h>

int main(void) {
  int i = 100;
  int j = 200;
  int k = 300;
  dfsan_label i_label = 1;
  dfsan_label j_label = 2;
  dfsan_label k_label = 4;
  dfsan_set_label(i_label, &i, sizeof(i));
  dfsan_set_label(j_label, &j, sizeof(j));
  dfsan_set_label(k_label, &k, sizeof(k));

  dfsan_label ij_label = dfsan_get_label(i + j);

  assert(ij_label & i_label);  // ij_label has i_label
  assert(ij_label & j_label);  // ij_label has j_label
  assert(!(ij_label & k_label));  // ij_label doesn't have k_label
  assert(ij_label == 3);  // Verifies all of the above

  // Or, equivalently:
  assert(dfsan_has_label(ij_label, i_label));
  assert(dfsan_has_label(ij_label, j_label));
  assert(!dfsan_has_label(ij_label, k_label));

  dfsan_label ijk_label = dfsan_get_label(i + j + k);

  assert(ijk_label & i_label);  // ijk_label has i_label
  assert(ijk_label & j_label);  // ijk_label has j_label
  assert(ijk_label & k_label);  // ijk_label has k_label
  assert(ijk_label == 7);  // Verifies all of the above

  // Or, equivalently:
  assert(dfsan_has_label(ijk_label, i_label));
  assert(dfsan_has_label(ijk_label, j_label));
  assert(dfsan_has_label(ijk_label, k_label));

  return 0;
}
```

## Origin Tracking

DataFlowSanitizer can track origins of labeled values. This feature is enabled by
`-mllvm -dfsan-track-origins=1`. For example,

```console
% cat test.cc
#include <sanitizer/dfsan_interface.h>
#include <stdio.h>

int main(int argc, char** argv) {
  int i = 0;
  dfsan_set_label(i_label, &i, sizeof(i));
  int j = i + 1;
  dfsan_print_origin_trace(&j, "A flow from i to j");
  return 0;
}

% clang++ -fsanitize=dataflow -mllvm -dfsan-track-origins=1 -fno-omit-frame-pointer -g -O2 test.cc
% ./a.out
Taint value 0x1 (at 0x7ffd42bf415c) origin tracking (A flow from i to j)
Origin value: 0x13900001, Taint value was stored to memory at
  #0 0x55676db85a62 in main test.cc:7:7
  #1 0x7f0083611bbc in __libc_start_main libc-start.c:285

Origin value: 0x9e00001, Taint value was created at
  #0 0x55676db85a08 in main test.cc:6:3
  #1 0x7f0083611bbc in __libc_start_main libc-start.c:285
```

By `-mllvm -dfsan-track-origins=1` DataFlowSanitizer collects only
intermediate stores a labeled value went through. Origin tracking slows down
program execution by a factor of 2x on top of the usual DataFlowSanitizer
slowdown and increases memory overhead by 1x. By `-mllvm -dfsan-track-origins=2`
DataFlowSanitizer also collects intermediate loads a labeled value went through.
This mode slows down program execution by a factor of 4x.

## Current status

DataFlowSanitizer is a work in progress, currently under development for
x86_64 Linux.

## Design

Please refer to the {doc}`design document<DataFlowSanitizerDesign>`.

---

### Clang Docs DataFlowSanitizerDesign (`clang/docs/DataFlowSanitizerDesign.md`)

# DataFlowSanitizer Design Document

This document sets out the design for DataFlowSanitizer, a general
dynamic data flow analysis. Unlike other Sanitizer tools, this tool is
not designed to detect a specific class of bugs on its own. Instead,
it provides a generic dynamic data flow analysis framework to be used
by clients to help detect application-specific issues within their
own code.

DataFlowSanitizer is a program instrumentation which can associate
a number of taint labels with any data stored in any memory region
accessible by the program. The analysis is dynamic, which means that
it operates on a running program, and tracks how the labels propagate
through that program.

## Use Cases

This instrumentation can be used as a tool to help monitor how data
flows from a program's inputs (sources) to its outputs (sinks).
This has applications from a privacy/security perspective in that
one can audit how a sensitive data item is used within a program and
ensure it isn't exiting the program anywhere it shouldn't be.

## Interface

A number of functions are provided which will attach taint labels to
memory regions and extract the set of labels associated with a
specific memory region. These functions are declared in the header
file `sanitizer/dfsan_interface.h`.

```c
/// Sets the label for each address in [addr,addr+size) to \c label.
void dfsan_set_label(dfsan_label label, void *addr, size_t size);

/// Sets the label for each address in [addr,addr+size) to the union of the
/// current label for that address and \c label.
void dfsan_add_label(dfsan_label label, void *addr, size_t size);

/// Retrieves the label associated with the given data.
///
/// The type of 'data' is arbitrary.  The function accepts a value of any type,
/// which can be truncated or extended (implicitly or explicitly) as necessary.
/// The truncation/extension operations will preserve the label of the original
/// value.
dfsan_label dfsan_get_label(long data);

/// Retrieves the label associated with the data at the given address.
dfsan_label dfsan_read_label(const void *addr, size_t size);

/// Returns whether the given label contains the label elem.
int dfsan_has_label(dfsan_label label, dfsan_label elem);

/// Computes the union of \c l1 and \c l2, resulting in a union label.
dfsan_label dfsan_union(dfsan_label l1, dfsan_label l2);

/// Flushes the DFSan shadow, i.e. forgets about all labels currently associated
/// with the application memory.  Use this call to start over the taint tracking
/// within the same process.
///
/// Note: If another thread is working with tainted data during the flush, that
/// taint could still be written to shadow after the flush.
void dfsan_flush(void);
```

The following functions are provided to check origin tracking status and results.

```
/* Detailed source-code truncated for AI context efficiency. */
```

The following functions are provided to register hooks called by custom wrappers.

```c
/// Sets a callback to be invoked on calls to `write`.  The callback is invoked
/// before the write is done. The write is not guaranteed to succeed when the
/// callback executes. Pass in NULL to remove any callback.
typedef void (*dfsan_write_callback_t)(int fd, const void *buf, size_t count);
void dfsan_set_write_callback(dfsan_write_callback_t labeled_write_callback);

/// Callbacks to be invoked on calls to `memcmp` or `strncmp`.
void dfsan_weak_hook_memcmp(void *caller_pc, const void *s1, const void *s2,
                            size_t n, dfsan_label s1_label,
                            dfsan_label s2_label, dfsan_label n_label);
void dfsan_weak_hook_strncmp(void *caller_pc, const char *s1, const char *s2,
                            size_t n, dfsan_label s1_label,
                            dfsan_label s2_label, dfsan_label n_label);
```

## Taint label representation

We use an 8-bit unsigned integer for the representation of a
label. The label identifier 0 is special, and means that the data item
is unlabelled. This is optimizing for low CPU and code size overhead
of the instrumentation. When a label union operation is requested at a
join point (any arithmetic or logical operation with two or more
operands, such as addition), we can simply OR the two labels in O(1).

Users are responsible for managing the 8 integer labels (i.e., keeping
track of what labels they have used so far, picking one that is yet
unused, etc).

## Origin tracking trace representation

An origin tracking trace is a list of chains. Each chain has a stack trace
where the DFSan runtime records a label propagation, and a pointer to its
previous chain. The very first chain does not point to any chain.

Every four 4-bytes aligned application bytes share a 4-byte origin trace ID. A
4-byte origin trace ID contains a 4-bit depth and a 28-bit hash ID of a chain.

A chain ID is calculated as a hash from a chain structure. A chain structure
contains a stack ID and the previous chain ID. The chain head has a zero
previous chain ID. A stack ID is a hash from a stack trace. The 4-bit depth
limits the maximal length of a path. The environment variable `origin_history_size`
can set the depth limit. Non-positive values mean unlimited. Its default value
is 16. When reaching the limit, origin tracking ignores following propagation
chains.

The first chain of a trace starts by `dfsan_set_label` with non-zero labels. A
new chain is appended at the end of a trace at stores or memory transfers when
`-dfsan-track-origins` is 1. Memory transfers include LLVM memory transfer
instructions, glibc memcpy and memmove. When `-dfsan-track-origins` is 2, a
new chain is also appended at loads.

Other instructions do not create new chains, but simply propagate origin trace
IDs. If an instruction has more than one operand with non-zero labels, the origin
trace ID of the last operand with non-zero label is propagated to the result of
the instruction.

## Memory layout and label management

The following is the memory layout for Linux/x86_64:

| Start          | End            | Use           |
| -------------- | -------------- | ------------- |
| 0x700000000000 | 0x800000000000 | application 3 |
| 0x610000000000 | 0x700000000000 | unused        |
| 0x600000000000 | 0x610000000000 | origin 1      |
| 0x510000000000 | 0x600000000000 | application 2 |
| 0x500000000000 | 0x510000000000 | shadow 1      |
| 0x400000000000 | 0x500000000000 | unused        |
| 0x300000000000 | 0x400000000000 | origin 3      |
| 0x200000000000 | 0x300000000000 | shadow 3      |
| 0x110000000000 | 0x200000000000 | origin 2      |
| 0x100000000000 | 0x110000000000 | unused        |
| 0x010000000000 | 0x100000000000 | shadow 2      |
| 0x000000000000 | 0x010000000000 | application 1 |

Each byte of application memory corresponds to a single byte of shadow
memory, which is used to store its taint label. We map memory, shadow, and
origin regions to each other with these masks and offsets:

- shadow_addr = memory_addr ^ 0x500000000000
- origin_addr = shadow_addr + 0x100000000000

As for LLVM SSA registers, we have not found it necessary to associate a label
with each byte or bit of data, as some other tools do. Instead, labels are
associated directly with registers. Loads will result in a union of
all shadow labels corresponding to bytes loaded, and stores will
result in a copy of the label of the stored value to the shadow of all
bytes stored to.

## Propagating labels through arguments

In order to propagate labels through function arguments and return values,
DataFlowSanitizer changes the ABI of each function in the translation unit.
There are currently two supported ABIs:

- Args -- Argument and return value labels are passed through additional
  arguments and by modifying the return type.
- TLS -- Argument and return value labels are passed through TLS variables
  `__dfsan_arg_tls` and `__dfsan_retval_tls`.

The main advantage of the TLS ABI is that it is more tolerant of ABI mismatches
(TLS storage is not shared with any other form of storage, whereas extra
arguments may be stored in registers which under the native ABI are not used
for parameter passing and thus could contain arbitrary values). On the other
hand the args ABI is more efficient and allows ABI mismatches to be more easily
identified by checking for nonzero labels in nominally unlabelled programs.

## Implementing the ABI list

The {ref}`ABI list <abi-list>` provides a list of functions
which conform to the native ABI, each of which is callable from an instrumented
program. This is implemented by replacing each reference to a native ABI
function with a reference to a function which uses the instrumented ABI.
Such functions are automatically-generated wrappers for the native functions.
For example, given the ABI list example provided in the user manual, the
following wrappers will be generated under the args ABI:

```llvm
define linkonce_odr { i8*, i16 } @"dfsw$malloc"(i64 %0, i16 %1) {
entry:
  %2 = call i8* @malloc(i64 %0)
  %3 = insertvalue { i8*, i16 } undef, i8* %2, 0
  %4 = insertvalue { i8*, i16 } %3, i16 0, 1
  ret { i8*, i16 } %4
}

define linkonce_odr { i32, i16 } @"dfsw$tolower"(i32 %0, i16 %1) {
entry:
  %2 = call i32 @tolower(i32 %0)
  %3 = insertvalue { i32, i16 } undef, i32 %2, 0
  %4 = insertvalue { i32, i16 } %3, i16 %1, 1
  ret { i32, i16 } %4
}

define linkonce_odr { i8*, i16 } @"dfsw$memcpy"(i8* %0, i8* %1, i64 %2, i16 %3, i16 %4, i16 %5) {
entry:
  %labelreturn = alloca i16
  %6 = call i8* @__dfsw_memcpy(i8* %0, i8* %1, i64 %2, i16 %3, i16 %4, i16 %5, i16* %labelreturn)
  %7 = load i16* %labelreturn
  %8 = insertvalue { i8*, i16 } undef, i8* %6, 0
  %9 = insertvalue { i8*, i16 } %8, i16 %7, 1
  ret { i8*, i16 } %9
}
```

As an optimization, direct calls to native ABI functions will call the
native ABI function directly and the pass will compute the appropriate label
internally. This has the advantage of reducing the number of union operations
required when the return value label is known to be zero (i.e. `discard`
functions, or `functional` functions with known unlabelled arguments).

## Checking ABI Consistency

DFSan changes the ABI of each function in the module. This makes it possible
for a function with the native ABI to be called with the instrumented ABI,
or vice versa, thus possibly invoking undefined behavior. A simple way
of statically detecting instances of this problem is to append the suffix
".dfsan" to the name of each instrumented-ABI function.

This will not catch every such problem; in particular function pointers passed
across the instrumented-native barrier cannot be used on the other side.
These problems could potentially be caught dynamically.

---

### Clang Docs DebuggingCoroutines (`clang/docs/DebuggingCoroutines.md`)

# Debugging C++ Coroutines


## Introduction

Coroutines in C++ were introduced in C++20, and the user experience for
debugging them can still be challenging. This document guides you on how to most
efficiently debug coroutines and how to navigate existing shortcomings in
debuggers and compilers.

Coroutines are generally used either as generators or for asynchronous
programming. In this document, we will discuss both use cases. Even if you are
using coroutines for asynchronous programming, you should still read the
generators section, as it introduces foundational debugging techniques also
applicable to the debugging of asynchronous programs.

Both compilers (clang, gcc, ...) and debuggers (lldb, gdb, ...) are
still improving their support for coroutines. As such, we recommend using the
latest available version of your toolchain.

This document focuses on clang and lldb. The screenshots show
[lldb-dap](https://marketplace.visualstudio.com/items?itemName=llvm-vs-code-extensions.lldb-dap)
in combination with VS Code. The same techniques can also be used in other
IDEs.

Debugging clang-compiled binaries with gdb is possible, but requires more
scripting. This guide comes with a basic GDB script for coroutine debugging.

This guide will first showcase the more polished, bleeding-edge experience, but
will also show you how to debug coroutines with older toolchains. In general,
the older your toolchain, the deeper you will have to dive into the
implementation details of coroutines (such as their ABI). The further down you go in
this document, the more low-level, technical the content will become. If
you are on an up-to-date toolchain, you will hopefully be able to stop reading
earlier.

## Debugging generators

One of the two major use cases for coroutines in C++ is generators, i.e.,
functions which can produce values via `co_yield`. Values are produced
lazily, on-demand. For this purpose, every time a new value is requested, the
coroutine gets resumed. As soon as it reaches a `co_yield` and thereby
returns the requested value, the coroutine is suspended again.

This logic is encapsulated in a `generator` type similar to this one:

```c++
// generator.hpp
#include <coroutine>

// `generator` is a stripped down, minimal generator type.
template<typename T>
struct generator {
  struct promise_type {
    T current_value{};

    auto get_return_object() {
      return std::coroutine_handle<promise_type>::from_promise(*this);
    }
    auto initial_suspend() { return std::suspend_always(); }
    auto final_suspend() noexcept { return std::suspend_always(); }
    auto return_void() { return std::suspend_always(); }
    void unhandled_exception() { __builtin_unreachable(); }
    auto yield_value(T v) {
      current_value = v;
      return std::suspend_always();
    }
  };

  generator(std::coroutine_handle<promise_type> h) : hdl(h) { hdl.resume(); }
  ~generator() { hdl.destroy(); }

  generator<T>& operator++() { hdl.resume(); return *this; } // resume the coroutine
  T operator*() const { return hdl.promise().current_value; }

  private:
  std::coroutine_handle<promise_type> hdl;
};
```

We can then use this `generator` class to print the Fibonacci sequence:

```c++
#include "generator.hpp"
#include <iostream>

generator<int> fibonacci() {
  co_yield 0;
  int prev = 0;
  co_yield 1;
  int current = 1;
  while (true) {
    int next = current + prev;
    co_yield next;
    prev = current;
    current = next;
  }
}

template<typename T>
void print10Elements(generator<T>& gen) {
  for (unsigned i = 0; i < 10; ++i) {
    std::cerr << *gen << "\n";
    ++gen;
  }
}

int main() {
  std::cerr << "Fibonacci sequence - here we go\n";
  generator<int> fib = fibonacci();
  for (unsigned i = 0; i < 5; ++i) {
    ++fib;
  }
  print10Elements(fib);
}
```

To compile this code, use `clang++ --std=c++23 generator-example.cpp -g`.

### Breakpoints inside the generators

We can set breakpoints inside coroutines just as we set them in regular
functions. For VS Code, that means clicking next the line number in the editor.
In the `lldb` CLI or in `gdb`, you can use `b` to set a breakpoint.

### Inspecting variables in a coroutine

If you hit a breakpoint inside the `fibonacci` function, you should be able
to inspect all local variables (`prev`, `current`, `next`) just like in
a regular function.

```{image} ./coro-generator-variables.png
```

Note the two additional variables `__promise` and `__coro_frame`. Those
show the internal state of the coroutine. They are not relevant for our
generator example but will be relevant for asynchronous programming described
in the next section.

### Stepping out of a coroutine

When single-stepping, you will notice that the debugger will leave the
`fibonacci` function as soon as you hit a `co_yield` statement. You might
find yourself inside some standard library code. After stepping out of the
library code, you will be back in the `main` function.

### Stepping into a coroutine

If you stop at `++fib` and try to step into the generator, you will first
find yourself inside `operator++`. Stepping into the `handle.resume()` will
not work by default.

This is because lldb does not step into functions from the standard library by
default. To make this work, you first need to run `settings set
target.process.thread.step-avoid-regexp ""`. You can do so from the "Debug
Console" towards the bottom of the screen. With that setting change, you can
step through `coroutine_handle::resume` and into your generator.

You might find yourself at the top of the coroutine at first, instead of at
your previous suspension point. In that case, single-step and you will arrive
at the previously suspended `co_yield` statement.

### Inspecting a suspended coroutine

The `print10Elements` function receives an opaque `generator` type. Let's
assume we are suspended at the `++gen;` line and want to inspect the
generator and its internal state.

To do so, we can simply look into the `gen.hdl` variable. LLDB comes with a
pretty printer for `std::coroutine_handle` which will show us the internal
state of the coroutine. For GDB, the pretty printer is provided by a script,
see {ref}`gdb-script` for setup instructions.

```{image} ./coro-generator-suspended.png
```

We can see two function pointers `resume` and `destroy`. These pointers
point to the resume / destroy functions. By inspecting those function pointers,
we can see that our `generator` is actually backed by our `fibonacci`
coroutine. When using VS Code + lldb-dap, you can Cmd+Click on the function
address (`0x555...` in the screenshot) to jump directly to the function
definition backing your coroutine handle.

Next, we see the `promise`. In our case, this reveals the current value of
our generator.

The `coro_frame` member represents the internal state of the coroutine. It
contains our internal coroutine state `prev`, `current`, `next`.
Furthermore, it contains many internal, compiler-specific members, which are
named based on their type. These represent temporary values which the compiler
decided to spill across suspension points, but which were not declared in our
original source code and hence have no proper user-provided name.

### Tracking the exact suspension point

Among the compiler-generated members, the `__coro_index` is particularly
important. This member identifies the suspension point at which the coroutine
is currently suspended. However, it is non-trivial to map this number back to
a source code location.

For GDB, the provided {ref}`gdb-script` already takes care of this and provides
the exact line number of the suspension point as part of the coroutine handle's
summary string. Unfortunately, LLDB's pretty-printer does not support this, yet.
Furthermore, those labels are only emitted starting with clang 21.0.

When debugging with LLDB or when using older clang versions, we will have to use
a different approach.

For simple cases, you might still be able to guess the suspension point correctly.
Alternatively, you might also want to modify your coroutine library to store
the line number of the current suspension point in the promise:

```c++
// For all promise_types we need a new `_coro_return_address` variable:
class promise_type {
  ...
  void* _coro_return_address = nullptr;
};

// For all the awaiter types we need:
class awaiter {
  ...
  template <typename Promise>
  __attribute__((noinline)) auto await_suspend(std::coroutine_handle<Promise> handle) {
        ...
        handle.promise()._coro_return_address = __builtin_return_address(0);
  }
};
```

This stores the return address of `await_suspend` within the promise.
Thereby, we can read it back from the promise of a suspended coroutine and map
it to an exact source code location. For a complete example, see the `task`
type used below for asynchronous programming.

Alternatively, we can modify the C++ code to store the line number in the
promise type. We can use `std::source_location` to get the line number of
the await and store it inside the `promise_type`. In the debugger, we can
then read the line number from the promise of the suspended coroutine.

```c++
// For all the awaiter types we need:
class awaiter {
  ...
  template <typename Promise>
  void await_suspend(std::coroutine_handle<Promise> handle,
                     std::source_location sl = std::source_location::current()) {
        ...
        handle.promise().line_number = sl.line();
  }
};
```

The downside of both approaches is that they come at the price of additional
runtime cost. In particular, the second approach increases binary size, since it
requires additional `std::source_location` objects, and those source
locations are not stripped by split-dwarf. Whether the first approach is worth
the additional runtime cost is a trade-off you need to make yourself.

## Async stack traces

Besides generators, the second common use case for coroutines in C++ is
asynchronous programming, usually involving libraries such as stdexec, folly,
cppcoro, boost::asio, or similar libraries. Some of those libraries already
provide custom debugging support, so in addition to this guide, you might want
to check out their documentation.

When using coroutines for asynchronous programming, your library usually
provides you with some `task` type. This type usually looks similar to this:

```
/* Detailed source-code truncated for AI context efficiency. */
```

Note how the `task::promise_type` has a member variable
`std::coroutine_handle<> continuation`. This is the handle of the coroutine
that will be resumed when the current coroutine is finished executing (see
`final_suspend`). In a sense, this is the "return address" of the coroutine.
It is set inside `operator co_await` when another coroutine calls our
generator and awaits for the next value to be produced.

The result value is returned via the `int result` member. It is written in
`return_value` and read by `Awaiter::await_resume`. Usually, the result
type of a task is a template argument. For simplicity's sake, we hard-coded the
`int` type in this example.

### Stack traces of in-flight coroutines

Let's assume you have the following program and set a breakpoint inside the
`write_output` function. There are multiple call paths through which this
function could have been reached. How can we find out said call path?

```c++
#include <iostream>
#include <string_view>
#include "async-task-library.hpp"

static task write_output(std::string_view contents) {
  std::cout << contents << "\n";
  co_return contents.size();
}

static task greet() {
  int bytes_written = 0;
  bytes_written += co_await write_output("Hello");
  bytes_written += co_await write_output("World");
  co_return bytes_written;
}

int main() {
  int bytes_written = greet().syncStart();
  std::cout << "Bytes written: " << bytes_written << "\n";
  return 0;
}
```

To do so, let's break inside `write_output`. We can understand our call-stack
by looking into the special `__promise` variable. This artificial variable is
generated by the compiler and points to the `promise_type` instance
corresponding to the currently in-flight coroutine. In this case, the
`__promise` variable contains the `continuation` which points to our
caller. That caller again contains a `promise` with a `continuation` which
points to our caller's caller.

```{image} ./coro-async-task-continuations.png
```

We can figure out the involved coroutine functions and their current suspension
points as discussed above in the "Inspecting a suspended coroutine" section.

When using LLDB's CLI, the command `p --ptr-depth 4 __promise` might also be
useful to automatically dereference all the pointers up to the given depth.

To get a flat representation of that call stack, we can use a debugger script,
such as the one shown in the {ref}`lldb-script` section. With that
script, we can run `coro bt` to get the following stack trace:

```
(lldb) coro bt
frame #0: write_output(std::basic_string_view<char, std::char_traits<char>>) at /home/avogelsgesang/Documents/corotest/async-task-example.cpp:6:16
[async] frame #1: greet() at /home/avogelsgesang/Documents/corotest/async-task-example.cpp:12:20
[async] frame #2: std::__n4861::coroutine_handle<std::__n4861::noop_coroutine_promise>::__frame::__dummy_resume_destroy() at /usr/include/c++/14/coroutine:298, suspension point unknown
frame #3: std::__n4861::coroutine_handle<task::promise_type>::resume() const at /usr/include/c++/14/coroutine:242:29
frame #4: task::syncStart() at /home/avogelsgesang/Documents/corotest/async-task-library.hpp:78:14
frame #5: main at /home/avogelsgesang/Documents/corotest/async-task-example.cpp:18:11
frame #6: __libc_start_call_main at sysdeps/nptl/libc_start_call_main.h:58:16
frame #7: __libc_start_main_impl at csu/libc-start.c:360:3
frame #8: _start at :4294967295
```

Note how the frames #1 and #2 are async frames.

The `coro bt` command already includes logic to identify the exact suspension
point of each frame based on the `_coro_suspension_point_addr` stored inside
the promise.

### Stack traces of suspended coroutines

Usually, while a coroutine is waiting for, e.g., an in-flight network request,
the suspended `coroutine_handle` is stored within the work queues inside the
IO scheduler. As soon as we get hold of the coroutine handle, we can backtrace
it by using `coro bt <coro_handle>` where `<coro_handle>` is an expression
evaluating to the coroutine handle of the suspended coroutine.

### Keeping track of all existing coroutines

Usually, we should be able to get hold of all currently suspended coroutines by
inspecting the worker queues of the IO scheduler. In cases where this is not
possible, we can use the following approach to keep track of all currently
suspended coroutines.

One such solution is to store the list of in-flight coroutines in a collection:

```c++
inline std::unordered_set<std::coroutine_handle<void>> inflight_coroutines;
inline std::mutex inflight_coroutines_mutex;

class promise_type {
public:
    promise_type() {
        std::unique_lock<std::mutex> lock(inflight_coroutines_mutex);
        inflight_coroutines.insert(std::coroutine_handle<promise_type>::from_promise(*this));
    }
    ~promise_type() {
        std::unique_lock<std::mutex> lock(inflight_coroutines_mutex);
        inflight_coroutines.erase(std::coroutine_handle<promise_type>::from_promise(*this));
    }
};
```

With this in place, it is possible to inspect `inflight_coroutines` from the
debugger and rely on LLDB's `std::coroutine_handle` pretty-printer to
inspect the coroutines.

This technique will track *all* coroutines, also the ones which are currently
awaiting another coroutine, though. To identify just the "roots" of our
in-flight coroutines, we can use the `coro in-flight inflight_coroutines`
command provided by the {ref}`lldb-script`.

Please note that the above is expensive from a runtime performance perspective,
and requires locking to prevent data races. As such, it is not recommended to
use this approach in production code.

## Known issues & workarounds for older LLDB versions

LLDB before 21.0 did not yet show the `__coro_frame` inside
`coroutine_handle`. To inspect the coroutine frame, you had to use the
approach described in the {ref}`devirtualization` section.

LLDB before 18.0 hid the `__promise` and `__coro_frame`
variables by default. The variables are still present, but they need to be
explicitly added to the "watch" pane in VS Code or requested via
`print __promise` and `print __coro_frame` from the debugger console.

LLDB before 16.0 did not yet provide a pretty-printer for
`std::coroutine_handle`. To inspect the coroutine handle, you had to manually
use the approach described in the {ref}`devirtualization`
section.

## Toolchain Implementation Details

This section covers the ABI as well as additional compiler-specific behavior.
The ABI is followed by all compilers, on all major systems, including Windows,
Linux, and macOS. Different compilers emit different debug information, though.

### Ramp, resume and destroy functions

Every coroutine is split into three parts:

- The ramp function allocates the coroutine frame and initializes it, usually
  copying over all variables into the coroutine frame
- The resume function continues the coroutine from its previous suspension point
- The destroy function destroys and deallocates the coroutine frame
- The cleanup function destroys the coroutine frame but does not deallocate it.
  It is used when the coroutine's allocation was elided thanks to
  [Heap Allocation Elision (HALO)](https://www.open-std.org/JTC1/SC22/WG21/docs/papers/2018/p0981r0.html)

The ramp function is called by the coroutine's caller, and available under the
original function name used in the C++ source code. The resume function is
called via `std::coroutine_handle::resume`. The destroy function is called
via `std::coroutine_handle::destroy`.

Information between the three functions is passed via the coroutine frame, a
compiler-synthesized struct that contains all necessary internal state. The
resume function knows where to resume execution by reading the suspension point
index from the coroutine frame. Similarly, the destroy function relies on the
suspension point index to know which variables are currently in scope and need
to be destructed.

Usually, the destroy function calls all destructors and deallocates the
coroutine frame. When a coroutine frame was elided thanks to HALO, only the
destructors need to be called, but the coroutine frame must not be deallocated.
In those cases, the cleanup function is used instead of the destroy function.

For coroutines allocated with `[[clang::coro_await_elidable]]`, clang also
generates a `.noalloc` variant of the ramp function, which does not allocate
the coroutine frame by itself, but instead expects the caller to allocate the
coroutine frame and pass it to the ramp function.

When trying to intercept all creations of new coroutines in the debugger, you
hence might have to set breakpoints in the ramp function and its `.noalloc`
variant.

### Artificial `__promise` and `__coro_frame` variables

Inside all coroutine functions, clang / LLVM synthesize a `__promise` and
`__coro_frame` variable. These variables are used to store the coroutine's
state. When inside the coroutine function, those can be used to directly
inspect the promise and the coroutine frame of the own function.

### The ABI of a coroutine

A `std::coroutine_handle` essentially only holds a pointer to a coroutine
frame. It resembles the following struct:

```c++
template<typename promise_type>
struct coroutine_handle {
  void* __coroutine_frame = nullptr;
};
```

The structure of coroutine frames is defined as

```c++
struct my_coroutine_frame {
  void (*__resume)(coroutine_frame*); // function pointer to the `resume` function
  void (*__destroy)(coroutine_frame*); // function pointer to the `destroy` function
  promise_type promise; // the corresponding `promise_type`
  ... // Internal coroutine state
}
```

For each coroutine, the compiler synthesizes a different coroutine type,
storing all necessary internal state. The actual coroutine type is type-erased
behind the `std::coroutine_handle`.

However, all coroutine frames always contain the `resume` and `destroy`
functions as their first two members. As such, we can read the function
pointers from the coroutine frame and then obtain the function's name from its
address.

The promise is guaranteed to be at a 16-byte offset from the coroutine frame.
If we have a coroutine handle at address 0x416eb0, we can hence reinterpret-cast
the promise as follows:

```text
print (task::promise_type)*(0x416eb0+16)
```

### Implementation in clang / LLVM

The C++ Coroutines feature in the Clang compiler is implemented in two parts of
the compiler. Semantic analysis is performed in Clang, and coroutine
construction and optimization take place in the LLVM middle-end.

For each coroutine function, the frontend generates a single corresponding
LLVM-IR function. This function uses special `llvm.coro.suspend` intrinsics
to mark the suspension points of the coroutine. The middle end first optimizes
this function and applies, e.g., constant propagation across the whole,
non-split coroutine.

CoroSplit then splits the function into ramp, resume and destroy functions.
This pass also moves stack-local variables which are alive across suspension
points into the coroutine frame. Most of the heavy lifting to preserve debugging
information is done in this pass. This pass needs to rewrite all variable
locations to point into the coroutine frame.

Afterwards, a couple of additional optimizations are applied before code
gets emitted, but none of them are really interesting regarding debugging
information.

For more details on the IR representation of coroutines and the relevant
optimization passes, see [Coroutines in LLVM](https://llvm.org/docs/Coroutines.html).

Emitting debug information inside `CoroSplit` forces us to generate
insufficient debugging information. Usually, the compiler generates debug
information in the frontend, as debug information is highly language specific.
However, this is not possible for coroutine frames because the frames are
constructed in the LLVM middle-end.

To mitigate this problem, the LLVM middle end attempts to generate some debug
information, which is unfortunately incomplete, since much of the
language-specific information is missing in the middle end.

(devirtualization)=

### Devirtualization of coroutine handles

Figuring out the promise type and the coroutine frame type of a coroutine
handle requires inspecting the `resume` and `destroy` function pointers.
There are two possible approaches to do so:

1. clang always names the type by appending `.coro_frame_ty` to the
   linkage name of the ramp function.
2. Both clang and GCC add the function-local `__promise` and
   `__coro_frame` variables to the resume and destroy functions.
   We can lookup their types and thereby get the types of promise
   and coroutine frame.

In general, the second approach is preferred, as it is more portable.

To do so, we look up the types in the destroy function and not the resume function
because the resume function pointer will be set to a `nullptr` as soon as a
coroutine reaches its final suspension point. If we used the resume function,
devirtualization would hence fail for all coroutines that have reached their final
suspension point.

LLDB comes with devirtualization support out of the box, as part of the
pretty-printer for `std::coroutine_handle`. For GDB, a similar pretty-printer
is provided by the {ref}`gdb-script`.

### Interpreting the coroutine frame in optimized builds

The `__coro_frame` variable usually refers to the coroutine frame of an
*in-flight* coroutine. This means the coroutine is currently executing.
However, the compiler only guarantees the coroutine frame to be in a consistent
state while the coroutine is suspended. As such, the variables inside the
`__coro_frame` variable might be outdated, particularly when optimizations
are enabled.

Furthermore, when optimizations are enabled, the compiler will layout the
coroutine frame more aggressively. Unused values are optimized out, and the
state will usually contain only the minimal information required to reconstruct
the coroutine's state.

clang / LLVM usually use variables like `__int_32_0` to represent this
optimized storage. Those values usually do not directly correspond to variables
in the source code.

When compiling the program

```c++
static task coro_task(int v) {
  int a = v;
  co_await some_other_task();
  a++; // __int_32_0 is 43 here
  std::cout << a << "\n";
  a++; // __int_32_0 is still 43 here
  std::cout << a << "\n";
  a++; // __int_32_0 is still 43 here!
  std::cout << a << "\n";
  co_await some_other_task();
  a++; // __int_32_0 is still 43 here!!
  std::cout << a << "\n";
  a++; // Why is __int_32_0 still 43 here?
  std::cout << a << "\n";
}
```

clang creates a single entry `__int_32_0` in the coroutine state.

Intuitively, one might assume that `__int_32_0` represents the value of the
local variable `a`. However, inspecting `__int_32_0` in the debugger while
single-stepping will reveal that the value of `__int_32_0` stays constant,
despite `a` being frequently incremented.

While this might be surprising, this is a result of the optimizer recognizing
that it can eliminate most of the load/store operations.
The above code is optimized to the equivalent of:

```c++
static task coro_task(int v) {
  store v into __int_32_0 in the frame
  co_await await_counter{};
  a = load __int_32_0
  std::cout << a+1 << "\n";
  std::cout << a+2 << "\n";
  std::cout << a+3 << "\n";
  co_await await_counter{};
  a = load __int_32_0
  std::cout << a+4 << "\n";
  std::cout << a+5 << "\n";
}
```

It should now be obvious why the value of `__int_32_0` remains unchanged
throughout the function. It is important to recognize that `__int_32_0` does
not directly correspond to `a`, but is instead a variable generated to assist
the compiler in code generation. The variables in an optimized coroutine frame
should not be thought of as directly representing the variables in the C++
source.

### Mapping suspension point indices to source code locations

To aid in mapping a `__coro_index` back to a source code location, clang 21.0
and newer emit special, compiler-generated labels for the suspension points.

In gdb, we can use the `info line` command to get the source code location of
the suspension point.

```
(gdb) info line -function coro_task -label __coro_resume_2
Line 45 of "llvm-example.cpp" starts at address 0x1b1b <_ZL9coro_taski.resume+555> and ends at 0x1b46 <_ZL9coro_taski.resume+598>.
Line 45 of "llvm-example.cpp" starts at address 0x201b <_ZL9coro_taski.destroy+555> and ends at 0x2046 <_ZL9coro_taski.destroy+598>.
Line 45 of "llvm-example.cpp" starts at address 0x253b <_ZL9coro_taski.cleanup+555> and ends at 0x2566 <_ZL9coro_taski.cleanup+598>.
```

LLDB does not support looking up labels, yet. For this reason, LLDB's pretty-printer
does not show the exact line number of the suspension point.

## Resources

(lldb-script)=

### LLDB Debugger Script

The following script provides the `coro bt` and `coro in-flight` commands
discussed above. It can be loaded into LLDB using `command script import
lldb_coro_debugging.py`. To load this by default, add this command to your
`~/.lldbinit` file.

Note that this script requires LLDB 21.0 or newer.

```
/* Detailed source-code truncated for AI context efficiency. */
```

(gdb-script)=

### GDB Debugger Script

The following script provides:

- a pretty-printer for coroutine handles
- a frame filter to add coroutine frames to the built-in `bt` command
- the `get_coro_frame` and `get_coro_promise` functions to be used in
  expressions, e.g. `p get_coro_promise(fib.coro_hdl)->current_state`

It can be loaded into GDB using `source gdb_coro_debugging.py`.
To load this by default, add this command to your `~/.gdbinit` file.

```
/* Detailed source-code truncated for AI context efficiency. */
```
p *get_coro_frame(coroutine_hdl)
```
"""
class GetCoroFrame(gdb.Function):
    def __init__(self):
        super(GetCoroFrame, self).__init__("get_coro_frame")

    def invoke(self, coroutine_hdl_raw):
        return CoroutineHandlePrinter(coroutine_hdl_raw).frame_ptr

GetCoroFrame()


"""
Get the coroutine frame pointer from a coroutine handle.

Usage:
```
p *get_coro_promise(coroutine_hdl)
```
/* Detailed source-code truncated for AI context efficiency. */
````

### Further Reading

The authors of the Folly libraries wrote a blog post series on how they debug coroutines:

- [Async stack traces in folly: Introduction](https://developers.facebook.com/blog/post/2021/09/16/async-stack-traces-folly-Introduction/)
- [Async stack traces in folly: Synchronous and asynchronous stack traces](https://developers.facebook.com/blog/post/2021/09/23/async-stack-traces-folly-synchronous-asynchronous-stack-traces/)
- [Async stack traces in folly: Forming an async stack from individual frames](https://developers.facebook.com/blog/post/2021/09/30/async-stack-traces-folly-forming-async-stack-individual-frames/)
- [Async Stack Traces for C++ Coroutines in Folly: Walking the async stack](https://developers.facebook.com/blog/post/2021/10/14/async-stack-traces-c-plus-plus-coroutines-folly-walking-async-stack/)
- [Async stack traces in folly: Improving debugging in the developer lifecycle](https://developers.facebook.com/blog/post/2021/10/21/async-stack-traces-folly-improving-debugging-developer-lifecycle/)

Besides some topics also covered here (stack traces from the debugger), Folly's blog post series also covers
additional topics, such as capturing async stack traces in performance profiles via eBPF filters
and printing async stack traces on crashes.

---

### Clang Docs DriverInternals (`clang/docs/DriverInternals.md`)

# Driver Design & Internals


## Introduction

This document describes the Clang driver. The purpose of this document
is to describe both the motivation and design goals for the driver, as
well as details of the internal implementation.

## Features and Goals

The Clang driver is intended to be a production quality compiler driver
providing access to the Clang compiler and tools, with a command line
interface which is compatible with the gcc driver.

Although the driver is part of and driven by the Clang project, it is
logically a separate tool which shares many of the same goals as Clang:


### GCC Compatibility

The number one goal of the driver is to ease the adoption of Clang by
allowing users to drop Clang into a build system which was designed to
call GCC. Although this makes the driver much more complicated than
might otherwise be necessary, we decided that being very compatible with
the gcc command line interface was worth it in order to allow users to
quickly test clang on their projects.

### Flexible

The driver was designed to be flexible and easily accommodate new uses
as we grow the clang and LLVM infrastructure. As one example, the driver
can easily support the introduction of tools which have an integrated
assembler; something we hope to add to LLVM in the future.

Similarly, most of the driver functionality is kept in a library which
can be used to build other tools which want to implement or accept a gcc
like interface.

### Low Overhead

The driver should have as little overhead as possible. In practice, we
found that the gcc driver by itself incurred a small but meaningful
overhead when compiling many small files. The driver doesn't do much
work compared to a compilation, but we have tried to keep it as
efficient as possible by following a few simple principles:

- Avoid memory allocation and string copying when possible.
- Don't parse arguments more than once.
- Provide a few simple interfaces for efficiently searching arguments.

### Simple

Finally, the driver was designed to be "as simple as possible", given
the other goals. Notably, trying to be completely compatible with the
gcc driver adds a significant amount of complexity. However, the design
of the driver attempts to mitigate this complexity by dividing the
process into a number of independent stages instead of a single
monolithic task.

## Internal Design and Implementation


### Internals Introduction

In order to satisfy the stated goals, the driver was designed to
completely subsume the functionality of the gcc executable; that is, the
driver should not need to delegate to gcc to perform subtasks. On
Darwin, this implies that the Clang driver also subsumes the gcc
driver-driver, which is used to implement support for building universal
images (binaries and object files). This also implies that the driver
should be able to call the language specific compilers (e.g. cc1)
directly, which means that it must have enough information to forward
command line arguments to child processes correctly.

### Design Overview

The diagram below shows the significant components of the driver
architecture and how they relate to one another. The orange components
represent concrete data structures built by the driver, the green
components indicate conceptually distinct stages which manipulate these
data structures, and the blue components are important helper classes.

```{image} DriverArchitecture.png
:align: center
:alt: Driver Architecture Diagram
```

### Driver Stages

The driver functionality is conceptually divided into five stages:

1. **Parse: Option Parsing**

   The command line argument strings are decomposed into arguments
   (`Arg` instances). The driver expects to understand all available
   options, although there is some facility for just passing certain
   classes of options through (like `-Wl,`).

   Each argument corresponds to exactly one abstract `Option`
   definition, which describes how the option is parsed along with some
   additional metadata. The Arg instances themselves are lightweight and
   merely contain enough information for clients to determine which
   option they correspond to and their values (if they have additional
   parameters).

   For example, a command line like "-Ifoo -I foo" would parse to two
   Arg instances (a JoinedArg and a SeparateArg instance), but each
   would refer to the same Option.

   Options are lazily created in order to avoid populating all Option
   classes when the driver is loaded. Most of the driver code only needs
   to deal with options by their unique ID (e.g., `options::OPT_I`),

   Arg instances themselves do not generally store the values of
   parameters. In many cases, this would simply result in creating
   unnecessary string copies. Instead, Arg instances are always embedded
   inside an ArgList structure, which contains the original vector of
   argument strings. Each Arg itself only needs to contain an index into
   this vector instead of storing its values directly.

   The clang driver can dump the results of this stage using the
   `-###` flag (which must precede any actual command
   line arguments). For example:

   ```console
   $ clang -### -Xarch_i386 -fomit-frame-pointer -Wa,-fast -Ifoo -I foo t.c
   Option 0 - Name: "-Xarch_", Values: {"i386", "-fomit-frame-pointer"}
   Option 1 - Name: "-Wa,", Values: {"-fast"}
   Option 2 - Name: "-I", Values: {"foo"}
   Option 3 - Name: "-I", Values: {"foo"}
   Option 4 - Name: "<input>", Values: {"t.c"}
   ```

   After this stage is complete the command line should be broken down
   into well defined option objects with their appropriate parameters.
   Subsequent stages should rarely, if ever, need to do any string
   processing.

2. **Pipeline: Compilation Action Construction**

   Once the arguments are parsed, the tree of subprocess jobs needed for
   the desired compilation sequence are constructed. This involves
   determining the input files and their types, what work is to be done
   on them (preprocess, compile, assemble, link, etc.), and constructing
   a list of Action instances for each task. The result is a list of one
   or more top-level actions, each of which generally corresponds to a
   single output (for example, an object or linked executable).

   The majority of Actions correspond to actual tasks, however there are
   two special Actions. The first is InputAction, which simply serves to
   adapt an input argument for use as an input to other Actions. The
   second is BindArchAction, which conceptually alters the architecture
   to be used for all of its input Actions.

   The clang driver can dump the results of this stage using the
   `-ccc-print-phases` flag. For example:

   ```console
   $ clang -ccc-print-phases -x c t.c -x assembler t.s
   0: input, "t.c", c
   1: preprocessor, {0}, cpp-output
   2: compiler, {1}, assembler
   3: assembler, {2}, object
   4: input, "t.s", assembler
   5: assembler, {4}, object
   6: linker, {3, 5}, image
   ```

   Here the driver is constructing seven distinct actions, four to
   compile the "t.c" input into an object file, two to assemble the
   "t.s" input, and one to link them together.

   A rather different compilation pipeline is shown here; in this
   example there are two top level actions to compile the input files
   into two separate object files, where each object file is built using
   `lipo` to merge results built for two separate architectures.

   ```console
   $ clang -ccc-print-phases -c -arch i386 -arch x86_64 t0.c t1.c
   0: input, "t0.c", c
   1: preprocessor, {0}, cpp-output
   2: compiler, {1}, assembler
   3: assembler, {2}, object
   4: bind-arch, "i386", {3}, object
   5: bind-arch, "x86_64", {3}, object
   6: lipo, {4, 5}, object
   7: input, "t1.c", c
   8: preprocessor, {7}, cpp-output
   9: compiler, {8}, assembler
   10: assembler, {9}, object
   11: bind-arch, "i386", {10}, object
   12: bind-arch, "x86_64", {10}, object
   13: lipo, {11, 12}, object
   ```

   After this stage is complete the compilation process is divided into
   a simple set of actions which need to be performed to produce
   intermediate or final outputs (in some cases, like `-fsyntax-only`,
   there is no "real" final output). Phases are well known compilation
   steps, such as "preprocess", "compile", "assemble", "link", etc.

3. **Bind: Tool & Filename Selection**

   This stage (in conjunction with the Translate stage) turns the tree
   of Actions into a list of actual subprocess to run. Conceptually, the
   driver performs a top down matching to assign Action(s) to Tools. The
   ToolChain is responsible for selecting the tool to perform a
   particular action; once selected the driver interacts with the tool
   to see if it can match additional actions (for example, by having an
   integrated preprocessor).

   Once Tools have been selected for all actions, the driver determines
   how the tools should be connected (for example, using an inprocess
   module, pipes, temporary files, or user provided filenames). If an
   output file is required, the driver also computes the appropriate
   file name (the suffix and file location depend on the input types and
   options such as `-save-temps`).

   The driver interacts with a ToolChain to perform the Tool bindings.
   Each ToolChain contains information about all the tools needed for
   compilation for a particular architecture, platform, and operating
   system. A single driver invocation may query multiple ToolChains
   during one compilation in order to interact with tools for separate
   architectures.

   The results of this stage are not computed directly, but the driver
   can print the results via the `-ccc-print-bindings` option. For
   example:

   ```console
   $ clang -ccc-print-bindings -arch i386 -arch ppc t0.c
   # "i386-apple-darwin9" - "clang", inputs: ["t0.c"], output: "/tmp/cc-Sn4RKF.s"
   # "i386-apple-darwin9" - "darwin::Assemble", inputs: ["/tmp/cc-Sn4RKF.s"], output: "/tmp/cc-gvSnbS.o"
   # "i386-apple-darwin9" - "darwin::Link", inputs: ["/tmp/cc-gvSnbS.o"], output: "/tmp/cc-jgHQxi.out"
   # "ppc-apple-darwin9" - "gcc::Compile", inputs: ["t0.c"], output: "/tmp/cc-Q0bTox.s"
   # "ppc-apple-darwin9" - "gcc::Assemble", inputs: ["/tmp/cc-Q0bTox.s"], output: "/tmp/cc-WCdicw.o"
   # "ppc-apple-darwin9" - "gcc::Link", inputs: ["/tmp/cc-WCdicw.o"], output: "/tmp/cc-HHBEBh.out"
   # "i386-apple-darwin9" - "darwin::Lipo", inputs: ["/tmp/cc-jgHQxi.out", "/tmp/cc-HHBEBh.out"], output: "a.out"
   ```

   This shows the tool chain, tool, inputs and outputs which have been
   bound for this compilation sequence. Here clang is being used to
   compile t0.c on the i386 architecture and darwin specific versions of
   the tools are being used to assemble and link the result, but generic
   gcc versions of the tools are being used on PowerPC.

4. **Translate: Tool Specific Argument Translation**

   Once a Tool has been selected to perform a particular Action, the
   Tool must construct concrete Commands which will be executed during
   compilation. The main work is in translating from the gcc style
   command line options to whatever options the subprocess expects.

   Some tools, such as the assembler, only interact with a handful of
   arguments and just determine the path of the executable to call and
   pass on their input and output arguments. Others, like the compiler
   or the linker, may translate a large number of arguments in addition.

   The ArgList class provides a number of simple helper methods to
   assist with translating arguments; for example, to pass on only the
   last of arguments corresponding to some option, or all arguments for
   an option.

   The result of this stage is a list of Commands (executable paths and
   argument strings) to execute.

5. **Execute**

   Finally, the compilation pipeline is executed. This is mostly
   straightforward, although there is some interaction with options like
   `-pipe`, `-pass-exit-codes` and `-time`.

### Additional Notes

#### The Compilation Object

The driver constructs a Compilation object for each set of command line
arguments. The Driver itself is intended to be invariant during
construction of a Compilation; an IDE should be able to construct a
single long lived driver instance to use for an entire build, for
example.

The Compilation object holds information that is particular to each
compilation sequence. For example, the list of used temporary files
(which must be removed once compilation is finished) and result files
(which should be removed if compilation fails).

#### Unified Parsing & Pipelining

Parsing and pipelining both occur without reference to a Compilation
instance. This is by design; the driver expects that both of these
phases are platform neutral, with a few very well defined exceptions
such as whether the platform uses a driver driver.

#### ToolChain Argument Translation

In order to match gcc very closely, the clang driver currently allows
tool chains to perform their own translation of the argument list (into
a new ArgList data structure). Although this allows the clang driver to
match gcc easily, it also makes the driver operation much harder to
understand (since the Tools stop seeing some arguments the user
provided, and see new ones instead).

For example, on Darwin `-gfull` gets translated into two separate
arguments, `-g` and `-fno-eliminate-unused-debug-symbols`. Trying to
write Tool logic to do something with `-gfull` will not work, because
Tool argument translation is done after the arguments have been
translated.

A long term goal is to remove this tool chain specific translation, and
instead force each tool to change its own logic to do the right thing on
the untranslated original arguments.

#### Unused Argument Warnings

The driver operates by parsing all arguments but giving Tools the
opportunity to choose which arguments to pass on. One downside of this
infrastructure is that if the user misspells some option, or is confused
about which options to use, some command line arguments the user really
cared about may go unused. This problem is particularly important when
using clang as a compiler, since the clang compiler does not support
anywhere near all the options that gcc does, and we want to make sure
users know which ones are being used.

To support this, the driver maintains a bit associated with each
argument of whether it has been used (at all) during the compilation.
This bit usually doesn't need to be set by hand, as the key ArgList
accessors will set it automatically.

When a compilation is successful (there are no errors), the driver
checks the bit and emits an "unused argument" warning for any arguments
which were never accessed. This is conservative (the argument may not
have been used to do what the user wanted) but still catches the most
obvious cases.

### Relation to GCC Driver Concepts

For those familiar with the gcc driver, this section provides a brief
overview of how things from the gcc driver map to the clang driver.

- **Driver Driver**

  The driver driver is fully integrated into the clang driver. The
  driver simply constructs additional Actions to bind the architecture
  during the *Pipeline* phase. The tool chain specific argument
  translation is responsible for handling `-Xarch_`.

  The one caveat is that this approach requires `-Xarch_` not be used
  to alter the compilation itself (for example, one cannot provide
  `-S` as an `-Xarch_` argument). The driver attempts to reject
  such invocations, and overall there isn't a good reason to abuse
  `-Xarch_` to that end in practice.

  The upside is that the clang driver is more efficient and does little
  extra work to support universal builds. It also provides better error
  reporting and UI consistency.

- **Specs**

  The clang driver has no direct correspondent for "specs". The
  majority of the functionality that is embedded in specs is in the
  Tool specific argument translation routines. The parts of specs which
  control the compilation pipeline are generally part of the *Pipeline*
  stage.

- **Toolchains**

  The gcc driver has no direct understanding of tool chains. Each gcc
  binary roughly corresponds to the information which is embedded
  inside a single ToolChain.

  The clang driver is intended to be portable and support complex
  compilation environments. All platform and tool chain specific code
  should be protected behind either abstract or well defined interfaces
  (such as whether the platform supports use as a driver driver).

---

### Clang Docs ExternalClangExamples (`clang/docs/ExternalClangExamples.md`)

# External Clang Examples

## Introduction

This page provides some examples of the kinds of things that people have
done with Clang that might serve as useful guides (or starting points) from
which to develop your own tools. They may be helpful even for something as
banal (but necessary) as how to set up your build to integrate Clang.

Clang's library-based design is deliberately aimed at facilitating use by
external projects, and we are always interested in improving Clang to
better serve our external users. Some typical categories of applications
where Clang is used are:

- Static analysis.
- Documentation/cross-reference generation.

If you know of (or wrote!) a tool or project using Clang, please post on
[the Discourse forums (Clang Frontend category)](https://discourse.llvm.org/c/clang/6) to have it added.
(or if you are already a Clang contributor, feel free to directly commit
additions). Since the primary purpose of this page is to provide examples
that can help developers, generally they must have code available.

## List of projects and tools

[https://github.com/Andersbakken/rtags/](https://github.com/Andersbakken/rtags/)

: "RTags is a client/server application that indexes c/c++ code and keeps
  a persistent in-memory database of references, symbolnames, completions
  etc."

[https://rprichard.github.io/CxxCodeBrowser/](https://rprichard.github.io/CxxCodeBrowser/)

: "A C/C++ source code indexer and navigator."

[https://github.com/etaoins/qconnectlint](https://github.com/etaoins/qconnectlint)

: "qconnectlint is a Clang tool for statically verifying the consistency
  of signal and slot connections made with Qt's `QObject::connect`."

[https://github.com/woboq/woboq_codebrowser](https://github.com/woboq/woboq_codebrowser)

: "The Woboq Code Browser is a web-based code browser for C/C++ projects.
  Check out [https://code.woboq.org/](https://code.woboq.org/) for an example!"

[https://github.com/mozilla/dxr](https://github.com/mozilla/dxr)

: "DXR is a source code cross-reference tool that uses static analysis
  data collected by instrumented compilers."

[https://github.com/eschulte/clang-mutate](https://github.com/eschulte/clang-mutate)

: "This tool performs a number of operations on C-language source files."

[https://github.com/gmarpons/Crisp](https://github.com/gmarpons/Crisp)

: "A coding rule validation add-on for LLVM/clang. Crisp rules are written
  in Prolog. A high-level declarative DSL to easily write new rules is under
  development. It will be called CRISP, an acronym for *Coding Rules in
  Sugared Prolog*."

[https://github.com/drothlis/clang-ctags](https://github.com/drothlis/clang-ctags)

: "Generate tag file for C++ source code."

[https://github.com/exclipy/clang_indexer](https://github.com/exclipy/clang_indexer)

: "This is an indexer for C and C++ based on the libclang library."

[https://github.com/holtgrewe/linty](https://github.com/holtgrewe/linty)

: "Linty - C/C++ Style Checking with Python & libclang."

[https://github.com/axw/cmonster](https://github.com/axw/cmonster)

: "cmonster is a Python wrapper for the Clang C++ parser."

[https://github.com/rizsotto/Constantine](https://github.com/rizsotto/Constantine)

: "Constantine is a toy project to learn how to write clang plugin.
  Implements pseudo const analysis. Generates warnings about variables,
  which were declared without const qualifier."

[https://github.com/jessevdk/cldoc](https://github.com/jessevdk/cldoc)

: "cldoc is a Clang based documentation generator for C and C++.
  cldoc tries to solve the issue of writing C/C++ software documentation
  with a modern, non-intrusive and robust approach."

[https://github.com/AlexDenisov/ToyClangPlugin](https://github.com/AlexDenisov/ToyClangPlugin)

: "The simplest Clang plugin implementing a semantic check for Objective-C.
  This example shows how to use the `DiagnosticsEngine` (emit warnings,
  errors, fixit hints). See also [http://l.rw.rw/clang_plugin](http://l.rw.rw/clang_plugin) for
  step-by-step instructions."

[https://invent.kde.org/sdk/clazy](https://invent.kde.org/sdk/clazy)

: "clazy is a compiler plugin which allows clang to understand Qt semantics.
  You get more than 50 Qt related compiler warnings, ranging from unneeded
  memory allocations to misusage of API, including fix-its for automatic
  refactoring."

[https://gerrit.libreoffice.org/gitweb?p=core.git;a=blob_plain;f=compilerplugins/README;hb=HEAD](https://gerrit.libreoffice.org/gitweb?p=core.git;a=blob_plain;f=compilerplugins/README;hb=HEAD)

: "LibreOffice uses a Clang plugin infrastructure to check during the build
  various things, some more, some less specific to the LibreOffice source code.
  There are currently around 50 such checkers, from flagging C-style casts and
  uses of reserved identifiers to ensuring that code adheres to lifecycle
  protocols for certain LibreOffice-specific classes. They may serve as
  examples for writing RecursiveASTVisitor-based plugins."

[https://github.com/banach-space/clang-tutor](https://github.com/banach-space/clang-tutor)

: "A collection of out-of-tree Clang plugins for teaching and learning."

---

### Clang Docs FAQ (`clang/docs/FAQ.md`)

# Frequently Asked Questions (FAQ)


## Driver

### I run `clang -cc1 ...` and get weird errors about missing headers

Given this source file:

```c
#include <stdio.h>

int main() {
  printf("Hello world\n");
}
```

If you run:

```console
$ clang -cc1 hello.c
hello.c:1:10: fatal error: 'stdio.h' file not found
#include <stdio.h>
         ^
1 error generated.
```

`clang -cc1` is the frontend, `clang` is the {doc}`driver
<DriverInternals>`. The driver invokes the frontend with options appropriate
for your system. To see these options, run:

```console
$ clang -### -c hello.c
```

Some clang command line options are driver-only options, some are frontend-only
options. Frontend-only options are intended to be used only by clang developers.
Users should not run `clang -cc1` directly, because `-cc1` options are not
guaranteed to be stable.

If you want to use a frontend-only option ("a `-cc1` option"), for example
`-ast-dump`, then you need to take the `clang -cc1` line generated by the
driver and add the option you need. Alternatively, you can run
`clang -Xclang <option> ...` to force the driver pass `<option>` to
`clang -cc1`.

### I get errors about some headers being missing (`stddef.h`, `stdarg.h`)

Some header files (`stddef.h`, `stdarg.h`, and others) are shipped with
Clang --- these are called builtin includes. Clang searches for them in a
directory relative to the location of the `clang` binary. If you moved the
`clang` binary, you need to move the builtin headers, too.

More information can be found in the {ref}`libtooling_builtin_includes`
section.

---

### Clang Docs FunctionEffectAnalysis (`clang/docs/FunctionEffectAnalysis.md`)

# Function Effect Analysis


## Introduction

Clang Function Effect Analysis is a language extension which can warn about "unsafe"
constructs. The feature is currently tailored for the Performance Constraint attributes
`nonblocking` and `nonallocating`; functions with these attributes are verified as not
containing any language constructs or calls to other functions which violate the constraint.
(See {doc}`AttributeReference`.)

## The `nonblocking` and `nonallocating` attributes

### Attribute syntax

The `nonblocking` and `nonallocating` attributes apply to function types, allowing them to be
attached to functions, blocks, function pointers, lambdas, and member functions.

```c++
// Functions
void nonblockingFunction() [[clang::nonblocking]];
void nonallocatingFunction() [[clang::nonallocating]];

// Function pointers
void (*nonblockingFunctionPtr)() [[clang::nonblocking]];

// Typedefs, type aliases.
typedef void (*NBFunctionPtrTypedef)() [[clang::nonblocking]];
using NBFunctionPtrTypeAlias_gnu = __attribute__((nonblocking)) void (*)();
using NBFunctionPtrTypeAlias_std = void (*)() [[clang::nonblocking]];

// C++ methods
struct Struct {
  void NBMethod() [[clang::nonblocking]];
};

// C++ lambdas
auto nbLambda = []() [[clang::nonblocking]] {};

// Blocks
void (^nbBlock)() = ^() [[clang::nonblocking]] {};
```

The attribute applies only to the function itself. In particular, it does not apply to any nested
functions or declarations, such as blocks, lambdas, and local classes.

This document uses the C++/C23 syntax `[[clang::nonblocking]]`, since it parallels the placement
of the `noexcept` specifier, and the attributes have other similarities to `noexcept`. The GNU
`__attribute__((nonblocking))` syntax is also supported. Note that it requires a different
placement on a C++ type alias.

Like `noexcept`, `nonblocking` and `nonallocating` have an optional argument, a compile-time
constant boolean expression. By default, the argument is `true`, so `[[clang::nonblocking]]`
is equivalent to `[[clang::nonblocking(true)]]`, and declares the function type as never blocking.

### Attribute semantics

Together with `noexcept`, the `nonallocating` and `nonblocking` attributes define an ordered
series of performance constraints. From weakest to strongest:

- `noexcept` (as per the C++ standard): The function type will never throw an exception.
- `nonallocating`: The function type will never allocate memory on the heap or throw an
  exception.
- `nonblocking`: The function type will never block on a lock, allocate memory on the heap,
  or throw an exception.

`nonblocking` includes the `nonallocating` guarantee.

While `nonblocking` and `nonallocating` are conceptually a superset of `noexcept`, neither
attribute implicitly specifies `noexcept`. Further, `noexcept` has a specified runtime behavior of
aborting if an exception is thrown, while the `nonallocating` and `nonblocking` attributes are
mainly for compile-time analysis and have no runtime behavior, except in code built
with Clang's {doc}`RealtimeSanitizer`. Nonetheless, Clang emits a
warning if, in C++, a function is declared `nonblocking` or `nonallocating` without
`noexcept`. This diagnostic is controlled by `-Wperf-constraint-implies-noexcept`.

`nonblocking(true)` and `nonallocating(true)` apply to function *types*, and by extension, to
function-like declarations. When applied to a declaration with a body, the compiler verifies the
function, as described in the section "Analysis and warnings", below.

`blocking` and `allocating` are synonyms for `nonblocking(false)` and
`nonallocating(false)`, respectively. They can be used on a function-like declaration to
explicitly disable any potential inference of `nonblocking` or `nonallocating` during
verification. (Inference is described later in this document). `nonblocking(false)` and
`nonallocating(false)` are legal, but superfluous when applied to a function *type*
that is not part of a declarator: `float (int) [[nonblocking(false)]]` and
`float (int)` are identical types.

For functions with no explicit performance constraint, the worst is assumed: the function
allocates memory and potentially blocks, unless it can be inferred otherwise. This is detailed in the
discussion of verification.

The following example describes the meanings of all permutations of the two attributes and arguments:

```c++
void nb1_na1() [[clang::nonblocking(true)]] [[clang::nonallocating(true)]];
// Valid; nonallocating(true) is superfluous but doesn't contradict the guarantee.

void nb1_na0() [[clang::nonblocking(true)]] [[clang::nonallocating(false)]];
// error: 'allocating' and 'nonblocking' attributes are not compatible

void nb0_na1() [[clang::nonblocking(false)]] [[clang::nonallocating(true)]];
// Valid; the function does not allocate memory, but may lock for other reasons.

void nb0_na0() [[clang::nonblocking(false)]] [[clang::nonallocating(false)]];
// Valid.
```

### Type conversions

A performance constraint can be removed or weakened via an implicit conversion. An attempt to add
or strengthen a performance constraint is unsafe and results in a warning. The rules for this
are comparable to that for `noexcept` in C++17 and later.

```c++
void unannotated();
void nonblocking() [[clang::nonblocking]];
void nonallocating() [[clang::nonallocating]];

void example()
{
  // It's fine to remove a performance constraint.
  void (*fp_plain)();
  fp_plain = unannotated;
  fp_plain = nonblocking;
  fp_plain = nonallocating;

  // Adding/spoofing nonblocking is unsafe.
  void (*fp_nonblocking)() [[clang::nonblocking]];
  fp_nonblocking = nullptr;
  fp_nonblocking = nonblocking;
  fp_nonblocking = unannotated;
  // ^ warning: attribute 'nonblocking' should not be added via type conversion
  fp_nonblocking = nonallocating;
  // ^ warning: attribute 'nonblocking' should not be added via type conversion

  // Adding/spoofing nonallocating is unsafe.
  void (*fp_nonallocating)() [[clang::nonallocating]];
  fp_nonallocating = nullptr;
  fp_nonallocating = nonallocating;
  fp_nonallocating = nonblocking; // no warning because nonblocking includes nonallocating
  fp_nonallocating = unannotated;
  // ^ warning: attribute 'nonallocating' should not be added via type conversion
}
```

### Virtual methods

In C++, when a virtual method has a performance constraint, overriding methods in
subclasses inherit the constraint.

```c++
struct Base {
  virtual void unsafe();
  virtual void safe() noexcept [[clang::nonblocking]];
};

struct Derived : public Base {
  void unsafe() [[clang::nonblocking]] override;
  // It's okay for an overridden method to be more constrained

  void safe() noexcept override;
  // This method is implicitly declared `nonblocking`, inherited from Base.
};
```

### Redeclarations, overloads, and name mangling

The `nonblocking` and `nonallocating` attributes, like `noexcept`, do not factor into
argument-dependent lookup and overloaded functions/methods.

First, consider that `noexcept` is integral to a function's type:

```c++
void f1(int);
void f1(int) noexcept;
// error: exception specification in declaration does not match previous
//   declaration
```

Unlike `noexcept`, a redeclaration of `f2` with an added or stronger performance constraint is
legal and propagates the attribute to the previous declaration:

```c++
int f2();
int f2() [[clang::nonblocking]]; // redeclaration with stronger constraint is OK.
```

This greatly eases adoption by making it possible to annotate functions in external libraries
without modifying library headers.

A redeclaration with a removed or weaker performance constraint produces a warning, paralleling
the behavior of `noexcept`:

```c++
int f2() { return 42; }
// warning: attribute 'nonblocking' on function does not match previous declaration
```

In C++14, the following two declarations of `f3` are identical (a single function). In C++17 they
are separate overloads:

```c++
void f3(void (*)());
void f3(void (*)() noexcept);
```

Similarly, the following two declarations of `f4` are separate overloads. This pattern may pose
difficulties due to ambiguity:

```c++
void f4(void (*)());
void f4(void (*)() [[clang::nonblocking]]);
```

The attributes have no effect on the mangling of function and method names.

### Objective-C

The attributes are currently unsupported on Objective-C methods.

## Analysis and warnings

### Constraints

Functions declared `nonallocating` or `nonblocking`, when defined, are verified according to the
following rules. Such functions:

1. May not allocate or deallocate memory on the heap. The analysis follows the calls to
   `operator new` and `operator delete` generated by the `new` and `delete` keywords, and
   treats them like any other function call. The global `operator new` and `operator delete`
   aren't declared `nonblocking` or `nonallocating` and so they are considered unsafe. (This
   is correct because most memory allocators are not lock-free. Note that the placement form of
   `operator new` is implemented inline in libc++'s `<new>` header, and is verifiably
   `nonblocking`, since it merely casts the supplied pointer to the result type.)
2. May not throw or catch exceptions. To throw, the compiler must allocate the exception on the
   heap. (Also, many subclasses of `std::exception` allocate a string). Exceptions are
   deallocated when caught.
3. May not make any indirect function call, via a virtual method, function pointer, or
   pointer-to-member function, unless the target is explicitly declared with the same
   `nonblocking` or `nonallocating` attribute (or stronger).
4. May not make direct calls to any other function, with the following exceptions:

   ```{eval-rst}
   a. The callee is also explicitly declared with the same ``nonblocking`` or ``nonallocating``
      attribute (or stronger).
   b. The callee is defined in the same translation unit as the caller, does not have the ``false``
      form of the required attribute, and can be verified to have the same attribute or stronger,
      according to these same rules.
   c. The callee is a built-in function that is known not to block or allocate.
   d. The callee is declared ``noreturn`` and, if compiling C++, the callee is also declared
      ``noexcept``. This special case excludes functions such as ``abort()`` and ``std::terminate()``
      from the analysis. (The reason for requiring ``noexcept`` in C++ is that a function declared
      ``noreturn`` could be a wrapper for ``throw``.)
   ```

5. May not invoke or access an Objective-C method or property, since `objc_msgSend()` calls into
   the Objective-C runtime, which may allocate memory or otherwise block.
6. May not access thread-local variables. Typically, thread-local variables are allocated on the
   heap when first accessed.

Functions declared `nonblocking` have an additional constraint:

7. May not declare static local variables (e.g. Meyers singletons). The compiler generates a lock
   protecting the initialization of the variable.

Violations of any of these rules result in warnings, in the `-Wfunction-effects` category:

```c++
void notInline();

void example() [[clang::nonblocking]]
{
  auto* x = new int;
  // warning: function with 'nonblocking' attribute must not allocate or deallocate
  //   memory

  if (x == nullptr) {
    static Logger* logger = createLogger();
    // warning: function with 'nonblocking' attribute must not have static local variables

    throw std::runtime_warning{ "null" };
    // warning: 'nonblocking" function 'example' must not throw exceptions
  }
  notInline();
  // warning: 'function with 'nonblocking' attribute must not call non-'nonblocking' function
  //   'notInline'
  // note (on notInline()): declaration cannot be inferred 'nonblocking' because it has no
  //   definition in this translation unit
}
```

### Inferring `nonblocking` or `nonallocating`

In the absence of a `nonblocking` or `nonallocating` attribute (whether `true` or `false`),
a function that is called from a performance-constrained function may be analyzed to
infer whether it has a desired attribute. This analysis happens when the function is not a virtual
method, and it has a visible definition within the current translation unit (i.e. its body can be
traversed).

```c++
void notInline();
int implicitlySafe() { return 42; }
void implicitlyUnsafe() { notInline(); }

void example() [[clang::nonblocking]]
{
  int x = implicitlySafe(); // OK
  implicitlyUnsafe();
  // warning: function with 'nonblocking' attribute must not call non-'nonblocking' function
  //   'implicitlyUnsafe'
  // note (on implicitlyUnsafe): function cannot be inferred 'nonblocking' because it calls
  //   non-'nonblocking' function 'notInline'
  // note (on notInline()): declaration cannot be inferred 'nonblocking' because it has no
  //   definition in this translation unit
}
```

### Lambdas and blocks

As mentioned earlier, the performance constraint attributes apply only to a single function and not
to any code nested inside it, including blocks, lambdas, and local classes. It is possible for a
nonblocking function to schedule the execution of a blocking lambda on another thread. Similarly, a
blocking function may create a `nonblocking` lambda for use in a realtime context.

Operations which create, destroy, copy, and move lambdas and blocks are analyzed in terms of the
underlying function calls. For example, the creation of a lambda with captures generates a function
call to an anonymous struct's constructor, passing the captures as parameters.

### Implicit function calls in the AST

The `nonblocking` / `nonallocating` analysis occurs at the Sema phase of analysis in Clang.
During Sema, there are some constructs which will eventually become function calls, but do not
appear as function calls in the AST. For example, `auto* foo = new Foo;` becomes a declaration
containing a `CXXNewExpr` which is understood as a function call to the global `operator new`
(in this example), and a `CXXConstructExpr`, which, for analysis purposes, is a function call to
`Foo`'s constructor. Most gaps in the analysis would be due to incomplete knowledge of AST
constructs which become function calls.

### Disabling diagnostics

Function effect diagnostics are controlled by `-Wfunction-effects`.

A construct like this can be used to exempt code from the checks described here:

```c++
#define NONBLOCKING_UNSAFE(...)                                    \
  _Pragma("clang diagnostic push")                                 \
  _Pragma("clang diagnostic ignored \"-Wunknown-warning-option\"") \
  _Pragma("clang diagnostic ignored \"-Wfunction-effects\"")       \
  __VA_ARGS__                                                      \
  _Pragma("clang diagnostic pop")
```

Disabling the diagnostic allows for:

- constructs which do block, but which in practice are used in ways to avoid unbounded blocking,
  e.g. a thread pool with semaphores to coordinate multiple realtime threads;
- using libraries which are safe but not yet annotated;
- incremental adoption in a large codebase.

## Adoption

There are a few common issues that arise when adopting the `nonblocking` and `nonallocating`
attributes.

### C++ exceptions

Exceptions pose a challenge to the adoption of the performance constraints. Common library functions
which throw exceptions include:

| Method                         | Alternative                                                       |
| ------------------------------ | ----------------------------------------------------------------- |
| `std::vector<T>::at()`         | `operator[](size_t)`, after verifying that the index is in range. |
| `std::optional<T>::value()`    | `operator*`, after checking `has_value()` or `operator bool()`.   |
| `std::expected<T, E>::value()` | Same as for `std::optional<T>::value()`.                          |

### `std::function<R(Args...)>`

`std::function<R(Args...)>` is generally incompatible with `nonblocking` and `nonallocating`
code, because a typical implementation may allocate heap memory in the constructor.

Alternatives:

- `std::function_ref` (available in C++26 or as `llvm::function_ref`). This is appropriate and
  optimal when a functor's lifetime does not need to extend past the function that created it.
- `inplace_function` from WG14. This solves the allocation problem by giving the functor wrapper
  a fixed size known at compile time and using an inline buffer.

While these alternatives both address the heap allocation of `std::function`, they are still
obstacles to `nonblocking/nonallocating` verification, for reasons detailed in the next section.

### Interactions with type-erasure techniques

`std::function<R(Args...)>` illustrates a common C++ type-erasure technique. Using template
argument deduction, it decomposes a function type into its return and parameter types. Additional
components of the function type, including `noexcept`, `nonblocking`, `nonallocating`, and any
other attributes, are discarded.

Standard library support for these components of a function type is not immediately forthcoming.

Code can work around this limitation in either of two ways:

1. Avoid abstractions like `std::function` and instead work directly with the original lambda type.
2. Create a specialized alternative, e.g. `nonblocking_function_ref<R(Args...)>` where all function
   pointers used in the implementation and its interface are `nonblocking`.

As an example of the first approach, when using a lambda as a *Callable* template parameter, the
attribute is preserved:

```c++
std::sort(vec.begin(), vec.end(),
  [](const Elem& a, const Elem& b) [[clang::nonblocking]] { return a.mem < b.mem; });
```

Here, the type of the `Compare` template parameter is an anonymous class generated from the
lambda, with an `operator()` method holding the `nonblocking` attribute.

A complication arises when a *Callable* template parameter, instead of being a lambda or class
implementing `operator()`, is a function pointer:

```c++
static bool compare_elems(const Elem& a, const Elem& b) [[clang::nonblocking]] {
  return a.mem < b.mem; };

std::sort(vec.begin(), vec.end(), compare_elems);
```

Here, the type of `compare_elems` is decomposed to `bool(const Elem&, const Elem&)`, without
`nonblocking`, when forming the template parameter. This can be solved using the second approach,
creating a specialized alternative which explicitly requires the attribute. In this case, it's
possible to use a small wrapper to transform the function pointer into a functor:

```c++
template <typename>
class nonblocking_fp;

template <typename R, typename... Args>
class nonblocking_fp<R(Args...)> {
public:
  using impl_t = R (*)(Args...) [[clang::nonblocking]];

private:
  impl_t mImpl{ nullptr_t };
public:
  nonblocking_fp() = default;
  nonblocking_fp(impl_t f) : mImpl{ f } {}

  R operator()(Args... args) const
  {
    return mImpl(std::forward<Args>(args)...);
  }
};

// deduction guide (like std::function's)
template< class R, class... ArgTypes >
nonblocking_fp( R(*)(ArgTypes...) ) -> nonblocking_fp<R(ArgTypes...)>;

// --

// Wrap the function pointer in a functor which preserves nonblocking.
std::sort(vec.begin(), vec.end(), nonblocking_fp{ compare_elems });
```

Now, the `nonblocking` attribute of `compare_elems` is verified when it is converted to a
`nonblocking` function pointer, as the argument to `nonblocking_fp`'s constructor. The template
parameter is the functor class `nonblocking_fp`.

### Static local variables

Static local variables are often used for lazily-constructed globals (Meyers singletons). Beyond the
compiler's use of a lock to ensure thread-safe initialization, it is dangerously easy to
inadvertently trigger initialization, involving heap allocation, from a `nonblocking` or
`nonallocating` context.

Generally, such singletons need to be replaced by globals, and care must be taken to ensure their
initialization before they are used from `nonblocking` or `nonallocating` contexts.

### Annotating libraries

It can be surprising that the analysis does not depend on knowledge of any primitives; it simply
assumes the worst, that all function calls are unsafe unless explicitly marked as safe or able to be
inferred as safe. With `nonblocking`, this appears to suffice for all but the most primitive of
spinlocks.

At least for an operating system's C functions, it is possible to define an override header which
redeclares safe common functions (e.g. `pthread_self()`) with the addition of `nonblocking`.
This may help in adopting the feature incrementally.

It also helps that many of the functions in the standard C libraries (notably `<math.h>`)
are treated as built-in functions by Clang, which the diagnosis understands to be safe.

Much of the C++ standard library consists of inline templated functions which work well with
inference. A small number of primitives may need explicit `nonblocking/nonallocating` attributes.

---

### Clang Docs HIPSupport (`clang/docs/HIPSupport.md`)

```{raw} html
<style type="text/css">
  .none { background-color: #FFCCCC }
  .part { background-color: #FFFF99 }
  .good { background-color: #CCFF99 }
</style>
```

```{role} none
```

```{role} part
```

```{role} good
```


# HIP Support

HIP (Heterogeneous-Compute Interface for Portability) [https://github.com/ROCm/HIP](https://github.com/ROCm/HIP) is
a C++ Runtime API and Kernel Language. It enables developers to create portable applications for
offloading computation to different hardware platforms from a single source code.

## AMD GPU Support

Clang provides HIP support on AMD GPUs via the ROCm platform [https://rocm.docs.amd.com/en/latest/#](https://rocm.docs.amd.com/en/latest/#).
The ROCm runtime forms the base for HIP host APIs, while HIP device APIs are realized through HIP header
files and the ROCm device library. The Clang driver uses the HIPAMD toolchain to compile HIP device code
to AMDGPU ISA via the AMDGPU backend, or SPIR-V via the workflow outlined below.
The compiled code is then bundled and embedded in the host executables.

## Intel GPU Support

Clang provides partial HIP support on Intel GPUs using the CHIP-Star project [https://github.com/CHIP-SPV/chipStar](https://github.com/CHIP-SPV/chipStar).
CHIP-Star implements the HIP runtime over oneAPI Level Zero or OpenCL runtime. The Clang driver uses the HIPSPV
toolchain to compile HIP device code into LLVM IR, which is subsequently translated to SPIR-V via the SPIR-V
backend or the out-of-tree LLVM-SPIRV translator. The SPIR-V is then bundled and embedded into the host executables.

:::{note}
While Clang does not directly provide HIP support for NVIDIA GPUs and CPUs, these platforms are supported via other means:

- NVIDIA GPUs: HIP support is offered through the HIP project [https://github.com/ROCm/HIP](https://github.com/ROCm/HIP), which provides a header-only library for translating HIP runtime APIs into CUDA runtime APIs. The code is subsequently compiled using NVIDIA's `nvcc`.
- CPUs: HIP support is available through the HIP-CPU runtime library [https://github.com/ROCm/HIP-CPU](https://github.com/ROCm/HIP-CPU). This header-only library enables CPUs to execute unmodified HIP code.
:::

## Example Usage

To compile a HIP program, use the following command:

```shell
clang++ -c --offload-arch=gfx906 -xhip sample.cpp -o sample.o
```

The `-xhip` option indicates that the source is a HIP program. If the file has a `.hip` extension,
Clang will automatically recognize it as a HIP program:

```shell
clang++ -c --offload-arch=gfx906 sample.hip -o sample.o
```

To link a HIP program, use this command:

```shell
clang++ --hip-link --offload-arch=gfx906 sample.o -o sample
```

In the above command, the `--hip-link` flag instructs Clang to link the HIP runtime library. However,
the use of this flag is unnecessary if a HIP input file is already present in your program.

For convenience, Clang also supports compiling and linking in a single step:

```shell
clang++ --offload-arch=gfx906 -xhip sample.cpp -o sample
```

In the above commands, `gfx906` is the GPU architecture that the code is being compiled for. The supported GPU
architectures can be found in the [AMDGPU Processor Table](https://llvm.org/docs/AMDGPUUsage.html#processors).
Alternatively, you can use the `amdgpu-arch` tool that comes with Clang to list the GPU architecture on your system:

```shell
amdgpu-arch
```

You can use `--offload-arch=native` to automatically detect the GPU architectures on your system:

```shell
clang++ --offload-arch=native -xhip sample.cpp -o sample
```

## Path Setting for Dependencies

Compiling a HIP program depends on the HIP runtime and device library. The paths to the HIP runtime and device libraries
can be specified either using compiler options or environment variables. The paths can also be set through the ROCm path
if they follow the ROCm installation directory structure.

### Order of Precedence for HIP Path

1. `--hip-path` compiler option
2. `HIP_PATH` environment variable *(use with caution)*
3. `--rocm-path` compiler option
4. `ROCM_PATH` environment variable *(use with caution)*
5. Default automatic detection (relative to Clang or at the default ROCm installation location)

### Order of Precedence for Device Library Path

1. `--hip-device-lib-path` compiler option
2. `HIP_DEVICE_LIB_PATH` environment variable *(use with caution)*
3. `--rocm-path` compiler option
4. `ROCM_PATH` environment variable *(use with caution)*
5. Default automatic detection (relative to Clang or at the default ROCm installation location)

```{list-table}
:header-rows: 1

* - Compiler Option
  - Environment Variable
  - Description
  - Default Value
* - `--rocm-path=<path>`
  - `ROCM_PATH`
  - Specifies the ROCm installation path.
  - Automatic detection
* - `--hip-path=<path>`
  - `HIP_PATH`
  - Specifies the HIP runtime installation path.
  - Determined by ROCm directory structure
* - `--hip-device-lib-path=<path>`
  - `HIP_DEVICE_LIB_PATH`
  - Specifies the HIP device library installation path.
  - Determined by ROCm directory structure
```

:::{note}
We recommend using the compiler options as the primary method for specifying these paths. While the environment variables `ROCM_PATH`, `HIP_PATH`, and `HIP_DEVICE_LIB_PATH` are supported, their use can lead to implicit dependencies that might cause issues in the long run. Use them with caution.
:::

## Predefined Macros

```
/* Detailed source-code truncated for AI context efficiency. */
```

Note that some architecture specific AMDGPU macros will have default values when
used from the HIP host compilation.

## Compilation Modes

Each HIP source file contains intertwined device and host code. Depending on the chosen compilation mode by the compiler options `-fno-gpu-rdc` and `-fgpu-rdc`, these portions of code are compiled differently.

### Device Code Compilation

**\`\`-fno-gpu-rdc\`\` Mode (default)**:

- Compiles to a self-contained, fully linked offloading device binary for each offloading device architecture.
- Device code within a Translation Unit (TU) cannot call functions located in another TU.

**\`\`-fgpu-rdc\`\` Mode**:

- Compiles to a bitcode for each GPU architecture.
- For each offloading device architecture, the bitcode from different TUs are linked together to create a single offloading device binary.
- Device code in one TU can call functions located in another TU.

### Host Code Compilation

**Both Modes**:

- Compiles to a relocatable object for each TU.
- These relocatable objects are then linked together.
- Host code within a TU can call host functions and launch kernels from another TU.

## HIP Fat Binary Registration and Unregistration

When compiling HIP for AMD GPUs, Clang embeds device code into HIP "fat
binaries" and generates host-side helper functions that register these
fat binaries with the HIP runtime at program start and unregister them at
program exit. In non-RDC mode (`-fno-gpu-rdc`), each compilation unit
typically produces its own HIP fat binary: a container that holds, for every
enabled GPU architecture, a fully linked offloading device image (for example,
a GPU code object) that can be loaded directly by the HIP runtime. In RDC mode
(`-fgpu-rdc`), each compilation unit contributes device code in a relocatable
form (for example, GPU object files or LLVM IR). A later device-link step links
those relocatable inputs into fully linked device images per GPU architecture
and then packages those images into a HIP fat binary container.

Registering a HIP fat binary allows the runtime to discover the kernels and
device variables defined in that container and to associate host-side addresses
and symbols with the corresponding GPU-side entities. For example, when a
host-side kernel launch stub is called, the HIP runtime uses information
established during registration (and the fat binary handle it returned) to
identify which GPU kernel symbol to launch from which device image.

At the LLVM IR level, Clang/LLVM typically create an internal module
constructor (for example `__hip_module_ctor` or a `.hip.fatbin_reg`
function) and add it to `@llvm.global_ctors`. This constructor is called by
the C runtime before `main` and it:

- calls `__hipRegisterFatBinary` with a pointer to an internal wrapper
  object that describes the HIP fat binary;
- stores the returned handle in an internal global variable;
- calls an internal helper such as `__hip_register_globals` to register
  kernels, device variables and other metadata associated with the fat binary;
- registers a corresponding module destructor with `atexit` so it will run
  during program termination and use the stored handle to unregister the fat
  binary from the HIP runtime.

The compiler-generated wrapper object is placed in the `.hipFatBinSegment`
section. Its layout is:

```c++
struct {
  uint32_t magic;
  uint32_t version;
  void *image;
  void *reserved;
};
```

The section is an internal ABI between Clang-generated host objects, the HIP
runtime, and binary tools that need to find HIP fat binaries. Consumers may
walk the raw section contents as a packed array of wrapper records, so compiler
and instrumentation passes must preserve the wrapper object layout in the
section.

The module destructor (for example `__hip_module_dtor` or a
`.hip.fatbin_unreg` function) loads the stored handle, checks that it is
non-null, calls `__hipUnregisterFatBinary` to unregister the fat binary from
the HIP runtime, and then clears the handle. This ensures that the HIP runtime
sees each fat binary registered exactly once and that it is unregistered once
at exit, even when multiple translation units contribute HIP kernels to the
same host program.

These registration/unregistration helpers are implementation details of Clang's
HIP code generation; user code should not call `__hipRegisterFatBinary` or
`__hipUnregisterFatBinary` directly.

### Implications for HIP Application Developers

From the point of view of HIP application code, Clang and the HIP runtime
provide the following guarantees:

- Kernels and device variables defined in HIP code will be registered with the
  HIP runtime before `main` begins execution.
- Fat binaries will be unregistered via an `atexit`-registered module
  destructor after `main` returns (or after `exit` is called).

Beyond these points, the detailed ordering of fat binary registration and
unregistration relative to user-defined global constructors, destructors and
other `atexit` handlers is not specified and should not be relied upon.
Applications should avoid depending on HIP kernels or device variables being
usable from global constructors or destructors, and instead perform HIP
initialization and teardown that touches device state in `main` (or in
functions called from `main`).

### Implications for HIP Runtime Developers

HIP runtime implementations that are linked with Clang-generated host code
must handle registration and unregistration in the presence of uncertain
global ctor/dtor ordering:

- `__hipRegisterFatBinary` must accept a pointer to the compiler-generated
  wrapper object and return an opaque handle that remains valid for as long as
  the fat binary may be used.
- `__hipUnregisterFatBinary` must accept the handle previously returned by
  `__hipRegisterFatBinary` and perform any necessary cleanup. It may be
  called late in process teardown, after other parts of the runtime have
  started shutting down, so it should be robust in the presence of partially
  torn-down state.
- Runtimes should use appropriate synchronization and guards so that fat
  binary registration does not observe uninitialized resources and
  unregistration does not release resources that are still required by other
  runtime components. In particular, registration and unregistration routines
  should be written to be safe under repeated calls and in the presence of
  concurrent or overlapping initialization/teardown logic.

## Syntax Difference with CUDA

Clang's front end, used for both CUDA and HIP programming models, shares the same parsing and semantic analysis mechanisms. This includes the resolution of overloads concerning device and host functions. While there exists a comprehensive documentation on the syntax differences between Clang and NVCC for CUDA at [Dialect Differences Between Clang and NVCC](https://llvm.org/docs/CompileCudaWithLLVM.html#dialect-differences-between-clang-and-nvcc), it is important to note that these differences also apply to HIP code compilation.

### Predefined Macros for Differentiation

To facilitate differentiation between HIP and CUDA code, as well as between device and host compilations within HIP, Clang defines specific macros:

- `__HIP__` : This macro is defined only when compiling HIP code. It can be used to conditionally compile code specific to HIP, enabling developers to write portable code that can be compiled for both CUDA and HIP.
- `__HIP_DEVICE_COMPILE__` : Defined exclusively during HIP device compilation, this macro allows for conditional compilation of device-specific code. It provides a mechanism to segregate device and host code, ensuring that each can be optimized for their respective execution environments.

## Function Pointers Support

Function pointers' support varies with the usage mode in Clang with HIP. The following table provides an overview of the support status across different use-cases and modes.

| Use Case                                 | `-fno-gpu-rdc` Mode (default) | `-fgpu-rdc` Mode |
| ---------------------------------------- | ----------------------------- | ---------------- |
| Defined and used in the same TU          | Supported                     | Supported        |
| Defined in one TU and used in another TU | Not Supported                | Supported        |

In the `-fno-gpu-rdc` mode, the compiler calculates the resource usage of kernels based only on functions present within the same TU. This mode does not support the use of function pointers defined in a different TU due to the possibility of incorrect resource usage calculations, leading to undefined behavior.

On the other hand, the `-fgpu-rdc` mode allows the definition and use of function pointers across different TUs, as resource usage calculations can accommodate functions from disparate TUs.

## Virtual Function Support

In Clang with HIP, support for calling virtual functions of an object in device or host code is contingent on where the object is constructed.

- **Constructed in Device Code**: Virtual functions of an object can be called in device code on a specific offloading device if the object is constructed in device code on an offloading device with the same architecture.
- **Constructed in Host Code**: Virtual functions of an object can be called in host code if the object is constructed in host code.

In other scenarios, calling virtual functions is not allowed.

### Explanation

An object constructed on the device side contains a pointer to the virtual function table on the device side, which is not accessible in host code, and vice versa. Thus, trying to invoke virtual functions from a context different from where the object was constructed will be disallowed because the appropriate virtual table cannot be accessed. The virtual function tables for offloading devices with different architectures are different, therefore trying to invoke virtual functions from an offloading device with a different architecture than where the object is constructed is also disallowed.

### Example Usage

```c++
class Base {
public:
   __device__ virtual void virtualFunction() {
      // Base virtual function implementation
   }
};

class Derived : public Base {
public:
   __device__ void virtualFunction() override {
      // Derived virtual function implementation
   }
};

__global__ void kernel() {
   Derived obj;
   Base* basePtr = &obj;
   basePtr->virtualFunction(); // Allowed since obj is constructed in device code
}
```

## Alias Attribute Support

Clang supports alias attributes in HIP code, allowing creation of alternative names for functions and variables.
: - Aliases work with `__host__`, `__device__`, and `__host__ __device__` functions and variables.
  - The alias attribute uses the syntax `__attribute__((alias("target_name")))`. Both weak and strong aliases are supported.
  - Outside of `extern "C"`, the alias target must use the mangled name of the aliasee
  - The alias is only emitted if the aliasee is emitted on the same side (ie \_\_host\_\_ or \_\_device\_\_), otherwise it is ignored.

### Example Usage

```c++
extern "C" {
  // Host function alias
  int __HostFunc(void) { return 0; }
  int HostFunc(void) __attribute__((weak, alias("__HostFunc")));

  // Device function alias
  __device__ int __DeviceFunc(void) { return 1; }
  __device__ int DeviceFunc(void) __attribute__((weak, alias("__DeviceFunc")));

  // Host-device function alias
  __host__ __device__ int __BothFunc(void) { return 2; }
  __host__ __device__ int BothFunc(void) __attribute__((alias("__BothFunc")));

  // Variable alias
  int __host_var = 3;
  extern int __attribute__((weak, alias("__host_var"))) host_var;
}
// Mangled / overload alias
__host__ __device__ float __Four(float f) { return 2.0f * f; }
__host__ __device__ int Four(void) __attribute__((weak, alias("_Z6__Fourv")));
__host__ __device__ float Four(float f) __attribute__((weak, alias("_Z6__Fourf")));
```

## Managed Variables

Clang currently implements the following diagnostics involving
`__managed__` variables:

- No dynamic initialization. Only constant initialization is permitted:

  ```c++
  struct A {
    int a;
    A() { a = 1; }
  };

  __managed__ A a; // error: dynamic initialization is not supported

  ```

- The address of a managed variable is not a constant expression:

  ```c++
  __managed__ int x;

  void foo() {
    static constexpr auto a = &x; // error: constexpr variable 'a' must be
                                  // initialized by a constant expression
  }
  ```

- Managed variables shall not be used in the initializer of a static/thread-local object,
  because that initialization may run before the HIP runtime has registered the
  managed variable, leaving its address null.
  Clang can diagnose direct uses of a managed variable within an initializer;
  however, it will not follow function calls, constructors,
  destructors, function pointers, or definitions in other translation units,
  i.e. even if a managed variable is used there, an error won't be emitted.
  Accessing a managed variable during static or thread-local initialization or
  destruction is still undefined behavior, even if Clang does not emit a
  diagnostic. Example:

  ```c++
  __managed__ int x;

  int *hostglob = &x;             // error: invalid use of a __managed__ variable

  int *getX() {
    return &x;
  }
  int *p = getX();                // No error emitted.
  ```

A managed variable is accessible from both host and device and its host and
device initializers must be consistent; otherwise the behavior is undefined.
A managed variable is emitted as an undefined global symbol in the device binary
and is registered with the HIP runtime by `__hipRegisterManagedVar` function
call during device module loading. Clang replaces device accesses to
a managed variable with loads from a pointer to a chunk of managed memory
allocated by the HIP runtime.

## C++17 Class Template Argument Deduction (CTAD) Support

Clang supports C++17 Class Template Argument Deduction (CTAD) in both host and
device code for HIP. This allows you to omit template arguments when creating
class template instances, letting the compiler deduce them from constructor
arguments.

```c++
#include <tuple>

__host__ __device__ void func() {
  std::tuple<int, int> t = std::tuple(1, 1);
}
```

In the above example, `std::tuple(1, 1)` automatically deduces the type to be
`std::tuple<int, int>`.

### Deduction Guides

User-defined deduction guides are also supported. Since deduction guides are not
executable code and only participate in type deduction, they semantically behave
as `__host__ __device__`. This ensures they are available for deduction in both
host and device contexts, and CTAD continues to respect any constraints on the
corresponding constructors in the usual C++ way.

```c++
template <typename T>
struct MyType {
  T value;
  __device__ MyType(T v) : value(v) {}
};

MyType(float) -> MyType<double>;

__device__ void deviceFunc() {
  MyType m(1.0f); // Deduces MyType<double>
}
```

:::{note}
Explicit HIP target attributes such as `__host__` or `__device__`
are currently only permitted on deduction guides when both are present
(`__host__ __device__`). This usage is deprecated and will be rejected
in a future version of Clang; prefer omitting HIP target attributes on
deduction guides entirely. Clang treats all deduction guides as if they
were `__host__ __device__`, so `__host__`-only, `__device__`-only,
or `__global__` deduction guides are rejected as ill-formed.
:::

## Host and Device Attributes of Default Destructors

If a default destructor does not have explicit host or device attributes,
clang infers these attributes based on the destructors of its data members
and base classes. If any conflicts are detected among these destructors,
clang diagnoses the issue. Otherwise, clang adds an implicit host or device
attribute according to whether the data members's and base classes's
destructors can execute on the host or device side.

For explicit template classes with virtual destructors, which must be emitted,
the inference adopts a conservative approach. In this case, implicit host or
device attributes from member and base class destructors are ignored. This
precaution is necessary because, although a constexpr destructor carries
implicit host or device attributes, a constexpr function may call a
non-constexpr function, which is by default a host function.

Users can override the inferred host and device attributes of default
destructors by adding explicit host and device attributes to them.

## Deferred Diagnostics

In HIP (and CUDA), a `__host__ __device__` function can be called from both
host and device code. Certain operations may not be valid on one side (e.g.,
calling a host-only function from device code, or referencing a device-only
function from host code). However, a `__host__ __device__` function
containing such operations is only ill-formed if the function is actually
reachable from a caller where the operation cannot be emitted.

Clang handles this through *deferred diagnostics*: errors and warnings in
`__host__ __device__` functions are recorded during parsing but not emitted
immediately. They are only emitted when a function whose linkage guarantees
IR emission (e.g., a kernel, or an externally visible `__host__` or
`__device__` function) directly or indirectly calls the
`__host__ __device__` function containing the invalid operation.

### HD-Promoted Functions

An *HD-promoted function* is a function that is implicitly or explicitly
`__host__ __device__` and is only emitted because a caller requires it —
it does not have standalone linkage that guarantees emission. HD-promoted
functions are the primary source of deferred diagnostics.

Common examples of HD-promoted functions:

- Lambdas without explicit `__host__` or `__device__` attributes
- `inline __host__ __device__` helper functions
- `__host__ __device__` template instantiations

When an HD-promoted function contains operations that are not valid on the
caller's side, clang emits the deferred diagnostics along with notes showing
how the function was reached.

#### Example

```c++
__host__ void host_only();

// This lambda is implicitly __host__ __device__. It is HD-promoted
// when called from a __device__ function.
__device__ auto lambda = [] {
  host_only();  // error: only emitted if lambda is used from device code
};

__device__ void df1() {
  lambda();  // triggers deferred diagnostic for lambda
}

__device__ void df2() {
  lambda();  // same lambda, same error — not duplicated
}
```

Clang emits the error once and lists all device callers:

```text
error: reference to __host__ function 'host_only' in __host__ __device__ function
  note: 'host_only' declared here
  note: called by 'df1'
  note: called by 'df2'
```

#### Call Chain Notes

When an HD-promoted function is reached through a chain of intermediate
functions, clang shows the full call chain. The first note in each chain uses
"called by" and subsequent notes use "which is called by":

```text
error: reference to __host__ function 'host_only' in __host__ __device__ function
  note: called by 'helper1'
  note: which is called by 'device_func1'
  note: called by 'helper2'
  note: which is called by 'device_func2'
```

Each "called by" starts a new chain, and "which is called by" continues it.
This makes it clear which device function ultimately forced the code into
device context.

## C++ Standard Parallelism Offload Support: Compiler And Runtime

## Introduction

This section describes the implementation of support for offloading the
execution of standard C++ algorithms to accelerators that can be targeted via
HIP. Furthermore, it enumerates restrictions on user defined code, as well as
the interactions with runtimes.

## Algorithm Offload: What, Why, Where

C++17 introduced overloads
[for most algorithms in the standard library](https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0024r2.html)
which allow the user to specify a desired
[execution policy](https://en.cppreference.com/w/cpp/algorithm#Execution_policies).
The [parallel_unsequenced_policy](https://en.cppreference.com/w/cpp/algorithm/execution_policy_tag_t)
maps relatively well to the execution model of AMD GPUs. This, coupled with the
the availability and maturity of GPU accelerated algorithm libraries that
implement most / all corresponding algorithms in the standard library
(e.g. [rocThrust](https://github.com/ROCm/rocm-libraries/tree/develop/projects/rocthrust)), makes
it feasible to provide seamless accelerator offload for supported algorithms,
when an accelerated version exists. Thus, it becomes possible to easily access
the computational resources of an AMD accelerator, via a well specified,
familiar, algorithmic interface, without having to delve into low-level hardware
specific details. Putting it all together:

- **What**: standard library algorithms, when invoked with the
  `parallel_unsequenced_policy`
- **Why**: democratise AMDGPU accelerator programming, without loss of user
  familiarity
- **Where**: only AMDGPU accelerators targeted by Clang/LLVM via HIP

## Small Example

Given the following C++ code:

```C++
bool has_the_answer(const std::vector<int>& v) {
  return std::find(std::execution::par_unseq, std::cbegin(v), std::cend(v), 42) != std::cend(v);
}
```

if Clang is invoked with the `--hipstdpar --offload-arch=foo` flags, the call
to `find` will be offloaded to an accelerator that is part of the `foo`
target family. If either `foo` or its runtime environment do not support
transparent on-demand paging (such as e.g. that provided in Linux via
[HMM](https://docs.kernel.org/mm/hmm.html)), it is necessary to also include
the `--hipstdpar-interpose-alloc` flag. If the accelerator specific algorithm
library `foo` uses doesn't have an implementation of a particular algorithm,
execution seamlessly falls back to the host CPU. It is legal to specify multiple
`--offload-arch`s. All the flags we introduce, as well as a thorough view of
various restrictions an their implementations, will be provided below.

## Implementation - General View

We built support for Algorithm Offload support atop the pre-existing HIP
infrastructure. More specifically, when one requests offload via `--hipstdpar`,
compilation is switched to HIP compilation, as if `-x hip` was specified.
Similarly, linking is also switched to HIP linking, as if `--hip-link` was
specified. Note that these are implicit, and one should not assume that any
interop with HIP specific language constructs is available e.g. `__device__`
annotations are neither necessary nor guaranteed to work.

Since there are no language restriction mechanisms in place, it is necessary to
relax HIP language specific semantic checks performed by the FE; they would
identify otherwise valid, offloadable code, as invalid HIP code. Given that we
know that the user intended only for certain algorithms to be offloaded, and
encoded this by specifying the `parallel_unsequenced_policy`, we rely on a
pass over IR to clean up any and all code that was not "meant" for offload. If
requested, allocation interposition is also handled via a separate pass over IR.

To interface with the client HIP runtime, and to forward offloaded algorithm
invocations to the corresponding accelerator specific library implementation, an
implementation detail forwarding header is implicitly included by the driver,
when compiling with `--hipstdpar`. In what follows, we will delve into each
component that contributes to implementing Algorithm Offload support.

## Implementation - Driver

We augment the `clang` driver with the following flags:

- `--hipstdpar` enables algorithm offload, which depending on phase, has the
  following effects:

  - when compiling:

    - `-x hip` gets prepended to enable HIP support;
    - the `AMDGPUToolchain` component checks for the `hipstdpar_lib.hpp`
      forwarding header,
      [rocThrust](https://rocm.docs.amd.com/projects/rocThrust/en/latest/) and
      [rocPrim](https://rocm.docs.amd.com/projects/rocPRIM/en/latest/) in
      their canonical locations, which can be overriden via flags found below;
      if all are found, the forwarding header gets implicitly included,
      otherwise an error listing the missing component is generated;
    - the `LangOpts.HIPStdPar` member is set.

  - when linking:

    - `--hip-link` and `-frtlib-add-rpath` gets appended to enable HIP
      support.

- `--hipstdpar-interpose-alloc` enables the interposition of standard
  allocation / deallocation functions with accelerator aware equivalents; the
  `LangOpts.HIPStdParInterposeAlloc` member is set;

- `--hipstdpar-path=` specifies a non-canonical path for the forwarding
  header; it must point to the folder where the header is located and not to the
  header itself;

- `--hipstdpar-thrust-path=` specifies a non-canonical path for
  [rocThrust](https://rocm.docs.amd.com/projects/rocThrust/en/latest/); it
  must point to the folder where the library is installed / built under a
  `/thrust` subfolder;

- `--hipstdpar-prim-path=` specifies a non-canonical path for
  [rocPrim](https://rocm.docs.amd.com/projects/rocPRIM/en/latest/); it must
  point to the folder where the library is installed / built under a
  `/rocprim` subfolder;

The [--offload-arch](https://llvm.org/docs/AMDGPUUsage.html#amdgpu-processors)
flag can be used to specify the accelerator for which offload code is to be
generated.

## Implementation - Front-End

When `LangOpts.HIPStdPar` is set, we relax some of the HIP language specific
`Sema` checks to account for the fact that we want to consume pure unannotated
C++ code:

1. `__device__` / `__host__ __device__` functions (which would originate in
   the accelerator specific algorithm library) are allowed to call implicitly
   `__host__` functions;
2. `__global__` functions (which would originate in the accelerator specific
   algorithm library) are allowed to call implicitly `__host__` functions;
3. resolving `__builtin` availability is deferred, because it is possible that
   a `__builtin` that is unavailable on the target accelerator is not
   reachable from any offloaded algorithm, and thus will be safely removed in
   the middle-end;
4. ASM parsing / checking is deferred, because it is possible that an ASM block
   that e.g. uses some constraints that are incompatible with the target
   accelerator is not reachable from any offloaded algorithm, and thus will be
   safely removed in the middle-end.

`CodeGen` is similarly relaxed, with implicitly `__host__` functions being
emitted as well. Because CUDA device code generation otherwise discards the
exception-handling representation of a C++ `try` statement, HIPStdPar emits an
unsupported-operation marker that is diagnosed later only if the containing
function is reachable from an accelerator kernel.

## Implementation - Middle-End

We add two `opt` passes:

1. `HipStdParAcceleratorCodeSelectionPass`

   - For all kernels in a `Module`, compute reachability, where a function
     `F` is reachable from a kernel `K` if and only if there exists a direct
     call-chain rooted in `F` that includes `K`;
   - Diagnose unsupported constructs, including C++ exception handling, when
     they are reachable from a kernel;
   - Remove all functions that are not reachable from kernels;
   - This pass is only run when compiling for the accelerator.

The first pass assumes that the only code that the user intended to offload was
that which was directly or transitively invocable as part of an algorithm
execution. It also assumes that an accelerator aware algorithm implementation
would rely on accelerator specific special functions (kernels), and that these
effectively constitute the only roots for accelerator execution graphs. Both of
these assumptions are based on observing how widespread accelerators,
such as GPUs, work.

1. `HipStdParAllocationInterpositionPass`

   - Iterate through all functions in a `Module`, and replace standard
     allocation / deallocation functions with accelerator-aware equivalents,
     based on a pre-established table; the list of functions that can be
     interposed is available
     [here](https://github.com/ROCm/roc-stdpar#allocation--deallocation-interposition-status);
   - This is only run when compiling for the host.

The second pass is optional.

## Implementation - Forwarding Header

The forwarding header implements two pieces of functionality:

1. It forwards algorithms to a target accelerator, which is done by relying on
   C++ language rules around overloading:

   - overloads taking an explicit argument of type
     `parallel_unsequenced_policy` are introduced into the `std` namespace;
   - these will get preferentially selected versus the master template;
   - the body forwards to the equivalent algorithm from the accelerator specific
     library

2. It provides allocation / deallocation functions that are equivalent to the
   standard ones, but obtain memory by invoking
   [hipMallocManaged](https://rocm.docs.amd.com/projects/HIP/en/latest/.doxygen/docBin/html/group___memory_m.html#gab8cfa0e292193fa37e0cc2e4911fa90a)
   and release it via [hipFree](https://rocm.docs.amd.com/projects/HIP/en/latest/.doxygen/docBin/html/group___memory.html#ga740d08da65cae1441ba32f8fedb863d1).

## Predefined Macros

```{list-table}
:header-rows: 1

* - Macro
  - Description
* - `__HIPSTDPAR__`
  - Defined when Clang is compiling code in algorithm offload mode, enabled
    with the `--hipstdpar` compiler option.
* - `__HIPSTDPAR_INTERPOSE_ALLOC__` / `__HIPSTDPAR_INTERPOSE_ALLOC_V1__`
  - Defined only when compiling in algorithm offload mode, when the user
    enables interposition mode with the `--hipstdpar-interpose-alloc` compiler
    option, indicating that all dynamic memory allocation / deallocation
    functions should be replaced with accelerator aware variants.
```

## Restrictions

We define two modes in which runtime execution can occur:

1. **HMM Mode** - this assumes that the
   [HMM](https://docs.kernel.org/mm/hmm.html) subsystem of the Linux kernel
   is used to provide transparent on-demand paging i.e. memory obtained from a
   system / OS allocator such as via a call to `malloc` or `operator new` is
   directly accessible to the accelerator and it follows the C++ memory model;
2. **Interposition Mode** - this is a fallback mode for cases where transparent
   on-demand paging is unavailable (e.g. in the Windows OS), which means that
   memory must be allocated via an accelerator aware mechanism, and system
   allocated memory is inaccessible for the accelerator.

The following restrictions imposed on user code apply to both modes:

1. Pointers to function, and all associated features, such as e.g. dynamic
   polymorphism, cannot be used (directly or transitively) by the user provided
   callable passed to an algorithm invocation;
2. `static` (except for program-wide unique ones) / `thread` storage
   duration variables cannot be used (directly or transitively) in name by the
   user provided callable;
3. User code must be compiled in `-fgpu-rdc` mode in order for global /
   namespace scope variables / program-wide unique `static` storage duration
   variables to be usable in name by the user provided callable;
4. Only algorithms that are invoked with the `parallel_unsequenced_policy` are
   candidates for offload;
5. Only algorithms that are invoked with iterator arguments that model
   [random_access_iterator](https://en.cppreference.com/w/cpp/iterator/random_access_iterator)
   are candidates for offload;
6. [Exceptions](https://en.cppreference.com/w/cpp/language/exceptions) cannot
   be used by the user provided callable;
7. Dynamic memory allocation (e.g. `operator new`) cannot be used by the user
   provided callable;
8. Selective offload is not possible i.e. it is not possible to indicate that
   only some algorithms invoked with the `parallel_unsequenced_policy` are to
   be executed on the accelerator.

In addition to the above, using **Interposition Mode** imposes the following
additional restrictions:

1. All code that is expected to interoperate has to be recompiled with the
   `--hipstdpar-interpose-alloc` flag i.e. it is not safe to compose libraries
   that have been independently compiled;

## Current Support

At the moment, C++ Standard Parallelism Offload is only available for AMD GPUs,
when the [ROCm](https://rocm.docs.amd.com/en/latest/) stack is used, on the
Linux operating system. Support is synthesised in the following table:

| [Processor](https://llvm.org/docs/AMDGPUUsage.html#amdgpu-processors) | HMM Mode | Interposition Mode |
| ---------------------------------------------------------------------- | -------- | ------------------ |
| GCN GFX9 (Vega)                                                        | YES      | YES                |
| GCN GFX10.1 (RDNA 1)                                                   | *NO*     | YES                |
| GCN GFX10.3 (RDNA 2)                                                   | *NO*     | YES                |
| GCN GFX11 (RDNA 3)                                                     | *NO*     | YES                |
| GCN GFX12 (RDNA 4)                                                     | *NO*     | YES                |

The minimum Linux kernel version for running in HMM mode is 6.4.

The forwarding header is packaged by
[ROCm](https://rocm.docs.amd.com/en/latest/), and is obtainable by installing
the `hipstdpar` packege. The list algorithms that can be offloaded is available
[here](https://github.com/ROCm/roc-stdpar#algorithm-support-status). More
details are available via the dedicated blog
[https://rocm.blogs.amd.com/software-tools-optimization/hipstdpar/README.html](https://rocm.blogs.amd.com/software-tools-optimization/hipstdpar/README.html).

### HIP Specific Elements

1. There is no defined interop with the
   [HIP kernel language](https://rocm.docs.amd.com/projects/HIP/en/latest/reference/kernel_language.html);
   whilst things like using `__device__` annotations might accidentally "work",
   they are not guaranteed to, and thus cannot be relied upon by user code;

   - A consequence of the above is that both bitcode linking and linking
     relocatable object files will "work", but it is not guaranteed to remain
     working or actively tested at the moment; this restriction might be relaxed
     in the future.

2. Combining explicit HIP, CUDA or OpenMP Offload compilation with
   `--hipstdpar` based offloading is not allowed or supported in any way.

3. There is no way to target different accelerators via a standard algorithm
   invocation ([this might be addressed in future C++ standards](https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2023/p2500r1.html));
   an unsafe (per the point above) way of achieving this is to spawn new threads
   and invoke the [hipSetDevice](https://rocm.docs.amd.com/projects/HIP/en/latest/.doxygen/docBin/html/group___device.html#ga43c1e7f15925eeb762195ccb5e063eae)
   interface e.g.:

   ```c++
   int accelerator_0 = ...;
   int accelerator_1 = ...;

   bool multiple_accelerators(const std::vector<int>& u, const std::vector<int>& v) {
     std::atomic<unsigned int> r{0u};

     thread t0{[&]() {
       hipSetDevice(accelerator_0);

       r += std::count(std::execution::par_unseq, std::cbegin(u), std::cend(u), 42);
     }};
     thread t1{[&]() {
       hitSetDevice(accelerator_1);

       r += std::count(std::execution::par_unseq, std::cbegin(v), std::cend(v), 314152)
     }};

     t0.join();
     t1.join();

     return r;
   }
   ```

   Note that this is a temporary, unsafe workaround for a deficiency in the C++
   Standard.

## Open Questions / Future Developments

1. The restriction on the use of `static` / `thread` storage duration
   variables in offloaded algorithms might be lifted;
2. The restriction on the use of dynamic memory allocation in offloaded
   algorithms will be lifted in the future.
3. The restriction on the use of pointers to function, and associated features
   such as dynamic polymorphism might be lifted in the future, when running in
   **HMM Mode**;
4. Offload support might be extended to cases where the `parallel_policy` is
   used for some or all targets.

## Profile-Guided Optimization for Device Code

Clang supports IR-level profile-guided optimization (PGO) for HIP device
code on AMD GPUs. `-fprofile-generate` instruments both host and
device code; running the instrumented binary writes separate host and
device raw profiles, which are merged independently and consumed by a
second build that passes the appropriate profile to each side.

### Prerequisites

The toolchain must be built with the AMDGPU profile runtime enabled,
which requires building `compiler-rt` for the `amdgcn-amd-amdhsa`
target via the runtimes build. A minimal CMake configuration is:

```console
$ cmake <llvm-project>/llvm \
    -DLLVM_ENABLE_PROJECTS='clang;lld' \
    -DLLVM_ENABLE_RUNTIMES=compiler-rt \
    -DLLVM_RUNTIME_TARGETS='default;amdgcn-amd-amdhsa' \
    -DRUNTIMES_amdgcn-amd-amdhsa_CACHE_FILES=<llvm-project>/compiler-rt/cmake/caches/AMDGPU.cmake \
    -DRUNTIMES_amdgcn-amd-amdhsa_LLVM_ENABLE_RUNTIMES='compiler-rt;libc' \
    -DRUNTIMES_amdgcn-amd-amdhsa_RUNTIMES_USE_LIBC=llvm-libc
```

`COMPILER_RT_BUILD_PROFILE_ROCM` controls building the host-side
ROCm/HIP device profile collection runtime, `clang_rt.profile_rocm`.
It is on by default for normal Linux and Windows compiler-rt builds,
and off for bare-metal profile builds; leave it enabled.
`RUNTIMES_USE_LIBC=llvm-libc` is required so the amdgcn profile
compile picks up LLVM-libc's `-isystem` / `-nostdlibinc` headers.

### Generate phase

The driver forwards `-fprofile-generate` to the device compiler and
links the device profile runtime into the embedded device image.

```console
$ clang++ -x hip demo.hip \
    --offload-arch=gfx1100 --offload-arch=gfx1101 \
    -fprofile-generate=pgo_data \
    -o demo.instr

$ ./demo.instr
```

When the instrumented binary exits, the runtime writes raw profile
files into `pgo_data/`. Host profiles use the standard LLVM profile
filename; device profiles use the same filename with the GPU
architecture name prepended to the basename, so each
`--offload-arch=` value produces its own set of device files. The
usual `LLVM_PROFILE_FILE` substitutions (`%p` for process ID,
`%m` for binary signature, etc.) apply to both, so multi-process
runs do not need a separate device-side naming scheme.

Merge the host profile and each device architecture's profile
separately:

```console
$ llvm-profdata merge -o host.profdata           pgo_data/default_*.profraw
$ llvm-profdata merge -o device.gfx1100.profdata pgo_data/gfx1100*.profraw
$ llvm-profdata merge -o device.gfx1101.profdata pgo_data/gfx1101*.profraw
```

### Use phase

Host and device compilations consume different profiles, and each GPU
architecture consumes its own. `-Xarch_host` selects the host
profile and `-Xarch_<gpu-arch>` selects the per-architecture device
profile:

```console
$ clang++ -x hip demo.hip \
    --offload-arch=gfx1100 --offload-arch=gfx1101 \
    -Xarch_host    -fprofile-use=host.profdata \
    -Xarch_gfx1100 -fprofile-use=device.gfx1100.profdata \
    -Xarch_gfx1101 -fprofile-use=device.gfx1101.profdata \
    -o demo
```

For a single-arch build, `-Xarch_device` is a convenient shorthand
that applies the same profile to every offload architecture:

```console
$ clang++ -x hip demo.hip --offload-arch=gfx1101 \
    -Xarch_host   -fprofile-use=host.profdata \
    -Xarch_device -fprofile-use=device.gfx1101.profdata \
    -o demo
```

### Block uniformity profiles

On AMDGPU targets, device PGO also records a per-block uniformity
signal. For each instrumented block, the profile records whether the
block is usually entered with all lanes in the wave active. During the
use phase, Clang attaches this information to the corresponding IR
terminators as `!block.uniformity.profile` metadata, which lets later
AMDGPU code generation distinguish blocks that are usually uniform from
blocks that are divergent.

No extra driver option is needed; use the same generate, merge, and use
commands shown above. `llvm-profdata show --counts` prints the
uniformity information when it is present:

```text
Block uniformity: [U, U, D, U]
```

`U` means the block was classified as uniform, and `D` means it was
classified as divergent. Profiles produced by older toolchains or by
targets that do not emit this data can still be used for ordinary PGO,
but they do not provide block-uniformity guidance.

### Notes

- The instrumented build is slower than a normal build; only the use
  phase produces the optimized binary intended for deployment.
- Set `LLVM_PROFILE_VERBOSE=1` to print runtime diagnostics for
  profile file creation and device profile collection.

## Source-Based Code Coverage for Device Code

Clang supports source-based code coverage for HIP device code on AMD GPUs.
Device code is instrumented with the same `-fprofile-instr-generate
-fcoverage-mapping` flags used for host code; counters live in the device
binary, are written to a `.profraw` file at process exit, and can be
consumed by `llvm-profdata` and `llvm-cov`.

### Prerequisites

Source-based device coverage relies on the AMDGPU profile runtime, so
the toolchain must be built with the same CMake configuration used for
HIP offload PGO. See the *Prerequisites* subsection under
[Profile-Guided Optimization for Device Code](#profile-guided-optimization-for-device-code).

### Example

Given a HIP program `demo.hip`, the following commands produce an LCOV
report covering device code:

```console
$ clang++ -x hip demo.hip \
    --offload-arch=gfx1101 \
    -fprofile-instr-generate -fcoverage-mapping \
    -o demo

$ llvm-objcopy --dump-section=.hip_fatbin=fatbin.bin demo
$ clang-offload-bundler --type=o --input=fatbin.bin \
    --output=device.gfx1101.o \
    --targets=hip-amdgcn-amd-amdhsa--gfx1101 --unbundle

$ LLVM_PROFILE_FILE="cov.%p.profraw" ./demo
$ llvm-profdata merge -sparse -o cov.profdata cov.*.profraw

$ llvm-cov report device.gfx1101.o -instr-profile=cov.profdata
$ llvm-cov show   device.gfx1101.o -instr-profile=cov.profdata
$ llvm-cov export device.gfx1101.o -instr-profile=cov.profdata \
    -format=lcov > coverage.lcov
```

The device ELF is extracted from the `.hip_fatbin` section of the host
binary and then unbundled with `clang-offload-bundler`. The unbundle
target string uses the bundle ID `hip-amdgcn-amd-amdhsa--<arch>`,
which is the offload kind (`hip`) followed by the standard
four-component target triple (`amdgcn-amd-amdhsa-`, with the empty
environment field giving the trailing dash) and then the target ID
(`<arch>`). See {doc}`ClangOffloadBundler` for the full bundle entry
ID grammar. `llvm-cov` is invoked against the device object because
the coverage mapping for device functions is emitted there.

## SPIR-V Support on HIPAMD ToolChain

The HIPAMD ToolChain supports targeting
[AMDGCN Flavoured SPIR-V](https://llvm.org/docs/SPIRVUsage.html#target-triples).
The support for SPIR-V in the ROCm and HIPAMD ToolChain is under active
development.

### Compilation Process

When compiling HIP programs with the intent of utilizing SPIR-V, the process
diverges from the traditional compilation flow:

#### Using `--offload-arch=amdgcnspirv`

- **Target Triple**: The `--offload-arch=amdgcnspirv` flag instructs the
  compiler to use the target triple `spirv64-amd-amdhsa`. This approach does
  generates generic AMDGCN SPIR-V which retains architecture specific elements
  without hardcoding them, thus allowing for optimal target specific code to be
  generated at run time, when the concrete target is known.
- **SPIR-V emission**: The program is compiled to LLVM Intermediate
  Representation (IR), which is subsequently lowered into SPIR-V via the SPIR-V
  backend.

  :::{note}
  The SPIR-V backend does not currently preserve debug information. Pass
  `-no-use-spirv-backend` on the command line to fall back to the legacy
  translation path, which retains debug information.
  :::
- **Clang Offload Bundler**: The resulting SPIR-V is embedded in the Clang
  offload bundler with the bundle ID `hip-spirv64-amd-amdhsa--amdgcnspirv`.

### Architecture Specific Macros

None of the architecture specific {doc}`AMDGPU macros <AMDGPUSupport>` are
defined when targeting SPIR-V. An alternative, more flexible mechanism to enable
doing per target / per feature code selection will be added in the future.

---

### Clang Docs HardwareAssistedAddressSanitizer (`clang/docs/HardwareAssistedAddressSanitizer.md`)

# Hardware-assisted AddressSanitizer


## Introduction

Hardware-assisted AddressSanitizer (HWASan) is a memory error detector similar
to {doc}`AddressSanitizer`, but based on memory tagging and address tagging
(such as Top-Byte Ignore on AArch64). It provides similar bug detection with
significantly lower memory overhead (~10–20%).

HWASan can detect:

- Out-of-bounds accesses (heap, stack; globals tagging is not supported on all platforms)
- Use-after-free
- Use-after-return and use-after-scope
- Double-free and invalid free

## Supported Platforms

- **Linux AArch64** (kernel 5.4+ with tagged address ABI; globals tagging is not implemented)
- **Android AArch64**
- **Linux RISC-V 64**
- **Linux x86_64** (experimental; requires CPU with Intel LAM and kernel support)

## Usage

Compile and link your program with `-fsanitize=hwaddress`:

```
/* Detailed source-code truncated for AI context efficiency. */
```

## Flags and Options

Runtime flags can be passed using the `HWASAN_OPTIONS` environment variable:

```console
$ HWASAN_OPTIONS="halt_on_error=0" ./a.out
```

To see the full list of available flags, run an instrumented binary with
`HWASAN_OPTIONS="help=1"`.

Flags passed via the `HWASAN_OPTIONS` environment variable take precedence over
compile-time default options.

### Compile-time Default Options

Default options can be specified at compile/link time by defining
the `__hwasan_default_options` function in your source code:

```c++
#include <sanitizer/hwasan_interface.h>

extern "C" const char *__hwasan_default_options() {
  return "halt_on_error=0";
}
```

### Options Evaluation with Integrated Sanitizers

HWASan works together with {doc}`LeakSanitizer` and {doc}`UndefinedBehaviorSanitizer`:

- `__hwasan_default_options()`, `__lsan_default_options()`, and `__ubsan_default_options()`
  are all evaluated independently by their respective runtimes.
- Similarly, `HWASAN_OPTIONS`, `LSAN_OPTIONS`, and `UBSAN_OPTIONS` environment
  variables are parsed separately by their respective runtimes.

## Disabling Instrumentation

Functions can be excluded from instrumentation using:

```c
__attribute__((no_sanitize("hwaddress")))
```

Conditional compilation is supported via `__has_feature(hwaddress_sanitizer)`.

## More Information

For details on the design, algorithm, and implementation of HWASan, see
{doc}`HardwareAssistedAddressSanitizerDesign`.

---

### Clang Docs HardwareAssistedAddressSanitizerDesign (`clang/docs/HardwareAssistedAddressSanitizerDesign.md`)

# Hardware-assisted AddressSanitizer Design Documentation

This page is a design document for
**hardware-assisted AddressSanitizer** (or **HWASan**)
a tool similar to {doc}`AddressSanitizer`,
but based on partial hardware assistance.

## Introduction

{doc}`AddressSanitizer`
tags every 8 bytes of the application memory with a 1 byte tag (using *shadow memory*),
uses *redzones* to find buffer-overflows and
*quarantine* to find use-after-free.
The redzones, the quarantine, and, to a lesser extent, the shadow, are the
sources of AddressSanitizer's memory overhead.
See the [AddressSanitizer paper][addresssanitizer paper] for details.

AArch64 has [Address Tagging][address tagging] (or top-byte-ignore, TBI), a hardware feature that allows
software to use the 8 most significant bits of a 64-bit pointer as
a tag. HWASAN uses [Address Tagging][address tagging]
to implement a memory safety tool, similar to {doc}`AddressSanitizer`,
but with smaller memory overhead and slightly different (mostly better)
accuracy guarantees.

Intel's [Linear Address Masking][linear address masking] (LAM) also provides address tagging for
x86_64, though it is not widely available in hardware yet. For x86_64, HWASAN
has a limited implementation using page aliasing instead.

## Algorithm

- Every heap/stack/global memory object is forcibly aligned by `TG` bytes
  (`TG` is e.g. 16 or 64). We call `TG` the **tagging granularity**.
- For every such object a random `TS`-bit tag `T` is chosen (`TS`, or tag size, is e.g. 4 or 8)
- The pointer to the object is tagged with `T`.
- The memory for the object is also tagged with `T` (using a `TG=>1` shadow memory)
- Every load and store is instrumented to read the memory tag and compare it
  with the pointer tag, exception is raised on tag mismatch.

For a more detailed discussion of this approach see <https://arxiv.org/pdf/1802.09517.pdf>

### Short granules

A short granule is a granule of size between 1 and `TG-1` bytes. The size
of a short granule is stored at the location in shadow memory where the
granule's tag is normally stored, while the granule's actual tag is stored
in the last byte of the granule. This means that in order to verify that a
pointer tag matches a memory tag, HWASAN must check for two possibilities:

- the pointer tag is equal to the memory tag in shadow memory, or
- the shadow memory tag is actually a short granule size, the value being loaded
  is in bounds of the granule and the pointer tag is equal to the last byte of
  the granule.

Pointer tags between 1 to `TG-1` are possible and are as likely as any other
tag. This means that these tags in memory have two interpretations: the full
tag interpretation (where the pointer tag is between 1 and `TG-1` and the
last byte of the granule is ordinary data) and the short tag interpretation
(where the pointer tag is stored in the granule).

When HWASAN detects an error near a memory tag between 1 and `TG-1`, it
will show both the memory tag and the last byte of the granule. Currently,
it is up to the user to disambiguate the two possibilities.

## Instrumentation

### Memory Accesses

In the majority of cases, memory accesses are prefixed with a call to
an outlined instruction sequence that verifies the tags. The code size
and performance overhead of the call is reduced by using a custom calling
convention that

- preserves most registers, and
- is specialized to the register containing the address, and the type and
  size of the memory access.

Currently, the following sequence is used:

```
/* Detailed source-code truncated for AI context efficiency. */
```

### Heap

Tagging the heap memory/pointers is done by `malloc`.
This can be based on any malloc that forces all objects to be TG-aligned.
`free` tags the memory with a different tag.

### Stack

Stack frames are instrumented by aligning all non-promotable allocas
by `TG` and tagging stack memory in function prologue and epilogue.

Tags for different allocas in one function are **not** generated
independently; doing that in a function with `M` allocas would require
maintaining `M` live stack pointers, significantly increasing register
pressure. Instead we generate a single base tag value in the prologue,
and build the tag for alloca number `M` as `ReTag(BaseTag, M)`, where
ReTag can be as simple as exclusive-or with constant `M`.

Stack instrumentation is expected to be a major source of overhead,
but could be optional.

### Globals

Most globals in HWASAN instrumented code are tagged. This is accomplished
using the following mechanisms:

- The address of each global has a static tag associated with it. The first
  defined global in a translation unit has a pseudorandom tag associated
  with it, based on the hash of the file path. Subsequent global tags are
  incremental from the previously-assigned tag.
- The global's tag is added to its symbol address in the object file's symbol
  table. This causes the global's address to be tagged when its address is
  taken.
- When the address of a global is taken directly (i.e. not via the GOT), a special
  instruction sequence needs to be used to add the tag to the address,
  because the tag would otherwise take the address outside of the small code
  model (4GB on AArch64). No changes are required when the address is taken
  via the GOT because the address stored in the GOT will contain the tag.
- An associated `hwasan_globals` section is emitted for each tagged global,
  which indicates the address of the global, its size and its tag. These
  sections are concatenated by the linker into a single `hwasan_globals`
  section that is enumerated by the runtime (via an ELF note) when a binary
  is loaded and the memory is tagged accordingly.

A complete example is given below:

```objdump
// int x = 1; int *f() { return &x; }
// clang -O2 --target=aarch64-linux-android30 -fsanitize=hwaddress -S -o - global.c

[...]
f:
      adrp    x0, :pg_hi21_nc:x            // set bits 12-63 to upper bits of untagged address
      movk    x0, #:prel_g3:x+0x100000000  // set bits 48-63 to tag
      add     x0, x0, :lo12:x              // set bits 0-11 to lower bits of address
      ret

[...]
      .data
.Lx.hwasan:
      .word   1

      .globl  x
      .set x, .Lx.hwasan+0x2d00000000000000

[...]
      .section        .note.hwasan.globals,"aG",@note,hwasan.module_ctor,comdat
.Lhwasan.note:
      .word   8                            // namesz
      .word   8                            // descsz
      .word   3                            // NT_LLVM_HWASAN_GLOBALS
      .asciz  "LLVM\000\000\000"
      .word   __start_hwasan_globals-.Lhwasan.note
      .word   __stop_hwasan_globals-.Lhwasan.note

[...]
      .section        hwasan_globals,"ao",@progbits,.Lx.hwasan,unique,2
.Lx.hwasan.descriptor:
      .word   .Lx.hwasan-.Lx.hwasan.descriptor
      .word   0x2d000004                   // tag = 0x2d, size = 4
```

### Error reporting

Errors are generated by the `HLT` instruction and are handled by a signal handler.

### Attribute

HWASAN uses its own LLVM IR Attribute `sanitize_hwaddress` and a matching
C function attribute. An alternative would be to re-use ASAN's attribute
`sanitize_address`. The reasons to use a separate attribute are:

- Users may need to disable ASAN but not HWASAN, or vise versa,
  because the tools have different trade-offs and compatibility issues.
- LLVM (ideally) does not use flags to decide which pass is being used,
  ASAN or HWASAN are being applied, based on the function attributes.

This does mean that users of HWASAN may need to add the new attribute
to the code that already uses the old attribute.

## Comparison with AddressSanitizer

HWASAN:
: - Is less portable than {doc}`AddressSanitizer`
    as it relies on hardware [Address Tagging][address tagging] (AArch64).
    Address Tagging can be emulated with compiler instrumentation,
    but it will require the instrumentation to remove the tags before
    any load or store, which is infeasible in any realistic environment
    that contains non-instrumented code.
  - May have compatibility problems if the target code uses higher
    pointer bits for other purposes.
  - May require changes in the OS kernels (e.g. Linux seems to dislike
    tagged pointers passed from address space:
    <https://www.kernel.org/doc/Documentation/arm64/tagged-pointers.txt>).
  - **Does not require redzones to detect buffer overflows**,
    but the buffer overflow detection is probabilistic, with roughly
    `1/(2**TS)` chance of missing a bug (6.25% or 0.39% with 4 and 8-bit TS
    respectively).
  - **Does not require quarantine to detect heap-use-after-free,
    or stack-use-after-return**.
    The detection is similarly probabilistic.

The memory overhead of HWASAN is expected to be much smaller
than that of AddressSanitizer:
`1/TG` extra memory for the shadow
and some overhead due to `TG`-aligning all objects.

## Security Considerations

HWASAN is a bug detection tool and its runtime is not meant to be
linked against production executables. While it may be useful for testing,
HWASAN's runtime was not developed with security-sensitive
constraints in mind and may compromise the security of the resulting executable.

## Supported architectures

HWASAN relies on [Address Tagging][address tagging] which is only available on AArch64.
For other 64-bit architectures it is possible to remove the address tags
before every load and store by compiler instrumentation, but this variant
will have limited deployability since not all of the code is
typically instrumented.

On x86_64, HWASAN utilizes page aliasing to place tags in userspace address
bits. Currently only heap tagging is supported. The page aliases rely on
shared memory, which will cause heap memory to be shared between processes if
the application calls `fork()`. Therefore x86_64 is really only safe for
applications that do not fork.

HWASAN does not currently support 32-bit architectures since they do not
support [Address Tagging][address tagging] and the address space is too constrained to easily
implement page aliasing.

## Related Work

- [SPARC ADI][sparc adi] and [Arm MTE][arm mte] implement a similar tool mostly in hardware.
- [Effective and Efficient Memory Protection Using Dynamic Tainting][effective and efficient memory protection using dynamic tainting] discusses
  similar approaches ("lock & key").
- [Watchdog][watchdog] discussed a heavier, but still somewhat similar
  "lock & key" approach.
- *TODO: add more "related work" links. Suggestions are welcome.*

[address tagging]: http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.den0024a/ch12s05s01.html
[addresssanitizer paper]: https://www.usenix.org/system/files/conference/atc12/atc12-final39.pdf
[arm mte]: https://developer.arm.com/documentation/108035/0100/Introduction-to-the-Memory-Tagging-Extension
[effective and efficient memory protection using dynamic tainting]: https://www.cc.gatech.edu/~orso/papers/clause.doudalis.orso.prvulovic.pdf
[linear address masking]: https://software.intel.com/content/www/us/en/develop/download/intel-architecture-instruction-set-extensions-programming-reference.html
[sparc adi]: https://lazytyped.blogspot.com/2017/09/getting-started-with-adi.html
[watchdog]: https://www.cis.upenn.edu/acg/papers/isca12_watchdog.pdf

---

### Clang Docs HowToSetupToolingForLLVM (`clang/docs/HowToSetupToolingForLLVM.md`)

# How To Setup Clang Tooling For LLVM

Clang Tooling provides infrastructure to write tools that need syntactic
and semantic information about a program. This term also relates to a set
of specific tools using this infrastructure (e.g. `clang-check`). This
document provides information on how to set up and use Clang Tooling for
the LLVM source code.

## Introduction

Clang Tooling needs a compilation database to figure out specific build
options for each file. Currently it can create a compilation database
from the `compile_commands.json` file, generated by CMake. When
invoking clang tools, you can either specify a path to a build directory
using a command line parameter `-p` or let Clang Tooling find this
file in your source tree. In either case you need to configure your
build using CMake to use clang tools.

## Setup Clang Tooling Using CMake and Make

If you intend to use make to build LLVM, you should have CMake 2.8.6 or
later installed (can be found [here](https://cmake.org)).

First, you need to generate Makefiles for LLVM with CMake. You need to
make a build directory and run CMake from it:

```console
$ mkdir your/build/directory
$ cd your/build/directory
$ cmake -DCMAKE_EXPORT_COMPILE_COMMANDS=ON path/to/llvm/sources
```

If you want to use clang instead of GCC, you can add
`-DCMAKE_C_COMPILER=/path/to/clang -DCMAKE_CXX_COMPILER=/path/to/clang++`.
You can also use `ccmake`, which provides a curses interface to configure
CMake variables.

As a result, the new `compile_commands.json` file should appear in the
current directory. You should link it to the LLVM source tree so that
Clang Tooling is able to use it:

```console
$ ln -s $PWD/compile_commands.json path/to/llvm/source/
```

Now you are ready to build and test LLVM using make:

```console
$ make check-all
```

## Setup Clang Tooling Using CMake on Windows

For Windows developers, the Visual Studio project generators in CMake do
not support [CMAKE_EXPORT_COMPILE_COMMANDS](https://cmake.org/cmake/help/latest/variable/CMAKE_EXPORT_COMPILE_COMMANDS.html).
However, the Ninja generator does support this variable and can be used
on Windows to generate a suitable `compile_commands.json` that invokes
the MSVC compiler.

First, you will need to install [Ninja]. Once installed, the Ninja
executable will need to be in your search path for CMake to locate it.

Next, assuming you already have Visual Studio installed on your machine, you
need to have the appropriate environment variables configured so that CMake
will locate the MSVC compiler for the Ninja generator. The [documentation](https://docs.microsoft.com/en-us/cpp/build/building-on-the-command-line?view=msvc-170#path_and_environment)
describes the necessary environment variable settings, but the simplest thing
is to use a [developer command-prompt window](https://docs.microsoft.com/en-us/cpp/build/building-on-the-command-line?view=msvc-170#developer_command_prompt_shortcuts)
or call a [developer command file](https://docs.microsoft.com/en-us/cpp/build/building-on-the-command-line?view=msvc-170#developer_command_file_locations)
to set the environment variables appropriately.

Now you can run CMake with the Ninja generator to export a compilation
database:

```console
C:\> mkdir build-ninja
C:\> cd build-ninja
C:\build-ninja> cmake -G Ninja -DCMAKE_EXPORT_COMPILE_COMMANDS=ON path/to/llvm/sources
```

It is best to keep your Visual Studio IDE build folder separate from the
Ninja build folder. This prevents the two build systems from negatively
interacting with each other.

Once the `compile_commands.json` file has been created by Ninja, you can
use that compilation database with Clang Tooling. One caveat is that because
there are indirect settings obtained through the environment variables,
you may need to run any Clang Tooling executables through a command prompt
window created for use with Visual Studio as described above. An
alternative, e.g. for using the Visual Studio debugger on a Clang Tooling
executable, is to ensure that the environment variables are also visible
to the debugger settings. This can be done locally in Visual Studio's
debugger configuration locally or globally by launching the Visual Studio
IDE from a suitable command-prompt window.

## Using Clang Tools

After you completed the previous steps, you are ready to run clang tools. If
you have a recent clang installed, you should have `clang-check` in
`$PATH`. Try to run it on any `.cpp` file inside the LLVM source tree:

```console
$ clang-check tools/clang/lib/Tooling/CompilationDatabase.cpp
```

If you're using vim, it's convenient to have clang-check integrated. Put
this into your `.vimrc`:

```
function! ClangCheckImpl(cmd)
  if &autowrite | wall | endif
  echo "Running " . a:cmd . " ..."
  let l:output = system(a:cmd)
  cexpr l:output
  cwindow
  let w:quickfix_title = a:cmd
  if v:shell_error != 0
    cc
  endif
  let g:clang_check_last_cmd = a:cmd
endfunction

function! ClangCheck()
  let l:filename = expand('%')
  if l:filename =~ '\.\(cpp\|cxx\|cc\|c\)$'
    call ClangCheckImpl("clang-check " . l:filename)
  elseif exists("g:clang_check_last_cmd")
    call ClangCheckImpl(g:clang_check_last_cmd)
  else
    echo "Can't detect file's compilation arguments and no previous clang-check invocation!"
  endif
endfunction

nmap <silent> <F5> :call ClangCheck()<CR><CR>
```

When editing a .cpp/.cxx/.cc/.c file, hit F5 to reparse the file. In
case the current file has a different extension (for example, .h), F5
will re-run the last clang-check invocation made from this vim instance
(if any). The output will go into the error window, which is opened
automatically when clang-check finds errors, and can be re-opened with
`:cope`.

Other `clang-check` options that can be useful when working with clang
AST:

- `-ast-print` --- Build ASTs and then pretty-print them.
- `-ast-dump` --- Build ASTs and then debug dump them.
- `-ast-dump-filter=<string>` --- Use with `-ast-dump` or `-ast-print` to
  dump/print only AST declaration nodes having a certain substring in a
  qualified name. Use `-ast-list` to list all filterable declaration node
  names.
- `-ast-list` --- Build ASTs and print the list of declaration node qualified
  names.

Examples:

```console
$ clang-check tools/clang/tools/clang-check/ClangCheck.cpp -ast-dump -ast-dump-filter ActionFactory::newASTConsumer
Processing: tools/clang/tools/clang-check/ClangCheck.cpp.
Dumping ::ActionFactory::newASTConsumer:
clang::ASTConsumer *newASTConsumer() (CompoundStmt 0x44da290 </home/alexfh/local/llvm/tools/clang/tools/clang-check/ClangCheck.cpp:64:40, line:72:3>
  (IfStmt 0x44d97c8 <line:65:5, line:66:45>
    <<<NULL>>>
      (ImplicitCastExpr 0x44d96d0 <line:65:9> '_Bool' <UserDefinedConversion>
...
$ clang-check tools/clang/tools/clang-check/ClangCheck.cpp -ast-print -ast-dump-filter ActionFactory::newASTConsumer
Processing: tools/clang/tools/clang-check/ClangCheck.cpp.
Printing <anonymous namespace>::ActionFactory::newASTConsumer:
clang::ASTConsumer *newASTConsumer() {
    if (this->ASTList.operator _Bool())
        return clang::CreateASTDeclNodeLister();
    if (this->ASTDump.operator _Bool())
        return clang::CreateASTDumper(nullptr /*Dump to stdout.*/,
                                      this->ASTDumpFilter);
    if (this->ASTPrint.operator _Bool())
        return clang::CreateASTPrinter(&llvm::outs(), this->ASTDumpFilter);
    return new clang::ASTConsumer();
}
```

## Using Ninja Build System

Optionally you can use the [Ninja] build system instead of make. It is
aimed at making your builds faster. Currently this step will require
building Ninja from sources.

To take advantage of using Clang Tools along with Ninja build you need
at least CMake 2.8.9.

Clone the Ninja git repository and build Ninja from sources:

```console
$ git clone git://github.com/martine/ninja.git
$ cd ninja/
$ ./bootstrap.py
```

This will result in a single binary `ninja` in the current directory.
It doesn't require installation and can just be copied to any location
inside `$PATH`, say `/usr/local/bin/`:

```console
$ sudo cp ninja /usr/local/bin/
$ sudo chmod a+rx /usr/local/bin/ninja
```

After doing all of this, you'll need to generate Ninja build files for
LLVM with CMake. You need to make a build directory and run CMake from
it:

```console
$ mkdir your/build/directory
$ cd your/build/directory
$ cmake -G Ninja -DCMAKE_EXPORT_COMPILE_COMMANDS=ON path/to/llvm/sources
```

If you want to use clang instead of GCC, you can add
`-DCMAKE_C_COMPILER=/path/to/clang -DCMAKE_CXX_COMPILER=/path/to/clang++`.
You can also use `ccmake`, which provides a curses interface to configure
CMake variables in an interactive manner.

As a result, the new `compile_commands.json` file should appear in the
current directory. You should link it to the LLVM source tree so that
Clang Tooling is able to use it:

```console
$ ln -s $PWD/compile_commands.json path/to/llvm/source/
```

Now you are ready to build and test LLVM using Ninja:

```console
$ ninja check-all
```

Other target names can be used in the same way as with make.

[ninja]: https://ninja-build.org/

---

### Clang Docs InternalsManual (`clang/docs/InternalsManual.md`)

# "Clang" CFE Internals Manual


## 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 Support Library

The LLVM `libSupport` library provides many underlying libraries and
[data-structures](https://llvm.org/docs/ProgrammersManual.html), including
command line option processing, various containers, and a system abstraction
layer, which is used for file system access.

## 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 Diagnostics Subsystem

The Clang Diagnostics subsystem is an important part of how the compiler
communicates with the human. Diagnostics are the warnings and errors produced
when the code is incorrect or dubious. In Clang, each diagnostic produced has
(at the minimum) a unique ID, an English translation associated with it, a
{ref}`SourceLocation <SourceLocation>` to "put the caret", and a severity
(e.g., `WARNING` or `ERROR`). They can also optionally include a number of
arguments to the diagnostic (which fill in "%0"'s in the string) as well as a
number of source ranges that are related to the diagnostic.

In this section, we'll be giving examples produced by the Clang command line
driver, but diagnostics can be {ref}`rendered in many different ways
<DiagnosticConsumer>` depending on how the `DiagnosticConsumer` interface is
implemented. A representative example of a diagnostic is:

```text
t.c:38:15: error: invalid operands to binary expression ('int *' and '_Complex float')
P = (P-42) + Gamma*4;
    ~~~~~~ ^ ~~~~~~~
```

In this example, you can see the English translation, the severity (error), you
can see the source location (the caret ("`^`") and file/line/column info),
the source ranges "`~~~~`", arguments to the diagnostic ("`int*`" and
"`_Complex float`"). You'll have to believe me that there is a unique ID
backing the diagnostic :).

Getting all of this to happen has several steps and involves many moving
pieces, this section describes them and talks about best practices when adding
a new diagnostic.

#### The `Diagnostic*Kinds.td` files

Diagnostics are created by adding an entry to one of the
`clang/Basic/Diagnostic*Kinds.td` files, depending on what library will be
using it. From this file, {program}`tblgen` generates the unique ID of the
diagnostic, the severity of the diagnostic and the English translation + format
string.

There is little sanity with the naming of the unique ID's right now. Some
start with `err_`, `warn_`, `ext_` to encode the severity into the name.
Since the enum is referenced in the C++ code that produces the diagnostic, it
is somewhat useful for it to be reasonably short.

The severity of the diagnostic comes from the set {`NOTE`, `REMARK`,
`WARNING`,
`EXTENSION`, `EXTWARN`, `ERROR`}. The `ERROR` severity is used for
diagnostics indicating the program is never acceptable under any circumstances.
When an error is emitted, the AST for the input code may not be fully built.
The `EXTENSION` and `EXTWARN` severities are used for extensions to the
language that Clang accepts. This means that Clang fully understands and can
represent them in the AST, but we produce diagnostics to tell the user their
code is non-portable. The difference is that the former are ignored by
default, and the latter warn by default. The `WARNING` severity is used for
constructs that are valid in the currently selected source language but that
are dubious in some way. The `REMARK` severity provides generic information
about the compilation that is not necessarily related to any dubious code. The
`NOTE` level is used to staple more information onto previous diagnostics.

These *severities* are mapped into a smaller set (the `Diagnostic::Level`
enum, {`Ignored`, `Note`, `Remark`, `Warning`, `Error`, `Fatal`}) of
output
*levels* by the diagnostics subsystem based on various configuration options.
Clang internally supports a fully fine-grained mapping mechanism that allows
you to map almost any diagnostic to the output level that you want. The only
diagnostics that cannot be mapped are `NOTE`s, which always follow the
severity of the previously emitted diagnostic and `ERROR`s, which can only
be mapped to `Fatal` (it is not possible to turn an error into a warning, for
example).

Diagnostic mappings are used in many ways. For example, if the user specifies
`-pedantic`, `EXTENSION` maps to `Warning`, if they specify
`-pedantic-errors`, it turns into `Error`. This is used to implement
options like `-Wunused_macros`, `-Wundef`, etc.

Mapping to `Fatal` should only be used for diagnostics that are considered so
severe that error recovery won't be able to recover sensibly from them (thus
spewing a ton of bogus errors). One example of this class of error is failure
to `#include` a file.

##### Extension vs ExtWarn

Deciding whether to use `Extension` or `ExtWarn` can be difficult. 
`ExtWarn` should be used if one of the following applies (or another good reason is stated):
- the extension is likely to be used incorrectly (e.g. `-Wvla`);
- the diagnosed code is likely wrong (e.g. `-Wmain`);
- the extension is likely surprising in some cases (e.g. `SFINAEFailure`);
- the extension is deprecated (e.g. `-Wauto-storage-class`).

`Extension` should be used in all other circumstances.

#### Diagnostic Wording

The wording used for a diagnostic is critical because it is the only way for a
user to know how to correct their code. Use the following suggestions when
wording a diagnostic:

- Diagnostics in Clang do not start with a capital letter and do not end with
  punctuation.

  - This does not apply to proper nouns like `Clang` or `OpenMP`, to
    acronyms like `GCC` or `ARC`, or to language standards like `C23`
    or `C++17`.
  - A trailing question mark is allowed. e.g., `unknown identifier %0; did
    you mean %1?`.

- Appropriately capitalize proper nouns like `Clang`, `OpenCL`, `GCC`,
  `Objective-C`, etc. and language standard versions like `C11` or `C++11`.

- The wording should be succinct. If necessary, use a semicolon to combine
  sentence fragments instead of using complete sentences. e.g., prefer wording
  like `'%0' is deprecated; it will be removed in a future release of Clang`
  over wording like `'%0' is deprecated. It will be removed in a future release
  of Clang`.

- The wording should be actionable and avoid using standards terms or grammar
  productions that a new user would not be familiar with. e.g., prefer wording
  like `missing semicolon` over wording like `syntax error` (which is not
  actionable) or `expected unqualified-id` (which uses standards terminology).

- The wording should clearly explain what is wrong with the code rather than
  restating what the code does. e.g., prefer wording like `type %0 requires a
  value in the range %1 to %2` over wording like `%0 is invalid`.

- The wording should have enough contextual information to help the user
  identify the issue in a complex expression. e.g., prefer wording like
  `both sides of the %0 binary operator are identical` over wording like
  `identical operands to binary operator`.

- Use single quotes to denote syntactic constructs or command line arguments
  named in a diagnostic message. e.g., prefer wording like `'this' pointer
  cannot be null in well-defined C++ code` over wording like `this pointer
  cannot be null in well-defined C++ code`.

- Prefer diagnostic wording without contractions whenever possible. The single
  quote in a contraction can be visually distracting due to its use with
  syntactic constructs, and contractions can be harder to understand for non-
  native English speakers.

#### The Format String

The format string for the diagnostic is very simple, but it has some power. It
takes the form of a string in English with markers that indicate where and how
arguments to the diagnostic are inserted and formatted. For example, here are
some simple format strings:

```c++
"binary integer literals are an extension"
"format string contains '\\0' within the string body"
"more '%%' conversions than data arguments"
"invalid operands to binary expression (%0 and %1)"
"overloaded '%0' must be a %select{unary|binary|unary or binary}2 operator"
     " (has %1 parameter%s1)"
```

These examples show some important points of format strings. You can use any
plain ASCII character in the diagnostic string except "`%`" without a
problem, but these are C strings, so you have to use and be aware of all the C
escape sequences (as in the second example). If you want to produce a "`%`"
in the output, use the "`%%`" escape sequence, like the third diagnostic.
Finally, Clang uses the "`%...[digit]`" sequences to specify where and how
arguments to the diagnostic are formatted.

Arguments to the diagnostic are numbered according to how they are specified by
the C++ code that {ref}`produces them <internals-producing-diag>`, and are
referenced by `%0` .. `%9`. If you have more than 10 arguments to your
diagnostic, you are doing something wrong :). Unlike `printf`, there is no
requirement that arguments to the diagnostic end up in the output in the same
order as they are specified; you could have a format string with "`%1 %0`"
that swaps them, for example. The text in between the percent and digit are
formatting instructions. If there are no instructions, the argument is just
turned into a string and substituted in.

Here are some "best practices" for writing the English format string:

- Keep the string short. It should ideally fit in the 80-column limit of the
  `DiagnosticKinds.td` file. This avoids the diagnostic wrapping when
  printed, and forces you to think about the important point you are conveying
  with the diagnostic.
- Take advantage of location information. The user will be able to see the
  line and location of the caret, so you don't need to tell them that the
  problem is with the 4th argument to the function: just point to it.
- Do not capitalize the diagnostic string, and do not end it with a period.
- If you need to quote something in the diagnostic string, use single quotes.

Diagnostics should never take random English strings as arguments: you
shouldn't use "`you have a problem with %0`" and pass in things like "`your
argument`" or "`your return value`" as arguments. Doing this prevents
{ref}`translating <internals-diag-translation>` the Clang diagnostics to other
languages (because they'll get random English words in their otherwise
localized diagnostic). The exceptions to this are C/C++ language keywords
(e.g., `auto`, `const`, `mutable`, etc) and C/C++ operators (`/=`).
Note that things like "pointer" and "reference" are not keywords. On the other
hand, you *can* include anything that comes from the user's source code,
including variable names, types, labels, etc. The "`select`" format can be
used to achieve this sort of thing in a localizable way, see below.

#### Formatting a Diagnostic Argument

Arguments to diagnostics are fully typed internally and come from a couple of
different classes: integers, types, names, and random strings. Depending on
the class of the argument, it can be optionally formatted in different ways.
This gives the `DiagnosticConsumer` information about what the argument means
without requiring it to use a specific presentation (consider this MVC for
Clang :).

It is really easy to add format specifiers to the Clang diagnostics system, but
they should be discussed before they are added. If you are creating a lot of
repetitive diagnostics and/or have an idea for a useful formatter, please bring
it up on the cfe-dev mailing list.

Here are the different diagnostic argument formats currently supported by
Clang:

**"s" format**

Example:

: `"requires %0 parameter%s0"`

Class:

: Integers

Description:

: This is a simple formatter for integers that is useful when producing English
  diagnostics. When the integer is 1, it prints as nothing. When the integer
  is not 1, it prints as "`s`". This allows some simple grammatical forms to
  be to be handled correctly, and eliminates the need to use gross things like
  `"requires %1 parameter(s)"`. Note, this only handles adding a simple
  "`s`" character, it will not handle situations where pluralization is more
  complicated such as turning `fancy` into `fancies` or `mouse` into
  `mice`. You can use the "plural" format specifier to handle such situations.

**"select" format**

Example:

: `"must be a %select{unary|binary|unary or binary}0 operator"`

Class:

: Integers

Description:

: This format specifier is used to merge multiple related diagnostics together
  into one common one, without requiring the difference to be specified as an
  English string argument. Instead of specifying the string, the diagnostic
  gets an integer argument, and the format string selects the numbered option.
  In this case, the "`%0`" value must be an integer in the range [0..2]. If
  it is 0, it prints "unary", if it is 1 it prints "binary" if it is 2, it
  prints "unary or binary". This allows other language translations to
  substitute reasonable words (or entire phrases) based on the semantics of the
  diagnostic instead of having to do things textually. The selected string
  does undergo formatting.

**"enum_select" format**

Example:

: `unknown frobbling of a %enum_select<FrobbleKind>{%VarDecl{variable declaration}|%FuncDecl{function declaration}}0 when blarging`

Class:

: Integers

Description:

: This format specifier is used exactly like a `select` specifier, except it
  additionally generates a namespace, enumeration, and enumerator list based on
  the format string given. In the above case, a namespace is generated named
  `FrobbleKind` that has an unscoped enumeration with the enumerators
  `VarDecl` and `FuncDecl`, which correspond to the values 0 and 1. This
  permits a clearer use of the `Diag` in source code, as the above could be
  called as: `Diag(Loc, diag::frobble) << diag::FrobbleKind::VarDecl`.

**"plural" format**

Example:

: `"you have %0 %plural{1:mouse|:mice}0 connected to your computer"`

Class:

: Integers

Description:

: This is a formatter for complex plural forms. It is designed to handle even
  the requirements of languages with very complex plural forms, as many Baltic
  languages have. The argument consists of a series of expression/form pairs,
  separated by ":", where the first form whose expression evaluates to true is
  the result of the modifier.

  An expression can be empty, in which case it is always true. See the example
  at the top. Otherwise, it is a series of one or more numeric conditions,
  separated by ",". If any condition matches, the expression matches. Each
  numeric condition can take one of three forms.

  - number: A simple decimal number matches if the argument is the same as the
    number. Example: `"%plural{1:mouse|:mice}0"`
  - range: A range in square brackets matches if the argument is within the
    range. The range is inclusive on both ends. Example:
    `"%plural{0:none|1:one|[2,5]:some|:many}0"`
  - modulo: A modulo operator is followed by a number, and equals sign and
    either a number or a range. The tests are the same as for plain numbers
    and ranges, but the argument is taken modulo the number first. Example:
    `"%plural{%100=0:even hundred|%100=[1,50]:lower half|:everything else}1"`

  The parser is very unforgiving. A syntax error, even whitespace, will abort,
  as will a failure to match the argument against any expression.

**"ordinal" format**

Example:

: `"ambiguity in %ordinal0 argument"`

Class:

: Integers

Description:

: This is a formatter which represents the argument number as an ordinal: the
  value `1` becomes `1st`, `3` becomes `3rd`, and so on. Values less than `1`
  are not supported. This formatter is currently hard-coded to use English
  ordinals.

**"human" format**

Example:

: `"total size is %human0 bytes"`

Class:

: Integers

Description:

: This is a formatter which represents the argument number in a human-readable
  format: the value `123` stays `123`, `12345` becomes `12.34k`,
  `6666666` becomes `6.67M`, and so on for 'G' and 'T'.

**"objcclass" format**

Example:

: `"method %objcclass0 not found"`

Class:

: `DeclarationName`

Description:

: This is a simple formatter that indicates the `DeclarationName` corresponds
  to an Objective-C class method selector. As such, it prints the selector
  with a leading "`+`".

**"objcinstance" format**

Example:

: `"method %objcinstance0 not found"`

Class:

: `DeclarationName`

Description:

: This is a simple formatter that indicates the `DeclarationName` corresponds
  to an Objective-C instance method selector. As such, it prints the selector
  with a leading "`-`".

**"q" format**

Example:

: `"candidate found by name lookup is %q0"`

Class:

: `NamedDecl *`

Description:

: This formatter indicates that the fully-qualified name of the declaration
  should be printed, e.g., "`std::vector`" rather than "`vector`".

**"diff" format**

Example:

: `"no known conversion %diff{from $ to $|from argument type to parameter type}1,2"`

Class:

: `QualType`

Description:

: This formatter takes two `QualType`s and attempts to print a template
  difference between the two. If tree printing is off, the text inside the
  braces before the pipe is printed, with the formatted text replacing the
  `$`. If tree printing is on, the text after the pipe is printed and a type
  tree is printed after the diagnostic message.

**"sub" format**

Example:

: Given the following record definition of type `TextSubstitution`:

  ```text
  def select_ovl_candidate : TextSubstitution<
    "%select{function|constructor}0%select{| template| %2}1">;
  ```

  which can be used as

  ```text
  def note_ovl_candidate : Note<
    "candidate %sub{select_ovl_candidate}3,2,1 not viable">;
  ```

  and will act as if it were written
  `"candidate %select{function|constructor}3%select{| template| %1}2 not viable"`.

Description:

: This format specifier is used to avoid repeating strings verbatim in multiple
  diagnostics. The argument to `%sub` must name a `TextSubstitution` tblgen
  record. The substitution must specify all arguments used by the substitution,
  and the modifier indexes in the substitution are re-numbered accordingly. The
  substituted text must itself be a valid format string before substitution.

**"quoted" format**

Example:

: `"expression %quoted0 evaluates to 0"`

Class:

: `String`

Description:

: This is a simple formatter which adds quotes around the given string.
  This is useful when the argument could be a string in some cases, but
  another class in other cases, and it needs to be quoted consistently.

(internals-producing-diag)=

#### Producing the Diagnostic

Now that you've created the diagnostic in the `Diagnostic*Kinds.td` file, you
need to write the code that detects the condition in question and emits the new
diagnostic. Various components of Clang (e.g., the preprocessor, `Sema`,
etc.) provide a helper function named "`Diag`". It creates a diagnostic and
accepts the arguments, ranges, and other information that goes along with it.

For example, the binary expression error comes from code like this:

```c++
if (various things that are bad)
  Diag(Loc, diag::err_typecheck_invalid_operands)
    << lex->getType() << rex->getType()
    << lex->getSourceRange() << rex->getSourceRange();
```

This shows the use of the `Diag` method: it takes a location (a
{ref}`SourceLocation <SourceLocation>` object) and a diagnostic enum value
(which matches the name from `Diagnostic*Kinds.td`). If the diagnostic takes
arguments, they are specified with the `<<` operator: the first argument
becomes `%0`, the second becomes `%1`, etc. The diagnostic interface
allows you to specify arguments of many different types, including `int` and
`unsigned` for integer arguments, `const char*` and `std::string` for
string arguments, `DeclarationName` and `const IdentifierInfo *` for names,
`QualType` for types, etc. `SourceRange`s are also specified with the
`<<` operator, but do not have a specific ordering requirement.

As you can see, adding and producing a diagnostic is pretty straightforward.
The hard part is deciding exactly what you need to say to help the user,
picking a suitable wording, and providing the information needed to format it
correctly. The good news is that the call site that issues a diagnostic should
be completely independent of how the diagnostic is formatted and in what
language it is rendered.

#### Fix-It Hints

In some cases, the front end emits diagnostics when it is clear that some small
change to the source code would fix the problem. For example, a missing
semicolon at the end of a statement or a use of deprecated syntax that is
easily rewritten into a more modern form. Clang tries very hard to emit the
diagnostic and recover gracefully in these and other cases.

However, for these cases where the fix is obvious, the diagnostic can be
annotated with a hint (referred to as a "fix-it hint") that describes how to
change the code referenced by the diagnostic to fix the problem. For example,
it might add the missing semicolon at the end of the statement or rewrite the
use of a deprecated construct into something more palatable. Here is one such
example from the C++ front end, where we warn about the right-shift operator
changing meaning from C++98 to C++11:

```text
test.cpp:3:7: warning: use of right-shift operator ('>>') in template argument
                       will require parentheses in C++11
A<100 >> 2> *a;
      ^
  (       )
```

Here, the fix-it hint is suggesting that parentheses be added, and showing
exactly where those parentheses would be inserted into the source code. The
fix-it hints themselves describe what changes to make to the source code in an
abstract manner, which the text diagnostic printer renders as a line of
"insertions" below the caret line. {ref}`Other diagnostic clients
<DiagnosticConsumer>` might choose to render the code differently (e.g., as
markup inline) or even give the user the ability to automatically fix the
problem.

Fix-it hints on errors and warnings need to obey these rules:

- Since they are automatically applied if `-Xclang -fixit` is passed to the
  driver, they should only be used when it's very likely they match the user's
  intent.
- Clang must recover from errors as if the fix-it had been applied.
- Fix-it hints on a warning must not change the meaning of the code.
  However, a hint may clarify the meaning as intentional, for example by adding
  parentheses when the precedence of operators isn't obvious.

If a fix-it can't obey these rules, put the fix-it on a note. Fix-its on notes
are not applied automatically.

All fix-it hints are described by the `FixItHint` class, instances of which
should be attached to the diagnostic using the `<<` operator in the same way
that highlighted source ranges and arguments are passed to the diagnostic.
Fix-it hints can be created with one of three constructors:

- `FixItHint::CreateInsertion(Loc, Code)`

  Specifies that the given `Code` (a string) should be inserted before the
  source location `Loc`.

- `FixItHint::CreateRemoval(Range)`

  Specifies that the code in the given source `Range` should be removed.

- `FixItHint::CreateReplacement(Range, Code)`

  Specifies that the code in the given source `Range` should be removed,
  and replaced with the given `Code` string.

(diagnosticconsumer)=

#### The `DiagnosticConsumer` Interface

Once code generates a diagnostic with all of the arguments and the rest of the
relevant information, Clang needs to know what to do with it. As previously
mentioned, the diagnostic machinery goes through some filtering to map a
severity onto a diagnostic level, then (assuming the diagnostic is not mapped
to "`Ignore`") it invokes an object that implements the `DiagnosticConsumer`
interface with the information.

It is possible to implement this interface in many different ways. For
example, the normal Clang `DiagnosticConsumer` (named
`TextDiagnosticPrinter`) turns the arguments into strings (according to the
various formatting rules), prints out the file/line/column information and the
string, then prints out the line of code, the source ranges, and the caret.
However, this behavior isn't required.

Another implementation of the `DiagnosticConsumer` interface is the
`TextDiagnosticBuffer` class, which is used when Clang is in `-verify`
mode. Instead of formatting and printing out the diagnostics, this
implementation just captures and remembers the diagnostics as they fly by.
Then `-verify` compares the list of produced diagnostics to the list of
expected ones. If they disagree, it prints out its own output. Full
documentation for the `-verify` mode can be found at
{ref}`verifying-diagnostics`.

There are many other possible implementations of this interface, and this is
why we prefer diagnostics to pass down rich structured information in
arguments. For example, an HTML output might want declaration names to be
linkified to where they come from in the source. Another example is that a GUI
might let you click on typedefs to expand them. This application would want to
pass significantly more information about types through to the GUI than a
simple flat string. The interface allows this to happen.

(internals-diag-translation)=

#### Adding Translations to Clang

Not possible yet! Diagnostic strings should be written in UTF-8, the client can
translate to the relevant code page if needed. Each translation completely
replaces the format string for the diagnostic.

(sourcelocation)=

(sourcemanager)=

### 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 `#include`s 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: its spelling
location and its expansion 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
expansion point or the location of the `_Pragma` itself).

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 "spelling location" for the token.

### `SourceRange` and `CharSourceRange`

% mostly taken from https://discourse.llvm.org/t/code-ranges-of-tokens-ast-elements/16893/2

Clang represents most source ranges by [first, last], where "first" and "last"
each point to the beginning of their respective tokens. For example, consider
the `SourceRange` of the following statement:

```text
x = foo + bar;
^first    ^last
```

To map from this representation to a character-based representation, the "last"
location needs to be adjusted to point to (or past) the end of that token with
either `Lexer::MeasureTokenLength()` or `Lexer::getLocForEndOfToken()`. For
the rare cases where character-level source ranges information is needed, we use
the `CharSourceRange` class.

## The Driver Library

The clang Driver and library are documented {doc}`here <DriverInternals>`.

## Precompiled Headers

Clang supports precompiled headers ({doc}`PCH <PCHInternals>`), which uses a
serialized representation of Clang's internal data structures, encoded with the
[LLVM bitstream format](https://llvm.org/docs/BitCodeFormat.html).

## The Frontend Library

The Frontend library contains functionality useful for building tools on top of
the Clang libraries, including several methods for outputting diagnostics.

### Compiler Invocation

One of the classes provided by the Frontend library is `CompilerInvocation`,
which holds information that describes the current invocation of the Clang `-cc1`
frontend. The information typically comes from the command line constructed by
the Clang driver or from clients performing custom initialization. The data
structure is split into logical units used by different parts of the compiler,
for example, `PreprocessorOptions`, `LanguageOptions`, or `CodeGenOptions`.

### Command Line Interface

The command line interface of the Clang `-cc1` frontend is defined alongside
the driver options in `clang/Options/Options.td`. The information making up an
option definition includes its prefix and name (for example `-std=`), form and
position of the option value, help text, aliases and more. Each option may
belong to a certain group and can be marked with zero or more flags. Options
accepted by the `-cc1` frontend are marked with the `CC1Option` flag.

### Command Line Parsing

Option definitions are processed by the `-gen-opt-parser-defs` tablegen
backend during early stages of the build. Options are then used for querying an
instance `llvm::opt::ArgList`, a wrapper around the command line arguments.
This is done in the Clang driver to construct individual jobs based on the
driver arguments and also in the `CompilerInvocation::CreateFromArgs` function
that parses the `-cc1` frontend arguments.

### Command Line Generation

Any valid `CompilerInvocation` created from a `-cc1` command line can be
also serialized back into semantically equivalent command line in a
deterministic manner. This enables features such as implicitly discovered,
explicitly built modules.

% TODO: Create and link corresponding section in Modules.md.

### Adding new Command Line Option

When adding a new command line option, the first place of interest is the header
file declaring the corresponding options class (e.g., `CodeGenOptions.h` for
command line option that affects the code generation). Create new member
variable for the option value:

```diff
  class CodeGenOptions : public CodeGenOptionsBase {

+   /// List of dynamic shared object files to be loaded as pass plugins.
+   std::vector<std::string> PassPlugins;

  }
```

Next, declare the command line interface of the option in the tablegen file
`clang/include/clang/Options/Options.td`. This is done by instantiating the
`Option` class (defined in `llvm/include/llvm/Option/OptParser.td`). The
instance is typically created through one of the helper classes that encode the
acceptable ways to specify the option value on the command line:

- `Flag` - the option does not accept any value,
- `Joined` - the value must immediately follow the option name within the same
  argument,
- `Separate` - the value must follow the option name in the next command line
  argument,
- `JoinedOrSeparate` - the value can be specified either as `Joined` or
  `Separate`,
- `CommaJoined` - the values are comma-separated and must immediately follow
  the option name within the same argument (see `Wl,` for an example).

The helper classes take a list of acceptable prefixes of the option (e.g.
`"-"`, `"--"` or `"/"`) and the option name:

```diff
  // Options.td

+ def fpass_plugin_EQ : Joined<["-"], "fpass-plugin=">;
```

Then, specify additional attributes via mix-ins:

- `HelpText` holds the text that will be printed besides the option name when
  the user requests help (e.g., via `clang --help`).
- `Group` specifies the "category" of options this option belongs to. This is
  used by various tools to categorize and sometimes filter options.
- `Flags` may contain "tags" associated with the option. These may affect how
  the option is rendered, or if it's hidden in some contexts.
- `Visibility` should be used to specify the drivers in which a particular
  option would be available. This attribute will impact tool --help
- `Alias` denotes that the option is an alias of another option. This may be
  combined with `AliasArgs` that holds the implied value.

```diff
  // Options.td

  def fpass_plugin_EQ : Joined<["-"], "fpass-plugin=">,
+   Group<f_Group>, Visibility<[ClangOption, CC1Option]>,
+   HelpText<"Load pass plugin from a dynamic shared object file.">;
```

New options are recognized by the `clang` driver mode if `Visibility` is
not specified or contains `ClangOption`. Options intended for `clang -cc1`
must be explicitly marked with the `CC1Option` flag. Flags that specify
`CC1Option` but not `ClangOption` will only be accessible via `-cc1`.
This is similar for other driver modes, such as `clang-cl` or `flang`.

Next, parse (or manufacture) the command line arguments in the Clang driver and
use them to construct the `-cc1` job:

```diff
  void Clang::ConstructJob(const ArgList &Args /*...*/) const {
    ArgStringList CmdArgs;
    // ...

+   for (const Arg *A : Args.filtered(OPT_fpass_plugin_EQ)) {
+     CmdArgs.push_back(Args.MakeArgString(Twine("-fpass-plugin=") + A->getValue()));
+     A->claim();
+   }
  }
```

The last step is implementing the `-cc1` command line argument
parsing/generation that initializes/serializes the option class (in our case,
`CodeGenOptions`) stored within `CompilerInvocation`. This can be done
automatically by using the marshalling annotations on the option definition:

```diff
  // Options.td

  def fpass_plugin_EQ : Joined<["-"], "fpass-plugin=">,
    Group<f_Group>, Flags<[CC1Option]>,
    HelpText<"Load pass plugin from a dynamic shared object file.">,
+   MarshallingInfoStringVector<CodeGenOpts<"PassPlugins">>;
```

Inner workings of the system are introduced in the {ref}`marshalling
infrastructure <OptionMarshalling>` section and the available annotations are
listed {ref}`here <OptionMarshallingAnnotations>`.

In case the marshalling infrastructure does not support the desired semantics,
consider simplifying it to fit the existing model. This makes the command line
more uniform and reduces the amount of custom, manually written code. Remember
that the `-cc1` command line interface is intended only for Clang developers,
meaning it does not need to mirror the driver interface, maintain backward
compatibility or be compatible with GCC.

If the option semantics cannot be encoded via marshalling annotations, you can
resort to parsing/serializing the command line arguments manually:

```diff
  // CompilerInvocation.cpp

  static bool ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args /*...*/) {
    // ...

+   Opts.PassPlugins = Args.getAllArgValues(OPT_fpass_plugin_EQ);
  }

  static void GenerateCodeGenArgs(const CodeGenOptions &Opts,
                                  SmallVectorImpl<const char *> &Args,
                                  CompilerInvocation::StringAllocator SA /*...*/) {
    // ...

+   for (const std::string &PassPlugin : Opts.PassPlugins)
+     GenerateArg(Args, OPT_fpass_plugin_EQ, PassPlugin, SA);
  }
```

Finally, you can specify the argument on the command line:
`clang -fpass-plugin=a -fpass-plugin=b` and use the new member variable as
desired.

```diff
  void EmitAssemblyHelper::EmitAssemblyWithNewPassManager(/*...*/) {
    // ...
+   for (auto &PluginFN : CodeGenOpts.PassPlugins)
+     if (auto PassPlugin = PassPlugin::load(PluginFN))
+        PassPlugin->registerPassBuilderCallbacks(PB);
  }
```

(optionmarshalling)=

### Option Marshalling Infrastructure

The option marshalling infrastructure automates the parsing of the Clang
`-cc1` frontend command line arguments into `CompilerInvocation` and their
generation from `CompilerInvocation`. The system replaces lots of repetitive
C++ code with simple, declarative tablegen annotations and is being used for
the majority of the `-cc1` command line interface. This section provides an
overview of the system.

**Note:** The marshalling infrastructure is not intended for driver-only
options. Only options of the `-cc1` frontend need to be marshalled to/from
`CompilerInvocation` instance.

To read and modify contents of `CompilerInvocation`, the marshalling system
uses key paths, which are declared in two steps. First, a tablegen definition
for the `CompilerInvocation` member is created by inheriting from
`KeyPathAndMacro`:

```text
// Options.td

class LangOpts<string field> : KeyPathAndMacro<"LangOpts->", field, "LANG_"> {}
//                   CompilerInvocation member  ^^^^^^^^^^
//                                    OPTION_WITH_MARSHALLING prefix ^^^^^
```

The first argument to the parent class is the beginning of the key path that
references the `CompilerInvocation` member. This argument ends with `->` if
the member is a pointer type or with `.` if it's a value type. The child class
takes a single parameter `field` that is forwarded as the second argument to
the base class. The child class can then be used like so:
`LangOpts<"IgnoreExceptions">`, constructing a key path to the field
`LangOpts->IgnoreExceptions`. The third argument passed to the parent class is
a string that the tablegen backend uses as a prefix to the
`OPTION_WITH_MARSHALLING` macro. Using the key path as a mix-in on an
`Option` instance instructs the backend to generate the following code:

```c++
// Options.inc

#ifdef LANG_OPTION_WITH_MARSHALLING
LANG_OPTION_WITH_MARSHALLING([...], LangOpts->IgnoreExceptions, [...])
#endif // LANG_OPTION_WITH_MARSHALLING
```

Such definition can be used in the function for parsing and generating
command line:

```
/* Detailed source-code truncated for AI context efficiency. */
```

The `PARSE_OPTION_WITH_MARSHALLING` and `GENERATE_OPTION_WITH_MARSHALLING`
macros are defined in `CompilerInvocation.cpp` and they implement the generic
algorithm for parsing and generating command line arguments.

(optionmarshallingannotations)=

### Option Marshalling Annotations

How does the tablegen backend know what to put in place of `[...]` in the
generated `Options.inc`? This is specified by the `Marshalling` utilities
described below. All of them take a key path argument and possibly other
information required for parsing or generating the command line argument.

**Note:** The marshalling infrastructure is not intended for driver-only
options. Only options of the `-cc1` frontend need to be marshalled to/from a
`CompilerInvocation` instance.

**Positive Flag**

The key path defaults to `false` and is set to `true` when the flag is
present on the command line.

```text
def fignore_exceptions : Flag<["-"], "fignore-exceptions">,
  Visibility<[ClangOption, CC1Option]>,
  MarshallingInfoFlag<LangOpts<"IgnoreExceptions">>;
```

**Negative Flag**

The key path defaults to `true` and is set to `false` when the flag is
present on the command line.

```text
def fno_verbose_asm : Flag<["-"], "fno-verbose-asm">,
  Visibility<[ClangOption, CC1Option]>,
  MarshallingInfoNegativeFlag<CodeGenOpts<"AsmVerbose">>;
```

**Negative and Positive Flag**

The key path defaults to the specified value (`false`, `true` or some
boolean value that's statically unknown in the tablegen file). Then, the key
path is set to the value associated with the flag that appears last on command
line.

```text
defm legacy_pass_manager : BoolOption<"f", "legacy-pass-manager",
  CodeGenOpts<"LegacyPassManager">, DefaultFalse,
  PosFlag<SetTrue, [], [], "Use the legacy pass manager in LLVM">,
  NegFlag<SetFalse, [], [], "Use the new pass manager in LLVM">,
  BothFlags<[], [ClangOption, CC1Option]>>;
```

With most such pairs of flags, the `-cc1` frontend accepts only the flag that
changes the default key path value. The Clang driver is responsible for
accepting both and either forwarding the changing flag or discarding the flag
that would just set the key path to its default.

The first argument to `BoolOption` is a prefix that is used to construct the
full names of both flags. The positive flag would then be named
`flegacy-pass-manager` and the negative `fno-legacy-pass-manager`.
`BoolOption` also implies the `-` prefix for both flags. It's also possible
to use `BoolFOption` that implies the `"f"` prefix and `Group<f_Group>`.
The `PosFlag` and `NegFlag` classes hold the associated boolean value,
arrays of elements passed to the `Flag` and `Visibility` classes and the
help text. The optional `BothFlags` class holds arrays of `Flag` and
`Visibility` elements that are common for both the positive and negative flag
and their common help text suffix.

**String**

The key path defaults to the specified string, or an empty one, if omitted. When
the option appears on the command line, the argument value is simply copied.

```text
def isysroot : JoinedOrSeparate<["-"], "isysroot">,
  Visibility<[ClangOption, CC1Option, FlangOption]>,
  MarshallingInfoString<HeaderSearchOpts<"Sysroot">, [{"/"}]>;
```

**List of Strings**

The key path defaults to an empty `std::vector<std::string>`. Values specified
with each appearance of the option on the command line are appended to the
vector.

```text
def frewrite_map_file : Separate<["-"], "frewrite-map-file">,
  Visibility<[ClangOption, CC1Option]>,
  MarshallingInfoStringVector<CodeGenOpts<"RewriteMapFiles">>;
```

**Integer**

The key path defaults to the specified integer value, or `0` if omitted. When
the option appears on the command line, its value gets parsed by `llvm::APInt`
and the result is assigned to the key path on success.

```text
def mstack_probe_size : Joined<["-"], "mstack-probe-size=">,
  Visibility<[ClangOption, CC1Option]>,
  MarshallingInfoInt<CodeGenOpts<"StackProbeSize">, "4096">;
```

**Enumeration**

The key path defaults to the value specified in `MarshallingInfoEnum` prefixed
by the contents of `NormalizedValuesScope` and `::`. This ensures correct
reference to an enum case is formed even if the enum resides in a different
namespace or is an enum class. If the value present on the command line does not
match any of the comma-separated values from `Values`, an error diagnostic is
issued. Otherwise, the corresponding element from `NormalizedValues` at the
same index is assigned to the key path (also correctly scoped). The number of
comma-separated string values and elements of the array within
`NormalizedValues` must match.

```text
def mthread_model : Separate<["-"], "mthread-model">,
  Visibility<[ClangOption, CC1Option]>,
  Values<"posix,single">, NormalizedValues<["POSIX", "Single"]>,
  NormalizedValuesScope<"LangOptions::ThreadModelKind">,
  MarshallingInfoEnum<LangOpts<"ThreadModel">, "POSIX">;
```

It is also possible to define relationships between options.

**Implication**

The key path defaults to the default value from the primary `Marshalling`
annotation. Then, if any of the elements of `ImpliedByAnyOf` evaluate to true,
the key path value is changed to the specified value or `true` if missing.
Finally, the command line is parsed according to the primary annotation.

```text
def fms_extensions : Flag<["-"], "fms-extensions">,
  Visibility<[ClangOption, CC1Option]>,
  MarshallingInfoFlag<LangOpts<"MicrosoftExt">>,
  ImpliedByAnyOf<[fms_compatibility.KeyPath], "true">;
```

**Condition**

The option is parsed only if the expression in `ShouldParseIf` evaluates to
true.

```text
def fopenmp_enable_irbuilder : Flag<["-"], "fopenmp-enable-irbuilder">,
  Visibility<[ClangOption, CC1Option]>,
  MarshallingInfoFlag<LangOpts<"OpenMPIRBuilder">>,
  ShouldParseIf<fopenmp.KeyPath>;
```

## 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 {ref}`Token <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
{ref}`Lexer <Lexer>` class) and a buffered token stream (provided by the
{ref}`TokenLexer <TokenLexer>` class).

(token)=

### The Token class

The `Token` class is used to represent a single lexed token. Tokens are
intended to be used by the lexer/preprocessor 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 periodically needs to buffer tokens up for tentative parsing and
various pieces of look-ahead. As such, the size of a `Token` matters. On a
32-bit system, `sizeof(Token)` is currently 16 bytes.

Tokens occur in two forms: {ref}`annotation tokens <AnnotationToken>` and
normal tokens. Normal tokens are those returned by the lexer, annotation
tokens represent semantic information and are produced by the parser, replacing
normal tokens in the token stream. Normal 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 normal 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 parser can do this
translation by replacing tokens returned by the preprocessor with "Annotation
Tokens".

(annotationtoken)=

### Annotation Tokens

Annotation tokens are tokens that are synthesized by the parser and injected
into the preprocessor's token stream (replacing existing tokens) to record
semantic information found by the parser. For example, if "`foo`" is found
to be a typedef, the "`foo`" `tok::identifier` token is replaced with an
`tok::annot_typename`. This is useful for a couple of reasons: 1) this makes
it easy to handle qualified type names (e.g., "`foo::bar::baz<42>::t`") in
C++ as a single "token" in the parser. 2) if the parser backtracks, the
reparse does not need to redo semantic analysis to determine whether a token
sequence is a variable, type, template, etc.

Annotation tokens are created by the parser and reinjected into the parser's
token stream (when backtracking is enabled). Because they can only exist in
tokens that the preprocessor-proper is done with, it doesn't need to keep
around flags like "start of line" that the preprocessor uses to do its job.
Additionally, an annotation token may "cover" a sequence of preprocessor tokens
(e.g., "`a::b::c`" is five preprocessor tokens). As such, the valid fields
of an annotation token are different than the fields for a normal token (but
they are multiplexed into the normal `Token` fields):

- **SourceLocation "Location"** --- The `SourceLocation` for the annotation
  token indicates the first token replaced by the annotation token. In the
  example above, it would be the location of the "`a`" identifier.
- **SourceLocation "AnnotationEndLoc"** --- This holds the location of the last
  token replaced with the annotation token. In the example above, it would be
  the location of the "`c`" identifier.
- **void\* "AnnotationValue"** --- This contains an opaque object that the
  parser gets from `Sema`. The parser merely preserves the information for
  `Sema` to later interpret based on the annotation token kind.
- **TokenKind "Kind"** --- This indicates the kind of Annotation token this is.
  See below for the different valid kinds.

Annotation tokens currently come in three kinds:

1. **tok::annot_typename**: This annotation token represents a resolved
   typename token that is potentially qualified. The `AnnotationValue` field
   contains the `QualType` returned by `Sema::getTypeName()`, possibly with
   source location information attached.
2. **tok::annot_cxxscope**: This annotation token represents a C++ scope
   specifier, such as "`A::B::`". This corresponds to the grammar
   productions "*::*" and "*:: [opt] nested-name-specifier*". The
   `AnnotationValue` pointer is a `NestedNameSpecifier *` returned by the
   `Sema::ActOnCXXGlobalScopeSpecifier` and
   `Sema::ActOnCXXNestedNameSpecifier` callbacks.
3. **tok::annot_template_id**: This annotation token represents a C++
   template-id such as "`foo<int, 4>`", where "`foo`" is the name of a
   template. The `AnnotationValue` pointer is a pointer to a `malloc`'d
   `TemplateIdAnnotation` object. Depending on the context, a parsed
   template-id that names a type might become a typename annotation token (if
   all we care about is the named type, e.g., because it occurs in a type
   specifier) or might remain a template-id token (if we want to retain more
   source location information or produce a new type, e.g., in a declaration of
   a class template specialization). template-id annotation tokens that refer
   to a type can be "upgraded" to typename annotation tokens by the parser.

As mentioned above, annotation tokens are not returned by the preprocessor,
they are formed on demand by the parser. This means that the parser has to be
aware of cases where an annotation could occur and form it where appropriate.
This is somewhat similar to how the parser handles Translation Phase 6 of C99:
String Concatenation (see C99 5.1.1.2). In the case of string concatenation,
the preprocessor just returns distinct `tok::string_literal` and
`tok::wide_string_literal` tokens and the parser eats a sequence of them
wherever the grammar indicates that a string literal can occur.

In order to do this, whenever the parser expects a `tok::identifier` or
`tok::coloncolon`, it should call the `TryAnnotateTypeOrScopeToken` or
`TryAnnotateCXXScopeToken` methods to form the annotation token. These
methods will maximally form the specified annotation tokens and replace the
current token with them, if applicable. If the current token is not valid for
an annotation token, it will remain an identifier or "`::`" token.

(lexer)=

### 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 identify 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 EOD 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 {ref}`MultipleIncludeOpt
  <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.

(tokenlexer)=

### The `TokenLexer` class

The `TokenLexer` class is a token provider that returns tokens from a list of
tokens that came from somewhere else. It is 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.

(multipleincludeopt)=

### 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.

(parser)=

## The Parser Library

This library contains a recursive-descent parser that polls tokens from the
preprocessor and notifies a client of the parsing progress.

Historically, the parser used to talk to an abstract `Action` interface that
had virtual methods for parse events, for example `ActOnBinOp()`. When Clang
grew C++ support, the parser stopped supporting general `Action` clients --
it now always talks to the {ref}`Sema library <Sema>`. However, the Parser
still accesses AST objects only through opaque types like `ExprResult` and
`StmtResult`. Only {ref}`Sema <Sema>` looks at the AST node contents of these
wrappers.

(ast)=

## The AST Library

(astphilosophy)=

### Design philosophy

#### Immutability

Clang AST nodes (types, declarations, statements, expressions, and so on) are
generally designed to be immutable once created. This provides a number of key
benefits:

- Canonicalization of the "meaning" of nodes is possible as soon as the nodes
  are created, and is not invalidated by later addition of more information.
  For example, we {ref}`canonicalize types <CanonicalType>`, and use a
  canonicalized representation of expressions when determining whether two
  function template declarations involving dependent expressions declare the
  same entity.
- AST nodes can be reused when they have the same meaning. For example, we
  reuse `Type` nodes when representing the same type (but maintain separate
  `TypeLoc`s for each instance where a type is written), and we reuse
  non-dependent `Stmt` and `Expr` nodes across instantiations of a
  template.
- Serialization and deserialization of the AST to/from AST files is simpler:
  we do not need to track modifications made to AST nodes imported from AST
  files and serialize separate "update records".

There are unfortunately exceptions to this general approach, such as:

- The first declaration of a redeclarable entity maintains a pointer to the
  most recent declaration of that entity, which naturally needs to change as
  more declarations are parsed.
- Name lookup tables in declaration contexts change after the namespace
  declaration is formed.
- We attempt to maintain only a single declaration for an instantiation of a
  template, rather than having distinct declarations for an instantiation of
  the declaration versus the definition, so template instantiation often
  updates parts of existing declarations.
- Some parts of declarations are required to be instantiated separately (this
  includes default arguments and exception specifications), and such
  instantiations update the existing declaration.

These cases tend to be fragile; mutable AST state should be avoided where
possible.

As a consequence of this design principle, we typically do not provide setters
for AST state. (Some are provided for short-term modifications intended to be
used immediately after an AST node is created and before it's "published" as
part of the complete AST, or where language semantics require after-the-fact
updates.)

#### Faithfulness

The AST intends to provide a representation of the program that is faithful to
the original source. We intend for it to be possible to write refactoring tools
using only information stored in, or easily reconstructible from, the Clang AST.
This means that the AST representation should either not desugar source-level
constructs to simpler forms, or -- where made necessary by language semantics
or a clear engineering tradeoff -- should desugar minimally and wrap the result
in a construct representing the original source form.

For example, `CXXForRangeStmt` directly represents the syntactic form of a
range-based for statement but also holds a semantic representation of the
range declaration and iterator declarations. It does not contain a
fully-desugared `ForStmt`, however.

Some AST nodes (for example, `ParenExpr`) represent only syntax, and others
(for example, `ImplicitCastExpr`) represent only semantics, but most nodes
will represent a combination of syntax and associated semantics. Inheritance
is typically used when representing different (but related) syntaxes for nodes
with the same or similar semantics.

(type)=

### The `Type` class and its subclasses

The `Type` class (and its subclasses) is 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 {ref}`QualType <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:

```c++
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:

```text
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 typedefs. 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.

(canonicaltype)=

#### 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`/`dyn_cast` 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 is 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`/`dyn_cast` 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 :).

(qualtype)=

### 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`, plus some
extended qualifiers required by language extensions) separately from the types
themselves. `QualType` is conceptually a pair of "`Type*`" and the bits
for these 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 ({ref}`Type <Type>` does not even
contain qualifiers).

In practice, the two most common type qualifiers (`const` and `restrict`)
are stored in the low bits of the pointer to the `Type` object, together with
a flag indicating whether extended qualifiers are present (which must be
heap-allocated). This means that `QualType` is exactly the same size as a
pointer.

(declarationname)=

### Declaration names

The `DeclarationName` class represents the name of a declaration in Clang.
Declarations in the C family of languages can take several different forms.
Most declarations are named by simple identifiers, e.g., "`f`" and "`x`" in
the function declaration `f(int x)`. In C++, declaration names can also name
class constructors ("`Class`" in `struct Class { Class(); }`), class
destructors ("`~Class`"), overloaded operator names ("`operator+`"), and
conversion functions ("`operator void const *`"). In Objective-C,
declaration names can refer to the names of Objective-C methods, which involve
the method name and the parameters, collectively called a *selector*, e.g.,
"`setWidth:height:`". Since all of these kinds of entities --- variables,
functions, Objective-C methods, C++ constructors, destructors, and operators
--- are represented as subclasses of Clang's common `NamedDecl` class,
`DeclarationName` is designed to efficiently represent any kind of name.

Given a `DeclarationName` `N`, `N.getNameKind()` will produce a value
that describes what kind of name `N` stores. There are 10 options (all of
the names are inside the `DeclarationName` class).

`Identifier`

: The name is a simple identifier. Use `N.getAsIdentifierInfo()` to retrieve
  the corresponding `IdentifierInfo*` pointing to the actual identifier.

`ObjCZeroArgSelector`, `ObjCOneArgSelector`, `ObjCMultiArgSelector`

: The name is an Objective-C selector, which can be retrieved as a `Selector`
  instance via `N.getObjCSelector()`. The three possible name kinds for
  Objective-C reflect an optimization within the `DeclarationName` class:
  both zero- and one-argument selectors are stored as a masked
  `IdentifierInfo` pointer, and therefore require very little space, since
  zero- and one-argument selectors are far more common than multi-argument
  selectors (which use a different structure).

`CXXConstructorName`

: The name is a C++ constructor name. Use `N.getCXXNameType()` to retrieve
  the {ref}`type <QualType>` that this constructor is meant to construct. The
  type is always the canonical type, since all constructors for a given type
  have the same name.

`CXXDestructorName`

: The name is a C++ destructor name. Use `N.getCXXNameType()` to retrieve
  the {ref}`type <QualType>` whose destructor is being named. This type is
  always a canonical type.

`CXXConversionFunctionName`

: The name is a C++ conversion function. Conversion functions are named
  according to the type they convert to, e.g., "`operator void const *`".
  Use `N.getCXXNameType()` to retrieve the type that this conversion function
  converts to. This type is always a canonical type.

`CXXOperatorName`

: The name is a C++ overloaded operator name. Overloaded operators are named
  according to their spelling, e.g., "`operator+`" or "`operator new []`".
  Use `N.getCXXOverloadedOperator()` to retrieve the overloaded operator (a
  value of type `OverloadedOperatorKind`).

`CXXLiteralOperatorName`

: The name is a C++11 user-defined literal operator. User-defined
  Literal operators are named according to the suffix they define,
  e.g., "`_foo`" for "`operator "" _foo`". Use
  `N.getCXXLiteralIdentifier()` to retrieve the corresponding
  `IdentifierInfo*` pointing to the identifier.

`CXXUsingDirective`

: The name is a C++ using directive. Using directives are not really
  NamedDecls, in that they all have the same name, but they are
  implemented as such in order to store them in DeclContext
  effectively.

`DeclarationName`s are cheap to create, copy, and compare. They require
only a single pointer's worth of storage in the common cases (identifiers,
zero- and one-argument Objective-C selectors) and use dense, uniqued storage
for the other kinds of names. Two `DeclarationName`s can be compared for
equality (`==`, `!=`) using a simple bitwise comparison, can be ordered
with `<`, `>`, `<=`, and `>=` (which provide a lexicographical ordering
for normal identifiers but an unspecified ordering for other kinds of names),
and can be placed into LLVM `DenseMap`s and `DenseSet`s.

`DeclarationName` instances can be created in different ways depending on
what kind of name the instance will store. Normal identifiers
(`IdentifierInfo` pointers) and Objective-C selectors (`Selector`) can be
implicitly converted to `DeclarationNames`. Names for C++ constructors,
destructors, conversion functions, and overloaded operators can be retrieved
from the `DeclarationNameTable`, an instance of which is available as
`ASTContext::DeclarationNames`. The member functions `getCXXConstructorName`,
`getCXXDestructorName`, `getCXXConversionFunctionName`, and
`getCXXOperatorName`, respectively, return `DeclarationName` instances for the
four kinds of C++ special function names.

(declcontext)=

### Declaration contexts

Every declaration in a program exists within some *declaration context*, such
as a translation unit, namespace, class, or function. Declaration contexts in
Clang are represented by the `DeclContext` class, from which the various
declaration-context AST nodes (`TranslationUnitDecl`, `NamespaceDecl`,
`RecordDecl`, `FunctionDecl`, etc.) will derive. The `DeclContext` class
provides several facilities common to each declaration context:

Source-centric vs. Semantics-centric View of Declarations

: `DeclContext` provides two views of the declarations stored within a
  declaration context. The source-centric view accurately represents the
  program source code as written, including multiple declarations of entities
  where present (see the section {ref}`Redeclarations and Overloads
  <Redeclarations>`), while the semantics-centric view represents the program
  semantics. The two views are kept synchronized by semantic analysis while
  the ASTs are being constructed.

Storage of declarations within that context

: Every declaration context can contain some number of declarations. For
  example, a C++ class (represented by `RecordDecl`) contains various member
  functions, fields, nested types, and so on. All of these declarations will
  be stored within the `DeclContext`, and one can iterate over the
  declarations via \[`DeclContext::decls_begin()`,
  `DeclContext::decls_end()`). This mechanism provides the source-centric
  view of declarations in the context.

Lookup of declarations within that context

: The `DeclContext` structure provides efficient name lookup for names within
  that declaration context. For example, if `N` is a namespace we can look
  for the name `N::f` using `DeclContext::lookup`. The lookup itself is
  based on a lazily-constructed array (for declaration contexts with a small
  number of declarations) or hash table (for declaration contexts with more
  declarations). The lookup operation provides the semantics-centric view of
  the declarations in the context.

Ownership of declarations

: The `DeclContext` owns all of the declarations that were declared within
  its declaration context, and is responsible for the management of their
  memory as well as their (de-)serialization.

All declarations are stored within a declaration context, and one can query
information about the context in which each declaration lives. One can
retrieve the `DeclContext` that contains a particular `Decl` using
`Decl::getDeclContext`. However, see the section
{ref}`LexicalAndSemanticContexts` for more information about how to interpret
this context information.

(redeclarations)=

#### Redeclarations and Overloads

Within a translation unit, it is common for an entity to be declared several
times. For example, we might declare a function "`f`" and then later
re-declare it as part of an inlined definition:

```c++
void f(int x, int y, int z = 1);

inline void f(int x, int y, int z) { /* ...  */ }
```

The representation of "`f`" differs in the source-centric and
semantics-centric views of a declaration context. In the source-centric view,
all redeclarations will be present, in the order they occurred in the source
code, making this view suitable for clients that wish to see the structure of
the source code. In the semantics-centric view, only the most recent "`f`"
will be found by the lookup, since it effectively replaces the first
declaration of "`f`".

(Note that because `f` can be redeclared at block scope, or in a friend
declaration, etc., it is possible that the declaration of `f` found by name
lookup will not be the most recent one.)

In the semantics-centric view, overloading of functions is represented
explicitly. For example, given two declarations of a function "`g`" that are
overloaded, e.g.,

```c++
void g();
void g(int);
```

the `DeclContext::lookup` operation will return a `DeclContext::lookup_result`
that contains a range of iterators over declarations of "`g`". Clients that
perform semantic analysis on a program that is not concerned with the actual
source code will primarily use this semantics-centric view.

(lexicalandsemanticcontexts)=

#### Lexical and Semantic Contexts

Each declaration has two potentially different declaration contexts: a
*lexical* context, which corresponds to the source-centric view of the
declaration context, and a *semantic* context, which corresponds to the
semantics-centric view. The lexical context is accessible via
`Decl::getLexicalDeclContext` while the semantic context is accessible via
`Decl::getDeclContext`, both of which return `DeclContext` pointers. For
most declarations, the two contexts are identical. For example:

```c++
class X {
public:
  void f(int x);
};
```

Here, the semantic and lexical contexts of `X::f` are the `DeclContext`
associated with the class `X` (itself stored as a `RecordDecl` AST node).
However, we can now define `X::f` out-of-line:

```c++
void X::f(int x = 17) { /* ...  */ }
```

This definition of "`f`" has different lexical and semantic contexts. The
lexical context corresponds to the declaration context in which the actual
declaration occurred in the source code, e.g., the translation unit containing
`X`. Thus, this declaration of `X::f` can be found by traversing the
declarations provided by \[`decls_begin()`, `decls_end()`) in the
translation unit.

The semantic context of `X::f` corresponds to the class `X`, since this
member function is (semantically) a member of `X`. Lookup of the name `f`
into the `DeclContext` associated with `X` will then return the definition
of `X::f` (including information about the default argument).

#### Transparent Declaration Contexts

In C and C++, there are several contexts in which names that are logically
declared inside another declaration will actually "leak" out into the enclosing
scope from the perspective of name lookup. The most obvious instance of this
behavior is in enumeration types, e.g.,

```c++
enum Color {
  Red,
  Green,
  Blue
};
```

Here, `Color` is an enumeration, which is a declaration context that contains
the enumerators `Red`, `Green`, and `Blue`. Thus, traversing the list of
declarations contained in the enumeration `Color` will yield `Red`,
`Green`, and `Blue`. However, outside of the scope of `Color` one can
name the enumerator `Red` without qualifying the name, e.g.,

```c++
Color c = Red;
```

There are other entities in C++ that provide similar behavior. For example,
linkage specifications that use curly braces:

```c++
extern "C" {
  void f(int);
  void g(int);
}
// f and g are visible here
```

For source-level accuracy, we treat the linkage specification and enumeration
type as a declaration context in which its enclosed declarations ("`Red`",
"`Green`", and "`Blue`"; "`f`" and "`g`") are declared. However, these
declarations are visible outside of the scope of the declaration context.

These language features (and several others, described below) have roughly the
same set of requirements: declarations are declared within a particular lexical
context, but the declarations are also found via name lookup in scopes
enclosing the declaration itself. This feature is implemented via
*transparent* declaration contexts (see
`DeclContext::isTransparentContext()`), whose declarations are visible in the
nearest enclosing non-transparent declaration context. This means that the
lexical context of the declaration (e.g., an enumerator) will be the
transparent `DeclContext` itself, as will the semantic context, but the
declaration will be visible in every outer context up to and including the
first non-transparent declaration context (since transparent declaration
contexts can be nested).

The transparent `DeclContext`s are:

- Enumerations (but not C++11 "scoped enumerations"):

  ```c++
  enum Color {
    Red,
    Green,
    Blue
  };
  // Red, Green, and Blue are in scope
  ```

- C++ linkage specifications:

  ```c++
  extern "C" {
    void f(int);
    void g(int);
  }
  // f and g are in scope
  ```

- Anonymous unions and structs:

  ```c++
  struct LookupTable {
    bool IsVector;
    union {
      std::vector<Item> *Vector;
      std::set<Item> *Set;
    };
  };

  LookupTable LT;
  LT.Vector = 0; // Okay: finds Vector inside the unnamed union
  ```

- C++11 inline namespaces:

  ```c++
  namespace mylib {
    inline namespace debug {
      class X;
    }
  }
  mylib::X *xp; // okay: mylib::X refers to mylib::debug::X
  ```

(multideclcontext)=

#### Multiply-Defined Declaration Contexts

C++ namespaces have the interesting property that
the namespace can be defined multiple times, and the declarations provided by
each namespace definition are effectively merged (from the semantic point of
view). For example, the following two code snippets are semantically
indistinguishable:

```c++
// Snippet #1:
namespace N {
  void f();
}
namespace N {
  void f(int);
}

// Snippet #2:
namespace N {
  void f();
  void f(int);
}
```

In Clang's representation, the source-centric view of declaration contexts will
actually have two separate `NamespaceDecl` nodes in Snippet #1, each of which
is a declaration context that contains a single declaration of "`f`".
However, the semantics-centric view provided by name lookup into the namespace
`N` for "`f`" will return a `DeclContext::lookup_result` that contains a
range of iterators over declarations of "`f`".

`DeclContext` manages multiply-defined declaration contexts internally. The
function `DeclContext::getPrimaryContext` retrieves the "primary" context for
a given `DeclContext` instance, which is the `DeclContext` responsible for
maintaining the lookup table used for the semantics-centric view. Given a
`DeclContext`, one can obtain the set of declaration contexts that are
semantically connected to this declaration context, in source order, including
this context (which will be the only result, for non-namespace contexts) via
`DeclContext::collectAllContexts`. Note that these functions are used
internally within the lookup and insertion methods of the `DeclContext`, so
the vast majority of clients can ignore them.

Because the same entity can be defined multiple times in different modules,
it is also possible for there to be multiple definitions of (for instance)
a `CXXRecordDecl`, all of which describe a definition of the same class.
In such a case, only one of those "definitions" is considered by Clang to be
the definition of the class, and the others are treated as non-defining
declarations that happen to also contain member declarations. Corresponding
members in each definition of such multiply-defined classes are identified
either by redeclaration chains (if the members are `Redeclarable`)
or by simply a pointer to the canonical declaration (if the declarations
are not `Redeclarable` -- in that case, a `Mergeable` base class is used
instead).

### Error Handling

Clang produces an AST even when the code contains errors. Clang won't generate
and optimize code for it, but it's used as parsing continues to detect further
errors in the input. Clang-based tools also depend on such ASTs, and IDEs in
particular benefit from a high-quality AST for broken code.

In the presence of errors, clang uses a few error-recovery strategies to present the
broken code in the AST:

- correcting errors: in cases where clang is confident about the fix, it
  provides a FixIt attaching to the error diagnostic and emits a corrected AST
  (reflecting the written code with FixIts applied). The advantage of that is to
  provide more accurate subsequent diagnostics. Typo correction is a typical
  example.
- representing invalid node: the invalid node is preserved in the AST in some
  form, e.g., when the "declaration" part of the declaration contains semantic
  errors, the Decl node is marked as invalid.
- dropping invalid node: this often happens for errors that we don’t have
  graceful recovery. Prior to Recovery AST, a mismatched-argument function call
  expression was dropped though a `CallExpr` was created for semantic analysis.

With these strategies, clang surfaces better diagnostics, and provides AST
consumers a rich AST reflecting the written source code as much as possible even
for broken code.

#### Recovery AST

The idea of Recovery AST is to use recovery nodes, which act as a placeholder to
maintain the rough structure of the parsing tree, preserve locations and
children, but have no language semantics attached to them.

For example, consider the following mismatched function call:

```c++
int NoArg();
void test(int abc) {
  NoArg(abc); // oops, mismatched function arguments.
}
```

Without Recovery AST, the invalid function call expression (and its child
expressions) would be dropped in the AST:

```
|-FunctionDecl <line:1:1, col:11> NoArg 'int ()'
`-FunctionDecl <line:2:1, line:4:1> test 'void (int)'
 |-ParmVarDecl <col:11, col:15> col:15 used abc 'int'
 `-CompoundStmt <col:20, line:4:1>
```

With Recovery AST, the AST looks like:

```
|-FunctionDecl <line:1:1, col:11> NoArg 'int ()'
`-FunctionDecl <line:2:1, line:4:1> test 'void (int)'
  |-ParmVarDecl <col:11, col:15> used abc 'int'
  `-CompoundStmt <col:20, line:4:1>
    `-RecoveryExpr <line:3:3, col:12> 'int' contains-errors
      |-UnresolvedLookupExpr <col:3> '<overloaded function type>' lvalue (ADL) = 'NoArg'
      `-DeclRefExpr <col:9> 'int' lvalue ParmVar 'abc' 'int'
```

An alternative is to use existing Exprs, e.g., CallExpr for the above example.
This would capture more call details (e.g., locations of parentheses) and allow
it to be treated uniformly with valid CallExprs. However, jamming the data we
have into CallExpr forces us to weaken its invariants, e.g., arg count may be
wrong. This would introduce a huge burden on consumers of the AST to handle such
"impossible" cases. So when we're representing (rather than correcting) errors,
we use a distinct recovery node type with extremely weak invariants instead.

`RecoveryExpr` is the only recovery node so far. In practice, broken decls
need more detailed semantics preserved (the current `Invalid` flag works
fairly well), and completely broken statements with interesting internal
structure are rare (so dropping the statements is OK).

#### Types and dependence

`RecoveryExpr` is an `Expr`, so it must have a type. In many cases the true
type can't really be known until the code is corrected (e.g., a call to a
function that doesn't exist). And it means that we can't properly perform type
checks on some containing constructs, such as `return 42 + unknownFunction()`.

To model this, we generalize the concept of dependence from C++ templates to
mean dependence on a template parameter or how an error is repaired. The
`RecoveryExpr` `unknownFunction()` has the totally unknown type
`DependentTy`, and this suppresses type-based analysis in the same way it
would inside a template.

In cases where we are confident about the concrete type (e.g., the return type
for a broken non-overloaded function call), the `RecoveryExpr` will have this
type. This allows more code to be typechecked, and produces a better AST and
more diagnostics. For example:

```C++
unknownFunction().size() // .size() is a CXXDependentScopeMemberExpr
std::string(42).size() // .size() is a resolved MemberExpr
```

Whether or not the `RecoveryExpr` has a dependent type, it is always
considered value-dependent, because its value isn't well-defined until the error
is resolved. Among other things, this means that clang doesn't emit more errors
where a RecoveryExpr is used as a constant (e.g., array size), but also won't try
to evaluate it.

#### ContainsErrors bit

Beyond the template dependence bits, we add a new “ContainsErrors” bit to
express “Does this expression or anything within it contain errors” semantic,
this bit is always set for RecoveryExpr, and propagated to other related nodes.
This provides a fast way to query whether any (recursive) child of an expression
had an error, which is often used to improve diagnostics.

```C++
// C++
void recoveryExpr(int abc) {
 unknownFunction(); // type-dependent, value-dependent, contains-errors

 std::string(42).size(); // value-dependent, contains-errors,
                         // not type-dependent, as we know the type is std::string
}
```

```C
// C
void recoveryExpr(int abc) {
  unknownVar + abc; // type-dependent, value-dependent, contains-errors
}
```

### The ASTImporter

The `ASTImporter` class imports nodes of an `ASTContext` into another
`ASTContext`. Please refer to the document {doc}`ASTImporter: Merging Clang
ASTs <LibASTImporter>` for an introduction. And please read through the
high-level [description of the import
algorithm](LibASTImporter.md#algorithm-of-the-import), this is essential for
understanding further implementation details of the importer.

(templated)=

#### Abstract Syntax Graph

Despite the name, the Clang AST is not a tree. It is a directed graph with
cycles. One example of a cycle is the connection between a
`ClassTemplateDecl` and its "templated" `CXXRecordDecl`. The *templated*
`CXXRecordDecl` represents all the fields and methods inside the class
template, while the `ClassTemplateDecl` holds the information which is
related to being a template, i.e., template arguments, etc. We can get the
*templated* class (the `CXXRecordDecl`) of a `ClassTemplateDecl` with
`ClassTemplateDecl::getTemplatedDecl()`. And we can get back a pointer of the
"described" class template from the *templated* class:
`CXXRecordDecl::getDescribedTemplate()`. So, this is a cycle between two
nodes: between the *templated* and the *described* node. There may be various
other kinds of cycles in the AST especially in case of declarations.

(structural-eq)=

#### Structural Equivalency

Importing one AST node copies that node into the destination `ASTContext`. To
copy one node means that we create a new node in the "to" context then we set
its properties to be equal to the properties of the source node. Before the
copy, we make sure that the source node is not *structurally equivalent* to any
existing node in the destination context. If it happens to be equivalent then
we skip the copy.

The informal definition of structural equivalency is the following:
Two nodes are **structurally equivalent** if they are

- builtin types and refer to the same type, e.g., `int` and `int` are
  structurally equivalent,
- function types and all their parameters have structurally equivalent types,
- record types and all their fields in order of their definition have the same
  identifier names and structurally equivalent types,
- variable or function declarations and they have the same identifier name and
  their types are structurally equivalent.

In C, two types are structurally equivalent if they are *compatible types*. For
a formal definition of *compatible types*, please refer to 6.2.7/1 in the C11
standard. However, there is no definition for *compatible types* in the C++
standard. Still, we extend the definition of structural equivalency to
templates and their instantiations similarly: besides checking the previously
mentioned properties, we have to check for equivalent template
parameters/arguments, etc.

The structural equivalent check can be and is used independently from the
ASTImporter, e.g., the `clang::Sema` class uses it also.

The equivalence of nodes may depend on the equivalency of other pairs of nodes.
Thus, the check is implemented as a parallel graph traversal. We traverse
through the nodes of both graphs at the same time. The actual implementation is
similar to breadth-first-search. Let's say we start the traverse with the
`<A,B>` pair of nodes. Whenever the traversal reaches a pair `<X,Y>` then the
following statements are true:

- A and X are nodes from the same ASTContext.

- B and Y are nodes from the same ASTContext.

- A and B may or may not be from the same ASTContext.

- if A == X and B == Y (pointer equivalency) then (there is a cycle during the
  traverse)

  - A and B are structurally equivalent if and only if

    - All dependent nodes on the path from \<A,B> to \<X,Y> are structurally
      equivalent.

When we compare two classes or enums and one of them is incomplete or has
unloaded external lexical declarations then we cannot descend to compare their
contained declarations. So in these cases they are considered equal if they
have the same names. This is the way how we compare forward declarations with
definitions.

% TODO Should we elaborate the actual implementation of the graph traversal,

% which is a very weird BFS traversal?

#### Redeclaration Chains

The early version of the `ASTImporter`'s merge mechanism squashed the
declarations, i.e., it aimed to have only one declaration instead of maintaining
a whole redeclaration chain. This early approach simply skipped importing a
function prototype, but it imported a definition. To demonstrate the problem
with this approach let's consider an empty "to" context and the following
`virtual` function declarations of `f` in the "from" context:

```c++
struct B { virtual void f(); };
void B::f() {} // <-- let's import this definition
```

If we imported the definition with the "squashing" approach then we would
end-up having one declaration which is indeed a definition, but `isVirtual()`
returns `false` for it. The reason is that the definition is indeed not
virtual, it is the property of the prototype!

Consequently, we must either set the virtual flag for the definition (but then
we create a malformed AST which the parser would never create), or we import
the whole redeclaration chain of the function. The most recent version of the
`ASTImporter` uses the latter mechanism. We do import all function
declarations - regardless of whether they are definitions or prototypes - in the order
as they appear in the "from" context.

% One definition

If we have an existing definition in the "to" context, then we cannot import
another definition, we will use the existing definition. However, we can import
prototype(s): we chain the newly imported prototype(s) to the existing
definition. Whenever we import a new prototype from a third context, that will
be added to the end of the redeclaration chain. This may result in long
redeclaration chains in certain cases, e.g., if we import from several
translation units which include the same header with the prototype.

% Squashing prototypes

To mitigate the problem of long redeclaration chains of free functions, we
could compare prototypes to see if they have the same properties and if yes
then we could merge these prototypes. The implementation of squashing of
prototypes for free functions is future work.

% Exception: Cannot have more than 1 prototype in-class

Chaining functions this way ensures that we do copy all information from the
source AST. Nonetheless, there is a problem with member functions: While we can
have many prototypes for free functions, we must have only one prototype for a
member function.

```c++
void f(); // OK
void f(); // OK

struct X {
  void f(); // OK
  void f(); // ERROR
};
void X::f() {} // OK
```

Thus, prototypes of member functions must be squashed, we cannot just simply
attach a new prototype to the existing in-class prototype. Consider the
following contexts:

```c++
// "to" context
struct X {
  void f(); // D0
};
```

```c++
// "from" context
struct X {
  void f(); // D1
};
void X::f() {} // D2
```

When we import the prototype and the definition of `f` from the "from"
context, then the resulting redecl chain will look like this `D0 -> D2'`,
where `D2'` is the copy of `D2` in the "to" context.

% Redecl chains of other declarations

Generally speaking, when we import declarations (like enums and classes) we do
attach the newly imported declaration to the existing redeclaration chain (if
there is structural equivalency). We do not import, however, the whole
redeclaration chain as we do in case of functions. Up till now, we haven't
found any essential property of forward declarations which is similar to the
case of the virtual flag in a member function prototype. In the future, this
may change, though.

#### Traversal during the Import

The node specific import mechanisms are implemented in
`ASTNodeImporter::VisitNode()` functions, e.g., `VisitFunctionDecl()`.
When we import a declaration then first we import everything which is needed to
call the constructor of that declaration node. Everything which can be set
later is set after the node is created. For example, in case of a
`FunctionDecl` we first import the declaration context in which the function
is declared, then we create the `FunctionDecl` and only then we import the
body of the function. This means there are implicit dependencies between AST
nodes. These dependencies determine the order in which we visit nodes in the
"from" context. As with the regular graph traversal algorithms like DFS, we
keep track which nodes we have already visited in
`ASTImporter::ImportedDecls`. Whenever we create a node then we immediately
add that to the `ImportedDecls`. We must not start the import of any other
declarations before we keep track of the newly created one. This is essential,
otherwise, we would not be able to handle circular dependencies. To enforce
this, we wrap all constructor calls of all AST nodes in
`GetImportedOrCreateDecl()`. This wrapper ensures that all newly created
declarations are immediately marked as imported; also, if a declaration is
already marked as imported then we just return its counterpart in the "to"
context. Consequently, calling a declaration's `::Create()` function directly
would lead to errors, please don't do that!

Even with the use of `GetImportedOrCreateDecl()` there is still a
probability of having an infinite import recursion if things are imported from
each other in wrong way. Imagine that during the import of `A`, the import of
`B` is requested before we could create the node for `A` (the constructor
needs a reference to `B`). And the same could be true for the import of `B`
(`A` is requested to be imported before we could create the node for `B`).
In case of the {ref}`templated-described swing <templated>` we take
extra attention to break the cyclical dependency: we import and set the
described template only after the `CXXRecordDecl` is created. As a best
practice, before creating the node in the "to" context, avoid importing of
other nodes which are not needed for the constructor of node `A`.

#### Error Handling

Every import function returns with either an `llvm::Error` or an
`llvm::Expected<T>` object. This enforces to check the return value of the
import functions. If there was an error during one import then we return with
that error. (Exception: when we import the members of a class, we collect the
individual errors with each member and we concatenate them in one Error
object.) We cache these errors in cases of declarations. During the next import
call if there is an existing error we just return with that. So, clients of the
library receive an Error object, which they must check.

During import of a specific declaration, it may happen that some AST nodes had
already been created before we recognize an error. In this case, we signal back
the error to the caller, but the "to" context remains polluted with those nodes
which had been created. Ideally, those nodes should not have been created, but
that time we did not know about the error, the error happened later. Since the
AST is immutable (most of the cases we can't remove existing nodes) we choose
to mark these nodes as erroneous.

We cache the errors associated with declarations in the "from" context in
`ASTImporter::ImportDeclErrors` and the ones which are associated with the
"to" context in `ASTImporterSharedState::ImportErrors`. Note that, there may
be several ASTImporter objects which import into the same "to" context but from
different "from" contexts; in this case, they have to share the associated
errors of the "to" context.

When an error happens, that propagates through the call stack, through all the
dependent nodes. However, in case of dependency cycles, this is not enough,
because we strive to mark the erroneous nodes so clients can act upon. In those
cases, we have to keep track of the errors for those nodes which are
intermediate nodes of a cycle.

An **import path** is the list of the AST nodes which we visit during an Import
call. If node `A` depends on node `B` then the path contains an `A->B`
edge. From the call stack of the import functions, we can read the very same
path.

Now imagine the following AST, where the `->` represents dependency in terms
of the import (all nodes are declarations).

```text
A->B->C->D
   `->E
```

We would like to import A.
The import behaves like a DFS, so we will visit the nodes in this order: ABCDE.
During the visitation we will have the following import paths:

```text
A
AB
ABC
ABCD
ABC
AB
ABE
AB
A
```

If during the visit of E there is an error then we set an error for E, then as
the call stack shrinks for B, then for A:

```text
A
AB
ABC
ABCD
ABC
AB
ABE // Error! Set an error to E
AB  // Set an error to B
A   // Set an error to A
```

However, during the import we could import C and D without any error and they
are independent of A,B and E. We must not set up an error for C and D. So, at
the end of the import we have an entry in `ImportDeclErrors` for A,B,E but
not for C,D.

Now, what happens if there is a cycle in the import path? Let's consider this
AST:

```text
A->B->C->A
   `->E
```

During the visitation, we will have the below import paths and if during the
visit of E there is an error then we will set up an error for E,B,A. But what's
up with C?

```text
A
AB
ABC
ABCA
ABC
AB
ABE // Error! Set an error to E
AB  // Set an error to B
A   // Set an error to A
```

This time we know that both B and C are dependent on A. This means we must set
up an error for C too. As the call stack reverses back we get to A and we must
set up an error to all nodes which depend on A (this includes C). But C is no
longer on the import path, it just had been previously. Such a situation can
happen only if during the visitation we had a cycle. If we didn't have any
cycle, then the normal way of passing an Error object through the call stack
could handle the situation. This is why we must track cycles during the import
process for each visited declaration.

#### Lookup Problems

When we import a declaration from the source context then we check whether we
already have a structurally equivalent node with the same name in the "to"
context. If the "from" node is a definition and the found one is also a
definition, then we do not create a new node, instead, we mark the found node
as the imported node. If the found definition and the one we want to import
have the same name but they are structurally in-equivalent, then we have an ODR
violation in case of C++. If the "from" node is not a definition then we add
that to the redeclaration chain of the found node. This behaviour is essential
when we merge ASTs from different translation units which include the same
header file(s). For example, we want to have only one definition for the class
template `std::vector`, even if we included `<vector>` in several
translation units.

To find a structurally equivalent node we can use the regular C/C++ lookup
functions: `DeclContext::noload_lookup()` and
`DeclContext::localUncachedLookup()`. These functions do respect the C/C++
name hiding rules, thus you cannot find certain declarations in a given
declaration context. For instance, unnamed declarations (anonymous structs),
non-first `friend` declarations and template specializations are hidden. This
is a problem, because if we use the regular C/C++ lookup then we create
redundant AST nodes during the merge! Also, having two instances of the same
node could result in false {ref}`structural in-equivalencies <structural-eq>`
of other nodes which depend on the duplicated node. Because of these reasons,
we created a lookup class which has the sole purpose to register all
declarations, so later they can be looked up by subsequent import requests.
This is the `ASTImporterLookupTable` class. This lookup table should be
shared amongst the different `ASTImporter` instances if they happen to import
to the very same "to" context. This is why we can use the importer specific
lookup only via the `ASTImporterSharedState` class.

##### ExternalASTSource

The `ExternalASTSource` is an abstract interface associated with the
`ASTContext` class. It provides the ability to read the declarations stored
within a declaration context either for iteration or for name lookup. A
declaration context with an external AST source may load its declarations
on-demand. This means that the list of declarations (represented as a linked
list, the head is `DeclContext::FirstDecl`) could be empty. However, member
functions like `DeclContext::lookup()` may initiate a load.

Usually, external sources are associated with precompiled headers. For example,
when we load a class from a PCH then the members are loaded only if we do want
to look up something in the class' context.

In case of LLDB, an implementation of the `ExternalASTSource` interface is
attached to the AST context which is related to the parsed expression. This
implementation of the `ExternalASTSource` interface is realized with the help
of the `ASTImporter` class. This way, LLDB can reuse Clang's parsing
machinery while synthesizing the underlying AST from the debug data (e.g., from
DWARF). From the view of the `ASTImporter` this means both the "to" and the
"from" context may have declaration contexts with external lexical storage. If
a `DeclContext` in the "to" AST context has external lexical storage then we
must take extra attention to work only with the already loaded declarations!
Otherwise, we would end up with an uncontrolled import process. For instance,
if we used the regular `DeclContext::lookup()` to find the existing
declarations in the "to" context then the `lookup()` call itself would
initiate a new import while we are in the middle of importing a declaration!
(By the time we initiate the lookup we haven't registered yet that we already
started to import the node of the "from" context.) This is why we use
`DeclContext::noload_lookup()` instead.

#### Class Template Instantiations

Different translation units may have class template instantiations with the
same template arguments, but with a different set of instantiated
`MethodDecls` and `FieldDecls`. Consider the following files:

```c++
// x.h
template <typename T>
struct X {
    int a{0}; // FieldDecl with InitListExpr
    X(char) : a(3) {}     // (1)
    X(int) {}             // (2)
};

// foo.cpp
void foo() {
    // ClassTemplateSpec with ctor (1): FieldDecl without InitlistExpr
    X<char> xc('c');
}

// bar.cpp
void bar() {
    // ClassTemplateSpec with ctor (2): FieldDecl WITH InitlistExpr
    X<char> xc(1);
}
```

In `foo.cpp` we use the constructor with number `(1)`, which explicitly
initializes the member `a` to `3`, thus the `InitListExpr` `{0}` is not
used here and the AST node is not instantiated. However, in the case of
`bar.cpp` we use the constructor with number `(2)`, which does not
explicitly initialize the `a` member, so the default `InitListExpr` is
needed and thus instantiated. When we merge the AST of `foo.cpp` and
`bar.cpp` we must create an AST node for the class template instantiation of
`X<char>` which has all the required nodes. Therefore, when we find an
existing `ClassTemplateSpecializationDecl` then we merge the fields of the
`ClassTemplateSpecializationDecl` in the "from" context in a way that the
`InitListExpr` is copied if not existent yet. The same merge mechanism should
be done in the cases of instantiated default arguments and exception
specifications of functions.

(visibility)=

#### Visibility of Declarations

During import of a global variable with external visibility, the lookup will
find variables (with the same name) but with static visibility (linkage).
Clearly, we cannot put them into the same redeclaration chain. The same is true
the in case of functions. Also, we have to take care of other kinds of
declarations like enums, classes, etc. if they are in anonymous namespaces.
Therefore, we filter the lookup results and consider only those which have the
same visibility as the declaration we currently import.

We consider two declarations in two anonymous namespaces to have the same
visibility only if they are imported from the same AST context.

#### Strategies to Handle Conflicting Names

During the import we lookup existing declarations with the same name. We filter
the lookup results based on their {ref}`visibility <visibility>`. If any of the
found declarations are not structurally equivalent then we bumped to a name
conflict error (ODR violation in C++). In this case, we return with an
`Error` and we set up the `Error` object for the declaration. However, some
clients of the `ASTImporter` may require a different, perhaps less
conservative and more liberal error handling strategy.

E.g., static analysis clients may benefit if the node is created even if there
is a name conflict. During the CTU analysis of certain projects, we recognized
that there are global declarations which collide with declarations from other
translation units, but they are not referenced outside from their translation
unit. These declarations should be in an unnamed namespace ideally. If we treat
these collisions liberally then CTU analysis can find more results. Note, the
feature to be able to choose between name conflict handling strategies is still an
ongoing work.

(cfg)=

### The `CFG` class

The `CFG` class is designed to represent a source-level control-flow graph
for a single statement (`Stmt*`). Typically instances of `CFG` are
constructed for function bodies (usually an instance of `CompoundStmt`), but
can also be instantiated to represent the control-flow of any class that
subclasses `Stmt`, which includes simple expressions. Control-flow graphs
are especially useful for performing [flow- or path-sensitive](https://en.wikipedia.org/wiki/Data_flow_analysis#Sensitivities) program
analyses on a given function.

#### Basic Blocks

Concretely, an instance of `CFG` is a collection of basic blocks. Each basic
block is an instance of `CFGBlock`, which simply contains an ordered sequence
of `Stmt*` (each referring to statements in the AST). The ordering of
statements within a block indicates unconditional flow of control from one
statement to the next. {ref}`Conditional control-flow
<ConditionalControlFlow>` is represented using edges between basic blocks. The
statements within a given `CFGBlock` can be traversed using the
`CFGBlock::*iterator` interface.

A `CFG` object owns the instances of `CFGBlock` within the control-flow
graph it represents. Each `CFGBlock` within a CFG is also uniquely numbered
(accessible via `CFGBlock::getBlockID()`). Currently the number is based on
the ordering the blocks were created, but no assumptions should be made on how
`CFGBlocks` are numbered other than their numbers are unique and that they
are numbered from 0..N-1 (where N is the number of basic blocks in the CFG).

#### Entry and Exit Blocks

Each instance of `CFG` contains two special blocks: an *entry* block
(accessible via `CFG::getEntry()`), which has no incoming edges, and an
*exit* block (accessible via `CFG::getExit()`), which has no outgoing edges.
Neither block contains any statements, and they serve the role of providing a
clear entrance and exit for a body of code such as a function body. The
presence of these empty blocks greatly simplifies the implementation of many
analyses built on top of CFGs.

(conditionalcontrolflow)=

#### Conditional Control-Flow

Conditional control-flow (such as those induced by if-statements and loops) is
represented as edges between `CFGBlocks`. Because different C language
constructs can induce control-flow, each `CFGBlock` also records an extra
`Stmt*` that represents the *terminator* of the block. A terminator is
simply the statement that caused the control-flow, and is used to identify the
nature of the conditional control-flow between blocks. For example, in the
case of an if-statement, the terminator refers to the `IfStmt` object in the
AST that represented the given branch.

To illustrate, consider the following code example:

```c++
int foo(int x) {
  x = x + 1;
  if (x > 2)
    x++;
  else {
    x += 2;
    x *= 2;
  }

  return x;
}
```

After invoking the parser+semantic analyzer on this code fragment, the AST of
the body of `foo` is referenced by a single `Stmt*`. We can then construct
an instance of `CFG` representing the control-flow graph of this function
body by single call to a static class method:

```c++
Stmt *FooBody = ...
std::unique_ptr<CFG> FooCFG = CFG::buildCFG(FooBody);
```

Along with providing an interface to iterate over its `CFGBlocks`, the
`CFG` class also provides methods that are useful for debugging and
visualizing CFGs. For example, the method `CFG::dump()` dumps a
pretty-printed version of the CFG to standard error. This is especially useful
when one is using a debugger such as gdb. For example, here is the output of
`FooCFG->dump()`:

```text
[ B5 (ENTRY) ]
   Predecessors (0):
   Successors (1): B4

[ B4 ]
   1: x = x + 1
   2: (x > 2)
   T: if [B4.2]
   Predecessors (1): B5
   Successors (2): B3 B2

[ B3 ]
   1: x++
   Predecessors (1): B4
   Successors (1): B1

[ B2 ]
   1: x += 2
   2: x *= 2
   Predecessors (1): B4
   Successors (1): B1

[ B1 ]
   1: return x;
   Predecessors (2): B2 B3
   Successors (1): B0

[ B0 (EXIT) ]
   Predecessors (1): B1
   Successors (0):
```

For each block, the pretty-printed output displays for each block the number of
*predecessor* blocks (blocks that have outgoing control-flow to the given
block) and *successor* blocks (blocks that have control-flow that have incoming
control-flow from the given block). We can also clearly see the special entry
and exit blocks at the beginning and end of the pretty-printed output. For the
entry block (block B5), the number of predecessor blocks is 0, while for the
exit block (block B0) the number of successor blocks is 0.

The most interesting block here is B4, whose outgoing control-flow represents
the branching caused by the sole if-statement in `foo`. Of particular
interest is the second statement in the block, `(x > 2)`, and the terminator,
printed as `if [B4.2]`. The second statement represents the evaluation of
the condition of the if-statement, which occurs before the actual branching of
control-flow. Within the `CFGBlock` for B4, the `Stmt*` for the second
statement refers to the actual expression in the AST for `(x > 2)`. Thus
pointers to subclasses of `Expr` can appear in the list of statements in a
block, and not just subclasses of `Stmt` that refer to proper C statements.

The terminator of block B4 is a pointer to the `IfStmt` object in the AST.
The pretty-printer outputs `if [B4.2]` because the condition expression of
the if-statement has an actual place in the basic block, and thus the
terminator is essentially *referring* to the expression that is the second
statement of block B4 (i.e., B4.2). In this manner, conditions for
control-flow (which also includes conditions for loops and switch statements)
are hoisted into the actual basic block.

#### Implicit Control-Flow

A key design principle of the `CFG` class was to not require any
transformations to the AST in order to represent control-flow.  Thus the `CFG`
does not perform any "lowering" of the statements in an AST: loops are not
transformed into guarded gotos, short-circuit operations are not converted to a
set of if-statements, and so on.

### Constant Folding in the Clang AST

There are several places where constants and constant folding matter a lot to
the Clang front-end. First, in general, we prefer the AST to retain the source
code as close to how the user wrote it as possible. This means that if they
wrote "`5+4`", we want to keep the addition and two constants in the AST, we
don't want to fold to "`9`". This means that constant folding in various
ways turns into a tree walk that needs to handle the various cases.

However, there are places in both C and C++ that require constants to be
folded. For example, the C standard defines what an "integer constant
expression" (i-c-e) is with very precise and specific requirements. The
language then requires i-c-e's in a lot of places (for example, the size of a
bitfield, the value for a case statement, etc). For these, we have to be able
to constant fold the constants, to do semantic checks (e.g., verify bitfield
size is non-negative and that case statements aren't duplicated). We aim for
Clang to be very pedantic about this, diagnosing cases when the code does not
use an i-c-e where one is required, but accepting the code unless running with
`-pedantic-errors`.

Things get a little bit more tricky when it comes to compatibility with
real-world source code. Specifically, GCC has historically accepted a huge
superset of expressions as i-c-e's, and a lot of real world code depends on
this unfortunate accident of history (including, e.g., the glibc system
headers). GCC accepts anything its "fold" optimizer is capable of reducing to
an integer constant, which means that the definition of what it accepts changes
as its optimizer does. One example is that GCC accepts things like "`case
X-X:`" even when `X` is a variable, because it can fold this to 0.

Another issue are how constants interact with the extensions we support, such
as `__builtin_constant_p`, `__builtin_inf`, `__extension__` and many
others. C99 obviously does not specify the semantics of any of these
extensions, and the definition of i-c-e does not include them. However, these
extensions are often used in real code, and we have to have a way to reason
about them.

Finally, this is not just a problem for semantic analysis. The code generator
and other clients have to be able to fold constants (e.g., to initialize global
variables) and have to handle a superset of what C99 allows. Further, these
clients can benefit from extended information. For example, we know that
"`foo() || 1`" always evaluates to `true`, but we can't replace the
expression with `true` because it has side effects.

#### Implementation Approach

After trying several different approaches, we've finally converged on a design
(Note, at the time of this writing, not all of this has been implemented,
consider this a design goal!). Our basic approach is to define a single
recursive evaluation method (`Expr::Evaluate`), which is implemented
in `AST/ExprConstant.cpp`. Given an expression with "scalar" type (integer,
fp, complex, or pointer) this method returns the following information:

- Whether the expression is an integer constant expression, a general constant
  that was folded but has no side effects, a general constant that was folded
  but that does have side effects, or an uncomputable/unfoldable value.
- If the expression was computable in any way, this method returns the
  `APValue` for the result of the expression.
- If the expression is not evaluatable at all, this method returns information
  on one of the problems with the expression. This includes a
  `SourceLocation` for where the problem is, and a diagnostic ID that explains
  the problem. The diagnostic should have `ERROR` type.
- If the expression is not an integer constant expression, this method returns
  information on one of the problems with the expression. This includes a
  `SourceLocation` for where the problem is, and a diagnostic ID that
  explains the problem. The diagnostic should have `EXTENSION` type.

This information gives various clients the flexibility that they want, and we
will eventually have some helper methods for various extensions. For example,
`Sema` should have a `Sema::VerifyIntegerConstantExpression` method, which
calls `Evaluate` on the expression. If the expression is not foldable, the
error is emitted, and it would return `true`. If the expression is not an
i-c-e, the `EXTENSION` diagnostic is emitted. Finally it would return
`false` to indicate that the AST is OK.

Other clients can use the information in other ways, for example, codegen can
just use expressions that are foldable in any way.

#### Extensions

This section describes how some of the various extensions Clang supports
interacts with constant evaluation:

- `__extension__`: The expression form of this extension causes any
  evaluatable subexpression to be accepted as an integer constant expression.
- `__builtin_constant_p`: This returns true (as an integer constant
  expression) if the operand evaluates to either a numeric value (that is, not
  a pointer cast to integral type) of integral, enumeration, floating or
  complex type, or if it evaluates to the address of the first character of a
  string literal (possibly cast to some other type). As a special case, if
  `__builtin_constant_p` is the (potentially parenthesized) condition of a
  conditional operator expression ("`?:`"), only the true side of the
  conditional operator is considered, and it is evaluated with full constant
  folding.
- `__builtin_choose_expr`: The condition is required to be an integer
  constant expression, but we accept any constant as an "extension of an
  extension". This only evaluates one operand depending on which way the
  condition evaluates.
- `__builtin_classify_type`: This always returns an integer constant
  expression.
- `__builtin_inf, nan, ...`: These are treated just like a floating-point
  literal.
- `__builtin_abs, copysign, ...`: These are constant folded as general
  constant expressions.
- `__builtin_strlen` and `strlen`: These are constant folded as integer
  constant expressions if the argument is a string literal.

(sema)=

## The Sema Library

This library is called by the {ref}`Parser library <Parser>` during parsing to
do semantic analysis of the input. For valid programs, Sema builds an AST for
parsed constructs.

### Concept Satisfaction Checking and Subsumption

As per the C++ standard, constraints are [normalized](https://eel.is/c++draft/temp.constr.normal)
and the normal form is used both for subsumption, and constraint checking.
Both depend on a parameter mapping that substitutes lazily. In particular,
we should not substitute in unused arguments.

Clang follows the order of operations prescribed by the standard.

Normalization happens prior to satisfaction and subsumption
and is handled by `NormalizedConstraint`.

Clang preserves in the normalized form intermediate concept-ids
(`ConceptIdConstraint`) This is used for diagnostics only and no substitution
happens in a ConceptIdConstraint if its expression is satisfied.

The normal form of each associated constraint expression is cached in
`Sema::NormalizedConstraintExprCache`, so that it is only computed once even if
several declarations share it (e.g. members of class template specializations).

A `NormalizedConstraint` is a recursive data structure, where each node
contains a parameter mapping, represented by the indexes of all parameter
being used.

Checking satisfaction is done by `ConstraintSatisfactionChecker`, recursively
walking `NormalizedConstraint`. At each level, we substitute the outermost
level of the template arguments referenced in the parameter mapping of a
normalized expression (`MultiLevelTemplateArgumentList`).

For the following example,

```c++
template <typename T>
concept A = __is_same(T, int);

template <typename U>
concept B = A<U> && __is_same(U, int);
```

The normal form of B is

```c++
   __is_same(T, int) /*T->U, innermost level*/
&& __is_same(U, int) {U->U} /*T->U, outermost level*/
```

After substitution in the mapping, we substitute in the constraint expression
using that copy of the `MultiLevelTemplateArgumentList`, and then evaluate it.

Because this is expensive, it is cached in
`UnsubstitutedConstraintSatisfactionCache`. Also we will cache the instantiation
result of parameter mappings to avoid unnecessary semantic checking.

Any error during satisfaction is recorded in `ConstraintSatisfaction`.
for nested requirements, `ConstraintSatisfaction` is stored (including
diagnostics) in the AST, which is something we might want to improve.

When an atomic constraint is not satisfied, we try to substitute into any
enclosing concept-id using the same mechanism described above, for
diagnostics purpose, and inject that in the `ConstraintSatisfaction`.

(codegen)=

## The CodeGen Library

CodeGen takes an {ref}`AST <AST>` as input and produces [LLVM IR code](https://llvm.org/docs/LangRef.html) from it.

## How to change Clang

### How to add an attribute

Attributes are a form of metadata that can be attached to a program construct,
allowing the programmer to pass semantic information along to the compiler for
various uses. For example, attributes may be used to alter the code generation
for a program construct, or to provide extra semantic information for static
analysis. This document explains how to add a custom attribute to Clang.
Documentation on existing attributes can be found [here](AttributeReference.md).

#### Attribute Basics

Attributes in Clang are handled in three stages: parsing into a parsed attribute
representation, conversion from a parsed attribute into a semantic attribute,
and then the semantic handling of the attribute.

Parsing of the attribute is determined by the various syntactic forms attributes
can take, such as GNU, C++11, and Microsoft style attributes, as well as other
information provided by the table definition of the attribute. Ultimately, the
parsed representation of an attribute object is a `ParsedAttr` object.
These parsed attributes chain together as a list of parsed attributes attached
to a declarator or declaration specifier. The parsing of attributes is handled
automatically by Clang, except for attributes spelled as so-called “custom”
keywords. When implementing a custom keyword attribute, the parsing of the
keyword and creation of the `ParsedAttr` object must be done manually.

Eventually, `Sema::ProcessDeclAttributeList()` is called with a `Decl` and
a `ParsedAttr`, at which point the parsed attribute can be transformed
into a semantic attribute. The process by which a parsed attribute is converted
into a semantic attribute depends on the attribute definition and semantic
requirements of the attribute. The end result, however, is that the semantic
attribute object is attached to the `Decl` object, and can be obtained by a
call to `Decl::getAttr<T>()`. Similarly, for statement attributes,
`Sema::ProcessStmtAttributes()` is called with a `Stmt` a list of
`ParsedAttr` objects to be converted into a semantic attribute.

The structure of the semantic attribute is also governed by the attribute
definition given in Attr.td. This definition is used to automatically generate
functionality used for the implementation of the attribute, such as a class
derived from `clang::Attr`, information for the parser to use, automated
semantic checking for some attributes, etc.

#### `include/clang/Basic/Attr.td`

The first step to adding a new attribute to Clang is to add its definition to
[include/clang/Basic/Attr.td](https://github.com/llvm/llvm-project/blob/main/clang/include/clang/Basic/Attr.td).
This tablegen definition must derive from the `Attr` (tablegen, not
semantic) type, or one of its derivatives. Most attributes will derive from the
`InheritableAttr` type, which specifies that the attribute can be inherited by
later redeclarations of the `Decl` it is associated with.
`InheritableParamAttr` is similar to `InheritableAttr`, except that the
attribute is written on a parameter instead of a declaration. If the attribute
applies to statements, it should inherit from `StmtAttr`. If the attribute is
intended to apply to a type instead of a declaration, such an attribute should
derive from `TypeAttr`, and will generally not be given an AST representation.
(Note that this document does not cover the creation of type attributes.) An
attribute that inherits from `IgnoredAttr` is parsed, but will generate an
ignored attribute diagnostic when used, which may be useful when an attribute is
supported by another vendor but not supported by clang.

The definition will specify several key pieces of information, such as the
semantic name of the attribute, the spellings the attribute supports, the
arguments the attribute expects, and more. Most members of the `Attr` tablegen
type do not require definitions in the derived definition as the default
suffice. However, every attribute must specify at least a spelling list, a
subject list, and a documentation list.

##### Spellings

All attributes are required to specify a spelling list that denotes the ways in
which the attribute can be spelled. For instance, a single semantic attribute
may have a keyword spelling, as well as a C++11 spelling and a GNU spelling. An
empty spelling list is also permissible and may be useful for attributes which
are created implicitly. The following spellings are accepted:

:::{list-table}
:header-rows: 1

* - Spelling
  - Description
* - `GNU`
  - Spelled with a GNU-style `__attribute__((attr))` syntax and placement.
* - `CXX11`
  - Spelled with a C++-style `[[attr]]` syntax with an optional vendor-specific
    namespace.
* - `C23`
  - Spelled with a C-style `[[attr]]` syntax with an optional vendor-specific
    namespace.
* - `Declspec`
  - Spelled with a Microsoft-style `__declspec(attr)` syntax.
* - `CustomKeyword`
  - The attribute is spelled as a keyword, and requires custom parsing.
* - `RegularKeyword`
  - The attribute is spelled as a keyword. It can be used in exactly the places
    that the standard `[[attr]]` syntax can be used, and appertains to exactly
    the same thing that a standard attribute would appertain to. Lexing and
    parsing of the keyword are handled automatically.
* - `GCC`
  - Specifies two or three spellings: the first is a GNU-style spelling, the
    second is a C++-style spelling with the `gnu` namespace, and the third is an
    optional C-style spelling with the `gnu` namespace. Attributes should only
    specify this spelling for attributes supported by GCC.
* - `Clang`
  - Specifies two or three spellings: the first is a GNU-style spelling, the
    second is a C++-style spelling with the `clang` namespace, and the third is
    an optional C-style spelling with the `clang` namespace. By default, a
    C-style spelling is provided.
* - `Pragma`
  - The attribute is spelled as a `#pragma`, and requires custom processing
    within the preprocessor. If the attribute is meant to be used by Clang, it
    should set the namespace to `"clang"`. Note that this spelling is not used
    for declaration attributes.
:::

The C++ standard specifies that “any [non-standard attribute] that is not
recognized by the implementation is ignored” (`[dcl.attr.grammar]`).
The rule for C is similar. This makes `CXX11` and `C23` spellings
unsuitable for attributes that affect the type system, that change the
binary interface of the code, or that have other similar semantic meaning.

`RegularKeyword` provides an alternative way of spelling such attributes.
It reuses the production rules for standard attributes, but it applies them
to plain keywords rather than to `[[…]]` sequences. Compilers that don't
recognize the keyword are likely to report an error of some kind.

For example, the `ArmStreaming` function type attribute affects
both the type system and the binary interface of the function.
It cannot therefore be spelled `[[arm::streaming]]`, since compilers
that don't understand `arm::streaming` would ignore it and miscompile
the code. `ArmStreaming` is instead spelled `__arm_streaming`, but it
can appear wherever a hypothetical `[[arm::streaming]]` could appear.

##### Subjects

Attributes appertain to one or more subjects. If the attribute attempts to
attach to a subject that is not in the subject list, a diagnostic is issued
automatically. Whether the diagnostic is a warning or an error depends on how
the attribute's `SubjectList` is defined, but the default behavior is to warn.
The diagnostics displayed to the user are automatically determined based on the
subjects in the list, but a custom diagnostic parameter can also be specified in
the `SubjectList`. The diagnostics generated for subject list violations are
calculated automatically or specified by the subject list itself. If a
previously unused Decl node is added to the `SubjectList`, the logic used to
automatically determine the diagnostic parameter in [utils/TableGen/ClangAttrEmitter.cpp](https://github.com/llvm/llvm-project/blob/main/clang/utils/TableGen/ClangAttrEmitter.cpp)
may need to be updated.

By default, all subjects in the SubjectList must either be a Decl node defined
in `DeclNodes.td`, or a statement node defined in `StmtNodes.td`. However,
more complex subjects can be created by creating a `SubsetSubject` object.
Each such object has a base subject which it appertains to (which must be a
Decl or Stmt node, and not a SubsetSubject node), and some custom code which is
called when determining whether an attribute appertains to the subject. For
instance, a `NonBitField` SubsetSubject appertains to a `FieldDecl`, and
tests whether the given FieldDecl is a bit field. When a SubsetSubject is
specified in a SubjectList, a custom diagnostic parameter must also be provided.

Diagnostic checking for attribute subject lists for declaration and statement
attributes is automated except when `HasCustomParsing` is set to `1`.

##### Documentation

All attributes must have some form of documentation associated with them.
Documentation is table generated on the public web server by a server-side
process that runs daily. Generally, the documentation for an attribute is a
stand-alone definition in [include/clang/Basic/AttrDocs.td](https://github.com/llvm/llvm-project/blob/main/clang/include/clang/Basic/AttrDocs.td)
that is named after the attribute being documented.

If the attribute is not for public consumption, or is an implicitly-created
attribute that has no visible spelling, the documentation list can specify the
`InternalOnly` object. Otherwise, the attribute should have its documentation
added to AttrDocs.td.

Documentation derives from the `Documentation` tablegen type. All derived
types must specify a documentation category and the actual documentation itself.
Additionally, it can specify a custom heading for the attribute, though a
default heading will be chosen when possible.

There are four predefined documentation categories: `DocCatFunction` for
attributes that appertain to function-like subjects, `DocCatVariable` for
attributes that appertain to variable-like subjects, `DocCatType` for type
attributes, and `DocCatStmt` for statement attributes. A custom documentation
category should be used for groups of attributes with similar functionality.
Custom categories are good for providing overview information for the attributes
grouped under it. For instance, the consumed annotation attributes define a
custom category, `DocCatConsumed`, that explains what consumed annotations are
at a high level.

Documentation content (whether it is for an attribute or a category) is written
using reStructuredText (RST) syntax.

After writing the documentation for the attribute, it should be locally tested
to ensure that there are no issues generating the documentation on the server.
Local testing requires a fresh build of clang-tblgen. To generate the attribute
documentation, execute the following command:

```
clang-tblgen -gen-attr-docs -I /path/to/clang/include /path/to/clang/include/clang/Basic/Attr.td -o /path/to/clang/docs/AttributeReference.md
```

When testing locally, *do not* commit changes to `AttributeReference.md`.
This file is generated by the server automatically, and any changes made to this
file will be overwritten.

##### Arguments

Attributes may optionally specify a list of arguments that can be passed to the
attribute. Attribute arguments specify both the parsed form and the semantic
form of the attribute. For example, if `Args` is
`[StringArgument<"Arg1">, IntArgument<"Arg2">]` then
`__attribute__((myattribute("Hello", 3)))` will be a valid use; it requires
two arguments while parsing, and the Attr subclass' constructor for the
semantic attribute will require a string and integer argument.

All arguments have a name and a flag that specifies whether the argument is
optional. The associated C++ type of the argument is determined by the argument
definition type. If the existing argument types are insufficient, new types can
be created, but it requires modifying [utils/TableGen/ClangAttrEmitter.cpp](https://github.com/llvm/llvm-project/blob/main/clang/utils/TableGen/ClangAttrEmitter.cpp)
to properly support the type.

##### Other Properties

The `Attr` definition has other members which control the behavior of the
attribute. Many of them are special-purpose and beyond the scope of this
document, however a few deserve mention.

If the parsed form of the attribute is more complex, or differs from the
semantic form, the `HasCustomParsing` bit can be set to `1` for the class,
and the parsing code in [Parser::ParseGNUAttributeArgs()](https://github.com/llvm/llvm-project/blob/main/clang/lib/Parse/ParseDecl.cpp)
can be updated for the special case. Note that this only applies to arguments
with a GNU spelling -- attributes with a \_\_declspec spelling currently ignore
this flag and are handled by `Parser::ParseMicrosoftDeclSpec`.

Note that setting this member to 1 will opt out of common attribute semantic
handling, requiring extra implementation efforts to ensure the attribute
appertains to the appropriate subject, etc.

If the attribute should not be propagated from a template declaration to an
instantiation of the template, set the `Clone` member to 0. By default, all
attributes will be cloned to template instantiations.

Attributes that do not require an AST node should set the `ASTNode` field to
`0` to avoid polluting the AST. Note that anything inheriting from
`TypeAttr` or `IgnoredAttr` automatically do not generate an AST node. All
other attributes generate an AST node by default. The AST node is the semantic
representation of the attribute.

The `LangOpts` field specifies a list of language options required by the
attribute. For instance, all of the CUDA-specific attributes specify `[CUDA]`
for the `LangOpts` field, and when the CUDA language option is not enabled, an
"attribute ignored" warning diagnostic is emitted. Since language options are
not table generated nodes, new language options must be created manually and
should specify the spelling used by `LangOptions` class.

Custom accessors can be generated for an attribute based on the spelling list
for that attribute. For instance, if an attribute has two different spellings:
'Foo' and 'Bar', accessors can be created:
`[Accessor<"isFoo", [GNU<"Foo">]>, Accessor<"isBar", [GNU<"Bar">]>]`
These accessors will be generated on the semantic form of the attribute,
accepting no arguments and returning a `bool`.

Attributes that do not require custom semantic handling should set the
`SemaHandler` field to `0`. Note that anything inheriting from
`IgnoredAttr` automatically do not get a semantic handler. All other
attributes are assumed to use a semantic handler by default. Attributes
without a semantic handler are not given a parsed attribute `Kind` enumerator.

"Simple" attributes, that require no custom semantic processing aside from what
is automatically provided, should set the `SimpleHandler` field to `1`.

Target-specific attributes may share a spelling with other attributes in
different targets. For instance, the ARM and MSP430 targets both have an
attribute spelled `GNU<"interrupt">`, but with different parsing and semantic
requirements. To support this feature, an attribute inheriting from
`TargetSpecificAttribute` may specify a `ParseKind` field. This field
should be the same value between all arguments sharing a spelling, and
corresponds to the parsed attribute's `Kind` enumerator. This allows
attributes to share a parsed attribute kind, but have distinct semantic
attribute classes. For instance, `ParsedAttr` is the shared
parsed attribute kind, but ARMInterruptAttr and MSP430InterruptAttr are the
semantic attributes generated.

By default, attribute arguments are parsed in an evaluated context. If the
arguments for an attribute should be parsed in an unevaluated context (akin to
the way the argument to a `sizeof` expression is parsed), set
`ParseArgumentsAsUnevaluated` to `1`.

If additional functionality is desired for the semantic form of the attribute,
the `AdditionalMembers` field specifies code to be copied verbatim into the
semantic attribute class object, with `public` access.

If two or more attributes cannot be used in combination on the same declaration
or statement, a `MutualExclusions` definition can be supplied to automatically
generate diagnostic code. This will disallow the attribute combinations
regardless of spellings used. Additionally, it will diagnose combinations within
the same attribute list, different attribute list, and redeclarations, as
appropriate.

#### Boilerplate

All semantic processing of declaration attributes happens in [lib/Sema/SemaDeclAttr.cpp](https://github.com/llvm/llvm-project/blob/main/clang/lib/Sema/SemaDeclAttr.cpp),
and generally starts in the `ProcessDeclAttribute()` function. If the
attribute has the `SimpleHandler` field set to `1` then the function to
process the attribute will be automatically generated, and nothing needs to be
done here. Otherwise, write a new `handleYourAttr()` function, and add that to
the switch statement. Please do not implement handling logic directly in the
`case` for the attribute.

Unless otherwise specified by the attribute definition, common semantic checking
of the parsed attribute is handled automatically. This includes diagnosing
parsed attributes that do not appertain to the given `Decl` or `Stmt`,
ensuring the correct minimum number of arguments are passed, etc.

If the attribute adds additional warnings, define a `DiagGroup` in
[include/clang/Basic/DiagnosticGroups.td](https://github.com/llvm/llvm-project/blob/main/clang/include/clang/Basic/DiagnosticGroups.td)
named after the attribute's `Spelling` with "\_"s replaced by "-"s. If there
is only a single diagnostic, it is permissible to use `InGroup<DiagGroup<"your-attribute">>`
directly in [DiagnosticSemaKinds.td](https://github.com/llvm/llvm-project/blob/main/clang/include/clang/Basic/DiagnosticSemaKinds.td)

All semantic diagnostics generated for your attribute, including automatically-
generated ones (such as subjects and argument counts), should have a
corresponding test case.

#### Semantic handling

Most attributes are implemented to have some effect on the compiler. For
instance, to modify the way code is generated, or to add extra semantic checks
for an analysis pass, etc. Having added the attribute definition and conversion
to the semantic representation for the attribute, what remains is to implement
the custom logic requiring use of the attribute.

The `clang::Decl` object can be queried for the presence or absence of an
attribute using `hasAttr<T>()`. To obtain a pointer to the semantic
representation of the attribute, `getAttr<T>` may be used.

The `clang::AttributedStmt` object can be queried for the presence or absence
of an attribute by calling `getAttrs()` and looping over the list of
attributes.

### How to add an expression or statement

Expressions and statements are one of the most fundamental constructs within a
compiler, because they interact with many different parts of the AST, semantic
analysis, and IR generation. Therefore, adding a new expression or statement
kind into Clang requires some care. The following list details the various
places in Clang where an expression or statement needs to be introduced, along
with patterns to follow to ensure that the new expression or statement works
well across all of the C languages. We focus on expressions, but statements
are similar.

1. Introduce parsing actions into the parser. Recursive-descent parsing is
   mostly self-explanatory, but there are a few things that are worth keeping
   in mind:

   - Keep as much source location information as possible! You'll want it later
     to produce great diagnostics and support Clang's various features that map
     between source code and the AST.
   - Write tests for all of the "bad" parsing cases, to make sure your recovery
     is good. If you have matched delimiters (e.g., parentheses, square
     brackets, etc.), use `Parser::BalancedDelimiterTracker` to give nice
     diagnostics when things go wrong.

2. Introduce semantic analysis actions into `Sema`. Semantic analysis should
   always involve two functions: an `ActOnXXX` function that will be called
   directly from the parser, and a `BuildXXX` function that performs the
   actual semantic analysis and will (eventually!) build the AST node. It's
   fairly common for the `ActOnXXX` function to do very little (often just
   some minor translation from the parser's representation to `Sema`'s
   representation of the same thing), but the separation is still important:
   C++ template instantiation, for example, should always call the `BuildXXX`
   variant. Several notes on semantic analysis before we get into construction
   of the AST:

   - Your expression probably involves some types and some subexpressions.
     Make sure to fully check that those types, and the types of those
     subexpressions, meet your expectations. Add implicit conversions where
     necessary to make sure that all of the types line up exactly the way you
     want them. Write extensive tests to check that you're getting good
     diagnostics for mistakes and that you can use various forms of
     subexpressions with your expression.
   - When type-checking a type or subexpression, make sure to first check
     whether the type is "dependent" (`Type::isDependentType()`) or whether a
     subexpression is type-dependent (`Expr::isTypeDependent()`). If any of
     these return `true`, then you're inside a template and you can't do much
     type-checking now. That's normal, and your AST node (when you get there)
     will have to deal with this case. At this point, you can write tests that
     use your expression within templates, but don't try to instantiate the
     templates.
   - For each subexpression, be sure to call `Sema::CheckPlaceholderExpr()`
     to deal with "weird" expressions that don't behave well as subexpressions.
     Then, determine whether you need to perform lvalue-to-rvalue conversions
     (`Sema::DefaultLvalueConversions`) or the usual unary conversions
     (`Sema::UsualUnaryConversions`), for places where the subexpression is
     producing a value you intend to use.
   - Your `BuildXXX` function will probably just return `ExprError()` at
     this point, since you don't have an AST. That's perfectly fine, and
     shouldn't impact your testing.

3. Introduce an AST node for your new expression. This starts with declaring
   the node in `include/clang/Basic/StmtNodes.td` and creating a new class for your
   expression in the appropriate `include/clang/AST/Expr*.h` header. It's best to
   look at the class for a similar expression to get ideas, and there are some
   specific things to watch for:

   - If you need to allocate memory, use the `ASTContext` allocator to
     allocate memory. Never use raw `malloc` or `new`, and never hold any
     resources in an AST node, because the destructor of an AST node is never
     called.
   - Make sure that `getSourceRange()` covers the exact source range of your
     expression. This is needed for diagnostics and for IDE support.
   - Make sure that `children()` visits all of the subexpressions. This is
     important for a number of features (e.g., IDE support, C++ variadic
     templates). If you have sub-types, you'll also need to visit those
     sub-types in `RecursiveASTVisitor`.
   - Add printing support (`StmtPrinter.cpp`) for your expression.
   - Add profiling support (`StmtProfile.cpp`) for your AST node, noting the
     distinguishing (non-source location) characteristics of an instance of
     your expression. Omitting this step will lead to hard-to-diagnose
     failures regarding matching of template declarations.
   - Add serialization support (`ASTReaderStmt.cpp`, `ASTWriterStmt.cpp`)
     for your AST node.

4. Teach semantic analysis to build your AST node. At this point, you can wire
   up your `Sema::BuildXXX` function to actually create your AST. A few
   things to check at this point:

   - If your expression can construct a new C++ class or return a new
     Objective-C object, be sure to update and then call
     `Sema::MaybeBindToTemporary` for your just-created AST node to be sure
     that the object gets properly destructed. An easy way to test this is to
     return a C++ class with a private destructor: semantic analysis should
     flag an error here with the attempt to call the destructor.
   - Inspect the generated AST by printing it using `clang -cc1 -ast-print`,
     to make sure you're capturing all of the important information about how
     the AST was written.
   - Inspect the generated AST under `clang -cc1 -ast-dump` to verify that
     all of the types in the generated AST line up the way you want them.
     Remember that clients of the AST should never have to "think" to
     understand what's going on. For example, all implicit conversions should
     show up explicitly in the AST.
   - Write tests that use your expression as a subexpression of other,
     well-known expressions. Can you call a function using your expression as
     an argument? Can you use the ternary operator?

5. Teach code generation to create IR to your AST node. This step is the first
   (and only) that requires knowledge of LLVM IR. There are several things to
   keep in mind:

   - Code generation is separated into scalar/aggregate/complex and
     lvalue/rvalue paths, depending on what kind of result your expression
     produces. On occasion, this requires some careful factoring of code to
     avoid duplication.
   - `CodeGenFunction` contains functions `ConvertType` and
     `ConvertTypeForMem` that convert Clang's types (`clang::Type*` or
     `clang::QualType`) to LLVM types. Use the former for values, and the
     latter for memory locations: test with the C++ "`bool`" type to check
     this. If you find that you are having to use LLVM bitcasts to make the
     subexpressions of your expression have the type that your expression
     expects, STOP! Go fix semantic analysis and the AST so that you don't
     need these bitcasts.
   - The `CodeGenFunction` class has a number of helper functions to make
     certain operations easy, such as generating code to produce an lvalue or
     an rvalue, or to initialize a memory location with a given value. Prefer
     to use these functions rather than directly writing loads and stores,
     because these functions take care of some of the tricky details for you
     (e.g., for exceptions).
   - If your expression requires some special behavior in the event of an
     exception, look at the `push*Cleanup` functions in `CodeGenFunction`
     to introduce a cleanup. You shouldn't have to deal with
     exception-handling directly.
   - Testing is extremely important in IR generation. Use `clang -cc1
     -emit-llvm` and [FileCheck](https://llvm.org/docs/CommandGuide/FileCheck.html) to verify that you're
     generating the right IR.

6. Teach template instantiation how to cope with your AST node, which requires
   some fairly simple code:

   - Make sure that your expression's constructor properly computes the flags
     for type dependence (i.e., the type your expression produces can change
     from one instantiation to the next), value dependence (i.e., the constant
     value your expression produces can change from one instantiation to the
     next), instantiation dependence (i.e., a template parameter occurs
     anywhere in your expression), and whether your expression contains a
     parameter pack (for variadic templates). Often, computing these flags
     just means combining the results from the various types and
     subexpressions.
   - Add `TransformXXX` and `RebuildXXX` functions to the `TreeTransform`
     class template in `Sema`. `TransformXXX` should (recursively)
     transform all of the subexpressions and types within your expression,
     using `getDerived().TransformYYY`. If all of the subexpressions and
     types transform without error, it will then call the `RebuildXXX`
     function, which will in turn call `getSema().BuildXXX` to perform
     semantic analysis and build your expression.
   - To test template instantiation, take those tests you wrote to make sure
     that you were type checking with type-dependent expressions and dependent
     types (from step #2) and instantiate those templates with various types,
     some of which type-check and some that don't, and test the error messages
     in each case.

7. There are some "extras" that make other features work better. It's worth
   handling these extras to give your expression complete integration into
   Clang:

   - Add code completion support for your expression in
     `SemaCodeComplete.cpp`.
   - If your expression has types in it, or has any "interesting" features
     other than subexpressions, extend libclang's `CursorVisitor` to provide
     proper visitation for your expression, enabling various IDE features such
     as syntax highlighting, cross-referencing, and so on. The
     `c-index-test` helper program can be used to test these features.

### Testing

All functional changes to Clang should come with test coverage demonstrating
the change in behavior. There are four kinds of tests:

- Unit tests: such tests are placed in `clang/test/unittest`.
- Diagnostic tests: such tests ensures that only specific diagnostics are
  emitted at specific source lines. Those tests are using `-verify` mode of
  `-cc1`, which is described below in
  {ref}`"Verifying Diagnostics" <verifying-diagnostics>`. Additional
  provisions for tests for C++ defect reports are described in
  {ref}`"C++ Defect Report Tests" <cxx-defect-report-tests>` section.
- AST dump tests: such tests pass printable AST output to the
  [FileCheck](https://llvm.org/docs/CommandGuide/FileCheck.html) utility,
  which check presence of certain patterns (or lack of thereof).
- LLVM IR tests: in such tests, the LLVM IR output of Clang is checked, which
  is needed in cases when checking diagnostics is not sufficient (e.g. when
  testing exception handling or object lifetime). Such tests pass LLVM IR
  output to the
  [FileCheck](https://llvm.org/docs/CommandGuide/FileCheck.html) utility,
  which check the presence of certain IR patterns (or lack of thereof).

(verifying-diagnostics)=

#### Verifying Diagnostics

Clang `-cc1` supports the `-verify` command line option as a way to
validate diagnostic behavior. This option will use special comments, called
directives, within the test file to verify that expected diagnostics appear in
the correct source locations. If all of the expected diagnostics match the
actual output of Clang, then the invocation will return normally. If there are
discrepancies between the expected and actual output, Clang will emit detailed
information about which expected diagnostics were not seen or which unexpected
diagnostics were seen, etc. A complete example is:

```c++
// RUN: %clang_cc1 -verify %s
int A = B; // expected-error {{use of undeclared identifier 'B'}}
```

If the test is run and the expected error is emitted on the expected line, the
diagnostic verifier will pass. However, if the expected error does not appear
or appears in a different location than expected, or if additional diagnostics
appear, the diagnostic verifier will fail and emit information as to why.

##### Directive Syntax

Syntax description of the directives is the following:

```{eval-rst}
.. parsed-literal::

  `directive`
      `prefix` ``-`` `diagnostic-kind` `regex-match`:sub:`opt` `diagnostic-loc`:sub:`opt` `quantifier`:sub:`opt` ``{{`` `delimiter-open`:sub:`opt` `diagnostic-text` `delimiter-close`:sub:`opt` ``}}``

  `diagnostic-kind`
      ``error``
      ``warning``
      ``note``
      ``remark``

  `regex-match`
      ``-re``

  `diagnostic-loc`
      ``@+`` `number`
      ``@-`` `number`
      ``@`` `line`
      ``@`` `file-path` ``:`` `line`
      ``@*``
      ``@*:*``
      ``@#`` `marker-name`

  `line`
      ``*``
      `number`

  `quantifier`
      ``+``
      `number` ``+``
      `number` ``-`` `number`

  `delimiter-open`
      ``{`` `delimiter-open`:sub:`opt`

  `delimiter-close`
      ``}`` `delimiter-close`:sub:`opt`

  `number`
      `digit` `number`:sub:`opt`

  `digit`
      ``0`` ``1`` ``2`` ``3`` ``4`` ``5`` ``6`` ``7`` ``8`` ``9``
```

Where:

- `prefix` is "expected" or a custom string
  ({ref}`Custom Prefixes <custom-prefixes>`).
- `delimiter-open` and `delimiter-close` have to have the same length
  ({ref}`Diagnostic Text <diagnostic-text>`).
- `file-path` is relative or absolte path to a file
  ({ref}`Diagnostic Location <diagnostic-location>`).
- `marker-name` is name of the marker placed somewhere in the source file
  ({ref}`Diagnostic Location <diagnostic-location>`).
- `diagnostic-text` is text of the expected diagnostic
  ({ref}`Diagnostic Text <diagnostic-text>`).

Examples:

- `// expected-note {{declared here}}`
  One note `declared here` has to be issued on the same line as the
  directive.
- `// expected-note {{{declared here}}}`
  Same as above, but uses additional delimiters for diagnostic text.
- `// expected-error@+1 0-1 {{expected identifier or '{'}}`
  Zero or one error `expected identifier or '{'` has to be issued on the next
  line after the directive zero or one time.
- `// cxx98-17-warning@#func-decl + {{target exception specification is not superset of source}}`
  One or more warnings
  `target exception specification is not superset of source` has to be issued
  on the line that has `// #func-decl` comment one or more times when CLI
  option `-verify=cxx98-17` is passed.
- `// expected-note@* 1 {{file entered}}`
  One note `file entered` has to be issued somewhere in the source file.
- `// expected-note@decls.h:2 {{previous declaration is here}}`
  One note `previous declaration is here` has to be issued at `decl.h`
  line 2.
- `// cxx11-17-error-re@-1 {{no matching constructor for initialization of 'A' (aka '(lambda at {{.+}})')}}`
  One error
  `no matching constructor for initialization of 'A' (aka '(lambda at <source location>)')`
  (ignoring the exact source location) has to be issued on the previous line
  before the directive when CLI option `-verify=cxx11-17` is passed.

(custom-prefixes)=

##### Custom Prefixes

The `-verify` command optionally accepts a comma-delimited list of one or
more verification prefixes that can be used to craft those special comments.
Each prefix must start with a letter and contain only alphanumeric characters,
hyphens, and underscores. `-verify` by itself is equivalent to
`-verify=expected`, meaning that special comments will start with
`expected`. Using different prefixes makes it easier to have separate
`RUN:` lines in the same test file which result in differing diagnostic
behavior. For example:

```c++
// RUN: %clang_cc1 -verify=foo,bar %s

int A = B; // foo-error {{use of undeclared identifier 'B'}}
int C = D; // bar-error {{use of undeclared identifier 'D'}}
int E = F; // expected-error {{use of undeclared identifier 'F'}}
```

The verifier will recognize `foo-error` and `bar-error` as special comments
but will not recognize `expected-error` as one because the `-verify` line
does not contain that as a prefix. Thus, this test would fail verification
because an unexpected diagnostic would appear on the declaration of `E`.

Multiple occurrences accumulate prefixes. For example,
`-verify -verify=foo,bar -verify=baz` is equivalent to
`-verify=expected,foo,bar,baz`.

(diagnostic-location)=

#### Diagnostic Location

Indicating that a line expects an error or a warning is easy. Put a comment
on the line that has the diagnostic, use
`expected-{error,warning,remark,note}` to tag if it's an expected error,
warning, remark, or note (respectively), and place the expected text between
`{{` and `}}` markers. The full text doesn't have to be included, only
enough to ensure that the correct diagnostic was emitted. (Note: full text
should be included in test cases unless there is a compelling reason to use
truncated text instead.)

For a full description of the matching behavior, including more complex
matching scenarios, see {ref}`"Diagnostic text" <diagnostic-text>` below.

Here's an example of the most commonly used way to specify expected
diagnostics:

```c++
int A = B; // expected-error {{use of undeclared identifier 'B'}}
```

You can place as many diagnostics on one line as you wish. To make the code
more readable, you can use backslashes to separate out the diagnostics into
multiple lines.

Alternatively, it is possible to specify the line on which the diagnostic
should appear by appending `@<line>` to `expected-<type>`, for example:

```c++
#warning some text
// expected-warning@10 {{some text}}
```

The line number may be absolute (as above), or relative to the current line by
prefixing the number with either `+` or `-`.

If the diagnostic is generated in a separate file, for example in a shared
header file, it may be beneficial to be able to declare the file in which the
diagnostic will appear, rather than placing the `expected-*` directive in the
actual file itself. This can be done using the following syntax:

```c++
// expected-error@path/include.h:15 {{error message}}
```

The path can be absolute or relative and the same search paths will be used as
for `#include` directives. The line number in an external file may be
substituted with `*` meaning that any line number will match (useful where
the included file is, for example, a system header where the actual line number
may change and is not critical).

As an alternative to specifying a fixed line number, the location of a
diagnostic can instead be indicated by a marker of the form `#<marker>`.
Markers are specified by including them in a comment, and then referenced by
appending the marker to the diagnostic with `@#<marker>`, as with:

```c++
#warning some text  // #1
// ... other code ...
// expected-warning@#1 {{some text}}
```

The name of a marker used in a directive must be unique within the compilation.

##### Quantifiers

The simple syntax above allows each specification to match exactly one
diagnostic. You can use the extended syntax to customize this. The extended
syntax is `expected-<type> <n> {{diag text}}`, where `<type>` is one of
`error`, `warning`, `remark`, or `note`, and `<n>` is a positive
integer. This allows the diagnostic to appear as many times as specified. For
example:

```c++
void f(); // expected-note 2 {{previous declaration is here}}
```

Where the diagnostic is expected to occur a minimum number of times, this can
be specified by appending a `+` to the number. For example:

```c++
void f(); // expected-note 0+ {{previous declaration is here}}
void g(); // expected-note 1+ {{previous declaration is here}}
```

In the first example, the diagnostic becomes optional, i.e., it will be
swallowed if it occurs, but will not generate an error if it does not occur. In
the second example, the diagnostic must occur at least once. As a short-hand,
"one or more" can be specified simply by `+`. For example:

```c++
void g(); // expected-note + {{previous declaration is here}}
```

A range can also be specified by `<n>-<m>`. For example:

```c++
void f(); // expected-note 0-1 {{previous declaration is here}}
```

In this example, the diagnostic may appear only once, if at all.

(diagnostic-text)=

##### Diagnostic Text

The default matching mode is simple string, which looks for the expected text
that appears between the first `{{` and `}}` pair of the comment. The string is
interpreted just as-is, with one exception: the sequence `\n` is converted to a
single newline character. This mode matches the emitted diagnostic when the
text appears as a substring at any position of the emitted message.

To enable matching against desired strings that contain `}}` or `{{`, the
string-mode parser accepts opening delimiters of more than two curly braces,
like `{{{`. It then looks for a closing delimiter of equal "width" (i.e `}}}`).
For example:

```c++
// expected-note {{{evaluates to '{{2, 3, 4}} == {0, 3, 4}'}}}
```

The intent is to allow the delimiter to be wider than the longest `{` or `}`
brace sequence in the content, so that if your expected text contains `{{{`
(three braces) it may be delimited with `{{{{` (four braces), and so on.

Regex matching mode may be selected by appending `-re` to the diagnostic type
and including regexes wrapped in double curly braces (`{{` and `}}`) in the
directive, such as:

```text
expected-error-re {{format specifies type 'wchar_t **' (aka '{{.+}}')}}
```

Examples matching error: "variable has incomplete type 'struct s'"

```c++
// expected-error {{variable has incomplete type 'struct s'}}
// expected-error {{variable has incomplete type}}
// expected-error {{{variable has incomplete type}}}
// expected-error {{{{variable has incomplete type}}}}

// expected-error-re {{variable has type 'struct {{.}}'}}
// expected-error-re {{variable has type 'struct {{.*}}'}}
// expected-error-re {{variable has type 'struct {{(.*)}}'}}
// expected-error-re {{variable has type 'struct{{[[:space:]](.*)}}'}}
```

##### Verifying the Directives

Clang `-cc1` also has `-verify-directives` mode, which can be enabled
alongside `-verify` to place additional restrictions on directives,
and strives to improve readability of the expected compiler output
for reviewers and future readers, but makes it a bit harder to write the test:

- Diagnostic text specified in a directive has to be a full match.
- Lexical order of directives has to match the order in which diagnostics are
  emitted.
- Each directive has to match exactly one diagnostic.
- Wildcards (`*`) are not allowed in the diagnostic location.

Most of the tests can be adapted to use this mode, but for some tests
it's not possible. Typical problems and their solutions are listed below.

- **Diagnostic is issued only sometimes.**
  The cause of variance needs to be identified and captured. Typically it is
  either a compiler option like language mode, in which case an additional
  custom prefix should be sufficient, or platform, in which case a triple has
  to be explicitly passed in command-line arguments.
- **Template instantiations at the end of translation unit.**
  Instantiations at the end of the TU cause associated diagnostics to appear
  too late. Instantiations need to happen before the next directive, and when
  it is possible, it still takes some creativity to achieve, especially in
  C++98 mode. Typical solutions include explicit template instantiations,
  manifestly constant-evaluated expressions, `enable_if`, and removing
  template parameters altogether.
- **Analysis-based warnings.** Some warnings, like `-Wunused`, are based
  on CFG analysis and are emitted later than e.g. parser would emit them,
  because some lookahead is required to collect all the necessary information
  for such analysis. Not much can be done in this case.
- **Lambdas.** When lambda is mentioned in diagnostic message, it is identified
  by its source location, which is typically not salient for the test,
  and would make it overspecified. In this case regex match can be used to skip
  over source location.

(cxx-defect-report-tests)=

#### C++ Defect Report Tests

C++ Defect Report tests are placed in `clang/test/CXX/drs` directory, which
consists of two types of files:

- files where tests are grouped by 100 by issue number, e.g. `cwg15xx.cpp`
  ("big files");
- files with individual tests or smaller groups of tests, e.g. `cwg177x.cpp`
  or `cwg787.cpp`.

C++ defect report tests are run in all language modes available via `-std=`,
except for modes with GNU extensions and `c++03`, as it is synonymous to
`c++98`. Exceptions, pedantic errors, and `-verify-directives` are enabled.

Big files are where most of the tests end up being placed to save on process
startup cost during test runs. Big files also serve as an index of tests:
even if test is placed in its individual file, it's still mentioned in the
big file where this test would be placed otherwise. Big files need all tests
to work with the same set of compiler options specified in RUN lines, but
sometimes tests need special provisions, in which case they should be placed
in their own file. Typical reasons for that include:

- **Test is checking AST dump or LLVM IR.** We don't yet know how
  to concatenate FileCheck directives from multiple tests into a single file
  without avoiding test interference.
- **Test is not compatible with `-verify-directives`.** For instance, some
  tests can't be rewritten to prevent instantiations at the end of TU.
- **Test needs C++20 modules.** Such tests require special RUN lines to compile
  modules in the right order.
- **Test prevents compiler from checking subsequent tests.** In some cases
  that involve templates Clang refuses to recover from expected errors and will
  skip over expected errors in subsequent tests.

C++ defect report tests make heavy use of markers. Marker names need to
be prefixed with `cwgNNN-`, where NNN is number of the core issue being
tested. This is especially needed in big files, because all markers share
the same namespace.

Some diagnostics are expected only in certain language modes. This in handled
in two parts. First, C++ defect report tests share a common pool of custom
prefixes:

- `expected` for diagnostics issued in all language modes;
- `cxxNN` (e.g. `cxx98`) for diagnostics issued only in one language mode;
- `since-cxxNN` (e.g. `since-cxx11`) for diagnostics that are issued
  in a certain language mode and all newer language modes;
- `cxxNN-MM` (e.g. `cxx98-14`) for diagnostics that appear in all language
  modes within a certain range.

Second, parts of tests that test features not universally available in all
language modes are guarded with `#if __cplusplus`. Prefixes of directives
in such parts need to reflect the latest `#if __cplusplus` guard to make
tests require less context to understand, even though this is not strictly
necessary to make the test work:

```c++
#if __cplusplus >= 201103L
enum : int { a };
enum class { b };
// since-cxx11-error@-1 {{scoped enumeration requires a name}}
#endif
```

On top of `-verify-directives`, C++ defect report tests use the following
conventions to make it easier to reconstruct compiler output while looking at
directives:

- Errors and warnings are placed on the next line after the line they are
  expecting a diagnostic at, and at the same indentation.

  ```c++
  namespace X::Y {}
  // cxx98-14-error@-1 {{nested namespace definition is a C++17 extension; define each namespace separately}}
  namespace X {
    namespace X::Y {}
    // cxx98-14-error@-1 {{nested namespace definition is a C++17 extension; define each namespace separately}}
  }
  ```

- Directives that are placed right after the line they are expecting
  a diagnostic at use relative offsets (`@-1`, `@-2`, and so on),
  as long as it's obvious that all relative offsets point to the same line.
  If there is a feeling readers would start counting lines to make sure
  they know where the diagnostic is expected, markers should be used instead.

  ```c++
  bool b = (void(*)(S, S))operator- < (void(*)(S, S))operator-;
  // cxx98-17-warning@-1 {{ordered comparison of function pointers ('void (*)(S, S)' and 'void (*)(S, S)')}}
  // cxx20-23-error@-2 {{expected '>'}}
  //   cxx20-23-note@-3 {{to match this '<'}}

  int *q = new int[T()]; // #cwg299-q
  // cxx98-11-error@#cwg299-q {{ambiguous conversion of array size expression of type 'T' to an integral or enumeration type}}
  //   cxx98-11-note@#cwg299-int {{conversion to integral type 'int' declared here}}
  //   cxx98-11-note@#cwg299-ushort {{conversion to integral type 'unsigned short' declared here}}
  // since-cxx14-error-re@#cwg299-q {{conversion from 'T' to '__size_t' (aka 'unsigned {{long long|long|int}}') is ambiguous}}
  //   since-cxx14-note@#cwg299-int {{candidate function}}
  //   since-cxx14-note@#cwg299-ushort {{candidate function}}
  ```

- Notes and remarks are indented by two spaces relative to the error or warning
  they are attached to.

  ```c++
  void (*p)() throw(int) = &f; // #cwg92-p
  // since-cxx17-error@#cwg92-p {{ISO C++17 does not allow dynamic exception specifications}}
  //   since-cxx17-note@#cwg92-p {{use 'noexcept(false)' instead}}
  // cxx98-14-error@#cwg92-p {{target exception specification is not superset of source}}
  ```

## Feature Test Macros

Clang implements several ways to test whether a feature is supported or not.
Some of these feature tests are standardized, like `__has_cpp_attribute` or
`__cpp_lambdas`, while others are Clang extensions, like `__has_builtin`.
The common theme among all the various feature tests is that they are a utility
to tell users that we think a particular feature is complete. However,
completeness is a difficult property to define because features may still have
lingering bugs, may only work on some targets, etc. We use the following
criteria when deciding whether to expose a feature test macro (or particular
result value for the feature test):

- Are there known issues where we reject valid code that should be accepted?
- Are there known issues where we accept invalid code that should be rejected?
- Are there known crashes, failed assertions, or miscompilations?
- Are there known issues on a particular relevant target?

If the answer to any of these is "yes", the feature test macro should either
not be defined or there should be very strong rationale for why the issues
should not prevent defining it. Note, it is acceptable to define the feature
test macro on a per-target basis if needed.

When in doubt, being conservative is better than being aggressive. If we don't
claim support for the feature but it does useful things, users can still use it
and provide us with useful feedback on what is missing. But if we claim support
for a feature that has significant bugs, we've eliminated most of the utility
of having a feature testing macro at all because users are then forced to test
what compiler version is in use to get a more accurate answer.

The status reported by the feature test macro should always be reflected in the
language support page for the corresponding feature ([C++](https://clang.llvm.org/cxx_status.html), [C](https://clang.llvm.org/c_status.html)) if applicable. This page can give
more nuanced information to the user as well, such as claiming partial support
for a feature and specifying details as to what remains to be done.

---

### Clang Docs IntroductionToTheClangAST (`clang/docs/IntroductionToTheClangAST.md`)

# Introduction to the Clang AST

This document gives a gentle introduction to the mysteries of the Clang
AST. It is targeted at developers who either want to contribute to
Clang, or use tools that work based on Clang's AST, like the AST
matchers.

```{raw} html
<center><iframe width="560" height="315" src="https://www.youtube.com/embed/VqCkCDFLSsc?vq=hd720" frameborder="0" allowfullscreen></iframe></center>
```

[Slides](https://llvm.org/devmtg/2013-04/klimek-slides.pdf)

## Introduction

Clang's AST is different from ASTs produced by some other compilers in
that it closely resembles both the written C++ code and the C++
standard. For example, parenthesis expressions and compile time
constants are available in an unreduced form in the AST. This makes
Clang's AST a good fit for refactoring tools.

Documentation for all Clang AST nodes is available via the generated
[Doxygen](https://clang.llvm.org/doxygen). The doxygen online
documentation is also indexed by your favorite search engine, which will
make a search for clang and the AST node's class name usually turn up
the doxygen of the class you're looking for (for example, search for:
clang ParenExpr).

## Examining the AST

A good way to familiarize yourself with the Clang AST is to actually look
at it on some simple example code. Clang has a builtin AST-dump mode,
which can be enabled with the flag `-ast-dump`.

Let's look at a simple example AST:

```
$ cat test.cc
int f(int x) {
  int result = (x / 42);
  return result;
}

# Clang by default is a frontend for many tools; -Xclang is used to pass
# options directly to the C++ frontend.
$ clang -Xclang -ast-dump -fsyntax-only test.cc
TranslationUnitDecl 0x5aea0d0 <<invalid sloc>>
... cutting out internal declarations of clang ...
`-FunctionDecl 0x5aeab50 <test.cc:1:1, line:4:1> f 'int (int)'
  |-ParmVarDecl 0x5aeaa90 <line:1:7, col:11> x 'int'
  `-CompoundStmt 0x5aead88 <col:14, line:4:1>
    |-DeclStmt 0x5aead10 <line:2:3, col:24>
    | `-VarDecl 0x5aeac10 <col:3, col:23> result 'int'
    |   `-ParenExpr 0x5aeacf0 <col:16, col:23> 'int'
    |     `-BinaryOperator 0x5aeacc8 <col:17, col:21> 'int' '/'
    |       |-ImplicitCastExpr 0x5aeacb0 <col:17> 'int' <LValueToRValue>
    |       | `-DeclRefExpr 0x5aeac68 <col:17> 'int' lvalue ParmVar 0x5aeaa90 'x' 'int'
    |       `-IntegerLiteral 0x5aeac90 <col:21> 'int' 42
    `-ReturnStmt 0x5aead68 <line:3:3, col:10>
      `-ImplicitCastExpr 0x5aead50 <col:10> 'int' <LValueToRValue>
        `-DeclRefExpr 0x5aead28 <col:10> 'int' lvalue Var 0x5aeac10 'result' 'int'
```

The toplevel declaration in
a translation unit is always the [translation unit
declaration](https://clang.llvm.org/doxygen/classclang_1_1TranslationUnitDecl.html).
In this example, our first user written declaration is the [function
declaration](https://clang.llvm.org/doxygen/classclang_1_1FunctionDecl.html)
of "`f`". The body of "`f`" is a [compound
statement](https://clang.llvm.org/doxygen/classclang_1_1CompoundStmt.html),
whose child nodes are a [declaration
statement](https://clang.llvm.org/doxygen/classclang_1_1DeclStmt.html)
that declares our result variable, and the [return
statement](https://clang.llvm.org/doxygen/classclang_1_1ReturnStmt.html).

## AST Context

All information about the AST for a translation unit is bundled up in
the class
[ASTContext](https://clang.llvm.org/doxygen/classclang_1_1ASTContext.html).
It allows traversal of the whole translation unit starting from
[getTranslationUnitDecl](https://clang.llvm.org/doxygen/classclang_1_1ASTContext.html#abd909fb01ef10cfd0244832a67b1dd64),
or to access Clang's [table of
identifiers](https://clang.llvm.org/doxygen/classclang_1_1ASTContext.html#a4f95adb9958e22fbe55212ae6482feb4)
for the parsed translation unit.

## AST Nodes

Clang's AST nodes are modeled on a class hierarchy that does not have a
common ancestor. Instead, there are multiple larger hierarchies for
basic node types like
[Decl](https://clang.llvm.org/doxygen/classclang_1_1Decl.html) and
[Stmt](https://clang.llvm.org/doxygen/classclang_1_1Stmt.html). Many
important AST nodes derive from
[Type](https://clang.llvm.org/doxygen/classclang_1_1Type.html),
[Decl](https://clang.llvm.org/doxygen/classclang_1_1Decl.html),
[DeclContext](https://clang.llvm.org/doxygen/classclang_1_1DeclContext.html)
or [Stmt](https://clang.llvm.org/doxygen/classclang_1_1Stmt.html), with
some classes deriving from both Decl and DeclContext.

There are also a multitude of nodes in the AST that are not part of a
larger hierarchy, and are only reachable from specific other nodes, like
[CXXBaseSpecifier](https://clang.llvm.org/doxygen/classclang_1_1CXXBaseSpecifier.html).

Thus, to traverse the full AST, one starts from the
[TranslationUnitDecl](https://clang.llvm.org/doxygen/classclang_1_1TranslationUnitDecl.html)
and then recursively traverses everything that can be reached from that
node - this information has to be encoded for each specific node type.
This algorithm is encoded in the
[RecursiveASTVisitor](https://clang.llvm.org/doxygen/classclang_1_1RecursiveASTVisitor.html).
See the [RecursiveASTVisitor tutorial](RAVFrontendAction.md).

The two most basic nodes in the Clang AST are statements
([Stmt](https://clang.llvm.org/doxygen/classclang_1_1Stmt.html)) and
declarations
([Decl](https://clang.llvm.org/doxygen/classclang_1_1Decl.html)). Note
that expressions
([Expr](https://clang.llvm.org/doxygen/classclang_1_1Expr.html)) are
also statements in Clang's AST.

---

### Clang Docs ItaniumMangleAbiTags (`clang/docs/ItaniumMangleAbiTags.md`)

# ABI tags

## Introduction

This text tries to describe gcc semantic for mangling "abi_tag" attributes
described in <https://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Attributes.html>

There is no guarantee the following rules are correct, complete or make sense
in any way as they were determined empirically by experiments with gcc5.

## Declaration

ABI tags are declared in an abi_tag attribute and can be applied to a
function, variable, class or inline namespace declaration. The attribute takes
one or more strings (called tags); the order does not matter.

See <https://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Attributes.html> for
details.

Tags on an inline namespace are called "implicit tags", all other tags are
"explicit tags".

## Mangling

All tags that are "active" on an `<unqualified-name>` are emitted after the
`<unqualified-name>`, before `<template-args>` or `<discriminator>`, and are
part of the same `<substitution>` the `<unqualified-name>` is.

They are mangled as:

```bnf
<abi-tags> ::= <abi-tag>*   # sort by name
<abi-tag> ::= B <tag source-name>
```

Example:

```c++
__attribute__((abi_tag("test")))
void Func();
// gets mangled as: _Z4FuncB4testv (prettified as `Func[abi:test]()`)
```

## Active tags

A namespace does not have any active tags. For types (class / struct / union /
enum), the explicit tags are the active tags.

For variables and functions, the active tags are the explicit tags plus any
"required tags" which are not in the "available tags" set:

```bnf
derived-tags := (required-tags - available-tags)
active-tags := explicit-tags + derived-tags
```

## Required tags for a function

If a function is used as a local scope for another name, and is part of
another function as local scope, it doesn't have any required tags.

If a function is used as a local scope for a guard variable name, it doesn't
have any required tags.

Otherwise the function requires any implicit or explicit tag used in the name
for the return type.

Example:

```c++
namespace A {
  inline namespace B __attribute__((abi_tag)) {
    struct C { int x; };
  }
}

A::C foo(); // gets mangled as: _Z3fooB1Bv (prettified as `foo[abi:B]()`)
```

## Required tags for a variable

A variable requires any implicit or explicit tag used in its type.

## Available tags

All tags used in the prefix and in the template arguments for a name are
available. Also, for functions, all tags from the `<bare-function-type>`
(which might include the return type for template functions) are available.

For `<local-name>`s all active tags used in the local part
(`<function-encoding>`) are available, but not implicit tags which were not
active.

Implicit and explicit tags used in the `<unqualified-name>` for a function (as
in the type of a cast operator) are NOT available.

Example: a cast operator to std::string (which is
`std::__cxx11::basic_string<...>`) will use 'cxx11' as an active tag, as it is
required from the return type `std::string` but not available.

---

### Clang Docs JSONCompilationDatabase (`clang/docs/JSONCompilationDatabase.md`)

# JSON Compilation Database Format Specification

This document describes a format for specifying how to replay single
compilations independently of the build system.

## Background

Tools based on the C++ Abstract Syntax Tree need full information how to
parse a translation unit. Usually this information is implicitly
available in the build system, but running tools as part of the build
system is not necessarily the best solution:

- Build systems are inherently change driven, so running multiple tools
  over the same code base without changing the code does not fit into
  the architecture of many build systems.
- Figuring out whether things have changed is often an IO bound
  process; this makes it hard to build low latency end user tools based
  on the build system.
- Build systems are inherently sequential in the build graph, for
  example due to generated source code. While tools that run
  independently of the build still need the generated source code to
  exist, running tools multiple times over unchanging source does not
  require serialization of the runs according to the build dependency
  graph.

## Supported Systems

Clang has the ability to generate compilation database fragments via
`-MJ argument <clang -MJ\<arg>>`. You can concatenate those
fragments together between `[` and `]` to create a compilation database.

Currently [CMake](https://cmake.org) (since 2.8.5) supports generation
of compilation databases for Unix Makefile builds (Ninja builds in the
works) with the option `CMAKE_EXPORT_COMPILE_COMMANDS`.

For projects on Linux, there is an alternative to intercept compiler
calls with a tool called [Bear](https://github.com/rizsotto/Bear).

[Bazel](https://bazel.build) can export a compilation database via
[this extractor extension](https://github.com/hedronvision/bazel-compile-commands-extractor).
Bazel is otherwise resistant to Bear and other compiler-intercept
techniques.

Clang's tooling interface supports reading compilation databases; see
the {doc}`LibTooling documentation <LibTooling>`. libclang and its
Python bindings also support this (since clang 3.2); see
[CXCompilationDatabase.h](https://clang.llvm.org/doxygen/group__COMPILATIONDB.html).

## Format

A compilation database is a JSON file, which consists of an array of
"command objects", where each command object specifies one way a
translation unit is compiled in the project.

Each command object contains the translation unit's main file, the
working directory of the compile run and the actual compile command.

Example:

```
[
  { "directory": "/home/user/llvm/build",
    "arguments": ["/usr/bin/clang++", "-Irelative", "-DSOMEDEF=With spaces, quotes and \\-es.", "-c", "-o", "file.o", "file.cc"],
    "file": "file.cc" },

  { "directory": "/home/user/llvm/build",
    "command": "/usr/bin/clang++ -Irelative -DSOMEDEF=\"With spaces, quotes and \\-es.\" -c -o file.o file.cc",
    "file": "file2.cc" },

  ...
]
```

The contracts for each field in the command object are:

- **directory:** The working directory of the compilation. All paths
  specified in the **command** or **file** fields must be either
  absolute or relative to this directory.

- **file:** The main translation unit source processed by this
  compilation step. This is used by tools as the key into the
  compilation database. There can be multiple command objects for the
  same file, for example if the same source file is compiled with
  different configurations.

- **arguments:** The compile command argv as list of strings.
  This should run the compilation step for the translation unit `file`.
  `arguments[0]` should be the executable name, such as `clang++`.
  Arguments should not be escaped, but ready to pass to `execvp()`.

- **command:** The compile command as a single shell-escaped string.
  Arguments may be shell quoted and escaped following platform conventions,
  with '`"`' and '`\`' being the only special characters. Shell expansion
  is not supported.

  Either **arguments** or **command** is required. **arguments** is preferred,
  as shell (un)escaping is a possible source of errors.

- **output:** The name of the output created by this compilation step.
  This field is optional. It can be used to distinguish different processing
  modes of the same input file.

## Build System Integration

The convention is to name the file compile_commands.json and put it at
the top of the build directory. Clang tools are pointed to the top of
the build directory to detect the file and use the compilation database
to parse C++ code in the source tree.

## Alternatives

For simple projects, Clang tools also recognize a `compile_flags.txt` file.
This should contain one argument per line. The same flags will be used to
compile any file.

Example:

```
-xc++
-I
libwidget/include/
```

Here `-I libwidget/include` is two arguments, and so becomes two lines.
Paths are relative to the directory containing `compile_flags.txt`.

---

### Clang Docs LLVMExceptionHandlingCodeGen (`clang/docs/LLVMExceptionHandlingCodeGen.md`)

# LLVM IR Generation for EH and Cleanups


## Overview

This document describes how Clang's LLVM IR generation represents exception
handling (EH) and C++ cleanups. It focuses on the data structures and control
flow patterns used to model normal and exceptional exits, and it outlines how
the generated IR differs across common ABI models.

For details on the LLVM IR representation of exception handling, see
[LLVM Exception Handling](https://llvm.org/docs/ExceptionHandling.html).

## Core Model

EH and cleanup handling is centered around an `EHScopeStack` that records
nested scopes for:

- **Cleanups**, which run on normal control flow, exceptional control flow, or
  both. These are used for destructors, full-expression cleanups, and other
  scope-exit actions.
- **Catch scopes**, which represent `try`/`catch` handlers.
- **Filter scopes**, used to model dynamic exception specifications and some
  platform-specific filters.
- **Terminate scopes**, used for `noexcept` and similar termination paths.

Each cleanup is a small object with an `Emit` method. When a cleanup scope is
popped, the IR generator decides whether it must materialize a normal cleanup
block (for fallthrough, branch-through, or unresolved `goto` fixups) and/or an
EH cleanup entry (when exceptional control flow can reach the cleanup). This
results in a flattened CFG where cleanup lifetime is represented by the blocks
and edges that flow into those blocks.

## Key Components

The LLVM IR generation for EH and cleanups is spread across several core
components:

- `CodeGenModule` owns module-wide state such as the LLVM module, target
  information, and the selected EH personality function. It provides access to
  ABI helpers via `CGCXXABI` and target-specific hooks.
- `CodeGenFunction` manages per-function state and IR building. It owns the
  `EHScopeStack`, tracks the current insertion point, and emits blocks, calls,
  and branches. Most cleanup and EH control flow is built here.
- `EHScopeStack` is the central stack of scopes used to model EH and cleanup
  semantics. It stores `EHCleanupScope` entries for cleanups, along with
  `EHCatchScope`, `EHFilterScope`, and `EHTerminateScope` for handlers and
  termination logic.
- `EHCleanupScope` stores the cleanup object plus state data (active flags,
  fixup depth, and enclosing scope links). When a cleanup scope is popped,
  `CodeGenFunction` decides whether to emit a normal cleanup block, an EH
  cleanup entry, or both.
- Cleanup emission helpers implement the mechanics of branching through
  cleanups, threading fixups, and emitting cleanup blocks.
- Exception emission helpers implement landing pads, dispatch blocks,
  personality selection, and helper routines for try/catch, filters, and
  terminate handling.
- `CGCXXABI` (and its ABI-specific implementations such as
  `ItaniumCXXABI` and `MicrosoftCXXABI`) provide ABI-specific lowering for
  throws, catch handling, and destructor emission details.
- The cleanup and exception handling code generation is driven by the flow of
  `CodeGenFunction` and its helper classes traversing the AST to emit IR for
  C++ expressions, classes, and statements.

AST traversal in `CodeGenFunction` emits code and pushes cleanups or EH scopes,
`EHScopeStack` records scope nesting, cleanup and exception helpers materialize
the CFG as scopes are popped, and `CGCXXABI` supplies ABI-specific details for
landing pads or funclets.

## Cleanup Destination Routing

When multiple control flow exits (`return`, `break`, `continue`,
fallthrough) pass through the same cleanup, the generated IR shares a single
cleanup block among them. Before entering the cleanup, each exit path stores a
unique index into a "cleanup destination" slot. After the cleanup code runs, a
`switch` instruction loads this index and dispatches to the appropriate final
destination. This avoids duplicating cleanup code for each exit while preserving
correct control flow.

For example, if a function has both a `return` and a `break` that exit
through the same destructor cleanup, both paths branch to the shared cleanup
block after storing their respective destination indices. The cleanup epilogue
then switches on the stored index to reach either the return block or the
loop-exit block.

When only a single exit passes through a cleanup (the common case), the switch
is unnecessary and the cleanup block branches directly to its sole destination.

### Branch Fixups for Forward Gotos

A `goto` statement that jumps forward to a label not yet seen poses a special
problem. The destination's enclosing cleanup scope is unknown at the point the
`goto` is emitted. This is handled by emitting an optimistic branch and
recording a "fixup." When the cleanup scope is later popped, any recorded fixups
are resolved by rewriting the branch to thread through the cleanup block and
adding the destination to the cleanup's switch.

## Exceptional Cleanups and EH Dispatch

Exceptional exits (`throw`, `invoke` unwinds) are routed through EH cleanup
entries, which are reached via a landing pad or a funclet dispatch block,
depending on the target ABI.

For Itanium-style EH (such as is used on x86-64 Linux), the IR uses `invoke`
to call potentially-throwing operations and a `landingpad` instruction to
capture the exception and selector values. The landing pad aggregates any
catch and cleanup clauses for the current scope, and branches to a dispatch
block that compares the selector to type IDs and jumps to the appropriate
handler.

For Windows, LLVM IR uses funclet-style EH: `catchswitch` and `catchpad` for
handlers, and `cleanuppad` for cleanups, with `catchret` and `cleanupret`
edges to resume normal flow. The personality function determines how these pads
are interpreted by the backend.

## Personality and ABI Selection

Each function with exception handling constructs is associated with a
personality function (e.g. \_\_gxx_personality_v0 for C++ on Linux). The
personality function determines the ABI-specifc EH behavior of the
function. The IR generation selects a personality function based on language
options and the target ABI (e.g., Itanium, MSVC SEH, SJLJ, Wasm EH). This
decision affects:

- Whether the IR uses landing pads or funclet pads.
- The shape of dispatch logic for catch and filter scopes.
- How termination or rethrow paths are modeled.
- Whether certain helper functions such as exception filters must be outlined.

Because the personality choice is made during IR generation, the CFG shape
directly reflects ABI-specific details.

## Example: Array of Objects with Throwing Constructor

Consider:

```c++
class MyClass {
public:
  MyClass(); // may throw
  ~MyClass();
};
void doSomething(); // may throw
void f() {
  MyClass arr[4];
  doSomething();
}
```

### High-level behavior

- Construction of `arr` proceeds element-by-element. If an element constructor
  throws, destructors must run for any elements that were successfully
  constructed before the throw in reverse order of construction.
- After full construction, the call to `doSomething` may throw, in which case
  the destructors for all constructed elements must run, in reverse order.
- On normal exit, destructors for all elements run in reverse order.

### Codegen flow and key components

- The surrounding compound statement enters a `CodeGenFunction::LexicalScope`,
  which is a `RunCleanupsScope` and is responsible for popping local cleanups
  at the end of the block.
- `CodeGenFunction::EmitDecl` routes the local variable to
  `CodeGenFunction::EmitVarDecl` and then `CodeGenFunction::EmitAutoVarDecl`,
  which in turn calls `EmitAutoVarAlloca`, `EmitAutoVarInit`, and
  `EmitAutoVarCleanups`.
- `CodeGenFunction::EmitCXXAggrConstructorCall` emits the array constructor
  loop. While emitting the loop body, it enters a `RunCleanupsScope` and uses
  `CodeGenFunction::pushRegularPartialArrayCleanup` to register a
  cleanup before calling `CodeGenFunction::EmitCXXConstructorCall` for one
  element in the loop iteration. If this constructor were to throw an exception,
  the cleanup handler would destroy the previously constructed elements in
  reverse order.
- `CodeGenFunction::EmitAutoVarCleanups` calls `emitAutoVarTypeCleanup`,
  which ultimately registers a `DestroyObject` cleanup via
  `CodeGenFunction::pushDestroy` / `pushFullExprCleanup` for the full-array
  destructor path.
- `DestroyObject` uses `CodeGenFunction::destroyCXXObject`, which emits the
  actual destructor call via `CodeGenFunction::EmitCXXDestructorCall`.
- Cleanup emission helpers (e.g., `CodeGenFunction::PopCleanupBlock` and
  `CodeGenFunction::EmitBranchThroughCleanup`) thread both normal and EH exits
  through the cleanup blocks as scopes are popped.
- The cleanup is represented as an `EHCleanupScope` on `EHScopeStack`, and
  its `Emit` method generates a loop that calls the destructor on the
  initialized range in reverse order.

The above function names and flow are accurate as of LLVM 22.0, but this is
subject to change as the code evolves, and this document might not be updated to
reflect the exact functions used.

## Example: Temporary object materialization

Consider:

```c++
class MyClass {
public:
  MyClass();
  ~MyClass();
};
void useMyClass(MyClass &);
void f() {
  useMyClass(MyClass());
}
```

### High-level behavior

- The temporary `MyClass` is materialized for the call argument.
- The temporary must be destroyed at the end of the full-expression, both on
  the normal path and on the exceptional path if `useMyClass` throws.
- If the constructor throws, the temporary is not considered constructed and no
  destructor runs.

### Codegen flow and key functions

- `CodeGenFunction::EmitExprWithCleanups` wraps the full-expression in a
  `RunCleanupsScope` so that full-expression cleanups are run after the call.
- `CodeGenFunction::EmitMaterializeTemporaryExpr` creates storage for the
  temporary via `createReferenceTemporary` and initializes it. For record
  temporaries this flows through `EmitAnyExprToMem` and
  `CodeGenFunction::EmitCXXConstructExpr`, which calls
  `CodeGenFunction::EmitCXXConstructorCall`.
- `pushTemporaryCleanup` registers the destructor as a full-expression
  cleanup by calling `CodeGenFunction::pushDestroy` for
  `SD_FullExpression` temporaries.
- The cleanup ultimately uses `DestroyObject` and
  `CodeGenFunction::destroyCXXObject`, which emits
  `CodeGenFunction::EmitCXXDestructorCall`.

The above function names and flow are accurate as of LLVM 22.0, but this is
subject to change as the code evolves, and this document might not be updated to
reflect the exact functions used.

---

### Clang Docs LTOVisibility (`clang/docs/LTOVisibility.md`)

# LTO Visibility

*LTO visibility* is a property of an entity that specifies whether it can be
referenced from outside the current LTO unit. A *linkage unit* is a set of
translation units linked together into an executable or DSO, and a linkage
unit's *LTO unit* is the subset of the linkage unit that is linked together
using link-time optimization; in the case where LTO is not being used, the
linkage unit's LTO unit is empty. Each linkage unit has only a single LTO unit.

The LTO visibility of a class is used by the compiler to determine which
classes the whole-program devirtualization (`-fwhole-program-vtables`) and
control flow integrity (`-fsanitize=cfi-vcall` and `-fsanitize=cfi-mfcall`)
features apply to. These features use whole-program information, so they
require the entire class hierarchy to be visible in order to work correctly.

If any translation unit in the program uses either of the whole-program
devirtualization or control flow integrity features, it is effectively an ODR
violation to define a class with hidden LTO visibility in multiple linkage
units. A class with public LTO visibility may be defined in multiple linkage
units, but the tradeoff is that the whole-program devirtualization and
control flow integrity features can only be applied to classes with hidden LTO
visibility. A class's LTO visibility is treated as an ODR-relevant property
of its definition, so it must be consistent between translation units.

In translation units built with LTO, LTO visibility is based on the
class's symbol visibility as expressed at the source level (i.e. the
`__attribute__((visibility("...")))` attribute, or the `-fvisibility=`
flag) or, on the Windows platform, the dllimport and dllexport attributes. When
targeting non-Windows platforms, classes with a visibility other than hidden
visibility receive public LTO visibility. When targeting Windows, classes
with dllimport or dllexport attributes receive public LTO visibility. All
other classes receive hidden LTO visibility. Classes with internal linkage
(e.g. classes declared in unnamed namespaces) also receive hidden LTO
visibility.

During the LTO link, all classes with public LTO visibility but not marked with
`[[clang::lto_visibility_public]]` (see below) will be refined to hidden LTO
visibility when the `--lto-whole-program-visibility` lld linker option is
applied (`-plugin-opt=whole-program-visibility` for gold). This flag can be
used to defer specifying whether classes have hidden LTO visibility until link
time, to allow bitcode objects to be shared by different LTO links. Due to an
implementation limitation, symbols associated with classes with hidden LTO
visibility may still be exported from the binary when using this flag. It is
unsafe to refer to these symbols, and their visibility may be relaxed to hidden
in a future compiler release.

A class defined in a translation unit built without LTO receives public
LTO visibility regardless of its object file visibility, linkage or other
attributes.

This mechanism will produce the correct result in most cases, but there are
two cases where it may wrongly infer hidden LTO visibility.

1. As a corollary of the above rules, if a linkage unit is produced from a
   combination of LTO object files and non-LTO object files, any hidden
   visibility class defined in both a translation unit built with LTO and
   a translation unit built without LTO must be defined with public LTO
   visibility in order to avoid an ODR violation.
2. Some ABIs provide the ability to define an abstract base class without
   visibility attributes in multiple linkage units and have virtual calls
   to derived classes in other linkage units work correctly. One example of
   this is COM on Windows platforms. If the ABI allows this, any base class
   used in this way must be defined with public LTO visibility.

Classes that fall into either of these categories can be marked up with the
`[[clang::lto_visibility_public]]` attribute. To specifically handle the
COM case, classes with the `__declspec(uuid())` attribute receive public
LTO visibility. On Windows platforms, clang-cl's `/MT` and `/MTd`
flags statically link the program against a prebuilt standard library;
these flags imply public LTO visibility for every class declared in the
`std` and `stdext` namespaces.

## Example

The following example shows how LTO visibility works in practice in several
cases involving two linkage units, `main` and `dso.so`.

```
/* Detailed source-code truncated for AI context efficiency. */
```

We will now describe the LTO visibility of each of the classes defined in
these linkage units.

Class `A` is not defined outside of `main`'s LTO unit, so it can have
hidden LTO visibility. This is inferred from the object file visibility
specified on the command line.

Class `B` is defined in `main`, both inside and outside its LTO unit. The
definition outside the LTO unit has public LTO visibility, so the definition
inside the LTO unit must also have public LTO visibility in order to avoid
an ODR violation.

Class `C` is defined in both `main` and `dso.so` and therefore must
have public LTO visibility. This is correctly inferred from the `visibility`
attribute.

Class `D` is an abstract base class with a derived class `E` defined
in `dso.so`. This is an example of the COM scenario; the definition of
`D` in `main`'s LTO unit must have public LTO visibility in order to be
compatible with the definition of `D` in `dso.so`, which is observable
by calling the function `mkE`.

---

### Clang Docs LanguageExtensions (`clang/docs/LanguageExtensions.md`)

# Clang Language Extensions


```{toctree}
:hidden: true

ObjectiveCLiterals
BlockLanguageSpec
Block-ABI-Apple
AutomaticReferenceCounting
PointerAuthentication
MatrixTypes
CXXTypeAwareAllocators
```

## Introduction

This document describes the language extensions provided by Clang. In addition
to the language extensions listed here, Clang aims to support a broad range of
GCC extensions. Please see the [GCC manual](https://gcc.gnu.org/onlinedocs/gcc/C-Extensions.html) for more information on
these extensions.

(langext-feature_check)=
(langext-feature-check)=

## Feature Checking Macros

Language extensions can be very useful, but only if you know you can depend on
them. In order to allow fine-grained feature checks, we support three builtin
function-like macros. This allows you to directly test for a feature in your
code without having to resort to something like autoconf or fragile "compiler
version checks".

### `__has_builtin`

This function-like macro takes a single identifier argument that is the name of
a builtin function, a builtin pseudo-function (taking one or more type
arguments), or a builtin template.
It evaluates to 1 if the builtin is supported or 0 if not.
It can be used like this:

```c++
#ifndef __has_builtin         // Optional of course.
  #define __has_builtin(x) 0  // Compatibility with non-clang compilers.
#endif

...
#if __has_builtin(__builtin_trap)
  __builtin_trap();
#else
  abort();
#endif
...
```

:::{note}
Prior to Clang 10, `__has_builtin` could not be used to detect most builtin
pseudo-functions.

`__has_builtin` should not be used to detect support for a builtin macro;
use `#ifdef` instead.

When compiling with target offloading, `__has_builtin` only considers the
currently active target.
:::

### `__has_constexpr_builtin`

This function-like macro takes a single identifier argument that is the name of
a builtin function, a builtin pseudo-function (taking one or more type
arguments), or a builtin template.
It evaluates to 1 if the builtin is supported and can be constant evaluated or
0 if not. It can be used for writing conditionally constexpr code like this:

```c++
#ifndef __has_constexpr_builtin         // Optional of course.
  #define __has_constexpr_builtin(x) 0  // Compatibility with non-clang compilers.
#endif

...
#if __has_constexpr_builtin(__builtin_fmax)
  constexpr
#endif
  double money_fee(double amount) {
      return __builtin_fmax(amount * 0.03, 10.0);
  }
...
```

For example, `__has_constexpr_builtin` is used in libcxx's implementation of
the `<cmath>` header file to conditionally make a function constexpr whenever
the constant evaluation of the corresponding builtin (for example,
`std::fmax` calls `__builtin_fmax`) is supported in Clang.

(langext-__has_feature-__has_extension)=
(langext-has-feature-has-extension)=

### `__has_feature` and `__has_extension`

These function-like macros take a single identifier argument that is the name
of a feature. `__has_feature` evaluates to 1 if the feature is both
supported by Clang and standardized in the current language standard or 0 if
not (but see {ref}`below <langext-has-feature-back-compat>`), while
`__has_extension` evaluates to 1 if the feature is supported by Clang in the
current language (either as a language extension or a standard language
feature) or 0 if not. They can be used like this:

```c++
#ifndef __has_feature         // Optional of course.
  #define __has_feature(x) 0  // Compatibility with non-clang compilers.
#endif
#ifndef __has_extension
  #define __has_extension __has_feature // Compatibility with pre-3.0 compilers.
#endif

...
#if __has_feature(cxx_rvalue_references)
// This code will only be compiled with the -std=c++11 and -std=gnu++11
// options, because rvalue references are only standardized in C++11.
#endif

#if __has_extension(cxx_rvalue_references)
// This code will be compiled with the -std=c++11, -std=gnu++11, -std=c++98
// and -std=gnu++98 options, because rvalue references are supported as a
// language extension in C++98.
#endif
```

(langext-has-feature-back-compat)=

For backward compatibility, `__has_feature` can also be used to test
for support for non-standardized features, i.e., features not prefixed `c_`,
`cxx_` or `objc_`.

Another use of `__has_feature` is to check for compiler features not related
to the language standard, such as {doc}`AddressSanitizer
<AddressSanitizer>`.

If the `-pedantic-errors` option is given, `__has_extension` is equivalent
to `__has_feature`.

The feature tag is described along with the language feature below.

The feature name or extension name can also be specified with a preceding and
following `__` (double underscore) to avoid interference from a macro with
the same name. For instance, `__cxx_rvalue_references__` can be used instead
of `cxx_rvalue_references`.

### `__has_cpp_attribute`

This function-like macro is available in C++20 by default, and is provided as an
extension in earlier language standards. It takes a single argument that is the
name of a double-square-bracket-style attribute. The argument can be either a
single identifier or a scoped identifier. If the attribute is supported, a
nonzero value is returned. If the attribute is a standards-based attribute, this
macro returns a nonzero value based on the year and month in which the attribute
was voted into the working draft. See [WG21 SD-6](https://isocpp.org/std/standing-documents/sd-6-sg10-feature-test-recommendations)
for the list of values returned for standards-based attributes. If the attribute
is not supported by the current compilation target, this macro evaluates to 0.
It can be used like this:

```c++
#ifndef __has_cpp_attribute         // For backwards compatibility
  #define __has_cpp_attribute(x) 0
#endif

...
#if __has_cpp_attribute(clang::fallthrough)
#define FALLTHROUGH [[clang::fallthrough]]
#else
#define FALLTHROUGH
#endif
...
```

The attribute scope tokens `clang` and `_Clang` are interchangeable, as are
the attribute scope tokens `gnu` and `__gnu__`. Attribute tokens in either
of these namespaces can be specified with a preceding and following `__`
(double underscore) to avoid interference from a macro with the same name. For
instance, `gnu::__const__` can be used instead of `gnu::const`.

### `__has_c_attribute`

This function-like macro takes a single argument that is the name of an
attribute exposed with the double square-bracket syntax in C mode. The argument
can either be a single identifier or a scoped identifier. If the attribute is
supported, a nonzero value is returned. If the attribute is not supported by the
current compilation target, this macro evaluates to 0. It can be used like this:

```c
#ifndef __has_c_attribute         // Optional of course.
  #define __has_c_attribute(x) 0  // Compatibility with non-clang compilers.
#endif

...
#if __has_c_attribute(fallthrough)
  #define FALLTHROUGH [[fallthrough]]
#else
  #define FALLTHROUGH
#endif
...
```

The attribute scope tokens `clang` and `_Clang` are interchangeable, as are
the attribute scope tokens `gnu` and `__gnu__`. Attribute tokens in either
of these namespaces can be specified with a preceding and following `__`
(double underscore) to avoid interference from a macro with the same name. For
instance, `gnu::__const__` can be used instead of `gnu::const`.

### `__has_attribute`

This function-like macro takes a single identifier argument that is the name of
a GNU-style attribute. It evaluates to 1 if the attribute is supported by the
current compilation target, or 0 if not. It can be used like this:

```c++
#ifndef __has_attribute         // Optional of course.
  #define __has_attribute(x) 0  // Compatibility with non-clang compilers.
#endif

...
#if __has_attribute(always_inline)
#define ALWAYS_INLINE __attribute__((always_inline))
#else
#define ALWAYS_INLINE
#endif
...
```

The attribute name can also be specified with a preceding and following `__`
(double underscore) to avoid interference from a macro with the same name. For
instance, `__always_inline__` can be used instead of `always_inline`.

### `__has_declspec_attribute`

This function-like macro takes a single identifier argument that is the name of
an attribute implemented as a Microsoft-style `__declspec` attribute. It
evaluates to 1 if the attribute is supported by the current compilation target,
or 0 if not. It can be used like this:

```c++
#ifndef __has_declspec_attribute         // Optional of course.
  #define __has_declspec_attribute(x) 0  // Compatibility with non-clang compilers.
#endif

...
#if __has_declspec_attribute(dllexport)
#define DLLEXPORT __declspec(dllexport)
#else
#define DLLEXPORT
#endif
...
```

The attribute name can also be specified with a preceding and following `__`
(double underscore) to avoid interference from a macro with the same name. For
instance, `__dllexport__` can be used instead of `dllexport`.

### `__is_identifier`

This function-like macro takes a single identifier argument that might be either
a reserved word or a regular identifier. It evaluates to 1 if the argument is just
a regular identifier and not a reserved word, in the sense that it can then be
used as the name of a user-defined function or variable. Otherwise it evaluates
to 0. It can be used like this:

```c++
...
#ifdef __is_identifier          // Compatibility with non-clang compilers.
  #if __is_identifier(__wchar_t)
    typedef wchar_t __wchar_t;
  #endif
#endif

__wchar_t WideCharacter;
...
```

## Include File Checking Macros

Not all developments systems have the same include files. The
{ref}`__has_include <langext-has-include>` and {ref}`__has_include_next <langext-has-include-next>` macros allow
you to check for the existence of an include file before doing a possibly
failing `#include` directive. Include file checking macros must be used
as expressions in `#if` or `#elif` preprocessing directives.

(langext-__has_include)=
(langext-has-include)=

### `__has_include`

This function-like macro takes a single file name string argument that is the
name of an include file. It evaluates to 1 if the file can be found using the
include paths, or 0 otherwise:

```c++
// Note the two possible file name string formats.
#if __has_include("myinclude.h") && __has_include(<stdint.h>)
# include "myinclude.h"
#endif
```

To test for this feature, use `#if defined(__has_include)`:

```c++
// To avoid problems with non-clang compilers not having this macro.
#if defined(__has_include)
#if __has_include("myinclude.h")
# include "myinclude.h"
#endif
#endif
```

(langext-__has_include_next)=
(langext-has-include-next)=

### `__has_include_next`

This function-like macro takes a single file name string argument that is the
name of an include file. It is like `__has_include` except that it looks for
the second instance of the given file found in the include paths. It evaluates
to 1 if the second instance of the file can be found using the include paths,
or 0 otherwise:

```c++
// Note the two possible file name string formats.
#if __has_include_next("myinclude.h") && __has_include_next(<stdint.h>)
# include_next "myinclude.h"
#endif

// To avoid problems with non-clang compilers not having this macro.
#if defined(__has_include_next)
#if __has_include_next("myinclude.h")
# include_next "myinclude.h"
#endif
#endif
```

Note that `__has_include_next`, like the GNU extension `#include_next`
directive, is intended for use in headers only, and will issue a warning if
used in the top-level compilation file. A warning will also be issued if an
absolute path is used in the file argument.

### `__has_warning`

This function-like macro takes a string literal that represents a command line
option for a warning and returns `true` if that is a valid warning option.

```c++
#if __has_warning("-Wformat")
...
#endif
```

(languageextensions-builtin-macros)=

## Builtin Macros

`__BASE_FILE__`
: Defined to a string that contains the name of the main input file passed to
  Clang.

`__FILE_NAME__`
: Clang-specific extension that functions similar to `__FILE__` but only
  renders the last path component (the filename) instead of an
  invocation-dependent full path to that file.

`__COUNTER__`
: Defined to an integer value that starts at zero and is incremented each time
  the `__COUNTER__` macro is expanded. This is a standard feature in C2y but
  is an extension in earlier language modes and in C++. This macro can only be
  expanded 2147483647 times at most.

`__INCLUDE_LEVEL__`
: Defined to an integral value that is the include depth of the file currently
  being translated. For the main file, this value is zero.

`__TIMESTAMP__`
: Defined to the date and time of the last modification of the current source
  file.

`__clang__`
: Defined when compiling with Clang.

`__clang_major__`
: Defined to the major marketing version number of Clang (e.g., the 2 in
  2.0.1). Note that marketing version numbers should not be used to check for
  language features, as different vendors use different numbering schemes.
  Instead, use the {ref}`langext-feature-check`.

`__clang_minor__`
: Defined to the minor version number of Clang (e.g., the 0 in 2.0.1). Note
  that marketing version numbers should not be used to check for language
  features, as different vendors use different numbering schemes. Instead, use
  the {ref}`langext-feature-check`.

`__clang_patchlevel__`
: Defined to the marketing patch level of Clang (e.g., the 1 in 2.0.1).

`__clang_version__`
: Defined to a string that captures the Clang marketing version, including the
  Subversion tag or revision number, e.g., "`1.5 (trunk 102332)`".

`__clang_literal_encoding__`
: Defined to a narrow string literal that represents the current encoding of
  narrow string literals, e.g., `"hello"`. This macro typically expands to
  "UTF-8" (but may change in the future if the
  `-fexec-charset="Encoding-Name"` option is implemented.)

`__clang_wide_literal_encoding__`
: Defined to a narrow string literal that represents the current encoding of
  wide string literals, e.g., `L"hello"`. This macro typically expands to
  "UTF-16" or "UTF-32" (but may change in the future if the
  `-fwide-exec-charset="Encoding-Name"` option is implemented.)

## Implementation-defined keywords

### \_\_datasizeof

`__datasizeof` behaves like `sizeof`, except that it returns the size of the
type ignoring tail padding.

### \_BitInt, \_ExtInt

Clang supports the C23 `_BitInt(N)` feature as an extension in older C modes
and in C++. This type was previously implemented in Clang with the same
semantics, but spelled `_ExtInt(N)`. This spelling has been deprecated in
favor of the standard type.

Note: the ABI for `_BitInt(N)` is still in the process of being stabilized,
so this type should not yet be used in interfaces that require ABI stability.

### C keywords supported in all language modes

Clang supports `_Alignas`, `_Alignof`, `_Atomic`, `_Complex`,
`_Generic`, `_Imaginary`, `_Noreturn`, `_Static_assert`,
`_Thread_local`, and `_Float16` in all language modes with the C semantics.

### \_\_alignof, \_\_alignof\_\_

`__alignof` and `__alignof__` return, in contrast to `_Alignof` and
`alignof`, the preferred alignment of a type. This may be larger than the
required alignment for improved performance.

### \_\_extension\_\_

`__extension__` suppresses extension diagnostics in the statement it is
prepended to.

### \_\_auto_type

`__auto_type` behaves the same as `auto` in C++11 but is available in all
language modes.

### \_\_imag, \_\_imag\_\_

`__imag` and `__imag__` can be used to get the imaginary part of a complex
value.

### \_\_real, \_\_real\_\_

`__real` and `__real__` can be used to get the real part of a complex value.

### \_\_asm, \_\_asm\_\_

`__asm` and `__asm__` are alternate spellings for `asm`, but available in
all language modes.

### \_\_complex, \_\_complex\_\_

`__complex` and `__complex__` are alternate spellings for `_Complex`.

### \_\_const, \_\_const\_\_, \_\_volatile, \_\_volatile\_\_, \_\_restrict, \_\_restrict\_\_

These are alternate spellings for their non-underscore counterparts, but are
available in all language modes.

### \_\_decltype

`__decltype` is an alternate spelling for `decltype`, but is also available
in C++ modes before C++11.

### \_\_inline, \_\_inline\_\_

`__inline` and `__inline__` are alternate spellings for `inline`, but are
available in all language modes.

### \_\_nullptr

`__nullptr` is an alternate spelling for `nullptr`. It is available in all C and C++ language modes.

### \_\_signed, \_\_signed\_\_

`__signed` and `__signed__` are alternate spellings for `signed`.
`__unsigned` and `__unsigned__` are **not** supported.

### \_\_typeof, \_\_typeof\_\_, \_\_typeof_unqual, \_\_typeof_unqual\_\_

`__typeof` and `__typeof__` are alternate spellings for `typeof`, but are
available in all language modes. These spellings result in the operand,
retaining all qualifiers.

`__typeof_unqual` and `__typeof_unqual__` are alternate spellings for the
C23 `typeof_unqual` type specifier, but are available in all language modes.
These spellings result in the type of the operand, stripping all qualifiers.

### \_\_char16_t, \_\_char32_t

`__char16_t` and `__char32_t` are alternate spellings for `char16_t` and
`char32_t` respectively, but are also available in C++ modes before C++11.
They are only supported in C++. `__char8_t` is not available.

% FIXME: This should list all the keyword extensions

(langext-vectors)=

## Vectors and Extended Vectors

Supports the GCC, OpenCL, AltiVec, NEON, SVE and RVV vector extensions.

OpenCL vector types are created using the `ext_vector_type` attribute. It
supports the `V.xyzw` syntax and other tidbits as seen in OpenCL. An example
is:

```c++
typedef float float4 __attribute__((ext_vector_type(4)));
typedef float float2 __attribute__((ext_vector_type(2)));

float4 foo(float2 a, float2 b) {
  float4 c;
  c.xz = a;
  c.yw = b;
  return c;
}
```

Query for this feature with `__has_attribute(ext_vector_type)`.

Giving `-maltivec` option to clang enables support for AltiVec vector syntax
and functions. For example:

```c++
vector float foo(vector int a) {
  vector int b;
  b = vec_add(a, a) + a;
  return (vector float)b;
}
```

NEON vector types are created using `neon_vector_type` and
`neon_polyvector_type` attributes. For example:

```c++
typedef __attribute__((neon_vector_type(8))) int8_t int8x8_t;
typedef __attribute__((neon_polyvector_type(16))) poly8_t poly8x16_t;

int8x8_t foo(int8x8_t a) {
  int8x8_t v;
  v = a;
  return v;
}
```

GCC vector types are created using the `vector_size(N)` attribute. The
argument `N` specifies the number of bytes that will be allocated for an
object of this type. The size has to be a multiple of the size of the vector
element type. For example:

```c++
// OK: This declares a vector type with four 'int' elements
typedef int int4 __attribute__((vector_size(4 * sizeof(int))));

// ERROR: '11' is not a multiple of sizeof(int)
typedef int int_impossible __attribute__((vector_size(11)));

int4 foo(int4 a) {
  int4 v;
  v = a;
  return v;
}
```

### Boolean Vectors

Clang also supports the `ext_vector_type` attribute with boolean element types in
C and C++. For example:

```c++
// legal for Clang, error for GCC:
typedef bool bool4 __attribute__((ext_vector_type(4)));
// Objects of bool4 type hold 8 bits, sizeof(bool4) == 1

bool4 foo(bool4 a) {
  bool4 v;
  v = a;
  return v;
}
```

Boolean vectors are a Clang extension of the ext vector type. Boolean vectors
are intended, though not guaranteed, to map to vector mask registers. The size
parameter of a boolean vector type is the number of bits in the vector. The
boolean vector is dense and each bit in the boolean vector is one vector
element. Query for this feature with `__has_feature(ext_vector_type_boolean)`.

The semantics of boolean vectors borrows from C bit-fields with the following
differences:

- Distinct boolean vectors are always distinct memory objects (there is no
  packing).
- Only the operators `?:`, `!`, `~`, `|`, `&`, `^` and comparison are allowed on
  boolean vectors.
- Casting a scalar bool value to a boolean vector type means broadcasting the
  scalar value onto all lanes (same as general ext_vector_type).

The size and alignment are both the number of bits rounded up to the next power
of two, but the alignment is at most the maximum vector alignment of the
target.

A boolean vector can be used in a ternary `?:` operator to select vector
elements of a different type.

```c++
typedef int int4 __attribute__((ext_vector_type(4)));
typedef bool bool4 __attribute__((ext_vector_type(4)));

int4 blend(bool4 cond, int4 a, int4 b) { return cond ? a : b; }
```

### Vector Literals

Vector literals can be used to create vectors from a set of scalars, or
vectors. Either parentheses or braces form can be used. In the parentheses
form the number of literal values specified must be one, i.e., referring to a
scalar value, or must match the size of the vector type being created. If a
single scalar literal value is specified, the scalar literal value will be
replicated to all the components of the vector type. In the brackets form any
number of literals can be specified. For example:

```c++
typedef int v4si __attribute__((__vector_size__(16)));
typedef float float4 __attribute__((ext_vector_type(4)));
typedef float float2 __attribute__((ext_vector_type(2)));

v4si vsi = (v4si){1, 2, 3, 4};
float4 vf = (float4)(1.0f, 2.0f, 3.0f, 4.0f);
vector int vi1 = (vector int)(1);    // vi1 will be (1, 1, 1, 1).
vector int vi2 = (vector int){1};    // vi2 will be (1, 0, 0, 0).
vector int vi3 = (vector int)(1, 2); // error
vector int vi4 = (vector int){1, 2}; // vi4 will be (1, 2, 0, 0).
vector int vi5 = (vector int)(1, 2, 3, 4);
float4 vf = (float4)((float2)(1.0f, 2.0f), (float2)(3.0f, 4.0f));
```

### Vector Operations

The table below shows the support for each operation by vector extension. A
dash indicates that an operation is not accepted according to a corresponding
specification.

| Operator | OpenCL | AltiVec | GCC | NEON | SVE | RVV |
| --- | --- | --- | --- | --- | --- | --- |
| [] | yes | yes | yes | yes | yes | yes |
| unary operators +, -- | yes | yes | yes | yes | yes | yes |
| ++, -- -- | yes | yes | yes | no | no | no |
| +,--,*,/,% | yes | yes | yes | yes | yes | yes |
| bitwise operators &,\|,^,~ | yes | yes | yes | yes | yes | yes |
| >>,<< | yes | yes | yes | yes | yes | yes |
| !, &&, \|\| | yes | -- | yes | yes | yes | yes |
| ==, !=, >, <, >=, <= | yes | yes | yes | yes | yes | yes |
| = | yes | yes | yes | yes | yes | yes |
| ?: <a class="footnote-reference brackets" href="#id5" id="id1" role="doc-noteref">[1]</a> | yes | -- | yes | yes | yes | yes |
| sizeof | yes | yes | yes | yes | yes <a class="footnote-reference brackets" href="#vls" id="id2" role="doc-noteref">[2]</a> | yes <a class="footnote-reference brackets" href="#vls" id="id3" role="doc-noteref">[2]</a> |
| C-style cast | yes | yes | yes | no | no | yes |
| reinterpret_cast | yes | no | yes | no | no | yes |
| static_cast | yes | no | yes | no | no | yes |
| const_cast | no | no | no | no | no | no |
| address &v[i] | no | no | no <a class="footnote-reference brackets" href="#id6" id="id4" role="doc-noteref">[3]</a> | no | no | no |

Both SVE and RVV define sizeless vector types which cannot be used in globals,
structs, unions, or arrays. Both provide an attribute (`arm_sve_vector_bits`
and `riscv_rvv_vector_bits` respectively) to create fixed-length
vector-length-specific (VLS) variants that remove these restrictions. Using
these attributes requires the command line option `-msve-vector-bits=<N>` or
`-mrvv-vector-bits=<N>` respectively. For SVE, the operators above are
supported on both sizeless and VLS types. For RVV, the operators are only
supported on VLS types.

See also {ref}`langext-builtin-shufflevector`, {ref}`langext-builtin-convertvector`.

<aside class="footnote-list brackets">
<aside class="footnote brackets" id="id5" role="doc-footnote">
<span class="label"><span class="fn-bracket">[</span><a role="doc-backlink" href="#id1">1</a><span class="fn-bracket">]</span></span>
<p>ternary operator(?:) has different behaviors depending on the condition
operand's vector type. If the condition is a GNU vector (i.e.,
<code>__vector_size__</code>), a NEON vector, an SVE vector or an RVV vector,
it's only available in C++ and uses normal bool conversions (that is, != 0).
If it's an extension (OpenCL) vector, it's only available in C and OpenCL C.
And it selects based on the signedness of the condition operands (OpenCL v1.1 s6.3.9).</p>
</aside>
<aside class="footnote brackets" id="vls" role="doc-footnote">
<span class="label"><span class="fn-bracket">[</span>2<span class="fn-bracket">]</span></span>
<span class="backrefs">(<a role="doc-backlink" href="#id2">1</a>,<a role="doc-backlink" href="#id3">2</a>)</span>
<p>sizeof can only be used on vector length specific SVE and RVV types.</p>
</aside>
<aside class="footnote brackets" id="id6" role="doc-footnote">
<span class="label"><span class="fn-bracket">[</span><a role="doc-backlink" href="#id4">3</a><span class="fn-bracket">]</span></span>
<p>Clang does not allow the address of an element to be taken while GCC
allows this. This is intentional for vectors with a boolean element type and
not implemented otherwise.</p>
</aside>
</aside>

### Vector Builtins

**Note: The implementation of vector builtins is work-in-progress and incomplete.**

In addition to the operators mentioned above, Clang provides a set of builtins
to perform additional operations on certain scalar and vector types.

Let `T` be one of the following types:

- an integer type (as in C23 6.2.5p22), but excluding enumerated types and `bool`
- the standard floating types `float` or `double`
- a half-precision floating point type, if one is supported on the target
- a vector type.

For scalar types, consider the operation applied to a vector with a single element.

*Vector Size*
To determine the number of elements in a vector, use `__builtin_vectorelements()`.
For fixed-sized vectors, e.g., defined via `__attribute__((vector_size(N)))` or ARM
NEON's vector types (e.g., `uint16x8_t`), this returns the constant number of
elements at compile-time. For scalable vectors, e.g., SVE or RISC-V V, the number of
elements is not known at compile-time and is determined at runtime. This builtin can
be used, e.g., to increment the loop-counter in vector-type agnostic loops.

*Elementwise Builtins*

Each builtin returns a vector equivalent to applying the specified operation
elementwise to the input.

Unless specified otherwise operation(±0) = ±0 and operation(±infinity) = ±infinity

The elementwise intrinsics `__builtin_elementwise_popcount`,
`__builtin_elementwise_bitreverse`, `__builtin_elementwise_add_sat`,
`__builtin_elementwise_sub_sat`, `__builtin_elementwise_max`,
`__builtin_elementwise_min`, `__builtin_elementwise_abs`,
`__builtin_elementwise_clzg`, `__builtin_elementwise_ctzg`, and
`__builtin_elementwise_fma` can be called in a `constexpr` context.

No implicit promotion of integer types takes place. The mixing of integer types
of different sizes and signs is forbidden in binary and ternary builtins.

| Name                                           | Operation                                                                                                                                                                                                                                                                                                          | Supported element types                      |
| ---------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------- |
| T \_\_builtin_elementwise_abs(T x)             | return the absolute value of a number x; the absolute value of the most negative integer remains the most negative integer                                                                                                                                                                                         | signed integer and floating point types      |
| T \_\_builtin_elementwise_fma(T x, T y, T z)   | fused multiply add, (x * y) + z.                                                                                                                                                                                                                                                                                   | floating point types                         |
| T \_\_builtin_elementwise_ceil(T x)            | return the smallest integral value greater than or equal to x                                                                                                                                                                                                                                                      | floating point types                         |
| T \_\_builtin_elementwise_sin(T x)             | return the sine of x interpreted as an angle in radians                                                                                                                                                                                                                                                            | floating point types                         |
| T \_\_builtin_elementwise_cos(T x)             | return the cosine of x interpreted as an angle in radians                                                                                                                                                                                                                                                          | floating point types                         |
| T \_\_builtin_elementwise_tan(T x)             | return the tangent of x interpreted as an angle in radians                                                                                                                                                                                                                                                         | floating point types                         |
| T \_\_builtin_elementwise_asin(T x)            | return the arcsine of x interpreted as an angle in radians                                                                                                                                                                                                                                                         | floating point types                         |
| T \_\_builtin_elementwise_acos(T x)            | return the arccosine of x interpreted as an angle in radians                                                                                                                                                                                                                                                       | floating point types                         |
| T \_\_builtin_elementwise_atan(T x)            | return the arctangent of x interpreted as an angle in radians                                                                                                                                                                                                                                                      | floating point types                         |
| T \_\_builtin_elementwise_atan2(T y, T x)      | return the arctangent of y/x                                                                                                                                                                                                                                                                                       | floating point types                         |
| T \_\_builtin_elementwise_sinh(T x)            | return the hyperbolic sine of angle x in radians                                                                                                                                                                                                                                                                   | floating point types                         |
| T \_\_builtin_elementwise_cosh(T x)            | return the hyperbolic cosine of angle x in radians                                                                                                                                                                                                                                                                 | floating point types                         |
| T \_\_builtin_elementwise_tanh(T x)            | return the hyperbolic tangent of angle x in radians                                                                                                                                                                                                                                                                | floating point types                         |
| T \_\_builtin_elementwise_floor(T x)           | return the largest integral value less than or equal to x                                                                                                                                                                                                                                                          | floating point types                         |
| T \_\_builtin_elementwise_log(T x)             | return the natural logarithm of x                                                                                                                                                                                                                                                                                  | floating point types                         |
| T \_\_builtin_elementwise_log2(T x)            | return the base 2 logarithm of x                                                                                                                                                                                                                                                                                   | floating point types                         |
| T \_\_builtin_elementwise_log10(T x)           | return the base 10 logarithm of x                                                                                                                                                                                                                                                                                  | floating point types                         |
| T \_\_builtin_elementwise_popcount(T x)        | return the number of 1 bits in x                                                                                                                                                                                                                                                                                   | integer types                                |
| T \_\_builtin_elementwise_pow(T x, T y)        | return x raised to the power of y                                                                                                                                                                                                                                                                                  | floating point types                         |
| T \_\_builtin_elementwise_bitreverse(T x)      | return the integer represented after reversing the bits of x                                                                                                                                                                                                                                                       | integer types                                |
| T \_\_builtin_elementwise_exp(T x)             | returns the base-e exponential, e^x, of the specified value                                                                                                                                                                                                                                                        | floating point types                         |
| T \_\_builtin_elementwise_exp2(T x)            | returns the base-2 exponential, 2^x, of the specified value                                                                                                                                                                                                                                                        | floating point types                         |
| T \_\_builtin_elementwise_exp10(T x)           | returns the base-10 exponential, 10^x, of the specified value                                                                                                                                                                                                                                                      | floating point types                         |
| T \_\_builtin_elementwise_ldexp(T x, IntT y)   | returns the product of x and 2 raised to the power y. y must be an integer type matching the shape of x.                                                                                                                                                                                                           | T: floating point types, IntT: integer types |
| T \_\_builtin_elementwise_sqrt(T x)            | return the square root of a floating-point number                                                                                                                                                                                                                                                                  | floating point types                         |
| T \_\_builtin_elementwise_roundeven(T x)       | round x to the nearest integer value in floating point format, rounding halfway cases to even (that is, to the nearest value that is an even integer), regardless of the current rounding direction.                                                                                                               | floating point types                         |
| T \_\_builtin_elementwise_round(T x)           | round x to the nearest integer value in floating point format, rounding halfway cases away from zero, regardless of the current rounding direction. May raise floating-point exceptions.                                                                                                                           | floating point types                         |
| T \_\_builtin_elementwise_trunc(T x)           | return the integral value nearest to but no larger in magnitude than x                                                                                                                                                                                                                                             | floating point types                         |
| T \_\_builtin_elementwise_nearbyint(T x)       | round x to the nearest integer value in floating point format, rounding according to the current rounding direction. May not raise the inexact floating-point exception. This is treated the same as `__builtin_elementwise_rint` unless {ref}`FENV_ACCESS is enabled <floating-point-environment>`.               | floating point types                         |
| T \_\_builtin_elementwise_rint(T x)            | round x to the nearest integer value in floating point format, rounding according to the current rounding direction. May raise floating-point exceptions. This is treated the same as `__builtin_elementwise_nearbyint` unless {ref}`FENV_ACCESS is enabled <floating-point-environment>`.                         | floating point types                         |
| T \_\_builtin_elementwise_canonicalize(T x)    | return the platform specific canonical encoding of a floating-point number                                                                                                                                                                                                                                         | floating point types                         |
| T \_\_builtin_elementwise_copysign(T x, T y)   | return the magnitude of x with the sign of y.                                                                                                                                                                                                                                                                      | floating point types                         |
| T \_\_builtin_elementwise_fmod(T x, T y)       | return the floating-point remainder of (x/y) whose sign matches the sign of x.                                                                                                                                                                                                                                     | floating point types                         |
| T \_\_builtin_elementwise_max(T x, T y)        | return x or y, whichever is larger For floating point types, follows semantics of maxNum in IEEE 754-2008. See [LangRef](http://llvm.org/docs/LangRef.html#i-fminmax-family) for the comparison.                                                                                                                   | integer floating point types (deprecated)    |
| T \_\_builtin_elementwise_min(T x, T y)        | return x or y, whichever is smaller For floating point types, follows semantics of minNum in IEEE 754-2008. See [LangRef](http://llvm.org/docs/LangRef.html#i-fminmax-family) for the comparison.                                                                                                                  | integer floating point types (deprecated)    |
| T \_\_builtin_elementwise_maxnum(T x, T y)     | return x or y, whichever is larger. Follows IEEE 754-2008 semantics (maxNum) with +0.0>-0.0. See [LangRef](http://llvm.org/docs/LangRef.html#i-fminmax-family) for the comparison.                                                                                                                                 | floating point types                         |
| T \_\_builtin_elementwise_minnum(T x, T y)     | return x or y, whichever is smaller. Follows IEEE 754-2008 semantics (minNum) with +0.0>-0.0. See [LangRef](http://llvm.org/docs/LangRef.html#i-fminmax-family) for the comparison.                                                                                                                                | floating point types                         |
| T \_\_builtin_elementwise_add_sat(T x, T y)    | return the sum of x and y, clamped to the range of representable values for the signed/unsigned integer type.                                                                                                                                                                                                      | integer types                                |
| T \_\_builtin_elementwise_sub_sat(T x, T y)    | return the difference of x and y, clamped to the range of representable values for the signed/unsigned integer type.                                                                                                                                                                                               | integer types                                |
| T \_\_builtin_elementwise_maximum(T x, T y)    | return x or y, whichever is larger. Follows IEEE 754-2019 semantics, see [LangRef](http://llvm.org/docs/LangRef.html#i-fminmax-family) for the comparison.                                                                                                                                                         | floating point types                         |
| T \_\_builtin_elementwise_minimum(T x, T y)    | return x or y, whichever is smaller. Follows IEEE 754-2019 semantics, see [LangRef](http://llvm.org/docs/LangRef.html#i-fminmax-family) for the comparison.                                                                                                                                                        | floating point types                         |
| T \_\_builtin_elementwise_maximumnum(T x, T y) | return x or y, whichever is larger. Follows IEEE 754-2019 semantics, see [LangRef](http://llvm.org/docs/LangRef.html#i-fminmax-family) for the comparison.                                                                                                                                                         | floating point types                         |
| T \_\_builtin_elementwise_minimumnum(T x, T y) | return x or y, whichever is smaller. Follows IEEE 754-2019 semantics, see [LangRef](http://llvm.org/docs/LangRef.html#i-fminmax-family) for the comparison.                                                                                                                                                        | floating point types                         |
| T \_\_builtin_elementwise_fshl(T x, T y, T z)  | perform a funnel shift left. Concatenate x and y (x is the most significant bits of the wide value), the combined value is shifted left by z (modulo the bit width of the original arguments), and the most significant bits are extracted to produce a result that is the same size as the original arguments.    | integer types                                |
| T \_\_builtin_elementwise_fshr(T x, T y, T z)  | perform a funnel shift right. Concatenate x and y (x is the most significant bits of the wide value), the combined value is shifted right by z (modulo the bit width of the original arguments), and the least significant bits are extracted to produce a result that is the same size as the original arguments. | integer types                                |
| T \_\_builtin_elementwise_clzg(T x[, T y])     | return the number of leading 0 bits in the first argument. If the first argument is 0 and an optional second argument is provided, the second argument is returned. It is undefined behaviour if the first argument is 0 and no second argument is provided.                                                       | integer types                                |
| T \_\_builtin_elementwise_ctzg(T x[, T y])     | return the number of trailing 0 bits in the first argument. If the first argument is 0 and an optional second argument is provided, the second argument is returned. It is undefined behaviour if the first argument is 0 and no second argument is provided.                                                      | integer types                                |
| T \_\_builtin_elementwise_clmul(T x, T y)      | perform a carry-less multiplication of x and y, returning the least significant bits of the wide result.                                                                                                                                                                                                           | integer types                                |
| T \_\_builtin_elementwise_pext(T x, T m)       | extract bits from x selected by the mask m, pack them contiguously into the least significant bits of the result, and zero the rest.                                                                                                                                                                               | integer types                                |
| T \_\_builtin_elementwise_pdep(T x, T m)       | deposit the least significant bits of x at the positions where m has a 1-bit, and zero the rest.                                                                                                                                                                                                                   | integer types                                |

*Reduction Builtins*

Each builtin returns a scalar equivalent to applying the specified
operation(x, y) as recursive even-odd pairwise reduction to all vector
elements. `operation(x, y)` is repeatedly applied to each non-overlapping
even-odd element pair with indices `i * 2` and `i * 2 + 1` with
`i in [0, Number of elements / 2)`. If the number of elements is not a
power of 2, the vector is widened with neutral elements for the reduction
at the end to the next power of 2.

These reductions support both fixed-sized and scalable vector types.

The integer reduction intrinsics, including `__builtin_reduce_max`,
`__builtin_reduce_min`, `__builtin_reduce_add`, `__builtin_reduce_mul`,
`__builtin_reduce_and`, `__builtin_reduce_or`, and `__builtin_reduce_xor`,
can be called in a `constexpr` context.

Example:

```c++
__builtin_reduce_add([e3, e2, e1, e0]) = __builtin_reduced_add([e3 + e2, e1 + e0])
                                       = (e3 + e2) + (e1 + e0)
```

Let `VT` be a vector type and `ET` the element type of `VT`.

| Name                                            | Operation                                                                                                                                                                                | Supported element types          |
| ----------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------- |
| ET \_\_builtin_reduce_max(VT a)                 | return the largest element of the vector. The floating point result will always be a number unless all elements of the vector are NaN.                                                   | integer and floating point types |
| ET \_\_builtin_reduce_min(VT a)                 | return the smallest element of the vector. The floating point result will always be a number unless all elements of the vector are NaN.                                                  | integer and floating point types |
| ET \_\_builtin_reduce_add(VT a)                 | +                                                                                                                                                                                        | integer types                    |
| ET \_\_builtin_reduce_mul(VT a)                 | \*                                                                                                                                                                                       | integer types                    |
| ET \_\_builtin_reduce_and(VT a)                 | &                                                                                                                                                                                        | integer types                    |
| ET \_\_builtin_reduce_or(VT a)                  | \|                                                                                                                                                                                       | integer types                    |
| ET \_\_builtin_reduce_xor(VT a)                 | ^                                                                                                                                                                                        | integer types                    |
| ET \_\_builtin_reduce_maximum(VT a)             | return the largest element of the vector. Follows IEEE 754-2019 semantics, see [LangRef](http://llvm.org/docs/LangRef.html#i-fminmax-family) for the comparison.                         | floating point types             |
| ET \_\_builtin_reduce_minimum(VT a)             | return the smallest element of the vector. Follows IEEE 754-2019 semantics, see [LangRef](http://llvm.org/docs/LangRef.html#i-fminmax-family) for the comparison.                        | floating point types             |
| ET \_\_builtin_reduce_assoc_fadd(VT a[, ET s])  | associative floating-point add reduction.                                                                                                                                                | floating point types             |
| ET \_\_builtin_reduce_in_order_fadd(VT a, ET s) | in order floating-point add reduction, initializing the accumulator with `(ET)s`, then adding each lane of the `a` in-order, starting from lane 0. The additions cannot be reassociated. | floating point types             |

*Masked Builtins*

Each builtin accesses memory according to a provided boolean mask. These are
provided as `__builtin_masked_load` and `__builtin_masked_store`. The first
argument is always a boolean mask vector. The `__builtin_masked_load` builtin
takes an optional third vector argument that will be used for the result of the
masked-off lanes. These builtins assume the memory is unaligned, use
`__builtin_assume_aligned` if alignment is desired.

The `__builtin_masked_expand_load` and `__builtin_masked_compress_store`
builtins have the same interface but store the result in consecutive indices.
Effectively this performs the `if (mask[i]) val[i] = ptr[j++]` and `if
(mask[i]) ptr[j++] = val[i]` pattern respectively.

The `__builtin_masked_gather` and `__builtin_masked_scatter` builtins handle
non-sequential memory access for vector types. These use a base pointer and a
vector of integer indices to gather memory into a vector type or scatter it to
separate indices.

Example:

```c++
using v8b = bool [[clang::ext_vector_type(8)]];
using v8i = int [[clang::ext_vector_type(8)]];

v8i load(v8b mask, int *ptr) { return __builtin_masked_load(mask, ptr); }

v8i load_expand(v8b mask, int *ptr) {
  return __builtin_masked_expand_load(mask, ptr);
}

void store(v8b mask, v8i val, int *ptr) {
  __builtin_masked_store(mask, val, ptr);
}

void store_compress(v8b mask, v8i val, int *ptr) {
  __builtin_masked_compress_store(mask, val, ptr);
}

v8i gather(v8b mask, v8i idx, int *ptr) {
  return __builtin_masked_gather(mask, idx, ptr);
}

void scatter(v8b mask, v8i val, v8i idx, int *ptr) {
  __builtin_masked_scatter(mask, idx, val, ptr);
}
```

## Matrix Types

Clang provides an extension for matrix types, which is currently being
implemented. See {ref}`the draft specification <matrixtypes>` for more details.

For example, the code below uses the matrix types extension to multiply two 4x4
float matrices and add the result to a third 4x4 matrix.

```c++
typedef float m4x4_t __attribute__((matrix_type(4, 4)));

m4x4_t f(m4x4_t a, m4x4_t b, m4x4_t c) {
  return a + b * c;
}
```

The matrix type extension also supports operations on a matrix and a scalar.

```c++
typedef float m4x4_t __attribute__((matrix_type(4, 4)));

m4x4_t f(m4x4_t a) {
  return (a + 23) * 12;
}
```

The matrix type extension supports division on a matrix and a scalar but not on a matrix and a matrix.

```c++
typedef float m4x4_t __attribute__((matrix_type(4, 4)));

m4x4_t f(m4x4_t a) {
  a = a / 3.0;
  return a;
}
```

The matrix type extension supports compound assignments for addition, subtraction, and multiplication on matrices
and on a matrix and a scalar, provided their types are consistent.

```c++
typedef float m4x4_t __attribute__((matrix_type(4, 4)));

m4x4_t f(m4x4_t a, m4x4_t b) {
  a += b;
  a -= b;
  a *= b;
  a += 23;
  a -= 12;
  return a;
}
```

The matrix type extension supports explicit casts. Implicit type conversion between matrix types is not allowed.

```c++
typedef int ix5x5 __attribute__((matrix_type(5, 5)));
typedef float fx5x5 __attribute__((matrix_type(5, 5)));

fx5x5 f1(ix5x5 i, fx5x5 f) {
  return (fx5x5) i;
}


template <typename X>
using matrix_4_4 = X __attribute__((matrix_type(4, 4)));

void f2() {
  matrix_5_5<double> d;
  matrix_5_5<int> i;
  i = (matrix_5_5<int>)d;
  i = static_cast<matrix_5_5<int>>(d);
}
```

The matrix type extension supports column and row major memory layouts, but not
all builtins are supported with row-major layout. The layout defaults to column
major and can be specified using `-fmatrix-memory-layout`. To enable column
major layout, use `-fmatrix-memory-layout=column-major`, and for row major
layout use `-fmatrix-memory-layout=row-major`

## Half-Precision Floating Point

Clang supports three half-precision (16-bit) floating point types:
`__fp16`, `_Float16` and `__bf16`. These types are supported
in all language modes, but their support differs between targets.
A target is said to have "native support" for a type if the target
processor offers instructions for directly performing basic arithmetic
on that type. In the absence of native support, a type can still be
supported if the compiler can emulate arithmetic on the type by promoting
to `float`; see below for more information on this emulation.

- `__fp16` is supported on all targets. The special semantics of this
  type mean that no arithmetic is ever performed directly on `__fp16` values;
  see below.

- `_Float16` is supported on the following targets:

  - 32-bit ARM (natively on some architecture versions)
  - 64-bit ARM (AArch64) (natively on ARMv8.2a and above)
  - AMDGPU (natively)
  - NVPTX (natively)
  - SPIR (natively)
  - X86 (if SSE2 is available; natively if AVX512-FP16 is also available)
  - RISC-V (natively if Zfh or Zhinx is available)
  - SystemZ (emulated)
  - LoongArch (emulated)

- `__bf16` is supported on the following targets (currently never natively):

  - 32-bit ARM
  - 64-bit ARM (AArch64)
  - RISC-V
  - X86 (when SSE2 is available)
  - LoongArch

(For X86, SSE2 is available on 64-bit and all recent 32-bit processors.)

`__fp16` and `_Float16` both use the binary16 format from IEEE
754-2008, which provides a 5-bit exponent and an 11-bit significand
(including the implicit leading 1). `__bf16` uses the [bfloat16](https://en.wikipedia.org/wiki/Bfloat16_floating-point_format) format,
which provides an 8-bit exponent and an 8-bit significand; this is the same
exponent range as `float`, just with greatly reduced precision.

`_Float16` and `__bf16` follow the usual rules for arithmetic
floating-point types. Most importantly, this means that arithmetic operations
on operands of these types are formally performed in the type and produce
values of the type. `__fp16` does not follow those rules: most operations
immediately promote operands of type `__fp16` to `float`, and so
arithmetic operations are defined to be performed in `float` and so result in
a value of type `float` (unless further promoted because of other operands).
See below for more information on the exact specifications of these types.

When compiling arithmetic on `_Float16` and `__bf16` for a target without
native support, Clang will perform the arithmetic in `float`, inserting
extensions and truncations as necessary. This can be done in a way that
exactly matches the operation-by-operation behavior of native support,
but that can require many extra truncations and extensions. By default,
when emulating `_Float16` and `__bf16` arithmetic using `float`, Clang
does not truncate intermediate operands back to their true type unless the
operand is the result of an explicit cast or assignment. This is generally
much faster but can generate different results from strict operation-by-operation
emulation. Usually the results are more precise. This is permitted by the
C and C++ standards under the rules for excess precision in intermediate operands;
see the discussion of evaluation formats in the C standard and [expr.pre] in
the C++ standard.

The use of excess precision can be independently controlled for these two
types with the `-ffloat16-excess-precision=` and
`-fbfloat16-excess-precision=` options. Valid values include:

- `none`: meaning to perform strict operation-by-operation emulation
- `standard`: meaning that excess precision is permitted under the rules
  described in the standard, i.e., never across explicit casts or statements
- `fast`: meaning that excess precision is permitted whenever the
  optimizer sees an opportunity to avoid truncations; currently this has no
  effect beyond `standard`

The `_Float16` type is an interchange floating type specified in
ISO/IEC TS 18661-3:2015 ("Floating-point extensions for C"). It will
be supported on more targets as they define ABIs for it.

The `__bf16` type is a non-standard extension, but it generally follows
the rules for arithmetic interchange floating types from ISO/IEC TS
18661-3:2015. In previous versions of Clang, it was a storage-only type
that forbade arithmetic operations. It will be supported on more targets
as they define ABIs for it.

The `__fp16` type was originally an ARM extension and is specified
by the [ARM C Language Extensions](https://github.com/ARM-software/acle/releases).
Clang uses the `binary16` format from IEEE 754-2008 for `__fp16`,
not the ARM alternative format. Operators that expect arithmetic operands
immediately promote `__fp16` operands to `float`.

It is recommended that portable code use `_Float16` instead of `__fp16`,
as it has been defined by the C standards committee and has behavior that is
more familiar to most programmers.

Because `__fp16` operands are always immediately promoted to `float`, the
common real type of `__fp16` and `_Float16` for the purposes of the usual
arithmetic conversions is `float`.

A literal can be given `_Float16` type using the suffix `f16`. For example,
`3.14f16`.

Because default argument promotion only applies to the standard floating-point
types, `_Float16` values are not promoted to `double` when passed as variadic
or untyped arguments. As a consequence, some caution must be taken when using
certain library facilities with `_Float16`; for example, there is no `printf` format
specifier for `_Float16`, and (unlike `float`) it will not be implicitly promoted to
`double` when passed to `printf`, so the programmer must explicitly cast it to
`double` before using it with an `%f` or similar specifier.

## Pragmas

### #pragma export

Clang supports the export pragma used to indicate an
external symbol is to be exported from the shared library being built. The
syntax for the pragma is:

```c++
#pragma export (name)
```

where `name` is the name of the external function or variable to be
exported. The symbol needs to have external linkage. The pragma may appear
before or after the declaration of `name`, but must precede the
definition. The pragma must also appear at file scope. If `name` is not
defined, the pragma will have no effect. The pragma needs to be specified
in the same translation unit as `name` is defined.

The pragma has the same effect as adding `__attribute__((visibility("default")))`
to the declaration of `name`.

In C++, the function being exported must be declared as `extern "C"`. If the
function has overloads, the pragma only applies to the overload with `extern "C"`
linkage. For example:

```c++
#pragma export(func)
int func(double) { return 0; }
extern "C" int func(int) { return 4;}
```

In the code above the pragma will export `func(int)` but not `func(double)`.

If none of the overloads are declared with `extern "C"` a warning will be
generated saying the pragma didn't resolve to a declaration. For example:

```c++
#pragma export(func)
int func(double) { return 0; } // warning: failed to resolve '#pragma export' to a declaration
```

## Overflow behavior types

Clang provides an extension that allows developers to annotate integer types
with explicit overflow behavior. This enables fine-grained control over whether
arithmetic operations should wrap on overflow (with two's complement semantics)
or be checked for overflow (trapping or reporting via sanitizers).

This feature is experimental and must be enabled with the `-cc1` option
`-fexperimental-overflow-behavior-types`.

Query for this feature with `__has_extension(overflow_behavior_types)`.

### Syntax

Overflow behavior can be specified using either attribute syntax or keyword
syntax:

**Attribute syntax:**

```c
typedef int __attribute__((overflow_behavior(wrap))) wrapping_int;
typedef int __attribute__((overflow_behavior(trap))) checked_int;
```

**Keyword syntax:**

```c
typedef int __ob_wrap wrapping_int;
typedef int __ob_trap checked_int;
```

The annotation can also be applied directly to variable declarations:

```c
int __ob_wrap counter = 0;
unsigned __ob_trap safe_index = 0;
```

### Semantics

**wrap behavior:**

When an integer type is annotated with `wrap` (or `__ob_wrap`), arithmetic
operations on values of that type use two's complement wrapping semantics on
overflow. This behavior is well-defined regardless of signedness. Compilers
must not optimize based on the assumption that overflow does not occur.

**trap behavior:**

When an integer type is annotated with `trap` (or `__ob_trap`), arithmetic
operations on values of that type are checked for overflow. If overflow occurs,
the program traps or reports via sanitizers (depending on compiler settings).

### Integer Promotions and Conversions

Overflow behavior types follow standard C integer promotion and conversion
rules. The overflow behavior annotation is preserved through implicit
promotions and conversions.

**Standard promotion rules apply:**

Integer literals without a suffix have type `int` (or a larger type if the
value requires it), following normal C rules. When such a literal is used in
an operation with an overflow behavior type, standard promotion rules determine
the result type, and the overflow behavior is propagated:

```c
typedef int __ob_wrap wrap_int;
wrap_int x = 100;
wrap_int y = x + 1;  // 1 is promoted; result is __ob_wrap int
```

**Combining different overflow behaviors:**

When operands have different overflow behaviors, `trap` takes precedence
over `wrap`:

```c
typedef int __ob_wrap wrap_int;
typedef int __ob_trap trap_int;
wrap_int a = 1;
trap_int b = 2;
auto c = a + b;  // Result is __ob_trap int (trap dominates)
```

**Conversion to standard types:**

When an overflow behavior type is converted to a standard integer type (without
an overflow behavior annotation), the overflow behavior is discarded. Compilers
may warn about this:

```c
typedef int __ob_wrap wrap_int;
wrap_int w = 42;
int i = w;  // Warning: discards overflow behavior
```

### Interaction with Compiler Flags

Overflow behavior annotations take precedence over global compiler flags:

- A `wrap` type wraps on overflow even when `-ftrapv` is enabled.
- A `trap` type is checked for overflow even when `-fwrapv` is enabled.

This allows mixing different overflow behaviors within the same program,
enabling developers to selectively apply wrapping or checking to specific
types while using different defaults elsewhere.

### Incompatible Assignments

Direct assignment between types with different overflow behaviors (`wrap`
vs `trap`) is an error:

```c
int __ob_wrap w;
int __ob_trap t;
w = t;  // Error: incompatible overflow behaviors
```

For more detailed documentation, see {doc}`OverflowBehaviorTypes`.

## Messages on `deprecated` and `unavailable` Attributes

An optional string message can be added to the `deprecated` and
`unavailable` attributes. For example:

```c++
void explode(void) __attribute__((deprecated("extremely unsafe, use 'combust' instead!!!")));
```

If the deprecated or unavailable declaration is used, the message will be
incorporated into the appropriate diagnostic:

```none
harmless.c:4:3: warning: 'explode' is deprecated: extremely unsafe, use 'combust' instead!!!
      [-Wdeprecated-declarations]
  explode();
  ^
```

Query for this feature with
`__has_extension(attribute_deprecated_with_message)` and
`__has_extension(attribute_unavailable_with_message)`.

## Attributes on Enumerators

Clang allows attributes to be written on individual enumerators. This allows
enumerators to be deprecated, made unavailable, etc. The attribute must appear
after the enumerator name and before any initializer, like so:

```c++
enum OperationMode {
  OM_Invalid,
  OM_Normal,
  OM_Terrified __attribute__((deprecated)),
  OM_AbortOnError __attribute__((deprecated)) = 4
};
```

Attributes on the `enum` declaration do not apply to individual enumerators.

Query for this feature with `__has_extension(enumerator_attributes)`.

## C++11 Attributes on using-declarations

Clang allows C++-style `[[]]` attributes to be written on using-declarations.
For instance:

```c++
[[clang::using_if_exists]] using foo::bar;
using foo::baz [[clang::using_if_exists]];
```

You can test for support for this extension with
`__has_extension(cxx_attributes_on_using_declarations)`.

## 'User-Specified' System Frameworks

Clang provides a mechanism by which frameworks can be built in such a way that
they will always be treated as being "system frameworks", even if they are not
present in a system framework directory. This can be useful to system
framework developers who want to be able to test building other applications
with development builds of their framework, including the manner in which the
compiler changes warning behavior for system headers.

Framework developers can opt-in to this mechanism by creating a
"`.system_framework`" file at the top-level of their framework. That is, the
framework should have contents like:

```none
.../TestFramework.framework
.../TestFramework.framework/.system_framework
.../TestFramework.framework/Headers
.../TestFramework.framework/Headers/TestFramework.h
...
```

Clang will treat the presence of this file as an indicator that the framework
should be treated as a system framework, regardless of how it was found in the
framework search path. For consistency, we recommend that such files never be
included in installed versions of the framework.

## Checks for Standard Language Features

The `__has_feature` macro can be used to query if certain standard language
features are enabled. The `__has_extension` macro can be used to query if
language features are available as an extension when compiling for a standard
which does not provide them. The features which can be tested are listed here.

Since Clang 3.4, the C++ SD-6 feature test macros are also supported.
These are macros with names of the form `__cpp_<feature_name>`, and are
intended to be a portable way to query the supported features of the compiler.
See [the C++ status page](https://clang.llvm.org/cxx_status.html#ts) for
information on the version of SD-6 supported by each Clang release, and the
macros provided by that revision of the recommendations.

### C++98

The features listed below are part of the C++98 standard. These features are
enabled by default when compiling C++ code.

#### C++ exceptions

Use `__has_feature(cxx_exceptions)` to determine if C++ exceptions have been
enabled. For example, compiling code with `-fno-exceptions` disables C++
exceptions.

#### C++ RTTI

Use `__has_feature(cxx_rtti)` to determine if C++ RTTI has been enabled. For
example, compiling code with `-fno-rtti` disables the use of RTTI.

### C++11

The features listed below are part of the C++11 standard. As a result, all
these features are enabled with the `-std=c++11` or `-std=gnu++11` option
when compiling C++ code.

#### C++11 SFINAE includes access control

Use `__has_feature(cxx_access_control_sfinae)` or
`__has_extension(cxx_access_control_sfinae)` to determine whether
access-control errors (e.g., calling a private constructor) are considered to
be template argument deduction errors (aka SFINAE errors), per [C++ DR1170](http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1170).

#### C++11 alias templates

Use `__has_feature(cxx_alias_templates)` or
`__has_extension(cxx_alias_templates)` to determine if support for C++11's
alias declarations and alias templates is enabled.

#### C++11 alignment specifiers

Use `__has_feature(cxx_alignas)` or `__has_extension(cxx_alignas)` to
determine if support for alignment specifiers using `alignas` is enabled.

Use `__has_feature(cxx_alignof)` or `__has_extension(cxx_alignof)` to
determine if support for the `alignof` keyword is enabled.

#### C++11 attributes

Use `__has_feature(cxx_attributes)` or `__has_extension(cxx_attributes)` to
determine if support for attribute parsing with C++11's square bracket notation
is enabled.

#### C++11 generalized constant expressions

Use `__has_feature(cxx_constexpr)` to determine if support for generalized
constant expressions (e.g., `constexpr`) is enabled.

#### C++11 `decltype()`

Use `__has_feature(cxx_decltype)` or `__has_extension(cxx_decltype)` to
determine if support for the `decltype()` specifier is enabled. C++11's
`decltype` does not require type-completeness of a function call expression.
Use `__has_feature(cxx_decltype_incomplete_return_types)` or
`__has_extension(cxx_decltype_incomplete_return_types)` to determine if
support for this feature is enabled.

#### C++11 default template arguments in function templates

Use `__has_feature(cxx_default_function_template_args)` or
`__has_extension(cxx_default_function_template_args)` to determine if support
for default template arguments in function templates is enabled.

#### C++11 `default`ed functions

Use `__has_feature(cxx_defaulted_functions)` or
`__has_extension(cxx_defaulted_functions)` to determine if support for
defaulted function definitions (with `= default`) is enabled.

#### C++11 delegating constructors

Use `__has_feature(cxx_delegating_constructors)` to determine if support for
delegating constructors is enabled.

#### C++11 `deleted` functions

Use `__has_feature(cxx_deleted_functions)` or
`__has_extension(cxx_deleted_functions)` to determine if support for deleted
function definitions (with `= delete`) is enabled.

#### C++11 explicit conversion functions

Use `__has_feature(cxx_explicit_conversions)` to determine if support for
`explicit` conversion functions is enabled.

#### C++11 generalized initializers

Use `__has_feature(cxx_generalized_initializers)` to determine if support for
generalized initializers (using braced lists and `std::initializer_list`) is
enabled.

#### C++11 implicit move constructors/assignment operators

Use `__has_feature(cxx_implicit_moves)` to determine if Clang will implicitly
generate move constructors and move assignment operators where needed.

#### C++11 inheriting constructors

Use `__has_feature(cxx_inheriting_constructors)` to determine if support for
inheriting constructors is enabled.

#### C++11 inline namespaces

Use `__has_feature(cxx_inline_namespaces)` or
`__has_extension(cxx_inline_namespaces)` to determine if support for inline
namespaces is enabled.

#### C++11 lambdas

Use `__has_feature(cxx_lambdas)` or `__has_extension(cxx_lambdas)` to
determine if support for lambdas is enabled.

#### C++11 local and unnamed types as template arguments

Use `__has_feature(cxx_local_type_template_args)` or
`__has_extension(cxx_local_type_template_args)` to determine if support for
local and unnamed types as template arguments is enabled.

#### C++11 noexcept

Use `__has_feature(cxx_noexcept)` or `__has_extension(cxx_noexcept)` to
determine if support for noexcept exception specifications is enabled.

#### C++11 in-class non-static data member initialization

Use `__has_feature(cxx_nonstatic_member_init)` to determine whether in-class
initialization of non-static data members is enabled.

#### C++11 `nullptr`

Use `__has_feature(cxx_nullptr)` or `__has_extension(cxx_nullptr)` to
determine if support for `nullptr` is enabled.

#### C++11 `override control`

Use `__has_feature(cxx_override_control)` or
`__has_extension(cxx_override_control)` to determine if support for the
override control keywords is enabled.

#### C++11 reference-qualified functions

Use `__has_feature(cxx_reference_qualified_functions)` or
`__has_extension(cxx_reference_qualified_functions)` to determine if support
for reference-qualified functions (e.g., member functions with `&` or `&&`
applied to `*this`) is enabled.

#### C++11 range-based `for` loop

Use `__has_feature(cxx_range_for)` or `__has_extension(cxx_range_for)` to
determine if support for the range-based for loop is enabled.

#### C++11 raw string literals

Use `__has_feature(cxx_raw_string_literals)` to determine if support for raw
string literals (e.g., `R"x(foo\bar)x"`) is enabled.

#### C++11 rvalue references

Use `__has_feature(cxx_rvalue_references)` or
`__has_extension(cxx_rvalue_references)` to determine if support for rvalue
references is enabled.

#### C++11 `static_assert()`

Use `__has_feature(cxx_static_assert)` or
`__has_extension(cxx_static_assert)` to determine if support for compile-time
assertions using `static_assert` is enabled.

#### C++11 `thread_local`

Use `__has_feature(cxx_thread_local)` to determine if support for
`thread_local` variables is enabled.

#### C++11 type inference

Use `__has_feature(cxx_auto_type)` or `__has_extension(cxx_auto_type)` to
determine C++11 type inference is supported using the `auto` specifier. If
this is disabled, `auto` will instead be a storage class specifier, as in C
or C++98.

#### C++11 strongly typed enumerations

Use `__has_feature(cxx_strong_enums)` or
`__has_extension(cxx_strong_enums)` to determine if support for strongly
typed, scoped enumerations is enabled.

#### C++11 trailing return type

Use `__has_feature(cxx_trailing_return)` or
`__has_extension(cxx_trailing_return)` to determine if support for the
alternate function declaration syntax with trailing return type is enabled.

#### C++11 Unicode string literals

Use `__has_feature(cxx_unicode_literals)` to determine if support for Unicode
string literals is enabled.

#### C++11 unrestricted unions

Use `__has_feature(cxx_unrestricted_unions)` to determine if support for
unrestricted unions is enabled.

#### C++11 user-defined literals

Use `__has_feature(cxx_user_literals)` to determine if support for
user-defined literals is enabled.

#### C++11 variadic templates

Use `__has_feature(cxx_variadic_templates)` or
`__has_extension(cxx_variadic_templates)` to determine if support for
variadic templates is enabled.

### C++14

The features listed below are part of the C++14 standard. As a result, all
these features are enabled with the `-std=C++14` or `-std=gnu++14` option
when compiling C++ code.

#### C++14 binary literals

Use `__has_feature(cxx_binary_literals)` or
`__has_extension(cxx_binary_literals)` to determine whether
binary literals (for instance, `0b10010`) are recognized. Clang supports this
feature as an extension in all language modes.

#### C++14 contextual conversions

Use `__has_feature(cxx_contextual_conversions)` or
`__has_extension(cxx_contextual_conversions)` to determine if the C++14 rules
are used when performing an implicit conversion for an array bound in a
*new-expression*, the operand of a *delete-expression*, an integral constant
expression, or a condition in a `switch` statement.

#### C++14 decltype(auto)

Use `__has_feature(cxx_decltype_auto)` or
`__has_extension(cxx_decltype_auto)` to determine if support
for the `decltype(auto)` placeholder type is enabled.

#### C++14 default initializers for aggregates

Use `__has_feature(cxx_aggregate_nsdmi)` or
`__has_extension(cxx_aggregate_nsdmi)` to determine if support
for default initializers in aggregate members is enabled.

#### C++14 digit separators

Use `__cpp_digit_separators` to determine if support for digit separators
using single quotes (for instance, `10'000`) is enabled. At this time, there
is no corresponding `__has_feature` name.

#### C++14 generalized lambda capture

Use `__has_feature(cxx_init_captures)` or
`__has_extension(cxx_init_captures)` to determine if support for
lambda captures with explicit initializers is enabled
(for instance, `[n(0)] { return ++n; }`).

#### C++14 generic lambdas

Use `__has_feature(cxx_generic_lambdas)` or
`__has_extension(cxx_generic_lambdas)` to determine if support for generic
(polymorphic) lambdas is enabled
(for instance, `[] (auto x) { return x + 1; }`).

#### C++14 relaxed constexpr

Use `__has_feature(cxx_relaxed_constexpr)` or
`__has_extension(cxx_relaxed_constexpr)` to determine if variable
declarations, local variable modification, and control flow constructs
are permitted in `constexpr` functions.

#### C++14 return type deduction

Use `__has_feature(cxx_return_type_deduction)` or
`__has_extension(cxx_return_type_deduction)` to determine if support
for return type deduction for functions (using `auto` as a return type)
is enabled.

#### C++14 runtime-sized arrays

Use `__has_feature(cxx_runtime_array)` or
`__has_extension(cxx_runtime_array)` to determine if support
for arrays of runtime bound (a restricted form of variable-length arrays)
is enabled.
Clang's implementation of this feature is incomplete.

#### C++14 variable templates

Use `__has_feature(cxx_variable_templates)` or
`__has_extension(cxx_variable_templates)` to determine if support for
templated variable declarations is enabled.

#### C++ type aware allocators

Use `__has_extension(cxx_type_aware_allocators)` to determine the existence of
support for the future C++2d type aware allocator feature. For full details, see
{doc}`C++ Type Aware Allocators <CXXTypeAwareAllocators>` for additional details.

### C11

The features listed below are part of the C11 standard. As a result, all these
features are enabled with the `-std=c11` or `-std=gnu11` option when
compiling C code. Additionally, because these features are all
backward-compatible, they are available as extensions in all language modes.

#### C11 alignment specifiers

Use `__has_feature(c_alignas)` or `__has_extension(c_alignas)` to determine
if support for alignment specifiers using `_Alignas` is enabled.

Use `__has_feature(c_alignof)` or `__has_extension(c_alignof)` to determine
if support for the `_Alignof` keyword is enabled.

#### C11 atomic operations

Use `__has_feature(c_atomic)` or `__has_extension(c_atomic)` to determine
if support for atomic types using `_Atomic` is enabled. Clang also provides
{ref}`a set of builtins <langext-c11-atomic>` which can be used to implement
the `<stdatomic.h>` operations on `_Atomic` types. Use
`__has_include(<stdatomic.h>)` to determine if C11's `<stdatomic.h>` header
is available.

Clang will use the system's `<stdatomic.h>` header when one is available, and
will otherwise use its own. When using its own, implementations of the atomic
operations are provided as macros. In the cases where C11 also requires a real
function, this header provides only the declaration of that function (along
with a shadowing macro implementation), and you must link to a library which
provides a definition of the function if you use it instead of the macro.

#### C11 generic selections

Use `__has_feature(c_generic_selections)` or
`__has_extension(c_generic_selections)` to determine if support for generic
selections is enabled.

As an extension, the C11 generic selection expression is available in all
languages supported by Clang. The syntax is the same as that given in the C11
standard.

In C, type compatibility is decided according to the rules given in the
appropriate standard, but in C++, which lacks the type compatibility rules used
in C, types are considered compatible only if they are equivalent.

Clang also supports an extended form of `_Generic` with a controlling type
rather than a controlling expression. Unlike with a controlling expression, a
controlling type argument does not undergo any conversions and thus is suitable
for use when trying to match qualified types, incomplete types, or function
types. Variable-length array types lack the necessary compile-time information
to resolve which association they match with and thus are not allowed as a
controlling type argument.

Use `__has_extension(c_generic_selection_with_controlling_type)` to determine
if support for this extension is enabled.

#### C11 `_Static_assert()`

Use `__has_feature(c_static_assert)` or `__has_extension(c_static_assert)`
to determine if support for compile-time assertions using `_Static_assert` is
enabled.

#### C11 `_Thread_local`

Use `__has_feature(c_thread_local)` or `__has_extension(c_thread_local)`
to determine if support for `_Thread_local` variables is enabled.

### C2y

The features listed below are part of the C2y standard. As a result, all these
features are enabled with the `-std=c2y` or `-std=gnu2y` option when
compiling C code.

#### C2y `_Countof`

Use `__has_feature(c_countof)` (in C2y or later mode) or
`__has_extension(c_countof)` (in C23 or earlier mode) to determine if support
for the `_Countof` operator is enabled. This feature is not available in C++
mode.

### Modules

Use `__has_feature(modules)` to determine if Modules have been enabled.
For example, compiling code with `-fmodules` enables the use of Modules.

More information can be found [here](Modules.md).

## Language Extensions Back-ported to Previous Standards

| Feature                                       | Feature Test Macro                 | Introduced In | Backported To |
| --------------------------------------------- | ---------------------------------- | ------------- | ------------- |
| variadic templates                            | \_\_cpp_variadic_templates         | C++11         | C++03         |
| Alias templates                               | \_\_cpp_alias_templates            | C++11         | C++03         |
| Non-static data member initializers           | \_\_cpp_nsdmi                      | C++11         | C++03         |
| Range-based `for` loop                        | \_\_cpp_range_based_for            | C++11         | C++03         |
| RValue references                             | \_\_cpp_rvalue_references          | C++11         | C++03         |
| Attributes                                    | \_\_cpp_attributes                 | C++11         | C++03         |
| Lambdas                                       | \_\_cpp_lambdas                    | C++11         | C++03         |
| Generalized lambda captures                   | \_\_cpp_init_captures              | C++14         | C++03         |
| Generic lambda expressions                    | \_\_cpp_generic_lambdas            | C++14         | C++03         |
| variable templates                            | \_\_cpp_variable_templates         | C++14         | C++03         |
| Binary literals                               | \_\_cpp_binary_literals            | C++14         | C++03         |
| Relaxed constexpr                             | \_\_cpp_constexpr                  | C++14         | C++11         |
| Static assert with no message                 | \_\_cpp_static_assert >= 201411L   | C++17         | C++11         |
| Pack expansion in generalized lambda-capture  | \_\_cpp_init_captures              | C++17         | C++03         |
| `if constexpr`                                | \_\_cpp_if_constexpr               | C++17         | C++11         |
| fold expressions                              | \_\_cpp_fold_expressions           | C++17         | C++03         |
| Lambda capture of \*this by value             | \_\_cpp_capture_star_this          | C++17         | C++03         |
| Attributes on enums                           | \_\_cpp_enumerator_attributes      | C++17         | C++03         |
| Guaranteed copy elision                       | \_\_cpp_guaranteed_copy_elision    | C++17         | C++03         |
| Hexadecimal floating literals                 | \_\_cpp_hex_float                  | C++17         | C++03         |
| `inline` variables                            | \_\_cpp_inline_variables           | C++17         | C++03         |
| Attributes on namespaces                      | \_\_cpp_namespace_attributes       | C++17         | C++11         |
| Structured bindings                           | \_\_cpp_structured_bindings        | C++17         | C++03         |
| template template arguments                   | \_\_cpp_template_template_args     | C++17         | C++03         |
| Familiar template syntax for generic lambdas  | \_\_cpp_generic_lambdas            | C++20         | C++03         |
| `static operator[]`                           | \_\_cpp_multidimensional_subscript | C++20         | C++03         |
| Designated initializers                       | \_\_cpp_designated_initializers    | C++20         | C++03         |
| Conditional `explicit`                        | \_\_cpp_conditional_explicit       | C++20         | C++03         |
| `using enum`                                  | \_\_cpp_using_enum                 | C++20         | C++03         |
| `auto` parameters                             |                                    | C++20         | C++03         |
| `if consteval`                                | \_\_cpp_if_consteval               | C++23         | C++20         |
| `static operator()`                           | \_\_cpp_static_call_operator       | C++23         | C++03         |
| Attributes on Lambda-Expressions              |                                    | C++23         | C++11         |
| Attributes on Structured Bindings             | \_\_cpp_structured_bindings        | C++26         | C++03         |
| Packs in Structured Bindings                  | \_\_cpp_structured_bindings        | C++26         | C++03         |
| Structured binding declaration as a condition | \_\_cpp_structured_bindings        | C++26         | C++98         |
| Static assert with user-generated message     | \_\_cpp_static_assert >= 202306L   | C++26         | C++11         |
| Pack Indexing                                 | \_\_cpp_pack_indexing              | C++26         | C++03         |
| `= delete ("should have a reason");`          | \_\_cpp_deleted_function           | C++26         | C++03         |
| Variadic Friends                              | \_\_cpp_variadic_friend            | C++26         | C++03         |
| Trivial Relocatability                        | \_\_cpp_trivial_relocatability     | C++26         | C++03         |
|``auto()`` cast                                | \_\_cpp_auto_cast                  | C++26         | C++03         |
| Pack Indexing for Template Names              | \_\_cpp_pack_indexing >= 202606L   | C++2d         | C++03         |
| Designated initializers (N494)                |                                    | C99           | C89           |
| `_Complex` (N693)                             |                                    | C99           | C89, C++      |
| `_Bool` (N815)                                |                                    | C99           | C89           |
| Variable-length arrays (N683)                 |                                    | C99           | C89, C++      |
| Flexible array members                        |                                    | C99           | C89, C++      |
| static and type quals in arrays               |                                    | C99           | C89           |
| `long long` (N601)                            |                                    | C99           | C89           |
| Hexadecimal floating constants (N308)         |                                    | C99           | C89           |
| Compound literals (N716)                      |                                    | C99           | C89, C++      |
| `//` comments (N644)                          |                                    | C99           | C89           |
| Mixed declarations and code (N740)            |                                    | C99           | C89           |
| init-statement in for (N740)                  |                                    | C99           | C89           |
| Variadic macros (N707)                        |                                    | C99           | C89           |
| Empty macro arguments (N570)                  |                                    | C99           | C89           |
| Trailing comma in enum declaration            |                                    | C99           | C89           |
| Implicit `return 0` in `main`                 |                                    | C99           | C89           |
| `__func__` (N611)                             |                                    | C99           | C89           |
| `_Generic` (N1441)                            |                                    | C11           | C89, C++      |
| `_Static_assert` (N1330)                      |                                    | C11           | C89, C++      |
| `_Atomic` (N1485)                             |                                    | C11           | C89, C++      |
| `_Thread_local` (N1364)                       |                                    | C11           | C89, C++      |
| Array & element qualification (N2607)         |                                    | C23           | C89           |
| Attributes (N2335)                            |                                    | C23           | C89           |
| `#embed` (N3017)                              |                                    | C23           | C89, C++      |
| Enum with fixed underlying type (N3030)       |                                    | C23           | C89           |
| `#warning` (N2686)                            |                                    | C23           | C89           |
| `_BitInt` (N3035)                             |                                    | C23           | C89, C++      |
| Binary literals (N2549)                       |                                    | C23           | C89           |
| Unnamed parameters in a function definition   |                                    | C23           | C89           |
| Free positioning of labels (N2508)            |                                    | C23           | C89           |
| `#elifdef` (N2645)                            |                                    | C23           | C89           |
| `__has_include` (N2799)                       |                                    | C23           | C89           |
| Octal literals prefixed with `0o` or `0O`     |                                    | C2y           | C89, C++      |
| `_Countof` (N3369, N3469)                     |                                    | C2y           | C89           |
| `_Generic` with a type operand (N3260)        |                                    | C2y           | C89, C++      |
| `++`/`--` on `_Complex` value (N3259)         |                                    | C2y           | C89, C++      |
| `__COUNTER__` (N3457)                         |                                    | C2y           | C89, C++      |
| If declarations (N3356)                       |                                    | C2y           | C89           |

## Builtin type aliases

Clang provides a few builtin aliases to improve the throughput of certain metaprogramming facilities.

### \_\_builtin_common_type

```c++
template <template <class... Args> class BaseTemplate,
          template <class TypeMember> class HasTypeMember,
          class HasNoTypeMember,
          class... Ts>
using __builtin_common_type = ...;
```

This alias is used for implementing `std::common_type`. If `std::common_type` should contain a `type` member,
it is an alias to `HasTypeMember<TheCommonType>`. Otherwise it is an alias to `HasNoTypeMember`. The
`BaseTemplate` is usually `std::common_type`. `Ts` are the arguments to `std::common_type`.

### \_\_type_pack_element

```c++
template <std::size_t Index, class... Ts>
using __type_pack_element = ...;
```

This alias returns the type at `Index` in the parameter pack `Ts`.

### \_\_make_integer_seq

```c++
template <template <class IntSeqT, IntSeqT... Ints> class IntSeq, class T, T N>
using __make_integer_seq = ...;
```

This alias returns `IntSeq` instantiated with `IntSeqT = T` and `Ints` being the pack `0, ..., N - 1`.

### \_\_builtin_dedup_pack

```c++
template <class... Ts>
using __builtin_dedup_pack = ...;
```

This alias takes a template parameter pack `Ts` and produces a new unexpanded pack containing the unique types
from `Ts`, with the order of the first occurrence of each type preserved.
It is useful in template metaprogramming to normalize type lists.

The resulting pack can be expanded in contexts like template argument lists or base specifiers.

**Example of Use**:

```c++
template <typename...> struct TypeList;

// The resulting type is TypeList<int, double, char>
template <typename ...ExtraTypes>
using MyTypeList = TypeList<__builtin_dedup_pack<int, double, int, char, double, ExtraTypes...>...>;
```

**Limitations**:

- This builtin can only be used inside a template.
- The resulting pack is currently only supported for expansion in template argument lists and base specifiers.
- This builtin cannot be assigned to a template template parameter.

### \_\_builtin_sort_pack

```c++
template <class... Ts>
using __builtin_sort_pack = ...;
```

This alias takes a template parameter pack `Ts` and produces a new unexpanded pack containing the same types
sorted by [`__builtin_type_order`](#builtin-type-order).

The resulting pack can be expanded in contexts like template argument lists or base specifiers.

**Example of Use**:

```c++
template <typename...> struct TypeList;

// Combined with `__builtin_dedup_pack` to canonicalize a type list.
template <typename ...ExtraTypes>
using MyTypeList = TypeList<
    __builtin_sort_pack<__builtin_dedup_pack<int, double, ExtraTypes...>...>...>;
```

**Limitations**:

- This builtin can only be used inside a template.
- The resulting pack is currently only supported for expansion in template argument lists and base specifiers.
- This builtin cannot be assigned to a template template parameter.

## Type Trait Primitives

Type trait primitives are special builtin constant expressions that can be used
by the standard C++ library to facilitate or simplify the implementation of
user-facing type traits in the `<type_traits>` header.

They are not intended to be used directly by user code because they are
implementation-defined and subject to change -- as such they're tied closely to
the supported set of system headers, currently:

- LLVM's own libc++
- GNU libstdc++
- The Microsoft standard C++ library

Clang supports the [GNU C++ type traits](https://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html) and a subset of the
[Microsoft Visual C++ type traits](<https://msdn.microsoft.com/en-us/library/ms177194(v=VS.100).aspx>),
as well as nearly all of the
[Embarcadero C++ type traits](<http://docwiki.embarcadero.com/RADStudio/Rio/en/Type_Trait_Functions_(C%2B%2B11)_Index>).

The following type trait primitives are supported by Clang. Those traits marked
(C++) provide implementations for type traits specified by the C++ standard;
`__X(...)` has the same semantics and constraints as the corresponding
`std::X_t<...>` or `std::X_v<...>` type trait.

- `__array_rank(type)` (Embarcadero):
  Returns the number of levels of array in the type `type`:
  `0` if `type` is not an array type, and
  `__array_rank(element) + 1` if `type` is an array of `element`.
- `__array_extent(type, dim)` (Embarcadero):
  The `dim`'th array bound in the type `type`, or `0` if
  `dim >= __array_rank(type)`.
- `__builtin_is_implicit_lifetime` (C++, GNU, Microsoft)
- `__builtin_is_virtual_base_of` (C++, GNU, Microsoft)
- `__can_pass_in_regs` (C++)
  Returns whether a class can be passed in registers under the current
  ABI. This type can only be applied to unqualified class types.
  This is not a portable type trait.
- `__has_nothrow_assign` (GNU, Microsoft, Embarcadero):
  Deprecated, use `__is_nothrow_assignable` instead.
- `__has_nothrow_move_assign` (GNU, Microsoft):
  Deprecated, use `__is_nothrow_assignable` instead.
- `__has_nothrow_copy` (GNU, Microsoft):
  Deprecated, use `__is_nothrow_constructible` instead.
- `__has_nothrow_constructor` (GNU, Microsoft):
  Deprecated, use `__is_nothrow_constructible` instead.
- `__has_trivial_assign` (GNU, Microsoft, Embarcadero):
  Deprecated, use `__is_trivially_assignable` instead.
- `__has_trivial_move_assign` (GNU, Microsoft):
  Deprecated, use `__is_trivially_assignable` instead.
- `__has_trivial_copy` (GNU, Microsoft):
  Deprecated, use `__is_trivially_copyable` instead.
- `__has_trivial_constructor` (GNU, Microsoft):
  Deprecated, use `__is_trivially_constructible` instead.
- `__has_trivial_move_constructor` (GNU, Microsoft):
  Deprecated, use `__is_trivially_constructible` instead.
- `__has_trivial_destructor` (GNU, Microsoft, Embarcadero):
  Deprecated, use `__is_trivially_destructible` instead.
- `__has_unique_object_representations` (C++, GNU)
- `__has_virtual_destructor` (C++, GNU, Microsoft, Embarcadero)
- `__is_abstract` (C++, GNU, Microsoft, Embarcadero)
- `__is_aggregate` (C++, GNU, Microsoft)
- `__is_arithmetic` (C++, Embarcadero)
- `__is_array` (C++, Embarcadero)
- `__is_assignable` (C++, MSVC 2015)
- `__is_base_of` (C++, GNU, Microsoft, Embarcadero)
- `__is_bounded_array` (C++, GNU, Microsoft, Embarcadero)
- `__is_class` (C++, GNU, Microsoft, Embarcadero)
- `__is_complete_type(type)` (Embarcadero):
  Return `true` if `type` is a complete type.
  Warning: this trait is dangerous because it can return different values at
  different points in the same program.
- `__is_compound` (C++, Embarcadero)
- `__is_const` (C++, Embarcadero)
- `__is_constructible` (C++, MSVC 2013)
- `__is_convertible` (C++, Embarcadero)
- `__is_nothrow_convertible` (C++, GNU)
- `__is_convertible_to` (Microsoft):
  Synonym for `__is_convertible`.
- `__is_destructible` (C++, MSVC 2013)
- `__is_empty` (C++, GNU, Microsoft, Embarcadero)
- `__is_enum` (C++, GNU, Microsoft, Embarcadero)
- `__is_final` (C++, GNU, Microsoft)
- `__is_floating_point` (C++, Embarcadero)
- `__is_function` (C++, Embarcadero)
- `__is_fundamental` (C++, Embarcadero)
- `__is_integral` (C++, Embarcadero)
- `__is_interface_class` (Microsoft):
  Returns `false`, even for types defined with `__interface`.
- `__is_layout_compatible` (C++, GNU, Microsoft)
- `__is_literal` (Clang):
  Synonym for `__is_literal_type`.
- `__is_literal_type` (C++, GNU, Microsoft):
  Note, the corresponding standard trait was deprecated in C++17
  and removed in C++20.
- `__is_lvalue_reference` (C++, Embarcadero)
- `__is_member_object_pointer` (C++, Embarcadero)
- `__is_member_function_pointer` (C++, Embarcadero)
- `__is_member_pointer` (C++, Embarcadero)
- `__is_nothrow_assignable` (C++, MSVC 2013)
- `__is_nothrow_constructible` (C++, MSVC 2013)
- `__is_nothrow_destructible` (C++, MSVC 2013)
- `__is_object` (C++, Embarcadero)
- `__is_pod` (C++, GNU, Microsoft, Embarcadero):
  Note, the corresponding standard trait was deprecated in C++20.
- `__is_pointer` (C++, Embarcadero)
- `__is_pointer_interconvertible_base_of` (C++, GNU, Microsoft)
- `__is_polymorphic` (C++, GNU, Microsoft, Embarcadero)
- `__is_reference` (C++, Embarcadero)
- `__is_rvalue_reference` (C++, Embarcadero)
- `__is_same` (C++, Embarcadero)
- `__is_same_as` (GCC): Synonym for `__is_same`.
- `__is_scalar` (C++, Embarcadero)
- `__is_scoped_enum` (C++, GNU, Microsoft, Embarcadero)
- `__is_sealed` (Microsoft):
  Synonym for `__is_final`.
- `__is_signed` (C++, Embarcadero):
  Returns false for enumeration types, and returns true for floating-point
  types. Note, before Clang 10, returned true for enumeration types if the
  underlying type was signed, and returned false for floating-point types.
- `__is_standard_layout` (C++, GNU, Microsoft, Embarcadero)
- `__is_trivial` (C++, GNU, Microsoft, Embarcadero)
- `__is_trivially_assignable` (C++, GNU, Microsoft)
- `__is_trivially_constructible` (C++, GNU, Microsoft)
- `__is_trivially_copyable` (C++, GNU, Microsoft)
- `__is_trivially_destructible` (C++, MSVC 2013)
- `__is_trivially_relocatable` (Clang) (Deprecated,
  use `__builtin_is_cpp_trivially_relocatable` instead).
  Returns true if moving an object
  of the given type, and then destroying the source object, is known to be
  functionally equivalent to copying the underlying bytes and then dropping the
  source object on the floor. This is true of trivial types,
  C++26 relocatable types, and types which
  were made trivially relocatable via the `clang::trivial_abi` attribute.
  This trait is deprecated and should be replaced by
  `__builtin_is_cpp_trivially_relocatable`. Note, however, that it is generally
  unsafe to relocate a C++-relocatable type with `memcpy` or `memmove`;
  use `__builtin_trivially_relocate`.
- `__builtin_is_cpp_trivially_relocatable` (C++): Returns true if an object
  is trivially relocatable, as defined by the C++26 standard [meta.unary.prop].
  Note that when relocating the caller code should ensure that if the object is polymorphic,
  the dynamic type is of the most derived type. Padding bytes should not be copied.
- `__is_trivially_equality_comparable` (Clang): Returns true if comparing two
  objects of the provided type is known to be equivalent to comparing their
  object representations. Note that types containing padding bytes are never
  trivially equality comparable.
- `__is_unbounded_array` (C++, GNU, Microsoft, Embarcadero)
- `__is_union` (C++, GNU, Microsoft, Embarcadero)
- `__is_unsigned` (C++, Embarcadero):
  Returns false for enumeration types. Note, before Clang 13, returned true for
  enumeration types if the underlying type was unsigned.
- `__is_void` (C++, Embarcadero)
- `__is_volatile` (C++, Embarcadero)
- `__reference_binds_to_temporary(T, U)` (Clang): Determines whether a
  reference of type `T` bound to an expression of type `U` would bind to a
  materialized temporary object. If `T` is not a reference type, the result
  is false. Note this trait will also return false when the initialization of
  `T` from `U` is ill-formed.
  Deprecated, use `__reference_constructs_from_temporary`.
- `__reference_constructs_from_temporary(T, U)` (C++)
  Returns true if a reference `T` can be direct-initialized from a temporary of type
  a non-cv-qualified `U`.
- `__reference_converts_from_temporary(T, U)` (C++)
  : Returns true if a reference `T` can be copy-initialized from a temporary of type
    a non-cv-qualified `U`.
- `__underlying_type` (C++, GNU, Microsoft)
- `__builtin_lt_synthesizes_from_spaceship`, `__builtin_gt_synthesizes_from_spaceship`,
  `__builtin_le_synthesizes_from_spaceship`, `__builtin_ge_synthesizes_from_spaceship` (Clang):
  These builtins can be used to determine whether the corresponding operator is synthesized from a spaceship operator.
- (builtin-type-order)=
  `__builtin_type_order` (C++): Returns `std::strong_ordering::less` if `T` precedes `U` in an
  implementation-defined total ordering of all types, `std::strong_ordering::greater` if `U` precedes `T`,
  and `std::strong_ordering::equal` if they are the same type.
  The order is stable across translation units for a given platform/ABI.

In addition, the following expression traits are supported:

- `__is_lvalue_expr(e)` (Embarcadero):
  Returns true if `e` is an lvalue expression.
  Deprecated, use `__is_lvalue_reference(decltype((e)))` instead.
- `__is_rvalue_expr(e)` (Embarcadero):
  Returns true if `e` is a prvalue expression.
  Deprecated, use `!__is_reference(decltype((e)))` instead.

There are multiple ways to detect support for a type trait `__X` in the
compiler, depending on the oldest version of Clang you wish to support.

- From Clang 10 onwards, `__has_builtin(__X)` can be used.

- From Clang 6 onwards, `!__is_identifier(__X)` can be used.

- From Clang 3 onwards, `__has_feature(X)` can be used, but only supports
  the following traits:

  - `__has_nothrow_assign`
  - `__has_nothrow_copy`
  - `__has_nothrow_constructor`
  - `__has_trivial_assign`
  - `__has_trivial_copy`
  - `__has_trivial_constructor`
  - `__has_trivial_destructor`
  - `__has_virtual_destructor`
  - `__is_abstract`
  - `__is_base_of`
  - `__is_class`
  - `__is_constructible`
  - `__is_convertible_to`
  - `__is_empty`
  - `__is_enum`
  - `__is_final`
  - `__is_literal`
  - `__is_standard_layout`
  - `__is_pod`
  - `__is_polymorphic`
  - `__is_sealed`
  - `__is_trivial`
  - `__is_trivially_assignable`
  - `__is_trivially_constructible`
  - `__is_trivially_copyable`
  - `__is_union`
  - `__underlying_type`

A simplistic usage example as might be seen in standard C++ headers follows:

```c++
#if __has_builtin(__is_convertible_to)
template<typename From, typename To>
struct is_convertible_to {
  static const bool value = __is_convertible_to(From, To);
};
#else
// Emulate type trait for compatibility with other compilers.
#endif
```

(builtin_structured_binding_size-doc)=
(builtin-structured-binding-size-doc)=

### \_\_builtin_structured_binding_size (C++)

The `__builtin_structured_binding_size(T)` type trait returns
the *structured binding size* ([dcl.struct.bind]) of type `T`

This is equivalent to the size of the pack `p` in `auto&& [...p] = declval<T&>();`.
If the argument cannot be decomposed, `__builtin_structured_binding_size(T)`
is not a valid expression (`__builtin_structured_binding_size` is SFINAE-friendly).

builtin arrays, builtin SIMD vectors,
builtin complex types, *tuple-like* types, and decomposable class types
are decomposable types.

A type is considered a valid *tuple-like* if `std::tuple_size_v<T>` is a valid expression,
even if there is no valid `std::tuple_element` specialization or suitable
`get` function for that type.

```c++
template<std::size_t Idx, typename T>
requires (Idx < __builtin_structured_binding_size(T))
decltype(auto) constexpr get_binding(T&& obj) {
    auto && [...p] = std::forward<T>(obj);
    return p...[Idx];
}
struct S { int a = 0, b = 42; };
static_assert(__builtin_structured_binding_size(S) == 2);
static_assert(get_binding<1>(S{}) == 42);
```

## Blocks

The syntax and high-level language feature description is in
{doc}`BlockLanguageSpec<BlockLanguageSpec>`. Implementation and ABI details for
the clang implementation are in {doc}`Block-ABI-Apple<Block-ABI-Apple>`.

Query for this feature with `__has_extension(blocks)`.

## ASM Goto with Output Constraints

Outputs may be used along any branches from the `asm goto` whether the
branches are taken or not.

Query for this feature with `__has_extension(gnu_asm_goto_with_outputs)`.

Prior to clang-16, the output may only be used safely when the indirect
branches are not taken. Query for this difference with
`__has_extension(gnu_asm_goto_with_outputs_full)`.

When using tied-outputs (i.e., outputs that are inputs and outputs, not just
outputs) with the `+r` constraint, there is a hidden input that's created
before the label, so numeric references to operands must account for that.

```c++
int foo(int x) {
    // %0 and %1 both refer to x
    // %l2 refers to err
    asm goto("# %0 %1 %l2" : "+r"(x) : : : err);
    return x;
  err:
    return -1;
}
```

This was changed to match GCC in clang-13; for better portability, symbolic
references can be used instead of numeric references.

```c++
int foo(int x) {
    asm goto("# %[x] %l[err]" : [x]"+r"(x) : : : err);
    return x;
  err:
    return -1;
}
```

## ASM Goto versus Branch Target Enforcement

Some target architectures implement branch target enforcement, by requiring
indirect (register-controlled) branch instructions to jump only to locations
marked by a special instruction (such as AArch64 `bti`).

The assembler code inside an `asm goto` statement is expected not to use a
branch instruction of that kind to transfer control to any of its destination
labels. Therefore, using a label in an `asm goto` statement does not cause
clang to put a `bti` or equivalent instruction at the label.

## Constexpr strings in GNU ASM statements

In C++11 mode (and greater), Clang supports specifying the template,
constraints, and clobber strings with a parenthesized constant expression
producing an object with the following member functions

```c++
constexpr const char* data() const;
constexpr size_t size() const;
```

such as `std::string`, `std::string_view`, `std::vector<char>`.
This mechanism follows the same rules as `static_assert` messages in
C++26, see `[dcl.pre]/p12`.

Query for this feature with `__has_extension(gnu_asm_constexpr_strings)`.

```c++
int foo() {
   asm((std::string_view("nop")) ::: (std::string_view("memory")));
}
```

## Objective-C Features

### Related result types

According to Cocoa conventions, Objective-C methods with certain names
("`init`", "`alloc`", etc.) always return objects that are an instance of
the receiving class's type. Such methods are said to have a "related result
type", meaning that a message send to one of these methods will have the same
static type as an instance of the receiver class. For example, given the
following classes:

```objc
@interface NSObject
+ (id)alloc;
- (id)init;
@end

@interface NSArray : NSObject
@end
```

and this common initialization pattern

```objc
NSArray *array = [[NSArray alloc] init];
```

the type of the expression `[NSArray alloc]` is `NSArray*` because
`alloc` implicitly has a related result type. Similarly, the type of the
expression `[[NSArray alloc] init]` is `NSArray*`, since `init` has a
related result type and its receiver is known to have the type `NSArray *`.
If neither `alloc` nor `init` had a related result type, the expressions
would have had type `id`, as declared in the method signature.

A method with a related result type can be declared by using the type
`instancetype` as its result type. `instancetype` is a contextual keyword
that is only permitted in the result type of an Objective-C method, e.g.

```objc
@interface A
+ (instancetype)constructAnA;
@end
```

The related result type can also be inferred for some methods. To determine
whether a method has an inferred related result type, the first word in the
camel-case selector (e.g., "`init`" in "`initWithObjects`") is considered,
and the method will have a related result type if its return type is compatible
with the type of its class and if:

- the first word is "`alloc`" or "`new`", and the method is a class method,
  or
- the first word is "`autorelease`", "`init`", "`retain`", or "`self`",
  and the method is an instance method.

If a method with a related result type is overridden by a subclass method, the
subclass method must also return a type that is compatible with the subclass
type. For example:

```objc
@interface NSString : NSObject
- (NSUnrelated *)init; // incorrect usage: NSUnrelated is not NSString or a superclass of NSString
@end
```

Related result types only affect the type of a message send or property access
via the given method. In all other respects, a method with a related result
type is treated the same way as method that returns `id`.

Use `__has_feature(objc_instancetype)` to determine whether the
`instancetype` contextual keyword is available.

### Automatic reference counting

Clang provides support for {doc}`automated reference counting
<AutomaticReferenceCounting>` in Objective-C, which eliminates the need
for manual `retain`/`release`/`autorelease` message sends. There are three
feature macros associated with automatic reference counting:
`__has_feature(objc_arc)` indicates the availability of automated reference
counting in general, while `__has_feature(objc_arc_weak)` indicates that
automated reference counting also includes support for `__weak` pointers to
Objective-C objects. `__has_feature(objc_arc_fields)` indicates that C structs
are allowed to have fields that are pointers to Objective-C objects managed by
automatic reference counting.

(objc-weak)=

### Weak references

Clang supports ARC-style weak and unsafe references in Objective-C even
outside of ARC mode. Weak references must be explicitly enabled with
the `-fobjc-weak` option; use `__has_feature((objc_arc_weak))`
to test whether they are enabled. Unsafe references are enabled
unconditionally. ARC-style weak and unsafe references cannot be used
when Objective-C garbage collection is enabled.

Except as noted below, the language rules for the `__weak` and
`__unsafe_unretained` qualifiers (and the `weak` and
`unsafe_unretained` property attributes) are just as laid out
in the {doc}`ARC specification <AutomaticReferenceCounting>`.
In particular, note that some classes do not support forming weak
references to their instances, and note that special care must be
taken when storing weak references in memory where initialization
and deinitialization are outside the responsibility of the compiler
(such as in `malloc`-ed memory).

Loading from a `__weak` variable always implicitly retains the
loaded value. In non-ARC modes, this retain is normally balanced
by an implicit autorelease. This autorelease can be suppressed
by performing the load in the receiver position of a `-retain`
message send (e.g., `[weakReference retain]`); note that this performs
only a single retain (the retain done when primitively loading from
the weak reference).

For the most part, `__unsafe_unretained` in non-ARC modes is just the
default behavior of variables and therefore is not needed. However,
it does have an effect on the semantics of block captures: normally,
copying a block which captures an Objective-C object or block pointer
causes the captured pointer to be retained or copied, respectively,
but that behavior is suppressed when the captured variable is qualified
with `__unsafe_unretained`.

Note that the `__weak` qualifier formerly meant the GC qualifier in
all non-ARC modes and was silently ignored outside of GC modes. It now
means the ARC-style qualifier in all non-GC modes and is no longer
allowed if not enabled by either `-fobjc-arc` or `-fobjc-weak`.
It is expected that `-fobjc-weak` will eventually be enabled by default
in all non-GC Objective-C modes.

(objc-fixed-enum)=

### Enumerations with a fixed underlying type

Clang provides support for C++11 enumerations with a fixed underlying type
within Objective-C and C [prior to C23](https://open-std.org/JTC1/SC22/WG14/www/docs/n3030.htm). For example, one can write an enumeration type as:

```c++
typedef enum : unsigned char { Red, Green, Blue } Color;
```

This specifies that the underlying type, which is used to store the enumeration
value, is `unsigned char`.

Use `__has_feature(objc_fixed_enum)` to determine whether support for fixed
underlying types is available in Objective-C.

Use `__has_extension(c_fixed_enum)` to determine whether support for fixed
underlying types is available in C prior to C23. This will also report `true` in C23
and later modes as the functionality is available even if it's not an extension in
those modes.

Use `__has_feature(c_fixed_enum)` to determine whether support for fixed
underlying types is available in C23 and later.

### Enumerations with no enumerators

Clang provides support for Microsoft extensions to support enumerations with no enumerators.

```c++
typedef enum empty { } A;
```

### Microsoft Anonymous Structs and Unions

Clang provides support for a Microsoft extension that allows use of named struct or union types to
declare anonymous members inside another struct or union, making their fields directly accessible
from the enclosing type.

For example, consider the following code:

```c
struct Inner {
    int x;
    int y;
};

struct Outer {
    struct Inner;  /* Microsoft extension: named anonymous struct member */
};

void f(struct Outer *o) {
    o->x = 1;      /* accesses x member of anonymous member of type Inner directly */
    o->y = 1;      /* accesses x member of anonymous member of type Inner directly */
}
```

Without this extension, such declarations generate a warning that the declaration does not
declare anything, the associated member names are not available for access, and the layout
of types containing such declarations are affected accordingly.

This extension can be controlled independently of other Microsoft extensions:

`-fms-anonymous-structs`
: Enable named anonymous struct/union support

`-fno-ms-anonymous-structs`
: Disable anonymous struct/union support

This extension is also **implicitly enabled** when either of the following options is used:

- `-fms-extensions`
- `-fms-compatibility`

When multiple controlling options are specified, the last option on the command line takes
precedence.

### Interoperability with C++11 lambdas

Clang provides interoperability between C++11 lambdas and blocks-based APIs, by
permitting a lambda to be implicitly converted to a block pointer with the
corresponding signature. For example, consider an API such as `NSArray`'s
array-sorting method:

```objc
- (NSArray *)sortedArrayUsingComparator:(NSComparator)cmptr;
```

`NSComparator` is simply a typedef for the block pointer `NSComparisonResult
(^)(id, id)`, and parameters of this type are generally provided with block
literals as arguments. However, one can also use a C++11 lambda so long as it
provides the same signature (in this case, accepting two parameters of type
`id` and returning an `NSComparisonResult`):

```objc
NSArray *array = @[@"string 1", @"string 21", @"string 12", @"String 11",
                   @"String 02"];
const NSStringCompareOptions comparisonOptions
  = NSCaseInsensitiveSearch | NSNumericSearch |
    NSWidthInsensitiveSearch | NSForcedOrderingSearch;
NSLocale *currentLocale = [NSLocale currentLocale];
NSArray *sorted
  = [array sortedArrayUsingComparator:[=](id s1, id s2) -> NSComparisonResult {
             NSRange string1Range = NSMakeRange(0, [s1 length]);
             return [s1 compare:s2 options:comparisonOptions
             range:string1Range locale:currentLocale];
     }];
NSLog(@"sorted: %@", sorted);
```

This code relies on an implicit conversion from the type of the lambda
expression (an unnamed, local class type called the *closure type*) to the
corresponding block pointer type. The conversion itself is expressed by a
conversion operator in that closure type that produces a block pointer with the
same signature as the lambda itself, e.g.,

```objc
operator NSComparisonResult (^)(id, id)() const;
```

This conversion function returns a new block that simply forwards the two
parameters to the lambda object (which it captures by copy), then returns the
result. The returned block is first copied (with `Block_copy`) and then
autoreleased. As an optimization, if a lambda expression is immediately
converted to a block pointer (as in the first example, above), then the block
is not copied and autoreleased: rather, it is given the same lifetime as a
block literal written at that point in the program, which avoids the overhead
of copying a block to the heap in the common case.

The conversion from a lambda to a block pointer is only available in
Objective-C++, and not in C++ with blocks, due to its use of Objective-C memory
management (autorelease).

### Object Literals and Subscripting

Clang provides support for {doc}`Object Literals and Subscripting
<ObjectiveCLiterals>` in Objective-C, which simplifies common Objective-C
programming patterns, makes programs more concise, and improves the safety of
container creation. There are several feature macros associated with object
literals and subscripting: `__has_feature(objc_array_literals)` tests the
availability of array literals; `__has_feature(objc_dictionary_literals)`
tests the availability of dictionary literals; `objc_constant_literals`
tests the availability of having number, array, and dictionary literals
emitted at compile time; `__has_feature(objc_subscripting)` tests the availability of object
subscripting.

### Objective-C Autosynthesis of Properties

Clang provides support for autosynthesis of declared properties. Using this
feature, clang provides default synthesis of those properties not declared
@dynamic and not having user-provided backing getter and setter methods.
`__has_feature(objc_default_synthesize_properties)` checks for availability
of this feature in version of clang being used.

(langext-objc-retain-release)=

### Objective-C retaining behavior attributes

In Objective-C, functions and methods are generally assumed to follow the
[Cocoa Memory Management](https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmRules.html)
conventions for ownership of object arguments and
return values. However, there are exceptions, and so Clang provides attributes
to allow these exceptions to be documented. These are used by ARC and the
[static analyzer](https://clang-analyzer.llvm.org) Some exceptions may be
better described using the `objc_method_family` attribute instead.

**Usage**: The `ns_returns_retained`, `ns_returns_not_retained`,
`ns_returns_autoreleased`, `cf_returns_retained`, and
`cf_returns_not_retained` attributes can be placed on methods and functions
that return Objective-C or CoreFoundation objects. They are commonly placed at
the end of a function prototype or method declaration:

```objc
id foo() __attribute__((ns_returns_retained));

- (NSString *)bar:(int)x __attribute__((ns_returns_retained));
```

The `*_returns_retained` attributes specify that the returned object has a +1
retain count. The `*_returns_not_retained` attributes specify that the return
object has a +0 retain count, even if the normal convention for its selector
would be +1. `ns_returns_autoreleased` specifies that the returned object is
+0, but is guaranteed to live at least as long as the next flush of an
autorelease pool.

**Usage**: The `ns_consumed` and `cf_consumed` attributes can be placed on
a parameter declaration; they specify that the argument is expected to have a
+1 retain count, which will be balanced in some way by the function or method.
The `ns_consumes_self` attribute can only be placed on an Objective-C
method; it specifies that the method expects its `self` parameter to have a
+1 retain count, which it will balance in some way.

```objc
void foo(__attribute__((ns_consumed)) NSString *string);

- (void) bar __attribute__((ns_consumes_self));
- (void) baz:(id) __attribute__((ns_consumed)) x;
```

Further examples of these attributes are available in the static analyzer's
{ref}`list of annotations for analysis <cocoa_mem>`.

Query for these features with `__has_attribute(ns_consumed)`,
`__has_attribute(ns_returns_retained)`, etc.

(langext-objective-c-available)=

### Objective-C @available

It is possible to use the newest SDK but still build a program that can run on
older versions of macOS and iOS by passing `-mmacos-version-min=` /
`-miphoneos-version-min=`.

Before LLVM 5.0, when calling a function that exists only in the OS that's
newer than the target OS (as determined by the minimum deployment version),
programmers had to carefully check if the function exists at runtime, using
null checks for weakly-linked C functions, `+class` for Objective-C classes,
and `-respondsToSelector:` or `+instancesRespondToSelector:` for
Objective-C methods. If such a check was missed, the program would compile
fine, run fine on newer systems, but crash on older systems.

As of LLVM 5.0, `-Wunguarded-availability` uses the [availability attributes](AttributeReference.md#availability) together
with the new `@available()` keyword to assist with this issue.
When a method that's introduced in the OS newer than the target OS is called, a
-Wunguarded-availability warning is emitted if that call is not guarded:

```objc
void my_fun(NSSomeClass* var) {
  // If fancyNewMethod was added in e.g., macOS 10.12, but the code is
  // built with -mmacos-version-min=10.11, then this unconditional call
  // will emit a -Wunguarded-availability warning:
  [var fancyNewMethod];
}
```

To fix the warning and to avoid the crash on macOS 10.11, wrap it in
`if(@available())`:

```objc
void my_fun(NSSomeClass* var) {
  if (@available(macOS 10.12, *)) {
    [var fancyNewMethod];
  } else {
    // Put fallback behavior for old macOS versions (and for non-mac
    // platforms) here.
  }
}
```

The `*` is required and means that platforms not explicitly listed will take
the true branch, and the compiler will emit `-Wunguarded-availability`
warnings for unlisted platforms based on those platform's deployment target.
More than one platform can be listed in `@available()`:

```objc
void my_fun(NSSomeClass* var) {
  if (@available(macOS 10.12, iOS 10, *)) {
    [var fancyNewMethod];
  }
}
```

If the caller of `my_fun()` already checks that `my_fun()` is only called
on 10.12, then add an [availability attribute](AttributeReference.md#availability) to it,
which will also suppress the warning and require that calls to my_fun() are
checked:

```objc
API_AVAILABLE(macos(10.12)) void my_fun(NSSomeClass* var) {
  [var fancyNewMethod];  // Now ok.
}
```

`@available()` is only available in Objective-C code. To use the feature
in C and C++ code, use the `__builtin_available()` spelling instead.

If existing code uses null checks or `-respondsToSelector:`, it should
be changed to use `@available()` (or `__builtin_available`) instead.

`-Wunguarded-availability` is disabled by default, but
`-Wunguarded-availability-new`, which only emits this warning for APIs
that have been introduced in macOS >= 10.13, iOS >= 11, watchOS >= 4 and
tvOS >= 11, is enabled by default.

(langext-overloading)=

### Objective-C++ ABI: protocol-qualifier mangling of parameters

Starting with LLVM 3.4, Clang produces a new mangling for parameters whose
type is a qualified-`id` (e.g., `id<Foo>`). This mangling allows such
parameters to be differentiated from those with the regular unqualified `id`
type.

This was a non-backward compatible mangling change to the ABI. This change
allows proper overloading, and also prevents mangling conflicts with template
parameters of protocol-qualified type.

Query the presence of this new mangling with
`__has_feature(objc_protocol_qualifier_mangling)`.

## Initializer lists for complex numbers in C

clang supports an extension which allows the following in C:

```c++
#include <math.h>
#include <complex.h>
complex float x = { 1.0f, INFINITY }; // Init to (1, Inf)
```

This construct is useful because there is no way to separately initialize the
real and imaginary parts of a complex variable in standard C, given that clang
does not support `_Imaginary`. (Clang also supports the `__real__` and
`__imag__` extensions from gcc, which help in some cases, but are not usable
in static initializers.)

Note that this extension does not allow eliding the braces; the meaning of the
following two lines is different:

```c++
complex float x[] = { { 1.0f, 1.0f } }; // [0] = (1, 1)
complex float x[] = { 1.0f, 1.0f }; // [0] = (1, 0), [1] = (1, 0)
```

This extension also works in C++ mode, as far as that goes, but does not apply
to the C++ `std::complex`. (In C++11, list initialization allows the same
syntax to be used with `std::complex` with the same meaning.)

For GCC compatibility, `__builtin_complex(re, im)` can also be used to
construct a complex number from the given real and imaginary components.

## OpenCL Features

Clang supports internal OpenCL extensions documented below.

### `__cl_clang_bitfields`

With this extension it is possible to enable bitfields in structs
or unions using the OpenCL extension pragma mechanism detailed in
[the OpenCL Extension Specification, section 1.2](https://www.khronos.org/registry/OpenCL/specs/3.0-unified/html/OpenCL_Ext.html#extensions-overview).

Use of bitfields in OpenCL kernels can result in reduced portability as struct
layout is not guaranteed to be consistent when compiled by different compilers.
If structs with bitfields are used as kernel function parameters, it can result
in incorrect functionality when the layout is different between the host and
device code.

**Example of Use**:

```c++
#pragma OPENCL EXTENSION __cl_clang_bitfields : enable
struct with_bitfield {
  unsigned int i : 5; // compiled - no diagnostic generated
};

#pragma OPENCL EXTENSION __cl_clang_bitfields : disable
struct without_bitfield {
  unsigned int i : 5; // error - bitfields are not supported
};
```

### `__cl_clang_function_pointers`

With this extension it is possible to enable various language features that
are relying on function pointers using regular OpenCL extension pragma
mechanism detailed in [the OpenCL Extension Specification,
section 1.2](https://www.khronos.org/registry/OpenCL/specs/3.0-unified/html/OpenCL_Ext.html#extensions-overview).

In C++ for OpenCL this also enables:

- Use of member function pointers;
- Unrestricted use of references to functions;
- Virtual member functions.

Such functionality is not conformant and does not guarantee to compile
correctly in any circumstances. It can be used if:

- the kernel source does not contain call expressions to (member-) function
  pointers, or virtual functions. For example, this extension can be used in
  metaprogramming algorithms to be able to specify/detect types generically.
- the generated kernel binary does not contain indirect calls because they
  are eliminated using compiler optimizations e.g., devirtualization.
- the selected target supports the function pointer like functionality e.g.
  most CPU targets.

**Example of Use**:

```c++
#pragma OPENCL EXTENSION __cl_clang_function_pointers : enable
void foo()
{
  void (*fp)(); // compiled - no diagnostic generated
}

#pragma OPENCL EXTENSION __cl_clang_function_pointers : disable
void bar()
{
  void (*fp)(); // error - pointers to function are not allowed
}
```

### `__cl_clang_variadic_functions`

With this extension it is possible to enable variadic arguments in functions
using regular OpenCL extension pragma mechanism detailed in [the OpenCL
Extension Specification, section 1.2](https://www.khronos.org/registry/OpenCL/specs/3.0-unified/html/OpenCL_Ext.html#extensions-overview).

This is not conformant behavior and it can only be used portably when the
functions with variadic prototypes do not get generated in binary e.g., the
variadic prototype is used to specify a function type with any number of
arguments in metaprogramming algorithms in C++ for OpenCL.

This extension can also be used when the kernel code is intended for targets
supporting the variadic arguments e.g., majority of CPU targets.

**Example of Use**:

```c++
#pragma OPENCL EXTENSION __cl_clang_variadic_functions : enable
void foo(int a, ...); // compiled - no diagnostic generated

#pragma OPENCL EXTENSION __cl_clang_variadic_functions : disable
void bar(int a, ...); // error - variadic prototype is not allowed
```

### `__cl_clang_non_portable_kernel_param_types`

With this extension it is possible to enable the use of some restricted types
in kernel parameters specified in [C++ for OpenCL v1.0 s2.4](https://www.khronos.org/opencl/assets/CXX_for_OpenCL.html#kernel_function).
The restrictions can be relaxed using regular OpenCL extension pragma mechanism
detailed in [the OpenCL Extension Specification, section 1.2](https://www.khronos.org/registry/OpenCL/specs/3.0-unified/html/OpenCL_Ext.html#extensions-overview).

This is not a conformant behavior and it can only be used when the
kernel arguments are not accessed on the host side or the data layout/size
between the host and device is known to be compatible.

**Example of Use**:

```c++
// Plain Old Data type.
struct Pod {
  int a;
  int b;
};

// Not POD type because of the constructor.
// Standard layout type because there is only one access control.
struct OnlySL {
  int a;
  int b;
  OnlySL() : a(0), b(0) {}
};

// Not standard layout type because of two different access controls.
struct NotSL {
  int a;
private:
  int b;
};

#pragma OPENCL EXTENSION __cl_clang_non_portable_kernel_param_types : enable
kernel void kernel_main(
  Pod a,

  OnlySL b,
  global NotSL *c,
  global OnlySL *d
);
#pragma OPENCL EXTENSION __cl_clang_non_portable_kernel_param_types : disable
```

### `__cl_clang_function_scope_local_variables`

This extension allows declaring variables in the local address space within
function scope, including non-kernel functions or nested scopes within a kernel,
using regular OpenCL extension pragma mechanism detailed in [the OpenCL
Extension Specification, section 1.2](https://www.khronos.org/registry/OpenCL/specs/3.0-unified/html/OpenCL_Ext.html#extensions-overview).

This relaxes the [Declaration Scopes and Variable Types](https://registry.khronos.org/OpenCL/specs/3.0-unified/html/OpenCL_C.html#_usage_for_declaration_scopes_and_variable_types)
rule that limits local-address-space variable declarations to the outermost
compound statement inside the body of the kernel function.

To expose static local allocations at kernel scope, targets can either force-
inline non-kernel functions that declare local memory or pass a kernel-allocated
local buffer to those functions via an implicit argument.

```c++
#pragma OPENCL EXTENSION __cl_clang_function_scope_local_variables : enable
kernel void kernel1(...)
{
  {
    local float a; // compiled - no diagnostic generated
  }
}
void foo()
{
  local float c; // compiled - no diagnostic generated
}

#pragma OPENCL EXTENSION __cl_clang_function_scope_local_variables : disable
kernel void kernel2(...)
{
  {
    local float a; // error - variables in the local address space can only be declared in the outermost scope of a kernel function
  }
}
void bar()
{
  local float c; // error - non-kernel function variable cannot be declared in local address space
}
```

### Remove address space builtin function

`__remove_address_space` allows to derive types in C++ for OpenCL
that have address space qualifiers removed. This utility only affects
address space qualifiers, therefore, other type qualifiers such as
`const` or `volatile` remain unchanged.

**Example of Use**:

```c++
template<typename T>
void foo(T *par){
  T var1; // error - local function variable with global address space
  __private T var2; // error - conflicting address space qualifiers
  __private __remove_address_space<T>::type var3; // var3 is __private int
}

void bar(){
  __global int* ptr;
  foo(ptr);
}
```

### Legacy 1.x atomics with generic address space

Clang allows the use of atomic functions from the OpenCL 1.x standards
with the generic address space pointer in C++ for OpenCL mode.

This is a non-portable feature and might not be supported by all
targets.

**Example of Use**:

```c++
void foo(__generic volatile unsigned int* a) {
  atomic_add(a, 1);
}
```

## WebAssembly Features

Clang supports the WebAssembly features documented below. For further
information related to the semantics of the builtins, please refer to the [WebAssembly Specification](https://webassembly.github.io/spec/core/).
In this section, when we refer to reference types, we are referring to
WebAssembly reference types, not C++ reference types unless stated
otherwise.

### `__builtin_wasm_table_set`

This builtin function stores a value in a WebAssembly table.
It takes three arguments.
The first argument is the table to store a value into, the second
argument is the index to which to store the value into, and the
third argument is a value of reference type to store in the table.
It returns nothing.

```c++
static __externref_t table[0];
extern __externref_t JSObj;

void store(int index) {
  __builtin_wasm_table_set(table, index, JSObj);
}
```

### `__builtin_wasm_table_get`

This builtin function is the counterpart to `__builtin_wasm_table_set`
and loads a value from a WebAssembly table of reference typed values.
It takes 2 arguments.
The first argument is a table of reference typed values and the
second argument is an index from which to load the value. It returns
the loaded reference typed value.

```c++
static __externref_t table[0];

__externref_t load(int index) {
  __externref_t Obj = __builtin_wasm_table_get(table, index);
  return Obj;
}
```

### `__builtin_wasm_table_size`

This builtin function returns the size of the WebAssembly table.
Takes the table as an argument and returns an unsigned integer (`size_t`)
with the current table size.

```c++
typedef void (*__funcref funcref_t)();
static funcref_t table[0];

size_t getSize() {
  return __builtin_wasm_table_size(table);
}
```

### `__builtin_wasm_table_grow`

This builtin function grows the WebAssembly table by a certain amount.
Currently, as all WebAssembly tables created in C/C++ are zero-sized,
this always needs to be called to grow the table.

It takes three arguments. The first argument is the WebAssembly table
to grow. The second argument is the reference typed value to store in
the new table entries (the initialization value), and the third argument
is the amount to grow the table by. It returns the previous table size
or -1. It will return -1 if not enough space could be allocated.

```c++
typedef void (*__funcref funcref_t)();
static funcref_t table[0];

// grow returns the new table size or -1 on error.
int grow(funcref_t fn, int delta) {
  int prevSize = __builtin_wasm_table_grow(table, fn, delta);
  if (prevSize == -1)
    return -1;
  return prevSize + delta;
}
```

### `__builtin_wasm_table_fill`

This builtin function sets all the entries of a WebAssembly table to a given
reference typed value. It takes four arguments. The first argument is
the WebAssembly table, the second argument is the index that starts the
range, the third argument is the value to set in the new entries, and
the fourth and the last argument is the size of the range. It returns
nothing.

```c++
static __externref_t table[0];

// resets a table by setting all of its entries to a given value.
void reset(__externref_t Obj) {
  int Size = __builtin_wasm_table_size(table);
  __builtin_wasm_table_fill(table, 0, Obj, Size);
}
```

### `__builtin_wasm_table_copy`

This builtin function copies elements from a source WebAssembly table
to a possibly overlapping destination region. It takes five arguments.
The first argument is the destination WebAssembly table, and the second
argument is the source WebAssembly table. The third argument is the
destination index from where the copy starts, the fourth argument is the
source index from where the copy starts, and the fifth and last argument
is the number of elements to copy. It returns nothing.

```c++
static __externref_t tableSrc[0];
static __externref_t tableDst[0];

// Copy nelem elements from [src, src + nelem - 1] in tableSrc to
// [dst, dst + nelem - 1] in tableDst
void copy(int dst, int src, int nelem) {
  __builtin_wasm_table_copy(tableDst, tableSrc, dst, src, nelem);
}
```

### `__builtin_wasm_memory_copy`

This builtin function copies bytes from a source memory to a possibly
overlapping destination region using the WebAssembly `memory.copy` instruction.
It takes five arguments:
1. Destination memory index (must be a constant integer)
2. Source memory index (must be a constant integer)
3. Destination pointer (`void *`)
4. Source pointer (`const void *`)
5. Number of bytes to copy (`size_t`)

It returns nothing. Note that unlike C `memcpy` or `memmove`, `memory.copy`
traps if either pointer is out of bounds even when the number of bytes is zero.

```c++
void copy(void *dst, const void *src, size_t n) {
  __builtin_wasm_memory_copy(0, 0, dst, src, n);
}
```

### `__builtin_wasm_memory_fill`

This builtin function sets bytes in memory using the WebAssembly `memory.fill`
instruction. It takes four arguments:
1. Memory index (must be a constant integer)
2. Destination pointer (`void *`)
3. Byte value to set (passed as `int`, lowest 8 bits used)
4. Number of bytes to set (`size_t`)

It returns nothing. Note that unlike C `memset`, `memory.fill` traps if the
pointer is out of bounds even when the number of bytes is zero.

```c++
void fill(void *dst, int val, size_t n) {
  __builtin_wasm_memory_fill(0, dst, val, n);
}
```

## Builtin Functions

Clang supports a number of builtin library functions with the same syntax as
GCC, including things like `__builtin_nan`, `__builtin_constant_p`,
`__builtin_choose_expr`, `__builtin_types_compatible_p`,
`__builtin_assume_aligned`, `__sync_fetch_and_add`, etc. In addition to
the GCC builtins, Clang supports a number of builtins that GCC does not, which
are listed here.

Please note that Clang does not and will not support all of the GCC builtins
for vector operations. Instead of using builtins, you should use the functions
defined in target-specific header files like `<xmmintrin.h>`, which define
portable wrappers for these. Many of the Clang versions of these functions are
implemented directly in terms of {ref}`extended vector support
<langext-vectors>` instead of builtins, in order to reduce the number of
builtins that we need to implement.

### `__builtin_alloca`

`__builtin_alloca` is used to dynamically allocate memory on the stack. Memory
is automatically freed upon function termination.

**Syntax**:

```c++
__builtin_alloca(size_t n)
```

**Example of Use**:

```c++
void init(float* data, size_t nbelems);
void process(float* data, size_t nbelems);
int foo(size_t n) {
  auto mem = (float*)__builtin_alloca(n * sizeof(float));
  init(mem, n);
  process(mem, n);
  /* mem is automatically freed at this point */
}
```

**Description**:

`__builtin_alloca` is meant to be used to allocate a dynamic amount of memory
on the stack. This amount is subject to stack allocation limits.

Query for this feature with `__has_builtin(__builtin_alloca)`.

### `__builtin_alloca_with_align`

`__builtin_alloca_with_align` is used to dynamically allocate memory on the
stack while controlling its alignment. Memory is automatically freed upon
function termination.

**Syntax**:

```c++
__builtin_alloca_with_align(size_t n, size_t align)
```

**Example of Use**:

```c++
void init(float* data, size_t nbelems);
void process(float* data, size_t nbelems);
int foo(size_t n) {
  auto mem = (float*)__builtin_alloca_with_align(
                      n * sizeof(float),
                      CHAR_BIT * alignof(float));
  init(mem, n);
  process(mem, n);
  /* mem is automatically freed at this point */
}
```

**Description**:

`__builtin_alloca_with_align` is meant to be used to allocate a dynamic amount of memory
on the stack. It is similar to `__builtin_alloca` but accepts a second
argument whose value is the alignment constraint, as a power of 2 in *bits*.

Query for this feature with `__has_builtin(__builtin_alloca_with_align)`.

(langext-__builtin_assume)=
(langext-builtin-assume)=

### `__builtin_assume`

`__builtin_assume` is used to provide the optimizer with a boolean
invariant that is defined to be true.

**Syntax**:

```c++
__builtin_assume(bool)
```

**Example of Use**:

```c++
int foo(int x) {
    __builtin_assume(x != 0);
    // The optimizer may short-circuit this check using the invariant.
    if (x == 0)
          return do_something();
    return do_something_else();
}
```

**Description**:

The boolean argument to this function is defined to be true. The optimizer may
analyze the form of the expression provided as the argument and deduce from
that information used to optimize the program. If the condition is violated
during execution, the behavior is undefined. The argument itself is never
evaluated, so any side effects of the expression will be discarded.

Query for this feature with `__has_builtin(__builtin_assume)`.

(langext-__builtin_assume_separate_storage)=
(langext-builtin-assume-separate-storage)=

### `__builtin_assume_separate_storage`

`__builtin_assume_separate_storage` is used to provide the optimizer with the
knowledge that its two arguments point to separately allocated objects.

**Syntax**:

```c++
__builtin_assume_separate_storage(const volatile void *, const volatile void *)
```

**Example of Use**:

```c++
int foo(int *x, int *y) {
    __builtin_assume_separate_storage(x, y);
    *x = 0;
    *y = 1;
    // The optimizer may optimize this to return 0 without reloading from *x.
    return *x;
}
```

**Description**:

The arguments to this function are assumed to point into separately allocated
storage (either different variable definitions or different dynamic storage
allocations). The optimizer may use this fact to aid in alias analysis. If the
arguments point into the same storage, the behavior is undefined. Note that the
definition of "storage" here refers to the outermost enclosing allocation of any
particular object (so for example, it's never correct to call this function
passing the addresses of fields in the same struct, elements of the same array,
etc.).

Query for this feature with `__has_builtin(__builtin_assume_separate_storage)`.

### `__builtin_assume_dereferenceable`

`__builtin_assume_dereferenceable` is used to provide the optimizer with the
knowledge that the pointer argument P is dereferenceable up to at least the
specified number of bytes.

**Syntax**:

```c++
__builtin_assume_dereferenceable(const void *, size_t)
```

**Example of Use**:

```c++
int foo(int *x, int y) {
    __builtin_assume_dereferenceable(x, sizeof(int));
    int z = 0;
    if (y == 1) {
      // The optimizer may execute the load of x unconditionally due to
      // __builtin_assume_dereferenceable guaranteeing sizeof(int) bytes can
      // be loaded speculatively without trapping.
      z = *x;
    }
    return z;
}
```

**Description**:

The arguments to this function provide a start pointer `P` and a size `S`.
`S` must be at least 1 and a constant. The optimizer may assume that `S`
bytes are dereferenceable starting at `P`. Note that this does not necessarily
imply that `P` is non-null as `nullptr` can be dereferenced in some cases.
The assumption also does not imply that `P` is not dereferenceable past `S`
bytes.

Query for this feature with `__has_builtin(__builtin_assume_dereferenceable)`.

### `__builtin_offsetof`

`__builtin_offsetof` is used to implement the `offsetof` macro, which
calculates the offset (in bytes) to a given member of the given type.

**Syntax**:

```c++
__builtin_offsetof(type-name, member-designator)
```

**Example of Use**:

```c++
struct S {
  char c;
  int i;
  struct T {
    float f[2];
  } t;
};

const int offset_to_i = __builtin_offsetof(struct S, i);
const int ext1 = __builtin_offsetof(struct U { int i; }, i); // C extension
const int offset_to_subobject = __builtin_offsetof(struct S, t.f[1]);
```

**Description**:

This builtin is usable in an integer constant expression which returns a value
of type `size_t`. The value returned is the offset in bytes to the subobject
designated by the member-designator from the beginning of an object of type
`type-name`. Clang extends the required standard functionality in the
following way:

- In C language modes, the first argument may be the definition of a new type.
  Any type declared this way is scoped to the nearest scope containing the call
  to the builtin.

Query for this feature with `__has_builtin(__builtin_offsetof)`.

### `__builtin_get_vtable_pointer`

`__builtin_get_vtable_pointer` loads and authenticates the primary vtable
pointer from an instance of a polymorphic C++ class. This builtin is needed
for directly loading the vtable pointer when on platforms using
{doc}`PointerAuthentication`.

**Syntax**:

```c++
__builtin_get_vtable_pointer(PolymorphicClass*)
```

**Example of Use**:

```c++
struct PolymorphicClass {
  virtual ~PolymorphicClass();
};

PolymorphicClass anInstance;
const void* vtablePointer = __builtin_get_vtable_pointer(&anInstance);
```

**Description**:

The `__builtin_get_vtable_pointer` builtin loads the primary vtable
pointer from a polymorphic C++ type. If the target platform authenticates
vtable pointers, this builtin will perform the authentication and produce
the underlying raw pointer. The object being queried must be polymorphic,
and so must also be a complete type.

Query for this feature with `__has_builtin(__builtin_get_vtable_pointer)`.

### `__builtin_call_with_static_chain`

`__builtin_call_with_static_chain` is used to perform a static call while
updating the static chain register.

**Syntax**:

```c++
T __builtin_call_with_static_chain(T expr, void* ptr)
```

**Example of Use**:

```c++
auto v = __builtin_call_with_static_chain(foo(3), foo);
```

**Description**:

This builtin returns `expr` after checking that `expr` is a non-member
static call expression. The call to that expression is made while using `ptr`
as a function pointer stored in a dedicated register to implement *static chain*
calling convention, as used by some language to implement closures or nested
functions.

Query for this feature with `__has_builtin(__builtin_call_with_static_chain)`.

### `__builtin_readcyclecounter`

`__builtin_readcyclecounter` is used to access the cycle counter register (or
a similar low-latency, high-accuracy clock) on those targets that support it.

**Syntax**:

```c++
__builtin_readcyclecounter()
```

**Example of Use**:

```c++
unsigned long long t0 = __builtin_readcyclecounter();
do_something();
unsigned long long t1 = __builtin_readcyclecounter();
unsigned long long cycles_to_do_something = t1 - t0; // assuming no overflow
```

**Description**:

The `__builtin_readcyclecounter()` builtin returns the cycle counter value,
which may be either global or process/thread-specific depending on the target.
As the backing counters often overflow quickly (on the order of seconds) this
should only be used for timing small intervals. When not supported by the
target, the return value is always zero. This builtin takes no arguments and
produces an unsigned long long result.

Query for this feature with `__has_builtin(__builtin_readcyclecounter)`. Note
that even if present, its use may depend on run-time privilege or other OS
controlled state.

### `__builtin_readsteadycounter`

`__builtin_readsteadycounter` is used to access the fixed frequency counter
register (or a similar steady-rate clock) on those targets that support it.
The function is similar to `__builtin_readcyclecounter` above except that the
frequency is fixed, making it suitable for measuring elapsed time.

**Syntax**:

```c++
__builtin_readsteadycounter()
```

**Example of Use**:

```c++
unsigned long long t0 = __builtin_readsteadycounter();
do_something();
unsigned long long t1 = __builtin_readsteadycounter();
unsigned long long secs_to_do_something = (t1 - t0) / tick_rate;
```

**Description**:

The `__builtin_readsteadycounter()` builtin returns the frequency counter value.
When not supported by the target, the return value is always zero. This builtin
takes no arguments and produces an unsigned long long result. The builtin does
not guarantee any particular frequency, only that it is stable. Knowledge of the
counter's true frequency will need to be provided by the user.

Query for this feature with `__has_builtin(__builtin_readsteadycounter)`.

### `__builtin_cpu_supports`

**Syntax**:

```c++
int __builtin_cpu_supports(const char *features);
```

**Example of Use:**:

```c++
if (__builtin_cpu_supports("sve"))
  sve_code();
```

**Description**:

The `__builtin_cpu_supports` function detects if the run-time CPU supports
features specified in string argument. It returns a positive integer if all
features are supported and 0 otherwise. Feature names are target specific. On
AArch64, features are combined using `+` like this
`__builtin_cpu_supports("flagm+sha3+lse+rcpc2+fcma+memtag+bti+sme2")`.
If a feature name is not supported, Clang will issue a warning and replace
builtin by the constant 0.

Query for this feature with `__has_builtin(__builtin_cpu_supports)`.

### `__builtin_dump_struct`

**Syntax**:

```c++
__builtin_dump_struct(&some_struct, some_printf_func, args...);
```

**Examples**:

```c++
struct S {
  int x, y;
  float f;
  struct T {
    int i;
  } t;
};

void func(struct S *s) {
  __builtin_dump_struct(s, printf);
}
```

Example output:

```none
struct S {
  int x = 100
  int y = 42
  float f = 3.141593
  struct T t = {
    int i = 1997
  }
}
```

```c++
#include <string>
struct T { int a, b; };
constexpr void constexpr_sprintf(std::string &out, const char *format,
                                 auto ...args) {
  // ...
}
constexpr std::string dump_struct(auto &x) {
  std::string s;
  __builtin_dump_struct(&x, constexpr_sprintf, s);
  return s;
}
static_assert(dump_struct(T{1, 2}) == R"(struct T {
  int a = 1
  int b = 2
}
)");
```

**Description**:

The `__builtin_dump_struct` function is used to print the fields of a simple
structure and their values for debugging purposes. The first argument of the
builtin should be a pointer to a complete record type to dump. The second argument `f`
should be some callable expression, and can be a function object or an overload
set. The builtin calls `f`, passing any further arguments `args...`
followed by a `printf`-compatible format string and the corresponding
arguments. `f` may be called more than once, and `f` and `args` will be
evaluated once per call. In C++, `f` may be a template or overload set and
resolve to different functions for each call.

In the format string, a suitable format specifier will be used for builtin
types that Clang knows how to format. This includes standard builtin types, as
well as aggregate structures, `void*` (printed with `%p`), and `const
char*` (printed with `%s`). A `*%p` specifier will be used for a field
that Clang doesn't know how to format, and the corresponding argument will be a
pointer to the field. This allows a C++ templated formatting function to detect
this case and implement custom formatting. A `*` will otherwise not precede a
format specifier.

This builtin does not return a value.

This builtin can be used in constant expressions.

Query for this feature with `__has_builtin(__builtin_dump_struct)`

(langext-__builtin_shufflevector)=
(langext-builtin-shufflevector)=

### `__builtin_shufflevector`

`__builtin_shufflevector` is used to express generic vector
permutation/shuffle/swizzle operations. This builtin is also very important
for the implementation of various target-specific header files like
`<xmmintrin.h>`. This builtin can be used within constant expressions.

**Syntax**:

```c++
__builtin_shufflevector(vec1, vec2, index1, index2, ...)
```

**Examples**:

```c++
// identity operation - return 4-element vector v1.
__builtin_shufflevector(v1, v1, 0, 1, 2, 3)

// "Splat" element 0 of V1 into a 4-element result.
__builtin_shufflevector(V1, V1, 0, 0, 0, 0)

// Reverse 4-element vector V1.
__builtin_shufflevector(V1, V1, 3, 2, 1, 0)

// Concatenate every other element of 4-element vectors V1 and V2.
__builtin_shufflevector(V1, V2, 0, 2, 4, 6)

// Concatenate every other element of 8-element vectors V1 and V2.
__builtin_shufflevector(V1, V2, 0, 2, 4, 6, 8, 10, 12, 14)

// Shuffle v1 with some elements being undefined. Not allowed in constexpr.
__builtin_shufflevector(v1, v1, 3, -1, 1, -1)
```

**Description**:

The first two arguments to `__builtin_shufflevector` are vectors that have
the same element type. The remaining arguments are a list of integers that
specify the elements indices of the first two vectors that should be extracted
and returned in a new vector. These element indices are numbered sequentially
starting with the first vector, continuing into the second vector. Thus, if
`vec1` is a 4-element vector, index 5 would refer to the second element of
`vec2`. An index of -1 can be used to indicate that the corresponding element
in the returned vector is a don't care and can be optimized by the backend.
Values of -1 are not supported in constant expressions.

The result of `__builtin_shufflevector` is a vector with the same element
type as `vec1`/`vec2` but that has an element count equal to the number of
indices specified.

Query for this feature with `__has_builtin(__builtin_shufflevector)`.

(langext-__builtin_convertvector)=
(langext-builtin-convertvector)=

### `__builtin_convertvector`

`__builtin_convertvector` is used to express generic vector
type-conversion operations. The input vector and the output vector
type must have the same number of elements. This builtin can be used within
constant expressions.

**Syntax**:

```c++
__builtin_convertvector(src_vec, dst_vec_type)
```

**Examples**:

```c++
typedef double vector4double __attribute__((__vector_size__(32)));
typedef float  vector4float  __attribute__((__vector_size__(16)));
typedef short  vector4short  __attribute__((__vector_size__(8)));
vector4float vf; vector4short vs;

// convert from a vector of 4 floats to a vector of 4 doubles.
__builtin_convertvector(vf, vector4double)
// equivalent to:
(vector4double) { (double) vf[0], (double) vf[1], (double) vf[2], (double) vf[3] }

// convert from a vector of 4 shorts to a vector of 4 floats.
__builtin_convertvector(vs, vector4float)
// equivalent to:
(vector4float) { (float) vs[0], (float) vs[1], (float) vs[2], (float) vs[3] }
```

**Description**:

The first argument to `__builtin_convertvector` is a vector, and the second
argument is a vector type with the same number of elements as the first
argument.

The result of `__builtin_convertvector` is a vector with the same element
type as the second argument, with a value defined in terms of the action of a
C-style cast applied to each element of the first argument.

Query for this feature with `__has_builtin(__builtin_convertvector)`.

### `__builtin_bitreverse`

- `__builtin_bitreverse8`
- `__builtin_bitreverse16`
- `__builtin_bitreverse32`
- `__builtin_bitreverse64`

**Syntax**:

```c++
__builtin_bitreverse32(x)
```

**Examples**:

```c++
uint8_t rev_x = __builtin_bitreverse8(x);
uint16_t rev_x = __builtin_bitreverse16(x);
uint32_t rev_y = __builtin_bitreverse32(y);
uint64_t rev_z = __builtin_bitreverse64(z);
```

**Description**:

The '`__builtin_bitreverse`' family of builtins is used to reverse
the bitpattern of an integer value; for example, `0b10110110` becomes
`0b01101101`. These builtins can be used within constant expressions.

### `__builtin_rotateleft`

- `__builtin_rotateleft8`
- `__builtin_rotateleft16`
- `__builtin_rotateleft32`
- `__builtin_rotateleft64`

**Syntax**:

```c++
__builtin_rotateleft32(x, y)
```

**Examples**:

```c++
uint8_t rot_x = __builtin_rotateleft8(x, y);
uint16_t rot_x = __builtin_rotateleft16(x, y);
uint32_t rot_x = __builtin_rotateleft32(x, y);
uint64_t rot_x = __builtin_rotateleft64(x, y);
```

**Description**:

The '`__builtin_rotateleft`' family of builtins is used to rotate
the bits in the first argument by the amount in the second argument.
For example, `0b10000110` rotated left by 11 becomes `0b00110100`.
The shift value is treated as an unsigned amount modulo the size of
the arguments. Both arguments and the result have the bitwidth specified
by the name of the builtin. These builtins can be used within constant
expressions.

### `__builtin_rotateright`

- `__builtin_rotateright8`
- `__builtin_rotateright16`
- `__builtin_rotateright32`
- `__builtin_rotateright64`

**Syntax**:

```c++
__builtin_rotateright32(x, y)
```

**Examples**:

```c++
uint8_t rot_x = __builtin_rotateright8(x, y);
uint16_t rot_x = __builtin_rotateright16(x, y);
uint32_t rot_x = __builtin_rotateright32(x, y);
uint64_t rot_x = __builtin_rotateright64(x, y);
```

**Description**:

The '`__builtin_rotateright`' family of builtins is used to rotate
the bits in the first argument by the amount in the second argument.
For example, `0b10000110` rotated right by 3 becomes `0b11010000`.
The shift value is treated as an unsigned amount modulo the size of
the arguments. Both arguments and the result have the bitwidth specified
by the name of the builtin. These builtins can be used within constant
expressions.

### `__builtin_stdc_rotate_left` and `__builtin_stdc_rotate_right`

**Syntax**:

```c
T __builtin_stdc_rotate_left(T value, count)
T __builtin_stdc_rotate_right(T value, count)
```

where `T` is any unsigned integer type and `count` is any integer type.

**Description**:

These builtins rotate the bits in `value` by `count` positions. The
`__builtin_stdc_rotate_left` builtin rotates bits to the left, while
`__builtin_stdc_rotate_right` rotates bits to the right. The first
argument (`value`) must be an unsigned integer type, including `_BitInt` types.
The second argument (`count`) can be any integer type. The rotation count is
normalized modulo the bit-width of the value being rotated, with negative
counts converted to equivalent positive rotations (e.g., rotating left
by `-1` is equivalent to rotating left by `BitWidth-1`). These builtins can
be used within constant expressions.

**Example of use**:

```c
unsigned char rotated_left = __builtin_stdc_rotate_left((unsigned char)0xB1, 3);
unsigned int rotated_right = __builtin_stdc_rotate_right(0x12345678U, 8);

unsigned char neg_rotate = __builtin_stdc_rotate_left((unsigned char)0xB1, -1);

unsigned _BitInt(20) value = 0xABCDE;
unsigned _BitInt(20) rotated = __builtin_stdc_rotate_left(value, 5);
```

### `__builtin_stdc_*` bit utilities

**Syntax**:

```c
unsigned int __builtin_stdc_leading_zeros(T value);
unsigned int __builtin_stdc_leading_ones(T value);
unsigned int __builtin_stdc_trailing_zeros(T value);
unsigned int __builtin_stdc_trailing_ones(T value);
unsigned int __builtin_stdc_first_leading_zero(T value);
unsigned int __builtin_stdc_first_leading_one(T value);
unsigned int __builtin_stdc_first_trailing_zero(T value);
unsigned int __builtin_stdc_first_trailing_one(T value);
unsigned int __builtin_stdc_count_zeros(T value);
unsigned int __builtin_stdc_count_ones(T value);
bool         __builtin_stdc_has_single_bit(T value);
unsigned int __builtin_stdc_bit_width(T value);
T            __builtin_stdc_bit_floor(T value);
T            __builtin_stdc_bit_ceil(T value);
```

where `T` is any unsigned integer type except `bool` and enumeration types,
including `_BitInt` types.

**Description**:

These builtins implement the C23 `<stdbit.h>` operations. Following the C23
standard, `unsigned int` is used as the `generic_return_type` for count and
position queries (`leading_zeros`, `leading_ones`, `trailing_zeros`,
`trailing_ones`, `first_leading_zero`, `first_leading_one`,
`first_trailing_zero`, `first_trailing_one`, `count_zeros`,
`count_ones`, `bit_width`); `has_single_bit` returns `bool`; and
`bit_floor`/`bit_ceil` return the same type as the operand. Zero and
all-ones cases follow the C23 definitions. All are usable in constant
expressions.

`bool` and enumeration types are rejected as arguments because C23 does not
permit them for these functions.

As a Clang extension, `_BitInt` types of arbitrary widths are supported. C23
only requires support for bit-precise integers whose width matches a standard
or extended integer type.

**Examples**:

```c
unsigned _BitInt(9) x = 0x11;
unsigned int lz  = __builtin_stdc_leading_zeros(x);
unsigned int tz  = __builtin_stdc_trailing_zeros(x);
unsigned int fto = __builtin_stdc_first_trailing_one(x);
unsigned int cz  = __builtin_stdc_count_zeros(x);
bool has_one    = __builtin_stdc_has_single_bit(x);
unsigned _BitInt(9) ceilv  = __builtin_stdc_bit_ceil((unsigned _BitInt(9))5);
unsigned _BitInt(9) floorv = __builtin_stdc_bit_floor((unsigned _BitInt(9))5);
```

### `__builtin_unreachable`

`__builtin_unreachable` is used to indicate that a specific point in the
program cannot be reached, even if the compiler might otherwise think it can.
This is useful to improve optimization and eliminates certain warnings. For
example, without the `__builtin_unreachable` in the example below, the
compiler assumes that the inline asm can fall through and prints a "function
declared '`noreturn`' should not return" warning.

**Syntax**:

```c++
__builtin_unreachable()
```

**Example of use**:

```c++
void myabort(void) __attribute__((noreturn));
void myabort(void) {
  asm("int3");
  __builtin_unreachable();
}
```

**Description**:

The `__builtin_unreachable()` builtin has completely undefined behavior.
Since it has undefined behavior, it is a statement that it is never reached and
the optimizer can take advantage of this to produce better code. This builtin
takes no arguments and produces a void result.

Query for this feature with `__has_builtin(__builtin_unreachable)`.

### `__builtin_unpredictable`

`__builtin_unpredictable` is used to indicate that a branch condition is
unpredictable by hardware mechanisms such as branch prediction logic.

**Syntax**:

```c++
__builtin_unpredictable(long long)
```

**Example of use**:

```c++
if (__builtin_unpredictable(x > 0)) {
   foo();
}
```

**Description**:

The `__builtin_unpredictable()` builtin is expected to be used with control
flow conditions such as in `if` and `switch` statements.

Query for this feature with `__has_builtin(__builtin_unpredictable)`.

### `__builtin_expect`

`__builtin_expect` is used to indicate that the value of an expression is
anticipated to be the same as a statically known result.

**Syntax**:

```c++
long __builtin_expect(long expr, long val)
```

**Example of use**:

```c++
if (__builtin_expect(x, 0)) {
   bar();
}
```

**Description**:

The `__builtin_expect()` builtin is typically used with control flow
conditions such as in `if` and `switch` statements to help branch
prediction. It means that its first argument `expr` is expected to take the
value of its second argument `val`. It always returns `expr`.

Query for this feature with `__has_builtin(__builtin_expect)`.

### `__builtin_expect_with_probability`

`__builtin_expect_with_probability` is similar to `__builtin_expect` but it
takes a probability as third argument.

**Syntax**:

```c++
long __builtin_expect_with_probability(long expr, long val, double p)
```

**Example of use**:

```c++
if (__builtin_expect_with_probability(x, 0, .3)) {
   bar();
}
```

**Description**:

The `__builtin_expect_with_probability()` builtin is typically used with
control flow conditions such as in `if` and `switch` statements to help
branch prediction. It means that its first argument `expr` is expected to take
the value of its second argument `val` with probability `p`. `p` must be
within `[0.0 ; 1.0]` bounds. This builtin always returns the value of `expr`.

Query for this feature with `__has_builtin(__builtin_expect_with_probability)`.

### `__builtin_prefetch`

`__builtin_prefetch` is used to communicate with the cache handler to bring
data into the cache before it gets used.

**Syntax**:

```c++
void __builtin_prefetch(const void *addr, int rw=0, int locality=3)
```

**Example of use**:

```c++
__builtin_prefetch(a + i);
```

**Description**:

The `__builtin_prefetch(addr, rw, locality)` builtin is expected to be used to
avoid cache misses when the developer has a good understanding of which data
are going to be used next. `addr` is the address that needs to be brought into
the cache. `rw` indicates the expected access mode: `0` for *read* and `1`
for *write*. In case of *read write* access, `1` is to be used. `locality`
indicates the expected persistence of data in cache, from `0` which means that
data can be discarded from cache after its next use to `3` which means that
data is going to be reused a lot once in cache. `1` and `2` provide
intermediate behavior between these two extremes.

Query for this feature with `__has_builtin(__builtin_prefetch)`.

### `__sync_swap`

`__sync_swap` is used to atomically swap integers or pointers in memory.

**Syntax**:

```c++
type __sync_swap(type *ptr, type value, ...)
```

**Example of Use**:

```c++
int old_value = __sync_swap(&value, new_value);
```

**Description**:

The `__sync_swap()` builtin extends the existing `__sync_*()` family of
atomic intrinsics to allow code to atomically swap the current value with the
new value. More importantly, it helps developers write more efficient and
correct code by avoiding expensive loops around
`__sync_bool_compare_and_swap()` or relying on the platform specific
implementation details of `__sync_lock_test_and_set()`. The
`__sync_swap()` builtin is a full barrier.

### `__builtin_addressof`

`__builtin_addressof` performs the functionality of the built-in `&`
operator, ignoring any `operator&` overload. This is useful in constant
expressions in C++11, where there is no other way to take the address of an
object that overloads `operator&`. Clang automatically adds
`[[clang::lifetimebound]]` to the parameter of `__builtin_addressof`.

**Example of use**:

```c++
template<typename T> constexpr T *addressof(T &value) {
  return __builtin_addressof(value);
}
```

### `__builtin_function_start`

`__builtin_function_start` returns the address of a function body.

**Syntax**:

```c++
void *__builtin_function_start(function)
```

**Example of use**:

```c++
void a() {}
void *p = __builtin_function_start(a);

class A {
public:
  void a(int n);
  void a();
};

void A::a(int n) {}
void A::a() {}

void *pa1 = __builtin_function_start((void(A::*)(int)) &A::a);
void *pa2 = __builtin_function_start((void(A::*)()) &A::a);
```

**Description**:

The `__builtin_function_start` builtin accepts an argument that can be
constant-evaluated to a function, and returns the address of the function
body. This builtin is not supported on all targets.

The returned pointer may differ from the normally taken function address
and is not safe to call. For example, with `-fsanitize=cfi`, taking a
function address produces a callable pointer to a CFI jump table, while
`__builtin_function_start` returns an address that fails
{doc}`cfi-icall<ControlFlowIntegrity>` checks.

### `__builtin_operator_new` and `__builtin_operator_delete`

A call to `__builtin_operator_new(args)` is exactly the same as a call to
`::operator new(args)`, except that it allows certain optimizations
that the C++ standard does not permit for a direct function call to
`::operator new` (in particular, removing `new` / `delete` pairs and
merging allocations), and that the call is required to resolve to a
[replaceable global allocation function](https://en.cppreference.com/w/cpp/memory/new/operator_new).

Likewise, `__builtin_operator_delete` is exactly the same as a call to
`::operator delete(args)`, except that it permits optimizations
and that the call is required to resolve to a
[replaceable global deallocation function](https://en.cppreference.com/w/cpp/memory/new/operator_delete).

These builtins are intended for use in the implementation of `std::allocator`
and other similar allocation libraries, and are only available in C++.

Query for this feature with `__has_builtin(__builtin_operator_new)` or
`__has_builtin(__builtin_operator_delete)`:

> - If the value is at least `201802L`, the builtins behave as described above.
> - If the value is non-zero, the builtins may not support calling arbitrary
>   replaceable global (de)allocation functions, but do support calling at least
>   `::operator new(size_t)` and `::operator delete(void*)`.

### `__builtin_trivially_relocate`

**Syntax**:

```c
T* __builtin_trivially_relocate(T* dest, T* src, size_t count)
```

Trivially relocates `count` objects of relocatable, complete type `T`
from `src` to `dest` and returns `dest`.
This builtin is used to implement `std::trivially_relocate`.

### `__builtin_invoke`

**Syntax**:

```c++
template <class Callee, class... Args>
decltype(auto) __builtin_invoke(Callee&& callee, Args&&... args);
```

`__builtin_invoke` is equivalent to `std::invoke`.

### `__builtin_preserve_access_index`

`__builtin_preserve_access_index` specifies a code section where
array subscript access and structure/union member access are relocatable
under bpf compile-once run-everywhere framework. Debuginfo (typically
with `-g`) is needed, otherwise, the compiler will exit with an error.
The return type for the intrinsic is the same as the type of the
argument.

**Syntax**:

```c
type __builtin_preserve_access_index(type arg)
```

**Example of Use**:

```c
struct t {
  int i;
  int j;
  union {
    int a;
    int b;
  } c[4];
};
struct t *v = ...;
int *pb =__builtin_preserve_access_index(&v->c[3].b);
__builtin_preserve_access_index(v->j);
```

### `__builtin_debugtrap`

`__builtin_debugtrap` causes the program to stop its execution in such a way that a debugger can catch it.

**Syntax**:

```c++
__builtin_debugtrap()
```

**Description**

`__builtin_debugtrap` is lowered to the [`llvm.debugtrap`](https://llvm.org/docs/LangRef.html#llvm-debugtrap-intrinsic) builtin. It should have the same effect as setting a breakpoint on the line where the builtin is called.

Query for this feature with `__has_builtin(__builtin_debugtrap)`.

### `__builtin_trap`

`__builtin_trap` causes the program to stop its execution abnormally.

**Syntax**:

```c++
__builtin_trap()
```

**Description**

`__builtin_trap` is lowered to the [`llvm.trap`](https://llvm.org/docs/LangRef.html#llvm-trap-intrinsic) builtin.

Query for this feature with `__has_builtin(__builtin_trap)`.

### `__builtin_arm_trap`

`__builtin_arm_trap` is an AArch64 extension to `__builtin_trap` which also accepts a compile-time constant value, encoded directly into the trap instruction for later inspection.

**Syntax**:

```c++
__builtin_arm_trap(const unsigned short payload)
```

**Description**

`__builtin_arm_trap` is lowered to the `llvm.aarch64.break` builtin, and then to `brk #payload`.

### `__builtin_verbose_trap`

`__builtin_verbose_trap` causes the program to stop its execution abnormally
and shows a human-readable description of the reason for the termination when a
debugger is attached or in a symbolicated crash log.

**Syntax**:

```c++
__builtin_verbose_trap(const char *category, const char *reason)
```

**Description**

`__builtin_verbose_trap` is lowered to the [`llvm.trap`](https://llvm.org/docs/LangRef.html#llvm-trap-intrinsic) builtin.
Additionally, clang emits debugging information that represents an artificial
inline frame whose name encodes the category and reason strings passed to the builtin,
prefixed by a "magic" prefix.

For example, consider the following code:

```c++
void foo(int* p) {
  if (p == nullptr)
    __builtin_verbose_trap("check null", "Argument must not be null!");
}
```

The debugging information would look as if it were produced for the following code:

```c++
__attribute__((always_inline))
inline void "__clang_trap_msg$check null$Argument must not be null!"() {
  __builtin_trap();
}

void foo(int* p) {
  if (p == nullptr)
    "__clang_trap_msg$check null$Argument must not be null!"();
}
```

However, the generated code would not actually contain a call to the artificial
function — it only exists in the debugging information.

Query for this feature with `__has_builtin(__builtin_verbose_trap)`. Note that
users need to enable debug information to enable this feature. A call to this
builtin is equivalent to a call to `__builtin_trap` if debug information isn't
enabled.

The optimizer can merge calls to trap with different messages, which degrades
the debugging experience.

### `__builtin_allow_runtime_check`

`__builtin_allow_runtime_check` returns true if the check at the current
program location should be executed. It is expected to be used to implement
`assert` like checks which can be safely removed by the optimizer.

**Syntax**:

```c++
bool __builtin_allow_runtime_check(const char* kind)
```

**Example of use**:

```c++
if (__builtin_allow_runtime_check("mycheck") && !ExpensiveCheck()) {
   abort();
}
```

**Description**

`__builtin_allow_runtime_check` is lowered to the [llvm.allow.runtime.check](https://llvm.org/docs/LangRef.html#llvm-allow-runtime-check-intrinsic)
intrinsic.

The `__builtin_allow_runtime_check()` can be used within control structures
like `if` to guard expensive runtime checks. The return value is determined
by the following compiler options and may differ per call site:

- `-mllvm -lower-allow-check-percentile-cutoff-hot=N`: Disable checks in hot
  code marked by the profile summary with a hotness cutoff in the range
  `[0, 999999]` (a larger N disables more checks).
- `-mllvm -lower-allow-check-random-rate=P`: Keep a check with probability P,
  a floating point number in the range `[0.0, 1.0]`.
- If both options are specified, a check is disabled if either condition is satisfied.
- If neither is specified, all checks are allowed.

Parameter `kind`, currently unused, is a string literal specifying the check
kind. Future compiler versions may use this to allow for more granular control,
such as applying different hotness cutoffs to different check kinds.

Query for this feature with `__has_builtin(__builtin_allow_runtime_check)`.

### `__builtin_nondeterministic_value`

`__builtin_nondeterministic_value` returns a valid nondeterministic value of the same type as the provided argument.

**Syntax**:

```c++
type __builtin_nondeterministic_value(type x)
```

**Examples**:

```c++
int x = __builtin_nondeterministic_value(x);
float y = __builtin_nondeterministic_value(y);
__m256i a = __builtin_nondeterministic_value(a);
```

**Description**

Each call to `__builtin_nondeterministic_value` returns a valid value of the type given by the argument.

The types currently supported are: integer types, floating-point types, vector types.

Query for this feature with `__has_builtin(__builtin_nondeterministic_value)`.

### `__builtin_sycl_unique_stable_name`

`__builtin_sycl_unique_stable_name()` is a builtin that takes a type and
produces a string literal containing a unique name for the type that is stable
across split compilations, mainly to support SYCL/Data Parallel C++ language.

In cases where the split compilation needs to share a unique token for a type
across the boundary (such as in an offloading situation), this name can be used
for lookup purposes, such as in the SYCL Integration Header.

The value of this builtin is computed entirely at compile time, so it can be
used in constant expressions. This value encodes lambda functions based on a
stable numbering order in which they appear in their local declaration contexts.
Once this builtin is evaluated in a constexpr context, it is erroneous to use
it in an instantiation which changes its value.

In order to produce the unique name, the current implementation of the builtin
uses Itanium mangling even if the host compilation uses a different name
mangling scheme at runtime. The mangler marks all the lambdas required to name
the SYCL kernel and emits a stable local ordering of the respective lambdas.
The resulting pattern is demanglable. When non-lambda types are passed to the
builtin, the mangler emits their usual pattern without any special treatment.

**Syntax**:

```c
// Computes a unique stable name for the given type.
constexpr const char * __builtin_sycl_unique_stable_name( type-id );
```

### `__builtin_popcountg`

`__builtin_popcountg` returns the number of 1 bits in the argument. The
argument can be of any unsigned integer type or fixed boolean vector.

**Syntax**:

```c++
int __builtin_popcountg(type x)
```

**Examples**:

```c++
unsigned int x = 1;
int x_pop = __builtin_popcountg(x);

unsigned long y = 3;
int y_pop = __builtin_popcountg(y);

unsigned _BitInt(128) z = 7;
int z_pop = __builtin_popcountg(z);
```

**Description**:

`__builtin_popcountg` is meant to be a type-generic alternative to the
`__builtin_popcount{,l,ll}` builtins, with support for other integer types,
such as `unsigned __int128` and C23 `unsigned _BitInt(N)`.

### `__builtin_clzg` and `__builtin_ctzg`

`__builtin_clzg` (respectively `__builtin_ctzg`) returns the number of
leading (respectively trailing) 0 bits in the first argument. The first argument
can be of any unsigned integer type or fixed boolean vector.

For boolean vectors, these builtins interpret the vector like a bit-field where
the ith element of the vector is bit i of the bit-field, counting from the
least significant end. `__builtin_clzg` returns the number of zero elements at
the end of the vector, while `__builtin_ctzg` returns the number of zero
elements at the start of the vector.

If the first argument is 0 and an optional second argument of `int` type is
provided, then the second argument is returned. If the first argument is 0, but
only one argument is provided, then the behavior is undefined.

**Syntax**:

```c++
int __builtin_clzg(type x[, int fallback])
int __builtin_ctzg(type x[, int fallback])
```

**Examples**:

```c++
unsigned int x = 1;
int x_lz = __builtin_clzg(x);
int x_tz = __builtin_ctzg(x);

unsigned long y = 2;
int y_lz = __builtin_clzg(y);
int y_tz = __builtin_ctzg(y);

unsigned _BitInt(128) z = 4;
int z_lz = __builtin_clzg(z);
int z_tz = __builtin_ctzg(z);
```

**Description**:

`__builtin_clzg` (respectively `__builtin_ctzg`) is meant to be a
type-generic alternative to the `__builtin_clz{,l,ll}` (respectively
`__builtin_ctz{,l,ll}`) builtins, with support for other integer types, such
as `unsigned __int128` and C23 `unsigned _BitInt(N)`.

### `__builtin_counted_by_ref`

`__builtin_counted_by_ref` returns a pointer to the count field from the
`counted_by` attribute.

The argument must be a flexible array member or a pointer with the `counted_by`
attribute. If the argument doesn't have the `counted_by` attribute, the builtin
returns `(void *)0`.

**Syntax**:

```c
T *__builtin_counted_by_ref(void *array)
```

**Examples**:

```c
#define alloc(P, FAM, COUNT) ({                                 \
   size_t __ignored_assignment;                                 \
   typeof(P) __p = NULL;                                        \
   __p = malloc(MAX(sizeof(*__p),                               \
                    sizeof(*__p) + sizeof(*__p->FAM) * COUNT)); \
                                                                \
   *_Generic(                                                   \
     __builtin_counted_by_ref(__p->FAM),                        \
       void *: &__ignored_assignment,                           \
       default: __builtin_counted_by_ref(__p->FAM)) = COUNT;    \
                                                                \
   __p;                                                         \
})
```

**Description**:

The `__builtin_counted_by_ref` builtin allows the programmer to prevent a
common error associated with the `counted_by` attribute. When using the
`counted_by` attribute, the `count` field **must** be set before the
flexible array member or pointer can be accessed. Otherwise, the sanitizers may
view such accesses as false positives. For instance, it's not uncommon for
programmers to initialize the flexible array before setting the `count` field:

```c
struct s {
  int dummy;
  short count;
  long array[] __attribute__((counted_by(count)));
};

struct s *ptr = malloc(sizeof(struct s) + sizeof(long) * COUNT);

for (int i = 0; i < COUNT; ++i)
  ptr->array[i] = i;

ptr->count = COUNT;
```

Enforcing the rule that `ptr->count = COUNT;` must occur after every
allocation of a struct with a `counted_by` member is prone to failure in large
code bases. This builtin mitigates this for allocators (like in Linux) that are
implemented in a way where the counter assignment can happen automatically.

**Note:** The value returned by `__builtin_counted_by_ref` cannot be assigned
to a variable, have its address taken, or passed into or returned from a
function, because doing so violates bounds safety conventions.

(builtin_stack_address-doc)=
(builtin-stack-address-doc)=

### `__builtin_stack_address`

`__builtin_stack_address` returns the address that separates the current
function's (i.e. the one calling the builtin) stack space and the region of the
stack that may be modified by called functions. The semantics match those of
GCC's builtin of the same name.

**Syntax**:

```c++
void *__builtin_stack_address()
```

**Example**:

```c++
void *sp = __builtin_stack_address();
```

**Description**:

The address returned by `__builtin_stack_address` identifies the starting
address of the stack region that may be used by called functions.

On some architectures (e.g. x86), it's sufficient to return the value in the
stack pointer register directly. On others (e.g. SPARCv9), adjustments are
required to the value of the stack pointer register.
`__builtin_stack_address` performs the necessary adjustments and returns the
correct boundary address.

### Multiprecision Arithmetic Builtins

Clang provides a set of builtins which expose multiprecision arithmetic in a
manner amenable to C. They all have the following form:

```c
unsigned x = ..., y = ..., carryin = ..., carryout;
unsigned sum = __builtin_addc(x, y, carryin, &carryout);
```

Thus one can form a multiprecision addition chain in the following manner:

```c
unsigned *x, *y, *z, carryin=0, carryout;
z[0] = __builtin_addc(x[0], y[0], carryin, &carryout);
carryin = carryout;
z[1] = __builtin_addc(x[1], y[1], carryin, &carryout);
carryin = carryout;
z[2] = __builtin_addc(x[2], y[2], carryin, &carryout);
carryin = carryout;
z[3] = __builtin_addc(x[3], y[3], carryin, &carryout);
```

The complete list of builtins are:

```c
unsigned char      __builtin_addcb (unsigned char x, unsigned char y, unsigned char carryin, unsigned char *carryout);
unsigned short     __builtin_addcs (unsigned short x, unsigned short y, unsigned short carryin, unsigned short *carryout);
unsigned           __builtin_addc  (unsigned x, unsigned y, unsigned carryin, unsigned *carryout);
unsigned long      __builtin_addcl (unsigned long x, unsigned long y, unsigned long carryin, unsigned long *carryout);
unsigned long long __builtin_addcll(unsigned long long x, unsigned long long y, unsigned long long carryin, unsigned long long *carryout);
unsigned char      __builtin_subcb (unsigned char x, unsigned char y, unsigned char carryin, unsigned char *carryout);
unsigned short     __builtin_subcs (unsigned short x, unsigned short y, unsigned short carryin, unsigned short *carryout);
unsigned           __builtin_subc  (unsigned x, unsigned y, unsigned carryin, unsigned *carryout);
unsigned long      __builtin_subcl (unsigned long x, unsigned long y, unsigned long carryin, unsigned long *carryout);
unsigned long long __builtin_subcll(unsigned long long x, unsigned long long y, unsigned long long carryin, unsigned long long *carryout);
```

### Checked Arithmetic Builtins

Clang provides a set of builtins that implement checked arithmetic for security
critical applications in a manner that is fast and easily expressible in C. As
an example of their usage:

```c
errorcode_t security_critical_application(...) {
  unsigned x, y, result;
  ...
  if (__builtin_mul_overflow(x, y, &result))
    return kErrorCodeHackers;
  ...
  use_multiply(result);
  ...
}
```

Clang provides the following checked arithmetic builtins:

```
/* Detailed source-code truncated for AI context efficiency. */
```

Each builtin performs the specified mathematical operation on the
first two arguments and stores the result in the third argument. If
possible, the result will be equal to mathematically-correct result
and the builtin will return 0. Otherwise, the builtin will return
1 and the result will be equal to the unique value that is equivalent
to the mathematically-correct result modulo two raised to the *k*
power, where *k* is the number of bits in the result type. The
behavior of these builtins is well-defined for all argument values.

The first three builtins work generically for operands of any integer type,
including boolean types. The operands need not have the same type as each
other, or as the result. The other builtins may implicitly promote or
convert their operands before performing the operation.

Query for this feature with `__has_builtin(__builtin_add_overflow)`, etc.

### Floating point builtins

### `__builtin_isfpclass`

`__builtin_isfpclass` is used to test if the specified floating-point values
fall into one of the specified floating-point classes.

**Syntax**:

```c++
int __builtin_isfpclass(fp_type expr, int mask)
int_vector __builtin_isfpclass(fp_vector expr, int mask)
```

**Example of use**:

```c++
if (__builtin_isfpclass(x, 448)) {
   // `x` is positive finite value
       ...
}
```

**Description**:

The `__builtin_isfpclass()` builtin is a generalization of functions `isnan`,
`isinf`, `isfinite` and some others defined by the C standard. It tests if
the floating-point value, specified by the first argument, falls into any of data
classes, specified by the second argument. The latter is an integer constant
bitmask expression, in which each data class is represented by a bit
using the encoding:

| Mask value | Data class         | Macro                    |
| ---------- | ------------------ | ------------------------ |
| 0x0001     | Signaling NaN      | \_\_FPCLASS_SNAN         |
| 0x0002     | Quiet NaN          | \_\_FPCLASS_QNAN         |
| 0x0004     | Negative infinity  | \_\_FPCLASS_NEGINF       |
| 0x0008     | Negative normal    | \_\_FPCLASS_NEGNORMAL    |
| 0x0010     | Negative subnormal | \_\_FPCLASS_NEGSUBNORMAL |
| 0x0020     | Negative zero      | \_\_FPCLASS_NEGZERO      |
| 0x0040     | Positive zero      | \_\_FPCLASS_POSZERO      |
| 0x0080     | Positive subnormal | \_\_FPCLASS_POSSUBNORMAL |
| 0x0100     | Positive normal    | \_\_FPCLASS_POSNORMAL    |
| 0x0200     | Positive infinity  | \_\_FPCLASS_POSINF       |

For convenience preprocessor defines macros for these values. The function
returns 1 if `expr` falls into one of the specified data classes, 0 otherwise.

In the example above the mask value 448 (0x1C0) contains the bits selecting
positive zero, positive subnormal and positive normal classes.
`__builtin_isfpclass(x, 448)` would return true only if `x` if of any of
these data classes. Using suitable mask value, the function can implement any of
the standard classification functions, for example, `__builtin_isfpclass(x, 3)`
is identical to `isnan`, `__builtin_isfpclass(x, 504)` - to `isfinite`
and so on.

If the first argument is a vector, the function is equivalent to the set of
scalar calls of `__builtin_isfpclass` applied to the input elementwise.

The result of `__builtin_isfpclass` is a boolean value, if the first argument
is a scalar, or an integer vector with the same element count as the first
argument. The element type in this vector has the same bit length as the
element of the first argument type.

This function never raises floating-point exceptions and does not canonicalize
its input. The floating-point argument is not promoted, its data class is
determined based on its representation in its actual semantic type.

### `__builtin_canonicalize`

```c
double __builtin_canonicalize(double);
float __builtin_canonicalizef(float);
long double __builtin_canonicalizel(long double);
```

Returns the platform specific canonical encoding of a floating point
number. This canonicalization is useful for implementing certain
numeric primitives such as frexp. See [LLVM canonicalize intrinsic](https://llvm.org/docs/LangRef.html#llvm-canonicalize-intrinsic) for
more information on the semantics.

### `__builtin_flt_rounds` and `__builtin_set_flt_rounds`

```c
int __builtin_flt_rounds();
void __builtin_set_flt_rounds(int);
```

Returns and sets current floating point rounding mode. The encoding of returned
values and input parameters is same as the result of FLT_ROUNDS, specified by C
standard:
\- `0` - toward zero
\- `1` - to nearest, ties to even
\- `2` - toward positive infinity
\- `3` - toward negative infinity
\- `4` - to nearest, ties away from zero
The effect of passing some other value to `__builtin_flt_rounds` is
implementation-defined. `__builtin_set_flt_rounds` is currently only supported
to work on x86, x86_64, powerpc, powerpc64, Arm and AArch64 targets. These builtins
read and modify the floating-point environment, which is not always allowed and may
have unexpected behavior. Please see the section on [Accessing the floating point environment](UsersManual.md#accessing-the-floating-point-environment) for more information.

### String builtins

Clang provides constant expression evaluation support for builtins forms of
the following functions from the C standard library headers
`<string.h>` and `<wchar.h>`:

- `memchr`
- `memcmp` (and its deprecated BSD / POSIX alias `bcmp`)
- `strchr`
- `strcmp`
- `strlen`
- `strncmp`
- `wcschr`
- `wcscmp`
- `wcslen`
- `wcsncmp`
- `wmemchr`
- `wmemcmp`

In each case, the builtin form has the name of the C library function prefixed
by `__builtin_`. Example:

```c
void *p = __builtin_memchr("foobar", 'b', 5);
```

In addition to the above, one further builtin is provided:

```c
char *__builtin_char_memchr(const char *haystack, int needle, size_t size);
```

`__builtin_char_memchr(a, b, c)` is identical to
`(char*)__builtin_memchr(a, b, c)` except that its use is permitted within
constant expressions in C++11 onwards (where a cast from `void*` to `char*`
is disallowed in general).

Constant evaluation support for the `__builtin_mem*` functions is provided
only for arrays of `char`, `signed char`, `unsigned char`, or `char8_t`,
despite these functions accepting an argument of type `const void*`.

Support for constant expression evaluation for the above builtins can be detected
with `__has_feature(cxx_constexpr_string_builtins)`.

### Variadic function builtins

Clang provides several builtins for working with variadic functions from the C
standard library `<stdarg.h>` header:

- `__builtin_va_list`

A predefined typedef for the target-specific `va_list` type. It is undefined
behavior to use a byte-wise copy of this type produced by calling `memcpy`,
`memmove`, or similar. Valid explicit copies are only produced by calling
`va_copy` or `__builtin_va_copy`.

- `void __builtin_va_start(__builtin_va_list list, <parameter-name>)`

A builtin function for the target-specific `va_start` function-like macro.
The `parameter-name` argument is the name of the parameter preceding the
ellipsis (`...`) in the function signature. Alternatively, in C23 mode or
later, it may be the integer literal `0` if there is no parameter preceding
the ellipsis. This function initializes the given `__builtin_va_list` object.
It is undefined behavior to call this function on an already initialized
`__builtin_va_list` object.

- `void __builtin_c23_va_start(__builtin_va_list list, ...)`

A builtin function for the target-specific `va_start` function-like macro,
available only in C23 and later. The builtin accepts zero or one argument for
the ellipsis (`...`). If such an argument is provided, it should be the name
of the parameter preceding the ellipsis, which is used for compatibility with
C versions before C23. It is an error to provide two or more variadic arguments.
This function initializes the given `__builtin_va_list` object. It is
undefined behavior to call this function on an already initialized
`__builtin_va_list` object.

- `void __builtin_va_end(__builtin_va_list list)`

A builtin function for the target-specific `va_end` function-like macro. This
function finalizes the given `__builtin_va_list` object such that it is no
longer usable unless re-initialized with a call to `__builtin_va_start` or
`__builtin_va_copy`. It is undefined behavior to call this function with a
`list` that has not been initialized by either `__builtin_va_start` or
`__builtin_va_copy`.

- `<type-name> __builtin_va_arg(__builtin_va_list list, <type-name>)`

A builtin function for the target-specific `va_arg` function-like macro. This
function returns the value of the next variadic argument to the call. It is
undefined behavior to call this builtin when there is no next variadic argument
to retrieve or if the next variadic argument does not have a type compatible
with the given `type-name`. The return type of the function is the
`type-name` given as the second argument. It is undefined behavior to call
this function with a `list` that has not been initialized by either
`__builtin_va_start` or `__builtin_va_copy`.

- `void __builtin_va_copy(__builtin_va_list dest, __builtin_va_list src)`

A builtin function for the target-specific `va_copy` function-like macro.
This function initializes `dest` as a copy of `src`. It is undefined
behavior to call this function with an already initialized `dest` argument.

### Memory builtins

Clang provides constant expression evaluation support for builtin forms of the
following functions from the C standard library headers
`<string.h>` and `<wchar.h>`:

- `memcpy`
- `memmove`
- `wmemcpy`
- `wmemmove`

In each case, the builtin form has the name of the C library function prefixed
by `__builtin_`.

Constant evaluation support is only provided when the source and destination
are pointers to arrays with the same trivially copyable element type, and the
given size is an exact multiple of the element size that is no greater than
the number of elements accessible through the source and destination operands.

#### Guaranteed inlined copy

```c
void __builtin_memcpy_inline(void *dst, const void *src, size_t size);
```

`__builtin_memcpy_inline` has been designed as a building block for efficient
`memcpy` implementations. It is identical to `__builtin_memcpy` but also
guarantees not to call any external functions. See LLVM IR [llvm.memcpy.inline](https://llvm.org/docs/LangRef.html#llvm-memcpy-inline-intrinsic) intrinsic
for more information.

This is useful to implement a custom version of `memcpy`, implement a
`libc` memcpy or work around the absence of a `libc`.

Note that the `size` argument must be a compile time constant.

Note that this intrinsic cannot yet be called in a `constexpr` context.

#### Guaranteed inlined memset

```c
void __builtin_memset_inline(void *dst, int value, size_t size);
```

`__builtin_memset_inline` has been designed as a building block for efficient
`memset` implementations. It is identical to `__builtin_memset` but also
guarantees not to call any external functions. See LLVM IR [llvm.memset.inline](https://llvm.org/docs/LangRef.html#llvm-memset-inline-intrinsic) intrinsic
for more information.

This is useful to implement a custom version of `memset`, implement a
`libc` memset or work around the absence of a `libc`.

Note that the `size` argument must be a compile time constant.

Note that this intrinsic cannot yet be called in a `constexpr` context.

### `__is_bitwise_cloneable`

A type trait is used to check whether a type can be safely copied by memcpy.

**Syntax**:

```c++
bool __is_bitwise_cloneable(Type)
```

**Description**:

Objects of bitwise cloneable types can be bitwise copied by memcpy/memmove. The
Clang compiler warrants that this behavior is well defined, and won't be
broken by compiler optimizations and sanitizers.

For implicit-lifetime types, the lifetime of the new object is implicitly
started after the copy. For other types (e.g., classes with virtual methods),
the lifetime isn't started, and using the object results in undefined behavior
according to the C++ Standard.

This builtin can be used in constant expressions.

### Atomic Min/Max builtins with memory ordering

There are two atomic builtins with min/max in-memory comparison and swap.
The syntax and semantics are similar to GCC-compatible \_\_atomic\_\* builtins.

- `__atomic_fetch_min`
- `__atomic_fetch_max`

The builtins work with signed and unsigned integers and require to specify memory ordering.
The return value is the original value that was stored in memory before comparison.

Clang provides two additional atomic builtins with incrementing behavior. These
builtins perform an unsigned increment or decrement modulo a wrap-around value.

- `__atomic_fetch_uinc`
- `__atomic_fetch_udec`

See the LLVM IR [atomicrmw](https://llvm.org/docs/LangRef.html#atomicrmw-instruction)
instruction for the complete semantics of uinc_wrap and udec_wrap.

Atomic memory scopes are designed to assist optimizations for systems with
several levels of memory hierarchy like GPUs. The following memory scopes are
currently supported:

Example:

```c
unsigned int val = __atomic_fetch_min(unsigned int *pi, unsigned int ui, __ATOMIC_RELAXED);
```

The third argument is one of the memory ordering specifiers `__ATOMIC_RELAXED`,
`__ATOMIC_CONSUME`, `__ATOMIC_ACQUIRE`, `__ATOMIC_RELEASE`,
`__ATOMIC_ACQ_REL`, or `__ATOMIC_SEQ_CST` following C++11 memory model semantics.

In terms of acquire-release ordering barriers these two operations are always
considered as operations with *load-store* semantics, even when the original value
is not actually modified after comparison.

(langext-__c11_atomic)=
(langext-c11-atomic)=

### \_\_c11_atomic builtins

Clang provides a set of builtins which are intended to be used to implement
C11's `<stdatomic.h>` header. These builtins provide the semantics of the
`_explicit` form of the corresponding C11 operation, and are named with a
`__c11_` prefix. The supported operations, and the differences from
the corresponding C11 operations, are:

- `__c11_atomic_init`
- `__c11_atomic_thread_fence`
- `__c11_atomic_signal_fence`
- `__c11_atomic_is_lock_free` (The argument is the size of the
  `_Atomic(...)` object, instead of its address)
- `__c11_atomic_store`
- `__c11_atomic_load`
- `__c11_atomic_exchange`
- `__c11_atomic_compare_exchange_strong`
- `__c11_atomic_compare_exchange_weak`
- `__c11_atomic_fetch_add`
- `__c11_atomic_fetch_sub`
- `__c11_atomic_fetch_and`
- `__c11_atomic_fetch_or`
- `__c11_atomic_fetch_xor`
- `__c11_atomic_fetch_nand` (Nand is not presented in `<stdatomic.h>`)
- `__c11_atomic_fetch_max`
- `__c11_atomic_fetch_min`

The macros `__ATOMIC_RELAXED`, `__ATOMIC_CONSUME`, `__ATOMIC_ACQUIRE`,
`__ATOMIC_RELEASE`, `__ATOMIC_ACQ_REL`, and `__ATOMIC_SEQ_CST` are
provided, with values corresponding to the enumerators of C11's
`memory_order` enumeration.

(Note that Clang additionally provides GCC-compatible `__atomic_*`
builtins and OpenCL 2.0 `__opencl_atomic_*` builtins. The OpenCL 2.0
atomic builtins are an explicit form of the corresponding OpenCL 2.0
builtin function, and are named with a `__opencl_` prefix. The macros
`__OPENCL_MEMORY_SCOPE_WORK_ITEM`, `__OPENCL_MEMORY_SCOPE_WORK_GROUP`,
`__OPENCL_MEMORY_SCOPE_DEVICE`, `__OPENCL_MEMORY_SCOPE_ALL_SVM_DEVICES`,
and `__OPENCL_MEMORY_SCOPE_SUB_GROUP` are provided, with values
corresponding to the enumerators of OpenCL's `memory_scope` enumeration.)

(langext-__scoped_atomic)=
(langext-scoped-atomic)=

### \_\_scoped_atomic builtins

Clang provides a set of atomics taking a memory scope argument. These atomics
are identical to the standard GNU / GCC atomic builtins but taking an extra
memory scope argument. These are designed to be a generic alternative to the
`__opencl_atomic_*` builtin functions for targets that support atomic memory
scopes.

- `__MEMORY_SCOPE_SYSTEM`
- `__MEMORY_SCOPE_DEVICE`
- `__MEMORY_SCOPE_WRKGRP`
- `__MEMORY_SCOPE_CLUSTR`
- `__MEMORY_SCOPE_WVFRNT`
- `__MEMORY_SCOPE_SINGLE`

This controls whether or not the atomic operation is ordered with respect to the
whole system, the current device, an OpenCL workgroup, wavefront, or just a
single thread. If these are used on a target that does not support atomic
scopes, then they will behave exactly as the standard GNU atomic builtins.

### Low-level ARM exclusive memory builtins

Clang provides overloaded builtins giving direct access to the three key ARM
instructions for implementing atomic operations.

```c
T __builtin_arm_ldrex(const volatile T *addr);
T __builtin_arm_ldaex(const volatile T *addr);
int __builtin_arm_strex(T val, volatile T *addr);
int __builtin_arm_stlex(T val, volatile T *addr);
void __builtin_arm_clrex(void);
```

The types `T` currently supported are:

- Integer types with width at most 64 bits (or 128 bits on AArch64).
- Floating-point types
- Pointer types.

Note that the compiler does not guarantee it will not insert stores which clear
the exclusive monitor in between an `ldrex` type operation and its paired
`strex`. In practice this is only usually a risk when the extra store is on
the same cache line as the variable being modified and Clang will only insert
stack stores on its own, so it is best not to use these operations on variables
with automatic storage duration.

Also, loads and stores may be implicit in code written between the `ldrex` and
`strex`. Clang will not necessarily mitigate the effects of these either, so
care should be exercised.

For these reasons the higher level atomic primitives should be preferred where
possible.

### Non-temporal load/store builtins

Clang provides overloaded builtins allowing generation of non-temporal memory
accesses.

```c
T __builtin_nontemporal_load(T *addr);
void __builtin_nontemporal_store(T value, T *addr);
```

The types `T` currently supported are:

- Integer types.
- Floating-point types.
- Vector types.

Note that the compiler does not guarantee that non-temporal loads or stores
will be used.

### C++ Coroutines support builtins

:::{warning}
This is a work in progress. Compatibility across Clang/LLVM releases is not
guaranteed.
:::

Clang provides experimental builtins to support C++ Coroutines as defined by
<https://wg21.link/P0057>. The following four are intended to be used by the
standard library to implement the `std::coroutine_handle` type.

**Syntax**:

```c
void  __builtin_coro_resume(void *addr);
void  __builtin_coro_destroy(void *addr);
bool  __builtin_coro_done(void *addr);
void *__builtin_coro_promise(void *addr, int alignment, bool from_promise)
```

**Example of use**:

```c++
template <> struct coroutine_handle<void> {
  void resume() const { __builtin_coro_resume(ptr); }
  void destroy() const { __builtin_coro_destroy(ptr); }
  bool done() const { return __builtin_coro_done(ptr); }
  // ...
protected:
  void *ptr;
};

template <typename Promise> struct coroutine_handle : coroutine_handle<> {
  // ...
  Promise &promise() const {
    return *reinterpret_cast<Promise *>(
      __builtin_coro_promise(ptr, alignof(Promise), /*from-promise=*/false));
  }
  static coroutine_handle from_promise(Promise &promise) {
    coroutine_handle p;
    p.ptr = __builtin_coro_promise(&promise, alignof(Promise),
                                                    /*from-promise=*/true);
    return p;
  }
};
```

Other coroutine builtins are either for internal clang use or for use during
development of the coroutine feature. See [Coroutines in LLVM](https://llvm.org/docs/Coroutines.html#intrinsics) for
more information on their semantics. Note that builtins matching the intrinsics
that take token as the first parameter (llvm.coro.begin, llvm.coro.alloc,
llvm.coro.free and llvm.coro.suspend) omit the token parameter and fill it to
an appropriate value during the emission.

**Syntax**:

```c
size_t __builtin_coro_size()
void  *__builtin_coro_frame()
void  *__builtin_coro_free(void *coro_frame)

void  *__builtin_coro_id(int align, void *promise, void *fnaddr, void *parts)
bool   __builtin_coro_alloc()
void  *__builtin_coro_begin(void *memory)
void   __builtin_coro_end(void *coro_frame, bool unwind)
char   __builtin_coro_suspend(bool final)
```

Note that there is no builtin matching the `llvm.coro.save` intrinsic. LLVM
automatically will insert one if the first argument to `llvm.coro.suspend` is
token `none`. If a user calls `__builtin_suspend`, clang will insert `token none`
as the first argument to the intrinsic.

### Source location builtins

Clang provides builtins to support C++ standard library implementation
of `std::source_location` as specified in C++20. With the exception
of `__builtin_COLUMN`, `__builtin_FILE_NAME` and `__builtin_FUNCSIG`,
these builtins are also implemented by GCC.

**Syntax**:

```c
const char *__builtin_FILE();
const char *__builtin_FILE_NAME(); // Clang only
const char *__builtin_FUNCTION();
const char *__builtin_FUNCSIG(); // Microsoft
unsigned    __builtin_LINE();
unsigned    __builtin_COLUMN(); // Clang only
const std::source_location::__impl *__builtin_source_location();
```

**Example of use**:

```c++
void my_assert(bool pred, int line = __builtin_LINE(), // Captures line of caller
               const char* file = __builtin_FILE(),
               const char* function = __builtin_FUNCTION()) {
  if (pred) return;
  printf("%s:%d assertion failed in function %s\n", file, line, function);
  std::abort();
}

struct MyAggregateType {
  int x;
  int line = __builtin_LINE(); // captures line where aggregate initialization occurs
};
static_assert(MyAggregateType{42}.line == __LINE__);

struct MyClassType {
  int line = __builtin_LINE(); // captures line of the constructor used during initialization
  constexpr MyClassType(int) { assert(line == __LINE__); }
};
```

**Description**:

The builtins `__builtin_LINE`, `__builtin_FUNCTION`, `__builtin_FUNCSIG`,
`__builtin_FILE` and `__builtin_FILE_NAME` return the values, at the
"invocation point", for `__LINE__`, `__FUNCTION__`, `__FUNCSIG__`,
`__FILE__` and `__FILE_NAME__` respectively. `__builtin_COLUMN` similarly
returns the column, though there is no corresponding macro. These builtins are
constant expressions.

When the builtins appear as part of a default function argument the invocation
point is the location of the caller. When the builtins appear as part of a
default member initializer, the invocation point is the location of the
constructor or aggregate initialization used to create the object. Otherwise
the invocation point is the same as the location of the builtin.

When the invocation point of `__builtin_FUNCTION` is not a function scope, the
empty string is returned.

The builtin `__builtin_COLUMN` returns the offset from the start of the line,
beginning from column 1. [This may differ from other implementations.](https://eel.is/c++draft/support.srcloc#tab:support.srcloc.current-row-3-column-2-sentence-2)

The builtin `__builtin_source_location` returns a pointer to constant static
data of type `std::source_location::__impl`. This type must have already been
defined, and must contain exactly four fields: `const char *_M_file_name`,
`const char *_M_function_name`, `<any-integral-type> _M_line`, and
`<any-integral-type> _M_column`. The fields will be populated in the same
manner as the above four builtins, except that `_M_function_name` is populated
with `__PRETTY_FUNCTION__` rather than `__FUNCTION__`.

### Alignment builtins

Clang provides builtins to support checking and adjusting alignment of
pointers and integers.
These builtins can be used to avoid relying on implementation-defined behavior
of arithmetic on integers derived from pointers.
Additionally, these builtins retain type information and, unlike bitwise
arithmetic, they can perform semantic checking on the alignment value.

**Syntax**:

```c
Type __builtin_align_up(Type value, size_t alignment);
Type __builtin_align_down(Type value, size_t alignment);
bool __builtin_is_aligned(Type value, size_t alignment);
```

**Example of use**:

```c++
char* global_alloc_buffer;
void* my_aligned_allocator(size_t alloc_size, size_t alignment) {
  char* result = __builtin_align_up(global_alloc_buffer, alignment);
  // result now contains the value of global_alloc_buffer rounded up to the
  // next multiple of alignment.
  global_alloc_buffer = result + alloc_size;
  return result;
}

void* get_start_of_page(void* ptr) {
  return __builtin_align_down(ptr, PAGE_SIZE);
}

void example(char* buffer) {
   if (__builtin_is_aligned(buffer, 64)) {
     do_fast_aligned_copy(buffer);
   } else {
     do_unaligned_copy(buffer);
   }
}

// In addition to pointers, the builtins can also be used on integer types
// and are evaluatable inside constant expressions.
static_assert(__builtin_align_up(123, 64) == 128, "");
static_assert(__builtin_align_down(123u, 64) == 64u, "");
static_assert(!__builtin_is_aligned(123, 64), "");
```

**Description**:

The builtins `__builtin_align_up`, `__builtin_align_down`, return their
first argument aligned up/down to the next multiple of the second argument.
If the value is already sufficiently aligned, it is returned unchanged.
The builtin `__builtin_is_aligned` returns whether the first argument is
aligned to a multiple of the second argument.
All of these builtins expect the alignment to be expressed as a number of bytes.

These builtins can be used for all integer types as well as (non-function)
pointer types. For pointer types, these builtins operate in terms of the integer
address of the pointer and return a new pointer of the same type (including
qualifiers such as `const`) with an adjusted address.
When aligning pointers up or down, the resulting value must be within the same
underlying allocation or one past the end (see C17 6.5.6p8, C++ [expr.add]).
This means that arbitrary integer values stored in pointer-type variables must
not be passed to these builtins. For those use cases, the builtins can still be
used, but the operation must be performed on the pointer cast to `uintptr_t`.

Null pointers are considered to be aligned to any requested alignment.
Therefore, `__builtin_is_aligned` evaluates to true for null pointer
arguments, and `__builtin_align_up` and `__builtin_align_down` preserve
the null pointer value.

If Clang can determine that the alignment is not a power of two at compile time,
it will result in a compilation failure. If the alignment argument is not a
power of two at run time, the behavior of these builtins is undefined.

## Non-standard C++11 Attributes

Clang's non-standard C++11 attributes live in the `clang` attribute
namespace.

Clang supports GCC's `gnu` attribute namespace. All GCC attributes which
are accepted with the `__attribute__((foo))` syntax are also accepted as
`[[gnu::foo]]`. This only extends to attributes which are specified by GCC
(see the list of [GCC function attributes](https://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html), [GCC variable
attributes](https://gcc.gnu.org/onlinedocs/gcc/Variable-Attributes.html), and
[GCC type attributes](https://gcc.gnu.org/onlinedocs/gcc/Type-Attributes.html)). As with the GCC
implementation, these attributes must appertain to the *declarator-id* in a
declaration, which means they must go either at the start of the declaration or
immediately after the name being declared.

For example, this applies the GNU `unused` attribute to `a` and `f`, and
also applies the GNU `noreturn` attribute to `f`.

Examples:

```c++
[[gnu::unused]] int a, f [[gnu::noreturn]] ();
```

## Target-Specific Extensions

Clang supports some language features conditionally on some targets.

### AMDGPU Language Extensions

#### \_\_builtin_amdgcn_fence

`__builtin_amdgcn_fence` emits a fence.

- `unsigned` atomic ordering, e.g., `__ATOMIC_ACQUIRE`
- `const char *` synchronization scope, e.g., `workgroup`
- Zero or more `const char *` address spaces names.

The address spaces arguments must be one of the following string literals:

- `"local"`
- `"global"`

If one or more address space name are provided, the code generator will attempt
to emit potentially faster instructions that order access to at least those
address spaces.
Emitting such instructions may not always be possible and the compiler is free
to fence more aggressively.

If no address spaces names are provided, all address spaces are fenced.

```c++
// Fence all address spaces.
__builtin_amdgcn_fence(__ATOMIC_SEQ_CST, "workgroup");
__builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "agent");

// Fence only requested address spaces.
__builtin_amdgcn_fence(__ATOMIC_SEQ_CST, "workgroup", "local")
__builtin_amdgcn_fence(__ATOMIC_SEQ_CST, "workgroup", "local", "global")
```

#### \_\_builtin_amdgcn_processor_is and \_\_builtin_amdgcn_is_invocable

`__builtin_amdgcn_processor_is` and `__builtin_amdgcn_is_invocable` provide
a functional mechanism for programatically querying:

- the identity of the current target processor;
- the capability of the current target processor to invoke a particular builtin.

**Syntax**:

```c
__amdgpu_feature_predicate_t __builtin_amdgcn_processor_is(const char*);
__amdgpu_feature_predicate_t __builtin_amdgcn_is_invocable(builtin_name);
```

**Example of use**:

```c++
if (__builtin_amdgcn_processor_is("gfx1201") ||
    __builtin_amdgcn_is_invocable(__builtin_amdgcn_s_sleep_var))
  __builtin_amdgcn_s_sleep_var(x);

if (!__builtin_amdgcn_processor_is("gfx906"))
  __builtin_amdgcn_s_wait_event_export_ready();
else if (__builtin_amdgcn_processor_is("gfx1010") ||
         __builtin_amdgcn_processor_is("gfx1101"))
  __builtin_amdgcn_s_ttracedata_imm(1);

while (__builtin_amdgcn_processor_is("gfx1101")) *p += x;

do {
  break;
} while (__builtin_amdgcn_processor_is("gfx1010"));

for (; __builtin_amdgcn_processor_is("gfx1201"); ++*p) break;

if (__builtin_amdgcn_is_invocable(__builtin_amdgcn_s_wait_event_export_ready))
  __builtin_amdgcn_s_wait_event_export_ready();
else if (__builtin_amdgcn_is_invocable(__builtin_amdgcn_s_ttracedata_imm))
  __builtin_amdgcn_s_ttracedata_imm(1);

do {
  break;
} while (
    __builtin_amdgcn_is_invocable(__builtin_amdgcn_global_load_tr_b64_i32));

for (; __builtin_amdgcn_is_invocable(__builtin_amdgcn_permlane64); ++*p)
  break;
```

**Description**:

The builtins return a value of type `__amdgpu_feature_predicate_t`, which is a
target specific type that behaves as if its C++ definition was the following:

```c++
struct __amdgpu_feature_predicate_t {
  __amdgpu_feature_predicate_t() = delete;
  __amdgpu_feature_predicate_t(const __amdgpu_feature_predicate_t&) = delete;
  __amdgpu_feature_predicate_t(__amdgpu_feature_predicate_t&&) = delete;

  explicit
  operator bool() const noexcept;
};
```

The builtins can be used in C as well, wherein the
`__amdgpu_feature_predicate_t` type behaves as an opaque, forward declared
type with conditional automated conversion to `_Bool` when used as the
predicate argument to a control structure:

```c
struct __amdgpu_feature_predicate_t ret();     // Error
void arg(struct __amdgpu_feature_predicate_t); // Error
void local() {
  struct __amdgpu_feature_predicate_t x;       // Error
  struct __amdgpu_feature_predicate_t y =
      __builtin_amdgcn_processor_is("gfx900"); // Error
}
void valid_use() {
  _Bool x = (_Bool)__builtin_amdgcn_processor_is("gfx900"); // OK
  if (__builtin_amdgcn_processor_is("gfx900"))       // Implicit cast to _Bool
    return;
  for (; __builtin_amdgcn_processor_is("gfx900");)   // Implicit cast to _Bool
    break;
  while (__builtin_amdgcn_processor_is("gfx900"))    // Implicit cast to _Bool
    break;
  do {
    break;
  } while (__builtin_amdgcn_processor_is("gfx900")); // Implicit cast to _Bool

  __builtin_amdgcn_processor_is("gfx900") ? x : !x;
}
```

The boolean interpretation of the predicate values returned by the builtins:

- indicates whether the current target matches the argument; the argument MUST
  be a string literal and a valid AMDGPU target
- indicates whether the builtin function passed as the argument can be invoked
  by the current target; the argument MUST be either a generic or AMDGPU
  specific builtin name

When invoked while compiling for a concrete target, the builtins are evaluated
early by Clang, and never produce any CodeGen effects / have no observable
side-effects in IR. Conversely, when compiling for AMDGCN flavoured SPIR-v,
which is an abstract target, a series of specialization constants are implicitly
created, in correspondence with the predicates. These predicates get resolved
when finalizing the compilation process for a concrete target, and shall reflect
the latter's identity and features. Thus, it is possible to author high-level
code, in e.g. HIP, that is target adaptive in a dynamic fashion, contrary to
macro based mechanisms.

#### \_\_builtin_amdgcn_ballot_w{32,64}

`__builtin_amdgcn_ballot_w{32,64}` returns a bitmask that contains its
boolean argument as a bit for every lane of the current wave that is currently
active (i.e., that is converged with the executing thread), and a 0 bit for
every lane that is not active.

The result is uniform, i.e., it is the same in every active thread of the wave.

#### \_\_builtin_amdgcn_inverse_ballot_w{32,64}

Given a wave-uniform bitmask, `__builtin_amdgcn_inverse_ballot_w{32,64}(mask)`
returns the bit at the position of the current lane. It is almost equivalent to
`(mask & (1 << lane_id)) != 0`, except that its behavior is only defined if
the given mask has the same value for all active lanes of the current wave.

#### \_\_builtin_amdgcn_av\_{load,store}\_b128

Signature:

```c
typedef __attribute__((__vector_size__(4 * sizeof(unsigned int)))) unsigned int v4u;

v4u __builtin_amdgcn_av_load_b128(v4u *src, int scope);

void __builtin_amdgcn_av_store_b128(v4u *dst, v4u data, int scope);
```

Load or store a vector of 4 unsigned integers from or to memory with cache
behavior specified by `scope`, which is one of the `__MEMORY_SCOPE_*` macros
defined for {ref}`scoped atomic builtins <langext-c11-atomic>`.

The pointer argument must point to the global or generic address space.

These builtins are supported on gfx9, gfx10, gfx11, and gfx12 targets.

They map to the LLVM intrinsics `llvm.amdgcn.av.load.b128` and
`llvm.amdgcn.av.store.b128` documented in [User Guide for AMDGPU Backend](https://llvm.org/docs/AMDGPUUsage.html).

### ARM/AArch64 Language Extensions

#### Memory Barrier Intrinsics

Clang implements the `__dmb`, `__dsb` and `__isb` intrinsics as defined
in the [Arm C Language Extensions](https://github.com/ARM-software/acle/releases).
Note that these intrinsics are implemented as motion barriers that block
reordering of memory accesses and side effect instructions. Other instructions
like simple arithmetic may be reordered around the intrinsic. If you expect to
have no reordering at all, use inline assembly instead.

#### Pointer Authentication

See {doc}`PointerAuthentication`.

### X86/X86-64 Language Extensions

The X86 backend has these language extensions:

#### Memory references to specified segments

Annotating a pointer with address space #256 causes it to be code generated
relative to the X86 GS segment register, address space #257 causes it to be
relative to the X86 FS segment, and address space #258 causes it to be
relative to the X86 SS segment. Note that this is a very very low-level
feature that should only be used if you know what you're doing (for example in
an OS kernel).

Here is an example:

```c++
#define GS_RELATIVE __attribute__((address_space(256)))
int foo(int GS_RELATIVE *P) {
  return *P;
}
```

Which compiles to (on X86-32):

```gas
_foo:
        movl    4(%esp), %eax
        movl    %gs:(%eax), %eax
        ret
```

You can also use the GCC compatibility macros `__seg_fs` and `__seg_gs` for
the same purpose. The preprocessor symbols `__SEG_FS` and `__SEG_GS`
indicate their support.

### PowerPC Language Extensions

#### Set the Floating Point Rounding Mode

PowerPC64/PowerPC64le supports the builtin function `__builtin_setrnd` to set
the floating point rounding mode. This function will use the least significant
two bits of integer argument to set the floating point rounding mode.

```c++
double __builtin_setrnd(int mode);
```

The effective values for mode are:

> - 0 - round to nearest
> - 1 - round to zero
> - 2 - round to +infinity
> - 3 - round to -infinity

Note that the mode argument will modulo 4, so if the integer argument is greater
than 3, it will only use the least significant two bits of the mode.
Namely, `__builtin_setrnd(102))` is equal to `__builtin_setrnd(2)`.

#### PowerPC cache builtins

The PowerPC architecture specifies instructions implementing cache operations.
Clang provides builtins that give direct programmer access to these cache
instructions.

Currently the following builtins are implemented in clang:

`__builtin_dcbf` copies the contents of a modified block from the data cache
to main memory and flushes the copy from the data cache.

**Syntax**:

```c
void __dcbf(const void* addr); /* Data Cache Block Flush */
```

**Example of Use**:

```c
int a = 1;
__builtin_dcbf (&a);
```

### z/OS Language Extensions

#### z/OS builtins

z/OS supports builtins for compare-and-swap operations that generate the
corresponding z/OS assembly instructions (CS, CSG, CDSG). These builtins compare
the value pointed to by oldptr to the value pointed to by curptr. If they are
equal, the value pointed to by newword (or newword itself for `__cs`) is
copied into the location pointed to by curptr. If they are unequal, the value
pointed to by curptr is copied into the location pointed to by oldptr.
The builtins return 0 if the values are equal, or 1 if they are unequal.

- `int __cs(unsigned int *oldptr, unsigned int *curptr, unsigned int newword)`

  Generates a 4-byte compare-and-swap using the CS instruction.
  Use `__cs` instead of `__cs1` when the newword arg is an r-value instead
  of an l-value.

- `int __cs1(void *oldptr, void *curptr, void *newword)`

  Generates a 4-byte compare-and-swap using the CS instruction.

- `int __csg(void *oldptr, void *curptr, void *newword)`

  Generates an 8-byte compare-and-swap using the CSG instruction.

- `int __cds1(void *oldptr, void *curptr, void *newword)`

  Generates an 8-byte compare-and-swap using the CSG instruction.

- `int __cdsg(void *oldptr, void *curptr, void *newword)`

  Generates a 16-byte compare-and-swap using the CDSG instruction.

## Extensions for Static Analysis

Clang supports additional attributes that are useful for documenting program
invariants and rules for static analysis tools, such as the [Clang Static
Analyzer](https://clang-analyzer.llvm.org/). These attributes are documented
in the analyzer's {doc}`list of annotations for analysis <analyzer/user-docs/Annotations>`.

## Extensions for Dynamic Analysis

Use `__has_feature(address_sanitizer)` to check if the code is being built
with {doc}`AddressSanitizer`.

Use `__has_feature(thread_sanitizer)` to check if the code is being built
with {doc}`ThreadSanitizer`.

Use `__has_feature(memory_sanitizer)` to check if the code is being built
with {doc}`MemorySanitizer`.

Use `__has_feature(dataflow_sanitizer)` to check if the code is being built
with {doc}`DataFlowSanitizer`.

Use `__has_feature(safe_stack)` to check if the code is being built
with {doc}`SafeStack`.

## Extensions for selectively disabling optimization

Clang provides a mechanism for selectively disabling optimizations in functions
and methods.

To disable optimizations in a single function definition, the GNU-style or C++11
non-standard attribute `optnone` can be used.

```c++
// The following functions will not be optimized.
// GNU-style attribute
__attribute__((optnone)) int foo() {
  // ... code
}
// C++11 attribute
[[clang::optnone]] int bar() {
  // ... code
}
```

To facilitate disabling optimization for a range of function definitions, a
range-based pragma is provided. Its syntax is `#pragma clang optimize`
followed by `off` or `on`.

All function definitions in the region between an `off` and the following
`on` will be decorated with the `optnone` attribute unless doing so would
conflict with explicit attributes already present on the function (e.g., the
ones that control inlining).

```c++
#pragma clang optimize off
// This function will be decorated with optnone.
int foo() {
  // ... code
}

// optnone conflicts with always_inline, so bar() will not be decorated.
__attribute__((always_inline)) int bar() {
  // ... code
}
#pragma clang optimize on
```

If no `on` is found to close an `off` region, the end of the region is the
end of the compilation unit.

Note that a stray `#pragma clang optimize on` does not selectively enable
additional optimizations when compiling at low optimization levels. This feature
can only be used to selectively disable optimizations.

The pragma has an effect on functions only at the point of their definition; for
function templates, this means that the state of the pragma at the point of an
instantiation is not necessarily relevant. Consider the following example:

```c++
template<typename T> T twice(T t) {
  return 2 * t;
}

#pragma clang optimize off
template<typename T> T thrice(T t) {
  return 3 * t;
}

int container(int a, int b) {
  return twice(a) + thrice(b);
}
#pragma clang optimize on
```

In this example, the definition of the template function `twice` is outside
the pragma region, whereas the definition of `thrice` is inside the region.
The `container` function is also in the region and will not be optimized, but
it causes the instantiation of `twice` and `thrice` with an `int` type; of
these two instantiations, `twice` will be optimized (because its definition
was outside the region) and `thrice` will not be optimized.

Clang also implements MSVC's range-based pragma,
`#pragma optimize("[optimization-list]", on | off)`. At the moment, Clang only
supports an empty optimization list, whereas MSVC supports the arguments, `s`,
`g`, `t`, and `y`. Currently, the implementation of `pragma optimize` behaves
the same as `#pragma clang optimize`. All functions
between `off` and `on` will be decorated with the `optnone` attribute.

```c++
#pragma optimize("", off)
// This function will be decorated with optnone.
void f1() {}

#pragma optimize("", on)
// This function will be optimized with whatever was specified on
// the commandline.
void f2() {}

// This will warn with Clang's current implementation.
#pragma optimize("g", on)
void f3() {}
```

For MSVC, an empty optimization list and `off` parameter will turn off
all optimizations, `s`, `g`, `t`, and `y`. An empty optimization and
`on` parameter will reset the optimizations to the ones specified on the
commandline.

```{list-table} Parameters (unsupported by Clang)
:header-rows: 1

* - Parameter
  - Type of optimization
* - g
  - Deprecated
* - s or t
  - Short or fast sequences of machine code
* - y
  - Enable frame pointers
```

(langext-loop-hint-optimizations)=

## Extensions for loop hint optimizations

The `#pragma clang loop` directive is used to specify hints for optimizing the
subsequent for, while, do-while, or c++11 range-based for loop. The directive
provides options for vectorization, interleaving, predication, unrolling and
distribution. Loop hints can be specified before any loop and will be ignored if
the optimization is not safe to apply.

There are loop hints that control transformations (e.g., vectorization, loop
unrolling) and there are loop hints that set transformation options (e.g.
`vectorize_width`, `unroll_count`). Pragmas setting transformation options
imply the transformation is enabled, as if it were enabled via the corresponding
transformation pragma (e.g., `vectorize(enable)`). If the transformation is
disabled (e.g., `vectorize(disable)`), that takes precedence over
transformations option pragmas implying that transformation.

### Vectorization, Interleaving, and Predication

A vectorized loop performs multiple iterations of the original loop
in parallel using vector instructions. The instruction set of the target
processor determines which vector instructions are available and their vector
widths. This restricts the types of loops that can be vectorized. The vectorizer
automatically determines if the loop is safe and profitable to vectorize. A
vector instruction cost model is used to select the vector width.

Interleaving multiple loop iterations allows modern processors to further
improve instruction-level parallelism (ILP) using advanced hardware features,
such as multiple execution units and out-of-order execution. The vectorizer uses
a cost model that depends on the register pressure and generated code size to
select the interleaving count.

Vectorization is enabled by `vectorize(enable)` and interleaving is enabled
by `interleave(enable)`. This is useful when compiling with `-Os` to
manually enable vectorization or interleaving.

```c++
#pragma clang loop vectorize(enable)
#pragma clang loop interleave(enable)
for(...) {
  ...
}
```

The vector width is specified by
`vectorize_width(_value_[, fixed|scalable])`, where \_value\_ is a positive
integer and the type of vectorization can be specified with an optional
second parameter. The default for the second parameter is 'fixed' and
refers to fixed width vectorization, whereas 'scalable' indicates the
compiler should use scalable vectors instead. Another use of vectorize_width
is `vectorize_width(fixed|scalable)` where the user can hint at the type
of vectorization to use without specifying the exact width. In both variants
of the pragma the vectorizer may decide to fall back on fixed width
vectorization if the target does not support scalable vectors.

The interleave count is specified by `interleave_count(_value_)`, where
\_value\_ is a positive integer. This is useful for specifying the optimal
width/count of the set of target architectures supported by your application.

```c++
#pragma clang loop vectorize_width(2)
#pragma clang loop interleave_count(2)
for(...) {
  ...
}
```

Specifying a width/count of 1 disables the optimization, and is equivalent to
`vectorize(disable)` or `interleave(disable)`.

Vector predication is enabled by `vectorize_predicate(enable)`, for example:

```c++
#pragma clang loop vectorize(enable)
#pragma clang loop vectorize_predicate(enable)
for(...) {
  ...
}
```

This predicates (masks) all instructions in the loop, which allows the scalar
remainder loop (the tail) to be folded into the main vectorized loop. This
might be more efficient when vector predication is efficiently supported by the
target platform.

### Loop Unrolling

Unrolling a loop reduces the loop control overhead and exposes more
opportunities for ILP. Loops can be fully or partially unrolled. Full unrolling
eliminates the loop and replaces it with an enumerated sequence of loop
iterations. Full unrolling is only possible if the loop trip count is known at
compile time. Partial unrolling replicates the loop body within the loop and
reduces the trip count.

If `unroll(enable)` is specified the unroller will attempt to fully unroll the
loop if the trip count is known at compile time. If the fully unrolled code size
is greater than an internal limit the loop will be partially unrolled up to this
limit. If the trip count is not known at compile time the loop will be partially
unrolled with a heuristically chosen unroll factor.

```c++
#pragma clang loop unroll(enable)
for(...) {
  ...
}
```

If `unroll(full)` is specified the unroller will attempt to fully unroll the
loop if the trip count is known at compile time identically to
`unroll(enable)`. However, with `unroll(full)` the loop will not be unrolled
if the loop count is not known at compile time.

```c++
#pragma clang loop unroll(full)
for(...) {
  ...
}
```

The unroll count can be specified explicitly with `unroll_count(_value_)` where
\_value\_ is a positive integer. If this value is greater than the trip count the
loop will be fully unrolled. Otherwise the loop is partially unrolled subject
to the same code size limit as with `unroll(enable)`.

```c++
#pragma clang loop unroll_count(8)
for(...) {
  ...
}
```

Unrolling of a loop can be prevented by specifying `unroll(disable)`.

Loop unroll parameters can be controlled by options
`-mllvm -unroll-count=n` and `-mllvm -pragma-unroll-threshold=n`.

### Loop Distribution

Loop Distribution allows splitting a loop into multiple loops. This is
beneficial for example when the entire loop cannot be vectorized but some of the
resulting loops can.

If `distribute(enable))` is specified and the loop has memory dependencies
that inhibit vectorization, the compiler will attempt to isolate the offending
operations into a new loop. This optimization is not enabled by default, only
loops marked with the pragma are considered.

```c++
#pragma clang loop distribute(enable)
for (i = 0; i < N; ++i) {
  S1: A[i + 1] = A[i] + B[i];
  S2: C[i] = D[i] * E[i];
}
```

This loop will be split into two loops between statements S1 and S2. The
second loop containing S2 will be vectorized.

Loop Distribution is currently not enabled by default in the optimizer because
it can hurt performance in some cases. For example, instruction-level
parallelism could be reduced by sequentializing the execution of the
statements S1 and S2 above.

If Loop Distribution is turned on globally with
`-mllvm -enable-loop-distribution`, specifying `distribute(disable)` can
be used the disable it on a per-loop basis.

### Disable Loop Invariant Code Motion

Loop Invariant Code Motion (LICM) moves loop invariant code outside of the loop.
If `licm(disable))` is specified, compiler will skip LICM on the specific loop.

```c++
#pragma clang loop licm(disable)
while (i < Length) {
  List[i] = A[x] * i * 2;
  i++;
}
```

The load for A[x] is loop invariant, it will not be hoisted out of the loop
when LICM is disabled.

### Additional Information

For convenience multiple loop hints can be specified on a single line.

```c++
#pragma clang loop vectorize_width(4) interleave_count(8)
for(...) {
  ...
}
```

If an optimization cannot be applied any hints that apply to it will be ignored.
For example, the hint `vectorize_width(4)` is ignored if the loop is not
proven safe to vectorize. To identify and diagnose optimization issues use
`-Rpass`, `-Rpass-missed`, and `-Rpass-analysis` command line options. See the
user guide for details.

## Extensions to specify floating-point flags

The `#pragma clang fp` pragma allows floating-point options to be specified
for a section of the source code. This pragma can only appear at file scope or
at the start of a compound statement (excluding comments). When using within a
compound statement, the pragma is active within the scope of the compound
statement.

Currently, the following settings can be controlled with this pragma:

`#pragma clang fp reassociate` allows control over the reassociation
of floating point expressions. When enabled, this pragma allows the expression
`x + (y + z)` to be reassociated as `(x + y) + z`.
Reassociation can also occur across multiple statements.
This pragma can be used to disable reassociation when it is otherwise
enabled for the translation unit with the `-fassociative-math` flag.
The pragma can take two values: `on` and `off`.

```c++
float f(float x, float y, float z)
{
  // Enable floating point reassociation across statements
  #pragma clang fp reassociate(on)
  float t = x + y;
  float v = t + z;
}
```

`#pragma clang fp reciprocal` allows control over using reciprocal
approximations in floating point expressions. When enabled, this
pragma allows the expression `x / y` to be approximated as `x *
(1.0 / y)`. This pragma can be used to disable reciprocal
approximation when it is otherwise enabled for the translation unit
with the `-freciprocal-math` flag or other fast-math options. The
pragma can take two values: `on` and `off`.

```c++
float f(float x, float y)
{
  // Enable floating point reciprocal approximation
  #pragma clang fp reciprocal(on)
  return x / y;
}
```

`#pragma clang fp contract` specifies whether the compiler should
contract a multiply and an addition (or subtraction) into a fused FMA
operation when supported by the target.

The pragma can take three values: `on`, `fast` and `off`. The `on`
option is identical to using `#pragma STDC FP_CONTRACT(ON)` and it allows
fusion as specified the language standard. The `fast` option allows fusion
in cases when the language standard does not make this possible (e.g., across
statements in C).

```c++
for(...) {
  #pragma clang fp contract(fast)
  a = b[i] * c[i];
  d[i] += a;
}
```

The pragma can also be used with `off` which turns FP contraction off for a
section of the code. This can be useful when fast contraction is otherwise
enabled for the translation unit with the `-ffp-contract=fast-honor-pragmas` flag.
Note that `-ffp-contract=fast` will override pragmas to fuse multiply and
addition across statements regardless of any controlling pragmas.

`#pragma clang fp exceptions` specifies floating point exception behavior. It
may take one of the values: `ignore`, `maytrap` or `strict`. Meaning of
these values is same as for [constrained floating point intrinsics](http://llvm.org/docs/LangRef.html#constrained-floating-point-intrinsics).

```c++
{
  // Preserve floating point exceptions
  #pragma clang fp exceptions(strict)
  z = x + y;
  if (fetestexcept(FE_OVERFLOW))
    ...
}
```

A `#pragma clang fp` pragma may contain any number of options:

```c++
void func(float *dest, float a, float b) {
  #pragma clang fp exceptions(maytrap) contract(fast) reassociate(on)
  ...
}
```

`#pragma clang fp eval_method` allows floating-point behavior to be specified
for a section of the source code. This pragma can appear at file or namespace
scope, or at the start of a compound statement (excluding comments).
The pragma is active within the scope of the compound statement.

When `pragma clang fp eval_method(source)` is enabled, the section of code
governed by the pragma behaves as though the command-line option
`-ffp-eval-method=source` is enabled. Rounds intermediate results to
source-defined precision.

When `pragma clang fp eval_method(double)` is enabled, the section of code
governed by the pragma behaves as though the command-line option
`-ffp-eval-method=double` is enabled. Rounds intermediate results to
`double` precision.

When `pragma clang fp eval_method(extended)` is enabled, the section of code
governed by the pragma behaves as though the command-line option
`-ffp-eval-method=extended` is enabled. Rounds intermediate results to
target-dependent `long double` precision. In Win32 programming, for instance,
the long double data type maps to the double, 64-bit precision data type.

The full syntax this pragma supports is
`#pragma clang fp eval_method(source|double|extended)`.

```c++
for(...) {
  // The compiler will use long double as the floating-point evaluation
  // method.
  #pragma clang fp eval_method(extended)
  a = b[i] * c[i] + e;
}
```

Note: `math.h` defines the typedefs `float_t` and `double_t` based on the active
evaluation method at the point where the header is included, not where the
typedefs are used. Because of this, it is unwise to combine these typedefs with
`#pragma clang fp eval_method`. To catch obvious bugs, Clang will emit an
error for any references to these typedefs within the scope of this pragma;
however, this is not a fool-proof protection, and programmers must take care.

The `#pragma float_control` pragma allows precise floating-point
semantics and floating-point exception behavior to be specified
for a section of the source code. This pragma can only appear at file or
namespace scope, within a language linkage specification or at the start of a
compound statement (excluding comments). When used within a compound statement,
the pragma is active within the scope of the compound statement. This pragma
is modeled after a Microsoft pragma with the same spelling and syntax. For
pragmas specified at file or namespace scope, or within a language linkage
specification, a stack is supported so that the `pragma float_control`
settings can be pushed or popped.

When `pragma float_control(precise, on)` is enabled, the section of code
governed by the pragma uses precise floating point semantics, effectively
`-ffast-math` is disabled and `-ffp-contract=on`
(fused multiply add) is enabled. This pragma enables `-fmath-errno`.

When `pragma float_control(precise, off)` is enabled, unsafe-floating point
optimizations are enabled in the section of code governed by the pragma.
Effectively `-ffast-math` is enabled and `-ffp-contract=fast`. This pragma
disables `-fmath-errno`.

When `pragma float_control(except, on)` is enabled, the section of code
governed by the pragma behaves as though the command-line option
`-ffp-exception-behavior=strict` is enabled,
when `pragma float_control(except, off)` is enabled, the section of code
governed by the pragma behaves as though the command-line option
`-ffp-exception-behavior=ignore` is enabled.

The full syntax this pragma supports is
`float_control(except|precise, on|off [, push])` and
`float_control(push|pop)`.
The `push` and `pop` forms, including using `push` as the optional
third argument, can only occur at file scope.

```c++
for(...) {
  // This block will be compiled with -fno-fast-math and -ffp-contract=on
  #pragma float_control(precise, on)
  a = b[i] * c[i] + e;
}
```

(langext-atomic-code-generation)=

## Extensions for controlling atomic code generation

The `[[clang::atomic]]` statement attribute enables users to control how
atomic operations are lowered in LLVM IR by conveying additional metadata to
the backend. The primary goal is to allow users to specify certain options,
like whether the affected atomic operations might be used with specific types of memory or
whether to ignore denormal mode correctness in floating-point operations,
without affecting the correctness of code that does not rely on these properties.

In LLVM, lowering of atomic operations (e.g., `atomicrmw`) can differ based
on the target's capabilities. Some backends support native atomic instructions
only for certain operation types or alignments, or only in specific memory
regions. Likewise, floating-point atomic instructions may or may not respect
IEEE denormal requirements. When the user is unconcerned about denormal-mode
compliance (for performance reasons) or knows that certain atomic operations
will not be performed on a particular type of memory, extra hints are needed to
tell the backend how to proceed.

A classic example is an architecture where floating-point atomic add does not
fully conform to IEEE denormal-mode handling. If the user does not mind ignoring
that aspect, they would prefer to emit a faster hardware atomic instruction,
rather than a fallback or CAS loop. Conversely, on certain GPUs (e.g., AMDGPU),
memory accessed via PCIe may only support a subset of atomic operations. To ensure
correct and efficient lowering, the compiler must know whether the user needs
the atomic operations to work with that type of memory.

The allowed atomic attribute values are now `remote_memory`, `fine_grained_memory`,
and `ignore_denormal_mode`, each optionally prefixed with `no_`. The meanings
are as follows:

- `remote_memory` means atomic operations may be performed on remote
  memory, i.e., memory accessed through off-chip interconnects (e.g., PCIe).
  On ROCm platforms using HIP, remote memory refers to memory accessed via
  PCIe and is subject to specific atomic operation support. See
  [ROCm PCIe Atomics](https://rocm.docs.amd.com/en/latest/conceptual/pcie-atomics.html) for further details. Prefixing with `no_remote_memory` indicates that
  atomic operations should not be performed on remote memory.
- `fine_grained_memory` means atomic operations may be performed on fine-grained
  memory, i.e., memory regions that support fine-grained coherence, where updates to
  memory are visible to other parts of the system even while modifications are ongoing.
  For example, in HIP, fine-grained coherence ensures that host and device share
  up-to-date data without explicit synchronization (see
  [HIP Definition](https://rocm.docs.amd.com/projects/HIP/en/docs-6.3.3/how-to/hip_runtime_api/memory_management/coherence_control.html#coherence-control)).
  Similarly, OpenCL 2.0 provides fine-grained synchronization in shared virtual memory
  allocations, allowing concurrent modifications by host and device (see
  [OpenCL 2.0 Overview](https://www.intel.com/content/www/us/en/developer/articles/technical/opencl-20-shared-virtual-memory-overview.html)).
  Prefixing with `no_fine_grained_memory` indicates that atomic operations should not
  be performed on fine-grained memory.
- `ignore_denormal_mode` means that atomic operations are allowed to ignore
  correctness for denormal mode in floating-point operations, potentially improving
  performance on architectures that handle denormals inefficiently. The negated form,
  if specified as `no_ignore_denormal_mode`, would enforce strict denormal mode
  correctness.

Any unspecified option is inherited from the global defaults, which can be set
by a compiler flag or the target's built-in defaults.

Within the same atomic attribute, duplicate and conflicting values are accepted,
and the last of any conflicting values wins. Multiple atomic attributes are
allowed for the same compound statement, and the last atomic attribute wins.

Without any atomic metadata, LLVM IR defaults to conservative settings for
correctness: atomic operations enforce denormal mode correctness and are assumed
to potentially use remote and fine-grained memory (i.e., the equivalent of
`remote_memory`, `fine_grained_memory`, and `no_ignore_denormal_mode`).

The attribute may be applied only to a compound statement and looks like:

```c++
[[clang::atomic(remote_memory, fine_grained_memory, ignore_denormal_mode)]]
{
    // Atomic instructions in this block carry extra metadata reflecting
    // these user-specified options.
}
```

A new compiler option now globally sets the defaults for these atomic-lowering
options. The command-line format has changed to:

```console
$ clang -fatomic-remote-memory -fno-atomic-fine-grained-memory -fatomic-ignore-denormal-mode file.cpp
```

Each option has a corresponding flag:
`-fatomic-remote-memory` / `-fno-atomic-remote-memory`,
`-fatomic-fine-grained-memory` / `-fno-atomic-fine-grained-memory`,
and `-fatomic-ignore-denormal-mode` / `-fno-atomic-ignore-denormal-mode`.

Code using the `[[clang::atomic]]` attribute can then selectively override
the command-line defaults on a per-block basis. For instance:

```c++
// Suppose the global defaults assume:
//   remote_memory, fine_grained_memory, and no_ignore_denormal_mode
// (for conservative correctness)

void example() {
    // Locally override the settings: disable remote_memory and enable
    // fine_grained_memory.
    [[clang::atomic(no_remote_memory, fine_grained_memory)]]
    {
        // In this block:
        //   - Atomic operations are not performed on remote memory.
        //   - Atomic operations are performed on fine-grained memory.
        //   - The setting for denormal mode remains as the global default
        //     (typically no_ignore_denormal_mode, enforcing strict denormal mode correctness).
        // ...
    }
}
```

Function bodies do not accept statement attributes, so this will not work:

```c++
void func() [[clang::atomic(remote_memory)]] {  // Wrong: applies to function type
}
```

Use the attribute on a compound statement within the function:

```c++
void func() {
    [[clang::atomic(remote_memory)]]
    {
        // Atomic operations in this block carry the specified metadata.
    }
}
```

The `[[clang::atomic]]` attribute affects only the code generation of atomic
instructions within the annotated compound statement. Clang attaches target-specific
metadata to those atomic instructions in the emitted LLVM IR to guide backend lowering.
This metadata is fixed at the Clang code generation phase and is not modified by later
LLVM passes (such as function inlining).

For example, consider:

```cpp
inline void func() {
  [[clang::atomic(remote_memory)]]
  {
    // Atomic instructions lowered with metadata.
  }
}

void foo() {
  [[clang::atomic(no_remote_memory)]]
  {
    func(); // Inlined by LLVM, but the metadata from 'func()' remains unchanged.
  }
}
```

Although current usage focuses on AMDGPU, the mechanism is general. Other
backends can ignore or implement their own responses to these flags if desired.
If a target does not understand or enforce these hints, the IR remains valid,
and the resulting program is still correct (although potentially less optimized
for that user's needs).

## Specifying an attribute for multiple declarations (#pragma clang attribute)

The `#pragma clang attribute` directive can be used to apply an attribute to
multiple declarations. The `#pragma clang attribute push` variation of the
directive pushes a new "scope" of `#pragma clang attribute` that attributes
can be added to. The `#pragma clang attribute (...)` variation adds an
attribute to that scope, and the `#pragma clang attribute pop` variation pops
the scope. You can also use `#pragma clang attribute push (...)`, which is a
shorthand for when you want to add one attribute to a new scope. Multiple push
directives can be nested inside each other.

The attributes that are used in the `#pragma clang attribute` directives
can be written using the GNU-style syntax:

```c++
#pragma clang attribute push (__attribute__((annotate("custom"))), apply_to = function)

void function(); // The function now has the annotate("custom") attribute

#pragma clang attribute pop
```

The attributes can also be written using the C++11 style syntax:

```c++
#pragma clang attribute push ([[noreturn]], apply_to = function)

void function(); // The function now has the [[noreturn]] attribute

#pragma clang attribute pop
```

The `__declspec` style syntax is also supported:

```c++
#pragma clang attribute push (__declspec(dllexport), apply_to = function)

void function(); // The function now has the __declspec(dllexport) attribute

#pragma clang attribute pop
```

A single push directive can contain multiple attributes, however,
only one syntax style can be used within a single directive:

```c++
#pragma clang attribute push ([[noreturn, noinline]], apply_to = function)

void function1(); // The function now has the [[noreturn]] and [[noinline]] attributes

#pragma clang attribute pop

#pragma clang attribute push (__attribute((noreturn, noinline)), apply_to = function)

void function2(); // The function now has the __attribute((noreturn)) and __attribute((noinline)) attributes

#pragma clang attribute pop
```

Because multiple push directives can be nested, if you're writing a macro that
expands to `_Pragma("clang attribute")` it's good hygiene (though not
required) to add a namespace to your push/pop directives. A pop directive with a
namespace will pop the innermost push that has that same namespace. This will
ensure that another macro's `pop` won't inadvertently pop your attribute. Note
that an `pop` without a namespace will pop the innermost `push` without a
namespace. `push`es with a namespace can only be popped by `pop` with the
same namespace. For instance:

```c++
#define ASSUME_NORETURN_BEGIN _Pragma("clang attribute AssumeNoreturn.push ([[noreturn]], apply_to = function)")
#define ASSUME_NORETURN_END   _Pragma("clang attribute AssumeNoreturn.pop")

#define ASSUME_UNAVAILABLE_BEGIN _Pragma("clang attribute Unavailable.push (__attribute__((unavailable)), apply_to=function)")
#define ASSUME_UNAVAILABLE_END   _Pragma("clang attribute Unavailable.pop")


ASSUME_NORETURN_BEGIN
ASSUME_UNAVAILABLE_BEGIN
void function(); // function has [[noreturn]] and __attribute__((unavailable))
ASSUME_NORETURN_END
void other_function(); // function has __attribute__((unavailable))
ASSUME_UNAVAILABLE_END
```

Without the namespaces on the macros, `other_function` will be annotated with
`[[noreturn]]` instead of `__attribute__((unavailable))`. This may seem like
a contrived example, but its very possible for this kind of situation to appear
in real code if the pragmas are spread out across a large file. You can test if
your version of clang supports namespaces on `#pragma clang attribute` with
`__has_extension(pragma_clang_attribute_namespaces)`.

### Subject Match Rules

The set of declarations that receive a single attribute from the attribute stack
depends on the subject match rules that were specified in the pragma. Subject
match rules are specified after the attribute. The compiler expects an
identifier that corresponds to the subject set specifier. The `apply_to`
specifier is currently the only supported subject set specifier. It allows you
to specify match rules that form a subset of the attribute's allowed subject
set, i.e., the compiler doesn't require all of the attribute's subjects. For
example, an attribute like `[[nodiscard]]` whose subject set includes
`enum`, `record` and `hasType(functionType)`, requires the presence of at
least one of these rules after `apply_to`:

```c++
#pragma clang attribute push([[nodiscard]], apply_to = enum)

enum Enum1 { A1, B1 }; // The enum will receive [[nodiscard]]

struct Record1 { }; // The struct will *not* receive [[nodiscard]]

#pragma clang attribute pop

#pragma clang attribute push([[nodiscard]], apply_to = any(record, enum))

enum Enum2 { A2, B2 }; // The enum will receive [[nodiscard]]

struct Record2 { }; // The struct *will* receive [[nodiscard]]

#pragma clang attribute pop

// This is an error, since [[nodiscard]] can't be applied to namespaces:
#pragma clang attribute push([[nodiscard]], apply_to = any(record, namespace))

#pragma clang attribute pop
```

Multiple match rules can be specified using the `any` match rule, as shown
in the example above. The `any` rule applies attributes to all declarations
that are matched by at least one of the rules in the `any`. It doesn't nest
and can't be used inside the other match rules. Redundant match rules or rules
that conflict with one another should not be used inside of `any`. Failing to
specify a rule within the `any` rule results in an error.

Clang supports the following match rules:

- `function`: Can be used to apply attributes to functions. This includes C++
  member functions, static functions, operators, and constructors/destructors.
- `function(is_member)`: Can be used to apply attributes to C++ member
  functions. This includes members like static functions, operators, and
  constructors/destructors.
- `hasType(functionType)`: Can be used to apply attributes to functions, C++
  member functions, and variables/fields whose type is a function pointer. It
  does not apply attributes to Objective-C methods or blocks.
- `type_alias`: Can be used to apply attributes to `typedef` declarations
  and C++11 type aliases.
- `record`: Can be used to apply attributes to `struct`, `class`, and
  `union` declarations.
- `record(unless(is_union))`: Can be used to apply attributes only to
  `struct` and `class` declarations.
- `enum`: Can be used to apply attributes to enumeration declarations.
- `enum_constant`: Can be used to apply attributes to enumerators.
- `variable`: Can be used to apply attributes to variables, including
  local variables, parameters, global variables, and static member variables.
  It does not apply attributes to instance member variables or Objective-C
  ivars.
- `variable(is_thread_local)`: Can be used to apply attributes to thread-local
  variables only.
- `variable(is_global)`: Can be used to apply attributes to global variables
  only.
- `variable(is_local)`: Can be used to apply attributes to local variables
  only.
- `variable(is_parameter)`: Can be used to apply attributes to parameters
  only.
- `variable(unless(is_parameter))`: Can be used to apply attributes to all
  the variables that are not parameters.
- `field`: Can be used to apply attributes to non-static member variables
  in a record. This includes Objective-C ivars.
- `namespace`: Can be used to apply attributes to `namespace` declarations.
- `objc_interface`: Can be used to apply attributes to `@interface`
  declarations.
- `objc_protocol`: Can be used to apply attributes to `@protocol`
  declarations.
- `objc_category`: Can be used to apply attributes to category declarations,
  including class extensions.
- `objc_method`: Can be used to apply attributes to Objective-C methods,
  including instance and class methods. Implicit methods like implicit property
  getters and setters do not receive the attribute.
- `objc_method(is_instance)`: Can be used to apply attributes to Objective-C
  instance methods.
- `objc_property`: Can be used to apply attributes to `@property`
  declarations.
- `block`: Can be used to apply attributes to block declarations. This does
  not include variables/fields of block pointer type.

The use of `unless` in match rules is currently restricted to a strict set of
sub-rules that are used by the supported attributes. That means that even though
`variable(unless(is_parameter))` is a valid match rule,
`variable(unless(is_thread_local))` is not.

### Supported Attributes

Not all attributes can be used with the `#pragma clang attribute` directive.
Notably, statement attributes like `[[fallthrough]]` or type attributes
like `address_space` aren't supported by this directive. You can determine
whether or not an attribute is supported by the pragma by referring to the
{doc}`individual documentation for that attribute <AttributeReference>`.

The attributes are applied to all matching declarations individually, even when
the attribute is semantically incorrect. The attributes that aren't applied to
any declaration are not verified semantically.

## Specifying section names for global objects (#pragma clang section)

The `#pragma clang section` directive provides a means to assign section-names
to global variables, functions and static variables.

The section names can be specified as:

```c++
#pragma clang section bss="myBSS" data="myData" rodata="myRodata" relro="myRelro" text="myText"
```

The section names can be reverted back to default name by supplying an empty
string to the section kind, for example:

```c++
#pragma clang section bss="" data="" text="" rodata="" relro=""
```

The `#pragma clang section` directive obeys the following rules:

- The pragma applies to all global variable, statics and function declarations
  from the pragma to the end of the translation unit.
- The pragma clang section is enabled automatically, without need of any flags.
- This feature is only defined to work sensibly for ELF, Mach-O and COFF targets.
- If section name is specified through \_attribute\_((section("myname"))), then
  the attribute name gains precedence.
- Global variables that are initialized to zero will be placed in the named
  bss section, if one is present.
- The `#pragma clang section` directive does not try to infer section-kind
  from the name. For example, naming a section "`.bss.mySec`" does NOT mean
  it will be a bss section name.
- The decision about which section-kind applies to each global is taken in the back-end.
  Once the section-kind is known, appropriate section name, as specified by the user using
  `#pragma clang section` directive, is applied to that global.

## Specifying Linker Options on ELF Targets

The `#pragma comment(lib, ...)` directive is supported on all ELF targets.
The second parameter is the library name (without the traditional Unix prefix of
`lib`). This allows you to provide an implicit link of dependent libraries.

## Embedding Copyright Information on AIX

Clang supports the `#pragma comment(copyright, "string")` directive for AIX
targets. This directive embeds a copyright or identifying string into the
compiled object file. The string is included in the final executable or shared
library and loaded into memory at program runtime. The directive is ignored on
non-AIX targets.

```c
#pragma comment(copyright, "string-literal")
```

The second argument is an ordinary string literal. Concatenated ordinary string
literals are also accepted. The directive is intended to appear at file scope;
Clang treats it as being at file scope when it appears within other scopes.

### Interaction with C++20 Modules

When `#pragma comment(copyright, ...)` appears in a C++20 module interface
unit, the copyright string is embedded only in the object file compiled from
that interface unit. Importing TUs do not re-emit the string.

(langext-evaluating-object-size)=

## Evaluating Object Size

Clang supports the builtins `__builtin_object_size` and
`__builtin_dynamic_object_size`. The semantics are compatible with GCC's
builtins of the same names, but the details are slightly different.

```c
size_t __builtin_[dynamic_]object_size(const void *ptr, int type)
```

Returns the number of accessible bytes `n` past `ptr`. The value returned
depends on `type`, which is required to be an integer constant between 0 and
3:

- If `type & 2 == 0`, the least `n` is returned such that accesses to
  `(const char*)ptr + n` and beyond are known to be out of bounds. This is
  `(size_t)-1` if no better bound is known.
- If `type & 2 == 2`, the greatest `n` is returned such that accesses to
  `(const char*)ptr + i` are known to be in bounds, for 0 \<= `i` < `n`.
  This is `(size_t)0` if no better bound is known.

```c
char small[10], large[100];
bool cond;
// Returns 100: writes of more than 100 bytes are known to be out of bounds.
int n100 = __builtin_object_size(cond ? small : large, 0);
// Returns 10: writes of 10 or fewer bytes are known to be in bounds.
int n10 = __builtin_object_size(cond ? small : large, 2);
```

- If `type & 1 == 0`, pointers are considered to be in bounds if they point
  into the same storage as `ptr` -- that is, the same stack object, global
  variable, or heap allocation.
- If `type & 1 == 1`, pointers are considered to be in bounds if they point
  to the same subobject that `ptr` points to. If `ptr` points to an array
  element, other elements of the same array, but not of enclosing arrays, are
  considered in bounds.

```c
struct X { char a, b, c; } x;
static_assert(__builtin_object_size(&x, 0) == 3);
static_assert(__builtin_object_size(&x.b, 0) == 2);
static_assert(__builtin_object_size(&x.b, 1) == 1);
```

```c
char a[10][10][10];
static_assert(__builtin_object_size(&a, 1) == 1000);
static_assert(__builtin_object_size(&a[1], 1) == 900);
static_assert(__builtin_object_size(&a[1][1], 1) == 90);
static_assert(__builtin_object_size(&a[1][1][1], 1) == 9);
```

The values returned by this builtin are a best effort conservative approximation
of the correct answers. When `type & 2 == 0`, the true value is less than or
equal to the value returned by the builtin, and when `type & 2 == 1`, the true
value is greater than or equal to the value returned by the builtin.

For `__builtin_object_size`, the value is determined entirely at compile time.
With optimization enabled, better results will be produced, especially when the
call to `__builtin_object_size` is in a different function from the formation
of the pointer. Unlike in GCC, enabling optimization in Clang does not allow
more information about subobjects to be determined, so the `type & 1 == 1`
case will often give imprecise results when used across a function call boundary
even when optimization is enabled.

[The pass_object_size and pass_dynamic_object_size attributes](AttributeReference.md#pass-object-size-pass-dynamic-object-size)
can be used to invisibly pass the object size for a pointer parameter alongside
the pointer in a function call. This allows more precise object sizes to be
determined both when building without optimizations and in the `type & 1 == 1`
case.

For `__builtin_dynamic_object_size`, the result is not limited to being a
compile time constant. Instead, a small amount of runtime evaluation is
permitted to determine the size of the object, in order to give a more precise
result. `__builtin_dynamic_object_size` is meant to be used as a drop-in
replacement for `__builtin_object_size` in libraries that support it. For
instance, here is a program that `__builtin_dynamic_object_size` will make
safer:

```c
void copy_into_buffer(size_t size) {
  char* buffer = malloc(size);
  strlcpy(buffer, "some string", strlen("some string"));
  // Previous line preprocesses to:
  // __builtin___strlcpy_chk(buffer, "some string", strlen("some string"), __builtin_object_size(buffer, 0))
}
```

Since the size of `buffer` can't be known at compile time, Clang will fold
`__builtin_object_size(buffer, 0)` into `-1`. However, if this was written
as `__builtin_dynamic_object_size(buffer, 0)`, Clang will fold it into
`size`, providing some extra runtime safety.

## Deprecating Macros

Clang supports the pragma `#pragma clang deprecated`, which can be used to
provide deprecation warnings for macro uses. For example:

```c
#define MIN(x, y) x < y ? x : y
#pragma clang deprecated(MIN, "use std::min instead")

int min(int a, int b) {
  return MIN(a, b); // warning: MIN is deprecated: use std::min instead
}
```

`#pragma clang deprecated` should be preferred for this purpose over
`#pragma GCC warning` because the warning can be controlled with
`-Wdeprecated`.

## Restricted Expansion Macros

Clang supports the pragma `#pragma clang restrict_expansion`, which can be
used restrict macro expansion in headers. This can be valuable when providing
headers with ABI stability requirements. Any expansion of the annotated macro
processed by the preprocessor after the `#pragma` annotation will log a
warning. Redefining the macro or undefining the macro will not be diagnosed, nor
will expansion of the macro within the main source file. For example:

```c
#define TARGET_ARM 1
#pragma clang restrict_expansion(TARGET_ARM, "<reason>")

/// Foo.h
struct Foo {
#if TARGET_ARM // warning: TARGET_ARM is marked unsafe in headers: <reason>
  uint32_t X;
#else
  uint64_t X;
#endif
};

/// main.c
#include "foo.h"
#if TARGET_ARM // No warning in main source file
X_TYPE uint32_t
#else
X_TYPE uint64_t
#endif
```

This warning is controlled by `-Wpedantic-macros`.

## Final Macros

Clang supports the pragma `#pragma clang final`, which can be used to
mark macros as final, meaning they cannot be undef'd or re-defined. For example:

```c
#define FINAL_MACRO 1
#pragma clang final(FINAL_MACRO)

#define FINAL_MACRO // warning: FINAL_MACRO is marked final and should not be redefined
#undef FINAL_MACRO  // warning: FINAL_MACRO is marked final and should not be undefined
```

This is useful for enforcing system-provided macros that should not be altered
in user headers or code. This is controlled by `-Wpedantic-macros`. Final
macros will always warn on redefinition, including situations with identical
bodies and in system headers.

## Line Control

Clang supports an extension for source line control, which takes the
form of a preprocessor directive starting with an unsigned integral
constant. In addition to the standard `#line` directive, this form
allows control of an include stack and header file type, which is used
in issuing diagnostics. These lines are emitted in preprocessed
output.

```c
# <line:number> <filename:string> <header-type:numbers>
```

The filename is optional, and if unspecified indicates no change in
source filename. The header-type is an optional, whitespace-delimited,
sequence of magic numbers as follows.

- `1:` Push the current source file name onto the include stack and
  enter a new file.
- `2`: Pop the include stack and return to the specified file. If
  the filename is `""`, the name popped from the include stack is
  used. Otherwise there is no requirement that the specified filename
  matches the current source when originally pushed.
- `3`: Enter a system-header region. System headers often contain
  implementation-specific source that would normally emit a diagnostic.
- `4`: Enter an implicit `extern "C"` region. This is not required on
  modern systems where system headers are C++-aware.

At most a single `1` or `2` can be present, and values must be in
ascending order.

Examples are:

```c
# 57 // Advance (or return) to line 57 of the current source file
# 57 "frob" // Set to line 57 of "frob"
# 1 "foo.h" 1 // Enter "foo.h" at line 1
# 59 "main.c" 2 // Leave current include and return to "main.c"
# 1 "/usr/include/stdio.h" 1 3 // Enter a system header
# 60 "" 2 // return to "main.c"
# 1 "/usr/ancient/header.h" 1 4 // Enter an implicit extern "C" header
```

## Intrinsics Support within Constant Expressions

The following builtin intrinsics can be used in constant expressions:

- `__builtin_addcb`
- `__builtin_addcs`
- `__builtin_addc`
- `__builtin_addcl`
- `__builtin_addcll`
- `__builtin_bitreverse8`
- `__builtin_bitreverse16`
- `__builtin_bitreverse32`
- `__builtin_bitreverse64`
- `__builtin_bswap16`
- `__builtin_bswap32`
- `__builtin_bswap64`
- `__builtin_clrsb`
- `__builtin_clrsbl`
- `__builtin_clrsbll`
- `__builtin_clz`
- `__builtin_clzl`
- `__builtin_clzll`
- `__builtin_clzs`
- `__builtin_clzg`
- `__builtin_ctz`
- `__builtin_ctzl`
- `__builtin_ctzll`
- `__builtin_ctzs`
- `__builtin_ctzg`
- `__builtin_ffs`
- `__builtin_ffsl`
- `__builtin_ffsll`
- `__builtin_fmax`
- `__builtin_fmin`
- `__builtin_fpclassify`
- `__builtin_inf`
- `__builtin_isinf`
- `__builtin_isinf_sign`
- `__builtin_isfinite`
- `__builtin_isnan`
- `__builtin_isnormal`
- `__builtin_nan`
- `__builtin_nans`
- `__builtin_parity`
- `__builtin_parityl`
- `__builtin_parityll`
- `__builtin_popcount`
- `__builtin_popcountl`
- `__builtin_popcountll`
- `__builtin_popcountg`
- `__builtin_rotateleft8`
- `__builtin_rotateleft16`
- `__builtin_rotateleft32`
- `__builtin_rotateleft64`
- `__builtin_rotateright8`
- `__builtin_rotateright16`
- `__builtin_rotateright32`
- `__builtin_rotateright64`
- `__builtin_subcb`
- `__builtin_subcs`
- `__builtin_subc`
- `__builtin_subcl`
- `__builtin_subcll`

The following x86-specific intrinsics can be used in constant expressions:

- `_addcarry_u32`
- `_addcarry_u64`
- `_bit_scan_forward`
- `_bit_scan_reverse`
- `__bsfd`
- `__bsfq`
- `__bsrd`
- `__bsrq`
- `__bswap`
- `__bswapd`
- `__bswap64`
- `__bswapq`
- `_castf32_u32`
- `_castf64_u64`
- `_castu32_f32`
- `_castu64_f64`
- `__lzcnt16`
- `__lzcnt`
- `__lzcnt64`
- `_mm_popcnt_u32`
- `_mm_popcnt_u64`
- `_popcnt32`
- `_popcnt64`
- `__popcntd`
- `__popcntq`
- `__popcnt16`
- `__popcnt`
- `__popcnt64`
- `__rolb`
- `__rolw`
- `__rold`
- `__rolq`
- `__rorb`
- `__rorw`
- `__rord`
- `__rorq`
- `_rotl`
- `_rotr`
- `_rotwl`
- `_rotwr`
- `_lrotl`
- `_lrotr`
- `_subborrow_u32`
- `_subborrow_u64`

## Debugging the Compiler

Clang supports a number of pragma directives that help debugging the compiler itself.
Syntax is the following: `#pragma clang __debug <command> <arguments>`.
Note, all of debugging pragmas are subject to change.

### `dump`

Accepts either a single identifier or an expression. When a single identifier is passed,
the lookup results for the identifier are printed to `stderr`. When an expression is passed,
the AST for the expression is printed to `stderr`. The expression is an unevaluated operand,
so things like overload resolution and template instantiations are performed,
but the expression has no runtime effects.
Type- and value-dependent expressions are not supported yet.

This facility is designed to aid with testing name lookup machinery.

## Predefined Macros

### `__GCC_DESTRUCTIVE_SIZE` and `__GCC_CONSTRUCTIVE_SIZE`

Specify the mimum offset between two objects to avoid false sharing and the
maximum size of contiguous memory to promote true sharing, respectively. These
macros are predefined in all C and C++ language modes, but can be redefined on
the command line with `-D` to specify different values as needed or can be
undefined on the command line with `-U` to disable support for the feature.

**Note: the values the macros expand to are not guaranteed to be stable. They
are are affected by architectures and CPU tuning flags, can change between
releases of Clang and will not match the values defined by other compilers such
as GCC.**

Compiling different TUs depending on these flags (including use of
`std::hardware_constructive_interference` or
`std::hardware_destructive_interference`) with different compilers, macro
definitions, or architecture flags will lead to ODR violations and should be
avoided.

## `#embed` Parameters

### `clang::offset`

The `clang::offset` embed parameter may appear zero or one time in the
embed parameter sequence. Its preprocessor argument clause shall be present and
have the form:

```text
( constant-expression )
```

and shall be an integer constant expression. The integer constant expression
shall not evaluate to a value less than 0. The token `defined` shall not
appear within the constant expression.

The offset will be used when reading the contents of the embedded resource to
specify the starting offset to begin embedding from. The resources is treated
as being empty if the specified offset is larger than the number of bytes in
the resource. The offset will be applied *before* any `limit` parameters are
applied.

## Union and aggregate initialization in C

In C23 (N2900), when an object is initialized from initializer `= {}`, all
elements of arrays, all members of structs, and the first members of unions are
empty-initialized recursively. In addition, all padding bits are initialized to
zero.

Clang guarantees the following behaviors:

- `1:` Clang supports initializer `= {}` mentioned above in all C
  standards.
- `2:` When unions are initialized from initializer `= {}`, bytes outside
  of the first members of unions are also initialized to zero.
- `3:` When unions, structures and arrays are initialized from initializer
  `= { initializer-list }`, all members not explicitly initialized in
  the initializer list are empty-initialized recursively. In addition, all
  padding bits are initialized to zero.

Currently, the above extension only applies to C source code, not C++.

## Empty Objects in C

The declaration of a structure or union type which has no named members is
undefined behavior (C23 and earlier) or implementation-defined behavior (C2y).
Clang allows the declaration of a structure or union type with no named members
in all C language modes. `sizeof` for such a type returns `0`, which is
different behavior than in C++ (where the size of such an object is typically
`1`).

## Qualified function types in C

Declaring a function with a qualified type in C is undefined behavior (C23 and
earlier) or implementation-defined behavior (C2y). Clang allows a function type
to be specified with the `const` and `volatile` qualifiers, but ignores the
qualifications.

```c
typedef int f(void);
const volatile f func; // Qualifier on function type has no effect.
```

Note, Clang does not allow an `_Atomic` function type because
of explicit constraints against atomically qualified (arrays and) function
types.

## Underspecified Object Declarations in C

C23 introduced the notion of [underspecified object declarations](https://www.open-std.org/jtc1/sc22/wg14/www/docs/n3006.htm)
(note, the final standards text is different from WG14 N3006 due to changes
during national body comment review). When an object is declared with the
`constexpr` storage class specifier or has a deduced type (with the `auto`
specifier), it is said to be "underspecified". Underspecified declarations have
different requirements than non-underspecified declarations. In particular, the
identifier being declared cannot be used in its initialization. e.g.,

```c
auto x = x; // Invalid
constexpr int y = y; // Invalid
```

The standard leaves it implementation-defined whether an underspecified
declaration may introduce additional identifiers as part of the declaration.

Clang allows additional identifiers to be declared in the following cases:

- A compound literal may introduce a new type. e.g.,

```c
auto x = (struct S { int x, y; }){ 1, 2 };      // Accepted by Clang
constexpr int i = (struct T { int x; }){ 1 }.x; // Accepted by Clang
```

- The type specifier for a `constexpr` declaration may define a new type.
  e.g.,

```c
constexpr struct S { int x; } s = { 1 }; // Accepted by Clang
```

- A function declarator may be declared with parameters, including parameters
  which introduce a new type. e.g.,

```c
constexpr int (*fp)(int x) = nullptr;              // Accepted by Clang
auto f = (void (*)(struct S { int x; } s))nullptr; // Accepted by Clang
```

- The initializer may contain a GNU statement expression which defines new
  types or objects. e.g.,

```c
constexpr int i = ({                              // Accepted by Clang
  constexpr int x = 12;
  constexpr struct S { int x; } s = { x };
  s.x;
});
auto x = ({ struct S { int x; } s = { 0 }; s; }); // Accepted by Clang
```

Clang intentionally does not implement the changed scoping rules from C23
for underspecified declarations. Doing so would significantly complicate the
implementation in order to get reasonable diagnostic behavior and also means
Clang fails to reject some code that should be rejected. e.g.,

```c
// This should be rejected because 'x' is not in scope within the initializer
// of an underspecified declaration. Clang accepts because it treats the scope
// of the identifier as beginning immediately after the declarator, same as with
// a non-underspecified declaration.
constexpr int x = sizeof(x);

// Clang rejects this code with a diagnostic about using the variable within its
// own initializer rather than rejecting the code with an undeclared identifier
// diagnostic.
auto x = x;
```

---

### Clang Docs LeakSanitizer (`clang/docs/LeakSanitizer.md`)

# LeakSanitizer


## Introduction

LeakSanitizer is a run-time memory leak detector. It can be combined with
{doc}`AddressSanitizer` to get both memory error and leak detection, or
used in a stand-alone mode. LSan adds almost no performance overhead
until the very end of the process, at which point there is an extra leak
detection phase.

## Usage

{doc}`AddressSanitizer`: integrates LeakSanitizer and enables it by default on
supported platforms.

```console
$ cat memory-leak.c
#include <stdlib.h>
void *p;
int main() {
  p = malloc(7);
  p = 0; // The memory is leaked here.
  return 0;
}
% clang -fsanitize=address -g memory-leak.c ; ASAN_OPTIONS=detect_leaks=1 ./a.out
==23646==ERROR: LeakSanitizer: detected memory leaks
Direct leak of 7 byte(s) in 1 object(s) allocated from:
    #0 0x4af01b in __interceptor_malloc /projects/compiler-rt/lib/asan/asan_malloc_linux.cc:52:3
    #1 0x4da26a in main memory-leak.c:4:7
    #2 0x7f076fd9cec4 in __libc_start_main libc-start.c:287
SUMMARY: AddressSanitizer: 7 byte(s) leaked in 1 allocation(s).
```

To use LeakSanitizer in stand-alone mode, link your program with
`-fsanitize=leak` flag. Make sure to use `clang` (not `ld`) for the
link step, so that it would link in proper LeakSanitizer run-time library
into the final executable.

## Suppressions

LeakSanitizer reports can be suppressed if you encounter leaks in third-party
libraries or known locations that cannot be fixed immediately.

### Suppression Format

Each suppression rule is specified on its own line in the form:

```text
leak:<pattern>
```

A memory leak is suppressed if `<pattern>` matches any function name, source
file name, or library/module name in the symbolized stack trace of the leak
report. Wildcards (`*`) are supported, and lines starting with `#` are treated
as comments.

Example suppression rules:

```text
# Suppress leak by function name (supports wildcards)
leak:MyKnownLeakyFunction
leak:*LeakyNamespace::*

# Suppress leak by source file name
leak:third_party/leaky_library.cpp

# Suppress leak by shared library / module name
leak:libcrypto.so
```

### Runtime Suppressions

To specify a suppressions file at runtime, pass its path via the `suppressions`
flag in the `LSAN_OPTIONS` environment variable:

```console
$ LSAN_OPTIONS="suppressions=MyLSan.supp" ./a.out
```

(When running LeakSanitizer as part of AddressSanitizer, `LSAN_OPTIONS` is still
used to pass LeakSanitizer-specific flags and suppressions.)

### Compile-time Default Suppressions

You can embed default suppressions directly into your executable at compile/link
time by defining the `__lsan_default_suppressions` function in your source code:

```c++
#include <sanitizer/lsan_interface.h>

extern "C" const char *__lsan_default_suppressions() {
  return "leak:MyKnownLeakyFunction\n"
         "leak:third_party/leaky_library.cpp\n"
         "leak:libcrypto.so\n";
}
```

Both default suppressions and suppressions passed in the file via
`LSAN_OPTIONS="suppressions=..."` will be parsed and applied.

### Programmatic Disabling

LeakSanitizer provides fine-grained programmatic control over leak detection
via `<sanitizer/lsan_interface.h>`:

- **Disable around specific code blocks**: Allocations made between calls to
  `__lsan_disable()` and `__lsan_enable()` will not be reported as leaks. This
  disabling is thread-local and only affects allocations made by the calling thread.
  In C++, you can use the RAII wrapper `__lsan::ScopedDisabler`:

  ```c++
  #include <sanitizer/lsan_interface.h>

  void foo() {
    __lsan::ScopedDisabler disabler;
    // Allocations made here will not be reported as leaks.
    leaky_third_party_init();
  }
  ```

- **Ignore specific objects**: `__lsan_ignore_object(const void *p)` marks the
  heap object pointed to by `p` (and anything reachable from it) as a non-leak.

- **Register custom root regions**: `__lsan_register_root_region(const void *p, size_t size)`
  and `__lsan_unregister_root_region(const void *p, size_t size)` register memory
  areas (such as custom memory pools or mapped regions) to be scanned for live
  pointers during leak checking.

- **Explicit leak checking**: `__lsan_do_leak_check()` triggers an immediate
  leak check. If leaks are detected and the `exitcode` flag is non-zero (default),
  the process terminates; otherwise, it returns normally. Calling this function
  disables subsequent automatic leak checks at process exit.
  `__lsan_do_recoverable_leak_check()` performs a leak check and returns `0` if
  no leaks were detected (or if leak detection is disabled), and `1` if leaks
  were found. It prints a report without terminating the process or disabling
  the end-of-process check.

- **Disable leak checking entirely**: Define `__lsan_is_turned_off()` to return
  `1` to disable leak checking for the program.

## Flags and Options

Runtime flags can be passed to LeakSanitizer via the `LSAN_OPTIONS` environment
variable:

```console
$ LSAN_OPTIONS="print_suppressions=0:report_objects=1" ./a.out
```

To see the full list of available flags, run an instrumented binary with
`LSAN_OPTIONS="help=1"`.

Flags passed via the `LSAN_OPTIONS` environment variable take precedence over
compile-time default options.

### Compile-time Default Options

Default options can also be specified at compile/link time by defining
`__lsan_default_options`:

```c++
#include <sanitizer/lsan_interface.h>

extern "C" const char *__lsan_default_options() {
  return "print_suppressions=0:report_objects=1";
}
```

## Security Considerations

LeakSanitizer is a bug detection tool and its runtime is not meant to be
linked against production executables. While it may be useful for testing,
LeakSanitizer's runtime was not developed with security-sensitive
constraints in mind and may compromise the security of the resulting executable.

## Supported Platforms

- Android
- Fuchsia
- Linux
- macOS
- NetBSD

## More Information

[https://github.com/google/sanitizers/wiki/AddressSanitizerLeakSanitizer](https://github.com/google/sanitizers/wiki/AddressSanitizerLeakSanitizer)

---

### Clang Docs LibASTImporter (`clang/docs/LibASTImporter.md`)

# ASTImporter: Merging Clang ASTs

The `ASTImporter` class is part of Clang's core library, the AST library.
It imports nodes of an `ASTContext` into another `ASTContext`.

In this document, we assume basic knowledge about the Clang AST. See the {doc}`Introduction
to the Clang AST <IntroductionToTheClangAST>` if you want to learn more
about how the AST is structured.
Knowledge about [matching the Clang AST](LibASTMatchers.md) and the [reference for the matchers](LibASTMatchersReference.html){.external} are also useful.


## Introduction

`ASTContext` holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic analysis of a file.
In some cases it is preferable to work with more than one `ASTContext`.
For example, we'd like to parse multiple different files inside the same Clang tool.
It may be convenient if we could view the set of the resulting ASTs as if they were one AST resulting from the parsing of each file together.
`ASTImporter` provides the way to copy types or declarations from one `ASTContext` to another.
We refer to the context from which we import as the **"from" context** or *source context*; and the context into which we import as the **"to" context** or *destination context*.

Existing clients of the `ASTImporter` library are Cross Translation Unit (CTU) static analysis and the LLDB expression parser.
CTU static analysis imports a definition of a function if its definition is found in another translation unit (TU).
This way the analysis can breach out from the single TU limitation.
LLDB's `expr` command parses a user-defined expression, creates an `ASTContext` for that and then imports the missing definitions from the AST what we got from the debug information (DWARF, etc).

## Algorithm of the import

Importing one AST node copies that node into the destination `ASTContext`.
Why do we have to copy the node?
Isn't enough to insert the pointer to that node into the destination context?
One reason is that the "from" context may outlive the "to" context.
Also, the Clang AST considers nodes (or certain properties of nodes) equivalent if they have the same address!

The import algorithm has to ensure that the structurally equivalent nodes in the different translation units are not getting duplicated in the merged AST.
E.g. if we include the definition of the vector template (`#include <vector>`) in two translation units, then their merged AST should have only one node which represents the template.
Also, we have to discover *one definition rule* (ODR) violations.
For instance, if there is a class definition with the same name in both translation units, but one of the definitions contains a different number of fields.
So, we look up existing definitions, and then we check the structural equivalency on those nodes.
The following pseudo-code demonstrates the basics of the import mechanism:

```cpp
// Pseudo-code(!) of import:
ErrorOrDecl Import(Decl *FromD) {
  Decl *ToDecl = nullptr;
  FoundDeclsList = Look up all Decls in the "to" Ctx with the same name of FromD;
  for (auto FoundDecl : FoundDeclsList) {
    if (StructurallyEquivalentDecls(FoundDecl, FromD)) {
      ToDecl = FoundDecl;
      Mark FromD as imported;
      break;
    } else {
      Report ODR violation;
      return error;
    }
  }
  if (FoundDeclsList is empty) {
    Import dependent declarations and types of ToDecl;
    ToDecl = create a new AST node in "to" Ctx;
    Mark FromD as imported;
  }
  return ToDecl;
}
```

Two AST nodes are *structurally equivalent* if they are

- builtin types and refer to the same type, e.g. `int` and `int` are structurally equivalent,
- function types and all their parameters have structurally equivalent types,
- record types and all their fields in order of their definition have the same identifier names and structurally equivalent types,
- variable or function declarations and they have the same identifier name and their types are structurally equivalent.

We could extend the definition of structural equivalency to templates similarly.

If A and B are AST nodes and *A depends on B*, then we say that A is a **dependant** of B and B is a **dependency** of A.
The words "dependant" and "dependency" are nouns in British English.
Unfortunately, in American English, the adjective "dependent" is used for both meanings.
In this document, with the "dependent" adjective we always address the dependencies, the B node in the example.

## API

Let's create a tool which uses the ASTImporter class!
First, we build two ASTs from virtual files; the content of the virtual files are synthesized from string literals:

```cpp
std::unique_ptr<ASTUnit> ToUnit = buildASTFromCode(
    "", "to.cc"); // empty file
std::unique_ptr<ASTUnit> FromUnit = buildASTFromCode(
    R"(
    class MyClass {
      int m1;
      int m2;
    };
    )",
    "from.cc");
```

The first AST corresponds to the destination ("to") context - which is empty - and the second for the source ("from") context.
Next, we define a matcher to match `MyClass` in the "from" context:

```cpp
auto Matcher = cxxRecordDecl(hasName("MyClass"));
auto *From = getFirstDecl<CXXRecordDecl>(Matcher, FromUnit);
```

Now we create the Importer and do the import:

```cpp
ASTImporter Importer(ToUnit->getASTContext(), ToUnit->getFileManager(),
                     FromUnit->getASTContext(), FromUnit->getFileManager(),
                     /*MinimalImport=*/true);
llvm::Expected<Decl *> ImportedOrErr = Importer.Import(From);
```

The `Import` call returns with `llvm::Expected`, so, we must check for any error.
Please refer to the [error handling](https://llvm.org/docs/ProgrammersManual.html#recoverable-errors) documentation for details.

```cpp
if (!ImportedOrErr) {
  llvm::Error Err = ImportedOrErr.takeError();
  llvm::errs() << "ERROR: " << Err << "\n";
  consumeError(std::move(Err));
  return 1;
}
```

If there's no error then we can get the underlying value.
In this example we will print the AST of the "to" context.

```cpp
Decl *Imported = *ImportedOrErr;
Imported->getTranslationUnitDecl()->dump();
```

Since we set **minimal import** in the constructor of the importer, the AST will not contain the declaration of the members (once we run the test tool).

```
TranslationUnitDecl 0x68b9a8 <<invalid sloc>> <invalid sloc>
`-CXXRecordDecl 0x6c7e30 <line:2:7, col:13> col:13 class MyClass definition
  `-DefinitionData pass_in_registers standard_layout trivially_copyable trivial literal
    |-DefaultConstructor exists trivial needs_implicit
    |-CopyConstructor simple trivial has_const_param needs_implicit implicit_has_const_param
    |-MoveConstructor exists simple trivial needs_implicit
    |-CopyAssignment trivial has_const_param needs_implicit implicit_has_const_param
    |-MoveAssignment exists simple trivial needs_implicit
    `-Destructor simple irrelevant trivial needs_implicit
```

We'd like to get the members too, so, we use `ImportDefinition` to copy the whole definition of `MyClass` into the "to" context.
Then we dump the AST again.

```cpp
if (llvm::Error Err = Importer.ImportDefinition(From)) {
  llvm::errs() << "ERROR: " << Err << "\n";
  consumeError(std::move(Err));
  return 1;
}
llvm::errs() << "Imported definition.\n";
Imported->getTranslationUnitDecl()->dump();
```

This time the AST is going to contain the members too.

```
TranslationUnitDecl 0x68b9a8 <<invalid sloc>> <invalid sloc>
`-CXXRecordDecl 0x6c7e30 <line:2:7, col:13> col:13 class MyClass definition
  |-DefinitionData pass_in_registers standard_layout trivially_copyable trivial literal
  | |-DefaultConstructor exists trivial needs_implicit
  | |-CopyConstructor simple trivial has_const_param needs_implicit implicit_has_const_param
  | |-MoveConstructor exists simple trivial needs_implicit
  | |-CopyAssignment trivial has_const_param needs_implicit implicit_has_const_param
  | |-MoveAssignment exists simple trivial needs_implicit
  | `-Destructor simple irrelevant trivial needs_implicit
  |-CXXRecordDecl 0x6c7f48 <col:7, col:13> col:13 implicit class MyClass
  |-FieldDecl 0x6c7ff0 <line:3:9, col:13> col:13 m1 'int'
  `-FieldDecl 0x6c8058 <line:4:9, col:13> col:13 m2 'int'
```

We can spare the call for `ImportDefinition` if we set up the importer to do a "normal" (not minimal) import.

```cpp
ASTImporter Importer( ....  /*MinimalImport=*/false);
```

With **normal import**, all dependent declarations are imported normally.
However, with minimal import, the dependent Decls are imported without definition, and we have to import their definition for each if we later need that.

Putting this all together here is how the source of the tool looks like:

```
/* Detailed source-code truncated for AI context efficiency. */
```

We may extend the `CMakeLists.txt` under let's say `clang/tools` with the build and link instructions:

```cmake
add_clang_executable(astimporter-demo ASTImporterDemo.cpp)
clang_target_link_libraries(astimporter-demo
  PRIVATE
  LLVMSupport
  clangAST
  clangASTMatchers
  clangBasic
  clangFrontend
  clangSerialization
  clangTooling
  )
```

Then we can build and execute the new tool.

```console
$ ninja astimporter-demo && ./bin/astimporter-demo
```

### Errors during the import process

Normally, either the source or the destination context contains the definition of a declaration.
However, there may be cases when both of the contexts have a definition for a given symbol.
If these definitions differ, then we have a name conflict, in C++ it is known as ODR (one definition rule) violation.
Let's modify the previous tool we had written and try to import a `ClassTemplateSpecializationDecl` with a conflicting definition:

```cpp
int main() {
  std::unique_ptr<ASTUnit> ToUnit = buildASTFromCode(
      R"(
      // primary template
      template <typename T>
      struct X {};
      // explicit specialization
      template<>
      struct X<int> { int i; };
      )",
      "to.cc");
  ToUnit->enableSourceFileDiagnostics();
  std::unique_ptr<ASTUnit> FromUnit = buildASTFromCode(
      R"(
      // primary template
      template <typename T>
      struct X {};
      // explicit specialization
      template<>
      struct X<int> { int i2; };
      // field mismatch:  ^^
      )",
      "from.cc");
  FromUnit->enableSourceFileDiagnostics();
  auto Matcher = classTemplateSpecializationDecl(hasName("X"));
  auto *From = getFirstDecl<ClassTemplateSpecializationDecl>(Matcher, FromUnit);
  auto *To = getFirstDecl<ClassTemplateSpecializationDecl>(Matcher, ToUnit);

  ASTImporter Importer(ToUnit->getASTContext(), ToUnit->getFileManager(),
                       FromUnit->getASTContext(), FromUnit->getFileManager(),
                       /*MinimalImport=*/false);
  llvm::Expected<Decl *> ImportedOrErr = Importer.Import(From);
  if (!ImportedOrErr) {
    llvm::Error Err = ImportedOrErr.takeError();
    llvm::errs() << "ERROR: " << Err << "\n";
    consumeError(std::move(Err));
    To->getTranslationUnitDecl()->dump();
    return 1;
  }
  return 0;
};
```

When we run the tool we have the following warning:

```console
to.cc:7:14: warning: type 'X<int>' has incompatible definitions in different translation units [-Wodr]
      struct X<int> { int i; };
             ^
to.cc:7:27: note: field has name 'i' here
      struct X<int> { int i; };
                          ^
from.cc:7:27: note: field has name 'i2' here
      struct X<int> { int i2; };
                        ^
```

Note, because of these diagnostics we had to call `enableSourceFileDiagnostics` on the `ASTUnit` objects.

Since we could not import the specified declaration (`From`), we get an error in the return value.
The AST does not contain the conflicting definition, so we are left with the original AST.

```
/* Detailed source-code truncated for AI context efficiency. */
```

#### Error propagation

If there is a dependent node we have to import before we could import a given node then the import error associated to the dependency propagates to the dependant node.
Let's modify the previous example and import a `FieldDecl` instead of the `ClassTemplateSpecializationDecl`.

```cpp
auto Matcher = fieldDecl(hasName("i2"));
auto *From = getFirstDecl<FieldDecl>(Matcher, FromUnit);
```

In this case we can see that an error is associated (`getImportDeclErrorIfAny`) to the specialization also, not just to the field:

```cpp
llvm::Expected<Decl *> ImportedOrErr = Importer.Import(From);
if (!ImportedOrErr) {
  llvm::Error Err = ImportedOrErr.takeError();
  consumeError(std::move(Err));

  // check that the ClassTemplateSpecializationDecl is also marked as
  // erroneous.
  auto *FromSpec = getFirstDecl<ClassTemplateSpecializationDecl>(
      classTemplateSpecializationDecl(hasName("X")), FromUnit);
  assert(Importer.getImportDeclErrorIfAny(FromSpec));
  // Btw, the error is also set for the FieldDecl.
  assert(Importer.getImportDeclErrorIfAny(From));
  return 1;
}
```

#### Polluted AST

We may recognize an error during the import of a dependent node. However, by that time, we had already created the dependant.
In these cases we do not remove the existing erroneous node from the "to" context, rather we associate an error to that node.
Let's extend the previous example with another class `Y`.
This class has a forward definition in the "to" context, but its definition is in the "from" context.
We'd like to import the definition, but it contains a member whose type conflicts with the type in the "to" context:

```cpp
std::unique_ptr<ASTUnit> ToUnit = buildASTFromCode(
    R"(
    // primary template
    template <typename T>
    struct X {};
    // explicit specialization
    template<>
    struct X<int> { int i; };

    class Y;
    )",
    "to.cc");
ToUnit->enableSourceFileDiagnostics();
std::unique_ptr<ASTUnit> FromUnit = buildASTFromCode(
    R"(
    // primary template
    template <typename T>
    struct X {};
    // explicit specialization
    template<>
    struct X<int> { int i2; };
    // field mismatch:  ^^

    class Y { void f() { X<int> xi; } };
    )",
    "from.cc");
FromUnit->enableSourceFileDiagnostics();
auto Matcher = cxxRecordDecl(hasName("Y"));
auto *From = getFirstDecl<CXXRecordDecl>(Matcher, FromUnit);
auto *To = getFirstDecl<CXXRecordDecl>(Matcher, ToUnit);
```

This time we create a shared_ptr for `ASTImporterSharedState` which owns the associated errors for the "to" context.
Note, there may be several different ASTImporter objects which import into the same "to" context but from different "from" contexts; they should share the same `ASTImporterSharedState`.
(Also note, we have to include the corresponding `ASTImporterSharedState.h` header file.)

```cpp
auto ImporterState = std::make_shared<ASTImporterSharedState>();
ASTImporter Importer(ToUnit->getASTContext(), ToUnit->getFileManager(),
                     FromUnit->getASTContext(), FromUnit->getFileManager(),
                     /*MinimalImport=*/false, ImporterState);
llvm::Expected<Decl *> ImportedOrErr = Importer.Import(From);
if (!ImportedOrErr) {
  llvm::Error Err = ImportedOrErr.takeError();
  consumeError(std::move(Err));

  // ... but the node had been created.
  auto *ToYDef = getFirstDecl<CXXRecordDecl>(
      cxxRecordDecl(hasName("Y"), isDefinition()), ToUnit);
  ToYDef->dump();
  // An error is set for "ToYDef" in the shared state.
  std::optional<ASTImportError> OptErr =
      ImporterState->getImportDeclErrorIfAny(ToYDef);
  assert(OptErr);

  return 1;
}
```

If we take a look at the AST, then we can see that the Decl with the definition is created, but the field is missing.

```
|-CXXRecordDecl 0xf66678 <line:9:7, col:13> col:13 class Y
`-CXXRecordDecl 0xf66730 prev 0xf66678 <:10:7, col:13> col:13 class Y definition
  |-DefinitionData pass_in_registers empty aggregate standard_layout trivially_copyable pod trivial literal has_constexpr_non_copy_move_ctor can_const_default_init
  | |-DefaultConstructor exists trivial constexpr needs_implicit defaulted_is_constexpr
  | |-CopyConstructor simple trivial has_const_param needs_implicit implicit_has_const_param
  | |-MoveConstructor exists simple trivial needs_implicit
  | |-CopyAssignment trivial has_const_param needs_implicit implicit_has_const_param
  | |-MoveAssignment exists simple trivial needs_implicit
  | `-Destructor simple irrelevant trivial needs_implicit
  `-CXXRecordDecl 0xf66828 <col:7, col:13> col:13 implicit class Y
```

We do not remove the erroneous nodes because by the time when we recognize the error it is too late to remove the node, there may be additional references to that already in the AST.
This is aligned with the overall [design principle of the Clang AST](InternalsManual.md#immutability): Clang AST nodes (types, declarations, statements, expressions, and so on) are generally designed to be **immutable once created**.
Thus, clients of the ASTImporter library should always check if there is any associated error for the node which they inspect in the destination context.
We recommend skipping the processing of those nodes which have an error associated with them.

## Using the `-ast-merge` Clang front-end action

The `-ast-merge <pch-file>` command-line switch can be used to merge from the given serialized AST file.
This file represents the source context.
When this switch is present then each top-level AST node of the source context is being merged into the destination context.
If the merge was successful then `ASTConsumer::HandleTopLevelDecl` is called for the Decl.
This means that we can execute the original front-end action on the extended AST.

### Example for C

Let's consider the following three files:

```c
// bar.h
#ifndef BAR_H
#define BAR_H
int bar();
#endif /* BAR_H */

// bar.c
#include "bar.h"
int bar() {
  return 41;
}

// main.c
#include "bar.h"
int main() {
    return bar();
}
```

Let's generate the AST files for the two source files:

```console
$ clang -cc1 -emit-pch -o bar.ast bar.c
$ clang -cc1 -emit-pch -o main.ast main.c
```

Then, let's check how the merged AST would look like if we consider only the `bar()` function:

```console
$ clang -cc1 -ast-merge bar.ast -ast-merge main.ast /dev/null -ast-dump
TranslationUnitDecl 0x12b0738 <<invalid sloc>> <invalid sloc>
|-FunctionDecl 0x12b1470 </path/bar.h:4:1, col:9> col:5 used bar 'int ()'
|-FunctionDecl 0x12b1538 prev 0x12b1470 </path/bar.c:3:1, line:5:1> line:3:5 used bar 'int ()'
| `-CompoundStmt 0x12b1608 <col:11, line:5:1>
|   `-ReturnStmt 0x12b15f8 <line:4:3, col:10>
|     `-IntegerLiteral 0x12b15d8 <col:10> 'int' 41
|-FunctionDecl 0x12b1648 prev 0x12b1538 </path/bar.h:4:1, col:9> col:5 used bar 'int ()'
```

We can inspect that the prototype of the function and the definition of it is merged into the same redeclaration chain.
What's more there is a third prototype declaration merged to the chain.
The functions are merged in a way that prototypes are added to the redecl chain if they refer to the same type, but we can have only one definition.
The first two declarations are from `bar.ast`, the third is from `main.ast`.

Now, let's create an object file from the merged AST:

```console
$ clang -cc1 -ast-merge bar.ast -ast-merge main.ast /dev/null -emit-obj -o main.o
```

Next, we may call the linker and execute the created binary file.

```console
$ clang -o a.out main.o
$ ./a.out
$ echo $?
41
$
```

### Example for C++

In the case of C++, the generation of the AST files and the way how we invoke the front-end is a bit different.
Assuming we have these three files:

```cpp
// foo.h
#ifndef FOO_H
#define FOO_H
struct foo {
    virtual int fun();
};
#endif /* FOO_H */

// foo.cpp
#include "foo.h"
int foo::fun() {
  return 42;
}

// main.cpp
#include "foo.h"
int main() {
    return foo().fun();
}
```

We shall generate the AST files, merge them, create the executable and then run it:

```console
$ clang++ -emit-ast foo.cpp
$ clang++ -emit-ast main.cpp
$ clang++ -cc1 -x c++ -ast-merge foo.ast -ast-merge main.ast /dev/null -ast-dump
$ clang++ -cc1 -x c++ -ast-merge foo.ast -ast-merge main.ast /dev/null -emit-obj -o main.o
$ clang++ -o a.out main.o
$ ./a.out
$ echo $?
42
$
```

---

### Clang Docs LibASTMatchers (`clang/docs/LibASTMatchers.md`)

# Matching the Clang AST

This document explains how to use Clang's LibASTMatchers to match interesting
nodes of the AST and execute code that uses the matched nodes. Combined with
{doc}`LibTooling`, LibASTMatchers helps to write code-to-code transformation
tools or query tools.

We assume basic knowledge about the Clang AST. See the {doc}`Introduction
to the Clang AST <IntroductionToTheClangAST>` if you want to learn more
about how the AST is structured.

## Introduction

LibASTMatchers provides a domain specific language to create predicates on
Clang's AST. This DSL is written in and can be used from C++, allowing users
to write a single program to both match AST nodes and access the node's C++
interface to extract attributes, source locations, or any other information
provided on the AST level.

AST matchers are predicates on nodes in the AST. Matchers are created by
calling creator functions that allow building up a tree of matchers, where
inner matchers are used to make the match more specific.

For example, to create a matcher that matches all class or union declarations
in the AST of a translation unit, you can call [recordDecl()](LibASTMatchersReference.html#recordDecl0Anchor). To narrow the match down,
for example to find all class or union declarations with the name "`Foo`",
insert a [hasName](LibASTMatchersReference.html#hasName0Anchor) matcher: the
call `recordDecl(hasName("Foo"))` returns a matcher that matches classes or
unions that are named "`Foo`", in any namespace. By default, matchers that
accept multiple inner matchers use an implicit [allOf()](LibASTMatchersReference.html#allOf0Anchor). This allows further narrowing
down the match, for example to match all classes that are derived from
"`Bar`": `recordDecl(hasName("Foo"), isDerivedFrom("Bar"))`.

## How to create a matcher

With more than a thousand classes in the Clang AST, one can quickly get lost
when trying to figure out how to create a matcher for a specific pattern. This
section will teach you how to use a rigorous step-by-step pattern to build the
matcher you are interested in. Note that there will always be matchers missing
for some part of the AST. See the section about {ref}`how to write your own
AST matchers <astmatchers-writing>` later in this document.

The precondition to using the matchers is to understand how the AST for what you
want to match looks like. The
{doc}`Introduction to the Clang AST <IntroductionToTheClangAST>` teaches you
how to dump a translation unit's AST into a human readable format.

If you are looking for a step-by-step walkthrough of writing a tool based on
LibASTMatchers, see the {doc}`LibASTMatchersTutorial`.

In general, the strategy to create the right matchers is:

1. Find the outermost class in Clang's AST you want to match.
2. Look at the [AST Matcher Reference](LibASTMatchersReference.html) for
   matchers that either match the node you're interested in or narrow down
   attributes on the node.
3. Create your outer match expression. Verify that it works as expected.
4. Examine the matchers for what the next inner node you want to match is.
5. Repeat until the matcher is finished.

(astmatchers-bind)=

## Binding nodes in match expressions

Matcher expressions allow you to specify which parts of the AST are interesting
for a certain task. Often you will want to then do something with the nodes
that were matched, like building source code transformations.

To that end, matchers that match specific AST nodes (so called node matchers)
are bindable; for example, `recordDecl(hasName("MyClass")).bind("id")` will
bind the matched `recordDecl` node to the string "`id`", to be later
retrieved in the [match callback](https://clang.llvm.org/doxygen/classclang_1_1ast__matchers_1_1MatchFinder_1_1MatchCallback.html).

## Writing your own matchers

There are multiple different ways to define a matcher, depending on its type
and flexibility.

### `VariadicDynCastAllOfMatcher<Base, Derived>`

Those match all nodes of type *Base* if they can be dynamically cast to
*Derived*. The names of those matchers are nouns, which closely resemble
*Derived*. `VariadicDynCastAllOfMatchers` are the backbone of the matcher
hierarchy. Most often, your match expression will start with one of them, and
you can {ref}`bind <astmatchers-bind>` the node they represent to ids for later
processing.

`VariadicDynCastAllOfMatchers` are callable classes that model variadic
template functions in C++03. They take an arbitrary number of
`Matcher<Derived>` and return a `Matcher<Base>`.

### `AST_MATCHER_P(Type, Name, ParamType, Param)`

Most matcher definitions use the matcher creation macros. Those define both
the matcher of type `Matcher<Type>` itself, and a matcher-creation function
named *Name* that takes a parameter of type *ParamType* and returns the
corresponding matcher.

There are multiple matcher definition macros that deal with polymorphic return
values and different parameter counts. See [ASTMatchersMacros.h](https://clang.llvm.org/doxygen/ASTMatchersMacros_8h.html).

(astmatchers-writing)=

### Matcher creation functions

Matchers are generated by nesting calls to matcher creation functions. Most of
the time those functions are either created by using
`VariadicDynCastAllOfMatcher` or the matcher creation macros (see above).
The free-standing functions are an indication that this matcher is just a
combination of other matchers, as is for example the case with [callee](LibASTMatchersReference.html#callee1Anchor).

---

### Clang Docs LibASTMatchersTutorial (`clang/docs/LibASTMatchersTutorial.md`)

# Tutorial for building tools using LibTooling and LibASTMatchers

This document is intended to show how to build a useful source-to-source
translation tool based on Clang's [LibTooling](LibTooling.md). It is
explicitly aimed at people who are new to Clang, so all you should need
is a working knowledge of C++ and the command line.

In order to work on the compiler, you need some basic knowledge of the
abstract syntax tree (AST). To this end, the reader is encouraged to
skim the {doc}`Introduction to the Clang
AST <IntroductionToTheClangAST>`

## Step 0: Obtaining Clang

As Clang is part of the LLVM project, you'll need to download LLVM's
source code first. Both Clang and LLVM are in the same git repository,
under different directories. For further information, see the [getting
started guide](https://llvm.org/docs/GettingStarted.html).

```console
mkdir ~/clang-llvm && cd ~/clang-llvm
git clone https://github.com/llvm/llvm-project.git
```

Next you need to obtain the CMake build system and Ninja build tool.

```console
cd ~/clang-llvm
git clone https://github.com/martine/ninja.git
cd ninja
git checkout release
./configure.py --bootstrap
sudo cp ninja /usr/bin/

cd ~/clang-llvm
git clone https://gitlab.kitware.com/cmake/cmake.git
cd cmake
git checkout next
./bootstrap
make
sudo make install
```

Okay. Now we'll build Clang!

```console
cd ~/clang-llvm
mkdir build && cd build
cmake -G Ninja ../llvm-project/llvm -DLLVM_ENABLE_PROJECTS="clang;clang-tools-extra" -DCMAKE_BUILD_TYPE=Release -DLLVM_BUILD_TESTS=ON
ninja
ninja check       # Test LLVM only.
ninja clang-test  # Test Clang only.
ninja install
```

And we're live.

All of the tests should pass.

Finally, we want to set Clang as its own compiler.

```console
cd ~/clang-llvm/build
ccmake ../llvm-project/llvm
```

The second command will bring up a GUI for configuring Clang. You need
to set the entry for `CMAKE_CXX_COMPILER`. Press `'t'` to turn on
advanced mode. Scroll down to `CMAKE_CXX_COMPILER`, and set it to
`/usr/bin/clang++`, or wherever you installed it. Press `'c'` to
configure, then `'g'` to generate CMake's files.

Finally, run ninja one last time, and you're done.

## Step 1: Create a ClangTool

Now that we have enough background knowledge, it's time to create the
simplest productive ClangTool in existence: a syntax checker. While this
already exists as `clang-check`, it's important to understand what's
going on.

First, we'll need to create a new directory for our tool and tell CMake
that it exists. As this is not going to be a core clang tool, it will
live in the `clang-tools-extra` repository.

```console
cd ~/clang-llvm/llvm-project
mkdir clang-tools-extra/loop-convert
echo 'add_subdirectory(loop-convert)' >> clang-tools-extra/CMakeLists.txt
vim clang-tools-extra/loop-convert/CMakeLists.txt
```

CMakeLists.txt should have the following contents:

```
set(LLVM_LINK_COMPONENTS support)

add_clang_executable(loop-convert
  LoopConvert.cpp
  )
target_link_libraries(loop-convert
  PRIVATE
  clangAST
  clangASTMatchers
  clangBasic
  clangFrontend
  clangSerialization
  clangTooling
  )
```

With that done, Ninja will be able to compile our tool. Let's give it
something to compile! Put the following into
`clang-tools-extra/loop-convert/LoopConvert.cpp`. A detailed explanation of
why the different parts are needed can be found in the [LibTooling
documentation](LibTooling.md).

```c++
// Declares clang::SyntaxOnlyAction.
#include "clang/Frontend/FrontendActions.h"
#include "clang/Tooling/CommonOptionsParser.h"
#include "clang/Tooling/Tooling.h"
// Declares llvm::cl::extrahelp.
#include "llvm/Support/CommandLine.h"

using namespace clang::tooling;
using namespace llvm;

// Apply a custom category to all command-line options so that they are the
// only ones displayed.
static llvm::cl::OptionCategory MyToolCategory("my-tool options");

// CommonOptionsParser declares HelpMessage with a description of the common
// command-line options related to the compilation database and input files.
// It's nice to have this help message in all tools.
static cl::extrahelp CommonHelp(CommonOptionsParser::HelpMessage);

// A help message for this specific tool can be added afterwards.
static cl::extrahelp MoreHelp("\nMore help text...\n");

int main(int argc, const char **argv) {
  auto ExpectedParser = CommonOptionsParser::create(argc, argv, MyToolCategory);
  if (!ExpectedParser) {
    // Fail gracefully for unsupported options.
    llvm::errs() << ExpectedParser.takeError();
    return 1;
  }
  CommonOptionsParser& OptionsParser = ExpectedParser.get();
  ClangTool Tool(OptionsParser.getCompilations(),
                 OptionsParser.getSourcePathList());
  return Tool.run(newFrontendActionFactory<clang::SyntaxOnlyAction>().get());
}
```

And that's it! You can compile our new tool by running ninja from the
`build` directory.

```console
cd ~/clang-llvm/build
ninja
```

You should now be able to run the syntax checker, which is located in
`~/clang-llvm/build/bin`, on any source file. Try it!

```console
echo "int main() { return 0; }" > test.cpp
bin/loop-convert test.cpp --
```

Note the two dashes after we specify the source file. The additional
options for the compiler are passed after the dashes rather than loading
them from a compilation database - there just aren't any options needed
right now.

## Intermezzo: Learn AST matcher basics

Clang recently introduced the {doc}`ASTMatcher
library <LibASTMatchers>` to provide a simple, powerful, and
concise way to describe specific patterns in the AST. Implemented as a
DSL powered by macros and templates (see
[ASTMatchers.h](https://clang.llvm.org/doxygen/ASTMatchers_8h_source.html) if you're
curious), matchers offer the feel of algebraic data types common to
functional programming languages.

For example, suppose you wanted to examine only binary operators. There
is a matcher to do exactly that, conveniently named `binaryOperator`.
I'll give you one guess what this matcher does:

```c++
binaryOperator(hasOperatorName("+"), hasLHS(integerLiteral(equals(0))))
```

Shockingly, it will match against addition expressions whose left hand
side is exactly the literal 0. It will not match against other forms of
0, such as `'\0'` or `NULL`, but it will match against macros that
expand to 0. The matcher will also not match against calls to the
overloaded operator `'+'`, as there is a separate `operatorCallExpr`
matcher to handle overloaded operators.

There are AST matchers to match all the different nodes of the AST,
narrowing matchers to only match AST nodes fulfilling specific criteria,
and traversal matchers to get from one kind of AST node to another. For
a complete list of AST matchers, take a look at the [AST Matcher
References](LibASTMatchersReference.html)

All matchers that are nouns describe entities in the AST and can be
bound, so that they can be referred to whenever a match is found. To do
so, simply call the method `bind` on these matchers, e.g.:

```c++
variable(hasType(isInteger())).bind("intvar")
```

## Step 2: Using AST matchers

Okay, on to using matchers for real. Let's start by defining a matcher
which will capture all `for` statements that define a new variable
initialized to zero. Let's start with matching all `for` loops:

```c++
forStmt()
```

Next, we want to specify that a single variable is declared in the first
portion of the loop, so we can extend the matcher to

```c++
forStmt(hasLoopInit(declStmt(hasSingleDecl(varDecl()))))
```

Finally, we can add the condition that the variable is initialized to
zero.

```c++
forStmt(hasLoopInit(declStmt(hasSingleDecl(varDecl(
  hasInitializer(integerLiteral(equals(0))))))))
```

It is fairly easy to read and understand the matcher definition ("match
loops whose init portion declares a single variable which is initialized
to the integer literal 0"), but deciding that every piece is necessary
is more difficult. Note that this matcher will not match loops whose
variables are initialized to `'\0'`, `0.0`, `NULL`, or any form of
zero besides the integer 0.

The last step is giving the matcher a name and binding the `ForStmt`
as we will want to do something with it:

```c++
StatementMatcher LoopMatcher =
  forStmt(hasLoopInit(declStmt(hasSingleDecl(varDecl(
    hasInitializer(integerLiteral(equals(0)))))))).bind("forLoop");
```

Once you have defined your matchers, you will need to add a little more
scaffolding in order to run them. Matchers are paired with a
`MatchCallback` and registered with a `MatchFinder` object, then run
from a `ClangTool`. More code!

Add the following to `LoopConvert.cpp`:

```c++
#include "clang/ASTMatchers/ASTMatchers.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"

using namespace clang;
using namespace clang::ast_matchers;

StatementMatcher LoopMatcher =
  forStmt(hasLoopInit(declStmt(hasSingleDecl(varDecl(
    hasInitializer(integerLiteral(equals(0)))))))).bind("forLoop");

class LoopPrinter : public MatchFinder::MatchCallback {
public :
  virtual void run(const MatchFinder::MatchResult &Result) {
    if (const ForStmt *FS = Result.Nodes.getNodeAs<clang::ForStmt>("forLoop"))
      FS->dump();
  }
};
```

And change `main()` to:

```c++
int main(int argc, const char **argv) {
  auto ExpectedParser = CommonOptionsParser::create(argc, argv, MyToolCategory);
  if (!ExpectedParser) {
    // Fail gracefully for unsupported options.
    llvm::errs() << ExpectedParser.takeError();
    return 1;
  }
  CommonOptionsParser& OptionsParser = ExpectedParser.get();
  ClangTool Tool(OptionsParser.getCompilations(),
                 OptionsParser.getSourcePathList());

  LoopPrinter Printer;
  MatchFinder Finder;
  Finder.addMatcher(LoopMatcher, &Printer);

  return Tool.run(newFrontendActionFactory(&Finder).get());
}
```

Now, you should be able to recompile and run the code to discover for
loops. Create a new file with a few examples, and test out our new
handiwork:

```console
cd ~/clang-llvm/build/
ninja loop-convert
vim ~/test-files/simple-loops.cc
bin/loop-convert ~/test-files/simple-loops.cc
```

## Step 3.5: More Complicated Matchers

Our simple matcher is capable of discovering for loops, but we would
still need to filter out many more ourselves. We can do a good portion
of the remaining work with some cleverly chosen matchers, but first we
need to decide exactly which properties we want to allow.

How can we characterize for loops over arrays which would be eligible
for translation to range-based syntax? Range based loops over arrays of
size `N` that:

- start at index `0`
- iterate consecutively
- end at index `N-1`

We already check for (1), so all we need to add is a check to the loop's
condition to ensure that the loop's index variable is compared against
`N` and another check to ensure that the increment step just
increments this same variable. The matcher for (2) is straightforward:
require a pre- or post-increment of the same variable declared in the
init portion.

Unfortunately, such a matcher is impossible to write. Matchers contain
no logic for comparing two arbitrary AST nodes and determining whether
or not they are equal, so the best we can do is matching more than we
would like to allow, and punting extra comparisons to the callback.

In any case, we can start building this sub-matcher. We can require that
the increment step be a unary increment like this:

```c++
hasIncrement(unaryOperator(hasOperatorName("++")))
```

Specifying what is incremented introduces another quirk of Clang's AST:
Usages of variables are represented as `DeclRefExpr`'s ("declaration
reference expressions") because they are expressions which refer to
variable declarations. To find a `unaryOperator` that refers to a
specific declaration, we can simply add a second condition to it:

```c++
hasIncrement(unaryOperator(
  hasOperatorName("++"),
  hasUnaryOperand(declRefExpr())))
```

Furthermore, we can restrict our matcher to only match if the
incremented variable is an integer:

```c++
hasIncrement(unaryOperator(
  hasOperatorName("++"),
  hasUnaryOperand(declRefExpr(to(varDecl(hasType(isInteger())))))))
```

And the last step will be to attach an identifier to this variable, so
that we can retrieve it in the callback:

```c++
hasIncrement(unaryOperator(
  hasOperatorName("++"),
  hasUnaryOperand(declRefExpr(to(
    varDecl(hasType(isInteger())).bind("incrementVariable"))))))
```

We can add this code to the definition of `LoopMatcher` and make sure
that our program, outfitted with the new matcher, only prints out loops
that declare a single variable initialized to zero and have an increment
step consisting of a unary increment of some variable.

Now, we just need to add a matcher to check if the condition part of the
`for` loop compares a variable against the size of the array. There is
only one problem - we don't know which array we're iterating over
without looking at the body of the loop! We are again restricted to
approximating the result we want with matchers, filling in the details
in the callback. So we start with:

```c++
hasCondition(binaryOperator(hasOperatorName("<")))
```

It makes sense to ensure that the left-hand side is a reference to a
variable, and that the right-hand side has integer type.

```c++
hasCondition(binaryOperator(
  hasOperatorName("<"),
  hasLHS(declRefExpr(to(varDecl(hasType(isInteger()))))),
  hasRHS(expr(hasType(isInteger())))))
```

Why? Because it doesn't work. Of the three loops provided in
`test-files/simple.cpp`, zero of them have a matching condition. A
quick look at the AST dump of the first for loop, produced by the
previous iteration of loop-convert, shows us the answer:

```
(ForStmt 0x173b240
  (DeclStmt 0x173afc8
    0x173af50 "int i =
      (IntegerLiteral 0x173afa8 'int' 0)")
  <<>>
  (BinaryOperator 0x173b060 '_Bool' '<'
    (ImplicitCastExpr 0x173b030 'int'
      (DeclRefExpr 0x173afe0 'int' lvalue Var 0x173af50 'i' 'int'))
    (ImplicitCastExpr 0x173b048 'int'
      (DeclRefExpr 0x173b008 'const int' lvalue Var 0x170fa80 'N' 'const int')))
  (UnaryOperator 0x173b0b0 'int' lvalue prefix '++'
    (DeclRefExpr 0x173b088 'int' lvalue Var 0x173af50 'i' 'int'))
  (CompoundStatement ...
```

We already know that the declaration and increments both match, or this
loop wouldn't have been dumped. The culprit lies in the implicit cast
applied to the first operand (i.e. the LHS) of the less-than operator,
an L-value to R-value conversion applied to the expression referencing
`i`. Thankfully, the matcher library offers a solution to this problem
in the form of `ignoringParenImpCasts`, which instructs the matcher to
ignore implicit casts and parentheses before continuing to match.
Adjusting the condition operator will restore the desired match.

```c++
hasCondition(binaryOperator(
  hasOperatorName("<"),
  hasLHS(ignoringParenImpCasts(declRefExpr(
    to(varDecl(hasType(isInteger())))))),
  hasRHS(expr(hasType(isInteger())))))
```

After adding binds to the expressions we wished to capture and
extracting the identifier strings into variables, we have array-step-2
completed.

## Step 4: Retrieving Matched Nodes

So far, the matcher callback isn't very interesting: it just dumps the
loop's AST. At some point, we will need to make changes to the input
source code. Next, we'll work on using the nodes we bound in the
previous step.

The `MatchFinder::run()` callback takes a `MatchFinder::MatchResult&` as its
parameter. We're most interested in its `Context` and `Nodes` members. Clang
uses the `ASTContext` class to represent contextual information about the AST,
as the name implies, though the most functionally important detail is that
several operations require an `ASTContext*` parameter. More immediately useful
is the set of matched nodes, and how we retrieve them.

Since we bind three variables (identified by ConditionVarName,
InitVarName, and IncrementVarName), we can obtain the matched nodes by
using the `getNodeAs()` member function.

In `LoopConvert.cpp` add

```c++
#include "clang/AST/ASTContext.h"
```

Change `LoopMatcher` to

```c++
StatementMatcher LoopMatcher =
    forStmt(hasLoopInit(declStmt(
                hasSingleDecl(varDecl(hasInitializer(integerLiteral(equals(0))))
                                  .bind("initVarName")))),
            hasIncrement(unaryOperator(
                hasOperatorName("++"),
                hasUnaryOperand(declRefExpr(
                    to(varDecl(hasType(isInteger())).bind("incVarName")))))),
            hasCondition(binaryOperator(
                hasOperatorName("<"),
                hasLHS(ignoringParenImpCasts(declRefExpr(
                    to(varDecl(hasType(isInteger())).bind("condVarName"))))),
                hasRHS(expr(hasType(isInteger())))))).bind("forLoop");
```

And change `LoopPrinter::run` to

```c++
void LoopPrinter::run(const MatchFinder::MatchResult &Result) {
  ASTContext *Context = Result.Context;
  const ForStmt *FS = Result.Nodes.getNodeAs<ForStmt>("forLoop");
  // We do not want to convert header files!
  if (!FS || !Context->getSourceManager().isWrittenInMainFile(FS->getForLoc()))
    return;
  const VarDecl *IncVar = Result.Nodes.getNodeAs<VarDecl>("incVarName");
  const VarDecl *CondVar = Result.Nodes.getNodeAs<VarDecl>("condVarName");
  const VarDecl *InitVar = Result.Nodes.getNodeAs<VarDecl>("initVarName");

  if (!areSameVariable(IncVar, CondVar) || !areSameVariable(IncVar, InitVar))
    return;
  llvm::outs() << "Potential array-based loop discovered.\n";
}
```

Clang associates a `VarDecl` with each variable to represent the variable's
declaration. Since the "canonical" form of each declaration is unique by
address, all we need to do is make sure neither `ValueDecl` (base class of
`VarDecl`) is `NULL` and compare the canonical Decls.

```c++
static bool areSameVariable(const ValueDecl *First, const ValueDecl *Second) {
  return First && Second &&
         First->getCanonicalDecl() == Second->getCanonicalDecl();
}
```

If execution reaches the end of `LoopPrinter::run()`, we know that the
loop shell looks like

```c++
for (int i= 0; i < expr(); ++i) { ... }
```

For now, we will just print a message explaining that we found a loop.
The next section will deal with recursively traversing the AST to
discover all changes needed.

As a side note, it's not as trivial to test if two expressions are the same,
though Clang has already done the hard work for us by providing a way to
canonicalize expressions:

```c++
static bool areSameExpr(ASTContext *Context, const Expr *First,
                        const Expr *Second) {
  if (!First || !Second)
    return false;
  llvm::FoldingSetNodeID FirstID, SecondID;
  First->Profile(FirstID, *Context, true);
  Second->Profile(SecondID, *Context, true);
  return FirstID == SecondID;
}
```

This code relies on the comparison between two `llvm::FoldingSetNodeIDs`. As
the documentation for `Stmt::Profile()` indicates, the `Profile()` member
function builds a description of a node in the AST, based on its properties,
along with those of its children. `FoldingSetNodeID` then serves as a hash we
can use to compare expressions. We will need `areSameExpr` later. Before you
run the new code on the additional loops added to test-files/simple.cpp, try to
figure out which ones will be considered potentially convertible.

---

### Clang Docs LibClang (`clang/docs/LibClang.md`)

# Libclang tutorial

The C Interface to Clang provides a relatively small API that exposes facilities for parsing source code into an abstract syntax tree (AST), loading already-parsed ASTs, traversing the AST, associating physical source locations with elements within the AST, and other facilities that support Clang-based development tools.
This C interface to Clang will never provide all of the information representation stored in Clang's C++ AST, nor should it: the intent is to maintain an API that is {ref}`relatively stable <Stability>` from one release to the next, providing only the basic functionality needed to support development tools.
The entire C interface of libclang is available in the file [Index.h]

## Essential types overview

All types of libclang are prefixed with `CX`

### CXIndex

An Index that consists of a set of translation units that would typically be linked together into an executable or library.

### CXTranslationUnit

A single translation unit, which resides in an index.

### CXCursor

A cursor representing a pointer to some element in the abstract syntax tree of a translation unit.

#### Code example

```cpp
// file.cpp
struct foo{
  int bar;
  int* bar_pointer;
};
```

```cpp
// main.cpp
#include <clang-c/Index.h>
#include <iostream>

int main(){
  CXIndex index = clang_createIndex(0, 0); //Create index
  CXTranslationUnit unit = clang_parseTranslationUnit(
    index,
    "file.cpp", nullptr, 0,
    nullptr, 0,
    CXTranslationUnit_None); //Parse "file.cpp"


  if (unit == nullptr){
    std::cerr << "Unable to parse translation unit. Quitting.\n";
    return 0;
  }
  CXCursor cursor = clang_getTranslationUnitCursor(unit); //Obtain a cursor at the root of the translation unit
}
```

```cmake
# CMakeLists.txt
cmake_minimum_required(VERSION 3.20)
project(my_clang_tool VERSION 0.1.0)

# This will find the default system installation of Clang; if you want to
# use a different build of clang, pass -DClang_DIR=/foobar/lib/cmake/clang
# to the CMake configure command, where /foobar is the build directory where
# you built Clang.
find_package(Clang CONFIG REQUIRED)

add_executable(my_clang_tool main.cpp)
target_include_directories(my_clang_tool PRIVATE ${CLANG_INCLUDE_DIRS})
target_link_libraries(my_clang_tool PRIVATE libclang)
```

### Visiting elements of an AST

The elements of an AST can be recursively visited with pre-order traversal with `clang_visitChildren`.

```cpp
clang_visitChildren(
  cursor, //Root cursor
  [](CXCursor current_cursor, CXCursor parent, CXClientData client_data){

    CXString current_display_name = clang_getCursorDisplayName(current_cursor);
    //Allocate a CXString representing the name of the current cursor

    std::cout << "Visiting element " << clang_getCString(current_display_name) << "\n";
    //Print the char* value of current_display_name

    clang_disposeString(current_display_name);
    //Since clang_getCursorDisplayName allocates a new CXString, it must be freed. This applies
    //to all functions returning a CXString

    return CXChildVisit_Recurse;


  }, //CXCursorVisitor: a function pointer
  nullptr //client_data
  );
```

The return value of `CXCursorVisitor`, the callable argument of `clang_visitChildren`, can return one of the three:

1. `CXChildVisit_Break`: Terminates the cursor traversal
2. `CXChildVisit_Continue`: Continues the cursor traversal with the next sibling of the cursor just visited, without visiting its children.
3. `CXChildVisit_Recurse`: Recursively traverse the children of this cursor, using the same visitor and client data

The expected output of that program is

```
Visiting element foo
Visiting element bar
Visiting element bar_pointer
```

### Extracting information from a Cursor

% The following functions take a ``CXCursor`` as an argument and return associated information.

#### Extracting the Cursor kind

`CXCursorKind clang_getCursorKind(CXCursor)` Describes the kind of entity that a cursor refers to. Example values:

- `CXCursor_StructDecl`: A C or C++ struct.
- `CXCursor_FieldDecl`: A field in a struct, union, or C++ class.
- `CXCursor_CallExpr`: An expression that calls a function.

#### Extracting the Cursor type

`CXType clang_getCursorType(CXCursor)`: Retrieve the type of a CXCursor (if any).

A `CXType` represents a complete C++ type, including qualifiers and pointers. It has a member field `CXTypeKind kind` and additional opaque data.

Example values for `CXTypeKind kind`

- `CXType_Invalid`: Represents an invalid type (e.g., where no type is available)
- `CXType_Pointer`: A pointer to another type
- `CXType_Int`: Regular `int`
- `CXType_Elaborated`: Represents a type that was referred to using an elaborated type keyword e.g. struct S, or via a qualified name, e.g., N::M::type, or both.

Any `CXTypeKind` can be converted to a `CXString` using `clang_getTypeKindSpelling(CXTypeKind)`.

A `CXType` holds additional necessary opaque type info, such as:

- Which struct was referred to?
- What type is the pointer pointing to?
- Qualifiers (e.g. `const`, `volatile`)?

Qualifiers of a `CXType` can be queried with:

- `clang_isConstQualifiedType(CXType)` to check for `const`
- `clang_isRestrictQualifiedType(CXType)` to check for `restrict`
- `clang_isVolatileQualifiedType(CXType)` to check for `volatile`

#### Code example

```cpp
//structs.cpp
struct A{
  int value;
};
struct B{
  int value;
  A struct_value;
};
```

```
/* Detailed source-code truncated for AI context efficiency. */
```

The expected output of program is:

```
Type Kind: Record, namely A
Type Kind: Int
Type Kind: Record, namely B
Type Kind: Int
Type Kind: Record, namely A
Type Kind: Record, namely A
```

Reiterating the difference between `CXType` and `CXTypeKind`: For an example

```cpp
const char* __restrict__ variable;
```

- Type Kind will be: `CXType_Pointer` spelled `"Pointer"`
- Type will be a complex `CXType` structure, spelled `"const char* __restrict__`

#### Retrieving source locations

`CXSourceRange clang_getCursorExtent(CXCursor)` returns a `CXSourceRange`, representing a half-open range in the source code.

Use `clang_getRangeStart(CXSourceRange)` and `clang_getRangeEnd(CXSourceRange)` to retrieve the starting and end `CXSourceLocation` from a source range, respectively.

Given a `CXSourceLocation`, use `clang_getExpansionLocation` to retrieve file, line and column of a source location.

#### Code example

```cpp
// Again, file.cpp
struct foo{
  int bar;
  int* bar_pointer;
};
```

```cpp
clang_visitChildren(
  cursor,
  [](CXCursor current_cursor, CXCursor parent, CXClientData client_data){

    CXType cursor_type = clang_getCursorType(current_cursor);
    CXString cursor_spelling = clang_getCursorSpelling(current_cursor);
    CXSourceRange cursor_range = clang_getCursorExtent(current_cursor);
    std::cout << "Cursor " << clang_getCString(cursor_spelling);

    CXFile file;
    unsigned start_line, start_column, start_offset;
    unsigned end_line, end_column, end_offset;

    clang_getExpansionLocation(clang_getRangeStart(cursor_range), &file, &start_line, &start_column, &start_offset);
    clang_getExpansionLocation(clang_getRangeEnd  (cursor_range), &file, &end_line  , &end_column  , &end_offset);
    std::cout << " spanning lines " << start_line << " to " << end_line;
    clang_disposeString(cursor_spelling);

    std::cout << "\n";
    return CXChildVisit_Recurse;
  },
  nullptr
);
```

The expected output of this program is:

```
Cursor foo spanning lines 2 to 5
Cursor bar spanning lines 3 to 3
Cursor bar_pointer spanning lines 4 to 4
```

### Complete example code

```
/* Detailed source-code truncated for AI context efficiency. */
```

```cmake
# CMakeLists.txt
cmake_minimum_required(VERSION 3.20)
project(my_clang_tool VERSION 0.1.0)

# This will find the default system installation of Clang; if you want to
# use a different build of clang, pass -DClang_DIR=/foobar/lib/cmake/clang
# to the CMake configure command, where /foobar is the build directory where
# you built Clang.
find_package(Clang CONFIG REQUIRED)

add_executable(my_clang_tool main.cpp)
target_include_directories(my_clang_tool PRIVATE ${CLANG_INCLUDE_DIRS})
target_link_libraries(my_clang_tool PRIVATE libclang)
```

(stability)=

## ABI and API Stability

The C interfaces in libclang are intended to be relatively stable. This allows
a programmer to use libclang without having to worry as much about Clang
upgrades breaking existing code. However, the library is not unchanging. For
example, the library will gain new interfaces over time as needs arise,
existing APIs may be deprecated for eventual removal, etc. Also, the underlying
implementation of the facilities by Clang may change behavior as bugs are
fixed, features get implemented, etc.

The library should be ABI and API stable over time, but ABI- and API-breaking
changes can happen in the following (non-exhaustive) situations:

- Adding new enumerator to an enumeration (can be ABI-breaking in C++).
- Removing an explicitly deprecated API after a suitably long deprecation
  period.
- Using implementation details, such as names or comments that say something
  is "private", "reserved", "internal", etc.
- Bug fixes and changes to Clang's internal implementation happen routinely and
  will change the behavior of callers.
- Rarely, bug fixes to libclang itself.

The library has version macros (`CINDEX_VERSION_MAJOR`,
`CINDEX_VERSION_MINOR`, and `CINDEX_VERSION`) which can be used to test for
specific library versions at compile time. The `CINDEX_VERSION_MAJOR` macro
is only incremented if there are major source- or ABI-breaking changes. Except
for removing an explicitly deprecated API, the changes listed above are not
considered major source- or ABI-breaking changes. Historically, the value this
macro expands to has not changed, but may be incremented in the future should
the need arise. The `CINDEX_VERSION_MINOR` macro is incremented as new APIs
are added. The `CINDEX_VERSION` macro expands to a value based on the major
and minor version macros.

In an effort to allow the library to be modified as new needs arise, the
following situations are explicitly unsupported:

- Loading different library versions into the same executable and passing
  objects between the libraries; despite general ABI stability, different
  versions of the library may use different implementation details that are not
  compatible across library versions.
- For the same reason as above, serializing objects from one version of the
  library and deserializing with a different version is also not supported.

Note: because libclang is a wrapper around the compiler frontend, it is not a
[security-sensitive component] of the LLVM Project. Consider using a sandbox
or some other mitigation approach if processing untrusted input.

[index.h]: https://github.com/llvm/llvm-project/blob/main/clang/include/clang-c/Index.h
[security-sensitive component]: https://llvm.org/docs/Security.html#what-is-considered-a-security-issue

---

### Clang Docs LibFormat (`clang/docs/LibFormat.md`)

# LibFormat

LibFormat is a library that implements automatic source code formatting based
on Clang. This document describes the LibFormat interface and design as well
as some basic style discussions.

If you just want to use `clang-format` as a tool or integrated into an editor,
checkout {doc}`ClangFormat`.

## Design

FIXME: Write up design.

## Interface

The core routine of LibFormat is `reformat()`:

```c++
tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
                               SourceManager &SourceMgr,
                               std::vector<CharSourceRange> Ranges);
```

This reads a token stream out of the lexer `Lex` and reformats all the code
ranges in `Ranges`. The `FormatStyle` controls basic decisions made during
formatting. A list of options can be found under {ref}`style-options`.

The style options are described in {doc}`ClangFormatStyleOptions`.

(style-options)=

## Style Options

The style options describe specific formatting options that can be used in
order to make `ClangFormat` comply with different style guides. Currently,
several style guides are hard-coded:

```c++
/// Returns a format style complying with the LLVM coding standards:
/// https://llvm.org/docs/CodingStandards.html.
FormatStyle getLLVMStyle();

/// Returns a format style complying with Google's C++ style guide:
/// http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml.
FormatStyle getGoogleStyle();

/// Returns a format style complying with Chromium's style guide:
/// https://chromium.googlesource.com/chromium/src/+/refs/heads/main/styleguide/styleguide.md
FormatStyle getChromiumStyle();

/// Returns a format style complying with the GNU coding standards:
/// https://www.gnu.org/prep/standards/standards.html
FormatStyle getGNUStyle();

/// Returns a format style complying with Mozilla's style guide
/// https://firefox-source-docs.mozilla.org/code-quality/coding-style/index.html
FormatStyle getMozillaStyle();

/// Returns a format style complying with Webkit's style guide:
/// https://webkit.org/code-style-guidelines/
FormatStyle getWebkitStyle();

/// Returns a format style complying with Microsoft's style guide:
/// https://docs.microsoft.com/en-us/visualstudio/ide/editorconfig-code-style-settings-reference
FormatStyle getMicrosoftStyle();
```

These options are also exposed in the {doc}`standalone tools <ClangFormat>`
through the `-style` option.

In the future, we plan on making this configurable.

---

### Clang Docs LibTooling (`clang/docs/LibTooling.md`)

# LibTooling

LibTooling is a library to support writing standalone tools based on Clang.
This document will provide a basic walkthrough of how to write a tool using
LibTooling.

For the information on how to setup Clang Tooling for LLVM see
{doc}`HowToSetupToolingForLLVM`

## Introduction

Tools built with LibTooling, like Clang Plugins, run `FrontendActions` over
code.

% See FIXME for a tutorial on how to write FrontendActions.

In this tutorial, we'll demonstrate the different ways of running Clang's
`SyntaxOnlyAction`, which runs a quick syntax check, over a bunch of code.

## Parsing a code snippet in memory

If you ever wanted to run a `FrontendAction` over some sample code, for
example to unit test parts of the Clang AST, `runToolOnCode` is what you
looked for. Let me give you an example:

```c++
#include "clang/Tooling/Tooling.h"

TEST(runToolOnCode, CanSyntaxCheckCode) {
  // runToolOnCode returns whether the action was correctly run over the
  // given code.
  EXPECT_TRUE(runToolOnCode(std::make_unique<clang::SyntaxOnlyAction>(), "class X {};"));
}
```

## Writing a standalone tool

Once you unit tested your `FrontendAction` to the point where it cannot
possibly break, it's time to create a standalone tool. For a standalone tool
to run clang, it first needs to figure out what command line arguments to use
for a specified file. To that end we create a `CompilationDatabase`. There
are different ways to create a compilation database, and we need to support all
of them depending on command-line options. There's the `CommonOptionsParser`
class that takes the responsibility to parse command-line parameters related to
compilation databases and inputs, so that all tools share the implementation.

### Parsing common tools options

`CompilationDatabase` can be read from a build directory or the command line.
Using `CommonOptionsParser` allows for explicit specification of a compile
command line, specification of build path using the `-p` command-line option,
and automatic location of the compilation database using source files paths.

```c++
#include "clang/Tooling/CommonOptionsParser.h"
#include "llvm/Support/CommandLine.h"

using namespace clang::tooling;
using namespace llvm;

// Apply a custom category to all command-line options so that they are the
// only ones displayed.
static cl::OptionCategory MyToolCategory("my-tool options");

int main(int argc, const char **argv) {
  // CommonOptionsParser::create will parse arguments and create a
  // CompilationDatabase.
  auto ExpectedParser = CommonOptionsParser::create(argc, argv, MyToolCategory);
  if (!ExpectedParser) {
    // Fail gracefully for unsupported options.
    llvm::errs() << toString(ExpectedParser.takeError());
    return 1;
  }
  CommonOptionsParser& OptionsParser = ExpectedParser.get();

  // Use OptionsParser.getCompilations() and OptionsParser.getSourcePathList()
  // to retrieve CompilationDatabase and the list of input file paths.
}
```

### Creating and running a ClangTool

Once we have a `CompilationDatabase`, we can create a `ClangTool` and run
our `FrontendAction` over some code. For example, to run the
`SyntaxOnlyAction` over the files "a.cc" and "b.cc" one would write:

```c++
// A clang tool can run over a number of sources in the same process...
std::vector<std::string> Sources;
Sources.push_back("a.cc");
Sources.push_back("b.cc");

// We hand the CompilationDatabase we created and the sources to run over into
// the tool constructor.
ClangTool Tool(OptionsParser.getCompilations(), Sources);

// The ClangTool needs a new FrontendAction for each translation unit we run
// on.  Thus, it takes a FrontendActionFactory as parameter.  To create a
// FrontendActionFactory from a given FrontendAction type, we call
// newFrontendActionFactory<clang::SyntaxOnlyAction>().
int result = Tool.run(newFrontendActionFactory<clang::SyntaxOnlyAction>().get());
```

### Putting it together --- the first tool

Now we combine the two previous steps into our first real tool. A more advanced
version of this example tool is also checked into the clang tree at
`tools/clang-check/ClangCheck.cpp`.

```c++
// Declares clang::SyntaxOnlyAction.
#include "clang/Frontend/FrontendActions.h"
#include "clang/Tooling/CommonOptionsParser.h"
#include "clang/Tooling/Tooling.h"
// Declares llvm::cl::extrahelp.
#include "llvm/Support/CommandLine.h"

using namespace clang::tooling;
using namespace llvm;

// Apply a custom category to all command-line options so that they are the
// only ones displayed.
static cl::OptionCategory MyToolCategory("my-tool options");

// CommonOptionsParser declares HelpMessage with a description of the common
// command-line options related to the compilation database and input files.
// It's nice to have this help message in all tools.
static cl::extrahelp CommonHelp(CommonOptionsParser::HelpMessage);

// A help message for this specific tool can be added afterwards.
static cl::extrahelp MoreHelp("\nMore help text...\n");

int main(int argc, const char **argv) {
  auto ExpectedParser = CommonOptionsParser::create(argc, argv, MyToolCategory);
  if (!ExpectedParser) {
    llvm::errs() << toString(ExpectedParser.takeError());
    return 1;
  }
  CommonOptionsParser& OptionsParser = ExpectedParser.get();
  ClangTool Tool(OptionsParser.getCompilations(),
                 OptionsParser.getSourcePathList());
  return Tool.run(newFrontendActionFactory<clang::SyntaxOnlyAction>().get());
}
```

### Running the tool on some code

When you check out and build clang, clang-check is already built and available
to you in bin/clang-check inside your build directory.

You can run clang-check on a file in the llvm repository by specifying all the
needed parameters after a "`--`" separator:

```bash
$ cd /path/to/source/llvm
$ export BD=/path/to/build/llvm
$ $BD/bin/clang-check tools/clang/tools/clang-check/ClangCheck.cpp -- \
      clang++ -D__STDC_CONSTANT_MACROS -D__STDC_LIMIT_MACROS \
      -Itools/clang/include -I$BD/include -Iinclude \
      -Itools/clang/lib/Headers -c
```

As an alternative, you can also configure cmake to output a compile command
database into its build directory:

```bash
# Alternatively to calling cmake, use ccmake, toggle to advanced mode and
# set the parameter CMAKE_EXPORT_COMPILE_COMMANDS from the UI.
$ cmake -DCMAKE_EXPORT_COMPILE_COMMANDS=ON .
```

This creates a file called `compile_commands.json` in the build directory.
Now you can run {program}`clang-check` over files in the project by specifying
the build path as first argument and some source files as further positional
arguments:

```bash
$ cd /path/to/source/llvm
$ export BD=/path/to/build/llvm
$ $BD/bin/clang-check -p $BD tools/clang/tools/clang-check/ClangCheck.cpp
```

(libtooling_builtin_includes)=

### Builtin includes

Clang tools need their builtin headers and search for them the same way Clang
does. Thus, the default location to look for builtin headers is in a path
`$(dirname /path/to/tool)/../lib/clang/3.3/include` relative to the tool
binary. This works out-of-the-box for tools running from llvm's toplevel
binary directory after building clang-resource-headers, or if the tool is
running from the binary directory of a clang install next to the clang binary.

Tips: if your tool fails to find `stddef.h` or similar headers, call the tool
with `-v` and look at the search paths it looks through.

### Linking

For a list of libraries to link, look at one of the tools' CMake files (for
example [clang-check/CMakeList.txt](https://github.com/llvm/llvm-project/blob/main/clang/tools/clang-check/CMakeLists.txt)).

---

### Clang Docs LifetimeSafety (`clang/docs/LifetimeSafety.md`)

# Lifetime Safety Analysis


## Introduction

Clang Lifetime Safety Analysis is a C and C++ language extension which warns about
potential dangling pointer defects in code. The analysis aims to detect
when a pointer, reference or view type (such as `std::string_view`) refers to an object
that is no longer alive, a condition that leads to use-after-free bugs and
security vulnerabilities. Common examples include pointers to stack variables
that have gone out of scope, pointers to heap objects that have been
freed, fields holding views to stack-allocated objects (dangling-field),
returning pointers/references to stack variables (return stack address) or
iterators into container elements invalidated by container operations (e.g.,
`std::vector::push_back`)

The analysis design is inspired by [Polonius, the Rust borrow checker](https://github.com/rust-lang/polonius),
but adapted to C++ idioms and constraints, such as the lack of exclusivity enforcement (alias-xor-mutability).
Further details on the analysis method can be found in the [RFC on Discourse](https://discourse.llvm.org/t/rfc-intra-procedural-lifetime-analysis-in-clang/86291/).

This is compile-time analysis; there is no run-time overhead.
It tracks pointer validity through intra-procedural data-flow analysis. While it does
not require lifetime annotations to get started, in their absence, the analysis
treats function calls optimistically, assuming no lifetime effects, thereby potentially missing dangling pointer issues. As more functions are annotated
with attributes like [clang::lifetimebound](AttributeReference.md#lifetimebound), [gsl::Owner](AttributeReference.md#owner), and
[gsl::Pointer](AttributeReference.md#pointer), the analysis can see through these lifetime contracts and enforce
lifetime safety at call sites with higher accuracy. This approach supports
gradual adoption in existing codebases.

:::{note}
This analysis is designed for bug finding, not verification. It may miss some
lifetime issues and can produce false positives. It does not guarantee the
absence of all lifetime bugs.
:::

### Getting Started

```c++
#include <string>
#include <string_view>

void simple_dangle() {
  std::string_view v;
  {
    std::string s = "hello";
    v = s;  // warning: object whose reference is captured does not live long enough
  }         // note: destroyed here
  std::cout << v; // note: later used here
}
```

This example demonstrates
a basic use-after-scope bug. The `std::string_view` object `v` holds a
reference to `s`, a `std::string`. The lifetime of `s` ends at the end of
the inner block, causing `v` to become a dangling reference.
The analysis flags the assignment `v = s` as defective because `s` is
destroyed while `v` is still alive and points to `s`, and adds a note
to where `v` is used after `s` has been destroyed.

```c
#include <stdio.h>
void simple_dangle() {
  int *ptr = NULL;
  {
    int i = 5;
    ptr = &i;   // warning: local variable 'i' does not live long enough
  }             // note: local variable 'i' is destroyed here
  *ptr = 6;     // note: later used here
}
```

This example demonstrates a simples use-after-scope bug in C. The `ptr` pointer
is set to `NULL` in the outer scope. In the inner scope ptr points to `i`, but
its lifetime ends at the end of the inner block which causes `ptr` to dangle
when it is set to 6.


### Running The Analysis

To run the analysis, compile with the `-Wlifetime-safety-permissive` flag, e.g.

```bash
clang -c -Wlifetime-safety-permissive example.cpp
```

This flag enables a core set of lifetime safety checks. For more fine-grained
control over warnings, see {ref}`warning_flags`. The analysis runs for both
C and C++ by default. Use `-fno-lifetime-safety-c` to disable the analysis
for C code.

## Lifetime Annotations

While lifetime analysis can detect many issues without annotations, its
precision increases significantly when types and functions are annotated with
lifetime contracts. These annotations clarify ownership semantics and lifetime
dependencies, enabling the analysis to reason more accurately about pointer
validity across function calls.

### Owner and Pointer Types

Lifetime analysis distinguishes between types that own the data they point to
(Owners) and types that are non-owning views or references to data owned by
others (Pointers). This distinction is made using GSL-style attributes:

- `[[gsl::Owner]]`: For types that manage the lifetime of a resource,
  like `std::string`, `std::vector`, `std::unique_ptr`.
- `[[gsl::Pointer]]`: For non-owning types that borrow resources,
  like `std::string_view`, or raw pointers (which are
  implicitly treated as pointers).

Many common STL types, such as `std::string_view` and container iterators,
are automatically recognized as Pointers or Owners. You can annotate your own
types using these attributes:

```c++
#include <string>
#include <string_view>

// Owner type
struct [[gsl::Owner]] MyObj {
  std::string Data = "Hello";
};

// View type
struct [[gsl::Pointer]] View {
  std::string_view SV;
  View() = default;
  View(const MyObj& O) : SV(O.Data) {}
  void use() const {}
};

void test() {
  View v;
  {
    MyObj o;
    v = o; // warning: object whose reference is captured does not live long enough
  }        // note: destroyed here
  v.use(); // note: later used here
}
```

Without these annotations, the analysis may not be able to determine whether a
type is owning or borrowing, which can affect analysis precision. For more
details on these attributes, see the Clang attribute reference for
[gsl::Owner](AttributeReference.md#owner) and
[gsl::Pointer](AttributeReference.md#pointer).

:::{note}
Types with mixed ownership semantics (owning some data while holding views to
other data) or types with multiple view fields with different lifetimes should
not be annotated. The analysis does not yet support expressing such nuanced
lifetime relationships.
Future enhancements, such as named lifetimes, may provide better support for
these patterns.
:::

### LifetimeBound

The `[[clang::lifetimebound]]` attribute can be applied to function parameters
or to the implicit `this` parameter of a method (by placing it after the
method declarator). It indicates that the returned value becomes invalid when
the attributed parameter or `this` object is destroyed.
This is crucial for functions that return views or references to their
arguments.

```c++
#include <string>
#include <string_view>

struct MyOwner {
  std::string s;
  std::string_view getView() const [[clang::lifetimebound]] { return s; }
};

void test_lifetimebound() {
  std::string_view sv;
  sv = MyOwner().getView(); // getView() is called on a temporary MyOwner
                           // warning: object whose reference is captured does not live long enough
                           // note: destroyed here
  (void)sv;                // note: later used here
}
```

Without `[[clang::lifetimebound]]` on `getView()`, the analysis would not
know that the value returned by `getView()` depends on the temporary
`MyOwner` object, and it would not be able to diagnose the dangling `sv`.

The analysis also tracks record types returned from functions and constructors
with `[[clang::lifetimebound]]` annotated parameters:

```c++
#include <string>

struct StringView {
  StringView();
  StringView(const std::string &s [[clang::lifetimebound]]);
};

StringView getStringView(const std::string &s [[clang::lifetimebound]]);

void test() {
  StringView a, b;
  {
    std::string s = "temp";
    StringView tmp(s);    // warning: object whose reference is captured does not live long enough
    a = tmp;
    b = getStringView(s); // warning: object whose reference is captured does not live long enough
  }                       // note: destroyed here
  (void)a;                // note: later used here
  (void)b;                // note: later used here
}
```

For more details, see [lifetimebound](AttributeReference.md#lifetimebound).

### NoEscape

(wlifetime-safety-noescape)=

The `[[clang::noescape]]` attribute can be applied to function parameters of
pointer or reference type. It indicates that the function will not allow the
parameter to escape its scope, for example, by returning it or assigning it to
a field or global variable. This is useful for parameters passed to callbacks
or visitors that are only used during the call and not stored.

For more details, see [noescape](AttributeReference.md#noescape).

## Checks Performed

### Use after scope

This check warns when a pointer or reference is used after the stack variable
it refers to has gone out of scope.

````{list-table}
:widths: 50 50
:header-rows: 1
:class: colored-code-table

* - Use after scope
  - Correct
* -
    ```c++
    void foo() {
      int* p;
      {
        int i = 0;
        p = &i;  // warning: 'p' does not live long enough
      }          // note: destroyed here
      (void)*p;  // note: later used here
    }
    ```
  -
    ```c++
    void foo() {
      int i = 0;
      int* p;
      {
        p = &i; // OK!
      }
      (void)*p;
     }
    ```
````

### Use after free

This check warns when a pointer or reference is used after the object it refers
to has been freed.

````{list-table}
:widths: 50 50
:header-rows: 1
:class: colored-code-table

* - Use after free
  - Correct
* -
    ```c++
    void foo() {
      int *p = new int(0); // warning: allocated object does not live long enough
      delete p;            // note: freed here
      (void)*p;            // note: later used here
    }
    ```
  -
    ```c++
    void foo() {
      int *p = new int(0);
      (void)*p;
      delete p; // OK!
    }
    ```
````

### Return of stack address

This check warns when a function returns a pointer or reference to a
stack-allocated variable, which will be destroyed when the function returns,
leaving the caller with a dangling pointer.

````{list-table}
:widths: 50 50
:header-rows: 1
:class: colored-code-table

* - Return of stack address
  - Correct
* -
    ```c++
    #include <string>
    #include <string_view>

    std::string_view bar() {
      std::string s = "on stack";
      std::string_view result = s;
      // warning: address of stack variable 's' is returned later
      return result; // note: returned here
    }
    ```
  -
    ```c++
    #include <string>
    #include <string_view>

    std::string bar() {
      std::string s = "on stack";
      std::string_view result = s;
      return result; // OK!
    }
    ```
````

### Dangling field

This check warns when a constructor or method assigns a pointer to a
stack-allocated variable or temporary to a field of the class.

````{list-table}
:widths: 50 50
:header-rows: 1
:class: colored-code-table

* - Dangling field
  - Correct
* -
    ```c++
    #include <string>
    #include <string_view>

    // Constructor finishes, leaving 'field' dangling.
    struct DanglingField {
      std::string_view field; // note: this field dangles
      DanglingField(std::string s) {
        field = s; // warning: stack variable 's' escapes to a field
      }
    };
    ```
  -
    ```c++
    // Make the field an owner.
    struct DanglingField {
      std::string field;
      DanglingField(std::string s) {
        field = s;
      }
    };
    // Or take a string_view parameter.
    struct DanglingField {
      std::string_view field;
      DanglingField(std::string_view s [[clang::lifetimebound]]) {
        field = s;
      }
    };
    };
    ```
````

### Use after invalidation (experimental)

This check warns when a pointer, reference or view is used after an operation
that may have invalidated it. This includes references to container elements
used after a container operation, and pointers to objects managed by owners such
as `std::unique_ptr` after operations like `reset`. For example, adding
elements to `std::vector` may cause reallocation, invalidating all existing
iterators, pointers and references to its elements.

:::{note}
Invalidation checking is highly experimental and may produce false positives.
:::

````{list-table}
:widths: 50 50
:header-rows: 1
:class: colored-code-table

* - Use after invalidation (experimental)
  - Correct
* -
    ```c++
    #include <vector>

    void baz(std::vector<int>& v) {
      int* p = &v[0]; // warning: 'v' is later invalidated
      v.push_back(4); // note: invalidated here
      *p = 10;        // note: later used here
    }
    ```
  -
    ```c++
    #include <vector>

    void baz(std::vector<int>& v) {
      v.push_back(4);
      int* p = &v[0]; // OK!
      *p = 10;
    }
    ```
````

The analysis also treats explicit destruction as invalidation. Explicit
destructor calls and `std::destroy_at` invalidate pointers, references and
views into the destroyed object.

```c++
#include <memory>
#include <string>

void explicit_destruction() {
  std::string s = "hello";
  const char *p = s.data(); // warning: object whose reference is captured is later invalidated
  std::destroy_at(&s);      // note: invalidated here
  (void)*p;                 // note: later used here
}

void unique_ptr_reset() {
  std::unique_ptr<int> u(new int(0));
  int *p = u.get(); // warning: object whose reference is captured is later invalidated
  u.reset();        // note: invalidated here
  (void)*p;         // note: later used here
}
```

## Annotation Inference and Suggestions

In addition to detecting lifetime violations, the analysis can suggest adding
`[[clang::lifetimebound]]` to function parameters or methods when it detects
that a pointer/reference to a parameter or `this` escapes via the return
value. This helps improve API contracts and allows the analysis to perform
more accurate checks in calling code.

To enable annotation suggestions, use `-Wlifetime-safety-suggestions`.

Fix-it hints normally insert `[[clang::lifetimebound]]`. If a visible
object-like macro expands to `[[clang::lifetimebound]]` or
`__attribute__((lifetimebound))`, Clang will use the last such macro
visible at the insertion point. To force a project-specific macro spelling,
use `-lifetime-safety-lifetimebound-macro=<macro>`.

```c++
#include <string_view>

// The analysis will suggest adding [[clang::lifetimebound]] to 'a'.
std::string_view return_view(std::string_view a) {
                          // ^^^^^^^^^^^^^^^^^^
                          // warning: parameter 'a' should be marked [[clang::lifetimebound]]
  return a;               // note: param returned here
}
```

### Translation-Unit-Wide Analysis and Inference

By default, lifetime analysis is intra-procedural for error checking.
However, for annotation inference to be effective, lifetime information needs
to propagate across function calls. You can enable experimental
translation-unit-wide analysis using:

- `-flifetime-safety-inference`: Enables inference of `lifetimebound`
  attributes across functions in a TU.
- `-fexperimental-lifetime-safety-tu-analysis`: Enables TU-wide analysis
  for better inference results.

(warning_flags)=
(warning-flags)=

## Warning flags

Lifetime safety warnings are organized into hierarchical groups, allowing users to
enable categories of checks incrementally. For example, `-Wlifetime-safety`
enables all dangling pointer checks, while `-Wlifetime-safety-permissive`
enables only the high-confidence subset of these checks.

- `-Wlifetime-safety-all`: Enables all lifetime safety warnings, including dangling pointer checks, annotation suggestions, and annotation validations.
- `-Wlifetime-safety`: Enables dangling pointer checks from both the `permissive` and `strict` groups listed below.

  - `-Wlifetime-safety-permissive`: Enables high-confidence checks for dangling pointers. **Recommended for initial adoption.**

    - `-Wlifetime-safety-use-after-scope`: Warns when a pointer to a stack variable is used after the variable's lifetime has ended.
    - `-Wlifetime-safety-use-after-free`: Warns when a pointer to an object is used after it's been freed.
    - `-Wlifetime-safety-return-stack-addr`: Warns when a function returns a pointer or reference to one of its local stack variables.
    - `-Wlifetime-safety-dangling-field`: Warns when a class field is assigned a pointer to a temporary or stack variable whose lifetime is shorter than the class instance.

  - `-Wlifetime-safety-strict`: Enables stricter and experimental checks. These may produce false positives in code that uses move semantics heavily, as the analysis might conservatively assume a use-after-free even if ownership was transferred.

    - `-Wlifetime-safety-use-after-scope-moved`: Same as `-Wlifetime-safety-use-after-scope` but for cases where the variable may have been moved from before its destruction.
    - `-Wlifetime-safety-return-stack-addr-moved`: Same as `-Wlifetime-safety-return-stack-addr` but for cases where the variable may have been moved from.
    - `-Wlifetime-safety-dangling-field-moved`: Same as `-Wlifetime-safety-dangling-field` but for cases where the variable may have been moved from.
    - `-Wlifetime-safety-invalidation`: Warns when a pointer, reference, iterator or view is used after an operation that may invalidate it, such as container mutation or explicit destruction (e.g., `std::unique_ptr::reset`, `std::destroy_at`) (Experimental).

- `-Wlifetime-safety-suggestions`: Enables suggestions to add `[[clang::lifetimebound]]` to function parameters and `this` parameters.

  - `-Wlifetime-safety-intra-tu-suggestions`: Suggestions for functions local to the translation unit.
    - `-Wlifetime-safety-intra-tu-constructor-suggestions`: Suggestions for constructors local to the translation unit.
  - `-Wlifetime-safety-cross-tu-suggestions`: Suggestions for functions visible across translation units (e.g., in headers).
    - `-Wlifetime-safety-cross-tu-constructor-suggestions`: Suggestions for constructors visible across translation units.

- `-Wlifetime-safety-validations`: Enables checks that validate existing lifetime annotations.

  - `-Wlifetime-safety-noescape`: Warns when a parameter marked with `[[clang::noescape]]` escapes the function.
  - `-Wlifetime-safety-lifetimebound-violation`: Warns when the analysis cannot verify that the return value can be lifetime bound to a parameter marked with `[[clang::lifetimebound]]`.

## Limitations

### Move Semantics

The analysis does not currently track ownership transfers through move operations.
Instead, it uses scope-based lifetime tracking: when an owner goes out of scope,
the analysis assumes the resource is destroyed, even if ownership was transferred
via `std::move()` or `std::unique_ptr::release()`.

This means that if a pointer or view is created from an owner, and that owner is
later moved-from and goes out of scope, the analysis will issue a
`-Wlifetime-safety-*-moved` warning. This warning indicates that the pointer
may be dangling, even though the resource may still be alive under a new owner.
These are often false positives when ownership has been safely transferred.

To avoid these warnings and ensure correctness, follow the
**"move-first-then-alias"** pattern: create views or raw pointers *after* the
ownership transfer, sourcing them from the new owner rather than the original
owner that will go out of scope.

For example:

````{list-table}
:widths: 50 50
:header-rows: 1
:align: left
:class: colored-code-table

* - Anti-Pattern: Aliasing Before Move
  - Good Practice: Move-First-Then-Alias
* -
    ```c++
    #include <memory>

    void use(int*);

    void bar() {
      std::unique_ptr<int> b;
      int* p;
      {
        auto a = std::make_unique<int>(42);
        p = a.get(); // warning!
        b = std::move(a);
      }
      use(p);
    }
    ```
  -
    ```c++
    #include <memory>

    void use(int*);

    void bar() {
      std::unique_ptr<int> b;
      int* p;
      {
        auto a = std::make_unique<int>(42);
        b = std::move(a);
        p = b.get(); // OK!
      }
      use(p);
    }
    ```
````

The same principle applies when moving ownership using `std::unique_ptr::release()`:

```{code-block} c++
:class: bad-code

#include <memory>
#include <utility>

void use(int*);
void take_ownership(int*);

void test_aliasing_before_release() {
  int* p;
  {
    auto u = std::make_unique<int>(1);
    p = u.get();
    //  ^ warning: 'u' does not live long enough!
    take_ownership(u.release());
  }
  use(p);
}
```

### `std::unique_ptr` with custom deleters

The analysis assumes standard ownership semantics for owner types like
`std::unique_ptr`: when a `unique_ptr` goes out of scope, it is assumed
that the owned object is destroyed and its memory is deallocated.
However, `std::unique_ptr` can be used with a custom deleter that modifies
this behavior. For example, a custom deleter might keep the memory alive
by transferring it to a memory pool, or simply do nothing, allowing
another system to manage the lifetime.

Because the analysis relies on scope-based lifetime for owners, it does not
support custom deleters that extend the lifetime of the owned object beyond
the lifetime of the `std::unique_ptr`. In such cases, the analysis will
assume the object is destroyed when the `std::unique_ptr` goes out of scope,
leading to false positive warnings if pointers to the object are used afterward.

```c++
#include <memory>

void use(int*);

struct NoOpDeleter {
  void operator()(int* p) const {
    // Do not delete p, memory is managed elsewhere.
  }
};

void test_custom_deleter() {
  int* p;
  {
    std::unique_ptr<int, NoOpDeleter> u(new int(42));
    p = u.get();  // warning: object whose reference is captured does not live long enough
  }               // note: destroyed here
  // With NoOpDeleter, p would still be valid here.
  // But analysis assumes standard unique_ptr semantics and memory being freed.
  use(p);         // note: later used here
}
```

### Dangling Fields

The lifetime analysis is intra-procedural. It analyzes one function or method at
a time.
This means if a field is assigned a pointer to a local variable or temporary
inside a constructor or method, and that local's lifetime ends before the method
returns, the analysis will issue a `-Wlifetime-safety-dangling-field` warning.
It must do so even if no *other* method of the class ever accesses this field,
because it cannot see how other methods are implemented or used.

```c++
#include <string>
#include <string_view>

struct MyWidget {
  std::string_view name_; // note: this field dangles
  MyWidget(std::string name) : name_(name) {} // warning: address of stack memory escapes to a field
  const char* data() { return name_.data(); } // Potential use-after-free if called
};
```

In this case, `name_` dangles after the constructor finishes.
Even if `data()` is never called, the analysis flags the dangling assignment
in the constructor because it represents a latent bug.
The recommended approach is to ensure fields only point to objects that outlive
the field itself, for example by storing an owned object (e.g., `std::string`)
or ensuring the borrowed object (e.g., one passed by `const&`) has a
sufficient lifetime.

## Performance

Lifetime analysis relies on Clang's CFG (Control Flow Graph). For functions
with very large or complex CFGs, analysis time can sometimes be significant. To mitigate
this, the analysis allows to skip functions where the number of CFG blocks exceeds
a certain threshold, controlled by the `-lifetime-safety-max-cfg-blocks=N` language
option.

---

--- METRICS ---
- Files Extracted: 100
- Estimated Token Budget: ~421265 tokens
- Canonical Reference: https://codewiki.google/github.com/llvm/llvm-project
