]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_codegen_cranelift/src/driver/jit.rs
Merge commit '7d53619064ab7045c383644cb445052d2a3d46db' into sync_cg_clif-2023-02-09
[rust.git] / compiler / rustc_codegen_cranelift / src / driver / jit.rs
1 //! The JIT driver uses [`cranelift_jit`] to JIT execute programs without writing any object
2 //! files.
3
4 use std::cell::RefCell;
5 use std::ffi::CString;
6 use std::os::raw::{c_char, c_int};
7 use std::sync::{mpsc, Mutex};
8
9 use rustc_codegen_ssa::CrateInfo;
10 use rustc_middle::mir::mono::MonoItem;
11 use rustc_session::Session;
12 use rustc_span::Symbol;
13
14 use cranelift_jit::{JITBuilder, JITModule};
15
16 // FIXME use std::sync::OnceLock once it stabilizes
17 use once_cell::sync::OnceCell;
18
19 use crate::{prelude::*, BackendConfig};
20 use crate::{CodegenCx, CodegenMode};
21
22 struct JitState {
23     backend_config: BackendConfig,
24     jit_module: JITModule,
25 }
26
27 thread_local! {
28     static LAZY_JIT_STATE: RefCell<Option<JitState>> = const { RefCell::new(None) };
29 }
30
31 /// The Sender owned by the rustc thread
32 static GLOBAL_MESSAGE_SENDER: OnceCell<Mutex<mpsc::Sender<UnsafeMessage>>> = OnceCell::new();
33
34 /// A message that is sent from the jitted runtime to the rustc thread.
35 /// Senders are responsible for upholding `Send` semantics.
36 enum UnsafeMessage {
37     /// Request that the specified `Instance` be lazily jitted.
38     ///
39     /// Nothing accessible through `instance_ptr` may be moved or mutated by the sender after
40     /// this message is sent.
41     JitFn {
42         instance_ptr: *const Instance<'static>,
43         trampoline_ptr: *const u8,
44         tx: mpsc::Sender<*const u8>,
45     },
46 }
47 unsafe impl Send for UnsafeMessage {}
48
49 impl UnsafeMessage {
50     /// Send the message.
51     fn send(self) -> Result<(), mpsc::SendError<UnsafeMessage>> {
52         thread_local! {
53             /// The Sender owned by the local thread
54             static LOCAL_MESSAGE_SENDER: mpsc::Sender<UnsafeMessage> =
55                 GLOBAL_MESSAGE_SENDER
56                     .get().unwrap()
57                     .lock().unwrap()
58                     .clone();
59         }
60         LOCAL_MESSAGE_SENDER.with(|sender| sender.send(self))
61     }
62 }
63
64 fn create_jit_module(
65     tcx: TyCtxt<'_>,
66     backend_config: &BackendConfig,
67     hotswap: bool,
68 ) -> (JITModule, CodegenCx) {
69     let crate_info = CrateInfo::new(tcx, "dummy_target_cpu".to_string());
70
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);
78
79     let mut cx = crate::CodegenCx::new(
80         tcx,
81         backend_config.clone(),
82         jit_module.isa(),
83         false,
84         Symbol::intern("dummy_cgu_name"),
85     );
86
87     crate::allocator::codegen(tcx, &mut jit_module, &mut cx.unwind_context);
88     crate::main_shim::maybe_create_entry_wrapper(
89         tcx,
90         &mut jit_module,
91         &mut cx.unwind_context,
92         true,
93         true,
94     );
95
96     (jit_module, cx)
97 }
98
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`");
102     }
103
104     if !tcx.sess.crate_types().contains(&rustc_session::config::CrateType::Executable) {
105         tcx.sess.fatal("can't jit non-executable crate");
106     }
107
108     let (mut jit_module, mut cx) = create_jit_module(
109         tcx,
110         &backend_config,
111         matches!(backend_config.codegen_mode, CodegenMode::JitLazy),
112     );
113     let mut cached_context = Context::new();
114
115     let (_, cgus) = tcx.collect_and_partition_mono_items(());
116     let mono_items = cgus
117         .iter()
118         .map(|cgu| cgu.items_in_deterministic_order(tcx).into_iter())
119         .flatten()
120         .collect::<FxHashMap<_, (_, _)>>()
121         .into_iter()
122         .collect::<Vec<(_, (_, _))>>();
123
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 {
127             match mono_item {
128                 MonoItem::Fn(inst) => match backend_config.codegen_mode {
129                     CodegenMode::Aot => unreachable!(),
130                     CodegenMode::Jit => {
131                         codegen_and_compile_fn(
132                             tcx,
133                             &mut cx,
134                             &mut cached_context,
135                             &mut jit_module,
136                             inst,
137                         );
138                     }
139                     CodegenMode::JitLazy => {
140                         codegen_shim(tcx, &mut cx, &mut cached_context, &mut jit_module, inst)
141                     }
142                 },
143                 MonoItem::Static(def_id) => {
144                     crate::constant::codegen_static(tcx, &mut jit_module, def_id);
145                 }
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");
149                 }
150             }
151         }
152     });
153
154     if !cx.global_asm.is_empty() {
155         tcx.sess.fatal("Inline asm is not supported in JIT mode");
156     }
157
158     tcx.sess.abort_if_errors();
159
160     jit_module.finalize_definitions().unwrap();
161     unsafe { cx.unwind_context.register_jit(&jit_module) };
162
163     println!(
164         "Rustc codegen cranelift will JIT run the executable, because -Cllvm-args=mode=jit was passed"
165     );
166
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<_>>();
171
172     let start_sig = Signature {
173         params: vec![
174             AbiParam::new(jit_module.target_config().pointer_type()),
175             AbiParam::new(jit_module.target_config().pointer_type()),
176         ],
177         returns: vec![AbiParam::new(jit_module.target_config().pointer_type() /*isize*/)],
178         call_conv: jit_module.target_config().default_call_conv,
179     };
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);
182
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 });
187     });
188
189     let f: extern "C" fn(c_int, *const *const c_char) -> c_int =
190         unsafe { ::std::mem::transmute(finalized_start) };
191
192     let (tx, rx) = mpsc::channel();
193     GLOBAL_MESSAGE_SENDER.set(Mutex::new(tx)).unwrap();
194
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<_>>();
199
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());
203
204         let ret = f(args.len() as c_int, argv.as_ptr());
205         std::process::exit(ret);
206     });
207
208     // Handle messages
209     loop {
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");
215             }
216         }
217     }
218 }
219
220 pub(crate) fn codegen_and_compile_fn<'tcx>(
221     tcx: TyCtxt<'tcx>,
222     cx: &mut crate::CodegenCx,
223     cached_context: &mut Context,
224     module: &mut dyn Module,
225     instance: Instance<'tcx>,
226 ) {
227     tcx.prof.generic_activity("codegen and compile fn").run(|| {
228         let _inst_guard =
229             crate::PrintOnPanic(|| format!("{:?} {}", instance, tcx.symbol_name(instance).name));
230
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);
233
234         crate::base::compile_fn(cx, cached_context, module, codegened_func);
235     });
236 }
237
238 extern "C" fn clif_jit_fn(
239     instance_ptr: *const Instance<'static>,
240     trampoline_ptr: *const u8,
241 ) -> *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 }
245         .send()
246         .expect("rustc thread hung up before lazy JIT request was sent");
247
248     // block on JIT compilation result
249     rx.recv().expect("rustc thread hung up before responding to sent lazy JIT request")
250 }
251
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();
256
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();
262
263             let name = tcx.symbol_name(instance).name;
264             let sig = crate::abi::get_function_sig(
265                 tcx,
266                 jit_module.target_config().default_call_conv,
267                 instance,
268             );
269             let func_id = jit_module.declare_function(name, Linkage::Export, &sig).unwrap();
270
271             let current_ptr = jit_module.read_got_entry(func_id);
272
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
276             // thread.
277             if current_ptr != trampoline_ptr {
278                 return current_ptr;
279             }
280
281             jit_module.prepare_for_function_redefine(func_id).unwrap();
282
283             let mut cx = crate::CodegenCx::new(
284                 tcx,
285                 backend_config,
286                 jit_module.isa(),
287                 false,
288                 Symbol::intern("dummy_cgu_name"),
289             );
290             codegen_and_compile_fn(tcx, &mut cx, &mut Context::new(), jit_module, instance);
291
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)
296         })
297     })
298 }
299
300 fn dep_symbol_lookup_fn(
301     sess: &Session,
302     crate_info: CrateInfo,
303 ) -> Box<dyn Fn(&str) -> Option<*const u8>> {
304     use rustc_middle::middle::dependency_format::Linkage;
305
306     let mut dylib_paths = Vec::new();
307
308     let data = &crate_info
309         .dependency_formats
310         .iter()
311         .find(|(crate_type, _data)| *crate_type == rustc_session::config::CrateType::Executable)
312         .unwrap()
313         .1;
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 => {}
318             Linkage::Static => {
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.");
322                 err.emit();
323             }
324             Linkage::Dynamic => {
325                 dylib_paths.push(src.dylib.as_ref().unwrap().0.clone());
326             }
327         }
328     }
329
330     let imported_dylibs = Box::leak(
331         dylib_paths
332             .into_iter()
333             .map(|path| unsafe { libloading::Library::new(&path).unwrap() })
334             .collect::<Box<[_]>>(),
335     );
336
337     sess.abort_if_errors();
338
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()) } {
342                 return Some(*sym);
343             }
344         }
345         None
346     })
347 }
348
349 fn codegen_shim<'tcx>(
350     tcx: TyCtxt<'tcx>,
351     cx: &mut CodegenCx,
352     cached_context: &mut Context,
353     module: &mut JITModule,
354     inst: Instance<'tcx>,
355 ) {
356     let pointer_type = module.target_config().pointer_type();
357
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();
361
362     let instance_ptr = Box::into_raw(Box::new(inst));
363
364     let jit_fn = module
365         .declare_function(
366             "__clif_jit_fn",
367             Linkage::Import,
368             &Signature {
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)],
372             },
373         )
374         .unwrap();
375
376     let context = cached_context;
377     context.clear();
378     let trampoline = &mut context.func;
379     trampoline.signature = sig.clone();
380
381     let mut builder_ctx = FunctionBuilderContext::new();
382     let mut trampoline_builder = FunctionBuilder::new(trampoline, &mut builder_ctx);
383
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);
387
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();
391
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);
400
401     module.define_function(func_id, context).unwrap();
402     cx.unwind_context.add_function(func_id, context, module.isa());
403 }