3 ms·
the compiler will rely on undefined behaviour all the time for any given set of optimisations, a lot of them are harmless. the compiler can't know if a use of u
by foxhill 12y ago
the compiler will rely on undefined behaviour all the time for any given set of optimisations, a lot of them are harmless. the compiler can't know if a use of undefined behaviour is intentional and safe, or unintentional and dangerous.
you could then argue that there are some cases in which undefined behaviour is obviously a mistake. and this is what the static code analysis in clang does. it's just not on by default.
- Kliment 12y agoHarmless or not, I'd like to have a way to know when the compiler is relying on undefined behavior for optimization, and use that to make an informed decision. I'd argue a very large number of the cases where undefined behavior is used by the compiler are actual mistakes in the code, and having a way to get those marked by the compiler would be useful.
- mikeash 12y agoThere's actually a pretty simple way to determine whether the compiler is relying on undefined behavior for optimization. Simply evaluate the following two criteria: 1. Are you using a C compiler? 2. Are optimizations enabled? If the answer to both of these is "yes", then the compiler is almost certainly relying on undefined behavior for optimization.
- foxhill 12y agowell, this would mean you'd get feedback every time you declare a variable without giving it an initial value? (even if the value is never read from before being written to - i.e is entirely safe to do?) or how about when you write a for loop? for(int i=0; i<LIMIT; i++) .. the compiler assumes that i cannot overflow in this case, because that would be undefined behaviour. on the most obvious level, it doesn't need to do an overflow check on each loop iteration, if it exploits undefined behaviour. and no, it simply can't check the value of LIMIT before the loop, because i may be changed in the loop body, or LIMIT itself may change. this also allows a myriad of other loop optimisations. pipelining, vectorization, unrolling.. i don't think you realise just how often undefined behaviour is used in compiler optimisations.
- Kliment 12y agoYes, and having the compiler tell me these things would be welcome. I'm not saying I don't WANT those optimizations, I just want to be aware when they happen.
- foxhill 12y agofor even simple programs, this would produce a very large output. we've become accustomed to the idea that C is a low level language, but actually it's somewhat high level. optimisations are in your code everywhere, and if a C compiler were to list even only the ones that exploit undefined behaviour.. well, it would essentially be noise.