# LLVM Project User Guide

The **LLVM Project** is a collection of modular and reusable compiler and
toolchain technologies. Despite its name, "LLVM" is not a single program — it is
a **monorepo** that builds a complete, production-grade compiler ecosystem:
the Clang C/C++/Objective-C compiler, the LLD linker, the LLDB debugger, the
libc++ standard library, MLIR, Flang (Fortran), and dozens of standalone
command-line tools for assembling, optimizing, analyzing, and transforming code.

This guide shows you how to **get** LLVM, how to **build** it from source, and
how to **use** its compilers and tools day-to-day. It is written against the
source tree at commit `53cbf88b6` and reflects what the code in this repository
actually does.

> [!NOTE]
> "LLVM" means three different things depending on context: (1) the umbrella
> **project**, (2) the **core libraries** for IR processing and code generation,
> and (3) the **intermediate representation (IR)** itself. This guide always
> says "the LLVM Project" for the umbrella and "LLVM Core" for the libraries.

---

## Table of Contents

1. [Quick Start](#1-quick-start)
2. [What Is the LLVM Project?](#2-what-is-the-llvm-project)
3. [Installation](#3-installation)
4. [Building LLVM from Source](#4-building-llvm-from-source)
5. [Compiling Code with Clang](#5-compiling-code-with-clang)
6. [The LLVM Core Tool Suite](#6-the-llvm-core-tool-suite)
7. [Developer Tooling (clang-format, clang-tidy, clangd)](#7-developer-tooling)
8. [Linking with LLD](#8-linking-with-lld)
9. [Debugging with LLDB](#9-debugging-with-lldb)
10. [Finding Bugs with Sanitizers](#10-finding-bugs-with-sanitizers)
11. [Working with LLVM IR](#11-working-with-llvm-ir)
12. [Advanced Workflows](#12-advanced-workflows)
13. [How LLVM Works (Concepts)](#13-how-llvm-works-concepts)
14. [Troubleshooting](#14-troubleshooting)
15. [Frequently Asked Questions](#15-frequently-asked-questions)
16. [Reference](#16-reference)

---

## 1. Quick Start

The fastest way to start using LLVM is to install a **prebuilt** Clang toolchain,
then compile a program.

=== "Linux (apt)"

    ```bash
    sudo apt-get update
    sudo apt-get install -y clang lld lldb
    clang --version
    ```

=== "macOS (Homebrew)"

    ```bash
    brew install llvm
    # Homebrew keeps LLVM keg-only; add it to PATH for this shell:
    export PATH="$(brew --prefix llvm)/bin:$PATH"
    clang --version
    ```

=== "Windows (winget)"

    ```powershell
    winget install LLVM.LLVM
    clang --version
    ```

Compile and run a first program:

```bash
cat > hello.c <<'EOF'
#include <stdio.h>
int main(void) { puts("Hello from Clang!"); return 0; }
EOF

clang -O2 hello.c -o hello
./hello
```

```text
Hello from Clang!
```

> [!TIP]
> If you only need a compiler, use the prebuilt packages above. Build from
> source (Section 4) only when you need a specific version, custom targets,
> experimental features, or you are developing LLVM itself.

---

## 2. What Is the LLVM Project?

The repository is a **monorepo** containing several top-level components. They
fall into two groups based on how they are enabled at build time: **projects**
(built with `LLVM_ENABLE_PROJECTS`) and **runtimes** (built with
`LLVM_ENABLE_RUNTIMES`).

### Core and projects

| Component | What it is | Typical user-facing tools |
|-----------|-----------|---------------------------|
| **LLVM Core** (`llvm/`) | The libraries, IR, optimizer, and code generators that everything else builds on | `opt`, `llc`, `lli`, `llvm-as`, `llvm-dis`, plus ~80 `llvm-*` utilities |
| **Clang** (`clang/`) | C, C++, Objective-C, and Objective-C++ frontend and compiler driver | `clang`, `clang++` |
| **Clang Tools Extra** (`clang-tools-extra/`) | Standalone developer tools built on Clang's libraries | `clang-tidy`, `clangd`, `clang-doc`, `clang-include-fixer` |
| **LLD** (`lld/`) | A fast, drop-in linker for ELF, COFF, Mach-O, and WebAssembly | `lld`, `ld.lld`, `lld-link`, `wasm-ld` |
| **LLDB** (`lldb/`) | A modern, scriptable source-level debugger | `lldb`, `lldb-server`, `lldb-dap` |
| **MLIR** (`mlir/`) | Multi-Level Intermediate Representation — a framework for building domain-specific compilers and IRs | `mlir-opt`, `mlir-translate` |
| **Flang** (`flang/`) | A Fortran frontend and compiler | `flang` |
| **BOLT** (`bolt/`) | Post-link binary optimizer that improves layout using profile data | `llvm-bolt` |
| **Polly** (`polly/`) | Polyhedral loop optimizer (cache locality, auto-parallelization) | (integrated into `opt`/`clang`) |

> [!NOTE]
> The set of "all" projects in this revision is exactly:
> `bolt`, `clang`, `clang-tools-extra`, `cross-project-tests`, `lld`, `lldb`,
> `mlir`, `polly`. `flang`, `libc`, and `compiler-rt` are *extra* projects that
> are preferably enabled as **runtimes** instead (see below).

### Runtimes

Runtime libraries are compiled *by* the just-built compiler so they match the
target you are producing code for. The default set is `libcxx`, `libcxxabi`,
`libunwind`, `libclc`, `compiler-rt`, and `openmp`.

| Runtime | What it provides |
|---------|------------------|
| **libc++** (`libcxx/`) | LLVM's implementation of the C++ standard library |
| **libc++abi** (`libcxxabi/`) | The low-level C++ ABI support library (exceptions, RTTI, demangling) |
| **libunwind** (`libunwind/`) | An implementation of the stack unwinder used for exceptions |
| **compiler-rt** (`compiler-rt/`) | Compiler runtime: builtins, profiling, and the sanitizers (ASan, TSan, MSan, UBSan) |
| **OpenMP** (`openmp/`) | The OpenMP runtime for parallel and offloaded code |
| **libc** (`libc/`) | LLVM's C standard library implementation |
| **libclc** (`libclc/`) | OpenCL C library |
| **offload** (`offload/`) | GPU/accelerator offload runtime |
| **flang-rt** (`flang-rt/`) | The Fortran runtime library |
| **libsycl**, **orc-rt**, **llvm-libgcc** | SYCL support, ORC JIT runtime, and a libgcc-compatible runtime |

The complete list of supported runtimes in this revision is: `libc`,
`libunwind`, `libcxxabi`, `libcxx`, `compiler-rt`, `openmp`, `llvm-libgcc`,
`offload`, `flang-rt`, `libclc`, `libsycl`, `orc-rt`.

> [!IMPORTANT]
> You do **not** have to build everything. Most users enable only the projects
> and runtimes they need. Building Clang alone is far faster than building the
> entire monorepo.

---

## 3. Installation

You have three options, in increasing order of effort: prebuilt packages,
official release binaries, or building from source (Section 4).

### Option A — System package manager (recommended)

=== "Ubuntu / Debian"

    ```bash
    # Distro packages:
    sudo apt-get install -y clang lld lldb llvm
    # Or the official LLVM apt repository for the latest release:
    bash -c "$(wget -O - https://apt.llvm.org/llvm.sh)"
    ```

=== "Fedora / RHEL"

    ```bash
    sudo dnf install -y clang lld lldb llvm
    ```

=== "Arch Linux"

    ```bash
    sudo pacman -S llvm clang lld lldb
    ```

=== "macOS"

    ```bash
    brew install llvm
    export PATH="$(brew --prefix llvm)/bin:$PATH"
    ```

=== "Windows"

    ```powershell
    winget install LLVM.LLVM
    # or: choco install llvm
    ```

### Option B — Official release binaries

Prebuilt binaries for every release are published on the project's GitHub
releases page, linked from [llvm.org](https://llvm.org). Download the archive
for your platform, extract it, and add its `bin/` directory to your `PATH`.

```bash
# Example shape (replace with the version/platform you downloaded):
tar xf clang+llvm-*-x86_64-linux-gnu.tar.xz
export PATH="$PWD/clang+llvm-*/bin:$PATH"
clang --version
```

### Verify your installation

```bash
clang --version
llvm-config --version    # prints the LLVM version of your toolchain
lld --version
```

```text
clang version 21.x.x
...
```

> [!TIP]
> `llvm-config` is the canonical way to discover where headers, libraries, and
> the version of an installed LLVM live. Tools and build systems use it to
> link against LLVM.

---

## 4. Building LLVM from Source

Building from source is a first-class workflow for LLVM users. Everything in
this section is grounded in the repository's `llvm/CMakeLists.txt`.

### Prerequisites

| Requirement | Minimum | Notes |
|-------------|---------|-------|
| **CMake** | `3.20.0` | Declared by `cmake_minimum_required(VERSION 3.20.0)` |
| **C++ host compiler** | C++17 capable | `LLVM_REQUIRED_CXX_STANDARD` is `17`; configuration **fails** if you force a lower `CMAKE_CXX_STANDARD` |
| **Build tool** | Ninja (recommended) or Make | Ninja gives the fastest incremental builds |
| **Python** | 3.x | Required to run the test suites and many helper scripts |
| **Disk** | 20–100+ GB | A full monorepo build with debug info is very large |
| **RAM** | 16+ GB recommended | Linking debug binaries is memory-hungry; see the link-jobs tip below |

> [!CAUTION]
> A full, debug build of the entire monorepo can consume **tens of gigabytes**
> of RAM during linking and **100+ GB** of disk. If you hit out-of-memory
> errors while linking, reduce parallel link jobs (see Troubleshooting).

### Get the source

```bash
git clone https://github.com/llvm/llvm-project.git
cd llvm-project
```

> [!TIP]
> For a faster, smaller checkout when you do not need full history, use a
> shallow clone: `git clone --depth=1 https://github.com/llvm/llvm-project.git`.

### Configure, build, and install

The build is always rooted at the **`llvm`** subdirectory. Select components
with `-DLLVM_ENABLE_PROJECTS` and `-DLLVM_ENABLE_RUNTIMES`.

```bash
cmake -S llvm -B build -G Ninja \
  -DCMAKE_BUILD_TYPE=Release \
  -DLLVM_ENABLE_PROJECTS="clang;lld" \
  -DLLVM_ENABLE_RUNTIMES="libcxx;libcxxabi;libunwind" \
  -DLLVM_TARGETS_TO_BUILD="host" \
  -DCMAKE_INSTALL_PREFIX="$HOME/llvm-install"

ninja -C build
ninja -C build install
```

```text
[1/4231] Building CXX object ...
...
[4231/4231] Linking CXX executable bin/clang-21
```

> [!NOTE]
> `LLVM_TARGETS_TO_BUILD="host"` builds only the backend for your current
> machine, which is dramatically faster than the default `"all"`. Use `"all"`
> only when you need cross-compilation to other architectures.

### Selecting components

```bash
# Just the C/C++ compiler:
-DLLVM_ENABLE_PROJECTS="clang"

# A self-hosting C++ toolchain (compiler + linker + standard library):
-DLLVM_ENABLE_PROJECTS="clang;lld" \
-DLLVM_ENABLE_RUNTIMES="libcxx;libcxxabi;libunwind;compiler-rt"

# Everything (slow, large):
-DLLVM_ENABLE_PROJECTS="all"
```

> [!WARNING]
> `LLVM_ENABLE_PROJECTS=openmp` has been **removed**. OpenMP must be enabled as
> a runtime (`-DLLVM_ENABLE_RUNTIMES="openmp"`), not a project. Configuration
> aborts with a fatal error if you try the old form.

### Build types

`CMAKE_BUILD_TYPE` controls optimization and debug info, and indirectly
controls assertions:

| `CMAKE_BUILD_TYPE` | Speed | Size | Assertions default |
|--------------------|-------|------|--------------------|
| `Release` | Fast | Small | **OFF** |
| `Debug` | Slow | Huge | **ON** |
| `RelWithDebInfo` | Fast + debuggable | Large | ON |
| `MinSizeRel` | Optimized for size | Smallest | OFF |

> [!TIP]
> Assertions are controlled by `LLVM_ENABLE_ASSERTIONS`, which defaults to
> `ON` for non-`Release` builds and `OFF` for `Release`. Keep assertions on
> while developing LLVM — they catch invariant violations early.

### Faster builds

```bash
# Use ccache to cache compilation results across rebuilds:
-DLLVM_CCACHE_BUILD=ON

# Build TableGen with optimization even in Debug builds (speeds up codegen):
-DLLVM_OPTIMIZED_TABLEGEN=ON

# Use lld to link (much faster than the system linker):
-DLLVM_ENABLE_LLD=ON

# Limit parallel link jobs to avoid running out of RAM:
-DLLVM_PARALLEL_LINK_JOBS=2
```

A common, fast developer configuration:

```bash
cmake -S llvm -B build -G Ninja \
  -DCMAKE_BUILD_TYPE=Release \
  -DLLVM_ENABLE_PROJECTS="clang;lld" \
  -DLLVM_TARGETS_TO_BUILD="host" \
  -DLLVM_ENABLE_ASSERTIONS=ON \
  -DLLVM_OPTIMIZED_TABLEGEN=ON \
  -DLLVM_CCACHE_BUILD=ON \
  -DLLVM_USE_LINKER=lld
```

### Run the tests

```bash
# Run LLVM's lit-based regression tests:
ninja -C build check-llvm

# Run only Clang's tests:
ninja -C build check-clang
```

> [!TIP]
> Each project exposes a `check-<project>` target (`check-llvm`, `check-clang`,
> `check-lld`, `check-mlir`, …). These run the `lit` test runner over the
> project's test suite.

See the full [Getting Started with LLVM](https://llvm.org/docs/GettingStarted.html#getting-the-source-code-and-building-llvm)
page for platform-specific notes and bootstrap builds.

---

## 5. Compiling Code with Clang

Clang is a drop-in replacement for GCC's command-line interface, so most flags
you already know work unchanged.

### Everyday compilation

```bash
# Compile a C program with optimization:
clang -O2 main.c -o main

# Compile C++ to a named binary, choosing a language standard:
clang++ -std=c++20 -O2 app.cpp -o app

# Compile to an object file only (no link):
clang -c module.c -o module.o

# Emit warnings aggressively:
clang -Wall -Wextra -Werror -O2 main.c -o main
```

### Common driver flags

| Flag | Purpose |
|------|---------|
| `-O0` / `-O1` / `-O2` / `-O3` | Optimization level (none → aggressive) |
| `-Os` / `-Oz` | Optimize for size / aggressively for size |
| `-g` | Emit debug information |
| `-c` | Compile only; do not link |
| `-S` | Emit assembly instead of an object file |
| `-emit-llvm` | Emit LLVM IR (`.ll` with `-S`, `.bc` with `-c`) |
| `-std=<std>` | Language standard (`c11`, `c17`, `c++17`, `c++20`, `c++23`, …) |
| `-target <triple>` | Cross-compile for the given target triple |
| `-fsanitize=<check>` | Enable a sanitizer (see Section 10) |
| `-I<dir>` / `-L<dir>` / `-l<lib>` | Add include dir / library dir / link a library |

> [!NOTE]
> `clang` and `clang++` are the same binary; the `++` form turns on C++ mode and
> links the C++ standard library automatically. Use `clang++` for C++ sources.

### Choosing the standard library (C++)

```bash
# Use LLVM's libc++ instead of the system libstdc++:
clang++ -stdlib=libc++ -std=c++20 app.cpp -o app
```

> [!TIP]
> Pair `-stdlib=libc++` with a libc++ you built or installed (Section 4) to get
> a fully LLVM-based C++ toolchain independent of the system GCC runtime.

---

## 6. The LLVM Core Tool Suite

LLVM Core ships roughly **eighty** standalone command-line tools. The most
important ones for everyday work are below; all are built into the `bin/`
directory of your build or install tree.

### The essential tools

| Tool | What it does |
|------|--------------|
| `opt` | Run LLVM IR through optimization and analysis **passes** |
| `llc` | Compile LLVM IR (`.ll`/`.bc`) to native assembly or object code |
| `lli` | Directly execute LLVM IR using the interpreter/JIT |
| `llvm-as` | Assemble textual IR (`.ll`) into bitcode (`.bc`) |
| `llvm-dis` | Disassemble bitcode (`.bc`) back into textual IR (`.ll`) |
| `llvm-link` | Link multiple IR/bitcode modules into one |
| `llvm-mc` | Standalone machine-code assembler/disassembler |
| `llvm-config` | Report version, paths, and flags for an LLVM installation |

### Inspection and binary-utility tools

| Tool | GNU analog | Purpose |
|------|-----------|---------|
| `llvm-objdump` | `objdump` | Disassemble and inspect object files |
| `llvm-nm` | `nm` | List symbols in object files |
| `llvm-readobj` / `llvm-readelf` | `readelf` | Dump object-file structure |
| `llvm-ar` | `ar` | Create and manage static archives |
| `llvm-objcopy` | `objcopy` | Copy and transform object files |
| `llvm-size` | `size` | Report section sizes |
| `llvm-strings` | `strings` | Extract printable strings |
| `llvm-cxxfilt` | `c++filt` | Demangle C++ symbol names |
| `llvm-dwarfdump` | — | Dump DWARF debug information |

### Profiling, coverage, and performance tools

| Tool | Purpose |
|------|---------|
| `llvm-profdata` | Merge and inspect profile data (for PGO) |
| `llvm-cov` | Generate source-level code-coverage reports |
| `llvm-mca` | Machine-code analyzer: model instruction throughput/latency |
| `llvm-exegesis` | Measure instruction latency/throughput on real hardware |
| `llvm-reduce` | Automatically shrink a failing IR test case |

> [!TIP]
> Run any tool with `--help` to see its full, version-accurate option list, and
> `--version` to confirm which build you are invoking. The flag set for these
> tools is defined in the source and is the authoritative reference.

---

## 7. Developer Tooling

Clang's libraries power a suite of source-level tools used directly in editors,
CI, and the command line.

### clang-format — code formatting

```bash
# Format in place using the project's .clang-format file:
clang-format -i src/*.cpp

# Preview a specific style without editing:
clang-format --style=LLVM src/main.cpp
```

> [!TIP]
> Drop a `.clang-format` file at your repository root to define a house style.
> `clang-format` walks up from each file to find it.

### clang-tidy — linting and static analysis

```bash
# Run the default checks on a file (needs a compilation database):
clang-tidy src/main.cpp -- -std=c++20

# Enable a specific set of checks and auto-apply fixes:
clang-tidy --checks='-*,modernize-*,bugprone-*' --fix src/main.cpp
```

> [!NOTE]
> `clang-tidy` works best with a `compile_commands.json` **compilation
> database**. Generate one with `cmake -DCMAKE_EXPORT_COMPILE_COMMANDS=ON` or
> with `clang-scan-deps`/`bear`.

### clangd — the language server

`clangd` provides code completion, go-to-definition, diagnostics, and refactors
to any editor that speaks the Language Server Protocol (VS Code, Neovim, Emacs,
and others).

```bash
# clangd is typically launched by your editor; verify it is found:
clangd --version
```

> [!TIP]
> Like `clang-tidy`, `clangd` needs a `compile_commands.json` to understand how
> your files are compiled. Point your editor's clangd plugin at it.

### Other tools in clang-tools-extra

| Tool | Purpose |
|------|---------|
| `clang-doc` | Generate API documentation from sources |
| `clang-include-fixer` | Add missing `#include` directives automatically |
| `clang-move` | Move C++ class/function definitions between files |
| `clang-reorder-fields` | Reorder struct/class fields safely |
| `clang-query` | Interactively explore the Clang AST with matchers |
| `pp-trace` | Trace preprocessor activity |

### Standalone Clang tools (in `clang/tools`)

| Tool | Purpose |
|------|---------|
| `clang-scan-deps` | Fast dependency scanning for build systems and modules |
| `clang-refactor` | Command-line refactoring engine |
| `clang-repl` | Interactive C++ interpreter (REPL) |
| `clang-check` | Run syntax checks and AST dumps |
| `scan-build` / `scan-view` | Drive and view the Clang Static Analyzer |

---

## 8. Linking with LLD

LLD is a fast linker that can replace the system linker. It exposes several
front-ends that mirror the platform linkers they replace.

| Driver | Replaces | Format |
|--------|----------|--------|
| `ld.lld` | `ld` / `ld.gold` | ELF (Linux, BSD) |
| `lld-link` | `link.exe` | COFF (Windows) |
| `ld64.lld` | `ld` | Mach-O (macOS) |
| `wasm-ld` | — | WebAssembly |

Use LLD through the Clang driver — this is the recommended way:

```bash
# Tell clang to use lld as the linker:
clang -fuse-ld=lld -O2 main.c -o main
```

> [!TIP]
> LLD is often several times faster than `ld.bfd` or `gold` on large links.
> Adding `-fuse-ld=lld` to your build's link flags is a cheap, drop-in speedup.

---

## 9. Debugging with LLDB

LLDB is the project's source-level debugger. Its command interface is similar
to GDB but with its own command grammar and a full Python scripting API.

```bash
# Start debugging a program:
lldb ./myprogram
```

```text
(lldb) breakpoint set --name main
(lldb) run
(lldb) frame variable
(lldb) step
(lldb) continue
```

Common LLDB commands:

| Command | Short form | Purpose |
|---------|-----------|---------|
| `breakpoint set --name <fn>` | `b <fn>` | Set a breakpoint |
| `run` | `r` | Start the program |
| `next` / `step` | `n` / `s` | Step over / into |
| `continue` | `c` | Resume execution |
| `frame variable` | `fr v` | Print local variables |
| `bt` | — | Print the call stack |

> [!NOTE]
> `lldb-dap` implements the Debug Adapter Protocol, which is how editors like
> VS Code talk to LLDB. `lldb-server` enables remote debugging.

> [!TIP]
> Compile with `-g` (and ideally `-O0` for faithful stepping) to get full
> debug information for LLDB.

---

## 10. Finding Bugs with Sanitizers

The **sanitizers** are runtime bug detectors built from `compiler-rt` and
enabled through Clang with `-fsanitize=`. They instrument your program to catch
errors that would otherwise be silent corruption.

| Sanitizer | Flag | Catches |
|-----------|------|---------|
| AddressSanitizer | `-fsanitize=address` | Buffer overflows, use-after-free, leaks |
| UndefinedBehaviorSanitizer | `-fsanitize=undefined` | Integer overflow, bad casts, null derefs |
| ThreadSanitizer | `-fsanitize=thread` | Data races |
| MemorySanitizer | `-fsanitize=memory` | Use of uninitialized memory |

```bash
# Build with AddressSanitizer and run:
clang -fsanitize=address -g -O1 buggy.c -o buggy
./buggy
```

```text
==12345==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x...
    #0 0x... in main buggy.c:7
...
```

> [!IMPORTANT]
> Sanitizers add runtime and memory overhead and are meant for **testing**, not
> production. Do not ship sanitizer-instrumented binaries.

> [!WARNING]
> Most sanitizers cannot be combined (e.g. you cannot use `address` and
> `memory` together). UBSan is the main exception and composes with others.

---

## 11. Working with LLVM IR

LLVM IR is the common language that connects frontends (like Clang) to the
optimizer and backends. Being able to read and manipulate it is a superpower.

### See the IR your code produces

```bash
# Emit human-readable LLVM IR:
clang -O2 -S -emit-llvm hello.c -o hello.ll
cat hello.ll
```

### The IR pipeline by hand

```bash
# 1. C source -> textual IR
clang -O0 -S -emit-llvm hello.c -o hello.ll

# 2. Optimize the IR with opt
opt -O2 hello.ll -S -o hello.opt.ll

# 3. IR -> native assembly with llc
llc hello.opt.ll -o hello.s

# 4. Or run the IR directly with the interpreter/JIT
lli hello.ll
```

```text
Hello from Clang!
```

### Bitcode round-trips

```bash
llvm-as hello.ll -o hello.bc      # text IR -> bitcode
llvm-dis hello.bc -o roundtrip.ll # bitcode -> text IR
```

> [!TIP]
> When reporting an optimizer or backend bug, attach the `.ll` file and the
> exact `opt`/`llc` command. Use `llvm-reduce` to shrink it to a minimal
> reproducer first.

---

## 12. Advanced Workflows

### Cross-compilation

```bash
# Compile for a different architecture using a target triple:
clang --target=aarch64-linux-gnu -O2 main.c -o main-arm64
```

> [!NOTE]
> Cross-compilation requires the target's backend to be built into your LLVM
> (`-DLLVM_TARGETS_TO_BUILD` must include it) and a sysroot/headers for the
> target. The 20 stable backends are listed in the Reference.

### Link-Time Optimization (LTO)

```bash
# Whole-program optimization across translation units:
clang -flto -O2 a.c b.c -o app
```

### Profile-Guided Optimization (PGO)

```bash
# 1. Build instrumented:
clang -fprofile-instr-generate -O2 app.c -o app-inst
# 2. Run representative workloads to collect raw profiles:
LLVM_PROFILE_FILE="app-%p.profraw" ./app-inst < workload
# 3. Merge the raw profiles:
llvm-profdata merge -output=app.profdata app-*.profraw
# 4. Rebuild using the profile:
clang -fprofile-instr-use=app.profdata -O2 app.c -o app-optimized
```

> [!TIP]
> PGO commonly yields 5–20% performance improvements on real workloads because
> the optimizer learns which branches and functions are hot.

---

## 13. How LLVM Works (Concepts)

You can use the tools above without this section, but understanding the pipeline
makes everything click.

### The three-phase design

```text
  Source code                LLVM IR                 Machine code
 (C/C++/Fortran/...)      (target-independent)     (x86/ARM/RISCV/...)
        │                       │                          │
   ┌────▼─────┐           ┌─────▼──────┐            ┌──────▼──────┐
   │ Frontend │  ──────▶  │  Optimizer │  ──────▶   │   Backend   │
   │ (Clang)  │           │   (opt)    │            │   (llc)     │
   └──────────┘           └────────────┘            └─────────────┘
```

1. **Frontend** (e.g. Clang) parses a source language and lowers it to LLVM IR.
2. **Optimizer** runs target-independent **passes** over the IR. Each pass
   analyzes or transforms the IR (inlining, dead-code elimination, vectorization
   — Polly adds polyhedral loop optimizations here).
3. **Backend** (code generator) lowers optimized IR to machine code for a
   specific target architecture.

Because the IR sits in the middle, **any** frontend can reuse **all** of LLVM's
optimizations and **all** of its backends. That reuse is the entire point of
LLVM.

### Where each component fits

- **Clang / Flang** are frontends — they produce IR.
- **LLVM Core** is the optimizer + the 20 backends.
- **MLIR** is a more general IR framework that can model higher-level,
  domain-specific abstractions and progressively lower them, often feeding into
  LLVM IR.
- **LLD** links the resulting object files into executables and libraries.
- **The runtimes** (libc++, compiler-rt, etc.) are linked into your final
  program to provide standard-library and runtime support.

> [!NOTE]
> This is why "LLVM is a compiler toolkit, not a compiler." It is the reusable
> machinery from which compilers are built.

---

## 14. Troubleshooting

### Error: `Requested CMAKE_CXX_STANDARD=... which is less than the required 17`

**Cause:** You passed a `CMAKE_CXX_STANDARD` lower than 17, but LLVM requires a
C++17 host compiler (`LLVM_REQUIRED_CXX_STANDARD` is `17`).
**Solution:** Remove the override, or set `-DCMAKE_CXX_STANDARD=17` (or higher).
**Prevention:** Do not pin an old C++ standard for the LLVM build; LLVM controls
this itself.

### Error: `Support for the LLVM_ENABLE_PROJECTS=openmp build mode has been removed`

**Cause:** You listed `openmp` in `LLVM_ENABLE_PROJECTS`.
**Solution:** Move it to runtimes: `-DLLVM_ENABLE_RUNTIMES="openmp"`.
**Prevention:** OpenMP, libc, and compiler-rt are runtimes, not projects.

### Error: `<name> isn't a known project`

**Cause:** A typo or a component that is actually a runtime appears in
`LLVM_ENABLE_PROJECTS`.
**Solution:** Use a name from the known-projects list (`bolt`, `clang`,
`clang-tools-extra`, `cross-project-tests`, `lld`, `lldb`, `mlir`, `polly`,
`flang`, `libc`, `compiler-rt`) or move it to `LLVM_ENABLE_RUNTIMES`.

### Error: `Runtime "<name>" is not a supported runtime`

**Cause:** An unsupported name in `LLVM_ENABLE_RUNTIMES`.
**Solution:** Choose from: `libc`, `libunwind`, `libcxxabi`, `libcxx`,
`compiler-rt`, `openmp`, `llvm-libgcc`, `offload`, `flang-rt`, `libclc`,
`libsycl`, `orc-rt`.

### Problem: The build runs out of memory while linking

**Cause:** Many large debug binaries link in parallel.
**Solution:** Cap parallel link jobs and use a faster linker:
```bash
cmake -S llvm -B build -G Ninja \
  -DLLVM_PARALLEL_LINK_JOBS=1 \
  -DLLVM_USE_LINKER=lld \
  -DCMAKE_BUILD_TYPE=Release
```
**Prevention:** Prefer `Release` or `RelWithDebInfo` over `Debug`; debug info
multiplies link memory.

### Problem: The build takes forever

**Cause:** Building all targets and all projects.
**Solution:** Set `-DLLVM_TARGETS_TO_BUILD="host"` and enable only the projects
you need. Add `-DLLVM_CCACHE_BUILD=ON` and `-DLLVM_OPTIMIZED_TABLEGEN=ON`.

### Problem: `clang-tidy` / `clangd` report nonsense or "file not found"

**Cause:** No compilation database, so the tool guesses the wrong flags.
**Solution:** Generate `compile_commands.json` with
`-DCMAKE_EXPORT_COMPILE_COMMANDS=ON` and point the tool at it.

### Problem: `[lldb] Misleading error message when re-importing command script`

**Cause:** A known, community-reported LLDB diagnostic issue (upstream issue
#206508) where re-importing a command script produces a confusing message.
**Solution:** Treat the message as informational; the import generally still
behaves as expected. Track the upstream issue for the fix.

> [!TIP]
> For runtime issues with the compiler itself, re-run with `-v` to see the exact
> sub-commands Clang invokes; this usually reveals a missing sysroot, header, or
> library path.

---

## 15. Frequently Asked Questions

**Q: Is "LLVM" a compiler?**
Not by itself. The LLVM Project is a *toolkit* for building compilers. Clang is
the C/C++ compiler built on it. "LLVM Core" is the optimizer and backends.

**Q: Do I need to build the whole monorepo?**
No. Enable only the projects/runtimes you need. Building just `clang` is far
faster than building everything.

**Q: What is the difference between a "project" and a "runtime"?**
Projects (`LLVM_ENABLE_PROJECTS`) are tools built by your host compiler.
Runtimes (`LLVM_ENABLE_RUNTIMES`) are libraries built *by the freshly built
Clang* so they match your target. libc++, compiler-rt, and OpenMP are runtimes.

**Q: Which architectures can LLVM target?**
The 20 stable backends include AArch64, AMDGPU, ARM, AVR, BPF, Hexagon, Lanai,
LoongArch, Mips, MSP430, NVPTX, PowerPC, RISCV, Sparc, SPIRV, SystemZ, VE,
WebAssembly, X86, and XCore. Five more are experimental (see Reference).

**Q: How do I use libc++ instead of libstdc++?**
Compile with `clang++ -stdlib=libc++`.

**Q: What language standards does Clang support?**
Use `-std=` with values like `c11`, `c17`, `c2x`, `c++17`, `c++20`, `c++23`.
Run `clang -std=help` (or check the version's release notes) for the exact set.

**Q: Why is my Clang version 21 when I expected something else?**
The LLVM Project uses a single rolling version for the whole monorepo, bumped
each major release. `clang --version` and `llvm-config --version` report it.

**Q: How do I report a bug or contribute?**
File issues and pull requests on the project's GitHub repository. See the
[Contributing to LLVM](https://llvm.org/docs/Contributing.html) guide and join
the [LLVM Discourse forums](https://discourse.llvm.org/).

**Q: Where is the authoritative flag reference for each tool?**
Run the tool with `--help`. The tools' option definitions in the source are the
source of truth; the rendered docs live at [llvm.org/docs](https://llvm.org/docs).

---

## 16. Reference

### Build component lists (from `llvm/CMakeLists.txt`)

**Projects** (`LLVM_ENABLE_PROJECTS`, `"all"` expands to):
`bolt`, `clang`, `clang-tools-extra`, `cross-project-tests`, `lld`, `lldb`,
`mlir`, `polly`. Extra projects: `flang`, `libc`, `compiler-rt`.

**Runtimes** (`LLVM_ENABLE_RUNTIMES`):
- Default: `libcxx`, `libcxxabi`, `libunwind`, `libclc`, `compiler-rt`, `openmp`
- Supported: `libc`, `libunwind`, `libcxxabi`, `libcxx`, `compiler-rt`,
  `openmp`, `llvm-libgcc`, `offload`, `flang-rt`, `libclc`, `libsycl`, `orc-rt`

### Stable backend targets (`LLVM_TARGETS_TO_BUILD`)

`AArch64`, `AMDGPU`, `ARM`, `AVR`, `BPF`, `Hexagon`, `Lanai`, `LoongArch`,
`Mips`, `MSP430`, `NVPTX`, `PowerPC`, `RISCV`, `Sparc`, `SPIRV`, `SystemZ`,
`VE`, `WebAssembly`, `X86`, `XCore`.

**Experimental targets:** `ARC`, `CSKY`, `DirectX`, `M68k`, `Xtensa`.
**Targets with JIT support:** `X86`, `PowerPC`, `AArch64`, `ARM`, `Mips`, `SystemZ`.

### Frequently used CMake options

| Option | Default | Purpose |
|--------|---------|---------|
| `CMAKE_BUILD_TYPE` | (none) | `Release` / `Debug` / `RelWithDebInfo` / `MinSizeRel` |
| `LLVM_ENABLE_PROJECTS` | `""` | Semicolon-separated projects, or `"all"` |
| `LLVM_ENABLE_RUNTIMES` | `""` | Semicolon-separated runtimes, or `"all"` |
| `LLVM_TARGETS_TO_BUILD` | `"all"` | Backends to build; use `"host"` for speed |
| `LLVM_ENABLE_ASSERTIONS` | ON (Debug) / OFF (Release) | Enable internal assertions |
| `LLVM_CCACHE_BUILD` | `OFF` | Cache compiles with ccache |
| `LLVM_OPTIMIZED_TABLEGEN` | `OFF` | Optimize TableGen even in Debug |
| `LLVM_ENABLE_LLD` | `OFF` | Link LLVM itself with lld |
| `LLVM_USE_LINKER` | (system) | Choose the linker (e.g. `lld`) |
| `LLVM_PARALLEL_LINK_JOBS` | (unbounded) | Cap concurrent link jobs |
| `BUILD_SHARED_LIBS` | `OFF` | Build component libs as shared (developer convenience) |
| `LLVM_BUILD_TESTS` | `OFF` | Build unit tests |
| `LLVM_BUILD_EXAMPLES` | `OFF` | Build example programs |
| `LLVM_INCLUDE_BENCHMARKS` | `ON` | Generate benchmark targets |
| `CMAKE_INSTALL_PREFIX` | (platform) | Install location |

### Key tools by component

| Component | Tools |
|-----------|-------|
| LLVM Core | `opt`, `llc`, `lli`, `llvm-as`, `llvm-dis`, `llvm-link`, `llvm-mc`, `llvm-objdump`, `llvm-nm`, `llvm-readobj`, `llvm-ar`, `llvm-objcopy`, `llvm-config`, `llvm-profdata`, `llvm-cov`, `llvm-mca`, `llvm-dwarfdump`, `llvm-reduce`, … (~80 total) |
| Clang | `clang`, `clang++`, `clang-format`, `clang-scan-deps`, `clang-refactor`, `clang-repl`, `clang-check`, `scan-build` |
| Clang Tools Extra | `clang-tidy`, `clangd`, `clang-doc`, `clang-include-fixer`, `clang-move`, `clang-query`, `pp-trace` |
| LLD | `ld.lld`, `lld-link`, `ld64.lld`, `wasm-ld` |
| LLDB | `lldb`, `lldb-server`, `lldb-dap` |
| MLIR | `mlir-opt`, `mlir-translate` |
| Flang | `flang` |
| BOLT | `llvm-bolt` |

### Official documentation

| Resource | URL |
|----------|-----|
| Getting Started / Building | https://llvm.org/docs/GettingStarted.html |
| Clang documentation | https://clang.llvm.org |
| LLD linker | https://lld.llvm.org |
| libc++ | https://libcxx.llvm.org |
| Contributing | https://llvm.org/docs/Contributing.html |
| Community forums | https://discourse.llvm.org |

> [!NOTE]
> This guide intentionally points to the official `llvm.org` documentation for
> the complete, per-flag references of `clang`, `opt`, `llc`, and the other
> tools. Those flag sets are large, change between releases, and are defined in
> the source; always confirm with `--help` for the exact version you run.

---

_Generated June 2026 from llvm/llvm-project at 53cbf88. AI-generated documentation. The library is checked by sampling (three repositories so far); this guide was not individually reviewed. Verify against the project before relying on it. Unofficial; not affiliated with or reviewed by the project._
