# An example of being able to compile both of these in the
# same module and calling foo from bar.
foo =
function(x, y)
{
return( x + y )
}
bar =
function(x, y)
{
return ( foo(x, y) + 10 )
}
foobar =
function(x, y)
{
return ( sqrt(foo(x, y)) )
}
foo.c = compileFunction(foo, DoubleType, list(DoubleType, DoubleType),
.routineInfo = list( sqrt = list(DoubleType, DoubleType) ))
fb = compileFunction(foobar, DoubleType, list(DoubleType, DoubleType),
module = as(foo.c, "Module"),
.routineInfo = list( sqrt = list(DoubleType, DoubleType) ),
foo = list(returnType = DoubleType,
params = c(DoubleType, DoubleType)))
run(fb, 4, 5) # gives 3 = sqrt(4 + 5)
.llvm(fb, 4, 5)
# Here we return an R function that is directly callable.
# Create a new module and we will need foo in that. So recreate.
foo.c = compileFunction(foo, DoubleType, list(DoubleType, DoubleType),
.routineInfo = list( sqrt = list(DoubleType, DoubleType) ))
fb = compileFunction(foobar, DoubleType, list(DoubleType, DoubleType),
module = as(foo.c, "Module"),
.routineInfo = list( sqrt = list(DoubleType, DoubleType) ),
foo = list(returnType = DoubleType,
params = c(DoubleType, DoubleType)),
asFunction = TRUE)
fb(4, 5)
# Here we show how to override how an expression is called
# by providing our own .compilerHandlers. Here we change
# any call to Sys.Date() to a constant.
myDate = function() {
return(Sys.Date())
}
myOPS = getCompilerHandlers()
myOPS[["Sys.Date"]] =
function(call, env, ir, ...) {
cat("In Sys.Date handler\n")
ir$createConstant(15015L)
}
# Note we specify .functionInfo so that we don't
# try to create a Function object in the module for Sys.Date which
# we won't end up calling.
f = compileFunction(myDate, Int32Type, optimize = FALSE,
.compilerHandlers = myOPS, .globals = NULL)
.llvm(f)
myPlus = function() {
return(1L + x)
}
Run the code above in your browser using DataLab