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