fulmicoton•

I love these posts... This is so much more constructive / more informed than the usual rants we get here.

The author put some serious sweat in learning Rust. Sometimes the solution to his problem exists but is non-trivial, some people put it in the comment and everybody gets smarter. Sometimes no rusty solution exist and it is also great to have a mental list of such points.

25
vks_•
       for _ in 0..h {
           for x in 0..w {
               dst[didx + x] = src[sidx + x];
           }
           sidx += sstride;
           didx += dstride;
       }

[...] Conclusion: rustc is too stupid to recognize copies.

Is it actually this simple? I think due to out-of-bound panics Rust cannot just optimize this into a copy. Adding an assert about the length of the arrays might fix this.

13
ssokolow•

I think I remember also reading that working backwards from the end of the array was another way to get the optimizer to collapse away the checks.

8
frankmcsherryabomonation · differential · timely•

It's an interesting question. I don't think going backwards will help, because you could have overflowed (imagine didx and sidx are u8), which I think is defined as wrapping in release.

I tried a bit to give hints to Rust to turn it in to a memcpy. Just establishing that the bounds hold didn't seem to work; the following is still a loop:

pub fn copy1(dst: &mut[usize], src: &[usize], off: usize, bound: usize) {
    { let dst1 = &dst[off..][..bound]; }
    { let src1 = &src[off..][..bound]; }
    for x in 0 .. bound {
        dst[off + x] = src[off + x];
    }
}

Changing x to go from off to off + bound didn't improve anything. But actually using the slices was fine; this ends up as a memcpy:

pub fn copy2(dst: &mut[usize], src: &[usize], off: usize, bound: usize) {
    let dst1 = &mut dst[off..][..bound];
    let src1 = &src[off..][..bound];
    for x in 0 .. bound {
        dst1[x] = src1[x];
    }
}

I just try and use slices everywhere, as it seems more readable to me, but it would be nice to understand this better to help out the folks who are used to the compiler being a bit more transparent.

12
ssokolow•

Point.

The optimizer can collapse away array access bounds checks if the first access passing ensures that the others must pass (ie. If it passes for x=y and all further accesses are in the range 0..y) but it doesn't really do anything for the way you're using sidx and didx as far as I can remember.

5
valarauca8•

I think due to out-of-bound panics Rust cannot just optimize this into a copy

The LLVM is bad at vectorization. Here is a simple function I spent about 10minutes trying to make vectorize yesterday. I couldn't get a single permutation that would vectorize.

To elid bounds checks you need to do

if arr.len() == X {
   for i in 0..X {
      //work
   }
}

Simple for i in 0..arr.len() doesn't always work

6
frankmcsherryabomonation · differential · timely•

I played around with vectorization a bit (not to be difficult, just trying to learn what works and doesn't). Rust seemed fine at vectorizing iterators without breaking control flow (e.g. not all or any, which I think you wanted). I couldn't get it to vectorize anything with early returns or plain iteration, without copy/pasting Rust source.

But, if you write your equality test using sum, which looks silly, it vectorizes on godbolt:

vec1.iter()
    .zip(vec2.iter())
    .map(|(x,y)| if *x == *y { 0 } else { 1 })
    .sum::<u32>()

I haven't had problems with for i in 0..arr.len() not working for eliding bounds checks; what was the problem you had?

11
oln•

But, if you write your equality test using sum, which looks silly, it vectorizes on godbolt:

I would think this is due to the fact that doing it like this will always iterate through the whole array, which makes it easier for llvm to reason about.

1
Veedrac•

LLVM doesn't know that old is as long as its len, so it can't actually use it to justify optimizations where there is early-out. Generally you need to do as u/frankmcsherry did and make a non-branching version, and if you want early-out you just have to chunk the loop manually at appropriate boundaries.

Such is life.

9
[deleted]•

[deleted]

1
Eroc33•

From a little experimentation it seems rust won't vectorize loops that break early.

Also as seen in these 2 examples rust doesn't seem to want to vectorize loops operating on booleans:

EDIT: I can't get any C/C++ compilers to auto-vectorize a loop with an early return either, although clang will vectorise loops using booleans, so rust does fall slightly short in that regard.

6
MEaster•

Let us not speak of my earlier dumbassery (I blame staying up later than I should), but this code with a bool vectorised, didn't it?

1
Eroc33•

Did you post the wrong link? I don't see any vector ops in the asm for the example you posted?

1
oln•

Yea, there are some interesting issues with vectorization of range iterators at the moment. On the positive side, there was a for_each function recently added to the iterator trait which should make it possible to simplify the output to llvm of a loop over a range (and probably in other cases too) a fair bit.

I did manage to get the example to partially unroll the loop using while instead of for, it still didn't vectorize though.

3
vks_•

Simple for i in 0..arr.len() doesn't always work

Yes, there could be side effects preventing optimization. This is the correct thing to do by the compiler!

Did you try assert_eq!(arr.len(), X);?

2
est31•

I think its about panic messages when there is an out of bounds error. Due to the way rust generates code, and the LLVM optimizer works, the optimizer has to keep the panic messages intact. This is one of the sadder parts actually.

2
matthieum•

I think if it can prove that there will be no panic, then it's fine.

Which is why a trick can be backward iteration: if the first access doesn't panic, then the subsequent accesses should not either.

1
MEaster•

Did you not try zipping two iterators together, and comparing all() like this. Though, admittedly, I only tried it to see what the compiler spat out.

1
stjepang•

Also it’s obvious how Rust makes the code that sacrifices checks for speed uglier (compare a + b and a.wrapping_add(b) or arr[i] and *ptr.offset(i as isize)).

The latter will become *ptr.add(i) with this RFC (in final comment period).

13
lu_zeroOP•

Probably using the iterators (in the case at hand chunk()-ing the slice and zipping might help the compiler figure out what you want) would lead to good performance, but takes a bit of time to figure out what's the best way to use them.

11
est31•

As someone who has written a decoder of his own, I can confirm that the bounds checks that Rust is doing are some of the major sources of issues with performance I ran into. It would be really good to get better ways to get rid of them in safe code, and to give coders a good way to know which bounds checks were eliminated and which ones the compiler couldn't eliminate. Optimally you could do #![deny(bounds_check)] and ensure there is a compile error if a bounds check that previously could be eliminated now reappeared due to a change. With the deny in place, you'll have to place #[allow(bounds_check)] to places where the optimizer missed optimizing bounds checks.

Iterators are nice, but they only work up to a certain level of complexity of access patterns, and codecs very often have very complicated access patterns.

E.g. take implementing huffman codes. Basically what you have is a totally unbalanced (thats its point) binary tree, and when decoding a word, you need to traverse the tree bit by bit and maybe stop somewhere. So generally, a good way of doing this performant is to use tables where you keep 256 entries around, each of them corresponding to a different entry byte, with the entry containing the decoded word and the number of bits the word is long. However, sometimes you have huffman trees with more than 8 bit words. I've tried to use a tree of 256-entry-blocks but this turned out to be not performant, probably due to cache locality. Instead I'm doing the following: the first 256-bytes-table contains either the value, or a pointer to a continuation of the tree. For the pointer I don't want to use a reference to not blow up cache locality, instead I'm using u32 numbers that then can be used as indices to an array. When creating these numbers, I know already that they are indices, but I can't encode it in the type system so what ends up happening is that Rust (probably) still does bounds checks when I'm looking up in the array, even though there is no point to do so.

Edit: also I want to point out that decoders are some of the areas where safe and fast systems programming languages could really shine in the future, because decoders often have to parse untrusted stuff, and due to their complexity they also pose an attack surface. Of course, there is only a handful of actually mature decoder projects (ffmpeg, libav, libvlc, & the infamous stagefright), and you can't make that much money from implementing decoders, so there will be certainly less developers and this means its not as big of a market for a language than say web service development, but virtually everyone is using decoders, either through their browsers or through apps on their mobile devices. The large scale usage of these decoders is part of the reason why there is such a strong demand to get them secured.

11
leonardo_m•

I suggested slice access methods that don't compile if the compiler isn't able to optimize their bound checks :-) I am not sure what's the best solution. Some alternative solutions should be tried and compared.

But this is only a part of the solution. There's a need for an optimization stage in the front-end (not performed by LLVM), improvements to the type system, and probably more.

Another disadvantage of Iterators that is often ignored is that they generate lot of code that the back-end has to optimize away. Even when LLVM is able to do this job well, it still takes lot of time and RAM compared to compiling C-like array code. Those abstractions have costs.

7
_zenith•

Yep. Not runtime cost (usually), but compile-time cost.

2
Veedrac•

FWIW, if the table size is a nice, constant power of two (which you can normally force it to be), you can avoid the check by doing a mask before access.

3
est31•

That's a quite nice idea in fact. Its not constant (the huffman setup is sent in the second packet) but I might be able to force it to be a power of two by filling it up.

2
Veedrac•

Glad I could help :). It's worth remembering that bounds checks only really hurt when they prevent other optimisations (vectorization especially), since they're easily-predicted branches, so it's only worth swapping them for a data dependency when they do.

3
neutralinostaritertools · rust•

Well.. counted loops with indexing aren't considered idiomatic Rust.

I know it still feels like we are all trying to find the best primitives for this kind of work together, and it's not finished yet. Yes, the Iterators are “weak” and don't cover everything (no efficient random access, for one).

The transformation of the first nested loop is typical of what we can do: The innermost loop was promoted to a method (Or specific purpose iterator - I believe using zip with element iterators would have accomplished it as well.)

10
NeuroXc•

To answer a couple of points:

maybe there is/there should be a way to tell compiler “hey, this slice is guaranteed to be this size, drop the unneeded checks”;

You can, with an assert statement.

non-checking arithmetic is a bit too inconvenient to write (by design, I suppose) but it may help to squeeze some performance;

Rust's arithmetic is non-checking (twos-complement wrapping) in release mode. This is why you see such small improvements by making it explicit--it's likely noise.

You likely didn't have to sacrifice as much in ergonomics as you thought. However, Rust's compiler does still have many optimizations it has not taken advantage of, and some of the simple tricks you can use to coerce optimizations are not necessarily easy to discover.

10
staticassert•

I've definitely noticed cases where rust should be optimizing out bounds checks but does not. I bet some of those performance come from bounds - like the copy example that comes first. Although I think due to side effects it can't do things like turn

for i in 0..arr.len {
    arr_a[i] = arr_b[i];
}

into:

arr_a[..].copy_from_slice(arr_b[..])

since when the sizes are different the semantics are not the same. So you have to tell the compiler up front the sizes are the same with an assert.

https://github.com/insanitybit/sqs-service-helper/blob/master/src/autoscaling.rs#L401

In my case it's a bit more complex - binary search always returns a value within the bounds of the array, and my indexes are mostly based on constant values. But the speed up moving to unchecked indexing was significant. I don't know if other compilers could really understand that this code can have its bounds checks optimized out, but I can understand it... so yay for unsafe.

For your request of indicating to the compiler "hey, i promise these bounds are legit" you have two options. I've found that an assert statement early on will eliminate bounds checks later. Or, as I did in my code, just use unsafe.

9
nerpderp83•

Other posts on Rust and performance

Sounds like we need a HowTo on writing numerical/codec code in Rust. Maybe u/veedrac can chime in on the subject.

7
leonardo_m•

Instead of using pointers with ptr.offset, try to use get_unchecked(_mut).

Arithmetic is checked in debug builds only (but in some cases you have to use the wrapping helpers to have the correct semantics in debug builds too).

#[inline(always)]

is sometimes better replaced by just:

#[inline].

The Rust compiler should not rely totally on the magic of LLVM optimizations when slice/array access is involved, and add optimizations, language features, and type system improvements to improve this important use case. Some budget of language features, language complexity, implementation and documentation effort should be spent on this. This is going to both improve the static safety of code (allowing a more intelligent compile-time knowledge of slice lengths and index intervals) and its run-time performance. The point is not to totally remove the need of unsafe slice access, but to reduce its need, and also allow the Rust programmer to be more aware of the tradeoffs (currently a Rust programmer can't even know where the compiler was unable to remove a bound test unless she takes a look at the assembly, this is quite silly).

6
fullouterjoin•

It would be really cool if there was an annotated output of the input source along with decisions the compiler made and why. Something like the nice error text but for optimizations that did or did not fire.

8
oln•

LLVM does have various debug output that can be helpful, though not quite as friendly as that. On nightly rust you can do rustc -Z debug-llvm (or alternatively RUSTFLAGS="-Z debug-llvm" cargo build) to get a ton of information about what llvm does. You might be able to narrow things down a bit using -C llvm-args=some-llvm-arg (which should work even on stable). I've used this to look into what prevents vectorization, I'm less familiar with other optimization passes.

3
newpavlovrustcrypto•

maybe there is/there should be a way to tell compiler “hey, this slice is guaranteed to be this size, drop the unneeded checks”;

You can pass reference to an array which can be created using arrayref crate. It's a bit inconvenient to use and I hope it will get better in future.

non-checking arithmetic is a bit too inconvenient to write (by design, I suppose) but it may help to squeeze some performance;

I think you can define wrapper types around numeric types which will define arithmetic traits in terms of wrapping_* methods, but I am not sure if it will be convenient to use. Idea for crate maybe?

Overall I agree with the point that Rust compiler is not smart enough yet and certainly can get better. For example in cases like foo[a..][..b] vs foo[a..a+b] or with loops (e.g. xoring &mut [u8; 16] and &[u8; 16] results in 16 xor instructions, instead of several movups and one pxor) and many other cases.

3
oln•

I think you can define wrapper types around numeric types which will define arithmetic traits in terms of wrapping_* methods,

The standard library actually has that already, the Wrapping<T> type.

2
newpavlovrustcrypto•

Well, today I've learned something new too. :)

1