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