This is an archive of the discontinued LLVM Phabricator instance.

Optimize std::midpoint for integers
ClosedPublic

Authored by jorgbrown on Oct 25 2019, 9:03 PM.

Details

Summary

Same idea as the current algorithm, that is, add (half of the difference between a and b) to a.

But we use a different technique for computing the difference: we compute b - a into a pair of integers that are named "sign_bit" and "diff". We have to use a pair because subtracting two 32-bit integers produces a 33-bit result.

Computing half of that is a simple matter of shifting diff right by 1, and adding sign_bit shifted left by 31. llvm knows how to do that with one instruction: shld.

The only tricky part is that if the difference is odd and negative, then shifting it by one isn't the same as dividing it by two - shifting a negative one produces a negative one, for example. So there's one more adjustment: if the sign bit and the low bit of diff are one, we add one.

For a demonstration of the codegen difference, see https://godbolt.org/z/7ar3K9 , which also has a built-in test.

Diff Detail

Event Timeline

jorgbrown created this revision.Oct 25 2019, 9:03 PM
mclow.lists accepted this revision.Oct 27 2019, 12:29 PM

This looks good to me.
Shorter code, still no branches; passes all the tests.

This revision is now accepted and ready to land.Oct 27 2019, 12:29 PM
This revision was automatically updated to reflect the committed changes.
Herald added a project: Restricted Project. · View Herald TranscriptNov 4 2019, 7:33 PM
Herald added a subscriber: christof. · View Herald Transcript

I did some playing with compiler explorer, and got even better codegen by sprinkling casts to _Up over the calculation to __half_diff.
This only makes a difference if _Tp is smaller than int.

_Up __half_diff = _Up(__diff / 2) + 
                  _Up(__sign_bit << __bitshift) + 
                  _Up(__sign_bit & __diff);