Skip to content
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

Compiler optimization #17

Open
tkaitchuck opened this issue Mar 1, 2019 · 2 comments
Open

Compiler optimization #17

tkaitchuck opened this issue Mar 1, 2019 · 2 comments

Comments

@tkaitchuck
Copy link

For whatever reason when I use array_ref!() and then look at the generated assembly, I can see the compiler for whatever reason is not able to elude the bounds checking when the array is split inside of the macro. This happens even at -O 3, and it is directly surrounded by an if check on the length of the slice.
I was able to work around it, by moving the slice outside of the macro. Creating a new macro where the caller has to pre-slice things so the sliced passed in is exactly the side of the desired array.

macro_rules! as_array {
    ($input:expr, $len:expr) => {{
        {
            #[inline]
            fn as_array<T>(slice: &[T]) -> &[T; $len] {
                assert_eq!(slice.len(), $len);
                unsafe {
                    &*(slice.as_ptr() as *const [_; $len])
                }
            }
            as_array($input)
        }
    }}
}

While this is a little more awkward to call, it is a lot easier to explain and because the compiler is able to elude the bounds checks performs better. It may be worth incorporating this method.

@droundy
Copy link
Owner

droundy commented Mar 1, 2019

Are you thinking that using as_array! internally in array_ref! could improve compiler optimizations?

@tkaitchuck
Copy link
Author

Yes. When I use the array_ref and look at the assembly generated it always seems to have a branch to panic in the event that the length is out of bounds, even when it's enclosed in an if statement explicitly testing the length. I'm not sure why. Something about the way the code gets structured.

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

No branches or pull requests

2 participants