1 //! The JIT driver uses [`cranelift_jit`] to JIT execute programs without writing any object
4 use std::cell::RefCell;
6 use std::os::raw::{c_char, c_int};
7 use std::sync::{mpsc, Mutex};
9 use rustc_codegen_ssa::CrateInfo;
10 use rustc_middle::mir::mono::MonoItem;
11 use rustc_session::Session;
12 use rustc_span::Symbol;
14 use cranelift_jit::{JITBuilder, JITModule};
16 // FIXME use std::sync::OnceLock once it stabilizes
17 use once_cell::sync::OnceCell;
19 use crate::{prelude::*, BackendConfig};
20 use crate::{CodegenCx, CodegenMode};
23 backend_config: BackendConfig,
24 jit_module: JITModule,
28 static LAZY_JIT_STATE: RefCell<Option<JitState>> = const { RefCell::new(None) };
31 /// The Sender owned by the rustc thread
32 static GLOBAL_MESSAGE_SENDER: OnceCell<Mutex<mpsc::Sender<UnsafeMessage>>> = OnceCell::new();
34 /// A message that is sent from the jitted runtime to the rustc thread.
35 /// Senders are responsible for upholding `Send` semantics.
37 /// Request that the specified `Instance` be lazily jitted.
39 /// Nothing accessible through `instance_ptr` may be moved or mutated by the sender after
40 /// this message is sent.
42 instance_ptr: *const Instance<'static>,
43 trampoline_ptr: *const u8,
44 tx: mpsc::Sender<*const u8>,
47 unsafe impl Send for UnsafeMessage {}
51 fn send(self) -> Result<(), mpsc::SendError<UnsafeMessage>> {
53 /// The Sender owned by the local thread
54 static LOCAL_MESSAGE_SENDER: mpsc::Sender<UnsafeMessage> =
60 LOCAL_MESSAGE_SENDER.with(|sender| sender.send(self))
66 backend_config: &BackendConfig,
68 ) -> (JITModule, CodegenCx) {
69 let crate_info = CrateInfo::new(tcx, "dummy_target_cpu".to_string());
71 let isa = crate::build_isa(tcx.sess, backend_config);
72 let mut jit_builder = JITBuilder::with_isa(isa, cranelift_module::default_libcall_names());
73 jit_builder.hotswap(hotswap);
74 crate::compiler_builtins::register_functions_for_jit(&mut jit_builder);
75 jit_builder.symbol_lookup_fn(dep_symbol_lookup_fn(tcx.sess, crate_info));
76 jit_builder.symbol("__clif_jit_fn", clif_jit_fn as *const u8);
77 let mut jit_module = JITModule::new(jit_builder);
79 let mut cx = crate::CodegenCx::new(
81 backend_config.clone(),
84 Symbol::intern("dummy_cgu_name"),
87 crate::allocator::codegen(tcx, &mut jit_module, &mut cx.unwind_context);
88 crate::main_shim::maybe_create_entry_wrapper(
91 &mut cx.unwind_context,
99 pub(crate) fn run_jit(tcx: TyCtxt<'_>, backend_config: BackendConfig) -> ! {
100 if !tcx.sess.opts.output_types.should_codegen() {
101 tcx.sess.fatal("JIT mode doesn't work with `cargo check`");
104 if !tcx.sess.crate_types().contains(&rustc_session::config::CrateType::Executable) {
105 tcx.sess.fatal("can't jit non-executable crate");
108 let (mut jit_module, mut cx) = create_jit_module(
111 matches!(backend_config.codegen_mode, CodegenMode::JitLazy),
113 let mut cached_context = Context::new();
115 let (_, cgus) = tcx.collect_and_partition_mono_items(());
116 let mono_items = cgus
118 .map(|cgu| cgu.items_in_deterministic_order(tcx).into_iter())
120 .collect::<FxHashMap<_, (_, _)>>()
122 .collect::<Vec<(_, (_, _))>>();
124 tcx.sess.time("codegen mono items", || {
125 super::predefine_mono_items(tcx, &mut jit_module, &mono_items);
126 for (mono_item, _) in mono_items {
128 MonoItem::Fn(inst) => match backend_config.codegen_mode {
129 CodegenMode::Aot => unreachable!(),
130 CodegenMode::Jit => {
131 codegen_and_compile_fn(
139 CodegenMode::JitLazy => {
140 codegen_shim(tcx, &mut cx, &mut cached_context, &mut jit_module, inst)
143 MonoItem::Static(def_id) => {
144 crate::constant::codegen_static(tcx, &mut jit_module, def_id);
146 MonoItem::GlobalAsm(item_id) => {
147 let item = tcx.hir().item(item_id);
148 tcx.sess.span_fatal(item.span, "Global asm is not supported in JIT mode");
154 if !cx.global_asm.is_empty() {
155 tcx.sess.fatal("Inline asm is not supported in JIT mode");
158 tcx.sess.abort_if_errors();
160 jit_module.finalize_definitions().unwrap();
161 unsafe { cx.unwind_context.register_jit(&jit_module) };
164 "Rustc codegen cranelift will JIT run the executable, because -Cllvm-args=mode=jit was passed"
167 let args = std::iter::once(&*tcx.crate_name(LOCAL_CRATE).as_str().to_string())
168 .chain(backend_config.jit_args.iter().map(|arg| &**arg))
169 .map(|arg| CString::new(arg).unwrap())
170 .collect::<Vec<_>>();
172 let start_sig = Signature {
174 AbiParam::new(jit_module.target_config().pointer_type()),
175 AbiParam::new(jit_module.target_config().pointer_type()),
177 returns: vec![AbiParam::new(jit_module.target_config().pointer_type() /*isize*/)],
178 call_conv: jit_module.target_config().default_call_conv,
180 let start_func_id = jit_module.declare_function("main", Linkage::Import, &start_sig).unwrap();
181 let finalized_start: *const u8 = jit_module.get_finalized_function(start_func_id);
183 LAZY_JIT_STATE.with(|lazy_jit_state| {
184 let mut lazy_jit_state = lazy_jit_state.borrow_mut();
185 assert!(lazy_jit_state.is_none());
186 *lazy_jit_state = Some(JitState { backend_config, jit_module });
189 let f: extern "C" fn(c_int, *const *const c_char) -> c_int =
190 unsafe { ::std::mem::transmute(finalized_start) };
192 let (tx, rx) = mpsc::channel();
193 GLOBAL_MESSAGE_SENDER.set(Mutex::new(tx)).unwrap();
195 // Spawn the jitted runtime in a new thread so that this rustc thread can handle messages
196 // (eg to lazily JIT further functions as required)
197 std::thread::spawn(move || {
198 let mut argv = args.iter().map(|arg| arg.as_ptr()).collect::<Vec<_>>();
200 // Push a null pointer as a terminating argument. This is required by POSIX and
201 // useful as some dynamic linkers use it as a marker to jump over.
202 argv.push(std::ptr::null());
204 let ret = f(args.len() as c_int, argv.as_ptr());
205 std::process::exit(ret);
210 match rx.recv().unwrap() {
211 // lazy JIT compilation request - compile requested instance and return pointer to result
212 UnsafeMessage::JitFn { instance_ptr, trampoline_ptr, tx } => {
213 tx.send(jit_fn(instance_ptr, trampoline_ptr))
214 .expect("jitted runtime hung up before response to lazy JIT request was sent");
220 pub(crate) fn codegen_and_compile_fn<'tcx>(
222 cx: &mut crate::CodegenCx,
223 cached_context: &mut Context,
224 module: &mut dyn Module,
225 instance: Instance<'tcx>,
227 tcx.prof.generic_activity("codegen and compile fn").run(|| {
229 crate::PrintOnPanic(|| format!("{:?} {}", instance, tcx.symbol_name(instance).name));
231 let cached_func = std::mem::replace(&mut cached_context.func, Function::new());
232 let codegened_func = crate::base::codegen_fn(tcx, cx, cached_func, module, instance);
234 crate::base::compile_fn(cx, cached_context, module, codegened_func);
238 extern "C" fn clif_jit_fn(
239 instance_ptr: *const Instance<'static>,
240 trampoline_ptr: *const u8,
242 // send the JIT request to the rustc thread, with a channel for the response
243 let (tx, rx) = mpsc::channel();
244 UnsafeMessage::JitFn { instance_ptr, trampoline_ptr, tx }
246 .expect("rustc thread hung up before lazy JIT request was sent");
248 // block on JIT compilation result
249 rx.recv().expect("rustc thread hung up before responding to sent lazy JIT request")
252 fn jit_fn(instance_ptr: *const Instance<'static>, trampoline_ptr: *const u8) -> *const u8 {
253 rustc_middle::ty::tls::with(|tcx| {
254 // lift is used to ensure the correct lifetime for instance.
255 let instance = tcx.lift(unsafe { *instance_ptr }).unwrap();
257 LAZY_JIT_STATE.with(|lazy_jit_state| {
258 let mut lazy_jit_state = lazy_jit_state.borrow_mut();
259 let lazy_jit_state = lazy_jit_state.as_mut().unwrap();
260 let jit_module = &mut lazy_jit_state.jit_module;
261 let backend_config = lazy_jit_state.backend_config.clone();
263 let name = tcx.symbol_name(instance).name;
264 let sig = crate::abi::get_function_sig(
266 jit_module.target_config().default_call_conv,
269 let func_id = jit_module.declare_function(name, Linkage::Export, &sig).unwrap();
271 let current_ptr = jit_module.read_got_entry(func_id);
273 // If the function's GOT entry has already been updated to point at something other
274 // than the shim trampoline, don't re-jit but just return the new pointer instead.
275 // This does not need synchronization as this code is executed only by a sole rustc
277 if current_ptr != trampoline_ptr {
281 jit_module.prepare_for_function_redefine(func_id).unwrap();
283 let mut cx = crate::CodegenCx::new(
288 Symbol::intern("dummy_cgu_name"),
290 codegen_and_compile_fn(tcx, &mut cx, &mut Context::new(), jit_module, instance);
292 assert!(cx.global_asm.is_empty());
293 jit_module.finalize_definitions().unwrap();
294 unsafe { cx.unwind_context.register_jit(&jit_module) };
295 jit_module.get_finalized_function(func_id)
300 fn dep_symbol_lookup_fn(
302 crate_info: CrateInfo,
303 ) -> Box<dyn Fn(&str) -> Option<*const u8>> {
304 use rustc_middle::middle::dependency_format::Linkage;
306 let mut dylib_paths = Vec::new();
308 let data = &crate_info
311 .find(|(crate_type, _data)| *crate_type == rustc_session::config::CrateType::Executable)
314 for &cnum in &crate_info.used_crates {
315 let src = &crate_info.used_crate_source[&cnum];
316 match data[cnum.as_usize() - 1] {
317 Linkage::NotLinked | Linkage::IncludedFromDylib => {}
319 let name = crate_info.crate_name[&cnum];
320 let mut err = sess.struct_err(&format!("Can't load static lib {}", name));
321 err.note("rustc_codegen_cranelift can only load dylibs in JIT mode.");
324 Linkage::Dynamic => {
325 dylib_paths.push(src.dylib.as_ref().unwrap().0.clone());
330 let imported_dylibs = Box::leak(
333 .map(|path| unsafe { libloading::Library::new(&path).unwrap() })
334 .collect::<Box<[_]>>(),
337 sess.abort_if_errors();
339 Box::new(move |sym_name| {
340 for dylib in &*imported_dylibs {
341 if let Ok(sym) = unsafe { dylib.get::<*const u8>(sym_name.as_bytes()) } {
349 fn codegen_shim<'tcx>(
352 cached_context: &mut Context,
353 module: &mut JITModule,
354 inst: Instance<'tcx>,
356 let pointer_type = module.target_config().pointer_type();
358 let name = tcx.symbol_name(inst).name;
359 let sig = crate::abi::get_function_sig(tcx, module.target_config().default_call_conv, inst);
360 let func_id = module.declare_function(name, Linkage::Export, &sig).unwrap();
362 let instance_ptr = Box::into_raw(Box::new(inst));
369 call_conv: module.target_config().default_call_conv,
370 params: vec![AbiParam::new(pointer_type), AbiParam::new(pointer_type)],
371 returns: vec![AbiParam::new(pointer_type)],
376 let context = cached_context;
378 let trampoline = &mut context.func;
379 trampoline.signature = sig.clone();
381 let mut builder_ctx = FunctionBuilderContext::new();
382 let mut trampoline_builder = FunctionBuilder::new(trampoline, &mut builder_ctx);
384 let trampoline_fn = module.declare_func_in_func(func_id, trampoline_builder.func);
385 let jit_fn = module.declare_func_in_func(jit_fn, trampoline_builder.func);
386 let sig_ref = trampoline_builder.func.import_signature(sig);
388 let entry_block = trampoline_builder.create_block();
389 trampoline_builder.append_block_params_for_function_params(entry_block);
390 let fn_args = trampoline_builder.func.dfg.block_params(entry_block).to_vec();
392 trampoline_builder.switch_to_block(entry_block);
393 let instance_ptr = trampoline_builder.ins().iconst(pointer_type, instance_ptr as u64 as i64);
394 let trampoline_ptr = trampoline_builder.ins().func_addr(pointer_type, trampoline_fn);
395 let jitted_fn = trampoline_builder.ins().call(jit_fn, &[instance_ptr, trampoline_ptr]);
396 let jitted_fn = trampoline_builder.func.dfg.inst_results(jitted_fn)[0];
397 let call_inst = trampoline_builder.ins().call_indirect(sig_ref, jitted_fn, &fn_args);
398 let ret_vals = trampoline_builder.func.dfg.inst_results(call_inst).to_vec();
399 trampoline_builder.ins().return_(&ret_vals);
401 module.define_function(func_id, context).unwrap();
402 cx.unwind_context.add_function(func_id, context, module.isa());