Commit graph

2476 commits

Author SHA1 Message Date
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
7594067b69 Auto merge of #90041 - jfrimmel:rt_copy_checks, r=Mark-Simulacrum
Re-enable `copy[_nonoverlapping]()` debug-checks

This commit re-enables the debug checks for valid usages of the two functions `copy()` and `copy_nonoverlapping()`. Those checks were commented out in #79684 in order to make the functions const. All that's been left was a FIXME, that could not be resolved until there is was way to only do the checks at runtime.
Since #89247 there is such a way: `const_eval_select()`. This commit uses that new intrinsic in order to either do nothing (at compile time) or to do the old checks (at runtime).

The change itself is rather small: in order to make the checks usable with `const_eval_select`, they are moved into a local function (one for `copy` and one for `copy_nonoverlapping` to keep symmetry).

The change does not break referential transparency, as there is nothing you can do at compile time, which you cannot do on runtime without getting undefined behavior. The CTFE-engine won't allow missuses. The other way round is also fine.

I've refactored the code to use `#[cfg(debug_assertions)]` on the new items. If that is not desired, the second commit can be dropped.
I haven't added any checks, as I currently don't know, how to test this properly.

Closes #90012.

cc `@rust-lang/lang,` `@rust-lang/libs` and `@rust-lang/wg-const-eval` (as those teams are linked in the issue above).
2021-11-13 05:19:39 +00:00
bors
032dfe4360 Auto merge of #89167 - workingjubilee:use-simd, r=MarkSimulacrum
pub use core::simd;

A portable abstraction over SIMD has been a major pursuit in recent years for several programming languages. In Rust, `std::arch` offers explicit SIMD acceleration via compiler intrinsics, but it does so at the cost of having to individually maintain each and every single such API, and is almost completely `unsafe` to use.  `core::simd` offers safe abstractions that are resolved to the appropriate SIMD instructions by LLVM during compilation, including scalar instructions if that is all that is available.

`core::simd` is enabled by the `#![portable_simd]` nightly feature tracked in https://github.com/rust-lang/rust/issues/86656 and is introduced here by pulling in the https://github.com/rust-lang/portable-simd repository as a subtree. We built the repository out-of-tree to allow faster compilation and a stochastic test suite backed by the proptest crate to verify that different targets, features, and optimizations produce the same result, so that using this library does not introduce any surprises. As these tests are technically non-deterministic, and thus can introduce overly interesting Heisenbugs if included in the rustc CI, they are visible in the commit history of the subtree but do nothing here. Some tests **are** introduced via the documentation, but these use deterministic asserts.

There are multiple unsolved problems with the library at the current moment, including a want for better documentation, technical issues with LLVM scalarizing and lowering to libm, room for improvement for the APIs, and so far I have not added the necessary plumbing for allowing the more experimental or libm-dependent APIs to be used. However, I thought it would be prudent to open this for review in its current condition, as it is both usable and it is likely I am going to learn something else needs to be fixed when bors tries this out.

The major types are
- `core::simd::Simd<T, N>`
- `core::simd::Mask<T, N>`

There is also the `LaneCount` struct, which, together with the SimdElement and SupportedLaneCount traits, limit the implementation's maximum support to vectors we know will actually compile and provide supporting logic for bitmasks. I'm hoping to simplify at least some of these out of the way as the compiler and library evolve.
2021-11-13 02:17:20 +00:00
Jubilee Young
7c3d72d069 Test core::simd works
These tests just verify some basic APIs of core::simd function, and
guarantees that attempting to access the wrong things doesn't work.
The majority of tests are stochastic, and so remain upstream, but
a few deterministic tests arrive in the subtree as doc tests.
2021-11-12 16:58:47 -08:00
Jubilee Young
39cb863253 Expose portable-simd as core::simd
This enables programmers to use a safe alternative to the current
`extern "platform-intrinsics"` API for writing portable SIMD code.
This is `#![feature(portable_simd)]` as tracked in #86656
2021-11-12 16:58:39 -08:00
Matthias Krüger
5b3cb68d97
Rollup merge of #90798 - edmorley:doc-unreachable-custom-message, r=dtolnay
Document `unreachable!` custom panic message

The `unreachable!` docs previously did not mention that there was a second form, `unreachable!("message")` that could be used to specify a custom panic message,

The docs now mention this feature in the same wording as currently used for `unimplemented!`:
https://doc.rust-lang.org/core/macro.unimplemented.html#panics
2021-11-12 19:17:33 +01:00
Matthias Krüger
70532c4503
Rollup merge of #90644 - est31:const_swap, r=Mark-Simulacrum
Extend the const swap feature

Adds the `const_swap` feature gate to three more swap functions. cc tracking issue #83163

```Rust
impl<T> [T] {
    pub const fn swap(&mut self, a: usize, b: usize);
    pub const unsafe fn swap_unchecked(&mut self, a: usize, b: usize);
}
impl<T: ?Sized> *mut T {
    pub const unsafe fn swap(self, with: *mut T);
}
2021-11-12 19:17:30 +01:00
Ed Morley
b41b2e5a5c
Document unreachable!() custom panic message
The `unreachable!` docs previously did not mention that there was a second
form, `unreachable!("message")` that could be used to specify a custom panic
message,

The docs now mention this in the same style as currently used for `unimplemented!`:
https://doc.rust-lang.org/core/macro.unimplemented.html#panics
2021-11-11 13:41:21 +00:00
Scott McMurray
5b115fcb68 Moar #[inline] 2021-11-10 11:57:14 -08:00
Scott McMurray
cc7d8014d7 Specialize array cloning for Copy types
Because after PR 86041, the optimizer no longer load-merges at the LLVM IR level, which might be part of the perf loss.  (I'll run perf and see if this makes a difference.)

Also I added a codegen test so this hopefully won't regress in future -- it passes on stable and with my change here, but not on the 2021-11-09 nightly.
2021-11-09 21:43:20 -08:00
est31
eeaa2f16aa Extend the const_swap feature
This makes the inherent method ptr::swap unstably
const, as well as slice::swap{,_unchecked}.
2021-11-09 20:09:56 +01:00
bors
d6082292a6 Auto merge of #86041 - bstrie:unmagic-array-copy, r=jackh726
Replace Copy/Clone compiler magic on arrays with library impls

With const generics the compiler no longer needs to fake these impls.
2021-11-09 17:13:44 +00:00
Julian Frimmel
60a9d5a5a9 Re-enable copy[_nonoverlapping]() runtime checks
This commit re-enables the debug checks for valid usages of the two
functions `copy()` and `copy_nonoverlapping()`. Those checks were com-
mented out in #79684 in order to make the functions const. All that's
been left was a FIXME, that could not be resolved until there is was way
to only do the checks at runtime.
Since #89247 there is such a way: `const_eval_select()`. This commit
uses that new intrinsic in order to either do nothing (at compile time)
or to do the old checks (at runtime).

The change itself is rather small: in order to make the checks usable
with `const_eval_select`, they are moved into a local function (one for
`copy` and one for `copy_nonoverlapping` to keep symmetry).

The change does not break referential transparency, as there is nothing
you can do at compile time, which you cannot do on runtime without get-
ting undefined behavior. The CTFE-engine won't allow missuses. The other
way round is also fine.
2021-11-09 10:02:09 +01:00
bstrie
61b1394ac7 Attempt to address perf regressions with #[inline] 2021-11-08 15:51:56 -05:00
bstrie
3024efff59 Update Copy/Clone documentation WRT arrays 2021-11-08 13:11:59 -05:00
bstrie
ce1143e94d impl Copy/Clone for arrays in std, not in compiler 2021-11-08 13:11:58 -05:00
bstrie
86c0ef8adc Add comments regarding superfluous !Sync impls 2021-11-08 13:07:20 -05:00
bors
90a273b785 Auto merge of #90348 - Amanieu:asm_feature_gates, r=joshtriplett
Add features gates for experimental asm features

This PR splits off parts of `asm!` into separate features because they are not ready for stabilization.

Specifically this adds:
- `asm_const` for `const` operands.
- `asm_sym` for `sym` operands.
- `asm_experimental_arch` for architectures other than x86, x86_64, arm, aarch64 and riscv.

r? `@nagisa`
2021-11-07 04:59:42 +00:00
Amanieu d'Antras
eb32c00216 Add features gates for experimental asm features 2021-11-07 01:23:53 +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
Yuki Okushi
0b3a002805
Reorder widening_impls to make the doc clearer 2021-11-05 11:55:51 -07:00
Scott McMurray
dc2c2603c6 Add more text and examples to `carrying_{add|mul}" 2021-11-04 00:51:45 -07:00
bors
c7e4740ec1 Auto merge of #86336 - camsteffen:char-array-pattern, r=joshtriplett
impl Pattern for char array

Closes #39511
Closes #86329
2021-10-31 15:45:39 +00:00
Matthias Krüger
88e5ae2dd3
Rollup merge of #89786 - jkugelman:must-use-len-and-is_empty, r=joshtriplett
Add #[must_use] to len and is_empty

Parent issue: #89692

r? `@joshtriplett`
2021-10-31 13:20:05 +01:00
Matthias Krüger
d4bdcdb1ec
Rollup merge of #89951 - ojeda:stable-unwrap_unchecked, r=dtolnay
Stabilize `option_result_unwrap_unchecked`

Closes https://github.com/rust-lang/rust/issues/81383.

Stabilization report: https://github.com/rust-lang/rust/issues/81383#issuecomment-944498212.

```@rustbot``` label +A-option-result +T-libs-api
2021-10-31 09:20:27 +01:00
Matthias Krüger
95750ae439
Rollup merge of #89897 - jkugelman:must-use-core, r=joshtriplett
Add #[must_use] to remaining core functions

I've run out of compelling reasons to group functions together across crates so I'm just going to go module-by-module. This is everything remaining from the `core` crate.

Ignored by clippy for reasons unknown:

```rust
core::alloc::Layout   unsafe fn for_value_raw<T: ?Sized>(t: *const T) -> Self;
core::any             const fn type_name_of_val<T: ?Sized>(_val: &T) -> &'static str;
```

Ignored by clippy because of `mut`:

```rust
str   fn split_at_mut(&mut self, mid: usize) -> (&mut str, &mut str);
```

<del>
Ignored by clippy presumably because a caller might want `f` called for side effects. That seems like a bad usage of `map` to me.

```rust
core::cell::Ref<'b, T>   fn map<U: ?Sized, F>(orig: Ref<'b, T>, f: F) -> Ref<'b, T>;
core::cell::Ref<'b, T>   fn map_split<U: ?Sized, V: ?Sized, F>(orig: Ref<'b, T>, f: F) -> (Ref<'b, U>, Ref<'b, V>);
```
</del>

Parent issue: #89692

r? ```@joshtriplett```
2021-10-31 09:20:26 +01:00
Matthias Krüger
e79e9f5e2a
Rollup merge of #89839 - jkugelman:must-use-mem-ptr-functions, r=joshtriplett
Add #[must_use] to mem/ptr functions

There's a lot of low-level / unsafe stuff here. Are there legit use cases for ignoring any of these return values?

* No regressions in `./x.py test --stage 1 library/std src/tools/clippy`.
* One regression in `./x.py test --stage 1 src/test/ui`. Fixed.
* I am unable to run `./x.py doc` on my machine so I'll need to wait for the CI to verify doctests pass. I eyeballed all the adjacent tests and they all look okay.

Parent issue: #89692

r? ```@joshtriplett```
2021-10-31 09:20:25 +01:00
Matthias Krüger
a26b1d2259
Rollup merge of #89835 - jkugelman:must-use-expensive-computations, r=joshtriplett
Add #[must_use] to expensive computations

The unifying theme for this commit is weak, admittedly. I put together a list of "expensive" functions when I originally proposed this whole effort, but nobody's cared about that criterion. Still, it's a decent way to bite off a not-too-big chunk of work.

Given the grab bag nature of this commit, the messages I used vary quite a bit. I'm open to wording changes.

For some reason clippy flagged four `BTreeSet` methods but didn't say boo about equivalent ones on `HashSet`. I stared at them for a while but I can't figure out the difference so I added the `HashSet` ones in.

```rust
// Flagged by clippy.
alloc::collections::btree_set::BTreeSet<T>   fn difference<'a>(&'a self, other: &'a BTreeSet<T>) -> Difference<'a, T>;
alloc::collections::btree_set::BTreeSet<T>   fn symmetric_difference<'a>(&'a self, other: &'a BTreeSet<T>) -> SymmetricDifference<'a, T>
alloc::collections::btree_set::BTreeSet<T>   fn intersection<'a>(&'a self, other: &'a BTreeSet<T>) -> Intersection<'a, T>;
alloc::collections::btree_set::BTreeSet<T>   fn union<'a>(&'a self, other: &'a BTreeSet<T>) -> Union<'a, T>;

// Ignored by clippy, but not by me.
std::collections::HashSet<T, S>              fn difference<'a>(&'a self, other: &'a HashSet<T, S>) -> Difference<'a, T, S>;
std::collections::HashSet<T, S>              fn symmetric_difference<'a>(&'a self, other: &'a HashSet<T, S>) -> SymmetricDifference<'a, T, S>
std::collections::HashSet<T, S>              fn intersection<'a>(&'a self, other: &'a HashSet<T, S>) -> Intersection<'a, T, S>;
std::collections::HashSet<T, S>              fn union<'a>(&'a self, other: &'a HashSet<T, S>) -> Union<'a, T, S>;
```

Parent issue: #89692

r? ```@joshtriplett```
2021-10-31 09:20:24 +01:00
Matthias Krüger
e7be8a2c07
Rollup merge of #89446 - chrismit3s:issue-88715-fix, r=joshtriplett
Add paragraph to ControlFlow docs to menion it works with the ? operator (#88715)

fixes #88715

r? ```@steveklabnik```
2021-10-31 09:20:21 +01:00
bors
0a09858b05 Auto merge of #90306 - kornelski:slicecloneasset, r=joshtriplett
track_caller for slice length assertions

`clone_from_slice` was missing `#[track_caller]`, and its assert did not report a useful location.

These are small generic methods, so hopefully track_caller gets inlined into nothingness, but it may be worth running a benchmark on this.
2021-10-31 01:56:40 +00:00
John Kugelman
6745e8da06 Add #[must_use] to len and is_empty 2021-10-30 19:25:12 -04:00
John Kugelman
887503ad14 Add #[must_use] to mem/ptr functions 2021-10-30 18:54:48 -04:00
John Kugelman
68b0d86294 Add #[must_use] to remaining core functions 2021-10-30 18:21:29 -04:00
Matthias Krüger
b531364a1a
Rollup merge of #90377 - WaffleLapkin:const_slice_from_raw_parts, r=oli-obk
Make `core::slice::from_raw_parts[_mut]` const

Responses to #90012 seem to allow ``@rust-lang/wg-const-eval`` to decide on use of `const_eval_select`, so we can make `core::slice::from_raw_parts[_mut]` const :)

---
This PR marks the following APIs as const:
```rust
// core::slice
pub const unsafe fn from_raw_parts<'a, T>(data: *const T, len: usize) -> &'a [T];
pub const unsafe fn from_raw_parts_mut<'a, T>(data: *mut T, len: usize) -> &'a mut [T];
```
---

Resolves #90011
r? ``@oli-obk``
2021-10-30 14:37:01 +02:00
Matthias Krüger
86087f906d
Rollup merge of #90371 - Veykril:patch-2, r=jyn514
Fix incorrect doc link

Looks like a copy paste mistake
2021-10-30 14:36:59 +02:00
Matthias Krüger
20bb93210d
Rollup merge of #89876 - AlexApps99:const_ops, r=oli-obk
Make most std::ops traits const on numeric types

This PR makes existing implementations of `std::ops` traits (`Add`, `Sub`, etc) [`impl const`](https://github.com/rust-lang/rust/issues/67792) where possible.
This affects:
- All numeric primitives (`u*`, `i*`, `f*`)
- `NonZero*`
- `Wrapping`

This is under the `rustc_const_unstable` feature `const_ops`.
I will write tests once I know what can and can't be kept for the final version of this PR.

Since this is my first PR to rustc (and hopefully one of many), please give me feedback on how to better handle the PR process wherever possible. Thanks

[Zulip discussion](https://rust-lang.zulipchat.com/#narrow/stream/219381-t-libs/topic/Const.20std.3A.3Aops.20traits.20PR)
2021-10-30 14:36:58 +02:00
bors
6d42707cde Auto merge of #90346 - ferrocene:pa-short-circuit, r=oli-obk
Replace some operators in libcore with their short-circuiting equivalents

In libcore there are a few occurrences of bitwise operators used in boolean expressions instead of their short-circuiting equivalents. This makes it harder to perform some kinds of source code analysis over libcore, for example [MC/DC] code coverage (a requirement in safety-critical environments).

This PR aims to remove as many bitwise operators in boolean expressions from libcore as possible, without any performance regression and without other changes. This means not all bitwise operators are removed, only the ones that don't have any difference with their short-circuiting counterparts. This already simplifies achieving MC/DC coverage, and the other functions can be changed in future PRs.

The PR is best reviewed commit-by-commit, and each commit has the resulting assembly in the message.

## Checked integer methods

These methods recently switched to bitwise operators in PRs https://github.com/rust-lang/rust/pull/89459 and https://github.com/rust-lang/rust/pull/89351. I confirmed bitwise operators are needed in most of the functions, except these two:

* `{integer}::checked_div` ([Godbolt link (nightly)](https://rust.godbolt.org/z/17efh5jPc))
* `{integer}::checked_rem` ([Godbolt link (nightly)](https://rust.godbolt.org/z/85qGWc94K))

`@tspiteri` already mentioned this was the case in https://github.com/rust-lang/rust/pull/89459#issuecomment-932728384, but opted to also switch those two to bitwise operators for consistency. As that makes MC/DC analysis harder this PR proposes switching those two back to short-circuiting operators.

## `{unsigned_ints}::carrying_add`

[Godbolt link (1.56.0)](https://rust.godbolt.org/z/vG9vx8x48)

In this instance replacing the `|` with `||` produces the exact same assembly when optimizations are enabled, so switching to the short-circuiting operator shouldn't have any impact.

## `{unsigned_ints}::borrowing_sub`

[Godbolt link (1.56.0)](https://rust.godbolt.org/z/asEfKaGE4)

In this instance replacing the `|` with `||` produces the exact same assembly when optimizations are enabled, so switching to the short-circuiting operator shouldn't have any impact.

## String UTF-8 validation

[Godbolt link (1.56.0)](https://rust.godbolt.org/z/a4rEbTvvx)

In this instance replacing the `|` with `||` produces practically the same assembly, with the two operands for the "or" swapped:

```asm
; Old
mov  rax, qword ptr [rdi + rdx + 8]
or   rax, qword ptr [rdi + rdx]
test rax, r9
je   .LBB0_7

; New
mov  rax, qword ptr [rdi + rdx]
or   rax, qword ptr [rdi + rdx + 8]
test rax, r8
je   .LBB0_7
```

[MC/DC]: https://en.wikipedia.org/wiki/Modified_condition/decision_coverage
2021-10-29 21:50:46 +00:00
Maybe Waffle
afaa54a99d Apply changes proposed in the review 2021-10-29 23:45:09 +03:00
Maybe Waffle
878ac10fe1 Use proper issue number for feature(const_slice_from_raw_parts) 2021-10-29 22:45:10 +03:00
Matthias Krüger
ae244d8b78
Rollup merge of #90336 - mbartlett21:patch-4, r=Mark-Simulacrum
Remove extra lines in examples for `Duration::try_from_secs_*`

None of the other examples have extra lines below the `#![feature(...)]` statements, so I thought it appropriate that these examples shouldn't either.
2021-10-29 00:30:30 +02:00
Maybe Waffle
991a296ce7 Make core::slice::from_raw_parts[_mut] const 2021-10-28 17:15:25 +03:00
Lukas Wirth
29a4e4a009
Fix incorrect doc link 2021-10-28 11:51:00 +02:00
bors
dd757b9e06 Auto merge of #90273 - nbdd0121:const, r=fee1-dead
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.

r? `@oli-obk`
`@rustbot` label A-const-eval T-compiler
2021-10-27 15:32:42 +00:00
Pietro Albini
68a4460b61
replace & with && in {integer}::checked_rem
Using short-circuit operators makes it easier to perform some kinds of
source code analysis, like MC/DC code coverage (a requirement in
safety-critical environments). The optimized x86 assembly is the same
between the old and new versions:

```
xor eax, eax
test esi, esi
je .LBB0_1
cmp edi, -2147483648
jne .LBB0_4
cmp esi, -1
jne .LBB0_4
ret
.LBB0_1:
ret
.LBB0_4:
mov eax, edi
cdq
idiv esi
mov eax, 1
ret
```
2021-10-27 17:01:05 +02:00
Pietro Albini
81130fe188
replace & with && in {integer}::checked_div
Using short-circuit operators makes it easier to perform some kinds of
source code analysis, like MC/DC code coverage (a requirement in
safety-critical environments). The optimized x86 assembly is the same
between the old and new versions:

```
xor eax, eax
test esi, esi
je .LBB0_1
cmp edi, -2147483648
jne .LBB0_4
cmp esi, -1
jne .LBB0_4
ret
.LBB0_1:
ret
.LBB0_4:
mov eax, edi
cdq
idiv esi
mov edx, eax
mov eax, 1
ret
```
2021-10-27 17:00:57 +02:00
Pietro Albini
a5a8bb0125
replace | with || in string validation
Using short-circuiting operators makes it easier to perform some kinds
of source code analysis, like MC/DC code coverage (a requirement in
safety-critical environments). The optimized x86_64 assembly is
equivalent between the old and new versions.

Old assembly of that condition:

```
mov  rax, qword ptr [rdi + rdx + 8]
or   rax, qword ptr [rdi + rdx]
test rax, r9
je   .LBB0_7
```

New assembly of that condition:

```
mov  rax, qword ptr [rdi + rdx]
or   rax, qword ptr [rdi + rdx + 8]
test rax, r8
je   .LBB0_7
```
2021-10-27 17:00:49 +02:00
Pietro Albini
9fb66969e3
replace | with || in {unsigned_int}::borrowing_sub
Using short-circuiting operators makes it easier to perform some kinds
of source code analysis, like MC/DC code coverage (a requirement in
safety-critical environments). The optimized x86_64 assembly is the same
between the old and new versions:

```
mov eax, edi
add dl, -1
sbb eax, esi
setb dl
ret
```
2021-10-27 17:00:46 +02:00
Pietro Albini
5913ef6660
replace | with || in {unsigned_int}::carrying_add
Using short-circuiting operators makes it easier to perform some kinds
of source code analysis, like MC/DC code coverage (a requirement in
safety-critical environments). The optimized x86_64 assembly is the same
between the old and new versions:

```
mov eax, edi
add dl, -1
adc eax, esi
setb dl
ret
```
2021-10-27 17:00:36 +02:00
Matthias Krüger
e3eebfeea6
Rollup merge of #90154 - camelid:remove-getdefid, r=jyn514
rustdoc: Remove `GetDefId`

See the individual commit messages for details.

r? `@jyn514`
2021-10-27 06:11:35 +02:00
mbartlett21
aa48de0b0e
Remove extra lines in examples for Duration::try_from_secs_* 2021-10-27 13:52:39 +10:00