Disabling optimizations when using llvm::createPrintModulePass

Hello,

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,
nullptr));
    llvmFunction->setCallingConv(llvm::CallingConv::C);
    llvm::BasicBlock * body = llvm::BasicBlock::Create(c, "__entry__",
llvmFunction);
    llvm::IRBuilder <> builder(body);
    llvm::Value * result =
builder.CreateBinOp(llvm::Instruction::BinaryOps::Add,
llvm::ConstantInt::getSigned(functionType, 40),
llvm::ConstantInt::getSigned(functionType, 2));
    builder.CreateRet(result);

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

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

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

And here is the result:

    ; ModuleID = 'test'

    define i16 @foo() {
    __entry__:
      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.)

Greetings,

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() {
__entry__:
  %0 = add i16 40, 2
  ret i16 %0
}

Thanks, Richard.