]> git.lizzy.rs Git - rust.git/blob - src/driver/aot.rs
Use dynamic dispatch for the inner Module
[rust.git] / src / driver / aot.rs
1 //! The AOT driver uses [`cranelift_object`] to write object files suitable for linking into a
2 //! standalone executable.
3
4 use std::path::PathBuf;
5
6 use rustc_codegen_ssa::back::linker::LinkerInfo;
7 use rustc_codegen_ssa::{CodegenResults, CompiledModule, CrateInfo, ModuleKind};
8 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
9 use rustc_middle::dep_graph::{WorkProduct, WorkProductId};
10 use rustc_middle::middle::cstore::EncodedMetadata;
11 use rustc_middle::mir::mono::{CodegenUnit, MonoItem};
12 use rustc_session::cgu_reuse_tracker::CguReuse;
13 use rustc_session::config::{DebugInfo, OutputType};
14
15 use cranelift_object::ObjectModule;
16
17 use crate::{prelude::*, BackendConfig};
18
19 fn new_module(tcx: TyCtxt<'_>, name: String) -> ObjectModule {
20     let module = crate::backend::make_module(tcx.sess, name);
21     assert_eq!(pointer_ty(tcx), module.target_config().pointer_type());
22     module
23 }
24
25 struct ModuleCodegenResult(CompiledModule, Option<(WorkProductId, WorkProduct)>);
26
27 impl<HCX> HashStable<HCX> for ModuleCodegenResult {
28     fn hash_stable(&self, _: &mut HCX, _: &mut StableHasher) {
29         // do nothing
30     }
31 }
32
33 fn emit_module(
34     tcx: TyCtxt<'_>,
35     name: String,
36     kind: ModuleKind,
37     module: ObjectModule,
38     debug: Option<DebugContext<'_>>,
39     unwind_context: UnwindContext<'_>,
40 ) -> ModuleCodegenResult {
41     let mut product = module.finish();
42
43     if let Some(mut debug) = debug {
44         debug.emit(&mut product);
45     }
46
47     unwind_context.emit(&mut product);
48
49     let tmp_file = tcx
50         .output_filenames(LOCAL_CRATE)
51         .temp_path(OutputType::Object, Some(&name));
52     let obj = product.object.write().unwrap();
53     if let Err(err) = std::fs::write(&tmp_file, obj) {
54         tcx.sess
55             .fatal(&format!("error writing object file: {}", err));
56     }
57
58     let work_product = if std::env::var("CG_CLIF_INCR_CACHE_DISABLED").is_ok() {
59         None
60     } else {
61         rustc_incremental::copy_cgu_workproduct_to_incr_comp_cache_dir(
62             tcx.sess,
63             &name,
64             &Some(tmp_file.clone()),
65         )
66     };
67
68     ModuleCodegenResult(
69         CompiledModule {
70             name,
71             kind,
72             object: Some(tmp_file),
73             dwarf_object: None,
74             bytecode: None,
75         },
76         work_product,
77     )
78 }
79
80 fn reuse_workproduct_for_cgu(
81     tcx: TyCtxt<'_>,
82     cgu: &CodegenUnit<'_>,
83     work_products: &mut FxHashMap<WorkProductId, WorkProduct>,
84 ) -> CompiledModule {
85     let incr_comp_session_dir = tcx.sess.incr_comp_session_dir();
86     let mut object = None;
87     let work_product = cgu.work_product(tcx);
88     if let Some(saved_file) = &work_product.saved_file {
89         let obj_out = tcx
90             .output_filenames(LOCAL_CRATE)
91             .temp_path(OutputType::Object, Some(&cgu.name().as_str()));
92         object = Some(obj_out.clone());
93         let source_file = rustc_incremental::in_incr_comp_dir(&incr_comp_session_dir, &saved_file);
94         if let Err(err) = rustc_fs_util::link_or_copy(&source_file, &obj_out) {
95             tcx.sess.err(&format!(
96                 "unable to copy {} to {}: {}",
97                 source_file.display(),
98                 obj_out.display(),
99                 err
100             ));
101         }
102     }
103
104     work_products.insert(cgu.work_product_id(), work_product);
105
106     CompiledModule {
107         name: cgu.name().to_string(),
108         kind: ModuleKind::Regular,
109         object,
110         dwarf_object: None,
111         bytecode: None,
112     }
113 }
114
115 fn module_codegen(
116     tcx: TyCtxt<'_>,
117     (backend_config, cgu_name): (BackendConfig, rustc_span::Symbol),
118 ) -> ModuleCodegenResult {
119     let cgu = tcx.codegen_unit(cgu_name);
120     let mono_items = cgu.items_in_deterministic_order(tcx);
121
122     let mut module = new_module(tcx, cgu_name.as_str().to_string());
123
124     let mut cx = crate::CodegenCx::new(
125         tcx,
126         backend_config,
127         &mut module,
128         tcx.sess.opts.debuginfo != DebugInfo::None,
129     );
130     super::predefine_mono_items(&mut cx, &mono_items);
131     for (mono_item, (linkage, visibility)) in mono_items {
132         let linkage = crate::linkage::get_clif_linkage(mono_item, linkage, visibility);
133         match mono_item {
134             MonoItem::Fn(inst) => {
135                 cx.tcx.sess.time("codegen fn", || {
136                     crate::base::codegen_fn(&mut cx, inst, linkage)
137                 });
138             }
139             MonoItem::Static(def_id) => {
140                 crate::constant::codegen_static(&mut cx.constants_cx, def_id)
141             }
142             MonoItem::GlobalAsm(item_id) => {
143                 let item = cx.tcx.hir().item(item_id);
144                 if let rustc_hir::ItemKind::GlobalAsm(rustc_hir::GlobalAsm { asm }) = item.kind {
145                     cx.global_asm.push_str(&*asm.as_str());
146                     cx.global_asm.push_str("\n\n");
147                 } else {
148                     bug!("Expected GlobalAsm found {:?}", item);
149                 }
150             }
151         }
152     }
153     let (global_asm, debug, mut unwind_context) =
154         tcx.sess.time("finalize CodegenCx", || cx.finalize());
155     crate::main_shim::maybe_create_entry_wrapper(tcx, &mut module, &mut unwind_context);
156
157     let codegen_result = emit_module(
158         tcx,
159         cgu.name().as_str().to_string(),
160         ModuleKind::Regular,
161         module,
162         debug,
163         unwind_context,
164     );
165
166     codegen_global_asm(tcx, &cgu.name().as_str(), &global_asm);
167
168     codegen_result
169 }
170
171 pub(super) fn run_aot(
172     tcx: TyCtxt<'_>,
173     backend_config: BackendConfig,
174     metadata: EncodedMetadata,
175     need_metadata_module: bool,
176 ) -> Box<(CodegenResults, FxHashMap<WorkProductId, WorkProduct>)> {
177     let mut work_products = FxHashMap::default();
178
179     let cgus = if tcx.sess.opts.output_types.should_codegen() {
180         tcx.collect_and_partition_mono_items(LOCAL_CRATE).1
181     } else {
182         // If only `--emit metadata` is used, we shouldn't perform any codegen.
183         // Also `tcx.collect_and_partition_mono_items` may panic in that case.
184         &[]
185     };
186
187     if tcx.dep_graph.is_fully_enabled() {
188         for cgu in &*cgus {
189             tcx.ensure().codegen_unit(cgu.name());
190         }
191     }
192
193     let modules = super::time(tcx, "codegen mono items", || {
194         cgus.iter()
195             .map(|cgu| {
196                 let cgu_reuse = determine_cgu_reuse(tcx, cgu);
197                 tcx.sess
198                     .cgu_reuse_tracker
199                     .set_actual_reuse(&cgu.name().as_str(), cgu_reuse);
200
201                 match cgu_reuse {
202                     _ if std::env::var("CG_CLIF_INCR_CACHE_DISABLED").is_ok() => {}
203                     CguReuse::No => {}
204                     CguReuse::PreLto => {
205                         return reuse_workproduct_for_cgu(tcx, &*cgu, &mut work_products);
206                     }
207                     CguReuse::PostLto => unreachable!(),
208                 }
209
210                 let dep_node = cgu.codegen_dep_node(tcx);
211                 let (ModuleCodegenResult(module, work_product), _) = tcx.dep_graph.with_task(
212                     dep_node,
213                     tcx,
214                     (backend_config, cgu.name()),
215                     module_codegen,
216                     rustc_middle::dep_graph::hash_result,
217                 );
218
219                 if let Some((id, product)) = work_product {
220                     work_products.insert(id, product);
221                 }
222
223                 module
224             })
225             .collect::<Vec<_>>()
226     });
227
228     tcx.sess.abort_if_errors();
229
230     let mut allocator_module = new_module(tcx, "allocator_shim".to_string());
231     let mut allocator_unwind_context = UnwindContext::new(tcx, allocator_module.isa(), true);
232     let created_alloc_shim =
233         crate::allocator::codegen(tcx, &mut allocator_module, &mut allocator_unwind_context);
234
235     let allocator_module = if created_alloc_shim {
236         let ModuleCodegenResult(module, work_product) = emit_module(
237             tcx,
238             "allocator_shim".to_string(),
239             ModuleKind::Allocator,
240             allocator_module,
241             None,
242             allocator_unwind_context,
243         );
244         if let Some((id, product)) = work_product {
245             work_products.insert(id, product);
246         }
247         Some(module)
248     } else {
249         None
250     };
251
252     let metadata_module = if need_metadata_module {
253         let _timer = tcx.prof.generic_activity("codegen crate metadata");
254         let (metadata_cgu_name, tmp_file) = tcx.sess.time("write compressed metadata", || {
255             use rustc_middle::mir::mono::CodegenUnitNameBuilder;
256
257             let cgu_name_builder = &mut CodegenUnitNameBuilder::new(tcx);
258             let metadata_cgu_name = cgu_name_builder
259                 .build_cgu_name(LOCAL_CRATE, &["crate"], Some("metadata"))
260                 .as_str()
261                 .to_string();
262
263             let tmp_file = tcx
264                 .output_filenames(LOCAL_CRATE)
265                 .temp_path(OutputType::Metadata, Some(&metadata_cgu_name));
266
267             let obj = crate::backend::with_object(tcx.sess, &metadata_cgu_name, |object| {
268                 crate::metadata::write_metadata(tcx, object);
269             });
270
271             if let Err(err) = std::fs::write(&tmp_file, obj) {
272                 tcx.sess
273                     .fatal(&format!("error writing metadata object file: {}", err));
274             }
275
276             (metadata_cgu_name, tmp_file)
277         });
278
279         Some(CompiledModule {
280             name: metadata_cgu_name,
281             kind: ModuleKind::Metadata,
282             object: Some(tmp_file),
283             dwarf_object: None,
284             bytecode: None,
285         })
286     } else {
287         None
288     };
289
290     Box::new((
291         CodegenResults {
292             crate_name: tcx.crate_name(LOCAL_CRATE),
293             modules,
294             allocator_module,
295             metadata_module,
296             metadata,
297             windows_subsystem: None, // Windows is not yet supported
298             linker_info: LinkerInfo::new(tcx),
299             crate_info: CrateInfo::new(tcx),
300         },
301         work_products,
302     ))
303 }
304
305 fn codegen_global_asm(tcx: TyCtxt<'_>, cgu_name: &str, global_asm: &str) {
306     use std::io::Write;
307     use std::process::{Command, Stdio};
308
309     if global_asm.is_empty() {
310         return;
311     }
312
313     if cfg!(not(feature = "inline_asm"))
314         || tcx.sess.target.is_like_osx
315         || tcx.sess.target.is_like_windows
316     {
317         if global_asm.contains("__rust_probestack") {
318             return;
319         }
320
321         // FIXME fix linker error on macOS
322         if cfg!(not(feature = "inline_asm")) {
323             tcx.sess.fatal(
324                 "asm! and global_asm! support is disabled while compiling rustc_codegen_cranelift",
325             );
326         } else {
327             tcx.sess
328                 .fatal("asm! and global_asm! are not yet supported on macOS and Windows");
329         }
330     }
331
332     let assembler = crate::toolchain::get_toolchain_binary(tcx.sess, "as");
333     let linker = crate::toolchain::get_toolchain_binary(tcx.sess, "ld");
334
335     // Remove all LLVM style comments
336     let global_asm = global_asm
337         .lines()
338         .map(|line| {
339             if let Some(index) = line.find("//") {
340                 &line[0..index]
341             } else {
342                 line
343             }
344         })
345         .collect::<Vec<_>>()
346         .join("\n");
347
348     let output_object_file = tcx
349         .output_filenames(LOCAL_CRATE)
350         .temp_path(OutputType::Object, Some(cgu_name));
351
352     // Assemble `global_asm`
353     let global_asm_object_file = add_file_stem_postfix(output_object_file.clone(), ".asm");
354     let mut child = Command::new(assembler)
355         .arg("-o")
356         .arg(&global_asm_object_file)
357         .stdin(Stdio::piped())
358         .spawn()
359         .expect("Failed to spawn `as`.");
360     child
361         .stdin
362         .take()
363         .unwrap()
364         .write_all(global_asm.as_bytes())
365         .unwrap();
366     let status = child.wait().expect("Failed to wait for `as`.");
367     if !status.success() {
368         tcx.sess
369             .fatal(&format!("Failed to assemble `{}`", global_asm));
370     }
371
372     // Link the global asm and main object file together
373     let main_object_file = add_file_stem_postfix(output_object_file.clone(), ".main");
374     std::fs::rename(&output_object_file, &main_object_file).unwrap();
375     let status = Command::new(linker)
376         .arg("-r") // Create a new object file
377         .arg("-o")
378         .arg(output_object_file)
379         .arg(&main_object_file)
380         .arg(&global_asm_object_file)
381         .status()
382         .unwrap();
383     if !status.success() {
384         tcx.sess.fatal(&format!(
385             "Failed to link `{}` and `{}` together",
386             main_object_file.display(),
387             global_asm_object_file.display(),
388         ));
389     }
390
391     std::fs::remove_file(global_asm_object_file).unwrap();
392     std::fs::remove_file(main_object_file).unwrap();
393 }
394
395 fn add_file_stem_postfix(mut path: PathBuf, postfix: &str) -> PathBuf {
396     let mut new_filename = path.file_stem().unwrap().to_owned();
397     new_filename.push(postfix);
398     if let Some(extension) = path.extension() {
399         new_filename.push(".");
400         new_filename.push(extension);
401     }
402     path.set_file_name(new_filename);
403     path
404 }
405
406 // Adapted from https://github.com/rust-lang/rust/blob/303d8aff6092709edd4dbd35b1c88e9aa40bf6d8/src/librustc_codegen_ssa/base.rs#L922-L953
407 fn determine_cgu_reuse<'tcx>(tcx: TyCtxt<'tcx>, cgu: &CodegenUnit<'tcx>) -> CguReuse {
408     if !tcx.dep_graph.is_fully_enabled() {
409         return CguReuse::No;
410     }
411
412     let work_product_id = &cgu.work_product_id();
413     if tcx
414         .dep_graph
415         .previous_work_product(work_product_id)
416         .is_none()
417     {
418         // We don't have anything cached for this CGU. This can happen
419         // if the CGU did not exist in the previous session.
420         return CguReuse::No;
421     }
422
423     // Try to mark the CGU as green. If it we can do so, it means that nothing
424     // affecting the LLVM module has changed and we can re-use a cached version.
425     // If we compile with any kind of LTO, this means we can re-use the bitcode
426     // of the Pre-LTO stage (possibly also the Post-LTO version but we'll only
427     // know that later). If we are not doing LTO, there is only one optimized
428     // version of each module, so we re-use that.
429     let dep_node = cgu.codegen_dep_node(tcx);
430     assert!(
431         !tcx.dep_graph.dep_node_exists(&dep_node),
432         "CompileCodegenUnit dep-node for CGU `{}` already exists before marking.",
433         cgu.name()
434     );
435
436     if tcx.try_mark_green(&dep_node) {
437         CguReuse::PreLto
438     } else {
439         CguReuse::No
440     }
441 }