X-Git-Url: https://git.ralfj.de/web.git/blobdiff_plain/52855956cef4c1113f3a2e5d6ab00509b8c6aaef..f1ccb4ac540754eeb5f1e9df6f42c13bbb5096cd:/personal/_posts/2020-07-15-unused-data.md?ds=inline diff --git a/personal/_posts/2020-07-15-unused-data.md b/personal/_posts/2020-07-15-unused-data.md index 5f4a771..500ecef 100644 --- a/personal/_posts/2020-07-15-unused-data.md +++ b/personal/_posts/2020-07-15-unused-data.md @@ -55,7 +55,7 @@ That transformation can be used to turn our `example` function into the followin {% highlight rust %} fn example(b: bool, num: u32) -> i32 { let mut acc = 0; - let incr = if b { 42 } else { 23 } + let incr = if b { 42 } else { 23 }; for _i in 0..num { acc += incr; } @@ -74,7 +74,9 @@ Before the optimization, that call was fine. After the optimization, that call is UB because we are doing `if b` where `b` is `3`. This is because loop-invariant code motion makes dead code live when the loop is not actually executed. -To fix this, we could require the compiler to prove that the loop runs at least once, but in general that will be hard (and in `example` it is impossible, since `num` can indeed be `0`). +(We can think of this as a form of "speculative execution", though entirely unrelated to CPU-level speculative execution.) +To fix the optimization, we could require the compiler to prove that the loop runs at least once (i.e., we could avoid speculative execution), but in general that will be hard (and in `example` it is impossible, since `num` can indeed be `0`). +Another option is to restructure the code to only compute `incr` if `num > 0`, but again this can be hard to do in general. So the alternative that Rust uses is to require that even "unused" data satisfies some basic validity. That makes `example(transmute(3u8), 0)` UB in *both* versions of `example`, and as such the optimization is correct for this input (and indeed for all possible inputs).