Skip to content

Harden stable implementation of black_box #54

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

Merged
merged 3 commits into from
Sep 27, 2019

Conversation

dsprenkels
Copy link
Contributor

This PR improves the implementation of black_box, using the fact that the semantics of volatile are pretty well defined. With this change, you could probably even omit #[inline(never)], and then it may even be more efficient (I didn't benchmark).

// Bailing out, hopefully the compiler doesn't use the fact that ``input`` is 0 or 1.

This patch also defines this case. ^

Example codegen: https://godbolt.org/z/3xYX1U

Daan Sprenkels added 2 commits September 12, 2019 17:23
In Rust, `core::ptr::read_volatile` is not formally specified.
However the current documentation mentions that "the semantics
will almost always end up pretty similar to C11's definition of
volatile".

In C11, a volatile read *always* reads a value from memory. So this
value *must* be in RAM in that form, at some time.

This allows us to create a relatively efficient optimization
barrier, by spilling the value to the stack, and immediadiately
reloading it again.

The benefit is that LTO could ever optimize the empty function
away, even if #[inline(always)] is specified (although this may
be very unlikely). However, `volatile` is concretely specified,
so this optimization barrier will not be lost.
b43b139 effectively disables the branches produced by LLVM, so
remove the statement that the non-`nightly` `black_box` does not
protect against these optimizations.
Copy link
Contributor

@hdevalence hdevalence left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks!

@hdevalence hdevalence changed the base branch from master to develop September 27, 2019 23:43
@hdevalence hdevalence merged commit 48a0690 into dalek-cryptography:develop Sep 27, 2019
@dsprenkels
Copy link
Contributor Author

Relevant for #37: this code relies on the fact that LLVM cannot optimize through an explicit memory lookup. This always involves an L1 round-trip.

Though afaik there is currently no way to kill the optimization in stable rust without using memory lookups or an opaque function.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants