getting Data stored in an LLVM variable

326 Views Asked by At

I am building a lifter that translates assembly code into LLVM IR. I was wondering if there is a possible way to check the data stored inside an LLVM variable. For example in my code below. I am creating a dummy LLVM function. Inside my function, I have just one basic block where I allocate memory for a single variable SRC and then I store an immediate value of 31 inside that allocated memory. The last step is I loaded from that memory into a variable called loaded. Is there a way to check that the value of the %loaded variable is in fact 31 ?.

int main()

{

llvm::LLVMContext context;

llvm::Type* type = llvm::Type::getVoidTy(context);

Module* modu = new Module("test", context);

modu->getOrInsertFunction("dummy",type);

Function* dummy = modu->getFunction("dummy");

BasicBlock* block = BasicBlock::Create(context, "entry", dummy);

IRBuilder<> builder(block);

llvm::Value* SRC = builder.CreateAlloca(Type::getInt32Ty(context), nullptr);

llvm::Value* s = builder.CreateStore(llvm::ConstantInt::get(context, llvm::APInt(/*nbits*/32, 31, true)), SRC,  /*isVolatile=*/false);

llvm::Value* loaded = builder.CreateLoad(SRC, "loaded");    

builder.CreateRetVoid();    

PassManager <llvm::Module>PM;

llvm::AnalysisManager  <llvm::Module>AM;

verifyFunction(*(modu->getFunction("dummy")), &llvm::errs());

verifyModule(*modu, &llvm::errs());

PassBuilder PB;

PB.registerModuleAnalyses(AM);    

PM.addPass(PrintModulePass());

PM.run(*modu, AM);

The output of my code looks like this:

; ModuleID = 'test'
source_filename = "test"

define void @dummy() {
entry:
%0 = alloca i32, align 4
store i32 31, i32* %0, align 4
%loaded = load i32, i32* %0, align 4
ret void
}
1

There are 1 best solutions below

2
On

You can insert a call to printf and compile this IR into a native executable. Running it will print out the variable value.

Alternatively, you can run lli on this IR under debugger and break on load handler.