From 543e77fb6b2e419625548a4c3e76050c62863425 Mon Sep 17 00:00:00 2001 From: Michael Woerister Date: Tue, 18 Jan 2022 11:47:57 +0100 Subject: [PATCH] Make sure std::panic::Location::caller() gets optimized away. --- library/core/src/panic/location.rs | 1 + src/test/codegen/track_caller_inlined.rs | 28 ++++++++++++++++++++++++ 2 files changed, 29 insertions(+) create mode 100644 src/test/codegen/track_caller_inlined.rs diff --git a/library/core/src/panic/location.rs b/library/core/src/panic/location.rs index 714e9b73c78a6..1b0bd17e8ffcf 100644 --- a/library/core/src/panic/location.rs +++ b/library/core/src/panic/location.rs @@ -83,6 +83,7 @@ impl<'a> Location<'a> { #[stable(feature = "track_caller", since = "1.46.0")] #[rustc_const_unstable(feature = "const_caller_location", issue = "76156")] #[track_caller] + #[inline(always)] // Mark as inline so that the call gets optimized away. pub const fn caller() -> &'static Location<'static> { crate::intrinsics::caller_location() } diff --git a/src/test/codegen/track_caller_inlined.rs b/src/test/codegen/track_caller_inlined.rs new file mode 100644 index 0000000000000..e83a0ed9b5267 --- /dev/null +++ b/src/test/codegen/track_caller_inlined.rs @@ -0,0 +1,28 @@ +// This test makes sure that calls to std::panic::Location::caller() +// don't result in an actual function call. The caller location is +// known at compile time so the call can always be optimized away. + +// compile-flags: -Copt-level=2 + +#![crate_type = "lib"] +#![feature(bench_black_box)] + +// The first check makes sure that the caller location is used at all, +// i.e. that std::hint::black_box() works. +// CHECK: %0 = alloca %"core::panic::location::Location"* + +// This check makes sure that no call to `std::panic::Location::caller()` +// is emitted. The sequence of characters is valid for both v0 and legacy +// mangling. +// CHECK-NOT: call {{.*}}8Location6caller + +// CHECK: call void asm sideeffect {{.*}}(%"core::panic::location::Location"** nonnull %0) + +#[track_caller] +fn foo() { + std::hint::black_box(std::panic::Location::caller()); +} + +pub fn bar() { + foo(); +}