]> git.lizzy.rs Git - rust.git/blob - src/driver.rs
Use anonymous lifetimes where possible
[rust.git] / src / driver.rs
1 use std::any::Any;
2 use std::ffi::CString;
3 use std::fs::File;
4 use std::os::raw::{c_char, c_int};
5
6 use rustc::middle::cstore::EncodedMetadata;
7 use rustc::mir::mono::{Linkage as RLinkage, Visibility};
8 use rustc::session::config::{DebugInfo, OutputType};
9 use rustc_codegen_ssa::back::linker::LinkerInfo;
10 use rustc_codegen_ssa::CrateInfo;
11
12 use cranelift_faerie::*;
13
14 use crate::prelude::*;
15
16 pub fn codegen_crate(
17     tcx: TyCtxt<'_>,
18     metadata: EncodedMetadata,
19     need_metadata_module: bool,
20 ) -> Box<dyn Any> {
21     tcx.sess.abort_if_errors();
22
23     let mut log = if cfg!(debug_assertions) {
24         Some(File::create(concat!(env!("CARGO_MANIFEST_DIR"), "/target/out/log.txt")).unwrap())
25     } else {
26         None
27     };
28
29     if std::env::var("SHOULD_RUN").is_ok()
30         && tcx.sess.crate_types.get().contains(&CrateType::Executable)
31     {
32         #[cfg(not(target_arch = "wasm32"))]
33         let _: ! = run_jit(tcx, &mut log);
34
35         #[cfg(target_arch = "wasm32")]
36         panic!("jit not supported on wasm");
37     }
38
39     run_aot(tcx, metadata, need_metadata_module, &mut log)
40 }
41
42 #[cfg(not(target_arch = "wasm32"))]
43 fn run_jit(tcx: TyCtxt<'_>, log: &mut Option<File>) -> ! {
44     use cranelift_simplejit::{SimpleJITBackend, SimpleJITBuilder};
45
46     let imported_symbols = load_imported_symbols_for_jit(tcx);
47
48     let mut jit_builder = SimpleJITBuilder::with_isa(
49         crate::build_isa(tcx.sess, false),
50         cranelift_module::default_libcall_names(),
51     );
52     jit_builder.symbols(imported_symbols);
53     let mut jit_module: Module<SimpleJITBackend> = Module::new(jit_builder);
54     assert_eq!(pointer_ty(tcx), jit_module.target_config().pointer_type());
55
56     let sig = Signature {
57         params: vec![
58             AbiParam::new(jit_module.target_config().pointer_type()),
59             AbiParam::new(jit_module.target_config().pointer_type()),
60         ],
61         returns: vec![AbiParam::new(
62             jit_module.target_config().pointer_type(), /*isize*/
63         )],
64         call_conv: CallConv::SystemV,
65     };
66     let main_func_id = jit_module
67         .declare_function("main", Linkage::Import, &sig)
68         .unwrap();
69
70     codegen_cgus(tcx, &mut jit_module, &mut None, log);
71     crate::allocator::codegen(tcx.sess, &mut jit_module);
72     jit_module.finalize_definitions();
73
74     tcx.sess.abort_if_errors();
75
76     let finalized_main: *const u8 = jit_module.get_finalized_function(main_func_id);
77
78     println!("Rustc codegen cranelift will JIT run the executable, because the SHOULD_RUN env var is set");
79
80     let f: extern "C" fn(c_int, *const *const c_char) -> c_int =
81         unsafe { ::std::mem::transmute(finalized_main) };
82
83     let args = ::std::env::var("JIT_ARGS").unwrap_or_else(|_| String::new());
84     let args = args
85         .split(" ")
86         .chain(Some(&*tcx.crate_name(LOCAL_CRATE).as_str().to_string()))
87         .map(|arg| CString::new(arg).unwrap())
88         .collect::<Vec<_>>();
89     let argv = args.iter().map(|arg| arg.as_ptr()).collect::<Vec<_>>();
90     // TODO: Rust doesn't care, but POSIX argv has a NULL sentinel at the end
91
92     let ret = f(args.len() as c_int, argv.as_ptr());
93
94     jit_module.finish();
95     std::process::exit(ret);
96 }
97
98 fn load_imported_symbols_for_jit(tcx: TyCtxt<'_>) -> Vec<(String, *const u8)> {
99     use rustc::middle::dependency_format::Linkage;
100
101     let mut dylib_paths = Vec::new();
102
103     let crate_info = CrateInfo::new(tcx);
104     let formats = tcx.sess.dependency_formats.borrow();
105     let data = formats.get(&CrateType::Executable).unwrap();
106     for &(cnum, _) in &crate_info.used_crates_dynamic {
107         let src = &crate_info.used_crate_source[&cnum];
108         match data[cnum.as_usize() - 1] {
109             Linkage::NotLinked | Linkage::IncludedFromDylib => {}
110             Linkage::Static => {
111                 let name = tcx.crate_name(cnum);
112                 let mut err = tcx.sess.struct_err(&format!("Can't load static lib {}", name.as_str()));
113                 err.note("rustc_codegen_cranelift can only load dylibs in JIT mode.");
114                 err.emit();
115             }
116             Linkage::Dynamic => {
117                 dylib_paths.push(src.dylib.as_ref().unwrap().0.clone());
118             }
119         }
120     }
121
122     let mut imported_symbols = Vec::new();
123     for path in dylib_paths {
124         use object::Object;
125         let lib = libloading::Library::new(&path).unwrap();
126         let obj = std::fs::read(path).unwrap();
127         let obj = object::File::parse(&obj).unwrap();
128         imported_symbols.extend(obj.dynamic_symbols().filter_map(|(_idx, symbol)| {
129             let name = symbol.name().unwrap().to_string();
130             if name.is_empty() || !symbol.is_global() || symbol.is_undefined() {
131                 return None;
132             }
133             let symbol: libloading::Symbol<*const u8> =
134                 unsafe { lib.get(name.as_bytes()) }.unwrap();
135             Some((name, *symbol))
136         }));
137         std::mem::forget(lib)
138     }
139
140     tcx.sess.abort_if_errors();
141
142     imported_symbols
143 }
144
145 fn run_aot(
146     tcx: TyCtxt<'_>,
147     metadata: EncodedMetadata,
148     need_metadata_module: bool,
149     log: &mut Option<File>,
150 ) -> Box<CodegenResults> {
151     let new_module = |name: String| {
152         let module: Module<FaerieBackend> = Module::new(
153             FaerieBuilder::new(
154                 crate::build_isa(tcx.sess, true),
155                 name + ".o",
156                 FaerieTrapCollection::Disabled,
157                 cranelift_module::default_libcall_names(),
158             )
159             .unwrap(),
160         );
161         assert_eq!(pointer_ty(tcx), module.target_config().pointer_type());
162         module
163     };
164
165     let emit_module = |name: &str,
166                        kind: ModuleKind,
167                        mut module: Module<FaerieBackend>,
168                        debug: Option<DebugContext>| {
169         module.finalize_definitions();
170         let mut artifact = module.finish().artifact;
171
172         if let Some(mut debug) = debug {
173             debug.emit(&mut artifact);
174         }
175
176         let tmp_file = tcx
177             .output_filenames(LOCAL_CRATE)
178             .temp_path(OutputType::Object, Some(name));
179         let obj = artifact.emit().unwrap();
180         std::fs::write(&tmp_file, obj).unwrap();
181         CompiledModule {
182             name: name.to_string(),
183             kind,
184             object: Some(tmp_file),
185             bytecode: None,
186             bytecode_compressed: None,
187         }
188     };
189
190     let mut faerie_module = new_module("some_file".to_string());
191
192     let mut debug = if tcx.sess.opts.debuginfo != DebugInfo::None
193         // macOS debuginfo doesn't work yet (see #303)
194         && !tcx.sess.target.target.options.is_like_osx
195     {
196         let debug = DebugContext::new(
197             tcx,
198             faerie_module.target_config().pointer_type().bytes() as u8,
199         );
200         Some(debug)
201     } else {
202         None
203     };
204
205     codegen_cgus(tcx, &mut faerie_module, &mut debug, log);
206
207     tcx.sess.abort_if_errors();
208
209     let mut allocator_module = new_module("allocator_shim.o".to_string());
210     let created_alloc_shim = crate::allocator::codegen(tcx.sess, &mut allocator_module);
211
212     rustc_incremental::assert_dep_graph(tcx);
213     rustc_incremental::save_dep_graph(tcx);
214     rustc_incremental::finalize_session_directory(tcx.sess, tcx.crate_hash(LOCAL_CRATE));
215
216     let metadata_module = if need_metadata_module {
217         use rustc::mir::mono::CodegenUnitNameBuilder;
218
219         let cgu_name_builder = &mut CodegenUnitNameBuilder::new(tcx);
220         let metadata_cgu_name = cgu_name_builder
221             .build_cgu_name(LOCAL_CRATE, &["crate"], Some("metadata"))
222             .as_str()
223             .to_string();
224
225         let mut metadata_artifact =
226             faerie::Artifact::new(crate::build_isa(tcx.sess, true).triple().clone(), metadata_cgu_name.clone());
227         crate::metadata::write_metadata(tcx, &mut metadata_artifact);
228
229         let tmp_file = tcx
230             .output_filenames(LOCAL_CRATE)
231             .temp_path(OutputType::Metadata, Some(&metadata_cgu_name));
232
233         let obj = metadata_artifact.emit().unwrap();
234         std::fs::write(&tmp_file, obj).unwrap();
235
236         Some(CompiledModule {
237             name: metadata_cgu_name,
238             kind: ModuleKind::Metadata,
239             object: Some(tmp_file),
240             bytecode: None,
241             bytecode_compressed: None,
242         })
243     } else {
244         None
245     };
246
247     Box::new(CodegenResults {
248         crate_name: tcx.crate_name(LOCAL_CRATE),
249         modules: vec![emit_module(
250             "dummy_name",
251             ModuleKind::Regular,
252             faerie_module,
253             debug,
254         )],
255         allocator_module: if created_alloc_shim {
256             Some(emit_module(
257                 "allocator_shim",
258                 ModuleKind::Allocator,
259                 allocator_module,
260                 None,
261             ))
262         } else {
263             None
264         },
265         metadata_module,
266         crate_hash: tcx.crate_hash(LOCAL_CRATE),
267         metadata,
268         windows_subsystem: None, // Windows is not yet supported
269         linker_info: LinkerInfo::new(tcx),
270         crate_info: CrateInfo::new(tcx),
271     })
272 }
273
274 fn codegen_cgus<'tcx>(
275     tcx: TyCtxt<'tcx>,
276     module: &mut Module<impl Backend + 'static>,
277     debug: &mut Option<DebugContext<'tcx>>,
278     log: &mut Option<File>,
279 ) {
280     let (_, cgus) = tcx.collect_and_partition_mono_items(LOCAL_CRATE);
281     let mono_items = cgus
282         .iter()
283         .map(|cgu| cgu.items_in_deterministic_order(tcx).into_iter())
284         .flatten()
285         .collect::<FxHashMap<_, (_, _)>>();
286
287     codegen_mono_items(tcx, module, debug.as_mut(), log, mono_items);
288
289     crate::main_shim::maybe_create_entry_wrapper(tcx, module);
290 }
291
292 fn codegen_mono_items<'tcx>(
293     tcx: TyCtxt<'tcx>,
294     module: &mut Module<impl Backend + 'static>,
295     debug_context: Option<&mut DebugContext<'tcx>>,
296     log: &mut Option<File>,
297     mono_items: FxHashMap<MonoItem<'tcx>, (RLinkage, Visibility)>,
298 ) {
299     let mut cx = CodegenCx::new(tcx, module, debug_context);
300     time("codegen mono items", move || {
301         for (mono_item, (linkage, visibility)) in mono_items {
302             crate::unimpl::try_unimpl(tcx, log, || {
303                 let linkage = crate::linkage::get_clif_linkage(mono_item, linkage, visibility);
304                 trans_mono_item(&mut cx, mono_item, linkage);
305             });
306         }
307
308         cx.finalize();
309     });
310 }
311
312 fn trans_mono_item<'clif, 'tcx, B: Backend + 'static>(
313     cx: &mut crate::CodegenCx<'clif, 'tcx, B>,
314     mono_item: MonoItem<'tcx>,
315     linkage: Linkage,
316 ) {
317     let tcx = cx.tcx;
318     match mono_item {
319         MonoItem::Fn(inst) => {
320             let _inst_guard =
321                 PrintOnPanic(|| format!("{:?} {}", inst, tcx.symbol_name(inst).as_str()));
322             debug_assert!(!inst.substs.needs_infer());
323             let _mir_guard = PrintOnPanic(|| {
324                 match inst.def {
325                     InstanceDef::Item(_)
326                     | InstanceDef::DropGlue(_, _)
327                     | InstanceDef::Virtual(_, _) => {
328                         let mut mir = ::std::io::Cursor::new(Vec::new());
329                         crate::rustc_mir::util::write_mir_pretty(
330                             tcx,
331                             Some(inst.def_id()),
332                             &mut mir,
333                         )
334                         .unwrap();
335                         String::from_utf8(mir.into_inner()).unwrap()
336                     }
337                     _ => {
338                         // FIXME fix write_mir_pretty for these instances
339                         format!("{:#?}", tcx.instance_mir(inst.def))
340                     }
341                 }
342             });
343
344             crate::base::trans_fn(cx, inst, linkage);
345         }
346         MonoItem::Static(def_id) => {
347             crate::constant::codegen_static(&mut cx.constants_cx, def_id);
348         }
349         MonoItem::GlobalAsm(node_id) => tcx
350             .sess
351             .fatal(&format!("Unimplemented global asm mono item {:?}", node_id)),
352     }
353 }
354
355 fn time<R>(name: &str, f: impl FnOnce() -> R) -> R {
356     println!("[{}] start", name);
357     let before = std::time::Instant::now();
358     let res = f();
359     let after = std::time::Instant::now();
360     println!("[{}] end time: {:?}", name, after - before);
361     res
362 }