3 ms·
Presumably you meant to do something with arr[i] or the whole loop could be elided. I'm not sure I understand your point, what is the type of n? If it's somethi
by dooglius 6y ago
Presumably you meant to do something with arr[i] or the whole loop could be elided. I'm not sure I understand your point, what is the type of n? If it's something bigger than int that's a bug and should result in a warning.
- aw1621107 6y agoFrom what I understand, the type of n isn't really the important part here; it's the type of the indexing variable (i) that makes a difference. On platforms where sizeof(int) is not the size of a register (e.g., x86_64 with 32-bit ints), UB signed overflow allows the compiler to not have to emit code to deal with the possibility of 32-bit overflow, which probably results in "sensible" assembly. This article [0] goes into a bit more detail. [0]: https://gist.github.com/rygorous/e0f055bfb74e3d5f0af20690759de5a7 https://gist.github.com/rygorous/e0f055bfb74e3d5f0af20690759...
- dooglius 6y agoThe article you linked says that compilers can prove a lack of overflow in this example, so UB is not necessary to assume here. It also claims that the compiler cannot prove this in more complex examples (but gives no explicit examples). What I'm saying is if the compiler cannot prove a lack of overflow in this way, that should be a warning.
- aw1621107 6y ago> The article you linked says that compilers can prove a lack of overflow in this example, so UB is not necessary to assume here. It's trivial to prove in that particular example because it's assumed that count is also an int (both i and count are in 32-bit registers). > It also claims that the compiler cannot prove this in more complex examples (but gives no explicit examples). The example doesn't even have to be that complex; you just need sizeof(n) > sizeof(i) and i to be signed (godbolt example at [0]). In that example, if the compiler can assume signed overflow is UB, then you get fairly sensible code generation. If the compiler cannot make that assumption (add the -fwrapv flag), then you get that movsxd instruction in the middle of the loop body. If you use -O2 instead of -O1, then -fwrapv prevents loop unrolling. > What I'm saying is if the compiler cannot prove a lack of overflow in this way, that should be a warning. I'm curious how frequently this warning might fire in real-life codebases, or when it does fire how frequently it's something the programmer can actually fix. Clang does have -Rpass-missed to emit some diagnostics when an optimization cannot be performed, but it doesn't emit anything in this particular case (though I'm not sure whether it's supposed to). [0]: https://godbolt.org/z/abq3n9 https://godbolt.org/z/abq3n9