Commit Graph

2628 Commits

Author SHA1 Message Date
Jason Newcomb
a74f3fb5fc Iterate directly on block indices in rustc_mir_transform 2025-02-21 16:10:31 -05:00
Matthias Krüger
1f6c75e682
Rollup merge of #137305 - nnethercote:rustc_middle-2, r=lcnr
Tweaks in and around `rustc_middle`

A bunch of tiny improvements I found while working on bigger things.

r? ```@lcnr```
2025-02-21 12:45:25 +01:00
Nicholas Nethercote
5d2d11fd5d Rename ClearCrossCrate::assert_crate_local.
As `unwrap_crate_local`, because it follows exactly the standard form of
an `unwrap` function.
2025-02-21 07:12:13 +11:00
Zachary S
7ba3d7b54e Remove BackendRepr::Uninhabited, replaced with an uninhabited: bool field in LayoutData.
Also update comments that refered to BackendRepr::Uninhabited.
2025-02-20 13:27:32 -06:00
Matthias Krüger
3fc6dfd5ed
Rollup merge of #137251 - Zalathar:holes-visitor, r=jieyouxu
coverage: Get hole spans from nested items without fully visiting them

This is a small simplification to the code that collects the spans of nested items within a function, so that those spans can be treated as “holes” to be avoided by the current function's coverage mappings.

The old code was using `nested_filter::All` to ensure that the visitor would see nested items. But we don't need the actual items themselves; we just need their spans, which we can obtain via a custom implementation of `visit_nested_item`.

This avoids the more expansive queries required by `nested_filter::All`.
2025-02-19 18:52:10 +01:00
bors
ed49386d3a Auto merge of #136539 - matthewjasper:late-normalize-errors, r=compiler-errors
Emit dropck normalization errors in borrowck

Borrowck generally assumes that any queries it runs for type checking will succeed, thinking that HIR typeck will have errored first if there was a problem. However as of #98641, dropck isn't run on HIR, so there's no direct guarantee that it doesn't error. While a type being well-formed might be expected to ensure that its fields are well-formed, this is not the case for types containing a type projection:

```rust
pub trait AuthUser {
    type Id;
}

pub trait AuthnBackend {
    type User: AuthUser;
}

pub struct AuthSession<Backend: AuthnBackend> {
    data: Option<<<Backend as AuthnBackend>::User as AuthUser>::Id>,
}

pub trait Authz: Sized {
    type AuthnBackend: AuthnBackend<User = Self>;
}

pub fn run_query<User: Authz>(auth: AuthSession<User::AuthnBackend>) {}
// ^ No User: AuthUser bound is required or inferred.
```

While improvements to trait solving might fix this in the future, for now we go for a pragmatic solution of emitting an error from borrowck (by rerunning dropck outside of a query) and making drop elaboration check if an error has been emitted previously before panicking for a failed normalization.

Closes #103899
Closes #135039

r? `@compiler-errors` (feel free to re-assign)
2025-02-19 07:49:08 +00:00
Zalathar
d38f6880c0 coverage: Make HolesVisitor::visit_hole_span a regular method 2025-02-19 14:02:29 +11:00
Zalathar
51f704f0ff coverage: Get hole spans from nested items without fully visiting them
It turns out that this visitor doesn't actually need `nested_filter::All` to
handle nested items; it just needs to override `visit_nested_item` and look up
the item's span.
2025-02-19 14:01:46 +11:00
Matthias Krüger
34535b6078
Rollup merge of #137213 - nnethercote:rm-rustc_middle-mir-tcx, r=compiler-errors
Remove `rustc_middle::mir::tcx` module.

This is a really weird module. For example, what does `tcx` in `rustc_middle::mir::tcx::PlaceTy` mean? The answer is "not much".

The top-level module comment says:

> Methods for the various MIR types. These are intended for use after
> building is complete.

Awfully broad for a module that has a handful of impl blocks for some MIR types, none of which really relates to `TyCtxt`. `git blame` indicates the comment is ancient, from 2015, and made sense then.

This module is now vestigial. This commit removes it and moves all the code within into `rustc_middle::mir::statement`. Some specifics:

- `Place`, `PlaceRef`, `Rvalue`, `Operand`, `BorrowKind`: they all have `impl` blocks in both the `tcx` and `statement` modules. The commit merges the former into the latter.

- `BinOp`, `UnOp`: they only have `impl` blocks in `tcx`. The commit moves these into `statement`.

- `PlaceTy`, `RvalueInitializationState`: they are defined in `tcx`. This commit moves them into `statement` *and* makes them available in `mir::*`, like many other MIR types.

r? `@tmandry`
2025-02-19 01:30:13 +01:00
Nicholas Nethercote
5d1551b9c6 Remove rustc_middle::mir::tcx module.
This is a really weird module. For example, what does `tcx` in
`rustc_middle::mir::tcx::PlaceTy` mean? The answer is "not much".

The top-level module comment says:

> Methods for the various MIR types. These are intended for use after
> building is complete.

Awfully broad for a module that has a handful of impl blocks for some
MIR types, none of which really relates to `TyCtxt`. `git blame`
indicates the comment is ancient, from 2015, and made sense then.

This module is now vestigial. This commit removes it and moves all the
code within into `rustc_middle::mir::statement`. Some specifics:

- `Place`, `PlaceRef`, `Rvalue`, `Operand`, `BorrowKind`: they all have `impl`
  blocks in both the `tcx` and `statement` modules. The commit merges
  the former into the latter.

- `BinOp`, `UnOp`: they only have `impl` blocks in `tcx`. The commit
  moves these into `statement`.

- `PlaceTy`, `RvalueInitializationState`: they are defined in `tcx`.
  This commit moves them into `statement` *and* makes them available in
  `mir::*`, like many other MIR types.
2025-02-19 10:26:05 +11:00
Matthias Krüger
10dd016a80
Rollup merge of #137203 - nnethercote:improve-MIR-modification, r=compiler-errors
Improve MIR modification

A few commits that simplify code that manipulates MIR bodies.

r? `@tmiasko`
2025-02-18 18:40:54 +01:00
Nicholas Nethercote
04eeda47ab Inline and replace Statement::replace_nop.
It has a single call site, and doesn't seem worth having as an API
function.
2025-02-18 13:43:43 +11:00
Nicholas Nethercote
69f5e342bf Inline and remove BasicBlockData::retain_statements.
It has a single call site, and the code is clearer this way.
2025-02-18 13:31:08 +11:00
Nicholas Nethercote
e3316ae453 Improve MirPatch documentation and naming.
It's currently lacking comments. This commit adds some, which is useful
because there are some methods with non-obvious behaviour.

The commit also renames two things:
- `patch_map` becomes `term_patch_map`, because it's only about
  terminators.
- `is_patched` becomes `is_term_patched`, for the same reason.

(I would guess that originally `MirPatch` only handled terminators, and
then over time it expanded to allow other modifications, but these names
weren't updated.)
2025-02-18 13:12:50 +11:00
Nicholas Nethercote
a1daa34ad0 Use MirPatch in EnumSizeOpt.
Instead of `expand_statements`. This makes the code shorter and
consistent with other MIR transform passes.

The tests require updating because there is a slight change in
MIR output:
- the old code replaced the original statement with twelve new
  statements.
- the new code inserts converts the original statement to a `nop` and
  then insert twelve new statements in front of it.

I.e. we now end up with an extra `nop`, which doesn't matter at all.
2025-02-18 12:52:56 +11:00
Nicholas Nethercote
fd7b4bf4e1 Move methods from Map to TyCtxt, part 2.
Continuing the work started in #136466.

Every method gains a `hir_` prefix, though for the ones that already
have a `par_` or `try_par_` prefix I added the `hir_` after that.
2025-02-18 10:17:44 +11:00
Matthew Jasper
cde8c6f52b Handle normalization failures in drop elaboration
Drop elaboration looks at fields of a type, which may error when we try
to normalize them. Borrowck will have detected this if HIR typeck
didn't, but we don't delete the MIR body for errors in borrowck so
still have to handle this happening in drop elaboration by checking
whether an error has been emitted.
2025-02-17 11:33:07 +00:00
Matthias Krüger
f3a4f1a02a
Rollup merge of #136466 - nnethercote:start-removing-Map, r=cjgillot
Start removing `rustc_middle::hir::map::Map`

`rustc_middle::hir::map::Map` is now just a low-value wrapper around `TyCtxt`. This PR starts removing it.

r? `@cjgillot`
2025-02-17 06:37:35 +01:00
Nicholas Nethercote
661f99ba03 Overhaul the intravisit::Map trait.
First of all, note that `Map` has three different relevant meanings.
- The `intravisit::Map` trait.
- The `map::Map` struct.
- The `NestedFilter::Map` associated type.

The `intravisit::Map` trait is impl'd twice.
- For `!`, where the methods are all unreachable.
- For `map::Map`, which gets HIR stuff from the `TyCtxt`.

As part of getting rid of `map::Map`, this commit changes `impl
intravisit::Map for map::Map` to `impl intravisit::Map for TyCtxt`. It's
fairly straightforward except various things are renamed, because the
existing names would no longer have made sense.

- `trait intravisit::Map` becomes `trait intravisit::HirTyCtxt`, so named
  because it gets some HIR stuff from a `TyCtxt`.
- `NestedFilter::Map` assoc type becomes `NestedFilter::MaybeTyCtxt`,
  because it's always `!` or `TyCtxt`.
- `Visitor::nested_visit_map` becomes `Visitor::maybe_tcx`.

I deliberately made the new trait and associated type names different to
avoid the old `type Map: Map` situation, which I found confusing. We now
have `type MaybeTyCtxt: HirTyCtxt`.
2025-02-17 13:21:35 +11:00
Nicholas Nethercote
f86f7ad5f2 Move some Map methods onto TyCtxt.
The end goal is to eliminate `Map` altogether.

I added a `hir_` prefix to all of them, that seemed simplest. The
exceptions are `module_items` which became `hir_module_free_items` because
there was already a `hir_module_items`, and `items` which became
`hir_free_items` for consistency with `hir_module_free_items`.
2025-02-17 13:21:02 +11:00
Scott McMurray
7e35729bfc Don't project into NonNull when dropping a Box 2025-02-15 23:20:52 -08:00
Matthias Krüger
bd094fb573
Rollup merge of #137008 - nnethercote:mv-code-into-rustc_mir_transform, r=oli-obk
Move code into `rustc_mir_transform`

I found two modules in other crates that are better placed in `rustc_mir_transform`, because that's the only crate that uses them.

r? ``@matthewjasper``
2025-02-14 16:23:34 +01:00
bors
905b1bf1cc Auto merge of #137010 - workingjubilee:rollup-g00c07v, r=workingjubilee
Rollup of 9 pull requests

Successful merges:

 - #135439 (Make `-O` mean `OptLevel::Aggressive`)
 - #136460 (Simplify `rustc_span` `analyze_source_file`)
 - #136904 (add `IntoBounds` trait)
 - #136908 ([AIX] expect `EINVAL` for `pthread_mutex_destroy`)
 - #136924 (Add profiling of bootstrap commands using Chrome events)
 - #136951 (Use the right binder for rebinding `PolyTraitRef`)
 - #136981 (ci: switch loongarch jobs to free runners)
 - #136992 (Update backtrace)
 - #136993 ([cg_llvm] Remove dead error message)

r? `@ghost`
`@rustbot` modify labels: rollup
2025-02-14 06:13:42 +00:00
Nicholas Nethercote
28b75a384e Move MirPatch from rustc_middle to rustc_mir_transform.
Because it's only used in `rustc_mir_transform`. (Presumably it is
currently in `rustc_middle` because lots of other MIR-related stuff is,
but that's not a hard requirement.) And because `rustc_middle` is huge
and it's always good to make it smaller.
2025-02-14 16:15:57 +11:00
Nicholas Nethercote
46c72362bc Move drop elaboration infrastructure.
`rustc_mir_dataflow/src/elaborate_drops.rs` contains some infrastructure
used by a few MIR passes: the `elaborate_drop` function, the
`DropElaborator` trait, etc.

`rustc_mir_transform/src/elaborate_drops.rs` (same file name, different
crate) contains the `ElaborateDrops` pass. It relies on a lot of the
infrastructure from `rustc_mir_dataflow/src/elaborate_drops.rs`.

It turns out that the drop infrastructure is only used in
`rustc_mir_transform`, so this commit moves it there. (The only
exception is the small `DropFlagState` type, which is moved to the
existing `rustc_mir_dataflow/src/drop_flag_effects.rs`.) The file is
renamed from `rustc_mir_dataflow/src/elaborate_drops.rs` to
`rustc_mir_transform/src/elaborate_drop.rs` (with no trailing `s`)
because (a) the `elaborate_drop` function is the most important export,
and (b) `rustc_mir_transform/src/elaborate_drops.rs` already exists.

All the infrastructure pieces that used to be `pub` are now
`pub(crate)`, because they are now only used within
`rustc_mir_transform`.
2025-02-14 16:05:34 +11:00
Jubilee
d82ec95083
Rollup merge of #136957 - Zalathar:counters, r=oli-obk
coverage: Eliminate more counters by giving them to unreachable nodes

When preparing a function's coverage counters and metadata during codegen, any part of the original coverage graph that was removed by MIR optimizations can be treated as having an execution count of zero.

Somewhat counter-intuitively, if we give those unreachable nodes a _higher_ priority for receiving physical counters (instead of counter expressions), that ends up reducing the total number of physical counters needed.

This works because if a node is unreachable, we don't actually create a physical counter for it. Instead that node gets a fixed zero counter, and any other node that would have relied on that physical counter in its counter expression can just ignore that term completely.
2025-02-13 17:46:11 -08:00
clubby789
2966256133 Make -O mean -C opt-level=3 2025-02-13 19:47:55 +00:00
Zalathar
ab786d3b98 coverage: Eliminate more counters by giving them to unreachable nodes
When preparing a function's coverage counters and metadata during codegen, any
part of the original coverage graph that was removed by MIR optimizations can
be treated as having an execution count of zero.

Somewhat counter-intuitively, if we give those unreachable nodes a _higher_
priority for receiving physical counters (instead of counter expressions), that
ends up reducing the total number of physical counters needed.

This works because if a node is unreachable, we don't actually create a
physical counter for it. Instead that node gets a fixed zero counter, and any
other node that would have relied on that physical counter in its counter
expression can just ignore that term completely.
2025-02-13 13:45:53 +11:00
bors
6dce9f8c2d Auto merge of #135994 - 1c3t3a:rename-unsafe-ptr, r=oli-obk
Rename rustc_middle::Ty::is_unsafe_ptr to is_raw_ptr

The wording unsafe pointer is less common and not mentioned in a lot of places, instead this is usually called a "raw pointer". For the sake of uniformity, we rename this method.
This came up during the review of
https://github.com/rust-lang/rust/pull/134424.

r? `@Noratrieb`
2025-02-12 23:18:14 +00:00
Jubilee Young
32fd1a7b72 compiler: replace ExternAbi::name calls with formatters
Most of these just format the ABI string, so... just format ExternAbi?
This makes it more consistent and less jank when we can do it.
2025-02-11 19:42:47 -08:00
Matthias Krüger
2cb21fb015
Rollup merge of #136786 - compiler-errors:de-de-duplicate-blocks, r=oli-obk
Remove the deduplicate_blocks pass

I don't think this pass does anything. It's a lot of complexity for 🤷  amount of benefit.

r? oli-obk
2025-02-11 18:04:42 +01:00
Bastian Kersting
f842ee8245 Rename rustc_middle::Ty::is_unsafe_ptr to is_raw_ptr
The wording unsafe pointer is less common and not mentioned in a lot of
places, instead this is usually called a "raw pointer". For the sake of
uniformity, we rename this method.
This came up during the review of
https://github.com/rust-lang/rust/pull/134424.
2025-02-10 12:49:18 +00:00
Jubilee
7f8108afc8
Rollup merge of #136053 - Zalathar:defer-counters, r=saethlin
coverage: Defer part of counter-creation until codegen

Follow-up to #135481 and #135873.

One of the pleasant properties of the new counter-assignment algorithm is that we can stop partway through the process, store the intermediate state in MIR, and then resume the rest of the algorithm during codegen. This lets it take into account which parts of the control-flow graph were eliminated by MIR opts, resulting in fewer physical counters and simpler counter expressions.

Those improvements end up completely obsoleting much larger chunks of code that were previously responsible for cleaning up the coverage metadata after MIR opts, while also doing a more thorough cleanup job.

(That change also unlocks some further simplifications that I've kept out of this PR to limit its scope.)
2025-02-10 00:51:49 -08:00
Michael Goulet
a6dcfe3af4 Remove the deduplicate_blocks pass 2025-02-09 18:58:14 +00:00
Matthias Krüger
d64bd3bedd
Rollup merge of #136722 - kornelski:visit-spans, r=chenyukang
Visit all debug info in MIR Visitor

I've been experimenting with simplifying debug info in MIR inliner, and discovered that MIR Visitor doesn't reliably visit all spans. This PR adds the missing visitor calls.
2025-02-09 19:44:52 +01:00
bors
124cc92199 Auto merge of #136751 - bjorn3:update_rustfmt, r=Mark-Simulacrum
Update bootstrap compiler and rustfmt

The rustfmt version we previously used formats things differently from what the latest nightly rustfmt does. This causes issues for subtrees that get formatted both in-tree and in their own repo. Updating the rustfmt used in-tree solves those issues. Also bumped the bootstrap compiler as the stage0 update command always updates both at the same
time.
2025-02-09 15:44:16 +00:00
bjorn3
1fcae03369 Rustfmt 2025-02-08 22:12:13 +00:00
Michael Goulet
b4641b2b3f Detect (non-raw) borrows of null ZST pointers in CheckNull 2025-02-08 21:38:16 +00:00
Kornel
699567058f
Visit SourceInfo of all Terminators 2025-02-08 00:23:06 +00:00
Matthias Krüger
5df99b0bd2
Rollup merge of #136627 - RalfJung:mir-validation-cfg-checker, r=compiler-errors
MIR validation: add comment explaining the limitations of CfgChecker

I hope this right but I am not sure.^^
Cc `@compiler-errors` `@lcnr` `@cjgillot` `@oli-obk`
2025-02-07 12:01:59 +01:00
Michael Goulet
de7d4a840e Don't reset cast kind without also updating the operand in simplify_cast 2025-02-06 18:39:35 +00:00
Zalathar
bd855b6c9e coverage: Remove the old code for simplifying counters after MIR opts 2025-02-06 21:44:31 +11:00
Zalathar
bf1f254b13 coverage: Don't create counters for code that was removed by MIR opts 2025-02-06 21:44:31 +11:00
Zalathar
20d051ec87 coverage: Defer part of counter-creation until codegen 2025-02-06 21:44:31 +11:00
Zalathar
ee7dc06cf1 coverage: Store BCB node IDs in mappings, and resolve them in codegen
Even though the coverage graph itself is no longer available during codegen,
its nodes can still be used as opaque IDs.
2025-02-06 21:44:29 +11:00
Ralf Jung
5934e0afef MIR validation: add comment explaining the limitations of CfgChecker 2025-02-06 11:36:58 +01:00
Felix S. Klock II
bcb8565f30 Contracts core intrinsics.
These are hooks to:

  1. control whether contract checks are run
  2. allow 3rd party tools to intercept and reintepret the results of running contracts.
2025-02-03 12:53:57 -08:00
许杰友 Jieyou Xu (Joe)
5bd0f32378
Rollup merge of #136464 - nnethercote:rm-TyCtxtAt-for-hooks, r=oli-obk
Remove hook calling via `TyCtxtAt`.

All hooks receive a `TyCtxtAt` argument.

Currently hooks can be called through `TyCtxtAt` or `TyCtxt`. In the latter case, a `TyCtxtAt` is constructed with a dummy span and passed to the hook.

However, in practice hooks are never called through `TyCtxtAt`, and always receive a dummy span. (I confirmed this via code inspection, and double-checked it by temporarily making the `TyCtxtAt` code path panic and running all the tests.)

This commit removes all the `TyCtxtAt` machinery for hooks. All hooks now receive `TyCtxt` instead of `TyCtxtAt`. There are two existing hooks that use `TyCtxtAt::span`: `const_caller_location_provider` and `try_destructure_mir_constant_for_user_output`. For both hooks the span is always a dummy span, probably unintentionally. This dummy span use is now explicit. If a non-dummy span is needed for these two hooks it would be easy to add it as an extra argument because hooks are less constrained than queries.

r? `@oli-obk`
2025-02-03 19:13:29 +08:00
Nicholas Nethercote
e661514bda Remove hook calling via TyCtxtAt.
All hooks receive a `TyCtxtAt` argument.

Currently hooks can be called through `TyCtxtAt` or `TyCtxt`. In the
latter case, a `TyCtxtAt` is constructed with a dummy span and passed to
the hook.

However, in practice hooks are never called through `TyCtxtAt`, and
always receive a dummy span. (I confirmed this via code inspection, and
double-checked it by temporarily making the `TyCtxtAt` code path panic
and running all the tests.)

This commit removes all the `TyCtxtAt` machinery for hooks. All hooks
now receive `TyCtxt` instead of `TyCtxtAt`. There are two existing hooks
that use `TyCtxtAt::span`: `const_caller_location_provider` and
`try_destructure_mir_constant_for_user_output`. For both hooks the span
is always a dummy span, probably unintentionally. This dummy span use is
now explicit. If a non-dummy span is needed for these two hooks it would
be easy to add it as an extra argument because hooks are less
constrained than queries.
2025-02-03 17:02:33 +11:00
Matthias Krüger
ce5db2f9f1
Rollup merge of #136358 - clubby789:opt-none-noinline, r=saethlin
`#[optimize(none)]` implies `#[inline(never)]`

Fixes #136329
2025-02-02 12:31:57 +01:00
Matthias Krüger
58a5f891f9
Rollup merge of #136279 - Zalathar:ensure-ok, r=oli-obk
Rename `tcx.ensure()` to `tcx.ensure_ok()`, and improve the associated docs

This is all based on my archaeology for https://rust-lang.zulipchat.com/#narrow/channel/182449-t-compiler.2Fhelp/topic/.60TyCtxtEnsure.60.

The main renamings are:
- `tcx.ensure()` → `tcx.ensure_ok()`
- `tcx.ensure_with_value()` → `tcx.ensure_done()`
- Query modifier `ensure_forwards_result_if_red` → `return_result_from_ensure_ok`

Hopefully these new names are a better fit for the *actual* function and purpose of these query call modes.
2025-02-02 12:31:55 +01:00
Matthias Krüger
2fd3007cbc
Rollup merge of #130514 - compiler-errors:unsafe-binders, r=oli-obk
Implement MIR lowering for unsafe binders

This is the final bit of the unsafe binders puzzle. It implements MIR, CTFE, and codegen for unsafe binders, and enforces that (for now) they are `Copy`. Later on, I'll introduce a new trait that relaxes this requirement to being "is `Copy` or `ManuallyDrop<T>`" which more closely models how we treat union fields.

Namely, wrapping unsafe binders is now `Rvalue::WrapUnsafeBinder`, which acts much like an `Rvalue::Aggregate`. Unwrapping unsafe binders are implemented as a MIR projection `ProjectionElem::UnwrapUnsafeBinder`, which acts much like `ProjectionElem::Field`.

Tracking:
- https://github.com/rust-lang/rust/issues/130516
2025-02-01 16:41:03 +01:00
Zalathar
9e4f10db65 Rename tcx.ensure_with_value() to tcx.ensure_done() 2025-02-01 12:42:39 +11:00
bors
854f22563c Auto merge of #136350 - matthiaskrgr:rollup-6eqfyvh, r=matthiaskrgr
Rollup of 9 pull requests

Successful merges:

 - #134531 ([rustdoc] Add `--extract-doctests` command-line flag)
 - #135860 (Compiler: Finalize dyn compatibility renaming)
 - #135992 (Improve documentation when adding a new target)
 - #136194 (Support clobber_abi in BPF inline assembly)
 - #136325 (Delay a bug when indexing unsized slices)
 - #136326 (Replace our `LLVMRustDIBuilderRef` with LLVM-C's `LLVMDIBuilderRef`)
 - #136330 (Remove unnecessary hooks)
 - #136336 (Overhaul `rustc_middle::util`)
 - #136341 (Remove myself from vacation)

r? `@ghost`
`@rustbot` modify labels: rollup
2025-01-31 20:16:46 +00:00
clubby789
2c35bd0499 #[optimize(none)] implies #[inline(never)] 2025-01-31 17:51:49 +00:00
Michael Goulet
442b9a9387 Validation 2025-01-31 17:40:28 +00:00
Michael Goulet
fc1a9186dc Implement MIR, CTFE, and codegen for unsafe binders 2025-01-31 17:19:53 +00:00
Matthias Krüger
95f746d2ef
Rollup merge of #136336 - nnethercote:overhaul-rustc_middle-util, r=jieyouxu
Overhaul `rustc_middle::util`

It's an odd module with some odd stuff in it.

r? `@Noratrieb`
2025-01-31 12:28:20 +01:00
Bastian Kersting
b151b513ba Insert null checks for pointer dereferences when debug assertions are enabled
Similar to how the alignment is already checked, this adds a check
for null pointer dereferences in debug mode. It is implemented similarly
to the alignment check as a MirPass.

This is related to a 2025H1 project goal for better UB checks in debug
mode: https://github.com/rust-lang/rust-project-goals/pull/177.
2025-01-31 11:13:34 +00:00
Nicholas Nethercote
140817380c Move find_self_call.
It's a function that does stuff with MIR and yet it weirdly has its own
module in `rustc_middle::util`. This commit moves it into
`rustc_middle::mir`, a more sensible home.
2025-01-31 16:04:13 +11:00
Nicholas Nethercote
1d2cb611f7 Remove the mir_build hook.
It was downgraded from a query in #122721 but it can just be a vanilla
function because it's not called in `rustc_middle`.
2025-01-31 15:15:01 +11:00
Bastian Kersting
851322b74d Refactor PointerFinder into a separate module
This also parameterize the "excluded pointee types" and exposes a
general method for inserting checks on pointers.

This is a preparation for adding a NullCheck that makes use of the same
code.
2025-01-30 10:08:37 +00:00
Matthias Krüger
21ddd7ab89
Rollup merge of #135748 - compiler-errors:len-2, r=RalfJung,oli-obk
Lower index bounds checking to `PtrMetadata`, this time with the right fake borrow semantics 😸

Change `Rvalue::RawRef` to take a `RawRefKind` instead of just a `Mutability`. Then introduce `RawRefKind::FakeForPtrMetadata` and use that for lowering index bounds checking to a `PtrMetadata`. This new `RawRefKind::FakeForPtrMetadata` acts like a shallow fake borrow in borrowck, which mimics the semantics of the old `Rvalue::Len` operation we're replacing.

We can then use this `RawRefKind` instead of using a span desugaring hack in CTFE.

cc ``@scottmcm`` ``@RalfJung``
2025-01-28 14:23:22 +01:00
Michael Goulet
eeecb56b73 Represent the raw pointer for a array length check as a new kind of fake borrow 2025-01-28 00:00:33 +00:00
Michael Goulet
057313b7a6 Reapply "Auto merge of #133734 - scottmcm:lower-indexing-to-ptrmetadata, r=davidtwco,RalfJung"
This reverts commit 122a55bb44.
2025-01-27 23:42:47 +00:00
Guillaume Gomez
03fdcffa1e
Rollup merge of #136114 - compiler-errors:more-idents, r=jieyouxu
Use identifiers more in diagnostics code

This should make the diagnostics code slightly more correct when rendering idents in mixed crate edition situations. Kinda a no-op, but a cleanup regardless.

r? oli-obk or reassign
2025-01-27 15:38:30 +01:00
Guillaume Gomez
f29979aebe
Rollup merge of #136082 - Zalathar:iter-nodes, r=oli-obk
Incorporate `iter_nodes` into `graph::DirectedGraph`

This helper method iterates over all node IDs in the dense range `0..num_nodes`.

In practice, we have a lot of graph-algorithm code that already assumes that nodes are densely numbered, by using `num_nodes` to allocate per-node indexed data structures. So I don't think this is actually a substantial change to the de-facto semantics of `graph::DirectedGraph`.

---

Resolves a FIXME from #135481.
2025-01-27 15:38:28 +01:00
Michael Goulet
c08624d8d2 Remove redundant to_ident_string calls 2025-01-27 01:23:34 +00:00
bors
d9b4598d7e Auto merge of #135753 - compiler-errors:from-ty-const, r=oli-obk
Get rid of `mir::Const::from_ty_const`

This function is strange, because it turns valtrees into `mir::Const::Value`, but the rest of the const variants stay as type system consts.

All of the callsites except for one in `instsimplify` (array length simplification of `ptr_metadata` call) just go through the valtree arm of the function, so it's easier to just create a `mir::Const` directly for those.

For the instsimplify case, if we have a type system const we should *keep* having a type system const, rather than turning it into a `mir::Const::Value`; it doesn't really matter in practice, though, bc `usize` has no padding, but it feels more principled.
2025-01-26 09:26:34 +00:00
Zalathar
d36e2b88d6 Incorporate iter_nodes into graph::DirectedGraph
This assumes that the set of valid node IDs is exactly `0..num_nodes`.

In practice, we have a lot of graph-algorithm code that already assumes that
nodes are densely numbered, by using `num_nodes` to allocate per-node indexed
data structures.
2025-01-26 14:08:42 +11:00
bors
6365178a6b Auto merge of #128657 - clubby789:optimize-none, r=fee1-dead,WaffleLapkin
Add `#[optimize(none)]`

cc #54882

This extends the `optimize` attribute to add `none`, which corresponds to the LLVM `OptimizeNone` attribute.

Not sure if an MCP is required for this, happy to file one if so.
2025-01-25 05:50:36 +00:00
Zalathar
2bdc67a75e coverage: Treat the "merged node flow graph" as a plain data struct
By removing all methods from this struct and treating it as a collection of
data fields, we make it easier for a future PR to store that data in a query
result, without having to move all of its methods into `rustc_middle`.
2025-01-24 16:13:12 +11:00
Zalathar
4b20a27ae0 coverage: Replace FrozenUnionFind with a plain IndexVec
This dedicated type seemed like a good idea at the time, but if we want to
store this information in a query result then a plainer data type is more
convenient.
2025-01-24 16:13:12 +11:00
Zalathar
52c1bfa7bb coverage: Simplify how counter terms are stored
Using `SmallVec` here was fine when it was a module-private detail, but if we
want to pass these terms across query boundaries then it's not worth the extra
hassle.

Replacing a method call with direct field access is slightly simpler.

Using the name `counter_terms` is more consistent with other code that tries to
maintain a distinction between (physical) "counters" and "expressions".
2025-01-24 16:13:12 +11:00
Zalathar
ff48331588 coverage: Make query coverage_ids_info return an Option
This reflects the fact that we can't compute meaningful info for a function
that wasn't instrumented and therefore doesn't have `function_coverage_info`.
2025-01-24 16:13:11 +11:00
Zalathar
ec6fc95d6d coverage: Remove some dead code from MC/DC branch mapping conversion 2025-01-24 16:06:18 +11:00
clubby789
7a9661d768 Disable non-required MIR opts with optimize(none)
Co-authored-by: Waffle Lapkin <waffle.lapkin@gmail.com>
2025-01-23 17:40:41 +00:00
Michael Goulet
e9a566002d Get rid of mir::Const::from_ty_const 2025-01-20 04:26:44 +00:00
Yotam Ofek
264fa0fc54 Run clippy --fix for unnecessary_map_or lint 2025-01-19 19:15:00 +00:00
bors
c62b732724 Auto merge of #135709 - lqd:bring-back-len, r=compiler-errors
Temporarily bring back `Rvalue::Len`

r? `@compiler-errors` as requested in https://github.com/rust-lang/rust/issues/135671#issuecomment-2599580364

> However, in the mean time, I'd rather we not crunch trying to find and more importantly validate the soundness of a solution 🤔

Agreed. To fix the IMO P-critical #135671 for which we somehow didn't have test coverage, this PR temporarily reverts:
- https://github.com/rust-lang/rust/pull/133734
- its bugfix https://github.com/rust-lang/rust/pull/134371
- https://github.com/rust-lang/rust/pull/134330

cc `@scottmcm`

I added the few samples from that issue as a test, but we can add more in the future, in particular it seems `@steffahn` [will work on that](https://github.com/rust-lang/rust/issues/135671#issuecomment-2599714354).

Fixes #135671. And if we want to land this, it should also be nominated for beta backport.
2025-01-19 06:09:51 +00:00
bors
98572840b6 Auto merge of #135715 - matthiaskrgr:rollup-9a18sxj, r=matthiaskrgr
Rollup of 4 pull requests

Successful merges:

 - #135641 ([rustdoc] Replace module list items `ul`/`li` with `dl`/`dd`/`dt` elements)
 - #135703 (Disallow `A { .. }` if `A` has no fields)
 - #135705 (Consolidate ad-hoc MIR lints into real pass-manager-based MIR lints)
 - #135708 (Some random compiler nits)

Failed merges:

 - #135685 (Remove unused `item-row` CSS class)

r? `@ghost`
`@rustbot` modify labels: rollup
2025-01-19 03:23:56 +00:00
Rémy Rakic
122a55bb44 Revert "Auto merge of #133734 - scottmcm:lower-indexing-to-ptrmetadata, r=davidtwco,RalfJung"
This reverts commit b57d93d8b9, reversing
changes made to 0aeaa5eb22.
2025-01-18 22:09:35 +00:00
Rémy Rakic
ca1c17c88d Revert "Auto merge of #134330 - scottmcm:no-more-rvalue-len, r=matthewjasper"
This reverts commit e108481f74, reversing
changes made to 303e8bd768.
2025-01-18 22:09:34 +00:00
Michael Goulet
b08f3d5bdb Consolidate ad-hoc MIR lints into real pass-manager-based MIR lints 2025-01-18 21:25:47 +00:00
Zalathar
ea0c86c434 coverage: Add a few more comments to counter creation 2025-01-18 22:14:16 +11:00
Zalathar
6000d5c462 coverage: Remove BcbCounter and BcbExpression
Making these separate types from `CovTerm` and `Expression` was historically
very helpful, but now that most of the counter-creation work is handled by
`node_flow` they are no longer needed.
2025-01-18 22:14:16 +11:00
Zalathar
4170b93cdc coverage: Flatten top-level counter creation into plain functions
- Move `make_bcb_counters` out of `CoverageCounters`
- Split out `make_node_counter_priority_list`
- Flatten `Transcriber` into the function `transcribe_counters`
2025-01-18 22:12:47 +11:00
Zalathar
48399442d4 coverage: Move phys_counter_for_node into CoverageCounters 2025-01-18 18:51:22 +11:00
Zalathar
a14c35c507 coverage: Remove the Site enum now that we only instrument nodes 2025-01-18 17:12:18 +11:00
Zalathar
6eabf03526 coverage: Make yank_to_spantree_root iterative instead of recursive
This avoids having to worry about stack space when traversing very long
spantree paths, e.g. when instrumenting a long sequence of if/else statements.
2025-01-16 22:07:18 +11:00
Zalathar
f1300c860e coverage: Completely overhaul counter assignment, using node-flow graphs 2025-01-16 22:07:18 +11:00
Matthias Krüger
988137c040
Rollup merge of #135377 - compiler-errors:impossible-step, r=oli-obk
Make MIR cleanup for functions with impossible predicates into a real MIR pass

It's a bit jarring to see the body of a function with an impossible-to-satisfy where clause suddenly go to a single `unreachable` terminator when looking at the MIR dump output in order, and I discovered it's because we manually replace the body outside of a MIR pass.

Let's make it into a fully flegded MIR pass so it's more clear what it's doing and when it's being applied.
2025-01-12 12:07:58 +01:00
Scott McMurray
7396ec3edb Address PR feedback 2025-01-11 15:56:58 -08:00
Scott McMurray
6e34369ef6 [mir-opt] simplify Repeats that don't actually repeat the operand 2025-01-11 15:56:53 -08:00
Michael Goulet
f1d622678b Make MIR cleanup for functions with impossible predicates into a real MIR pass 2025-01-11 20:50:39 +00:00
Rémy Rakic
a13354bea0 rename BitSet to DenseBitSet
This should make it clearer that this bitset is dense, with the
advantages and disadvantages that it entails.
2025-01-11 11:34:01 +00:00
bors
7e4077d06f Auto merge of #135274 - saethlin:array-repeats, r=compiler-errors
Add an InstSimplify for repetitive array expressions

I noticed in https://github.com/rust-lang/rust/pull/135068#issuecomment-2569955426 that GVN's implementation of this same transform was quite profitable on the deep-vector benchmark. But of course GVN doesn't run in unoptimized builds, so this is my attempt to write a version of this transform that benefits the deep-vector case and is fast enough to run in InstSimplify.

The benchmark suite indicates that this is effective.
2025-01-11 06:33:55 +00:00
David Wood
cc9a9ecccb
mir_build: check annotated functions w/out callers 2025-01-10 18:37:57 +00:00
David Wood
dbec6bedf4
inline: move should inline check 2025-01-10 18:37:56 +00:00
David Wood
5f316f5e00
validator: move force inline check 2025-01-10 18:37:56 +00:00