1

I am building a lifter that lifts from armv7m instructions to llvm IR. so I am trying to translate all armv7m instructions to their equivalent llvm instructions. I am new to llvm and I wanted to create and print an llvm instruction. So just starting with a simple add instruction my code is:

            llvm::LLVMContext TheContext;

            llvm::IRBuilder<> Builder(TheContext);  

            auto* L = ConstantInt::get(Type::getInt32Ty(TheContext), 41);

            auto* R = ConstantInt::get(Type::getInt32Ty(TheContext), 42);       

            llvm::Value* Add=Builder.CreateAdd(L, R, "addtmp");             

            Add->print(llvm::errs());

The output I want is

%addtmp = add i32 41, i32 42;

The output I get is

i32 83

First point, How can I display the instruction without being evaluated, please?.

Second point. As you can see in the above code

auto* L = ConstantInt::get(Type::getInt32Ty(TheContext), 41);

auto* R = ConstantInt::get(Type::getInt32Ty(TheContext), 42);

I am creating two constant ints as operands for my add instruction, now how can I create an operand to the add instruction that isn't an int ..just a variable. A place holder you might say. For example the x and the y variables here.

 %tmp = add i32 %x, %y
hany erfan
  • 95
  • 7
  • The evaluation you mention is called constant folding, and it's done by the builder. You can just create the instruction yourself instead using [BinaryOperator::Create()](https://llvm.org/doxygen/classllvm_1_1BinaryOperator.html#aa6655ccc115ddade69c02b6dcc30c5fe), IMO it's as easy to use the *::Create() functions as the builder. As for the placeholders... I think the general answer is that compilers tend to generate IR only when they hav the operands. For various reasons. – arnt May 08 '21 at 19:28

1 Answers1

1

The reason you received an i32 83 instead of an add instruction is that the default FolderTy template argument for the llvm::IRBuilder is llvm::ConstantFolder.

https://llvm.org/doxygen/classllvm_1_1IRBuilder.html

template <typename FolderTy = ConstantFolder,
          typename InserterTy = IRBuilderDefaultInserter>
class IRBuilder : public IRBuilderBase {

To combat this issue you can use llvm::NoFolder which does not perform constant folding. https://llvm.org/doxygen/classllvm_1_1NoFolder.html#details

Mats Jun
  • 351
  • 2
  • 8