Disabling optimizations when using llvm::createPrintModulePass


using the LLVM API, I've build one very simple function that adds two
ConstantInts and returns the result.

I noticed that, when I emit IR code, it is optimized to a simple "ret
i16 42" when I add 40 and 2. I'd like to see the operations that are
necessary to compute the result, though.
Can I somehow disable this optimization in the pass, leading to more
verbose IR code?

Here is the code I use to create the IR:

    llvm::LLVMContext c;
    llvm::Module module("test", c);
    llvm::Type * functionType = llvm::IntegerType::get(c, 16);
    llvm::Function * llvmFunction = llvm::cast
<llvm::Function>(module.getOrInsertFunction("foo", functionType,
    llvm::BasicBlock * body = llvm::BasicBlock::Create(c, "__entry__",
    llvm::IRBuilder <> builder(body);
    llvm::Value * result =
llvm::ConstantInt::getSigned(functionType, 40),
llvm::ConstantInt::getSigned(functionType, 2));

    llvm::verifyModule(module, llvm::PrintMessageAction);

    std::string errorInfo;
    llvm::raw_fd_ostream fileStream("test.ll", errorInfo);

    llvm::PassManager pm;
    pm.add(llvm::createPrintModulePass(& fileStream));

And here is the result:

    ; ModuleID = 'test'

    define i16 @foo() {
      ret i16 42

(Somehow I am beginning to get the feeling that operations on literals
are always evaluated at compile-time and that this can not be
prevented, except for first storing the values in memory.)


Daniel Albuschat

IRBuilder is a templated class, and one of the template arguments is the constant folder to use. By default it uses the ConstantFolder class which does target-independant constant folding. If you want to disable constant folding you can specify the NoFolder class instead, i.e. declare the builder as follows:

IRBuilder<true, llvm::NoFolder> builder(body)

Nice, the output is now:

; ModuleID = 'test'

define i16 @foo() {
  %0 = add i16 40, 2
  ret i16 %0

Thanks, Richard.