[LLVMdev] Get the value of a GlobalVariable

Óscar Fuentes
Sun, 20 Jan 2013 21:25:43 -0000

Varun Agrawal <varun729 at gmail.com> writes:

> GlobalVariable *my_global = Mod->getNamedGlobal("MY_GLOBAL");
>
> I want to know the value which was stored in this variable, I use the
> following command, but it gives error:
> APInt value = my_global->getValue();
>
> Error is:
> llvm/lib/IR/Constants.cpp:1257: llvm::Constant
> *llvm::Constant::getSplatValue() const: Assertion
> `this->getType()->isVectorTy() && "Only valid for
vectors!"' failed.

ExecutionEngine::getPointerToGlobal returns a void* to the memory
address used by the GlobalValue (a GlobalVariable in your case.) Then
you only need to cast the void* to the correct pointer type (int* in
your case) and read it:

int value =
*static_cast<int*>(MyExecutionEngine->getPointerToGlobal(my_global));