Here we look at global variables. We will create a global variable in a module and a routine that increments it. Then we will retrieve the value.
We start with the usual initialization steps and create our module.
library(Rllvm) InitializeNativeTarget() mod = Module("global")
Next we create the global variable. We define a a constant to use as the initial value.
one = createIntegerConstant(-101L) gvar = createGlobalVariable("gv", one, mod, Int32Type)
So now we define the function that increments the global variable.
fun = Function("inc", Int32Type, module = mod) e = Block(fun, "entry") ir = IRBuilder(e)
tmp = ir$createLocalVariable(Int32Type, "tmp") zero = createIntegerConstant(0L) createBitCast(ir, zero, Int32Type, "cast") v = ir$createLoad(gvar) ans = ir$binOp(Add, v, 1L) #tmp = ir$createLoad(gvar) ir$createStore(ans, gvar) g = ir$createLoad(gvar) ir$createStore(g, tmp)
ret = Block(fun) ir$createBr(ret)
ir$setInsertPoint(ret) v = ir$createLoad(tmp) #ir$createRetVoid() ir$createRet(v)
Let's add another function to get the current value.
getGV = Function("getGV", Int32Type, module = mod) b = Block(getGV) ir = IRBuilder(b) #tmp = ir$createLocalVariable(Int32Type, "tmp") #zero = createIntegerConstant(0L) #ir$createBitCast(zero, Int32Type) ans = ir$createLoad(gvar) #val = ir$createStore(ans, tmp) #ans = ir$createLoad(tmp) ir$createReturn(ans)
ee = ExecutionEngine(mod) run(getGV, .ee = ee) run(fun, .ee = ee) run(fun, .ee = ee) run(fun, .ee = ee) run(getGV, .ee = ee) replicate(10, run(fun, .ee = ee)) run(getGV, .ee = ee)