Use of `core::intrinsics::assume()` on separate crate

I want to create a crate with a macro, debug_assume!(), that asserts a specific condition in debug builds and provides optimization hint in release builds.

Now, I'm using core::intrinsics::assume() for that, but unfortunately that's not stable. I can bypass this in two ways:

  1. Using #![feature(core_intrinsics)] in the crate. Unfortunately because this is a macro, I need that in the importing crate and not in the imported crate.
  2. Using a separate function, something like:
#[doc(hidden)]
#[inline(always)]
pub unsafe fn __assume(b: bool) {
    std::intrinsics::assume(b);
}

macro_rules! debug_assume {
    // ...
    $crate::__assume($cond)
}

But now, even with #[inline(always)], I'm not sure the compiler will consider the hint.

Is there anyone that knows to say either how to per-function use nightly feature or whether the compiler will take the above hint?

I am pretty sure it will.

You can add #[allow_internal_unstable(core_intrinsics)] to the macro definition.

Be warned that assume can not only enable optimizations but also prevent them as LLVM tries to preserve assume calls even when doing so requires some optimizations to not be performed.

No. Using nightly is viral in that if any part of any crate you depend on uses nightly, your executable will also need to use nightly.

The Rust Reference says #[inline(always)] is just a hint, but in practice it's pretty much guaranteed to be inlined.

I believe there are bits of the standard library where you need to know that a new stack frame won't be created (here for example), so it's probably safe to rely on #[inline(always)] always working.

Consider using this alternative:

#[doc(hidden)]
#[inline(always)]
pub unsafe fn __assume(b: bool) {
    if !b {
        std::hint::unreachable_unchecked();
    }
}
1 Like

inline(always) cannot work on recursive code, which is why it can't be guaranteed. I don't know for sure, but I don't think there are other cases where inlining can fail. If there is, it'd be interesting to know about it.