]> git.lizzy.rs Git - rust.git/blob - src/driver/jit.rs
8ab9433643242d5c2c17829ecab15413e12ed98e
[rust.git] / 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::lazy::{Lazy, SyncOnceCell};
7 use std::os::raw::{c_char, c_int};
8 use std::sync::{mpsc, Mutex};
9
10 use cranelift_codegen::binemit::{NullStackMapSink, NullTrapSink};
11 use rustc_codegen_ssa::CrateInfo;
12 use rustc_middle::mir::mono::MonoItem;
13
14 use cranelift_jit::{JITBuilder, JITModule};
15
16 use crate::{prelude::*, BackendConfig};
17 use crate::{CodegenCx, CodegenMode};
18
19 struct JitState {
20     backend_config: BackendConfig,
21     jit_module: JITModule,
22 }
23
24 thread_local! {
25     static LAZY_JIT_STATE: RefCell<Option<JitState>> = RefCell::new(None);
26 }
27
28 /// The Sender owned by the rustc thread
29 static GLOBAL_MESSAGE_SENDER: SyncOnceCell<Mutex<mpsc::Sender<UnsafeMessage>>> =
30     SyncOnceCell::new();
31
32 /// A message that is sent from the jitted runtime to the rustc thread.
33 /// Senders are responsible for upholding `Send` semantics.
34 enum UnsafeMessage {
35     /// Request that the specified `Instance` be lazily jitted.
36     ///
37     /// Nothing accessible through `instance_ptr` may be moved or mutated by the sender after
38     /// this message is sent.
39     JitFn {
40         instance_ptr: *const Instance<'static>,
41         trampoline_ptr: *const u8,
42         tx: mpsc::Sender<*const u8>,
43     },
44 }
45 unsafe impl Send for UnsafeMessage {}
46
47 impl UnsafeMessage {
48     /// Send the message.
49     fn send(self) -> Result<(), mpsc::SendError<UnsafeMessage>> {
50         thread_local! {
51             /// The Sender owned by the local thread
52             static LOCAL_MESSAGE_SENDER: Lazy<mpsc::Sender<UnsafeMessage>> = Lazy::new(||
53                 GLOBAL_MESSAGE_SENDER
54                     .get().unwrap()
55                     .lock().unwrap()
56                     .clone()
57             );
58         }
59         LOCAL_MESSAGE_SENDER.with(|sender| sender.send(self))
60     }
61 }
62
63 fn create_jit_module<'tcx>(
64     tcx: TyCtxt<'tcx>,
65     backend_config: &BackendConfig,
66     hotswap: bool,
67 ) -> (JITModule, CodegenCx<'tcx>) {
68     let imported_symbols = load_imported_symbols_for_jit(tcx);
69
70     let isa = crate::build_isa(tcx.sess, backend_config);
71     let mut jit_builder = JITBuilder::with_isa(isa, cranelift_module::default_libcall_names());
72     jit_builder.hotswap(hotswap);
73     crate::compiler_builtins::register_functions_for_jit(&mut jit_builder);
74     jit_builder.symbols(imported_symbols);
75     let mut jit_module = JITModule::new(jit_builder);
76
77     let mut cx = crate::CodegenCx::new(tcx, backend_config.clone(), jit_module.isa(), false);
78
79     crate::allocator::codegen(tcx, &mut jit_module, &mut cx.unwind_context);
80     crate::main_shim::maybe_create_entry_wrapper(
81         tcx,
82         &mut jit_module,
83         &mut cx.unwind_context,
84         true,
85         true,
86     );
87
88     (jit_module, cx)
89 }
90
91 pub(crate) fn run_jit(tcx: TyCtxt<'_>, backend_config: BackendConfig) -> ! {
92     if !tcx.sess.opts.output_types.should_codegen() {
93         tcx.sess.fatal("JIT mode doesn't work with `cargo check`");
94     }
95
96     if !tcx.sess.crate_types().contains(&rustc_session::config::CrateType::Executable) {
97         tcx.sess.fatal("can't jit non-executable crate");
98     }
99
100     let (mut jit_module, mut cx) = create_jit_module(
101         tcx,
102         &backend_config,
103         matches!(backend_config.codegen_mode, CodegenMode::JitLazy),
104     );
105
106     let (_, cgus) = tcx.collect_and_partition_mono_items(());
107     let mono_items = cgus
108         .iter()
109         .map(|cgu| cgu.items_in_deterministic_order(tcx).into_iter())
110         .flatten()
111         .collect::<FxHashMap<_, (_, _)>>()
112         .into_iter()
113         .collect::<Vec<(_, (_, _))>>();
114
115     super::time(tcx, backend_config.display_cg_time, "codegen mono items", || {
116         super::predefine_mono_items(tcx, &mut jit_module, &mono_items);
117         for (mono_item, _) in mono_items {
118             match mono_item {
119                 MonoItem::Fn(inst) => match backend_config.codegen_mode {
120                     CodegenMode::Aot => unreachable!(),
121                     CodegenMode::Jit => {
122                         cx.tcx.sess.time("codegen fn", || {
123                             crate::base::codegen_fn(&mut cx, &mut jit_module, inst)
124                         });
125                     }
126                     CodegenMode::JitLazy => codegen_shim(&mut cx, &mut jit_module, inst),
127                 },
128                 MonoItem::Static(def_id) => {
129                     crate::constant::codegen_static(tcx, &mut jit_module, def_id);
130                 }
131                 MonoItem::GlobalAsm(item_id) => {
132                     let item = tcx.hir().item(item_id);
133                     tcx.sess.span_fatal(item.span, "Global asm is not supported in JIT mode");
134                 }
135             }
136         }
137     });
138
139     if !cx.global_asm.is_empty() {
140         tcx.sess.fatal("Inline asm is not supported in JIT mode");
141     }
142
143     tcx.sess.abort_if_errors();
144
145     jit_module.finalize_definitions();
146     unsafe { cx.unwind_context.register_jit(&jit_module) };
147
148     println!(
149         "Rustc codegen cranelift will JIT run the executable, because -Cllvm-args=mode=jit was passed"
150     );
151
152     let args = std::iter::once(&*tcx.crate_name(LOCAL_CRATE).as_str().to_string())
153         .chain(backend_config.jit_args.iter().map(|arg| &**arg))
154         .map(|arg| CString::new(arg).unwrap())
155         .collect::<Vec<_>>();
156
157     let start_sig = Signature {
158         params: vec![
159             AbiParam::new(jit_module.target_config().pointer_type()),
160             AbiParam::new(jit_module.target_config().pointer_type()),
161         ],
162         returns: vec![AbiParam::new(jit_module.target_config().pointer_type() /*isize*/)],
163         call_conv: jit_module.target_config().default_call_conv,
164     };
165     let start_func_id = jit_module.declare_function("main", Linkage::Import, &start_sig).unwrap();
166     let finalized_start: *const u8 = jit_module.get_finalized_function(start_func_id);
167
168     LAZY_JIT_STATE.with(|lazy_jit_state| {
169         let mut lazy_jit_state = lazy_jit_state.borrow_mut();
170         assert!(lazy_jit_state.is_none());
171         *lazy_jit_state = Some(JitState { backend_config, jit_module });
172     });
173
174     let f: extern "C" fn(c_int, *const *const c_char) -> c_int =
175         unsafe { ::std::mem::transmute(finalized_start) };
176
177     let (tx, rx) = mpsc::channel();
178     GLOBAL_MESSAGE_SENDER.set(Mutex::new(tx)).unwrap();
179
180     // Spawn the jitted runtime in a new thread so that this rustc thread can handle messages
181     // (eg to lazily JIT further functions as required)
182     std::thread::spawn(move || {
183         let mut argv = args.iter().map(|arg| arg.as_ptr()).collect::<Vec<_>>();
184
185         // Push a null pointer as a terminating argument. This is required by POSIX and
186         // useful as some dynamic linkers use it as a marker to jump over.
187         argv.push(std::ptr::null());
188
189         let ret = f(args.len() as c_int, argv.as_ptr());
190         std::process::exit(ret);
191     });
192
193     // Handle messages
194     loop {
195         match rx.recv().unwrap() {
196             // lazy JIT compilation request - compile requested instance and return pointer to result
197             UnsafeMessage::JitFn { instance_ptr, trampoline_ptr, tx } => {
198                 tx.send(jit_fn(instance_ptr, trampoline_ptr))
199                     .expect("jitted runtime hung up before response to lazy JIT request was sent");
200             }
201         }
202     }
203 }
204
205 #[no_mangle]
206 extern "C" fn __clif_jit_fn(
207     instance_ptr: *const Instance<'static>,
208     trampoline_ptr: *const u8,
209 ) -> *const u8 {
210     // send the JIT request to the rustc thread, with a channel for the response
211     let (tx, rx) = mpsc::channel();
212     UnsafeMessage::JitFn { instance_ptr, trampoline_ptr, tx }
213         .send()
214         .expect("rustc thread hung up before lazy JIT request was sent");
215
216     // block on JIT compilation result
217     rx.recv().expect("rustc thread hung up before responding to sent lazy JIT request")
218 }
219
220 fn jit_fn(instance_ptr: *const Instance<'static>, trampoline_ptr: *const u8) -> *const u8 {
221     rustc_middle::ty::tls::with(|tcx| {
222         // lift is used to ensure the correct lifetime for instance.
223         let instance = tcx.lift(unsafe { *instance_ptr }).unwrap();
224
225         LAZY_JIT_STATE.with(|lazy_jit_state| {
226             let mut lazy_jit_state = lazy_jit_state.borrow_mut();
227             let lazy_jit_state = lazy_jit_state.as_mut().unwrap();
228             let jit_module = &mut lazy_jit_state.jit_module;
229             let backend_config = lazy_jit_state.backend_config.clone();
230
231             let name = tcx.symbol_name(instance).name;
232             let sig = crate::abi::get_function_sig(tcx, jit_module.isa().triple(), instance);
233             let func_id = jit_module.declare_function(name, Linkage::Export, &sig).unwrap();
234
235             let current_ptr = jit_module.read_got_entry(func_id);
236
237             // If the function's GOT entry has already been updated to point at something other
238             // than the shim trampoline, don't re-jit but just return the new pointer instead.
239             // This does not need synchronization as this code is executed only by a sole rustc
240             // thread.
241             if current_ptr != trampoline_ptr {
242                 return current_ptr;
243             }
244
245             jit_module.prepare_for_function_redefine(func_id).unwrap();
246
247             let mut cx = crate::CodegenCx::new(tcx, backend_config, jit_module.isa(), false);
248             tcx.sess.time("codegen fn", || crate::base::codegen_fn(&mut cx, jit_module, instance));
249
250             assert!(cx.global_asm.is_empty());
251             jit_module.finalize_definitions();
252             unsafe { cx.unwind_context.register_jit(&jit_module) };
253             jit_module.get_finalized_function(func_id)
254         })
255     })
256 }
257
258 fn load_imported_symbols_for_jit(tcx: TyCtxt<'_>) -> Vec<(String, *const u8)> {
259     use rustc_middle::middle::dependency_format::Linkage;
260
261     let mut dylib_paths = Vec::new();
262
263     let crate_info = CrateInfo::new(tcx);
264     let formats = tcx.dependency_formats(());
265     let data = &formats
266         .iter()
267         .find(|(crate_type, _data)| *crate_type == rustc_session::config::CrateType::Executable)
268         .unwrap()
269         .1;
270     for &(cnum, _) in &crate_info.used_crates_dynamic {
271         let src = &crate_info.used_crate_source[&cnum];
272         match data[cnum.as_usize() - 1] {
273             Linkage::NotLinked | Linkage::IncludedFromDylib => {}
274             Linkage::Static => {
275                 let name = tcx.crate_name(cnum);
276                 let mut err =
277                     tcx.sess.struct_err(&format!("Can't load static lib {}", name.as_str()));
278                 err.note("rustc_codegen_cranelift can only load dylibs in JIT mode.");
279                 err.emit();
280             }
281             Linkage::Dynamic => {
282                 dylib_paths.push(src.dylib.as_ref().unwrap().0.clone());
283             }
284         }
285     }
286
287     let mut imported_symbols = Vec::new();
288     for path in dylib_paths {
289         use object::{Object, ObjectSymbol};
290         let lib = libloading::Library::new(&path).unwrap();
291         let obj = std::fs::read(path).unwrap();
292         let obj = object::File::parse(&*obj).unwrap();
293         imported_symbols.extend(obj.dynamic_symbols().filter_map(|symbol| {
294             let name = symbol.name().unwrap().to_string();
295             if name.is_empty() || !symbol.is_global() || symbol.is_undefined() {
296                 return None;
297             }
298             if name.starts_with("rust_metadata_") {
299                 // The metadata is part of a section that is not loaded by the dynamic linker in
300                 // case of cg_llvm.
301                 return None;
302             }
303             let dlsym_name = if cfg!(target_os = "macos") {
304                 // On macOS `dlsym` expects the name without leading `_`.
305                 assert!(name.starts_with('_'), "{:?}", name);
306                 &name[1..]
307             } else {
308                 &name
309             };
310             let symbol: libloading::Symbol<'_, *const u8> =
311                 unsafe { lib.get(dlsym_name.as_bytes()) }.unwrap();
312             Some((name, *symbol))
313         }));
314         std::mem::forget(lib)
315     }
316
317     tcx.sess.abort_if_errors();
318
319     imported_symbols
320 }
321
322 fn codegen_shim<'tcx>(cx: &mut CodegenCx<'tcx>, module: &mut JITModule, inst: Instance<'tcx>) {
323     let tcx = cx.tcx;
324
325     let pointer_type = module.target_config().pointer_type();
326
327     let name = tcx.symbol_name(inst).name;
328     let sig = crate::abi::get_function_sig(tcx, module.isa().triple(), inst);
329     let func_id = module.declare_function(name, Linkage::Export, &sig).unwrap();
330
331     let instance_ptr = Box::into_raw(Box::new(inst));
332
333     let jit_fn = module
334         .declare_function(
335             "__clif_jit_fn",
336             Linkage::Import,
337             &Signature {
338                 call_conv: module.target_config().default_call_conv,
339                 params: vec![AbiParam::new(pointer_type), AbiParam::new(pointer_type)],
340                 returns: vec![AbiParam::new(pointer_type)],
341             },
342         )
343         .unwrap();
344
345     cx.cached_context.clear();
346     let trampoline = &mut cx.cached_context.func;
347     trampoline.signature = sig.clone();
348
349     let mut builder_ctx = FunctionBuilderContext::new();
350     let mut trampoline_builder = FunctionBuilder::new(trampoline, &mut builder_ctx);
351
352     let trampoline_fn = module.declare_func_in_func(func_id, trampoline_builder.func);
353     let jit_fn = module.declare_func_in_func(jit_fn, trampoline_builder.func);
354     let sig_ref = trampoline_builder.func.import_signature(sig);
355
356     let entry_block = trampoline_builder.create_block();
357     trampoline_builder.append_block_params_for_function_params(entry_block);
358     let fn_args = trampoline_builder.func.dfg.block_params(entry_block).to_vec();
359
360     trampoline_builder.switch_to_block(entry_block);
361     let instance_ptr = trampoline_builder.ins().iconst(pointer_type, instance_ptr as u64 as i64);
362     let trampoline_ptr = trampoline_builder.ins().func_addr(pointer_type, trampoline_fn);
363     let jitted_fn = trampoline_builder.ins().call(jit_fn, &[instance_ptr, trampoline_ptr]);
364     let jitted_fn = trampoline_builder.func.dfg.inst_results(jitted_fn)[0];
365     let call_inst = trampoline_builder.ins().call_indirect(sig_ref, jitted_fn, &fn_args);
366     let ret_vals = trampoline_builder.func.dfg.inst_results(call_inst).to_vec();
367     trampoline_builder.ins().return_(&ret_vals);
368
369     module
370         .define_function(
371             func_id,
372             &mut cx.cached_context,
373             &mut NullTrapSink {},
374             &mut NullStackMapSink {},
375         )
376         .unwrap();
377 }