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