[llvm-dev] Fwd: I cannot change value of global variable in LLVM IR using IRBuilder

Emma Luciano via llvm-dev llvm-dev at lists.llvm.org
Wed Jun 3 01:34:59 PDT 2020


Hi Everyone,

I'm quite new to LLVM and I want to update value of global variable in LLVM
IR. I created new global variable in ModulePass:

bool runOnModule(llvm::Module &M) {
    IRBuilder<> Builder(M.getContext());
    Instruction *I = &*inst_begin(M.getFunction("main"));
    Builder.SetInsertPoint(I);
    M.getOrInsertGlobal("globalKey", Builder.getInt64Ty());
    GlobalVariable* gVar = M.getNamedGlobal("globalKey");
    gVar->setLinkage(GlobalValue::InternalLinkage);
    gVar->setAlignment(Align(8));
    gVar->setInitializer(Builder.getInt64(0));
    gVar->setConstant(false);

    for (Function &F : M.functions()) {
        InstructionVisitor visitor(DL,
getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F));
        for (Instruction &I : instructions(F)) {
            visitor.visit(I);
        }
    }
    return true;}

Later in InstructionVisitor I try to update it like that:

IRBuilder<> Builder(I->getContext());Builder.SetInsertPoint(I->getNextNode());
GlobalVariable* key = I->getModule()->getNamedGlobal("globalKey");
if (key) {
    LoadInst* load = Builder.CreateLoad(key);
    Value* inc = Builder.CreateAdd(load, Builder.getInt64(1));
    StoreInst* store = Builder.CreateStore(inc, key);}

I print that global variable during execution of instrumented code. I
access it's value by key->getOperand(0), but it's unchanged. I'm using ORC
JIT based on this tutorial:
https://llvm.org/docs/tutorial/BuildingAJIT2.html and I run ModulePass from
optimizeModule function from this tutorial.

In IR it looks like that:

  %2 = load i64, i64* @globalKey
  %3 = add i64 %2, 1
  store i64 %3, i64* @globalKey

I tried updating value of global variable, which was present in source code
that I'm instrumenting. It didn't work either.

I created corresponding stackoverflow topic:
https://stackoverflow.com/questions/62142574/how-can-i-update-global-variable-value-in-llvm-ir-using-irbuilder?fbclid=IwAR2X7uGhUjm_SN2UcxWYqaRQW2-cs6iPbMx2_tbKubeyYUkZ_pS6rkFfY9I

I will be really grateful for help.

Regards,

Emma Luciano
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/llvm-dev/attachments/20200603/0a77406a/attachment-0001.html>


More information about the llvm-dev mailing list