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