Example - Cumulative Sum of a Vector

This is an example of how we compile a simple implementation of a function to compute the cumulative sum of a vector via a loop in R.

library(Rllvm)

InitializeNativeTarget()
mod = Module("Cumsum")
ptrDouble = pointerType(DoubleType)
fun = Function("Cumsum", VoidType, c(x = ptrDouble, ans = ptrDouble, len = Int32Type), mod)
names(fun) = c("x", "ans", 'len')
params = getParameters(fun)
entry = Block(fun, "entry")
ir = IRBuilder(entry)
iv = ir$createLocalVariable(Int32Type, "i")
xref = ir$createLocalVariable(ptrDouble, "x_addr")
ans.ref = ir$createLocalVariable(ptrDouble, "ans_addr")
len.ref = ir$createLocalVariable(Int32Type, "len_addr")
ir$createStore(1L, iv)
ir$createStore(params$x, xref)
ir$createStore(params$ans, ans.ref)
ir$createStore(params$len, len.ref)

a = ir$createLoad(xref)
b = ir$createGEP(a, 0L)
x0 = ir$createLoad(b)
a = ir$createLoad(ans.ref)
b = ir$createGEP(a, 0L)
ir$createStore(x0, b)
cond = Block(fun, "loopCondition")
ret = Block(fun, "return")
body = Block(fun, "loopBody")
ir$createBr(cond)
ir$setInsertPoint(cond)
a = ir$createLoad(iv)
b = ir$createLoad(len.ref)
ok = ir$createICmp(ICMP_SLT, a, b)
ir$createCondBr(ok, body, ret)
ir$setInsertPoint(ret)
ir$createRetVoid()
ir$setInsertPoint(body)
a = ir$createLoad(iv)
b = ir$binOp(Sub, a, ir$createConstant(1L))
r = ir$createLoad(ans.ref)
idx = ir$createSExt(b, 64L)
ans.i1 = ir$createLoad(ir$createGEP(r, idx))
a = ir$createLoad(xref)
i = ir$createLoad(iv)
idx = ir$createSExt(i, 64L)
xi = ir$createLoad(ir$createGEP(a, idx))
tmp = ir$binOp(FAdd, ans.i1, xi)
x = ir$createLoad(ans.ref)
i = ir$createLoad(iv)
i = ir$createSExt(i, 64L)
ans.i = ir$createGEP(x, i)
ir$createStore(tmp, ans.i)
i = ir$createLoad(iv)
inc = ir$binOp(Add, i, 1L)
ir$createStore(inc, iv)
ir$createBr(cond)