LLVM opt mem2reg has no effect

Recently, when compiled with -O0, clang started to add optnone attribute to each function, which prevents further optimizations afterwards including mem2reg pass. To prevent that, add -Xclang -disable-O0-optnone to clang.


Another answer already points out that with -O0 (or without -O option), your functions are annotated with the optnone attribute. Another effect of lowering the optimization level is that no TBAA metadata seems to be generated, which also affects later optimizations.

So to prepare a file for opt, I found that it is better to keep your optimization level, and pass the option -Xclang -disable-llvm-passes (the help text for this option reads "Use together with -emit-llvm to get pristine LLVM IR from the frontend by not running any LLVM passes at all").

The complete invocation becomes:

clang -S -emit-llvm -O -Xclang -disable-llvm-passes source.c