Skip to content

Commit

Permalink
Move likely/unlikely argument outside of invisible unsafe block
Browse files Browse the repository at this point in the history
The previous `likely!`/`unlikely!` macros were unsound because it
permits the caller's expr to contain arbitrary unsafe code.

    pub fn huh() -> bool {
        likely!(std::ptr::read(&() as *const () as *const bool))
    }

Before: compiles cleanly.
After:

    error[E0133]: call to unsafe function is unsafe and requires unsafe function or block
       |
    70 |     likely!(std::ptr::read(&() as *const () as *const bool))
       |             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ call to unsafe function
       |
       = note: consult the function's documentation for information on how to avoid undefined behavior
  • Loading branch information
dtolnay committed Nov 14, 2020
1 parent 98d6634 commit afb8170
Showing 1 changed file with 6 additions and 6 deletions.
12 changes: 6 additions & 6 deletions compiler/rustc_data_structures/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,19 +47,19 @@ pub fn cold_path<F: FnOnce() -> R, R>(f: F) -> R {
#[macro_export]
macro_rules! likely {
($e:expr) => {
#[allow(unused_unsafe)]
{
unsafe { std::intrinsics::likely($e) }
match $e {
#[allow(unused_unsafe)]
e => unsafe { std::intrinsics::likely(e) },
}
};
}

#[macro_export]
macro_rules! unlikely {
($e:expr) => {
#[allow(unused_unsafe)]
{
unsafe { std::intrinsics::unlikely($e) }
match $e {
#[allow(unused_unsafe)]
e => unsafe { std::intrinsics::unlikely(e) },
}
};
}
Expand Down

0 comments on commit afb8170

Please sign in to comment.