Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 2 additions & 3 deletions josh-sync.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
org = "rust-lang"
repo = "rustc-dev-guide"
path = "src/doc/rustc-dev-guide"

[push-pr]
suffix = "r? @ghost"
push-pr.suffix = "r? @ghost"
pull-pr.suffix = "r? @ghost"
99 changes: 45 additions & 54 deletions src/hir.md
Original file line number Diff line number Diff line change
@@ -1,14 +1,12 @@
# The HIR

The HIR – "High-Level Intermediate Representation" – is the primary IR used
in most of rustc.
The HIR – "High-Level Intermediate Representation" – is the primary IR used in most of rustc.
It is a compiler-friendly representation of the abstract
syntax tree (AST) that is generated after parsing, macro expansion, and name
resolution (see [Lowering](./hir/lowering.md) for how the HIR is created).
Many parts of HIR resemble Rust surface syntax quite closely, with
the exception that some of Rust's expression forms have been desugared away.
For example, `for` loops are converted into a `loop` and do not appear in
the HIR.
syntax tree (AST) that is generated after parsing, macro expansion,
and name resolution (see [Lowering](./hir/lowering.md) for how the HIR is created).
Many parts of HIR resemble Rust surface syntax quite closely,
with the exception that some of Rust's expression forms have been desugared away.
For example, `for` loops are converted into a `loop` and do not appear in the HIR.
This makes HIR more amenable to analysis than a normal AST.

This chapter covers the main concepts of the HIR.
Expand All @@ -30,19 +28,17 @@ cargo rustc -- -Z unpretty=hir

## Out-of-band storage and the `Crate` type

The top-level data-structure in the HIR is the [`Crate`], which stores
the contents of the crate currently being compiled (we only ever
The top-level data-structure in the HIR is the [`Crate`],
which stores the contents of the crate currently being compiled (we only ever
construct HIR for the current crate).
Whereas in the AST the crate
data structure basically just contains the root module, the HIR
`Crate` structure contains a number of maps and other things that
Whereas in the AST the crate data structure basically just contains the root module,
the HIR `Crate` structure contains a number of maps and other things that
serve to organize the content of the crate for easier access.

[`Crate`]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_middle/hir/struct.Crate.html

For example, the contents of individual items (e.g. modules,
functions, traits, impls, etc) in the HIR are not immediately
accessible in the parents.
functions, traits, impls, etc) in the HIR are not immediately accessible in the parents.
So, for example, if there is a module item `foo` containing a function `bar()`:

```rust
Expand All @@ -53,8 +49,7 @@ mod foo {

then in the HIR the representation of module `foo` (the [`Mod`]
struct) would only have the **`ItemId`** `I` of `bar()`.
To get the details of the function `bar()`, we would lookup `I` in the
`items` map.
To get the details of the function `bar()`, we would lookup `I` in the `items` map.

[`Mod`]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_hir/hir/struct.Mod.html

Expand All @@ -69,11 +64,10 @@ integration with incremental compilation.
This way, if you gain access
to an [`&rustc_hir::Item`] (e.g. for the mod `foo`), you do not immediately
gain access to the contents of the function `bar()`.
Instead, you only
gain access to the **id** for `bar()`, and you must invoke some
function to lookup the contents of `bar()` given its id; this gives
the compiler a chance to observe that you accessed the data for
`bar()`, and then record the dependency.
Instead, you only gain access to the **id** for `bar()`,
and you must invoke some function to lookup the contents of `bar()` given its id; this gives
the compiler a chance to observe that you accessed the data for `bar()`,
and then record the dependency.

[`&rustc_hir::Item`]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_hir/hir/struct.Item.html

Expand All @@ -83,29 +77,27 @@ the compiler a chance to observe that you accessed the data for

The HIR uses a bunch of different identifiers that coexist and serve different purposes.

- A [`DefId`], as the name suggests, identifies a particular definition, or top-level
item, in a given crate.
- A [`DefId`], as the name suggests, identifies a particular definition, or top-level item,
in a given crate.
It is composed of two parts: a [`CrateNum`] which identifies
the crate the definition comes from, and a [`DefIndex`] which identifies the definition
within the crate.
Unlike [`HirId`]s, there isn't a [`DefId`] for every expression, which
makes them more stable across compilations.
the crate the definition comes from,
and a [`DefIndex`] which identifies the definition within the crate.
Unlike [`HirId`]s, there isn't a [`DefId`] for every expression,
which makes them more stable across compilations.

- A [`LocalDefId`] is basically a [`DefId`] that is known to come from the current crate.
This allows us to drop the [`CrateNum`] part, and use the type system to ensure that
only local definitions are passed to functions that expect a local definition.

- A [`HirId`] uniquely identifies a node in the HIR of the current crate.
It is composed of two parts:
an `owner` and a `local_id` that is unique within the `owner`.
It is composed of two parts: an `owner` and a `local_id` that is unique within the `owner`.
This combination makes for more stable values which are helpful for incremental compilation.
Unlike [`DefId`]s, a [`HirId`] can refer to [fine-grained entities][Node] like expressions,
but stays local to the current crate.

- A [`BodyId`] identifies a HIR [`Body`] in the current crate.
It is currently only a wrapper around a [`HirId`].
For more info about HIR bodies, please refer to the
[HIR chapter][hir-bodies].
For more info about HIR bodies, please refer to the [HIR chapter][hir-bodies].

These identifiers can be converted into one another through the [`TyCtxt`].

Expand All @@ -122,47 +114,46 @@ These identifiers can be converted into one another through the [`TyCtxt`].
## HIR Operations

Most of the time when you are working with the HIR, you will do so via [`TyCtxt`].
It contains a number of methods, defined in the `hir::map` module and
mostly prefixed with `hir_`, to convert between IDs of various kinds and to
lookup data associated with a HIR node.
It contains a number of methods, defined in the `hir::map` module and mostly prefixed with `hir_`,
to convert between IDs of various kinds and to lookup data associated with a HIR node.

[`TyCtxt`]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_middle/ty/context/struct.TyCtxt.html

For example, if you have a [`LocalDefId`], and you would like to convert it
to a [`HirId`], you can use [`tcx.local_def_id_to_hir_id(def_id)`][local_def_id_to_hir_id].
For example, if you have a [`LocalDefId`], and you would like to convert it to a [`HirId`],
you can use [`tcx.local_def_id_to_hir_id(def_id)`][local_def_id_to_hir_id].
You need a `LocalDefId`, rather than a `DefId`, since only local items have HIR nodes.

[local_def_id_to_hir_id]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_middle/ty/context/struct.TyCtxt.html#method.local_def_id_to_hir_id

Similarly, you can use [`tcx.hir_node(n)`][hir_node] to lookup the node for a
[`HirId`].
This returns a `Option<Node<'hir>>`, where [`Node`] is an enum
defined in the map.
By matching on this, you can find out what sort of
node the `HirId` referred to and also get a pointer to the data
itself. Often, you know what sort of node `n` is – e.g. if you know
that `n` must be some HIR expression, you can do
[`tcx.hir_expect_expr(n)`][expect_expr], which will extract and return the
[`&hir::Expr`][Expr], panicking if `n` is not in fact an expression.
Similarly, you can use [`tcx.hir_node(n)`][hir_node] to lookup the node for a [`HirId`].
This returns a `Option<Node<'hir>>`, where [`Node`] is an enum defined in the map.
By matching on this,
you can find out what sort of node the `HirId` referred to and also get a pointer to the data
itself.
Often, you know what sort of node `n` is – e.g. if you know
that `n` must be some HIR expression, you can do [`tcx.hir_expect_expr(n)`][expect_expr],
which will extract and return the [`&hir::Expr`][Expr],
panicking if `n` is not in fact an expression.

[hir_node]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_middle/ty/context/struct.TyCtxt.html#method.hir_node
[`Node`]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_hir/hir/enum.Node.html
[expect_expr]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_middle/ty/context/struct.TyCtxt.html#method.expect_expr
[Expr]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_hir/hir/struct.Expr.html

Finally, you can find the parents of nodes, via
calls like [`tcx.parent_hir_node(n)`][parent_hir_node].
Finally, you can find the parents of nodes,
via calls like [`tcx.parent_hir_node(n)`][parent_hir_node].

[parent_hir_node]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_middle/ty/context/struct.TyCtxt.html#method.parent_hir_node


## HIR Bodies

A [`rustc_hir::Body`] represents some kind of executable code, such as the body
of a function/closure or the definition of a constant.
Bodies are associated with an **owner**, which is typically some kind of item
(e.g. an `fn()` or `const`), but could also be a closure expression
(e.g. `|x, y| x + y`). You can use the [`TyCtxt`] to find the body
A [`rustc_hir::Body`] represents some kind of executable code,
such as the body of a function/closure, or the definition of a constant.
Bodies are associated with an **owner**,
which is typically some kind of item (e.g. an `fn()` or `const`),
but could also be a closure expression (e.g. `|x, y| x + y`).
You can use the [`TyCtxt`] to find the body
associated with a given def-id ([`hir_maybe_body_owned_by`]) or to find
the owner of a body ([`hir_body_owner_def_id`]).

Expand Down
73 changes: 31 additions & 42 deletions src/parallel-rustc.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,13 @@ As of <!-- date-check --> November 2024, most of the rust compiler is now
parallelized.

- The codegen part is executed concurrently by default.
You can use the `-C
codegen-units=n` option to control the number of concurrent tasks.
- The parts after HIR lowering to codegen such as type checking, borrowing
checking, and mir optimization are parallelized in the nightly version.
Currently, they are executed in serial by default, and parallelization is
manually enabled by the user using the `-Z threads = n` option.
- Other parts, such as lexical parsing, HIR lowering, and macro expansion, are
still executed in serial mode.
You can use the `-C codegen-units=n` option to control the number of concurrent tasks.
- The parts after HIR lowering to codegen, such as type checking, borrow-checking,
and mir optimization are parallelized in the nightly version.
Currently, they are executed serially by default,
and parallelization is manually enabled by the user using the `-Z threads = n` option.
- Other parts, such as lexical parsing, HIR lowering, and macro expansion,
are still executed in serial mode.

<div class="warning">
The following sections are kept for now but are quite outdated.
Expand All @@ -34,8 +33,7 @@ The following sections are kept for now but are quite outdated.
During monomorphization the compiler splits up all the code to
be generated into smaller chunks called _codegen units_.
These are then generated by independent instances of LLVM running in parallel.
At the end, the linker
is run to combine all the codegen units together into one binary.
At the end, the linker is run to combine all the codegen units together into one binary.
This process occurs in the [`rustc_codegen_ssa::base`] module.

[`rustc_codegen_ssa::base`]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_codegen_ssa/base/index.html
Expand All @@ -44,8 +42,7 @@ This process occurs in the [`rustc_codegen_ssa::base`] module.

The underlying thread-safe data-structures used in the parallel compiler
can be found in the [`rustc_data_structures::sync`] module.
These data structures
are implemented differently depending on whether `parallel-compiler` is true.
These data structures are implemented differently, depending on whether `parallel-compiler` is true.

| data structure | parallel | non-parallel |
| -------------------------------- | --------------------------------------------------- | ------------ |
Expand All @@ -61,8 +58,8 @@ are implemented differently depending on whether `parallel-compiler` is true.
can cause lock contention resulting in degraded performance as the number of
threads increases beyond 4. So we audit the use of these data structures
which leads to either a refactoring so as to reduce the use of shared state,
or the authoring of persistent documentation covering the specific of the
invariants, the atomicity, and the lock orderings.
or the authoring of persistent documentation covering the specific of the invariants,
the atomicity, and the lock orderings.

- On the other hand, we still need to figure out what other invariants
during compilation might not hold in parallel compilation.
Expand All @@ -73,31 +70,27 @@ are implemented differently depending on whether `parallel-compiler` is true.

[`WorkerLocal`] is a special data structure implemented for parallel compilers.
It holds worker-locals values for each thread in a thread pool.
You can only
access the worker local value through the `Deref` `impl` on the thread pool it
You can only access the worker local value through the `Deref` `impl` on the thread pool it
was constructed on.
It panics otherwise.

`WorkerLocal` is used to implement the `Arena` allocator in the parallel
environment, which is critical in parallel queries.
Its implementation is
located in the [`rustc_data_structures::sync::worker_local`] module.
`WorkerLocal` is used to implement the `Arena` allocator in the parallel environment,
which is critical in parallel queries.
Its implementation is located in the [`rustc_data_structures::sync::worker_local`] module.
However,
in the non-parallel compiler, it is implemented as `(OneThread<T>)`, whose `T`
can be accessed directly through `Deref::deref`.
in the non-parallel compiler, it is implemented as `(OneThread<T>)`,
whose `T` can be accessed directly through `Deref::deref`.

[`rustc_data_structures::sync::worker_local`]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_data_structures/sync/worker_local/index.html
[`WorkerLocal`]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_data_structures/sync/worker_local/struct.WorkerLocal.html

## Parallel iterator

The parallel iterators provided by the [`rayon`] crate are easy ways to
implement parallelism.
The parallel iterators provided by the [`rayon`] crate are easy ways to implement parallelism.
In the current implementation of the parallel compiler,
we use [a custom fork of `rayon`][rustc-rayon] to run tasks in parallel.

Some iterator functions are implemented to run loops in parallel
when `parallel-compiler` is true.
Some iterator functions are implemented to run loops in parallel when `parallel-compiler` is true.

| Function(Omit `Send` and `Sync`) | Introduction | Owning Module |
| ------------------------------------------------------------ | ------------------------------------------------------------ | -------------------------- |
Expand Down Expand Up @@ -136,30 +129,26 @@ There are still many loops that have the potential to use parallel iterators.
The query model has some properties that make it actually feasible to evaluate
multiple queries in parallel without too much effort:

- All data a query provider can access is via the query context, so
the query context can take care of synchronizing access.
- All data a query provider can access is via the query context,
so the query context can take care of synchronizing access.
- Query results are required to be immutable so they can safely be used by
different threads concurrently.

When a query `foo` is evaluated, the cache table for `foo` is locked.

- If there already is a result, we can clone it, release the lock and
we are done.
- If there is no cache entry and no other active query invocation computing the
same result, we mark the key as being "in progress", release the lock and
start evaluating.
- If there *is* another query invocation for the same key in progress, we
release the lock, and just block the thread until the other invocation has
computed the result we are waiting for.
- If there already is a result, we can clone it, release the lock, and we are done.
- If there is no cache entry and no other active query invocation computing the same result,
we mark the key as being "in progress", release the lock, and start evaluating.
- If there *is* another query invocation for the same key in progress, we release the lock,
and just block the thread until the other invocation has computed the result we are waiting for.
**Cycle error detection** in the parallel
compiler requires more complex logic than in single-threaded mode.
When
worker threads in parallel queries stop making progress due to interdependence,
the compiler uses an extra thread *(named deadlock handler)* to detect, remove and
report the cycle error.
When worker threads in parallel queries stop making progress due to interdependence,
the compiler uses an extra thread *(named deadlock handler)* to detect,
remove, and report the cycle error.

The parallel query feature still has implementation to do, most of which is
related to the previous `Data Structures` and `Parallel Iterators`.
The parallel query feature still has implementation to do,
most of which is related to the previous `Data Structures` and `Parallel Iterators`.
See [this open feature tracking issue][tracking].

## Rustdoc
Expand Down
4 changes: 3 additions & 1 deletion src/tests/compiletest.md
Original file line number Diff line number Diff line change
Expand Up @@ -808,8 +808,10 @@ pub fn identity(ts: TokenStream) -> TokenStream {
> force-host` and `//@ no-prefer-dynamic` headers in the proc-macro.

### Auxiliary lint
<!-- date-check Nov 2026 -->

By using an `aux-lint` directive in a `ui-fulldeps` test, you can build a 'lint library' file which will be loaded into rustc's lints when running your test.
By using an `aux-lint` directive in a `ui-fulldeps` test,
you can build a 'lint library' file which will be loaded into rustc's lints when running your test.

```rs
// tests/ui-fulldeps/lint_test.rs
Expand Down
6 changes: 3 additions & 3 deletions src/tests/x86_64-gnu-parallel-frontend.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
# Parallel frontend testing on CI

If you see any test failures in `tests/ui` from the CI job `test-x86_64-gnu-parallel-frontend`, please
add `//@ ignore-parallel-frontend triage` to the failing test, even if your PR is otherwise
entirely unrelated to parallel compiler or its testing.
If you see any test failures in `tests/ui` from the CI job `test-x86_64-gnu-parallel-frontend`,
please add `//@ ignore-parallel-frontend triage` to the failing test,
even if your PR is otherwise entirely unrelated to parallel compiler or its testing.
In some time people from the parallel rustc working group will triage the failing test, make a
tracking issue for it, and try to debug the problem.

Expand Down
Loading