From ed0d8fa3e8c061fdd22fb95f6cfadbada864118d Mon Sep 17 00:00:00 2001 From: AngelicosPhosphoros Date: Sat, 3 Apr 2021 20:58:15 +0300 Subject: [PATCH] Optimize PartialOrd le Closes https://github.com/rust-lang/rust/issues/73338 This change stops default implementation of `le()` method from generating jumps. --- library/core/src/cmp.rs | 3 +- src/test/codegen/issue-73338-effecient-cmp.rs | 39 +++++++++++++++++++ 2 files changed, 41 insertions(+), 1 deletion(-) create mode 100644 src/test/codegen/issue-73338-effecient-cmp.rs diff --git a/library/core/src/cmp.rs b/library/core/src/cmp.rs index 5bab1fb93db..adb033e6bdf 100644 --- a/library/core/src/cmp.rs +++ b/library/core/src/cmp.rs @@ -981,7 +981,8 @@ pub trait PartialOrd: PartialEq { #[must_use] #[stable(feature = "rust1", since = "1.0.0")] fn le(&self, other: &Rhs) -> bool { - matches!(self.partial_cmp(other), Some(Less | Equal)) + // Pattern `Some(Less | Eq)` optimizes worse than negating `None | Some(Greater)`. + !matches!(self.partial_cmp(other), None | Some(Greater)) } /// This method tests greater than (for `self` and `other`) and is used by the `>` operator. diff --git a/src/test/codegen/issue-73338-effecient-cmp.rs b/src/test/codegen/issue-73338-effecient-cmp.rs new file mode 100644 index 00000000000..85c2bbfd040 --- /dev/null +++ b/src/test/codegen/issue-73338-effecient-cmp.rs @@ -0,0 +1,39 @@ +// This test checks that comparison operation +// generated by #[derive(PartialOrd)] +// doesn't contain jumps for C enums + +// compile-flags: -Copt-level=3 + +#![crate_type="lib"] + +#[repr(u32)] +#[derive(Copy, Clone, Eq, PartialEq, PartialOrd)] +pub enum Foo { + Zero, + One, + Two, +} + +#[no_mangle] +pub fn compare_less(a: Foo, b: Foo)->bool{ + // CHECK-NOT: br {{.*}} + a < b +} + +#[no_mangle] +pub fn compare_le(a: Foo, b: Foo)->bool{ + // CHECK-NOT: br {{.*}} + a <= b +} + +#[no_mangle] +pub fn compare_ge(a: Foo, b: Foo)->bool{ + // CHECK-NOT: br {{.*}} + a >= b +} + +#[no_mangle] +pub fn compare_greater(a: Foo, b: Foo)->bool{ + // CHECK-NOT: br {{.*}} + a > b +}