5 ms·
> If UB was instead defined to trap, most optimizations that are made possible by UB would still be possible, but without the footgun part. ... on hardware whe
by mike_hock 5y ago
> If UB was instead defined to trap, most optimizations that are made possible by UB would still be possible, but without the footgun part.
... on hardware where the native instruction happens to trap.
Otherwise it needs to generate a conditional branch and explicit trap instruction, which is as unoptimal as any other imposed behavior.
- fay59 5y agoNo, you’ve missed the point. It’s still much better to have a trap than “any other imposed behaviour” because the compiler can reason that this condition is impossible on the happy path and remove code accordingly. Removing code is both among the most sensitive and the most effective optimizations that compilers do, and they use UB as another signal for “unreachable”. The current model of “assume things never happen and don’t plan anything in particular if it does happen” does no one a service.
- mike_hock 5y agoIf you impose that the unhappy path must trap, the compiler has to guarantee that. Conversely, if the compiler can reason that the condition is impossible, it can remove code regardless of what behavior is imposed for the condition that it knows can't happen.