Commit Graph

1987 Commits

Author SHA1 Message Date
Oli Scherer
d87e9636d5 Run the "is this static mutable" logic the same way as in in_mutable_memory 2024-04-17 09:50:44 +00:00
Oli Scherer
8c9cba2be7 Validate nested static items 2024-04-17 09:50:15 +00:00
Ralf Jung
ae7b07f2dc interpret: rename base_pointer -> root_pointer
also in Miri, "base tag" -> "root tag"
2024-04-17 07:35:48 +02:00
Ralf Jung
9e239bdc76 interpret: pass MemoryKind to adjust_alloc_base_pointer 2024-04-17 07:35:48 +02:00
Matthias Krüger
45940fe6d8
Rollup merge of #122813 - nnethercote:nicer-quals, r=compiler-errors
Qualifier tweaking

Adding and removing qualifiers in some cases that make things nicer. Details in individual commits.

r? `@compiler-errors`
2024-04-17 05:44:52 +02:00
Guillaume Gomez
4885ddfa92
Rollup merge of #123675 - oli-obk:static_wf_ice, r=compiler-errors
Taint const qualifs if a static is referenced that didn't pass wfcheck

It is correct to only check the signature here, as the ICE is caused by `USE_WITH_ERROR` trying to allocate memory to store the result of `WITH_ERROR` before evaluating it.

fixes #123153
2024-04-17 00:00:22 +02:00
zetanumbers
24a24ec6ba Add simple async drop glue generation
Explainer: https://zetanumbers.github.io/book/async-drop-design.html

https://github.com/rust-lang/rust/pull/121801
2024-04-16 20:45:07 +03:00
Matthias Krüger
4971d9ffe4
Rollup merge of #124024 - RalfJung:interpret-comment, r=oli-obk
interpret: remove outdated comment

In https://github.com/rust-lang/rust/pull/107756, allocation became generally fallible, so the "only panic if there is provenance" no longer applies.

r? ``@oli-obk``
2024-04-16 17:54:46 +02:00
Ralf Jung
5b8b9cfaaa interpret: remove outdated comment 2024-04-16 17:33:12 +02:00
Ralf Jung
18bfca50f1 interpret: pass MemoryKind to before_memory_deallocation 2024-04-16 16:37:34 +02:00
Maybe Waffle
7ce867f552 Add an assertion in const eval 2024-04-16 11:56:21 +00:00
Maybe Waffle
ceead1bda6 Change intrinsic types to use u32 instead of T to match stable reexports 2024-04-16 11:53:04 +00:00
Oli Scherer
801413ecd1 Taint const qualifs if a static is referenced that didn't pass wfcheck 2024-04-16 10:43:41 +00:00
Nicholas Nethercote
b03ae74c84 Rename a tiny module.
So it doesn't clash with `rustc_middle::ty`.
2024-04-16 16:37:28 +10:00
Nicholas Nethercote
e93f754289 Always use ty:: qualifier for TyKind enum variants.
Because that's the way it should be done.
2024-04-16 16:29:13 +10:00
Oli Scherer
84acfe86de Actually create ranged int types in the type system. 2024-04-08 12:02:19 +00:00
Ben Kimock
a7912cb421 Put checks that detect UB under their own flag below debug_assertions 2024-04-06 11:21:47 -04:00
Jacob Pratt
4332498a6d
Rollup merge of #123401 - Zalathar:assert-size-aarch64, r=fmease
Check `x86_64` size assertions on `aarch64`, too

(Context: https://rust-lang.zulipchat.com/#narrow/stream/131828-t-compiler/topic/Checking.20size.20assertions.20on.20aarch64.3F)

Currently the compiler has around 30 sets of `static_assert_size!` for various size-critical data structures (e.g. various IR nodes), guarded by `#[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]`.

(Presumably this cfg avoids having to maintain separate size values for 32-bit targets and unusual 64-bit targets. Apparently it may have been necessary before the i128/u128 alignment changes, too.)

This is slightly incovenient for people on aarch64 workstations (e.g. Macs), because the assertions normally aren't checked until we push to a PR. So this PR adds `aarch64` to the `#[cfg(..)]` guarding all of those assertions in the compiler.

---

Implemented with a simple find/replace. Verified by manually inspecting each `static_assert_size!` in `compiler/`, and checking that either the replacement succeeded, or adding aarch64 wouldn't have been appropriate.
2024-04-03 20:17:06 -04:00
joboet
989660c3e6
rename expose_addr to expose_provenance 2024-04-03 16:00:38 +02:00
Zalathar
2d47cd77ac Check x86_64 size assertions on aarch64, too
This makes it easier for contributors on aarch64 workstations (e.g. Macs) to
notice when these assertions have been violated.
2024-04-03 16:53:03 +11:00
Jacob Pratt
e9ef8e1efa
Rollup merge of #122935 - RalfJung:with-exposed-provenance, r=Amanieu
rename ptr::from_exposed_addr -> ptr::with_exposed_provenance

As discussed on [Zulip](https://rust-lang.zulipchat.com/#narrow/stream/136281-t-opsem/topic/To.20expose.20or.20not.20to.20expose/near/427757066).

The old name, `from_exposed_addr`, makes little sense as it's not the address that is exposed, it's the provenance. (`ptr.expose_addr()` stays unchanged as we haven't found a better option yet. The intended interpretation is "expose the provenance and return the address".)

The new name nicely matches `ptr::without_provenance`.
2024-04-02 20:37:39 -04:00
bors
88c2f4f5f5 Auto merge of #123385 - matthiaskrgr:rollup-v69vjbn, r=matthiaskrgr
Rollup of 8 pull requests

Successful merges:

 - #123198 (Add fn const BuildHasherDefault::new)
 - #123226 (De-LLVM the unchecked shifts [MCP#693])
 - #123302 (Make sure to insert `Sized` bound first into clauses list)
 - #123348 (rustdoc: add a couple of regression tests)
 - #123362 (Check that nested statics in thread locals are duplicated per thread.)
 - #123368 (CFI: Support non-general coroutines)
 - #123375 (rustdoc: synthetic auto trait impls: accept unresolved region vars for now)
 - #123378 (Update sysinfo to 0.30.8)

Failed merges:

 - #123349 (Fix capture analysis for by-move closure bodies)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-04-02 21:23:53 +00:00
bors
a77322c16f Auto merge of #118310 - scottmcm:three-way-compare, r=davidtwco
Add `Ord::cmp` for primitives as a `BinOp` in MIR

Update: most of this OP was written months ago.  See https://github.com/rust-lang/rust/pull/118310#issuecomment-2016940014 below for where we got to recently that made it ready for review.

---

There are dozens of reasonable ways to implement `Ord::cmp` for integers using comparison, bit-ops, and branches.  Those differences are irrelevant at the rust level, however, so we can make things better by adding `BinOp::Cmp` at the MIR level:

1. Exactly how to implement it is left up to the backends, so LLVM can use whatever pattern its optimizer best recognizes and cranelift can use whichever pattern codegens the fastest.
2. By not inlining those details for every use of `cmp`, we drastically reduce the amount of MIR generated for `derive`d `PartialOrd`, while also making it more amenable to MIR-level optimizations.

Having extremely careful `if` ordering to μoptimize resource usage on broadwell (#63767) is great, but it really feels to me like libcore is the wrong place to put that logic.  Similarly, using subtraction [tricks](https://graphics.stanford.edu/~seander/bithacks.html#CopyIntegerSign) (#105840) is arguably even nicer, but depends on the optimizer understanding it (https://github.com/llvm/llvm-project/issues/73417) to be practical.  Or maybe [bitor is better than add](https://discourse.llvm.org/t/representing-in-ir/67369/2?u=scottmcm)?  But maybe only on a future version that [has `or disjoint` support](https://discourse.llvm.org/t/rfc-add-or-disjoint-flag/75036?u=scottmcm)?  And just because one of those forms happens to be good for LLVM, there's no guarantee that it'd be the same form that GCC or Cranelift would rather see -- especially given their very different optimizers.  Not to mention that if LLVM gets a spaceship intrinsic -- [which it should](https://rust-lang.zulipchat.com/#narrow/stream/131828-t-compiler/topic/Suboptimal.20inlining.20in.20std.20function.20.60binary_search.60/near/404250586) -- we'll need at least a rustc intrinsic to be able to call it.

As for simplifying it in Rust, we now regularly inline `{integer}::partial_cmp`, but it's quite a large amount of IR.  The best way to see that is with 8811efa88b (diff-d134c32d028fbe2bf835fef2df9aca9d13332dd82284ff21ee7ebf717bfa4765R113) -- I added a new pre-codegen MIR test for a simple 3-tuple struct, and this PR change it from 36 locals and 26 basic blocks down to 24 locals and 8 basic blocks.  Even better, as soon as the construct-`Some`-then-match-it-in-same-BB noise is cleaned up, this'll expose the `Cmp == 0` branches clearly in MIR, so that an InstCombine (#105808) can simplify that to just a `BinOp::Eq` and thus fix some of our generated code perf issues.  (Tracking that through today's `if a < b { Less } else if a == b { Equal } else { Greater }` would be *much* harder.)

---

r? `@ghost`
But first I should check that perf is ok with this
~~...and my true nemesis, tidy.~~
2024-04-02 19:21:44 +00:00
Oli Scherer
64b75f736d Forbid implicit nested statics in thread local statics 2024-04-02 13:00:46 +00:00
Michael Goulet
4ff8a9bd6b Don't inherit codegen attrs from parent static 2024-03-31 22:34:00 -04:00
Matthias Krüger
45cec32ac3
Rollup merge of #123133 - xiaoxiangxianzi:master, r=fmease
chore: fix some comments
2024-03-27 23:27:24 +01:00
xiaoxiangxianzi
3157114f0b chore: fix some comments
Signed-off-by: xiaoxiangxianzi <zhaoyizheng@outlook.com>
2024-03-27 22:32:53 +08:00
Guillaume Gomez
bffeb052d1
Rollup merge of #123021 - compiler-errors:coroutine-layout-lol, r=oli-obk
Make `TyCtxt::coroutine_layout` take coroutine's kind parameter

For coroutines that come from coroutine-closures (i.e. async closures), we may have two kinds of bodies stored in the coroutine; one that takes the closure's captures by reference, and one that takes the captures by move.

These currently have identical layouts, but if we do any optimization for these layouts that are related to the upvars, then they will diverge -- e.g. https://github.com/rust-lang/rust/pull/120168#discussion_r1536943728.

This PR relaxes the assertion I added in #121122, and instead make the `TyCtxt::coroutine_layout` method take the `coroutine_kind_ty` argument from the coroutine, which will allow us to differentiate these by-move and by-ref bodies.
2024-03-27 10:13:43 +01:00
bors
c98ea0d808 Auto merge of #111769 - saethlin:ctfe-backtrace-ctrlc, r=RalfJung
Print a backtrace in const eval if interrupted

Demo:
```rust
#![feature(const_eval_limit)]
#![const_eval_limit = "0"]

const OW: u64 = {
    let mut res: u64 = 0;
    let mut i = 0;
    while i < u64::MAX {
        res = res.wrapping_add(i);
        i += 1;
    }
    res
};

fn main() {
    println!("{}", OW);
}
```
```
╭ ➜ ben@archlinux:~/rust
╰ ➤ rustc +stage1 spin.rs
^Cerror[E0080]: evaluation of constant value failed
 --> spin.rs:8:33
  |
8 |         res = res.wrapping_add(i);
  |                                 ^ Compilation was interrupted

note: erroneous constant used
  --> spin.rs:15:20
   |
15 |     println!("{}", OW);
   |                    ^^

note: erroneous constant used
  --> spin.rs:15:20
   |
15 |     println!("{}", OW);
   |                    ^^
   |
   = note: this note originates in the macro `$crate::format_args_nl` which comes from the expansion of the macro `println` (in Nightly builds, run with -Z macro-backtrace for more info)

error: aborting due to previous error

For more information about this error, try `rustc --explain E0080`.
```
2024-03-26 00:04:03 +00:00
Michael Goulet
9bda9ac76e Relax validation now 2024-03-24 21:15:23 -04:00
Michael Goulet
b7d67eace7 Require coroutine kind type to be passed to TyCtxt::coroutine_layout 2024-03-24 21:12:49 -04:00
Matthias Krüger
19d3827efe
Rollup merge of #122937 - Zalathar:unbox, r=oli-obk
Unbox and unwrap the contents of `StatementKind::Coverage`

The payload of coverage statements was historically a structure with several fields, so it was boxed to avoid bloating `StatementKind`.

Now that the payload is a single relatively-small enum, we can replace `Box<Coverage>` with just `CoverageKind`.

This patch also adds a size assertion for `StatementKind`, to avoid accidentally bloating it in the future.

``@rustbot`` label +A-code-coverage
2024-03-24 17:08:16 +01:00
Scott McMurray
3da115a93b Add+Use mir::BinOp::Cmp 2024-03-23 23:23:41 -07:00
Matthias Krüger
3d9ee88ea2
Rollup merge of #122168 - compiler-errors:inline-coroutine-body-validation, r=cjgillot
Fix validation on substituted callee bodies in MIR inliner

When inlining a coroutine, we will substitute the MIR body with the args of the call. There is code in the MIR validator that attempts to prevent query cycles, and will use the coroutine body directly when it detects that's the body that's being validated. That means that when inlining a coroutine body that has been substituted, it may no longer be parameterized over the original args of the coroutine, which will lead to substitution ICEs.

Fixes #119064
2024-03-24 01:05:51 +01:00
Ralf Jung
f2cff5ebb9 also rename the SIMD intrinsic 2024-03-23 23:03:37 +01:00
bors
2f090c30dd Auto merge of #122629 - RalfJung:assert-unsafe-precondition, r=saethlin
refactor check_{lang,library}_ub: use a single intrinsic

This enacts the plan I laid out [here](https://github.com/rust-lang/rust/pull/122282#issuecomment-1996917998): use a single intrinsic, called `ub_checks` (in aniticpation of https://github.com/rust-lang/compiler-team/issues/725), that just exposes the value of `debug_assertions` (consistently implemented in both codegen and the interpreter). Put the language vs library UB logic into the library.

This makes it easier to do something like https://github.com/rust-lang/rust/pull/122282 in the future: that just slightly alters the semantics of `ub_checks` (making it more approximating when crates built with different flags are mixed), but it no longer affects whether these checks can happen in Miri or compile-time.

The first commit just moves things around; I don't think these macros and functions belong into `intrinsics.rs` as they are not intrinsics.

r? `@saethlin`
2024-03-23 21:11:00 +00:00
Ralf Jung
6177530420 refactor check_{lang,library}_ub: use a single intrinsic, put policy into library 2024-03-23 18:45:05 +01:00
bors
020bbe46bd Auto merge of #122947 - matthiaskrgr:rollup-10j7orh, r=matthiaskrgr
Rollup of 11 pull requests

Successful merges:

 - #120577 (Stabilize slice_split_at_unchecked)
 - #122698 (Cancel `cargo update` job if there's no updates)
 - #122780 (Rename `hir::Local` into `hir::LetStmt`)
 - #122915 (Delay a bug if no RPITITs were found)
 - #122916 (docs(sync): normalize dot in fn summaries)
 - #122921 (Enable more mir-opt tests in debug builds)
 - #122922 (-Zprint-type-sizes: print the types of awaitees and unnamed coroutine locals.)
 - #122927 (Change an ICE regression test to use the original reproducer)
 - #122930 (add panic location to 'panicked while processing panic')
 - #122931 (Fix some typos in the pin.rs)
 - #122933 (tag_for_variant follow-ups)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-03-23 15:58:17 +00:00
bors
d6eb0f5a09 Auto merge of #122582 - scottmcm:swap-intrinsic-v2, r=oli-obk
Let codegen decide when to `mem::swap` with immediates

Making `libcore` decide this is silly; the backend has so much better information about when it's a good idea.

Thus this PR introduces a new `typed_swap` intrinsic with a fallback body, and replaces that fallback implementation when swapping immediates or scalar pairs.

r? oli-obk

Replaces #111744, and means we'll never need more libs PRs like #111803 or #107140
2024-03-23 13:57:55 +00:00
Ralf Jung
038e7c6c38 rename MIR int2ptr casts to match library name 2024-03-23 13:18:33 +01:00
Zalathar
ab92699f4a Unbox and unwrap the contents of StatementKind::Coverage
The payload of coverage statements was historically a structure with several
fields, so it was boxed to avoid bloating `StatementKind`.

Now that the payload is a single relatively-small enum, we can replace
`Box<Coverage>` with just `CoverageKind`.

This patch also adds a size assertion for `StatementKind`, to avoid
accidentally bloating it in the future.
2024-03-23 22:05:11 +11:00
Ralf Jung
928bd3b4e0 tag_for_variant follow-ups 2024-03-23 10:45:42 +01:00
bors
0ad5e0d2de Auto merge of #122900 - matthiaskrgr:rollup-nls90mb, r=matthiaskrgr
Rollup of 8 pull requests

Successful merges:

 - #114009 (compiler: allow transmute of ZST arrays with generics)
 - #122195 (Note that the caller chooses a type for type param)
 - #122651 (Suggest `_` for missing generic arguments in turbofish)
 - #122784 (Add `tag_for_variant` query)
 - #122839 (Split out `PredicatePolarity` from `ImplPolarity`)
 - #122873 (Merge my contributor emails into one using mailmap)
 - #122885 (Adjust better spastorino membership to triagebot's adhoc_groups)
 - #122888 (add a couple more tests)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-03-22 22:35:11 +00:00
Michael Goulet
78ebb939c1 Fix validation on substituted callee bodies in MIR inliner 2024-03-22 17:17:03 -04:00
Matthias Krüger
96be3e7cc8
Rollup merge of #122784 - jswrenn:tag_for_variant, r=compiler-errors
Add `tag_for_variant` query

This query allows for sharing code between `rustc_const_eval` and `rustc_transmutability`. It's a precursor to a PR I'm working on to entirely replace the bespoke layout computations in `rustc_transmutability`.

r? `@compiler-errors`
2024-03-22 20:31:29 +01:00
Jack Wrenn
2de9010f66 Add tag_for_variant query
This query allows for sharing code between `rustc_const_eval` and
`rustc_transmutability`.

Also moves `DummyMachine` to `rustc_const_eval`.
2024-03-22 17:01:49 +00:00
Michael Goulet
7be0dbe772 Make RawPtr take Ty and Mutbl separately 2024-03-22 11:13:29 -04:00
Michael Goulet
ff0c31e6b9 Programmatically convert some of the pat ctors 2024-03-22 11:13:29 -04:00
Matthias Krüger
e13c40c7bd
Rollup merge of #122542 - Zalathar:cleanup, r=oli-obk
coverage: Clean up marker statements that aren't needed later

Some of the marker statements used by coverage are added during MIR building for use by the InstrumentCoverage pass (during analysis), and are not needed afterwards.

```@rustbot``` label +A-code-coverage
2024-03-22 11:37:00 +01:00
Matthias Krüger
84e55be8da
Rollup merge of #122537 - RalfJung:interpret-allocation, r=oli-obk
interpret/allocation: fix aliasing issue in interpreter and refactor getters a bit

That new raw getter will be needed to let Miri pass pointers to natively executed FFI code ("extern-so" mode).

While doing that I realized our get_bytes_mut are named less scary than get_bytes_unchecked so I rectified that. Also I realized `mem_copy_repeatedly` would break if we called it for multiple overlapping copies so I made sure this does not happen.

And I realized that we are actually [violating Stacked Borrows in the interpreter](https://rust-lang.zulipchat.com/#narrow/stream/136281-t-opsem/topic/I.20think.20Miri.20violates.20Stacked.20Borrows.20.F0.9F.99.88).^^ That was introduced in https://github.com/rust-lang/rust/pull/87777.

r? ```@oli-obk```
2024-03-22 11:36:59 +01:00
Zalathar
91aae58568 coverage: Clean up marker statements that aren't needed later
Some of the marker statements used by coverage are added during MIR building
for use by the InstrumentCoverage pass (during analysis), and are not needed
afterwards.
2024-03-22 20:20:41 +11:00
Matthias Krüger
4f3050b85a
Rollup merge of #121543 - onur-ozkan:clippy-args, r=oli-obk
various clippy fixes

We need to keep the order of the given clippy lint rules before passing them.
Since clap doesn't offer any useful interface for this purpose out of the box,
we have to handle it manually.

Additionally, this PR makes `-D` rules work as expected. Previously, lint rules were limited to `-W`. By enabling `-D`, clippy began to complain numerous lines in the tree, all of which have been resolved in this PR as well.

Fixes #121481
cc `@matthiaskrgr`
2024-03-20 05:51:22 +01:00
onur-ozkan
81d7d7aabd resolve clippy errors
Signed-off-by: onur-ozkan <work@onurozkan.dev>
2024-03-20 00:12:00 +03:00
Oli Scherer
3a09680671 Ensure nested statics have a HIR node to prevent various queries from ICEing 2024-03-19 09:38:15 +00:00
bors
196ff446d2 Auto merge of #122493 - lukas-code:sized-constraint, r=lcnr
clean up `Sized` checking

This PR cleans up `sized_constraint` and related functions to make them simpler and faster. This should not make more or less code compile, but it can change error output in some rare cases.

## enums and unions are `Sized`, even if they are not WF

The previous code has some special handling for enums, which made them sized if and only if the last field of each variant is sized. For example given this definition (which is not WF)
```rust
enum E<T1: ?Sized, T2: ?Sized, U1: ?Sized, U2: ?Sized> {
    A(T1, T2),
    B(U1, U2),
}
```
the enum was sized if and only if `T2` and `U2` are sized, while `T1` and `T2` were ignored for `Sized` checking. After this PR this enum will always be sized.

Unsized enums are not a thing in Rust and removing this special case allows us to return an `Option<Ty>` from `sized_constraint`, rather than a `List<Ty>`.

Similarly, the old code made an union defined like this
```rust
union Union<T: ?Sized, U: ?Sized> {
    head: T,
    tail: U,
}
```
sized if and only if `U` is sized, completely ignoring `T`. This just makes no sense at all and now this union is always sized.

## apply the "perf hack" to all (non-error) types, instead of just type parameters

This "perf hack" skips evaluating `sized_constraint(adt): Sized` if `sized_constraint(adt): Sized` exactly matches a predicate defined on `adt`, for example:

```rust
// `Foo<T>: Sized` iff `T: Sized`, but we know `T: Sized` from a predicate of `Foo`
struct Foo<T /*: Sized */>(T);
```

Previously this was only applied to type parameters and now it is applied to every type. This means that for example this type is now always sized:

```rust
// Note that this definition is WF, but the type `S<T>` not WF in the global/empty ParamEnv
struct S<T>([T]) where [T]: Sized;
```

I don't anticipate this to affect compile time of any real-world program, but it makes the code a bit nicer and it also makes error messages a bit more consistent if someone does write such a cursed type.

## tuples are sized if the last type is sized

The old solver already has this behavior and this PR also implements it for the new solver and `is_trivially_sized`. This makes it so that tuples work more like a struct defined like this:

```rust
struct TupleN<T1, T2, /* ... */ Tn: ?Sized>(T1, T2, /* ... */ Tn);
```

This might improve the compile time of programs with large tuples a little, but is mostly also a consistency fix.

## `is_trivially_sized` for more types

This function is used post-typeck code (borrowck, const eval, codegen) to skip evaluating `T: Sized` in some cases. It will now return `true` in more cases, most notably `UnsafeCell<T>` and `ManuallyDrop<T>` where `T.is_trivially_sized`.

I'm anticipating that this change will improve compile time for some real world programs.
2024-03-19 04:21:14 +00:00
Matthias Krüger
980248605a
Rollup merge of #122158 - estebank:feature-sugg, r=WaffleLapkin
Provide structured suggestion for `#![feature(foo)]`

```
error: `S2<'_>` is forbidden as the type of a const generic parameter
  --> $DIR/lifetime-in-const-param.rs:5:23
   |
LL | struct S<'a, const N: S2>(&'a ());
   |                       ^^
   |
   = note: the only supported types are integers, `bool` and `char`
help: add `#![feature(adt_const_params)]` to the crate attributes to enable more complex and user defined types
   |
LL + #![feature(adt_const_params)]
   |
```

Fix #55941.
2024-03-18 22:24:38 +01:00
Esteban Küber
6c31f6ce12 Provide structured suggestion for #![feature(foo)]
```
error: `S2<'_>` is forbidden as the type of a const generic parameter
  --> $DIR/lifetime-in-const-param.rs:5:23
   |
LL | struct S<'a, const N: S2>(&'a ());
   |                       ^^
   |
   = note: the only supported types are integers, `bool` and `char`
help: add `#![feature(adt_const_params)]` to the crate attributes to enable more complex and user defined types
   |
LL + #![feature(adt_const_params)]
   |
```

Fix #55941.
2024-03-18 16:08:58 +00:00
Matthias Krüger
3fa48ec849
Rollup merge of #122647 - RalfJung:box-to-raw-retag, r=oli-obk
add_retag: ensure box-to-raw-ptr casts are preserved for Miri

In https://github.com/rust-lang/rust/pull/122233 I added `retag_box_to_raw` not realizing that we can already do `addr_of_mut!(*bx)` to turn a box into a raw pointer without an intermediate reference. We just need to ensure this information is preserved past the ElaborateBoxDerefs pass.

r? ``@oli-obk``
2024-03-18 16:27:08 +01:00
Oli Scherer
adda9da604 Avoid various uses of Option<Span> in favor of using DUMMY_SP in the few cases that used None 2024-03-18 09:34:08 +00:00
Ralf Jung
c96fa5e143 add_retag: ensure box-to-raw-ptr casts are preserved for Miri 2024-03-18 10:32:25 +01:00
Scott McMurray
7d537106a1 Let codegen decide when to mem::swap with immediates
Making `libcore` decide this is silly; the backend has so much better information about when it's a good idea.

So introduce a new `typed_swap` intrinsic with a fallback body, but replace that implementation for immediates and scalar pairs.
2024-03-17 11:59:18 -07:00
Ralf Jung
872781b226 interpret/memory: explain why we use == on bool 2024-03-17 19:32:03 +01:00
Ben Kimock
9e0d1a3284 Print a backtrace in const eval if interrupted 2024-03-17 11:55:20 -04:00
Ralf Jung
7be47b219d interpret/allocation: fix aliasing issue in interpreter and refactor getters a bit
- rename mutating functions to be more scary
- add a new raw bytes getter
2024-03-15 15:58:37 +01:00
Lukas Markeffsky
8fe99f57a4 remove unnecessary sized checks 2024-03-14 21:28:48 +01:00
Oli Scherer
a316c21dc8 Rename some things around validation error reporting to signal that it is in fact about validation failures 2024-03-14 12:21:35 +00:00
Oli Scherer
16046c77aa Move the entire success path into eval_body_using_ecx 2024-03-14 12:21:29 +00:00
Oli Scherer
2e6c4900b6 Move validation into eval_body_using_ecx 2024-03-14 12:21:23 +00:00
Oli Scherer
cc7e0b2200 Share the InterpCx creation between static and const evaluation 2024-03-14 12:21:18 +00:00
Oli Scherer
02a0ac8058 Remove an argument that can be computed cheaply 2024-03-14 12:21:12 +00:00
Oli Scherer
d3b7b558aa Directly pass in the stack instead of computing it from a machine 2024-03-14 12:21:06 +00:00
Oli Scherer
d2d2bd2736 Move generate_stacktrace_from_stack away from InterpCx to avoid having to know the Machine type 2024-03-14 12:20:58 +00:00
Oli Scherer
6b936b6c08 Move InterpCx into eval_in_interpreter 2024-03-14 11:40:42 +00:00
Oli Scherer
8b8efd157b Move error handling into const_validate_mplace 2024-03-14 11:40:36 +00:00
Oli Scherer
93888cd0a4 Move only usage of take_static_root_alloc to its definition and inline it 2024-03-14 11:40:30 +00:00
Oli Scherer
d6c999754c Generalize eval_in_interpreter with a helper trait 2024-03-14 11:40:23 +00:00
Oli Scherer
71f1943cbf Fix accidental re-addition of removed code in a previous PR 2024-03-14 11:39:27 +00:00
bors
cb580ff677 Auto merge of #122243 - RalfJung:local-place-sanity-check, r=oli-obk
interpret: ensure that Place is never used for a different frame

We store the address where the stack frame stores its `locals`. The idea is that even if we pop and push, or switch to a different thread with a larger number of frames, then the `locals` address will most likely change so we'll notice that problem. This is made possible by some recent changes by `@WaffleLapkin,` where we no longer use `Place` across things that change the number of stack frames.

I made these debug assertions for now, just to make sure this can't cost us any perf.

The first commit is unrelated but it's a one-line comment change so it didn't warrant a separate PR...

r? `@oli-obk`
2024-03-14 07:28:07 +00:00
Felix S. Klock II
9c33cc62aa placate tidy. 2024-03-13 10:51:12 -04:00
Felix S. Klock II
a8549b4152 downgrade mutable-ptr-in-final-value from hard-error to future-incompat lint to address issue 121610. 2024-03-13 10:32:39 -04:00
bors
9ce37dc729 Auto merge of #122240 - RalfJung:miri-addr-reuse, r=oli-obk
miri: add some chance to reuse addresses of previously freed allocations

The hope is that this can help us find ABA issues.

Unfortunately this needs rustc changes so I can't easily run the regular benchmark suite. I used `src/tools/miri/tests/pass/float_nan.rs` as a substitute:
```
Before:
Benchmark 1: ./x.py run miri --stage 0 --args src/tools/miri/tests/pass/float_nan.rs --args --edition=2021
  Time (mean ± σ):      9.570 s ±  0.013 s    [User: 9.279 s, System: 0.290 s]
  Range (min … max):    9.561 s …  9.579 s    2 runs

After:
Benchmark 1: ./x.py run miri --stage 0 --args src/tools/miri/tests/pass/float_nan.rs --args --edition=2021
  Time (mean ± σ):      9.698 s ±  0.046 s    [User: 9.413 s, System: 0.279 s]
  Range (min … max):    9.666 s …  9.731 s    2 runs
```
That's a ~1.3% slowdown, which seems fine to me. I have seen a lot of noise in this style of benchmarking so I don't quite trust this anyway; we can make further experiments in the Miri repo after this migrated there.

r? `@oli-obk`
2024-03-13 09:22:55 +00:00
Oli Scherer
bbedde835e Exhaustively match on the mutability and nestedness 2024-03-12 05:53:47 +00:00
Oli Scherer
926bfe5078 s/mt/mutability/ 2024-03-12 05:53:46 +00:00
Oli Scherer
d3514a036d Ensure nested allocations in statics do not get deduplicated 2024-03-12 05:53:46 +00:00
Oli Scherer
0b4cbee660 Add nested bool to DefKind::Static.
Will be used in the next commit
2024-03-12 05:53:46 +00:00
Oli Scherer
9816915954 Change DefKind::Static to a struct variant 2024-03-12 05:53:46 +00:00
Jubilee
f6ca4258d2
Rollup merge of #122249 - RalfJung:machine-read-hook, r=oli-obk
interpret: do not call machine read hooks during validation

Fixes https://github.com/rust-lang/miri/issues/3347

r? ``@oli-obk``
2024-03-11 09:29:36 -07:00
Jubilee
9300fbbed1
Rollup merge of #121893 - RalfJung:const-interior-mut-tests, r=oli-obk
Add tests (and a bit of cleanup) for interior mut handling in promotion and const-checking

Basically these are the parts of https://github.com/rust-lang/rust/pull/121786 that can be salvaged.

r? ``@oli-obk``
2024-03-11 09:29:34 -07:00
Ralf Jung
279465b5e8 const-checking: add some corner case tests, and fix some nits 2024-03-11 14:15:24 +01:00
bors
cd81f5b27e Auto merge of #122132 - nnethercote:diag-renaming3, r=nnethercote
Diagnostic renaming 3

A sequel to https://github.com/rust-lang/rust/pull/121780.

r? `@davidtwco`
2024-03-11 00:34:44 +00:00
Nicholas Nethercote
e9f0d9be0e Rename DecorateLint as LintDiagnostic.
To match `derive(LintDiagnostic)`.
2024-03-11 10:04:50 +11:00
Nicholas Nethercote
7a294e998b Rename IntoDiagnostic as Diagnostic.
To match `derive(Diagnostic)`.

Also rename `into_diagnostic` as `into_diag`.
2024-03-11 09:15:09 +11:00
Nicholas Nethercote
a09b1d33a7 Rename IntoDiagnosticArg as IntoDiagArg.
Also rename `into_diagnostic_arg` as `into_diag_arg`, and
`NotIntoDiagnosticArg` as `NotInotDiagArg`.
2024-03-11 09:12:19 +11:00
Nicholas Nethercote
256d802233 Remove unused impls from some subdiagnostics. 2024-03-11 09:08:33 +11:00
Matthias Krüger
9ccbbda6ac
Rollup merge of #122290 - RalfJung:mir-printing, r=compiler-errors
MIR printing: print the path of uneval'd const

Currently it just prints `const _` which makes it impossible to say which constant is being referred to.

Also refer to promoteds in a consistent way; previously MIR printing would do
```
promoted[0] in C1: &Option<Cell<i32>> = {
    // ...
}
```
Now that should be
```
const C1::promoted[0]: &Option<Cell<i32>> = {
    // ...
}
```

We don't seem to have a test for that so I tried it by hand, it seems to work:
```
const main::promoted[12]: &[&str; 3] = {
    let mut _0: &[&str; 3];
    let mut _1: [&str; 3];
    let mut _2: &str;
    let mut _3: &str;
    let mut _4: &str;
    let mut _5: &str;

    bb0: {
        _3 = const "b";
        _2 = &(*_3);
        _5 = const "c";
        _4 = &(*_5);
        _1 = [const "a", move _2, move _4];
        _0 = &_1;
        return;
    }
}
```
2024-03-10 22:16:43 +01:00
Matthias Krüger
b02f2a0e76
Rollup merge of #122286 - RalfJung:resolve, r=compiler-errors
use Instance::expect_resolve() instead of unwraping Instance::resolve()
2024-03-10 22:16:43 +01:00
Ralf Jung
7d99e80c55 MIR printing: print the path of uneval'd const; refer to promoteds in a consistent way 2024-03-10 14:59:41 +01:00
Ralf Jung
aa9145e6ea use Instance::expect_resolve() instead of unwraping Instance::resolve() 2024-03-10 11:49:33 +01:00
Matthias Krüger
fdcd05178d
Rollup merge of #121860 - mu001999:master, r=Nilstrieb
Add a tidy check that checks whether the fluent slugs only appear once

As ``````@Nilstrieb`````` said in https://github.com/rust-lang/rust/pull/121828#issuecomment-1972622855:
> Might make sense to have a tidy check that checks whether the fluent slugs only appear once in the source code and lint for that
there's a tidy check already for sorting

We can get the tidy check error:
```
tidy check
tidy error: /path/to/rust/compiler/rustc_const_eval/messages.ftl: message `const_eval_invalid_align` is not used
tidy error: /path/to/rust/compiler/rustc_lint/messages.ftl: message `lint_trivial_untranslatable_diag` is not used
tidy error: /path/to/rust/compiler/rustc_parse/messages.ftl: message `parse_invalid_literal_suffix` is not used
tidy error: /path/to/rust/compiler/rustc_infer/messages.ftl: message `infer_need_type_info_in_coroutine` is not used
tidy error: /path/to/rust/compiler/rustc_passes/messages.ftl: message `passes_expr_not_allowed_in_context` is not used
tidy error: /path/to/rust/compiler/rustc_passes/messages.ftl: message `passes_layout` is not used
tidy error: /path/to/rust/compiler/rustc_parse/messages.ftl: message `parse_not_supported` is not used
```

r? ``````@Nilstrieb``````
2024-03-10 10:58:16 +01:00
Ralf Jung
c3342b41b5 remove unnecessary frame parameter from after_local_allocated 2024-03-10 09:52:29 +01:00
bors
768408af12 Auto merge of #121662 - saethlin:precondition-unification, r=RalfJung
Distinguish between library and lang UB in assert_unsafe_precondition

As described in https://github.com/rust-lang/rust/pull/121583#issuecomment-1963168186, `assert_unsafe_precondition` now explicitly distinguishes between language UB (conditions we explicitly optimize on) and library UB (things we document you shouldn't do, and maybe some library internals assume you don't do).

`debug_assert_nounwind` was originally added to avoid the "only at runtime" aspect of `assert_unsafe_precondition`. Since then the difference between the macros has gotten muddied. This totally revamps the situation.

Now _all_ preconditions shall be checked with `assert_unsafe_precondition`. If you have a precondition that's only checkable at runtime, do a `const_eval_select` hack, as done in this PR.

r? RalfJung
2024-03-10 01:23:54 +00:00
Ralf Jung
bf47df8b0b interpret: do not call machine read hooks during validation 2024-03-09 20:00:24 +01:00
Ralf Jung
4497990dff remove some frame parameters that are no longer needed 2024-03-09 18:28:14 +01:00
Ralf Jung
b888e895de remove a machine hook that is no longer used 2024-03-09 18:28:14 +01:00
Ralf Jung
2005c2e54d interpret: ensure that Place is never used for a different frame 2024-03-09 18:28:14 +01:00
Ben Kimock
27cf4bb985
Only enable library UB checks in const-eval/Miri when debug_assertions are enabled
Co-authored-by: Ralf Jung <post@ralfj.de>
2024-03-09 11:34:15 -05:00
Ralf Jung
16e869a678 interpret: pass Size and Align to before_memory_deallocation 2024-03-09 13:53:40 +01:00
Ralf Jung
e632e3f9a5 miri: do not apply aliasing restrictions to Box with custom allocator 2024-03-09 13:08:55 +01:00
Ben Kimock
5a93a59fd5 Distinguish between library and lang UB in assert_unsafe_precondition 2024-03-08 18:53:58 -05:00
Matthias Krüger
2c3ca0931d
Rollup merge of #122076 - WaffleLapkin:mplace-args, r=RalfJung
Tweak the way we protect in-place function arguments in interpreters

Use `MPlaceTy` instead of `PlaceTy` in `FnArg` and ignore (copy) locals in an earlier step ("Locals that don't have their address taken are as protected as they can ever be").

This seems to be crucial for tail call support (as they can't refer to caller's locals which are killed when replacing the stack frame).

r? `@RalfJung`
cc `@oli-obk`
see https://github.com/rust-lang/rust/pull/121273#issuecomment-1980210690
2024-03-08 21:02:00 +01:00
Maybe Waffle
a98432213b Tweak the way we protect in-place function arguments in interpreters
Use `MPlaceTy` instead of `PlaceTy` in `FnArg` and ignore (copy) locals in an
earlier step ("Locals that don't have their address taken are as protected as
they can ever be").

This seems to be crucial for tail call support (as they can't refer to caller's
locals which are killed when replacing the stack frame).
2024-03-08 13:08:35 +00:00
Matthias Krüger
8abeac230a
Rollup merge of #122183 - RalfJung:read-discriminant-uninhabited-variant, r=tmiasko
interpret: update comment about read_discriminant on uninhabited variants
2024-03-08 13:22:29 +01:00
Matthias Krüger
3d71bada5a
Rollup merge of #122173 - compiler-errors:ptr-equality-in-ctfe, r=lcnr
Don't ICE in CTFE if raw/fn-ptr types differ

Fixes #121688

r? lcnr
2024-03-08 13:22:27 +01:00
Ralf Jung
2e5f86c6a7 interpret: update comment about read_discriminant on uninhabited variants 2024-03-08 10:52:33 +01:00
Matthias Krüger
d774fbea7c
Rollup merge of #119365 - nbdd0121:asm-goto, r=Amanieu
Add asm goto support to `asm!`

Tracking issue: #119364

This PR implements asm-goto support, using the syntax described in "future possibilities" section of [RFC2873](https://rust-lang.github.io/rfcs/2873-inline-asm.html#asm-goto).

Currently I have only implemented the `label` part, not the `fallthrough` part (i.e. fallthrough is implicit). This doesn't reduce the expressive though, since you can use label-break to get arbitrary control flow or simply set a value and rely on jump threading optimisation to get the desired control flow. I can add that later if deemed necessary.

r? ``@Amanieu``
cc ``@ojeda``
2024-03-08 08:19:17 +01:00
Michael Goulet
025ad403a9 Don't ICE in CTFE if raw/fn-ptr types differ 2024-03-08 02:57:06 +00:00
bors
52f8aec14c Auto merge of #121985 - RalfJung:interpret-return-place, r=oli-obk
interpret: avoid a long-lived PlaceTy in stack frames

`PlaceTy` uses a representation that's not very stable under changes to the stack. I'd feel better if we didn't have one in the long-term machine state.

r? `@oli-obk`
2024-03-07 12:33:19 +00:00
Matthias Krüger
efe9deace8
Rollup merge of #121382 - nnethercote:rework-untranslatable_diagnostic-lint, r=davidtwco
Rework `untranslatable_diagnostic` lint

Currently it only checks calls to functions marked with `#[rustc_lint_diagnostics]`. This PR changes it to check calls to any function with an `impl Into<{D,Subd}iagnosticMessage>` parameter. This greatly improves its coverage and doesn't rely on people remembering to add `#[rustc_lint_diagnostics]`. It also lets us add `#[rustc_lint_diagnostics]` to a number of functions that don't have an `impl Into<{D,Subd}iagnosticMessage>`, such as `Diag::span`.

r? ``@davidtwco``
2024-03-06 22:02:46 +01:00
Nicholas Nethercote
b7d58eef4b Rewrite the untranslatable_diagnostic lint.
Currently it only checks calls to functions marked with
`#[rustc_lint_diagnostics]`. This commit changes it to check calls to
any function with an `impl Into<{D,Subd}iagMessage>` parameter. This
greatly improves its coverage and doesn't rely on people remembering to
add `#[rustc_lint_diagnostics]`.

The commit also adds `#[allow(rustc::untranslatable_diagnostic)`]
attributes to places that need it that are caught by the improved lint.
These places that might be easy to convert to translatable diagnostics.

Finally, it also:
- Expands and corrects some comments.
- Does some minor formatting improvements.
- Adds missing `DecorateLint` cases to
  `tests/ui-fulldeps/internal-lints/diagnostics.rs`.
2024-03-06 14:19:01 +11:00
bors
b77e0184a9 Auto merge of #122045 - matthiaskrgr:rollup-5l3vpn7, r=matthiaskrgr
Rollup of 9 pull requests

Successful merges:

 - #121065 (Add basic i18n guidance for `Display`)
 - #121744 (Stop using Bubble in coherence and instead emulate it with an intercrate check)
 - #121829 (Dummy tweaks (attempt 2))
 - #121857 (Implement async closure signature deduction)
 - #121894 (const_eval_select: make it safe but be careful with what we expose on stable for now)
 - #122014 (Change some attributes to only_local.)
 - #122016 (will_wake tests fail on Miri and that is expected)
 - #122018 (only set noalias on Box with the global allocator)
 - #122028 (Remove some dead code)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-03-06 02:18:22 +00:00
Matthias Krüger
b08837f180
Rollup merge of #122018 - RalfJung:box-custom-alloc, r=oli-obk
only set noalias on Box with the global allocator

As discovered in https://github.com/rust-lang/miri/issues/3341, `noalias` and custom allocators don't go well together.

rustc can now check whether a Box uses the global allocator. This replaces the previous ad-hoc and rather unprincipled check for a zero-sized allocator.

This is the rustc part of fixing that; Miri will also need a patch.
2024-03-05 22:10:02 +01:00
Jason Newcomb
be9b125d41 Convert TypeVisitor and DefIdVisitor to use VisitorResult 2024-03-05 13:28:15 -05:00
Ralf Jung
f391c0793b only set noalias on Box with the global allocator 2024-03-05 15:03:33 +01:00
Matthias Krüger
92ff43d87b
Rollup merge of #121997 - RalfJung:cast-float-ty, r=compiler-errors
interpret/cast: make more matches on FloatTy properly exhaustive

Actually implementing these is pretty trivial (at least once all the scalar methods are added, which happens in https://github.com/rust-lang/rust/pull/121926), but I'm staying consistent with the other f16/f128 PRs. Also adding adding all the tests to Miri would be quite a lot of work.

There's probably some way to reduce the code duplication here with more use of generics... but that's a future refactor.^^

r? ```@tgross35```
2024-03-05 06:40:33 +01:00
Nicholas Nethercote
18715c98c6 Rename DiagnosticMessage as DiagMessage. 2024-03-05 12:14:49 +11:00
Ralf Jung
3f0b6a0d1c consistently use MPlaceTy for return places 2024-03-04 23:40:26 +01:00
Ralf Jung
681dc38283
typo
Co-authored-by: Rémy Rakic <remy.rakic+github@gmail.com>
2024-03-04 23:18:02 +01:00
Ralf Jung
86e88fccd3 interpret/cast: make more matches on FloatTy properly exhaustive 2024-03-04 22:05:37 +01:00
Ralf Jung
8de72e4e8b interpret: avoid a long-lived PlaceTy in stack frames 2024-03-04 19:01:39 +01:00
Guillaume Boisseau
200019c199
Rollup merge of #121731 - oli-obk:eager_opaque_checks, r=compiler-errors
Now that inlining, mir validation and const eval all use reveal-all, we won't be constraining hidden types here anymore

r? `@compiler-errors`

one bubble down, two more to go

the test is unrelated, just something I noticed would be good to test in both the old solver and the new.
2024-03-02 20:13:23 +01:00
r0cky
d88c7ffc62 Remove unused fluent messages 2024-03-03 00:57:45 +08:00
Ralf Jung
d9a2886ef8 add comment and test: we do not do value-based reasoning for promotion of unions 2024-03-02 10:52:49 +01:00
bors
6cbf0926d5 Auto merge of #121728 - tgross35:f16-f128-step1-ty-updates, r=compiler-errors
Add stubs in IR and ABI for `f16` and `f128`

This is the very first step toward the changes in https://github.com/rust-lang/rust/pull/114607 and the [`f16` and `f128` RFC](https://rust-lang.github.io/rfcs/3453-f16-and-f128.html). It adds the types to `rustc_type_ir::FloatTy` and `rustc_abi::Primitive`, and just propagates those out as `unimplemented!` stubs where necessary.

These types do not parse yet so there is no feature gate, and it should be okay to use `unimplemented!`.

The next steps will probably be AST support with parsing and the feature gate.

r? `@compiler-errors`
cc `@Nilstrieb` suggested breaking the PR up in https://github.com/rust-lang/rust/pull/120645#issuecomment-1925900572
2024-03-01 03:36:11 +00:00
Matthias Krüger
255fdcc858
Rollup merge of #121782 - RalfJung:mutable-ref-in-static, r=oli-obk
allow statics pointing to mutable statics

Fixes https://github.com/rust-lang/rust/issues/120450 for good. We can even simplify our checks: no need to specifically go looking for mutable references in const, we can just reject any reference that points to something mutable.

r? `@oli-obk`
2024-02-29 20:50:04 +01:00
Ralf Jung
3cc8c8d44b allow statics pointing to mutable statics 2024-02-29 09:34:15 +01:00
bors
c475e2303b Auto merge of #121489 - nnethercote:diag-renaming, r=davidtwco
Diagnostic renaming

Renaming various diagnostic types from `Diagnostic*` to `Diag*`. Part of https://github.com/rust-lang/compiler-team/issues/722. There are more to do but this is enough for one PR.

r? `@davidtwco`
2024-02-28 20:39:38 +00:00
Trevor Gross
e3f63d9375 Add f16 and f128 to rustc_type_ir::FloatTy and rustc_abi::Primitive
Make changes necessary to support these types in the compiler.
2024-02-28 12:58:32 -05:00
Oli Scherer
0bb2a6b780 Now that inlining, mir validation and const eval all use reveal-all, we won't be constraining hidden types here anymore 2024-02-28 09:59:50 +00:00
Nicholas Nethercote
8f3b007abc Rename DiagnosticImportance as DiagImportance. 2024-02-28 08:55:38 +11:00
Nicholas Nethercote
8199632aa8 Rename DiagnosticArg{,Map,Name,Value} as DiagArg{,Map,Name,Value}. 2024-02-28 08:55:37 +11:00
Nicholas Nethercote
899cb40809 Rename DiagnosticBuilder as Diag.
Much better!

Note that this involves renaming (and updating the value of)
`DIAGNOSTIC_BUILDER` in clippy.
2024-02-28 08:55:35 +11:00
Oli Scherer
8a6d3535f7 Split rustc_type_ir to avoid rustc_ast from depending on it 2024-02-27 18:11:23 +00:00
bors
381d69953b Auto merge of #121549 - matthiaskrgr:rollup-1hvu3lb, r=matthiaskrgr
Rollup of 7 pull requests

Successful merges:

 - #121435 (Account for RPITIT in E0310 explicit lifetime constraint suggestion)
 - #121490 (Rustdoc: include crate name in links for local primitives)
 - #121520 (delay cloning of iterator items)
 - #121522 (check that simd_insert/extract indices are in-bounds)
 - #121531 (Ignore less tests in debug builds)
 - #121539 (compiler/rustc_target/src/spec/base/apple/tests.rs: Avoid unnecessary large move)
 - #121542 (update stdarch)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-02-24 21:08:39 +00:00
Gary Guo
b044aaa905 Change InlineAsm to allow multiple targets instead 2024-02-24 18:50:09 +00:00
Matthias Krüger
86a7fc840f compiler: clippy::complexity fixes 2024-02-23 19:56:35 +01:00
Ralf Jung
134e2b2056 interpret: do no ICE on OOB shuffle/insert/extract indices 2024-02-23 19:43:59 +01:00
Nicholas Nethercote
b38ed1afa6 Overhaul Diagnostic args.
First, introduce a typedef `DiagnosticArgMap`.

Second, make the `args` field public, and remove the `args` getter and
`replace_args` setter. These were necessary previously because the getter
had a `#[allow(rustc::potential_query_instability)]` attribute, but that
was removed in #120931 when the args were changed from `FxHashMap` to
`FxIndexMap`. (All the other `Diagnostic` fields are public.)
2024-02-22 12:51:05 +11:00
León Orell Valerian Liehr
bd7ba278e5
Rollup merge of #121396 - RalfJung:mir-const-value-inspect, r=oli-obk
make it possible for outside crates to inspect a mir::ConstValue with the interpreter

For MiniRust we need to convert MIR constant values into MiniRust constant values. However, it's not currently possible to get nice high-level access to the inerts of a `ConstValue`: we can access the raw contents (the allocation / `ScalarInt`), but if it is e.g. of enum type and we want to determine which variant is encoded, we are stuck. There's only `try_destructure_mir_constant_for_user_output` which is meant for diagnostics, so it doesn't fit.

The interpreter has all the APIs to traverse such a value, so we just need a way to get such a ConstValue into an interpreter instance. This adds the public functions necessary to make that happen.
2024-02-21 16:33:00 +01:00
Ralf Jung
9eabdc2a4c make it possible for outside crates to inspect a mir::ConstValue with the interpreter 2024-02-21 14:32:52 +01:00
Nicholas Nethercote
2903bbbc15 Convert bugs back to delayed_bugs.
This commit undoes some of the previous commit's mechanical changes,
based on human judgment.
2024-02-21 10:35:54 +11:00
Nicholas Nethercote
010f3944e0 Convert delayed_bugs to bugs.
I have a suspicion that quite a few delayed bug paths are impossible to
reach, so I did an experiment.

I converted every `delayed_bug` to a `bug`, ran the full test suite,
then converted back every `bug` that was hit. A surprising number were
never hit.

The next commit will convert some more back, based on human judgment.
2024-02-21 10:20:05 +11:00
bors
29f87ade9d Auto merge of #120576 - nnethercote:merge-Diagnostic-DiagnosticBuilder, r=davidtwco
Overhaul `Diagnostic` and `DiagnosticBuilder`

Implements the first part of https://github.com/rust-lang/compiler-team/issues/722, which moves functionality and use away from `Diagnostic`, onto `DiagnosticBuilder`.

Likely follow-ups:
- Move things around, because this PR was written to minimize diff size, so some things end up in sub-optimal places. E.g. `DiagnosticBuilder` has impls in both `diagnostic.rs` and `diagnostic_builder.rs`.
- Rename `Diagnostic` as `DiagInner` and `DiagnosticBuilder` as `Diag`.

r? `@davidtwco`
2024-02-20 12:05:09 +00:00
Nicholas Nethercote
f6f8779843 Reduce capabilities of Diagnostic.
Currently many diagnostic modifier methods are available on both
`Diagnostic` and `DiagnosticBuilder`. This commit removes most of them
from `Diagnostic`. To minimize the diff size, it keeps them within
`diagnostic.rs` but changes the surrounding `impl Diagnostic` block to
`impl DiagnosticBuilder`. (I intend to move things around later, to give
a more sensible code layout.)

`Diagnostic` keeps a few methods that it still needs, like `sub`,
`arg`, and `replace_args`.

The `forward!` macro, which defined two additional methods per call
(e.g. `note` and `with_note`), is replaced by the `with_fn!` macro,
which defines one additional method per call (e.g. `with_note`). It's
now also only used when necessary -- not all modifier methods currently
need a `with_*` form. (New ones can be easily added as necessary.)

All this also requires changing `trait AddToDiagnostic` so its methods
take `DiagnosticBuilder` instead of `Diagnostic`, which leads to many
mechanical changes. `SubdiagnosticMessageOp` gains a type parameter `G`.

There are three subdiagnostics -- `DelayedAtWithoutNewline`,
`DelayedAtWithNewline`, and `InvalidFlushedDelayedDiagnosticLevel` --
that are created within the diagnostics machinery and appended to
external diagnostics. These are handled at the `Diagnostic` level, which
means it's now hard to construct them via `derive(Diagnostic)`, so
instead we construct them by hand. This has no effect on what they look
like when printed.

There are lots of new `allow` markers for `untranslatable_diagnostics`
and `diagnostics_outside_of_impl`. This is because
`#[rustc_lint_diagnostics]` annotations were present on the `Diagnostic`
modifier methods, but missing from the `DiagnosticBuilder` modifier
methods. They're now present.
2024-02-20 13:22:17 +11:00
Oli Scherer
9062697917 Always evaluate free constants and statics, even if previous errors occurred 2024-02-19 22:11:13 +00:00
Matthias Krüger
45d5773704
Rollup merge of #121085 - davidtwco:always-eager-diagnostics, r=nnethercote
errors: only eagerly translate subdiagnostics

Subdiagnostics don't need to be lazily translated, they can always be eagerly translated. Eager translation is slightly more complex as we need to have a `DiagCtxt` available to perform the translation, which involves slightly more threading of that context.

This slight increase in complexity should enable later simplifications - like passing `DiagCtxt` into `AddToDiagnostic` and moving Fluent messages into the diagnostic structs rather than having them in separate files (working on that was what led to this change).

r? ```@nnethercote```
2024-02-17 18:47:40 +01:00
Ralf Jung
340f8aac7e const_mut_refs: allow mutable refs to statics 2024-02-17 10:19:17 +01:00
Guillaume Gomez
0c92146034
Rollup merge of #121179 - RalfJung:zst-mutable-refs, r=oli-obk
allow mutable references in const values when they point to no memory

Fixes https://github.com/rust-lang/rust/issues/120450

The second commit is just some drive-by test suite cleanup.

r? `@oli-obk`
2024-02-16 17:08:13 +01:00
bors
dfa88b328f Auto merge of #120500 - oli-obk:intrinsics2.0, r=WaffleLapkin
Implement intrinsics with fallback bodies

fixes #93145 (though we can port many more intrinsics)
cc #63585

The way this works is that the backend logic for generating custom code for intrinsics has been made fallible. The only failure path is "this intrinsic is unknown". The `Instance` (that was `InstanceDef::Intrinsic`) then gets converted to `InstanceDef::Item`, which represents the fallback body. A regular function call to that body is then codegenned. This is currently implemented for

* codegen_ssa (so llvm and gcc)
* codegen_cranelift

other backends will need to adjust, but they can just keep doing what they were doing if they prefer (though adding new intrinsics to the compiler will then require them to implement them, instead of getting the fallback body).

cc `@scottmcm` `@WaffleLapkin`

### todo

* [ ] miri support
* [x] default intrinsic name to name of function instead of requiring it to be specified in attribute
* [x] make sure that the bodies are always available (must be collected for metadata)
2024-02-16 09:53:01 +00:00
Ralf Jung
0702701297 allow mutable references in const values when they point to no memory 2024-02-16 10:09:12 +01:00
bors
1be468815c Auto merge of #120486 - reitermarkus:use-generic-nonzero, r=dtolnay
Use generic `NonZero` internally.

Tracking issue: https://github.com/rust-lang/rust/issues/120257
2024-02-16 07:46:31 +00:00
bors
fa9f77ff35 Auto merge of #120931 - chenyukang:yukang-cleanup-hashmap, r=michaelwoerister
Clean up potential_query_instability with FxIndexMap and UnordMap

From https://github.com/rust-lang/rust/pull/120485#issuecomment-1916437191

r? `@michaelwoerister`
2024-02-15 12:36:37 +00:00
David Wood
b80fc5d4e8
errors: only eagerly translate subdiagnostics
Subdiagnostics don't need to be lazily translated, they can always be
eagerly translated. Eager translation is slightly more complex as we need
to have a `DiagCtxt` available to perform the translation, which involves
slightly more threading of that context.

This slight increase in complexity should enable later simplifications -
like passing `DiagCtxt` into `AddToDiagnostic` and moving Fluent messages
into the diagnostic structs rather than having them in separate files
(working on that was what led to this change).

Signed-off-by: David Wood <david@davidtw.co>
2024-02-15 10:34:41 +00:00
bors
6a4222b511 Auto merge of #116564 - oli-obk:evaluated_static_in_metadata, r=RalfJung,cjgillot
Store static initializers in metadata instead of the MIR of statics.

This means that adding generic statics would be even more difficult, as we can't evaluate statics from other crates anymore, but the subtle issue I have encountered make me think that having this be an explicit problem is better.

The issue is that

```rust
static mut FOO: &mut u32 = &mut 42;
static mut BAR = unsafe { FOO };
```

gets different allocations, instead of referring to the same one. This is also true for non-static mut, but promotion makes `static FOO: &u32 = &42;` annoying to demo.

Fixes https://github.com/rust-lang/rust/issues/61345

## Why is this being done?

In order to ensure all crates see the same nested allocations (which is the last issue that needs fixing before we can stabilize [`const_mut_refs`](https://github.com/rust-lang/rust/issues/57349)), I am working on creating anonymous (from the Rust side, to LLVM it's like a regular static item) static items for the nested allocations in a static. If we evaluate the static item in a downstream crate again, we will end up duplicating its nested allocations (and in some cases, like the `match` case, even duplicate the main allocation).
2024-02-15 10:28:31 +00:00
Oli Scherer
73b38c661d Do not allocate a second "background" alloc id for the main allocation of a static.
Instead we re-use the static's alloc id within the interpreter for its initializer to refer to the `Allocation` that only exists within the interpreter.
2024-02-15 10:25:18 +00:00
Oli Scherer
e2386270df Return ConstAllocation from eval_static_initializer query directly 2024-02-15 10:25:18 +00:00
Oli Scherer
be6ccf13e3 Store static initializers in metadata instead of the MIR of statics. 2024-02-15 10:25:18 +00:00
Oli Scherer
95004e5ae2 Add new query just for static initializers 2024-02-15 10:25:18 +00:00
Oli Scherer
fc9d1a8133 Split a bool argument into two named functions 2024-02-15 10:25:18 +00:00
Markus Reiter
746a58d435
Use generic NonZero internally. 2024-02-15 08:09:42 +01:00
Michael Goulet
e6a21f549e Enforce coroutine-closure layouts are identical 2024-02-15 01:18:09 +00:00
yukang
3f27e4b3ea clean up potential_query_instability with FxIndexMap and UnordMap 2024-02-14 18:36:37 +08:00
Nicholas Nethercote
05849e8c2f Use fewer delayed bugs.
For some cases where it's clear that an error has already occurred,
e.g.:
- there's a comment stating exactly that, or
- things like HIR lowering, where we are lowering an error kind

The commit also tweaks some comments around delayed bug sites.
2024-02-14 20:30:37 +11:00
clubby789
4de3a3af4a Bump indexmap
`swap` has been deprecated in favour of `swap_remove` - the behaviour
is the same though.
2024-02-13 21:03:34 +00:00
Matthias Krüger
93e9579b5d
Rollup merge of #120959 - nnethercote:rm-good_path, r=oli-obk
Remove good path delayed bugs

Because they're not that useful, and kind of annoying. Details in the individual commits.

r? ```@compiler-errors```
2024-02-13 17:38:10 +01:00
Nicholas Nethercote
9f2aa09765 Remove good_path_delayed_bug.
It's only has a single remaining purpose: to ensure that a diagnostic is
printed when `trimmed_def_paths` is used. It's an annoying mechanism:
weak, with odd semantics, badly named, and gets in the way of other
changes.

This commit replaces it with a simpler `must_produce_diag` mechanism,
getting rid of a diagnostic `Level` along the way.
2024-02-13 09:33:35 +11:00
Matthias Krüger
cb0d74be28
Rollup merge of #120958 - ShoyuVanilla:remove-subst, r=oli-obk
Dejargonize `subst`

In favor of #110793, replace almost every occurence of `subst` and `substitution` from rustc codes, but they still remains in subtrees under `src/tools/` like clippy and test codes (I'd like to replace them after this)
2024-02-12 23:18:54 +01:00
Matthias Krüger
15896bdd18
Rollup merge of #120950 - compiler-errors:miri-async-closurs, r=RalfJung,oli-obk
Fix async closures in CTFE

First commit renames `is_coroutine_or_closure` into `is_closure_like`, because `is_coroutine_or_closure_or_coroutine_closure` seems confusing and long.

Second commit fixes some forgotten cases where we want to handle `TyKind::CoroutineClosure` the same as closures and coroutines.

The test exercises the change to `ValidityVisitor::aggregate_field_path_elem` which is the source of #120946, but not the change to `UsedParamsNeedSubstVisitor`, though I feel like it's not that big of a deal. Let me know if you'd like for me to look into constructing a test for the latter, though I have no idea what it'd look like (we can't assert against `TooGeneric` anywhere?).

Fixes #120946

r? oli-obk cc ``@RalfJung``
2024-02-12 23:18:53 +01:00
Matthias Krüger
3f67169a5f
Rollup merge of #120933 - RalfJung:const-check-misc, r=oli-obk
check_consts: fix duplicate errors, make importance consistent

This is stuff I noticed while working on https://github.com/rust-lang/rust/pull/120932, but it's orthogonal to that PR.

r? ``@oli-obk``
2024-02-12 18:04:09 +01:00
Matthias Krüger
ebe36ac815
Rollup merge of #120917 - chenyukang:yukang-dead-parameters, r=compiler-errors
Remove a bunch of dead parameters in functions

Found this kind of issue when working on https://github.com/rust-lang/rust/pull/119650
I wrote a trivial toy lint and manual review to find these.
2024-02-12 18:04:08 +01:00
Matthias Krüger
f08ece38a8
Rollup merge of #120833 - nnethercote:more-internal-emit_diagnostics-cleanups, r=oli-obk
More internal emit diagnostics cleanups

Miscellaneous improvements.

r? ``@oli-obk``
2024-02-12 18:04:07 +01:00
Oli Scherer
0eee945680 Make is_intrinsic query return the intrinsic name 2024-02-12 09:33:52 +00:00
Ralf Jung
5fa69deb00 fix cycle error when a static and a promoted are mutually recursive
This also now allows promoteds everywhere to point to 'extern static', because why not?
We still check that constants cannot transitively reach 'extern static' through references.
(We allow it through raw pointers.)
2024-02-12 09:48:14 +01:00
Nicholas Nethercote
e0a0cc2971 Remove dcx arg from ReportErrorExt::add_args.
Because it also has a `DiagnosticBuilder` arg, which contains a `dcx`
reference.

Also rename some `builder` variables as `diag`, because that's the usual
name.
2024-02-12 18:39:18 +11:00
Shoyu Vanilla
3856df059e Dejargnonize subst 2024-02-12 15:46:35 +09:00
yukang
2bcbc16caf remove a bunch of dead parameters in fn 2024-02-12 09:51:35 +08:00
Matthias Krüger
90b4e4116f
Rollup merge of #120885 - RalfJung:normal-visitor, r=compiler-errors
interpret/visitor: ensure we only see normalized types

[Prior discussion on Zulip](https://rust-lang.zulipchat.com/#narrow/stream/146212-t-compiler.2Fconst-eval/topic/Normalization.20after.20field.20projection)
r? `@compiler-errors`
2024-02-11 23:19:09 +01:00
Matthias Krüger
4c154a1a48
Rollup merge of #120872 - petrochenkov:opthirpar, r=cjgillot
hir: Refactor getters for HIR parents

See individual commits.

I ended up removing on of the FIXMEs from https://github.com/rust-lang/rust/pull/120206 instead of addressing it.
2024-02-11 23:19:08 +01:00
Michael Goulet
87816378ab Fix async closures in CTFE 2024-02-11 22:09:52 +00:00
Michael Goulet
cb024ba6e3 is_closure_like 2024-02-11 22:09:52 +00:00
bors
a166af7729 Auto merge of #120903 - matthiaskrgr:rollup-tmsuzth, r=matthiaskrgr
Rollup of 9 pull requests

Successful merges:

 - #119213 (simd intrinsics: add simd_shuffle_generic and other missing intrinsics)
 - #120272 (Suppress suggestions in derive macro)
 - #120773 (large_assignments: Allow moves into functions)
 - #120874 (Take empty `where` bounds into account when suggesting predicates)
 - #120882 (interpret/write_discriminant: when encoding niched variant, ensure the stored value matches)
 - #120883 (interpret: rename ReadExternStatic → ExternStatic)
 - #120890 (Adapt `llvm-has-rust-patches` validation to take `llvm-config` into account.)
 - #120895 (don't skip coercions for types with errors)
 - #120896 (Print kind of coroutine closure)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-02-11 17:43:51 +00:00
Ralf Jung
e13de311d5 make Primary/Secondary importance consistent between CellBorrow and MutBorrow 2024-02-11 15:12:10 +01:00
Ralf Jung
d5de9a6105 check_consts: fix some duplicate errors by not calling check_static unnecessarily 2024-02-11 15:12:10 +01:00
bors
9aa232ecc7 Auto merge of #120405 - cjgillot:gvn-pointer, r=oli-obk
Fold pointer operations in GVN

This PR proposes 2 combinations of cast operations in MIR GVN:
- a chain of `PtrToPtr` or `MutToConstPointer` casts can be folded together into a single `PtrToPtr` cast;
- we attempt to evaluate more ptr ops when there is no provenance.

In particular, this allows to read from static slices.

This is not yet sufficient to see through slice operations that use `PtrComponents` (because that's a union), but still a step forward.

r? `@ghost`
2024-02-11 04:24:40 +00:00
Matthias Krüger
09bbcd6667
Rollup merge of #120883 - RalfJung:extern-static-err, r=oli-obk
interpret: rename ReadExternStatic → ExternStatic

This error shows up for reads and writes, so `ReadExternStatic` is misleading.
2024-02-11 01:37:56 +01:00
Matthias Krüger
e82e087582
Rollup merge of #120882 - RalfJung:set-discriminant, r=compiler-errors
interpret/write_discriminant: when encoding niched variant, ensure the stored value matches

Cc https://github.com/rust-lang/unsafe-code-guidelines/issues/487
2024-02-11 01:37:55 +01:00
Ralf Jung
29db7890ba interpret/visitor: ensure we only see normalized types 2024-02-10 17:00:24 +01:00
Ralf Jung
77f8c3caea detect consts that reference extern statics 2024-02-10 16:13:48 +01:00
Ralf Jung
9c0623fe8f validation: descend from consts into statics 2024-02-10 16:13:47 +01:00
Ralf Jung
4e77e368eb unstably allow constants to refer to statics and read from immutable statics 2024-02-10 16:12:55 +01:00
Ralf Jung
d56f3b6a5d interpret: rename ReadExternStatic → ExternStatic 2024-02-10 16:06:02 +01:00
Ralf Jung
18ed966ab5 interpret/write_discriminant: when encoding niched variant, ensure the stored value matches 2024-02-10 15:33:58 +01:00
Matthias Krüger
0b7f0ff230
Rollup merge of #117614 - RalfJung:static-mut-refs, r=davidtwco,oli-obk
static mut: allow mutable reference to arbitrary types, not just slices and arrays

For historical reasons, we allow this:
```rust
static mut ARRAY: &'static mut [isize] = &mut [1];
```
However, we do not allow this:
```rust
static mut INT: &'static mut isize = &mut 1;
```

I think that's terribly inconsistent. I don't care much for `static mut`, but we have to keep it around for backwards compatibility and so we have to keep supporting it properly in the compiler. In recent refactors of how we deal with mutability of data in `static` and `const`, I almost made a fatal mistake since I tested `static mut INT: &'static mut isize = &mut 1` and concluded that we don't allow such `'static` mutable references even inside `static mut`. After all, nobody would expect this to be allowed only for arrays and slices, right?!?? So for the sake of our own sanity, and of whoever else reverse engineers these rules in the future to understand what the Rust compiler accepts or does not accept, I propose that we accept this for all types, not just arrays and slices.
2024-02-10 13:12:28 +01:00
Vadim Petrochenkov
b07283815b hir: Remove hir::Map::{opt_parent_id,parent_id,get_parent,find_parent} 2024-02-10 12:24:46 +03:00
Camille GILLOT
304b4ad8b9 Compute unsizing casts in GVN. 2024-02-09 21:01:57 +00:00
Matthias Krüger
99bafad6c2
Rollup merge of #120354 - lukas-code:metadata-normalize, r=lcnr
improve normalization of `Pointee::Metadata`

This PR makes it so that `<Wrapper<Tail> as Pointee>::Metadata` is normalized to `<Tail as Pointee>::Metadata` if we don't know `Wrapper<Tail>: Sized`. With that, the trait solver can prove projection predicates like `<Wrapper<Tail> as Pointee>::Metadata == <Tail as Pointee>::Metadata`, which makes it possible to use the metadata APIs to cast between the tail and the wrapper:

```rust
#![feature(ptr_metadata)]

use std::ptr::{self, Pointee};

fn cast_same_meta<T: ?Sized, U: ?Sized>(ptr: *const T) -> *const U
where
    T: Pointee<Metadata = <U as Pointee>::Metadata>,
{
    let (thin, meta) = ptr.to_raw_parts();
    ptr::from_raw_parts(thin, meta)
}

struct Wrapper<T: ?Sized>(T);

fn cast_to_wrapper<T: ?Sized>(ptr: *const T) -> *const Wrapper<T> {
    cast_same_meta(ptr)
}
```

Previously, this failed to compile:

```
error[E0271]: type mismatch resolving `<Wrapper<T> as Pointee>::Metadata == <T as Pointee>::Metadata`
  --> src/lib.rs:16:5
   |
15 | fn cast_to_wrapper<T: ?Sized>(ptr: *const T) -> *const Wrapper<T> {
   |                    - found this type parameter
16 |     cast_same_meta(ptr)
   |     ^^^^^^^^^^^^^^ expected `Wrapper<T>`, found type parameter `T`
   |
   = note: expected associated type `<Wrapper<T> as Pointee>::Metadata`
              found associated type `<T as Pointee>::Metadata`
   = note: an associated type was expected, but a different one was found
```

(Yes, you can already do this with `as` casts. But using functions is so much  *safer* , because you can't change the metadata on accident.)

---

This PR essentially changes the built-in impls of `Pointee` from this:

```rust
// before

impl Pointee for u8 {
    type Metadata = ();
}

impl Pointee for [u8] {
    type Metadata = usize;
}

// ...

impl Pointee for Wrapper<u8> {
    type Metadata = ();
}

impl Pointee for Wrapper<[u8]> {
    type Metadata = usize;
}

// ...

// This impl is only selected if `T` is a type parameter or unnormalizable projection or opaque type.
fallback impl<T: ?Sized> Pointee for Wrapper<T>
where
    Wrapper<T>: Sized
{
    type Metadata = ();
}

// This impl is only selected if `T` is a type parameter or unnormalizable projection or opaque type.
fallback impl<T /*: Sized */> Pointee for T {
    type Metadata = ();
}
```

to this:

```rust
// after

impl Pointee for u8 {
    type Metadata = ();
}

impl Pointee for [u8] {
    type Metadata = usize;
}

// ...

impl<T: ?Sized> Pointee for Wrapper<T> {
    // in the old solver this will instead project to the "deep" tail directly,
    // e.g. `Wrapper<Wrapper<T>>::Metadata = T::Metadata`
    type Metadata = <T as Pointee>::Metadata;
}

// ...

// This impl is only selected if `T` is a type parameter or unnormalizable projection or opaque type.
fallback impl<T /*: Sized */> Pointee for T {
    type Metadata = ();
}
```
2024-02-09 19:21:16 +01:00
bors
e28fae52d9 Auto merge of #120843 - matthiaskrgr:rollup-med37z5, r=matthiaskrgr
Rollup of 8 pull requests

Successful merges:

 - #113671 (Make privacy visitor use types more (instead of HIR))
 - #120308 (core/time: avoid divisions in Duration::new)
 - #120693 (Invert diagnostic lints.)
 - #120704 (A drive-by rewrite of `give_region_a_name()`)
 - #120809 (Use `transmute_unchecked` in `NonZero::new`.)
 - #120817 (Fix more `ty::Error` ICEs in MIR passes)
 - #120828 (Fix `ErrorGuaranteed` unsoundness with stash/steal.)
 - #120831 (Startup objects disappearing from sysroot)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-02-09 15:34:48 +00:00
Matthias Krüger
116efb5bb1
Rollup merge of #120817 - compiler-errors:more-mir-errors, r=oli-obk
Fix more `ty::Error` ICEs in MIR passes

Fixes #120791 - Add a check for `ty::Error` in the `ByMove` coroutine pass
Fixes #120816 - Add a check for `ty::Error` in the MIR validator

Also a drive-by fix for a FIXME I had asked oli to add

r? oli-obk
2024-02-09 14:41:51 +01:00
Matthias Krüger
46a0448405
Rollup merge of #120693 - nnethercote:invert-diagnostic-lints, r=davidtwco
Invert diagnostic lints.

That is, change `diagnostic_outside_of_impl` and `untranslatable_diagnostic` from `allow` to `deny`, because more than half of the compiler has been converted to use translated diagnostics.

This commit removes more `deny` attributes than it adds `allow` attributes, which proves that this change is warranted.

r? ````@davidtwco````
2024-02-09 14:41:50 +01:00
Michael Goulet
e32c1ddc52 Don't ice in validation when error body is created 2024-02-09 00:40:43 +00:00
Ben Kimock
8836ac5758 Add a new debug_assertions instrinsic (compiler)
And in clippy
2024-02-08 11:49:08 -05:00
Guillaume Boisseau
62c2628eba
Rollup merge of #120302 - oli-obk:const_intern_cleanups, r=RalfJung
various const interning cleanups

After #119044 I noticed that some things can be simplified and refactored.

This is also a requirement for https://github.com/rust-lang/rust/pull/116564 as there we'll need to treat the base allocation differently from the others

r? ````@RalfJung````
2024-02-07 18:24:42 +01:00
Matthias Krüger
176c4ba5c3
Rollup merge of #120423 - RalfJung:indirect-structural-match, r=petrochenkov
update indirect structural match lints to match RFC and to show up for dependencies

This is a large step towards implementing https://github.com/rust-lang/rfcs/pull/3535.
We currently have five lints related to "the structural match situation":
- nontrivial_structural_match
- indirect_structural_match
- pointer_structural_match
- const_patterns_without_partial_eq
- illegal_floating_point_literal_pattern

This PR concerns the first 3 of them. (The 4th already is set up to show for dependencies, and the 5th is removed by https://github.com/rust-lang/rust/pull/116284.) nontrivial_structural_match is being removed as per the RFC; the other two are enabled to show up in dependencies.

Fixes https://github.com/rust-lang/rust/issues/73448 by removing the affected analysis.
2024-02-06 22:45:41 +01:00
Matthias Krüger
6908d3ec9e
Rollup merge of #120683 - RalfJung:symbolic-alignment-ice, r=oli-obk
miri: fix ICE with symbolic alignment check on extern static

Fixes https://github.com/rust-lang/miri/issues/3288. Also fixes [this example](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=38ee338ff10726be72bdd6efa3386763).

This could almost be a Miri PR, except for that typo fix in the validator. I started this as a rustc patch since I thought I need rustc changes, and now it'd be too annoying to turn this into a Miri PR...

r? `@oli-obk`
2024-02-06 19:40:10 +01:00
Ralf Jung
25635b9a96 miri: fix ICE with symbolic alignment check on extern static 2024-02-06 10:17:42 +01:00
Michael Goulet
ca44416023 Fix drop shim for AsyncFnOnce closure, AsyncFnMut shim for AsyncFn closure 2024-02-06 02:22:58 +00:00
Michael Goulet
427896dd7e Construct body for by-move coroutine closure output 2024-02-06 02:22:58 +00:00
Michael Goulet
fc4fff4038 Build a shim to call async closures with different AsyncFn trait kinds 2024-02-06 02:22:58 +00:00
Michael Goulet
a82bae2172 Teach typeck/borrowck/solvers how to deal with async closures 2024-02-06 02:22:58 +00:00
Michael Goulet
c567eddec2 Add CoroutineClosure to TyKind, AggregateKind, UpvarArgs 2024-02-06 02:22:58 +00:00
Nicholas Nethercote
0ac1195ee0 Invert diagnostic lints.
That is, change `diagnostic_outside_of_impl` and
`untranslatable_diagnostic` from `allow` to `deny`, because more than
half of the compiler has be converted to use translated diagnostics.

This commit removes more `deny` attributes than it adds `allow`
attributes, which proves that this change is warranted.
2024-02-06 13:12:33 +11:00
Oli Scherer
c94769a974
Clarify order of operations during interning
Co-authored-by: Ralf Jung <post@ralfj.de>
2024-02-05 22:21:40 +01:00
Ralf Jung
9f58cf43c7 get rid of nontrivial_structural_match lint and custom_eq const qualif 2024-02-05 20:36:09 +01:00
Lukas Markeffsky
0c1f401d98 old solver: improve normalization of Pointee::Metadata 2024-02-05 15:37:21 +01:00
Matthias Krüger
e348f0739d
Rollup merge of #120587 - lukas-code:miri-tail-normalize, r=RalfJung
miri: normalize struct tail in ABI compat check

fixes https://github.com/rust-lang/miri/issues/3282
extracted from https://github.com/rust-lang/rust/pull/120354, see https://github.com/rust-lang/rust/pull/120354#discussion_r1469154220 for context

r? ```@RalfJung```
2024-02-05 06:37:16 +01:00
Matthias Krüger
ca36ed27be
Rollup merge of #119600 - aDotInTheVoid:comment-fix, r=compiler-errors
Remove outdated references to librustc_middle

The relevant comment is now in 791a53f380/compiler/rustc_middle/src/tests.rs (L3-L13)
2024-02-05 06:37:14 +01:00
Nicholas Nethercote
6fdaf3ef7f Use DiagnosticArgName in a few more places. 2024-02-03 09:02:50 +11:00
Lukas Markeffsky
30e7b87e26 miri: normalize struct tail in ABI compat check 2024-02-02 21:39:00 +01:00
Guillaume Gomez
f99b510429
Rollup merge of #120488 - nnethercote:diag-lifetimes, r=oli-obk
Diagnostic lifetimes cleanups

Some diagnostic simplifications.

r? `@oli-obk`
2024-01-30 11:19:20 +01:00
Guillaume Gomez
e0e96a1829
Rollup merge of #120387 - RalfJung:large-array-followup, r=oli-obk
interpret/memory: fix safety comment for large array memset optimization

Also fix the doc comment for `check_and_deref_ptr`.
2024-01-30 11:19:14 +01:00
Nicholas Nethercote
5350edb9e8 Remove the lifetime from DiagnosticArgValue.
Because it's almost always static.

This makes `impl IntoDiagnosticArg for DiagnosticArgValue` trivial,
which is nice.

There are a few diagnostics constructed in
`compiler/rustc_mir_build/src/check_unsafety.rs` and
`compiler/rustc_mir_transform/src/errors.rs` that now need symbols
converted to `String` with `to_string` instead of `&str` with `as_str`,
but that' no big deal, and worth it for the simplifications elsewhere.
2024-01-30 18:46:06 +11:00
Oli Scherer
5d46b982c5 Document base vs nested alloc interning 2024-01-29 08:59:51 +00:00
Oli Scherer
a57a00ebf6 separately intern the outermost alloc from the rest 2024-01-29 08:59:46 +00:00
Oli Scherer
a73c44889a Prefer external iteration now that we don't actually recurse anymore 2024-01-29 08:53:54 +00:00
Oli Scherer
b6d0225caf prefer instrumentation over entry/exit tracing statements 2024-01-29 08:53:54 +00:00
Oli Scherer
7a2b66319e interning doesn't check alignment anymroe, because it doesn't do any more projections. 2024-01-29 08:53:54 +00:00
Nicholas Nethercote
5d9dfbd08f Stop using String for error codes.
Error codes are integers, but `String` is used everywhere to represent
them. Gross!

This commit introduces `ErrCode`, an integral newtype for error codes,
replacing `String`. It also introduces a constant for every error code,
e.g. `E0123`, and removes the `error_code!` macro. The constants are
imported wherever used with `use rustc_errors::codes::*`.

With the old code, we have three different ways to specify an error code
at a use point:
```
error_code!(E0123)  // macro call

struct_span_code_err!(dcx, span, E0123, "msg");  // bare ident arg to macro call

\#[diag(name, code = "E0123")]  // string
struct Diag;
```

With the new code, they all use the `E0123` constant.
```
E0123  // constant

struct_span_code_err!(dcx, span, E0123, "msg");  // constant

\#[diag(name, code = E0123)]  // constant
struct Diag;
```

The commit also changes the structure of the error code definitions:
- `rustc_error_codes` now just defines a higher-order macro listing the
  used error codes and nothing else.
- Because that's now the only thing in the `rustc_error_codes` crate, I
  moved it into the `lib.rs` file and removed the `error_codes.rs` file.
- `rustc_errors` uses that macro to define everything, e.g. the error
  code constants and the `DIAGNOSTIC_TABLES`. This is in its new
  `codes.rs` file.
2024-01-29 07:41:41 +11:00
Ralf Jung
9a819ab8f7 static mut: allow reference to arbitrary types, not just slices and arrays 2024-01-28 10:00:23 +01:00
Michael Goulet
866364cc5d Normalize field types before checking validity 2024-01-26 18:36:15 +00:00
Ralf Jung
bdfb9172c1 interpret/memory: fix safety comment for large array memset optimization 2024-01-26 17:54:41 +01:00
Ralf Jung
64cd13ff3b add test for GVN issue; cleanup in dataflow_const_prop 2024-01-26 10:40:29 +01:00
Ralf Jung
1025a12b64 interpret: project_downcast: do not ICE for uninhabited variants 2024-01-26 09:01:56 +01:00
bors
69db514ed9 Auto merge of #119968 - clubby789:unused-feature, r=compiler-errors
Remove unused/unnecessary features

~~The bulk of the actual code changes here is replacing try blocks with equivalent closures. I'm not entirely sure that's a good idea since it may have perf impact, happy to revert if that's the case/the change is unwanted.~~

I also removed a lot of `recursion_limit = "256"` since everything seems to build fine without that and most don't have any comment justifying it.
2024-01-26 03:18:34 +00:00
bors
dd2559e08e Auto merge of #116167 - RalfJung:structural-eq, r=lcnr
remove StructuralEq trait

The documentation given for the trait is outdated: *all* function pointers implement `PartialEq` and `Eq` these days. So the `StructuralEq` trait doesn't really seem to have any reason to exist any more.

One side-effect of this PR is that we allow matching on some consts that do not implement `Eq`. However, we already allowed matching on floats and consts containing floats, so this is not new, it is just allowed in more cases now. IMO it makes no sense at all to allow float matching but also sometimes require an `Eq` instance. If we want to require `Eq` we should adjust https://github.com/rust-lang/rust/pull/115893 to check for `Eq`, and rule out float matching for good.

Fixes https://github.com/rust-lang/rust/issues/115881
2024-01-26 00:17:00 +00:00
clubby789
fd29f74ff8 Remove unused features 2024-01-25 14:01:33 +00:00
bors
039d887928 Auto merge of #119911 - NCGThompson:is-statically-known, r=oli-obk
Replacement of #114390: Add new intrinsic `is_var_statically_known` and optimize pow for powers of two

This adds a new intrinsic `is_val_statically_known` that lowers to [``@llvm.is.constant.*`](https://llvm.org/docs/LangRef.html#llvm-is-constant-intrinsic).` It also applies the intrinsic in the int_pow methods to recognize and optimize the idiom `2isize.pow(x)`. See #114390 for more discussion.

While I have extended the scope of the power of two optimization from #114390, I haven't added any new uses for the intrinsic. That can be done in later pull requests.

Note: When testing or using the library, be sure to use `--stage 1` or higher. Otherwise, the intrinsic will be a noop and the doctests will be skipped. If you are trying out edits, you may be interested in [`--keep-stage 0`](https://rustc-dev-guide.rust-lang.org/building/suggested.html#faster-builds-with---keep-stage).

Fixes #47234
Resolves #114390
`@Centri3`
2024-01-25 05:16:53 +00:00
bors
68411c9554 Auto merge of #119627 - oli-obk:const_prop_lint_n̵o̵n̵sense, r=cjgillot
Remove all ConstPropNonsense

We track all locals and projections on them ourselves within the const propagator and only use the InterpCx to actually do some low level operations or read from constants (via `OpTy` we get for said constants).

This helps moving the const prop lint out from the normal pipeline and running it just based on borrowck information. This in turn allows us to make progress on https://github.com/rust-lang/rust/pull/108730#issuecomment-1875557745

there are various follow up cleanups that can be done after this PR (e.g. not matching on Rvalue twice and doing binop checks twice), but lets try landing this one first.

r? `@RalfJung`
2024-01-25 03:16:07 +00:00
bors
cd6d8f2a04 Auto merge of #118336 - saethlin:const-to-op-cache, r=RalfJung
Return a finite number of AllocIds per ConstAllocation in Miri

Before this, every evaluation of a const slice would produce a new AllocId. So in Miri, this program used to have unbounded memory use:
```rust
fn main() {
    loop {
        helper();
    }
}

fn helper() {
    "ouch";
}
```
Every trip around the loop creates a new AllocId which we need to keep track of a base address for. And the provenance GC can never clean up that AllocId -> u64 mapping, because the AllocId is for a const allocation which will never be deallocated.

So this PR moves the logic of producing an AllocId for a ConstAllocation to the Machine trait, and the implementation that Miri provides will only produce 16 AllocIds for each allocation. The cache is also keyed on the Instance that the const is evaluated in, so that equal consts evaluated in two functions will have disjoint base addresses.

r? RalfJung
2024-01-24 10:17:12 +00:00
Ralf Jung
0df7810734 remove StructuralEq trait 2024-01-24 07:56:23 +01:00
León Orell Valerian Liehr
6131ba62ad
Rollup merge of #120139 - compiler-errors:fnonce-shim, r=BoxyUwU
Do not normalize closure signature when building `FnOnce` shim

It is not necessary to normalize the closure signature when building an `FnOnce` shim for an `Fn`/`FnMut` closure. That closure shim is just calling `FnMut::call_mut(&mut self)` anyways.

It's also somewhat sketchy that we were ever doing this to begin with, since we're normalizing with a `ParamEnv::reveal_all()` param-env, which is definitely not right with possibly polymorphic substs.

This cuts out a tiny bit of unnecessary work in `Instance::resolve` and simplifies the signature because now we can unconditionally return an `Instance`.
2024-01-23 21:53:56 +01:00
Oli Scherer
1f398abcb6 const prop nonsense eliminated 2024-01-23 16:34:43 +00:00