dirkschumacher / armacmp

🚀 Automatically compile linear algebra R code to C++ with Armadillo

Home Page:https://dirkschumacher.github.io/armacmp/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Make input vars of main function values instead of const refs

dirkschumacher opened this issue · comments

I think this should be possible without an extra variable. It is also possible to detect that automatically and then make the input var not a reference.

function(X) {
  X <- X + 10
  return(X)
}

How about const arma::T& if and only if nothing is detected. Otherwise, copy the data arma::T. I think this would be the safest way forward.

Reusing memory via armadillo's advanced ctor would modify the R object and be undesirable cause of confusion.

That is:

#include<RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]

// [[Rcpp::export]]
void ref_update(arma::vec& x) {
    x += 10;
}
(x = 1.1:5.1)
# [1] 1.1 2.1 3.1 4.1 5.1

ref_update(x)

x
# [1] 11.1 12.1 13.1 14.1 15.1

Thanks. I think this is the way to go

Note to self: currently I only know during the compile step if a variable is reassigned. But then the code has already emitted for the initial assignment. So there needs to be another mechanism that works on the AST before the compilation step (which is good).

Once this is implemented, I could add constexpr to scalar assignments that are not reassigned.

Checked the assembly code of some simple examples: I think it does not matter to add constexpr to any simple scalar assignment.

fun <- armacmp::armacmp(function(X) {
  X <- X + 10
  return(X)
}, verbose = TRUE)
#> R function
#> 
#> function (X) 
#> {
#>     X <- X + 10
#>     return(X)
#> }
#> 
#> C++ function translation
#> 
#> arma::mat armacmp_fun(arma::mat X)
#> {
#> X = X + 10.0;
#> return X;
#> }

Created on 2019-08-12 by the reprex package (v0.3.0)