viirya commented on a change in pull request #1849: URL: https://github.com/apache/arrow-datafusion/pull/1849#discussion_r810593508
########## File path: datafusion-jit/src/jit.rs ########## @@ -0,0 +1,698 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +use crate::api::GeneratedFunction; +use crate::ast::{BinaryExpr, Expr, JITType, Literal, Stmt, TypedLit, BOOL, I64, NIL}; +use cranelift::prelude::*; +use cranelift_jit::{JITBuilder, JITModule}; +use cranelift_module::{DataContext, Linkage, Module}; +use datafusion_common::internal_err; +use datafusion_common::{DataFusionError, Result}; +use std::collections::HashMap; +use std::slice; + +/// The basic JIT class. +#[allow(clippy::upper_case_acronyms)] +pub struct JIT { + /// The function builder context, which is reused across multiple + /// FunctionBuilder instances. + builder_context: FunctionBuilderContext, + + /// The main Cranelift context, which holds the state for codegen. Cranelift + /// separates this from `Module` to allow for parallel compilation, with a + /// context per thread, though this is not the case now. + ctx: codegen::Context, + + /// The data context, which is to data objects what `ctx` is to functions. + data_ctx: DataContext, + + /// The module, with the jit backend, which manages the JIT'd + /// functions. + module: JITModule, +} + +impl Default for JIT { + fn default() -> Self { + let builder = JITBuilder::new(cranelift_module::default_libcall_names()); + let module = JITModule::new(builder); + Self { + builder_context: FunctionBuilderContext::new(), + ctx: module.make_context(), + data_ctx: DataContext::new(), + module, + } + } +} + +impl JIT { + /// New while registering external functions + pub fn new<It, K>(symbols: It) -> Self + where + It: IntoIterator<Item = (K, *const u8)>, + K: Into<String>, + { + let mut flag_builder = settings::builder(); + flag_builder.set("use_colocated_libcalls", "false").unwrap(); + flag_builder.set("is_pic", "true").unwrap(); + flag_builder.set("opt_level", "speed").unwrap(); + flag_builder.set("enable_simd", "true").unwrap(); + let isa_builder = cranelift_native::builder().unwrap_or_else(|msg| { + panic!("host machine is not supported: {}", msg); + }); + let isa = isa_builder.finish(settings::Flags::new(flag_builder)); + let mut builder = + JITBuilder::with_isa(isa, cranelift_module::default_libcall_names()); + builder.symbols(symbols); + let module = JITModule::new(builder); + Self { + builder_context: FunctionBuilderContext::new(), + ctx: module.make_context(), + data_ctx: DataContext::new(), + module, + } + } + + /// Compile the generated function into machine code. + pub fn compile(&mut self, func: GeneratedFunction) -> Result<*const u8> { + let GeneratedFunction { + name, + params, + body, + ret, + } = func; + + // Translate the AST nodes into Cranelift IR. + self.translate(params, ret, body)?; + + // Next, declare the function to jit. Functions must be declared + // before they can be called, or defined. + let id = self.module.declare_function( + &name, + Linkage::Export, + &self.ctx.func.signature, + )?; + + // Define the function to jit. This finishes compilation, although + // there may be outstanding relocations to perform. Currently, jit + // cannot finish relocations until all functions to be called are + // defined. For now, we'll just finalize the function below. + self.module.define_function(id, &mut self.ctx)?; + + // Now that compilation is finished, we can clear out the context state. + self.module.clear_context(&mut self.ctx); + + // Finalize the functions which we just defined, which resolves any + // outstanding relocations (patching in addresses, now that they're + // available). + self.module.finalize_definitions(); + + // We can now retrieve a pointer to the machine code. + let code = self.module.get_finalized_function(id); + + Ok(code) + } + + /// Create a zero-initialized data section. + pub fn create_data(&mut self, name: &str, contents: Vec<u8>) -> Result<&[u8]> { Review comment: do we have test for this? ########## File path: datafusion-jit/src/api.rs ########## @@ -0,0 +1,630 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! Constructing a function AST at runtime. + +use crate::ast::*; +use crate::jit::JIT; +use datafusion_common::internal_err; +use datafusion_common::{DataFusionError, Result}; +use parking_lot::Mutex; +use std::collections::HashMap; +use std::collections::VecDeque; +use std::fmt::{Debug, Display, Formatter}; +use std::sync::Arc; + +/// External Function signature +struct ExternFuncSignature { + name: String, + /// pointer to the function + code: *const u8, + params: Vec<JITType>, + returns: Option<JITType>, +} + +#[derive(Clone, Debug)] +/// A function consisting of AST nodes that JIT can compile. +pub struct GeneratedFunction { + pub(crate) name: String, + pub(crate) params: Vec<(String, JITType)>, + pub(crate) body: Vec<Stmt>, + pub(crate) ret: Option<(String, JITType)>, +} + +#[derive(Default)] +/// State of Assembler, keep tracking of generated function names +/// and registered external functions. +pub struct AssemblerState { + name_next_id: HashMap<String, u8>, + extern_funcs: HashMap<String, ExternFuncSignature>, +} + +impl AssemblerState { + /// Create a fresh function name with prefix `name`. + pub fn fresh_name(&mut self, name: impl Into<String>) -> String { + let name = name.into(); + if !self.name_next_id.contains_key(&name) { + self.name_next_id.insert(name.clone(), 0); + } + + let id = self.name_next_id.get_mut(&name).unwrap(); + let name = format!("{}_{}", &name, id); + *id += 1; + name + } +} + +/// The very first step for constructing a function at runtime. +pub struct Assembler { + state: Arc<Mutex<AssemblerState>>, +} + +impl Default for Assembler { + fn default() -> Self { + Self { + state: Arc::new(Default::default()), + } + } +} + +impl Assembler { + /// Register an external Rust function to make it accessible by runtime generated functions. + /// Parameters and return types are used to impose type safety while constructing an AST. + pub fn register_extern_fn( + &self, + name: impl Into<String>, + ptr: *const u8, + params: Vec<JITType>, + returns: Option<JITType>, + ) -> Result<()> { + let extern_funcs = &mut self.state.lock().extern_funcs; + let fn_name = name.into(); + let old = extern_funcs.insert( + fn_name.clone(), + ExternFuncSignature { + name: fn_name, + code: ptr, + params, + returns, + }, + ); + + match old { + None => Ok(()), + Some(old) => internal_err!("Extern function {} already exists", old.name), + } + } + + /// Create a new FunctionBuilder with `name` prefix + pub fn new_func_builder(&self, name: impl Into<String>) -> FunctionBuilder { + let name = self.state.lock().fresh_name(name); + FunctionBuilder::new(name, self.state.clone()) + } + + /// Create JIT env which we could compile the AST of constructed function + /// into runnable code. + pub fn create_jit(&self) -> JIT { + let symbols = self + .state + .lock() + .extern_funcs + .values() + .map(|s| (s.name.clone(), s.code)) + .collect::<Vec<_>>(); + JIT::new(symbols) + } +} + +/// Function builder API. Stores the state while +/// we are constructing an AST for a function. +pub struct FunctionBuilder { + name: String, + params: Vec<(String, JITType)>, + ret: Option<(String, JITType)>, + fields: VecDeque<HashMap<String, JITType>>, + assembler_state: Arc<Mutex<AssemblerState>>, +} + +impl FunctionBuilder { + fn new(name: impl Into<String>, assembler_state: Arc<Mutex<AssemblerState>>) -> Self { + let mut fields = VecDeque::new(); + fields.push_back(HashMap::new()); + Self { + name: name.into(), + params: Vec::new(), + ret: None, + fields, + assembler_state, + } + } + + /// Add one more parameter to the function. + pub fn param(mut self, name: impl Into<String>, ty: JITType) -> Self { + let name = name.into(); + assert!(!self.fields.back().unwrap().contains_key(&name)); + self.params.push((name.clone(), ty)); + self.fields.back_mut().unwrap().insert(name, ty); + self + } + + /// Set return type for the function. Functions are of `void` type by default if + /// you do not set the return type. + pub fn ret(mut self, name: impl Into<String>, ty: JITType) -> Self { + let name = name.into(); + assert!(!self.fields.back().unwrap().contains_key(&name)); + self.ret = Some((name.clone(), ty)); + self.fields.back_mut().unwrap().insert(name, ty); + self + } + + /// Enter the function body at start the building. + pub fn enter_block(&mut self) -> CodeBlock { Review comment: For one `FunctionBuilder`, `enter_block` can only be called once at the beginning of building, right? -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
