LLVM sometimes does this, but when it doesn't, you may insert asserts to guide the optimizer, as explained here https://news.ycombinator.com/item?id=33808853
I think this technique works in C and C++ too (if you use clang or gcc)