6

For example:

int x=0;
int y=0;

where x and y are global variables, and in main() function we do the following:

x++;
y++;

How to get the newest value of global variables x and y in llvm.

when I try to do errs()<<g; they give the initial value as @BB0 = global i32 but I need to get the actual value like x=1, by using llvm.

R.Omar
  • 645
  • 1
  • 6
  • 18
  • When, exactly, are you running LLVM? Why do you expect it to know about run-time values? – Oak Jun 13 '17 at 21:00
  • I implement code in MCJIT to get all instructions. I want to get the value of global variable by its name after running lli file.ll – R.Omar Jun 13 '17 at 21:05
  • Is this possible, to get back the value of each global variable? – R.Omar Jun 13 '17 at 21:31

2 Answers2

3

Assuming you're using LLVM's API:

If the global is constant you can access its initialization value directly, for example:

Constant* myGlobal = new GlobalVariable( myLlvmModule, myLlvmType, true, GlobalValue::InternalLinkage, initializationValue );
...
Constant* constValue = myGlobal->getInitializer();

And if that value is of e.g. integer type, you can retrieve it like so:

ConstantInt* constInt = cast<ConstantInt>( constValue );
int64_t constIntValue = constInt->getSExtValue();

If the global isn't constant, you must load the data it points to (all globals are actually pointers):

Value* loadedValue = new LoadInst( myGlobal );
2

A global is basically a pointer. You can get the address in the host program via ExecutionEngine::getGlobalValueAddress and then you can dereference that address in order to get the stored value.

Oak
  • 26,231
  • 8
  • 93
  • 152