A compiler translates a certain language to machine code. If it is optimizing it will use that language's semantics for optimization. That is necessary, otherwise we would be writing almost everything in assembly.
> Know what optimizations your compiler can do, and carefully consider the effect of each one on security programming patterns. In particular, be careful of optimizations that can remove code or branches, and code that prevents errors which "should be impossible" if the rest of the program is correct.
A priority is to understand the language one is writing in.
> When possible, consider disabling compiler optimizations that can eliminate or weaken security checks.
A better solution is to use assembly language and thus exactly specify your program's semantics within the program; that compiler flag could be removed by whoever builds the program, or something like link-time optimization.