gear icon indicating copy to clipboard operation
gear copied to clipboard

Optimize calls to const syscalls

Open NikVolf opened this issue 3 years ago • 2 comments

gr_origin gr_program_id gr_size gr_source gr_value

but caching them should occur per-message

NikVolf avatar Sep 12 '22 11:09 NikVolf

Foreign global variables is currently not supported https://github.com/rust-lang/rust/issues/60825

we still can implement it via calling functions like thefn cache below in our executor right before executing each messages or sth similiar in the start section https://github.com/gear-tech/gear/issues/938

//! gstd/src/config.rs
pub(crate) static mut GR_ORIGIN: H256 = [0; 32];

unsafe extern "C" fn cache(cache_origin: *mut H256, ...) {
        let mut origin = [0; 32];
        *mut origin = cache_origin;
  
        // ...
    }
}
//! gstd/src/exec.rs
pub const fn origin() -> H256 {
    GR_ORIGIN
}

but seems not necessary since not all of the programs are going to use all of the cached methods

clearloop avatar Feb 27 '23 14:02 clearloop

My proposal is to make 2 fake sys-callsgr_is_getter_called(u32) and gr_set_getter_called(u32), that take number of getter sys-call as argument

enum GetterSysCallsEnumeration {
  Size,
  ProgramId,
  ...
}

On instrumentation we will change call $gr_is_getter_called to code which will check whether corresponding bit is set in special global '__gear_flags', which by default on instantiation will be set to 0. call $gr_set_getter_called will be changed to code, which will set corresponding bit in global var.

In gstd we should make this code for each getter sys-call calling:

static mut OriginStorage: Option<MessageId>  = None;
...

let val = if gr_is_getter_called(gr_origin_no) {
  // take it from some static storage
  OriginStorage.unwrap()
} else {
  // call sys-call and set 
  let val = gr_origin();
  OriginStorage.replace(val);
  gr_set_getter_called(gr_origin_no);
  val
}
// use val

On instantiation global __gear_flags is set to 0, so we will not take wrong value from static storages.

grishasobol avatar Mar 23 '23 07:03 grishasobol