-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcallRFunction.R
299 lines (240 loc) · 10.6 KB
/
callRFunction.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
callRFunction =
function(call, env, ir, ...)
{
funName = as.character(call[[1]])
funTypes = env$.CallableRFunctions[[funName]]
if(funName == ".R") {
if(length(call) > 1)
funTypes = eval(call[[3]])
call = call[[2]]
}
# We have the call to the R function. But we need to match the arguments.
# We have to convert regular objects to R objects. However, when we have a SEXPType
# that hasn't been updated within the routine, we can pass this directly.
# We can generate code to create the call. Alternatively, within the same R session
# we can R_PreserveObject the call and then reuse it at call-time in the compiled code.
# We have to fill in the arguments for each call.
# We want to create the call expression just once, regardless if we pass it from the compiler
# or create it ourselves.
# How do we assign an R object to a global variable in a module.
# We could serialize the call to a byte stream and restore it in the module.
# Use getVariable.
# Need to compile any arguments that are expressions.
# compile(e, env, ir, ...)
# put the current call into the module with name <funName>.call
#
# Potentially, preserve the call by putting it in the environment of the R function that is a proxy for the
# the LLVM routine.
id = sprintf("%s_expression", funName)
llvmAddSymbol(R_GlobalEnv = getNativeSymbolInfo("R_GlobalEnv"))
createGlobalVariable("R_GlobalEnv", env$.module, SEXPType)
#XXX We need to specify the caller. If the caller has given us the ExecutionEngine
# we could set this. Check !is.null(env$.ExecEngine).
callVar = createGlobalVariable(id, env$.module, SEXPType, getNULLPointer(SEXPType))
# compileSetCall(id, sprintf("setCall_%s", id), env$.module)
# Add info to .SetCallFuns to have the top-level compiler generate these routines when it is finished.
env$.SetCallFuns[[ length(env$.SetCallFuns) + 1L]] = createCall = list(var = id,
name = sprintf("setCall_%s", id),
createCallFun = sprintf("create_%s", id),
deserializeCallFun = sprintf("deserialize_%s", id),
call = call)
cc = Function(createCall$createCallFun, SEXPType, list(), module = env$.module)
cc = Function(createCall$deserializeCallFun, SEXPType, list(), module = env$.module)
e = substitute( if( var == NULL ) var <- mk(),
list(var = as.name(createCall$var), mk = as.name(createCall$deserializeCallFun),
msg = sprintf("calling %s\n", createCall$createCallFun)))
env$.remainingExpressions = list(NULL) #XXXX
compile(e, env, ir, ...)
# if(!is.null(env$.ExecEngine) ) {
# env$.module[[id, .ee = env$.ExecEngine]] = call
# }
# Now, generate the code that puts the local variables into the call.
insertLocalValues(call, id, env, ir, ...)
#!!! debug: show the updated expressions.
#compile(substitute(Rf_PrintValue(var), list(var = as.name(id))) , env, ir, ...)
# Then evaluate the call
e = substitute(r_ans <- Rf_eval(callVar, R_GlobalEnv), list(callVar = as.name(id)))
val = compile(e, env, ir, ...)
compile(quote(Rf_protect(r_ans)), env, ir, ...)
# Do we need to protect this return value?
# compile(quote(Rf_protect(r_ans)), env, ir, ...)
# compile(quote(Rf_unprotect_ptr(rans)), env, ir, ...)
# Now get the result and marshall it back
if(sameType(funTypes[[1]], StringType)) {
# memory management.
marshallAns = quote(ans <- strdup(R_CHAR(STRING_ELT(r_ans, 0)))) # XXXX Somebody needs to free this.
} else if(sameType(funTypes[[1]], Int32Type)) {
marshallAns = quote(ans <- Rf_asInteger(r_ans))
} else if(sameType(funTypes[[1]], DoubleType)) {
marshallAns = quote(ans <- Rf_asReal(r_ans))
} else if(sameType(funTypes[[1]], SEXPType)) {
return(val)
} else {
stop("don't know how to handle this type")
}
e = compile(marshallAns, env, ir)
# compile(quote(Rf_PrintValue(r_ans)), env, ir, ...)
compile(quote(Rf_unprotect(1L)), env, ir, ...)
e
}
# Also in createLoop.R. So put into a function.
# But we don't need them and actually introduced a bug since we spelled r_ans as rans in the Rf_eval() later on
# So better to let the type specification work for us.
createCompilerLocalVariable =
function(name, type, env, ir)
{
tmp = createFunctionVariable(type, name, env, ir)
assign(name, tmp, env)
env$.types[[name]] = type
tmp
}
compileSetCall =
#
# This creates a new function/routine in the module
# that allows us to call it from R to set a SEXP type
# that is a call to a global variable that will then be used
# to callback to R from an LLVM-generated routine.
function(varName, funName, module)
{
f = function(tmp) {
R_PreserveObject(tmp)
var = tmp
}
body(f)[[3]][[2]] = as.name(varName)
# Can we compile a new function while currently in the middle of compiling another with a different IRBuilder.
compileFunction(f, VoidType, list(SEXPType), module, name = funName)
}
compileCreateCall =
#
# Do we want to make this a separate routine
#
function(env, ir, call, globalVarName = NA, ...)
{
funName = as.character(call[[1]])
# Rf_protect( ) around the entire thing ?
e = substitute( zz <- Rf_allocVector(LANGSXP, nels) , # LANGSXP
list(nels = length(call)))
compile(e, env, ir, ...)
tmp = substitute(SETCAR(zz, Rf_install(id)), list(id = funName))
compile(tmp, env, ir, ...)
compile(quote(cur <- CDR(zz)), env, ir, ...)
argNames = names(call)
for(i in seq(along = call)[-1]) {
val = if(is.name(call[[i]]))
substitute(Rf_install(x), list(x = as.character(call[[i]])))
else if(is.integer(call[[i]]))
substitute(Rf_ScalarInteger(x), list(x = call[[i]]))
else if(is.numeric(call[[i]]))
substitute(Rf_ScalarReal(x), list(x = call[[i]]))
else if(is.logical(call[[i]]))
substitute(Rf_ScalarLogical(x), list(x = call[[i]]))
else if(is.character(call[[i]]))
substitute(Rf_mkString(x), list(x = call[[i]]))
else {
warning("cannot recreate non-local value in R expression")
quote(Rf_install("<expr>"))
}
tmp = substitute(SETCAR(cur, val), list(val = val))
compile(tmp, env, ir, ...)
if(length(argNames) && argNames[i] != "") {
compile(substitute(SET_TAG(cur, Rf_install(id)), list(id = argNames[i])), env, ir, ...)
}
if(i < length(call))
compile(quote(cur <- CDR(cur)), env, ir, ...)
}
if(!is.na(globalVarName) && globalVarName != "") {
e = substitute( if( var != NULL ) R_ReleaseObject(var), list(var = as.name(globalVarName)))
set = substitute( v <- zz, list(v = as.name(globalVarName)))
env$.remainingExpressions = list(set) #XXX horrible. Needed to get the NextBlock
compile(e, env, ir, ...)
compile(set, env, ir, ...)
}
compile(quote(return(zz)), env, ir, ...) # ir$createRet(ir$createLoad(getVariable()))
# compile(quote({printf("expression: "); Rf_PrintValue(zz)}), env, ir, ...)
}
compileCreateCallRoutine =
#
# Do we need a new compiler?
# Do we want to make this a separate routine
#
function(env, ir, call, name, globalVarName = NA)
{
# The function should have already been declared in callRFunction.
# But here it is as it used to be:
# f = Function(name, VoidType, list(), module = env$.module)
compilerStartFunction(env, ir, name, SEXPType)
compileCreateCall(env, ir, call, globalVarName)
}
createDeserializeCall =
function(env, ir, call, name, globalVarName = NA, ...)
{
compilerStartFunction(env, ir, name, SEXPType)
llvmAddSymbol(getNativeSymbolInfo("R_loadRObjectFromString", "RLLVMCompile"))
# serialize the call to a string
txt = saveRObjectAsString(call)
# create call to the C routine to deserialize this and compile this expression
e = substitute(R_loadRObjectFromString(x), list(x = txt))
v = compile(e, env, ir, ...)
ir$createRet(v)
}
insertLocalValues =
#
# Given the call template, generate the code to insert local variables into
# the
function(call, callVar, env, ir, ...)
{
# For now, only deal with literals, symbols and calls!
# Probably just loop over all of them and determine if they involve local variables.
call = call[-1]
w = sapply(call, function(x) is.name(x) || is.call(x))
if(any(w)) {
# need to CDR() up to the first element. Then insert the value and go to the next one.
# Get the first argument, i.e. skip over the function name/obj.
compile(substitute(el <- CDR(v), list(v = as.name(callVar))), env, ir, ...)
jmp = substitute(el <- CDR(el), list(call = as.name(callVar)))
e = quote(SETCAR(el, val))
for(i in seq(along = w)) {
if(w[i]) {
varName = call[[i]]
usesLocal = usesLocalVariables(call[[i]], env)
if(usesLocal) {
if(is.call(varName)) {
var = compile(substitute(.tmp <- e, list(e = call[[i]])), env, ir, ...)
varName = as.name(".tmp")
} else {
var = getVariable(as.character(varName), env, load = FALSE, searchR = FALSE)
if(!is(var, "Argument"))
var = ir$createLoad(var)
}
ty = Rllvm::getType(var)
v = if(sameType(ty, Int32Type))
substitute(Rf_ScalarInteger(x), list(x = varName))
else if(sameType(ty, DoubleType))
substitute(Rf_ScalarReal(x), list(x = varName))
else if(sameType(ty, StringType))
substitute(Rf_mkString(x), list(x = varName))
else if(sameType(ty, SEXPType))
as.name(varName)
else
stop("don't know how to handle this type yet")
e[[3]] = v
compile(e, env, ir, ...)
} # end of usesLocal
compile(jmp, env, ir, ...)
}
}
}
}
usesLocalVariables =
function(expr, env)
{
f = function() "will be replaced by expr"
body(f) = expr
info = findGlobals(f, FALSE)
localVarNames = c(names(env$.localVarTypes), env$.params@names, names(env$.types))
any(info$variables %in% localVarNames)
}
# NOT USED
isRAtomic =
function(x)
is.logical(x) || is.integer(x) || is.numeric(x) || is.character(x)