function.rs 13.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
//! This module provides an idiomatic Rust API for creating and working with TVM functions.
//!
//! For calling an already registered TVM function use [`function::Builder`]
//! To register a TVM packed function from Rust side either
//! use [`function::register`] or the macro [`register_global_func`].
//!
//! See the tests and examples repository for more examples.

use std::{
    collections::BTreeMap,
    ffi::{CStr, CString},
    mem,
    os::raw::{c_char, c_int, c_void},
    ptr, slice, str,
    sync::Mutex,
};

18 19 20 21 22 23 24
use failure::Error;

use crate::{
    errors,
    ffi::{self, TVMValue},
    Module, TVMArgValue, TVMRetValue,
};
25 26 27 28 29 30

lazy_static! {
    static ref GLOBAL_FUNCTIONS: Mutex<BTreeMap<&'static str, Option<Function>>> = {
        let mut out_size = 0 as c_int;
        let name = ptr::null_mut() as *mut c_char;
        let mut out_array = name as *mut _;
31
        check_call!(ffi::TVMFuncListGlobalNames(
32 33 34 35 36 37 38 39 40 41 42 43 44 45
            &mut out_size as *mut _,
            &mut out_array
        ));
        let names_list = unsafe { slice::from_raw_parts(out_array, out_size as usize) };
        Mutex::new(
            names_list
                .into_iter()
                .map(|&p| (unsafe { CStr::from_ptr(p).to_str().unwrap() }, None))
                .collect(),
        )
    };
}

/// Wrapper around TVM function handle which includes `is_global`
46
/// indicating whether the function is global or not, and `is_cloned` showing
47 48 49 50
/// not to drop a cloned function from Rust side.
/// The value of these fields can be accessed through their respective methods.
#[derive(Debug, Hash)]
pub struct Function {
51
    pub(crate) handle: ffi::TVMFunctionHandle,
52 53 54 55 56 57 58 59 60 61
    // whether the registered function is global or not.
    is_global: bool,
    // whether the function has been cloned from frontend or not.
    is_cloned: bool,
}

unsafe impl Send for Function {}
unsafe impl Sync for Function {}

impl Function {
62
    pub(crate) fn new(handle: ffi::TVMFunctionHandle) -> Self {
63 64
        Function {
            handle: handle,
65
            is_global: false,
66 67 68 69 70
            is_cloned: false,
        }
    }

    /// For a given function, it returns a function by name.
71
    pub fn get<S: AsRef<str>>(name: S) -> Option<&'static Function> {
72 73 74 75
        let mut globals = GLOBAL_FUNCTIONS.lock().unwrap();
        globals.get_mut(name.as_ref()).and_then(|maybe_func| {
            if maybe_func.is_none() {
                let name = CString::new(name.as_ref()).unwrap();
76 77
                let mut handle = ptr::null_mut() as ffi::TVMFunctionHandle;
                check_call!(ffi::TVMFuncGetGlobal(
78 79 80
                    name.as_ptr() as *const c_char,
                    &mut handle as *mut _
                ));
81 82 83 84 85
                maybe_func.replace(Function {
                    handle: handle,
                    is_global: true,
                    is_cloned: false,
                });
86 87 88 89 90 91 92 93 94 95
            }
            unsafe {
                std::mem::transmute::<Option<&Function>, Option<&'static Function>>(
                    maybe_func.as_ref(),
                )
            }
        })
    }

    /// Returns the underlying TVM function handle.
96
    pub fn handle(&self) -> ffi::TVMFunctionHandle {
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
        self.handle
    }

    /// Returns `true` if the underlying TVM function is global and `false` otherwise.
    pub fn is_global(&self) -> bool {
        self.is_global
    }

    /// Returns `true` if the underlying TVM function has been cloned
    /// from the frontend and `false` otherwise.
    pub fn is_cloned(&self) -> bool {
        self.is_cloned
    }
}

impl Clone for Function {
    fn clone(&self) -> Function {
114 115 116 117
        Self {
            handle: self.handle,
            is_global: self.is_global,
            is_cloned: true,
118 119 120 121 122 123
        }
    }
}

impl Drop for Function {
    fn drop(&mut self) {
124 125
        if !self.is_global && !self.is_cloned {
            check_call!(ffi::TVMFuncFree(self.handle));
126 127 128 129 130 131 132
        }
    }
}

/// Function builder in order to create and call functions.
///
/// *Note:* Currently TVM functions accept *at most* one return value.
133
#[derive(Default)]
134 135
pub struct Builder<'a, 'm> {
    pub func: Option<&'m Function>,
136
    pub arg_buf: Vec<TVMArgValue<'a>>,
137 138 139 140 141 142
    pub ret_buf: Option<TVMRetValue>,
}

impl<'a, 'm> Builder<'a, 'm> {
    pub fn new(
        func: Option<&'m Function>,
143
        arg_buf: Vec<TVMArgValue<'a>>,
144 145 146 147 148 149 150 151 152
        ret_buf: Option<TVMRetValue>,
    ) -> Self {
        Self {
            func,
            arg_buf,
            ret_buf,
        }
    }

153 154
    pub fn get_function(&mut self, name: &'m str) -> &mut Self {
        self.func = Function::get(name);
155 156 157 158
        self
    }

    /// Pushes a [`TVMArgValue`] into the function argument buffer.
159
    pub fn arg<T: 'a>(&mut self, arg: &'a T) -> &mut Self
160
    where
161
        TVMArgValue<'a>: From<&'a T>,
162
    {
163
        self.arg_buf.push(arg.into());
164 165 166 167
        self
    }

    /// Pushes multiple [`TVMArgValue`]s into the function argument buffer.
168
    pub fn args<T: 'a, I>(&mut self, args: I) -> &mut Self
169
    where
170 171
        I: IntoIterator<Item = &'a T>,
        TVMArgValue<'a>: From<&'a T>,
172
    {
173
        args.into_iter().for_each(|arg| {
174
            self.arg(&arg);
175
        });
176 177 178 179 180
        self
    }

    /// Sets an output for a function that requirs a mutable output to be provided.
    /// See the `basics` in tests for an example.
181
    pub fn set_output<T>(&mut self, ret: T) -> &mut Self
182
    where
183
        TVMRetValue: From<T>,
184
    {
185 186
        self.ret_buf = Some(ret.into());
        self
187 188 189
    }

    /// Calls the function that created from `Builder`.
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
    pub fn invoke(&mut self) -> Result<TVMRetValue, Error> {
        #![allow(unused_unsafe)]
        ensure!(self.func.is_some(), errors::FunctionNotFoundError);

        let num_args = self.arg_buf.len();
        let (mut values, mut type_codes): (Vec<ffi::TVMValue>, Vec<ffi::TVMTypeCode>) = self
            .arg_buf
            .iter()
            .map(|tvm_arg| (tvm_arg.value, tvm_arg.type_code as ffi::TVMTypeCode))
            .unzip();

        let mut ret_val = unsafe { std::mem::uninitialized::<TVMValue>() };
        let mut ret_type_code = 0;
        check_call!(ffi::TVMFuncCall(
            self.func.ok_or(errors::FunctionNotFoundError)?.handle,
            values.as_mut_ptr(),
            type_codes.as_mut_ptr() as *mut i32,
            num_args as c_int,
            &mut ret_val as *mut _,
            &mut ret_type_code as *mut _
        ));
211

212
        Ok(unsafe { TVMRetValue::from_tvm_value(ret_val, ret_type_code as i64) })
213 214 215 216 217 218 219
    }
}

/// Converts a [`Function`] to builder. Currently, this is the best way to work with
/// TVM functions.
impl<'a, 'm> From<&'m Function> for Builder<'a, 'm> {
    fn from(func: &'m Function) -> Self {
220
        Builder::new(Some(func), Vec::new(), None)
221 222 223 224 225 226
    }
}

/// Converts a mutable reference of a [`Module`] to [`Builder`].
impl<'a, 'm> From<&'m mut Module> for Builder<'a, 'm> {
    fn from(module: &'m mut Module) -> Self {
227
        Builder::new(module.entry(), Vec::new(), None)
228 229 230 231
    }
}

unsafe extern "C" fn tvm_callback(
232
    args: *mut ffi::TVMValue,
233 234
    type_codes: *mut c_int,
    num_args: c_int,
235
    ret: ffi::TVMRetValueHandle,
236 237 238
    fhandle: *mut c_void,
) -> c_int {
    // turning off the incorrect linter complaints
239
    #![allow(unused_assignments, unused_unsafe)]
240 241 242 243
    let len = num_args as usize;
    let args_list = slice::from_raw_parts_mut(args, len);
    let type_codes_list = slice::from_raw_parts_mut(type_codes, len);
    let mut local_args: Vec<TVMArgValue> = Vec::new();
244
    let mut value = mem::uninitialized::<ffi::TVMValue>();
245
    let mut tcode = mem::uninitialized::<c_int>();
246 247
    let rust_fn =
        mem::transmute::<*mut c_void, fn(&[TVMArgValue]) -> Result<TVMRetValue, Error>>(fhandle);
248 249 250
    for i in 0..len {
        value = args_list[i];
        tcode = type_codes_list[i];
251 252 253
        if tcode == ffi::TVMTypeCode_kNodeHandle as c_int
            || tcode == ffi::TVMTypeCode_kFuncHandle as c_int
            || tcode == ffi::TVMTypeCode_kModuleHandle as c_int
254
        {
255
            check_call!(ffi::TVMCbArgToReturn(&mut value as *mut _, tcode));
256
        }
257
        local_args.push(TVMArgValue::new(value.into(), (tcode as i64).into()));
258 259 260 261 262 263 264 265 266 267
    }

    let rv = match rust_fn(local_args.as_slice()) {
        Ok(v) => v,
        Err(msg) => {
            crate::set_last_error(&msg);
            return -1;
        }
    };

268
    let (mut ret_val, ret_tcode) = rv.into_tvm_value();
269
    let mut ret_type_code = ret_tcode as c_int;
270
    check_call!(ffi::TVMCFuncSetReturn(
271 272 273 274 275 276 277 278 279
        ret,
        &mut ret_val as *mut _,
        &mut ret_type_code as *mut _,
        1 as c_int
    ));
    0
}

unsafe extern "C" fn tvm_callback_finalizer(fhandle: *mut c_void) {
280 281
    let rust_fn =
        mem::transmute::<*mut c_void, fn(&[TVMArgValue]) -> Result<TVMRetValue, Error>>(fhandle);
282 283 284
    mem::drop(rust_fn);
}

285 286 287 288
fn convert_to_tvm_func(f: fn(&[TVMArgValue]) -> Result<TVMRetValue, Error>) -> Function {
    let mut fhandle = ptr::null_mut() as ffi::TVMFunctionHandle;
    let resource_handle = f as *mut fn(&[TVMArgValue]) -> Result<TVMRetValue, Error>;
    check_call!(ffi::TVMFuncCreateFromCFunc(
289 290 291 292 293
        Some(tvm_callback),
        resource_handle as *mut c_void,
        Some(tvm_callback_finalizer),
        &mut fhandle as *mut _
    ));
294
    Function::new(fhandle)
295 296 297
}

/// Registers a Rust function with signature
298
/// `fn(&[TVMArgValue]) -> Result<TVMRetValue, Error>`
299 300 301 302 303 304 305 306 307 308
/// as a **global TVM packed function** from frontend to TVM backend.
///
/// Use [`register_global_func`] if overriding an existing global TVM function
/// is not required.
///
/// ## Example
///
/// ```
/// use std::convert::TryInto;
///
309
/// fn sum(args: &[TVMArgValue]) -> Result<TVMRetValue, Error> {
310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326
///     let mut ret = 0i64;
///     for arg in args.iter() {
///         let arg: i64 = arg.try_into()?;
///         ret += arg;
///     }
///     let ret_val = TVMRetValue::from(&ret);
///     Ok(ret_val)
/// }
///
/// tvm::function::register(sum, "mysum".to_owned(), false).unwrap();
/// let mut registered = function::Builder::default();
/// registered.get_function("mysum", true);
/// assert!(registered.func.is_some());
/// let ret: i64 = registered.args(&[10, 20, 30]).invoke().unwrap().try_into().unwrap();
/// assert_eq!(ret, 60);
/// ```
pub fn register<S: AsRef<str>>(
327
    f: fn(&[TVMArgValue]) -> Result<TVMRetValue, Error>,
328 329
    name: S,
    override_: bool,
330
) -> Result<(), Error> {
331 332
    let func = convert_to_tvm_func(f);
    let name = CString::new(name.as_ref())?;
333 334
    check_call!(ffi::TVMFuncRegisterGlobal(
        name.into_raw(),
335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350
        func.handle(),
        override_ as c_int
    ));
    Ok(())
}

/// Convenient macro for registering functions from frontend to backend as global
/// TVM packed functions without overriding. If overriding an existing function is needed
/// use the [`function::register`] function instead.
///
/// ## Example
///
/// ```
/// use std::convert::TryInto;
///
/// register_global_func! {
351
///     fn sum(args: &[TVMArgValue]) -> Result<TVMRetValue, Error> {
352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371
///         let mut ret = 0f64;
///         for arg in args.iter() {
///             let arg: f64 = arg.try_into()?;
///             ret += arg;
///         }
///         let ret_val = TVMRetValue::from(&ret);
///         Ok(ret_val)
///     }
/// }
///
/// let mut registered = function::Builder::default();
/// registered.get_function("sum", true);
/// assert!(registered.func.is_some());
/// let ret: f64 = registered.args(&[10f64, 20f64, 30f64]).invoke().unwrap().try_into().unwrap();
/// assert_eq!(ret, 60f64);
/// ```
#[macro_export]
macro_rules! register_global_func {
    {
        $(#[$m:meta])*
372
        fn $fn_name:ident($args:ident : &[TVMArgValue]) -> Result<TVMRetValue, Error> {
373 374 375 376
            $($code:tt)*
        }
    } => {{
        $(#[$m])*
377
        fn $fn_name($args: &[TVMArgValue]) -> Result<TVMRetValue, Error> {
378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430
            $($code)*
        }

        $crate::function::register($fn_name, stringify!($fn_name).to_owned(), false).unwrap();
    }}
}

/// Convenient macro for calling TVM packed functions by providing a
/// function identifier and some arguments. This macro outputs a `Result` type
/// and let user to perform proper error handling.
///
/// **Note**: this macro does *not* expect an outside mutable output. To
/// set mutable output use [`set_output`] directly in the builder pattern.
///
/// [`set_output`]:function/struct.Builder.html#method.set_output
///
/// ## Example
///
/// Instead of
///
/// ```
/// function::Builder::from(func).arg(&a).arg(&b).invoke();
/// ```
///
/// one can use
///
/// ```
/// call_packed!(func, &a, &b);
/// ```
#[macro_export]
macro_rules! call_packed {
    ($fn_name:expr, $($arg:expr),*) => {{
        let mut builder = $crate::function::Builder::from($fn_name);
        $(
            builder.arg($arg);
        )*
        builder.invoke()
    }}
}

#[cfg(test)]
mod tests {
    use super::*;

    static CANARY: &str = "module._LoadFromFile";

    #[test]
    fn list_global_func() {
        assert!(GLOBAL_FUNCTIONS.lock().unwrap().contains_key(CANARY));
    }

    #[test]
    fn get_fn() {
431 432
        assert!(Function::get(CANARY).is_some());
        assert!(Function::get("does not exists!").is_none());
433 434 435 436
    }

    #[test]
    fn provide_args() {
437
        let str_arg = CString::new("test").unwrap();
438
        let mut func = Builder::default();
439
        func.get_function("tvm.graph_runtime.remote_create")
440
            .args(&[10, 20])
441 442
            .arg(&str_arg);
        assert_eq!(func.arg_buf.len(), 3);
443 444
    }
}