Commit graph

107 commits

Author SHA1 Message Date
Ralf Jung
70d418c315 Revert "require full validity when determining the discriminant of a value"
This reverts commit 0a2b7d71d9, reversing
changes made to 47c1bd1bcc.
This caused several unforeseen problems:
- https://github.com/rust-lang/rust/issues/91029
- https://github.com/rust-lang/rust/pull/89764#issuecomment-973588007
2021-11-20 12:33:04 -05:00
bors
50f2c29200 Auto merge of #90535 - tmiasko:clone-from, r=oli-obk
Implement `clone_from` for `State`

Data flow engine uses `clone_from` for domain values.  Providing an
implementation of `clone_from` will avoid some intermediate memory
allocations.

Extracted from #90413.

r? `@oli-obk`
2021-11-20 04:12:03 +00:00
Matthias Krüger
cf69f9e220
Rollup merge of #90999 - RalfJung:miri_simd, r=oli-obk
fix CTFE/Miri simd_insert/extract on array-style repr(simd) types

The changed test would previously fail since `place_index` would just return the only field of `f32x4`, i.e., the array -- rather than *indexing into* the array which is what we have to do.

The new helper methods will also be needed for https://github.com/rust-lang/miri/issues/1912.

r? ``````@oli-obk``````
2021-11-20 01:09:41 +01:00
Yuki Okushi
48947eafda
Rollup merge of #90633 - tmiasko:candidate-struct, r=nagisa
Refactor single variant `Candidate` enum into a struct

`Candidate` enum has only a single `Ref` variant.  Refactor it into a
struct and reduce overall indentation of the code by two levels.

No functional changes.
2021-11-19 13:06:34 +09:00
Yuki Okushi
0a2b7d71d9
Rollup merge of #90895 - RalfJung:read-discriminant-valid, r=oli-obk
require full validity when determining the discriminant of a value

This resolves (for now) the semantic question that came up in https://github.com/rust-lang/rust/pull/89764: arguably, reading the discriminant of a value is 'using' that value, so we are in our right to demand full validity. Reading a discriminant is somewhat special in that it works for values of *arbitrary* type; all the other primitive MIR operations work on specific types (e.g. `bool` or an integer) and basically implicitly require validity as part of just "doing their job".

The alternative would be to just require that the discriminant itself is valid, if any -- but then what do we do for types that do not have a discriminant, which kind of validity do we check? [This code](81117ff930/compiler/rustc_codegen_ssa/src/mir/place.rs (L206-L215)) means we have to at least reject uninhabited types, but I would rather not special case that.

I don't think this can be tested in CTFE (since validity is not enforced there), I will add a compile-fail test to Miri:
```rust
#[allow(enum_intrinsics_non_enums)]
fn main() {
    let i = 2u8;
    std::mem::discriminant(unsafe { &*(&i as *const _ as *const bool) }); // UB
}
```

(I tried running the check even on the CTFE machines, but then it runs during ConstProp and that causes all sorts of problems. We could run it for ConstEval but not ConstProp, but that simply does not seem worth the effort currently.)

r? ``@oli-obk``
2021-11-19 02:22:58 +09:00
Ralf Jung
2f1a1f530b fix CTFE/Miri simd_insert/extract on array-style repr(simd) types 2021-11-18 09:10:35 -05:00
Yuki Okushi
fff9055afb
Rollup merge of #90892 - RalfJung:miri-partial-ptr-copy, r=oli-obk
fix ICE on Miri/CTFE copy of half a pointer

Fixes https://github.com/rust-lang/miri/issues/1910
r? `````@oli-obk`````
2021-11-16 09:14:22 +09:00
Ralf Jung
498ebc46ba require full validity when determining the discriminant of a value 2021-11-14 13:08:51 -05:00
Ralf Jung
94ca0b392d fix ICE on Miri/CTFE copy of half a pointer 2021-11-13 20:56:01 -05:00
bors
d212d902ae Auto merge of #89551 - jhpratt:stabilize-const_raw_ptr_deref, r=oli-obk
Stabilize `const_raw_ptr_deref` for `*const T`

This stabilizes dereferencing immutable raw pointers in const contexts.
It does not stabilize `*mut T` dereferencing. This is behind the
same feature gate as mutable references.

closes https://github.com/rust-lang/rust/issues/51911
2021-11-13 17:10:15 +00:00
bors
800a156c1e Auto merge of #88670 - camelid:miri-uninit-num, r=RalfJung
miri: Detect uninitialized integers and floats

Part of rust-lang/miri#1340.

Companion Miri PR: rust-lang/miri#1904

r? `@RalfJung`
2021-11-10 09:36:03 +00:00
Noah Lev
d8a1454dd8 miri: Detect uninitialized integers and floats
Change the Miri engine to allow configuring whether to check
initialization of integers and floats. This allows the Miri tool to
optionally check for initialization if requested by the user.
2021-11-09 16:21:36 -08:00
Matthias Krüger
fd74c93403
Rollup merge of #89561 - nbdd0121:const_typeck, r=nikomatsakis
Type inference for inline consts

Fixes #78132
Fixes #78174
Fixes #81857
Fixes #89964

Perform type checking/inference of inline consts in the same context as the outer def, similar to what is currently done to closure.

Doing so would require `closure_base_def_id` of the inline const to return the outer def, and since `closure_base_def_id` can be called on non-local crate (and thus have no HIR available), a new `DefKind` is created for inline consts.

The type of the generated anon const can capture lifetime of outer def, so we couldn't just use the typeck result as the type of the inline const's def. Closure has a similar issue, and it uses extra type params `CK, CS, U` to capture closure kind, input/output signature and upvars. I use a similar approach for inline consts, letting it have an extra type param `R`, and then `typeof(InlineConst<[paremt generics], R>)` would just be `R`. In borrowck region requirements are also propagated to the outer MIR body just like it's currently done for closure.

With this PR, inline consts in expression position are quitely usable now; however the usage in pattern position is still incomplete -- since those does not remain in the MIR borrowck couldn't verify the lifetime there. I have left an ignored test as a FIXME.

Some disucssions can be found on [this Zulip thread](https://rust-lang.zulipchat.com/#narrow/stream/260443-project-const-generics/topic/inline.20consts.20typeck).
cc `````@spastorino````` `````@lcnr`````
r? `````@nikomatsakis`````

`````@rustbot````` label A-inference F-inline_const T-compiler
2021-11-09 19:00:40 +01:00
Deadbeef
f1126f1272
Make select_* methods return Vec for TraitEngine 2021-11-08 23:35:23 +08:00
Gary Guo
02c1774cd3 Give inline const separate DefKind 2021-11-07 03:59:06 +00:00
Jacob Pratt
0cdbeaa2a3
Stabilize const_raw_ptr_deref for *const T
This stabilizes dereferencing immutable raw pointers in const contexts.
It does not stabilize `*mut T` dereferencing. This is placed behind the
`const_raw_mut_ptr_deref` feature gate.
2021-11-06 17:05:15 -04:00
Matthias Krüger
0a5640b55f use matches!() macro in more places 2021-11-06 16:13:14 +01:00
Tomasz Miąsko
59edb9d382 Remove Candidate::source_info 2021-11-05 21:31:25 +01:00
Tomasz Miąsko
7bc827b34b Refactor single variant Candidate enum into a struct
`Candidate` enum has only a single `Ref` variant.  Refactor it into a
struct and reduce overall indentation of the code by two levels.

No functional changes.
2021-11-05 21:31:18 +01:00
Tomasz Miąsko
bc4931ed7e addr_of! grants mutable access, maybe?
The exact set of permissions granted when forming a raw reference is
currently undecided https://github.com/rust-lang/rust/issues/56604.

To avoid presupposing any particular outcome, adjust the const
qualification to be compatible with decision where raw reference
constructed from `addr_of!` grants mutable access.
2021-11-03 16:43:12 +01:00
Tomasz Miąsko
b285e0c5d8 Remove MaybeMutBorrowedLocals 2021-11-03 16:43:12 +01:00
Tomasz Miąsko
73f5b65818 Implement clone_from for State
Data flow engine uses `clone_from` for domain values.  Providing an
implementation of `clone_from` will avoid some intermediate memory
allocations.
2021-11-03 00:00:00 +00:00
Tomasz Miąsko
3a95338f31 Remove unnecessary Option from promote_candidate return type 2021-10-31 00:00:00 +00:00
bors
9ed5b94b28 Auto merge of #90373 - tmiasko:union-qualification, r=oli-obk
Use type based qualification for unions

Union field access is currently qualified based on the qualification of
a value previously assigned to the union. At the same time, every union
access transmutes the content of the union, which might result in a
different qualification.

For example, consider constants A and B as defined below, under the
current rules neither contains interior mutability, since a value used
in the initial assignment did not contain `UnsafeCell` constructor.

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

union U { i: u32, c: std::cell::Cell<u32> }
const A: U = U { i: 0 };
const B: std::cell::Cell<u32> = unsafe { U { i: 0 }.c };
```

To avoid the issue, the changes here propose to consider the content of
a union as opaque and use type based qualification for union types.

Fixes #90268.

`@rust-lang/wg-const-eval`
2021-10-29 12:21:09 +00:00
bors
37f70a0e1e Auto merge of #90214 - tmiasko:indirect-mutation-qualif, r=ecstatic-morse,oli-obk
Consider indirect mutation during const qualification dataflow

Previously a local would be qualified if either one of two separate data
flow computations indicated so. First determined if a local could
contain the qualif, but ignored any forms of indirect mutation. Second
determined if a local could be mutably borrowed (and so indirectly
mutated), but which in turn ignored the qualif.

The end result was incorrect because the effect of indirect mutation was
effectivelly ignored in the all but the final stage of computation.

In the new implementation the indirect mutation is directly incorporated
into the qualif data flow. The local variable becomes immediately
qualified once it is mutably borrowed and borrowed place type can
contain the qualif.

In general we will now reject additional programs, program that were
prevously unintentionally accepted.

There are also some cases which are now accepted but were previously
rejected, because previous implementation didn't consider whether
borrowed place could have the qualif under the consideration.

Fixes #90124.

r? `@ecstatic-morse`
2021-10-29 08:38:39 +00:00
Mark Rousskov
3215eeb99f
Revert "Add rustc lint, warning when iterating over hashmaps" 2021-10-28 11:01:42 -04:00
Tomasz Miąsko
3f778f31b6 Use type based qualification for unions
Union field access is currently qualified based on the qualification of
a value previously assigned to the union. At the same time, every union
access transmutes the content of the union, which might result in a
different qualification.

For example, consider constants A and B as defined below, under the
current rules neither contains interior mutability, since a value used
in the initial assignment did not contain `UnsafeCell` constructor.

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

union U { i: u32, c: std::cell::Cell<u32> }
const A: U = U { i: 0 };
const B: std::cell::Cell<u32> = unsafe { U { i: 0 }.c };
```

To avoid the issue, the changes here propose to consider the content of
a union as opaque and use type based qualification for union types.
2021-10-28 00:00:00 +00:00
Gary Guo
223f58085a Remove is_const_fn in find_mir_or_eval_fn 2021-10-27 07:21:28 +01:00
Tomasz Miąsko
93f85f5a9d Consider indirect mutation during const qualification dataflow
Previously a local would be qualified if either one of two separate data
flow computations indicated so. First determined if a local could
contain the qualif, but ignored any forms of indirect mutation. Second
determined if a local could be mutably borrowed (and so indirectly
mutated), but which in turn ignored the qualif.

The end result was incorrect because the effect of indirect mutation was
effectivelly ignored in the all but the final stage of computation.

In the new implementation the indirect mutation is directly incorporated
into the qualif data flow. The local variable becomes immediately
qualified once it is mutably borrowed and borrowed place type can
contain the qualif.

In general we will now reject additional programs, program that were
prevously unintentionally accepted.

There are also some cases which are now accepted but were previously
rejected, because previous implementation didn't consider whether
borrowed place could have the qualif under the consideration.
2021-10-26 08:20:01 +02:00
Gary Guo
cc4345a1c5 Clean up special function const checks
Mark them as const and `#[rustc_do_not_const_check]` instead of hard-coding
them in const-eval checks.
2021-10-25 17:32:01 +01:00
Matthias Krüger
87822b27ee
Rollup merge of #89558 - lcnr:query-stable-lint, r=estebank
Add rustc lint, warning when iterating over hashmaps

r? rust-lang/wg-incr-comp
2021-10-24 15:48:42 +02:00
bors
91b931926f Auto merge of #90203 - matthiaskrgr:rollup-v215wew, r=matthiaskrgr
Rollup of 5 pull requests

Successful merges:

 - #85833 (Scrape code examples from examples/ directory for Rustdoc)
 - #88041 (Make all proc-macro back-compat lints deny-by-default)
 - #89829 (Consider types appearing in const expressions to be invariant)
 - #90168 (Reset qualifs when a storage of a local ends)
 - #90198 (Add caveat about changing parallelism and function call overhead)

Failed merges:

r? `@ghost`
`@rustbot` modify labels: rollup
2021-10-23 15:53:50 +00:00
Matthias Krüger
74a0c492c1
Rollup merge of #90168 - tmiasko:const-qualif-storage, r=matthewjasper
Reset qualifs when a storage of a local ends

Reset qualifs when a storage of a local ends to ensure that the local qualifs
are affected by the state from previous loop iterations only if the local is
kept alive.

The change should be forward compatible with a stricter handling of indirect
assignments, since storage dead invalidates all existing pointers to the local.
2021-10-23 14:58:42 +02:00
bors
aa5740c715 Auto merge of #90104 - spastorino:coherence-for-negative-trait, r=nikomatsakis
Implement coherence checks for negative trait impls

The main purpose of this PR is to be able to [move Error trait to core](https://github.com/rust-lang/project-error-handling/issues/3).

This feature is necessary to handle the following from impl on box.

```rust
impl From<&str> for Box<dyn Error> { ... }
```

Without having negative traits affect coherence moving the error trait into `core` and moving that `From` impl to `alloc` will cause the from impl to no longer compiler because of a potential future incompatibility. The compiler indicates that `&str` _could_ introduce an `Error` impl in the future, and thus prevents the `From` impl in `alloc` that would cause overlap with `From<E: Error> for Box<dyn Error>`. Adding `impl !Error for &str {}` with the negative trait coherence feature will disable this error by encoding a stability guarantee that `&str` will never implement `Error`, making the `From` impl compile.

We would have this in `alloc`:

```rust
impl From<&str> for Box<dyn Error> {} // A
impl<E> From<E> for Box<dyn Error> where E: Error {} // B
```

and this in `core`:

```rust
trait Error {}
impl !Error for &str {}
```

r? `@nikomatsakis`

This PR was built on top of `@yaahc` PR #85764.

Language team proposal: to https://github.com/rust-lang/lang-team/issues/96
2021-10-23 12:51:15 +00:00
Tomasz Miąsko
e4aeeca667 Reset qualifs when a storage of a local ends
to ensure that the local qualifs are affected by the state from previous
loop iterations only if the local is kept alive.

The change should be forward compatible with a stricter handling of
indirect assignments, since storage dead invalidates all existing
pointers to the local.
2021-10-23 09:26:22 +02:00
Matthias Krüger
8fb194c86f
Rollup merge of #89920 - hudson-ayers:location-detail-control, r=davidtwco
Implement -Z location-detail flag

This PR implements the `-Z location-detail` flag as described in https://github.com/rust-lang/rfcs/pull/2091 .

`-Z location-detail=val` controls what location details are tracked when using `caller_location`. This allows users to control what location details are printed as part of panic messages, by allowing them to exclude any combination of filenames, line numbers, and column numbers. This option is intended to provide users with a way to mitigate the size impact of `#[track_caller]`.

Some measurements of the savings of this approach on an embedded binary can be found here: https://github.com/rust-lang/rust/issues/70579#issuecomment-942556822 .

Closes #70580 (unless people want to leave that open as a place for discussion of further improvements).

This is my first real PR to rust, so any help correcting mistakes / understanding side effects / improving my tests is appreciated :)

I have one question: RFC 2091 specified this as a debugging option (I think that is what -Z implies?). Does that mean this can never be stabilized without a separate MCP? If so, do I need to submit an MCP now, or is the initial RFC specifying this option sufficient for this to be merged as is, and then an MCP would be needed for eventual stabilization?
2021-10-23 05:28:23 +02:00
Yuki Okushi
a656bc5b08
Rollup merge of #90069 - tmiasko:promoted-const-qualif, r=oli-obk
Fix const qualification when executed after promotion

The const qualification was so far performed before the promotion and
the implementation assumed that it will never encounter a promoted.

With `const_precise_live_drops` feature, checking for live drops is
delayed until after drop elaboration, which in turn runs after
promotion. so the assumption is no longer true. When evaluating
`NeedsNonConstDrop` it is now possible to encounter promoteds.

Use type base qualification for the promoted. It is a sound
approximation in general, and in the specific case of promoteds and
`NeedsNonConstDrop` it is precise.

Fixes #89938.
2021-10-22 19:42:49 +09:00
Hudson Ayers
e1d94b8fd1 Configure saved panic locations based on location-detail flag 2021-10-21 10:41:19 -07:00
Tomasz Miąsko
74c6636d27 Verify that only NeedsNonConstDrop expects promoteds 2021-10-21 11:14:41 +02:00
Yuki Okushi
afdd0c3ade
Rollup merge of #90071 - cjgillot:no-blocks, r=oli-obk
Remove hir::map::blocks and use FnKind instead

The principal tool is `FnLikeNode`, which is not often used and can be easily implemented using `rustc_hir::intravisit::FnKind`.
2021-10-21 14:11:08 +09:00
Santiago Pastorino
6975afd141
Add polarity to TraitPredicate 2021-10-20 12:10:41 -03:00
Camille GILLOT
6e98688e68 Replace FnLikeNode by FnKind. 2021-10-19 23:31:51 +02:00
Yuki Okushi
f7024998c7
Rollup merge of #88860 - nbdd0121:panic, r=m-ou-se
Deduplicate panic_fmt

std's begin_panic_fmt and core's panic_fmt are duplicates. Merge them to declutter code and remove a lang item.
2021-10-20 04:35:14 +09:00
bors
1af55d19c7 Auto merge of #89933 - est31:let_else, r=michaelwoerister
Adopt let_else across the compiler

This performs a substitution of code following the pattern:

```
let <id> = if let <pat> = ... { identity } else { ... : ! };
```

To simplify it to:

```
let <pat> = ... { identity } else { ... : ! };
```

By adopting the `let_else` feature (cc #87335).

The PR also updates the syn crate because the currently used version of the crate doesn't support `let_else` syntax yet.

Note: Generally I'm the person who *removes* usages of unstable features from the compiler, not adds more usages of them, but in this instance I think it hopefully helps the feature get stabilized sooner and in a better state. I have written a [comment](https://github.com/rust-lang/rust/issues/87335#issuecomment-944846205) on the tracking issue about my experience and what I feel could be improved before stabilization of `let_else`.
2021-10-19 14:41:39 +00:00
Gary Guo
9370156957 Deduplicate panic_fmt
std's begin_panic_fmt and core's panic_fmt are duplicates.
Merge them to declutter code and remove a lang item.
2021-10-19 15:02:21 +01:00
Tomasz Miąsko
7581bae996 Fix const qualification when executed after promotion
The const qualification was so far performed before the promotion and
the implementation assumed that it will never encounter a promoted.

With `const_precise_live_drops` feature, checking for live drops is
delayed until after drop elaboration, which in turn runs after
promotion. so the assumption is no longer true. When evaluating
`NeedsNonConstDrop` it is now possible to encounter promoteds.

Use type base qualification for the promoted. It is a sound
approximation in general, and in the specific case of promoteds and
`NeedsNonConstDrop` it is precise.
2021-10-19 00:00:00 +00:00
Tomasz Miąsko
915a581bcb Do not promote values with const drop that need to be dropped
Changes from #88558 allowed using `~const Drop` in constants by
introducing a new `NeedsNonConstDrop` qualif.

The new qualif was also used for promotion purposes, and allowed
promotion to happen for values that needs to be dropped but which
do have a const drop impl.

Since for promoted the drop implementation is never executed,
this lead to observable change in behaviour. For example:

```rust

struct Panic();

impl const Drop for Panic {
    fn drop(&mut self) {
        panic!();
    }
}

fn main() {
    let _ = &Panic();
}
```

Restore the use of `NeedsDrop` qualif during promotion to avoid the issue.
2021-10-18 21:56:57 +02:00
Tomasz Miąsko
171cbc01ef Rename needs_drop to needs_non_const_drop 2021-10-18 20:51:22 +02:00
bors
6f53ddfa74 Auto merge of #89514 - davidtwco:polymorphize-shims-and-predicates, r=lcnr
polymorphization: shims and predicates

Supersedes #75737 and #75414. This pull request includes up some changes to polymorphization which hadn't landed previously and gets stage2 bootstrapping and the test suite passing when polymorphization is enabled. There are still issues with `type_id` and polymorphization to investigate but this should get polymorphization in a reasonable state to work on.

- #75737 and #75414 both worked but were blocked on having the rest of the test suite pass (with polymorphization enabled) with and without the PRs. It makes more sense to just land these so that the changes are in.
- #75737's changes remove the restriction of `InstanceDef::Item` on polymorphization, so that shims can now be polymorphized. This won't have much of an effect until polymorphization's analysis is more advanced, but it doesn't hurt.
- #75414's changes remove all logic which marks parameters as used based on their presence in predicates - given #75675, this will enable more polymorphization and avoid the symbol clashes that predicate logic previously sidestepped.
- Polymorphization now explicitly checks (and skips) foreign items, this is necessary for stage2 bootstrapping to work when polymorphization is enabled.
- The conditional determining the emission of a note adding context to a post-monomorphization error has been modified. Polymorphization results in `optimized_mir` running for shims during collection where that wouldn't happen previously, some errors are emitted during `optimized_mir` and these were considered post-monomorphization errors with the existing logic (more errors and shims have a `DefId` coming from the std crate, not the local crate), adding a note that resulted in tests failing. It isn't particularly feasible to change where polymorphization runs or prevent it from using `optimized_mir`, so it seemed more reasonable to not change the conditional.
- `characteristic_def_id_of_type` was being invoked during partitioning for self types of impl blocks which had projections that depended on the value of unused generic parameters of a function - this caused a ICE in a debuginfo test. If partitioning is enabled and the instance needs substitution then this is skipped. That test still fails for me locally, but not with an ICE, but it fails in a fresh checkout too, so 🤷‍♂️.

r? `@lcnr`
2021-10-17 12:33:12 +00:00
est31
1418df5888 Adopt let_else across the compiler
This performs a substitution of code following the pattern:

let <id> = if let <pat> = ... { identity } else { ... : ! };

To simplify it to:

let <pat> = ... { identity } else { ... : ! };

By adopting the let_else feature.
2021-10-16 07:18:05 +02:00