Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rollup of 6 pull requests #67220

Merged
merged 15 commits into from
Dec 11, 2019
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Optimize Ord trait implementation for bool
Casting the booleans to `i8`s and converting their difference
into `Ordering` generates better assembly than casting them to
`u8`s and comparing them.
Krishna Sai Veera Reddy committed Nov 29, 2019
commit 4ca769ad091ef0018f5a20effaf4b4f428a034d7
11 changes: 10 additions & 1 deletion src/libcore/cmp.rs
Original file line number Diff line number Diff line change
@@ -1006,6 +1006,7 @@ pub fn max_by_key<T, F: FnMut(&T) -> K, K: Ord>(v1: T, v2: T, mut f: F) -> T {

// Implementation of PartialEq, Eq, PartialOrd and Ord for primitive types
mod impls {
use crate::hint::unreachable_unchecked;
use crate::cmp::Ordering::{self, Less, Greater, Equal};

macro_rules! partial_eq_impl {
@@ -1126,7 +1127,15 @@ mod impls {
impl Ord for bool {
#[inline]
fn cmp(&self, other: &bool) -> Ordering {
(*self as u8).cmp(&(*other as u8))
// Casting to i8's and converting the difference to an Ordering generates
// more optimal assembly.
// See <https://github.com/rust-lang/rust/issues/66780> for more info.
match (*self as i8) - (*other as i8) {
-1 => Less,
0 => Equal,
1 => Greater,
_ => unsafe { unreachable_unchecked() },
}
}
}

8 changes: 8 additions & 0 deletions src/libcore/tests/cmp.rs
Original file line number Diff line number Diff line change
@@ -9,6 +9,14 @@ fn test_int_totalord() {
assert_eq!(12.cmp(&-5), Greater);
}

#[test]
fn test_bool_totalord() {
assert_eq!(true.cmp(&false), Greater);
assert_eq!(false.cmp(&true), Less);
assert_eq!(true.cmp(&true), Equal);
assert_eq!(false.cmp(&false), Equal);
}

#[test]
fn test_mut_int_totalord() {
assert_eq!((&mut 5).cmp(&&mut 10), Less);
17 changes: 17 additions & 0 deletions src/test/codegen/bool-cmp.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
// This is a test for optimal Ord trait implementation for bool.
// See <https://github.com/rust-lang/rust/issues/66780> for more info.

// compile-flags: -C opt-level=3

#![crate_type = "lib"]

use std::cmp::Ordering;

// CHECK-LABEL: @cmp_bool
#[no_mangle]
pub fn cmp_bool(a: bool, b: bool) -> Ordering {
// CHECK: zext i1
// CHECK: zext i1
// CHECK: sub nsw
a.cmp(&b)
}